/*
 * FWB aka Friends with Benefits 
 */

var fwb = {
    login_url : "",
    api: "/_fwb/json/",
    methods: {
        IS_LOGGED_IN : "is_logged_in.php?",
        FRIENDS_GET  : "friends_get.php?",
        SEND_EMAIL   : "send_email.php?",
        SHARE        : "share.php?"
    },
    user: {
        is_logged_in : false,
        uid          : "",
        first_name   : "",
        last_name    : "",
        pic_small    : "",
        friends      : null
    },
    share_form: {
        title         : "",
        link          : "",
        publishLabel  : "Publish this story to your profile?",
        friendsLabel  : "Send to:",
        shareBtnLabel : "Share",
        rendered      : false
    },

    init: function() {
        // add the checkbox plugin hooks to jquery.
        jQuery.fn.check = function(mode) {
                // if mode is undefined, use 'on' as default
                var mode = mode || "on";
                return this.each(function() {
                switch(mode) {
                    case "on":
                        this.checked = true;
                        break;
                    case "off":
                        this.checked = false;
                        break;
                    case "toggle":
                        this.checked = !this.checked;
                        break;
                }
            });
        };

        this.check_login();
    },

    no_cache: function() {
        return "&nocache=" + (new Date()).getTime() + Math.floor(Math.random()*20000) + "&callback=?";
    },

    check_login: function() {
        $.getJSON(this.api + this.methods.IS_LOGGED_IN + this.no_cache(), this.handle_check_login);
    },
    handle_check_login: function(data) {
        fwb.user.is_logged_in = data.is_logged_in;
        fwb.login_url = data.login_url;
        if ( data.is_logged_in ) {
            fwb.user.uid = data.uid;
            fwb.user.first_name = data.first_name;
            fwb.user.last_name = data.last_name;
            fwb.user.pic_small = data.pic_small;
            $("#fwb_login_status").html("<span class='welcome'>Welcome, <b>" + data.first_name + "</b> - </span><span class='logout'><a href='/_fwb/logout.php?next=" + escape(document.location) + "'>Logout</a></span>");
            $("#fwb_login_status").show();
            $("#fwb_login_btn").hide();
        } else {
            // update the link for the login button to a popup.
            $("#fwb_login_btn a").click(
                    function () {
                        fwb.show_login();
                        return false;
                    }
                );
            $("#fwb_login_status").hide();
            $("#fwb_login_btn").show();
        }
        $(document).trigger("fwbReady", fwb.user.is_logged_in);
        $("#fwb_login_status").trigger("fwbReady", fwb.user.is_logged_in); //backwards compatability
    },
    show_login: function() {
        // URL,ID,WIDTH,HEIGHT,RESIZE,SCROLL,MENU,TOOL,LOCATION,DIRECTORIES,STATUS
        popupWin(this.login_url, "FBLOGIN", 646, 436, "yes", "yes", "no", "no", "no", "no", "no");
        return false;
    },

    friends_get: function(callback) {
        if (this.user.friends != null) callback();
        $.getJSON(this.api + this.methods.FRIENDS_GET + this.no_cache(), this.handle_friends_get);
    },
    handle_friends_get: function(data) {
        if (data.messages.has_error) {
            alert("An error occured when we tried to get your friends:\n" + data.messages.message[0].message);
            return;
        }
        if (!data.friends.length) {
            alert("You don't have any friends on Facebook to share this link with.");
            return;
        }
        fwb.user.friends = data.friends;
        fwb.build_share_form();
    },

    show_share_button: function(event, isLoggedIn) {
        title = event.data.title || document.title;
        link = event.data.link || document.location;
        params = event.data.params || {};
        fwb.share_form.title = escape(title);
        fwb.share_form.link = escape(link);
        if (params.publishLabel) fwb.share_form.publishLabel = params.publishLabel;
        if (params.friendsLabel) fwb.share_form.friendsLabel = params.friendsLabel;
        if (params.shareBtnLabel) fwb.share_form.shareBtnLabel = params.shareBtnLabel;

        var shareBtn = $("#fwb_share_button");
        shareBtn.html('Share using <a href="" onclick="fwb.show_share(); return false;"><img src="/_fwb/img/facebook.jpg" align="absmiddle" /></a>');
        shareBtn.show();
        return;
    },
    show_share: function(skipValidation) {
        var _skipValidation = skipValidation || false;
        var shareElement = $("#fwb_share");
        if (!_skipValidation) {
            if (shareElement.css("display") == "block") {
                shareElement.slideUp("fast");
                return;
            }
            if ( !this.user.is_logged_in ) {
                shareElement.slideDown("fast");
                shareElement.html("You must <a href='' onclick='fwb.show_login(); return false;'>login to Facebook</a> to share this page with your friends.");
                return;
            }
            if ( !this.share_form.rendered ) {
                shareElement.slideDown("fast");
                shareElement.html("<em>Loading.  Please wait...</em>");
                this.friends_get( this.build_share_form );
                return;
            }
        }

        shareElement.show();
        $("#fwb_share_form").show();
        $("#fwb_share_form_msg").hide();
    },
    build_share_form: function() {
        var html = '<div id="fwb_share_form"><form><fieldset>';
        var curPic = "";
        html += '<div id="fwb_publish_to_profile_container"><label id="fwb_publish_to_profile_lbl" for="fwb_publish_to_profile">' + this.share_form.publishLabel + '</label><input type="checkbox" name="publish" id="fwb_publish_to_profile" value="1" /></div>';
        html += '<div id="fwb_share_to_container"><label id="fwb_share_to_lbl">' + this.share_form.friendsLabel + '</label><div id="fwb_share_to_friends">';
        $.each(this.user.friends, function(i, friend) {
                if (friend.name != "") {
                    curPic = friend.pic_square;
                    if (curPic == "" ) curPic = "http://static.ak.fbcdn.net/pics/q_silhouette.gif";
                    html += "<div class='fwb_share_to_friend' id='fwb_friendBox_" + friend.uid + "' onclick='fwb.select_friend(\"" + friend.uid + "\");'>";
                    html += "<div class='fwb_share_to_friend_pic'><img src='" + curPic + "' /></div>";
                    html += "<div class='fwb_share_to_friend_info'><p class='fwb_share_to_friend_name'>";
                    if (friend.name.length > 11) {
                        html += friend.name.substring(0, 11) + "...</p>";
                    } else {
                        html += friend.name + "</p>";
                    }
                    if (friend.city != "") {
                        html += "<p class='fwb_share_to_friend_city'>"
                        if (friend.city.length > 11) {
                            html += friend.city.substring(0, 11) + "...";
                        } else {
                            html += friend.city;
                        }
                        html += "</p>";
                    }
                    html += "</div></div>";
                    html += "<input type='checkbox' style='display: none;' name='to' class='fwb_friend_cbx' id='fwb_friend_" + friend.uid + "' value='" + friend.uid + "' />";
                }
            });
        html += '</div></div>';
        html += '<div id="fwb_share_btn_share_container"><input type="button" id="fwb_share_btn_share" value="' + this.share_form.shareBtnLabel + '" onclick="fwb.share();" /></div>';
        html += '<input type="hidden" name="title" id="fwb_share_title" value="' + this.share_form.title + '" />';
        html += '<input type="hidden" name="link" id="fwb_share_link" value="' + this.share_form.link + '" />';
        html += '</fieldset></form></div>';
        html += '<div id="fwb_share_form_msg"></div>';
        $("#fwb_share").html(html);

        this.share_form.rendered = true;
        this.show_share(true);
    },
    select_friend: function(friend) {
        $("#fwb_friendBox_" + friend).toggleClass("selected");
        $("#fwb_friend_" + friend).check("toggle");
    },
    share: function() {
        var formVars = $("#fwb_share_form form").serialize();
        var methodURL = this.api + this.methods.SHARE;
        methodURL = methodURL + formVars;
        var shareBtn = $("#fwb_share_btn_share");
        shareBtn.attr("disabled", true);
        shareBtn.val("Please wait...");
        $.getJSON(methodURL + this.no_cache(), this.handle_share);
    },
    handle_share: function(data) {
        var msg = $("#fwb_share_form_msg");
        var animateOut = true;
        $("#fwb_share_form").hide();
        if (data.messages.has_error) {
            msg.html("<em>An error occurred: " + data.messages.message[0].message + "</em> - <a href='' onclick='fwb.show_share( true ); return false;'>Try again.</a>");
            animateOut = false;
        } else {
            msg.html("<em>Your message has been sent.</em>");
            // uncheck all of the friends now.
            $(".fwb_friend_cbx").check("off");
            $(".fwb_share_to_friend").removeClass("selected");
        }
        msg.show();
        if (animateOut)
            $("#fwb_share").animate({opacity: 1.0}, 4500).fadeOut("slow");
        var shareBtn = $("#fwb_share_btn_share");
        shareBtn.attr("disabled", false);
        shareBtn.val( fwb.share_form.shareBtnLabel );
    }
};

// sometimes jquery seems to not be registered
// when using include_once.  this will make
// sure we don't do anything until it's loaded.
var jqueryLoaded = false;
var jqueryTimeout = null;
function loadFWB() {
    if (jqueryLoaded) return;
    if ( typeof($) == "function" ) {
        jqueryLoaded = true;
        clearTimeout(jqueryTimeout);
        $(document).ready(function() {
            fwb.init();
        });
    } else {
        jqueryTimeout = setTimeout("loadFWB()", 2000);
    }
}
//loadFWB();