/*
	
	Created for FOG Media
	by Marc Qualie
	
	@requires		mootools-core-1.2.4.js
					mootools-more-1.2.4.2.js
	
*/

var fog = {
	
	ajaxUrl		: '/request.php',			// Url where server will handle requests
	colors		: {							// Color constants for UI clean-ness
		warning: '#ffc800',
		error: '#ffc800',
		success: '#090',
		debug: '#fff',
		info: '#e5e5e5'
	},
	pingEnabled: true,						// Should we ping the server?
	pingInterval: 30000,					// How often to ping the server with presence information
	pingCount: 0,							// Increases, useful for modular calculations
	useDebug: false,						// Should debugging be enabled?
	allowCommands: true,					// Listen for key commands
	
	// Default values
	user: {},								// Object contaning logged in user info
	loggedin: 0,							// Indicates whether user is logged in
	idletime: 0,							// Idle time can be used to update user status on the server
	ajaxID: 0,								// Each ajax request gets it's unique ID
	intervals: {},							// Object containing intervals
	res: [0, 0],							// Screen resolution
	reqInProgress: 0,						// 
	ads: [],								// Ad array containing predefined ads, for later parsing
	tips: false,							//
	mouse: {x:0, y:0},						// Access mouse position without event triggering
	
	// Initialize the class
	init : function() {
		window.addEvent('resize', fog.onResize);
		window.fireEvent('resize');
		window.addEvent('switchtab', fog.onSwitchTab);
		fog.flagsInit();
		fog.adsInit();
		
		// Add Logo
		if (Browser.Plugins.Flash.version > 0) { var logo = new Swiff('/images/layout-v3/logo.swf', { id: 'logoswf', container: $('logo_con'), width: 252, height: 100, params: { allowScriptAccess: true } }); }
		
		// Mouse Events
		window.addEvent('mousemove', function(e) {
			fog.mouse = {x: e.client.x, y:e.client.y}
		});
		
		// Initialize tips
		var a = $$('a').filter( function(i) {
			if (!i.get('title') || i.tiprendered) return false;
			if (!i.get('href')) return false;
			if (i.get('href').indexOf('javascript:') === 0) return false;
			i.tiprendered = 1;
			return true;
		});
		fog.tips = new Tips(a, {
			showDelay: 10,
			offset: {x: 16, y: 16}
		});
		
		// Initialize PING
		if (fog.user.uid > 0) fog.intervals.ping = setInterval(fog.auth.ping, fog.pingInterval);
		
		fog.parse();
	},
	
	// Flags
	flags: [
		// Language, Flag, Subdomain
		['English', 'en', 'http://www.freeonlinegames.com/'],
		['Català', 'ad', 'http://ca.freeonlinegames.com/'],
		['česky', 'cz', 'http://cs.freeonlinegames.com/'],
		['Deutsh', 'de', 'http://de.freeonlinegames.com/'],
		['dansk', 'dk', 'http://dk.freeonlinegames.com/'],
		['Español', 'es', 'http://es.freeonlinegames.com/'],
		['suomi', 'fi', 'http://fi.freeonlinegames.com/'],
		['Magyar', 'hu', 'http://hu.freeonlinegames.com/'],
		['עברית', 'il', 'http://he.freeonlinegames.com/'],
		['Italiano', 'it', 'http://it.freeonlinegames.com/'],
		['Lietuvių kalba', 'lt', 'http://lt.freeonlinegames.com/'],
		['latviešu valoda', 'lv', 'http://lv.freeonlinegames.com/'],
		['Norsk bokmål', 'no', 'http://nb.freeonlinegames.com/'],
		['polski', 'pl', 'http://pl.freeonlinegames.com/'],
		['Português', 'pt', 'http://pt.freeonlinegames.com/'],
		['română', 'ro', 'http://ro.freeonlinegames.com/'],
		['русский язык', 'ru', 'http://ru.freeonlinegames.com/'],
		['العربية', 'sa', 'http://ar.freeonlinegames.com/'],
		['Türkçe', 'tr', 'http://tr.freeonlinegames.com/'],
		['中文', 'zh', 'http://zh.freeonlinegames.com/'],
		['简化字', 'zh', 'http://zh-cn.freeonlinegames.com/'],
		['Ελληνικά', 'gr', 'http://el.freeonlinegames.com/'],
		['hrvatski', 'hr', 'http://hr.freeonlinegames.com/'],
		['ქართული', 'ge', 'http://ka.freeonlinegames.com/'],
		['한국어', 'kr', 'http://ko.freeonlinegames.com/'],
		['Mакедонски', 'mk', 'http://mk.freeonlinegames.com/'],
		['‎بهاس ملايو', 'my', 'http://ms.freeonlinegames.com/'],
		['Shqip', 'al', 'http://sq.freeonlinegames.com/'],
		['svenska', 'se', 'http://sv.freeonlinegames.com/'],
		['ไทย', 'th', 'http://th.freeonlinegames.com/'],
		['Українська', 'ua', 'http://uk.freeonlinegames.com/'],
		['Tiếng Việt', 'vn', 'http://vi.freeonlinegames.com/'],
		['Nýjustu Leikir', 'is', 'http://is.freeonlinegames.com/'],
		['Les jeux derniers', 'fr', 'http://fr.freeonlinegames.com/'],
		['Последни игри', 'bg', 'http://bg.freeonlinegames.com/'],
		['Najnovšie hry', 'sk', 'http://sk.freeonlinegames.com/'],
		['Најновије игре', 'rs', 'http://sr.freeonlinegames.com/'],
		['Uusimad mängud', 'ee', 'http://et.freeonlinegames.com/'],
		['Хамгийн сүүлийн үеийн тоглоом','mn', 'http://mn.freeonlinegames.com/'],
		['Mga Bagong Laro', 'ph', 'http://tl.freeonlinegames.com/']
	],
	flagsInit : function() {
		/*
		fog.flags.each(function(f, i) {
			$('flags').appendChild(new Element('li', {
				id: 'flag'+i,
				html: "<a href='"+f[2]+"' title='"+f[0]+"'>"+f[1]+"</a>"
			}) );
		});
		$('flags').appendChild(new Element('div', {'class':'cl'}) );
		*/
		window.addEvent('load', fog.flagsLoad);
	},
	flagsLoad: function() {
		fog.flags.each(function(f, i) {
			if ($('flag'+i))
				if ($('flag'+i).getChildren()[0])
					$('flag'+i).getChildren()[0].innerHTML = "<img src='/images/lang/"+f[1]+".png'/>";
		});
	},
	
	// Dynamic Advertising
	adsInit: function() {
		fog.ads.each(function(a) {
			fog.debug('Render AD '+a, fog.colors.success);
			$('ad_content_'+a).set('html', '').appendChild($('ad_rendered_'+a).setStyle('display', 'block'));
		});
	},
	
	// Parse tags
	parse : function() {
		fog.popup.parse();
		fog.tabs.parse();
		
		for (var i in fog.reqHistory) {
			if (!fog.reqHistory[i].container) continue;
			if (typeof(fog.reqHistory[i].container) != 'string') continue;
			if ($(fog.reqHistory[i].container).innerHTML.indexOf('<fb:') > -1 && !fog.reqHistory[i].parsed) {
				fog.plugins.facebook.renderXFBML(fog.reqHistory[i].container);
				fog.reqHistory[i].parsed = 1;
			}
		}
		
		if (fog.tips) {
			var a = $$('a').filter( function(i) {
				if (!i.get('title') || i.tiprendered) return false;
				if (!i.get('href')) return false;
				if (i.get('href').indexOf('javascript:') === 0) return false;
				i.tiprendered = 1;
				return true;
			});
			fog.tips.attach(a);
		}
		
		// Input fixing
		$$('input', 'textarea').each( function(i) {
			var o = new OverText(i);
		});
	},
	
	// Authentication
	auth : {
		login : function(user, pass, rdiv) {
			fog.request('user.login', 'verify=1&user=' + user + '&pass=' + pass, (rdiv ? rdiv : 'login-response'));
		},
		loginPopup : function() {
			fog.popup.show('User Login', 'user.login', 'showform=1', 275);
		},
		signup : function(user, email, pass, pass2, terms) {
			fog.request('user.signup', 'username=' + user + '&email=' + email + '&password=' + pass + '&password_confirm=' + pass2 + '&accept_terms=' + terms, 'login-response');
		},
		ping : function() {
			if (!fog.pingEnabled) return;
			fog.pingCount ++;
			fog.request('user.ping', 'c=' + fog.pingCount + '&idletime=' + fog.ideltime);
		}
	},
	
	// Member functions
	members : {
		isTweening : false,
		timer : false,
		toggle : function(btnId) {
			//if (fog.members.isTweening == 1) return;
			var btn = $(btnId + '-btn');
			var btns = ['login', 'signup', 'connect'];
			clearTimeout(fog.members.timer);
			btns.each(function(bId) {
				var b = $(bId + '-box');
				if (b.hasClass('open') && btnId != bId) {
					fog.members.btnClose(bId);
					fog.members.timer = setTimeout("fog.members.btnOpen('" + btnId + "');", 600);
					//return;
				}
			});
			if (btn.hasClass('open')) {
				fog.members.btnClose(btnId);
			} else {
				fog.members.btnOpen(btnId);
			}
		},
		btnOpen : function(btnId) {
			fog.members.isTweening = 1;
			$(btnId + '-box').tween('height', $(btnId + '-box').scrollHeight + 'px');
			$(btnId + '-box').addClass('open');
			$(btnId + '-btn').addClass('open');
			setTimeout("fog.members.isTweening = 0", 500);
		},
		btnClose : function(btnId) {
			fog.members.isTweening = 1;
			$(btnId + '-box').tween('height', '0px');
			$(btnId + '-box').removeClass('open');
			$(btnId + '-btn').removeClass('open');
			setTimeout("fog.members.isTweening = 0", 500);
		}
	},
	
	// Request Class - BETA v1.0.1
	req : {},
	reqHistory : {},
	request : function(method, data, container) {
		fog.ajaxID += 1;
		var ajaxid = fog.ajaxID;
		if ($('popup_loading') && container == fog.popup.PopupContentID) { fog.reqInProgress ++; $('popup_loading').style.display = 'block'; }
		fog.latency.data[ajaxid] = { id: ajaxid, start: new Date().getTime(), method: method }
		fog.reqHistory[ajaxid] = {
			'method': method,
			'data': data,
			'container': container
		}
		var url = fog.ajaxUrl + '?method=' + method + '&ajaxid=' + ajaxid + (typeof (container) == 'string' ? '&ajaxcontainer=' + container : '') + '&nocache=' + Math.round(Math.random() * 100000);
		if (typeof(container) == 'object') {
				fog.req[fog.ajaxID] = new Request({
				url			: url,
				method		: 'post',
				evalScripts	: true,
				onComplete	: (function() { container.onSuccess(); if ($('popup_loading') && container == fog.popup.PopupContentID) { fog.reqInProgress --; if (fog.reqInProgress < 1) $('popup_loading').style.display = 'none'; } fog.latency.data[this].end = new Date().getTime(); fog.latency.update(); setTimeout(fog.parse, 100) }).bind(ajaxid),
				onFailure	: function(xhr) { container.onFailure(); fog.debug('XHR Error: ' + xhr.status, fog.colors.error); }
			}).send(data);
			fog.debug('Request: ' + method, fog.colors.info);
		} else if (container) {
			fog.req[fog.ajaxID] = new Request.HTML({
				url			: url,
				method		: 'post',
				update		: $(container),
				evalScripts	: true,
				onComplete	: (function() { if ($('popup_loading') && container == fog.popup.PopupContentID) { fog.reqInProgress --; if (fog.reqInProgress < 1) $('popup_loading').style.display = 'none'; } fog.latency.data[this].end = new Date().getTime(); fog.latency.update(); setTimeout(fog.parse, 100) }).bind(ajaxid),
				onFailure	: function(xhr) { fog.debug('XHR Error: ' + xhr.status, fog.colors.error); }
			}).send(data);
			fog.debug('HTML Request: ' + method, fog.colors.info);
		} else {
			fog.req[fog.ajaxID] = new Request({
				url			: url,
				method		: 'post',
				onComplete	: (function() { fog.latency.data[this].end = new Date().getTime(); fog.latency.update(); setTimeout(fog.parse, 100) }).bind(ajaxid),
				onSuccess	: function(text) { eval(text); },
				onFailure	: function(xhr) { fog.debug('XHR Error: ' + xhr.status, fog.colors.error); }
			}).send(data);
			fog.debug('JSON Request: ' + method, fog.colors.info);
		}
	},
	
	// Popup
	popup : {
		PopupContentID		: "popup_content_div",
		show : function(pu_title, pu_page, pu_data, pu_width) {
			if (!fog.popup.PopupBack) fog.popup.create();
			$$('object', 'embed', 'iframe').each( function(o) { if (o.id != 'logoswf') o.style.visibility = 'hidden'; });
			$$($(fog.popup.PopupContentID).getElements('iframe')).each( function(o) { o.style.visibility = 'visible'; });
			// Once effects have started show layers
			fog.popup.PopupBack.style.display = "block";
			fog.popup.PopupWrap.style.visibility = 'hidden';
			fog.popup.PopupWrap.style.display = 'block';
			// Defaults
			if (!pu_width) pu_width = 500;
			// Increase size to add special effects
			if (pu_width == "100%") {
				fog.popup.PopupWrap.style.minWidth = (fog.popup.WindowSize[0] - 20) + "px";
				//fog.popup.PopupWrap.style.height = (fog.popup.WindowSize[1] - 400) + "px";
				fog.popup.PopupWrap.style.height = (fog.popup.PopupBack.clientHeight - 20) + "px";
				fog.popup.PopupContent.style.height = (fog.popup.PopupBack.clientHeight - 70) + "px";
			} else {
				fog.popup.PopupWrap.style.width = pu_width + "px";		
			}
			// Set text
			if (pu_page != fog.popup.pageLast) fog.popup.PopupContent.innerHTML = "loading..";
			if (pu_page != "this-text") fog.request(pu_page, "post_back_id="+fog.popup.PopupContentID+"&"+pu_data, fog.popup.PopupContentID);
			if (pu_page == "this-text") fog.popup.PopupContent.innerHTML = pu_data;
			if (pu_title) fog.popup.PopupTitle.innerHTML = pu_title;
			pu_width_last = pu_width;
			fog.popup.pageLast = pu_page;
			setTimeout("fog.popup.PopupWrap.style.visibility = 'visible';", 300);
		},
		parse : function() {
			if (!fog.popup.PopupBack) return;
			if (fog.popup.PopupBack.style.display == 'none') return;
			fog.popup.PopupWrap.style.marginTop = ((fog.res[1] / 2) - (fog.popup.PopupWrap.clientHeight / 2)) + "px";
			if (pu_width_last == "100%") {
				fog.popup.PopupWrap.style.minWidth = (fog.res[0] - 20) + "px";
				fog.popup.PopupWrap.style.height = (fog.popup.PopupBack.clientHeight - 20) + "px";
				fog.popup.PopupContent.style.height = (fog.popup.PopupBack.clientHeight - 70) + "px";
			} else {
				fog.popup.PopupContent.style.maxHeight = (fog.popup.PopupBack.clientHeight - 90) + "px";
			}
		},
		close : function() {
			fog.popup.PopupBack.style.display = "none";
			fog.popup.PopupWrap.style.display = "none";
			fog.popup.PopupContent.style.height = "auto";
			fog.popup.PopupWrap.style.height = "auto";
			pu_width_last = "";
			fog.popup.pageLast = "";
			$$('object', 'embed', 'iframe').each( function(o) { if (o.id != 'logoswf') o.style.visibility = 'visible'; });
		},
		isopen : function() {
			if (!fog.popup.PopupBack) return false;
			return fog.popup.PopupBack.style.display == 'block' ? true : false;
		},
		create : function() {
			fog.popup.PopupBack = new Element('div', {
				'class': 'mq_popup back'
			});
			fog.popup.PopupWrap = new Element('div', {
				'id': 'mq_popup-wrap',
				'class': 'mq_popup wrap'
			});
			fog.popup.PopupHold = new Element('div', {
				'class': 'mq_popup hold'
			});
			fog.popup.PopupClose = new Element('a', {
				'class': 'mq_popup close',
				'href': 'javascript:void(0)',
				'events': {
					'click': function() { fog.popup.close(); }
				}
			});
			fog.popup.PopupLoading = new Element('div', {
				'id': 'popup_loading',
				'class': 'mq_popup loading'
			});
			fog.popup.PopupTitle = new Element('div', {
				'class': 'mq_popup title',
				'id': fog.popup.PopupContentID + "_title"
			});
			fog.popup.PopupContent = new Element('div', {
				'id': fog.popup.PopupContentID,
				'class': 'mq_popup content'
			});
			// Create Stucture
			fog.popup.PopupBack.appendChild(fog.popup.PopupWrap);
			fog.popup.PopupWrap.appendChild(fog.popup.PopupHold);
			fog.popup.PopupHold.appendChild(fog.popup.PopupClose);
			fog.popup.PopupHold.appendChild(fog.popup.PopupLoading);
			fog.popup.PopupHold.appendChild(fog.popup.PopupTitle);
			fog.popup.PopupHold.appendChild(fog.popup.PopupContent);
			$(document.body).appendChild(fog.popup.PopupBack);
			
			setInterval(fog.popup.parse, 100);
		}
	},
	
	// Tabs
	tabs : {
		select : function(i) {
			var t = $(i + '-tab');
			t.getParent().getElements('li').each(function(l) {
				var c = $(l.id.replace('-tab', '-con'));
				if (l.id == t.id) {
					l.addClass('sl');
					if (c) c.addClass('sl');
				} else {
					l.removeClass('sl');
					if (c) c.removeClass('sl');
				}
			});
			fog.parse();
		},
		parse : function() {
			$$('.tabs li').each(function(t) {
				if (!t.hasClass('parsed')) {
					if (t.id) {
						var f = (function() { fog.tabs.select(this.id.replace('-tab', '')); }).bind(t);
						t.addEvent('click', f);
					}
					t.addClass('parsed');
				}
			});
			$$('input', 'textarea').each(function(i) {
				i.addEvent('focus', function() { fog.allowCommands = false; });
				i.addEvent('blur', function() { fog.allowCommands = true; });
			});
		}
	},
	
	// Random functions
	submitRating : function(g, r) {
		$('howtovote').setStyle('display', 'none');
		$('sendingvote').setStyle('display', 'inline');
		fog.request('game.rate', 'g='+g+'&r='+r, {
			onSuccess: function() {
				$('sendingvote').setStyle('display', 'none');
				$('sentvote').setStyle('display', 'inline');
			},
			onFailure: function(xhr) {
				$('sendingvote').setStyle('display', 'none');
				$('sentvote').setStyle('display', 'inline');
				$('sentvote').innerHTML = 'Error: ' + xhr.status;
			}
		});
		return false;
	},
	showGame : function() {
		$('adaptvDiv').setStyle('display', 'none');
		$('custom').setStyle('display', 'block');
		fog.adjustGame();
	},
	adjustGame : function() {
		$('gameBlankHolder').setStyle('height', $('absoluteContainer').clientHeight);
	},
	
	// Event initiated functions
	onResize : function() {
		fog.res = window.innerHeight ? [window.innerWidth, window.innerHeight] : [document.body.offsetWidth, document.body.offsetHeight];
		fog.popup.parse();
	},
	onSwitchTab : function() {
		
	},
	
	// Debugging
	debug : function(text, color) {
		var d = $('fog-debug');
		if (!d) {
			var d = new Element('div', {
				'id' : 'fog-debug',
				'styles' : {
					'display' : 'none',
					'position' : 'fixed',
					'background' : 'url(/images/layout-v3/trans.png) repeat 0px 0px',
					'top' : '5px',
					'right' : '5px',
					'border' : '1px solid #000',
					'outline' : '1px solid #fff',
					'padding' : '3px',
					'color' : '#fff',
					'font-family' : 'Courier',
					'font-size' : '10px',
					'line-height' : '15px',
					'z-index' : 99999,
					'width' : '200px',
					//'opacity' : 0.9,
					'max-height' : '300px',
					'overflow-y' : 'auto'
				}
			});
			document.body.appendChild(d);
		}
		if (text) {
			var l = new Element('div', {
				'styles' : {
					'color' : (color ? color : fog.colors.debug)
				},
				'html' : text
			});
			d.appendChild(l);
		}
		d.style.display = fog.useDebug ? 'block' : 'none';
		d.scrollTop = d.scrollHeight;
	},
	latency : {
		range : {min: 0, max: 0},
		data : {},
		show : function() {
			var d = $('latency-column');
			if (!d) {
				var d = new Element('div', {
					'id' : 'latency-column',
					'styles' : {
						'display' : 'block',
						'position' : 'fixed',
						'background' : 'url(/images/layout-v3/trans.png) repeat 0px 0px',
						'top' : '0px',
						'left' : '0px',
						//'border' : '1px solid #000',
						//'outline' : '1px solid #fff',
						//'padding' : '3px',
						//'color' : '#fff',
						//'font-family' : 'Courier',
						'font-size' : '8px',
						'line-height' : '10px',
						'z-index' : 99999,
						'width' : '160px',
						//'opacity' : 0.9,
						'height' : '100%',
						'overflow' : 'hidden'
					}
				});
				document.body.appendChild(d);
					var l = new Element('div', {
					'id' : 'latency-col-' + i,
					'styles' : {
						//'width' : (fog.latency.data[i].total / 8),
						'height' : '20px',
						'background': '#fff',
						'margin': '4px 0px 4px 0px'
					},
					'html' : 'Max: <span id=\'latencyMax\'>0</span><br/>Min: <span id=\'latencyMin\'>0</span>'
				});
				d.appendChild(l);
				d.appendChild(new Element('div'));
			}
			for (var i in fog.latency.data) {
				if (!$('latency-col-' + i) && fog.latency.data[i].end > 0) {
					fog.latency.data[i].total = fog.latency.data[i].end - fog.latency.data[i].start;
					var l = new Element('div', {
						'id' : 'latency-col-' + i,
						'styles' : {
							'width' : (fog.latency.data[i].total / 8),
							'height' : '10px',
							'background': (fog.latency.data[i].total < 300 ? '#0f0' : (fog.latency.data[i].total > 600 ? '#f00' : (fog.latency.data[i].total ? '#ffc800' : '#ccc'))),
							'margin': '0px 0px 0px 0px'
						},
						'html' : (fog.latency.data[i].total + "<div style='position:absolute;top:0px;left:0px;width:160px;text-align:right;color:#fff'>" + fog.latency.data[i].method + "</div>")
					});
					if (fog.latency.data[i].total > fog.latency.range.max) fog.latency.range.max = fog.latency.data[i].total;
					if (fog.latency.data[i].total < fog.latency.range.min || fog.latency.range.min == 0) fog.latency.range.min = fog.latency.data[i].total;
					d.insertBefore(l, d.getChildren()[1]);
				}
			}
			$('latencyMax').innerHTML = fog.latency.range.max;
			$('latencyMin').innerHTML = fog.latency.range.min;
			//d.scrollTop = d.scrollHeight;
			Cookie.write('latencyon', '1');
		},
		update : function() {
			if ($('latency-column')) fog.latency.show();
		},
		hide : function() {
			document.body.removeChild($('latency-column'));
			Cookie.dispose('latencyon');
		}
	},
	latencyInit : ( function() { window.addEvent('domready', function() { if (Cookie.read('latencyon')) { fog.latency.show(); } }); } )(),
	
	// Plugins
	plugins : {
		scoreplug : {
			gameid : 0,
			gamefile: '',
			gamewidth: 0,
			gameheight: 0,
			partnerid : 0,
			highscore : 0,
			render : function() {
				var swiff = new Swiff("http://www.scoreplug.com/partnerAPI/connector/connector_fog.swf", {
					id: "connectorContainer",
					container: "connectorContainerDiv",
					width: 1,
					height: 1,
					params: {
						allowScriptAccess:"always",
						scale: "noscale"
					},
					vars: {
						gameId: fog.plugins.scoreplug.gameid,
						partnerId: fog.plugins.scoreplug.partnerid,
						userId: fog.user.uid,
						userName: fog.user.username,
						userAvatar: fog.user.avatar
					}
				});
				connector = swiff.object;
				swiff = new Swiff("/labs/scoreplug/swf/scorePlugModules/PartnerProjectEN_FOG_branded.swf", {
					id: "scoreboardContainer",
					container: "scoreboardContainerDiv",
					width: 300,
					height: 350,
					params: {
						allowScriptAccess:"always",
						scale: "exactFit"
					},
					vars: {
						isSignInUser: (fog.user.uid > 0 ? 1 : 0)
					}
				});
				scoreboard = swiff.object;
				if (fog.plugins.scoreplug.asversion == 2) {
					swiff = new Swiff(fog.plugins.scoreplug.gamefile, {
						id: "gameContainer",
						container: "gameContainerDiv",
						width: fog.plugins.scoreplug.gamewidth,
						height: fog.plugins.scoreplug.gameheight,
						params: {
							allowScriptAccess:"always",
							scale: "scale",
							wMode: "opaque"
						},
						vars: {}
					});
				} else {
					/*
					att = { data:'swf/scorePlugModules/container.swf', width:'700', height:'600' };
					par = {	scale:'scale', salign:'lt' ,allowScriptAccess:'always',flashvars:'gamePath=games/as3/764.swf'};
					id = 'gameContainer';
					game = swfobject.createSWF(att, par, id);
					*/
					swiff = new Swiff('/labs/scoreplug/swf/scorePlugModules/container.swf', {
						id: "gameContainer",
						container: "gameContainerDiv",
						width: fog.plugins.scoreplug.gamewidth,
						height: fog.plugins.scoreplug.gameheight,
						params: {
							allowScriptAccess: "always",
							scale: "scale",
							wMode: "opaque",
							salign: "lt"
						},
						vars: {
							gamePath: fog.plugins.scoreplug.gamefile
						}
					});
				}
				game = swiff.object;
			},
			updateScore : function(gameId, userId, curScore) {
				fog.debug('Score: ' + gameId + ', ' + userId + ', ' + curScore, fog.colors.warning);
				if (curScore > fog.plugins.scoreplug.highscore) {
					fog.plugins.scoreplug.highscore = curScore;
					fog.request('scores.update', 's='+curScore+'&u='+userId+'&g='+gameId);
				}
			}
		},
		
		/* Facebook connect shortcuts */
		facebook : {
			fogConnectURL : 'http://'+location.hostname+'/connect/?utm_source=facebook.com&utm_medium=stream',
			renderXFBML : function(obj) {
				FB.ensureInit( (function() {
					FB.XFBML.Host.parseDomElement($(this));
				}).bind(obj) );
			},
			onlogin : function() {
				fog.popup.show('Facebook Settings', 'settings.edit', 's=facebook');
			},
			inviteFriends : function() {
				fog.popup.show('Invite Facebook Friends', 'facebook.invite', '', '790');
				/*
				return;
				FB.Connect.streamPublish(
					'',
					{
						'name': 'FOG Connect',
						'description': "FOG Connect has over 3,000 games for you and your friends to play against, compete for high scores of simply share all your favorites easily",
						'media': [
							{'type':'image', 'src':'http://'+location.hostname+fog.user.avatar, 'href':fog.plugins.facebook.fogConnectURL}
						]
					},
					null,
					null,
					'Invite your friends to join you on FOG',
					fog.plugins.inviteFriendsCallback
				);
				*/
			},
			inviteFriendsCallback : function(post_id, exception) {
				
			},
			shareScores : function(sa) {
				var sc = new Object();
				for (var i = 0; i < sa.length; i++) {
					sc[sa[i].name] = {
						'href': fog.plugins.facebook.fogConnectURL,
						'text': sa[i].score + ' points'
					}
				}
				FB.Connect.streamPublish(
					'',
					{
						'name': 'FOG Connect',
						'caption': "Why don't you see if you can beat my scores?",
						'properties': sc,
						'media': [
							{'type':'image', 'src':'http://'+location.hostname+fog.user.avatar, 'href':fog.plugins.facebook.fogConnectURL}
						]
					},
					[
						{'text': 'Join FOG Connect', 'href': fog.plugins.facebook.fogConnectURL}
					],
					null,
					'Invite your friends to join you on FOG',
					fog.plugins.inviteFriendsCallback
				);
			}
		}
	}
}

// Older FOG Functions - included for compatibility
function submitRating(g, r) {
	fog.debug('Depreciated function: submitRating()', fog.colors.error);
	return false;
}
function showGame() {
	fog.debug('Depreciated function: showGame()', fog.colors.error);
	fog.showGame();
}

// Score Plug API
function UpdateScore(gameId, userId, curScore) { fog.plugins.scoreplug.updateScore(gameId, userId, curScore); }
function showUser(userId) { fog.debug('showUser: ' + userId); fog.popup.show('User Profile', 'user.profile', 'uid='+userId); }
function loginPopup() { fog.debug('loginPopup: ' + userId); fog.auth.loginPopup(); }

// Development Shortcuts
var ksq = '';
var ksa = [
	{k:'togglesocial', f: function() { fog.popup.show('Dev', 'dev.toggle', '', '65'); } },
	{k:'closepopup', f: function() { fog.popup.close(); } },
	{k:'showstats', f: function() { fog.popup.show('Statistics', 'stats.show', '', '600'); } },
	{k:'debugon', f: function() { fog.useDebug = true; fog.debug('', fog.colors.success); } },
	{k:'debugoff', f: function() { fog.useDebug = false; fog.debug('', fog.colors.error); } },
	{k:'latencyon', f: function() { fog.latency.show(); } },
	{k:'latencyoff', f: function() { fog.latency.hide(); } },
	{k:'feedback', f: function() { fog.popup.show('Feedback', 'dev.feedback', '', '300'); } },
	{k:'changecountry', f: function() { fog.popup.show('Country', 'this-text', "<form action='http://www0.freeonlinegames.com/fogadm/setcountry.php' method='get'><input type='text' name='cc' value='"+Cookie.read('fog-country')+"' style='width:42px'/><input type='submit' value='SET' style='width:42px'/></form>", '100'); } },
	{k:'devcompress', f: function() { fog.popup.show('Compress Images', 'dev.compress', 's=images', '600'); } }
];
document.addEvent('keydown', function(e) {
	if (!fog.allowCommands) return;
	ksq += e.key;
	for (var i = 0; i < ksa.length; i++) {
		if (ksq.length > 20) ksq = ksq.substr(ksq.length - 20, 20);
		if (ksq.substr(ksq.length - ksa[i].k.length, ksa[i].k.length) == ksa[i].k) ksa[i].f();
	}
});

