﻿/*
*   jfbLike :  used for Facebook Like Button setup and interaction. only subscribes for first trigger of 'Like' and 'Unlike'
*   useage:	
*           $("#placeToCreateLikeButton").jfbLike({url:'path/to/somewhere', likeCallback:function(){dosomething}});
*           
*	
*   dependencies: jquery-latest.js(currently 1.4.2)
*                               http://connect.facebook.net/en_US/all.js#xfbml=1 reference - cannot load this via javascript: something in the remote script fails the draw of the button if it is loaded asynchronously.
*/
(function ($) {
    // plugin definition
    $.fn.jfbLike = function (options) {
        // Extend our default options with those provided.
        var opts = $.extend({}, $.fn.jfbLike.defaults, options);

        var likeFn = function (rspnse) {
            opts.likeCallback();
        }
        $.fn.jfbLike.callbacks.push({name: 'edge.create', fn: likeFn});
        var unlikeFn = function (rspnse) {
            opts.unlikeCallback();
        }
        $.fn.jfbLike.callbacks.push({name: 'edge.remove', fn: unlikeFn});

        //remove existing
        $(opts.fbLikeId).remove();
        var $container = $(this);
        $.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
            $("html").attr("xmlns", "http://www.w3.org/1999/xhtml");
            $("html").attr("xmlns:fb", "http://www.facebook.com/2008/fbml");
            $container.append('<div  id="' + opts.fbLikeId + '"><div id="fb-root"></div><fb:like href="' + opts.url + '" send="false" layout="button_count" width="200" show_faces="false" font="verdana"></fb:like></div>');

            FB.Event.subscribe('edge.create', likeFn);
            FB.Event.subscribe('edge.remove', unlikeFn);
        });
    }
    $.fn.jfbLike.defaults = {
        fbLikeId: "jfbLike",
        url: "",
        likeCallback: function () {
            alert('liked!');
        },
        unlikeCallback: function () {
            alert('unliked!!');
        }
    };

    $.fn.jfbLike.clear = function () {
        for(var i=0;i < $.fn.jfbLike.callbacks.length;i++)
        {
            FB.Event.unsubscribe($.fn.jfbLike.callbacks[i].name, $.fn.jfbLike.callbacks[i].fn);
        }
        $.fn.jfbLike.callbacks = [];
    };
    $.fn.jfbLike.callbacks = new Array();
})(jQuery);
