jQuery.noConflict(); // this is here so jQuery will play nicely with prototype

if (typeof GGE == "undefined" || !GGE) { var GGE = {} }

GGE.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=(""+a[i]).split(".");
        o=GGE;

        for (j=(d[0] == "GGE") ? 1 : 0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    
    return o;
};

GGE.env = (function(){
	// Thanks to yahoo UI toolkit for detect functionality
	var _detect = function(){
		var ua = navigator.userAgent,
    	m,
    	o = {};

	    // Modern KHTML browsers should qualify as Safari X-Grade
    	if ((/KHTML/).test(ua)) {
       		o.webkit=1;
	    }
	    // Modern WebKit browsers are at least X-Grade
	    m=ua.match(/AppleWebKit\/([^\s]*)/);
	    if (m&&m[1]) {
	        o.webkit=parseFloat(m[1]);
	
	        // Mobile browser check
	        if (/ Mobile\//.test(ua)) {
	            o.mobile = "Apple"; // iPhone or iPod Touch
	        } else {
	            m=ua.match(/NokiaN[^\/]*/);
	            if (m) {
	                o.mobile = m[0]; // Nokia N-series, ex: NokiaN95
	            }
	        }
	
	        m=ua.match(/AdobeAIR\/([^\s]*)/);
	        if (m) {
	            o.air = m[0]; // Adobe AIR 1.0 or better
	        }
	
	    }
	
	    if (!o.webkit) { // not webkit
	        // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
	        m=ua.match(/Opera[\s\/]([^\s]*)/);
	        if (m&&m[1]) {
	            o.opera=parseFloat(m[1]);
	            m=ua.match(/Opera Mini[^;]*/);
	            if (m) {
	                o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
	            }
	        } else { // not opera or webkit
	            m=ua.match(/MSIE\s([^;]*)/);
	            if (m&&m[1]) {
	                o.ie=parseFloat(m[1]);
	            } else { // not opera, webkit, or ie
	                m=ua.match(/Gecko\/([^\s]*)/);
	                if (m) {
	                    o.gecko=1; // Gecko detected, look for revision
	                    m=ua.match(/rv:([^\s\)]*)/);
	                    if (m&&m[1]) {
	                        o.gecko=parseFloat(m[1]);
	                    }
	                }
	            }				
	        }
	    }
	
	    m=ua.match(/Caja\/([^\s]*)/);
	    if (m&&m[1]) {
	        o.caja=parseFloat(m[1]);
	    }
	    
	    return o;
	}
	return{
		construct: function(){
			this.values.agent = _detect();
		},
		
		values: {
			agent: null
		}
	}
})();

GGE.log = function(msg){
	//console.log(msg);
}

GGE.publish = function(){
	var platforms = [];
	return {
		addPlatform: function(platform){
			platforms.push(platform);
		},
		// 
		// Do method, sensitive to platforms established
		doAction: function(type,do_platforms,data){
			var type_method = 'publish' + type.slice(0,1).toUpperCase() + type.slice(1);
			
			for(var i=0; i < do_platforms.length; i++){
				GGE[do_platforms[i]][type_method].call('',data);
			}
		}
	}
}();

GGE.init = (function(){
	return{
		config: function(){
			GGE.FBConnect.construct();
		}
	}
})();

// dynamically load javascript files
GGE.load = (function(){
	var init_libraries = [
		{'lib':'config','callback':GGE.init.config}
	]; // initial libraries
		
	var queue = [];
	
    var _enqueue = function(file,callback) {
    	var js_rev = '1';
        var url = '/js/'+js_rev+'/'+file+'.js';
        
        callback = callback || function(){};
        
        queue.push( {
            'type':    "text/javascript",
            'src':     url,
            'callback': callback
        } );
    }

	// method to dynamically load javascript file
	var _include = function(lib) {
		var head = document.getElementsByTagName('head')[0];
		var script = document.createElement('script');
		script.src = lib.src;
		script.url = lib.url;
		head.appendChild(script);

		_processCallback(script,lib);
	}
	
	var _processCallback = function(script,lib){
		if(GGE.env.values.agent.ie){ // IE
	        script.onreadystatechange = function() {
	            var rs = this.readyState;
	            if ("loaded" === rs || "complete" === rs) lib.callback.call();
	    	}
    	}
    	else if(GGE.env.values.agent.webkit){ 	// safari
	        script.addEventListener("load", function() {
	            lib.callback.call();
	        });
	    }
		else{ // firefox and opera
			script.onload = function(){
	            lib.callback.call();
			}
		}
	}
	
	return{
		
		// load initial libraries
		construct: function(){
			for(var i=0; i < init_libraries.length; i++){
				_enqueue(init_libraries[i].lib,init_libraries[i].callback);
			}
			this.processQueue();
		},
		
		processQueue: function(){
			for(lib in queue){
				if(queue.hasOwnProperty(lib))
					_include(queue[lib]);
			}
		}
	}
	
})();

GGE.AdManager = (function(){
	return{
		construct: function(){
//			GA_googleAddSlot("ca-pub-0600361198168652", "GGE-Game-Profile-Pre-Tabs");
			//GA_googleAddSlot("ca-pub-0600361198168652", "GGE-Game-Profile-Sidebar-Top");
			
			jQuery('iframe.ad_placement').each(function(){
				
				//jQuery(this).html('<script language="JavaScript">GA_googleFillSlot('+'this.id'+');</script>');
				GA_googleAddSlot("ca-pub-0600361198168652", this.id);
			//	GA_googleFillSlot(this.id);
			})
			
			GA_googleFetchAds();
			
			jQuery('iframe.ad_placement').each(function(){
				jQuery(this).html('<script type="text/javascript">GA_googleFillSlot("GGE-Game-Profile-Pre-Tabs");</script>');
				//console.log(jQuery('iframe#ad_code'));
				//jQuery(this).html('<script type="text/javascript">GA_googleFillSlot("GGE-Game-Profile-Pre-Tabs");</script>');
				//jQuery(this).
				//GA_googleFillSlot(this.id);
			})
		}
	}
})();

// Facebook Connect class
GGE.FBConnect = (function(){
	var template_data;
	
	return {
		construct: function(){
			jQuery('a#fblogin').click(GGE.FBConnect.triggerLogin); // used by site login
			jQuery('a#fbconnect').click(GGE.FBConnect.connectAccount); // used by account linking process
			jQuery('a#sitelogout').click(GGE.FBConnect.logout);// logout
			FB.init(GGE.config.api_key, "/xd_receiver.htm"); 
			FB.ensureInit(function() {
				
			});
		},
		
		triggerLogin: function(){
			FB.ensureInit(function() {
				FB.Connect.requireSession(function(){
					window.location = '/facebook/register/';
				});
			});
			return false;
		},
		
		connectAccount: function(){
			FB.ensureInit(function() {
				FB.Connect.requireSession(function(){
					var extra_url = jQuery('#fbconnect_auto_friend:checked').length == 1 ? 'friends' : ''
					window.location = '/account/facebook/connect/'+extra_url;
				});
			});
			return false;			
		},
		
		logout: function(){
			FB.Connect.logout(function(){window.location='/logout/'});
			return false;
		},
		
		sessionEstablished: function(){
			
		},
		
		loginThen: function(callback){
			FB.ensureInit(function() {
				FB.Connect.requireSession(function(){
					callback.call();
				});
			});
		},
		
		displayPublishForm: function(display_func){
			FB_RequireFeatures(["XFBML","CanvasUtil"], function(){
				FB.Facebook.init(GGE.config.api_key, "/xd_receiver.htm");
				FB.Connect.ifUserConnected(GGE.FBConnect['show'+display_func+'Form'], function(){GGE.FBConnect.loginThen(GGE.FBConnect['show'+display_func+'Form'])});
			});			
		},

		publishReview: function(data){
			template_data = {
				"title":data.title,
				"game_url":data.game_url,
				"review_url":data.review_url,
				"bottom_line":data.bottom_line,
				"body":data.body,
				"rating":data.rating,
				"images":data.images.slice(0,5)
			}; 
			
			GGE.FBConnect.displayPublishForm('Review');
		},
		
		showReviewForm: function(data){
			FB.Connect.showFeedDialog(GGE.config.review_bundle, template_data, [], '', null, FB.RequireConnect.require);
		},
	
		publishGamelist: function(data){
			var games_array = [];
			for(var i=0; i < data.games.length; i++){
				games_array.push('<a href=\''+data.games[i].link+'\'>'+encodeURI(data.games[i].title)+'</a>');
			}
			
			template_data = {
				"title":data.title,
				"list_url":data.list_url,
				"description":data.description,
				"images":data.images.slice(0,5),
				"games":games_array.join(', ').replace(/\%20/g,' ')
			}; 
			
			GGE.FBConnect.displayPublishForm('Gamelist');
		},
		
		showGamelistForm: function(){
			FB.Connect.showFeedDialog(GGE.config.gamelist_bundle, template_data, [], '', null, FB.RequireConnect.require);			
		},
	
		publishGame: function(data){
			
			template_data = {
				"title":data.title,
				"link":data.link,
				"description":data.description,
				"images":data.images
			};
			
			GGE.FBConnect.displayPublishForm('Game');
		},
	
		showGameForm: function(){
			FB.Connect.showFeedDialog(GGE.config.game_bundle, template_data, [], '', null, FB.RequireConnect.require);
		}
	}
})();

jQuery(document).ready(function(){
	GGE.env.construct();
	GGE.load.construct();
//	GGE.AdManager.construct();
});

