(function() {
    var initializing = false,
    fnTest = /xyz/.test(function() {
        xyz;
    }) ? /b_superb/: /.*/;
    this.gClass = function() {};
    gClass.extend = function(prop) {
        var _super = this.prototype;
        initializing = true;
        var prototype = new this();
        initializing = false;
        for (var name in prop) {
            prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn) {
                return function() {
                    var tmp = this._super;
                    this._super = _super[name];
                    var ret = fn.apply(this, arguments);
                    this._super = tmp;
                    return ret;
                };
            })(name, prop[name]) : prop[name];
        }
        function gClass() {
            if (!initializing && this.initialize)
            this.initialize.apply(this, arguments);
        }
        gClass.prototype = prototype;
        gClass.constructor = gClass;
        gClass.extend = arguments.callee;
        return gClass;
    };
})();

if (Function.prototype.bind == undefined) {
    jQuery.extend(Function.prototype, {
        bind: function(what) {
            var thisfunc = this;
            return function() {
                thisfunc.apply(what, arguments);
            }
        }
    });
}

var GawkerBase = gClass.extend({
    initialize: function() {},
    setOptions: function(options) {
        var baseOptions = this.options;
        this.options = options;
        for (optionName in baseOptions) {
            if (!this.options[optionName])
            {
                this.options[optionName] = baseOptions[optionName];
            }
        }
    }
});
/*
var XHR = GawkerBase.extend({
    options: {
        type: 'POST',
        dataType: 'json',
        klass: null
    },
    initialize: function(options) {
        this.setOptions(options);
    },
    send: function(url, queryString) {
        Logger.debugLog(this.options.klass + ' sending...');
        this.options.url = url;
        this.options.data = queryString;
        jQuery.ajax(this.options);
    }
});
*/



var SclipoBase = GawkerBase.extend({

    initialize: function() {},

    setOptions: function( options ) {
        // this flipping needs if we don't want member variables to be totally garbled
        var baseOptions = this.options;
        this.options = options;
        for( optionName in baseOptions ) {
            if ( !this.options[optionName] )
            {
                this.options[optionName] = baseOptions[optionName];
            }
        }
    }

});


var Sclipo_FBC = SclipoBase.extend({
    initialize: function( appid, receiver) {
        this.logging_enabled = false;
        this.appid = appid;
        this.receiver = receiver;
        this.fbInit();
    },
    fbInit: function() {
        FB.Facebook.init( this.appid, this.receiver );
    },
    fbReady: function( callback, option, optional ) {
        FB.Facebook.get_sessionWaitable().waitUntilReady(function() {
            this.fb_sess = FB.Facebook.apiClient.get_session();
            FB.Facebook.apiClient.users_getInfo( this.fb_sess['uid'], new Array('name'), function(result,ex){
                this.fb_user = result;
                try {
                    this.fb_user = this.fb_user[0];
                    if( this.fb_user.uid ) {
                        if( callback ) {
                            switch( callback ) {
                                case 'fbLoginOrRegister':
                                    this.fbLoginOrRegister();
                                break;
                                case 'fbComment':
                                    this.fbComment( option, optional );
                                break;
                                case 'fbFriends':
                                    this.fbFriends();
                                break;
                                case 'fbAskForMail':
                                    this.fbAskForMail();
                                break;
                                case 'fbAskForUpdate':
                                    this.fbAskForUpdate();
                                break;
                                case 'fbAskForOffline':
                                    this.fbAskForOffline();
                                break;
                                case 'fbLogout':
                                    this.fbLogout();
                                break;
                            }
                        }
                        return true;
                    } else {
                        return false;
                    }   
                } catch( e ) {}
            }.bind(this));
        }.bind(this));
    },
    fbLoginOrRegister: function() {
        // not sure about the arbitrary div id here
//        alert('cargar box connected user');
//        alert(window.location.href);
        $.post("/fbook/FBConnect", { url: window.location.href }, 
         function(data){  
            if (data != '')
            {
                $.facebox(data);
            }
            else
            {
                window.location.reload(true);
            }
//            alert(data);
//            window.location = data;
         });  
//        jQuery('.menubar_facebook_connect_placeholder').load( '/fbook/FBConnect' );
    },
/*
    fbComment: function( id, cid ) {
        // type hint doesn't seem to do anything here
        jQuery.post( '/?op=fb&action=publishComment', { 'id': id, 'cid' : cid }, function(data){
            gmfbc.fbPublishComment( data );
        }, "json" );
    },
    fbFriends: function() {
        // chainable?
        jQuery('#spinner').show();
        jQuery('#fb_friend_finder').load( '/?op=fb&action=fbFriends' );
    },
*/
    fbPublishComment: function( data ) {
        // still have to eval this json content.. even though it's a raw obj.. not sure why it's wrapped in 'content')
        data = eval( "(" + data.content + ")" );
        
        try{
            FB.Connect.showFeedDialog(data.bundle, data.template);
        } catch( e ) { 
//          console.log("ERROR!");
//          console.log( e );
        }
    },
    fbLogout: function() {
        FB.Connect.logout( function() { window.location = '/join/slogout'; });
    },
    fbAskForMail: function() {
        FB.Connect.showPermissionDialog('email');
    },
    fbAskForUpdate: function() {
        FB.Connect.showPermissionDialog('status_update');
    },
    fbAskForOffline: function() {
        FB.Connect.showPermissionDialog('offline_access');
    }
});

function redrawFBML()
{
    // only needed if delivering via ajax
    FB.Bootstrap.requireFeatures(["XFBML"], function() {
        FB.XFBML.Host.parseDomTree();
    });
}

function popupFbInvite(title, actionpost, type, content, actiontext, reference, invitation) {
    FB.ensureInit(function() {
	 	FB.Connect.requireSession(function() {
			var _de = document.createElement("div");
		    var _df = new FB.UI.PopupDialog(title, _de, false, false);
    		var fbml = '<fb:request-form action="http://sclipo.com/'+actionpost+'" method="POST" invite="' + invitation + '" type="'+type+'" content="'+content+'">' +
					   '<input id="reference" type="hidden" fb_protected="true" value="' + reference + '" name="reference" />'+	
					   '<fb:multi-friend-selector class="mfs" email_invite="false" rows="3" bypass="cancel" showborder="true" actiontext="'+actiontext+'" />';
		    _de.setAttribute("fbml", fbml);
	    	_df.setContentWidth(760);
		    _df.set_placement(FB.UI.PopupPlacement.topCenter);
    		_df.show();
	    	FB_RequireFeatures(["XFBML"], function() {
	    		var _e0 = new FB.XFBML.ServerFbml(_de);
		        FB.XFBML.Host.addElement(_e0);
    		});
	 	});
	});
}


