
function validateEmail(elementValue){ 
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
	return emailPattern.test(elementValue); 
}


function changeDefenceSettingsHelp(select) {
  $value = select.options[select.selectedIndex].value;

  for($i=1;$i<=3;$i++) {
    document.getElementById("defSettings_"+$i).style.display="none";
  }
  document.getElementById("defSettings_"+$value).style.display="block";
}

function changeAttackHelp(select) {
  $value = select.options[select.selectedIndex].value;

  document.getElementById('assault').style.display="none";
  document.getElementById('robbery').style.display="none";
  document.getElementById('destroy').style.display="none";
  document.getElementById('devastating').style.display="none";

  document.getElementById($value).style.display="block";
}

function showHideDetails(select) {
  var value = select.options[select.selectedIndex].value;
	
  for( var i = 0; i < select.length; i++ ) {	
	  document.getElementById(select.options[i].value).style.display="none";
  }

  document.getElementById(value).style.display="block";
  
}


function confirmAction(action) {

	promena = confirm(action);
	if(promena) return true;
	else		return false;
}

function redirect(location)
{
	window.location.href = location;
}

function userCashQuestion()
{
	promenna = confirm("Opravdu chcete okamžitý přepočet? Snížíte tím morálku z zvedne se nám kriminalita!!!");
	if (promenna) redirect('main.php?action=userRecountAction');
	else return false;
}

function helpScreen2(height,width,type,id,column) {
	$win = window.open("help.php?type="+type+"&id="+id+"&column="+column+"","zaklínač help","width="+width+",height="+height+",resizable=no,left=100,top=100");
}

function helpScreen(height,width,text,caption) {
	$win = window.open("","zaklínač help","width="+width+",height="+height+",resizable=no");
	$win.document.write('<html><body>');
	$win.document.write('<h3>Zaklínač help - '+caption+'<h3><br />');
	$win.document.write(text);
	$win.document.write('</html></body>');
	$win.document.close();
	return true;
}

//funkce na zobrazeni/schovani kontextove napovedy
function getObj( objId)
{
	if( document.getElementById)
		return document.getElementById(objId);
	else if( document.all)
		return document.all[objId];
	else if( document.layers)
		return document.layers[objId];
}

function show(objId)
{
	$("#"+objId).show();
}

function hide(objId)
{
	// schovej element
	$("#"+objId).hide();
}

function changeVisibility(objId) {
	//zjisti, jak je na tom element
	
	if( $("#"+objId+":visible").size()  ) {
		$("#"+objId).hide();
	} else {
		$("#"+objId).show();
	}
	return;
}

function slideInOut(objId) {
	if ($("#"+objId).is(":hidden")) {
		 $("#"+objId).slideDown("slow");
	} else {
		$("#"+objId).slideUp("slow");
	}
}

function schowHideSchoolHelp() {
	if ($("#school_fast_help").is(":hidden")) {
		$("#school_fast_help").slideDown("slow");
		$("#schoolFastRoll").attr("src",'img/rollBack.jpg');
	} else {
		$("#school_fast_help").slideUp("slow");
		$("#schoolFastRoll").attr("src",'img/rollUp.jpg');
	}
}

function sendFastQuestion() {
	
	var message = $("#school_fast_question").val();
	if( message.lenght == 0 ) {
		alert('Musíš napsat nějaký dotaz!');
		return;
	}
	
	function fastQuestion() {
		this.data = 'action=messageAction&messageAction=schoolFastQuestion&message='+message,
		this.type = "POST";
		this.url  = "main.php";
		this.cache = false;
		this.dataType = "json";
	}
	
	var fastQuestion = new fastQuestion;
	
	fastQuestion.success = function(data) {
		infoMessage('Zpráva byla odeslána tvému mentorovi');
		$("#school_fast_question").val('');
	}
	
	callAjax(fastQuestion);
}

function slideIn(objId) {
	$("#"+objId).slideUp("slow");
}


function slideDown(objId) {
	$("#"+objId).slideDown("slow");
}



 
function pasteSmile(objId,smileyId) {
	var smilesMap = new Array('' ,';)' ,';(', ';)', ':P', ':D', '::-(', ';o*', ':o()', '*OMG*',
							 '():)' ,':X', ':/', '|p', '*LOL*',':?','- ]:)[ -','B:)','G: )',
							 '|-@',':-)~',':!','=)(=','*DEVIL*','*ROSE*','*BOOM*','*OK*','*DRINK*','*BREAK-HEARTH*');
	
	
	actObj =  getObj(objId);
	actObj.value = actObj.value+' '+ smilesMap[smileyId]+' ';
}

function pasteTextVarianth(objId,what) {
	var varianth;
	
	actObj =  getObj(objId);
	
	if(what == 'bold') varianth = '[B] [/B]';
	if(what == 'italic') varianth = '[I] [/I]';
	if(what == 'underline') varianth = '[U] [/U]';
	
	actObj.value = actObj.value+' '+ varianth+' ';
	
}

function getBigDate(idTarget) {
	
	var now = new Date();
	
	if( idTarget == 'recountEnd' && typeof recountStart != 'undefined') {
			return recountStart;
	} else if (idTarget == 'attackStart' && typeof attackStart != 'undefined') {  
		return attackStart;
	} else { 
		
		iHour = 0;
		if(now.getHours() >= 0 && now.getHours() < 2) iHour = 2;
		if(now.getHours() >= 2 && now.getHours() < 4) iHour = 4;
		if(now.getHours() >= 4 && now.getHours() < 6) iHour = 6;
		if(now.getHours() >= 6 && now.getHours() < 8) iHour = 8;
		if(now.getHours() >= 8 && now.getHours() < 10) iHour = 10;
		if(now.getHours() >= 10 && now.getHours() < 12) iHour = 12;
		if(now.getHours() >= 12 && now.getHours() < 14) iHour = 14;
		if(now.getHours() >= 14 && now.getHours() < 16) iHour = 16;
		if(now.getHours() >= 16 && now.getHours() < 18) iHour = 18;
		if(now.getHours() >= 18 && now.getHours() < 20) iHour = 20;
		if(now.getHours() >= 20 && now.getHours() < 22) iHour = 22;
		if(now.getHours() >= 22 && now.getHours() < 24) iHour = 24;
		
		return new Date(now.getFullYear(),now.getMonth(),now.getDate(),iHour);
	}
}

   	var timerID = null;
	var timerRunning = false;
	
	function showtime(idTarget) {
		//serverData je definovano v informationPage
		var today = new Date();
		var BigDay = getBigDate(idTarget);
		
		var myTime = parseInt((today.getTime()-start.getTime()));
					
		msPerDay = 24 * 60 * 60 * 1000 ;
		timeLeft = (BigDay.getTime() - serverDate.getTime() - myTime);
		
		//$("#test").html( serverDate.getFullYear()+'.'+serverDate.getMonth()+'.'+serverDate.getDate()+' '+serverDate.getHours()+':'+serverDate.getMinutes()+':'+serverDate.getSeconds() );
		//$("#test2").html( BigDay.getFullYear()+'.'+BigDay.getMonth()+'.'+BigDay.getDate()+' '+BigDay.getHours()+':'+BigDay.getMinutes()+':'+BigDay.getSeconds() );
		
		e_daysLeft = timeLeft / msPerDay;
		daysLeft = Math.floor(e_daysLeft);
		
		e_hrsLeft = (e_daysLeft - daysLeft)*24;
		e_hrsLeft+=(daysLeft*24);	//pricteni dni, pokud jsou
		
		hrsLeft = Math.floor(e_hrsLeft);
		minsLeft = Math.floor((e_hrsLeft - hrsLeft)*60);
		e_minsLeft = (e_hrsLeft - hrsLeft)*60;
		secLeft = Math.floor(e_hrsLeft);
		secLeft = Math.floor((e_minsLeft - minsLeft)*60);
		
		if(daysLeft < 0) {
			daysLeft = hrsLeft = minsLeft = secLeft = 0;
		}
		
		if(daysLeft == 0) sDay = 'dní';
		if(daysLeft == 1) sDay = 'den';
		if(daysLeft > 1)  sDay = 'dny';
		if(daysLeft >= 5)  sDay = 'dní';
		
		if(hrsLeft == 0) sHour = 'hodin';
		if(hrsLeft == 1) sHour = 'hodina';
		if(hrsLeft > 1)  sHour = 'hodiny';
		if(hrsLeft >= 5)  sHour = 'hodin';
		
		if(minsLeft == 0) sMin = 'minut';
		if(minsLeft == 1) sMin = 'minuta';
		if(minsLeft > 1)  sMin = 'minuty';
		if(minsLeft >= 5)  sMin = 'minut';
		
		if(secLeft == 0) sSec = 'sekund';
		if(secLeft == 1) sSec = 'sekunda';
		if(secLeft > 1)  sSec = 'sekundy';
		if(secLeft >= 5)  sSec = 'sekund';
		
		if (idTarget == 'attackStart' && typeof attackStart != undefined) {
			sText='Do začátku bojů zbývá: '+hrsLeft+' '+sHour+', '+minsLeft+' '+sMin+', '+secLeft+' '+sSec+'.';
		} else {
			sText='Do systémového přepočtu zbývá: '+hrsLeft+' '+sHour+', '+minsLeft+' '+sMin+', '+secLeft+' '+sSec+'.';
		}
		
		document.getElementById(idTarget).innerHTML = sText;
		
		timerID = setTimeout("showtime('"+idTarget+"')",1000);
		timerRunning = true;
		
	}
   
	
	var timerID = null;
	var timerRunning = false;
	
	function stopclock () {
		if(timerRunning)
		clearTimeout(timerID);
		timerRunning = false;
	}
	
	function stopClock() {
		stopclock();
		return;
	}
	
	function startclock () {
		stopclock();
		showtime('recountEnd');
		
		if (typeof attackStart != undefined) {
			showtime('attackStart');
		}
	}
	
	/* funkce hleda v poli bonusu a v pripade vyhledani, vypise */
	function getUnitToUnitBonus(aUnitToUnitBonus) {
	
	  aDefCheck = document.getElementsByName('defenderUnit');
	  aAttCheck = document.getElementsByName('attackerUnit');
	  
	  iDefenderUnit = 0;
	  iAttackerUnit = 0;
	  
	  for(i = 0; i < aDefCheck.length; i++) {
	      if (aDefCheck[i].checked)  iDefenderUnit = aDefCheck[i].value;
	   }
	   
	  for(i = 0; i < aAttCheck.length; i++) {
	      if (aAttCheck[i].checked)  iAttackerUnit = aAttCheck[i].value;
	   }

	  sResultText = '';		  
	  if (iDefenderUnit > 0 && iAttackerUnit > 0) {
	  	
	  	iUnitToUnitBonus = aUnitToUnitBonus[iDefenderUnit][iAttackerUnit];
	  	if(!iUnitToUnitBonus) iUnitToUnitBonus = 0;
	  	
	  	if (iUnitToUnitBonus < 0) sResultText = '<span class="down_factor">'+iUnitToUnitBonus+'%</span>';
	  	else					  sResultText = '<span class="up_factor">+'+iUnitToUnitBonus+'%</span>';	
	  }
	  
  	  document.getElementById('unit2unit').innerHTML = sResultText;
	  
	}

//zmena visibility
function changeAttackVisibility(element,key) {
    
    if ($(element).attr('src') == 'img/rollUp.jpg') {
		$(element).attr('src','img/rollBack.jpg');
    	$("tr[@name="+key+"]").removeClass("hideElement");		
		
    } else {
    	$(element).attr('src','img/rollUp.jpg');
    	$("tr[@name="+key+"]").addClass("hideElement");
    }
}

function getStatsArrow(id,direction) {
	return '<img src="img/arrows_stats_'+direction+'.gif" alt="'+direction+'" onclick="changeStats(\''+id+'\',\''+direction+'\')" />';
}

function getAbilityStatsArrow(id,direction) {
	return '<img src="img/arrows_stats_'+direction+'.gif" alt="'+direction+'" onclick="changeAbilityStats(\''+id+'\',\''+direction+'\')" />';
}

function changeAbilityStats( id, direction ) {
	
	//zvyseni atributu
 	if (direction == 'right') {
 		
 		var level = $("#"+id+"Text").text();
 		$("#"+id+"Text").text(  ++level  );
 		
 		//zruseni sipky
 		if( level >= MAX_ABILITY_LEVEL ) {
 			$("#"+id+"_right").html('&nbsp;');
 		}
 		
 		level = $("#"+id).val();
 		$("#"+id).val( ++level );
 		
 		level = $("#abilityStat").val();
 		$("#abilityStat").val( --level  );
 		
 		//zruseni sipky
 		if( $("#abilityStat").val() <= 0 ) {
 			$("#"+id+"_right").html('&nbsp;');
 		}
 		
 		//pridani sipky
 		$("#"+id+"_left").html( getAbilityStatsArrow(id, 'left') );
 	}
 	
 	//snizeni atributu
 	if (direction == 'left') {
 		var level = $("#"+id+"Text").text();
 		$("#"+id+"Text").text(  --level  );
 		
 		level = $("#"+id).val();
 		$("#"+id).val( --level );
 		
 		level = $("#abilityStat").val();
 		$("#abilityStat").val(  ++level  );
 		
 		//zruseni sipky
 		if( $("#"+id).val() <= 0 ) {
 			$("#"+id+"_left").html('&nbsp;');
 		}
 		
 		//pridani sipky
 		$("#"+id+"_right").html( getAbilityStatsArrow(id, 'right') );
 		
 	}
	
}

function changeStats(id, direction ) {
 
  //zvyseni atributu
 if (direction == 'right') {
 	
 	var reUseStats = $(":input[@name='reUseStats']").val();
 	 	
 	//zmena inputu
 	var value = $(":input[@name='"+id+"']").val();
 	$(":input[@name='"+id+"']").val(++value)
 	
 	//zmena inputu sumy
 	var stats = $(":input[@name='stats']").val();
 	$(":input[@name='stats']").val(--stats);
 	
 	//zmena textu v html
 	var actualPts = $("#"+id+"").html();
 	$("#"+id+"").html(++actualPts);
 }
 
 if (direction == 'left') {
 	
 	var reUseStats = $(":input[@name='reUseStats']").val();
 	if (reUseStats > 0) {
 		$(":input[@name='reUseStats']").val(--reUseStats);
 	}
 	
 	if (reUseStats == 0) {	$("#reUseStatsText").html('0');  }
  	else { 	$("#reUseStatsText").html(reUseStats);		}
 	
 	var value = $(":input[@name='"+id+"']").val();
 	$(":input[@name='"+id+"']").val(--value);
 	
 	var stats = $(":input[@name='stats']").val();
 	$(":input[@name='stats']").val(++stats);
 	
 	var actualPts = $("#"+id+"").html();
 	$("#"+id+"").html(--actualPts);
 	 	 	
 	if(actualPts == 0) {
 		$("#"+id+"").html('0');
 		$("#"+id+"_left").html('&nbsp;');
 	}
 	
 	if (value == 0) {
 		$("#"+id+"_left").html('&nbsp;');
 	}
 }
 
 //moznost posunu hodnoty zpet
 if (value > 0) {
 	$("#"+id+"_left").html(getStatsArrow(id,'left'));
 } else {
 	$("#"+id+"_left").html('&nbsp');
 }

 //pokud je reUseBoxu
 if (isReUseStats  && reUseStats == 0) {
 	$("#strength_left").html('&nbsp');
 	$("#live_left").html('&nbsp');
 	$("#defence_left").html('&nbsp');
 }
 
 if (reUseStats > 0) {
 	
 	if($("#strength").html() <= 0 || (id == 'strength' && direction == 'right')) {
 		$("#strength_left").html('&nbsp;');
 	} else {
 		$("#strength_left").html(getStatsArrow('strength','left'));
 	}
 	
 	if($("#live").html() <= 0 || (id == 'live' && direction == 'right')) {
 		$("#live_left").html('&nbsp;');
 	} else {
 		$("#live_left").html(getStatsArrow('live','left'));
 	}
 	
 	if($("#defence").html() <= 0 || (id == 'defence' && direction == 'right')) {
 		$("#defence_left").html('&nbsp;');
 	} else {
 		$("#defence_left").html(getStatsArrow('defence','left'));
 	}
 }  
 
 //osetreni vycerpani vsech atributu
 if( stats <= 0) {
 	$("#strength_right").html('&nbsp');
 	$("#live_right").html('&nbsp');
 	$("#defence_right").html('&nbsp');
 } else {
 	if(isReUseStats && id == 'strength' && direction == 'left') { 
 		$("#strength_right").html('&nbsp;');
 	} else {
 		$("#strength_right").html(getStatsArrow('strength','right'));
 	}
 	
 	if(isReUseStats && id == 'live' && direction == 'left') { 
 		$("#live_right").html('&nbsp;');
 	} else {
 		$("#live_right").html(getStatsArrow('live','right'));
 	}
 	
 	if(isReUseStats && id == 'defence' && direction == 'left') { 
 		$("#defence_right").html('&nbsp;');
 	} else {
 		$("#defence_right").html(getStatsArrow('defence','right'));
 	}
 }
 
  if (stats <= 0) {	$("#statsText").html('0');  }
  else { 	$("#statsText").html(stats);		}
  
  actualPts = $("#strength").html();
  if(actualPts >= maxStats) {
 	$("#strength_right").html('');		
  }
  
  actualPts = $("#live").html();
  if(actualPts >= maxStats) {
 	$("#live_right").html('');		
  }
  
  actualPts = $("#defence").html();
  if(actualPts >= maxStats) {
 	$("#defence_right").html('');		
  }
 
}

function slideDown (id) {
	$("#"+id).show("slide", { direction: "up" }, 1000);
	
}

function slideUp ( id ) {
	$("#"+id).hide("slide", { direction: "up" }, 1000);
}
 
//animace msgBoxu detailu budov
function msgBox ( text , type) {
  $("#msgBox_"+type).css( "color","green" ).text( text );
} 

function errBox ( text , type ) {
  $("#msgBox_"+type).css( "color","red" ).text( text );
}

function errorMessage(err) {
	$.growlUI(err,'&nbsp;', 5000, null, 'growlError');
}

function infoMessage(info) {
	$.growlUI(info, '&nbsp;'); 
}
 
//upgrade budov
function upgradeBuilding(type) {
								
		function upgrade() {
			this.data = 'action=buildings&upgrade=1&building_'+type+'=true';
			this.type = "POST";
			this.url  = "main.php";
			this.cache = false;
			this.dataType = "xml";
		}
		
		var upgrade = new upgrade;
		upgrade.success = function(data) {
			
			var msg = $(data).find("/root/msg").text();
			var err = $(data).find("/root/err").text();
			
			if ( err.length > 0) {
				errorMessage( err );
			} else {
			
				$("#buildingLevel_"+type).text( $(data).find("/root/level").text() );
				$("#upgrade_"+type).text( $(data).find("/root/upgrade").text() );
				$("#buildingLimit_"+type).text( $(data).find("/root/limit").text() );
				$("#userCash").text( $(data).find("/root/userCash").text() );
				$("#favour2").text( $(data).find("/root/favour2").text() );
				$("#freeArea").text( $(data).find("/root/freeArea").text() );
				
				if ( $(data).find("/root/canUpgrade").text() == '1') { $("#upgradeBtn"+type).show();}
				else 												 { $("#upgradeBtn"+type).hide();}
				
				if ( $(data).find("/root/canBuy").text() == '1') { $("#buyBtn"+type).show();}
				else 											 { $("#buyBtn"+type).hide();}
				
				infoMessage( msg );
			}
		}
		
		upgrade.error = function(event, request, settings) {
			alert("Chyba při upgradu!"+request);
		}
					
		callAjax(upgrade);
}

function buyBuilding ( type ) {

	var amount = ( $(":input[@name='amount_"+type+"']").size() > 0 ) ? $(":input[@name='amount_"+type+"']").val() : 1; 
		
	function buy() {
			this.data = 'action=buildings&buy=1&building_'+type+'=true&amount='+amount;
			this.type = "POST";
			this.url  = "main.php";
			this.cache = false;
			this.dataType = "xml";
		}
		
		var buy = new buy;
		buy.success = function(data) {

			if(this.dataType == 'text') {
				alert(data);
				return;
			}
			
			var msg = $(data).find("/root/msg").text();
			var err = $(data).find("/root/err").text();
			
			
			if ( err.length > 0) {
				errorMessage( err );
			} else {
				
				$("#buildingExists_"+type).text( $(data).find("/root/amount").text() );
				$("#buildingLimit_"+type).text( $(data).find("/root/limit").text() );
				$("#userCash").text( $(data).find("/root/userCash").text() );
				$("#freeArea").text( $(data).find("/root/freeArea").text() );
				
				if ( $(data).find("/root/canUpgrade").text() == '1') { $("#upgradeBtn"+type).show(); }
				else 												 { $("#upgradeBtn"+type).hide(); }
				
				if ( $(data).find("/root/canBuy").text() == '1') { $("#buyBtn"+type).show();}
				else 											 { $("#buyBtn"+type).hide();}
				
				infoMessage( msg );
			}
		}
		
		buy.error = function(event, request, settings) {
			alert("Chyba při nákupu!"+request);
		}
		
		buy.beforeSend = function () {
			 $("#ajaxLoaderMessage_"+type).text("kupuji");
			 $("#ajaxLoader_"+type).show();
		}
		
		buy.complete = function () {
			 $("#ajaxLoader_"+type).hide();
		}
					
		callAjax(buy);
}

function sellBuilding ( type ) {
	
	function sell() {
			this.data = 'action=buildings&sell=1&building_'+type+'=true&amount='+$(":input[@name='amount_"+type+"']").val();
			this.type = "POST";
			this.url  = "main.php";
			this.cache = false;
			this.dataType = "xml";
		}
		
		var sell = new sell;
		
		sell.success = function(data) {
			
			var msg = $(data).find("/root/msg").text();
			var err = $(data).find("/root/err").text();
			
			if ( err.length > 0) {
				errorMessage( err );
			} else {
				$("#buildingExists_"+type).text( $(data).find("/root/amount").text() );
				$("#buildingLimit_"+type).text( $(data).find("/root/limit").text() );
				$("#userCash").text( $(data).find("/root/userCash").text() );
				$("#freeArea").text( $(data).find("/root/freeArea").text() );
				
				if ( $(data).find("/root/canUpgrade").text() == '1') { $("#upgradeBtn"+type).show();}
				else 												 { $("#upgradeBtn"+type).hide();}
				
				if ( $(data).find("/root/canBuy").text() == '1') { $("#buyBtn"+type).show();}
				else 											 { $("#buyBtn"+type).hide();}
				
				infoMessage( inf );
			}
		}
		
		sell.error = function(event, request, settings) {
			alert("Chyba při prodeji!"+request);
		}
		
		sell.beforeSend = function () {
			 $("#ajaxLoaderMessage_"+type).text("prodávám");
			 $("#ajaxLoader_"+type).show('');
		}
		
		sell.complete = function () {
			 $("#ajaxLoader_"+type).hide();
		}
					
		callAjax(sell);
	
}

function callAjax( setup ) {
	//inicializace ajax-loaderu
		
	$.ajax({
		//setup
		type: setup.type,
		url: setup.url,
		data: setup.data,
		cache: setup.cache,
		dataType: setup.dataType,
		
		//funkce
		success: setup.success,
		error: setup.error,
		beforeSend: setup.beforeSend,
		complete: setup.complete
	});
}

function poverToCount(power, id) {

	var val = $("#unit_"+id).val();
    $("#unit_"+id).val( Math.floor( val / power) );
}



