﻿/* Index.js
** (C) 2010 eblizz, Inc. all rights reserved.
*/

/// <summary>
/// State of this page in javasript
/// </summary>
var pageState = 0;

/// <summary>
/// Closes the action area if open.
/// </summary>
function closeActionArea() {
    jQuery("#actionArea").empty();
    pageState = 0;
}

function attachClosePopupButton() {
    jQuery('#actionArea .closePopupButton').click(function (e) { e.preventDefault(); closeActionArea(); });
}

function updateActionArea() {

}

function beginUpdateActionArea() {
    jQuery('#actionAreaInfoProgress').html("<img src='/Assets/Images/Site/loading_100x13.gif' class='centered block loadinglargebar'/>");
    // maybe disable everything.
}

function failedEditAccountSettings() {

    jQuery('#actionAreaInfoProgress').empty();
    jQuery('#actionAreaInfoProgress').html('<p>Failed to update account</p>');
}


function successEditAccountSettings() {
    attachClosePopupButton();
    // WE MUST CHECK FOR MODEL AREAS. IF THEY HAPPEN, THEN DON'T UPDATE
    if ($('#newAccountName').text() == '') {
        jQuery('#actionAreaInfoProgress').empty();
    }
    else {
        jQuery('#yourAccountName').text($('#newAccountName').text());
        jQuery('#actionAreaInfoProgress').html('<p>Account settings changed.</p>');
    }
}


function failedCreateAccount() {

    jQuery('#actionAreaInfoProgress').empty();
    jQuery('#actionAreaInfoProgress').html('<p>Failed to create account</p>');
}


function successCreateAccount() {
    attachClosePopupButton();
    jQuery('#moreAccountsListAjaxContainer').html("<img src='/Assets/Images/Site/loading_100x13.gif' class='centered block loadinglargebar'/>");
    jQuery("#moreAccountsListAjaxContainer").load("/GetEblizzed/Manage/Index_MoreAccountsList/" + CORE.Core.urlEncode(LOCAL_DATA.accountId) + "/?cb=" + CORE.Core.createCacheBuster(), function () {  });
}



function addToUserSearchResult(itemUid,itemName,itemPic) {
    var str = '<div class="userlinkitem">';

    str += "<table> <tr height='20'> <td width='60' rowspan='2' >";
   
    if (itemPic) {
        str += '<img class="userlinkitemImage" src="' + itemPic + '"/>';
    }
    else  {
        str += '<img class="userlinkitemImage" src="/Assets/Images/Site/NoUserImage_48x48.png"/>';
    }

    
    str += "</td><td align='left'  width='136'>";
    
   
    str += '<span class="userlinkitemName" style="display:block;position:relative;margin:4px;margin-top:0px;">' + itemName + '</span>';
//    str += '<span style="display:none" class="userlinkitemUid" >' + itemUid + '</span>';

    str += "</td> </tr><tr height='30'> <td align='right' width='136'>";

  
    str += '<a href="#" class="buttoncommand_76 allowaccessbutton" style="margin-right:4px;float:right;" data-facebookUserId="' + itemUid +'">Allow</a>';
    str += "</td>   </tr></table>";

    // url encode  
    str += '</div>';


    jQuery('#friendResultBox').append(str);
}

/// <summary>
/// Attaches the handlers to the link to user functionality, once loaded.
/// </summary>
function attachLinkToUser() {
    jQuery('#buttonSearchFriends').click(function (e) {
        e.preventDefault();

        var searchText = jQuery.trim(jQuery('#friendToSearch').val());

        jQuery('#linkToUserError').text('');

        if (searchText === '') {
            jQuery('#linkToUserError').text('Please enter at least 2 characters.');
        }
        else {
            try {
                var currentUser = CORE.Gateways.FacebookConnect.identityKey;

                jQuery('#friendResultBox').html("<p  class='notificationtext centered block' style='margin-top:10px;margin-bottom:10px;'>Searching...</p> <img  src='/Assets/Images/Site/loading_220x19.gif' alt='' style='margin:20px;margin-top:10px;' class='centered block'/>");

                FB.Facebook.apiClient.fql_query("SELECT uid,name,pic_square FROM user WHERE uid in (select uid1 from friend where uid2 = '" + currentUser + "') and strpos(upper(name), '" + searchText.toUpperCase() + "') >= 0 ORDER BY name",
                                 function (rows) {
                                     jQuery('#friendResultBox').empty();

                                     if (CORE.Core.isArrayWithItems(rows)) {
                                         jQuery(rows).each(function (idx, item) {

                                             addToUserSearchResult(item.uid, item.name, item.pic_square);

                                         });

                                         jQuery('#friendResultBox').append("<div class='clear'></div>");
                                        


                                     }
                                     else {
                                         jQuery('#friendResultBox').html("<p class='notificationtext centered block' style='margin-top:10px;margin-bottom:10px;'>Search returned no friends.</p>");
                                     }

                                 });



            }
            catch (ex) {
                jQuery('#linkToUserError').text('Could not access friends list. Please try again in a couple of seconds.');
                jQuery('#friendResultBox').html("<p class='notificationtext centered block' style='margin-top:10px;margin-bottom:10px;'>No friends to show.</p>");
            }
        }



    });
}


(function ($) {

    function addTooltip(item, body) {

        $(item).local_tooltip({
            track: true,
            delay: 0,
            fade: 0,
            showURL: false,
            opacity: 1,
            fixPNG: true,
            showBody: " - ",
            extraClass: "pretty",
            top: -15,
            left: 5,
            adjustViewport: false,
            bodyHandler: function () {
                return body;
            }

        });
    }

    $(document).ready(function () {
        $.ajaxSetup({ cache: false });

        addTooltip("a.actionboxitemimagelinknew", "<h3>Add a New Site</h3> <p>Click here to add a new site.</p");
        addTooltip("a.actionboxitemimagelinksample", "<h3>View Sample</h3> <p>Click here to view the sample site.</p");
        $("a.actionboxitemimagelinksite").each(function (idx, item) {
            var siteName = $(item).attr("title");

            addTooltip(item, "<h3>" + siteName + "</h3> <p>Click here to manage this site.</p");
        });


        $('#largefbconnectbutton').click(function (e) {
            e.preventDefault();
            CORE.Gateways.FacebookConnect.login();
        });

        $('#accountSettings').click(function (e) {
            e.preventDefault();
            if (pageState != 1) {
                pageState = 1;
                $("#actionArea").html("<img src='/Assets/Images/Site/loading_100x13.gif' class='centered block loadinglargebar'/>");
                $("#actionArea").load("/GetEblizzed/Manage/Index_EditAccountSettings/" + CORE.Core.urlEncode(LOCAL_DATA.accountId) + "/?cb=" + CORE.Core.createCacheBuster(), function () { attachClosePopupButton(); });
   
            }
            else {
                closeActionArea();
            }
        });

        $('#linkToUser').click(function (e) {
            e.preventDefault();
            if (pageState != 2) {
                pageState = 2;
                $("#actionArea").html("<img src='/Assets/Images/Site/loading_100x13.gif' class='centered block loadinglargebar'/>");
                $("#actionArea").load("/GetEblizzed/Manage/Index_LinkToUser/" + CORE.Core.urlEncode(LOCAL_DATA.accountId) + "/?cb=" + CORE.Core.createCacheBuster(), function () {  attachClosePopupButton(); attachLinkToUser(); });
              
            }
            else {
                closeActionArea();
            }
        });

        $('#createNewAccount').click(function (e) {
            e.preventDefault();

            if (pageState != 3) {
                pageState = 3;
                $("#actionArea").html("<img src='/Assets/Images/Site/loading_100x13.gif' class='centered block loadinglargebar'/>");
                $("#actionArea").load("/GetEblizzed/Manage/Index_CreateAccount/" + CORE.Core.urlEncode(LOCAL_DATA.accountId) + "/?cb=" + CORE.Core.createCacheBuster(), function () { attachClosePopupButton(); });
              
            } else {
                closeActionArea();
            }
        });

        $('a.removeuserbutton').livequery('click',function(e) {
            e.preventDefault();
            var securityPrincipalId = $(this).attr('data-securityprincipalid');

            var owner = $(this).parents('div.accessitemcontainer');
             var url = "/GetEblizzed/Manage/Index_LinkToUserFacebookRemove/" + CORE.Core.urlEncode(LOCAL_DATA.accountId) + "/";
           // var uid = jQuery(this).parent().children('.userlinkitemUid').text();

             jQuery.post(url, { targetSecurityPrincipalId: securityPrincipalId }, function (data, textStatus) {
                 jQuery('#actionAreaInfoProgress').html(data);

                 
                 owner.fadeOut('slow', function() { owner.remove();});

             });



        });

        $('a.allowaccessbutton').livequery('click',function (e2) {
             e2.preventDefault();

             var uid = $(this).attr('data-facebookUserId');

             var url = "/GetEblizzed/Manage/Index_LinkToUserFacebook/" + CORE.Core.urlEncode(LOCAL_DATA.accountId) + "/";
           // var uid = jQuery(this).parent().children('.userlinkitemUid').text();

             jQuery.post(url, { targetUserId: uid }, function (data, textStatus) {
                if(data) 
                {                
                     var item =  $(data).hide();
                     item.prependTo($('#accessitemcontainerhost'));                    

                     item.slideDown('slow');
                                 
                 }
                 else {
                    jQuery('#actionAreaInfoProgress').html("<p>Failed to grant access.</p>");
                 
                 }
             });


         });


    });

})(jQuery);

