var PAMessage;
var pageLoaded = false;
var PAQuickAccessSet = false;
var PAQuickAccessObj = document.getElementById("PAQuickAccess");


var i=0;
var i2=0;
var NewsArray = new Array;
var NewsArray2 = new Array;

var  MyPlayAllMemberStatusDummy = new Array;
var  ustateArray = new Array;
var userstateCounter = 0;

var MonthNames = new Array("Jan.","Feb.","Mar.","Apr.","May","June","July","Aug.","Sep.","Oct.","Nov.","Dec.");

var MousePosition = new Array();




var firstclick = 1;
var popupclosing = null;
var haveabreak = 0;

// set focus for textfield
// needs to be added in onLoad
// id setFocus must be applied to the certain textfield
function setFocus(){
	var field = document.getElementById("setFocus");
	if(field.type == "textfield"){
		field.focus();
	}
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

function FlashMovie(src, movie, width, height, version, quality, menu, bgcolor, flashvars, wmode)
{
	document.write("<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version="+version+",0,0,0' width='" +width+ "' height='" +height+ "' id='" +movie+ "'>");
	document.write("<param name='movie' value='" +src+ "' />");
	document.write("<param name='FlashVars' value='" +flashvars+ "'>");
	document.write("<param name='quality' value='" +quality+ "' />");
	document.write("<param name='menu' value='" +menu+ "' />");
	document.write("<param name='bgcolor' value='" +bgcolor+ "' />");
	document.write("<param name='wmode' value='" +wmode+ "' />");
	document.write("<embed src='" +src+ "' swLiveConnect='true' menu='" +menu+ "' wmode='" +wmode+ "' FlashVars='" +flashvars+ "' quality='" +quality+ "' bgcolor='" +bgcolor+ "' width='" +width+ "' height='" +height+ "' name='" +movie+ "' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />");
	document.write("</object>");
}
//document.onmousemove = OnMouseMoveEvent;


function OnMouseMoveEvent(event){
	GetMousePosition(event);
	Scroll(event);
}

function closeAllSupportMore(obj) {
	for(i=0; i< obj.parentNode.parentNode.getElementsByTagName("div").length; i++){
			if(obj.parentNode.parentNode.getElementsByTagName("div")[i].className=="Big"){
				obj.parentNode.parentNode.getElementsByTagName("div")[i].style.display='none';
			}
	}
}

function SupportShowMore(obj){
	closeAllSupportMore(obj);
	for(i=0; i< obj.parentNode.getElementsByTagName("div").length; i++){
			if(obj.parentNode.getElementsByTagName("div")[i].className=="Big"){
				obj.parentNode.getElementsByTagName("div")[i].style.display='block';
			}
	}
 }

function GetMousePosition(event){
	if (!event)		event = window.event;
	MousePosition[0] = event.clientX;
	MousePosition[1] = event.clientY;
	return true;
}

function ChangeNewsBanner()
{
	if(document.getElementById('NewsBannerRotation')) {
		document.getElementById('NewsBannerRotation').innerHTML = NewsArray[i];
	}
	i = (i+1) % NewsArray.length;
	return true;
}

function ResetCurrentWindowSize(){
	window.outerWidth = window.outerWidth +1 -1;
}

function StartNewsBanner()
{
	if  (NewsArray.length < 1) NewsArray[0] = 'No news available';
	ChangeNewsBanner();
	window.setInterval("ChangeNewsBanner()", 5000);
}

function ChangeBannerText(obj){
	obj.innerHTML = NewsBannerTexts[i];
	i++;
}


function ChangeNewsBanner2()
{
	if(document.getElementById('NewsBannerRotation2')) {
		document.getElementById('NewsBannerRotation2').innerHTML = NewsArray2[i2];
	}
	i2 = (i2+1) % NewsArray2.length;
	return true;
}

function StartNewsBanner2()
{
	if  (NewsArray2.length < 1) NewsArray2[0] = 'No news available';
	ChangeNewsBanner2();
	window.setInterval("ChangeNewsBanner2()", 5000);
}



function ShowAndHide(id){
	if (document.getElementById(id).style.display != "none"){
		document.getElementById(id).style.display="none";
	}
	else{
		document.getElementById(id).style.display="block";
	}
}

function getElementsByClassName(ClassName){
	var AllObjs;
	var res = new Array();
	var j = 0;
	if		(document.all)										AllObjs=document.all;
	else if	(document.getElementsByTagName && !document.all)	AllObjs=document.getElementsByTagName("*");
	for(var i = 0; i < AllObjs.length; i++){
		if(AllObjs[i].className==ClassName){
		res[j]=AllObjs[i];
		j++;
		}
	}
	return res;
}


if (!(!!(window.attachEvent && !window.opera)))
{
	Node.prototype.getElementsByCName = function (ClassName){
		var res = new Array();
		for (i=0; i < this.childNodes.length; i++){
			if (this.childNodes[i].className == ClassName)	res.push(this.childNodes[i]);
			if (this.childNodes[i].hasChildNodes()) res.concat(this.childNodes[i].getElementsByCName(ClassName));
		}
		return res;
	};
};

function CleanUp(ClassName,Except){
	var Objs = getElementsByClassName(ClassName);
	
	for(var i = 0; i < Objs.length; i++){
		if (Objs[i] != document.getElementById(Except)) Objs[i].style.display = "none";
	}
}

function resizeIFrame(height) {
	height += 50;
	if (height < document.getElementById('Community').offsetHeight){
		height = document.getElementById('Community').offsetHeight;
		height -=350;
	}
	document.getElementById('forum_iframe').style.height = height + "px";
	document.getElementById('forum_iframe').style.width = '737px';
}

function retrievalEnterText(selection) {
  if (selection=='PW') {document.getElementById('EnterText').innerHTML='Please enter login';}
  else {document.getElementById('EnterText').innerHTML='Please enter your e-mail address';}
}

function getParentById(obj, id) { 
  var node = obj.parentNode;
  if (!node) return null; 
  if ((node.id) && (node.id.toUpperCase() == id.toUpperCase()))
    return node
  else
    return getParentById(node, id);
}

function expand(obj){
	var all = obj.getElementsByTagName("div");
	for(i=0; i<all.length; i++){
		if(all[i].className == "MoreInfo"){
		
			if(all[i].style.display!="block"){
				all[i].style.display="block";
			}else{
				all[i].style.display="none";
			}
		}
		
	}
}

function show_player_time()
{
	if ($('fz-time-utc') && $('fz-time-own')) {

        var d = new Date();
        var UTCHour = d.getUTCHours() < 10 ? "0" + d.getUTCHours() : d.getUTCHours();
        var UTCMins = d.getUTCMinutes() < 10 ? "0" + d.getUTCMinutes() : d.getUTCMinutes();
        var UTCSecs = d.getUTCSeconds() < 10 ? "0" + d.getUTCSeconds() : d.getUTCSeconds();
        var UTCDay = d.getUTCDate();
        var Day = d.getDate();
        var UTCMonth = d.getUTCMonth() + 1;
		UTCMonth = (UTCMonth < 10) ? "0" + UTCMonth : UTCMonth;
        var Month = d.getMonth() + 1;
		Month = (Month < 10) ? "0" + Month : Month;
		
        var UTCFullYear = d.getUTCFullYear() - 2000;
		UTCFullYear = UTCFullYear <10 ? "0" + UTCFullYear : UTCFullYear;
		
		var FullYear = d.getFullYear() - 2000;
		FullYear = FullYear <10 ? "0" + FullYear : FullYear;
		
        var PCTHour = d.getHours() < 10 ? "0" + d.getHours() : d.getHours();
		
		
		$('fz-time-utc').innerHTML = UTCHour + ":" + UTCMins + ":" + UTCSecs + " &nbsp;" + UTCDay + "/" + UTCMonth + "/" + UTCFullYear;
		$('fz-time-own').innerHTML = PCTHour + ":" + UTCMins + ":" + UTCSecs + " &nbsp;" +    Day + "/" +    Month + "/" +    FullYear;
								
		//document.getElementById('fz-time-utc').firstChild.data = UTCHour + ":" + UTCMins + ":" + UTCSecs + " " + UTCDay + "/" + UTCMonth + "/" + UTCFullYear;
		//document.getElementById('fz-time-own').firstChild.data = PCTHour + ":" + UTCMins + ":" + UTCSecs + " " +    Day + "/" +    Month + "/" +    FullYear;		
		playerTime = setTimeout("show_player_time()", 1000);

    }

}


function SortNodesInElement(ref,type,direction){
	if (document.getElementById(ref)){
		ref = document.getElementById(ref);
	}
	else{
		return false;
	}
	
	if (direction == '1'){
		ref.insertBefore(ref.getElementsByTagName(type)[0],ref.getElementsByTagName(type)[ref.getElementsByTagName(type).length - 1].nextSibling);
	}
	if (direction == '-1'){
		ref.insertBefore(ref.getElementsByTagName(type)[ref.getElementsByTagName(type).length - 1],ref.getElementsByTagName(type)[0]);
	}

	return true;

}

function SetNewAttribute(element,attribute,value){
	var Attribute = document.createAttribute(attribute);
	Attribute.nodeValue = value;
	element.setAttributeNode(Attribute);
	return true;
}

function currentPosition(obj) {
	var currentLeft = currentTop = 0;
	if (obj.offsetParent) {
		currentLeft = obj.offsetLeft
		currentTop = obj.offsetTop
		while (obj = obj.offsetParent) {
			currentLeft += obj.offsetLeft
			currentTop += obj.offsetTop
		}
	}
	return [currentLeft,currentTop];
}


function ShowHelpBubble(e, text){
	if (!e) e = window.event;
	var mousex = e.clientX;
	var mousey = e.clientY;
	
	if (document.getElementById('HelpContainer').style.display == "none"){
		
	  var windowWidth = 0, windowHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	  }

		if(window.pageYOffset){
			var yAdjust = window.pageYOffset;
		}
		else{
			var yAdjust = document.documentElement.scrollTop;
		}
		if(window.pageXOffset){
			var xAdjust = window.pageXOffset;
		}
		else{
			var xAdjust = document.documentElement.scrollLeft;
		}
		var top = mousey -35 + yAdjust;
		var left = mousex+17 + xAdjust;
		
		
		
		document.getElementById('HelpContainer').style.display = "block";
		document.getElementById('HelpContainerText').innerHTML = text;
		document.getElementById('HelpContainer').style.height = null;
		
		var container = $('HelpContainer');
		if (top - yAdjust < 0) top = yAdjust + 5;
		if (left - xAdjust < 0) left = xAdjust + 5;
		
		if((container.getHeight()- yAdjust + top) > windowHeight - 8){
			top = windowHeight - container.getHeight() - 25 + yAdjust;
		}
		if((container.getWidth() - xAdjust + left) > windowWidth - 8){
			left -= container.getWidth() + 30;
		}
		
		document.getElementById('HelpContainer').style.width = '160px';
		document.getElementById('HelpContainer').style.position = "absolute";
		document.getElementById('HelpContainer').style.left = left + "px";
		document.getElementById('HelpContainer').style.top = top + "px";
		
		return true;
	}
	return false;
}

function HideHelpBubble(){
	document.getElementById('HelpContainer').style.height = "0px";
	document.getElementById('HelpContainer').style.left = "100px";
	document.getElementById('HelpContainer').style.top = "100px";
	document.getElementById('HelpContainer').style.overflow = "hidden";	
	document.getElementById('HelpContainer').style.display = "none";
}

function SetAllCheckboxes(id,value){
	var inputs = document.getElementById(id).getElementsByTagName("input");
	for (var i = 0;i < inputs.length;i++){
		if (inputs[i].type=="checkbox"){
			inputs[i].checked = value;
			inputs[i].onchange();
		}
	}
}

function nextObject(obj){
	var n = obj;
	do n = n.nextSibling;
	while (n && n.nodeType != 1);
	return n;
}
 
function previousObject(obj) {
	var p = obj;
	do p = p.previousSibling;
	while (p && p.nodeType != 1);
	return p;
}

function getParent(obj, tagName) { 
  var node = obj.parentNode;
  if (!node) return null; 
  if (node.nodeName.toUpperCase() == tagName.toUpperCase())
    return node
  else
    return getParent(node, tagName);
}

function previousObj(obj, tagName) {
	var p = obj;
	do p = p.previousSibling;
	while (p && p.nodeName.toUpperCase() != tagName.toUpperCase());
	return p;
}

function nextObj(obj, tagName) {
	var p = obj;
	do p = p.nextSibling;
	while (p && p.nodeName.toUpperCase() != tagName.toUpperCase());
	return p;
}



/* ***************************** Flash ****************************** */

function setWmode($wmode){
	switch($wmode) {
		case "opaque":
		case "transparent":
			this._params.wmode = $wmode;
			break;
		default:
			this._params.wmode = "window";
	}
}

var res = getElementsByClassName("flashMovie");

if (res){
	for (var i = 0; i<res.length; i++){
		res[i].setWmode("opaque");
	}
}


function styleOnChange (obj, attribute, highlight, def){
	if (obj.defaultSelected){
		obj.style.attribute = def;
	}
	else{
		obj.style.attribute = highlight;
	}
}

function createStringfromSelects(listID,dummyID){
	var list = document.getElementById(listID);
	var dummy = document.getElementById(dummyID);
	var res="";
	for (var i = 0; i<MyPlayAllMemberStatusDummy.length; i++){
		res += MyPlayAllMemberStatusDummy[i].id.substring(8) + ":" + document.getElementById('MyPlayAllMemberStatusList').getElementsByTagName('select')[i].value;
		if (i<MyPlayAllMemberStatusDummy.length-1){
			res += "|";
		}
	}
	dummy.value = res;
	$('member_states_form').submit();
}

/* Thanks to Zack Smith -- zacksmithdesign.com  */
/* Function testPassword licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php */
function testPassword()
{
		var passwd =  $F('password1');
		var intScore   = 0
		var strVerdict = "weak"
		var strLog     = ""
		
		// PASSWORD LENGTH
		if (passwd.length<5)                         // length 4 or less
		{
			intScore = (intScore+3)
			strLog   = strLog + "3 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>4 && passwd.length<8) // length between 5 and 7
		{
			intScore = (intScore+6)
			strLog   = strLog + "6 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>7 && passwd.length<16)// length between 8 and 15
		{
			intScore = (intScore+12)
			strLog   = strLog + "12 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>15)                    // length 16 or more
		{
			intScore = (intScore+18)
			strLog   = strLog + "18 point for length (" + passwd.length + ")\n"
		}
		
		
		// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
		if (passwd.match(/[a-z]/))                              // [verified] at least one lower case letter
		{
			intScore = (intScore+1)
			strLog   = strLog + "1 point for at least one lower case char\n"
		}
		
		if (passwd.match(/[A-Z]/))                              // [verified] at least one upper case letter
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one upper case char\n"
		}
		
		// NUMBERS
		if (passwd.match(/\d+/))                                 // [verified] at least one number
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one number\n"
		}
		
		if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/))             // [verified] at least three numbers
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least three numbers\n"
		}
		
		
		// SPECIAL CHAR
		if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
		{
			intScore = (intScore+8)
			strLog   = strLog + "8 points for at least one special char\n"
		}
		
									 // [verified] at least two special characters
		if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
		{
			intScore = (intScore+8)
			strLog   = strLog + "8 points for at least two special chars\n"
		}
	
		
		// COMBOS
		if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))        // [verified] both upper and lower case
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for upper and lower letters\n"
		}

		if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) // [verified] both letters and numbers
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters and numbers\n"
		}
 
									// [verified] letters, numbers, and special characters
		if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/))
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters, numbers and special chars\n"
		}
	
	
		if(intScore < 10)
		{
		   strVerdict = "very_weak"
		}
		else if (intScore > 9 && intScore < 20)
		{
		   strVerdict = "weak"
		}
		else if (intScore > 19 && intScore < 30)
		{
		   strVerdict = "mediocre"
		}
		else if (intScore > 29 && intScore < 45)
		{
		   strVerdict = "strong"
		}
		else
		{
		   strVerdict = "stronger"
		}
	
	
		translate_pw_strength(strVerdict);
	
	/*document.forms.passwordForm.score.value = (intScore)
	document.forms.passwordForm.verdict.value = (strVerdict)
	document.forms.passwordForm.matchlog.value = (strLog)*/
	
	
	return;
}

if (!(!!(window.attachEvent && !window.opera)))
{
Node.prototype.byClass = function(className,rootObject) {
   return getElementsByClassNameAndRoot(className,rootObject);
};
};

function getElementsByClassNameAndRoot(ClassName,rootObject){
	if (!rootObject) rootObject = document;
	var AllObjs;
	var res = new Array();
	var j = 0;
	if		(document.all)										AllObjs=rootObject.all;
	else if	(document.getElementsByTagName && !document.all)	AllObjs=rootObject.getElementsByTagName("*");
	for(var i = 0; i < AllObjs.length; i++){
		if(AllObjs[i].className==ClassName){
		res[j]=AllObjs[i];
		j++;
		}
	}
	return res;
}

function switchStyleDisplay(obj){
	switchStyleDisplay2(null, obj, 'none', null, null);
}

var paqaOpen = false;

function switchStyleDisplay2(e, obj, effect, origin, targetid){
	if (!e) var e = window.event;
		//$('KUCHEN').innerHTML = 'X:' + e.target.id;
		//if (origin.id != targetid) return;
	if (obj.style.display=="block"){
		if (paqaOpen && e.target.id == 'PAQuickAccessWindow')
		{
			obj.style.display="none";
			paqaOpen = false;
			//AjaxSetAllFlashMode('visible');
		}
	}
	else{
		//AjaxSetAllFlashMode('hidden');
		if (paqaOpen) return;
		paqaOpen = true;
		switch (effect)
		{
			case 'none': {obj.style.display="block"; break;}
			case 'opacity': {
				setOpacityOfElm(obj, 0);
				obj.style.display="block";
				new Effect.Opacity(obj.id,
			    { duration: 1.0, 
			      transition: Effect.Transitions.linear, 
			      from: 0, to: 1 });
				break;
			}
		}
		
	}
}

function eventKiller(e)
{return;
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function showPAQuickAccess(){
	window.clearTimeout(quickAccesTimer);
	if(!PAQuickAccessSet){
		var obj =  document.getElementById("PAQuickAccess");
		// obj.setAttribute("onmouseover", "");
		// obj.style.height = "415px";
		// obj.style.cursor = "auto";
		// setOpacityOfElm(obj, 0);
		// document.getElementById(obj.id+"Over").style.visibility = "visible";		
		// new Effect.Opacity(obj.id,
			    // { duration: 0.3, 
			      // transition: Effect.Transitions.linear, 
			      // from: 0, to: 1 });
		PAQuickAccessSet = true;
		obj.style.visibility = "visible";
	}	
}

function hidePAQuickAccess(){
	window.clearTimeout(quickAccesTimer);
	if (PAQuickAccessSet){
		var obj =  document.getElementById("PAQuickAccess");
		document.getElementById(obj.id+"Over").style.visibility = "hidden";
		obj.style.height = "15px";
		obj.style.cursor = "pointer";
		PAQuickAccessSet = false;
		
		document.getElementById("PAQuickAccessSubmit").blur();
		obj.onmouseover="quickAccesTimer = window.setTimeout('showPAQuickAccess()', 500);";
		obj.setAttribute("onmouseover", "quickAccesTimer = window.setTimeout('showPAQuickAccess()', 500);");
	}
}

function  highlightPAGamesMenu(obj){
	obj.style.background = "url('" + JsRoutingBaseImages + "learnmore/dark.gif')";
}
function unHighlightPAGamesMenu(obj){
	obj.style.background = "transparent";
}










// Konstantin stuff -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

var to_checkfornewmessages;

function ki_checkfornewmessages() {
	// also do check when it is gamerclient to push "account balance is low" message
	//if (!isgamerclient && isloggedin) {
	if (isloggedin) {
		window.clearTimeout(to_checkfornewmessages);
		
		new Ajax.Request(site_base_dir + "ajaxcall/checkfornewmessages/lol/rand="+Math.round(Math.random()*1000000), {    
					method:'get',
					onSuccess: function(transport){ 
						try{
							// only set notification on website
							if (!isgamerclient) {
								$('checkfornewmessage').innerHTML = transport.responseText;
							}
						} catch(e) {}
					},
					onFailure: function(){ } 
		}); 	
		
		to_checkfornewmessages = setTimeout(ki_checkfornewmessages, 60000);
	}
	
}




var calendar_act = 0;

function kk_calendar_move(calendarid, month, year, playerid, type) {
	
	count = $(calendarid).getElementsByTagName("div").length;
	
	if(calendar_act == 0){
		calendar_monthes = new Array();
		
		prevyear = year;
		prevmonth = month-(count-2);
		if(prevmonth <= 0){
			prevmonth = 12 + prevmonth;
			prevyear = year-1;
		}
		nextyear = year;
		nextmonth = month+(count-2);
		if(nextmonth >= 13){
			nextmonth = nextmonth - 12;
			nextyear = year+1;
		}
		
		$(calendarid).getElementsByTagName("div")[0].getElementsByTagName("a")[0].href="javascript:kk_calendar_move('"+calendarid+"',"+prevmonth+","+prevyear+","+playerid+",'"+type+"');";
		$(calendarid).getElementsByTagName("div")[count-1].getElementsByTagName("a")[0].href="javascript:kk_calendar_move('"+calendarid+"',"+nextmonth+","+nextyear+","+playerid+",'"+type+"');";
		
		kkget_month(calendarid, month, year, playerid, type);
	}
}

function kkget_month(calendarid, month, year, playerid, type){
		
				
		if(!playerid || playerid==0){
			new Ajax.Request(site_base_dir+"/ajaxcall/kkcalendarmove/"+type+"/0/calxx"+month+"xx"+year, {
			method:'get', 
			onSuccess: function(transport) {
							$(calendarid).innerHTML = transport.responseText;
					   },
			onCreate: function(transport) {
							$(calendarid).innerHTML = "<img src='"+site_base_dir_img+"loader2.gif' alt='PLAYALL Loading' style='display:block;margin:40px auto 0 auto;' />";							
			},
			onFailure: function(){ },
			onLoading: function(){ }
			});
			return;
		}
		
		count = $(calendarid).getElementsByTagName("div").length;
		
		new Ajax.Request(site_base_dir+"/ajaxcall/kkcalendarmove/"+type+"/"+playerid+"/calxx"+month+"xx"+year+"/?boxmode=0", {
			method:'get', 
			onSuccess: function(transport) {
							$(calendarid).getElementsByTagName("div")[calendar_act+1].innerHTML = transport.responseText;
							calendar_act++;
							if(calendar_act == count - 2){
								calendar_act = 0;
							} else {
								month++;
								if(month == 13){
									month = 1;
									year++;
								}
								kkget_month(calendarid, month, year, playerid, type);
							}
					   },
			onCreate: function(transport) { 
							$(calendarid).getElementsByTagName("div")[calendar_act+1].innerHTML = "<img src='"+site_base_dir_img+"loader2.gif' alt='PLAYALL Loading' style='display:block;margin:40px auto 0 auto;' />";							
			},
			onFailure: function(){ },
			onLoading: function(){ }
		});
}





function kk_calendar_show(popupid,showing, month, year, dayid, monthid, yearid, type) {

	calpopup = document.getElementById(popupid);
	
	if(showing == 1){
		if(month == 0){
			now = new Date();
			month = now.getMonth();
			year = now.getYear();
			
			for (i = 0; i < document.getElementsByName(monthid)[0].length; ++i){
			    if (document.getElementsByName(monthid)[0].options[i].selected == true){
					month = document.getElementsByName(monthid)[0].options[i].value;
					break;
				}
			}
			for (i = 0; i < document.getElementsByName(yearid)[0].length; ++i){
			    if (document.getElementsByName(yearid)[0].options[i].selected == true){
					year = document.getElementsByName(yearid)[0].options[i].value;
					break;
				}
			}
		}
		
		if(type == 'fraglive') {
			aCallName = 'kkcalendarshowfraglive';
		} else {
			aCallName = 'kkcalendarshow';
		}
		
		new Ajax.Request("ajaxcall/"+aCallName+"/"+popupid+"xx"+month+"xx"+year+"xx"+dayid+"xx"+monthid+"xx"+yearid, {
		method:'get', 
		onSuccess: function(transport) {
						calpopup.innerHTML = transport.responseText;
						calpopup.style.display = "block";
						calpopup.nextSibling.style.visibility = "hidden";
						
						document.getElementsByName(monthid)[0].onchange = function() {
							document.onclick = null;
							kk_calendar_show(popupid, 1, 0, 0, dayid, monthid, yearid);
						}
						document.getElementsByName(yearid)[0].onchange = function() {
							document.onclick = null;
							kk_calendar_show(popupid, 1, 0, 0, dayid, monthid, yearid);
						}
						document.getElementsByName(dayid)[0].onchange = function() {
							document.onclick = null;
							kk_calendar_show(popupid, 1, 0, 0, dayid, monthid, yearid);
						}
						firstclick = 1;
						document.onclick = function(event) {
							if(firstclick == 1 && document.all){
								firstclick = 0;
								return;
							}
							event = event ? event : window.event;
							if(event.target)
								eventobj = event.target;
							else
								eventobj = event.srcElement;
							if(eventobj.name == monthid || eventobj.name == yearid || eventobj.name == dayid)return;
							if(eventobj.className.indexOf("alendar") == -1){
								kk_calendar_show(popupid, 0, 0, 0, dayid, monthid, yearid);
							}
						};
				   },
		onCreate: function(transport) { /* .innerHTML = 'Creating request'; */},
		onFailure: function(){ /* .innerHTML = 'Unable to fetch message'; */ },
		onLoading: function(){ /* .innerHTML = 'Loading response ...'; */ }
		});
	} else {
		calpopup.style.display = "none";
		calpopup.nextSibling.style.visibility = "visible";
		document.getElementsByName(monthid)[0].onchange = null;
		document.getElementsByName(yearid)[0].onchange = null;
		document.onclick = null;
	}

}


function kk_calendar_click(day, month, year, dayid, monthid, yearid) {

	for (i = 0; i < document.getElementsByName(dayid)[0].length; ++i){
		if (document.getElementsByName(dayid)[0].options[i].value == day){
			document.getElementsByName(dayid)[0].options[i].selected = true;
			break;
		}
	}
	for (i = 0; i < document.getElementsByName(monthid)[0].length; ++i){
		if (document.getElementsByName(monthid)[0].options[i].value == month){
			document.getElementsByName(monthid)[0].options[i].selected = true;
			break;
		}
	}
	for (i = 0; i < document.getElementsByName(yearid)[0].length; ++i){
		if (document.getElementsByName(yearid)[0].options[i].value == year){
			document.getElementsByName(yearid)[0].options[i].selected = true;
			break;
		}
	}
}











/****** fraglive ********/

function ServerListShowHide(obj, id){
	var par = getParent(obj, "tr");
	if(obj.className == "Hide"){
		obj.className = "Show";
		par.className = "SectionCollapse";
	}
	else{
		obj.className = "Hide";
		par.className = "Section";
	}

	var next = nextObj(par , "tr");
	
	next = next.getElementsByTagName("table");
	
	for (var i=0; i< next.length; i++){

		if (next[i].className=="ServerList" || next[i].className=="ServerListShow"){
			if(next[i].className == "ServerListShow"){ 
				next[i].className ="ServerList";
			}
			else{ 
				next[i].className = "ServerListShow";
			}
		}
	}
	
	
}



/*
function YesNoQuestionPopup(question,yes,no){
	Event.observe(window, 'scroll', AjaxFitYesNoQuestionPopup, false);
	Event.observe(window, 'resize', AjaxFitYesNoQuestionPopup, false);

	NotSubmittedFormData = false;
	document.getElementById("YesNoQuestionPopupText").innerHTML=question.replace("\'","'");
	document.getElementById("YesNoQuestionPopupControls").innerHTML=yes.replace("\'","'") + no.replace("\'","'");
	document.getElementById("ContentBlocker").style.display="block";
	document.getElementById("YesNoQuestionPopup").style.display="block";
	//ContentBlocker();
	AjaxFitYesNoQuestionPopup();
}
*/

function Mouse (e)
{
	if(!e) e = window.event;
	if(!e) return null;
	var body = window.document.body;
	var mouse = {};
	// Position im Dokument
	mouse.Y = e.pageY ? e.pageY : e.clientY + document.documentElement.scrollTop;
	mouse.X = e.pageX ? e.pageX : e.clientX + document.documentElement.scrollLeft;
	// alert();
	// Position im Browserfenster
	mouse.clientX = e.clientX ? e.clientX : e.pageX - window.pageXOffset;
	mouse.clientY = e.clientY ? e.clientY : e.pageY - window.pageYOffset;
	return mouse;
}; 

function toolTip(e,tip,addClass){
	var obj = document.getElementById("toolTipBox");
	
	if (!obj || tip){
		if (!obj){
			var obj = Builder.node('div', 	{
											id: 'toolTipBox'
											},
											[tip]
			);
		}
		document.body.appendChild(obj);

		//if (obj.innerHTML==unescape(tip)) return;
		var mouse = Mouse (e);
		if (!mouse) return;
		if (!obj) return;
		if (!tip) return;
		obj.innerHTML=tip.match(/^[0-9\|]+$/) ? tooltipdetransform(tip) : tip.replace(/\{q\}/g,"'");
		obj.style.top = (mouse.Y+10) + "px";
		obj.style.left = (mouse.X+10) + "px";
		
		if (addClass){
			if (!obj.className.match(addClass)) obj.className += " " + addClass;
		}
		var innerWidth = window.innerWidth ? window.innerWidth : (document.body.clientWidth? document.body.clientWidth : document.documentElement.clientWidth);
		var scrollX = window.pageXOffset ? window.pageXOffset : (document.body.scrollLeft? document.body.scrollLeft : document.documentElement.scrollLeft);
		
		obj.style.display = "block";//alert (obj.offsetWidth+obj.offsetLeft);
		if ((obj.offsetWidth+obj.offsetLeft-scrollX)>innerWidth)obj.style.left = innerWidth-obj.offsetWidth-22+scrollX + "px";
	}
	else{
		if (obj && !tip){
			obj.parentNode.removeChild(obj);
		}
	}
}

function tooltipdetransform(text){
	if (!text.match(/[0-9\|]*/)) return text;
	var textAsArray = text.split("|");
	var res = "";
	for (var i = 0; i<textAsArray.length; i++) if (textAsArray[i]!="") res += chr(textAsArray[i]);
	//alert(String.fromCharCode(64));
	//return res;
	return html_entity_decode(res);
}

function ContentBlocker(){
	var obj = document.getElementById("ContentBlocker");
	if(obj){
		obj.fade({ duration: 0.1,afterFinish:  function(){obj.parentNode.removeChild(obj);} });
	}
	else{		
		var obj = Builder.node('div', 	{
										id: 'ContentBlocker',
										style: 'display:none;'
										},
										[tip]
		);
		
		document.body.appendChild(obj);
		
		obj.appear({ duration: 0.6 });
	}
}

function backgroundToBottom(obj){
	obj.style.backgroundPosition = "left bottom";
}
function backgroundToTop(obj){
	obj.style.backgroundPosition = "left top";
}

function prepareSurveyToSend(){
	dummyform = $("surveydummy");
	var textAnswers = dummyform.getElementsByTagName("textarea");
	var radioAnswers = dummyform.getElementsByTagName("input");
	var result = "";
	
	for (var i=0; i<radioAnswers.length; i++){
		if (radioAnswers[i].type=="radio" && radioAnswers[i].checked){
			result += radioAnswers[i].name.replace(/survey-/,"") + "|select|" + radioAnswers[i].value + "||";
		}
	}
	
	for (var i=0; i<textAnswers.length; i++){
		if (textAnswers[i].value){
			result +=  textAnswers[i].id.replace(/survey-/,"") + "|text|" + escape(textAnswers[i].value) + "||";
		}
	}
	
	$("answers").value=result;
	
	//$("survey").submit();
	document.forms.survey.submit();
}

function updateServerPlayers(sid) {
	
		new Ajax.Request(site_base_dir + "ajaxcall/updateserverplayers/"+sid+"/rand="+Math.round(Math.random()*1000000), {    
					method:'get',
					onSuccess: function(transport){ 
						try{
							var oldPlayers = trim($(sid+'-players').innerHTML);
							var newPlayers = trim(transport.responseText);
							if(newPlayers != oldPlayers) {
								$(sid+'-players').innerHTML = newPlayers;
								Effect.Pulsate(sid+'-players');
							}					
						} catch(e) {}
					},
					onFailure: function(){ } 
		}); 
}

function updateAllServerPlayers() {
	new Ajax.Request(site_base_dir + 'ajaxcall/updateallserverplayers/fl/', {    
					method:'get',
					onSuccess: function(transport){ 
						xml = transport.responseXML;
						numberServers = xml.getElementsByTagName("server").length;											
						
						for (i=0; i<numberServers; i++) {
							serverID  = xml.getElementsByTagName("sid")[i].firstChild.nodeValue;
							serverPlayers  = xml.getElementsByTagName("players")[i].firstChild.nodeValue;
							if($(serverID+'-players')) {
								if($(serverID+'-players').innerHTML != serverPlayers) {
									$(serverID+'-players').innerHTML = serverPlayers;
									Effect.Pulsate(serverID+'-players');
								}
							}
						}
					},
					onFailure: function(){ } 
		});
}

function ismaxlength(obj){
	var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : ""
	
	if (obj.getAttribute && obj.value.length>mlength) {
		obj.value=obj.value.substring(0,mlength);
	}
}

function trim (zeichenkette) {
  // Erst führende, dann Abschließende Whitespaces entfernen
  // und das Ergebnis dieser Operationen zurückliefern
  return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}


var playerrelation_interval = 15000;
var playerrelation_pause = false;
var playerrelation_show;
var playerrelation_total;
var playerrelation_aktiv = false;
function changeRelations(hide,show,total,interval){
	if (playerrelation_aktiv) window.clearTimeout(playerrelation_aktiv);
	if (hide==0 && show==0){
		if (playerrelation_aktiv){
			window.clearTimeout(playerrelation_aktiv);
			playerrelation_aktiv = null;
			playerrelation_pause = true;
			$("relationRotationStop").innerHTML=">";
			return;
		}
		else{
			playerrelation_aktiv = window.setTimeout(function(){changeRelations(playerrelation_show,playerrelation_show+1,total,playerrelation_interval);}, playerrelation_interval);
			playerrelation_pause = false;
			$("relationRotationStop").innerHTML="||";
			return 
		}
	}
	else if (hide==1 && show==1){
		if (playerrelation_pause){
			$('relationArray-'+playerrelation_show).hide();
			playerrelation_show++;
			if (playerrelation_show>=total) playerrelation_show=0;
			Effect.Appear('relationArray-'+playerrelation_show);
			return;
		}
		else{
			window.clearTimeout(playerrelation_aktiv);
			$('relationArray-'+playerrelation_show).hide();
			playerrelation_show++;
			if (playerrelation_show>=total) playerrelation_show=0;
			Effect.Appear('relationArray-'+playerrelation_show);
			playerrelation_aktiv = window.setTimeout(function(){changeRelations(playerrelation_show,playerrelation_show+1,total,playerrelation_interval);}, playerrelation_interval);
			return;
		}
	}
	else if (hide==-1 && show==-1){
		if (playerrelation_pause){
			$('relationArray-'+playerrelation_show).hide();
			playerrelation_show--;
			if (playerrelation_show<0) playerrelation_show=total-1;
			Effect.Appear('relationArray-'+playerrelation_show);
			return;
		}
		else{
			$('relationArray-'+playerrelation_show).hide();
			playerrelation_show--;
			if (playerrelation_show<0) playerrelation_show=total-1;
			Effect.Appear('relationArray-'+playerrelation_show);
			playerrelation_aktiv = window.setTimeout(function(){changeRelations(playerrelation_show,playerrelation_show-1,total,playerrelation_interval);}, playerrelation_interval);
			return;
		}
	}
	if (hide>=0) $('relationArray-'+hide).hide();
	if (show>=total) show=0;
	
	playerrelation_show = show;
	playerrelation_total = total;
	Effect.Appear('relationArray-'+playerrelation_show);
	playerrelation_aktiv = window.setTimeout(function(){changeRelations(playerrelation_show,playerrelation_show+1,total,playerrelation_interval);}, playerrelation_interval);
}

function forumDeepLink(){
	var loc = location.href.split("#");
	if (loc.length<2) return;	
	loc = loc[1];
	
	var forum_loc = window.frames[0].location.href.split("profileurl");
	if (forum_loc.length<2) return;
	forum_loc = forum_loc[0] + loc;
	
	window.frames[0].location.href = forum_loc;
}

function blogDeepLink(){
	var loc = location.href.split("#");
	if (loc.length<2) return;	
	loc = loc[1];
	
	var forum_loc = window.frames[0].location.href.split("profileurl");
	if (forum_loc.length<2) return;
	forum_loc = forum_loc[0] + loc;
	
	window.frames[0].location.href = forum_loc;
}

// all games for private server (of this user)
var psAllGames = new Array();

// add a game to array
function addPrivateServerGame(gameInput) {
	psAllGames.push(gameInput);	
}

function set_private_server_game(class_name,game,mode){
	$$("."+class_name).each(function(tr){tr.className = tr.className.replace(/activeprivateservergame/,"");});
	game.className += " activeprivateservergame";
	var game_short = game.id.replace(/privateservergame-/,"");
	$(class_name + "input").value = game_short;

	// hide other game dropdowns
	psAllGames.each( function(curGame) {
		if(curGame != game_short) {
			$("privateserverdetails-" + curGame).hide();
		}
	});
	// show selected game dropdowns
	$("privateserverdetails-" + game_short).show();
	
	
	// set default values on load (check if no prefill after failed submit)
	if(mode == 'load') {		
		// if no prefill
		if($("privateservermapinput").value == "") {		
			$("privateservermapinput").value = $("privateservermap-" + game_short).value;
		}
		
		// if no prefill
		if($("privateserverconfiginput").value == "") {
			$("privateserverconfiginput").value= $("privateserverconfig-" + game_short).value;
			configID = $("privateserverconfig-" + game_short).value;
			$('privateserverConfigDetails').innerHTML = $("configDetails-" + configID).value;			
		}
		
		// if no prefill
		if($("privateserverstakeinput").value == "") {		
			$("privateserverstakeinput").value = $("privateserverstake").value;
		}
		
		// if no prefill
		if($("privateserverlocationinput").value == "") {		
			$("privateserverlocationinput").value = $("privateserverlocation").value;
		}
	} else {
		// user changes game
		$("privateservermapinput").value = $("privateservermap-" + game_short).value;
		$("privateserverconfiginput").value= $("privateserverconfig-" + game_short).value;
		configID = $("privateserverconfig-" + game_short).value;
		$('privateserverConfigDetails').innerHTML = $("configDetails-" + configID).value;
		$("privateserverstakeinput").value = $("privateserverstake").value;
		$("privateserverlocationinput").value = $("privateserverlocation").value;
	}
}

function reconstruct_form_data (game) {	
	// reconstruct players
	var players = new Array;
	var players = $("privateserverplayersinput").value.split("|");
	$$(".privateserverplayerscheckbox").each(function (obj){ var user = obj.id.replace(/user-/g,"");if (in_array(user,players)) select_player_div(obj);} );	
	
	// reconstruct dropdowns
	var map = $("privateservermapinput").value;
	for(i = 0; i < $("privateservermap-"+game).options.length; i++) {
		if($("privateservermap-"+game).options[i].value == map) {
			$("privateservermap-"+game).options[i].selected = true;
		}		
	}	
	
	var config = $("privateserverconfiginput").value;
	for(i = 0; i < $("privateserverconfig-"+game).options.length; i++) {
		if($("privateserverconfig-"+game).options[i].value == config) {
			$("privateserverconfig-"+game).options[i].selected = true;
		}		
	}
	$('privateserverConfigDetails').innerHTML = $("configDetails-" + config).value;
	
	var stake = $("privateserverstakeinput").value;
	for(i = 0; i < $("privateserverstake").options.length; i++) {
		if($("privateserverstake").options[i].value == stake) {
			$("privateserverstake").options[i].selected = true;
		}		
	}
	
	var location = $("privateserverlocationinput").value
	for(i = 0; i < $("privateserverlocation").options.length; i++) {
		if($("privateserverlocation").options[i].value == location) {
			$("privateserverlocation").options[i].selected = true;
		}		
	}
}

function reconstruct_challenge_players() {	
	var players = new Array;
	var players = $("privateserverplayersinput").value.split("|");
	$$(".privateserverplayerscheckbox").each(function (obj){
		var user = obj.id.replace(/user-/g,"");
		if (in_array(user,players)) {
			select_player_div(obj);
		}
	} );
}

function config_details_challenge() {	
	var configCh = $("config").value;
	$('privateserverConfigDetails').innerHTML = $("configDetails-" + configCh).value;
}


function select_player_div(obj){
	obj.checked = "checked";
	obj.parentNode.style.borderColor = '#693';
	obj.parentNode.style.backgroundColor = '#99BF3B';	
}



function set_private_server_players(checkboxContainer, inputObj){
	var players = new Array();
	var checkboxes = checkboxContainer.getElementsByTagName("input");
	for (var i=0; i<checkboxes.length; i++){
		if (checkboxes[i].type=="checkbox" && checkboxes[i].checked==true) players.push(checkboxes[i].id.replace(/user-/g,""));
	}
	inputObj.value = players.join("|");
}

Array.prototype.in_array = function(needle) {
for(var i=0; i < this.length; i++) if(this[ i] === needle) return true;
return false;
}

function in_array(item,arr) {
	for(p=0;p<arr.length;p++) if (item == arr[p]) return true;
	return false;
}

function openServerDetails(elemId) {
	//add "-content" to the trigger id to have box id and toggle visibility
	var contentId = elemId +'-content';
	// alert('hier')
	$(contentId).toggle();
	if ($(contentId).visible())	{
		//start data request
		AjaxSessionInfosUpdaters[elemId] = window.setInterval("AjaxRequestSessionInfo("+elemId+")",10000);
		AjaxRequestSessionInfo(elemId);
	} else {
		try	{
			window.clearInterval(AjaxSessionInfosUpdaters[elemId]);
		} catch(Exception) {}
	}
	
	location.href=location.href.replace("#directjoin","") +"#directjoin";
}



// server queueing
function queueUser(sid) {
	try {
		new Ajax.Request(site_base_dir + "ajaxcall/queue/add/"+sid+"/rand="+Math.round(Math.random()*1000000), {    
			method:'get',
			onSuccess: function(transport){ 			
				try{
					if(trim(transport.responseText) == "added") {
						$('session_'+sid+'_queue_button').hide();
						$('session_'+sid+'_queue_button_inactive2').hide();
						$('session_'+sid+'_queue_button_inactive').show();
						getQueue();					
					}
				} catch(e) {}
			},
			onFailure: function(){ } 
		});
	} catch(e) {}
}


// server queueing
function leaveQueue(sid) {
	try {
		new Ajax.Request(site_base_dir + "ajaxcall/queue/leave/"+sid+"/rand="+Math.round(Math.random()*1000000), {    
			method:'get',
			onSuccess: function(transport){ 			
				try{
					// reload queue list
					getQueue();
				} catch(e) {}
			},
			onFailure: function(){ } 
		});
	} catch(e) {}
}

var timeOutServerQueue;
// server queueing
function getQueue() {
	try {
		window.clearTimeout(timeOutServerQueue);
		
		new Ajax.Request(site_base_dir + "ajaxcall/queue/get/rand="+Math.round(Math.random()*1000000), {    
			method:'get',
			onSuccess: function(transport){ 			
				try{
					queueObj = jsonParse(transport.responseText);	
					
					if(queueObj.length > 0) {				
						output = '<div class="text">&nbsp;</div>';
						
						queueObj.each(function(input) {					
							// check if threshold is reached and autojoin server					
							
							if(input.queued >= input.threshold) {
								autoJoin(input.link, input.sid);
							}
							output += '<div class="queue-server"><img title="" src="'+site_base_dir_img+'icons/games/'+input.gameshort+'_m.png" alt="" class="logo" /><span class="server-name"><a href="'+site_base_dir+input.link+input.sid+'">'+input.serverName+'</a></span><br/><a href="javascript:leaveQueue(\''+input.sid+'\')" class="leave">'+input.trLeave+'</a>'+input.queued+'/'+input.threshold+' '+input.trPlayers+'</div>';
						});	
						
						//output += '<div class="clearer"></div>';
						
						$('lobby').innerHTML = output;
						
						if(!$('lobby').visible()) {
							Effect.BlindDown('lobby');
						}
					} else {
						if($('lobby').visible()) {
							Effect.BlindUp('lobby');
						}					
					}
				
				} catch(e) {}
			},
			onFailure: function(){ } 
		});
		
		timeOutServerQueue = setTimeout(getQueue, 60000);
	} catch(e) {}
}


function autoJoin(link, sid) {
	new Ajax.Request(site_base_dir + "ajaxcall/queue/clear/rand="+Math.round(Math.random()*1000000), {    
		method:'get',
		onSuccess: function(transport){ 			
			try{
				if(trim(transport.responseText) == "cleared") {
					window.location.href = site_base_dir+link+'-/logic/processwrapper/pjsinit/sid='+sid;				
				}
			} catch(e) {}
		},
		onFailure: function(){ } 
	});
}


function saveElementStatus(id, value) {
	if(isloggedin) {	
		var url = site_base_dir + 'ajaxcall/setelementstatus/'+id+'/'+value;
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) { }
		});
	}
}



// Copyright (C) 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * Parses a string of well-formed JSON text.
 *
 * If the input is not well-formed, then behavior is undefined, but it is
 * deterministic and is guaranteed not to modify any object other than its
 * return value.
 *
 * This does not use `eval` so is less likely to have obscure security bugs than
 * json2.js.
 * It is optimized for speed, so is much faster than json_parse.js.
 *
 * This library should be used whenever security is a concern (when JSON may
 * come from an untrusted source), speed is a concern, and erroring on malformed
 * JSON is *not* a concern.
 *
 *                      Pros                   Cons
 *                    +-----------------------+-----------------------+
 * json_sans_eval.js  | Fast, secure          | Not validating        |
 *                    +-----------------------+-----------------------+
 * json_parse.js      | Validating, secure    | Slow                  |
 *                    +-----------------------+-----------------------+
 * json2.js           | Fast, some validation | Potentially insecure  |
 *                    +-----------------------+-----------------------+
 *
 * json2.js is very fast, but potentially insecure since it calls `eval` to
 * parse JSON data, so an attacker might be able to supply strange JS that
 * looks like JSON, but that executes arbitrary javascript.
 * If you do have to use json2.js with untrusted data, make sure you keep
 * your version of json2.js up to date so that you get patches as they're
 * released.
 *
 * @param {string} json per RFC 4627
 * @param {function} opt_reviver optional function that reworks JSON objects
 *     post-parse per Chapter 15.12 of EcmaScript3.1.
 *     If supplied, the function is called with a string key, and a value.
 *     The value is the property of 'this'.  The reviver should return
 *     the value to use in its place.  So if dates were serialized as
 *     {@code { "type": "Date", "time": 1234 }}, then a reviver might look like
 *     {@code
 *     function (key, value) {
 *       if (value && typeof value === 'object' && 'Date' === value.type) {
 *         return new Date(value.time);
 *       } else {
 *         return value;
 *       }
 *     }}.
 *     If the reviver returns {@code undefined} then the property named by key
 *     will be deleted from its container.
 *     {@code this} is bound to the object containing the specified property.
 * @return {Object|Array}
 * @author Mike Samuel <mikesamuel@gmail.com>
 */
var jsonParse = (function () {
  var number
      = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
  var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
      + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
  var string = '(?:\"' + oneChar + '*\")';

  // Will match a value in a well-formed JSON file.
  // If the input is not well-formed, may match strangely, but not in an unsafe
  // way.
  // Since this only matches value tokens, it does not match whitespace, colons,
  // or commas.
  var jsonToken = new RegExp(
      '(?:false|true|null|[\\{\\}\\[\\]]'
      + '|' + number
      + '|' + string
      + ')', 'g');

  // Matches escape sequences in a string literal
  var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g');

  // Decodes escape sequences in object literals
  var escapes = {
    '"': '"',
    '/': '/',
    '\\': '\\',
    'b': '\b',
    'f': '\f',
    'n': '\n',
    'r': '\r',
    't': '\t'
  };
  function unescapeOne(_, ch, hex) {
    return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16));
  }

  // A non-falsy value that coerces to the empty string when used as a key.
  var EMPTY_STRING = new String('');
  var SLASH = '\\';

  // Constructor to use based on an open token.
  var firstTokenCtors = { '{': Object, '[': Array };

  var hop = Object.hasOwnProperty;

  return function (json, opt_reviver) {
    // Split into tokens
    var toks = json.match(jsonToken);
    // Construct the object to return
    var result;
    var tok = toks[0];
    if ('{' === tok) {
      result = {};
    } else if ('[' === tok) {
      result = [];
    } else {
      throw new Error(tok);
    }

    // If undefined, the key in an object key/value record to use for the next
    // value parsed.
    var key;
    // Loop over remaining tokens maintaining a stack of uncompleted objects and
    // arrays.
    var stack = [result];
    for (var i = 1, n = toks.length; i < n; ++i) {
      tok = toks[i];

      var cont;
      switch (tok.charCodeAt(0)) {
        default:  // sign or digit
          cont = stack[0];
          cont[key || cont.length] = +(tok);
          key = void 0;
          break;
        case 0x22:  // '"'
          tok = tok.substring(1, tok.length - 1);
          if (tok.indexOf(SLASH) !== -1) {
            tok = tok.replace(escapeSequence, unescapeOne);
          }
          cont = stack[0];
          if (!key) {
            if (cont instanceof Array) {
              key = cont.length;
            } else {
              key = tok || EMPTY_STRING;  // Use as key for next value seen.
              break;
            }
          }
          cont[key] = tok;
          key = void 0;
          break;
        case 0x5b:  // '['
          cont = stack[0];
          stack.unshift(cont[key || cont.length] = []);
          key = void 0;
          break;
        case 0x5d:  // ']'
          stack.shift();
          break;
        case 0x66:  // 'f'
          cont = stack[0];
          cont[key || cont.length] = false;
          key = void 0;
          break;
        case 0x6e:  // 'n'
          cont = stack[0];
          cont[key || cont.length] = null;
          key = void 0;
          break;
        case 0x74:  // 't'
          cont = stack[0];
          cont[key || cont.length] = true;
          key = void 0;
          break;
        case 0x7b:  // '{'
          cont = stack[0];
          stack.unshift(cont[key || cont.length] = {});
          key = void 0;
          break;
        case 0x7d:  // '}'
          stack.shift();
          break;
      }
    }
    // Fail if we've got an uncompleted object.
    if (stack.length) { throw new Error(); }

    if (opt_reviver) {
      // Based on walk as implemented in http://www.json.org/json2.js
      var walk = function (holder, key) {
        var value = holder[key];
        if (value && typeof value === 'object') {
          var toDelete = null;
          for (var k in value) {
            if (hop.call(value, k) && value !== holder) {
              // Recurse to properties first.  This has the effect of causing
              // the reviver to be called on the object graph depth-first.

              // Since 'this' is bound to the holder of the property, the
              // reviver can access sibling properties of k including ones
              // that have not yet been revived.

              // The value returned by the reviver is used in place of the
              // current value of property k.
              // If it returns undefined then the property is deleted.
              var v = walk(value, k);
              if (v !== void 0) {
                value[k] = v;
              } else {
                // Deleting properties inside the loop has vaguely defined
                // semantics in ES3 and ES3.1.
                if (!toDelete) { toDelete = []; }
                toDelete.push(k);
              }
            }
          }
          if (toDelete) {
            for (var i = toDelete.length; --i >= 0;) {
              delete value[toDelete[i]];
            }
          }
        }
        return opt_reviver.call(holder, key, value);
      };
      result = walk({ '': result }, '');
    }

    return result;
  };
})();

function fitNewsSheet(id){
	var obj = $(id);
	var bg = $(id+'-bg');
	bg.style.height = (obj.offsetHeight - 1032) + "px";
}

function getWindowSize (w) {
	var width, height;
	w = w ? w : window;
	width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
	return { width: width, height: height };
}

/* Dual licensed under the MIT and GPL. http://phpjs.org/pages/license */
function chr(codePt) {
    // Converts a codepoint number to a character  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/chr
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: chr(75);
    // *     returns 1: 'K'
    // *     example 1: chr(65536) === '\uD800\uDC00';
    // *     returns 1: true
    
    if (codePt > 0xFFFF) { // Create a four-byte string (length 2) since this code point is high
                                             //   enough for the UTF-16 encoding (JavaScript internal use), to
                                             //   require representation with two surrogates (reserved non-characters
                                             //   used for building other characters; the first is "high" and the next "low")
        codePt -= 0x10000;
        return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF));
    }
    else {
        return String.fromCharCode(codePt);
    }
}

function highlightCurrentSubSection(){
	if (!Prototype.Browser.IE) return;
	var obj = document.getElementsByClassName("iecurrent");
	
	if (obj && obj.length)obj[obj.length-1].addClassName('iecurrent-replacement');
	
}

/* Dual licensed under the MIT and GPL. http://phpjs.org/pages/license */
function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/get_html_translation_table    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
     useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

/* Dual licensed under the MIT and GPL. http://phpjs.org/pages/license */
function html_entity_decode (string, quote_style) {
    // Convert all HTML entities to their applicable characters  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/html_entity_decode    // +   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)
    // +   bugfixed by: Onno Marsman    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    } 
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}

function reload_after(time){
	setInterval(function(){location.reload();}, time);

}



function surveyCheckMandatory(checkFields) {
	var checkedFields = $$(':checked');
	
	for(i=0; i<checkFields.length; i++) {
		found = false;
		for(x=0; x<checkedFields.length; x++) {
			if(found == false) {
				if(checkedFields[x].name == checkFields[i]) {
					// mandatory field is checked
					found = true;
				}
			}		
		}
		
		if(found == false) {		
			$('surveyerrormessage').show();
			return false;
		}
	}
	
	return true;
}



Effect.BlendRight = function(element, element2) {
  element = $(element);
  element2 = $(element2);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
	scaleContent: false,
	scaleY: false,
	scaleFrom: 8,
	scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
	restoreAfterFinish: true,
	afterSetup: function(effect) {
	  effect.element.makeClipping().setStyle({
		width: '0px',
		height: effect.dims[0] + 'px'
	  }).show();
	},
	afterFinishInternal: function(effect) {
	  effect.element.undoClipping();
	  element2.show();
	}
  }, arguments[1] || { }));
};



Effect.BlendLeft = function(element, element2) {
  element = $(element);
  element2 = $(element2);
  element.makeClipping();
  return new Effect.Scale(element, 8,
    Object.extend({ scaleContent: false,
      scaleY: false,
      scaleMode: 'box',
      scaleContent: false,
      restoreAfterFinish: true,
      afterSetup: function(effect) {
        effect.element.makeClipping().setStyle({
          height: effect.dims[0] + 'px'
        }).show();
      },
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      },
	  beforeStart: function(effect) {
		element2.hide()
	  }
    }, arguments[1] || { })
  );
};

function partner() {
	partnerfieldwidth = 0;
	$$('.partner-image').each(function(obj){
		partnerfieldwidth+=(obj.getWidth()+21);
		$('moveit').setStyle({width:partnerfieldwidth+"px"});					
	});
	
	Event.observe('partnerMoveRight', 'mouseover', function(){
		var left = ($("moveit").getStyle("left")!=null) ? $("moveit").getStyle("left") : 0;
		var position = parseFloat(left);
		if(position > (950-partnerfieldwidth)) {
			var partnerMoveRight = new Effect.MoveBy('moveit', 0, -(partnerfieldwidth-950+position),{duration:(partnerfieldwidth-950+position)/150, transition:Effect.Transitions.sinoidal});
			Event.observe('partnerMoveRight', 'mouseout', function(){
				partnerMoveRight.cancel();
			});
		}
	});
	
	Event.observe('partnerMoveLeft', 'mouseover', function(){
		var left = ($("moveit").getStyle("left")!=null) ? $("moveit").getStyle("left") : 0;
		var position = parseFloat(left);
		if(position < 0) {
			var partnerMoveLeft = new Effect.MoveBy('moveit', 0, -position, {duration:(-position)/150, transition:Effect.Transitions.sinoidal});
			Event.observe('partnerMoveLeft', 'mouseout', function(){
				partnerMoveLeft.cancel();
			});
		}
	});

}
					
// GAME NAVIGATION

function gamerouting(path, lobby) {
	var path_array = path.split("/");
	
	var routing = true;
	var current = "";
	var befor = "";
	var zone = "";
	if(path_array.length == 1) {
		$("gamezones").addClassName(path_array[0]);
		$(path_array[0]).addClassName("active");
		$(path_array[0]+"-content").addClassName("active");
		
		$$("#"+path_array[0]+"-gamemodes div")[0].addClassName("active");
		$($$("#"+path_array[0]+"-gamemodes div")[0].id+"-content").addClassName("active");		
	} else {
		var path_array_length = path_array.length;
		for(var i = 0; i < path_array_length; i++) {
			if(routing) {
				befor = current;
				if(i==0) {
					current = path_array[i];
					zone = path_array[i];
				} else {
					current = current+"-"+path_array[i];
				}
				
				if(i==1 && !$(current)) {
					$$("#"+befor+"-gamemodes div")[0].addClassName("active");
					$($$("#"+befor+"-gamemodes div")[0].id+"-content").addClassName("active");	
					routing = false;
					continue;
				}

				if(path_array[i]== "void") {
					$(path_array[0]+"-"+path_array[1]+"-content").removeClassName("active");
				}
					
				if($(current)) {
					if(i==0) {
						$("gamezones").addClassName(current);
					}
					
					$(current).addClassName("active");	
					$(current).addClassName("current");
					
					if( i!=2) {
						$(current+"-content").addClassName("active");
					}
				}
			}
		}
	}
	
	// toggle the lobby
	if(lobby) {
		$("gameslobby-content").addClassName("is_visible");
		$("gameslobby").addClassName("active");
	} else {
		$("gameslobby-content").setStyle({
			"display":"none"
		});
	}
}

function gamenavigationtoggle(obj) {
	var gamezone = (obj.hasClassName("gamezone")) ? true : false;
	var objId = obj.id;
	
	if(gamezone)
		var hide = $$(".gameicon, .gamemode-content, .gamemode, .gamezone-content, .gamezone");
	
	else
		var hide = $$(".gameicon, .gamemode-content, .gamemode");

	
	// hide all elements
	hide.each(function(obj){
		obj.removeClassName("active");
		obj.removeClassName("void");
	});	
	
	// activate selected elements
	obj.addClassName("active");
	$(objId+"-content").addClassName("active");

	if(gamezone) {
		obj.parentNode.removeClassName(obj.parentNode.classNames());
		
		obj.parentNode.addClassName(objId);
		$$("#"+objId+"-gamemodes div")[0].addClassName("active");
		$($$("#"+objId+"-gamemodes div")[0].id+"-content").addClassName("active");
	}
}
var infoSetTimeout = null;

function gamenavigationinfotext_on(obj) {
	this.obj = obj;
	infoSetTimeout = setTimeout(function(){
		$(obj.parentNode.id+"-infotext").addClassName("active");
	}, 250);
	
}

function gamenavigationinfotext_off(obj) {
	clearTimeout(infoSetTimeout);
	$(obj.parentNode.id+"-infotext").removeClassName("active");
}

function feedbackbarBottom() {
	if($("feedbackbar").hasClassName("active")) {
		new Effect.Morph($("feedbackbar-content"), {
			style: 'height:0px;', 
			duration: 0.5,
			afterFinish: function() {
				$("feedbackbar").removeClassName("active");
			}
		});
	} else {
		new Effect.Morph($("feedbackbar-content"), {
			style: 'height:150px;', 
			duration: 0.5, 
			afterFinish: function() {
				$("feedbackbar").addClassName("active");
			}
		});
	}
}