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.sort = "date"; // "alpha";
	me.filter = "all"; // 

	var URL_BB_FIND_USER = "/user/find-user.json?username=";
	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="; 

	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.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();

		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").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()
	{
	};

	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...
			billboard.player.setQueue( queue, "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("visibility","visible");
		}
		else {
			$(".find-head .filter-nav").css("visibility","hidden");
		}

		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;
			}
		});

		// 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("input[name=email]").val();
			var message = $(this).find("textarea[name=message]").val();
			if ( emails.length <= 0 ) { 
				$("form[name=invite-email-form] input[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 > 250 ) { 
				document.getElementById("email-error-msg").innerHTML="<p>Message length should not exceed 250 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("input[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 a").click( function() { 
			$(this).parents("ul:first").find("li").removeClass("active");
			$(this).parent().addClass("active");
         });


		// init the invite by email functionlity 
		$(".filter-nav.option li:last a").click( function() {
			// show the invite form...
			$(".find-tab").hide();
			$("#email-error-msg").hide();
			$(".follow-wrapper").hide();
			$("#invite-email").removeClass("success");
			$("#invite-email").show();
		});

		// facebook displaying functionlity 
		$(".filter-nav.option li:first a").click( function() { 
			// show the invite form...
			$(".find-tab").hide();
			$("#addpeople-error-msg").hide();
			$(".follow-wrapper").hide();
			$("#found-people-list").show();
            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:first a").click();
				  });
				 return false;
			 }
				
            $.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'];

					  //To display the user list obtained from findUsers function
					  me.displayFacebookFriend(list);
					}						   
					else {
						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:first a").click();
							  });
							 return false;
						}
						$("#found-people-list .filter-nav ul,#found-people-list .add-people").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;

			
		});

		//Call the click function of email functionality
		//$(".filter-nav.option li:last a").click();
		$(".filter-nav.option a").parents("ul:first").find("li").removeClass("active");
		$(".filter-nav.option a").parents("ul:last").find("li").removeClass("active");
		$("#found-people-list").show();

		// init the username form
		// Changed for BBCOM-264
		$(".add-people a").click( function() {

			var str="";
			var allVals = [];
			
			
            $('.person-profile :checked').each(function() {
				//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
				}else{
				  str=str+socialStr[0]+",";	  //Take facebook Id in case facebookId is present
				}
	            //allVals.push($(this).val());
           	});
			
			var flength=str.length;
			//Validation that atleast one user should be selected 
			if(allVals.length==0 && flength==0){
				$("#addpeople-error-msg").html("<p>&nbsp;&nbsp;Please select atleast one user to proceed.</p>");
				$("#addpeople-error-msg").show();
			}else
				$("#addpeople-error-msg").hide();

			if( flength>2 && (str.split(",").length >1)){
				str=str.substring(0,flength-1);
				me.inviteFacebookFriends(str);
			}


			billboard.user.requireLogin( function() { 
				billboard.social.follow( allVals, function(data) {
					billboard.info( "follow result" );
					var user = billboard.user.username;
					billboard.facebook.publish("follow",allVals);
					billboard.navigateToUrl( "/user/"+user+"/connections/following" );
				});
			});	
		});
			
		
		$("form[name=find-user-form]").submit( function() {
			
			var username = $(this).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 = {};
				$.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'];

					  //To display the user list obtained from findUsers function
					  me.displayUsers(list);
					}						   
					else {
						$("#found-people-list .filter-nav ul,#found-people-list .add-people").hide();
						$(".people-list fieldset#find-person-group").html("<div class='sorry'>Sorry. There are no users that match "+username+"</div>");
					}
				});

				$(".filter-nav.option a").parents("ul:first").find("li").removeClass("active");
				$(".filter-nav.option a").parents("ul:last").find("li").removeClass("active");
				$(".follow-wrapper").hide();
				$("#addpeople-error-msg").hide();
				//Hiding the invite div
				$("#invite-email").hide();
				$("#found-people-list").show();
				return false;
			}
		});
	};
	
	/**
	 *
	 */
	me.displayUsers = function( users ) 
	{
		billboard.log( "Profile.displayUsers()");
		billboard.log( users );
		var person;
		var url;
		var param={};
		$(".message-wrapper").hide();
		$(".people-list fieldset").empty();

		for ( var i=0;i<users.length;i++ ) {
			param ={};
			param.username = users[i].username;
			param.facebookId = users[i].facebookId;
	
			//Position of getUser function changed to handle multiple users  
			billboard.social.getUserProfile( param, function(data,param) {
				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");
				person.find(".profile-image img").attr("src", url);
				person.find(".profile-image").attr("href", "/user/"+ param.username );
				person.find(".profile-name").text( param.username );
				person.find(".profile-name").attr("href", "/user/"+ param.username );
				//person.find("input[type=checkbox]").attr("checked","checked");
				person.find("input[type=checkbox]").attr("value","0<"+ param.username);
				
				if ( !param.facebookId  || param.facebookId=='undefined') {
					person.find(".facebook-image").hide();
				}
				person.find(".profile-image-facebook ").hide();
				//Fix for BBCOM-288 Scenario 3
				$(".billboard-members fieldset").append( person.show());
				});
		}

		//$(".follow-wrapper").hide();
		//$("#facebookusers").hide();
		$("#found-people-list .filter-nav ul,#found-people-list .add-people").show();

		billboard.hijackLinks( ".people-list fieldset" );
	};


	me.displayFacebookFriend = function( users ) 
	{
		billboard.log( "Profile.displayFacebookFriend()");
		billboard.log( users );
		//alert(users);
		var person;
		var url;
		$(".people-list fieldset").empty();

		for ( var i=0;i<users.length;i++ ) {
			var username = users[i].username;
					
				person = $("#person-profile-template").clone();
				person.removeAttr("id");
				
				
			
       		if(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();
			}

		 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') $(".non-billboard fieldset").append( person.show() ); 
			else $(".billboard-members fieldset").append( person.show() ); 
			
		}

		//$(".follow-wrapper").hide();
		$(".message-wrapper").show();
		$("#facebookusers").show();
		$("#found-people-list .filter-nav ul,#found-people-list .add-people").show();


		billboard.hijackLinks( ".people-list fieldset" );
		//billboard.hijackLinks( ".facebook-people-list fieldset" );
		//billboard.hijackLinks( ".message-wrapper" );
	};

	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.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 (a.created < b.created) ? 1 : (a.created > b.created) ? -1 : 0;
							});
				for ( var i=0;i<events.length;i++ ) {
					me.displayActivity( events[i] );
				}
			}
		});
	};

	/**
	 *
	 */
	me.displayActivity = function( event )
	{
		billboard.log("Profile.displayActivity()");
		billboard.log(event);
		var cats = ["none","rating","comment","follow"];

		var type, id;
		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 ) { 
			type = event.container.ExternalEntity.uid.split("-")[0];
			id = event.container.ExternalEntity.uid.split("-")[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="article";
			}

			if ( type == "news" ) type = "article";
			var dataString="id="+id;
			var url = "/favorite-"+type+".json";
			$.ajax({  
					type: "POST",  
					url: url,
					data: dataString, 
                    dataType : "json",					
					error:function() { return;},
					success: function(result) {  
						if(result.response.head.status != "error")
						  result.response.body.FavoriteItemView.type = type;
						
						if ( typeof(result.response) == "undefined" || result.response.head.status=="error") {
							return;
						}
						if(typeof(result.response.body)!='undefined')
						 event.item = result.response.body.FavoriteItemView;
						//billboard.log(event);
						//billboard.log("1. filtering activity: ["+me.filter+"], "+event.message );
						
					if ( (me.filter == "all") || 
							(me.filter == "user" ) ||
							(me.filter=="follow") ||
							(me.filter=="rating" && event.message.indexOf("love")>=0)
							) { 
						
						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( 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 { 
			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;
			}
			billboard.social.getUser( id,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;

						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 lid = $(this).parents(".favorite-row").find(".lala-id").text();
										var lname = $(this).parents(".favorite-row").find(".name a").text();
										//billboard.log( lid + ":" + lname );
										billboard.player.setQueue( [ {title:lname,id:lid} ] );
									});
								}
								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[0].lalaId && item.songs.length > 0 ) {
									 
									
									row.find(".action .playbtn").click( function() { 
									//billboard.log( $(this) );
									//billboard.log( $(this).parents(".favorite-row") );
									var queue = [];var lname,lid;
									for ( var i=0;i<item.songs.length;i++ ) {
										lname = item.songs[i].name;
										lid = item.songs[i].lalaId;
										queue.push( { id:lid,title:lname}  );
									}
									//billboard.log( lid + ":" + lname );
									billboard.player.setQueue( queue );
											});
								}
								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; 
    
	 $.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++ ) {
								user = list[i];
								item = $("#follow-template").clone().removeAttr("id");
								item.find(".follow-name a").text( user.firstName+' '+user.lastName );
								src = (user.profilePhotoUrl)?(user.profilePhotoUrl):("/images/defaults/user-69.gif");
								item.find(".profile-imgwrap img").attr("src",src);
								item.show();
								$(".follow-wrapper").append( item );
							}
							$("#found-people-list").hide();
							$(".follow-wrapper").show();
						}
					}						   
					else {
							$(".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();
						//$("#found-people-list .filter-nav ul,#found-people-list .add-people").hide();
						//$(".people-list fieldset").html("<div class='sorry'>Sorry. There are no users that match "+username+"</div>");
					}
				});
				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);
