
function fb_getLoggedInUser(){
    if(fbc.connected && fbc.uid) return fbc.uid;

    FB.getLoginStatus(function(response) {
      if (response.authResponse) {
          return response.authResponse.userID;
      }
      else return null;
    });
}

function onFBLinkPress(){

    FB.getLoginStatus(function(response) {

      if (response.authResponse) {
        var params = response.authResponse;
        $.post(config.base_path + "/user/aj_fb?a=link", params,function(data){
            if(data.status=="OK") reloadPage();
        },"json");
      } else {
         FB.login(function(response) {
            var params = response.authResponse;
            $.post(config.base_path + "/user/aj_fb?a=link", params,function(data){
                if(data.status=="OK") reloadPage();
            },"json");
         }, {scope:'offline_access,publish_stream,user_birthday,friends_birthday,email'});
      }
    });
}

function onFBLoginPress(callback){
    FB.getLoginStatus(function(response) {
      if (response.authResponse) {
         fb_responseHandler(response, callback);
      } else {
         FB.login(function(response) {
            fb_responseHandler(response, callback);
         }, {scope:'offline_access,publish_stream,user_birthday,friends_birthday,email'});
      }
    });
}

function fb_responseHandler(response, callback){
      if (response.authResponse) {
            var params = response.authResponse;
            $.post(config.base_path + "/user/aj_fb?a=linked", params, function(data){
                var popup = $("#popup");
                popup.css("position","absolute");
                if($.browser.msie) popup.css("top",document.documentElement.scrollTop+150);
                else popup.css("top",window.pageYOffset+150);
                $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")

                if(data.status=="OK"){
                    $(callback);
                }
                else if(data.status=="FAILED" && data.email=="proxy"){
                    $(".content",popup).load("/user/fbnoproxy", {}, function(){
                        popup.removeClass().addClass("fbnoproxy");
                        $("h3",popup).html('A Valid Email Address Is Required');
                        $(".link-button .need-account",popup).hide();

                        $("div.link-button a.unsubscribe",popup).removeAttr("onclick");
                        $("div.link-button a.unsubscribe",popup).html("Cancel").unbind("click").click(function(){
                                $("#popup").jqmHide();
                                $(this).attr("onclick", "location.href=this.href; return false;");
                                return false;
                        }).show();

                        $(".link-button .button",popup).html("Retry &raquo;").unbind("click").click(function(){
                            $("#popup").jqmHide();
                            $("div.link-button a.unsubscribe",popup).attr("onclick", "location.href=this.href; return false;");
                            onFBLoginPress(callback);
                            return false;
                        });

                        $(".close",popup).click(function(){
                            $("#popup").jqmHide();
                            $("div.link-button a.unsubscribe",popup).attr("onclick", "location.href=this.href; return false;");
                        });
                        popup.jqmShow();
                    });
                    return false;
                }
                else {
                    $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
                    $("h3",popup).html('Accept Terms <span class="onetime">(You only need to do this once)</span>');
                    $("div.link-button a.unsubscribe",popup).hide();
                    $(".link-button .need-account",popup).hide();

                    $(".content",popup).load("/static/popup-login-fbagree.php", {}, function(){
                        popup.removeClass().addClass("fbtermsonly");
                        $(".link-button .button",popup).html("Finish &raquo;").unbind("click").click(function(){
                            if($(this).hasClass("disabled")) return false;
                            $(this).addClass("disabled");
                            if($("#popup .content #fbc_terms:checked").length<=0){
                                $(".fbc_termsonly_error", popup).html("You must agree to the Terms of Service.").show();
                                $(this).removeClass("disabled");
                                return false;
                            }
                            $(".link-button .button",popup).html("Finish &raquo;").unbind("click");
                            $(".fbc_termsonly_error", popup).hide();
                            $("#popup .link-button .ajax").show();
                            var news = ($("#popup .content #fbc_newsletter:checked").length>0);
                            $.post(config.base_path + "/user/fbajaxlogin", {newsletter:news}, function(data){
                                $("#popup .link-button .ajax").hide();
                                if(data.status=="OK") {
                                    if(callback) $(callback);
                                }
                                else {
                                    $("#popup").jqmHide();
                                    showMessage(data.error, "Alert");
                                    return;
                                }
                            }, "json");
                            return false;
                        });
                        popup.jqmShow();

                    });
                    return false;

                }
            }, 'json');

          // user is logged in and granted some permissions.
      } else {
        // user is not logged in
      }
}

function showBirthdayPerm(callback){
   onFBLoginPress(callback);
   return false;
}

function fb_validateEmailOnly(e, ec, terms_sel){

    if($(terms_sel+":checked").length<=0){ return 'You must agree with the Terms of Service and Privacy Policy to continue.'; }
    // check for empty
    if(e=="" || ec==""){ return 'Please enter an email address.'; }
    // check email format
    if (!validateEmail(e)) { return 'Please enter a valid email.'; }
    // check email match
    if((e!="" && ec!="") && e!=ec){ return 'Emails don\'t match.'; }

    return '';
}

function fb_publishCardToStream(p_fbid, p_attch){
    var attch = {
         method: 'feed',
         display: 'iframe',
         app_id: fbc.appid,
         name: p_attch.name,
         link: p_attch.href,
         description: p_attch.description,
         message: ''
    }
    if(p_attch.media){
        var m = p_attch.media[0];
        if(m.type=='image')
            attch.picture = m.src;
    }
    if(p_fbid) attch.to = p_fbid;
    FB.ui(attch);
    return false;
}

function fb_sendMessage(p_fbid, p_attch){
    var attch = {
         method: 'send',
         display: 'iframe',
         app_id: fbc.appid,
         name: p_attch.name,
         link: p_attch.href,
         description: p_attch.description
    }
    if(p_attch.media){
        var m = p_attch.media[0];
        if(m.type=='image')
            attch.picture = m.src;
    }
    if(p_fbid) attch.to = p_fbid;
    FB.ui(attch);
    return false;
}

/*
function fb_publishCardToStatus(msg){
    FB.ensureInit(function() {
        FB.Connect.streamPublish(msg, null, null, null, null, function(post_id, exception){});
        if($(".fb_friend_list .options li.ajax-loader").length>0)
            $(".fb_friend_list .options li.ajax-loader").hide();
    });
}
*/

function bindFBDock(dock_id, fbpost_attch, is_overlay){
    var dock = $("#"+dock_id);
    if(is_overlay) dock = $("#cardthumb_overlay #"+dock_id);
    
    // toggle options
    dock.find(".options .close").click(function(e){
        e.preventDefault();
        if(dock.is(":visible")) dock.fadeOut();
        else {
            dock.fadeIn();
        }
    });

    // fetch friend list
    dock.find(".friendpost .post_friend_link").click(function(e){
        e.preventDefault();
        dock.find(".friendpost").addClass("selected");
        dock.find(".friend_list_holder")
               .html('<div class="select_friend"><div class="ajax-loader"><img src="http://cdn.someecards.com/someecards/sec/images/ajax-loader-white.gif" /> Loading friend list...</div></div>');
        $.get("/user/fbgetfriends?sendcard=1&did="+dock_id+((!fb_getLoggedInUser())?'&nc=1':''), {}, function(data){
            dock.find(".friend_list_holder").html(data);
            var fb_frlist = dock.find("ul.friend_list");

            // lazy loader
            var lazyloadTimeout;
            fb_frlist.scroll(function(e){
                clearTimeout(lazyloadTimeout);
                lazyloadTimeout = setTimeout(function(){
                    var threshold = 50, top = fb_frlist.scrollTop(), hei = fb_frlist.height()+threshold;
                    fb_frlist.find("li[class!=loaded]:visible").each(function(){
                        var img_top = top+$(this).position().top;
                        if(img_top >= (top-threshold) && img_top <= (top+hei) ){
                            var i = $(this).children("img.profile_thumb");
                            i.attr("src", i.attr("id")).removeAttr('id');
                            $(this).addClass("loaded");
                        }
                    });
                }, 50);
            });

            // friend click
            fb_frlist.children("li").click(function(e){
                e.preventDefault();
                var frid = $(this).attr("id").substr(12);
                fb_publishCardToStream(frid, fbpost_attch);
            });

            dock.find(".fb_find_friends").keyup(function(e){
                var q = $.trim($(this).val().toLowerCase());
                if(q != '') dock.find(".clear_fb_search").show();
                else dock.find(".clear_fb_search").hide();
                var llc = 0;
                fb_frlist.children("li").each(function(i){
                    var n = $(this).children("label").html().toLowerCase();
                    if(n.indexOf(q)!=-1){
                        $(this).show();
                        if(!$(this).hasClass("loaded") && llc<17){
                            var i = $(this).children("img.profile_thumb");
                            i.attr("src", i.attr("id")).removeAttr('id');
                            $(this).addClass("loaded");
                            llc++;
                        }
                    }
                    else $(this).hide();
                });

            });
            dock.find(".clear_fb_search").click(function(e){
                e.preventDefault();
                dock.find(".fb_find_friends").val('').trigger("keyup");
            });

        });
    });

    // publish to stream
    dock.find(".publishToStream").click(function(e){
        e.preventDefault();
        if(!fb_getLoggedInUser()){
            onFBLinkPress();
            return false;
        }
        fb_publishCardToStream(null, fbpost_attch);

    });

    dock.find(".sendMessage").click(function(e){
        e.preventDefault();
        dock.find(".options li.ajax-loader").show();
        fb_sendMessage(null, fbpost_attch);
    });

    // publish status
    /*
    dock.find(".publishToStatus").click(function(e){
        e.preventDefault();
        dock.find(".options li.ajax-loader").show();
        fb_publishCardToStatus(fbpost_attch.name+': '+fbpost_attch.short_url);
    });
    */

}

function toggleFBDock(dockid){
    var dock = $(dockid);
    if(dock.is(":visible")) dock.fadeOut();
    else {
        dock.fadeIn();
        dock.find(".friendpost .post_friend_link").trigger('click');
    }

}

