// homepage animation stuff
var anim_current = 1;
var anim_info = new Array( 3 );
var anim_data = new Array( 3 );
var anim_link = new Array( 3 );
var anim_file = new Array( 3 );
var anim_path = new Array( 3 );

function $(idToGet) {
	return document.getElementById(idToGet);
}

// initialize animation data
function anim_init() {

	// only do this if the animation is available
	if ($( 'animList' ) == null ) { return false; }
	var animations	= $( 'animList' ).getElementsByTagName( 'li' );
	for(var y = 0; y < animations.length; y++ ) { anim_info[ y + 1 ] = animations[ y ]; }

	if ($( 'animData' ) == null ) { return false; }
	animations	= $( 'animData' ).getElementsByTagName( 'li' );
	for (var y = 0; y < animations.length; y++ ) { anim_data[ y + 1 ] = animations[ y ]; }

	animations	= $( 'animData' ).getElementsByTagName( 'a' );
	for (var y = 0; y < animations.length; y++ ) { anim_path[ y + 1 ] = animations[ y ].href; }

	if ($( 'animNumber' ) == null ) { return false; }
	animations	= $( 'animNumber' ).getElementsByTagName( 'a' );
	for (var y = 0; y < animations.length; y++ ) {
		anim_link[ y + 1 ] = animations[ y ];
		filename = animations[ y ].href.split( "#" );
		anim_file[ y + 1 ] = filename[ 1 ];
		animations[ y ].href = "#";
	}

}

function anim_start() {
	anim_set( 1 );
}

// switch to next animation
function anim_next() {

	// make sure the animation can jump forward
	if ( $( 'animList' ) == null ) { return; }

	anim_current ++;

	if ( anim_current > 3 ) { anim_current = 1;	}

	anim_set();

}

// switch to previous animation
function anim_prev() {
	anim_current --;

	if ( anim_current < 1 ) { anim_current = 3; }
	anim_set();
}

function anim_set (anim_new) {

	// if anim_new is set then change current anim
	if (anim_new != null) {
		anim_current = anim_new;
	}

	// check animation has loaded ok
	if (anim_info[anim_current] == null) {
		return;
	}

	// loop through icon holders and set selected value
	for (var y = 1; y <= 3; y++) {
		// if selected set class name else remove
		if (y == anim_current) {
			anim_info[y].className = 'selected';
			anim_data[y].className = 'selected';
			anim_link[y].className = 'selected';
		} else {
			anim_info[y].className = '';
			anim_data[y].className = '';
			anim_link[y].className = '';
		}
	}

	if ($('animHolder') != null) {

		$('animHolder').innerHTML = AC_FL_GetContent(
			'id', 'animation',
			'name', 'animation',
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0',
			'width', '290',
			'height', '200',
			'quality', 'high',
			'bgcolor', '#ffffff',
			'menu', 'false',
			'allowscriptaccess', 'sameDomain',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'movie', '[SERVER_ROOT]/swfcontent/animations/' + anim_file[anim_current] + '?url=' + anim_path[anim_current] + '&amp;game_id=' + anim_file[anim_current] + '&amp;page_id=homepage',
			'wmode', 'transparent'
		);
		
		statTracker('/animations/views/homepage/' + anim_file[anim_current]);

		// loop through icon holders and set selected value
		for( var y = 1; y <= 3; y++ ) {
			// if selected set class name else remove
			if ( y == anim_current ) {
				//parent.anim_info[ y ].className = "selected";
				anim_info[ y ].className = "selected";
				anim_data[ y ].className = "selected";
				anim_link[ y ].className = "selected";
			} else {
				anim_info[ y ].className = "";
				anim_data[ y ].className = "";
				anim_link[ y ].className = "";
			}
		}


	} else {

		// loop through icon holders and set selected value
		for (var y = 1; y <= 3; y++) {
			// if selected set class name else remove
			if (y == anim_current) {
				anim_info[ y ].className = 'selected';
				anim_data[ y ].className = 'selected';
				anim_link[ y ].className = 'selected';
			} else {
				anim_info[ y ].className = '';
				anim_data[ y ].className = '';
				anim_link[ y ].className = '';
			}
		}

		frames['animHolderFrame'].location.href = 'animdata.php?anim=' + anim_current;

	}

	return false;

}

// player homepage animation
var player_current = 1;
var playersAnim_time = 0;
var player_info = new Array(3);
var player_link = new Array(3);
var player_file = new Array(3);

// initialize animation data
function player_init() {

	// only do this if the animation is available
	// player tab info
	if ($('playerList') == null) {
		return false;
	}
	
	var animations	= $('playerList' ).getElementsByTagName( 'li' );
	for (var y = 0; y < animations.length; y++) {
		player_info[ y + 1 ] = animations[ y ];
	}

	// player id
	if ( $( 'playerNumber' ) == null ) { return false; }
	animations	= $( 'playerNumber' ).getElementsByTagName( 'a' );
	for( var y = 0; y < animations.length; y++ ) {
		player_link[ y + 1 ] 	= animations[ y ];
		filename 				= animations[ y ].href.split( "#" );
		player_file[ y + 1 ]	= filename[ 1 ];
		animations[ y ].href 	= "#";

		$( "playerHolder" ).innerHTML = $( "playerHolder" ).innerHTML + AC_FL_GetContent(
			'id', 'animation',
			'name', 'animation',
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0',
			'width', '290',
			'height', '260',
			'quality', 'high',
			'bgcolor', '#ffffff',
			'menu', 'false',
			'allowscriptaccess', 'sameDomain',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'movie', '/players/swf/components/featuredplayer?uid=' + player_file[ y + 1 ],
			'wmode', 'transparent'
		);
	}

}

function player_start() {

	player_set( 1 );

}

// switch to next animation
function player_next() {

	player_current ++;

	if ( player_current > 3 ) { player_current = 1;	}

	player_set();

}

// switch to previous animation
function player_prev() {

	player_current --;

	if ( player_current < 1 ) { player_current = 3; }

	player_set();

}

function player_set( player_new ) {

	// if anim_new is set then change current anim
	if ( player_new != null ) { player_current = player_new; }

	// check animation has loaded ok
	if( player_info[ player_current ] == null ) { return; }

	// loop through icon holders and set selected value
	for( var y = 1; y <= 3; y++ ) {
		// if selected set class name else remove
		if ( y == player_current ) {
			player_info[ y ].className = "selected";
			player_link[ y ].className = "selected";
		} else {
			player_info[ y ].className = "";
			player_link[ y ].className = "";
		}
	}

	if( $( "playerHolder" ) != null ) {
		scrollPos = (player_current - 1) * 260;
		$( 'playerHolder' ).scrollTop = scrollPos;
	}

	clearTimeout( playersAnim_time );
	playersAnim_time = setTimeout( "player_next();", 10 * 1000 );

	return false;

}

function confirmSubmit( message ) {

	var agree = confirm( message );

	if ( agree ) {
		return true;
	} else {
		return false;
	}

}
/* LIST ALL GAMES */

//var req = getXMLHttpRequest();
function list_init(languageCountrycode, category) { //category = games, ecards, toons
	xml_loadXMLDoc('/' + category + '/' + languageCountrycode + '/full_' + category + '_list.php', xml_onReadyStateChange_list);
//	list_ready();
}

function list_ready() {

	if($('gameList') == null) {
		return;
	}

	if(document.forms['jumpList'] == null) {
		return;
	}

	// list all games menu
	var games	= $('gameList').getElementsByTagName('a');

	document.forms['jumpList'].jumpSelect.options[0] = new Option(language[9], "");

	var oCount = 1;
	for( var y = 0; y < games.length; y++ ) {

		jlText = "";
		jlText = games[ y ].innerHTML;
		jlText = jlText.replace( /&amp;/, "&" );
		jlText = jlText.replace( "<img src=\"/images/challenge_game.gif\" style=\"margin: 0pt 0pt 0pt 4px; vertical-align: middle;\">", "" );
		jlText = jlText.replace( "<IMG style=\"MARGIN: 0px 0px 0px 4px; VERTICAL-ALIGN: middle\" src=\"http://cms.miniclip.com/images/challenge_game.gif\">", "" );
		jlText = jlText.replace( "<IMG style=\"MARGIN: 0px 0px 0px 4px; VERTICAL-ALIGN: middle\" src=\"http://www.miniclip.com/images/challenge_game.gif\">", "" );
		jlText = jlText.replace(/^\s+|\s+$/g, ''); // trim

		if( jlText != "" ) {
			document.forms[ 'jumpList' ].jumpSelect.options[ oCount ] = new Option( jlText, games[ y ].href );
			oCount ++;
		}

	}

	document.forms[ 'jumpList' ].jumpSelect.onchange = function() {
		list_jump();
	}

	// grab cookies
	var list_display = cookie_read( 'list_display' );

	// no cookie so set default
	if ( list_display == null ) {

		cookie_create( "list_display", "1", 150 );
		list_display = 1;

	// hidden so hide stuff
	} else if( list_display == "0" ) {

		$( 'WrapperComplete' ).className = "hidden";
		$( 'listToggle' ).innerHTML = language[ 7 ];
	}
}

// show/ hide the list
function list_toggle() {

	// grab cookies
	var list_display = cookie_read( 'list_display' );

	// currently hidden so show
	if( list_display == "0" ) {

		$( 'WrapperComplete' ).className = "shown";
		$( 'listToggle' ).innerHTML = language[ 8 ];
		cookie_create( "list_display", "1", 150 );

	// else hide
	} else {

		$( 'WrapperComplete' ).className = "hidden";
		$( 'listToggle' ).innerHTML = language[ 7 ];
		cookie_create( "list_display", "0", 150 );

	}

}

function list_jump( list ) {

	if( list == null ) { list = "jumpList"; }

	var newIndex = document.forms[ list ].jumpSelect.selectedIndex;

	if ( newIndex != 0 ) {

		url = document.forms[ list ].jumpSelect.options[ newIndex ].value;
		top.location = url;

	}

}

/* MORE MENU */

var more_displayed = false;

function more_display() {

	if ( more_displayed == true ) {
		$( 'moreNav' ).className = "hidden";
		more_displayed = false;
	} else {
		$( 'moreNav' ).className = "shown";
		more_displayed = true;
	}

}

/* clear current page links */
function clearCurrentLink() {
	var a = document.getElementsByTagName("A");

	for(var i = 0; i < a.length; i++) {
		if(a[i].href == window.location.href.split("#")[0] || a[i].href == window.location.href.split("?")[0]) {
			a[i].className = a[i].className + " current";
		}
	}
}

/* RECENTLY PLAYED */
function recent_save() {
	// load existing recent games
	var recentgame = t_gameId;
	var recentlist = recent_load();
	var savedgames = 0;

	if( recentlist != null ) {
		var recentArray = recentlist.split( "|" );

		// loop through array
		for( i = 0; i < recentArray.length; i++ ) {

			// remove duplicates and crop list to recent 6
			if ( recentArray[ i ] != t_gameId && savedgames < 5 ) {
				recentgame = recentgame + "|" + recentArray[ i ];
				savedgames ++;
			}
		}
	}

	// save new list
	cookie_create( "recent_games", recentgame, 28 );
}

function recent_load() {

	// load recent games into array
	recentlist = cookie_read( "recent_games" );

	return recentlist;

}

function recent_write() {

	var mg_latest = $( "mg_latest" );

	if( mg_latest == null ) { return; }

	var recentlist = recent_load();
	var outputHTML = "<ul>";

	if( recentlist != null ) {

		var recentArray = recentlist.split( "|" );

		// loop through array
		for( i = 0; i <= recentArray.length; i++ ) {

			var gamelist = $( "tid_" + recentArray[ i ] );

			if ( recentArray[ i ] != 0 && gamelist != null ) {

				gamename = gamelist.innerHTML;
				gameurl = gamelist.href;

				outputHTML = outputHTML + "<li><a href=\"" + gameurl + "\">" + gamename + "</a></li>\n";

			}

		}

		outputHTML = outputHTML + "</ul>";

	} else {

		outputHTML = language[ 4 ];

	}

	mg_latest.innerHTML = outputHTML;

}

/* set homepage for IE */
function SetHomepage() {

	return;

	var monkey = new Array();
		monkey['img'] = 'ieHomepage_monkey.png';
		monkey['url']  = 'javascript:history.go(0);';
		monkey['onclick'] = 'onClick="SetHomepageAction(this)"';
		monkey['alt'] = 'Set Miniclip.com as your homepage';

//	var petOne = new Array();
//		petOne['img'] = 'homepagePetsPush01.jpg';
//		petOne['url']  = '/players/en/create-your-yome.php';
//		petOne['onclick'] = '';
//		petOne['alt'] = 'Adopt a pet now!';

//	var petTwo = new Array();
//		petTwo['img'] = 'homepagePetsPush02.jpg';
//		petTwo['url']  = '/players/en/create-your-yome.php';
//		petTwo['onclick'] = '';
//		petTwo['alt'] = 'Adopt a pet now!';

	var sketchstarPush = new Array();
		sketchstarPush['img'] = 'homepage-banner-topright_play.png';
		sketchstarPush['url']  = '/sketch-star/';
		sketchstarPush['onclick'] = '';
		sketchstarPush['alt'] = 'Create Free Animations! Play Sketch Star &raquo;';

	var randArray = new Array();
//		randArray[0] = petOne;
//		randArray[1] = petTwo;
		randArray[0] = sketchstarPush;
	if(document.all && cookie_read('homepageSet') != 'cookieset') {
		randArray[2] = monkey;
	}

	var randResult = Math.floor(Math.random() * randArray.length);
	var randShow = randArray[randResult];

	document.write('<a href="' + randShow['url'] + '" ' + randShow['onclick'] + '><img src="/images/' + randShow['img'] + '" alt="' + randShow['alt'] + '" /></a>');
}

function SetHomepageAction(object) {
	document.body.style.behavior="url(#default#homepage)";
	document.body.setHomePage("http://www.miniclip.com/");
	cookie_create("homepageSet", "cookieset", 365);
	statTracker("/click/setHomepage");
}

/* COOKIES */
function cookie_create(name, value, days) {

	if(days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	} else {
		var expires = "";
	}

	document.cookie = name + "=" + value + expires + "; path=/";
}

function cookie_read(name) {

	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0 ) return c.substring(nameEQ.length, c.length);
	}

	return "";

}

function cookie_erase(name) {
	createCookie(name, "", -1);
}

/* CLIPBOARD (IE only - need to add mozilla version) */
function cb_init() {

	// check we're not in MSIE
	if ( navigator.appName != "Microsoft Internet Explorer" ) {

		// grab all the divs
		var divs = document.getElementsByTagName( "div" );

		// if a copy div replace content
		for( var i = 0; i < divs.length; i++ ) {
			var div = divs[ i ];
			// hide unusable buttons
			if ( div.className == "copyButton" ) {
				div.innerHTML = language[ 6 ];
			}
		}
	}

}

function cb_copy(item) {
	copied = item.createTextRange();
	item.focus();
	item.select();
	copied.execCommand("Copy");
}

/* GENERIC STUFF */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function writeEmail(name, display_name) {

	address = name + "&#64" + "miniclip.com";
	if (display_name == null) {
		document.write("<a href='mailto:" + address + "'>" + address + "</a>");
	} else {
		document.write("<a href='mailto:" + address + "'>" + display_name + "</a>");
	}

}

function prerollCreateGame(pr_gamename, pr_gamewidth, pr_gameheight) {

	// --------------------------------------------------------------------
	// create the code for a flash game, simple function that can be reused
	// --------------------------------------------------------------------
	str_return = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" width=\"" + pr_gamewidth + "\" height=\"" + pr_gameheight + "\">";
	str_return = str_return + "<param name=\"movie\" value=\"" + pr_gamename + "\">";
	str_return = str_return + "<param name=\"quality\" value=\"high\">";
	str_return = str_return + "<param name=\"menu\" value=\"false\">";
	str_return = str_return + "<embed src=\"" + pr_gamename + "\" quality=\"high\" menu=\"false\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"" + pr_gamewidth + "\" height=\"" + pr_gameheight + "\"></embed>";
	str_return = str_return + "</object>";

	$("video_ad").innerHTML = str_return;

}

var BrowserDetect = {
	init: function () {
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			this.navigator = data[i].string;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function removeSidebarBoxAd() {

	outputHtml = "";
	outputHtml = outputHtml + "<style type='text/css'>";
	outputHtml = outputHtml + "#sidebarBoxBackground {display:none;}";
	outputHtml = outputHtml + "#sidebarBoxForeground {display:none;}";
	outputHtml = outputHtml + "#sideBar {margin-top:-5px;}";
	outputHtml = outputHtml + "</style>";
	document.write(outputHtml);
	addLoadEvent(removeSidebarBoxAdComplete);

}

function removeSidebarBoxAdComplete() {
	if($("sidebarBoxBackground") != null) {
		$("sidebarBoxBackground").innerHTML = "";
	}
	if($("sidebarBoxForeground") != null) {
		$("sidebarBoxForeground").innerHTML = "";
	}
}

function insertHomepageVideo( htmlCode ) {
	$("homepageVideoInsert").innerHTML = htmlCode;
	$("homepageVideoInsert").style.display = "block";
}

function removeHomepageVideo() {
	$("homepageVideoInsert").innerHTML = "";
	$("homepageVideoInsert").style.display = "none";
}

function resizeFrame( f ) {
	$( f ).style.height = "50px";
	url = $( f ).contentWindow.location.href;
	if(url.indexOf("miniclip.com") > 0) {
		$( f ).style.height = $( f ).contentWindow.document.body.scrollHeight + "px";
	} else {
		$( f ).style.height = "500px";
	}
}

var shockwaveInstalled = null;
var shockwaveFirstTime = true;
var shockwaveTimeout = null;

function shockwaveIsInstalled() {

	var tVersionString = "0";

	if (navigator.mimeTypes && navigator.mimeTypes["application/x-director"] && navigator.mimeTypes["application/x-director"].enabledPlugin) {
		if (navigator.plugins && navigator.plugins["Shockwave for Director"] && (tVersionIndex = navigator.plugins["Shockwave for Director"].description.indexOf(".")) != - 1) {
			tVersionString = navigator.plugins["Shockwave for Director"].description.substring(tVersionIndex-2, tVersionIndex+2);
		}
	} else if(navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0) {

		try {
			var obj = new ActiveXObject("SWCtl.SWCtl");
			if(obj != null) {
				tVersionString = obj.ShockwaveVersion("");
			}
		} catch(e) {

		}

		if(obj != null) {
			delete obj;
		}

	}

	if(parseInt(tVersionString) >= 11) {
		shockwaveInstalled = true;
	} else {
		shockwaveInstalled = false;
	}

	return shockwaveInstalled;

}

function shockwaveInstall() {

	var showGoldBar = true;

	if(shockwaveIsInstalled()) {

		// track new installs
		if(shockwaveFirstTime == false || cookie_read("sw") == 1) {
			statPageview("/sw/newInstall");
			cookie_erase("sw");
		}

		// track total users with install
		statTracker("/sw/installed");

		// hide installation messaging
		$("shockwaveGameContainer").style.display = "block";
		$("shockwaveInstallWrapper").style.display = "none";
		$("shockwaveInstallBar").style.display = "none";
		$("blackOverlay").style.display = "none";
		$("shockwaveInstallBar").innerHTML = "";

	} else {

		// track not installed
		if(shockwaveFirstTime == true) {
			statPageview("/sw/notInstalled");
			cookie_create("sw", "1", 10);
		}

		var goldbarMessage = "<div id='shockwaveDescription'><p><strong>Adobe Shockwave Required</strong></p><p>Installing is easy. When you see the yellow bar above, follow these steps &raquo;</p></div>";

		// if firefox or similar
		if(navigator.appName == "Netscape") {
			// if version 3
			if(navigator.userAgent.indexOf("Firefox/3") >= 0) {
				goldbarMessage = goldbarMessage + "<div id='shockwaveInstructions'><p>Click <strong>Install Missing Plugins</strong></p><p>Follow the instructions</p><p>Restart Firefox to finish</p></div>";
			// other versions
			} else {
				showGoldBar = false;
			}
		} else {
			goldbarMessage = goldbarMessage + "<div id='shockwaveInstructions'><p><strong>Click the Yellow bar</strong> above</p><p>Choose <strong>Install ActiveX Control</strong></p><p><strong>Click Install</strong> when prompted</p></div>";
		}

		goldbarMessage = goldbarMessage + "<div class='arrow'></div>";

		if(showGoldBar == true) {
			$("shockwaveGameContainer").style.display = "none";
			$("shockwaveInstallWrapper").style.display = "block";
			$("shockwaveInstallBar").style.display = "block";
			$("blackOverlay").style.display = "block";
			$("shockwaveInstallBar").innerHTML = goldbarMessage;
		}

		shockwaveTimeout = setTimeout("shockwaveInstall()", 4 * 1000);
	}

	shockwaveFirstTime = false;

}

function LoginBoxNotification(action){

	switch(action){
		case 'user_logged_in':
		case 'user_logged_out':

			from = urlParam('from');
			challenge_uid = urlParam('challenge_uid');
			challenge_url = decodeURIComponent(urlParam('challenge_url'));

			redirect_url = '';

			if (from == 'challenge') {
				redirect_url = challenge_url + '?challenge=' + challenge_uid + '&from=' + from;
			}

			if (redirect_url != '') {
				window.location.href = redirect_url;
			} else {
				window.location.reload();
			}
	}
}

function urlParam (name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ) {
		return "";
	} else {
		return results[1];
	}
}

function statTracker(path) {
	//alert('TEST : ' + path);
	_gaq.push(['b._trackPageview', path]);
}

function adTracker() {
	tracker = new Image();
	tracker.src = 'http://ads.miniclip.com/RealMedia/ads/adstream_sx.ads/miniclip.com/clubpenguintracking/142334@x01';
}

function jsDebug(data) {
	outputHtml = "";
	outputHtml = outputHtml + "<div style=\"background:#F5F5FF; margin-bottom:1px; padding:5px;\">";
	outputHtml = outputHtml + data;
	outputHtml = outputHtml + "</div>";
	$("jsDebugDataBox").innerHTML = $("jsDebugDataBox").innerHTML + outputHtml;
}





var hpto = new Object;
var toolbarHomepageTakeover = false;

function runTakeover(hpto) {

	// ---------
	// banner ad
	// ---------

	if (hpto.MpuURL != undefined) {
		hpto_MPU_URL = hpto.MpuURL;
		if (hpto.ClickURL != undefined) {
			hpto_MPU_URL = hpto_MPU_URL + '?clickTag=' + encodeURIComponent(hpto.ClickURL.replace('[timestamp]', ord));
		}
		takeoverEmbed = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" id="Ad_that_changes_background_AS1" width="300" height="250" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="' + hpto_MPU_URL + '" /><param name="quality" value="high" /><embed src="' + hpto_MPU_URL + '" quality="high" width="300" height="250" swLiveConnect=true id="Ad_that_changes_background_AS1" name="Ad_that_changes_background_AS1" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
		if ($('takeoverMPU') != null) {
			$('takeoverMPU').innerHTML = takeoverEmbed;
		} else {
			document.write(takeoverEmbed);
		}
	}

	// ----
	// skin
	// ----

	if (hpto.ImageURL_1 == undefined) {
		hpto_ImageURL_1 = hpto.ImageURL;
	} else {
		hpto_ImageURL_1 = hpto.ImageURL_1;
	}

	// Set defaults and fallbacks
	if ( hpto_ImageURL_1 != "" ) {
		hpto_Image_1 = 'url(' + hpto_ImageURL_1 + ') no-repeat center top !important';
	} else {
		hpto_Image_1 = '';
	}

	if (hpto.Colour == '') {
		hpto.Colour = '#333333';
	}

	// Define header options
	switch(hpto.Header) {
	case 1:
		headerHeight = 35;
		break;
	case 2:
		headerHeight = 65;
		break;
	case 3:
		headerHeight = 105;
		break;
	default:
		headerHeight = 0;
	}

	// Set wrapper/logo visibility
	if (hpto.Wrapper == true) {

		$('wrapper').style.marginTop = headerHeight + 'px';

		hpto.hpto_Logo = 'h1 a, h1 a:hover, h1 { background:url( /images/bg_h1.png ) no-repeat 12px 10px; }';

	} else {

		$('wrapper').style.background = 'none';
		$('wrapper').style.padding = headerHeight + 'px 0 0 0';

		if ( hpto.hpto_Logo == false ) {
			hpto.hpto_Logo = 'h1, h1 a, h1 a:hover { background: none; }';
		} else {
			hpto.hpto_Logo = 'h1, h1 a, h1 a:hover { background: url( /images/takeovers/takeoverLogo.png ) no-repeat 12px 10px; }';
		}

		// adjust tabs
		if ($('wrapper') != null) {
			$('wrapper').style.paddingTop = String(headerHeight).concat('px');
		}
	}

	if ($("toolbarPush")) {
		$("toolbarPush").innerHTML = '';
	}
	toolbarHomepageTakeover = true;
	document.body.style.marginRight = '';
	
	
	// Clickable Takeover
	if (hpto.bgClickURL !== undefined) {
		
		bgClickURL = hpto.bgClickURL;
		noBubble = false;
	
		document.body.onclick = function() {
			if (noBubble == false) {
				location.href = bgClickURL;
			}
			noBubble = false;
		}
		
		$('wrapper').onclick = function() {
			noBubble = true;
		};
		
		$('footer').onclick = function() {
			noBubble = true;
		};
		
		document.body.style.cursor = 'pointer';
		$('wrapper').style.cursor = 'default';
		$('footer').style.cursor = 'default';
		
	}
	
	
	// Build the Takeover
	document.body.style.backgroundColor     = hpto.Colour;
	document.body.style.backgroundImage     = 'url(' + hpto_ImageURL_1 + ')';
	document.body.style.backgroundRepeat    = 'no-repeat';
	document.body.style.backgroundPosition  = 'top center';

	if($('beta') != null) {
		$('beta').style.display            = 'none';
	}
	hideMonkey();

	document.write('<style type="text/css">');
		document.write('.flagsHeader { display: none; }\n');
		document.write(hpto.hpto_Logo + '\n');
		document.write('.corner_bl.g, .corner_br.g { background-image: none; }\n');
		document.write('.ad_728_90 { margin-top: 25px; }\n');
	document.write('</style>');


	// ------
	// footer
	// ------
	if (hpto.FootURL != undefined) {
		if (hpto.FootURL.length > 0) {
			var hpto_FootImg = new Image();
			hpto_FootImg.src = hpto.FootURL;
			$('footerTakeover').innerHTML = '<img src="' + hpto.FootURL + '" />';
		}
	}

	// -----
	// stats
	// -----

	// Get statistics variables from array
	hpto_Agency = hpto.Agency;
	hpto_Client = hpto.Client;
	hpto_Campaign = hpto.Campaign;

	// If blank, set unknown.
	if(hpto_Agency == undefined) {
		hpto_Agency = "unknown";
	}
	if(hpto_Client == undefined) {
		hpto_Client = "unknown";
	}
	if(hpto_Campaign == undefined) {
		hpto_Campaign = "unknown";
	}

	// tracking
	if (hpto.TrackURL != undefined) {
		hpto.TrackURL = hpto.TrackURL.replace('[timestamp]', ord);
		tracker = new Image();
		tracker.src = hpto.TrackURL;
	}

	// Log takeover view to Google Analytics
	trackHPTO();

}

function trackHPTO(args) {

	// Get statistics variables from array
	hpto_Agency = hpto.Agency;
	hpto_Client = hpto.Client;
	hpto_Campaign = hpto.Campaign;

	// If blank, set unknown.
	if(hpto_Agency == undefined) {
		hpto_Agency = "unknown";
	}
	if(hpto_Client == undefined) {
		hpto_Client = "unknown";
	}
	if(hpto_Campaign == undefined) {
		hpto_Campaign = "unknown";
	}
	if (args == undefined) {
		args = '';
	}

	var path = '/takeovers/' + encodeURI(hpto_Agency.replace(' ', '-')) + '/' + encodeURI(hpto_Client.replace(' ', '-')) + '/' + encodeURI(hpto_Campaign.replace(' ', '-')) + args;
	statTracker(path);

}

var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;

// Handle all the FSCommand messages in a Flash movie.
function Ad_that_changes_background_AS1_DoFSCommand(command, args) {

	var Ad_that_changes_background_AS1Obj = isInternetExplorer ? document.all.Ad_that_changes_background_AS1 : document.Ad_that_changes_background_AS1;

	imagePath = hpto['ImageURL_' + args];
	if (imagePath == undefined) {
		imagePath = hpto.ImageURL;
	}
	
	bgColor = hpto['Colour_' + args];
	if (bgColor == undefined) {
		bgColor = hpto.Colour;
	}

	document.body.style.backgroundImage = 'url(' + imagePath + ')';
	document.body.style.backgroundColor = bgColor;

	trackHPTO('/swapBackground/' + args);
}

// Hook for Internet Explorer.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
	document.write('<script language=\"VBScript\"\>\n');
	document.write('On Error Resume Next\n');
	document.write('Sub Ad_that_changes_background_AS1_FSCommand(ByVal command, ByVal args)\n');
	document.write('	Call Ad_that_changes_background_AS1_DoFSCommand(command, args)\n');
	document.write('End Sub\n');
	document.write('</script\>\n');
}





function attachTracking() {

	var banner_ids = ['banner_leaderboard', 'banner_boxad', 'banner_pushad_small', 'banner_pushad_big', 'ss_pushad_big', 'ss_pushad_small'];
	var banner_anchor = null;

	for (var i = 0; i < banner_ids.length; i++) {
		banner_anchor = $(banner_ids[i]);

		if (banner_anchor && banner_anchor.href) {

			banner_anchor.onclick = function(e) {
				// stop browser from following the link
				if (!e) var e = window.event;
				e.cancelBubble = true;
				if (e.stopPropagation) e.stopPropagation();

				var image = this.getElementsByTagName('img');
				var path_list = image[0].src.split("/");
				var image_file = path_list[path_list.length - 1].split(".");

				var analytics_path = new Array();

				analytics_path[0] = 'adserver/click';
				analytics_path[1] = adServerProperties;
				analytics_path[2] = this.id;
				analytics_path[3] = image_file[0];

				statTracker(analytics_path.join('/'));
				// go to target url
				window.location.href = this.href;

				return false;

			}

			var image = banner_anchor.getElementsByTagName('img');
			var path_list = image[0].src.split("/");
			var image_file = path_list[path_list.length - 1].split(".");

			var analytics_path = new Array();

			analytics_path[0] = 'adserver/view';
			analytics_path[1] = adServerProperties;
			analytics_path[2] = banner_anchor.id;
			analytics_path[3] = image_file[0];

			statTracker(analytics_path.join('/'));

		}

	}

}

function setBodyMargin() {
	if(document.body.offsetWidth % 2 == 1) {
		document.body.style.marginRight = "1px";
	} else {
		document.body.style.marginRight = "0";
	}
}

var userAge = 0;

// Newsletter Signup (Added by Ben H - 23/04/09)
function coppaAge(coppa_age, form_id, email) {

	// Set Minimum Age Limit
	var ageLimit = 13;

	var userAge = $(coppa_age).value;

	var reg = /^([a-zA-Z0-9_\-\.]+)@((([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4})(\]?)$/;
	var address = document.forms[form_id].elements[email].value;

	if (userAge < ageLimit) {
		$("newsletterForm").innerHTML = '<h3>Sorry!</h3><p class="error">The Miniclip Newsletter is only available to players aged 13 years or over.</p>';
		cookie_create("coppaAge", theYear, 3); // Set a cookie to stop them from trying again
	} else {
		if ((reg.test(address) == false) || (userAge <= ageLimit)) {
			alert('Invalid Email Address');
			return false;
		} else {
			statTracker('/newsletter/signup/');
			return true;
		}
	}

}

function coppaCheck () {
	var age = cookie_read("coppaAge");
	if (age.length > 0 && age < 13) {
		document.getElementById("newsletterForm").innerHTML = '<h3>Sorry!</h3><p class="error">The Miniclip Newsletter is only available to players aged 13 years or over.</p>';
	}
}

/* Toolbar Push Strip */
function toolbarPush() {

	// make sure the game is running on a game page (t_gameId is only available on game pages)
	if (typeof(t_gameId) == 'undefined') {
		return;
	}

	// make sure there is space for the toolbar
	if (toolbarHomepageTakeover == true) {
		return;
	}


	if ($("toolbarPush")) {
		// make sure we're on www
		if(document.domain == "www.miniclip.com") {
			// see if the toolbar can be shown (variable "hidetoolbar" set in some templates)
			if (window['hideToolbar'] == undefined) {
				// see if the toolbar is installed with the toolbar cookie
				var toolbarId = cookie_read("minicliptb_id");

				if (toolbarId.length < 1) {
					// insert toolbar
					outputHtml = '<div class="toolbarContain">';
					outputHtml += '<a href="/games/en/toolbar/">Get the all new Miniclip toolbar for your browser!</a>';
					outputHtml += '<div class="toolbarBody">';
					outputHtml += '<a href="/games/en/toolbar/">Get the all new Miniclip toolbar for your browser!</a>';
					outputHtml += '</div>';
					outputHtml += '</div>';

					//$("toolbarPush").innerHTML = outputHtml;
					$("toolbarPush").innerHTML = '';
				}

			}
		}
	}
}

function reloadAvatar() {
	setTimeout('reloadAvatarReal()', 1500);
}

function reloadAvatarReal() {
	newSrc = $('loginbox_avatar').src + "&dc=" + (Math.random() * 10000000000000000);
	$('loginbox_avatar').src = newSrc;
}

/* TOOLBAR */

var cookName = "minicliptoolbar_id";
var cookieGame = "minicliptoolbarsession";
var msg_noplace = "There is no space to add more Miniclips, use the \"Edit My Miniclips...\" function to make space for new games.";

var gameurl = new Array();
var gametit = new Array();

var Maxgame = ( gametit.length - 1 );

// Function to extract game information from cookie
function toolbar_list() {

	var mg = $( 'mg_miniclips' );

	if( mg == null ) { return; }

	var thecook = cookie_read( cookieGame );
	var output = "";

	if( thecook == null || thecook == "" ) {

		output = language[ 0 ];

	} else {

		thecook.toString();

		var cookArray = thecook.split( "~" );

		for( var ig = 1; ig < 12; ig = ig + 2 ) {

			if ( ig < cookArray.length ) {
				var num = cookArray[ ig ].split( "^" );

				tidVal = $( 'tid_' + num[ 1 ] );

				if( tidVal != null ) {
					detail1 = tidVal.href;
					detail2 = tidVal.innerHTML;

					output = output + "<li><a href='javascript:toolbar_delete( " + num[ 1 ] + " );' class='toolbar_delete'><img src='http://images-vip.napmia.miniclip.com/images/button_delete.gif' alt='delete this miniclip' /></a><a href='" + detail1 + "'>" + detail2 +"</a></li>";
				}
			}
		}

	}

	mg.innerHTML = output;

}

function toolbar_add( thegameid, refresh_list ) {

	var thecook = cookie_read( cookieGame );
	thecook.toString();

	gameName = $( "tid_" + thegameid ).innerHTML;

	// if game already exists...
	if ( thecook.indexOf( "^" + thegameid + "~" ) >= 0 ){
		alert(language[ 3 ] + " " + gameName + " " + language[ 2 ]);
		return;
	}

	var theline = "";

	if ( thecook.length < 5 ) {
		theline += "gm1^" + gameName + "~";
		theline += "ur1^" + thegameid + "~";
	} else {
		theline += "gm1^" + gameName + "~";
		theline += "ur1^" + thegameid + "~";
		theline += thecook;
	}

	countTheCook = thecook.split( "~" );
	toolbarcook = cookie_read( cookName );

	cookie_create( cookieGame, theline, 20000 );
	toolbar_refresh( 0, "add", gameName );

	if( refresh_list == true ) {
		toolbar_list();
	}

}

function toolbar_delete( gameID ) {
	var thecook = cookie_read( cookieGame );
	var theline = "";

	gameName = $( "tid_" + gameID ).innerHTML;

	thegames = thecook.split( "~" );

	for( i = 0; i < thegames.length - 2; i = i + 2 ) {

		// with the old code gameID could be 1 (3-foot-ninja) and it would delete any game with
		// a 1 in it. so i removed indexOf.. /andreas
		number = thegames[ i + 1 ].split( "^" );
		number = number[1];

		if (number == gameID) {
//		if( thegames[ i + 1 ].indexOf( gameID ) > -1 ) {

		} else {
			theline += thegames[ i ] + "~" + thegames[ i + 1 ] + "~";
		}

	}
	cookie_create( cookieGame, theline, 20000 );
	toolbar_refresh( 0, "remove", gameName );
	toolbar_list();

}

function toolbar_refresh( full, addOrRemove, gameName ){

	var thecook = cookie_read( cookieGame );
	thecook = thecook.toString();

	if (thecook.length > 5) {

		if (full == 1) {
			alert(msg_noplace);
		} else if( addOrRemove == "add" ){
			//alert( gameName + " has been added to My Miniclips. Click \"My Miniclips\" in the toolbar to use it!" );
		} else if (addOrRemove == "remove") {
			//alert (gameName + " " + language[1]);
		}
	}
}

function hideMonkey() {
	if ($('homepageMonkey') != null) {
		$('homepageMonkey').innerHTML = '';
	}
}

function detectUnityWebPlayer () {
	var tInstalled = false;
	if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1) {
		tInstalled = detectUnityWebPlayerActiveX();
	} else if (navigator.mimeTypes && navigator.mimeTypes["application/vnd.unity"]) {
		if (navigator.mimeTypes["application/vnd.unity"].enabledPlugin && navigator.plugins && navigator.plugins["Unity Player"]) {
			tInstalled = true;
		}
	}
	return tInstalled;
}

function initTopTen() {

	// only do this if the animation is available
	if ($('topTen') == null ) {
		return false;
	}
	
	var topTenItems = $('topTen').getElementsByTagName('li');
	
	for (var y = 0; y < topTenItems.length; y++) {
		topTenItems[y].id = 'topTenItem' + y;
		topTenItems[y].onmouseover = function() {
			tempTopTenItems = $('topTen').getElementsByTagName('li');
			for (var x = 0; x < topTenItems.length; x++) {
				tempTopTenItems[x].className = '';
				$(tempTopTenItems[x].id + 'Details').style.display = 'none';
			}
			this.className = 'active';
			
			$(this.id + 'Details').style.display = 'block';
		}
	}

}


/* Navigation v2 Stuff */

function siteSearchText() {
	if ($('siteSearch')) {
		var searchMessage = '';
		$('siteSearch').value = searchMessage;
		$('siteSearch').onfocus = function() {
			if (this.value == searchMessage) {
				this.value = '';
			}
		};
		$('siteSearch').onblur = function() {
			if (this.value == '') {
				this.value = searchMessage;
			}
		};
	}
}

var showMoreStatus = false;

function showMoreNav() {

	var showMoreStatus = $('moreNavContent').className == "shown";

	if (showMoreStatus == true) {
		$('moreNavContent').className = "hidden";
		$('moreNavShow').innerHTML = "More";
		$('moreNavShow').style.backgroundPosition = '0px 7px';
	} else {
		$('moreNavContent').className = "shown";
		$('moreNavShow').innerHTML = "Less";
		$('moreNavShow').style.backgroundPosition = '0px -9px';
	}

	if ($('sideBar')) {

		var startHeight = 70;
		var wideActive = document.body.className.indexOf('bigVideo');

		if (showMoreStatus == true) {
			if (wideActive < 0) {
				$('sideBar').style.marginTop = '-' + startHeight + 'px';
			}

			showMoreStatus = false;
		} else {
			if (wideActive < 0) {
				$('sideBar').style.marginTop = '-' + ($('moreNavContent').offsetHeight + startHeight) + 'px';
			}

			showMoreStatus = true;
		}
	}

	return false;
}

function homepageBigAd() {
	document.body.className = document.body.className + ' bigVideo';
}


// Alert user if they try to leave an ongoing game
var _inGame = false;
var _text = "";

function lobbyInGame(inGame, text) {
	_inGame = inGame;
	_text = text;
}

function lobbyConfirmLeave() {
	if (_inGame) {
		return _text;
	}
}

window.onbeforeunload = lobbyConfirmLeave;


// Equalise Div Heights

matchColumns=function(){ 
	var divs,contDivs,maxHeight,divHeight,d; 
	divs=document.getElementsByTagName('div'); 
	contDivs=[]; 
	maxHeight=0;  
	for(var i=0;i<divs.length;i++){  
		// make collection with <div> elements with class attribute "equal"
		if(/\bequal\b/.test(divs[i].className)){ 
			d=divs[i]; 
			contDivs[contDivs.length]=d;  
			if(d.offsetHeight){ 
				divHeight=d.offsetHeight; 					
			}
			else if(d.style.pixelHeight){ 
				divHeight=d.style.pixelHeight;					 
			} 
			maxHeight=Math.max(maxHeight,divHeight); 
		} 
	} 
	for(var i=0;i<contDivs.length;i++){ 
		contDivs[i].style.height=maxHeight + "px"; 
	} 
}  
window.onload=function(){ 
	if(document.getElementsByTagName){ 
		matchColumns();			 
	} 
}