if ( window.console == undefined || window.console.log == undefined ) {	window.console = { log:function(msg){ /* msg */ } } }
if ( typeof(window.billboard)=="undefined"){ billboard={}; }
/**
 *
 * Billboard Profile
 *
 */
billboard.profile = new ( function($)  
{
	var me = this;
	me.page = 0;
	me.numPerPage = 10;
	me.totalNumPages = 0;
	me.sort = "date"; // "alpha";
	me.filter = "all"; //
	me.events;
	me.neighborChartList = [];

	var URL_BB_FIND_USER = "/user/find-user.json?username=";
	var URL_CF_USERGET = "rest/v1/user/get";
	var URL_BB_EMAIL_FRIEND = "/user/email/email-friend.svc";
	var URL_BB_NEWSLETTER_SUBSCRIBE = "/services/user/newsletter-subscribe.json";
	var URL_BB_NEWSLETTER_UNSUBSCRIBE = "/services/user/newsletter-unsubscribe.json";
	var URL_BB_DEACTIVATE = "/user/deactivate.json";
	var URL_BB_SEARCH_FACEBOOK_FRIENDS="/user/fb/showfriend.json";
	var URL_BB_INVITE_FACEBOOK_FRIENDS="/user/fb/invitefacebookfriends.json?facebookids="; 
	var URL_CF_GET_HIGHESTRATED = "rest/v1/query/entity/highest_rated";
	var URL_CF_ACTIVITY_GET = "rest/v1/activityevent/get";
	var URL_BB_GET_NCHARTS = "/user/community/getNeighborhoodCharts.json?user=";

	var USER_RESULT_VISIBLE_COUNT = 6;
	var FB_RESULT_VISIBLE_COUNT = 5;
	var BB_RESULT_VISIBLE_COUNT = 3;

	var monthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");


	me.init = function()
	{
		billboard.log("Profile.init()");
		/**
		 * register listeners... 
		 */
		billboard.broadcaster.addListener( "pageLoaded", me.onPageLoaded );
		billboard.broadcaster.addListener( "userLoggedIn", me.onLogIn );
	};

	me.onLogIn = function()
	{
		if ( billboard.user.username == billboard.publicUser ) {
			$(".follow.login-required").hide();
		}
        
        if (billboard.section == 'profile' 
            && billboard.subsection == 'settings') {
				if(billboard.user.facebookId!=null && billboard.user.facebookId!=""){
					$("input[name=enableFB]").removeAttr("disabled");
					$("input[name=unlinkAccounts]").removeAttr("disabled");
				}
				else{
					$("input[name=enableFB]").attr("disabled","disabled");
					$("input[name=unlinkAccounts]").attr("disabled","disabled");
				}
        }

        if (billboard.section == 'profile' 
            && billboard.user.username == billboard.publicUser){
            $("#change-profile-photo").show(); 
            $("#change-photo").click(function(){
                billboard.social.uploadPhoto();
                return false;
            });
			if( billboard.subsection == "find-people" )
				$(".find-head .filter-nav").css("display","block");
        }

		if ( billboard.section == "profile" && billboard.subsection == "find-people" && billboard.publicUser != billboard.user.username ) {
			billboard.navigateToUrl( "/user/"+billboard.user.username+"/find" );
		}
	};

    var newsletterSubscribeForm = '<form id="subscribe-newsletter" method="post" action="/services/user/newsletter-subscribe.json">'
        + '<p>Email Address</p>'
        + '<p><input type="text" name="email"/></p>'
        + '<p><input type="submit" value="Subscribe" ></p>'
        + '</form>';

    var rightRailSubmit = function(cont){
        me.subscribeNewsletter(
            $("#subscribe-container input[name=email]").val()
            , function(data){
                if (data.response.head.status == 'success'){
                    if (data.response.body.RecipientModel.result == 'TRUE'){
                        cont.html('<p>Thank you for subscribing.</p>');
						billboard.metrics.trackPageView("/footer/newsletter/thankyou");
                    } else {
                        cont.html(
                            '<p>'
                            + (data.response.body.RecipientModel.errorDescription.indexOf("not a valid email") > -1 ? 'The email you have entered is invalid' : data.response.body.RecipientModel.errorDescription)
                            + '. Please <a href="/footer/newsletter" id="try-again">try again</a>.</p>'
                        );
                        $("#try-again").click(function(){
                            me.loadSubscribeForm(cont);
                            return false;
                        });
                    }
                } else {
                    cont.html(
                        '<p>'
                        + data.response.head.message
                        + '. Please <a href="/footer/newsletter" id="try-again">try again</a>.</p>'
                    );
                    $("#try-again").click(function(){
                        me.loadSubscribeForm(cont);
                        return false;
                    });
                }
            }
        );
        return false;
    };

	me.initNewsletterSubscribe = function(){
		var newsletterContainer = $("#subscribe-container");
		var statusContainer = $("#subscribe-container #status-container");
		if (newsletterContainer.length > 0){
			$("#subscribe-container #join-billboard").click(function(){
				if(billboard.user.isLoggedIn()){
					$.getJSON( "/services/user/newsletter-subscribe.json?email="+billboard.user.email, function( data, status ) { 
						if (data.response.head.status == 'success'){
							if (data.response.body.RecipientModel.result == 'TRUE'){
								$("#subscribe-container #status-container").html('<p>Thank you for subscribing.</p>');

							} 
						}
						else {
							me.loadSubscribeForm(statusContainer);
					        return false;
						}
					});
					return false;
					
				}
				
				else {
					me.loadSubscribeForm(statusContainer);
					return false;
				}
			});
		} 
	}; 

    me.loadSubscribeForm = function(cont){
        var $form = $(newsletterSubscribeForm);
        cont.html($form); 
        $form.submit(function(){
            return rightRailSubmit(cont); 
        });
    };

    me.subscribeNewsletter = function(pEmail,callback){
        $.getJSON(
	        URL_BB_NEWSLETTER_SUBSCRIBE
            ,{
                email : pEmail
            }
            ,callback
        );
    };

    me.unsubscribeNewsletter = function(pEmail,callback){
        $.getJSON(
	        URL_BB_NEWSLETTER_UNSUBSCRIBE
            ,{
                email : pEmail
            }
            ,callback
        );
    };

	/**
	 * if we're in the profile section do stuff off subsection switch
	 */
	me.onPageLoaded = function()
	{
		billboard.log("Profile.onPageLoaded()");

        me.initNewsletterSubscribe();

$("#subscribe-container #join-billboard").click();
		if ( billboard.section == 'profile' ) {
			// activate follow button
			$("a.follow").click( function() { 
				billboard.user.requireLogin( function() {
					billboard.social.follow( billboard.publicUser, function(data) {
						billboard.log( "follow result" );
						var user = billboard.user.username;
						billboard.navigateToUrl( "/user/"+user+"/connections/following" );
					});
				});
				return false;
			});


			// show/hide the follow button next to a username
			if ( billboard.user.isLoggedIn() && billboard.publicUser != billboard.user.username ) {
				$(".header .follow").show();
			}

			// if logged in and on own page show the change profile photo button
			if ( billboard.user.isLoggedIn() && billboard.user.username == billboard.publicUser){
                $("#change-profile-photo .find-people-btn").attr("href", "/user/" + billboard.user.username + "/find");
				$("#change-profile-photo").show(); 
                $("#change-photo").click(function(){
                    billboard.social.uploadPhoto();
                    return false;
                });
			}

			if ( billboard.subsection == 'activity' ) {
				me.initActivityTab();
			}
			else if ( billboard.subsection == 'chart' ) {
				me.initChart();
			}
			else if ( billboard.subsection == 'followers' ) {
				me.initFollowersTab();
			}
			else if ( billboard.subsection == 'following' ) {
				me.initFollowingTab();
			}
			else if ( billboard.subsection == 'favorites' ) {
				me.initFavoritesTab();
			}
			else if ( billboard.subsection == 'settings' ) {
                me.initSettings();
			}
			else if ( billboard.subsection == "find-people" ) {
				me.initFindPeopleTab();
			}
		}
	};

	me.initActivityTab = function()
	{
		var timeout;
		billboard.info("Profile.initActivityTab()");
		me.filter = "all";

		// activate buttons
		$(".filter-nav a").click( function(){
			$(this).parent().parent().find("li").removeClass('active');
			$(this).parent().addClass('active');
		});

		$(".filter-all a").click( function(){ 
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout(function(){
				me.filter = "all";
				me.getActivity( billboard.publicUser );
			}, 500);
			
		});
		$(".filter-user a").click( function(){ 
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout(function(){
				me.filter = "user";
				me.getActivity( billboard.publicUser );
			}, 500);
		});
		$(".filter-following a").click( function(){ 
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout(function(){
				me.filter = "follow";
				me.getActivity( billboard.publicUser );
			}, 500);
		});
		$(".filter-favorites a").click( function(){ 
			if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){
				me.filter = "rating";
				me.getActivity( billboard.publicUser );
			}, 500);
		});
		
		// load activities
		me.getActivity( billboard.publicUser );
	};

	me.initChart = function()
	{
		billboard.log("Profile.initChartTab()"); 

		var entityId = "";

		me.neighborCharts( billboard.publicUser, function() {
			$("#chart-item-container .meter .hate").click( function() {
				var id = $(this).parents(".love-bar").find(".entityId").text();
				var thisptr = $(this).parents(".love-bar");
				var el = $(this);
				billboard.user.requireLogin( function() {
					billboard.social.hate( id, function(data) { 
						thisptr.find(".meter div").text( data.loveHateTotal + " votes" );
						thisptr.find(".love-meter-container .percentage").text( data.loveHatePercentage + "%" );
						thisptr.find(".meter .hate span").css("background-position","left bottom");
						thisptr.find(".meter .love span").css("background-position","right bottom");
						var numWidth = parseInt($(".meter").css("width"));
						var w = Math.round((numWidth - 48) * (data.loveHatePercentage/100));
						thisptr.find(".meter").css("background-position",24+w+"px");
					});
					billboard.facebook.publish("hate",el);
					googleA.trackSocialEvent("Hated", el);
				});
			});

			$("#chart-item-container .meter .love").click( function() {
				var id = $(this).parents(".love-bar").find(".entityId").text();
				var thisptr = $(this).parents(".love-bar");
				var el = $(this);
				billboard.user.requireLogin( function() { 
					billboard.social.love(id,function(data) { 
						thisptr.find(".meter div").text( data.loveHateTotal + " votes" );
						thisptr.find(".love-meter-container .percentage").text( data.loveHatePercentage + "%" );
						thisptr.find(".meter .hate span").css("background-position","left bottom");
						thisptr.find(".meter .love span").css("background-position","right bottom");
						var numWidth = parseInt($(".meter").css("width"));
						var w = Math.round((numWidth - 48) * (data.loveHatePercentage/100));
						thisptr.find(".meter").css("background-position",24+w+"px");
					});
					
					billboard.facebook.publish("love",el);
					googleA.trackSocialEvent("Loved", el);
				});
			});
			
			//$("#neighborhood-chart .play-all-songs").click(function(){
																	
				//var url = 'testing';
					
				//javascript:billboard.player.playMSSong(url);													
																	
				//billboard.player.setQueue(me.neighborChartList);
			//});

		});
	};

	me.initFollowersTab = function()
	{
		if ( billboard.user.isLoggedIn() ) {
			$(".find-button a").attr("href", "/user/"+billboard.user.username+"/find" );
			billboard.hijackLinks( ".find-button" );
		}
		
		// activate followers buttons
		me.getFollowers( billboard.publicUser );
	};
	me.initFollowingTab = function()
	{
		billboard.log("Profile.initFollowingTab()");
		// activate 'find friends' button
		if ( billboard.user.isLoggedIn() ) {
			$(".find-button a").attr("href", "/user/"+billboard.user.username+"/find" );
			billboard.hijackLinks( ".find-button" );
		}

		// activate delete buttons
		if ( billboard.user.isLoggedIn() && billboard.publicUser == billboard.user.username ) {
			$(".follow .delete").css("display", "block" );
		}

		// activate following buttons
		$(".filter-date").click( function(){ 
			me.sort = "date";
			$(this).parent().find("li").removeClass('active');
			$(this).addClass('active');
			me.getFollowing( billboard.publicUser );
		});
		$(".filter-alpha").click( function(){ 
			me.sort = "alpha";
			$(this).parent().find("li").removeClass('active');
			$(this).addClass('active');
			me.getFollowing( billboard.publicUser );
		});

		me.getFollowing( billboard.publicUser );
	}

	me.initFavoritesTab = function()
	{
		var timeout;
		// activate filters...
		$(".filter-nav ul li a").click( function() {
			var thisEl = this;
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout(function(){
				me.filterFavorites( $(thisEl).attr("class") );
			}, 500);
		});

		me.filter = "all";

		$(".favorite-header .playbtn").click( function() {
			// get all songs n' IDs
			var tracks = $("#favorites-container .lala-id");
			var queue = [];
			for ( var i=0;i<tracks.length;i++ ) {
				lname = $(tracks[i]).parents(".favorite-row").find(".name a").text();
				lid = $(tracks[i]).parents(".favorite-row").find(".lala-id").text();

				queue.push( { id:lid,title:lname}  );
			}

			// send to the player...
			
			//var url = 'testing';
					
			//javascript:billboard.player.playMSSong(url);
			billboard.player.setQueue( queue, "Favorites" );
			googleA.trackEvent (1, 'List', 'Favorites' );
		});
		
		me.getFavorites( billboard.publicUser );
	};

	me.initFindPeopleTab = function()
	{
		billboard.log("Profile.initFindPeopleTab()");
		//alert("Public User: "+billboard.publicUser+"  BB User: "+billboard.user.username);
		// if this is public find page... hide some stuff
		if ( billboard.publicUser.length>0 && billboard.publicUser == billboard.user.username ) {
			$(".find-head .filter-nav").css("display","block");
		}
		else {
			$(".find-head .filter-nav").css("display","none");
		}
			
		$(".filter-nav.option ul").find(".active").removeClass("active");
		$(".filter-nav.option ul li.username").addClass("active");

		if ( !billboard.publicUser || billboard.publicUser.length <= 0 ) {
			$(".find-cancel").hide();
			$("a.follow").hide();
		}
		$(".find-cancel").click( function() {
			billboard.navigateToUrl( "/user/"+billboard.publicUser+"/connections/following" );
		});

		// search field clearing.
		$(".search-field").focus(function() {
			if( this.value == this.defaultValue ) {
				this.value = "";
			}
		}).blur(function() {
			if( !this.value.length ) {
				this.value = this.defaultValue;
			}
		});
		$("form[name=find-by-network] input[name=tusername], form[name=find-by-network] input[name=password]").keypress(function(e){
			if (e.which == 13){
				$("form[name=find-by-network] .email-search").click();
				return false;
			}
		});

		//var findByNetworkForm = $("form[name=find-by-network]");
		$("form[name=find-by-network] .email-search").click( function() {
			var email = $(this).parents("form").find("input[name=tusername]").val();
			var password = $(this).parents("form").find("input[name=password]").val();

			$(".people-list fieldset").empty();
			$(".loading-results").show();
			$(".nonbb-list").hide();
			
			$.ajax({
				url: "/user/emailsContacts.json?email="+email+"&pwd="+password,
				dataType: "json",

				success: function(data,status,callback){
					$(".loading-results").hide();
					if ( data.response.head.status == "success" ) {
						$(".bb-list .message-wrapper p").text("You have Gmail contact already on Billboard.com!");
						 var gmailContactList = data.response.body['UserView[]'];
						 
						 billboard.log(" gmaillist: " + gmailContactList.length)

						 $("#found-people-list").addClass("network-list");
						 
						 me.displayUsers(gmailContactList, true);
						
					}else{
						if(data.response.head.status == "error"){
							$("#found-people-list .filter-nav").hide();
							$(".people-list fieldset#find-person-group").html("<div class='sorry'>Sorry. " + data.response.head.message+"</div>");
							}else{
								$("#found-people-list .filter-nav").hide();
								$(".people-list fieldset#find-person-group").html("<div class='sorry'>Sorry. There are no Billboard.com users found in your contact list.</div>");
							}
							return false;
					}
				},
				error: function( err, errMsg ){
					$(".loading-results").hide();
					$("#found-people-list .filter-nav, #found-people-list .message-wrapper").hide();
					$(".people-list fieldset#find-person-group").html("<div class='sorry'>An error has occurred - <span style='color:#ff0000;font-style:italic'>"+ errMsg + "</span>. Please try again.</div>");
				},
				complete: function(){
					$("#found-people-list").show();
				}
			});

			$(".addpeople-error-msg").hide();
			//Hiding the invite div
			$("#invite-email,#bynetwork").hide();
			return false;
		});
		// activate the invite by email form
		var form = $("form[name=invite-email-form]");
		form.find("input[name=email]").focus( function() {$(this).css("background-color","##E1F2F9");} );
		form.find("input[name=email]").blur( function() {$(this).css("background-color","#ffffff");} );
		form.find("textarea").focus( function() {$(this).css("background-color","##E1F2F9");} );
		form.find("textarea").blur( function() {$(this).css("background-color","#ffffff");} );

		$("form[name=invite-email-form]").submit( function() {
			var emails = $(this).find("textarea[name=email]").val();
			var message = $(this).find("textarea[name=message]").val();
			if ( emails.length <= 0 ) { 
				$("form[name=invite-email-form] textarea[name=email]").css("background-color","#ffcccc");
				return false;
			}
			if ( emails.length > 100 ) { 
				document.getElementById("email-error-msg").innerHTML="<p>Email addresses should not exceed 100 characters</p>";
				$("#email-error-msg").show();
				return false;
			}

			if ( message.length <= 0 ) {
				$("form[name=invite-email-form] textarea").css("background-color","#ffcccc");
				return false;
			}
			
			if ( message.length > 300 ) { 
				document.getElementById("email-error-msg").innerHTML="<p>Message length should not exceed 300 characters</p>";
				$("#email-error-msg").show();
				return false;
			}
			
			emails = (emails.indexOf(",")>=0)?(emails.split(",")):[emails];
			
			var validEmail =true;
			for(var c=0;c<emails.length;c++){
				if(!validateEmail(emails[c]))
					validEmail = false;
			}

			if(!validEmail){
				document.getElementById("email-error-msg").innerHTML="<p>Invalid Email address specified</p>";
				$("#email-error-msg").show();
			return false;
			}
			else
				$("#email-error-msg").hide();

			subject = "Your friend "+billboard.user.username+" recommends the NEW Billboard.com";
			billboard.log( "invite: emails: "+emails+", message: "+message );

			var url = URL_BB_EMAIL_FRIEND;
			var messagePrefix = "Your friend "+billboard.user.username+" would like to invite you to use the new Billboard.com <br /><br />";
			var messageSuffix = "<br /><br />Click here to experience the new <a href='"+billboard.properties.domainName+"'>Billboard.com.</a>";
			url = url + "?to="+escape(emails)+"&msg="+messagePrefix+escape(message)+messageSuffix+"&subject="+escape(subject);
			$.get( url, function( data, status ) {
				if ( status == "success" ) {
					form.find("textarea[name=email]").val("");
					form.find("textarea[name=message]").val("");
					$("#invite-email").addClass("success");
				}
			});

			return false;
		});


		// init the facebook/invite by email highlighting (active states)
		$(".filter-nav.option li:not('.facebook') a").click( function() { 
			if($(this).parent("li").attr("class").indexOf("username")>-1)
				$("#find-user-form").show();
			else $("#find-user-form").hide();
			$(this).parents("ul").find(".active").removeClass("active");
			$(this).parent().addClass("active");
			$(".loading-results").hide();
			$("#found-people-list").removeClass("network-list");
         });


		// init the invite by email functionlity 
		$(".filter-nav.option li:last a, #invite-email .send-more-invites").click( function() {
			var emailmsg = billboard.user.username + " " + $("#email-message").val();
			$("#email-message").val(billboard.user.username + " has invited you to join the Billboard.com community where you can keep up with the charts, listen to free streams of thousands of albums, favorite the songs you love, watch exclusive interviews with hot artists and find out the latest news.");

			// show the invite form...
			$(".find-tab").hide();
			$("#email-error-msg").hide();
			//$(".follow-wrapper").hide();
			
			$("#invite-email").removeClass("success");
			$("#invite-email").show();
		});
		
		$(".filter-nav.option li.username a").click( function() {
			// show the invite form...
			$(".find-tab").hide();
			//$(".follow-wrapper").hide();
		});
		
		$(".filter-nav.option li.network a").click( function() {
			// show the invite form...
			$(".find-tab").hide();
			//$(".follow-wrapper").hide();
			$("#bynetwork").removeClass("success");
			$("#bynetwork").show();
			$("#bynetwork form :input").val("");
			/* $.getJSON( "/user/emailsContacts.json", function(data,status,callback) {
					if ( data.response.head.status == "success" ) {
						 billboard.info("data1.response = " + data ); 
						 var yahooLogin = data.response.body.String;
						 billboard.info("yahooLogin = " + yahooLogin ); 
					 var loggedIn = window.open(yahooLogin,'Yahoo Login','scrollbars=yes,resizable=yes, width=650,height=400')
				        
						 

					}else{
						billboard.info("no response");
						return false;
					}
				});
		
		*/
		
		
		});

		// facebook displaying functionlity 
		$(".filter-nav.option li.facebook a").click( function() { 
			
            var userfbId = FB.Connect.get_loggedInUser();
            var url = URL_BB_SEARCH_FACEBOOK_FRIENDS;
			//Additional check for user in session BBCOM-300 
            if(!isNaN(parseInt(userfbId, 10)) && billboard.user.isLoggedIn()){
			 url = url+"?facebookid="+userfbId; 
			}else{
				  FB.Connect.requireSession(function() { 
					  billboard.user.onFbLogin();
					  $(".filter-nav.option li.facebook a").click();
				  });
				 return false;
			 }
            
			$(".find-tab,.addpeople-error-msg").hide();
			$(".loading-results").hide();
			$("#found-people-list").removeClass("network-list");

			$(this).parents("ul").find(".active").removeClass("active");
			$(".filter-nav.option li.facebook").addClass("active");
			$("#find-user-form").hide();

			$(".people-list fieldset").empty();
			$(".nonbb-list,.bb-list").hide();

			$(".bb-list .message-wrapper p").text("You have Facebook friends already on Billboard.com!");
			$(".nonbb-list .message-wrapper p").html("These friends of yours are not on Billboard.com yet. <br/>Invite them today! Add up to 10 friends at a time.");

			//display loading icon
			$(".loading-results").show();
			
			

			$.getJSON( url, function(data,status) {
				$("#found-people-list").show();
				if ( data.response.head.status == "success" ) {
					$(".loading-results").hide();
					// To get the user list from the JSON object named 'com.billboard.model.view.UserView-array'
					//var list = data.response.body['com.billboard.model.view.UserView-array'];
                                        var list = data.response.body['UserView[]'];
				  //To display the user list obtained from findUsers function
					  if(list)
						me.displayFacebookFriend(list);
					  else
						  $(".people-list fieldset#find-person-group").html("<div class='sorry'>An error has occurred. Please try again later.</div>");
				}						   
				else {
					$(".loading-results").hide();
					if(FB.ApiClient.sessionIsExpired){
						  //Logout necessary as user needs to relogin for BBOM-307
						  FB.Connect.logout();
						  FB.Connect.requireSession(function() { 
						  billboard.user.onFbLogin();
						  $(".filter-nav.option li.facebook a").click();
						  });
						 return false;
					}
					$("#found-people-list .filter-nav").hide();
					$(".people-list fieldset#find-person-group").html("<div class='sorry'>Sorry. "+data.response.head.message+"</div>");
					$("#facebookusers").hide();//Hide users in case of showing errors
				}
			});
			
			return false;

		});

		$("#found-people-list .choose-network").click(function(){
			$(".filter-nav.option li.network a").click();
		});
		
		// Changed for BBCOM-264
		$(".add-people a").click( function() {

			var str="";
			var allVals = [];
			var elem = ".billboard-members .person-profile";
			var confVals = [];
			var personInfo ={};

			if($(this).hasClass("invite-billboard")){
				elem = ".non-billboard .person-profile";
			}

            $(elem + ' :checked').each(function() {
				personInfo = {};
				//alert($(this).val());
				var socialStr=[];
				socialStr=($(this).val()).split("<");//Social String is composed of facebookId and billboard username
				
				if(socialStr[0]=="0"){
				  allVals.push(socialStr[1]); //Take Billboard username in case of non facebook user
				  personInfo.username = $(this).parents(".person-profile").find(".profile-name").text();
				  personInfo.bbname = $(this).parents(".person-profile").find(".billboard-member").text();
				}else{
				  str=str+socialStr[0]+",";	  //Take facebook Id in case facebookId is present
				  personInfo.username = $(this).parents(".person-profile").find(".profile-name-facebook").text();
				}

				personInfo.imageUrl = $(this).parents(".person-profile").find(".profile-image img").attr("src");
				personInfo.showBbMember = $(this).parents(".person-profile").find(".billboard-member").is(":visible") ? 'true' : 'false';
					
	            //allVals.push($(this).val());
				confVals.push(personInfo);
           	});
			
			var flength=str.length;
			//Validation that atleast one user should be selected 
			
			$(".addpeople-error-msg").hide();

			if($(this).hasClass("invite-billboard")){
				billboard.log(str.split(",").length );
				if(flength==0){
					$(".non-billboard .addpeople-error-msg").html("<p>Please select at least one user to proceed.</p>");
					$(".addpeople-error-msg").show();
				}
				else if(str.split(",").length > 11){
					$(".non-billboard .addpeople-error-msg").html("<p>Please add up to 10 friends at a time.</p>");
					$(".addpeople-error-msg").show();
				}
				else if( flength>2 && (str.split(",").length >1)){
					str=str.substring(0,flength-1);
					me.inviteFacebookFriends(str);
				}
			}
			else{
				if(allVals.length ==0){
					$(".billboard-members .addpeople-error-msg").html("<p>Please select at least one user to proceed.</p>");
					$(".billboard-members .addpeople-error-msg").show();
				}
				else {
					billboard.user.requireLogin( function() { 
						billboard.social.follow( allVals, function(data) {
							billboard.info( "follow result" );
							var user = billboard.user.username;
							billboard.facebook.publish("follow",allVals);
							me.inviteConfirmation("byuser",confVals);
							//billboard.navigateToUrl( "/user/"+user+"/connections/following" );
						});
					});	
				}
			}
		});
			
		$("form[name=find-user-form] input.search-field").keypress(function(e){
			if (e.which == 13){
				$("form[name=find-user-form] a.search-friend").click();
				return false;
			}
		});

		$("form[name=find-user-form] a.search-friend").click( function() {
			
			$(".people-list fieldset").empty();

			$("#found-people-list .filter-nav, #found-people-list .nonbb-list").hide();

			var username = $(this).parents("form").find("input").val();
			if ( username && username.length>0 ) {
				var url = URL_BB_FIND_USER + username;

				//Changes made in the code for displaying a list of users instead of single user BBCOM-121

				//var user = {};
				
				//display loading icon
				$(".loading-results").show();

				$.getJSON( url, function(data,status) {
					if ( data.response.head.status == "success" ) {
						$(".loading-results").hide();
						//user = data.response.body.UserView;							
						// To get the user list from the JSON object named 'com.billboard.model.view.UserView-array'
						//var list = data.response.body['com.billboard.model.view.UserView-array'];
						var list = data.response.body['UserView[]'];

					  //To display the user list obtained from findUsers function
					  me.displayUsers(list);
					}						   
					else {
						$("#found-people-list").show();
						$(".loading-results").hide();
						$(".people-list fieldset#find-person-group").html("<div class='sorry'>Sorry. There are no users that match "+username+"</div>");
					}
				});

				$(".message-wrapper,.addpeople-error-msg").hide();
				//Hiding the invite div
				$("#invite-email").hide();
				
				return false;
			}
		});
	};
	
	/**
	 *
	 */
	me.displayUsers = function( users, isNetwork ) 
	{
		billboard.log( "Profile.displayUsers()");
		billboard.log( users );
		var person;
		var url;
		var param={};

		$(".message-wrapper, .nonbb-list").hide();
		$("#found-people-list, #found-people-list .bb-list").show();
		
		$(".people-list fieldset").empty();

		$(".result-div").removeClass("bb-result");

		for ( var i=0;i<users.length;i++ ) {
			param ={};
			param.username = users[i].username;
			param.facebookId = users[i].facebookId;
			param.email = (users[i].email) ? users[i].email : "";
	
			//Position of getUser function changed to handle multiple users  
			billboard.social.getUserProfile( param, function(data,param) {
				//billboard.info("getUserProfile data: " + data.user);
				if(typeof(data.user)!='undefined'){
				url = (data.user.profile_photo_url)?
					(data.user.profile_photo_url):("/images/icons/no-image-user.gif");
				}
				person = $("#person-profile-template").clone();
				person.removeAttr("id");
				if( users.length > USER_RESULT_VISIBLE_COUNT ) person.addClass("person-scroll");
				person.find(".profile-image img").attr("src", url);
				person.find(".profile-image").attr("href", "/user/"+ param.username );
				if(isNetwork){
					person.find(".profile-name").text( param.email );
					person.find(".profile-name").removeAttr("href");
					person.find(".profile-name").addClass("disabled-anchor");
					person.find(".billboard-member").text("on Billboard.com as " + param.username);
				}
				else {
					person.find(".profile-name").text( param.username );
					person.find(".profile-name").attr("href", "/user/"+ param.username );
					person.find(".billboard-member").hide();
				}
				//person.find("input[type=checkbox]").attr("checked","checked");
				person.find("input[type=checkbox]").attr("value","0<"+ param.username);
				
				person.find(".profile-image-facebook ").hide();

				//Fix for BBCOM-288 Scenario 3
				$(".billboard-members fieldset").append( person.show());
				});
			
		}
		
		$("#found-people-list .filter-nav").find(".active").removeClass("active");
		$("#found-people-list .filter-nav").find(".select-all").parent("li").addClass("active");
		$("#found-people-list .follow-filter-nav").show();
		$("#found-people-list .fb-filter-nav").hide();

		billboard.hijackLinks( ".people-list fieldset" );
	};


	me.displayFacebookFriend = function( users ) 
	{
		billboard.log( "Profile.displayFacebookFriend()");
		billboard.log( users );
		//alert(users);
		var person;
		var url;
		var count_bb =0;
		var count_nonbb = 0;
		
		$(".bb-list .result-div").addClass("bb-result");
		$(".nonbb-list,.bb-list").show();

		for ( var i=0;i<users.length;i++ ) {
			if(users[i].username){
				var username = users[i].username;

				person = $("#person-profile-template").clone();
				person.removeAttr("id");

				if(users[i].profilePhotoUrl && users[i].profilePhotoUrl!='null' && users[i].profilePhotoUrl!=""){
					if ( !users[i].id|| users[i].id=='undefined'){
						person.find(".profile-image-facebook img").attr("src", users[i].profilePhotoUrl);
					}else{
						person.find(".profile-image img").attr("src", users[i].profilePhotoUrl);
					}
				}else{
					person.find(".profile-image img").attr("src", "/images/icons/no-image-user.gif");
				}

				//person.find(".profile-city-state").text(users[i].city+', '+users[i].state);

				person.find("input[@name=add][type=checkbox]").attr("checked","checked");
				if ( !users[i].id|| users[i].id=='undefined')
					person.find("input[@name=add][type=checkbox]").val(users[i].facebookId+"<");
				else
					person.find("input[@name=add][type=checkbox]").val("0<"+username);

				//alert(users[i].userId);
				var personprofile=person.find(".profile-name");
				//Check for Billboard User
				if ( !users[i].id|| users[i].id=='undefined'){//Only Facebook Users
					person.find(".billboard-member").hide();
					personprofile=person.find(".profile-name-facebook");
					//person.find(".profile-image").attr("href", "" );
					person.find(".profile-image").hide();
				}
				else{//Billboard as well as facebook users
					person.find(".profile-name").attr("href", "/user/"+username );
					person.find(".profile-image").attr("href", "/user/"+username );
					person.find(".profile-image-facebook").hide();
					person.find(".billboard-member").html("on Billboard.com as " + username);
				}

				personprofile.text(users[i].firstName+' '+users[i].lastName);

				if( !users[i].city || !users[i].state || !users[i].city || users[i].state=='undefined'){
					person.find(".profile-city-state").hide();
				}
				if(!users[i].firstName || !users[i].firstName || !users[i].lastName || users[i].lastName=='undefined'){
					personprofile.text(username);
				}

				if ( !users[i].id|| users[i].id=='undefined') {
					count_nonbb++;
					person.addClass("invite-bb");
					$(".non-billboard fieldset").append( person.show() ); 
				}
				else{
					count_bb++;
					$(".billboard-members fieldset").append( person.show() ); 
				}

			}
		}

		//$(".follow-wrapper").hide();
		if(users.length>0){
			$(".message-wrapper").show();
			$("#facebookusers").show();
			$("#found-people-list .filter-nav").find(".active").removeClass("active");
			$("#found-people-list .filter-nav").find(".select-all").parent("li").addClass("active");
			$("#found-people-list .filter-nav").show();
		}
		if(count_nonbb ==0 )
			$(".nonbb-list").hide();
		else if(count_bb ==0)
			$(".bb-list").hide();
		else if(count_bb > BB_RESULT_VISIBLE_COUNT)
			$(".bb-list .person-profile").addClass("person-scroll");
		else if(count_nonbb > FB_RESULT_VISIBLE_COUNT)
			$(".nonbb-list .person-profile").addClass("person-scroll");
		

		billboard.hijackLinks( ".people-list fieldset" );
		//billboard.hijackLinks( ".facebook-people-list fieldset" );
		//billboard.hijackLinks( ".message-wrapper" );
	};
	
	me.inviteConfirmation = function(by, val){
		billboard.log("Profile.inviteConfirmation( " + by + " )");
		billboard.log(val);
		var person, count, parentdiv;
		var byfb = false;

		if(by == "byuser"){
			$(".bb-list .message-wrapper").show();
			$(".bb-list .message-wrapper p").text("You are now following these Billboard.com members.");
			if($(".billboard-members .result-div").hasClass("bb-result"))
				count = BB_RESULT_VISIBLE_COUNT;
			else count = USER_RESULT_VISIBLE_COUNT;
			parentdiv = ".bb-list";
		}
		else if(by == "byfb"){
			$(".nonbb-list .message-wrapper p").text("You have invited these Facebook friends to Billboard.com.");
			count = FB_RESULT_VISIBLE_COUNT;
			parentdiv = ".nonbb-list";
			byfb = true;
		}

		$(parentdiv + " .result-div fieldset").empty();
		$(parentdiv + " .filter-nav, .find-head #find-user-form").hide();
	
		for(var i=0;i<val.length;i++){
			person = $("#person-profile-template").clone();
			person.removeAttr("id");
			if( val.length > count) person.addClass("person-scroll");
			person.find(".profile-image img").attr("src", val[i].imageUrl);
			person.find(".profile-name").text( val[i].username );
			if(!byfb && val[i].showBbMember == 'false'){
				person.find(".profile-image").attr("href", "/user/"+ val[i].username );
				person.find(".profile-name").attr("href", "/user/"+ val[i].username );
			}
			else {
				person.find(".profile-image").removeAttr("href");
				person.find(".profile-name").removeAttr("href");
				person.find(".profile-name,.profile-image").addClass("disabled-anchor");
			}

			person.find("input[type=checkbox]").hide();
			person.find(".profile-image-facebook ").hide();
			
			if(val[i].showBbMember == 'false')
				person.find(".billboard-member").hide();
			else person.find(".billboard-member").text(val[i].bbname);

			$(parentdiv + " fieldset").append( person.show());
		}


	};

	me.getFollowers = function( username )
	{
		username = (username)?(username):(billboard.user.username);
		billboard.log( "Profile.getFollowers("+username+")" );
		billboard.social.browseConnections( username, 'followers', me.sort, function(res) { 
			billboard.log("Profile.getFollowers()");
			billboard.log( res );

			//$(".follow-count").text( res.list.length + " Followers");
			me.populateFollowers( res.connections );
		});		
	};

	me.populateFollowers = function( users ) 
	{
		billboard.log("Profile.populateFolowers("+users.length+")");
		billboard.log( users );

		var len = users.length;
		$(".follow-head .follow-count").text( len + " Followers" );
		for ( var i=0;i<len;i++ ) {			
			users[i].profile_photo_url = users[i].profilePhotoUrl;
			users[i].external_id = users[i].username;
		}

		me.populateUsers( users );
	};

	me.getFollowing = function( username )
	{
		username = (username)?(username):(billboard.user.username);
		billboard.log( "Profile.getFollowing("+username+")" );
		billboard.social.browseConnections( username, 'following', me.sort, function(data) { 
			billboard.log( data );
			$(".follow-head .follow-count").text( data.connections.length + " Following" );
			me.populateFollowing( data.connections );
		});		

		/* TAB - hey gowri why'd we do this, i forget? it kills the following tab
		billboard.social.getActivity( username, me.filter, function(data) { 
			billboard.log("getActivity result");
			var events = data.activityevents;
			billboard.log(" "+events.length+" # of events" );
			for ( var i=0;i<events.length;i++ ) {
				me.displayActivity( events[i] );
			}
		});
		*/	
	};

	/**
	 *
	 */
	me.populateFollowing = function( following ) 
	{
		billboard.log("Profile.populateFollowing("+following.length+")");
		var len = following.length;
		var item,src,url;
		
		// sort...
		for ( var i=0;i<len;i++ ) {
			following[i] = following[i].to_user;
		}
		
		var sortFunc;
		if (me.sort=="date") { 
			sortFunc = function( a, b ) { 
				return (a.created<b.created)?(-1):(b.created<a.created)?(1):(0); 
			}
		}
		else {
			sortFunc = function( a, b ) { 
				return (a.username<b.username)?(-1):(b.username<a.username)?(1):(0); 
			}
		}
		following.sort( sortFunc );
		me.populateUsers( following );
	};

	/**
	 * fill the follow-wrapper with a bunch of user 'icons'
	 */
	me.populateUsers = function( users ) 
	{	
		billboard.log("Profile.populateUsers("+users.length+")");
		billboard.log( users );
		// sort..
		var len = users.length;
		var item,src,url;
		$(".follow-wrapper").empty();
		billboard.info(" creating user tiles");
		if (len > 0) {
			for ( var i=0;i<len;i++ ) {
				item = $("#follow-template").clone().removeAttr("id");
				item.find(".follow-name a").text( users[i].external_id );
				url = "/user/"+users[i].external_id;
				item.find(".follow-name a").attr("href",url);
				src = (users[i].profile_photo_url)?(users[i].profile_photo_url):("/images/defaults/user-69.gif");
				item.find(".profile-imgwrap img").attr("src",src);
				item.find(".profile-imgwrap a").attr("href",url);
				// activate delete button
				item.find(".delete").click( function() {
					var user = $(this).parent().find(".follow-name a").text();
					billboard.log(" ending relationship with " + user );
					billboard.social.stopFollow( user, function(data) { 
						me.getFollowing( billboard.publicUser );						
					});
				});

				item.show();
				$(".follow-wrapper").append( item );
				//$(".follow-wrapper").append( $("<div></div>") );
			}
		}
		else {
			if ( billboard.subsection == 'followers' ) {
				$(".follow-wrapper").append( $('<div class="no-results">No one\'s following you yet. Make yourself visible! If you\'d like a following, just keep adding to your profile and invite friends to join Billboard.</div>') );
			}
			if ( billboard.subsection == 'following' ) {
				if ( billboard.publicUser == billboard.user.username ) { 
					$(".follow-wrapper").append( $('<div class="no-results">Haven\'t connected to anyone yet? There\'s a whole crowd of people here, united by music, defining what they love and what they don\'t. Find them. Compare tastes. Discover new music. Get in on the conversation.</div>') );
				}
			}
		}
		// turn on manage buttons if private profile
		// if ( public user == profile user ) { turn on all ".delete"'s }
		
		// TODO: run hijack...
		billboard.hijackLinks( ".follow-wrapper" );
		
	};

	/**
	 *
	 */
	me.filterFavorites = function( filter ) 
	{
		$(".filter-nav ul li").removeClass("active");
		$("."+filter).parent().addClass("active");

		me.filter = filter.substr( 7 );

		billboard.log( "filter: "+me.filter );
		
		me.getFavorites( billboard.publicUser );
	
	};
	
	me.neighborCharts = function(username, callback)
	{
		var params = {};
		var d = new Date();
		var curr_date = d.getDate();
		var curr_month = d.getMonth();
		var curr_year = d.getFullYear();

		username = (username)?(username):(billboard.user.username);
		$("#chart-item-container").empty();
		me.neighborChartList = [];
		

		$("#neighborhood-chart .neighborhood-chart-top p.date").text("For " +monthNames[curr_month] + " " + curr_date + ", " + curr_year);
		
		$.ajax({  
			type: "POST",  
			url: URL_BB_GET_NCHARTS + username,
			async: false, 
			data: username, 
            dataType : "text",	
            timeout: 5000,
        	error:function() { 
				billboard.info("data: error" );
			},
			success: function(data){
				var strLen = data.length;
				var songList = data.slice(1,strLen-1);
				var songIds=songList.split(",");
				var isLast = false;
				for(i=0; i < songIds.length; i++){
				   params = {};
				   params.id = songIds[i].replace(/^\s+|\s+$/g, '');
				   params.isLast = (i+1 == songIds.length) ? true : false;
				   me.getNeighborChartsDetails(params, function(){
					   if(callback) callback();
				   });
				}
			}
		});
	};

	me.getNeighborChartsDetails = function(params, callback){
		var entityId = "";
		var isLast = params.isLast;
		var callback = callback;
		var truncTitle = "";
		var chartItem = {};
		
	

		billboard.getItemDetails( params.id, "song", function(data) {
			if ( typeof(data) == "undefined" || typeof(data.response) == "undefined" ) {
				return;
			}
			var item = data.response.body.FavoriteItemView;
			var row = $("#chart-item-template").clone();
			var rowText;
			var artistNm = "undefined";
			
			if ( row ) {
				row.removeAttr("id");
				if ( item.type == "song" ) {
					entityId = "song-" + item.id;
					row.find(".love-bar").append("<div class='entityId' style='display:none'>" + entityId + "</div>");
					if(item.photoUrl && item.photoUrl.length > 0)
						row.find(".stats .thumbnail img").attr("src", item.photoUrl);
					
					truncTitle = (item.title.length <=18) ? item.title : (item.title.charAt(18)!= " ") ? item.title.substring(0,18) + "..." : item.title.substring(0,17) +"...";
					row.find(".unit-2 h2 a").html( truncTitle );
					row.find(".unit-2 h2 a").attr("href",item.url );
					row.find(".stats .thumbnail").attr("href", item.url);
					row.find(".stats .rank").text(me.neighborChartList.length+1);
					var artistLink = "";
					if(item.artists){
						for(i=0; i < item.artists.length; i++){
						   artistLink += "<a href='"+  	item.artists[i].link + "'> "+ item.artists[i].name + "</a> &nbsp;" ;
						}
						row.find(".unit-2 h3").html(artistLink);
					}
					
					if ( item.song_url && item.song_url.length > 0 ) {
						$(".play").show();
						row.find(".item").append( $("<div class='song_url'>"+item.song_url+"</div>").hide() );
						row.find(".play").click( function() { 
							var surl = $(this).parents(".item").find(".song_url").text();
							var lname = $(this).parents(".item").find(".unit-2 h2 a").text();
							var photo = $(this).parents(".item").find(".unit-1 img").attr("src");
							var link = $(this).parents(".item").find(".unit-2 h2 a").attr("href");
							if(item.artists)
							
								artistNm = item.artists[0].name;
							billboard.player.playMSSong(surl);
							googleA.trackEvent ( 1, 'Song', artistNm, lname, photo, link);
							//billboard.facebook.publishPlay(lname,artistNm,photo,link);
						});
						chartItem.title = item.title;
						chartItem.id = item.lalaId;
						me.neighborChartList.push(chartItem);
					}
					row.hover(function(){
							row.css({"background-image" : "url(/images/backgrounds/drop-shadow-top-small-light-pink.png)"});
							row.find(".item").css("background-color","#fdf4f9");
						},
						function(){
							row.css({"background-image" : "url('/images/backgrounds/drop-shadow-top-small.png')"});
							row.find(".item").css("background-color","#ffffff");
					});
					
					billboard.hijackLinks( row );
					$("#chart-item-container").append(row.show());
					billboard.social.updateLoveHateBar($("#chart-item-container .item:last"));
					
				}
				
			}
			else {
				billboard.log("row no good");
				billboard.log( row );
			}

			if(isLast && callback) callback();
		});
	};

	
	/**
	 *
	 */
	me.getActivity = function( username )
	{
		billboard.log("Profile.getActivity()");
		username = (username)?(username):(billboard.user.username);

		$("#activity-list-container").empty();

		billboard.social.getActivity( username, me.filter, function(data) { 
			billboard.log("getActivity result");
			var events = data.activityevents;
			
			billboard.log(" "+events.length+" # of events" );
			if(events.length==0) {
			billboard.log('Filter is: '+me.filter);
			 if(me.filter=='rating')
			$("#activity-list-container").append( "<div class='no-results'>Admit it:Music is part of who you are. Search for artists and albums you love to start building your profile.</div> " );
			 else if (me.filter=='follow')
			$("#activity-list-container").append( "<div class='no-results'>Haven't connected to anyone yet? There's a whole crowd of people here, united by music, defining what they love and what they don't. Find them. Compare tastes. Discover new music. Get in on the conversation.</div>" );
			}
			else {
				events.sort(function(a, b){
								return (new Date(a.created) < new Date(b.created)) ? 1 : (new Date(a.created) > new Date(b.created)) ? -1 : 0;
							});
				me.activityPagination(events);
			
			}
		});
	};
	
	me.activityPagination = function(event)
	{
		var events = event;
		var eventDetails;
		var favevent = [];
		var dataString;

		me.page = 0;

		for(i=0; i<events.length; i++){
			//billboard.info("activityPagination dispa page: " +i + " " +formatDate( events[i].created));
			if ( events[i].container && events[i].container.ExternalEntity && events[i].container.ExternalEntity.uid && events[i].container.ExternalEntity.uid.indexOf("user") == -1 ) { 
				if ( (me.filter == "all") || 
							(me.filter == "user" ) ||
							(me.filter=="follow") ||
							(me.filter=="rating" && events[i].message.indexOf("love")>=0)
							){ 
						dta = events[i].container.ExternalEntity.uid.split("-");
						if( dta.length <= 3 || dta[1] == 'of' ){ //dta[1] == 'of' special case for column/photos-of-the-week
							type = dta[0];
							id = dta[dta.length-1];

							if( type.indexOf("forum") >-1){
								events.splice(i,1);
								i--;
								continue;
							}
							if(type.indexOf("video") >-1){
								continue;
							}
						
							if ( typeof(id)!="undefined" && typeof(type)!="undefined"  ) { 
								if(type != "song" && type != "album" && type != "artist"){
									type="article";
								}
								else continue; //only perform check for articles
								url = "/favorite-"+type+".json";
								dataString = "id=" + id;	
						
								$.ajax({  
										type: "POST",  
										url: url,
										async: false, 
										data: dataString, 
										dataType : "json",
										success: function(result) {
											if ( typeof(result.response) == "undefined" || result.response.head.status=="error" ) {
												events.splice(i,1);
												i--;
											}	
											return;
										},
										error: function(){
											events.splice(i,1);
											i--;
										}
								});
							}
						}
						else{
							events.splice(i,1);
							i--;
						}
				}
				else if(me.filter=="rating" && events[i].message.indexOf("love") == -1){
						events.splice(i,1);
						i--;
				}
			}
			else if(me.filter=="rating"){
					events.splice(i,1);
					i--;
			}
		}
	
		var li, ul;
		me.totalNumPages = Math.ceil(events.length/me.numPerPage);
		$(".profile-listing .pagination").hide();
		
		if(events.length <= me.numPerPage){
			me.getPage( me.page, events );
					
		 }
		
		if ( events.length > me.numPerPage ) {
			
			ul = $(".profile-listing .pagination ul");
			if ( billboard.subsection == "conversations" && $("#conversation-id").text().length <= 0 ) {
				$(".profile-listing .pagination").hide();
			}
			ul.empty();
			$(".profile-listing .pagination").show();
			if ( me.page ==0 ) {
				
				me.getPage( me.page, events );
			}
			
			// add the previous arrow if higher than page 1
			
			li = $("<li class='arrow-left'><a href='javascript:void(0);'>&lt;</a></li>");
			ul.append( li );
			ul.find(".arrow-left a").click(function(){
				me.getPage( me.page-1, events );
				return false;
			});

			// initialize, page 1, no previous page
			if(me.page == 0)
				$(".profile-listing .pagination .arrow-left").hide();
			
			
			// add all page numbers
			for ( var i=0;i<me.totalNumPages;i++ ) {
				li = $("<li class='activitypage-"+ i +"'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				if ( i == me.page ) li.addClass("on");
				ul.append( li  );
				ul.find(".activitypage-"+ i +" a").click( function() { 
					me.getPage( ($(this).text()-1), events );
					return false;
		
				});
			
				
				
			}
			
			// add the next arrow if less than total pages
			
			li = $("<li class='arrow-right'><a href='javascript:void(0);'>&gt;</a></li>");
			ul.append( li );
			ul.find(".arrow-right a").click(function(){
				me.getPage(me.page+1, events );
				return false;
			});
				
			if ( me.page < (me.totalNumPages-1) ) 
				$(".profile-listing .pagination .arrow-right").show();
			else $(".profile-listing .pagination .arrow-right").hide();
		}
		
	};
	me.getPage = function( num, events)
	{

		billboard.log("in getPage page: " + num + "even: " + events);
		var count = (events) ? events.length :0;
		me.page = num;

		// scroll back up to the nav
		var jump =  $("#content").offset().top;
		$('html,body').animate( {scrollTop: jump }, 1000 );

		$(".profile-listing .pagination ul li").removeClass("on");
		$(".profile-listing .pagination ul li.activitypage-" + me.page).addClass("on");
		
		// hide or show the previous arrow
		if( me.page > 0 )
			$(".profile-listing .pagination .arrow-left").show();
		else $(".profile-listing .pagination .arrow-left").hide();

		// hide or show the next arrow
		if ( me.page < (me.totalNumPages-1) ) 
			$(".profile-listing .pagination .arrow-right").show();
		else $(".profile-listing .pagination .arrow-right").hide();

		$("#activity-list-container .activity-row").remove();
		if(count > 0 && num == 0){
			for(i=num*me.numPerPage; i<count && i<=(num*me.numPerPage)+9; i++){
					me.displayActivity( events[i]);
				}	
			}
		
		if(count > 0 && num > 0){
			for(i=num*me.numPerPage; i<count && i<(num*me.numPerPage)+10; i++){
					billboard.info("num>0: " +num*me.numPerPage + "Date: " +formatDate( events[i].created));
					me.displayActivity( events[i] );
				
				}	
			}
		
	};
	/**
	 *
	 */
	me.displayActivity = function( event )
	{
		//alert("activiy in display: " + formatDate( event.created ));
		billboard.log(event);
		var cats = ["none","rating","comment","follow"];

		var type, dta, id;
		var dataString ="";
		var url = "";
		var performer;
		var target;
		var artists;
		var photo_url = "/images/defaults/user-69.gif"; 

		if ( event.container && event.container.ExternalEntity && event.container.ExternalEntity.uid && event.container.ExternalEntity.uid.indexOf("user") == -1 ) { 
			
			dta = event.container.ExternalEntity.uid.split("-");
			type = dta[0];
			id = dta[dta.length-1];
		
			if ( typeof(id)=="undefined" || typeof(type)=="undefined"  ) { 
				billboard.error( "getItemDetails() -  a required parameter was null", true );
				return;
			}
			if(type != "song" && type != "album" && type != "artist" && type!="video")
					type="article";
			url = "/favorite-"+type+".json";
			dataString = "id=" + id;	   
				
		
			if(type!="video"){
				$.ajax({  
						type: "POST",  
						url: url,
						async: false, 
						data: dataString, 
						dataType : "json",
						error: function() { return; },
						success: function(result) {  
					
							if(result.response.head.status != "error"){
								result.response.body.FavoriteItemView.type = type;
								billboard.info("activiy after ajax error1: " + formatDate( event.created ));
							}
							  
							if ( typeof(result.response) == "undefined" || result.response.head.status=="error") {
								//if(callback) callback(index);
								billboard.info("activiy after ajax error2: " + formatDate( event.created )+ " Type: " + type + " Id: " + id +" "+ result.response.head.message);
								return;
							}
							if(typeof(result.response.body)!='undefined'){
								billboard.info("activiy after ajax error3: " + formatDate( event.created ));
								 event.item = result.response.body.FavoriteItemView;
							}
							
						if ( (me.filter == "all") || 
								(me.filter == "user" ) ||
								(me.filter=="follow") ||
								(me.filter=="rating" && event.message.indexOf("love")>=0)
								) { 
							//billboard.info("activiy after ajax filter: " + formatDate( event.created ) + "filter: " + me.filter);
							var elem;

							dateStr = formatDate( event.created );
							performer = event.performer.user.external_id;
							photo_url = event.performer && event.performer.user.profile_photo_url!=null ? event.performer.user.profile_photo_url : "/images/defaults/user-69.gif";
							
							elem = $("#activity-template").clone();
							elem.removeAttr("id");
							if(typeof(event.item) !="undefined")
							elem.find("img").attr("src",photo_url);
							elem.find(".user").text( performer );
							elem.find(".user").attr("href","/user/"+performer);

							if ( event.message.indexOf("love") >= 0 ) {
								elem.find(".action").append( $("<img src='/images/icons/heart.png' />") );
							}
							else if ( event.message.indexOf("hate") >= 0 ) {
								elem.find(".action").append( $("<img src='/images/icons/dagger.png' />") );
							}
							else {
								elem.find(".action").html( decodeURI(event.message) );
							}
							if(typeof(event.item) !="undefined"){
								// get artist names
								if(event.item.artists){
									artists ="";
									for(var i=0;i<event.item.artists.length;i++){
										artists += '<a href="'+ event.item.artists[i].link +'">' + event.item.artists[i].name + '</a>';
										if(i+2<event.item.artists.length) artists += ", ";
										else if(i+2 == event.item.artists.length) artists += " and "; 
									}
								}
								if( type =='song') elem.find(".target").html( 'the song <a href="'+ event.item.url +'"> "'+ event.item.title +'"</a> by ' + artists);
								else if( type =='album') elem.find(".target").html( 'the album <a href="'+ event.item.url +'"><i>'+ event.item.title +'</i></a> by <a href="'+ event.item.artistURL +'">' + event.item.artist + '</a>');
								else if( type == 'article') elem.find(".target").html( 'the article <a href="'+ event.item.url +'">' + event.item.title +'</a>');
								else if( event.item.title && event.item.title!=null ){
									elem.find(".target a").html( event.item.title );
									elem.find(".target a").attr("href",event.item.url);
								}
							}
							
							elem.find(".date").html( dateStr );
							elem.show();
							$("#activity-list-container").append( elem );
							
							billboard.hijackLinks( elem );
						}
						
					}
					
				});
			}
			else{
				$.getJSON( "http://www.billboard.com/3rdparty/data/brightcove/services/library?command=find_video_by_id&video_id="+id+"&callback=?", function(data,status) {
					dateStr = formatDate( event.created );
					performer = event.performer.user.external_id;
					photo_url = event.performer && event.performer.user.profile_photo_url!=null ? event.performer.user.profile_photo_url : "/images/defaults/user-69.gif";
					elem = $("#activity-template").clone();
					elem.removeAttr("id");
					elem.find("img").attr("src",photo_url);
					elem.find(".user").text( performer );
					elem.find(".user").attr("href","/user/"+performer);

					if ( event.message.indexOf("love") >= 0 ) {
						elem.find(".action").append( $("<img src='/images/icons/heart.png' />") );
					}
					else if ( event.message.indexOf("hate") >= 0 ) {
						elem.find(".action").append( $("<img src='/images/icons/dagger.png' />") );
					}
					else {
						elem.find(".action").html( event.message );
					}
					elem.find(".target a").html( data.name );
					elem.find(".target a").attr("href","/video/id/" + data.id);
					elem.find(".date").html( dateStr );
					elem.show();
					$("#activity-list-container").append( elem );
					
					billboard.hijackLinks( elem );
							
				});
			}
			
			
		}
		else { 
			//billboard.info("activiy in else display: " + formatDate( event.created ));
			type = "user";
			if ( event.container && event.container.user) {
				id = event.container.user.external_id;
			}
			else if(event.container && event.container.ExternalEntity && event.container.ExternalEntity.uid) {
				id = event.container.ExternalEntity.uid.split("-")[1];
			}
			else if( !event.container && event.performer.user){
				id = event.performer.user.external_id;
			}
			var idString="user="+id;
			 url = billboard.social.getExecuteUrl(URL_CF_USERGET, { user:id });
			
				$.ajax({  
					type: "POST",  
					url:url,
					async: false, 
	                dataType : "json",					
					error:function() { return;},
					success: function(data) { 
				photo_url = "/images/defaults/user-69.gif"; 
				if(event.item && event.item.profile_photo_url!=null) 
					photo_url = event.item.profile_photo_url; 
				else if(event.performer && event.performer.user.profile_photo_url!=null)
					photo_url = event.performer.user.profile_photo_url;
				event.item = data.user;
				//billboard.log( event );
				//billboard.log("2. filtering activity: ["+me.filter+"], "+event.message );
				
				if (me.filter == "all" || me.filter == "user" || me.filter == "follow" ) { 
					dateStr = formatDate( event.created );
					performer = event.performer.user.external_id;
					target = event.item.external_id;

					elem = $("#activity-template").clone();
					elem.removeAttr("id");
					//elem.find("img").attr("src",event.item.photoUrl);
					elem.find("img").attr("src",photo_url);
					elem.find(".user").text( performer );
					elem.find(".action").html( " " + event.message + " " );
					if(event.category!=4){
						elem.find(".target a").html( target );
						elem.find(".target a").attr( "href", "/user/"+target );
					}
					elem.find(".date").html( dateStr );
					elem.show();
					$("#activity-list-container").append( elem );
					
					billboard.hijackLinks( elem );
				}
					}
			});
		}
	};

	me.removeAllFavorites = function()
	{
		//billboard.log("Profile.removeAllFavorites()");

		var favs = $("#favorites-container .entity-id");
		billboard.log( favs.length );
		
		for ( var i=0;i<favs.length;i++ ) {
			me.removeFavorite( $(favs[i]).text() );
		}

		$(".favorite-header h2").text( "0 Favorites" );
		billboard.modal.hide();
	};

	me.removeFavorite = function( id )
	{
		//billboard.info("Profile.removeFavorite("+id+")");
		if ( id && id.length ) {
			billboard.social.rate ( id, 'entity', 'CustomRating0', 0, function(response) {
				// find the element in the list, and rmove it
				var ents = $("#favorites-container .entity-id");
				for ( var i=0;i<ents.length;i++ ) {
					if ( $(ents[i]).text() == id ) {
						$(ents[i]).parent().remove();
					}
				}
			});
		}
		else {
			billboard.error("Entity Id is null");
		}
	};

	me.getFavorites = function( username )
	{			
		username = (username)?(username):(billboard.user.username);
		billboard.log( "Profile.getFavorites("+username+")" );

		$("#favorites-container").empty();

		$(".favorite-header .playbtn").hide();
		$(".favorite-header h2").text( "0 Favorites" );

		//billboard.social.browseEntity( username, function(data) { 		
		//billboard.social.search( "ratedby:"+username, "entity", null, 0, 100, function(data) { 
		var t = me.filter=="article"?"all":me.filter;
		billboard.social.getHighestRated( t, { period:"LastYear",rating:"CustomRating0",start:0, count:100, user:username }, function( data ) { 
			billboard.log( "<--- getHighestRated results -->" );
			billboard.log( data );
			
			var id,type;
			var entities = data.entities;

			var favorites = new Array();
			var count = 0;
			for ( var i=0;i<entities.length;i++ ) {
				/*
				type = entities[i].uid.split("-")[0];
				id = entities[i].uid.split("-")[1];
				*/
				//Code change for BBCOM-38 to pass in the correct UIDs
				var lastIndex = entities[i].uid.lastIndexOf("-"); 
				type = entities[i].uid.substr(0,lastIndex); 
				id = entities[i].uid.substr(lastIndex + 1); 

				// only use the ones we "love" which should have a value > 0, and make sure its 
				// a "good" entity, with a type prefix
				if ( entities[i].sort_rank == 0 || !type || !id ) {
					continue;
				}

				
				if ( type != "song" && type != "album" && type != "artist"){
					type="article";
				}

				billboard.log( "filter: "+me.filter +", type: "+type );
				if ( type == me.filter || me.filter == "all" ) {

					count++;

					// pull back the information for all favorites
					billboard.getItemDetails( id, type, function(data) {
						if ( typeof(data) == "undefined" || typeof(data.response) == "undefined" ) {
							// SWALLOWING THIS: billboard.error("Profile.search() - getItemDetails returned null response");
							return;
						}
						var item = data.response.body.FavoriteItemView;
						var row = $("#"+item.type+"-row-template").clone();
						var rowText;
						var artistNm = "undefined";

						if ( row ) {
							if ( item.type == "song" ) {
								//billboard.log("adding song item");
								if(item.photoUrl && item.photoUrl.length > 0)
									row.find(".pic img").attr("src", item.photoUrl);
								
								row.find(".details .name a").html( item.title );
								//row.find(".details .artist a").html( item.artist );
								row.find(".details .name a").attr("href",item.url );
								//row.find(".details .artist a").attr("href",item.url );
								var artistLink = "";
								if(item.artists){
									for(i=0; i < item.artists.length; i++){
									   artistLink += "<a href='"+  	item.artists[i].link + "'> "+ item.artists[i].name + "</a> &nbsp;" ;
									}
									row.find(".details .artist a").append(artistLink);
								}
								
								if ( item.lalaId && item.lalaId.length > 0 ) {
									$(".favorite-header .playbtn").show();
									row.append( $("<div class='lala-id'>"+item.lalaId+"</div>").hide() );
									row.find(".action .playbtn").click( function() { 
										//billboard.log( $(this) );
										//billboard.log( $(this).parents(".favorite-row") );
										var song_url = $(this).parents(".favorite-row").find(".song_url").text();
										var lname = $(this).parents(".favorite-row").find(".name a").text();
										var photo= $(this).parents(".favorite-row").find(".pic img").attr("src");
										var link = $(this).parents(".favorite-row").find(".name a").attr("href");
										//billboard.log( lid + ":" + lname );
										if(item.artists)
											artistNm = item.artists[0].name;
											
											//var url = 'testing';
					
					                     	javascript:billboard.player.playMSSong(surl);
											
										billboard.player.setQueue( [ {title:lname,id:lid} ] );
										googleA.trackEvent ( 1, 'Song', artistNm, lname, photo, link);
										//billboard.facebook.publishPlay(lname,artistNm,photo,link);
									});
								}
								else {
									row.find(".action a").hide();
								}
							}
							else if ( item.type == "album" ) {
								//billboard.log("adding album item");
								if(item.photoUrl && item.photoUrl.length > 0)
									row.find(".pic img").attr("src", item.photoUrl);							
								row.find(".pic img a").attr("href",item.url );
								row.find(".details .name a").html( item.title );
								row.find(".details .name a").attr("href",item.url );
								row.find(".details .artist a").html( item.artist );
								row.find(".details .artist a").attr("href",item.artistURL );
								if ( item.songs != undefined && item.songs[0].song_url && item.songs.song_url > 0 ) {
									 
									
									row.find(".action .playbtn").click( function() { 
									//billboard.log( $(this) );
									//billboard.log( $(this).parents(".favorite-row") );
									var queue = [];var lname,surl;
									for ( var i=0;i<item.songs.length;i++ ) {
										lname = item.songs[i].name;
										surl = item.songs[i].song_url;
										queue.push( { id:surl,title:lname}  );
									}
									//billboard.log( lid + ":" + lname );
									
									//var url = 'testing';
					
									javascript:billboard.player.playMSSong(surl);
									
									//billboard.player.setQueue( queue );
									googleA.trackEvent ( 1, 'Album', item.artist, item.title );
											});
								}
								else {
										row.find(".action a").hide();
				                }								
							}
							else if ( item.type == "artist" ) {
								//billboard.log("adding artist item");
								row.find(".pic img").attr("src", item.photoUrl);
								row.find(".pic img a").attr("href", item.url );
								row.find(".details .artist a").html( item.title );
								row.find(".details .artist a").attr("href", item.url);
							}
							else if ( item.type == "article" ) {
								//billboard.log("adding article item");
								row.find(".pic img").attr("src", item.photoUrl);
								row.find(".pic img a").attr( "href", item.url );
								row.find(".details .news-name a").html( item.title );
								row.find(".details .news-name a").attr( "href", item.url );
								row.mouseover( function(){$(this).addClass("tout-highlight");});
								row.mouseout( function(){	$(this).removeClass("tout-highlight");});
							}
							if ( billboard.user.isLoggedIn() && billboard.user.username == billboard.publicUser){
								row.find(".action").css("display", "block");
								row.find(".action .trash").css("display", "block");

								if(item.type == "article"){
									lastIndex = item.url.lastIndexOf("/");
									var articleUrl = item.url.substr(0,lastIndex);
									var articleType = articleUrl.substr(articleUrl.lastIndexOf("/")+1,lastIndex); 

									if(articleUrl.indexOf("column")!=-1)
									articleType = "column\/"+articleType;

									row.find(".action .trash").attr("href", "javascript:billboard.profile.removeFavorite('"+articleType+"-"+item.id+"')");
									row.append( $("<div class='entity-id'>"+articleType+"-"+item.id+"</div>") );
								}
								else{
									row.find(".action .trash").attr("href", "javascript:billboard.profile.removeFavorite('"+item.type+"-"+item.id+"')");
									row.append( $("<div class='entity-id'>"+item.type+"-"+item.id+"</div>") );
								}
							}


							// update the header that contains the favorite count
							var c = parseInt( $(".favorite-header h2").text().split(" ")[0] );
							if ( isNaN(c) ) c = 0;
							$(".favorite-header h2").text( (c+1) + " Favorites" );

							row.removeAttr("id");
							billboard.hijackLinks( row );
							row.show();
							$("#favorites-container").append( row );
						}
						else {
							billboard.log("row no good");
							billboard.log( row );
						}
					});
				}
			}

			// update favorite count display
			//			$(".favorite-header h2").text( count + " Favorites" );

			// 
			if ( count == 0 ) {
				$("#favorites-container").append( $('<div class="no-results">Admit it:Music is part of who you are. Search for artists and albums you love to start building your profile.</div>') );
			} 
			else if ( count != 0) {
				if ( billboard.user.isLoggedIn() && billboard.user.username == billboard.publicUser){
					$(".remove-all").css("display", "block");
					$('#favorites-listing .remove-all').click(function(){
						var removeAllHtml='<div class="removeAllMessage"><div><h2>Clear All Favorites?</h2>By doing this, you\'ll delete all of your saved artists, albums, songs and articles - for good. Are you sure?<div class="modal-buttons"><a class="button type-five cancel no-ajax" href="javascript:void(0);"><span>Cancel</span></a><a class="button type-four remove" href="javascript:void(0);"><span>Yes, clear all</span></a></div></div></div>';
						billboard.modal.show(removeAllHtml,true);

						$(".removeAllMessage a.cancel").click(function(){
							billboard.modal.hide();
							return false;
						});
						$(".removeAllMessage a.remove").click(function(){
							billboard.profile.removeAllFavorites();
							return false;
						});

						return;
					});
				}				
			}			
		});
	};

    var initEmail = '';
    var initPassword = '';
    var initCity = '';
    var initState = '';
    var initComments = true;
    var initNewsletter = 'false';

    me.initSettings = function(){

        initEmail = $("#edit-settings [name=email]").val();
        initPassword = $("#edit-settings [name=password]").val();
        initCity = $("#edit-settings [name=city]").val();
        initState = $("#edit-settings [name=state]").val();
        initComments = $($("#edit-settings [name=profileComment]")[0]).attr("checked");
        initNewsletter = $("input[name=newsletterDailyNews]").val();

        if (billboard.user.isLoggedIn() && billboard.user.username == billboard.publicUser){
            $("#change-profile-photo").show(); 
        }

        $(".setting-edit, .change-fields .cancel").click(function(){
            me.editSetting(this);
            return false;
        });        

        $(".change-fields button").click( function() {		
            var value = $(this).attr("id");
            value = value.substring(value.indexOf("-")+1);
            $("#edit-settings [name=change]").val(value);
            //Validate password, 
            if ( value == 'password' ) {
                me.validateSetting();
            } 
			else {
                me.editSettings();
            } 
            return false;
        });        

        $("#edit-settings").submit(function(){
            $("#edit-settings [name=change]").val("options");
            me.editSettings();
            return false;
        });

        
		$("#edit-settings #deactivate").click(function(){
			var confirmDeactivate='<center><div id="deactivate-account" class="deactivate-account">Are you sure you want to deactivate your account? All your activity and favorites will be deleted.<br/><br/><button type="submit" >Deactivate</button><button class="cancel-deactivate" type="submit" >Cancel</button></div></center>';
			billboard.modal.show(confirmDeactivate,true);
			$('#deactivate-account  button').click(function(){
				var confirm=$(this).html();
				if(confirm=='Deactivate') {
					billboard.modal.hide();	
					me.deactivateAccount();
				}
				else
				billboard.modal.hide();		   

			});
			
			return false;
		});

        $("input[name=enableFB]").click(function(){
            var $chbx = $("input[name=enableFB]");
            if($chbx.attr("disabled") != "disabled"
                || $chbx.attr("disabled") == false){
                var fbCheckboxes = $("#fb-checkboxes :checkbox");
                $.each(fbCheckboxes,function(i,v){
                    if($chbx.attr("checked") == true){
                        $(v).attr("disabled","");
                    } else {
                        $(v).attr("disabled","disabled");
                        $(v).attr("checked","");
                    }
                });
            }
        });

        $("input[name=unlinkAccounts]").click(function(){
            var fbOptions = $("#fb-options :checkbox:not([name=unlinkAccounts])");
            $.each(fbOptions,function(i,v){
                if($("input[name=unlinkAccounts]").attr("checked") == true){
                    $(v).attr("checked","");
                    $(v).attr("disabled","disabled");
                } else {
                    $(v).attr("disabled","");
                }
            });
        });

        if(billboard.user.facebookId!=null && billboard.user.facebookId!="") {
            $("input[name=enableFB]").removeAttr("disabled");
            $("input[name=unlinkAccounts]").removeAttr("disabled");
        } else {
            $("input[name=enableFB]").attr("disabled","disabled");
            $("input[name=unlinkAccounts]").attr("disabled","disabled");
        }

        $("input[name=newsletterDailyNews]").click(function(){
            $("input[name=newsletterDailyNews]").val() == 'true' ? $("input[name=newsletterDailyNews]").val('false') : $("input[name=newsletterDailyNews]").val('true');
        });
    };

    me.editSetting = function(clickAnchor){
        var anchor = $(clickAnchor);
        var settingAction = anchor.attr("id");
        var setting = settingAction.substring(settingAction.indexOf("-") + 1); 
        var settingType = settingAction.substring(0,settingAction.indexOf("-")); 
        if (setting == 'email'){
            $("#edit-settings [name=email]").val(initEmail);
        } else if (setting == 'password'){
            $("#edit-settings [name=password]").val(initPassword);
        } else if (setting == 'location'){
            $("#edit-settings [name=city]").val(initCity);
            $("#edit-settings [name=state]").val(initState);
        } else if (setting == 'comments'){
            if (initComments == true){
                $($("#edit-settings [name=profileComment]")[0]).attr("checked",true);
                $($("#edit-settings [name=profileComment]")[1]).attr("checked",false);
            } else {
                $($("#edit-settings [name=profileComment]")[0]).attr("checked",false);
                $($("#edit-settings [name=profileComment]")[1]).attr("checked",true);
            }
        }
        $("#change-" + setting).toggle();
        var hasError = $("#setting-" + setting).find(".error");
        if (hasError.length > 0){
           $("#setting-" + setting + " .error").remove(); 
        }
    };
 
	me.validateSetting = function(){
	 
		var pass=$('#change-password input').val();
		
		
		if(pass.length<6||pass.length>50||pass.indexOf(' ')>-1||pass.indexOf('~')>-1||pass.indexOf('{')>-1||pass.indexOf('}')>-1||pass.indexOf('|')>-1) 
		{
			var oldText = $("#setting-password").text();
			oldText = oldText.indexOf("-") >= 0 ? oldText.substring(0,oldText.indexOf("-") - 1) : oldText;
			$("#setting-password").html(oldText + ' <span class="error">- ' + ' Passwords must be 6 to 50 characters long and can only contain the following characters a-z A-Z 0-9 ` ! @ $ % ^ & * ( )  _ = + [ ] ; : \' " , < . > / ?' + '</span>');
			return false;
		}
		else { 
			var oldText = $("#setting-password").text();
			if( oldText.indexOf("-") >= 0 )
			oldText=oldText.substring(0,oldText.indexOf("-") ) ;
			$("#setting-password").html(oldText);
			me.editSettings();
			}
	};

    me.editSettings = function(){
        var $form = $("#edit-settings");
        var change = $("#edit-settings [name=change]").val();

        //build the string of parameters
        //var fields = $("#edit-settings :checkbox:not([name=newsletterDailyNews])").serialize();
        var fields = '';
        if (change == 'options'){
            //set the value of checked checkboxes to true
            var trueCheckBoxes = $("#edit-settings :checkbox:checked:not([name=newsletterDailyNews])");
            for (var i = 0; i < trueCheckBoxes.length; i++){
                trueCheckBoxes[i].value = true;
                fields += trueCheckBoxes[i].name + "=true&"
            }
            //add the unchecked check boxes and pass as false
            var falseCheckBoxes = $("#edit-settings :checkbox:not(:checked):not([name=newsletterDailyNews])");
            for (var i = 0; i < falseCheckBoxes.length; i++){
                falseCheckBoxes[i].value = "false";
                fields += falseCheckBoxes[i].name + "=false&"
            }
            fields = fields.substring(0,fields.length - 1);
			me.updateFbPublishing(fields);
        } else if (change != 'options' && change != 'location' && change != 'comments'){
            fields = change + "=" + $("#edit-settings [name=" + change +"]").val();
        } else if (change == 'location'){
                fields = $("#edit-settings [name=city]").val() != '' ? "city=" + $("#edit-settings [name=city]").val() : "city=";
                fields += $("#edit-settings [name=state]").val() != '' ? "&state=" + $("#edit-settings [name=state]").val() : '&state=';
        } else if (change == 'comments'){
            fields = "profileComment=" + $("#edit-settings [name=profileComment]:checked").val();
        }

billboard.log("change = " + change);
billboard.log("the fields = " + fields);

        $.ajax({
            type: "POST"
            ,url: $form.attr("action")
            ,data : fields
            ,dataType : "json"
            ,success:function(data, textStatus) {
                if (data.response.head.status == "success"){
                    $(".change-fields").hide();
                    if (change == 'email'){
                        $("#setting-email").html($("#edit-settings [name=email]").val());
                        initEmail = $("#edit-settings [name=email]").val();
                    } else if (change == 'password'){
                        initPassword = $("#edit-settings [name=password]").val();
                    } else if (change == 'location'){
                        $("#setting-" + change).html($("#edit-settings [name=city]").val() + ($("#edit-settings [name=city]").val() == '' || $("#edit-settings [name=state]").val() == '' ? '' : ', ') + $("#edit-settings [name=state]").val());
                        initCity = $("#edit-settings [name=city]").val();
                        initState = $("#edit-settings [name=state]").val();
                    } else if (change == 'comments'){
                        if ($($("#edit-settings [name=profileComment]")[0]).attr("checked") == true){
                            $("#setting-" + change).html("On");
                            $($("#edit-settings [name=profileComment]")[0]).attr("checked",true);
                            $($("#edit-settings [name=profileComment]")[1]).attr("checked",false);
                            initComments = true;
                        } else {
                            $("#setting-" + change).html("Off");
                            $($("#edit-settings [name=profileComment]")[0]).attr("checked",false);
                            $($("#edit-settings [name=profileComment]")[1]).attr("checked",true);
                            initComments = false;
                        }
                    } else if (change == 'options'){
                        $('html,body').animate( {scrollTop: 0 }, 1000 );
                        $("#content-wrapper .header #profile-status-message").html(data.response.head.message);
                        //facebook connect setttings
                        if ($("input[name=unlinkAccounts]").attr("checked") == 'checked'
                            || $("input[name=unlinkAccounts]").attr("checked") == true){
                            if(FB != null && FB.Connect.get_loggedInUser() != null) {
								
								var fbId = FB.Connect.get_loggedInUser();

								FB.Connect.logout(function(){
									
									FB.Facebook.apiClient.revokeAuthorization(fbId,billboard.user.logout());
								});

								
								
                            } else {
                                $("#content-wrapper .header #profile-status-message").text('Attempt to unlink your facebook account failed.  Please try again.');
                                $("#content-wrapper .header #profile-status-message").addClass("error");
                            }
                        } else if ($("input[name=enableFB]").attr("checked") == 'checked'
                            || $("input[name=enableFB]").attr("checked") == true){
                            $("input[name=unlinkAccounts]").attr("checked","")
                            $("input[name=unlinkAccounts]").attr("disabled","")
                        }

                        //subscribe silverpop
                        if (($("input[name=newsletterDailyNews]").attr("checked") == 'checked'
                            || $("input[name=newsletterDailyNews]").attr("checked") == true)
                            && initNewsletter != $("input[name=newsletterDailyNews]").val()){
                            me.subscribeNewsletter(
                                $("input[name=email]").val()
                                , function(data){
                                    if (data.response.head.status == 'success'){
                                        if (data.response.body.RecipientModel.result != 'TRUE'){
                                            $("#content-wrapper .header #profile-status-message").html("Daily News - " + data.response.body.RecipientModel.errorDescription);
                                            $("#content-wrapper .header #profile-status-message").addClass("error");
                                        } else { 
                                            initNewsletter = $("input[name=newsletterDailyNews]").val();
                                        }
                                    } else {
                                        $("#content-wrapper .header #profile-status-message").html("Daily News - " + data.response.head.message);
                                        $("#content-wrapper .header #profile-status-message").addClass("error");
                                    }
                                }
                            );
                        } else if (($("input[name=newsletterDailyNews]").attr("checked") == ''
                            || $("input[name=newsletterDailyNews]").attr("checked") == false)
                            && initNewsletter != $("input[name=newsletterDailyNews]").val()){
                            me.unsubscribeNewsletter(
                                $("input[name=email]").val()
                                , function(data){
                                    if (data.response.head.status == 'success'){
                                        if (data.response.body.RecipientModel.result != 'SUCCESS'){
                                            $("#content-wrapper .header #profile-status-message").html("Daily News - " + data.response.body.RecipientModel.errorDescription);
                                            $("#content-wrapper .header #profile-status-message").addClass("error");
                                        } else { 
                                            initNewsletter = $("input[name=newsletterDailyNews]").val();
                                        }
                                    } else {
                                        $("#content-wrapper .header #profile-status-message").html("Daily News - " + data.response.head.message);
                                        $("#content-wrapper .header #profile-status-message").addClass("error");
                                    }
                                }
                            );
                        }
                    }
                } else {
                    if (change != 'options'){
                        var oldText = $("#setting-" + change).text();
                        oldText = oldText.indexOf("-") >= 0 ? oldText.substring(0,oldText.indexOf("-") - 1) : oldText;
                        $("#setting-" + change).html(oldText + ' <span class="error">- ' + data.response.head.message + '</span>');
                    } else {
                        $('html,body').animate( {scrollTop: 0 }, 1000 );
                        $("#content-wrapper .header #profile-status-message").html(data.response.head.message);
                        $("#content-wrapper .header #profile-status-message").addClass("error");
                    }
                }
            }
            ,error:function(xHRequest, textStatus, errorThrown){
                if (change != 'options'){
                    var oldText = $("#setting-" + change).text();
                    oldText = oldText.indexOf("-") >= 0 ? oldText.substring(0,oldText.indexOf("-") - 1) : oldText;
                    $("#setting-" + change).html(oldText + ' <span class="error">- ' + textStatus + ' - ' + errorThrown + '</span>');
                } else {
                    $('html,body').animate( {scrollTop: 0 }, 1000 );
                    $("#content-wrapper .header #profile-status-message").html(textStatus + ' - ' + errorThrown);
                    $("#content-wrapper .header #profile-status-message").addClass("error");
                }
            }
            ,complete:function(xHRequest, textStatus){
                if (xHRequest.status == 404){
                    $('html,body').animate( {scrollTop: 0 }, 1000 );
                    $("#content-wrapper .header #profile-status-message").html(textStatus);
                    $("#content-wrapper .header #profile-status-message").addClass("error");
                }
            }
        });
    };
	me.updateFbPublishing = function(fields) {
		fields = fields.split("&");
		jQuery.each(fields, function(){
			var item = this.split("=");
			newVal = (item[1] == "true") ? true : false;
			if(item[0] == 'enableFB') billboard.user.fbPublishActivities = newVal;
			else if(item[0] == 'fbPublishComment') billboard.user.fbPublishComments= newVal;
			else if(item[0] == 'fbPublishMusicLabel') billboard.user.fbPublishWinGame= newVal;
			else if(item[0] == 'fbPublishMusicOfYourLife') billboard.user.fbPublishSoyl= newVal;
			else if(item[0] == 'fbPublishFavorites') billboard.user.fbPublishFavorites= newVal;
		});
	};
    me.deactivateAccount = function(){
        $.getJSON(
	        URL_BB_DEACTIVATE
            ,{
                userName : billboard.user.username
            }
            ,function(data){
                if (data.response.head.status == 'success'){
                    billboard.user.logout();
                    billboard.navigateToUrl("/");
                } else {
                    $('html,body').animate( {scrollTop: 0 }, 1000 );
                    $("#content-wrapper .header #profile-status-message").html( data.response.head.status + " - " + data.response.head.message );
                    $("#content-wrapper .header #profile-status-message").addClass("error");
                }
            }
       );
    };

/*
   This method is used for inviting facebook friends to join Billboard.
   It takes a variable as a String which is a comma(',') deliminated facebook ids.
*/
	me.inviteFacebookFriends= function(facebookids){
     me.showFacebookEmailAuthorization();
     var url = URL_BB_INVITE_FACEBOOK_FRIENDS+facebookids; 
	 var confVals = [];
	 var personInfo ={};
    
	 $.getJSON( url, function(data,status) {
					if ( data.response.head.status == "success" ) {
						//user = data.response.body.UserView;							
						// To get the user list from the JSON object named 'com.billboard.model.view.UserView-array'
						var list = data.response.body['com.billboard.model.view.UserView-array'];
						var len = list.length;
						var item,src;
						var user;
					  //To display the user list to whom the billboard invite has been sent
						if (len > 0) {
							for ( var i=0;i<len;i++ ) {
								personInfo = {};
								user = list[i];
								personInfo.username = user.firstName + " " + user.lastName;
								personInfo.imageUrl = (user.profilePhotoUrl)?(user.profilePhotoUrl):("/images/icons/no-image-user.gif");
								personInfo.showBbMember = "false";

								confVals.push(personInfo);


							}
							me.inviteConfirmation("byfb", confVals);
							//$("#found-people-list").hide();
							//$(".follow-wrapper").show();
						}
					}						   
					else {
						$(".people-list fieldset#find-person-group").html("<div class='sorry'>You have replenished your notification limit to send invite today. Please come back tomarrow to send invite.</div>");
							//$(".follow-wrapper .message").text("You have replenished your notification limit to send invite today. Please come back tomarrow to send invite.");
							//$("#found-people-list").hide();
							//$(".follow-wrapper").show();
				
					}
				});
				return false;
	};

/**
  This method taking special permissing for sending email
  to his/her friends using the Billboards application.
*/
	me.showFacebookEmailAuthorization=function(){
		
		FB.Facebook.apiClient.users_hasAppPermission('email',function(permissions){				
				//alert('email permission: '+permissions);
				if ( permissions != 1 ) {
				FB.Connect.showPermissionDialog('email', function(result) {
				});
				}
				else {
				billboard.log("Successful login through facebook for sending email");
				}
			});
	   return false;
	};

})(jQuery);

