var url = document.location.pathname;
var dmn = document.domain;
var dbg = false;
var _gaq = [];

/**
 * Analytics
 */
switch ( dmn )
{
	case 'www.gamenode.com':
		_gaq = [['_setAccount', 'UA-16182025-1'], ['_trackPageview'], ['_trackPageLoadTime']];
		break;
	case 'www.gamezone.nl':
		_gaq = [['_setAccount', 'UA-16182025-3'], ['_trackPageview'], ['_trackPageLoadTime']];
		break;
	case 'www.nodojuegos.com':
		_gaq = [['_setAccount', 'UA-16182025-6'], ['_trackPageview'], ['_trackPageLoadTime']];
		break;
	case 'beta.gamenode.com':
		_gaq = [['_setAccount', 'UA-16182025-5'], ['_trackPageview'], ['_trackPageLoadTime']];
		break;
}


init = {
	data : [],
	page : null,
	preinitialize : function()
	{
		// 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) {}
	
		// Preload images
		var images = [];
		var files = ['core/category-down.png'];
		var total = files.length;
		var counter = 0;
		
		for( counter; counter < total; counter++) 
		{
			images[counter]	= new Image();
			images[counter].src	= '/images/' + files[counter];
		}
	
		/**
		 * Insert Google analytics
		 */
		var element = document.createElement('script');
		element.type = 'text/javascript';
		element.async = true;
		element.src = 'http://www.google-analytics.com/ga.js';
		
		var scripts = document.getElementsByTagName('script')[0];
		scripts.parentNode.insertBefore(element, scripts);
	},
	creationcomplete : function()
	{
		init.page = document.getElementsByTagName('body')[0].id;
		var fill = false;
		
		/**
		 * Load data
		 */
		var element = document.getElementById('data');
		var attributes = element.attributes;
		var total = attributes.length;
	
		for ( var i = 0; i < total; i++ )
		{
			var attribute = attributes.item(i);

			if ( attribute.nodeName.substring( 0, 4 ) == 'data' )
			{
				init.data[attribute.nodeName.substring( 5 )] = attribute.nodeValue;
			}
		}
		
		user.init();
		toolkit.init();
		
		switch ( init.page )
		{
			case 'category':
				category.onload();
				category.setActive();
				fill = true;
				break;
				
			case 'two-column-left':
				fill = true;
				break;
			
			case 'game':
				game.onload();
				category.setActive();
				comment.emotify();
				comment.message();
				game.spacer();
				com.roqz.Tooltip.init('medals');
				break;
		}
		
		if ( fill )
		{
			var height = document.getElementById( 'main' ).offsetHeight;
			var fill = document.getElementById( 'fill' );
			
			if ( height > 600 )
			{
				fill.style.display = 'block';
				fill.style.height = height - 636 + 'px';
				update( 'fill' );
			}
		}
	}
};

/**
 *
 */
var lang = {
	get: function( prop )
	{
		var domain;
		
		if ( domain = this.domains[dmn] )
		{
			if ( this[domain][prop] )
			{
				return this[domain][prop];
			}
			else
			{
				return this.english[prop];
			}
		}
		else
		{
			return this.english[prop];
		}
	},
	english:
	{
		favorite_duplicate	: 'This game is already in favorites!',
		favorite_maximum	: 'You already have 6 favorite games, please remove one first.',
		favorite_delete		: 'Are you sure you want to remove this game?',
		http_status_error	: 'Oops, something went wrong. Please try again.',
		last_played_default	: 'The games you have played appear in this list so you can find them back easily.',
		my_games_default	: '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.',
		comment_warning		: 'Spam and obscene language will not be tolerated!',
		comment_error_login : 'You have to login before you can post a comment.',
		comment_post_short	: 'I think your comment is a bit short.',
		comment_post_shout	: 'Do you really have to shout?\nPlease don\'t write with all capital letters.',
		comment_post_smilies: 'You don\'t have to use that many smiley\'s.\nWrite some more text or remove some smiley\'s.',
		comment_edit_error	: 'You can\'t edit this comment.',
		comment_mark_abuse	: 'Are you sure you want to report this comment as abusive/spam?',
		comment_mark_login	: 'You have to login before you can vote on comments.',
		thank_you			: 'Thank you!'
	},
	dutch:
	{
		favorite_duplicate	: 'Dit spel staat al in je favorieten!',
		favorite_maximum	: 'Je hebt al 6 spellen in je favoriten. Haal eerst een spel weg voordat je een nieuwe toevoegt.',
		favorite_delete		: 'Weet je zeker dat je dit spel wilt verwijderen?',
		http_status_error	: 'Er is iets fout gegaan, probeer het opnieuw.',
		last_played_default	: 'Hier verschijnen de spelletjes die je hebt gespeeld zodat je ze makkelijk terug kunt vinden.',
		my_games_default	: 'Je kunt je favoriete spelletjes hier toevoegen door op de knop &quot;Toevoegen aan Mijn Spelletjes&quot; te drukken als je een spel speelt.',
		comment_warning		: 'Deze website is voor alle leeftijden. Spam wordt niet getolereerd. Houd je aan de regels of je rechten om te reageren worden zonder waarschuwing ingetrokken.',
		comment_error_login : 'Je moet eerst inloggen voordat je een reactie kunt plaatsen.',
		comment_post_short	: 'Je reactie is te kort.',
		comment_post_shout	: 'Je hoeft niet te schreeuwen. Gebruik wat minder hoofdletters.',
		comment_post_smilies: 'Je gebruikt wel heel veel smilies. Haal er een paar weg of gebruik wat meer tekst.',
		comment_edit_error	: 'Je kunt deze reactie niet bewerken.',
		comment_mark_abuse	: 'Weet je zeker dat je deze reactie als ongepast wilt rapporteren?',
		comment_mark_login	: 'Je moet eerst inloggen voordat je op reacties kunt stemmen.',
		thank_you			: 'Dank je!'

	},
	domains:
	{
		'beta.gamenode.com'	: 'english',
		'www.gamezone.nl'	: 'dutch'
	}
}

controlpanel = {
	toggle : function( value )
	{
		switch ( value )
		{
			case 0:
				document.getElementById( 'tab-login' ).className = 'tab-inactive';
				document.getElementById( 'tab-signup' ).className = 'tab-active';
				document.getElementById( 'user' ).style.display = 'none';
				document.getElementById( 'signup' ).style.display = 'block';
				break;
				
			case 1:
				document.getElementById( 'tab-login' ).className = 'tab-active';
				document.getElementById( 'tab-signup' ).className = 'tab-inactive';
				document.getElementById( 'user' ).style.display = 'block';
				document.getElementById( 'signup' ).style.display = 'none';
				break;
		}
	
		update( 'tab-login' );
		update( 'tab-signup' );
	},
	tween : function()
	{
		var login = document.getElementById( 'login' );
		var retrieve = document.getElementById( 'retrieve' );

		if ( login.style.display == 'none' )
		{
			var callback = function()
			{
				retrieve.style.display = 'none';
				var tween = new com.roqz.transitions.Tween( login, 'alpha', com.roqz.transitions.easing.linear, 0, 1, 100 );
			};
			
			var tween = new com.roqz.transitions.Tween( retrieve, 'alpha', com.roqz.transitions.easing.linear, 1, 0, 100, callback );
		}
		else
		{
			var callback = function()
			{
				login.style.display = 'none';
				var tween = new com.roqz.transitions.Tween( retrieve, 'alpha', com.roqz.transitions.easing.linear, 0, 1, 100 );
			};
			
			var tween = new com.roqz.transitions.Tween( login, 'alpha', com.roqz.transitions.easing.linear, 1, 0, 100, callback );
		}
	}
}

/*
 *
 */
user = {
	uid : 'null',
	unm : 'null',
	init : function()
	{
		user.uid = init.data['user'];
		user.unm = init.data['name'];	
	},
	login : function()
	{
		var request = new com.roqz.net.HTTPRequest();
		request.url = '/login/';
		request.callback = this.response;
		//request.loader = 'loginLoader';
		request.form = 'login';
		request.send();
	},
	logout : function()
	{
		var request			= new com.roqz.net.HTTPRequest();
		request.url			= '/logout/';
		request.callback	= this.response;
		request.send();
	},
	response : function( result )
	{
		if ( result.success == 'true' )
		{
			var callback = function ()
			{
				document.getElementById( 'controlpanel' ).innerHTML = result.html;
				var tween = new com.roqz.transitions.Tween( 'controlpanel', 'alpha', com.roqz.transitions.easing.linear, 0, 1, 100 );
			};
			
			var tween = new com.roqz.transitions.Tween( 'controlpanel', 'alpha', com.roqz.transitions.easing.linear, 1, 0, 100, callback );

			/**
			 * Update user info if login is succesful
			 */
			if ( result.action == 'login' )
			{
				user.uid = result.uid;
				user.unm = result.unm;
			}
			else
			{
				user.destroy();
			}
			
			/**
			 * Change the editor message if we're viewing a game
			 */
			if ( init.page == 'game' )
			{
				comment.message();	
			}
		}
		else
		{
			document.getElementById('login-message').innerHTML = result.error;
			user.destroy();
		}
	},
	destroy : function()
	{
		user.uid = 'null';
		user.unm = 'null';
	},
	password : function()
	{
		var request = new com.roqz.net.HTTPRequest();
		request.url			= '/passwordrequest/';
		request.callback	= this.passwordResponse;
		//request.loader		= 'passwordLoader';
		request.button		= 'password-button';
		request.form		= 'password-form';
		request.send();
	},
	passwordResponse : function( result )
	{
		var element = document.getElementById('password-message');

		if ( result.success == true )
		{
			element.innerHTML = result.html;
		}
		else
		{
			element.innerHTML = result.error;
		}
	}
}



/**
 *
 */
suggestions = {
	data : null,			// search suggestion list object
	loading : false,
	lookup : function()
	{
		if ( suggestions.loading )
		{
			return;
		}
		
		if ( !suggestions.data )
		{
			suggestions.loading	= true;
			
			var request	= new com.roqz.net.HTTPRequest();
			request.url	= '/search-suggestions/';
			request.callback = suggestions.response;
			request.loader = 'suggestion-loader';
			request.method = 'GET';
			request.send();
		}
		else
		{
			suggestions.display();
		}
	},
	response : function( result )
	{
		suggestions.loading = false;
		suggestions.data = result;
		suggestions.display();
	},
	display : function()
	{
		var element = document.getElementById( 'search-suggestions' );
		var results = '';
		var total = 0;
		var value = document.getElementById( 'suggestion-input' ).value.toLowerCase();
		var length = value.length;
		var data = suggestions.data;

		if ( length > 0 )
		{
			for ( var i in data )
			{
				if ( data[i][0].toLowerCase().indexOf( value ) > -1 )
				{
					results += '<a href="' + data[i][1] + '">' + data[i][0] + '</a><br>';
					
					total++;
					
					if ( total > 9 )
					{
						break;	
					}
				}
			}
			
			if ( results != '' )
			{
				element.innerHTML = results;
				element.style.display = 'block';
				update( 'search-suggestions' );
			}
			else
			{
				element.style.display = 'none';
			}
		}
		else
		{
			element.style.display = 'none';
		}
	}
}

category = {
	set : function ( index )
	{
		com.roqz.cookie.set( 's', index );
		window.location.reload();
	},
	onload : function()
	{
		var index = com.roqz.cookie.get( 's' );
		var dropdown = document.getElementById( 'sort' );

		if ( index == null )
		{
			index = 1;	
		}
		
		if ( dropdown.length > 1 )
		{
			dropdown.selectedIndex = index;
		}
	},
	getSection : function( string )
	{
		var pos;
		
		pos = string.lastIndexOf( '.' );
		string = string.substring( pos );
		pos = string.indexOf( '/' );
		string = string.substring( pos );
		pos = string.indexOf( '/', 1 );
		string = string.substring( 0, pos + 1 );
		
		return string;
	},
	setActive : function()
	{
		var menu = document.getElementById( 'category-menu' );
		var items = menu.getElementsByTagName( 'a' );
		var section = this.getSection( url );
		
		for ( var category in items )
		{
			if ( href = items[category].href )
			{
				if ( section == this.getSection( href ) )
				{
					items[category].className = "active";
				}
			}
		}
	}
}

game = {
	gid : 'null',
	hss : 'null',
	onload : function()
	{
		game.gid = init.data['game'];
		game.hss = init.data['highscore'];
		
		if ( user.uid != 'null' )
		{
			setTimeout( game.ping, 10000 );
		}
		
 		if ( game.hss == 2 )
		{
 			game.bridge();
		}
	},
	spacer : function()
	{
		var fill = document.getElementById( 'fill' );
		fill.style.height = '0px';
		//fill.style.height = findPos( document.getElementById( 'related' ) )[0] - findPos( fill )[0] - 22 + "px";
		
		fill.style.height = ROQZ.Dom.element.position( 'related' )[1] - ROQZ.Dom.element.position( 'fill' )[1] - 36 + "px";
	},
	flash : function ( 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="allowFullScreen" value="true"><param name="AllowScriptAccess" value="always"><param name="quality" value="high"><embed src="' + file + '" quality="high" allowFullScreen="true"  AllowScriptAccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="100%" height="100%"></embed></object>');
	},
	shockwave : function( 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>');
	},
	bridge : function()
	{
		var options = {
			partnerID: "713108ed13655e0c",
			id: "bridge",
			gateway: "http://www.gamenode.com/highscore/",
			logoURL: "http://www.gamenode.com/images/favicon.jpg",
			siteURL: "http://" + dmn + "/",
			siteName: "GameNode",
			callback: game.update,
			postMedals: "true",
			width: 0,
			height: 0,
			debug: "false",
			denyFriends: "true"
		};

		if ( user.uid != 'null' )
		{
			options.username	= user.unm;
			options.userID		= user.uid;
			options.sessionID	= game.gid;
		}
		else
		{
			options.sessionID	= game.gid;
			options.denyScores	= "Login to GameNode to submit your scores!";
		}

		Mochi.addLeaderboardIntegration( options );
	},
	update : function ( value )
	{
		setTimeout( function() {
			var request = new com.roqz.net.HTTPRequest();
			request.url = '/highscore/';
			request.callback = game.updateResponse;
			request.post.submission	= 'update';
			request.post.gid = game.gid;
			request.send();
		}, 1000 );
	},
	updateResponse : function( result )
	{
		if ( result.success == 'true' )
		{
			if ( medals = document.getElementById( 'medals' ) )
			{
				medals.innerHTML = result.medals;
				com.roqz.Tooltip.init('medals');
			}
			
			if ( score = document.getElementById( 'highscores' ) )
			{
				score.innerHTML = result.scores;
			}
		}
	},
	ping : function()
	{
		var request	= new com.roqz.net.HTTPRequest();
		request.url	= '/ping/';
		request.post.gid = game.gid;
		request.callback = game.pingResponse;
		request.send();
	},
	pingResponse : function( result )
	{
		if ( result.success == 'true' )
		{
			setTimeout( game.ping, 250000 );	
		}
		else
		{
			//alert( result );
		}
	},
	tween : function()
	{
		var showRating = document.getElementById( 'showrating' );
		var doRating = document.getElementById( 'dorating' );

		if ( showRating.style.display == 'none' )
		{
			var callback = function()
			{
				doRating.style.display = 'none';
				var tween = new com.roqz.transitions.Tween( showRating, 'alpha', com.roqz.transitions.easing.linear, 0, 1, 100 );
			};
			
			var tween = new com.roqz.transitions.Tween( doRating, 'alpha', com.roqz.transitions.easing.linear, 1, 0, 100, callback );
		}
		else
		{
			var callback = function()
			{
				showRating.style.display = 'none';
				var tween = new com.roqz.transitions.Tween( doRating, 'alpha', com.roqz.transitions.easing.linear, 0, 1, 100 );
			};
			
			var tween = new com.roqz.transitions.Tween( showRating, 'alpha', com.roqz.transitions.easing.linear, 1, 0, 100, callback );
		}
	},
	hover : function( value )
	{
		document.getElementById('doimg').style.background = 'url(/images/stars/stars' + value + '.png)';
	},
	rate : function( value )
	{
		var request			= new com.roqz.net.HTTPRequest();
		request.url			= '/rate/';
		request.callback	= game.rateResponse;
		request.loader		= 'rating-loader';
		request.post.id		= game.gid;
		request.post.rating	= value;
		request.send();
	},
	rateResponse : function( 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( game.tween, 1000);
			}
		}
		else
		{
			alert( lang.get('http_status_error') );
		}
	}
}

toolkit = {
	state : false,
	timer : null,
	move : -120,
	init : function()
	{
		document.getElementById( 'toolkit-tab' ).onmouseover = toolkit.show;
		document.getElementById( 'toolkit-social' ).innerHTML = '<h2>SOCIAL MEDIA</h2><iframe src="http://www.facebook.com/plugins/like.php?href=' + document.location + '&amp;send=false&amp;layout=button_count&amp;width=225&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=trebuchet+ms&amp;height=21" scrolling="no" frameborder="0" class="social" allowTransparency="true"></iframe><div class="social"><g:plusone size="medium"></g:plusone></div><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><div id="stumbleupon"></div>';
		
		var a = document.createElement('script');
		a.type = 'text/javascript';
		a.async = true;
		a.src = 'https://apis.google.com/js/plusone.js';

		var b = document.createElement('script');
		b.type = 'text/javascript';
		b.async = true;
		b.src = ('http://platform.twitter.com/widgets.js');
		
		var c = document.createElement('script');
		c.type="text/javascript";
		c.async = true;
		c.src = 'http://www.stumbleupon.com/hostedbadge.php?s=1&a=1&d=stumbleupon&r=' + document.location;

		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(a, s);
		s.parentNode.insertBefore(b, s);
		s.parentNode.insertBefore(c, s);
		
		if ( init.page == 'game' )
		{
			toolkit.move = 0;	
		}
	},
	show : function()
	{
		if ( !toolkit.state )
		{
			toolkit.state = true;
			var Tween =  new com.roqz.transitions.Tween( 'toolkit', 'x', com.roqz.transitions.easing.linear, -524, toolkit.move, 300 );
			
			document.getElementById( 'toolkit' ).onmouseout = function()
			{
				toolkit.timer = setTimeout( toolkit.hide, 1000 );
			}
			
			document.getElementById( 'toolkit' ).onmouseover = function()
			{
				clearTimeout( toolkit.timer );
			}
		}
	},
	hide : function()
	{
		var Tween =  new com.roqz.transitions.Tween( 'toolkit', 'x', com.roqz.transitions.easing.linear, toolkit.move, -524, 300 );
		toolkit.state = false;
	},
	favorite : function()
	{
		var request = new com.roqz.net.HTTPRequest();
		request.url = '/ajax/';
		request.callback = toolkit.response;
//		request.loader = 'rating-loader';
		request.post.id = game.gid;
		request.post.module	= 'favorite';
		request.post.action = 'add';
		request.send();
	},
	response : function( result )
	{
		if ( result.success == 'true' )
		{
			document.getElementById('toolkit-favorites').innerHTML = result.html;
		}
		else
		{
			alert( result.message );
		}
	},
	remove : function( id )
	{
		if ( confirm('Are your sure you want to remove this game?') )
		{
			var request = new com.roqz.net.HTTPRequest();
			request.url = '/ajax/';
			request.callback = toolkit.response;
	//		request.loader = 'rating-loader';
			request.post.id = id;
			request.post.module	= 'favorite';
			request.post.action = 'remove';
			request.send();
		}
	}
}

comment = {
	cid : 'null',
	send : function()
	{
		if ( user.uid )
		{
			//var obj = document.getElementById('commenttext');
			var text		= document.getElementById('comment-text').value;
			var tmp_smiley	= text;
			var tmp_caps	= text;
			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( lang.get('comment_post_short') );
			}
			else if ( ( tmp_caps.length / tmp_smiley.length ) > 0.8 )
			{
				alert( lang.get('comment_post_shout') );
			}
			else if ( ( tmp_smiley.length / 5 ) < tmp_count - 1 )
			{
				alert( lang.get('comment_post_smilies') );
			}
			else
			{
				var request = new com.roqz.net.HTTPRequest();
				request.url = '/comments/';
				request.callback = comment.sendResponse;
				request.loader = 'comment-loader';
				request.button = 'comment-button';
				request.post.action = 'submit';
				request.post.gid = game.gid;
				request.post.cid = comment.cid;
				request.post.comment = text;
				request.send();
			}
		}
		else
		{
			alert( lang.get('comment_mark_login') );
		}
	},
	sendResponse : function( result )
	{
		if ( result.success == 'true' )
		{
			comment.cid = 'null';
			document.getElementById('comment-text').value = '';
			document.getElementById('comments').innerHTML = result.html;
			window.location.hash = '#comments';
			game.spacer();
			comment.emotify();
		}
		else
		{
			alert( lang.get('http_status_error') );
		}
	},
	edit : function( value )
	{
		var request	= new com.roqz.net.HTTPRequest();
		request.url	= '/comments/';
		request.callback = comment.editResponse;
		request.post.action = 'edit';
		request.post.gid = game.gid;
		request.post.cid = value;
		request.send();
	},
	editResponse : function( result )
	{
		if ( result.success == 'true' )
		{
			comment.cid = result.cid;
			document.getElementById('comment-text').value = result.comment;
			window.location.hash = '#editcomment';
			game.spacer();
			comment.emotify();
		}
		else
		{
			alert( lang.get('comment_edit_error') );
		}
	},
	getPage : function( value )
	{
		var request			= new com.roqz.net.HTTPRequest();
		request.url			= '/comments/';
		request.callback	= comment.getPageResponse;
		request.loader		= 'pagination-loader';
		request.post.action	= 'getpage';
		request.post.gid	= game.gid;
		request.post.page	= value;
		request.send();
	},
	getPageResponse : function( result )
	{
		if ( result.success == 'true' )
		{
			document.getElementById('comments').innerHTML = result.html;
			//updateSpacer();
			game.spacer();
			comment.emotify();
		}
		else
		{
			//alert( result );
			alert( lang.get('http_status_error') );
		}	
	},
	mark : function( cid, action )
	{
		if ( user.uid )
		{
			if ( action == 'warn' )
			{
				if ( !confirm( lang.get('comment_mark_abuse') ) )
				{
					return;
				}
			}
			
			var request			= new com.roqz.net.HTTPRequest();
			request.url			= '/comments/';
			request.callback	= comment.markResponse;
			request.post.action	= 'mark';
			request.post.value	= action;
			request.post.gid	= game.gid;
			request.post.cid	= cid;
			request.send();
		}
		else
		{
			alert( lang.get('comment_mark_login') );
		}
	},
	markResponse : function( 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( lang.get('thank_you') );
			}
		}
		else
		{
			alert( result.error );
		}	
	},
	message : function()
	{
		var div = document.getElementById( 'editor-message' );

		if ( user.uid != 'null' )
		{
			div.className = 'border orange';
			div.innerHTML = lang.get('comment_warning');
		}
		else
		{
			div.className = 'border red';
			div.innerHTML = lang.get('comment_error_login');
		}
	},
	insert : function( value )
	{
		value = ' ' + value + ' ';
		var obj = document.getElementById('comment-text');
		
		//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;
		}
		
		comment.hide();
	},
	emotify : function()
	{
		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;
		}	
	},
	show : function()
	{
		document.getElementById('list').style.display = 'block';
	},
	hide : function()
	{
		document.getElementById('list').style.display = 'none';
	}
}

/**
 * Signup form
 */
signUp = {
 	check : function()
	{
		var request	= new com.roqz.net.HTTPRequest();
		request.url	=  '/checkusername/';
		request.callback = signUp.checkResponse;
		request.loader = 'check-loader';
		request.button = 'checkButton';
		request.post.username = document.forms['signup'].signup_username.value;
		request.send();
	},
	checkResponse : function( result )
	{
		if ( result.success == 'true' )
		{
			document.getElementById('username_error').innerHTML = result.html;
		}
		else
		{
			document.getElementById('username_error').innerHTML = result.error;
		}
	},
	limit : function( 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;
	}
}

/**
 * Game submit form
 */
gamesubmit = {
	timer : null,
	gameComplete : false,
	thumbComplete : false,
	uploadFlash : function()
	{
		this.gameComplete = false;
		document.forms['flash'].submit();
		document.forms['flash'].apc_file.disabled = true;
		this.timer = setTimeout( this.progress, 1000 );
	},
	uploadThumb : function()
	{
		document.forms['thumb'].submit();
	},
	progress : function() 
	{
		var request = new com.roqz.net.HTTPRequest();
		request.url = '/submit-a-game/';
		request.callback = gamesubmit.progressResponse;
		request.post.action = 'progress';
		request.post.key = document.forms['flash'].APC_UPLOAD_PROGRESS.value;
		request.send();
	},
	progressResponse : function( response )
	{
		if ( response.success == 'true' && !gamesubmit.gameComplete )
		{
			var progress = Math.round( response.progress.current / response.progress.total * 100 );
			document.getElementById('apc-label').innerHTML = response.progress.filename;
			document.getElementById('apc-progress').style.width = progress * 3 + 'px';
			document.getElementById('flash-status').innerHTML = '<i>Uploading ' + progress + '% complete...</i>';

			if ( progress == 100 )
			{
				document.getElementById('apc-progress').style.width = '0px';
			}
			else
			{
				gamesubmit.timer = setTimeout( gamesubmit.progress, 500 );
			}
		}
		else
		{
			document.getElementById('apc-progress').style.display = "none";
		}
	},
	flashResult : function( success, width, height )
	{
		gamesubmit.gameComplete = true;
		clearTimeout( this.timer );
		document.getElementById('apc-progress').style.width = '0px';
		document.forms['flash'].apc_file.disabled = false;
		
		if ( success )
		{
			document.getElementById('flash-status').innerHTML = "Upload complete. Width: " + width + "px, height: " + height + "px.";
		}
		else
		{
			document.getElementById('flash-status').innerHTML = '<span style="color:#FF0000">Wrong file type.</a>';
		}
	},
	thumbResult : function( success, file )
	{
		if ( success )
		{
			document.getElementById('apc-thumb').innerHTML = file;
			document.getElementById('thumb-status').innerHTML = 'That looks like a nice thumb.';
		}
		else
		{
			document.getElementById('thumb-status').innerHTML = '<span style="color:#FF0000">Wrong file type.</a>';
		}
	},
	helpShow : function( element )
	{
		document.getElementById( element.name + '_help' ).style.display = 'block';
	},
	helpHide : function( element )
	{
		document.getElementById( element.name + '_help' ).style.display = 'none';
	},
	doSubmit : function()
	{
			
	},
	getPage : function( value )
	{
		var request			= new com.roqz.net.HTTPRequest();
		request.url			= '/submit-a-game/';
		request.callback	= gamesubmit.getPageResponse;
		//request.loader		= 'pagination-loader';
		request.post.action	= 'getpage';
		request.post.page	= value;
		request.send();
	},
	getPageResponse : function( result )
	{
		if ( result.success == 'true' )
		{
			document.getElementById('games').innerHTML = result.html;
			//updateSpacer();
			//game.spacer();
		}
		else
		{
			//alert( result );
			alert( lang.get('http_status_error') );
		}	
	},
}


function update( element )
{
	if ( typeof PIE != 'undefined' )
	{
		PIE.Element.getInstance( document.getElementById( element ) ).update( true );
	}
}


/**
 * Return user data
 */
function API_getUserData()
{
	data = new Object;
	
	if ( user.uid != 'null' )
	{
		data.name		= user.unm;
		data.id			= user.uid;
		data.success	= true;
	}
	else
	{
		data.success	= false;
	}
	
	return data;
}

init.preinitialize();

ROQZ.Event.DomReady.add( init.creationcomplete );

