(function($) {
    $.fn.oauthenticator = function(options) {
        var opts = $.extend({}, $.fn.oauthenticator.defaults, options);

        return this.each(function() {
            // style the mouse pointer
            $(this).hover(
                function() { $(this).css('cursor', 'pointer'); },
                function() { $(this).css('cursor', 'auto'); }
            );
            // onclick action
            this.network = $(this).attr('name');
            $(this).click(onClick);
        });

        // Ajax callback
        function onClick() {
            if (opts.callback) {
                $.ajax({
                    url: opts.callback,
                    type: 'POST',
                    dataType: 'json',
                    data: { network: this.network },
                    success: function(json){
                        if (json.status == true) {
                            window.location.hash = 'settings';
                            window.location.reload();
                        }
                        // Authentication callback
                        if (json.callback == undefined) {
                            return;
                        }
                        if (opts.connect) {
                            openCenteredWindow(json.callback);
                        }
                    }
                });
            }
            return false;
        }

        function openCenteredWindow(url) {
            var width = 800;
            var height = 800;
            var left = parseInt((screen.availWidth/2) - (width/2));
            var top = parseInt((screen.availHeight/2) - (height/2));
            var windowFeatures = "width=" + width + ",height=" + height + ",status,resizable,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
            myWindow = window.open(url, "subWind", windowFeatures);
        }
    }

    $.fn.oauthenticator.defaults = { callback: false, connect: true }
})(jQuery);

