﻿  
    
    var fbSession = null;
window.fbAsyncInit = function() {
    debug("INIT");
    FB.init({ appId: '143371375692003', status: true, cookie: true, xfbml: true, oauth:true  });
    FB.UIServer.setLoadedNode = function (a, b){FB.UIServer._loadedNodes[a.id] = b; }
    
 
     FB.getLoginStatus(function(response) {
  if (response.authResponse) {
  fbSession=response.authResponse.userID
  fbSessionToken=response.authResponse.accessToken
  }
});  
    
    };
    
    /*
    FB.Event.subscribe('auth.statusChange', function(response) {
        debug("auth.statusChange");
        fbSession = response.session;
        if (response.session != null)
            debug("session: " + response.session.uid);
        else
            debug("no session");
    });
    FB.Event.subscribe('auth.sessionChange', function(response) {
        debug("auth.sessionChange");
        fbSession = response.session;
        if (response.session != null)
            debug("session: " + response.session.uid);
        else
            debug("no session");
    });
    FB.Event.subscribe('auth.logout', function(response) {
        debug("auth.logout");
        _albums_data = null;
        _all_friend_data = null;
        _current_albums_page = 0;
        _current_friends_page = 0;
        _friend_data = null;
        _ext_perms = false;
        _photos_data = null;
        fbSession = response.session;
    });
*/

(function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
} ());

function debug(msg) {
    var date = new Date();
    var _msg = date.toLocaleTimeString() + "." + date.getMilliseconds() + " - " + msg + "\n";
    //alert(_msg);
    $("#__debug").append(_msg);
}

function ShowFB() {
    GetFacebookFriends();
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }
    else {
        return document[movieName];
    }
}

function OpenFriendsSelectorAndHideFlash() {
    var left = $("#CreateFlash").offset().left, top = $("#CreateFlash").offset().top;

    if (jQuery.support.cssFloat) {
        $("#CreateFlash").css("visibility", "hidden");
        $("#FBPlaceholder").css("position", "absolute");
        $("#FBPlaceholder").css("left", left + 75);
        $("#FBPlaceholder").css("top", top + 50);
    }
    else {        
        $("#create").css("position", "absolute");
        $("#create").css("top", "-10000px");
        $("#create").css("left", "-10000px");

        $("#CreateFlash").prepend($("#FBPlaceholder").css("position", "relative").css("left", 75).css("top", 50));
    }

    $("#FBPlaceholder").show();
}
function CloseFriendsSelectorAndShowFlash() {
    $("#FBPlaceholder").hide();

    if (jQuery.support.cssFloat) {
        $("#CreateFlash").css("visibility", "");
    }
    else {
        $("#create").css("position", "relative");
        $("#create").css("top", "0");
        $("#create").css("left", "0");
    }
}

var _all_friend_data = null;
var _friend_data = null;
var _current_friends_page = 0;
var _current_albums_page = 0;
var _albums_data = null;
var _ext_perms = false;
var _kMaxRows = 10;
var _kMsgLogin = 1;
var _kMsgWait = 2;
var _kMsgNoFriends = 3;
var _kMsgNoAlbums = 4;
var _kMsgNoPhotos = 5;

$(document).ready(function() {
    $(".FBCloseButton").attr("value", lblFBSelector_Close).click(function() {
        SetOptionsOnFlashBeforeClosing();
        CloseFriendsSelectorAndShowFlash();
    });
});

function ShowFacebookUsername(uid, name) {
    $("#FacebookUserPlaceholder").html("<b>" + decodeURI(name) + "</b>");
}
function ShowFacebookAlbumName(name) {
    $("#FacebookAlbumnamePlaceholder").html(decodeURI(name));
}

function SetWaiting() {
    ShowStatusMessage(_kMsgWait);
}

function ShowSearchBox() {
    $("#DivFilterFriends").show();
}

function HideSearchBox() {
    $("#DivFilterFriends").hide();
}

function NoSessionCleanup() {
    HideSearchBox();
    $("#FacebookUserPlaceholder").html("");
    $("#FacebookAlbumnamePlaceholder").html("");
    $("#FacebookInfoPlaceholder").html("");
    _albums_data = null;
    _all_friend_data = null;
    _current_albums_page = 0;
    _current_friends_page = 0;
    _friend_data = null;
    _ext_perms = false;
    _photos_data = null;

    ShowStatusMessage(_kMsgLogin);
}

function doFBLogin() {

 FB.login(function(response) {
   if (response.authResponse) {
      fbSession=response.authResponse.userID
  fbSessionToken=response.authResponse.accessToken
     GetFacebookFriends();
   } else {
    // user cancelled login
   }
 }, {scope: 'publish_stream,user_photos,friends_photos'});
} 

function ShowStatusMessage(messageId) {
    switch (messageId) {
        case _kMsgLogin:
            $("#DivFilterFriends").hide();
            ShowFacebookUsername("", lblFBSelector_NeedLogin);
            $("#FacebookInfoPlaceholder").html("<div align=\"center\"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><table cellpadding=\"6\" cellspacing=\"0\" class=\"normaltext\"><tr id=\"trStatusMessage\"><td><img src=\"/images/icon_FB_small.gif\" width=\"16\" height=\"16\" /></td><td><a href=\"#\" onclick=\"doFBLogin(); return false;\"><strong>" + lblFBSelector_Login + "</strong></a></td></tr></table></div>");
            break;
        case _kMsgWait:
            $("#FacebookInfoPlaceholder").html("<div align=\"center\"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><table cellpadding=\"6\" cellspacing=\"0\" class=\"normaltext\"><tr id=\"trStatusMessage\"><td><strong>" + lblFBSelector_Wait + "</strong></td></tr></table></div>");
            break;
        case _kMsgNoFriends:
            $("#FacebookInfoPlaceholder").html("<div align=\"center\"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><table cellpadding=\"6\" cellspacing=\"0\" class=\"normaltext\"><tr id=\"trStatusMessage\"><td><strong>" + lblFBSelector_NoFriends + "</strong></td></tr></table></div>");
            break;
        case _kMsgNoAlbums:
            $("#FacebookInfoPlaceholder").html("<div align=\"center\"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><table cellpadding=\"6\" cellspacing=\"0\" class=\"normaltext\"><tr id=\"trStatusMessage\"><td><strong>" + lblFBSelector_NoAlbums + "</strong></td></tr></table></div>");
            break;
        case _kMsgNoPhotos:
            $("#FacebookInfoPlaceholder").html("<div align=\"center\"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><table cellpadding=\"6\" cellspacing=\"0\" class=\"normaltext\"><tr id=\"trStatusMessage\"><td><strong>" + lblFBSelector_NoPhotos + "</strong></td></tr></table></div>");
            break;
    }
}

function GetFacebookFriends() {
    debug("GetFacebookFriends");
    if (_all_friend_data == null) {
        debug("will get login status");
        if (fbSession != null) {
            debug("will get friends");
            _all_friend_data = null;
            OpenFriendsSelectorAndHideFlash();
            SetWaiting();
            FB.api("/me", function(response) {
                var myName = response.name;
                debug("my name: " + myName);
                FB.api('/me/friends', function(response) {
                    debug("error: " + response.error_msg);
                    response.data.push({ id: fbSession, name: "***" + myName + "***" });
                    _all_friend_data = response.data.sort(function(a, b) {
                        var x = a.name.toLowerCase();
                        var y = b.name.toLowerCase();
                        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
                    });

                    debug("All friends: " + _all_friend_data.length);
                    _friend_data = _all_friend_data.slice();

                    $("#filterFriends").keyup(function(event) {
                        _friend_data = $.grep(_all_friend_data, function(element, index) {
                            return (element.name.toLowerCase().indexOf($("#filterFriends").val().toLowerCase(), 0) >= 0);
                        });
                        debug("Filtered friends: " + _friend_data.length);
                        ShowFacebookFriends(0);
                    });

                    ShowFacebookFriends(0);
                });
            });
        }
        else {
            debug("no session");
            NoSessionCleanup();
            OpenFriendsSelectorAndHideFlash();
        }
    }
    else {
        ShowFacebookFriends(0);
        OpenFriendsSelectorAndHideFlash();
    }
}

function GetFriendsCell(friendData) {
    return "<td width=\"55\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"lnkFBUser\" uid=\"" + friendData.id + "\" username=\"" + encodeURI(friendData.name) + "\"><img src=\"http://graph.facebook.com/" + friendData.id + "/picture?type=square\"/></a></td><td width=\"160\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"lnkFBUser\" uid=\"" + friendData.id + "\" username=\"" + encodeURI(friendData.name) + "\">" + friendData.name + "</a></td>";
}

function ShowFacebookFriends(first_page) {
    _current_friends_page = first_page;
    _albums_data = null;

    ShowSearchBox();
    $("#FacebookUserPlaceholder").html("");
    $("#FacebookAlbumnamePlaceholder").html("");
    $("#FacebookInfoPlaceholder").html("");
    $("#FacebookBackPlaceholder").html("");

    if (first_page == null)
        first_page = 0;
    if (_friend_data != null && _friend_data.length > 0) {
        first_page = parseInt(first_page);

        $("#FacebookUserPlaceholder").html(lblFBSelector_ChooseFriend);

        var strHtml = "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";

        var nextPage = first_page + _kMaxRows, prevPage = first_page - _kMaxRows;
        debug("prev: " + parseInt(prevPage));
        debug("next: " + parseInt(nextPage));
        debug("max: " + parseInt(_friend_data.length / 2));

        if (prevPage >= 0) {
            strHtml += "<tr><td colspan=\"5\" align=\"center\" style=\"font-size:18px;border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"prevFriends\">" + lblFBSelector_Previous + "</a></td></tr>";
        }

        for (var i = first_page, j = 0; i < _friend_data.length / 2 && j < _kMaxRows; i++, j++) {
            strHtml += "<tr>";
            var firstIndex = i * 2;
            if (_friend_data[firstIndex]) {
                strHtml += GetFriendsCell(_friend_data[firstIndex]);
            }
            else {
                strHtml += "<td width=\"55\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td><td width=\"160\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td>";
            }
            strHtml += "<td width=\"19\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td>";
            if (_friend_data[firstIndex + 1]) {
                strHtml += GetFriendsCell(_friend_data[firstIndex + 1]);
            }
            else {
                strHtml += "<td width=\"55\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td><td width=\"160\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td>";
            }
            strHtml += "</tr>";
        }

        if (nextPage < _friend_data.length / 2) {
            strHtml += "<tr><td colspan=\"5\" align=\"center\" style=\"font-size:18px;border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"nextFriends\">" + lblFBSelector_Next + "</a></td></tr>";
        }

        strHtml += "</table>";
        $("#FacebookInfoPlaceholder").html(strHtml);

        $("a.lnkFBUser").css("cursor", "pointer").click(function() {
            GetFacebookAlbums($(this).attr("uid"), $(this).attr("username"));
        });
        $("a.prevFriends").css("cursor", "pointer").click(function() {
            ShowFacebookFriends(parseInt(prevPage));
        });
        $("a.nextFriends").css("cursor", "pointer").click(function() {
            ShowFacebookFriends(parseInt(nextPage));
        });

    }
    else {
        ShowStatusMessage(_kMsgNoFriends);
    }
    //OpenFriendsSelectorAndHideFlash();
}

function _GetFacebookAlbums(uid, username) {
    debug("will get albums");
    SetWaiting();
    FB.api("/" + uid + "/albums?limit=100", function(response) {
        _albums_data = new Array();
        var albums = response.data;
        debug("Total albums: " + response.data.length);
        for (var i = 0; i < albums.length; i++) {
            var row = albums[i];
            if (row.id != uid && row.count) {
                var _album = { aid: row.id, cover: "https://graph.facebook.com/" + row.id + "/picture?access_token=" + fbSessionToken, name: row.name, size: row.count };
                _albums_data.push(_album);
            }
        }
        debug("Total albums: " + _albums_data.length);

        ShowFacebookAlbums(uid, username, 0);
    });
}

function GetFacebookAlbums(uid, username) {
    debug("GetFacebookAlbums");
    if (_albums_data == null) {
        _photos_data = null;
        _GetFacebookAlbums(uid, username);
    }
}

function GetAlbumsCell(albumData) {
    //strHtml += "<a class=\"lnkFBAlbum\" aid=\"" + _albums_data[i].aid + "\" name=\"" + encodeURI(_albums_data[i].name) + "\"><img width=\"50\" src=\"" + _albums_data[i].cover + "\"/>&nbsp;" + _albums_data[i].name + " (" + _albums_data[i].size + ")</a>";
    return "<td width=\"55\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"lnkFBAlbum\" aid=\"" + albumData.aid + "\" name=\"" + encodeURI(albumData.name) + "\"><img width=\"50\" src=\"" + albumData.cover + "\"/></a></td><td width=\"160\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"lnkFBAlbum\" aid=\"" + albumData.aid + "\" name=\"" + encodeURI(albumData.name) + "\">" + albumData.name + " (" + albumData.size + ")</a></td>";
}

function ShowFacebookAlbums(uid, username, albums_page) {
    if (albums_page == null)
        albums_page = 0;
    _current_albums_page = albums_page;

    ShowFacebookUsername(uid, username);
    HideSearchBox();

    $("#FacebookBackPlaceholder").html("<a class=\"back\" uid=\"" + uid + "\">" + lblFBSelector_BackFriends + "</a>");
    $("a.back").css("cursor", "pointer").click(function() {
        ShowFacebookFriends(_current_friends_page);
    });

    if (null != _albums_data && _albums_data.length > 0) {

        var strHtml = "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";

        var nextPage = _current_albums_page + _kMaxRows, prevPage = _current_albums_page - _kMaxRows;
        debug("prev: " + parseInt(prevPage));
        debug("next: " + parseInt(nextPage));
        debug("max: " + parseInt(_albums_data.length / 2));

        if (prevPage >= 0) {
            strHtml += "<tr><td colspan=\"5\" align=\"center\" style=\"font-size:18px;border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"prevAlbums\">" + lblFBSelector_Previous + "</a></td></tr>";
        }

        for (var i = _current_albums_page, j = 0; i < _albums_data.length / 2 && j < _kMaxRows; i++, j++) {
            strHtml += "<tr>";
            var firstIndex = i * 2;
            if (_albums_data[firstIndex]) {
                strHtml += GetAlbumsCell(_albums_data[firstIndex]);
            }
            else {
                strHtml += "<td width=\"55\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td><td width=\"160\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td>";
            }
            strHtml += "<td width=\"19\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td>";
            if (_albums_data[firstIndex + 1]) {
                strHtml += GetAlbumsCell(_albums_data[firstIndex + 1]);
            }
            else {
                strHtml += "<td width=\"55\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td><td width=\"160\" style=\"border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\">&nbsp;</td>";
            }
            strHtml += "</tr>";
        }

        if (nextPage < _albums_data.length / 2) {
            strHtml += "<tr><td colspan=\"5\" align=\"center\" style=\"font-size:18px;border-bottom:thin solid #E5E5E5;padding-bottom:5px; padding-top:5px;\"><a class=\"nextAlbums\">Next</a></td></tr>";
        }

        strHtml += "</table>";
        $("#FacebookInfoPlaceholder").html(strHtml);

        $("a.lnkFBAlbum").css("cursor", "pointer").click(function() {
            GetFacebookPhotos(uid, username, $(this).attr("name"), $(this).attr("aid"));
        });
        $("a.prevAlbums").css("cursor", "pointer").click(function() {
            ShowFacebookAlbums(uid, username, parseInt(prevPage));
        });
        $("a.nextAlbums").css("cursor", "pointer").click(function() {
            ShowFacebookAlbums(uid, username, parseInt(nextPage));
        });
    }
    else {
        ShowStatusMessage(_kMsgNoAlbums);
    }
}

var _photos_data = null;

function GetFacebookPhotos(uid, username, albumname, aid) {
    debug("GetFacebookPhotos");
    debug("will get login status");
    if (fbSession != null) {
        debug("will get photos for aid: " + aid);
        SetWaiting();
        FB.api("/" + aid + "/photos?limit=200", function(response) {
            _photos_data = response.data;
            debug("Photos: " + _photos_data.length);
            ShowFacebookUsername(uid, username + " - " + albumname);
            ShowFacebookPhotos(uid, username, albumname, aid);
        });
    }
    else {
        debug("no session");
        NoSessionCleanup();
    }
}

function ShowFacebookPhotos(uid, username, albumname, aid) {
    if (_photos_data.length > 0) {

        $("#FacebookBackPlaceholder").html("<a class=\"back\" uid=\"" + uid + "\">" + lblFBSelector_BackAlbums + "</a>");
        $("a.back").css("cursor", "pointer").click(function() {
            ShowFacebookAlbums(uid, username, _current_albums_page);
        });
        if (albumname != "" && albumname != null)
            ShowFacebookAlbumName(albumname);

        var strHtml = "<table width=\"430\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\">";
        for (var i = 0; i < _photos_data.length; i++) {
            if (i % 4 == 0)
                strHtml += "<tr>";
            strHtml += "<td><a class=\"lnkFBPhoto\" pid=\"" + _photos_data[i].id + "\" source=\"" + _photos_data[i].source + "\"><img width=\"100\" src=\"" + _photos_data[i].picture + "\"/></a></td>";
            if (i % 4 == 3 || i == _photos_data.length - 1)
                strHtml += "</tr>";
        }
        strHtml += "</table>";
        $("#FacebookInfoPlaceholder").html(strHtml);

        $("a.lnkFBPhoto").css("cursor", "pointer").click(function() {
            //ShowFacebookPhotoPreview(uid, aid, $(this).attr("pid"), $(this).attr("source"));
            SetPhoto($(this).attr("source"));
        });
    }
    else {
        ShowStatusMessage(_kMsgNoPhotos);
    }
}

function ShowFacebookPhotoPreview(uid, aid, pid, source) {
    $("#FacebookBackPlaceholder").html("<a class=\"back\" uid=\"" + uid + "\">" + lblFBSelector_BackPhotos + "</a>");
    $("a.back").css("cursor", "pointer").click(function() { ShowFacebookPhotos(uid, "", aid); });
    debug("Preview: " + source);
    $("#FacebookInfoPlaceholder").html("<a class=\"lnkFBPreview\" pid=\"" + pid + "\"><img width=\"400\" src=\"" + source + "\"/></a><br/>");
    $("a.lnkFBPreview").css("cursor", "pointer").click(function() {
        SetPhoto($("img", this).attr("src"));
    });
}

function SetPhoto(url) {
    CloseFriendsSelectorAndShowFlash();
    if ($("#create").length > 0) {
        thisMovie("create").sendTextToFlash(url);
    }
    if ($("#createLarge").length > 0)
        thisMovie("createLarge").sendTextToFlash(url);
}

function SetOptionsOnFlashBeforeClosing() {
    if ($("#create").length > 0)
        thisMovie("create").sendTextToFlash("");
    if ($("#createLarge").length > 0)
        thisMovie("createLarge").sendTextToFlash("");
}
