﻿var fbFriendSelector;
var fbUser;

function FbShowFriendSelector()
{
    FB_RequireFeatures(["CanvasUtil", "Api"], function() 
    {
                FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "xd_receiver.htm");
                //Login Dialog
                FB.Connect.requireSession(function(){
                    var session = FB.Facebook.apiClient.get_session();
                    fbUser = session['uid'];
                    FB.Facebook.apiClient.fql_query("SELECT uid, name, pic FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = " + fbUser + ") ORDER BY name", showFriends);

                });
                
     });
          

}

function showFriends(result){
    fbFriendSelector = new fb_FriendSelector(result, 20);
    //var friendTag = "<fb:multi-friend-selector actiontext=\"Select the friends you want to invite. (All of them.)\" rows=\"5\"></fb:multi-friend-selector>";
     $('#divfbfs').html(fbFriendSelector.getHTML());
     //$('#divfbfs').html(friendTag);
}

function FBVictoryStorySubmit(victorystoryId)
{
    var url = 'facebook/victorystories' + '?victorystoryId=' + victorystoryId;
        FBSubmit(url);
}
function FBChallengeSubmit(challengeId)
{
    var url = 'facebook/challenge' + '?challengecalendarId=' + challengeId;
        FBSubmit(url);
}
function FBSubmit(url) {
    try {
        FB_RequireFeatures(["CanvasUtil", "Api"], function() {
        FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "/xd_receiver.htm");
            //Login Dialog
            FB.Connect.requireSession(function() {
                var session = FB.Facebook.apiClient.get_session();
                //suffix user id and additional keys to query string
                url += '&userId=' + session['uid'];
                for (var key in session) url += '&' + 'fb_sig_' + key + '=' + session[key];
                //Check to see if the current logged in user already has granted extended permissions to the application
                FB.Facebook.apiClient.users_hasAppPermission("publish_stream",
                    function(check_result) {

                        if (check_result == 0) {
                            //Display the Extended Permissions Dialog if the user does not already have the permission
                            //Extended Permissions Dialog
                            FB.Connect.showPermissionDialog("publish_stream", //permission
                                function(perm_result) {
                                    //alert(perm_result);
                                    if (perm_result != null) {
                                        //Call the ajax post to send quiz to controller for submission
                                        SubmitPost(url);
                                    }

                                }, //callback
                                false, //showProfileSelector
                                null   //profileSelectorIds              
                                );


                        }
                        else if (check_result == 1) {
                            //alert(check_result);
                            //Call the ajax post to send quiz to controller for submission
                            SubmitPost(url);
                        }
                    }
                    );
            });
        });
    }
    catch (e) {
        //TODO: Add code to load mobile window with facebook error message.
        alert("Unable to connect to facebook. Please try again.");
    }
}
function SubmitPost(Url) //generic version
{
    var theData = $.toJSON(Url);
    $.ajax({
                url: Url,
                type: 'POST',
                data: theData,
                dataType: 'JSON',
                contentType: "application/json; charset=utf-8",
                success: function(data)
                {
                }
            });
}  
function FbQuizSubmit(quizId)
 {
   try
   {
        FB_RequireFeatures(["CanvasUtil", "Api"], function() 
        {
                FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "/xd_receiver.htm");
                //Login Dialog
                FB.Connect.requireSession(function(){
                    var session = FB.Facebook.apiClient.get_session();
                    var url = 'FbQuiz/SendQuiz' + '?fb_sig_added=1&quizid=' + quizId + '&userId=' + session['uid']
                    for(var key in session) url += '&'+'fb_sig_'+key+'='+session[key];
                    
                    //Check to see if the current logged in user already has granted extended permissions to the application
                    FB.Facebook.apiClient.users_hasAppPermission("publish_stream", 
                    function(check_result){
                     
                            if(check_result == 0)
                            {
                                //Display the Extended Permissions Dialog if the user does not already have the permission
                                 //Extended Permissions Dialog
                                FB.Connect.showPermissionDialog("publish_stream", //permission
                                function(perm_result){
                                //alert(perm_result);
                                if(perm_result != null)
                                {
                                    //Call the ajax post to send quiz to controller for submission
                                    QuizSubmitPost(url);
                                }
                                
                                }, //callback
                                false, //showProfileSelector
                                null   //profileSelectorIds              
                                );
                               
                                               
                            }
                            else if( check_result == 1)
                            {
                                //alert(check_result);
                                //Call the ajax post to send quiz to controller for submission
                                QuizSubmitPost(url);
                            }
                        }
                    );
                    
                   
                    
                    });
        });
    }
    catch(e)
    {
        //TODO: Add code to load mobile window with facebook error message.
        alert("Unable to connect to facebook. Please try again.");
    }
    
    //return quizConfirm;
}

function QuizSubmitPost(quizUrl)
{
    var quiz = $.toJSON(quizUrl);
    $.ajax({
                url: quizUrl,
                type: 'POST',
                data: quiz,
                dataType: 'JSON',
                contentType: "application/json; charset=utf-8",
                success: function(data)
                {
                  // passSelectedDateData(data);
                }
            });
            

}

function passSelectedDateData(data)
{
   alert(data.ReturnCode);
}

function FbNotify()
{
     FB_RequireFeatures(["CanvasUtil", "Api"], function() 
            {
                    FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "xd_receiver.htm");
                    //Login Dialog
                    FB.Connect.requireSession(function(){
                        var session = FB.Facebook.apiClient.get_session();
                        var postUrl = 'challenge/inviteFb'+'?fb_sig_added=1'
                        for(var key in session) postUrl += '&'+'fb_sig_'+key+'='+session[key];
                        
                        var userEmail = "Adeola.Dada@arcww.com";
                        var friendIds = "660655966,100000047793925";
                        var message = "test notification/invite from Adeola on specialk";
                        var friendNames = "Warner Shaw,Arcww Dever";
                        var userName = "Adeola";

                        var inviteInfo = new Array(userEmail, friendIds, userName, message, friendNames);
                        
                        var inviteData = $.toJSON(inviteInfo);
                        $.ajax({
                                    url: postUrl,
                                    type: 'POST',
                                    data: inviteData,
                                    dataType: 'JSON',
                                    contentType: "application/json; charset=utf-8",
                                    success: function(data)
                                    {
                                      alert(data.Result['Message']);
                                    }
                        });
                        
                    });
                    
                    
    });

}

// Grabs current logged in users friends
function GetCurrentUserFriends() {
    try {
        FB_RequireFeatures(["CanvasUtil", "Api"], function() {
            FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "xd_receiver.htm");
            //Login Dialog
            FB.Connect.requireSession(function() {
                var session = FB.Facebook.apiClient.get_session();
                var url = '/facebook/GetCurrentUsersFriends' + '?fb_sig_added=1&userId=' + session['uid']
                for (var key in session) url += '&' + 'fb_sig_' + key + '=' + session[key];

                //Check to see if the current logged in user already has granted extended permissions to the application
                FB.Facebook.apiClient.users_hasAppPermission("publish_stream",
                    function(check_result) {

                        if (check_result == 0) {
                            //Display the Extended Permissions Dialog if the user does not already have the permission
                            //Extended Permissions Dialog
                            FB.Connect.showPermissionDialog("publish_stream", //permission
                                function(perm_result) {
                                    //alert(perm_result);
                                    if (perm_result != null) {
                                        SubmitGetCurrentUserFriendsPost(url);
                                    }

                                }, //callback
                                false, //showProfileSelector
                                null   //profileSelectorIds              
                                );


                        }
                        else if (check_result == 1) {
                           SubmitGetCurrentUserFriendsPost(url);
                        }
                    }
                    );



            });
        });
    }
    catch (e) {
        //TODO: Add code to load mobile window with facebook error message.
        alert("Unable to connect to facebook. Please try again.");
    }


}




function GetVictoryChainConnection() 
{
    var url = null;
    
    try 
    {
    	FB_RequireFeatures(["CanvasUtil","Api"], function()
    	{
        	FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "xd_receiver.htm");
            FB.Connect.requireSession(function()
            {
				var session = FB.Facebook.apiClient.get_session();
				url = 'fb_sig_added=1&userId=' + session['uid']
				for (var key in session)
				{
					url += '&' + 'fb_sig_' + key + '=' + session[key];
				}
				
				document.getElementById('victory-stories').verifyFBuser();
            });
        });
    }
    catch (e) {
        //TODO: Add code to load mobile window with facebook error message.
        alert(e);
    }

    return url;
}







function SearchCurrentUsersFriends(SearchString)
{
	try
	{
		FB_RequireFeatures(["CanvasUtil", "Api"], function()
		{
        	FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "xd_receiver.htm");
            
        	// Login Dialog
            FB.Connect.requireSession(function()
            {
            	var session = FB.Facebook.apiClient.get_session();
                var url = '/facebook/SearchCurrentUsersFriends?searchstring=' + SearchString +  '&fb_sig_added=1&userId=' + session['uid']
                
                for(var key in session) url += '&' + 'fb_sig_' + key + '=' + session[key];

                //Check to see if the current logged in user already has granted extended permissions to the application
                FB.Facebook.apiClient.users_hasAppPermission("publish_stream", function(check_result)
                {
                	if(check_result == 0)
                	{
                		// Display the Extended Permissions Dialog if the user does not already have the permission
                        // Extended Permissions Dialog
                	    FB.Connect.showPermissionDialog("publish_stream", function(perm_result)
                        {
                        	if(perm_result != null)
                        	{
                        		SubmitSearchCurrentUserFriendsPost(url);
                            }
                        }, //callback
                        false, //showProfileSelector
                        null //profileSelectorIds              
                        );
                    }
                    else if(check_result == 1)
                    {
                    	SubmitSearchCurrentUserFriendsPost(url);
                    }
                });
            });
        });
    }
    catch(e)
    {
        //TODO: Add code to load mobile window with facebook error message.
        alert("Unable to connect to facebook. Please try again.");
    }
}

function SetSelectedFriendForInvite(isChecked, friendId)
{
	try
	{
		FB_RequireFeatures(["CanvasUtil", "Api"], function()
		{
        	FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "xd_receiver.htm");
            
        	// Login Dialog
            FB.Connect.requireSession(function()
            {
            	var session = FB.Facebook.apiClient.get_session();
                var url = '/facebook/SetSelectedFriendForInvite?userId='+session['uid']+'&friendId='+friendId+ '&selectedstatus='+ isChecked +'&fb_sig_added=1';
                
                for(var key in session) url += '&' + 'fb_sig_' + key + '=' + session[key];

                //Check to see if the current logged in user already has granted extended permissions to the application
                FB.Facebook.apiClient.users_hasAppPermission("publish_stream", function(check_result)
                {
                	if(check_result == 0)
                	{
                		// Display the Extended Permissions Dialog if the user does not already have the permission
                        // Extended Permissions Dialog
                	    FB.Connect.showPermissionDialog("publish_stream", function(perm_result)
                        {
                        	if(perm_result != null)
                        	{
                        		SubmitSetSelectedFriendForInvite(url);
                            }
                        }, //callback
                        false, //showProfileSelector
                        null //profileSelectorIds              
                        );
                    }
                    else if(check_result == 1)
                    {
                    	SubmitSetSelectedFriendForInvite(url);
                    }
                });
            });
        });
    }
    catch(e)
    {
        //TODO: Add code to load mobile window with facebook error message.
        alert("Unable to connect to facebook. Please try again.");
    }
}

function SetInvitedFriends()
{
	try {
        FB_RequireFeatures(["CanvasUtil", "Api"], function() {
            FB.Facebook.init("49a196f96a22da487ba37ac1dc5ae691", "xd_receiver.htm");

            // Login Dialog
            FB.Connect.requireSession(function() {
                var session = FB.Facebook.apiClient.get_session();
                var url = '/facebook/SendCurrentUsersSelectedFriends?userId=' + session['uid'] + '&fb_sig_added=1';

                for (var key in session) url += '&' + 'fb_sig_' + key + '=' + session[key];

                //Check to see if the current logged in user already has granted extended permissions to the application
                FB.Facebook.apiClient.users_hasAppPermission("email", function(check_result) {
                    if (check_result == 0) {
                        // Display the Extended Permissions Dialog if the user does not already have the permission
                        // Extended Permissions Dialog
                        FB.Connect.showPermissionDialog("email", function(perm_result) {
                            if (perm_result != null) {
                                SubmitSetInvitedFriends(url);
                            }
                        }, //callback
                        false, //showProfileSelector
                        null //profileSelectorIds              
                        );
                    }
                    else if (check_result == 1)
                    {
                    	SubmitSetInvitedFriends(url);
                    }
                });
            });
        });
    }
    catch (e) {
        //TODO: Add code to load mobile window with facebook error message.
        alert("Unable to connect to facebook. Please try again.");
    }
}

// Submits user information to facebook to get list of friends
function SubmitGetCurrentUserFriendsPost(url)
{
    var friends = $.toJSON(url);

    $.ajax({
        url: url,
        type: 'POST',
        data: friends,
        dataType: 'JSON',
        contentType: "application/json; charset=utf-8",
        success: handleUserFriends // Callback
    });
}

// Searches through current logged in users list of friends
function SubmitSearchCurrentUserFriendsPost(url)
{
    var friends = $.toJSON(url);

    $.ajax({
        url: url,
        type: 'POST',
        data: friends,
        dataType: 'JSON',
        contentType: "application/json; charset=utf-8",
        success: handleSearchFriends // Callback
    });
}

// Add or removes selected friend to invite system
function SubmitSetSelectedFriendForInvite(url)
{
	var friend = $.toJSON(url);

    $.ajax({
        url: url,
        type: 'POST',
        data: friend,
        dataType: 'JSON',
        contentType: "application/json; charset=utf-8",
        success: handleSetFriendInvite // Callback
    });
}

// Submit selected friends to invite system
function SubmitSetInvitedFriends(url)
{
	// Show loading image
	$('#send-facebook-invites-btn').hide();
	$('#fb-loading-img').show();
	
	var friends = $.toJSON(url);

    $.ajax({
        url: url,
        type: 'POST',
        data: friends,
        dataType: 'JSON',
        contentType: "application/json; charset=utf-8",
        success: handleInvitedFriends // Callback
    });
}

// Once we have friends for the database we show them to the user
function handleUserFriends(data)
{
	// Converting return JSON to a JS object
    var returnObj = $.evalJSON(data);
	
    // Hide Invite A Buddy Welcome Modal
    $('#find-buddy-modal').dialog('close');
	
	// Empty Container
	$('#facebook-buddy-list').empty();
    
	// Attach change events to future elements
	$('#facebook-buddy-list input[type="checkbox"]').live('click', function()
	{
		var isChecked = $(this).attr('checked');
		var friendId = $(this).val();
		
		SetSelectedFriendForInvite(isChecked, friendId);
	});
	
    // Loop through all friends
	$.each(returnObj.DataPackets, function(i)
	{
		if(this.Selected == false)
		{
			$('#facebook-buddy-list').append('<div class="buddy"><div class="left"><img src="'+this.ImageUrl+'" width="50" height="50" alt="" /><span class="name">'+this.FirstName+' '+this.LastName+'</span></div><div class="right"><label for="'+this.Uid+'">Invite</label><input type="checkbox" id="'+this.Uid+'" value="'+this.Uid+'" /></div></div>');
		}
		else
		{
			$('#facebook-buddy-list').append('<div class="buddy"><div class="left"><img src="'+this.ImageUrl+'" width="50" height="50" alt="" /><span class="name">'+this.FirstName+' '+this.LastName+'</span></div><div class="right"><label for="'+this.Uid+'">Invite</label><input type="checkbox" checked="checked" id="'+this.Uid+'" value="'+this.Uid+'" /></div></div>');
		}
	});
	
	// Show Facebook Friend Modal
	$('#facebook-buddy-modal').dialog('open');
}

// Search through the list of friends
function handleSearchFriends(data)
{
	// Converting return JSON to a JS object
    var returnObj = $.evalJSON(data);
    
    // Empty Container
	$('#facebook-buddy-list').empty();
	
	// Attach change events to future elements
	$('#facebook-buddy-list input[type="checkbox"]').live('change', function()
	{
		var isChecked = $(this).attr('checked');
		var friendId = $(this).val();
		
		SetSelectedFriendForInvite(isChecked, friendId);
	});
    
    // Loop through all friends
	$.each(returnObj.DataPackets, function(i)
	{
		if(this.Selected == false)
		{
			$('#facebook-buddy-list').append('<div class="buddy"><div class="left"><img src="'+this.ImageUrl+'" width="50" height="50" alt="" /><span class="name">'+this.FirstName+' '+this.LastName+'</span></div><div class="right"><label for="'+this.Uid+'">Invite</label><input type="checkbox" id="'+this.Uid+'" value="'+this.Uid+'" /></div></div>');
		}
		else
		{
			$('#facebook-buddy-list').append('<div class="buddy"><div class="left"><img src="'+this.ImageUrl+'" width="50" height="50" alt="" /><span class="name">'+this.FirstName+' '+this.LastName+'</span></div><div class="right"><label for="'+this.Uid+'">Invite</label><input type="checkbox" checked="checked" id="'+this.Uid+'" value="'+this.Uid+'" /></div></div>');
		}
	});
}

// Handles when a user adds or removes a friend
function handleSetFriendInvite(data)
{
	// Converting return JSON to a JS object
    var returnObj = $.evalJSON(data);
}

// Handles when a user has submitted all their friends to the invite system
function handleInvitedFriends(data)
{
	// Converting return JSON to a JS object
    var returnObj = $.evalJSON(data);
    
    if(returnObj.ReturnCode == 1)
    {
    	// Hide loading image
		$('#fb-loading-img').hide();
		
    	$('#invitations-have-sent').show();
		$('#send-facebook-invites-btn').hide();
    }
    else
    {
    	// Hide loading image
		$('#fb-loading-img').hide();
		$('#send-facebook-invites-btn').show();
    }
}