// Sharing module behaviour
jQuery.getScript('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js');

function toggleSharingModulePopup() {
	var sharingBox = document.getElementById( "sharingModulePopup" );
	if ( sharingBox.style.display == "none" )  {
		sharingBox.style.display = "block";
	} else {
		sharingBox.style.display = "none";
	}
}

// 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 );

$mc = function(idToGet) {
	return document.getElementById(idToGet);
}

// initialize animation data
function anim_init() {

	// only do this if the animation is available
	if ($mc('animList') == null) {
		return false;
	}
	var animations	= $mc('animList').getElementsByTagName( 'li' );
	for(var y = 0; y < animations.length; y++) {
		anim_info[ y + 1 ] = animations[ y ];
	}

	if ($mc('animData') == null) {
		return false;
	}
	animations	= $mc('animData').getElementsByTagName( 'li' );
	for (var y = 0; y < animations.length; y++ ) {
		anim_data[ y + 1 ] = animations[ y ];
	}

	animations	= $mc( 'animData' ).getElementsByTagName( 'a' );
	for (var y = 0; y < animations.length; y++ ) {
		anim_path[ y + 1 ] = animations[ y ].href;
	}

	if ($mc('animNumber') == null) {
		return false;
	}
	animations	= $mc( '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 ( $mc( '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 ($mc('animHolder') != null) {

		//new SWFObject version
		movieLocation = '[SERVER_ROOT]/swfcontent/animations/' + anim_file[anim_current] + '.swf?url=' + anim_path[anim_current] + '&game_id=' + anim_file[anim_current] + '&page_id=homepage';
		var flashvars = {};
		var params = {};
		params.menu = "false";
		params.quality = "high";
		params.bgcolor = "#ffffff";
		params.wmode = "opaque";
		params.allowscriptaccess = "always";
		var attributes = {};
		swfobject.embedSWF(movieLocation, "animHolder", "290", "200", "9.0.0", false, flashvars, params, attributes);

		//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);


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( $mc( "playerHolder" ) != null ) {
		scrollPos = (player_current - 1) * 260;
		$mc( '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;
	}

}

/* 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";
		}
	}
}


/* 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 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] = 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) {

	days = days * 60 * 24;
	cookie_create_time (name, value, days);

}


/* COOKIES */
function cookie_create_time(name, value, duration) {

	// duration in minutes
	if (duration) {
		var date = new Date();
		date.setTime(date.getTime() + (duration * 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) {
	cookie_create (name, '', -1);
}

/* 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>";

	$mc("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($mc("sidebarBoxBackground") != null) {
		$mc("sidebarBoxBackground").innerHTML = "";
	}
	if($mc("sidebarBoxForeground") != null) {
		$mc("sidebarBoxForeground").innerHTML = "";
	}
}

function insertHomepageVideo( htmlCode ) {
	$mc("homepageVideoInsert").innerHTML = htmlCode;
	$mc("homepageVideoInsert").style.display = "block";
}

function removeHomepageVideo() {
	$mc("homepageVideoInsert").innerHTML = "";
	$mc("homepageVideoInsert").style.display = "none";
}

function resizeFrame( f ) {
	$mc( f ).style.height = "50px";
	url = $mc( f ).contentWindow.location.href;
	if(url.indexOf("miniclip.com") > 0) {
		$mc( f ).style.height = $mc( f ).contentWindow.document.body.scrollHeight + "px";
	} else {
		$mc( 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) {
			//statTracker("/sw/newInstall");
			cookie_erase("sw");
		}

		// hide installation messaging
		$mc("shockwaveGameContainer").style.display = "block";
		$mc("shockwaveInstallWrapper").style.display = "none";
		$mc("shockwaveInstallBar").style.display = "none";
		$mc("blackOverlay").style.display = "none";
		$mc("shockwaveInstallBar").innerHTML = "";

	} else {

		// track not installed
		if(shockwaveFirstTime == true) {
			//statTracker("/sw/notInstalled");
			cookie_create("sw", "1", 10);
		}
		var goldbarMessage = "<div id='shockwaveDescription'><p><strong>Adobe Shockwave Required</strong></p><p>Installing is easy.<br>Just follow these steps &raquo;</p></div>";

		// if firefox or similar
		if(navigator.appName == "Netscape") {
			// if version >3
			if(navigator.userAgent.indexOf("Firefox") != -1) {
				firefoxVersion = navigator.userAgent.charAt(navigator.userAgent.indexOf("Firefox/")+8);
				if(firefoxVersion >= 3) {
					goldbarMessage = goldbarMessage + "<div id='shockwaveInstructions'><p>Click <strong>Install Missing Plugins</strong></p><p>Follow the instructions</p><p>You're done. Enjoy the game!</p></div><div class='arrow'></div>";
				}
			}
			else if(navigator.userAgent.indexOf("Chrome") != -1) {
				goldbarMessage = goldbarMessage + "<div id='shockwaveInstructions'><p><a href='http://get.adobe.com/shockwave/' target='_blank'><strong>Click here</strong></a> to install Adobe Shockwave</p><p>Follow the instructions</p><p>You're done. Enjoy the game!</p></div>";
			} else {
				showGoldBar = false;
			}
		}
		else if((navigator.appName == "Microsoft Internet Explorer") &&	(navigator.userAgent.charAt(navigator.userAgent.indexOf("MSIE ")+5) >= 9)) {
			goldbarMessage = goldbarMessage + "<div id='shockwaveInstructions'><p><strong>Click Install in the bar BELOW</strong></p><p>Allow the installation when prompted</p></div><div class='arrowDown'></div>";
		}
		else if(navigator.appName == "Opera") {
			goldbarMessage = goldbarMessage + "<div id='shockwaveInstructions'><p><a href='http://get.adobe.com/shockwave/' target='_blank'><strong>Click here</strong></a> to install Adobe Shockwave</p><p>Follow the instructions</p><p>You're done. Enjoy the game!</p></div>";
		}
		else {
			goldbarMessage = goldbarMessage + "<div id='shockwaveInstructions'><p><strong>Click the yellow bar</strong> above</p><p>Choose <strong>Install This Addon...</strong></p><p><strong>Click Install</strong> when prompted</p></div><div class='arrow'></div>";
		}

		if(showGoldBar == true) {
			$mc("shockwaveGameContainer").style.display = "none";
			$mc("shockwaveInstallWrapper").style.display = "block";
			$mc("shockwaveInstallBar").style.display = "block";
			$mc("blackOverlay").style.display = "block";
			$mc("shockwaveInstallBar").innerHTML = goldbarMessage;
		}

		shockwaveTimeout = setTimeout("shockwaveInstall()", 4 * 1000);
	}

	shockwaveFirstTime = false;

}

function LoginBoxNotification(action){
	// if possible  refresh the toolbar
	if (typeof setTimeout("RefreshToolbarByCTID", 500) == 'function') {
		// refresh miniclip toolbar
		setTimeout("RefreshToolbarByCTID('CT3067892')", 500);
	}
	switch(action){
		case 'user_logged_in':
		case 'user_logged_out':

			refreshToolbar();

			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;
			}else if (typeof(redirect_new) != 'undefined') {
				redirect_url = redirect_new;
			}

			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) {
	if (typeof(_gaq) != 'undefined') {
		/*
		var st = document.createElement('script');
		st.type = 'text/javascript';
		st.src = '/php/services/indigo/dfp.php?t=' + path;

		var head=document.getElementsByTagName('head')[0];
		head.appendChild(st);
		*/

		//alert('GA tracking: '+path);
		_gaq.push(['b._trackPageview', path]);
	}
}

function eventTracker(category, action, opt_label, opt_value) {
	if (typeof(_gaq) != 'undefined') {
		_gaq.push(['b._trackEvent', category, action, opt_label, opt_value]);
	}
}

function statTrackerDelay(redirect, path) {
	if (typeof(_gaq) != 'undefined') {
		_gaq.push(['b._trackPageview', path]);
		setTimeout('document.location = "' + redirect + '"', 500);
	}
}


// used to track unique visitors on additional pages that don't feature real ads
function adTracker(track_url) {
	if (track_url == undefined) {
		track_url = 'http://ads.miniclip.com/RealMedia/ads/adstream_sx.ads/miniclip.com/clubpenguintracking/142334@x01';
	}
	if (document.location.protocol != 'https:') {
		tracker = new Image();
		tracker.src = track_url;
	}
}

function flashTracker(url) {
	if (document.location.protocol != 'https:') {
		tracker = new Image();
		tracker.src = url;
	}
}

function jsDebug(data) {
	outputHtml = "";
	outputHtml = outputHtml + "<div style=\"background:#F5F5FF; margin-bottom:1px; padding:5px;\">";
	outputHtml = outputHtml + data;
	outputHtml = outputHtml + "</div>";
	$mc("jsDebugDataBox").innerHTML = $mc("jsDebugDataBox").innerHTML + outputHtml;
}





var hpto = new Object;
var toolbarHomepageTakeover = false;
var hptoDisplay = false;

function runTakeover(hpto) {

	if (hptoDisplay == true) {
		return;
	}

	// ---------
	// 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 ($mc('takeoverMPU') != null) {
			$mc('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
	if (hpto.CPTO == true) {
		if (hpto.Hide728 == true) {
			headerHeight = 35;
			clickHeight = 65;
		} else {
			headerHeight = 105;
			clickHeight = 105;
		}
	} else {
		switch(hpto.Header) {
			case 1:
				headerHeight = 35;
				clickHeight = 35;
				break;
			case 2:
				headerHeight = 65;
				clickHeight = 65;
				break;
			case 3:
				headerHeight = 105;
				clickHeight = 105;
				break;
			default:
				headerHeight = 0;
		}
	}

	// Set wrapper/logo visibility
	if ($mc('wrapper') != null) {
		if (hpto.Wrapper == true) {
			$mc('wrapper').style.marginTop = headerHeight + 'px';
			hpto.hpto_Logo = 'h1 a, h1 a:hover, h1.ad a, h1.ad a:hover { background:url( /images/bg_h1.png ) no-repeat 12px 10px; }';
		} else {
			$mc('wrapper').style.background = 'none';
			$mc('wrapper').style.padding = headerHeight + 'px 0 0 0';

			if ( hpto.hpto_Logo == false ) {
				hpto.hpto_Logo = 'h1.ad, h1 { background: none; }';
			} else {
				hpto.hpto_Logo = 'h1.ad, h1 { background: url( /images/takeovers/takeoverLogo.png ) no-repeat 12px 10px; }';
			}

			$mc('wrapper').style.paddingTop = String(headerHeight).concat('px');
		}
	}

	if ($mc("toolbarPush")) {
		$mc("toolbarPush").innerHTML = '';
	}
	toolbarHomepageTakeover = true;
	document.body.style.marginRight = '';

	// Clickable Takeover
	if (hpto.bgClickURL !== undefined) {

		bgClickURL = hpto.bgClickURL;
		noBubble = false;

		if(hpto.Agency == "internal") {
			document.body.onclick = function() {
				if (noBubble == false) {
					window.location.href = bgClickURL;
				}
				noBubble = false;
			}
		} else {
			document.body.onclick = function() {
				if (noBubble == false) {
					window.open(bgClickURL);
				}
				noBubble = false;
			}
		}

		$mc('wrapper').onclick = function() {
			noBubble = true;
		};

		$mc('footer').onclick = function() {
			noBubble = true;
		};

		document.body.style.cursor = 'pointer';
		$mc('wrapper').style.cursor = 'default';
		$mc('footer').style.cursor = 'default';

	} else {

		document.body.onclick = null;

	}


	//Clickable Area
	isInternal = '';

	if(hpto.Agency !== "internal") {
		isInternal = ' target="_blank"';
	}

	if ((hpto.areaClickURL !== undefined) && (hpto.areaClickPosition !== undefined)) {
		trackpath = hpto.areaClickPosition + '/' + hpto.Agency + '/' + hpto.Client + '/' + hpto.Campaign;
		trackclass = 'hpto-click-button-' + hpto.areaClickPosition + ' hpto-click-button-' + clickHeight;
		trackdiv = '<div id="hpto-click-button" class="' + trackclass + '"><a href="' + hpto.areaClickURL + '"' + isInternal + ' onClick="statTracker(\'/takeovers/clickable-area/' + trackpath + '/\');">Click Here</a></div>';
		jQuery(trackdiv).insertBefore('#wrapper h1');
	}


	// 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($mc('beta') != null) {
		$mc('beta').style.display            = 'none';
	}
	hideMonkey();

	document.write('<style type="text/css">');
	document.write('.flagsHeader { display: none; }\n');
	document.write(hpto.hpto_Logo + '\n');
	if (headerHeight > 0) {
		document.write('.ad_728_90 { margin-top: 25px; }\n');
	}
	if (hpto.Hide728 == true) {
		document.write('.ad_728_90, .block_728_90 { display:none; }\n');
	}
	if (hpto.HideBreadcrumb == true) {
		document.write('h1.ad {margin-top: 40px;}\n');
		document.write('body.H_game .breadcrumbs, body.H_game .hGameCat {display: none;}\n');
	}
	document.write('.corner_bl.g, .corner_br.g { background-image: none; }\n');
	document.write('</style>');


	// ------
	// footer
	// ------
	if (hpto.FootURL != undefined) {
		if (hpto.FootURL.length > 0) {
			var hpto_FootImg = new Image();
			hpto_FootImg.src = hpto.FootURL;
			$mc('footerTakeover').innerHTML = '<img src="' + hpto.FootURL + '" />';
		}
	}

	// -----
	// stats
	// -----

	// Get statistics variables from array
	if (hpto.Agency == 'internal') {
		hpto_Agency = 'Miniclip-Internal';
	} else {
		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;
	}

	hptoDisplay = true;

	// Log takeover view to Google Analytics
	trackHPTO();

	hpto = new Object();

}

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 = '/advertising/takeovers/' + encodeURI(hpto_Agency.replace(' ', '-')) + '/' + encodeURI(hpto_Client.replace(' ', '-')) + '/' + encodeURI(hpto_Campaign.replace(' ', '-')) + args;
	statTracker(path);

}

var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;

// 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 setBodyMargin() {
	if(document.body.offsetWidth % 2 == 1) {
		document.body.style.marginRight = "1px";
	} else {
		document.body.style.marginRight = "0";
	}
}

var userAge = 0;

// Newsletter Signup
function coppaAge () {

	// Set Minimum Age Limit
	var ageLimit = 13;

	var userAge = jQuery('#coppa_age').val();

	var reg = /^([a-zA-Z0-9_\-\.]+)@((([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4})(\]?)$/;
	var address = jQuery('#email_address').val();

	if (userAge < ageLimit) {
		jQuery("#newsletterForm").html('<h3>Sorry!</h3><p class="error">The Miniclip Newsletter is only available to players aged 13 years or over.</p>');
		cookie_create('coppaAge', userAge, 3); // Set a cookie to stop them from trying again
	} else {
		if ((reg.test(address) == false) || (userAge <= ageLimit)) {
			alert('Invalid Email Address');
		} else {
			//statTracker('/newsletter/signup/');
			jQuery ('#email_form').submit();
		}
	}

	return false;

}


/* 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 ($mc("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>';

					//$mc("toolbarPush").innerHTML = outputHtml;
					$mc("toolbarPush").innerHTML = '';
				}

			}
		}
	}
}

function reloadAvatar() {
	setTimeout('reloadAvatarReal()', 1500);
}

function reloadAvatarReal() {
	newSrc = $mc('loginbox_avatar').src + "&dc=" + (Math.random() * 10000000000000000);
	$mc('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 = $mc( '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 = $mc( '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 = $mc( "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 = $mc( "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 ($mc('homepageMonkey') != null) {
		$mc('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 ($mc('topTen') == null ) {
		return false;
	}

	var topTenItems = $mc('topTen').getElementsByTagName('li');

	for (var y = 0; y < topTenItems.length; y++) {
		topTenItems[y].id = 'topTenItem' + y;
		topTenItems[y].onmouseover = function() {
			tempTopTenItems = $mc('topTen').getElementsByTagName('li');
			for (var x = 0; x < topTenItems.length; x++) {
				tempTopTenItems[x].className = '';
				$mc(tempTopTenItems[x].id + 'Details').style.display = 'none';
			}
			this.className = 'active';

			$mc(this.id + 'Details').style.display = 'block';
		}
	}

}


/* Navigation v2 Stuff */

var showMoreStatus = false;

function showMoreNav() {

	var showMoreStatus = $mc('moreNavContent').className == "shown";

	if (showMoreStatus == true) {
		$mc('moreNavContent').className = "hidden";
		//$mc('moreNavShow').innerHTML = "More";
		$mc('moreNavShow').style.backgroundPosition = '0px 7px';
	} else {
		$mc('moreNavContent').className = "shown";
		//$mc('moreNavShow').innerHTML = "Less";
		$mc('moreNavShow').style.backgroundPosition = '0px -9px';
	}

	if ($mc('sideBar')) {

		var startHeight = 70;
		var wideActive = document.body.className.indexOf('bigVideo');

		if (showMoreStatus == true) {
			if (wideActive < 0) {
				$mc('sideBar').style.marginTop = '-' + startHeight + 'px';
			}

			showMoreStatus = false;
		} else {
			if (wideActive < 0) {
				$mc('sideBar').style.marginTop = '-' + ($mc('moreNavContent').offsetHeight + startHeight) + 'px';
			}

			showMoreStatus = true;
		}
	}

	return false;

}

var raptor = true;

function homepageBigAd() {
	jQuery('body').addClass('bigVideo');
	raptor = false;
}


// 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;
	}
}

function autoResize(id){

	var newheight;
	var newwidth;

	if(document.getElementById){
		newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
		newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
	}

	document.getElementById(id).height= (newheight) + "px";
	document.getElementById(id).width= (newwidth) + "px";
}


window.onbeforeunload = lobbyConfirmLeave;


// Game page share box
shareVisible = false;
hasHidden = false;

function linksInit () {

	jQuery('a[href^="http"]').each(function() {
		href = this.href.toLowerCase();
		if (href.indexOf('miniclip.com') >= 0 &&
			href.indexOf('www') == -1 &&
			href.indexOf('devcms') == -1 &&
			href.indexOf('icq') == -1 &&
			href.indexOf('cms') == -1 &&
			href.indexOf('ads') == -1 &&
			href.indexOf('support') == -1
			) {
			jQuery(this).click(function() {
				return trackLink(this.href);
			});
		}
	});

}


function trackLink (url) {
	_gaq.push(['_link', url]);
	return true;
}


// Simple Set Clipboard System
// Author: Joseph Huckaby

var ZeroClipboard = {

	version: "1.0.7",
	clients: {}, // registered upload clients on page, indexed by id
	moviePath: 'ZeroClipboard.swf', // URL to movie
	nextId: 1, // ID of next movie

	$: function(thingy) {
		// simple DOM lookup utility function
		if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
		if (!thingy.addClass) {
			// extend element with a few useful methods
			thingy.hide = function() {
				this.style.display = 'none';
			};
			thingy.show = function() {
				this.style.display = '';
			};
			thingy.addClass = function(name) {
				this.removeClass(name);
				this.className += ' ' + name;
			};
			thingy.removeClass = function(name) {
				var classes = this.className.split(/\s+/);
				var idx = -1;
				for (var k = 0; k < classes.length; k++) {
					if (classes[k] == name) {
						idx = k;
						k = classes.length;
					}
				}
				if (idx > -1) {
					classes.splice( idx, 1 );
					this.className = classes.join(' ');
				}
				return this;
			};
			thingy.hasClass = function(name) {
				return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
			};
		}
		return thingy;
	},

	setMoviePath: function(path) {
		// set path to ZeroClipboard.swf
		this.moviePath = path;
	},

	dispatch: function(id, eventName, args) {
		// receive event from flash movie, send to client
		var client = this.clients[id];
		if (client) {
			client.receiveEvent(eventName, args);
		}
	},

	register: function(id, client) {
		// register new client to receive events
		this.clients[id] = client;
	},

	getDOMObjectPosition: function(obj, stopObj) {
		// get absolute coordinates for dom element
		var info = {
			left: 0,
			top: 0,
			width: obj.width ? obj.width : obj.offsetWidth,
			height: obj.height ? obj.height : obj.offsetHeight
		};

		while (obj && (obj != stopObj)) {
			info.left += obj.offsetLeft;
			info.top += obj.offsetTop;
			obj = obj.offsetParent;
		}

		return info;
	},

	Client: function(elem) {
		// constructor for new simple upload client
		this.handlers = {};

		// unique ID
		this.id = ZeroClipboard.nextId++;
		this.movieId = 'ZeroClipboardMovie_' + this.id;

		// register client with singleton to receive flash events
		ZeroClipboard.register(this.id, this);

		// create movie
		if (elem) this.glue(elem);
	}
};

ZeroClipboard.Client.prototype = {

	id: 0, // unique ID for us
	ready: false, // whether movie is ready to receive events or not
	movie: null, // reference to movie object
	clipText: '', // text to copy to clipboard
	handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
	cssEffects: true, // enable CSS mouse effects on dom container
	handlers: null, // user event handlers

	glue: function(elem, appendElem, stylesToAdd) {
		// glue to DOM element
		// elem can be ID or actual DOM element object
		this.domElement = ZeroClipboard.$(elem);

		// float just above object, or zIndex 99 if dom element isn't set
		var zIndex = 99;
		if (this.domElement.style.zIndex) {
			zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
		}

		if (typeof(appendElem) == 'string') {
			appendElem = ZeroClipboard.$(appendElem);
		}
		else if (typeof(appendElem) == 'undefined') {
			appendElem = document.getElementsByTagName('body')[0];
		}

		// find X/Y position of domElement
		var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);

		// create floating DIV above element
		this.div = document.createElement('div');
		var style = this.div.style;
		style.position = 'absolute';
		style.left = '' + box.left + 'px';
		style.top = '' + box.top + 'px';
		style.width = '' + box.width + 'px';
		style.height = '' + box.height + 'px';
		style.zIndex = zIndex;

		if (typeof(stylesToAdd) == 'object') {
			for (addedStyle in stylesToAdd) {
				style[addedStyle] = stylesToAdd[addedStyle];
			}
		}

		// style.backgroundColor = '#f00'; // debug

		appendElem.appendChild(this.div);

		this.div.innerHTML = this.getHTML( box.width, box.height );
	},

	getHTML: function(width, height) {
		// return HTML for movie
		var html = '';
		var flashvars = 'id=' + this.id +
		'&width=' + width +
		'&height=' + height;

		if (navigator.userAgent.match(/MSIE/)) {
			// IE gets an OBJECT tag
			var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
			html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
		}
		else {
			// all other browsers get an EMBED tag
			html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
		}
		return html;
	},

	hide: function() {
		// temporarily hide floater offscreen
		if (this.div) {
			this.div.style.left = '-2000px';
		}
	},

	show: function() {
		// show ourselves after a call to hide()
		this.reposition();
	},

	destroy: function() {
		// destroy control and floater
		if (this.domElement && this.div) {
			this.hide();
			this.div.innerHTML = '';

			var body = document.getElementsByTagName('body')[0];
			try {
				body.removeChild( this.div );
			} catch(e) {
			;
			}

			this.domElement = null;
			this.div = null;
		}
	},

	reposition: function(elem) {
		// reposition our floating div, optionally to new container
		// warning: container CANNOT change size, only position
		if (elem) {
			this.domElement = ZeroClipboard.$(elem);
			if (!this.domElement) this.hide();
		}

		if (this.domElement && this.div) {
			var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
			var style = this.div.style;
			style.left = '' + box.left + 'px';
			style.top = '' + box.top + 'px';
		}
	},

	setText: function(newText) {
		// set text to be copied to clipboard
		this.clipText = newText;
		if (this.ready) this.movie.setText(newText);
	},

	addEventListener: function(eventName, func) {
		// add user event listener for event
		// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
		if (!this.handlers[eventName]) this.handlers[eventName] = [];
		this.handlers[eventName].push(func);
	},

	setHandCursor: function(enabled) {
		// enable hand cursor (true), or default arrow cursor (false)
		this.handCursorEnabled = enabled;
		if (this.ready) this.movie.setHandCursor(enabled);
	},

	setCSSEffects: function(enabled) {
		// enable or disable CSS effects on DOM container
		this.cssEffects = !!enabled;
	},

	receiveEvent: function(eventName, args) {
		// receive event from flash
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');

		// special behavior for certain events
		switch (eventName) {
			case 'load':
				// movie claims it is ready, but in IE this isn't always the case...
				// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
				this.movie = document.getElementById(this.movieId);
				if (!this.movie) {
					var self = this;
					setTimeout( function() {
						self.receiveEvent('load', null);
					}, 1 );
					return;
				}

				// firefox on pc needs a "kick" in order to set these in certain cases
				if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
					var self = this;
					setTimeout( function() {
						self.receiveEvent('load', null);
					}, 100 );
					this.ready = true;
					return;
				}

				this.ready = true;
				this.movie.setText( this.clipText );
				this.movie.setHandCursor( this.handCursorEnabled );
				break;

			case 'mouseover':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('hover');
					if (this.recoverActive) this.domElement.addClass('active');
				}
				break;

			case 'mouseout':
				if (this.domElement && this.cssEffects) {
					this.recoverActive = false;
					if (this.domElement.hasClass('active')) {
						this.domElement.removeClass('active');
						this.recoverActive = true;
					}
					this.domElement.removeClass('hover');
				}
				break;

			case 'mousedown':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('active');
				}
				break;

			case 'mouseup':
				if (this.domElement && this.cssEffects) {
					this.domElement.removeClass('active');
					this.recoverActive = false;
				}
				break;
		} // switch eventName

		if (this.handlers[eventName]) {
			for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
				var func = this.handlers[eventName][idx];

				if (typeof(func) == 'function') {
					// actual function reference
					func(this, args);
				}
				else if ((typeof(func) == 'object') && (func.length == 2)) {
					// PHP style object + method, i.e. [myObject, 'myMethod']
					func[0][ func[1] ](this, args);
				}
				else if (typeof(func) == 'string') {
					// name of function
					window[func](this, args);
				}
			} // foreach event handler defined
		} // user defined handler for event
	}

};

function icqBrandBar() {

	/* Set ICQ Background */
	document.body.style.backgroundColor = '#72c628';
	document.body.style.backgroundImage = 'url("/images/icq-branding/siteGreenBg.png")';
	document.body.style.backgroundPosition = 'center';
	document.body.style.backgroundRepeat = 'repeat-y';

	/* Construct ICQ Brand Bar */
	navCompiled = ('<ul>');
	navCompiled += ('<li class="icq-logo"><a href="http://www.icq.com">icq</a></li>');

	for (var i in navText) {
		navCompiled += ('<li><a href="' + navUrl[i] + '">' + navText[i] + '</a></li>');
	}

	navCompiled += ('</ul>');

	document.getElementById('icq-brandBar').innerHTML = navCompiled;

	/* Unhide ICQ Brand Bar */
	document.getElementById('icq-brandBar').style.display = 'block';

	hptoDisplay = true;

}


// Check for miniclip.com
if (typeof(window.location.hostname) != 'undefined' && window.location.hostname == 'miniclip.com') {

	// Supress all errors on production.
	window.onerror=function(){
		return true;
	}
}

//New Search Box
function siteSearchClear (div) {
	jQuery(div).css('color', '#000');

	if (jQuery(div).val() == '') {
		jQuery(div).css('color', '#aaa');
	}
}

function siteSearchFocus(div) {
	if (jQuery(div).val() == "Search") {
		jQuery(div).focus();
		return false;
	}
}

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;
	}
}



// Code moved here from notification.js
/*
    Example data structure:
    var data = [{
        id: 1,
        excerpt: 'Hello, this is notification number one!',
        message: 'message',
        button: {
            link: 'http://www.google.com',
            'target': '_blank',
            'label': 'label'
        },
        icon: 'exclamation'
    }, {
        id: 2,
        excerpt: 'Merry Christmas',
        message: 'and happy new year',
        button: {
            link: 'http://www.whazzup.com',
            'target': '_blank',
            'label': 'label'
        },
        icon: 'exclamation'
    }];
 */

//hack to avoid running problematic jQuery stuff for games list and notification bar in webgame iframes - breaks IE
if (this.location.href.indexOf('webgame.php') == -1) {
	// we have to declare this globally
	var closed_notifications;

	jQuery(document).ready(function() {

		jQuery('.fullgameslist div.toggle').click(function() {
			container = jQuery(this).attr('rel');
			jQuery(this).toggleClass('show');
			jQuery(container).slideToggle();
			cookie_name = 'm' + container.replace('#', '')

			if (jQuery(this).text() == 'Show') {
				// display the container
				jQuery(this).text('Hide');
				cookie_create(cookie_name, 0, 99);
			} else {
				// hide the container
				jQuery(this).text('Show');
				cookie_create(cookie_name, 1, 99);
			}
		});
		jQuery('#moreNavShow').click(function() {
			showMoreNav();
			return false;
		});

		// only do this if not in frameset
		if (top == self) {
			jQuery('#siteSearch').focus();
		}

		displayNotificationBar = true;
		// if its not an iframe
		if (window.location != window.parent.location) {
			displayNotificationBar = false;
		}

		if (toolbarHomepageTakeover == true) {
			displayNotificationBar = false;
		}

		if (displayNotificationBar == true) {

			jQuery.getJSON('/php/services/notification.php', function(data)
			{
				closed_notifications = cookie_read('closed_notifications');
				if (closed_notifications){
					closed_notifications = closed_notifications.split(',');
				} else {
					closed_notifications = [];
				}

				var temp = [];
				var d_len = data.length;
				for (var d=0; d<d_len; d++){
					if (!in_array(data[d].id, closed_notifications)){
						temp.push(data[d]);
					}
				}
				data = temp;

				if (data.length > 0){
					renderNotification(data[0]);
				}
			});

		}
		
		// remove games in certain territories
		var exclude_list = new Array(
			'AL', 'AD', 'AT', 'BE', 'BA', 'BG',
			'HR', 'CZ', 'DK', 'EE', 'FI', 'FR',
			'DE', 'GR', 'HU', 'IS', 'IE', 'IT',
			'LV', 'LI', 'LT', 'LU', 'MK', 'MT',
			'MC', 'ME', 'NL', 'NO', 'PL', 'PT',
			'RO', 'SM', 'CS', 'SK', 'SI', 'ES',
			'SE', 'CH', 'TR', 'UK', 'GB'
		);
		if (jQuery.inArray(cookie_read('ipLocation'), exclude_list) > 0) {
			jQuery('.game_id_2071').remove();
			jQuery('.game_id_2481').remove();			
		}
	});
//end of jQuery hiding from webgame iframes
}

function renderNotification(data) {
	// create html for the notification
	var html = '';
	html += '<div class="siteNotification" id="notification_' + data.id + '">';
	html += '   <div class="icon"><img width="18" height="19" src="/images/sitenotification/announcement_icon_' + data.icon + '.png" /></div>';
	html += '   <div class="close"><a href="#">Close</a></div>';
	//html += '   <div onClick="readFull()" class="container">';
	html += '   <div class="container">';
	html += '       <span class="excerpt">' + data.excerpt + '</span>';
	// html += '       <span class="full">' + data.message + '<br />';

	if (typeof data.link != 'undefined' && data.link != null) {
		html += '       <a class="button" href="' + data.link + '" target="' + data.target + '">' + data.label + '</a>';
	}
	// html += '       </span>';
	html += '   </div>';
	html += '</div>';
	jQuery('body').prepend(html);

	// and bind click event to close button
	jQuery('.close').bind('click', function(){
		var id = jQuery(this).closest('.siteNotification').attr('id').replace('notification_', '');
		jQuery('#notification_' + id).slideUp("slow", function(){
			jQuery(this).remove();
		});

		if (!in_array(id, closed_notifications)){
			closed_notifications.push(id);
		}

		cookie_create('closed_notifications', closed_notifications.join(','), 10);
		statTracker('binary/games/notification/'  + data.id + '/click/close/');
	});

	jQuery('#notification_' + data.id + ' .container a').click(function(){
		statTracker('binary/games/notification/'  + data.id + '/link/click/' + jQuery(this).attr('href'));
	});

	statTracker('binary/games/notification/'  + data.id + '/impression/');
}

function readFull() {
/*jQuery(".siteNotification .excerpt").fadeOut("slow", function(){
		jQuery(".siteNotification .full").fadeIn();
	});*/

//statTracker('binary/games/notification/read_full/click/');
}

function in_array (needle, haystack) {
	var key = '';
	for (key in haystack) {
		if (haystack[key] == needle) {
			return true;
		}
	}
	return false;
}

function isNumber(n)
{
	return !isNaN(parseFloat(n)) && isFinite(n);
}

var _enabledws = ['devcms', 'cmsftl', 'webmad60', 'webmad61', 'webmad62', 'webmad63', 'webmad64', 'webmad65'];
function initActivity()
{
	if (typeof _webserver == 'undefined') {
	} else {
		var enabled = false;

		/*for (i in _enabledws) {
            if (_enabledws[i] == _webserver) {
                enabled = true;
            }
        }*/
		var part = _webserver.replace(/webmad|webftl/, "");

		if (isNumber(part) && part%2 == 0) {
			enabled = true;
		} else {
			if (_webserver == 'devcms' || _webserver == 'cmsftl') {
				enabled = true;
			}
		}
		enabled = true;
		if (enabled) {

			jQuery.ajax({
				url: "/php/services/activity.php" //+ new Date().getTime()
			});
			setInterval(function() {
				jQuery.ajax({
					url: "/php/services/activity.php" //+ new Date().getTime()
				});
			}, 60000);
		}
	}
}


// SS Fan Art
function initSSFanArt(game_id) {
	// only do this if the animation is available
	if ($mc('fan_art_container') == null) {
		return false;
	}

	// set params to send
	var req_data = {
		game_id: game_id
	}

	// request fan art template from sketch-star
	jQuery.ajax({
		url: '/sketch-star/ss-lib/ajax.php?action=getGameFanPage',
		data:     req_data,
		dataType: 'html',
		success: function (fan_art_html, textStatus, jqXHR)
		{
			if (fan_art_html) {
				$mc('fan_art_container').innerHTML = fan_art_html;
			}
		}
	});
}

// SS Homepage Module
function initHomepage() {
	// only do this if the animation is available
	if ($mc('ss_external_homepage') == null) {
		return false;
	}

	// request fan art template from sketch-star
	jQuery.ajax({
		url: '/sketch-star/ss-lib/ajax.php?action=getHomepageModule',
		dataType: 'html',
		success: function (homepage_html, textStatus, jqXHR)
		{
			if (homepage_html) {
				$mc('ss_external_homepage').innerHTML = homepage_html;
			}
		}
	});
}
addLoadEvent(initHomepage);


/*
 * Facebook stuffs
 */

function sendPost(trigger, data)
{
	return null;
}

function fb_login(ingame){
	FB.login(function(response) {
		if (response.authResponse) {
			if (response.status == "connected") {
				// user is logged in and granted some permissions. Perms is a comma separated list of granted permissions
				if(ingame == false || ingame == 'false'){
					// call flash function to say php is handling the request
					notifyFlash(response.authResponse.accessToken);
					// redirect user to success page and set cookie to redirect back to
					cookie_create('fblogin_redirect_location', document.URL, 1);
					window.location = '/players/en/facebook-success.php?fb_token=' + response.authResponse.accessToken;
					
				} else {
					// send the token to flash - it's an ingame login and we dont want to refresh
					notifyFlash(response.authResponse.accessToken);
				}

			// logged in to facebook and granted permissions
			} else {
			// user is logged in to facebook, but did not grant any permissions
			}
		} else {
		// user is not logged in to facebook
		}
	}, {
		scope:'publish_stream,email,user_birthday,offline_access'
	});

	refreshToolbar();
}

function notifyFlash(token){
	var flashHandle = null;

	if (typeof(jQuery('.loginBox embed, .loginBox object')[0]) != 'undefined' && typeof(jQuery('.loginBox embed, .loginBox object')[0].notifyFacebookConnected) != 'undefined') {
		flashHandle = jQuery('.loginBox embed, .loginBox object')[0];
	} else if(typeof(jQuery('#leagueInfo embed, #leagueInfo object')[0]) != 'undefined' && typeof(jQuery('#leagueInfo embed, #leagueInfo object')[0].notifyFacebookConnected) != 'undefined') {
		flashHandle = jQuery('#leagueInfo embed, #leagueInfo object')[0];
	} else if (typeof(jQuery('#flashCommsWrapper object, #flashCommsWrapper embed')[0]) != 'undefined' && typeof(jQuery('#flashCommsWrapper object, #flashCommsWrapper embed')[0].notifyFacebookConnected) != 'undefined') {
		flashHandle = jQuery('#flashCommsWrapper object, #flashCommsWrapper embed')[0];
	}

	if(flashHandle != null){
		flashHandle.notifyFacebookConnected(token);
	}
}

function shareExpander() {
	if (shareVisible == true) {
		document.getElementById('game-controls').style.display = 'block';
		document.getElementById('game-description').style.display = 'block';
		document.getElementById('share-expandable').style.display = 'none';
		document.getElementById('share-button').className = '';
		shareVisible = false;
		hasHidden = true;
	//statTracker('/share-box/views/closed/');
	} else {
		document.getElementById('game-controls').style.display = 'none';
		document.getElementById('game-description').style.display = 'none';
		document.getElementById('share-expandable').style.display = 'block';
		document.getElementById('share-button').className = 'active';
		shareVisible = true;
		//statTracker('/share-box/views/opened/');

		if (hasHidden == false) {
			clipEmail.setText(location.href);
			clipEmail.glue('copy-button-email');
			clipIM.setText(location.href);
			clipIM.glue('copy-button-im');
		}
	}
	return false;
}


function refreshToolbar () {
	if (typeof IsToolbarInstalled == 'function') {
		if (IsToolbarInstalled('CT3067892')) {
			var gamebar = new TPI.Toolbar('CT3067892');
			gamebar.Refresh();
		}
	}
}

jQuery(document).ready(function() {
	
	function copyButton(buttonId) {
		jQuery('#'+buttonId).html('Copied').css({
			'background-color': '#B2E57F',
			'color': '#006600',
			'border-color': '#006600'
		});
				
		jQuery('#'+buttonId).delay(2000).animate({
			backgroundColor: '#FF7C00',
			color: '#FF7C00'
		}, 500, function() {
			jQuery('#'+buttonId).html('Copy');
			jQuery('#'+buttonId).css({
				'border-color': '#000000'
			});
			
		});
		
		jQuery('#'+buttonId).animate({
			color: '#FFFFFF'
		}, 500);
	}
	
	jQuery('#webmaster-button').click(function() {
		
		expandable_open = jQuery('.expandables').is(':visible');
		webmaster_open = jQuery('.webmaster-expandable').is(':visible');
		
		jQuery('.expandables').hide();
		jQuery('#game-controls').hide();
		jQuery('#game-description').hide();
			
		if (webmaster_open) {
			jQuery('#game-controls').show();
			jQuery('#game-description').show();
			clipEmbed.destroy();
			clipIcon.destroy();
		} else {
			jQuery('.webmaster-expandable').show();
			
			ZeroClipboard.setMoviePath( '/swfcontent/zeroClipboard.swf' );
			
			var clipEmbed = new ZeroClipboard.Client();
			var clipIcon = new ZeroClipboard.Client();
			
			var embed = jQuery('#EmbedCode').text();
			var icon = jQuery('#IconCode').text();
			
			clipEmbed.setText(embed);
			clipEmbed.addEventListener( 'mouseUp', function(client) { 
				jQuery('#EmbedCode').select();
				copyButton('copy-button-embed');
				
			});
			clipEmbed.glue('copy-button-embed');
			
			clipIcon.setText(icon);
			clipIcon.addEventListener( 'mouseUp', function(client) { 
				jQuery('#IconCode').select();
				copyButton('copy-button-icon');
			});
			
			clipIcon.glue('copy-button-icon');
		}
		
	});
	
	jQuery('#share-button').click(function() {
		
		expandable_open = jQuery('.expandables').is(':visible');
		share_open = jQuery('#share-expandable').is(':visible');
		
		jQuery('.expandables').hide();
		jQuery('#game-controls').hide();
		jQuery('#game-description').hide();
			
		if (share_open) {
			jQuery('#game-controls').show();
			jQuery('#game-description').show();
			clipEmail.destroy();
			clipIM.destroy();
		} else {
			jQuery('#share-expandable').show();
			
			ZeroClipboard.setMoviePath( '/swfcontent/zeroClipboard.swf' );
			
			var clipEmail = new ZeroClipboard.Client();
			var clipIM = new ZeroClipboard.Client();
			
			clipEmail.setText(location.href);
			clipEmail.addEventListener( 'mouseUp', function(client) { 
				jQuery('#copy-email').select();
				copyButton('copy-button-email');
			});
			clipEmail.glue('copy-button-email');
			
			clipIM.setText(location.href);
			clipIM.addEventListener( 'mouseUp', function(client) { 
				jQuery('#copy-im').select();
				copyButton('copy-button-im');
			});
			clipIM.glue('copy-button-im');
		}
		
	});
//	jQuery('#share-button').click(function() {
//		jQuery('.expandables').hide();
//		if (share_visible == true) {
//			jQuery('#game-controls').show();
//			jQuery('#game-description').show();
//			share_visible = false;
//		} else {
//			jQuery('#game-controls').hide();
//			jQuery('#game-description').hide();
//			jQuery('#share-expandable').show();
//			share_visible = true;
//		}
//		webmaster_visible = false;
//	});
//
//	ZeroClipboard.setMoviePath('/swfcontent/zeroClipboard.swf');
//	var copyEmbed = new ZeroClipboard.Client();
//	copyEmbed.setHandCursor(true);
//	copyEmbed.addEventListener('onMouseUp', function () {
//		alert('Copied to clipboard');
//	});
//	copyEmbed.glue('#CopyEmbed');
//
//	jQuery('#EmbedCode').focus(function() {
//		this.select();
//	});
//	jQuery('#IconCode').focus(function() {
//		this.select();
//	});
});


var showcase_display = true;
var showcase_cookie = 'showcase_display';

function showcase_viewer () {

	statTracker ('/advertising/js_showcase/view/');
	setTimeout ('showcase_display_button()', 2500);

}


function showcase_display_button () {

	if (jQuery('#showcase_container object, #showcase_container embed').length <= 0) {
		jQuery('#showcase_container').remove ();
		return;
	}

	showcase_display = cookie_read (showcase_cookie);

	showcase_close_button = jQuery ('<span id="showcase_close">X</span>');
	showcase_close_button.click (function() {
		
		statTracker ('/advertising/js_showcase/close/' + cookie_read('ipLocation') + '/');
		
		if (mcto.showcaseTrackCloseUrl != undefined) {
			adTracker (mcto.showcaseTrackCloseUrl);
		}
				
		cookie_create_time (showcase_cookie, 1, 4 * 60);
		showcase_create_open_button ();

		jQuery ('#showcase_container').animate ({
			height:0
		},
		200,
		function () {
			jQuery('#showcase_container object, #showcase_container embed, #showcase_container div').remove();
		});

		jQuery (this).remove ();

	});

	jQuery ('#showcase_container').append (showcase_close_button);

}


function showcase_create_open_button () {

	showcase_open_button = jQuery ('<div id="showcase_open"><a href=""><div id="showcase_open_arrow"></div>Show Ad</a></div>');
	showcase_open_button.find ('a').click (function() {

		statTracker ('/advertising/js_showcase/open/' + cookie_read('ipLocation') + '/');
		cookie_erase (showcase_cookie);
		window.location.reload ();
		return false;

	});
	jQuery ('#showcase_container').after (showcase_open_button);

}


function plusOneCallback(response){
	if(response.state == 'on'){
		jQuery.ajax({
			type: 'POST',
			url: '/php/services/google/award/add.php'
		});
	} else {
		jQuery.ajax({
			type: 'POST',
			url: '/php/services/google/award/remove.php'
		});
	}
}

// back-compat! DO NOT REMOVE! (ask Kieran first)
function attachTracking()
{

}

//hack to avoid running problematic jQuery stuff for gamebar in webgame iframes - breaks IE
if (this.location.href.indexOf('webgame.php') == -1) {
	//check if the toolbar needs to be refreshed following a login
	jQuery(document).ready(function() {
		// check if a refresh toolbar cookie has been set
		if (cookie_read('refresh_toolbar') == '1' || cookie_read('refresh_toolbar') == 1) {
			// remove cookie so toolbar will not be refreshed
			cookie_erase('refresh_toolbar');
			// create a new one with a new value, expires in 1 day
			var d = new Date();
			d.setTime(d.getTime() + 86400);
			document.cookie = "refresh_toolbar=0; expires=" + d.toGMTString() + "; path=/; domain=." + document.domain;
			// if possible  refresh the toolbar
			if (typeof RefreshToolbarByCTID == 'function') {
				// refresh miniclip toolbar
				RefreshToolbarByCTID('CT3067892');
			}
		}
	});
}


jQuery(document).ready(function($) {

	// url
	var url     = '/php/services/user/favourites.php'

	$("#fav-toggle").click(function() {

		// game id
		var parent  = $(this).parent();
		var game_id = $(this).data("id");
		var state   = parent.hasClass("selected");
		var action  = state ? 'remove' : 'add';
		var nonce   = $(this).data("token");

		var toolbar     = new TPI.Toolbar("CT3067892");
		var ret         = toolbar.IsVisible();
		
		platform = window.navigator.platform;
		if (platform != 'MacIntel' && platform != 'MacPPC') {
			var gamebar_link = 'http://ie.conduit-download.com/92/306/CT3067892/Downloads/CT3067892_miniclip.exe';
		} else {
			var gamebar_link = 'http://miniclip.ourtoolbar.com/exe';
		}
		
		var msg_html    = $('<div id="Gamebar_message" class="favorite_message" style="clear:both">You need to be logged in to the Miniclip Gamebar to store your favourite games! Get it <a href="'+gamebar_link+'" class="click_area" style="font-weight:bold;">here</a></div>');

		//msg_html.hide();

		// is it available
		if(!ret.returnValue || !game_id) {
			if ($(".favorite_message").length > 0) {

			} else {
				$("#game-info").prepend(msg_html);

			}

			return false;
		} else {

			$.ajax({
				type: "POST",
				url: url,
				data: {
					"game_id" : game_id, 
					"action" : action, 
					"nonce" : nonce
				},
				success: function(data) {
					if (data.status == true) {

						if (action == 'add') {
							parent.addClass("selected");
							$("#fav-toggle").text("Remove from Favorites");
						} else {
							parent.removeClass("selected");
							$("#fav-toggle").text("Add to Favorites");
						}

						// if possible  refresh the toolbar
						if (typeof RefreshToolbarByCTID == 'function') {
							// refresh miniclip toolbar
							RefreshToolbarByCTID('CT3067892');
						}

					}
				},
				dataType: "json"
			});
		}

		return false;
	});

/*
	// easter egg
	jQuery(document).keyup(function(event) {
		if (event.which == 27) {
			// if boss button doesn't exist then drop it in
			if (jQuery('#boss_button').length == 0) {
				bossDiv = jQuery ('<div id="boss_button" style="position:fixed; top:0; left:0; width:100%; height:100%; background:url(/images/boss-button.png) top left no-repeat #eee; display:none;">&nbsp;</div>');
				jQuery('body').append (bossDiv);
				messageDiv = jQuery ('<div id="boss_message" style="border:2px solid #fff; z-index:999; color:#fff; position:fixed; top:100px; left:50%; width:400px; margin-left:-216px; background:#09f; font-size:16px; padding:15px;">Press the \'Escape Key\' to return to Miniclip</div>');
				jQuery('body').append (messageDiv);
			}
			
			if (jQuery('#wrapper').css('visibility') == 'hidden') {
				jQuery('#wrapper,embed,object,iframe').css('visibility', 'visible');
				statTracker ('/easter/boss-button/turn-off/');				
			} else {
				jQuery('#wrapper,embed,object,iframe').css('visibility', 'hidden');
				jQuery('#boss_message').show().delay(2000).fadeOut();
				statTracker ('/easter/boss-button/turn-on/');
			}

			// toggle boss button - defaults to hidden so can always be toggled
			jQuery('#boss_button').fadeToggle ();
			// toggle everything else
			jQuery('#footer').toggle ();
			jQuery('#extraFooter').toggle ();
			
			// delete gamebar stuff - not ideal, but can be removed in the future
			jQuery('#conduit_toolbar_promostrip').remove ();
		}
	})*/
});


jQuery(document).ready(function() {
	jQuery('.query').focus(function() {
		jQuery(this).val('');
	});
//	jQuery('.query').blur(function() {
//		var queryString = jQuery(this).val();
//		if (queryString == '') {
//			jQuery(this).val('Search');
//		}
//	});
});
