var mx;
var my;
var checkMenuLayer = false;
var htmlScriptSeparatorString = "|HTML_SCRIPT_SEPARATOR|";

// forces the levelsystem flash to poll getEvents.php immediately and not wait until it's time to poll again
function doPoll() {
	sendPollEvent('<event_refresh />');
}

// called by the levelsystem flash when it detects that the user credits has changed from the last poll
function onUserCreditsUpdateFromServer(currentCredits) {
	$("#currentUserCreditsSpan").text(currentCredits);
}

// Functions to get browser scroll and width/height
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
	n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function getFlashById(id) {
	var flashObject = document[id];
	return flashObject;
}


function setFlashHeight(id, height) {
	var flashMovie = document.getElementById(id);
	if (flashMovie != null) {
		flashMovie.height = height + "px";
	}
}

function setFlashWidth(id, width) {
	var flashMovie = document.getElementById(id);
	if (flashMovie != null) {
		flashMovie.width = width + "px";
	}
}

function getClientHeight() {
	return $(window).height();
}

function getClientWidth() {
	return $(window).width();
}


function getScrollTop() {
	return f_filterResults (window.pageYOffset ? window.pageYOffset : 0, document.documentElement ? document.documentElement.scrollTop : 0, document.body ? document.body.scrollTop : 0);
}

function getScrollLeft() {
	return f_filterResults (window.pageXOffset ? window.pageXOffset : 0, document.documentElement ? document.documentElement.scrollLeft : 0, document.body ? document.body.scrollLeft : 0);
}

function lockPage() {
	// Draw div over entire page to avoid pressing on keys while the layer is loading
	var lockdiv = document.createElement('div');
	lockdiv.setAttribute('id', "lockPageDiv");

	// TODO: Fix positioning for IE and make div come out on top in IE
	if (document.all) {
		lockdiv.style.width    = "100%";
		lockdiv.style.height   = "100%";
	}
	else {
		lockdiv.style.width    = document.documentElement.clientWidth;
		lockdiv.style.height   = document.documentElement.clientHeight;
	}

	lockdiv.style.overflow    = "hidden";
	lockdiv.style.position    = "absolute";
	lockdiv.style.left        = "0px";
	lockdiv.style.top         = "0px";

	document.body.appendChild(lockdiv);
}

function unlockPage() {
	elements = document.getElementsByClassName("dialog-mask");
	if (elements) {
		for (var n=0;n<elements.length;n++) {
			elements[n].style.display = "none";
		}
	}
}

// Mouse move tracker
if (document.all || document.getElementById) {
	document.onmousemove = mouse_move;
}
else if (document.layers) {
	window.captureEvents(Event.MOUSEMOVE);
	window.onMouseMove = mouse_move;
}

// Called when the logout button is clicked to halt polling (because if the redirect when logging out is not happening immediately a poll can happen which will result in a session lost message
function killPolling() {
	var flashObject = getFlashById("levelsystem");
	if (flashObject && flashObject.kill != undefined) {
		flashObject.kill();
	}
}

function openWindow(winId, page, parameters, width, height)
{
	window.open(page+parameters,winId, 'resizable=yes,toolbar=no,scrollbars=yes,width='+width+',height='+height+',top=0,left=0');
}

function goToPage(link) {
	location.href=link;
}

function calcInputCharsLeft(inputField, charsLeftSpan, maxChars) {
	if (inputField.value.length > maxChars) {
		inputField.value = inputField.value.substring(0, maxChars);
	}
	document.getElementById(charsLeftSpan).innerHTML = (maxChars - inputField.value.length);
}

function iframeGoToPage(objectName, link)
{
	var isInternetExplorer = (document.all) ? true : false;
	var ns6_mozilla = (document.getElementById) ? true : false;
	if (isInternetExplorer) {
		var object = eval("document."+objectName);
		object.location=link;
	}
	else if (ns6_mozilla) {
		var object = document.getElementById(objectName);
		object.src=link;
	}
}

function iframeResize(objectName, width, height)
{
	var isInternetExplorer = (document.all) ? true : false;
	var ns6_mozilla = (document.getElementById) ? true : false;
	if (isInternetExplorer) {
		var object = document.all[objectName];
		object.width=width+"px";
		object.height=height+"px";
	}
	else if (ns6_mozilla) {
		var object = document.getElementById(objectName);
		object.width=width+"px";
		object.height=height+"px";
	}
}

function switchClassName(id, newClass) {
	document.getElementById(id).className = newClass;
}

function showLayerMessageWindow(msg, title, trackMouse, xOffset, yOffset) {
	if (!title) {
		title = "";
	}
	openLightBox(350, title, msg);
}

function layer_move(layer, x, y)
{
	if (document.all) {
		document.all[layer].style.pixelLeft=x;
		document.all[layer].style.pixelTop=y;
	}
	else if (document.layers) {
		document.layers[layer].left = x;
		document.layers[layer].top = y;
	}
	else if (document.getElementById) {
		document.getElementById(layer).style.left=x+"px";
		document.getElementById(layer).style.top=y+"px";
	}
}

function layer_move_y(layer, y)
{
	if (document.all)
	document.all[layer].style.pixelTop=y;
	else if (document.layers)
	document.layers[layer].top = y;
	else if (document.getElementById)
	document.getElementById(layer).style.top=y;
}

function mouse_move(ev)
{
	if (document.all) {
		mx = window.event.clientX + getScrollLeft();
		my = window.event.clientY + getScrollTop();
	}
	else if (document.layers || document.getElementById) {
		mx = ev.pageX;
		my = ev.pageY;
	}

	if (checkMenuLayer) {
		if($("#popbox").length>0) {
			checkBox("popbox", {offsetTop: 30});
		}
		else {
			checkBox("userMenuLayer");
		}
	}
}

function layer_write(layer, str, append) {
	str = html_entity_decode(str);
	if (document.getElementById) {
		if (document.getElementById(layer)) {
			if (append != null) {
				document.getElementById(layer).innerHTML += str;
			}
			else {
				document.getElementById(layer).innerHTML= str;
			}
		}
	}
	else if(document.all) {
		if (document.all(layer)) {
			if (append != null) {
				document.all(layer).innerHTML += str;
			}
			else {
				document.all(layer).innerHTML= str;
			}
		}
	}
}

function layer_hide(layer) {
	if (document.getElementById && document.getElementById(layer)) {
		document.getElementById(layer).style.visibility = "hidden";
	}
}

function layer_show(layer) {
	if (document.getElementById && document.getElementById(layer)) {
		document.getElementById(layer).style.visibility = "visible";
	}
}

function changeImageSrc(imageName, newSrc)
{
	if(document.images)
	document.images[imageName].src = newSrc;
	else if(document.all)
	document.all(imageName).src = newSrc;
	else if(document.getElementById)
	document.getElementById(imageName).src = newSrc;
}

function buttonChangeClass(buttonID, buttonClass)
{
	if(document.all) {
		document.all('button_'+buttonID+'_left').className = buttonClass+'_left';
		document.all('button_'+buttonID+'_middle').className = buttonClass+'_middle';
		document.all('button_'+buttonID+'_right').className = buttonClass+'_right';
	}
	else if(document.getElementById) {
		document.getElementById('button_'+buttonID+'_left').className = buttonClass+'_left';
		document.getElementById('button_'+buttonID+'_middle').className = buttonClass+'_middle';
		document.getElementById('button_'+buttonID+'_right').className = buttonClass+'_right';
	}
}

function submitForm(formName)
{
	if(document.all)
	document.all(formName).submit();
	else if(document.getElementById)
	document.getElementById(formName).submit();
}

function md5Login(f) {
	var lf = document.forms["login"];
	var lf2 = document.forms["logindata"];
	md5c = lf['md5c'].value;
	lf['md5c'].value = "";
	username = lf2['username'].value;
	password = lf2['password'].value.toLowerCase();
	try {
		lf['logindata[md5]'].value = hex_hmac_md5(md5c, password);
		lf['logindata[username]'].value = username;
	}
	catch(error) {
		alert("There was a client problem when logging in: " + error.description + "\\nPlease report this to info@powerchallenge.com\\n");
		return false;
	}
	lf.submit();
	return false;
}

function calculateCountDown(now, then) {
	var date = new Date(now);
	var end = new Date(then);
	var seconds = Math.floor(end.getTime() - date.getTime());

	if (seconds < 0)
	return -1;

	var minutes = Math.floor(seconds / 60);
	seconds = Math.floor(seconds - (minutes*60));
	var hours = Math.floor(minutes/60);
	minutes = Math.floor(minutes - (hours*60));
	var days = Math.floor(hours/24);
	hours = Math.floor(hours - (days*24));
	//  var months = Math.floor(days/30);
	//  days = Math.floor(days - (months*30));
	//  var years = Math.floor(months/12);
	//  months = Math.floor(months - (years*12));

	var time = new Array();
	//  time['years'] = years;
	//  time['months'] = months;
	time['days'] = days;
	time['hours'] = hours;
	time['minutes'] = minutes;
	time['seconds'] = seconds;

	return time;
}

iframes_regular = new Array();

function disableBanners() {
	var iframes = document.getElementsByTagName("IFRAME");
	for(var i=0; i<iframes.length; i++) {
		if (isLikelyIframeBanner(iframes[i].name)) {
			if (iframes[i].src.indexOf("blank.html") == -1) {
				iframes_regular[iframes[i].name] = iframes[i].src;
				iframes[i].src = "blank.html";
				iframes[i].style.visibility = "hidden";
			}
		}
	}

	// hide all divs named BANNER_WRAPPER (we don't use getElementsByName() because that is not officially supported for div elements).
	var bannerWrappers = getElementsByTagAndName("DIV", "BANNER_WRAPPER");
	for(var i=0; i<bannerWrappers.length; i++) {
		bannerWrappers[i].style.visibility = "hidden";
	}
}

function enableBanners() {
	//--- if a lightbox is open, never enable banners (they will be enabled automatically when the last lightbox is closed)
	if ($.weeboxs.length()) {
		return;
	}

	var iframes = document.getElementsByTagName("IFRAME");
	for(var i=0; i<iframes.length; i++) {
		if (isLikelyIframeBanner(iframes[i].name)) {
			iframes[i].src = iframes_regular[iframes[i]["name"]];
			iframes[i].style.visibility = "visible";
		}
	}

	// show all divs named BANNER_WRAPPER
	var bannerWrappers = getElementsByTagAndName("DIV", "BANNER_WRAPPER");
	for(var i=0; i<bannerWrappers.length; i++) {
		bannerWrappers[i].style.visibility = "visible";
	}
}

function getElementsByTagAndName(tag, name) {
	var foundElements = new Array();
	var tagList = document.getElementsByTagName(tag);
	for(var i=0; i<tagList.length; i++) {
		var nameValue = tagList[i].getAttribute("name");
		if(nameValue == name) {
			foundElements.push(tagList[i]);
		}
	}
	return foundElements;
}

function isLikelyIframeBanner(name) {
	if (name.substr(0,1) == 'a' && name.length == 8)
	return true;
	return false;
}

function hideSelects() {
	var selects = document.getElementsByTagName("SELECT");
	for(var i=0; i<selects.length; i++) {
		selects[i].style.display = 'none';
	}
}

function showSelects() {
	var selects = document.getElementsByTagName("SELECT");
	for(var i=0; i<selects.length; i++) {
		selects[i].style.display = '';
	}
}

function findObjectByName(objectname, list) {
	for (var i = 0; i < list.length; i++)
	if (list[i].name == objectname)
	return list[i];
	return null;
}

function clearSelect(select) {
	while (select.options.length > 0)
	select.options[0] = null;
}

function showAuthentificationLayer(redirect_url)
{
	var width   = 600;
	var header  = 'Authentification Required';

	var content = '<span id="authentification_layer"><img src="img/trans.gif" width=600 height=1></span>';
	var opacity = 'overlay';
	// TODO: Make y placement depend on window size
	var posX    = document.documentElement.clientWidth/2 - 210;
	var posY    = 250;
	var delParam = "";//'<a href="#" onclick="javascript: ajaxCall(\'com/authenticated/ajax/notifyCom.php\', \'val=clearRewards\', \'writeLayer\', \'reward_layer\');"><img title=\''+str_delete_button+'\'src=\'img/trashcan.gif\' border=0></a>';

	lightboxShow(width, header, content, opacity, delParam, "", "button_small_red_white", null);

	ajaxCall('com/authenticated/ajax/notifyCom.php', 'val=getAuthentificationRequest&redirect_url='+redirect_url, 'writeLayer', 'authentification_layer');
	unlockPage();
}

function showChallengeInactiveLayer()
{
	var width = 250;

	var header = "";
	var content = '<span id="challenge_inactive_layer">You need to perform a version check before you can challenge or be challenged. <a href="?p=version_check">Do version check now.</a></span>';
	var opacity = 'none';
	var posX    = -250;
	var posY    = 0;
	var relToMouse = 1;

	openLightBox(width, header, content, opacity, posX, posY, relToMouse, "", "light_", "button_special_x_white");
}

function showChatSettingsMenu() {
	ajaxCall('com/authenticated/ajax/com.php', 'val=loadChatSettingsItems', 'ajax_openSettingsMenu', '');
}

function ajax_openSettingsMenu(readyState, response, responseParameter) {
	if (readyState == 1) {
		showGeneralMouseMenu(new Array(), "", true);
	}
	else if (readyState == 4) {
		try {
			var responseArray = eval(response);
			var menuTitle = responseArray[0];
			var menuItems = responseArray[1];
		}
		catch(error) {
			var menuTitle = "Server Error: ";
			var menuItems = new Array(new Array("text", error));
		}
		showGeneralMouseMenu(menuItems, menuTitle, false);
	}
}

/* PowerWindow uses an array set by phpclass: Lightbox */
function powerwindow(id) {

	$.weeboxs.open(
	html_entity_decode(LightboxArr[id]['content'])
	,
	{
		title: LightboxArr[id]['title'],
		width: LightboxArr[id]['width'],
		onopen: LightboxArr[id]['onOpen'],
		onclose: LightboxArr[id]['onCloseButtonClick']
	}
	);
}

function powerwindowByIdString(id, openedAutomatically) {
	// if opening the lightbox was triggered automatically, do not open it if a lightbox is already open
	if (openedAutomatically && $.weeboxs.length()) {
		return;
	}

	for (var i=0;i<LightboxArr.length;i++) {
		if (LightboxArr[i]["id"] == id) {
			powerwindow(i);
			break;
		}
	}
}

function doGATrack( trackID ) {
	function deleteDoubleSlashes(input)
	{
		s = input.replace("//", "/");
		while(s != input)
		{
			input = s;
			s = input.replace("//", "/");
		}

		return s;
	};

	if (typeof(pageTracker) != "undefined") {
		finalID = trackID;
		if( typeof(trackIDPrefix) == "string" )
		finalID = trackIDPrefix + finalID;

		finalID = deleteDoubleSlashes(finalID);
		pageTracker._trackPageview(finalID);
	}
}

function trackPageView( page ) {
	doGATrack( "/page/" + page );
}

function trackPageEvent( event ) {
	doGATrack( "/event/" + event );
}

function trackPageLightbox( lightbox ) {
	doGATrack( "/lightbox/" + lightbox );
}

function openLightBox(width, header, content, overlay, relPosX, relPosY, relToMouse, delParam, prefix, closeButtonCSS, showContentOnly, onCloseButtonClick) {
	lightboxShow(width, header, content, overlay, delParam, prefix, closeButtonCSS, onCloseButtonClick, -1, showContentOnly);
}

function showHideLayer(name) {
	var layer = document.getElementById(name);
	if (layer.style.display == '') {
		layer.style.display = 'none';
	}
	else {
		layer.style.display = '';
	}
}

var friendsListWantsToBeOpen = false;
function toggleFriendsList(layerId, imageId, forceOpen) {
	var layer = document.getElementById(layerId);
	var image = document.getElementById(imageId);
	if (layer.style.display == '' && !forceOpen) {
		layer.style.display = 'none';
		friendsListWantsToBeOpen = false;
		image.src = 'img/button_maximize.gif';
	}
	else {
		layer.style.display = '';
		friendsListWantsToBeOpen = true;
		image.src = 'img/button_minimize.gif';
	}
}

function getPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
	while(1)
	{
		curleft += obj.offsetLeft;
		if(!obj.offsetParent)
		break;
		obj = obj.offsetParent;
	}
	else if(obj.x)
	curleft += obj.x;
	return curleft;
}

function getPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
	while(1)
	{
		curtop += obj.offsetTop;
		if(!obj.offsetParent)
		break;
		obj = obj.offsetParent;
	}
	else if(obj.y)
	curtop += obj.y;
	return curtop;
}


function checkBox(element, options) {

	_options = options;
	defaults = {
		offsetTop: 10,
		offsetRight: 10,
		offsetBottom: 10,
		offsetLeft: 10
	};

	if (typeof(_options) == "undefined") {
		_options = {};
	}
	if (typeof(_options.offsetTop) == "undefined") {
		_options.offsetTop = _options.offsetTop;
	}
	if (typeof(_options.offsetRight) == "undefined") {
		_options.offsetRight = _options.offsetRight;
	}
	if (typeof(_options.offsetBottom) == "undefined") {
		_options.offsetBottom = _options.offsetBottom;
	}
	if (typeof(_options.offsetLeft) == "undefined") {
		_options.offsetLeft = _options.offsetLeft;
	}
	options = $.extend({}, defaults, _options);

	var obj = document.getElementById(element);
	if (obj.style.visibility != "visible") {
		return;
	}

	var objX    = getPosX(obj);
	var objY    = getPosY(obj);

	var objMinX_Left = objX - options.offsetLeft;
	var objMaxX_Right = objX + obj.offsetWidth + options.offsetRight;
	var objMinY_Top = objY - options.offsetTop;
	var objMaxY_Bottom = objY + obj.offsetHeight + options.offsetBottom;

	var mouseX  = mx;
	var mouseY  = my;

	var thinkOutSideTheBox = false;
	if (mouseX < objMinX_Left || mouseX > objMaxX_Right) {
		thinkOutSideTheBox = true;
	}
	if (mouseY < objMinY_Top || mouseY > objMaxY_Bottom) {
		thinkOutSideTheBox = true;
	}

	if (thinkOutSideTheBox) {
		if (element == "userMenuLayer" || element == "popbox") {
			checkMenuLayer = false; // Disable check since layer is no longer showing
			if (element == "popbox") {
				enableBanners();
			}
		}

		if (element == "userMenuLayer") {
			layer_hide(element);
		}
		else {
			$("#"+element).remove();
		}
	}
}

function initUpdateOnlineTracker(userIdsStr) {
	ajaxCall('com/authenticated/ajax/com.php', 'val=getOnlineStatus&ids='+userIdsStr, 'response_getOnlineStatus', '');
	window.setInterval("sendOnlineTrackerRequestForUsers('"+userIdsStr+"')", 10000);

}

// called each interval and triggers a request to update online status for users
function sendOnlineTrackerRequestForUsers(userIdsStr) {
	// if we have access to flash polling, use that, otherwise use old ajax polling
	if (!sendGeneralRequestNextPoll('get_online_status', userIdsStr, 'updateOnlineTracker')) {
		ajaxCall('com/authenticated/ajax/com.php', 'val=getOnlineStatus&ids='+userIdsStr, 'response_getOnlineStatus', '');
	}
}

// used to send a general request to getEvents.php the next time it is polled.
function sendGeneralRequestNextPoll(requestName, requestParameter, responseFunction) {
	var flashObject = getFlashById("levelsystem");
	if (flashObject && flashObject.sendGeneralRequestNextPoll != undefined) {
		flashObject.sendGeneralRequestNextPoll(requestName, requestParameter, responseFunction);
		return true;
	}
	return false;
}

function response_getOnlineStatus(readyState, response, responseParameter) {
	if (readyState != 4) {
		return;
	}
	updateOnlineTracker(response);
}


function updateOnlineTracker(response) {
	try {
		eval(response); // Creates associative array named users
	}
	catch(error) {
		//			alert(error);
	}

	if (typeof(users) == "undefined")
	return;

	for (var i=0; i<OnlineTracker.OnlineItems.length; i++) {
		var userId = OnlineTracker.OnlineItems[i].userId;
		var newStatus = users[userId];

		if (OnlineTracker.OnlineItems[i].status == newStatus)
		continue;

		OnlineTracker.OnlineItems[i].setStatus(newStatus);

		if (OnlineTracker.OnlineItems[i].tag == "buddylist")
		buddyList.updateStatus(userId, newStatus);
		else {
			var onlineElement = document.getElementById("icon_" + OnlineTracker.OnlineItems[i].spanId);
			if (onlineElement != null) {
				try {
					var srcStr = onlineElement.src;
					var status_width = parseInt(srcStr.substring(srcStr.lastIndexOf("_")+1, srcStr.lastIndexOf("."))); // using the width css property to retrieve the current width would be more elegant, but that doesn't work in IE when refreshing
					onlineElement.src = "common/img/icons/"+newStatus+"_"+status_width+".png";
					onlineElement.title = newStatus;
				}
				catch(error) {
					//alert(error);
				}
			}
		}
	}
}

function notifyAddBuddy(userId) {
	ajaxCall('com/authenticated/ajax/com.php', 'val=getBuddyData&id='+userId+'&del_event=1', 'addJsBuddy', '');
}

function notifyRemoveBuddy(userId) {
	buddyList.removeBuddy(userId);
	//myBuddyList.writeBuddyList();
	/*if (friendsListWantsToBeOpen) {
	toggleFriendsList('offlineFriends', 'offlineFriendsToggle', true);
	}*/
	ajaxCall('com/authenticated/ajax/com.php', 'val=deleteExecuteEvent', '', '');
}

function addJsBuddy(readyState, response, responseParameter) {
	if (readyState == 4) {
		eval(response);
		buddyList.addBuddy(user[0], user[1], user[2], user[3], user[4], user[5], user[6], user[7]);
		/*myBuddyList.writeBuddyList();
		if (friendsListWantsToBeOpen) {
		toggleFriendsList('offlineFriends', 'offlineFriendsToggle', true);
		}*/
	}
}

function changeSetting(optionName, value) {
	ajaxCall('com/authenticated/ajax/com.php', 'val=changeSetting&option_name='+optionName+'&value='+value, '', '');
}

function changeChatRestriction(value) {
	ajaxCall('com/authenticated/ajax/com.php', 'val=changeChatRestriction&value='+value, 'updateLevelSystem', '');
}

function changeChallengeRestriction(value) {
	ajaxCall('com/authenticated/ajax/com.php', 'val=changeChallengeRestriction&value='+value, 'updateLevelSystem', '');
}

// when chat/challenge setting has changed, send a dummy poll event to make the levelsystem do a poll and update itself, so the new setting is reflected in the gfx
function updateLevelSystem(readyState, response, responseParameter) {
	if (readyState == 4) {
		doPoll();
	}
}


function checkUsernameAvailability(username) {
	ajaxCall('com/anonymous/ajax/com.php', 'val=checkUsernameAvailability&username='+encodeURIComponent(username), 'updateUsernameAvailability', '');
}

function updateUsernameAvailability(readyState, response, responseParameter) {
	if (readyState == 4) {
		var username_availability = document.getElementById('username_availability');

		// response[0] = status
		// response[1] = message
		// response[2] = additional details (suggested username or error message)
		response = response.split(';');

		if (response[0] == "AVAILABLE") {
			username_availability.innerHTML = response[1];
			username_availability.style.display = "block";
			username_availability.style.fontWeight = "bold";
			username_availability.className = "green_text";
		}
		else if (response[0] == "UNAVAILABLE") {
			username_availability.innerHTML = response[1];
			username_availability.style.display = "block";
			username_availability.style.fontWeight = "bold";
			username_availability.className = "red_text";
		}
		else if (response[0] == "INVALID") {
			username_availability.innerHTML = response[1];
			username_availability.style.display = "block";
			username_availability.style.fontWeight = "bold";
			username_availability.className = "red_text";
		}

		if(response[2]) {
			username_availability.innerHTML = username_availability.innerHTML +
			"<div style='color: black; font-weight: normal'>" + response[2] + "</div>";
		}
	}
}

function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"'); // "
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function change_tab(tabFamily, thisTab) {

	ptUL = document.getElementById('powertabs_list_'+tabFamily);

	for (var i=0; i< tabsArr[tabFamily].length; i++) {
		ptUL.childNodes[i].childNodes[0].className='';
	}

	ptUL.childNodes[thisTab].childNodes[0].className='selected';

	if (tabsArr[tabFamily]["header"]) {
		document.getElementById('powertabs_header_'+tabFamily).innerHTML = tabsArr[tabFamily]["header"];
	}

	if (tabsArr[tabFamily]["footer"]) {
		document.getElementById('powertabs_footer_'+tabFamily).innerHTML = tabsArr[tabFamily]["footer"];
	}

	if (tabsArr[tabFamily][thisTab]["html"]==true) {
		document.getElementById('powertabs_content_'+tabFamily).style.display='block';
		document.getElementById('powertabs_frame_'+tabFamily).style.display='none';
		document.getElementById('powertabs_content_'+tabFamily).innerHTML=tabsArr[tabFamily][thisTab]["content"];
	} else {
		document.getElementById('powertabs_content_'+tabFamily).style.display='none';
		document.getElementById('powertabs_frame_'+tabFamily).style.display='block';
		document.getElementById('powertabs_frame_'+tabFamily).src=tabsArr[tabFamily][thisTab]["content"];
	}
}

function activate_tab(tabFamily) {
	if (tabsArr[tabFamily]["header"]) {
		document.getElementById('powertabs_header_'+tabFamily).innerHTML = tabsArr[tabFamily]["header"];
	}

	if (tabsArr[tabFamily]["footer"]) {
		document.getElementById('powertabs_footer_'+tabFamily).innerHTML = tabsArr[tabFamily]["footer"];
	}

	if (tabsArr[tabFamily][thisTab]["html"]==true) {
		document.getElementById('powertabs_content_'+tabFamily).style.display='block';
		document.getElementById('powertabs_frame_'+tabFamily).style.display='none';
		document.getElementById('powertabs_content_'+tabFamily).innerHTML=tabsArr[tabFamily][thisTab]["content"];
	} else {
		document.getElementById('powertabs_content_'+tabFamily).style.display='none';
		document.getElementById('powertabs_frame_'+tabFamily).style.display='block';
		document.getElementById('powertabs_frame_'+tabFamily).src=tabsArr[tabFamily][thisTab]["content"];
	}
}

function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit)
	field.value = field.value.substring(0, maxlimit);
	else
	cntfield.value = maxlimit - field.value.length;
}

function selectMoveRows(select1, select2) {
	var optionId   = "";
	var optionText = "";

	// Move rows from select1 to select2 from bottom to top
	for (var i = select1.options.length-1; i >= 0; i--) {
		if (select1.options[i].selected == true) {
			optionId   = select1.options[i].value;
			optionText = select1.options[i].text;

			var newRow = new Option(optionText, optionId);

			select2.options[select2.length] = newRow;
			select1.options[i] = null;
		}
	}
	selectSort(select2);
}

function selectSort(selectList) {
	var optionId   = "";
	var optionText = "";

	for (var x = 0; x < selectList.length-1; x++) {
		for (var y = x+1; y < selectList.length; y++) {
			if (selectList[x].text > selectList[y].text) {
				// Swap rows
				optionId   = selectList[x].value;
				optionText = selectList[x].text;

				selectList[x].value = selectList[y].value;
				selectList[x].text  = selectList[y].text;

				selectList[y].value = optionId;
				selectList[y].text  = optionText;
			}
		}
	}
}

function checkGameSwitch(gameId, strQuestion) {
	if (!gameId || isNaN(gameId)) {
		return;
	}

	if (confirm(strQuestion)) {
		location.href="games/switcher.php?game_id="+gameId;
	}
	return;
}

function languageSwitch(newLang) {
	location.href="?lang="+newLang;
}

function ajax_openUserMenu(readyState, response, responseParameter) {
	var userId = responseParameter;

	var username = "";
	var teamName = "";
	var countryShort = "";

	if (readyState == 1) {
		showUserMenu(new Array(), username, teamName, countryShort, true);
	}
	else if (readyState == 4) {
		var menuItems = new Array();

		if (response != "") {
			try {
				var menuArray = eval(response);
				if (menuArray.length == 4) {
					menuItems = menuArray[0]; // Creates associative array named users
					username = menuArray[1]; // Use username sent from the server
					teamName = menuArray[2]; // Use teamname sent from the server
					countryShort = menuArray[3]; // Use country sent from the server
				}
			}
			catch(error) {
				//alert(error);
				return;
			}
		}
		showUserMenu(menuItems, username, teamName, countryShort, false);
	}
}

function showGeneralMouseMenu(contentObject, title, showLoading, topRightContent, openDirection, useMousePosition) {
	var contentString = null;
	var menuItems = null;

	if (typeof(contentObject) == "string") {
		contentString = contentObject;
	}
	else {
		menuItems = contentObject;
	}

	if (topRightContent == undefined) {
		topRightContent = "";
	}

	if (useMousePosition == undefined) {
		useMousePosition = true;
	}

	var content = "";
	content += "<table border=0 cellpadding=0 cellspacing=0 class=\"general_mouse_menu_frame\"><tr><td>";
	content += "<table border=0 cellspacing=0 cellpadding=0 width=150 class=\"general_mouse_menu_table\">";

	content += " <tr>";
	content += "  <td style=\"cursor:default;\" class=h1 width=1 NOWRAP>" + title + "</td><td align=\"right\">"+topRightContent+"</td>";
	content += " </tr>";
	content += " <tr>";
	content += "  <td colspan=3><hr></td>";
	content += " </tr>";

	if (showLoading) {
		content += " <tr>";
		content += "  <td align=center><img src=\"common/img/icons/ajax_loader.gif\"></td>";
		content += " </tr>";
	}
	else {
		if (contentString != null) {
			content += " <tr>";
			content += "  <td NOWRAP>" + contentString + "</td>";
			content += " </tr>";
		}
		else {
			for (var i=0; i<menuItems.length; i++) {
				if (menuItems[i][0] == "item") {
					var onclick = "";
					if (menuItems[i][3] != "")
					onclick = " onclick=\""+menuItems[i][3]+"; layer_hide('userMenuLayer'); return false;\"";

					content += " <tr>";
					if (menuItems[i][2] != "") {
						content += "  <td NOWRAP><a href=\"#\"" + onclick + "><b>&bull; " + menuItems[i][1] + "</b></a></td>";
					}
					else {
						content += "  <td NOWRAP><a href=\"#\"" + onclick + ">" + menuItems[i][1] + "</a></td>";
					}
					content += " </tr>";
				}
				else {
					content += " <tr>";
					content += "  <td>" + menuItems[i][1] + "</td>";
					content += " </tr>";
				}
			}
		}
	}

	content += "</table>";
	content += "</td></tr></table>";

	layer_write("userMenuLayer", content);
	layer_show("userMenuLayer");
	if (useMousePosition) {
		positionMouseMenu("userMenuLayer", openDirection);
	}
	checkMenuLayer = true;
}

function showUserMenu(menuItems, username, teamName, countryShort, showLoading) {
	var content = "";
	content += "<table border=0 cellpadding=0 cellspacing=0 class=\"user_menu_frame\"><tr><td>";
	content += "<table border=0 cellspacing=0 cellpadding=0 width=100 class=\"user_menu_table\">";
	if (username) {
		if (countryShort)
		flagImg = "<img src=\"common/img/flags/15/"+countryShort+".gif\">";
		else
		flagImg = "";

		content += " <tr>";
		content += "  <td>";
		content += "   <table border=0 cellspacing=0 cellpadding=0 width=100%>";
		content += "    <tr>";
		content += "     <td style=\"cursor:default;\" class=h1 width=1 NOWRAP>"+username+"</td>";
		content += "     <td style=\"padding-left:5px;\" align=right>"+flagImg+"</td>";
		content += "    </tr>";
		content += "   </table>";
		content += "  </td>";
		content += " </tr>";
	}

	if (teamName) {
		content += " <tr>";
		content += "  <td colspan=2 style=\"cursor:default;\" NOWRAP>"+teamName+"</td>";
		content += " </tr>";
	}
	content += "<td colspan=3><hr></td>";
	for (var i=0; i<menuItems.length; i++) {
		var onclick = "";
		if (menuItems[i][2] != "")
		onclick = " onclick=\""+menuItems[i][2]+"\"";

		content += " <tr>";
		content += "  <td NOWRAP><a href=\""+menuItems[i][1]+"\""+onclick+">"+menuItems[i][0]+"</a></td>";
		content += "  <td>"+menuItems[i][3]+"</td>";
		content += " </tr>";
	}
	if (showLoading) {
		content += "<tr><td align=center><img src=\"common/img/icons/ajax_loader.gif\"></td></tr>";
	}

	content += "</table>";
	content += "</td></tr></table>";

	layer_write("userMenuLayer", content);
	layer_show("userMenuLayer");
	positionMouseMenu("userMenuLayer");
	checkMenuLayer = true;
}

function positionMouseMenu(layerName, openDirection) {
	if (openDirection == undefined || openDirection == "") {
		openDirection = "DOWN_RIGHT";
	}
	var mouseMenuWidth = document.getElementById(layerName).offsetWidth;
	var mouseMenuHeight = document.getElementById(layerName).offsetHeight;

	switch(openDirection) {
		case "DOWN_RIGHT":
		mouseMenuX = mx - 10;
		mouseMenuY = my - 10;
		break;
		case "DOWN_LEFT":
		mouseMenuX = mx - mouseMenuWidth + 10;
		mouseMenuY = my - 10;
		break;
	}

	if (typeof getScrollLeft != "undefined" && typeof getClientWidth != "undefined") {
		mouseMenuX = Math.min(mouseMenuX, getScrollLeft() + getClientWidth() - mouseMenuWidth);
	}

	if (typeof getScrollTop != "undefined" && typeof getClientHeight != "undefined") {
		mouseMenuY = Math.max(Math.min(mouseMenuY, getScrollTop() + getClientHeight() - mouseMenuHeight), 1);
	}

	// Try to prevent the user menu from appearing on top of a banner (banners are often flash and not always embedded with wmode, which means the dhtml will be obscured by it)
	if (typeof getScrollTop != "undefined" && typeof getScrollTop != "undefined") {
		var newMouseMenuX = mouseMenuX;
		var newMouseMenuY = mouseMenuY;
		var iframes = document.getElementsByTagName("IFRAME");
		for(var i=0; i<iframes.length; i++) {
			var iframe = iframes[i];
			// the iframe is a banner
			if (isLikelyIframeBanner(iframe.name)) {
				// and it's actually showing an ad and is not actively hidden
				if (iframe.src.indexOf("blank.html") == -1 && iframe.style.visibility != "hidden") {
					var newCoords = moveRectangleAwayFromElement(newMouseMenuX, newMouseMenuY, mouseMenuWidth, mouseMenuHeight, iframe);
					newMouseMenuX = newCoords[0];
					newMouseMenuY = newCoords[1];
				}
			}
		}

		// Try to prevent the user menu from appearing on top of any elements with the name "noDHTMLOver", those probably contains flash movie embedded with wmode = window
		var noHTMLOverElements = document.getElementsByName("noDHTMLOver");
		if (noHTMLOverElements.length > 0) {
			for(var i=0; i<noHTMLOverElements.length; i++) {
				var newCoords = moveRectangleAwayFromElement(newMouseMenuX, newMouseMenuY, mouseMenuWidth, mouseMenuHeight, noHTMLOverElements[i]);
				newMouseMenuX = newCoords[0];
				newMouseMenuY = newCoords[1];
			}
		}

		// only use the new coord after checking against banners if the position still means the cursor is over the menu (otherwise it will close itself immediately after the mouse is moved)
		if (newMouseMenuX > mouseMenuX - mouseMenuWidth) {
			mouseMenuX = newMouseMenuX;
		}
		if (newMouseMenuY > mouseMenuY - mouseMenuHeight) {
			mouseMenuY = newMouseMenuY;
		}
	}

	layer_move(layerName, mouseMenuX, mouseMenuY);
}

function moveRectangleAwayFromElement(rectPosX, rectPosY, rectWidth, rectHeight, elem) {
	var elemPosArray = findElementAbsolutePos(elem);

	// we could retrieve the absolute position of the element
	if (elemPosArray != null) {
		var elemX = elemPosArray[0];
		var elemY = elemPosArray[1];
		var elemWidth = elem.offsetWidth;
		var elemHeight = elem.offsetHeight;
		var newPossibleCoordX = rectPosX;
		var newPossibleCoordY = rectPosY;

		// if the menu overlaps try to get a smaller x coord so it doesn't overlap
		if (rectPosX + rectWidth > elemX && rectPosY + rectHeight > elemY && rectPosY < elemY + elemHeight) {
			if (elemX - rectWidth > getScrollLeft()) {
				newPossibleCoordX = elemX - rectWidth;
			}
		}

		// if the menu overlaps try to get a smaller y coord so it doesn't overlap
		if (rectPosY + rectHeight > elemY && rectPosX + rectWidth > elemX && rectPosX < elemX + elemWidth) {
			if (elemY - rectHeight > getScrollTop()) {
				newPossibleCoordY = elemY - rectHeight;
			}
		}

		// if we have new positions i both x and y, use the one that results in the smallest distance moved
		if (Math.abs(newPossibleCoordX - rectPosX) > 0 && Math.abs(newPossibleCoordY - rectPosY) > 0) {
			if (Math.abs(newPossibleCoordX - rectPosX) < Math.abs(newPossibleCoordY - rectPosY)) {
				rectPosX = newPossibleCoordX;
			} else {
				rectPosY = newPossibleCoordY;
			}
		} else { // otherwise we use the new position in either x or y
			rectPosX = newPossibleCoordX;
			rectPosY = newPossibleCoordY;
		}
	}

	return new Array(rectPosX, rectPosY);
}

function findElementAbsolutePos(element) {
	var leftPos = 0;
	var topPos = 0;

	if (element.offsetParent) {
		if (element.style.position == "fixed") {
			leftPos += getScrollLeft();
			topPos += getScrollTop();
		}

		do {
			leftPos += element.offsetLeft;
			topPos += element.offsetTop;
		} while (element = element.offsetParent);

		return [leftPos, topPos];
	}
	return null;
}

function createCookie(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() {
	jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
		return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
	};
});

function pcWindowState(el, id) {
	$("div#"+id).slideFadeToggle("fast", "",  function () {
		if (document.getElementById(id).style.display=="none") {
			el.className = "window_title_minimized";
			if (id.indexOf('temp_unique_')==-1)
			createCookie(windowStatePrefix + "windowState_" + id, 0, 40);
		} else {
			el.className = "window_title_expanded";
			if (id.indexOf('temp_unique_')==-1)
			createCookie(windowStatePrefix + "windowState_" + id, 1, 40);
		}
	});
}


/*
*  Same as pcWindowState but dedicated for Club Membership Required lightbox
*/
function pcWindowStateLightbox(el, id) {

	$("div#"+id).slideFadeToggle("fast", "",  function () {
		if (document.getElementById(id).style.display=="none") {
			if (id.indexOf('temp_unique_')==-1)
			createCookie(windowStatePrefix + "windowState_" + id, 0, 40);
		} else {
			if (id.indexOf('temp_unique_')==-1)
			createCookie(windowStatePrefix + "windowState_" + id, 1, 40);
		}
		lightboxUpdatePositions();
	});
}

/*
*  Same as pcWindowState but dedicated for Table
*/
function pcTableState(toggleId, targetId, linkClosed, linkOpen) {
	$("div#"+targetId).slideFadeToggle("fast", "",  function () {
		if (document.getElementById(targetId).style.display=="none") {
			layer_write(toggleId, linkClosed);
		} else {
			layer_write(toggleId, linkOpen);
		}
	});
}

/*
* Wrapper for showClubMemberLightbox combined with trackPageLightbox
*/

function badgeEditorShowCMLightbox() {
	showClubMemberLightbox(1);
	trackPageLightbox('CM_oops_badge');
}

/*
* Function displaying Club Membership Required lightbox
*/

function showClubMemberLightbox(type) {
	ajaxCall('com/authenticated/ajax/com.php', 'val=getLightboxData&ltype=' + type, 'fillLightbox', '');
}

/*
* Function filling the contents of a Club Membership Required lightbox
*/
function fillLightbox(readyState, response, responseParameter) {
	if (readyState == 4) {
		// the eval creates us title and content variable used in openLightBox
		eval(response);

		openLightBox(400, title, content, "none", '', '', 0, "", "light_", "button_special_x_white");
	}
}


/*
* Functions for club membership promo box (sept 2008)
*/
function displayClubPromo() {
	ajaxCall('com/authenticated/ajax/payment.php', 'val=displayClubPromo', 'fillClubPromoLightbox', '');
	trackPageLightbox('CM_club_promo');
}

function fillClubPromoLightbox(readyState, response, responseParameter) {
	if (readyState == 4) {
		// the eval creates us title and content variable used in openLightBox
		eval(response);

		openLightBox(600, title, content, "none", '', '', 0, "", "light_", "button_special_x_white");
	}
}

/*
* club promo end
*/


/*
* Offline challenge lighbotx confirmation box
*/

function offlineChallengeLightbox(uid) {
	var content = "<div style=\"text-align: center; padding-bottom: 20px;\"><img src=\"common/img/icons/ajax_loader.gif\" width=\"16\" height=\"16\"></div>";
	openLightBox(400, '', content, "none", '', '', 0, "", "light_", "button_special_x_white");
	ajaxCall('com/authenticated/ajax/com.php', 'val=getOfflineChallengeLightbox&uid=' + uid, 'fillOfflineChallengeLightbox', '');
}


/*
* Function filling the contents of a Club Membership Required lightbox
*/
function fillOfflineChallengeLightbox(readyState, response, responseParameter) {
	if (readyState == 4) {
		// the eval creates us title and content variable used in openLightBox
		eval(response);
		lightboxHide();
		openLightBox(400, title, content, "none", '', '', 0, "", "light_", "button_special_x_white");
	}
}

function html_entity_decode( string ) {
	// http://kevin.vanzonneveld.net
	// +   original by: john (http://www.jd-tech.net)
	// +      input by: ger
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// %          note: table from http://www.the-art-of-web.com/html/character-codes/
	// *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
	// *     returns 1: 'Kevin & van Zonneveld'

	var histogram = {}, histogram_r = {}, code = 0;
	var entity = chr = '';

	histogram['34'] = 'quot';
	histogram['38'] = 'amp';
	histogram['60'] = 'lt';
	histogram['62'] = 'gt';
	histogram['160'] = 'nbsp';
	histogram['161'] = 'iexcl';
	histogram['162'] = 'cent';
	histogram['163'] = 'pound';
	histogram['164'] = 'curren';
	histogram['165'] = 'yen';
	histogram['166'] = 'brvbar';
	histogram['167'] = 'sect';
	histogram['168'] = 'uml';
	histogram['169'] = 'copy';
	histogram['170'] = 'ordf';
	histogram['171'] = 'laquo';
	histogram['172'] = 'not';
	histogram['173'] = 'shy';
	histogram['174'] = 'reg';
	histogram['175'] = 'macr';
	histogram['176'] = 'deg';
	histogram['177'] = 'plusmn';
	histogram['178'] = 'sup2';
	histogram['179'] = 'sup3';
	histogram['180'] = 'acute';
	histogram['181'] = 'micro';
	histogram['182'] = 'para';
	histogram['183'] = 'middot';
	histogram['184'] = 'cedil';
	histogram['185'] = 'sup1';
	histogram['186'] = 'ordm';
	histogram['187'] = 'raquo';
	histogram['188'] = 'frac14';
	histogram['189'] = 'frac12';
	histogram['190'] = 'frac34';
	histogram['191'] = 'iquest';
	histogram['192'] = 'Agrave';
	histogram['193'] = 'Aacute';
	histogram['194'] = 'Acirc';
	histogram['195'] = 'Atilde';
	histogram['196'] = 'Auml';
	histogram['197'] = 'Aring';
	histogram['198'] = 'AElig';
	histogram['199'] = 'Ccedil';
	histogram['200'] = 'Egrave';
	histogram['201'] = 'Eacute';
	histogram['202'] = 'Ecirc';
	histogram['203'] = 'Euml';
	histogram['204'] = 'Igrave';
	histogram['205'] = 'Iacute';
	histogram['206'] = 'Icirc';
	histogram['207'] = 'Iuml';
	histogram['208'] = 'ETH';
	histogram['209'] = 'Ntilde';
	histogram['210'] = 'Ograve';
	histogram['211'] = 'Oacute';
	histogram['212'] = 'Ocirc';
	histogram['213'] = 'Otilde';
	histogram['214'] = 'Ouml';
	histogram['215'] = 'times';
	histogram['216'] = 'Oslash';
	histogram['217'] = 'Ugrave';
	histogram['218'] = 'Uacute';
	histogram['219'] = 'Ucirc';
	histogram['220'] = 'Uuml';
	histogram['221'] = 'Yacute';
	histogram['222'] = 'THORN';
	histogram['223'] = 'szlig';
	histogram['224'] = 'agrave';
	histogram['225'] = 'aacute';
	histogram['226'] = 'acirc';
	histogram['227'] = 'atilde';
	histogram['228'] = 'auml';
	histogram['229'] = 'aring';
	histogram['230'] = 'aelig';
	histogram['231'] = 'ccedil';
	histogram['232'] = 'egrave';
	histogram['233'] = 'eacute';
	histogram['234'] = 'ecirc';
	histogram['235'] = 'euml';
	histogram['236'] = 'igrave';
	histogram['237'] = 'iacute';
	histogram['238'] = 'icirc';
	histogram['239'] = 'iuml';
	histogram['240'] = 'eth';
	histogram['241'] = 'ntilde';
	histogram['242'] = 'ograve';
	histogram['243'] = 'oacute';
	histogram['244'] = 'ocirc';
	histogram['245'] = 'otilde';
	histogram['246'] = 'ouml';
	histogram['247'] = 'divide';
	histogram['248'] = 'oslash';
	histogram['249'] = 'ugrave';
	histogram['250'] = 'uacute';
	histogram['251'] = 'ucirc';
	histogram['252'] = 'uuml';
	histogram['253'] = 'yacute';
	histogram['254'] = 'thorn';
	histogram['255'] = 'yuml';

	// Reverse table. Cause for maintainability purposes, the histogram is
	// identical to the one in htmlentities.
	for (code in histogram) {
		entity = histogram[code];
		histogram_r[entity] = code;
	}

	return string.replace(/(\&([a-zA-Z]+)\;)/g, function(full, m1, m2){
		if (m2 in histogram_r) {
			return String.fromCharCode(histogram_r[m2]);
		} else {
			return "&" + m2 + ";";
		}
	});
}

function trim(str) {
	return str.replace(/(^\s*)|(\s*$)/g, "");
}

function createCookie(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 readCookie(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 null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);

}

function implode( glue, pieces ) {
	return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}

function explode( delimiter, string, limit ) {
	// http://kevin.vanzonneveld.net
	// +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +     improved by: kenneth
	// +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +     improved by: d3x
	// +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// *     example 1: explode(' ', 'Kevin van Zonneveld');
	// *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
	// *     example 2: explode('=', 'a=bc=d', 2);
	// *     returns 2: ['a', 'bc=d']

	var emptyArray = { 0: '' };

	// third argument is not required
	if ( arguments.length < 2
	|| typeof arguments[0] == 'undefined'
	|| typeof arguments[1] == 'undefined' )
	{
		return null;
	}

	if ( delimiter === ''
	|| delimiter === false
	|| delimiter === null )
	{
		return false;
	}

	if ( typeof delimiter == 'function'
	|| typeof delimiter == 'object'
	|| typeof string == 'function'
	|| typeof string == 'object' )
	{
		return emptyArray;
	}

	if ( delimiter === true ) {
		delimiter = '1';
	}

	if (!limit) {
		return string.toString().split(delimiter.toString());
	} else {
		// support for limit argument
		var splitted = string.toString().split(delimiter.toString());
		var partA = splitted.splice(0, limit - 1);
		var partB = splitted.join(delimiter.toString());
		partA.push(partB);
		return partA;
	}
}

function validateValue( strValue, type ) {
	//var ec = '€?‚ƒ„…†‡ˆ‰Š‹Œ?Ž??‘’“”•–—˜™š›œ?žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôö÷øùúûüýþ';
	var ec = '€?‚ƒ„…†‡ˆ‰Š‹Œ?Ž??‘’“”•–—˜™š›œ?žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿';

	switch(type) {
		case "username":
		var pattern = /(^[0-9a-zA-Z_Ã¥Ã¤Ã¶Ã…Ã„Ã–\.-]{3,30}$)/i; break;
		case "cupname":
		var pattern = /(^[A-Za-z 0-9_Ã¥Ã¤Ã¶Ã…Ã„Ã–Ã±Ã‘Ã?Ã¡Ã‰Ã©Ã«Ã­Ã¯Ã³Ã´ÃµÃšÃºÃ¼Ã½Ã£ÃƒÃ§Ã‡.!Ã¸Ã¦Ã˜Ã†\-'+ec+']{1,30}$)/i; break;
		case "username_login":
		var pattern = /(^[0-9a-zA-Z_Ã¥Ã¤Ã¶Ã…Ã„Ã–\.-]{1,30}$)/i; break;
		case "email":
		var pattern = /(^[a-z0-9]+[a-z0-9_\\.-]*@([a-z0-9]+([\.-][a-z0-9]+)*)\\.[a-z]{2,4}$)/i; break;
		case "email_uppercase":
		var pattern = /(^[a-zA-Z0-9]+[a-zA-Z0-9_\\.-]*@([a-zA-Z0-9]+([\.-][a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,4}$)/i; break;
		case "common":
		var pattern = /(^[A-Za-z 0-9Ã¥Ã¤Ã¶Ã…Ã„Ã–Ã±Ã‘Ã¦Ã?Ã¡Ã‰Ã©Ã«Ã­Ã¯Ã³Ã´ÃµÃšÃºÃ¼Ã½Ã£ÃƒÃ§Ã‡.,/Ã¸Ã¦Âº\-'+ec+']+$)/i; break;
		case "teamname":
		var pattern = /(^[A-Za-z 0-9Ã¥Ã¤Ã¶Ã…Ã„Ã–Ã±Ã‘Ã?Ã¡Ã‰Ã©Ã«Ã­Ã¯Ã³Ã´ÃµÃšÃºÃ¼Ã½Ã£ÃƒÃ§Ã‡.!Ã¸Ã¦Ã˜Ã†\-'+ec+']+$)/i; break;
		case "mobilno":
		var pattern = /(^[0-9-]{8,}$)/i; break;
		case "float":
		var pattern = /(^[-0-9]*\.*[0-9]*$)/i; break;
		case "numbers":
		var pattern = /(^[-0-9]+$)/i; break;
		case "signednumbers":
		var pattern = /(^[-0-9]+$)/i; break;
		case "comma_separated_numbers":
		var pattern = /(^[0-9]+(,[0-9]+)*$)/i; break;
		case "training_position_data":
		var pattern = /(^[0-9]+_[0-9]+_[0-9]+_[0-9]+(,[0-9]+_[0-9]+_[0-9]+_[0-9]+)*$)/i; break;
		case "training_save_data":
		var pattern = /(^(player|trainer)_+[0-9]+_[0-9]+_[0-9]+_[0-9]+(&(player|trainer)_+[0-9]+_[0-9]+_[0-9]+_[0-9]+)*$)/i; break;
		case "tactics_save_data":
		var pattern = /(^(player|sub|goalie)=[0-9]+_[0-9]+_[0-9]+(&(player|sub|goalie)=[0-9]+_[0-9]+_[0-9]+)*$)/i; break;
		case "hexcolor":
		var pattern = /(^[a-fA-F0-9]{6,6})/i; break;
		case "parameter":
		var pattern = /(^[A-Za-z 0-9_\.\-]+$)/i; break;
		case "url":
		var pattern = /(^[A-Za-z0-9._~,@/:?&=+-]+$)/i; break;
		case "sport":
		var pattern = /(^[soccer|hockey]$)/i; break;
		case "digits+letters":
		var pattern = /(^[a-zA-Z0-9'+ec+']+$)/i; break;
		case "safe":
		var pattern = /([a-zA-Z0-9_])/i; break;
		case "datetime":
		var pattern = /(^\d{4}\-\d{1,2}\-\d{1,2} \d{2}:\d{2}:\d{2}$)/i; break; // Only validates formatting
		case "adidas_team":
		var pattern = /(^(predator|f50)$)/i; break;
		case "date":
		var pattern = /(^\d{4}\-\d{1,2}\-\d{1,2}$)/i; break;  // Only validates formatting
		case "base64":
		var pattern = /([A-Za-z0-9+/=]+$)/i; break;
		default:
		alert("No such validation type."); return false; break;
	}

	var objRegExp = new RegExp(pattern);

	//check if string matches pattern
	return objRegExp.test(strValue);
}

function commonShowRegistration(link, errorStr, tracker) {
	if (typeof tracker != 'undefined') {
		trackPageLightbox(tracker);
	}
	$.weeboxs.open(link, {contentType:'ajax', boxid:'sign_up', onopen: function(){trackPageLightbox("sign_up")}, onclose: function(){trackPageLightbox("sign_up_closed");$.weeboxs.getTopBox().close();}});
}

$(function() {
	if (typeof($.livequery) == "function") {
		$('#registerForm').livequery(function() {
			var options = {
				target:     '#registration_form_div',
				success: function (responseText, statusText) {
					$("#signUpButtonDivWrapper").css("visibility" , "visible");
				},
				error: function () {
					$('#registration_form_div').html("A error occurred. Please try again.");
					$("#signUpButtonDivWrapper").css("visibility" , "visible");
				}
			};
			$('#registerForm').ajaxForm(options);
			return false;
		});
	}
});

function getScrollbarWidth() {
	var container = $('<div></div>');
	var innerDiv  = $('<div></div>');

	container.append(innerDiv);
	container.css({
	'width'      : '50px',
	'height'     : '50px',
	'overflow-y' : 'hidden',
	'position'   : 'absolute',
	'top'        : '-100px',
	'left'       : '-100px'
	});
	innerDiv.css('height', '100px');

	// Append container, do calculations, then remove it
	$('body').append(container);
	var w1 = innerDiv.innerWidth();
	container.css('overflow-y', 'scroll');
	var w2 = innerDiv.innerWidth();
	$(container).remove();
	return (w1 - w2);
}

function syncBodyColWidths(headId, bodyId) {
	var headFields = $('#'+headId).find('td');
	var lastIndex  = headFields.length - 1;

	headFields.each(
	function(i) {
		var width = $(this).width();

		// Subtract scrollbar width from the last body column
		if (i == lastIndex) {
			width -= getScrollbarWidth();
		}
		$('#'+bodyId+' tr:eq(0) td:eq('+i+')').width(width);
	}
	);
}

$(function() {
	if (typeof($.livequery) == "function") {
		$('#b2b_guestbookForm').livequery(function() {
			var options = {
				beforeSubmit: function () {
					$("#b2b_message").val("");
				},
				success: function (responseText, statusText) {
					if (responseText.substr(0,4)=="<tr>") {
						if (typeof(guestbookIdentifier) != "undefined" && guestbookIdentifier == $("#b2b_userId").val()) {
							$.weeboxs.getTopBox().close();
							load_guestbook();
						}
						else {
							$("#b2b_guestbookContainer").empty();
							$("#b2b_guestbookContainer").html("<p style=\"padding: 10px 0 10px 0; text-align: center;\">Your message has been posted.</p>");
							$.weeboxs.getTopBox().setCenterPosition();
							$(this).oneTime(3000, null, function() {
								$.weeboxs.getTopBox().close();
							});
						}
					}
					else {
						clientErr("#b2b_guestbook_client_message", responseText);
					}
				}
			};
			$('#b2b_guestbookForm').ajaxForm(options);
			return false;
		});
	}
});

$(function() {
	$(".pc_button").live("mouseover", 
		function(){
			var cssParams = {backgroundPosition: 'bottom left'};
			$(this).css(cssParams).find(".button_middle, .button_expand").css(cssParams);
			$(this).find(".button_right").css({backgroundPosition: 'bottom right'});
		}
	);
	$(".pc_button").live("mouseout", 
		function(){
			var cssParams = {backgroundPosition: 'top left'};
			$(this).css(cssParams).find(".button_middle, .button_expand").css(cssParams);
			$(this).find(".button_right").css({backgroundPosition: 'top right'});
		}
	);
});


$(function() {

	$.popbox = function(data, options){

		if ($("#popbox").length > 0) {
			$("#popbox").remove();
		}

		var self = this;
		this._options = options;
		this.defaults = {
			parent: 'body',
			appendMode: 'append',
			contentType: 'html'
		};

		this.initOptions = function() {
			if (typeof(self._options) == "undefined") {
				self._options = {};
			}
			if (typeof(self._options.parent) == "undefined") {
				self._options.parent = self._options.parent;
			}
			if (typeof(self._options.appendMode) == "undefined") {
				self._options.appendMode = self._options.appendMode;
			}
			if (typeof(self._options.contentType) == "undefined") {
				self._options.contentType = self._options.contentType;
			}
			self.options = $.extend({}, self.defaults, self._options);
		};

		self.initOptions();

		html = ''+
		'<div id="popbox" class="dialog-box"><table><tr><td>'+
		' <div class="rounded-content">'+
		'  <div class="rounded-t"></div>'+
		'  <div class="dialog-header">'+
		'   <h2 class="dialog-title"></h2>'+
		'  </div>'+
		'  <table style="clear: both;"><tr><td class="dialog-content"></td></tr></table>'+
		' </div>'+
		' <div class="rounded-b"><div></div></div>'+
		'</td></tr></table></div>';

		switch (self.options.appendMode) {
			case 'append':
			$(self.options.parent).append(html);
			break;
			case 'appendTo':
			$(self.options.parent).appendTo(html);
			break;
			case 'insertBefore':
			$(html).insertBefore(self.options.parent);
			break;
			case 'insertAfter':
			$(html).insertAfter(self.options.parent);
			break;
		}

		disableBanners();
		self.box = $("#popbox");
		self.box.css({position: 'absolute', visibility: 'visible'});

		checkMenuLayer = true;
		this.setContent = function(data) {
			self.box.find('.dialog-content').html(data);
		}

		if (self.options.contentType == "ajax") {
			$.ajax({
				url: data,
				dataType: 'html',
				cache: true,
				beforeSend: function(){
					self.box.find('.dialog-content').html('<div class="dialog-loading"></div>');
				},
				success: function(data){
					self.setContent("<div class=\"dialog-content-div clearfix\">"+data+"</div>");
				}
			})
		}
		else {
			self.setContent("<div class=\"dialog-content-div clearfix\">"+data+"</div>");
		}

		return true;

	}

});

function pc_pngFix(selector) {
	if ($.browser.msie && $.browser.versionNumber < 7) {
		DD_belatedPNG.fix(selector);
	}
}


/**
*
* Ajax
*
*
**/   

function ajaxCall(url, parameters, responseFunction, responseParameter, async) {
  var url=url+"?"+parameters+"&sid="+Math.random();
  var AC = new ajaxCom();
  AC.setCallUrl(url);
  AC.setResponseFunction(responseFunction);
  AC.setResponseParameter(responseParameter);
  AC.setAsync(async);
  AC.run();
}

function ajaxPost(url, postdata, responseFunction, responseParameter) {
  var url=url+"?sid="+Math.random();
  var AC = new ajaxCom();
  AC.setCallUrl(url);
  AC.setPostData( postdata );
  AC.setResponseFunction(responseFunction);
  AC.setResponseParameter(responseParameter);
  AC.run("POST");
}

function ajaxCom() {
  this.callUrl           = null;
  this.responseFunction  = null;
  this.responseParameter = null;
  this.xmlHttp           = null;
  this.response          = null;
  this.async						= true;
  this.postData 	    = null;

  this.setCallUrl = function(url) {
    this.callUrl = url;
  }

  this.setResponseFunction = function(responseFunction) {
    this.responseFunction  = responseFunction;
  }

  this.setResponseParameter = function(responseParameter) {
    this.responseParameter  = responseParameter
  }
  this.setPostData = function(data){
    this.postData = data;
  }
  this.setAsync = function(async){
  	if (async != undefined)
    	this.async = async;
  }
  
  this.handleResponse = function() {
    if (this.responseFunction)
      eval(this.responseFunction)(this.xmlHttp.readyState, this.response, this.responseParameter);
  }

  this.createXmlHttpObject = function() {
    var objXMLHttp=null;
    if (window.XMLHttpRequest) {
      objXMLHttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
      objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return objXMLHttp;
  }
  
  this.run = function(method) {
    this.xmlHttp = this.createXmlHttpObject();
    if (this.xmlHttp == null) {
      this.response = "Your browser does not support ajax. Content not loaded.";
      this.handleResponse();
      return;
    }
    else {
    	if (this.async) {
		      var self = this;
		    
		      this.xmlHttp.onreadystatechange = function() {
		        if (self.xmlHttp.readyState == 4 || self.xmlHttp.readyState == "complete") {
		          self.response = self.xmlHttp.responseText;
		          self.handleResponse();
		        }
		        else
		          self.handleResponse();
	    	  }
      }
      if ( typeof(method) !== undefined && method == "POST" ) {
				this.xmlHttp.open("POST", this.callUrl, this.async );
				this.xmlHttp.setRequestHeader("Method", "POST " + this.callUrl + " HTTP/1.1");
				this.xmlHttp.setRequestHeader("If-Modified-Since", "Thu, 01 Mar 2007");
				this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				this.xmlHttp.send(this.postData);
      } else
      {
     	  this.xmlHttp.open("GET",this.callUrl,this.async);
	   		this.xmlHttp.send(null);
	   		if (this.async==false) {
					this.response = this.xmlHttp.responseText;
					this.handleResponse();
	   		}
      }
    }
  }
}

function writeLayer(readyState, response, responseParameter, layerAppend) {
	if (readyState == 4) {

		if (response.indexOf(htmlScriptSeparatorString) != -1) {
			var htmlString = response.split(htmlScriptSeparatorString)[0];
			var scriptString = response.split(htmlScriptSeparatorString)[1];
		}	else {
			var htmlString = response;
			var scriptString = null;
		}

		layer_write(responseParameter, htmlString, layerAppend);

		if (scriptString != null) {
			try {
				eval(scriptString);
			}
			catch(error) {
				layer_write("writeLayerFn", "Server error: Script error");
			}
		}
	}
}

function writeLayerInLightbox(readyState, response, responseParameter) {
  if (readyState == 4) {
		writeLayer(readyState, response, responseParameter);
		lightboxUpdatePositions();
  }
}

function appendLayer(readyState, response, responseParameter) {
	if (readyState == 4) {
		writeLayer(readyState, response, responseParameter, 'append');
	}
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}
}

// This function is used to create a countdown block 
// with days, hours, minutes and with or without seconds
var timeNow = new Array();
function updateCounter(futureTime, timeIdentifier, el, identifier, displaySeconds) {
	timeNow[timeIdentifier]++;
	var localTime = timeNow[timeIdentifier];
	if (localTime >= futureTime) {
		$("#"+el).html("Match has been played");
		clearInterval(identifier);
		return;
	}
	var time = calculateCountDown(localTime, futureTime);
	if (time["minutes"].toString().length < 2) {
		time["minutes"] = time["minutes"];
	}
	if (time["seconds"].toString().length < 2) {
		time["seconds"] = time["seconds"];
	}
	var dayString = "";
	if (time["days"] > 0) {
		var dayString = time["days"]+"d ";
	}
	if (typeof(displaySeconds) != 'undefined' && displaySeconds) {
		$("#"+el).html(dayString+time["hours"]+"h "+time["minutes"]+"m "+time["seconds"]+"s");
	}
	else {
		$("#"+el).html(dayString+time["hours"]+"h "+time["minutes"]+"m");
	}
	timeNow[timeIdentifier] = localTime;
}