var IE = document.all?true:false

if ( !IE ) document.captureEvents(Event.MOUSEMOVE)

document.onmousemove = getMPos;

var x = 0;
var y = 0;

window.changedNotes=Array();

window.groupsSelected=0;

function chat() {
	window.open("http://www.lightirc.com/start/lightIRC.swf?host=tal.de.eu.gamesurge.net&nickselect=no&nick=feorar_%25&autojoin=#feorar", "Feorar-Chat", "width=640,height=480,scrollbars=no");
	window.focus();
	error("Der Chat wurde in einem seperaten Fenster ge&ouml;ffnet. Du ben&ouml;tigst den Adobe Flash Player, um den Chat zu benutzen.");
}

function noop() {
	return;
}

function wrapper_ress_tip(ressource) {
	window.RTTimeout=setTimeout('ress_tip('+ressource+')',500);
}

function wrapper_no_ress_tip() {
	if ( window.RTTimeout ) clearTimeout(window.RTTimeout);
	hdiv();
}

function ress_tip(ressource) {
	var tips=Array();
	tips[0]='<b>Edelsteine</b><br>Edelsteine werden f&uuml;r bestimmte zus&auml;tzliche Funktionen des Spiels wie Profilbild oder Dorf-&Uuml;bersichtsliste ben&ouml;tigt.<br> Edelsteine erh&auml;ltst Du, wenn Du dem Feorar-Projekt hilfst, indem Du die Verbreitung Feorars f&ouml;rderst (Edelsteine werden <b>nicht</b> f&uuml;r Geld verkauft!).';
	tips[1]='<b>Gold</b><br>Gold ben&ouml;tigst Du zum Ausbau des Schlosses und zum Gr&uuml;nden und Erobern neuer Siedlungen. Mit jedem gebauten Geb&auml;ude erh&auml;ltst Du eine bestimmte Menge Gold.';
	tips[2]='<b>Holz</b><br>Du ben&ouml;tigst viel Holz zum Ausbau von Geb&auml;uden und zum Bau von Schiffen.<br>Holz wird von Holzf&auml;llern abgebaut. Wenn Deine Siedlung im Wald liegt, produzierst Du mehr Holz. Baue ein S&auml;gewerk, um Deine Produktion zus&auml;tzlich zu steigern.';
	tips[3]='<b>Stein</b><br>Stein ist ein elementarer Rohstoff, der so gut wie &uuml;berall ben&ouml;tigt wird.<br>Stein wird in Steinbrüchen gewonnen und dann zu Ziegeln oder Bausteinen verarbeitet. Wenn Deine Siedlung im Sumpf liegt, produzierst Du mehr Stein. Baue einen Steinmetz, um Deine Produktion zus&auml;tzlich zu steigern.';
	tips[4]='<b>Eisen</b><br>Eisen ben&ouml;tigst Du haupts&auml;chlich zur Ausr&uuml;stung Deiner Soldaten.<br>Eisen wird in Eisenminen gef&ouml;rdert. Wenn Deine Siedlung im Gebirge liegt, produzierst Du mehr Eisen. Baue eine Eisengie&szlig;erei, um Deine Produktion zus&auml;tzlich zu steigern.';
	tips[5]='<b>Nahrung</b><br>Jeder deiner Dorfbewohner und Soldaten ben&ouml;tigt st&auml;ndig Nahrung, um zu &uuml;berleben. Deshalb sinkt Deine Produktion mit wachsender Siedlungs- und Armeegr&ouml;&szlig;e.<br>Nahrung wird auf Getreidefeldern abgebaut. Liegt Deine Siedlung am Wasser, so k&ouml;nnen Deine Bauern auch Fische fangen; Du produzierst deshalb mehr Nahrung. Baue eine Getreidem&uuml;hle und eine B&auml;ckerei, um Deine Produktion zus&auml;tzlich zu steigern.';
	tips[6]='<b>Silber</b><br>Silber ist eine wichtige W&auml;hrung im Handel und wird vor allem f&uuml;r Rituale wie die Anrufung eines Helden ben&ouml;tigt.<br>Silber wird in geringen Mengen in Silberminen gefunden. Mit einer M&uuml;nzpr&auml;gerei kannst Du den Wert des produzierten Silbers verbessern und so die Produktion erh&ouml;hen.';
	tips[7]='<b>Lagerkapazit&auml;t</b><br>Du kannst nur eine bestimmte Menge an Rohstoffen lagern. Wenn Du mehr Rohstoffe einnimmst, als Du lagern kannst, gehen &uuml;berz&auml;hlige Rohstoffe verloren.<br>Baue ein Rohstofflager, um Deine Lagerkapazit&auml;t zu erh&ouml;hen.';
	tips[8]='<b>Einwohner</b><br>Mit dem Ausbau eines Geb&auml;udes w&auml;chst Dein Dorf um den bei "Versorgungskosten" angegebenen Wert an Einwohnern.';
	
	sdiv(tips[ressource],true);
}

function helpme() {
	$j('#questionnanswer').fadeIn(500);
}

function getAnswers() {
	$('answer').style.textAlign='center';
	$('answer').innerHTML='<img src="/img/spinner.gif">';
	var question=$('question').value;
	$j.post('/ajax/getFAQ.php', 
		{ question:question },
		function(data) {
			$('answer').innerHTML='';
			$('answer').style.textAlign='left';
			$('answer').innerHTML=data;
		}
	);
}

function setCooldownImage(objid,left,ges) {
	percentage=left/ges;
	percentage*=100;
	percentage*=3.6;
	percentage=Math.round(percentage);
	
	percentage=360-percentage;
	
	obj=$(objid);
	obj.src='/img/cd_images/'+percentage+'.png';
// 	alert(obj.src);
	obj.number=percentage;
	
// 	alert(percentage);
	if ( percentage < 0 || percentage > 360 ) {
// 		alert('set');
		$(objid+'_frame').src="/img/abilities/frame_active.png";
		return 0;
	}
	
	perStep=ges/360;
// 	alert(perStep);
	setTimeout('incCooldownImage(\''+objid+'\',\''+perStep+'\')',perStep*1000);
}

function incCooldownImage(objid,perStep) {
	obj=$(objid);
	next=Number(obj.number)+1;
	
	if ( next < 0 || next > 360 ) {
// 		alert('set');
		$(objid+'_frame').src="/img/abilities/frame_active.png";
		return 0;
	}
// 	alert(next);
	obj.src='/img/cd_images/'+next+'.png';
	obj.number=next;
// 	alert(perStep);
	
	setTimeout('incCooldownImage(\''+objid+'\',\''+perStep+'\')',perStep*1000);
}

function selectGroup(gid) {

}

function checkPass() {
	setTimeout('rlyCheckPass()',30);
	setTimeout('rlyCheckNick()',30);
}

function newNote() {
	if ( ! window.drag ) window.drag=0;
	window.drag+=1;
	id='note_'+window.drag;
	
// 	alert(id);
	
	d=new Date;
	h=d.getHours();
	m=d.getMinutes();
	s=d.getSeconds();
	if ( h < 10 ) h="0"+h;
	if ( m < 10 ) m="0"+m;
	if ( s < 10 ) s="0"+s;
	
	str=d.getDate()+"."+d.getMonth()+"."+d.getFullYear()+", "+h+":"+m+":"+s;
	
	obj=$('notes');
	obj.id='notes_old_abandoned_'+id;
	
	obj.innerHTML+='<div class="note" onmouseout="setT_o(this.id);" onmouseover="clearTimeout($(this.id).to); setCurrentNote(this.id);" style="z-index:999999; position:absolute; left:'+window.x+'px; top:'+window.y+'px;" id="'+id+'"><div id="date_'+id+'" style="background-image:url(/img/33b.png); cursor:default;">'+str+'</div><div style="position:absolute; right:2px; top:0px; cursor:pointer;" onclick="db_removeNote(\''+id+'\'); $j($(\''+id+'\')).hide(600); $j($(\''+id+'\')).destroyed=1; ">x</div><textarea id="text_'+id+'" onfocus="window.spFocus=true;" onchange="db_uploadNote_saveContents(this);" onblur="window.spFocus=false;" cols=5 rows=5 onmouseover="clearTimeout($(\''+id+'\').to);" style="background-color:transparent; border:0px; width:100%; height:100%; margin-top:2px; margin-left:1px; margin-right:1px; margin-bottom:5px;" id="text_'+id+'"></textarea></div> <div id="notes"></div>';
	$(id).notSavedYet=1;
// 	alert($(id).notSavedYet);
	$j($(id)).hide();
	$j($(id)).show(500);
}

function db_uploadNote_saveContents(obj) {
// 	alert(window.changedNotes);
	sendData='';
	id=obj.id.replace('text_note_','');
	if ( obj.realIdentifier ) id=obj.realIdentifier;
	
// 	alert("id: "+id+"; realIdent: "+obj.realIdentifier);
	
	sendData=id+'@'+obj.value;
	
// 	alert($('note_'+id).notSavedYet);
	
	if ( ! $('note_'+id).notSavedYet ) {
		sendData=encodeURIComponent(sendData);
		
		new Ajax.Request('/ajax/saveNotes.php?ac=saveText&queryString='+sendData);	
	}
	else {
		sendData=$('date_note_'+id).innerHTML+'[**-OneFromAnotherEntrySeperator##~]'+$('text_note_'+id).value+'[**-OneFromAnotherEntrySeperator##~]'+$('note_'+id).style.left.replace('px','')+'|'+$('note_'+id).style.top.replace('px','');
		
		sendData=encodeURIComponent(sendData);
		
// 		alert('/ajax/saveNotes.php?ac=createNew&queryString='+sendData);
		new Ajax.Request('/ajax/saveNotes.php?ac=createNew&queryString='+sendData, {
			onSuccess: function(transport) {
				obj.realIdentifier=transport.responseText;
				$('note_'+id).realIdentifier=transport.responseText;
			}
		});
		$('note_'+id).notSavedYet=0;
	}
	

}

function db_uploadNote_savePosition(obj) {
	
	id=obj.id.replace('note_','');
	if ( obj.realIdentifier ) id=obj.realIdentifier;
	
	sendData=id+'@'+$('note_'+id).style.left.replace('px','')+'|'+$('note_'+id).style.top.replace('px','');
	
	sendData=encodeURIComponent(sendData);
	
// 	alert('/ajax/saveNotes.php?ac=updPosition&queryString='+sendData);
	new Ajax.Request('/ajax/saveNotes.php?ac=updPosition&queryString='+sendData);
	
}

function db_uploadNote_saveSize(obj) {
	
	id=obj.id.replace('note_','');
	if ( obj.realIdentifier ) id=obj.realIdentifier;
	
	sendData=id+'@'+$('note_'+id).style.width.replace('px','')+'|'+$('note_'+id).style.height.replace('px','');
	
	sendData=encodeURIComponent(sendData);
	
//  	alert('/ajax/saveNotes.php?ac=updSize&queryString='+sendData);
	new Ajax.Request('/ajax/saveNotes.php?ac=updSize&queryString='+sendData);
	
}

function db_removeNote(obj) {
	obj=$(obj);
// 	alert('rem');
	id=obj.id.replace('note_','');
	if ( obj.realIdentifier ) id=obj.realIdentifier;
	
	sendData=id;
	
	sendData=encodeURIComponent(sendData);
	
// 	alert('/ajax/saveNotes.php?ac=remove&queryString='+sendData);
	new Ajax.Request('/ajax/saveNotes.php?ac=remove&queryString='+sendData);
}

function setT_o(obj) {
	obj=$(obj);
	obj.to=setTimeout('unsetCurrentNote(\''+obj.id+'\')',550);
}

function setCurrentNote(obj) {
	obj=$(obj);
	$j(obj).resizable({
	   stop: function(event,ui) { db_uploadNote_saveSize(this); }
	});
	
	$j(obj).draggable({
  	   stop: function(event, ui) { db_uploadNote_savePosition(this); }
	});
}

function unsetCurrentNote(obj) {
	obj=$(obj);
	$j(obj).resizable('destroy');
	
	$j(obj).draggable('destroy');
}

function rlyCheckPass() {
	a=$('regf1');
	b=$('regf2');
	
	if ( a.value == '' ) return 0;
	
	if ( a.value != b.value ) {
		$('reg2').style.color='darkred';
		$('reg2').innerHTML='Passw&ouml;rter stimmen nicht &uuml;berein';
	}
	else {
		$('reg2').style.color='darkgreen';
		$('reg2').innerHTML='Passw&ouml;rter stimmen &uuml;berein';
	}
}

function rlyCheckNick() {
	nick=$('regf0').value;
	if ( nick.search("'") != -1 || nick.search('"') != -1 ) {
		$('reg1').style.color='darkred';
		$('reg1').innerHTML='Name darf folgende Zeichen nicht enthalten: \' &quot; ';
		window.nickBlurCheckd=0;
	}
	else if ( ! window.nickBlurCheckd ) {
		$('reg1').style.color='darkgrey';
		$('reg1').innerHTML='Warten...';
	}
}

function checkNickBlur() {
	new Ajax.Request('/ajax/checkNickExists.php?nick='+$('regf0').value, {
		onSuccess: function(transport) {
			if ( transport.responseText == 'ok' ) {
				$('reg1').style.color='darkgreen';
				$('reg1').innerHTML='Name ist noch verf&uuml;gbar';
			}
			else {
				$('reg1').style.color='darkred';
				$('reg1').innerHTML='Entschuldigung, dieser Name ist schon vergeben';
			}
		}	
	});
	window.nickBlurCheckd=1;
}

function quickanswer_show() {
	obj=$('quickanswer');
	obj.style.display='block';
	obj.style.width='590px';
	obj.style.height='0px';
	
	for ( i=0; i<50; i++ ) {
		setTimeout('$(\''+obj.id+'\').style.height=\''+i*4+'px\'',i*5);
	}
	
	setTimeout('$(\'sendbutton\').style.display=\'block\'',320);
	setTimeout('$(\'answer\').focus()',250);
	
	$('answer_link').style.display='none';
}

function incrRess(rn,by) {
	
	duration=$('r'+rn).every;
	setTo=Number(Number($('r'+rn).innerHTML)+Number(by));
	
	if ( setTo > Number($('kapazitaet').innerHTML) ) return 0;
	
	setTimeout('$(\'r'+rn+'\').innerHTML='+setTo,duration);
	
// 	if ( duration > 2500 ) {
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#eeeeee 0px 0px 5px\'',Number(duration-100));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#aaaaaa 0px 0px 5px\'',Number(duration-60));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#777777 0px 0px 4px\'',Number(duration-20));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#888888 0px 0px 4px\'',Number(duration-20));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#999999 0px 0px 3px\'',Number(duration-60));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#AAAAAA 0px 0px 3px\'',Number(duration+100));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#BBBBBB 0px 0px 2px\'',Number(duration+140));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#cccccc 0px 0px 2px\'',Number(duration+180));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#DDDDDD 0px 0px 1px\'',Number(duration+220));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#EEEEEE 0px 0px 1px\'',Number(duration+260));
// 		setTimeout('$(\'r'+rn+'\').style.textShadow=\'#FFFFFF 0px 0px 0px\'',Number(duration+300));
// 	}
	
	setTimeout('incrRess(\''+rn+'\','+by+')',duration+1);
}

function startRess(rn) {
	val=Number($('r'+rn).innerHTML);
	prod=Number($('p'+rn).innerHTML);
	if ( prod == 0 ) return 0;
	everyNsecs=Number(3600/prod*1000);
	if ( prod < 0 ) {
		everyNsecs=everyNsecs * (-1);
		$('r'+rn).every=everyNsecs;
		incrRess(rn,-1);
	}
	else {
		$('r'+rn).every=everyNsecs;
		incrRess(rn,1);
	}
}

function islFadeStep(oid,step) {
	obj=$(oid);
	
	if ( step == 0 ) {
		obj.style.color='#444444';
	}
	if ( step == 1 ) {
		obj.style.color='#555555';
	}
	if ( step == 2 )  {
		obj.style.color='#666666';
	}
	if ( step == 3 ) {
		obj.style.color='#777777';
	}
	if ( step == 4 ) {
		obj.style.color='#888888';
	}
}


function islFade(obj) {
	obj=$(obj);
	
	n=40;
	
	obj.t=Array();
	obj.t[0]=setTimeout('islFadeStep("'+obj.id+'",0)',n*0);
	obj.t[1]=setTimeout('islFadeStep("'+obj.id+'",1)',n*1);
	obj.t[2]=setTimeout('islFadeStep("'+obj.id+'",2)',n*2);
	obj.t[3]=setTimeout('islFadeStep("'+obj.id+'",3)',n*3);
	obj.t[4]=setTimeout('islFadeStep("'+obj.id+'",4)',n*4);
}

function islFadeout(obj) {
	obj=$(obj);
	
	clearTimeout(obj.t[0]);
	clearTimeout(obj.t[1]);
	clearTimeout(obj.t[2]);
	clearTimeout(obj.t[3]);
	clearTimeout(obj.t[4]);
	
	setTimeout('islFadeStep("'+obj.id+'",4)',n*0);
	setTimeout('islFadeStep("'+obj.id+'",3)',n*1);
	setTimeout('islFadeStep("'+obj.id+'",2)',n*2);
	setTimeout('islFadeStep("'+obj.id+'",1)',n*3);
	setTimeout('islFadeStep("'+obj.id+'",0)',n*4);
	
	setTimeout('$("'+obj.id+'").style.borderBottom="'+obj.prevBorder+'"',n*5);
	setTimeout('$("'+obj.id+'").style.color="'+obj.prevCol+'"',n*5);
}


function liFade(obj) {
	obj=$(obj);
	
	n=40;
	
	obj.t=Array();
	obj.t[0]=setTimeout('liFadeStep("'+obj.id+'",0)',n*0);
	obj.t[1]=setTimeout('liFadeStep("'+obj.id+'",1)',n*1);
	obj.t[2]=setTimeout('liFadeStep("'+obj.id+'",2)',n*2);
	obj.t[3]=setTimeout('liFadeStep("'+obj.id+'",3)',n*3);
	obj.t[4]=setTimeout('liFadeStep("'+obj.id+'",4)',n*4);
}

function liFadeout(obj) {
	obj=$(obj);
	
	clearTimeout(obj.t[0]);
	clearTimeout(obj.t[1]);
	clearTimeout(obj.t[2]);
	clearTimeout(obj.t[3]);
	clearTimeout(obj.t[4]);
	
	setTimeout('liFadeStep("'+obj.id+'",4)',n*0);
	setTimeout('liFadeStep("'+obj.id+'",3)',n*1);
	setTimeout('liFadeStep("'+obj.id+'",2)',n*2);
	setTimeout('liFadeStep("'+obj.id+'",1)',n*3);
	setTimeout('liFadeStep("'+obj.id+'",0)',n*4);
	
	setTimeout('$("'+obj.id+'").style.borderBottom="'+obj.prevBorder+'"',n*5);
	setTimeout('$("'+obj.id+'").style.color="'+obj.prevCol+'"',n*5);
	
	if ( typeof(liFadeInit) == 'function' ) {
		setTimeout('liFadeInit("'+obj.id+'")',n*5+1);
	}
}

window.storeH=Array();
function setmap(x,y) {
	if ( IE ) {
// 		window.location='/map/'+x+','+y;
		alert("IE");
	}
	try {
// 		$j($('mapContents')).animate({opacity:0.7},50);
		$('linkspan').innerHTML='Laden...';
		if ( x != 'home' ) url='/ajax/fastCreateMap.php?X='+x+'&Y='+y;
		else url='/ajax/fastCreateMap.php';
		new Ajax.Request(url, {
			onSuccess: function(transport) {
				a=transport.responseText.split('[====================');
				b=a[1];
				b=b.split('====================]');
				b=b[0];
// 				alert(b);
				$('mapContents').innerHTML=a[0];
				
				eval(b);
				
				if ( window.flagv ) showflags();
// 				$j($('mapContents')).animate({opacity:1.0},50);
			}
		});
		
		$('gmp').href='/gmap/'+x+','+y;
		$('smp').href='/map/'+x+','+y;
		
		$('linkspan').innerHTML='Link zu dieser Ansicht: <a href="/map/'+x+','+y+'">/map/'+x+','+y+'</a>';
		
		for ( i=1; i<9; i++ ) $('d_'+i).href='#ThisUrlWontWork';
	}
	catch ( err ) {
		alert("Setmap err:");
		window.location='/map/'+x+','+y;
	}
}

function bc_next(i) {
	n=i+1;
	if ( ! $('bau_'+n) ) return 0;
	$('bau_'+i).style.display='none';
	$('bau_'+n).style.display='inline-table';
}

function bc_prev(i) {
	n=i-1;
	if ( ! $('bau_'+n) ) return 0;
	$('bau_'+i).style.display='none';
	$('bau_'+n).style.display='inline-table';
}

function showTip(id) {
	if ( id == 0 ) return 0;
	new Ajax.Request('/ajax/tip.php?id='+id, {
		onSuccess: function(transport) {
			$('tipc').innerHTML=transport.responseText;
			if ( $('tipc').innerHTML == 'NONE' ) {
				showTip(1);
			}
			else window.currentTip=id;
			$('tnum').innerHTML='(Tip '+window.currentTip+' von '+window.maxTip+')';
		}
	});
}

function checkNames(l) {
	if ( ! l ) return 0;
	new Ajax.Request('/ajax/checknames.php?namelist='+l, {
		onSuccess: function(transport) {
			$('namecheck').innerHTML=transport.responseText;
		}
	});
}

function expandShadbox(obj) {
	$j(obj).show(500);
}

function collapseShadbox(obj) {
	if ( obj.collapsed ) {
		expandShadbox(obj);
		obj.collapsed=0;
		return 0;
	}

	$j(obj).hide(700);
	obj.collapsed=1;
}

function extractCookieVal(key) {
	c=document.cookie;
	all=document.cookie.split(';');
	la=all.length;
	for ( i=0; i<la; i++ ) {
		all[i]=all[i].replace(/^ /,'');
		cur=all[i].split('=');
		if ( cur[0] == key ) return cur[1];
	}
}

function hide(el) {
	$(el).style.display='none';
}

function contextMenu(config,menutitle) {
	this.confignum=config;
	if ( ! window.contextConfigs ) return 0;
	this.config=window.contextConfigs[config];
	if ( ! this.config ) this.config='Failed to load configuration.:#{}';
	this.config=this.config.split('{}');
	names=new Array();
	hrefs=new Array();
	this.config.each(function(r) {
		if ( ! r ) return 0;
		spl=r.split(':');
		names.push(spl[0]);
		hrefs.push(spl[1]);
	});
	
	linklist=Array();
	l=names.length;
	content='';
	subtr=0;
	for ( var i=0; i<l; i++ ) {
		if ( names[i] && hrefs[i] ) {
			j=Number(i)-subtr;
			if ( names[i].search(/\[sect\]/) != '-1' ) {
				content=content+'<div class="cmenuSubTitle">'+hrefs[i]+'</div>';
				continue;
			}
			set="document.cookie='pcle_"+this.confignum+'='+j+"';";
			set+="setTimeout(&quot;hideContMenu()&quot;,50);";
			content=content+'<a class="cmenu" id="cm_'+i+'" onclick="this.style.backgroundColor=&quot;#FF4400&quot;; '+set+'" onmouseover="fadein(this)" onmouseout="fadeout(this)" onclick="'+set+'" href="'+hrefs[i]+'">'+names[i]+'</a>';
		}
		else subtr=Number(subtr)+1;
	}
	
	this.content=content;
	this.menutitle=menutitle;
}

function hideContMenu() {
	window.tio=setTimeout('$j($(\'contMenu\')).hide(750)',2);
}

function fadein(obj) {
	n=40;
	
	obj.t=Array();
	obj.t[0]=setTimeout('fistep("'+obj.id+'",0)',n*0);
	obj.t[1]=setTimeout('fistep("'+obj.id+'",1)',n*1);
	obj.t[2]=setTimeout('fistep("'+obj.id+'",2)',n*2);
	obj.t[3]=setTimeout('fistep("'+obj.id+'",3)',n*3);
	obj.t[4]=setTimeout('fistep("'+obj.id+'",4)',n*4);
}

function fistep(oid,step) {
	obj=$(oid);
	if ( step == 0 ) {
		 obj.style.backgroundColor='#5E5042';
		 obj.style.color='#AAAAAA';
	}
	if ( step == 1 ) {
		 obj.style.backgroundColor='#78653C';
		 obj.style.color='#888888';
	}
	if ( step == 2 )  {
		 obj.style.backgroundColor='#A58734';
		 obj.style.color='#555555';
	}
	if ( step == 3 ) {
		 obj.style.backgroundColor='#D58920';
		 obj.style.color='#222222';
	}
	if ( step == 4 ) {
		 obj.style.backgroundColor='#FFBB00';
		 obj.style.color='#000000';
	}
}

function fadeout(obj) {
	clearTimeout(obj.t[0]);
	clearTimeout(obj.t[1]);
	clearTimeout(obj.t[2]);
	clearTimeout(obj.t[3]);
	clearTimeout(obj.t[4]);
	
	setTimeout('fistep("'+obj.id+'",4)',n*0);
	setTimeout('fistep("'+obj.id+'",3)',n*1);
	setTimeout('fistep("'+obj.id+'",2)',n*2);
	setTimeout('fistep("'+obj.id+'",1)',n*3);
	setTimeout('fistep("'+obj.id+'",0)',n*4);
	
	setTimeout('$("'+obj.id+'").style.backgroundColor="#3F3F3F"',n*5);
	setTimeout('$("'+obj.id+'").style.color="white"',n*5);
}

contextMenu.prototype.show=function() {
	
	if ( ! window.contextConfigs ) return 0;
	
	if ( ! window.x ) window.x=extractCookieVal('px');
	if ( ! window.y ) window.y=extractCookieVal('py');
	
	$('contMenu').style.left=window.x-120+"px";
	num=extractCookieVal('pcle_'+this.confignum);
	if ( ! num ) num=0;
	$('contMenu').style.top=window.y-40-num*20+"px";
	$('contMenuItems').innerHTML='<div class="cmenuTitle">'+this.menutitle+'</div>';
	$('contMenuItems').innerHTML+=this.content;
	$j($('contMenu')).fadeIn(300);
	window.cme=1;
}

function cvChange(id,x,y) {
	window.contextConfigs[998]='Karte zentrieren:/map/'+x+','+y+'{}Truppen schicken:/gid/4/'+x+','+y+'{}Rohstoffe schicken [Land]:/gid/39/'+x+','+y+'{}Rohstoffe schicken [Meer]:/gid/7/'+x+','+y+'';
}

function cvShow() {
	goto=new contextMenu(998,'Aktionen');
	goto.show();
}

function checkMon() {
	obj=$('lcapt');
	len=obj.value.length;
	
	if ( len == 3 ) {
		$('loginform').submit();
		$j($('loginform')).fadeTo(500,0.5);
	}
}

function test_captcha() {
	obj=$('lcapt');
	len=obj.value.length;
	
	if ( $('luser').value == 'Benutzername' ) {
		$j($('luser')).animate({backgroundColor:'#005EFF'},500);
		$('luser').focus();
		return false;
	}
	
	if ( $('lpass').value == 'Passwort' ) {
		$j($('lpass')).animate({backgroundColor:'#005EFF'},500);
		$('lpass').focus();
		return false;
	}
	
	if ( len < 3 ) {
		$j($('lcapt')).animate({backgroundColor:'#005EFF'},500);
		$('lcapt').focus();
		return false;
	}
	
	return true;
}
function AEchk() {
	// fuer armeesystem, onkeypress
	obj=$(window.armyElFocused);
	diff=obj.value-obj.prekpvalue;
	obj.prekpvalue=obj.value;
// 	alert(diff);
	
	if ( ! checkArmySubtrDefaultgrp(diff) ) obj.value=obj.prekpvalue;
}

function checkContextMenu(event) {
	
	if ( window.captMon ) {
		setTimeout('checkMon()',20);
	}
	
	if ( window.armyElFocused ) {
		setTimeout('AEchk()',20);
	}
	
	if ( window.keyHandler_qa ) {
		if ( window.qa_timeout ) clearTimeout(window.qa_timeout);
		window.qa_timeout=setTimeout('getAnswers()',750);
	}

	if ( window.disableCMenu == true || ! window.contextConfigs || window.cMenDisabled ) return 0;
// 	alert(window.cMenDisabled);
	la=document.forms.length;
	if ( window.spFocus ) return 0;
	for ( i=0; i<la; i++ ) {
		lb=document.forms[i].length;
		for ( j=0; j<lb; j++ ) {
			t=document.forms[i].elements[j];
			if ( t.hasFocus ) return 0;
		}
	}
	
	if ( ! event ) event=window.event;
	if ( event.keyCode ) kc=event.keyCode;
	if ( event.which ) kc=event.which;
	
	if ( window.keyCheckerMap ) {
		if ( kc == 48 ) {
			if ( window.flagv ) hideflags();
			else showflags();
		}
		if ( kc == 55 ) setmap('home',false);
		if ( kc == 56 ) {
			$('i_2').src='/img/map/active_2.png';
			setmap(window.sx,Number(window.sy)+1);
		}
		if ( kc == 50 ) {
			$('i_4').src='/img/map/active_4.png';
			setmap(window.sx,Number(window.sy)-1);
		}
		if ( kc == 52 ) {
			$('i_3').src='/img/map/active_3.png';
			setmap(Number(window.sx)-1,Number(window.sy));
		}
		if ( kc == 54 ) {
			$('i_1').src='/img/map/active_1.png';
			setmap(Number(window.sx)+1,Number(window.sy));
		}
	}
	
	if ( kc == 103 ) { // "g"
		goto=new contextMenu(0,'Navigation');
		goto.show();
	}
	
	if ( kc == 82 ) { // "R"
		goto=new contextMenu(1,'Rohstoffe senden: Land');
		goto.show();
	}
	if ( kc == 69 ) { // "E"
		goto=new contextMenu(2,'Rohstoffe senden: Meer');
		goto.show();
	}
	
	if ( kc == 101 ) { // "r"
		goto=new contextMenu(3,'Handels-Verlauf: Meer');
		goto.show();
	}
	
	if ( kc == 114 ) { // "e"
		goto=new contextMenu(4,'Handels-Verlauf: Land');
		goto.show();
	}
	
	if ( kc == 97 ) { // "a"
		goto=new contextMenu(5,'Letzte Angriffsziele');
		goto.show();
	}
	
	if ( kc == 102 ) { // "f"
		goto=new contextMenu(7,'Rohstofflager voll...');
		goto.show();
	}
	
	if ( kc == 99 ) { // "c"
		goto=new contextMenu(8,'Berichte und Nachrichten');
		goto.show();
	}
	
	if ( kc == 121 ) { // "y"
		goto=new contextMenu(999,'Benutzerdefiniertes Menu');
		goto.show();
	}
	
	t=$('loginform');
	if ( kc == 113 && ! t ) { // "q"
		goto=new contextMenu(6,'Feorar verlassen?');
		goto.show();
	}
	else if ( kc == 113 ) $('loginform').submit();
}

document.onkeypress=checkContextMenu;

function fillFields() {
	try {
	user=$('luser');
	pass=$('lpass');
	if ( ! user.value && ! pass.value ) {
		setTimeout('$(\'luser\').value=\'Benutzername\'',600);
		setTimeout('$(\'lpass\').value=\'Passwort\'',600);
	}
	}
	catch (err) { }
}

function getMPos(ev) {
	document.mouseMoved=1;
	if (IE) { // grab the x-y pos.s if browser is IE
		x = event.clientX + document.body.scrollLeft
		y = event.clientY + document.body.scrollTop
	} else {  // grab the x-y pos.s if browser is NS
			x = ev.pageX
			y = ev.pageY
	}  
	if ( x < 0 ) { x = 0 }
	if ( y < 0 ) { y = 0 }  
  
	window.x=x;
	window.y=y;
	
	x+=10;
	y+=10;
  
	$('ddiv').style.left=x+"px";
	$('ddiv').style.top=y+"px";
	
	$('mouse_status').style.left=Number(x-60)+"px";
	$('mouse_status').style.top=Number(y-30)+"px";
	return true
}

function sdiv(c,darker) {
	$('ddiv').innerHTML=c;
	if (darker) $('ddiv').style.backgroundImage='url(/img/90b.png)';
	else $('ddiv').style.backgroundImage='url(/img/75b.png)';
	clearTimeout(window.ddto);
// 	$j($('ddiv')).stop().animate({opacity: 1.0},50);
	$j($('ddiv')).fadeIn(150);
}

function hdiv() {
	window.ddto=setTimeout('$j($(\'ddiv\')).fadeOut(150)',150);;
// 	$j($('ddiv')).stop().animate({opacity: 0.0},400);
}

function clock() {

	if ( ! $('sc_s') ) return 0;
	
	setTimeout('clock()',1000);
	
	s=$('sc_s');
	m=$('sc_m');
	h=$('sc_h');
	
	secs=Number(s.innerHTML);
	mins=Number(m.innerHTML);
	hours=Number(h.innerHTML);
	
	secs=secs+1;
	if ( secs >= 60 ) {
		secs="0";
		mins=mins+1;
	}
	if ( mins >= 60 ) {
		mins="0";
		hours=hours+1;
	}
	
	if ( hours >= 24 ) {
		secs="0";
		mins="0";
		hours="0";
	}
	
	if ( secs < 10 ) secs="0"+secs;
	if ( mins < 10 ) mins="0"+mins;
	
	s.innerHTML=secs;
	m.innerHTML=mins;
	h.innerHTML=hours;
}

function addTroops() {
	ges=Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
	troopSelect=$("ctl");
	elements=troopSelect.getElementsByTagName('INPUT');
	
	count=elements.length;
	
	any_selected=false;
	
	for ( i=0; i<count; i++ ) {
		if ( elements[i].id.search('grpentry') == -1 ) continue;
		splitd=elements[i].id.split('_');
		troop_id=splitd[4];
		group_id=splitd[2];
		
		if ( $("g_"+group_id).checked ) {
			ges[troop_id]+=parseInt(elements[i].value);
			if ( parseInt(elements[i].value) > 0 ) any_selected=true;
		}
		
// 		document.writeln("«"+troop_id+"::"+elements[i].value+"»");
	}
	
	if ( any_selected == true ) {
		$j($('used_trp')).animate({backgroundColor:'darkgreen'},200);
	}
	else {
		$j($('used_trp')).animate({backgroundColor:'darkred'},200);
	}
	
// 	alert(ges);
	
	len=ges.length;
	for ( i=0; i<len; i++ ) {
		val=ges[i];
		obj=$('troopfield_'+'summary_'+i);
		if ( obj ) {
			obj.innerHTML=val;
			if ( obj.innerHTML > 0 ) {
				obj.className='mark';
			}
			else {
				obj.className='dontmark';
			}
		}
	}
	
	getMsAndDispTime(ges);
}

function rmpc() {
	amount=$('am').value;
	cost=window.cper;
	tc=Number(cost*amount);
	$('cost').innerHTML='('+tc+' Rohstoffe)';
}

function getMsAndDispTime(troops) {
	mms=0;
	
	$('pathVisualisation').innerHTML='Berechne Pfad, bitte warten...';
	
	len=troops.length;
	
	for ( i=0; i<len; i++ ) {
		num=troops[i];
		if ( num > 0 && mms < window.troopSpeeds[i] ) {
			mms=window.troopSpeeds[i];
		}
	}
	
// 	alert(mms);
	
	xa=$('hx').value;
	ya=$('hy').value;
	xb=$('x').value;
	yb=$('y').value;
	
	r=Math.round(Math.random()*10000);
	
	if ( $('land').checked ) {
		via='land';
	}
	else via='sea';
	
// 	alert(via);
	
	new Ajax.Request('/ajax/getTime.php?ms='+mms+'&x1='+xa+'&y1='+ya+'&x2='+xb+'&y2='+yb+'&id='+r+'&way='+via, {
		onSuccess: function(transport) {
// 			alert(transport.responseText);
			text=transport.responseText.split('//////////////////////////////////SPLIT///////////////////////////////////');
// 			alert(text);
			counter=text[0];
			img=text[1];
// 			alert(counter);

// 			countUp('bcdt'+r);
			
// 			alert(img);
			$('time_info').innerHTML=counter;
			$('pathVisualisation').innerHTML=img;
			
			countUp('bcdt'+r);
		}
	});
	
// 	$('ltime').innerHTML="Ankunft um <b>"+h+":"+m+":"+s+"</b> Uhr";
}

function betreffaendern() {
          if(document.getElementById('betreff').value == '(kein Betreff)')
          {
            document.getElementById('betreff').value = '';
          }
	}
	
function toggleVisibility(eid) {
	o=document.getElementById(eid);
// 	collapseShadbox(o);
	if ( o.style.display == 'none' ) $j(o).show(300);
	else  $j(o).hide(300);
	saveSidebarCollapseStatus();
}

function toggleArrowSource(id) {
	c=document.getElementById(id);
	if ( c.src.search('a-down.gif') != -1 ) c.src='/img/a-right.gif';
	else c.src='/img/a-down.gif';
}

function glogin() {
	$('luser').value='Gast';
	$('lpass').value='guest';
	document.loginform.submit();
}

function sbar(dur,w,eid,rtf) {
	h=Number($(rtf+"h").value)*3600;
	s=Number($(rtf+"s").value)-1;
	m=Number($(rtf+"m").value)*60;
	
	secl=h+m+s;

	p=secl/dur;
	if ( secl == 0 ) p=0;
	cw=w-p*w;
// 	alert(h+","+m+","+s);
	
// 	alert(m+","+s);
	
	$(eid).style.width=Math.round(cw)+"px";
	
// 	alert(Math.round(cw)+"px, "+p);
	
	$j($(eid)).animate({width:'100%'},{duration:secl*1000,easing:"linear"});
// 	setTimeout("sbar('"+dur+"','"+w+"','"+eid+"','"+rtf+"')",1000);
}

function initializeSidebarCollapseStatus() {
	c = document.cookie.split('scs=');
	if ( ! c[1] ) return 0;
//	alert('1::'+c[1]);
	c = c[1];
	c = c.split('||');
	c = c[1];
	c = c.split('*');
	
	var boxes=new Array('allgemein','comm','trp','sys','other','isl');
	var arrows=new Array('a','b','c','d','f','e');
	
	i=0;
	c.each (function(s) {
		if ( ! boxes[i] ) return 0;
//		alert('['+i+']'+boxes[i]+' : '+s);
		obj=document.getElementById(boxes[i]);
		if ( ! obj ) return 1;
		else obj=obj.style;
		obj.display=s;
		if ( s == 'none' ) toggleArrowSource(arrows[i]);
		i+=1;
	});	
}

function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    var tmp_arr = [], i = ac = c = c1 = c2 = 0;
 
    while ( i < str_data.length ) {
        c = str_data.charCodeAt(i);
        if (c < 128) {
            tmp_arr[ac++] = String.fromCharCode(c); 
            i++;
        } else if ((c > 191) && (c < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    
    return tmp_arr.join('');
}

function saveSidebarCollapseStatus() {
	var a = new Date();
	a = new Date(a.getTime() +1000*60*60*24*365);
	
	trpStyle=document.getElementById('trp');
	if ( ! trpStyle ) trpStyle='block';
	else trpStyle=trpStyle.style.display;
	
	sysStyle=document.getElementById('trp');
	if ( ! sysStyle ) sysStyle='block';
	else sysStyle=sysStyle.style.display;
	
	document.cookie = 'scs=||'+document.getElementById('allgemein').style.display+'*'+document.getElementById('comm').style.display+'*'+trpStyle+'*'+sysStyle+'*'+document.getElementById('other').style.display+'*'+document.getElementById('isl').style.display+'||;'+'expires='+a.toGMTString()+';';
	
//	alert(document.cookie);
}

function open_help(id) {
	$('helptext').innerHTML='Lade Informationen vom Server, bitte warten...';
// 	$j($('outer_helpbox')).animate({opacity:0.0},1);
	$j($('outer_hlpbox')).fadeIn(500);
// 	$j($('outer_helpbox')).animate({opacity:0.5},1500);
	new Ajax.Request('/ajax/help.php?id='+id, {
		onSuccess: function(transport) {
			$('helptext').innerHTML=utf8_decode(transport.responseText);
		}
	});
}

function open_url(url) {
	$('helptext').innerHTML='Lade Informationen vom Server, bitte warten...';
// 	$j($('outer_helpbox')).animate({opacity:0.0},1);
	$j($('outer_hlpbox')).show()
// 	$j($('outer_helpbox')).animate({opacity:0.5},1500);
	new Ajax.Request(url, {
		onSuccess: function(transport) {
			$('helptext').innerHTML=utf8_decode(transport.responseText);
		}
	});
}

function close_help() {
	$j($('outer_hlpbox')).hide();
}


function countUp(n) {
	
// 	if ( ! $(n) ) return 0;
	
	stunden=Number(document.getElementById(n+"h").value);
	minuten=Number(document.getElementById(n+"m").value);
	sekunden=Number(document.getElementById(n+"s").value);
	
	sekunden=sekunden+1;
	
	if ( sekunden > 59 ) {
		sekunden=00;
		minuten=minuten+1;
	}
	
	if ( minuten > 59 ) {
		minuten=00;
		stunden=stunden+1;
	}
	
	if ( sekunden < 10 ) {
		sekunden="0"+sekunden;
	}
	
	if ( minuten < 10 ) {
		minuten="0"+minuten;
	}
	
	if ( stunden < 10 ) {
		stunden="0"+stunden;
	}
	
	document.getElementById(n+"h").value=stunden;
	document.getElementById(n+"m").value=minuten;
	document.getElementById(n+"s").value=sekunden;
	
	document.getElementById(n).innerHTML=stunden+":"+minuten+":"+sekunden;
	
	setTimeout("countUp('"+n+"')",1000);
}

function refreshAttacks() {
	$j($('trp')).stop();
	$('trp').style.textAlign='center';
	$('trp').innerHTML='<img src="/img/spinner2.gif" alt="Loading...">';
	$j.get("/ajax/getAttacks.php",
		function(data) {
			window.data=data;
			$j($('trp')).fadeOut(300);
			setTimeout('setAttacksDivContents()',300);
		}
	);
	
// 	$('trp').
}

function refreshBuildings() {
	$('down_infobox').style.textShadow='white 0px 0px 7px,white 0px 0px 7px,white 0px 0px 7px,white 0px 0px 7px';
	
	$j.get("/ajax/getBuild.php",
		function(data) {
			$('down_infobox').innerHTML='';
			$('down_infobox').innerHTML=data;
			data.evalScripts();
			setTimeout('$(\'down_infobox\').style.textShadow=\'white 0px 0px 6px,white 0px 0px 6px\'',200);
			setTimeout('$(\'down_infobox\').style.textShadow=\'white 0px 0px 5px,white 0px 0px 5px\'',400);
			setTimeout('$(\'down_infobox\').style.textShadow=\'white 0px 0px 5px\'',600);
			setTimeout('$(\'down_infobox\').style.textShadow=\'white 0px 0px 4px\'',800);
			setTimeout('$(\'down_infobox\').style.textShadow=\'white 0px 0px 2px\'',1000);
			setTimeout('$(\'down_infobox\').style.textShadow=\'none\'',1200);
		}
	);
}

function setAttacksDivContents() {
	$('trp').style.textAlign='left';
	$('trp').innerHTML=window.data;
	window.data.evalScripts();
	$j($('trp')).fadeIn(500);
}

function reloadEmpireTableRow(rowId) {
	$j.get('/_empire&only_row='+rowId,function(result) {
		$(rowId).innerHTML=result;
		result.evalScripts();
	});
}

function timer(n,w,func) {
	
	$(n).style.padding='2px';
	$(n).style.paddingLeft='3px';
	$(n).style.paddingRight='3px';
	
	if ( ! w ) w='i';
	
	stunden=Number(document.getElementById(n+"h").value);
	minuten=Number(document.getElementById(n+"m").value);
	sekunden=Number(document.getElementById(n+"s").value);
	
	sekunden=sekunden-1;
	
	skip="false";
	
	if ( stunden <= 0 && minuten <= 0 && sekunden <= 0 ) {
		if ( w == 'i' ) document.getElementById(n).value='00:00:00';
		else document.getElementById(n).innerHTML='00:00:00';
// 		if ( ! window.donreload ) setTimeout("location.reload()",1700);
		if ( w == 'i' && ! func ) setTimeout("document.getElementById('"+n+"').value='--:--:--'",1700);
		else if ( ! func ) setTimeout("document.getElementById('"+n+"').innerHTML='<span style=\"font-size:85%; color:black;\" onclick=\"location.reload()\"><img style=\"position:relative; width:12px; top:3px;\" src=\"/img/refresh.png\"> neu laden</span>'",1700);
		
		if ( func ) {
			eval(func);
		}
		
		return 1;
		skip="true";
	}
	
	if ( skip != "true" ) {
	
		if ( sekunden < 0 ) {
			sekunden=59;
			minuten=minuten-1;
		}
		
		if ( minuten < 0 ) {
			minuten=59;
			stunden=stunden-1;
		}
		
		if ( sekunden < 10 ) {
			sekunden="0"+sekunden;
		}
		
		if ( minuten < 10 ) {
			minuten="0"+minuten;
		}
		
		if ( stunden < 10 ) {
			stunden="0"+stunden;
		}
		
// 		if ( sekunden == 10 && minuten == 0 && stunden == 0 ) {
// 			if ( n.search('btimer') == -1 ) {
// 				for ( i=0; i<255; i++ ) {
// 					v=255-i;
// 					if ( v < 0 ) v=0;
// 					setTimeout('$(\''+n+'\').style.backgroundColor=\'rgb('+v+','+v+','+v+')\'',39*i);
// 					
// 					v=i;
// 					g=Math.round(v/2);
// 					
// 					if ( v > 255 ) v=255;
// 					setTimeout('$(\''+n+'\').style.color=\'rgb('+v+','+g+','+0+')\'',39*i);
// 				}
// 			}
// 		}
		
		document.getElementById(n+"h").value=stunden;
		document.getElementById(n+"m").value=minuten;
		document.getElementById(n+"s").value=sekunden;
		
		if ( w == 'i' ) document.getElementById(n).value=stunden+":"+minuten+":"+sekunden;
		else document.getElementById(n).innerHTML=stunden+":"+minuten+":"+sekunden;
			
	}


	
	setTimeout("timer('"+n+"','"+w+"','"+func+"')",1000);
}

function checkDCoordinates() {
	if ( ! $('x').value || ! $('y').value ) {
		document.getElementById('imsg').innerHTML='<img src="/img/n.png"> Koordinaten unvollst&auml;ndig...';
// 		document.getElementById('coord').innerHTML='<img src="/img/n.png"> Koordinaten unvollst&auml;ndig...';
		$j($('target')).animate({backgroundColor:'darkred'},200);
		return 0;
	}
	setTimeout('checkCoordinates()',500);
}

function checkCoordinates() {
	
	new Ajax.Request('/ajax/checkCoord.php?x='+$('x').value+'&y='+$('y').value, {
		onSuccess: function(transport) {
			document.getElementById('imsg').innerHTML=transport.responseText;
// 			alert(transport.responseText);
			if ( transport.responseText.search('<img src="/img/y.png">') != -1 ) {
				$j($('target')).animate({backgroundColor:'darkgreen'},200);
			}
			else {
				$j($('target')).animate({backgroundColor:'darkred'},200);
			}
// 			document.getElementById('coord').innerHTML=transport.responseText;
		}
	});
	
}

function checkAttackType() {
// 	alert($('off').checked);
	if ( $('off').checked || $('deff').checked || ( $('merge').checked && $('merge_commit').checked ) ) {
		$j($('atk_type')).animate({backgroundColor:'darkgreen'},200);
	}
	else {
		$j($('atk_type')).animate({backgroundColor:'darkred'},200);
	}
}

function checkTradeCoords(way) {
	new Ajax.Request('/ajax/checkCoord.php?no_astar=1&ctime=1&way='+way+'&x='+$('x').value+'&y='+$('y').value, {
		onSuccess: function(transport) {
			document.getElementById('imsg').innerHTML=transport.responseText;
		}
	});
}

function checkDTradeCoordinates(way) {
	if ( ! $('x').value || ! $('y').value ) {
		document.getElementById('imsg').innerHTML='<img src="/img/n.png"> Koordinaten unvollst&auml;ndig...';
		return 0;
	}
	$('imsg').innerHTML='Laden...<br>';
	setTimeout('checkTradeCoords("'+way+'")',1000);
}

function checkTS() {
// 	if ( ! $('off').checked && ! $('deff').checked && ! $('merge').checked ) document.getElementById('type').innerHTML='<br><img src="/img/n.png"> Kein Truppenbewegungs-Typ gew&auml;hlt';
// 	else if ( $('off').checked ) $('type').innerHTML='<br><img src="/img/y.png"> Gew&auml;hlte Siedlung wird angegriffen';
// 	else if ( $('deff').checked ) $('type').innerHTML='<br><img src="/img/y.png"> Gew&auml;hlte Siedlung wird unterst&uuml;tzt';
// 	else if ( $('merge').checked ) $('type').innerHTML='<br><img src="/img/y.png"> Truppen werden in die gew&auml;hlte Siedlung verschoben';
// 
// 	setTimeout('checkTS()',1000);
}

function getGroups() {
	groups=Array(0);
	str='';
// 	alert($('trselect').length);
	for ( var i=0; i < $('trselect').length; ++i ) {
		if ( $('trselect').elements[i].type == "checkbox" ) {
			e=$('trselect').elements[i];
			if ( e.value == 'on' ) {
				groups.push(e.value);
				str=str+(e.name);
			}
		}
	}

	setTimeout('getGroups()',2000);
}

function enableSend() {
// 	a=false;
// 	b=false;
// 	c=false;
// 	
// 	if ( $('coord').innerHTML.search('y.png') > 0 ) a=true;
// 	if ( $('type').innerHTML.search('y.png') > 0 ) b=true;
// 	if ( window.groupsSelected > 0 ) c=true;
// 	
// 	if ( a && b && c ) {
// 		$('send').style.display='inline';
// 	}
// 	else $('send').style.display='none';
// 	setTimeout('enableSend()',300);
}

function showGroup(key,me) {
	document.getElementById('g_'+key).style.display='inline';
	document.getElementById('gd_'+key).style.display='none';
	me.style.cursor='default';
	if ( window.cedgid && window.cedgid != key ){
		if ( window.cgch == true ) {
			sendRequest(window.cedgid);
			window.cgch=false;
		}
		else hideGroup(window.cedgid,me);
	}
	window.cedgid=key;
}

function hideGroup(key,me) {
	document.getElementById('g_'+key).style.display='none';
	document.getElementById('gd_'+key).style.display='inline';
	me.style.cursor='pointer';
}

function setState(obj,state) {
	if ( window.stopSpin != 1 ) {
		obj=$(obj);
		obj.value=state;
	}
}

function enableSpin(obj) {
	window.stopSpin=0;
	spin(obj);
}

function spin(obj) {
	obj=$(obj);
	obj.style.fontFamily='monospace';
	obj.style.width='20px';
	obj.style.backgroundImage='none';
	obj.value='/';
	obj.blur();
	setTimeout("setState('"+obj.id+"','-')",50);
	setTimeout("setState('"+obj.id+"','\')",100);
	setTimeout("setState('"+obj.id+"','|')",150);
	setTimeout("if ( ! window.stopSpin ) spin('"+obj.id+"')",200);
}

function disableSpin(obj) {
	window.stopSpin=1;
	obj.backgroundImage='url(/img/save.png)';
	obj.value="";
}

function sendRequest(gid) {
	fields=Array();
	group=$(gid);
	objects=group.getElementsByTagName("INPUT");
	
	originalid=gid;
	
	gid=gid.split('_');
	gid=gid[2];
	
	for ( var i=0; i<objects.length; i++ ) {
		fields.push(objects[i]);
	}
	
	uid=Array();
	
	string='/ajax/updGrp.php?gid='+gid;
	
	
	fields.each(function(c) {
// 		alert(c.value);
// 		if ( ! c.value ) return 0;
		s=c.id.replace('grpentry__','');
		arr=s.split('_');
		
		if ( arr[2] ) string=string+'&ct_'+arr[2]+'='+c.value;
		
		uid[arr[2]]=c.value;
	});
	
	name=$(originalid+'__name').value;
	string=string+'&name='+name;
// 	alert(name);
	
	
	new Ajax.Request(string, {
		onSuccess: function(transport) {
			if ( transport.responseText.search('<!-- success -->') != -1 ) {
				
				div=$(group.id+'__ndiv');
				$j(div).fadeOut(2000);
				
				obj.changed=0;
			}
			else {
				error("Speichern fehlgeschlagen. Der Server meldet: "+transport.responseText);
			}
		}
	});
	
	group.changed=false;
}

function updF(id,me) {
	t=document.getElementById(id);
	s=document.getElementById(me);
	
	if ( ! window.maingrpCache ) window.maingrpCache=Array();
	
	if ( ! window.maingrpCache[id] ) {
		 window.maingrpCache[id]=t.value;
	}
	
	if ( ! window.subgrpCache ) window.subgrpCache=Array();
	
	if ( ! window.subgrpCache[id] ) {
		window.subgrpCache[id]=s.value;
	}
	
	max=Number(window.maingrpCache[id]) + Number(window.subgrpCache[id])+1;
	nval=Number(window.maingrpCache[id]) + (Number(window.subgrpCache[id])-Number(s.value));
	if ( nval >= 0 ) t.value=nval;
	else s.value=Number(window.maingrpCache[id]) + Number(window.subgrpCache[id]);
	
	window.cUpdMax=max;
}

// Eingabefelder

function start(id,step,min,max) {
	window.objCache=Array();
	window.cUpdElement=id;
	window.cUpdStep=step;
	if ( min ) window.cUpdMin=min;
	if ( max ) window.cUpdMax=max;
// 	alert(max);
// 	document.getElementById(id).className='ddfield_ac';
	window.restoreOnmousemove=document.onmousemove;
	document.onmousemove=gPos;
}

function stop() {
// 	alert("stop");
	if ( window.restoreOnmousemove ) document.onmousemove=window.restoreOnmousemove;
	else if ( window.cUpdElement ) document.onmousemove='';
	window.prevx='';
	
	if ( window.cUpdElement ) {
		a=document.getElementById(window.cUpdElement);
// 		document.getElementById(window.cUpdElement).className='ddfield';
	}
	
	if ( window.maingrpCache ) window.maingrpCache=Array();
	if ( window.subgrpCache ) window.subgrpCache=Array();
	window.cUpdElement='';
}

function gPos(e) {
	a=document.getElementById(window.cUpdElement);
	
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
	}
	
	if ( window.prevx && a ) {
		val=Number(a.value);
		old_a_value=val;
		change=( posx - window.prevx ) * window.cUpdStep;
		if ( e.shiftKey == 1 ) change=change / 10;
		if ( e.ctrlKey == 1 ) change=change * 10;
		newv=val + change;
		
		if ( ! window.objCache[window.cUpdElement] ) window.objCache[window.cUpdElement]=val;
		window.objCache[window.cUpdElement]=window.objCache[window.cUpdElement]+change;
		
		rnewv=Math.round(window.objCache[window.cUpdElement]);
		
		window.objCache[window.cUpdElement]=Math.round(window.objCache[window.cUpdElement]*10)/10;
		
		
		if ( window.objCache[window.cUpdElement] == rnewv || window.objCache[window.cUpdElement] +1 < val || window.objCache[window.cUpdElement] -1 > val ) a.value=rnewv;
		
		if ( window.cUpdMax ) {
			if ( window.cUpdMax < a.value ) a.value=window.cUpdMax - 1;
		}
		if ( window.cUpdMin ) {
			if ( window.cUpdMin - 1 > a.value ) a.value=window.cUpdMin - 1;
		}
		
		if ( ! checkArmySubtrDefaultgrp(a.value-val) ) {
			a.value=old_a_value;
			return 0;
		}
		
		if ( window.cUpdMax && window.cUpdMin && a.style.width ) {
			v=a.value;
			w=Number(a.style.width.replace('px',''));
			
			r=(v - window.cUpdMin) / (window.cUpdMax - 1 - window.cUpdMin);
			pwidth=r*w;
			
			set=Math.round(-800 + pwidth);
			
			a.style.backgroundPosition=set +'px';
			
		}
		
		
		if ( window.cUpdMax && window.cUpdMin && ! a.style.width ) {
			w=100;
			
			v=a.value;
// 			w=Number(a.style.width.replace('px',''));
			
			r=(v - window.cUpdMin + 1  ) / (window.cUpdMax - 1 - window.cUpdMin);
			
// 			alert(r+"updmax: "+window.cUpdMin+' max:'+window.cUpdMax+' // v:'+v);
			
			pos=Number(100-(Number(Math.round(r*100))))-1;
			pos=-pos;
			$('mouse_status').style.backgroundPosition=pos+'px';
// 			$('mouse_status').innerHTML=pos+'px';
		}
		
// 		document.getElementById('a').value=rnewv;
// 		document.getElementById('b').value=window.objCache[window.cUpdElement];
	}
	window.prevx=posx;
	a.blur();
	
	$('mouse_status').style.left=Number(posx-50)+"px";
	$('mouse_status').style.top=Number(posy-20)+"px";
// 	a.focus();
}

// Link-Effekte

function refreshLabels() {
	all_labels=$('body').getElementsByTagName("LABEL");
	for ( i=0; i < all_labels.length; i++ ) {
		lb=all_labels[i].getElementsByTagName("INPUT");
		lc=lb[0];
		if ( ! lc ) continue;
		
		currentlySelected=lc.checked;
		
		if ( ! currentlySelected ) {
			all_labels[i].className='p';
		}
		else {
			all_labels[i].className='selected';
		}
	}
}

function toggleHelpModule() {
	if ( window.helpModuleEnabled ) disableHelpModule();
	else enableHelpModule();
}

function enableHelpModule() {
	window.helpModuleEnabled=1;
	
	la=$('body').getElementsByTagName("*");
	for ( i=0; i < la.length; i++ ) {
		if ( la[i].id.search('helpbox') != -1 ) {
			obj=la[i];
			fancy_box=$(la[i].id.replace('helpbox','fancybox'));
			$j(fancy_box).fadeIn(300) //.style.display='block';
		}
	}
	
	$('helpmode_link').innerHTML='Hilfemodus aktiv; zum deaktivieren hier klicken. Klicke auf ein blau schraffiertes Element f&uuml;r Informationen.';
}

function disableHelpModule() {
	window.helpModuleEnabled=0;
	
	la=$('body').getElementsByTagName("*");
	for ( i=0; i < la.length; i++ ) {
		if ( la[i].id.search('helpbox') != -1 ) {
			obj=la[i];
			fancy_box=$(la[i].id.replace('helpbox','fancybox'));
			$j(fancy_box).fadeOut(300) //.style.display='none';
		}
	}
	$('helpmode_link').innerHTML='Hilfe zur aktuellen Seite';
}

function setupFieldsForCMenu() {
	la=$('body').getElementsByTagName("*");
	for ( i=0; i < la.length; i++ ) {
		if ( la[i].id.search('helpbox') != -1 ) {
			obj=la[i];
			number=la[i].id.replace('helpbox_','');
			obj.onclick=function() {
				if ( window.helpModuleEnabled ) {
					open_help(number);
				}
				else return 0;
			}
			fancy_id=la[i].id.replace('helpbox','fancybox');
			obj.innerHTML='<div class="helpbg" id="'+fancy_id+'"></div>'+obj.innerHTML;
		}
		if ( la[i].tagName == 'TEXTAREA' || la[i].tagName == 'INPUT' ) {
			
			t=la[i];
			
			if ( t.onblur || t.onfocus ) continue;
			
			t.hasFocus=false;
		
			t.onfocus=function(){ this.hasFocus=true; };
			t.onblur =function(){ this.hasFocus=false; };
		}
		
		if ( la[i].tagName == 'LABEL' ) {
			la[i].currentlySelected=0;
			if ( la[i].onclick ) continue;
			la[i].onclick=function() { refreshLabels(); };
		}
	}
	
	refreshLabels();
}

function setupEffects() {
	
	if ( ! window.specialScript ) {
	
		la=$('body').getElementsByTagName("*");
		for ( i=0; i < la.length; i++ ) {
			
			if ( la[i].tagName == 'A' && ! la[i].onmouseover && ! la[i].onmouseout ) {
				
				if ( la[i].parentNode.parentNode.className == 'troopList' || la[i].parentNode.parentNode.id == 'ress_links' || la[i].parentNode.className == 'pagenav' || ( la[i].innerHTML.search('<img') != -1 && la[i].innerHTML.search('>') == Number(la[i].innerHTML.length)-1 ) ) continue;
				
				if ( ! la[i].id ) la[i].id='a_item_'+i;
				
				if ( la[i].parentNode.parentNode.parentNode.id == 'isl' ) {
					la[i].onmouseover=function(event) { islFade(this.id); };
					la[i].onmouseout=function(event) { islFadeout(this.id); };
				}
				else if ( ! la[i].className && ! la[i].style.color ) {
					la[i].onmouseover=function(event) { liFade(this.id); };
					la[i].onmouseout=function(event) { liFadeout(this.id); };
					
					try {
						liFadeInit(la[i]);
					}
					catch(err) { }
				}
				
				if ( ! la[i].prevCol ) la[i].prevCol=la[i].style.color;
				if ( ! la[i].prevBorder ) la[i].prevBorder=la[i].style.borderBottom;
				la[i].pleft=la[i].style.paddingLeft.replace('px','');
			}
		}
		
	}
	
}

function login_user_focus() {
	obj=$('luser');
	if ( obj.value == 'Benutzername' ) obj.value='';
}

function login_user_blur() {
	obj=$('luser');
	if ( obj.value == '' ) obj.value='Benutzername';
}

function login_pass_focus() {
	obj=$('lpass');
	if ( obj.value == 'Passwort' ) obj.value='';
}

function login_pass_blur() {
	obj=$('lpass');
	if ( obj.value == '' ) obj.value='Passwort';
}

function fadeOutArmy(aid) {
	la=$('body').getElementsByTagName("*");
	for ( i=0; i < la.length; i++ ) {
		obj=la[i];
		name=obj.id;
// 		document.writeln(name);
		if ( name.search('below_'+aid) != -1 ) {
// 			alert(name);
			$j(obj).animate({opacity:0.7},0);
		}
	}
// 	document.writeln('below_'+aid);
}

function fadeInArmy(aid) {
	la=$('body').getElementsByTagName("*");
	for ( i=0; i < la.length; i++ ) {
		obj=la[i];
		name=obj.id;
		if ( name.search('below_'+aid) != -1 ) {
// 			alert(name);
			$j(obj).animate({opacity:1.0},0);
		}
	}
}


function toggleArmies(aid) {
	la=$('body').getElementsByTagName("*");
	for ( i=0; i < la.length; i++ ) {
		obj=la[i];
		name=obj.id;
		if ( name.search('below_'+aid) != -1 ) {
			if ( obj.hidden ) {
				$j(obj).slideDown(400);
				obj.hidden=0;
			}
			else {
				$j(obj).slideUp(400);
				obj.hidden=1;
			}
		}
	}
}

function error(errmsg) {	
	container=$('sysmsg');
	div='<div class="errmsg" id="current_err">'+errmsg+'</div>';
	container.innerHTML=div;
	
	$j($('sysmsg_outer')).queue( [ ] ).stop();
	
	$('sysmsg_outer').style.opacity=1;
	$('sysmsg_outer').style.top='42%';
	$('sysmsg_outer').style.left='34%';
	$('sysmsg_outer').style.width='26%';
	$('sysmsg_outer').style.height='10%';
	$j($('sysmsg_outer')).hide(0);
	
	errmsg=$('current_err');
	$j($('sysmsg_outer')).show(200);
	$j($('sysmsg_outer')).animate({ opacity:1}, 3000);
	$j($('sysmsg_outer')).animate({top:'5px',left:'1%',width:'98%',height:'60px'},700);
	$j($('sysmsg_outer')).animate({opacity:1}, 7000);
	$j($('sysmsg_outer')).animate({opacity:0},3000);
	
	$j($('sysmsg_outer')).hide(0);
}

function setupEditing(parentID) {
	la=$(parentID).getElementsByTagName("*");
	for ( i=0; i < la.length; i++ ) {
		obj=la[i];
// 		document.writeln(obj.id);
		if ( obj.id.search('grpentry') != -1 ) {
			obj.onmouseover=function() {
				$j(this).animate({backgroundColor:'#CCCCCC',color:'black'},200);
			};
			obj.onmouseout=function() {
				if ( this.value != 0 ) {
					this.parentNode.className='marked';
				}
				else {
					this.parentNode.className='';
				}
				fadeout_army_field(this);
			};
			obj.onblur=function() {
				if ( this.value != 0 ) {
					this.parentNode.className='marked';
				}
				else {
					this.parentNode.className='';
				}
				this.fixed=0;
				if ( ! this.started ) {
					fadeout_army_field(this);
				}
			};
			obj.onfocus=function() {
				this.fixed=1;
				window.armyElFocused=this.id;
				this.prekpvalue=this.value;
				this.initialvalue=this.value;
			}
			obj.onmousedown=function() {
				v=this.value;
				v=v/500;
				
				if ( v == 0 || v < 0.4 ) v=0.4;
				
				tid=this.id.split('__');
				tid=tid[2];
				
				subtrObj=$('defaultgrp__'+tid);
				max=Number(subtrObj.value)+Number(this.value);
				
				start(this.id,v,1,Number(Number(max)+2));
				this.started=1;
				
				$('mouse_status').style.display='block';
				$j($('mouse_status')).fadeTo('fast',0.7);
			}
			obj.onmouseup=function() {
				if ( this.value != 0 ) {
					this.parentNode.className='marked';
				}
				else {
					this.parentNode.className='';
				}
				
				stop();
				this.started=0;
				
				$('mouse_status').style.display='none';
				$j($('mouse_status')).fadeTo('fast',0.7);
			}
		}
	}
}

function fadeout_army_field(obj) {
	if ( obj.fixed ) return 0;
	if ( ! obj.parentNode.className ) {
		$j(obj).animate({backgroundColor:'#DDDDDD',color:'#7F7F7F'},200);
	}
	else {
		$j(obj).animate({backgroundColor:'#DDDDDD'},200);
	}
}

function checkArmySubtrDefaultgrp(change) {
// 	alert(change);
	if ( window.armyElFocused && window.armyElFocused.search('defaultgrp') == -1 ) {
		ae=$(window.armyElFocused);
		tid=window.armyElFocused.split('__');
		tid=tid[2];
		
		subtrObj=$('defaultgrp__'+tid);
		
// 		if ( ! subtrObj ) {
// 			document.writeln('defaultgrp__'+tid);
// 			stop();
// 		}
// 		
		val=subtrObj.value;
		if ( val-change < 0 ) return 0;
		if ( ! val ) val=0;
		
		subtrObj.value-=Number(change);
		gid=window.armyElFocused.split('__');
		gid=gid[1];
		obj=$(window.armyElFocused).parentNode.parentNode.parentNode.parentNode.parentNode;
		if ( ! obj.changed ) {
			markChanged(obj);
		}
		
		return 1;
	
	}
	return 0;
}

function markChanged(obj) {
	obj.changed=1;
	div=$(obj.id+'__ndiv');
	
	div.innerHTML='<input class=test style="border:1px solid #444444; color:#CCCCCC; outline:none; background-color:#555555; -moz-outline-radius:0px; background-image:none; padding:0px;" type=button onclick="sendRequest(\''+obj.id+'\')" value="&Auml;nderungen speichern">';
	$j(div).fadeIn(800);
}

function getCurrentlySelectedArmies(parentID) {
	la=$(parentID).getElementsByTagName("input");
	for ( i=0; i < la.length; i++ ) {
		obj=la[i];
	}
}

function camelizeTables() {
	var tables=document.getElementsByClassName('stat');
	var amount=tables.length;
	
	for ( var i=0; i<amount; i++ ) {
		var table=tables[i];
		i+=1;
		
		var rows=table.getElementsByTagName('TR');
		var rows_amount=rows.length;
		
		var toggle=false;
		for ( var j=0; j<rows_amount; j++) {
			row=rows[j];
			if ( toggle ) {
				row.className='odd';
				toggle=false
			}
			else {
				row.className='';
				toggle=true;
			}
		}
	}
}

function removeEffectsForForumLinks() {
	var div=$('forum');
	if ( ! div ) return;
	var links=div.getElementsByTagName('A');
	var amount=links.length;
	for (var i=0; i<amount; i++ ) {
		var a=links[i];
		a.onmouseover=function() {
			return 0;
		}
		a.onmouseout=function() {
			return 0;
		}
	}
}

$j(document).ready(function() {
	camelizeTables();
	removeEffectsForForumLinks();
})
camelizeTables();

function toggle_select(id,vis) {
	el=$(id);
// 	alert(el.checked);
	if ( el.checked == true ) {
		el.checked=false;
		$(vis).className='notselected';
// 		self.style.backgroundColor='red';
	}
	else {
		el.checked=true;
		$(vis).className='selected';
// 		self.style.backgroundColor='blue';
	}
// 	alert(el.checked);
	
	window.groupsSelected=window.groupsSelected+1;
}
