/**
 * Variables initilisation
 */
var url = document.location.pathname;
var dmn = document.domain.replace( 'www.', '' );
var tmr = setInterval( loadReadyState, 20 );

var fvs = new Array( 0 );		// array of favorite games
var rct = new Array( 0 );		// array of recent played games
var pdt = new Array( 0 );		// page data

var dbg = false;					// display debug output
var ini = false;				// initialised or not
var rdy = false;				// DOM is ready for Flash

var itm = '';
var tag = '';					// tag of the game
var ttl = '';					// title of the game
var gwd	= '';					// game width
var ght	= '';					// game height
var gml = '';					// game left margin
var unm = '';					// username

var gbr = 0;					// width of the border around the game
var wht = 0;					// height of current window
var srt = 1;					// game sort method
var opc = 0;					// opacity
var png = 0;					// ping timer
var htm = 0;					// highlight timer
var cdt	= 0;					// comment id to edit
var hss = 0;					// highscore system
var gid = false;				// gameid
var uid = false;				// userid
var unm = false;				// username
var sid = false;				// sessionid

window.onload = setReady;


/**
 * Break out of iframes
 */
if (parent.frames.length > 0)
{
	top.location.replace(document.location);
}


/**
 * Enable IE background image cache for rating hovers
 */
try
{
	document.execCommand("BackgroundImageCache", false, true);
}
catch(err)
{
}


/**
 * Call init after cache hit in Firefox
 */
window.onpageshow = function ( evt )
{
	if ( evt.persisted ) init();
};


/**
 * Execute init function if page is loaded far enough
 */
function loadReadyState()
{
	if ( document.getElementById("footer") )
	{
		clearInterval( tmr );

		if ( !ini )
		{
			ini = true;
			init();
		}
	}
}


/**
 * Page is ready for the Flash External Interface
 */
function setReady()
{
	rdy = true;
}


/**
 * Initialisation
 */
function init()
{
	cookieRead();

	// check if we are viewing a game	
	if ( gid )
	{
		preloadImages();

		tag = url.substring( url.search( dmn + '/' ), url.length );
		ttl = document.getElementById("gametitle").innerHTML;
		itm = tag + "^" + ttl;

		// if we allready have the game, remove it
		if ( rct.length > 0 )
		{
			for ( var i = 0; i < rct.length; i++ )
			{
				if (rct[i] == itm)
				{
					rct.splice(i, 1);
				}
			}
		}

		rct.unshift( itm );

		if ( rct.length > 5 )
		{
			rct.pop();
		}

		cookieWrite();

		var game = document.getElementById( 'gameobject' ).style;
		
		gwd = game.width;
		ght = game.height;
		gml	= game.marginLeft;
		gbr	= game.borderTopWidth;
		gwd = gwd.substring(0, gwd.length - 2);
		ght = ght.substring(0, ght.length - 2);
		gml = gml.substring(0, gml.length - 2);
		gbr	= parseInt(gbr.substring(0, gbr.length - 2));

		highscoreEnable();		
		switchAddToMyGames();
		switchCommentWarning();
		emoReplace();
		
		if ( uid )
		{
			png	= setTimeout( ping, 60000 );
		}
	}

	// Get the heigth of this window
	if ( typeof( window.innerWidth ) == 'number' )
	{
		wht = window.innerHeight;
	}
	else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
		//IE 6+ in 'standards compliant mode'
		wht = document.documentElement.clientHeight;
	}
	else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	{
		//IE 4 compatible
		wht = document.body.clientHeight;
	}

	// preselect the sort 
	if ( element = document.getElementById('sort') )
	{
		element.selectedIndex = srt;
	}
	
	updateSpacer();
	updateLastMyGames();
}


/**
 * Create a scaleable Flash onject
 */
function createFlashControl(file, version, width, height, resize)
{
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + version + '" width="100%" height="100%"><param name="movie" value="' + file + '"><param name="quality" value="high"><embed src="' + file + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="100%" height="100%"></embed></object>');

	if (resize) enableButton( 'zoomin', zoomIn );
}

function createShockwaveControl(file, version, width, height, parameters)
{
	var paramembed	= '';

	document.write('<object classid="clsid:166B1BCA-3F9C-11CF-8075-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=' + version + '" width="' + width + '" height="' + height + '"><param name="src" value="' + file + '">');

	if (parameters.length > 0)
	{
		var allparam = parameters.split("|");

		for(var i = 0; i < allparam.length; i++)
		{
			var param = allparam[i].split("=");
			paramembed = param[0] + '="' + param[1] + '"';
			document.write('<param name="' + param[0] + '" value="' + param[1] + '">');
		}
	}

	document.write('<param name="menu" value="false"><param name="swStretchStyle" value="fill"><param name="swRemote" value="swSaveEnabled=\'false\' swVolume=\'false\' swRestart=\'false\' swPausePlay=\'false\' swFastForward=\'false\' swContextMenu=\'false\'"><embed src="' + file + '"' + paramembed + ' swRemote="swSaveEnabled=\'true\' swVolume=\'false\' swRestart=\'false\' swPausePlay=\'false\' swFastForward=\'false\' swContextMenu=\'false\'" pluginspage="http://www.macromedia.com/shockwave/download/" width="' + width + '" height="' + height + '" swStretchStyle="fill"></embed></object>');
}


var addtoInterval = null;
var popupWin = '';

function addtoWin(addtoFullURL)
{
	if (!popupWin.closed && popupWin.location)
	{
		popupWin.location.href = addtoFullURL;
		var addtoInterval = setInterval("closeAddTo();",1000);
	}
	else
	{
		popupWin = window.open(addtoFullURL,'addtoPopUp','width=770px,height=500px,menubar=1,toolbar=1,status=1,location=1,resizable=1,scrollbars=1,left=0,top=100');
		var addtoInterval = setInterval("closeAddTo();",1000);
		if (!popupWin.opener) popupWin.opener = self;
	}
	
	if (window.focus)
	{
		popupWin.focus();
	}
	
	return false;
}

// closes the popupWin
function closeAddTo()
{
	if (!popupWin.closed && popupWin.location)
	{
		if (popupWin.location.href == AddURL)	//if it's the same url as what was bookmarked, close the win
		popupWin.close();
	}
	else
	{	//if it's closed - clear the timer
		clearInterval(addtoInterval);
		return true;
	}
}

//
function addurl(addsite)
{
	switch(addsite)
	{
		case 1:	//	Blink ID:1
			var AddSite = "http://www.blinklist.com/index.php?Action=Blink/addblink.php";
			var AddUrlVar = "url";
			var AddTitleVar = "title";
			var AddNoteVar = "description";
			var AddReturnVar = "";
			var AddOtherVars = "&Action=Blink/addblink.php";
			break;
		case 2:	//	Del.icio.us	ID:2 &v=3&noui=yes&jump=close
			var AddSite = "http://del.icio.us/post?";
			var AddUrlVar = "url";
			var AddTitleVar = "title";
			var AddNoteVar = "";
			var AddReturnVar = "";
			var AddOtherVars = "";
			break;
		case 3:	//	Digg ID:3
			var AddSite = "http://digg.com/submit?";
			var AddUrlVar = "url";
			var AddTitleVar =  "";
			var AddNoteVar =  "";
			var AddReturnVar =  "";
			var AddOtherVars = "&phase=2";
			break;
		case 4:	//	Furl ID:4
			var AddSite = "http://www.furl.net/storeIt.jsp?";
			var AddUrlVar = "u";
			var AddTitleVar = "t";
			var AddNoteVar = "";
			var AddReturnVar = "";
			var AddOtherVars = "";
			break;
		case 5:	//	GOOGLE ID:5
			var AddSite = "http://fusion.google.com/add?";
			var AddUrlVar = "feedurl";
			var AddTitleVar = "";
			var AddNoteVar = "";
			var AddReturnVar = "";
			var AddOtherVars = "";
			break;
		case 6:	//	Simpy ID:6
			var AddSite = "http://simpy.com/simpy/LinkAdd.do?";
			var AddUrlVar = "href";
			var AddTitleVar = "title";
			var AddNoteVar = "note";
			var AddReturnVar = "_doneURI";
			var AddOtherVars = "&v=6&src=bookmarklet";
			break;
		case 7:	//	Yahoo ID: 7
			var AddSite = "http://myweb2.search.yahoo.com/myresults/bookmarklet?";
			var AddUrlVar = "u";
			var AddTitleVar = "t";
			var AddNoteVar = "";
			var AddReturnVar = "";
			var AddOtherVars = "&d=&ei=UTF-8";
			break;
		case 8:	//	Spurl ID: 8 	d.selection?d.selection.createRange().text:d.getSelection()
			var AddSite = "http://www.spurl.net/spurl.php?";
			var AddUrlVar = "url";
			var AddTitleVar = "title";
			var AddNoteVar = "blocked";
			var AddReturnVar = "";
			var AddOtherVars = "&v=3";
			break;
	}
//	Build the URL
	AddURL		= document.location.href;
	AddTitle	= document.title;
	var addtoFullURL = AddSite + AddUrlVar + "=" + AddURL + "&" + AddTitleVar + "=" + AddTitle + AddOtherVars;

	if (AddNoteVar != "")
	{
		var addtoFullURL = addtoFullURL + "&" + AddNoteVar + "=" + AddTitle;
	}

	if (AddReturnVar != "")
	{
		var addtoFullURL = addtoFullURL + "&" + AddReturnVar + "=" + AddURL;
	}

	addtoWin(addtoFullURL);
	return true;
}

/**
 * Disable JavaScript errors
 *
 * Checking across domains causes errors, this is to supress these
 */
//window.onerror = handleError;

function handleError()
{
	return true;
}


/**
 * Bookmarking (IE only)
 */
function addToFavorites()
{
	var title	= document.title;
	var url		= document.location.href;

	if ( navigator.appName == 'Microsoft Internet Explorer')
	{
		window.external.AddFavorite(url, title);
	}
	else
	{
		alert('Sorry, this function doesn\'t work in this browser.\nPlease bookmark this site manually.');
	}
}


/**
 * Obfuscate email address to prevent spam
 */
function insertEmail()
{
  document.write("<a href=" + "ma" + "il" + "to:" + "legal" + "@" + "gamenode" + ".com" + ">" + "legal" + "@" + "gamenode" + ".com" + "</a>");
}


/**
 * Write cookies
 */
function cookieWrite()
{
	var date = new Date();
	date.setTime( date.getTime() + (31536000000) );

	document.cookie = "gn_fvs=" + escape( fvs.join("|") ) + "; expires=" + date.toGMTString() + "; path=/; domain=." + dmn;
	document.cookie = "gn_rct=" + escape( rct.join("|") ) + "; expires=" + date.toGMTString() + "; path=/; domain=." + dmn;
	document.cookie = "gn_srt=" + escape( srt ) + "; expires=" + date.toGMTString() + "; path=/; domain=." + dmn;
	
	cookieRead();
}

/**
 * Read cookies
 */
function cookieRead()
{
	var cky = document.cookie.split('; ');

	for(var i = 0; i < cky.length; i++)
	{
		var str = cky[i];

		// strip all whitespace
		while (str.charAt(0) == ' ')
		{
			str = str.substring(1, str.length);
		}

		// find the lastplayed cookie
		if (str.indexOf('gn_rct=') == 0)
		{
			var mck = unescape(str.substring(7, str.length));
			if (mck.length > 0) rct = mck.split("|");
		}

		// find the lastplayed cookie
		if (str.indexOf('gn_fvs=') == 0)
		{
			var mck = unescape(str.substring(7, str.length));
			if (mck.length > 0) fvs = mck.split("|");
		}

		// find sort cookie
		if (str.indexOf('gn_srt=') == 0)
		{
			var mck = unescape(str.substring(7, str.length));
			if (mck.length > 0) srt = mck;
		}
		
		// find userid
		if (str.indexOf('gn_pdt=') == 0)
		{
			var mck = unescape(str.substring(7, str.length));
			
			if (mck.length > 0)
			{
				var gud = mck.parseJSON();
				
				if ( gud['gid'] )
				{
					gid = gud['gid'];
					uid = gud['uid'];
					unm = gud['unm'];
					hss = gud['hss'];
				}
			}
		}
	}	
}


function getOffsetTop( element )
{
	var offset = 0;

	if ( element.offsetTop )
	{
	   offset = offset + element.offsetTop;
	}
	
	var parent = element.offsetParent;
	
	while ( parent )
	{
		if ( parent.offsetTop )
		{
			offset = offset + parent.offsetTop;
		}
		parent = parent.offsetParent;
	}

	return offset;
}


function updateLastMyGames()
{
	// if lastplayed is in the html fill it in
	if (document.getElementById("lastplayed"))
	{
		if (rct.length > 0)
		{
			var tmp = '<ul>';

			for (var i = 0; i < rct.length; i++)
			{
				var titm = rct[i].split("^");
				
				ltm = titm[1];
				
				if (titm[1].length > 20)
				{
					titm[1] = titm[1].substring(0, 18) + '...';
				}
				
				tmp += '<li><a href="' + titm[0] + '" title="' + ltm + '">' + titm[1] + '</a>' + '</li>';
			}

			tmp += '</ul>';
		}
		else
		{
			tmp = '<span style="font-size:11px"><i>The games you have played appear in this list so you can find them back easily.</i></span>';
		}
		
		document.getElementById("lastplayed").innerHTML = tmp;
	}
	
	// if mygames is in the html fill it in
	if (document.getElementById("mygames"))
	{
		if (fvs.length > 0)
		{
			var tmp = '<ul>';

			for (var i = 0; i < fvs.length; i++)
			{
				titm = fvs[i].split("^");
				
				ltm = titm[1];
				
				if (titm[1].length > 16)
				{
					titm[1] = titm[1].substring(0, 14) + '...';
				}
				
				tmp += '<li><img src="/images/buttons/delete2.gif" width="12" height="12" onclick="delMyGame(' + i + ');" style="float:right;margin: 3px 8px 0px 0px;cursor:pointer;"><a href="' + titm[0] + '" title="' + ltm + '">' + titm[1] + '</a></li>';
			}
			
			tmp += '</ul>';
		}
		else
		{
			tmp = '<div style="font-size:11px;width:148px;"><i>You can add your favorite games here. While playing a game, click on the &quot;Add to MyGames&quot; button in the menu above the game.</i></div>';
		}
			
		document.getElementById("mygames").innerHTML = tmp;
	}
}

/**
 * Adjust the height of the spacer bottom right
 */
function updateSpacer()
{
	if ( document.getElementById( 'leftspacer' ) )
	{
		var mid = document.getElementById( 'leftspacermid' );
		var spacer = document.getElementById( 'leftspacer' );
		
		mid.style.height = "0px";
		
		var page = ( (document.height !== undefined) ? document.height : document.body.offsetHeight );
		
		if ( gid )
		{
			var page = getOffsetTop( document.getElementById( 'related' ) ) + 4;
		}
		else
		{
			var page = getOffsetTop( document.getElementById( 'footer' ) );
		}
		
		mid.style.height = ( page - getOffsetTop( spacer ) - 14) + "px";
	}
}


/**
 * Disable the "Add to My Games" button if the game is in the users favorites
 */
function switchAddToMyGames()
{
	var found = false;
	
	for (var i = 0; i < fvs.length; i++)
	{
		if (fvs[i] == itm)
		{
			found = true;
		}
	}
	
	if ( found )
	{
		disableButton( 'addmygames' );
	}
	else
	{
		enableButton( 'addmygames', addMyGame );
	}
}


/**
 * Switch warning above comment submit form depending on use state
 */
function switchCommentWarning()
{
	var div = document.getElementById( 'commentwarning' );
	
	if ( div )
	{
		if ( uid )
		{
			div.className = 'comment_warning';
			div.innerHTML = 'This website is for all ages. Spam and obscene language will not be tolerated! Follow the rules or you will have your commenting rights revoked without warning.';
		}
		else
		{
			div.className = 'comment_error';
			div.innerHTML = 'You have to login before you can post a comment.';
		}
	}
}


/**
 * Set the background style of buttons
 */
function setStyle( elementObject, color, background, image )
{
	var obj = document.getElementById ( elementObject );
	obj.style.color = '#' + color;
	obj.style.background = '#' + background + ' url(/images/buttons/' + image + ') 5px 0px no-repeat';
}


/**
 * Zoom in on game
 */
function zoomIn()
{
	var wheight		= wht - 50;
	var width		= 0;
	var height		= Math.floor( ((810 - (2 * gbr )) / gwd) * ght );
	var game		= document.getElementById('gameobject').style;
	
	if ( height < ght ) return;
	if ( (gwd >= 806) || (ght >= wheight) ) return;
	
	if ( height > wheight )
	{
		width			= Math.floor( (wheight / ght) * gwd );
		game.width		= width + "px";
		game.height		= wheight + "px";
		game.marginLeft	= Math.floor( (810 - width) / 2) - gbr + "px";
	}
	else
	{
		game.width		= 810 - (2 * gbr) + "px";
		game.height		= height + "px";
		game.marginLeft	= 2 - gbr + "px";
	}
	
	disableButton( 'zoomin' );
	enableButton( 'zoomout', zoomOut );
	updateSpacer();
}


/**
 * Zoom out of game
 */
function zoomOut()
{
	var game		= document.getElementById('gameobject').style;
	game.width		= gwd + "px";
	game.marginLeft	= gml + "px";
	game.height		= ght + "px";
	
	disableButton( 'zoomout' );
	enableButton( 'zoomin', zoomIn );
	updateSpacer();
}


/**
 * Enable button in bar3
 */
function enableButton ( buttonObject, buttonFunction )
{
	var button	= document.getElementById( buttonObject );
	button.style.cursor	= 'pointer';
	button.onmouseover	= new Function ("setStyle( '" + buttonObject + "', 'FFFFFF', '2E437D', '" + buttonObject + "' + '_b.png');");
	button.onmouseout	= new Function ("setStyle( '" + buttonObject + "', '444444', 'E0E3EC', '" + buttonObject + "' + '_a.png');");
	button.onclick		= buttonFunction;
	setStyle( buttonObject, '444444', 'E0E3EC', buttonObject + '_a.png');
}


/**
 * Disable button in bar3
 */
function disableButton( buttonObject )
{
	var button	= document.getElementById( buttonObject );
	button.style.cursor = 'default';
	button.onmouseover	= '';
	button.onmouseout	= '';
	button.onclick		= '';
	setStyle( buttonObject, '999999', 'E0E3EC', buttonObject + '_c.png');
}


/**
 * Add a game to a users favorites
 */
function addMyGame()
{
	for (var i = 0; i < fvs.length; i++)
	{
		if (fvs[i] == itm)
		{
			alert('This game is already in favorites!');
			return;
		}
	}
	
	if (fvs.length >= 6)
	{
		alert('You already have 6 favorite games, please remove one first.');
		return;
	}

	fvs.push(itm);
	
	cookieWrite();
	updateLastMyGames();
	switchAddToMyGames();
}


/**
 * Delete a game from a users favorites
 */
function delMyGame(id)
{
	if (confirm('Are you sure you want to remove this game?'))
	{
		fvs.splice(id, 1);
		cookieWrite();
		updateLastMyGames();
		switchAddToMyGames();
	}
}


/**
 * Sort the games and reload the page
 */
function changeSort(index)
{
	srt = index;
	cookieWrite();
	window.location.reload();
}


/**
 * Limit textfield input characters
 */
function inputLimit( obj, charset )
{
	if ( charset == 'username' )
	{
		var charList = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	}

	var string = obj.value;
	var length = string.length;
	var filter = '';
	
	for (var i = 0; i < length; i++)
	{
		if ( charList.indexOf( string.charAt(i) ) != -1 )
		{
			filter += string.charAt(i);
		}
	}

	obj.value = filter;
} 


/**
 * Ping the server for some statistics
 */
function ping()
{
	var request			= new HTTPRequest();
	request.url			= '/ping/';
	request.callback	= pingResponse;
	request.send();
}

function pingResponse( result )
{
	if ( result.success == 'true' )
	{
		document.getElementById('usertoolbar').innerHTML = result.html;
		switchCommentWarning();
	}
	else
	{
		setLoggedOut();
	}	
}


/**
 * Send the active spotlight game to Flash
 */
function highLightStart( itemnr )
{
	stm = setTimeout( function(){highLight( itemnr )}, 500 );
}

function highLightStop()
{
	clearTimeout( stm );
}

function highLight( itemnr )
{
	if ( !rdy ) return;
	
	var spotlight;
	
	var item1	= document.getElementById('item1');
	var item2	= document.getElementById('item2');
	var item3	= document.getElementById('item3');
	
	item1.style.backgroundImage = "none";
	item2.style.backgroundImage = "none";
	item3.style.backgroundImage = "none";
	
	document.getElementById( 'item' + itemnr ).style.backgroundImage = "url(/images/main/spotlight.png)";
	
	if (navigator.appName.indexOf("Microsoft") != -1)
	{
		spotlight = window['spotlightswf'];
	}
	else
	{
		spotlight = document['spotlightswf'];
	}

	spotlight.show( itemnr );
}



/**
 * Toggle between login and password retrieval
 */
function toggleStyleDisplay( id1, id2 )
{
	var id1	= document.getElementById( id1 );
	var id2	= document.getElementById( id2 );
	
	opc = 100;

	if (id1.style.display == 'none')
	{
		var callback = function() { fadeSwitch ( id2, id1 ) };
		fadeOut( id2, callback );
	}
	else
	{
		var callback = function() { fadeSwitch ( id1, id2 ) };
		fadeOut( id1, callback );
	}
}

function fadeSwitch( id1, id2 )
{
	id1.style.display = 'none';
	changeOpacity( id2 );
	id2.style.display = 'block';
	fadeIn( id2 );
}

function fadeOut( id1, callback )
{
	if ( opc > 0 )
	{
		opc -= 20;
		changeOpacity( id1 );
		setTimeout( function(){fadeOut(id1, callback)}, 25 );
	}
	else if ( callback )
	{
		callback();
	}
}

function fadeIn( id1, callback )
{
	if ( opc < 100 )
	{
		opc += 20;
		changeOpacity( id1 );
		setTimeout(function(){fadeIn(id1, callback)}, 25 );
	}
	else if ( callback )
	{
		callback();
	}
}

function changeOpacity( obj )
{
	if ( opc == 0 )
	{
		opacity = 0;
	}
	else
	{
		opacity = opc / 100;
	}

	obj.style.opacity		= opacity;
	obj.style.MozOpacity	= opacity;
	obj.style.KhtmlOpacity	= opacity;
	obj.style.filter		= "alpha(opacity=" + opc + ")";
}


/**
 * User login
 */
function login()
{
	var request			= new HTTPRequest();
	request.url			= '/login/';
	request.callback	= loginResponse;
	request.loader		= 'loginLoader';
	request.post		= getFormValues('login');
	request.send();
}

function loginResponse( result )
{
	if ( result.success == 'true' )
	{
		var container = document.getElementById('usertoolbar');
		
		var callback = function () { document.getElementById('usertoolbar').innerHTML = result.html; fadeIn ( container ) };
		
		fadeOut ( container, callback );
		uid = result.uid;
		highscoreEnable();
		switchCommentWarning();
	}
	else
	{
		document.getElementById('loginerror').innerHTML = result.error;
		uid = false;
		switchCommentWarning();
	}
}

function setLoggedOut()
{
	uid = false;
	switchCommentWarning();
}


/**
 * User logout
 */
function logout()
{
	var request			= new HTTPRequest();
	request.url			= '/logout/';
	request.callback	= logoutResponse;
	request.send();
}

function logoutResponse( result )
{
	if (result.success == 'true')
	{
		var container = document.getElementById('usertoolbar');
		var callback = function () { document.getElementById('usertoolbar').innerHTML = result.html; fadeIn ( container ) };
		
		fadeOut ( container, callback );
		setLoggedOut();
	}
}

/**
 * Retreive user password
 */
function password()
{
	var request			= new HTTPRequest();
	request.url			= '/passwordrequest/';
	request.callback	= passwordResponse;
	request.loader		= 'passwordLoader';
	request.post		= getFormValues('password');
	request.send();
}

function passwordResponse( result )
{
	if ( result.success == 'true' )
	{
		document.getElementById('passworderror').innerHTML = result.html;
	}
	else
	{
		document.getElementById('passworderror').innerHTML = result.error;
	}
}


/**
 * Rate a game
 */
function showRating( value )
{
	document.getElementById('doimg').style.background = 'url(/images/stars/stars' + value + '.png)';
}

function setRating( value )
{
	var request			= new HTTPRequest();
	request.url			= '/rate/';
	request.callback	= ratingResponse;
	request.loader		= 'rateLoader';
	request.post.id		= gid;
	request.post.rating	= value;
	request.send();
}

function ratingResponse( result )
{
	if (result.success == 'true')
	{
		var doimg		= document.getElementById('doimg');
		var dotext		= document.getElementById('dotext');
		var showlink	= document.getElementById('showlink');
		var showimg		= document.getElementById('showimg');
		var showtext	= document.getElementById('showtext');
		
		if ( doimg && dotext && showlink && showimg && showtext )
		{
			if ( result.ilg == 'true' )
			{
				dotext.innerHTML	= 'Thank you!';
				showlink.innerHTML	= '<a onclick="toggleStyleDisplay(\'showrating\', \'dorating\');">You\'re rating: ' + result.rating + '</a>';
			}
			else
			{
				doimg.innerHTML		= '<img src="/images/stars/stars' + result.rating + '.png" width="74" height="14" alt="Rated ' + result.rating + '/10" title="Rated ' + result.rating + '/10">';
				dotext.innerHTML	= 'Thank you!';
				showlink.innerHTML	= 'You\'ve already rated this game';
			}

			showimg.innerHTML	= '<img src="/images/stars/stars' + result.round + '.png" width="74" height="14" alt="Rated ' + result.float + '/10" title="Rated ' + result.float + '/10">';
			showtext.innerHTML	= 'Rated ' + result.float + '/10 after ' + result.count + ' votes';
			
			setTimeout(function(){toggleStyleDisplay('showrating', 'dorating')}, 1000);
		}
	}
	else
	{
		alert('Oops, something went wrong, please try again.');
	}
}


/**
 * Get a page with comments from the server
 */
function commentsGetPage( value )
{
	var request			= new HTTPRequest();
	request.url			= '/comments/';
	request.callback	= commentsGetPageResponse;
	request.post.action	= 'getpage';
	request.post.gid	= gid;
	request.post.page	= value;
	request.send();
}

function commentsGetPageResponse( result )
{
	if ( result.success == 'true' )
	{
		document.getElementById('commentdiv').innerHTML = result.html;
		updateSpacer();
		emoReplace();
	}
	else
	{
		alert( result );
		alert('Oops, something went wrong, please try again.');
	}	
}

/**
 * Submit a comment
 */
function commentsSubmit()
{
	if ( uid )
	{
		//var obj = document.getElementById('commenttext');
		var comment		= document.getElementById('commenttext').value;
		var tmp_smiley	= comment;
		var tmp_caps	= comment;
		var tmp_count	= 0;
		
		var smiley_array = [':)',':(',';)',':D',':P','8)',':rolleyes:',':rofl:',':blush:',':cry:',':angry:',':yawn:',':blushing:',':sneaky:',':unshure:',':woot:',':whistle:',':wacko:',':yes:',':no:',':huh:',':ninja:',':laugh:',':mad:'];
		var smiley_count = smiley_array.length;
	
		for ( var i = 0; i < smiley_count; i++ )
		{
			var intIndexOfMatch = tmp_smiley.indexOf( smiley_array[i] );
	
			while ( intIndexOfMatch != -1 )
			{
				tmp_count++;
				
				tmp_smiley = tmp_smiley.replace( smiley_array[i], '' );
				intIndexOfMatch = tmp_smiley.indexOf( smiley_array[i] );
			}
		}		
		
		tmp_smiley	= tmp_smiley.replace(/\s+/g, '' );
		tmp_caps	= tmp_smiley.replace(/[^A-Z]/g,"")
		
		if ( tmp_smiley.length < 8 )
		{
			alert("I think your comment is a bit short.");
		}
		else if ( ( tmp_caps.length / tmp_smiley.length ) > 0.8 )
		{
			alert("Do you really have to shout?\nPlease don't write with all capital letters.");
		}
		else if ( ( tmp_smiley.length / 5 ) < tmp_count - 1 )
		{
			alert("You don't have to use that many smiley's.\nWrite some more text or remove some smiley's.");
		}
		else
		{
			var request			= new HTTPRequest();
			request.url			= '/comments/';
			request.callback	= commentsSubmitResponse;
			request.loader		= 'commentLoader';
			request.button		= 'commentButton';
			request.post.action	= 'submit';
			request.post.gid	= gid;
			request.post.cid	= cdt;
			request.post.comment= comment;
			request.send();
		}
	}
	else
	{
		alert('You have to login before you can post a comment.');
	}
}

function commentsSubmitResponse( result )
{
	if ( result.success == 'true' )
	{
		cdt = 0;
		document.getElementById('commenttext').value = '';
		document.getElementById('commentdiv').innerHTML = result.html;
		window.location.hash = '#comments';
		updateSpacer();
		emoReplace();
	}
	else
	{
		alert('Oops, something went wrong, please try again.');
	}	
}


/**
 * Edit comment
 */
function commentEdit( value )
{
	var request			= new HTTPRequest();
	request.url			= '/comments/';
	request.callback	= commmentEditResponse;
	request.post.action	= 'edit';
	request.post.gid	= gid;
	request.post.cid	= value;
	request.send();
}

function commmentEditResponse( result )
{
	if ( result.success == 'true' )
	{
		cdt = result.cid;
		document.getElementById('commenttext').value = result.comment;
		window.location.hash = '#editcomment';
		updateSpacer();
		emoReplace();
	}
	else
	{
		alert('You can\'t edit this comment.');
	}		
}


/**
 * Report a comment to moderators
 */
function commentsMark( cid, action )
{
	if ( uid )
	{
		if ( action == 'warn' )
		{
			if ( !confirm('Are you sure you want to report this comment as abusive/spam?') )
			{
				return;
			}
		}
		
		var request			= new HTTPRequest();
		request.url			= '/comments/';
		request.callback	= commentsMarkResponse;
		request.post.action	= 'mark';
		request.post.value	= action;
		request.post.gid	= gid;
		request.post.cid	= cid;
		request.send();
	}
	else
	{
		alert('You have to login before you can vote on comments.');
	}
}

function commentsMarkResponse( result )
{
	if ( result.success == 'true' )
	{
		if ( document.getElementById('v' + result.gid ) )
		{
			obj = document.getElementById('v' + result.gid );
			obj.innerHTML = result.html;
		}
		
		if ( result.type == 'warn')
		{
			alert('Thank you!');
		}
	}
	else
	{
		alert( result.error );
	}	
}


/**
 *
 */
function highscoreEnable()
{
 		if ( hss == 2 )
		{
			var options = {	partnerID: "713108ed13655e0c",
							id: "bridge",
							gateway: "http://www.gamenode.com/highscore/",
							logoURL: "http://www.gamenode.com/images/main/favicon.jpg",
							siteURL: "http://www.gamenode.com/",
							siteName: "GameNode",
							callback: highscoreSubmit,
							width: 0,
							height: 0,
							debug: "false",
							denyFriends: "true"
					};
			
			if ( unm )
			{
				options.username	= unm;
				options.userID		= uid;
				options.sessionID	= gid;
			}
			else
			{
				options.denyScores	= "Login to GameNode to submit your scores!";
			}
				
			//userPrefix: "http://www.gamenode.com/profile/", gateway: "http://beta.gamenode.com/accounts/",denyScores: "Login to GameNode to submit your scores!",
			Mochi.addLeaderboardIntegration( options );
		}
}

/**
 * Submit highscores
 */
function highscoreSubmit( params )
{
	var request			= new HTTPRequest();
	request.url			= '/highscore/';
	request.callback	= highscoreSubmitResponse;
	request.post.action	= 'getscores';
	request.post.gid	= gid;
	request.send();
}

function highscoreSubmitResponse()
{
	if ( result.success == 'true' )
	{
		alert( result.data );
	}
	else
	{
		//alert( result.error );
	}	
}

 
/**
 * Preload images for button hovers
 */
function preloadImages()
{
	imageObjects	= new Array(0);
	imageFiles		= new Array( 'stars/stars0.png', 'stars/stars1.png', 'stars/stars2.png', 'stars/stars3.png', 'stars/stars4.png', 'stars/stars5.png', 'stars/stars6.png', 'stars/stars7.png', 'stars/stars8.png', 'stars/stars9.png', 'stars/stars10.png', 'buttons/addmygames_a.png', 'buttons/addmygames_b.png', 'buttons/addmygames_c.png', 'buttons/zoomin_a.png', 'buttons/zoomin_b.png', 'buttons/zoomin_c.png', 'buttons/zoomout_a.png', 'buttons/zoomout_b.png', 'buttons/zoomout_c.png' );
	imageCount		= imageFiles.length;

	for( i = 0; i < imageCount; i++) 
	{
		imageObjects[i]		= new Image();
		imageObjects[i].src	= '/images/' + imageFiles[i];
	}
}


/**
 * Javascript isset() function
 */
function isset( varname )
{
	return( typeof(window[varname]) != 'undefined' );
}


/**
 * Replace comments text html smilies to images
 */
function emoReplace()
{
	var smiley_array	= [':)',':(',';)',':D',':P','8)',':rolleyes:',':rofl:',':blush:',':cry:',':angry:',':yawn:',':blushing:',':sneaky:',':unshure:',':woot:',':whistle:',':wacko:',':yes:',':no:',':huh:',':ninja:',':laugh:',':mad:'];
	var smiley_count	= smiley_array.length;
	var elements		= document.getElementById('comments');
	var elements		= elements.getElementsByTagName('span');
	var total			= elements.length;
	var counter			= 0;

	for ( counter; counter < total; counter++ )
	{
		text = elements[counter].innerHTML;
	
		for ( var i = 0; i < smiley_count; i++ )
		{
			var smiley_img = '<img src="/images/emoticons/' + i + '.gif">';
			var intIndexOfMatch = text.indexOf( smiley_array[i] );
	
			while ( intIndexOfMatch != -1 )
			{
				text = text.replace( smiley_array[i], smiley_img );
				intIndexOfMatch = text.indexOf( smiley_array[i] );
			}
		}
		
		elements[counter].innerHTML = text;
	}
}


/**
 * Insert smiley at caret position (from phpMyAdmin)
 */
function emoInsert( value )
{
	value = ' ' + value + ' ';
	var obj = document.getElementById('commenttext');
	//IE support
	if ( document.selection )
	{
		obj.focus();
		sel = document.selection.createRange();
		sel.text = value;
	}
	//MOZILLA/NETSCAPE support
	else if ( obj.selectionStart || obj.selectionStart == '0' )
	{
		var startPos	= obj.selectionStart;
		var endPos		= obj.selectionEnd;
		obj.value		= obj.value.substring( 0, startPos ) + value + obj.value.substring( endPos, obj.value.length );
	}
	else
	{
		obj.value += value;
	}
	
	document.getElementById('emolist').style.display = 'none';
}


/**
 * AJAX Request Object
 */
function HTTPRequest()
{
	this.url			= '';
	this.callback		= '';
	this.loader			= '';
	this.post			= new Object();
	this.mimeType		= 'text/html';		// 'text/xml'
	
	var httpRequest		= false;			// protected
	var parent			= this;				// Otherwise object is not available from onreadystatechange function call
	
	this.send = function()
	{
		var parameters	= '';
		
		// Mozilla, Safari,...
		if (window.XMLHttpRequest) 
		{
			this.httpRequest = new XMLHttpRequest();
			
			if ( this.httpRequest.overrideMimeType )
			{
				this.httpRequest.overrideMimeType( this.mimeType );
			}
		}
		// Internet Explorer
		else if ( window.ActiveXObject )
		{
			try
			{
				this.httpRequest = new ActiveXObject('Msxml2.XMLHTTP');
			}
			catch (e)
			{
				try
				{
					this.httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
				}
				catch (e) {}
			}
		}
		
		if ( !this.httpRequest )
		{
			alert('Please update your browser.');
			return false;
		}
		
		if ( this.loader )
		{
			var loaderElement = document.getElementById( this.loader );
			loaderElement.style.visibility = "visible";
		}
		
		if ( this.button )
		{
			document.getElementById( this.button ).disabled = true;
		}
		
		for ( var i in this.post )
		{
			parameters += i + "=" + escape( this.post[i] ) + "&";
		}

		this.httpRequest.open( 'POST', this.url, true );
		this.httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.httpRequest.setRequestHeader("Content-length", parameters.length );
		this.httpRequest.setRequestHeader("Connection", "close");
		this.httpRequest.onreadystatechange = this.response;
		this.httpRequest.send( parameters );
	};
	
	this.response = function()
	{
		if ( parent.httpRequest.readyState == 4 )
		{
			if ( parent.httpRequest.status == 200 )
			{
				if ( dbg ) 
				{
					alert(parent.httpRequest.responseText);
				}
				parent.callback( parent.httpRequest.responseText.parseJSON() );
			}
			else
			{
				alert('Oops, something went wrong. Please try again.');
			}
			
			if ( parent.loader )
			{
				var loaderElement = document.getElementById( parent.loader );
				loaderElement.style.visibility = "hidden";
			}
			
			if ( parent.button )
			{
				document.getElementById( parent.button ).disabled = false;
			}
		}		
	};
}


/**
 * innerHTML replacement test (not used)
 */
function setInnerHTML( id, html )
{
	if ( obj = document.getElementById( id ) )
	{
		while( obj.firstChild )
		{
			obj.removeChild( obj.firstChild );
		}
		
		// create a DIV element, using the variable eDIV as a reference to it
		eDIV = document.createElement("div");

		//use the setAttribute method to assign it an id
		//eDIV.setAttribute("id","myDiv");
		
		// append your newly created DIV element to an already existing element.
		obj.appendChild(eDIV);
	}
}


/**
 * Returns an object with all values of a form
 *
 * !Currently only text fields
 */
function getFormValues(form)
{
	var values = new Object();

	var formElements	= document.forms[form].elements;
	var elementsCount	= formElements.length;

	for ( var i = 0; i < elementsCount; i++)
	{
		element = formElements[i];

		if (element.type == "text" || element.type == "password")
		{
			values[element.name] = element.value;
		}
	/*	
		if (obj.childNodes[i].type == "checkbox")
			{
				if (obj.childNodes[i].checked)
				{
					getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
				}
				else
				{
					getstr += obj.childNodes[i].name + "=&";
				}
			}
			if (obj.childNodes[i].type == "radio")
			{
				if (obj.childNodes[i].checked)
				{
					getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
				}
			}
		*/
	}
	
	return values;
}


/**
 * Javascript JSON function
 *
 * Original Authorship: Douglas Crockford
 * Originating Website: http://www.JSON.org
 */
(function (s) {
	var m = {
		'\b': '\\b',
		'\t': '\\t',
		'\n': '\\n',
		'\f': '\\f',
		'\r': '\\r',
		'"' : '\\"',
		'\\': '\\\\'
	};

	s.parseJSON = function (filter)
	{
		try
		{ //if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this))
			if (/^("(\\.|[^"\\\n\r])*?\"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this))
			{
				var j = eval('(' + this + ')');
				
				if (typeof filter === 'function')
				{
					function walk(k, v)
					{
						if (v && typeof v === 'object')
						{
							for (var i in v)
							{
								if (v.hasOwnProperty(i))
								{
									v[i] = walk(i, v[i]);
								}
							}
						}
						
						return filter(k, v);
					}
	
					j = walk('', j);
				}
				
				return j;
			}
		}
		catch (e)
		{
	
		}
		
		throw new SyntaxError("parseJSON");
	};
	
	        s.toJSONString = function ()
        {

            // If the string contains no control characters, no quote characters, and no
            // backslash characters, then we can simply slap some quotes around it.
            // Otherwise we must also replace the offending characters with safe
            // sequences.

            if (/["\\\x00-\x1f]/.test(this))
            {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function (a, b)
                {
                    var c = m[b];
                    if (c) return c;
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };

}) (String.prototype);