				   
				    FB.init({ 
                         appId:'204874249538850', cookie:true, 
                         status:true, xfbml:true, oauth:true 
                     });		

 
					//check if user is already logged in    
     			  	FB.getLoginStatus(function(response) 
					{	
						if (response.authResponse) 
						{
                             						   						   
						    // logged in and connected user, someone we know                            
						    FB.api('/me', function(myResponse) 
							{
                            displayUser(myResponse);
                            });
                        }	else {	  
                    	      if (loggedIn == 0 && haveDisplayedRegsiterScreen == 0){	  
                    	        //Show the div for onetime prompt
                    		    buildPopup ("REG_SCREEN", 0, 480, 0, 0);
                    		    setCookie (DSPL_REG_SCREEN_COOKIE_NAME, 1);
                    	     }
                    	}			
                    });

var myFriendsList;
friendCount = 0;
var friendsWhoLike = new Array();
var pageKeyTokens = new Array();
var tokensToSearch = new Array();
var pageEntityName = "";
				   
//displays the user credentials on the web pages on mYusic.com
function displayUser(user){
    

    if (user.name.toLowerCase()!= 'undefined')
    {
    	 
		 setCookie (DSPL_REG_SCREEN_COOKIE_NAME, 1);
		 apptype="fb";
		 loggedIn = 1;
		 setLoggedinStatusCookie (loggedIn);
         displayLogoutButton();
		 var carouselImage = document.getElementById('car');
		 var timelineImage = document.getElementById('TimelineMsgUser');
		 var musicRoomUser = document.getElementById('musicRoomUser');
		 var musicRoomUserMsg = document.getElementById('musicRoomUserMsg');
		 var frndLikeMsgP = document.getElementById('frndLikeP'); 
		 var numFriendUsersDiv = document.getElementById('numFriendUsers');
		 
		 if (frndLikeMsgP != null){
		 	frndLikeMsgP.innerHTML = "Hey " + user.first_name + ", looks like you have not tried the new <i>Friends Forever</i> feature!";
		 }	
		 
		 if (carouselImage != null){
		     carouselImage.src = 'https://graph.facebook.com/' + user.id + '/picture';
		 }
		 
		 if (timelineImage != null){
		     timelineImage.src = 'https://graph.facebook.com/' + user.id + '/picture';
		 }
		 
		 if (musicRoomUser != null){
		     musicRoomUser.src = 'https://graph.facebook.com/' + user.id + '/picture';
		 }	 
		 
		 if (musicRoomUserMsg != null){
		     document.getElementById('musicRoomUserMsg').innerHTML = 'Hey ' + user.first_name + ', Welcome to your mYusic Room';
		 }	 
		 
		 
    	 var recoMsg = document.getElementById('recoMsg');
		 if (recoMsg != null){
        	 recoMsg.innerHTML = 'Hi,&nbsp;' + user.first_name + ' - Here are a few recommendations from your friends!';
    		 $('#loginRegMessage').html('');    
    
    		 //Display the message to check if the user wants to find friends who like this page
    		 $('#friendLikes').show();
			 
			 	
		}	 
		$('#inviteFBFriends').html('<img src="/DailyPosts/images/InviteFriends.jpg" alt="Invite Friends" />');
		
		if (numFriendUsersDiv != null){
		    findFriendsWhoAreUsers (1);
		}	 
    	
		if (hasFriendPermissions == -1)
    	{	
    	    //We have not checked for the permission in this session
            FB.api('/me/permissions', function(permissions){
    	        if(permissions.data[0].friends_likes == 'undefined' || permissions.data[0].friends_likes == null || permissions.data[0].friends_likes == '0')
    		    {
    			    
					
					//Set the cookies value to 0
    				setCookie(HAS_FRIEND_PERM_COOKIE_NAME , 0);					
					hasFriendPermissions = 0;
                    if (document.getElementById('FRIEND_LIKE_SCREEN') != null){
                		if (haveDisplayedFrndLikeScreen == -1){
                			  setCookie (DSPL_FRND_LIKE_COOKIE_NAME, 1);		
                			  buildPopup ("FRIEND_LIKE_SCREEN", 0, 480, 0, 0);
                		}
            		}						
  
    			}
    			else if (permissions.data[0].friends_likes == '1')
    			{
    			    setCookie(HAS_FRIEND_PERM_COOKIE_NAME , 1);
					hasFriendPermissions = 1;
    			}
    		});
    	}//End of if hasFriendPermissions == -1 
    }//End of if user.name != undefined    							      
}//End of function
					
function doLogin (source){
    
    if (source == 'fbLogin'){
		
		$('#PERMS_MSG').fadeIn().css({ 'width': 350  }).prepend('<a href="#" class="loginclose"><img src="/DailyPosts/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');

        var popMargTop = ($('#PERMS_MSG').height()+ 80) / 2;
        //var popMargLeft = ($('#PERMS_MSG').width()+ 80) / 2;

       //Apply Margin to Popup
        $('#PERMS_MSG').css({
            'margin-top' : -popMargTop,
            'left' : 30
         });

        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({'filter' : 'alpha(opacity=50)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
		
		setTimeout( function() {
		     $('#fade , #PERMS_MSG').fadeOut(function() {
             $('#fade, a.loginclose').remove();  //fade them both out
       });
	    }, 20000 );
		
      $('a.loginclose').live('click', function() { //When clicking on the close or fade layer...
	      $('#fade , #PERMS_MSG').fadeOut(function() {
              $('#fade, a.loginclose').remove();  //fade them both out
          });
          return false;
      });			
        	    
		doFBLogin();

    }
}

function doFBLogin ()
{

  
      	FB.login (function (response){
    	    if(response.authResponse){
    		     FB.api('/me', function(myResponse){
                     displayUser(myResponse);
                 });    
    		}
    		else{
    		   // alert ("user did not log in");
    		}
	   }, {scope: 'email, user_likes, publish_stream, user_birthday, user_location'});
	
	
}		

function inviteFriends()
{
    //alert("here")
	try{
        FB.ui({method: 'apprequests', message: 'Hey, I just discovered a cool new music service for all things bollywood! Just tell the player your mood or activity and listen for hours!', title: 'Explore, Discover, Share...', display:'popup'});
	    return false;
	}
	catch (err)
	{
	    alert (err.description);
	}
}	

//find out friends who are users & display. the option mYusicRoom is used to determine whether to display for the room or elsewhere
function findFriendsWhoAreUsers (mYusicRoom){
    FB.api ( {method:'friends.getAppUsers'}, function (response) {
	        
			var numFriendUsers = response.length;
			if (numFriendUsers >=6){ j=6;} else {j=numFriendUsers;}
			//now take 6 random friends and display their pictures!
			for (i=0; i<j; i++){
			    var randNum =  Math.floor(Math.random()* numFriendUsers);
				var friendId = response[randNum];
				var friendImgSrc = 'https://graph.facebook.com/' + friendId + '/picture';
				  
				if (mYusicRoom){
				    imageIndex = i+1;
				    $("#friend" + imageIndex).attr("src", friendImgSrc) ;
			}	
		    if (mYusicRoom){
			    $('#numFriendUsers').html (numFriendUsers + " friends use mYusic! Invite more friends.");
			}		
		}
	});
}	

//function to find friends who are likely to like this page! The parameter notFromDailyPost signifies that the call to the function is from a different page
//The other pages are being implemented to be generic and UI agnostic. This parameter helps reuse the function written for the Daily Post originally  

function findFriendLikes(notFromDailyPost)
{
    hasFriendPermissions = getCookie (HAS_FRIEND_PERM_COOKIE_NAME);
	
	if (hasFriendPermissions == -1)
	{
	    //Figure out...	
	} else if (hasFriendPermissions == 0)
	
	{
    	 //Don't have perms. Instead of popping up an OAuth window and doing a page refresh, login the user with the perms
		 //buildPopup ("PERMS_MSG", 1, 350, 30, 15000);
         try{
        	 FB.login (function (response){
        	        if(response.authResponse){
    				    if (notFromDailyPost){
    					    processFriendLikes(notFromDailyPost);
						} else {
						    processFriendLikes();
						}	
            		}
            		else{
            		   //alert("Did not get perms");
            		}
        	 }, {scope: 'friends_likes'});
		  }
		  catch(err){
		      //alert(err.description);
		  }		 
	}  else if (hasFriendPermissions == 1){
           if (notFromDailyPost){
    		   processFriendLikes(notFromDailyPost);
			} else {
			    processFriendLikes();
			}	
	}
}			 	
	
function processFriendLikes(notFromDailyPost)
{
        myFriendsList = ""
        friendCount = 0;
        friendsWhoLike = new Array();
        
        tokensToSearch = new Array();
        pageEntityName = "";
	    
		document.getElementById('friendLikesHeader').innerHTML = "Reading Friend Likes...";
		document.getElementById('friendLikesStatusText').innerHTML = "Processing...";
		document.getElementById('friendsWhoLike').innerHTML = "Friends who might like this:"; 
		$('#sendToFriendWallMsg, #sendToFriendWallImg').hide(); 
		
		
		//Find the various entities on the page
		pageKeyTokens = $('meta[name=ONE_KEY]').attr("content").split ("~")
		
		
		//Now see if there are any synonymns e.g. Romantic,Love,Romance~Rafi~Sultanpuri means that Love & Romance are synonymns to search for
		for (i=0; i<pageKeyTokens.length; i++){
		    synonymnTokens = pageKeyTokens[i].split(",");
			for (j=0; j<synonymnTokens.length; j++){
			    tokensToSearch.push(jQuery.trim(synonymnTokens[j]));
			}
		}
		
		//alert (tokensToSearch);

		var statusHTMLElement = document.getElementById('friendLikesStatusText');
		var friendListHTMLElement = document.getElementById('friendsWhoLike');

		document.getElementById('friendLikesHeader').innerHTML = "Fetching Data from Facebook...";
		statusHTMLElement.innerHTML = "Starting";
		//friendListHTMLElement.innerHTML = "Friends who like this:";

		document.getElementById('progress').src = '/DailyPosts/images/progress.gif';
		
		if (notFromDailyPost){
		   //Do Nothing. Don't build the popup	

		} else {   

		    buildPopup ("FRIEND_LIKES", 0, 500, 0, 0);
		}	
        
		FB.api('/me/friends?fields=id, name, first_name', function(friendsList) {
            //alert(JSON.stringify(friendsList));
		    myFriendsList = friendsList;
			//alert(JSON.stringify(myFriendsList));
			friendCount = friendsList.data.length;
            for( i=0; i<friendsList.data.length; i++) {
                friendId = friendsList.data[i].id;
				friendName = friendsList.data[i].first_name;
				if (notFromDailyPost) {
				    getFriendLikesFromFB (i, friendId, notFromDailyPost);
				} else {
				    getFriendLikesFromFB (i, friendId);
				}	
			}					
       });
}

function getFriendLikesFromFB (friendIndex, friendId, notFromDailyPost)
{
    try{
	     FB.api('/'+friendId+'/likes', function(likes) {
		    // var pageKey = $('meta[name=ONE_KEY]').attr("content");
			 
			 
			 myFriendsList.data[friendIndex].likesYorN = '0';
			 for (i=0; i<likes.data.length; i++){
			     for(j=0; j<tokensToSearch.length; j++){
    				 if (likes.data[i].name.indexOf(tokensToSearch[j]) != -1){			 
        		         myFriendsList.data[friendIndex].likesYorN = '1';
    				 }				     
				 }
    		 }
			 
    		 friendCount--;
    		 document.getElementById('friendLikesStatusText').innerHTML = friendCount + " friends to go ... ";
       		if (notFromDailyPost){
       		    $('#socialStatsFriends').html ("Finding likely fans amongst friends! " + friendCount + " friends to go ... ");
       		}			 
    		 if (friendCount == 0){
    		     document.getElementById('friendLikesHeader').innerHTML = "Fetched data from Facebook. Processing...";
    			 //alert(JSON.stringify(myFriendsList));
				 if (notFromDailyPost){
				     processRecdLikes(notFromDailyPost);
				 } else {
    			     processRecdLikes();
				 }	 
			} 	      
		 });
	}
	catch (error){
	    myFriendsList.data[friendIndex].likesYorN = '0';
	}   
}

function processRecdLikes(notFromDailyPost)
{
    var pageKey = $('meta[name=ONE_KEY]').attr("content");
	var friendListHTMLElement = document.getElementById('friendsWhoLike');
	var statusHTMLElement = document.getElementById('friendLikesStatusText');
	

	//We do all this fun to make sure there is a gramatically right representation. E.g. "Rafi~Majrooh Sultanpuri" is rendered as Rafi & Majrooh Sultanpuri
	for(i=0;i<pageKeyTokens.length;i++){
	    synonymnTokens = pageKeyTokens[i].split(",");
	    if (i == 0){
		    //we are at the first element
		    pageEntityName = pageEntityName + synonymnTokens[0];
		}else if (i == pageKeyTokens.length - 1){
		    //we are at the last element
			pageEntityName = pageEntityName + " & "  + synonymnTokens[0];
		}else{
		    //one of the middle elements
		    pageEntityName = pageEntityName + ", "  + synonymnTokens[0]; 
		}	
	    
	}
	
	//alert (pageEntityName);	
	
	//alert(JSON.stringify(myFriendsList));
    firstFriend = 1;
	processedFriendCount = myFriendsList.data.length;
	friendsWhoLikeIndex = 0;

	if (notFromDailyPost){
        socialDataJSONObject = '{"data": [' ;	
	}


	
	for( i=0; i<myFriendsList.data.length; i++) {
		thisFriendLikes = 0; 	
        myFriend = myFriendsList.data[i];	    
        
		if (notFromDailyPost){
		    socialDataString = '{"id":"' + myFriend.id + '", "firstName":"' + myFriend.first_name + '", "name":"' + myFriend.name + '"}';
		}
		
		if (myFriend.likesYorN == '1'){		    
		    thisFriendLikes = 1;
			friendsWhoLike [friendsWhoLikeIndex] = myFriend.id + "," + myFriend.first_name;
			friendsWhoLikeIndex++;			

		}	
		
		if (thisFriendLikes == 1){
    		if (firstFriend == 1){
    		    friendListHTMLElement.innerHTML = "<u><strong>Friends who are likely fans</strong></u>: " +  myFriend.name;
				firstFriend = 0;
    			if (notFromDailyPost){
    			    socialDataJSONObject += socialDataString ;   
    			}
				
    		} else {
    		    friendListHTMLElement.innerHTML = friendListHTMLElement.innerHTML + ', ' + myFriend.name;
    			if (notFromDailyPost){
    			    socialDataJSONObject += ', ' + socialDataString ;   
    			}
				
    		}
		}
	    processedFriendCount--;		
		statusHTMLElement.innerHTML = processedFriendCount + " friends to go ... ";	

	}
	
	if (notFromDailyPost){
	    socialDataJSONObject += ']}';
        $('#socialStatsData').html(socialDataJSONObject);
		
		//set html in socialStatsFriends
        if(friendsWhoLike.length == 0){
		    $('#socialStatsFriends').html ('None of your friends seem to be a fan. Click the Send button to recommend this to your friends!');
		    $('#socialSendToFriendWallImg').show();
		} else {
		    $('#socialStatsFriends').html(friendListHTMLElement.innerHTML);
	        $('#socialSendToFriendWallImg, #socialSendToFriendMailBox').show();			
		}	
		$('#socialStatsProgress').attr('src', 'images/ShareWithFriends.jpg');
    }

	document.getElementById('progress').src = '/DailyPosts/images/Done.jpg';
	document.getElementById('friendLikesHeader').innerHTML = "Send these songs alongwith a personal message to friends!"; 
	statusHTMLElement.innerHTML = "";
	
    if (friendsWhoLike.length == 0){
	    friendListHTMLElement.innerHTML = "Looks like none of your friends has experienced the combo of " + pageEntityName + " Songs. Click the Send button to recommend this to your friends!";
		$('#sendToFriendWallMsg, #sendToFriendWallImg').hide(); 
	} else{
	    $('#sendToFriendWallMsg, #sendToFriendWallImg').show();
	}	 

}

							   


//Send the post to wall of friends, who are likely to like this page
function sendToFriendWall()
{
    
	if (friendsWhoLike.length != 0){
	    document.getElementById('progress').src = 'images/progress.gif';
	}
	
	//pageEntityName = "";
	
    //Read the OpenGraph Tags
	var ogData = jQuery('head').ogp();

   
	//Bug in the OG library...returns individual data items as an array...So read element 0 of each to get the right value!
	pictureName = ogData.image[0];
	linkName = ogData.url[0];
	postName = ogData.title[0];
	descriptionText = ogData.description[0];
	source = ogData.site_name[0];
	captionValue = "Explore, Discover, Share...";
	var strActionLinks = '[{"name": "Tune In", "link": "' + linkName + '"}]';
	var action_links = jQuery.parseJSON( strActionLinks );
	
	
	 

	

    //How many friends do we have to send this post to
    friendsToPost = friendsWhoLike.length; 	


	
	
    for (i=0; i<friendsWhoLike.length; i++){
	    var myFriend = friendsWhoLike[i];
		var myFriendTokens = myFriend.split (",");
		id = myFriendTokens[0];
		name = myFriendTokens[1];	
	    messageText = "Hey " + name + ", I was browsing through mYusic and stumbled upon a cool combo of " + pageEntityName + " songs! Hope you enjoy it as much as I did!"; 
    	console.log(id, name);
    	var postObject = {message: messageText, 
	            link: linkName ,  
				picture: pictureName,  
				name: postName,  
				caption: captionValue,     
				description: descriptionText, 
				actions: action_links 
				};    
		
		
		FB.api ('/' + id + '/feed', 'post', postObject, function (response){		    
			//decrement the number of friends left to post to
			friendsToPost--;
    	    if (!response || response.error) {			
                //alert('Oops! Looks like we did something wrong!');
				console.log (response.error);
            }
			if (friendsToPost == 0){
			    document.getElementById('progress').src = '/DailyPosts/images/Done.jpg';
				//$('#fade , #FRIEND_LIKES').fadeOut(function() {
                //    $('#fade, a.FRIEND_LIKESClose').remove();  //fade them both out
                //});
			} 
  	    
    	});
	}
}

//pop up the send to friend dialog from facebook 
function sendToFriendMail()
{
    document.getElementById('progress').src = 'images/progress.gif'; 
	linkURL = jQuery('head').ogp().url[0]; 
    if (friendsWhoLike.length > 0){
	   var myFriend = friendsWhoLike[0];
	   var myFriendTokens = myFriend.split (",");
	   id = myFriendTokens[0];
	}else{
	    id = '';
	}   
	
	try{
	      FB.ui({
          method:  'send',    
          link:    linkURL, 
		  display: 'popup',
		  to:      id,
		  message: 'Hey, I was browsing through mYusic and stumbled upon a cool set of songs! Hope you enjoy it as much as I did!' 
          });
	} catch(err){
	    alert('Oops! looks like we did something wrong or there is a problem connecting to facebook. Please try again.');
	}
	document.getElementById('progress').src = '/DailyPosts/images/Done.jpg';
}

