﻿/// <reference path="jquery-vsdoc.js" />
// need to prevent executing FB.Loader.loadedCallback after FB.Connect has been loaded
//var accomplishedRqst = 0;
// need to prevent fbScript multi loading
var fbScriptIsBeingLoaded = false;
function fbTimeoutCallback() {
    if (!window.FB && window.showMessageBox)
        showMessageBox("Cannot connect to Facebook. Try again later.");
}
function loadFBScript(callback) {
    if (fbScriptIsBeingLoaded)
        return;

    fbScriptIsBeingLoaded = true;
    $.getScript("http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php",
        function () {
            if (!window.FB) {
                if (window.showMessageBox)
                    showMessageBox("Cannot connect to Facebook. Try again later.");
                return;
            }
            //            FB.init("573f4a102df6fea8530f044c3e7846eb", "http://www.lavva.com/xd_receiver.htm", { doNotUseCachedConnectState: true });
            FB.init({ appId: '116990036145', status: true, cookie: true, xfbml: true, channelUrl: "http://www.lavva.com/xd_receiver.htm" });
            // make sure if FB.Connect has been loaded then make login
            FB.ensureInit(function () {
                callback()
            });
        }
    );
    fbScriptIsBeingLoaded = false;
}

function fbOnConnected() {
}

function fbLogin(onSuccess, skipFBInit) {
    // if FB already loaded
    if (!skipFBInit) {
        // try to load FB script and make attempt again
        loadFBScript(function () { fbLogin(onSuccess, true); });
    }
    if (window.FB) {

        FB.getLoginStatus(function (response) {
                if (response.session) {
                    onSuccess();
                }
                else {
                    FB.login(function (response) { if (response.perms) onSuccess(); }, { perms: 'user_birthday,user_activities,user_about_me,user_education_history,user_events,user_groups,user_hometown,user_interests,user_likes,user_location,user_notes,user_online_presence,user_photo_video_tags,user_photos,user_religion_politics,user_status,user_videos,user_website,user_work_history,email,read_stream,friends_interests,friends_likes,friends_hometown,friends_location,friends_groups,friends_activities,friends_birthday,friends_education_history,friends_events,friends_hometown,friends_likes,friends_interests,friends_photos,friends_videos,friends_status,friends_website,friends_work_history,offline_access,publish_stream' });
                }
        });
        //FB.Connect.requireSession(function(exception) { fbLoginSuccess(exception, onSuccess); }, true);
    }

}
function fbLoginSuccess(exception, onSuccess) {
    if (exception)
        return;

    FB.ensureInit(function () {
        FB.Facebook.apiClient.users_hasAppPermission('read_stream',
                        function (res1) {
                            if (res1 == 0)
                                FB.Connect.showPermissionDialog("email,user_birthday,user_activities,user_about_me,user_education_history,user_events,user_groups,user_hometown,user_interests,user_likes,user_location,user_notes,user_online_presence,user_photo_video_tags,user_photos,user_religion_politics,user_status,user_videos,user_website,user_work_history,read_stream,friends_interests,friends_likes,friends_hometown,friends_location,friends_groups,friends_activities,friends_birthday,friends_education_history,friends_events,friends_hometown,friends_likes,friends_interests,friends_photos,friends_videos,friends_status,friends_website,friends_work_history,offline_access,publish_stream");
                            else
                                FB.Facebook.apiClient.users_hasAppPermission('publish_stream',
                                function (res2) {
                                    if (res2 == 0)
                                        FB.Connect.showPermissionDialog("email,user_birthday,user_activities,user_about_me,user_education_history,user_events,user_groups,user_hometown,user_interests,user_likes,user_location,user_notes,user_online_presence,user_photo_video_tags,user_photos,user_religion_politics,user_status,user_videos,user_website,user_work_history,read_stream,friends_interests,friends_likes,friends_hometown,friends_location,friends_groups,friends_activities,friends_birthday,friends_education_history,friends_events,friends_hometown,friends_likes,friends_interests,friends_photos,friends_videos,friends_status,friends_website,friends_work_history,offline_access,publish_stream");
                                });
                        });

    });
    onSuccess();
}

function addFBLogoutOnEndRequest() {
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (prm) {
        prm.add_endRequest(function (sender, args) { prm.remove_endRequest(arguments.callee); setTimeout(fbLogout, 1, false); });
    }
}

function fbLogout(skipFBInit, onSuccess) {
    if (window.FB) {
        FB.logout(function () { if (typeof (onSuccess) == 'function') onSuccess(); else fbLogoutSuccess(); }) //FB.Connect.logout
    }
    else if (!skipFBInit) {
        // try to load FB script and make attempt again
        loadFBScript(function () { fbLogout(true, typeof (onSuccess) == 'function' ? onSuccess : null); });
    }
}
function fbLogoutSuccess() {
}
function fbReparseAll() {
    //alert("...parsing");
}
function fbSharing(link, skipFBInit) {
    try {
        if (window.FB)
            FB.ensureInit(function () {
                FB.Connect.showShareDialog(decodeURIComponent(link));
            });
        else if (!skipFBInit)
        // try to load FB script and make attempt again
            loadFBScript(function () { fbSharing(decodeURIComponent(link), true); });
    }
    catch (luk)
    { }
}

/*Send invitation via JS*/
// show window
function fbShowInviteWindow(skipFBInit) {
    if (window.FB) {
        var permiss = "read_stream, publish_stream";
        var show = function () {
            //show window
            var el = document.getElementById("fbInviteWrapper");
            el.style.display = "block";

            //set fbml invitation code
            el = document.getElementById("fbInviteContainer");
            el.innerHTML =
                '<fb:serverfbml>\
                    <script type="text/fbml">\
                    <fb:fbml>\
                        <fb:request-form action="' + window.location + '" method="POST" invite="true" type="Lavva" \
                            content="Your friend invite you to be social with Lavva <fb:req-choice url=\'http:\/\/www.facebook.com/login.php?api_key=573f4a102df6fea8530f044c3e7846eb\' label=\'Go to Lavva!\' />  " >\
                            <fb:multi-friend-selector condensed="false" showborder="false" rows="3" bypass="cancel" \
                                actiontext="Invite your friends to use Lavva."/>\
                        </fb:request-form>\
                    </fb:fbml>\
                    </script>\
                </fb:serverfbml>';
            if (FB && FB.XFBML && FB.XFBML.Host)
                FB.XFBML.Host.parseDomElement(el);
            //FB.Facebook.apiClient.friends_get('', fbProcessFriends);
        };
        show();
        //FB.Connect.showPermissionDialog(permiss, show);
    }
    else if (!skipFBInit)
    // try to load FB script and make attempt again
        loadFBScript(function () { fbShowInviteWindow(true); });
}

var fbInvFriends = null;
var userInvFields = ['name', 'pic_square'];

// save friends and begin to get friends` info
function fbProcessFriends(res) {
    if (res && res.length) {
        fbInvFriends = res;
        FB.Facebook.apiClient.users_getInfo(res[0], userInvFields,
            function (res, ex) { fbShowInvUser(res, ex, 1); }
            );
    }
}

// get all friends` info
function fbShowInvUser(res, ex, index) {
    // show friend
    if (res && res.length) {
        var container = document.getElementById("fbInviteContainer");
        var el = document.createElement("div");
        el["class"] = "fbIFriendItem";
        el.innerHTML = "<div><input type='checkbox'/></div><div><img src='" + res[0].pic_square + "'/> <span>" + res[0].name + "</span></div>";
        container.appendChild(el);
    }
    // get next friend
    if (index < fbInvFriends.length) {
        FB.Facebook.apiClient.users_getInfo(fbInvFriends[index], userInvFields,
            function (r, ex) { fbShowInvUser(r, ex, index + 1); }
            );
    }
}
// hide window
function fbHideInviteWindow() {
    var el = document.getElementById("fbInviteWrapper");
    el.style.display = "none";
}

function fbSendNotifications() {
    var api = FB.Facebook.apiClient;
    var ids = fbInvFriends;
    try {
        api.notifications_send(ids, "Welcome to the http:://next.lavva.com/", sendNRes);
    }
    catch (ex) { }
}

function sendNRes(res, ex) {
    alert("For now all invited");
    fbHideInviteWindow();
}

function fireFBLink(anchor) {
    $($(anchor).parents('.xPLH').get(0)).append(loaderHTML);
    $('#fbWdgWrp').load(anchor.href + ' #fbMainContent',
        function () { $('#fbWdgWrp').find(".pwLoader").remove(); });
    return false;
}
function fbShowComments(id) {
    if ($("#" + id).is(':hidden'))
        $("#" + id).show();
    else
        $("#" + id).hide();
}
function fbSendComment(anchor) {
    var value = $.trim($(anchor).parent().find(".fbCmntTB").val());
    if (value && value != "")
        anchor.href += "&cmv=" + encodeURIComponent(value);
    else
        return false;
    return fireFBLink(anchor);
}
function fbShareThought(anchor) {
    $('.fbShareTBI').children().each(function () { $(this).text($(this).text() + " "); });
    var value = $.trim($('.fbShareTBI').text());
    if (value && value != "") {
        anchor.href += "&sv=" + encodeURIComponent(value);
    }
    else
        return false;
    return fireFBLink(anchor);
}

