var http = getHTTPObject();

function hidecontent()
{
	var varDom = document.getElementById('balloon');
	try
	{
		varDom.style.display="none";
	}
	catch (ex)
	{
		if (disable_debug_handler == true)
		{
			debug(ex);
		}
	}
	return true;
}
	
function getHTTPObject()
{
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	@else
		xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
	{
		try
		{
			xmlhttp = new XMLHttpRequest();
		}
		catch (e)
		{
			xmlhttp = false;
		}
	}
	return xmlhttp;
}

function checkSneakAttack(confirmstring, kingdomconfirmstring)
{
	var touserid;
	try
	{
		touserid = document.getElementById('TextBoxUserID').value;
		http.open("GET", "handlerchecksneakattack.ashx?id=" + touserid + "|" + Math.random(), true);
		http.onreadystatechange = function()
		{
    		if (http.readyState == 4)
    		{
			    var result = http.responseText;
			    var postresult = true;
			    var intResult = parseInt(result);
			    if (intResult != 3)
			    {
			        if ((intResult % 2) == 0)
			        {
    				    var confirmresult = confirm(confirmstring);
	    			    postresult = confirmresult;
	    			}
	    			if (postresult && intResult < 2)
	    			{
    				    var confirmresult = confirm(kingdomconfirmstring);
	    			    postresult = confirmresult;
	    			}
			    }
			    if (postresult)
			    {
				    document.getElementById('JavaPostBack').value = "1";
				    document.Form1.submit();
			    }
			}
		};
	}
	catch (e)
	{
		document.getElementById('JavaPostBack').value = "1";
		document.Form1.submit();
	}
	http.send(null);
}

function checkTicketPrice()
{
	try
	{
		http.open("GET", "handlergen.ashx?rand=" + Math.random() + "&type=23", true);
		http.onreadystatechange = function()
	    {
		    if (http.readyState == 4)
    	    {
		        var result = http.responseText;
		        var priceIndex = result.indexOf('|');
		        if (priceIndex <= 0)
		        {
		            alert("Error");
		            document.getElementById('JavaPostBack').value = "-1000";
			        document.Form1.submit();
		        }
		        else
		        {
		            var price = result.substring(0, result.indexOf('|'));
		            result = result.substring(result.indexOf('|') + 1, result.length);
		            var confirmresult = confirm(result);
		            if (confirmresult)
		            {
    		            document.getElementById('JavaPostBack').value = price;
	    	            document.Form1.submit();
			        }
			    }
		    }
		};
	}
	catch (e)
	{
	}
	http.send(null);
}

function checkPrice(sellType)
{
	var itemType;
	var transportType = 1;
	var amount;
	var fleetID = 0;
	try
	{
	    itemType = document.getElementById('itemtype')[document.getElementById('itemtype').selectedIndex].value;
	    amount = document.getElementById('amount').value;
	    var doNotCheck = false;
	    if (amount == null || amount.length == 0 || !isNum(amount) || parseInt(amount) <= 0)
	    {
	        doNotCheck = true;
	        amount = 1;
	    }
	    if (!doNotCheck)
	    {
	        if (document.getElementById('rb2').checked)
	            transportType = 2;
	        else if (document.getElementById('rb3').checked)
	            transportType = 3;
	        if (transportType > 1 && document.getElementById('CheckBoxUseEscortFleet').checked && document.getElementById('VisibilityDropDownListEscortFleets').selectedIndex > -1)
	            fleetID = document.getElementById('VisibilityDropDownListEscortFleets')[document.getElementById('VisibilityDropDownListEscortFleets').selectedIndex].value;
	    }
	            
		http.open("GET", "handlergen.ashx?rand=" + Math.random() + "&type=" + sellType + "&var1=" + itemType + "&var2=" + transportType + "&var3=" + amount + "&var4=" + fleetID, true);
		http.onreadystatechange = function()
	    {
		    if (http.readyState == 4)
    	    {
			    if (!doNotCheck)
			    {
			        var result = http.responseText;
			        var priceIndex = result.indexOf('|');
			        if (priceIndex <= 0)
			        {
			            alert("Error in demand. Please try again after 1 hour.");
			            document.getElementById('JavaPostBack').value = "-1000";
				        document.Form1.submit();
			        }
			        else
			        {
		                var price = result.substring(0, result.indexOf('|'));
			            result = result.substring(result.indexOf('|') + 1, result.length);
			            var confirmresult = confirm(result);
			            if (confirmresult)
			            {
				            document.getElementById('JavaPostBack').value = price;
				            document.Form1.submit();
			            }
			        }
			    }
		    }
		};
	}
	catch (e)
	{
	}
	http.send(null);
}

function dw(str)
{
	document.write(str);
}


function generateBalloon()
{
	dw('<div id="balloon" style="z-index: 1000; DISPLAY: none; POSITION: absolute">');
	dw('	<table width="350" cellSpacing="0" cellPadding="0" border="0">');
	dw('	<tr>');
	dw('		<td class="popup" vAlign="top" width="6"><img height="6" src="balloonimages/mt1.png" width="6" border="0"></td>');
	dw('		<td class="popup" vAlign="top" style="background-image:url(balloonimages/mt2.png)"></td>');
	dw('		<td class="popup" vAlign="top" width="6"><img height="6" src="balloonimages/mt3.png" width="6" border="0"></td>');
	dw('	</tr>');
	dw('	<tr bgColor="#ffffff">');
	dw('		<td class="popup" vAlign="top" style="background-image:url(balloonimages/mt4.png)"></td>');
	dw('		<td class="popup" vAlign="top" bgColor="#f9f7f7">');
	dw('            <table cellSpacing="0" cellPadding="0" border="0"><tr><td><img alt="" src="balloonimages/mb_01.png"></td><td><img alt="Page Up" src="balloonimages/mb_02.png" onclick="document.getElementById(\'ballooncontent\').scrollTop -= 100;" style="cursor:pointer;cursor:hand;"></td><td><img alt="" src="balloonimages/mb_03.png"></td><td><img alt="" src="balloonimages/mb_07.png"></td></tr></table>');
	dw('			<div id="ballooncontent" style="background-image: url(balloonimages/bg.jpg); margin: 0px; text-align: center; overflow: hidden; WIDTH: 350px;"> <!--CO--></div>');
	dw('            <table cellSpacing="0" cellPadding="0" border="0"><tr><td><img alt="" src="balloonimages/mb_01.png"></td><td><img alt="Page Down" src="balloonimages/mb_06.png" onclick="document.getElementById(\'ballooncontent\').scrollTop += 100;" style="cursor:pointer;cursor:hand;"></td><td><img alt="" src="balloonimages/mb_03.png"></td><td><img alt="Close" src="balloonimages/mb_04.png" onclick="closeballoon(\'balloon\')" style="cursor:pointer;cursor:hand;"></td></tr></table>');
	dw('		</td>');
	dw('		<td class="popup" vAlign="top" style="background-image:url(balloonimages/mt5.png)"></td>');
	dw('	</tr>');
	dw('	<tr>');
	dw('		<td class="popup" vAlign="top" width="6"><img height="6" src="balloonimages/mt6.png" width="6" border="0"></td>');
	dw('		<td class="popup" vAlign="top" style="background-image:url(balloonimages/mt7.png)"></td>');
	dw('		<td class="popup" vAlign="top" width="6"><img height="6" src="balloonimages/mt8.png" width="6" border="0"></td>');
	dw('	</tr>');
	dw('	</table>');
	dw('</div>');
	
	document.getElementById('ballooncontent').style.height = document.body.offsetHeight - 50;

    if (window.addEventListener)
    {//DOM method for binding an event  - standart browserlar 
	    window.addEventListener("resize", HandleBalloonPositionChange, false) ;
	    window.addEventListener("scroll", HandleBalloonPositionChange, false) ;
    }
    else if (window.attachEvent)
    {//IE exclusive method for binding an event 
	    window.attachEvent("onresize", HandleBalloonPositionChange);
	    window.attachEvent("onscroll", HandleBalloonPositionChange);
    }
    else if (document.getElementById)
    {//support older modern browsers 
	    window.resize=HandleBalloonPositionChange();
	    window.scroll=HandleBalloonPositionChange();
    }
}

function HandleBalloonPositionChange()
{
	document.getElementById('balloon').style.left = document.body.clientWidth - document.getElementById('balloon').clientWidth;
	document.getElementById('balloon').style.top = document.body.scrollTop;
	document.getElementById('ballooncontent').style.height = document.body.clientHeight - 50;
}

function closeballoon(str)
{
	document.getElementById(str).style.display="none";
}

function updateHotListContent(userid, funcname, minimumAttackRangeInRankings)
{
   	http.open("GET", "hotlist.aspx?id=" + userid + "|" + Math.random() + "&action=" + funcname, true);
	http.onreadystatechange = function()
	{
		if (http.readyState == 4)
		{
			document.getElementById("ballooncontent").innerHTML=http.responseText;
			document.getElementById("ballooncontent").style.backgroundImage = "url(balloonimages/bg2.jpg)";
			balloon.style.display="";
			document.getElementById('balloon').style.left = document.body.clientWidth - document.getElementById('balloon').clientWidth;
			document.getElementById('balloon').style.top = document.body.scrollTop;
			ChangeColorForPointRangeAndRelations(0, document.getElementById('point').value, document.getElementById('rels').value, minimumAttackRangeInRankings);
		}
	};
	http.send(null);
}

function updateBalloonContent(url)
{
	http.open("GET", url, true);
	http.onreadystatechange = function()
	{
		if (http.readyState == 4)
		{
			document.getElementById('ballooncontent').innerHTML=http.responseText;
			document.getElementById("ballooncontent").style.backgroundImage = "url(balloonimages/bg.jpg)";
			balloon.style.display="";
			HandleBalloonPositionChange();
		}
	};
	http.send(null);
	document.getElementById('ballooncontent').scrollTop=0;
}

function ExodusKeyPress(e, NA)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 0 || keynum == 13 || (keynum >= 35 && keynum <= 40) || keynum == 46)
        return true;
    if (keynum == 8)
    {
        deleteAtCursor(document.getElementById('newlocation'));
        updateProductionTurns(document.getElementById('newlocation').value, NA);
    }
    else if (keynum >= 48 && keynum <= 57)
    {
        insertAtCursor(document.getElementById('newlocation'), String.fromCharCode(keynum));
        updateExodusTurns(document.getElementById('newlocation').value, NA);
    }
    return false;
}

function updateExodusTurns(val, NA)
{
	if (!isNum(val))
	{
	    document.getElementById('turns').innerHTML = NA;
	}
	else if (val == 0)
	{
	    document.getElementById('turns').innerHTML = NA;
	}
	else
	{
	    if (parseInt(val) > 1000000)
	    {
	        val = 1000000;
	        document.getElementById('newlocation').value = val;
	    }
        var distance;
        if (Math.floor(curlocation / 10) == Math.floor(val / 10))
            distance = 1;
        else if (Math.floor(curlocation / 100) == Math.floor(val / 100))
            distance = 2;
        else if (Math.floor(curlocation / 1000) == Math.floor(val / 1000))
            distance = 3;
        else if (Math.floor(curlocation / 10000) == Math.floor(val / 10000))
            distance = 4;
        else
            distance = 5;
	    document.getElementById('turns').innerHTML = distance * turnsperdistance;
	}
}

function ProductionKeyPress(e, NA)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 0 || keynum == 13 || (keynum >= 35 && keynum <= 40) || keynum == 46)
        return true;
    if (keynum == 8)
    {
        deleteAtCursor(document.getElementById('amount'));
        updateProductionTurns(document.getElementById('amount').value, NA);
    }
    else if (keynum >= 48 && keynum <= 57)
    {
		if (navigator.appName.indexOf("Microsoft") == -1) // probably caused by assigning defaultbutton="ButtonProduceID" in productionnew.aspx
			insertAtCursor(document.getElementById('amount'), String.fromCharCode(keynum));
        updateProductionTurns(document.getElementById('amount').value, NA);
    }
    return false;
}

function updateProductionTurns(val, NA)
{
	if (!isNum(val))
	{
	    document.getElementById('turns').innerHTML = NA;
	    document.getElementById('gold').innerHTML = NA;
	}
	else if (val == 0)
	{
	    document.getElementById('turns').innerHTML = NA;
	    document.getElementById('gold').innerHTML = NA;
	}
	else
	{
        if (document.getElementById('maxamount').innerHTML == '0')
	        val = 0;
	    else if (parseInt(val) > parseInt(document.getElementById('maxamount').innerHTML))
	        val = document.getElementById('maxamount').innerHTML;
	    document.getElementById('turns').innerHTML = CalculateProductionTurnsToComplete(pointpower, val, requiredpoint, optimalpoint, currentpoint);
	    var temp = document.getElementById('requiredgold').innerHTML.split(' ');
	    document.getElementById('gold').innerHTML = val * temp[0];
	}
	if (document.getElementById('amount').value != val)
	    document.getElementById('amount').value = val;
}

function ConstructionKeyPressAmount(e, NA)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 0 || keynum == 13 || (keynum >= 35 && keynum <= 40) || keynum == 46)
        return true;
    if (keynum == 8)
    {
        deleteAtCursor(document.getElementById('amount'));
        updateConstructionTurns(document.getElementById('amount').value, document.getElementById('workers').value, NA);
    }
    else if (keynum >= 48 && keynum <= 57)
    {
        insertAtCursor(document.getElementById('amount'), String.fromCharCode(keynum));
        updateConstructionTurns(document.getElementById('amount').value, document.getElementById('workers').value, NA);
    }
    return false;
}

function ConstructionKeyPressWorkers(e, NA)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 0 || keynum == 13 || (keynum >= 35 && keynum <= 40) || keynum == 46)
        return true;
    if (keynum == 8)
    {
        deleteAtCursor(document.getElementById('workers'));
        updateConstructionTurns(document.getElementById('amount').value, document.getElementById('workers').value, NA);
    }
    else if (keynum >= 48 && keynum <= 57)
    {
        insertAtCursor(document.getElementById('workers'), String.fromCharCode(keynum));
        updateConstructionTurns(document.getElementById('amount').value, document.getElementById('workers').value, NA);
    }
    return false;
}

function updateConstructionTurns(amount, workers, NA)
{
	if (!isNum(amount))
	    document.getElementById('optimalworkers').innerHTML = NA;
	else if (amount == 0)
	    document.getElementById('optimalworkers').innerHTML = NA;
	else
	{
        if (document.getElementById('maxamount').innerHTML == '0')
	        amount = 0;
	    else if (parseInt(amount) > parseInt(document.getElementById('maxamount').innerHTML))
	        amount = document.getElementById('maxamount').innerHTML;
	    document.getElementById('optimalworkers').innerHTML = amount * optimalpoint;
	}

	if (isNum(workers))
	{
        if (document.getElementById('maxworkers').innerHTML == '0')
	        workers = 0;
	    else if (parseInt(workers) > parseInt(document.getElementById('maxworkers').innerHTML))
	        workers = document.getElementById('maxworkers').innerHTML;
	}

	if (!isNum(amount) || !isNum(workers))
	    document.getElementById('turns').innerHTML = NA;
	else if (amount == 0 || workers == 0)
	    document.getElementById('turns').innerHTML = NA;
	else
	    document.getElementById('turns').innerHTML = CalculateProductionTurnsToComplete(workers, amount, requiredpoint, optimalpoint, currentpoint);

	if (document.getElementById('amount').value != amount)
	    document.getElementById('amount').value = amount;
	if (document.getElementById('workers').value != workers)
	    document.getElementById('workers').value = workers;
}

function isNum(argvalue)
{
    argvalue = argvalue.toString();
    if (argvalue.length == 0)
        return false;
    for (var n = 0; n < argvalue.length; n++)
        if (argvalue.substring(n, n + 1) < "0" || argvalue.substring(n, n + 1) > "9")
            return false;
    return true;
}

function deleteAtCursor(myField)
{
    //IE support
    // if (document.selection)
    if (navigator.appName.indexOf("Microsoft") != -1)
    {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = '';
    }
    //MOZILLA/NETSCAPE support
    // else if (myField.selectionStart || myField.selectionStart == '0')*/
    else if (navigator.appName.indexOf("Mozilla") != -1 || navigator.appName.indexOf("Netscape") != -1 || navigator.appName.indexOf("Opera") != -1)
    {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        if (startPos == endPos)
            myField.value = myField.value.substring(0, startPos - 1) + myField.value.substring(startPos, myField.value.length);
        else
            myField.value = myField.value.substring(0, startPos) + myField.value.substring(endPos, myField.value.length);
    }
    else
        myField.value = myField.value.substring(0, myField.value.length - 1);
}

function insertAtCursor(myField, myValue)
{
    //IE support
    // if (document.selection)
    if (navigator.appName.indexOf("Microsoft") != -1)
    {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        sel.select();
        while (myField.value.length > 1 && myField.value.substring(0, 1) == '0')
            myField.value = myField.value.substring(1, myField.value.length);
    }
    //MOZILLA/NETSCAPE support
    // else if (myField.selectionStart || myField.selectionStart == '0')*/
    else if (navigator.appName.indexOf("Mozilla") != -1 || navigator.appName.indexOf("Netscape") != -1 || navigator.appName.indexOf("Opera") != -1)
    {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
        while (myField.value.length > 1 && myField.value.substring(0, 1) == '0')
            myField.value = myField.value.substring(1, myField.value.length);
    }
    else
        myField.value += myValue;
}

function CalculateProductionTurnsToComplete(pppower, weaponamount, pp, optimalpp, currentpp)
{
    var produceamountCeil = Math.ceil(pppower / optimalpp);
	var produceamountFloor = Math.floor(pppower / optimalpp);
	if (produceamountFloor == produceamountCeil)
	    produceamountCeil += 1;
	if (produceamountCeil > weaponamount)
		return Math.ceil((pp * weaponamount - currentpp) / Math.floor(Math.atan(0.5773504 * pppower / (optimalpp * weaponamount)) / 0.523598775594983 * (optimalpp * weaponamount)));
	else
	{
	    var result1 = CalculateProductionTurnsToCompleteAux(produceamountCeil, pppower, weaponamount, pp, optimalpp, currentpp);
	    var result2 = 10000000;
	    if (produceamountFloor > 0)
	        result2 = CalculateProductionTurnsToCompleteAux(produceamountFloor, pppower, weaponamount, pp, optimalpp, currentpp);
	    return Math.min(result1, result2);
	}
}

function CalculateProductionTurnsToCompleteAux(produceamount, pppower, weaponamount, pp, optimalpp, currentpp)
{
	var turnswithoptimal = Math.ceil((pp * (Math.floor(weaponamount / produceamount) * produceamount) - currentpp) / Math.floor(pppower));
	if (weaponamount % produceamount == 0)
		return turnswithoptimal;
	else
		return turnswithoptimal + Math.max(1, Math.ceil((pp * weaponamount - (currentpp + pppower * turnswithoptimal)) / Math.floor(Math.atan(0.5773504 * pppower / (optimalpp * (weaponamount % produceamount))) / 0.523598775594983 * (optimalpp * (weaponamount % produceamount)))));
}

function TrainingKeyPress(e, NA, Gold)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 0 || keynum == 13 || (keynum >= 35 && keynum <= 40) || keynum == 46)
        return true;
    if (keynum == 8)
    {
        deleteAtCursor(document.getElementById('amount'));
        updateTrainingCost(document.getElementById('amount').value, NA, Gold);
    }
    else if (keynum >= 48 && keynum <= 57)
    {
        insertAtCursor(document.getElementById('amount'), String.fromCharCode(keynum));
        updateTrainingCost(document.getElementById('amount').value, NA, Gold);
    }
    return false;
}

function updateTrainingCost(amount, NA, Gold)
{
	if (!isNum(amount))
	    document.getElementById('totalcost').innerHTML = NA;
	else if (amount == 0)
	    document.getElementById('totalcost').innerHTML = NA;
	else
	{
	    if (document.getElementById('maxamount').innerHTML == '0')
	        amount = 0;
	    else if (parseInt(amount) > parseInt(document.getElementById('maxamount').innerHTML))
	        amount = document.getElementById('maxamount').innerHTML;
        var temp = document.getElementById('goldcost').innerHTML.split(' ');
        document.getElementById('totalcost').innerHTML = amount * temp[0] + Gold;
	}
	if (document.getElementById('amount').value != amount)
	    document.getElementById('amount').value = amount;
}

function TextBoxLimitKeyPress(event, maxLength, textBoxID)
{
    if (document.getElementById(textBoxID).value.length > maxLength)
        return false;
    return true;
}

function TextBoxLimitKeyUp(maxLength, textBoxID)
{
    if (document.getElementById(textBoxID).value.length > maxLength)
        document.getElementById(textBoxID).value = document.getElementById(textBoxID).value.substring(0, maxLength);
}

function TextBoxOnlyNumberWithLimit(e, textbox, limit)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 0 || keynum == 13 || (keynum >= 35 && keynum <= 40) || keynum == 46)
        return true;
    if (keynum == 8)
        deleteAtCursor(textbox);
    else if (keynum >= 48 && keynum <= 57)
    {
        insertAtCursor(textbox, String.fromCharCode(keynum));
        LimitTextBox(textbox, limit);
    }
    return false;
}

function LimitTextBox(textbox, limit)
{
    if (!isNum(textbox.value))
    {   
        if (textbox.value.toString().length > 0)
            textbox.value = '';
    }
    else if (parseInt(textbox.value) > parseInt(limit))
        textbox.value = limit;
}

function updateFleetOrderAttackTargetCosts(NA)
{
    var userid = document.getElementById('TextBoxUserID').value;
    var location = -1;
    if (issizezero == 1 || !isNum(userid) || userid == 0)
    {
        document.getElementById('LabelGold').innerHTML = NA;
        document.getElementById('LabelFood').innerHTML = NA;
        document.getElementById('LabelTurns').innerHTML = NA;
    }
    else
    {
        try
        {
            http.open("GET", "handlergen.ashx?type=25&var1=" + userid + "&rand=" + Math.random(), true);
	        http.onreadystatechange = function()
	        {
		        if (http.readyState == 4)
		        {
		            location = parseInt(http.responseText);
                    if (location == -1)
                    {
                        document.getElementById('LabelGold').innerHTML = NA;
                        document.getElementById('LabelFood').innerHTML = NA;
                        document.getElementById('LabelTurns').innerHTML = NA;
                    }
                    else
                    {
                        var distance;
		                if (Math.floor(ownuserid / 10) == Math.floor(location / 10))
			                distance = 1;
		                else if (Math.floor(ownuserid / 100) == Math.floor(location / 100))
			                distance = 2;
		                else if (Math.floor(ownuserid / 1000) == Math.floor(location / 1000))
			                distance = 3;
		                else if (Math.floor(ownuserid / 10000) == Math.floor(location / 10000))
			                distance = 4;
		                else
			                distance = 5;
                        document.getElementById('LabelGold').innerHTML = gold * (turns * distance + orderconst);
                        document.getElementById('LabelFood').innerHTML = food * (turns * distance + orderconst);
                        document.getElementById('LabelTurns').innerHTML = turns * distance + orderconst;
                    }
                }
	        };
        }
        catch (e)
        {
            document.getElementById('LabelGold').innerHTML = NA;
            document.getElementById('LabelFood').innerHTML = NA;
            document.getElementById('LabelTurns').innerHTML = NA;
        }
        http.send(null);
	}
}

function updateFleetOrderAttackTradeShipsCosts(userid, NA)
{
    if (issizezero == 1)
    {
        document.getElementById('LabelGold').innerHTML = NA;
        document.getElementById('LabelFood').innerHTML = NA;
    }
    else
    {
        document.getElementById('LabelGold').innerHTML = gold * (3 + parseInt(document.getElementById('time')[document.getElementById('time').selectedIndex].value));
        document.getElementById('LabelFood').innerHTML = food * (3 + parseInt(document.getElementById('time')[document.getElementById('time').selectedIndex].value));
    }
}

function updateSpyOperationCost(NA)
{
    var userid = document.getElementById('TextBoxUserID').value;
    var location = -1;
    if (!isNum(userid) || userid == 0)
    {
        document.getElementById('LabelGold').innerHTML = NA;
        document.getElementById('LabelTurns').innerHTML = NA;
    }
    else
    {
        try
        {
            http.open("GET", "handlergen.ashx?type=25&var1=" + userid + "&rand=" + Math.random(), true);
	        http.onreadystatechange = function()
	        {
		        if (http.readyState == 4)
		        {
		            location = parseInt(http.responseText);
                    if (location == -1)
                    {
                        document.getElementById('LabelGold').innerHTML = NA;
                        document.getElementById('LabelTurns').innerHTML = NA;
                    }
                    else
                    {
                        var distance;
		                if (Math.floor(ownuserid / 10) == Math.floor(location / 10))
			                distance = 1;
		                else if (Math.floor(ownuserid / 100) == Math.floor(location / 100))
			                distance = 2;
		                else if (Math.floor(ownuserid / 1000) == Math.floor(location / 1000))
			                distance = 3;
		                else if (Math.floor(ownuserid / 10000) == Math.floor(location / 10000))
			                distance = 4;
		                else
			                distance = 5;
                        document.getElementById('LabelGold').innerHTML = goldperturn * (operationturns + distance * movementturns);
                        document.getElementById('LabelTurns').innerHTML = operationturns + distance * movementturns;
                    }
                }
	        };
        }
        catch (e)
        {
            document.getElementById('LabelGold').innerHTML = NA;
            document.getElementById('LabelTurns').innerHTML = NA;
        }
        http.send(null);
	}
}

function getMinutes()
{
    var mydate = new Date();
    document.getElementById('clientMinutes').value = Math.floor(mydate.getTime() / 60000) - mydate.getTimezoneOffset();
}

function getHeight()
{
    document.getElementById('clientHeight').value = screen.height;
}

function trysigningin(login, fail, success, offvacation, deleted, forced)
{
    document.getElementById('status').innerHTML = login;
    setTimeout('trysigningin2("' + fail + '", "' + success + '", "' + offvacation + '", "' + deleted + '", "' + forced + '");', 500);
}

function trysigningin2(fail, success, offvacation, deleted, forced)
{
    var user = document.getElementById('username').value;
    var pass = document.getElementById('password').value;
    var worldid = document.getElementById('world').options[document.getElementById('world').selectedIndex].value;
    var worldname = document.getElementById('world').options[document.getElementById('world').selectedIndex].text;
    worldname = worldname.substring(0, worldname.indexOf('(') - 1);
    var cmin = document.getElementById('clientMinutes').value;
    var cht = document.getElementById('clientHeight').value;
    var crem;
    if (document.getElementById('checkremember').checked)
        crem = "1";
    else
        crem = "0";
    
    var loginresult = "0";
    http.open("GET", "login.aspx?id=" + Math.random() + "&user=" + user + "&pass=" + pass + "&world=" + worldid + "&cmin=" + cmin + "&wname=" + worldname + "&crem=" + crem + "&cht=" + cht, false);
    http.send(null);
    if (http.readyState == 4)
    {
        if (http.status == 200)
            loginresult = http.responseText;
    }
	if (parseInt(loginresult) == 1)
	{
	    document.getElementById('status').innerHTML = success;
	    setTimeout('location.replace("game.aspx");', 500);
	}
	else if (parseInt(loginresult) == 2)
	{
	    document.getElementById('status').innerHTML = success;
	    setTimeout('location.replace("game.aspx?type=1");', 500);
	}
	else if (parseInt(loginresult) == 3)
	{
	    document.getElementById('status').innerHTML = fail;
	    alert(forced);
	}
	else if (parseInt(loginresult) == 8)
	{
		document.getElementById('status').innerHTML = fail;
	    alert(deleted);
	}
	else if (parseInt(loginresult) == 9)
	{
	    var answer = confirm(offvacation);
	    if (answer)
	    {
	        loginresult = "0";
            http.open("GET", "login.aspx?id=" + Math.random() + "&user=" + user + "&pass=" + pass + "&world=" + worldid + "&cmin=" + cmin + "&wname=" + worldname + "&crem=" + crem + "&cht=" + cht + "&force=true", false);
            http.send(null);
            if (http.readyState == 4)
            {
                if (http.status == 200)
                    loginresult = http.responseText;
            }
            if (loginresult == 1)
	        {
	            document.getElementById('status').innerHTML = success;
	            setTimeout('location.replace("game.aspx");', 500);
	        }
	        else if (loginresult == 2)
	        {
	            document.getElementById('status').innerHTML = success;
	            setTimeout('location.replace("game.aspx?type=1");', 500);
	        }
	    }
	    else
	        document.getElementById('status').innerHTML = fail;
	}
	else
	    document.getElementById('status').innerHTML = fail;
}

function SignInKeyPress(e, login, fail, success, offvacation, deleted, forced)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 13)
    {
        trysigningin(login, fail, success, offvacation, deleted, forced);
        return false;
    }
    else
        return true;
}

function resetColorForField(elementname)
{
    document.getElementById(elementname).style.color = "#ffd700";
}

function setColorForFieldUpdateField(elementname, val, haspercentage)
{
    if (document.getElementById(elementname).innerHTML.length > 0)
    {
		var pre
		if (haspercentage)
		{
			pre = parseInt(document.getElementById(elementname).innerHTML.split('%')[0])
		}
		else
		{
			pre = parseInt(document.getElementById(elementname).innerHTML)
		}
		
        if (pre < parseInt(val))
        {
            document.getElementById(elementname).style.color = "#00ff00";
            setTimeout("resetColorForField('" + elementname + "');" , 5000);
        }
        else if (pre > parseInt(val))
        {
            document.getElementById(elementname).style.color = "#ff0000";
            setTimeout("resetColorForField('" + elementname + "');" , 5000);
        }
        else
            document.getElementById(elementname).style.color = "#ffd700";
    }
    if (haspercentage)
	{
		document.getElementById(elementname).innerHTML = '%' + val;
	}
	else
	{
		document.getElementById(elementname).innerHTML = val;
	}
}

function updateFields(params)
{
    setColorForFieldUpdateField('food', params[0], false);
    setColorForFieldUpdateField('horse', params[1], false);
    setColorForFieldUpdateField('wood', params[2], false);
    setColorForFieldUpdateField('stone', params[3], false);
    setColorForFieldUpdateField('gold', params[4], false);
    setColorForFieldUpdateField('copper', params[5], false);
    setColorForFieldUpdateField('tin', params[6], false);
    setColorForFieldUpdateField('bronze', params[7], false);
    setColorForFieldUpdateField('iron', params[8], false);
    setColorForFieldUpdateField('gunpowder', params[9], false);
    
    setColorForFieldUpdateField('population', params[10], false);
    setColorForFieldUpdateField('morale', params[11], true);
    
    if(params[12]>0)
    {
		document.getElementById('hasnewmessage').style.display = ''
    }
    else
    {
		document.getElementById('hasnewmessage').style.display = 'none'
    }
    if(params[13]>0)
    {
		document.getElementById('hasnewevent').style.display = ''
    }
    else
    {
		document.getElementById('hasnewevent').style.display = 'none'
    }
}

function updateShortInfoContent(user, posx, posy)
{
    if (document.getElementById("lastuser").value == user)
    {
        document.getElementById('shortinfo').style.display="none";
        document.getElementById("lastuser").value = '0';
    }
    else
    {
        document.getElementById("lastuser").value = user;
        http.open("GET", "shortuserinfo.aspx?id=" + user + "&code=" + Math.random(), true);
	    http.onreadystatechange = function()
	    {
		    if (http.readyState == 4)
		    {
		        var params=http.responseText.split(',');
		        document.getElementById("shortinfo1text").innerHTML = text1;
		        document.getElementById("shortinfo2text").innerHTML = text2;
		        document.getElementById("shortinfo3text").innerHTML = text3;
		        document.getElementById("shortinfo4text").innerHTML = text4;
		        document.getElementById("shortinfo5text").innerHTML = text5;
		        document.getElementById("shortinfo6text").innerHTML = text6;
		        document.getElementById("shortinfo7text").innerHTML = text7;
			    document.getElementById("shortinfo1").innerHTML = params[0];
			    document.getElementById("shortinfo2").innerHTML = params[1];
			    document.getElementById("shortinfo3").innerHTML = params[2];
			    document.getElementById("shortinfo4").innerHTML = params[3];
			    if (params[4] == "0")
			        document.getElementById("shortinfo5").innerHTML = text8;
			    else
			        document.getElementById("shortinfo5").innerHTML = text9;
			    if (params[5] == "0")
			        document.getElementById("shortinfo6").innerHTML = text8;
			    else
			        document.getElementById("shortinfo6").innerHTML = text9;
			    if (params[6] == "0")
			        document.getElementById("shortinfo7").innerHTML = text8;
			    else
			        document.getElementById("shortinfo7").innerHTML = text9;
			    document.getElementById('shortinfo').style.display="";
			    document.getElementById('shortinfo').style.left = posx + 17;
			    document.getElementById('shortinfo').style.top = posy + 17;
		    }
	    };
	    http.send(null);
	}
}

function generateShortInfo()
{
	dw('<div id="shortinfo" style="DISPLAY: none; POSITION: absolute"><table cellSpacing="0" cellPadding="0" border="0" style="background-color: #592331; border-right: #461C27 thin solid; border-bottom: #38161F thin solid; border-left: #7A3245 thin solid; border-top: #9C3E56 thin solid; margin: 0px; overflow: hidden; font-family: Verdana; font-size: 8pt; color: #ffffff;"><tr><td id="shortinfo1text" width="130"></td><td id="shortinfo1" width="190"></td></tr><tr><td id="shortinfo2text"></td><td id="shortinfo2"></td></tr><tr><td id="shortinfo3text"></td><td id="shortinfo3"></td></tr><tr><td id="shortinfo4text"></td><td id="shortinfo4"></td></tr><tr><td id="shortinfo5text"></td><td id="shortinfo5"></td></tr><tr><td id="shortinfo6text"></td><td id="shortinfo6"></td></tr><tr><td id="shortinfo7text"></td><td id="shortinfo7"></td></tr></table></div>');
}

function findX(obj)
{
    var curleft = 0;
    if(obj.offsetParent)
    while(1)
    {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}

function findY(obj)
{
    var curtop = 0;
    if(obj.offsetParent)
    while(1)
    {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}

function TextBoxLanguageFinderSwitch(e, labelid, text, lang)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 0 || keynum == 13 || (keynum >= 35 && keynum <= 40) || keynum == 46)
        return true;
    if (keynum == 8)
        deleteAtCursor(document.getElementById('TextBoxUserID'));
    else if (keynum >= 48 && keynum <= 57)
    {
        insertAtCursor(document.getElementById('TextBoxUserID'), String.fromCharCode(keynum));
        TextBoxLanguageFinderClicker(labelid, text, lang);
    }
    return false;
}

function TextBoxLanguageFinderClicker(labelid, text, lang)
{
    labelid.style.cursor = 'hand';
    labelid.style.cursor = 'pointer';
    labelid.style.textDecoration = 'underline';
    labelid.onclick = function()
    {
        var control = labelid;
        try
        {
            http.open("GET", "handlergetlanguage.ashx?id=" + document.getElementById('TextBoxUserID').value + "&lang=" + lang + "&rand=" + Math.random(), true);
	        http.onreadystatechange = function()
	        {
		        if (http.readyState == 4)
		        {
		            control.innerHTML = http.responseText;
		            control.style.cursor = '';
		            control.style.textDecoration = 'none';
	                if (control.addEventListener)
                    {//DOM method for binding an event  - standart browserlar 
    	                window.removeEventListener("click", null, true) ;
                    }
                    else if (control.attachEvent)
                    {//IE exclusive method for binding an event 
                        window.detachEvent("onclick", null);
                    }
                    else if (document.getElementById)
                    {//support older modern browsers 
                        control.click = null;
                    }
                }
	        };
        }
        catch (e)
        {}
        http.send(null);
    }
    labelid.innerHTML = text;
}

function TextBoxLanguageFinder(labelid, lang)
{
    var control = labelid;
    try
    {
        http.open("GET", "handlergetlanguage.ashx?id=" + document.getElementById('TextBoxUserID').value + "&lang=" + lang + "&rand=" + Math.random(), true);
        http.onreadystatechange = function()
        {
	        if (http.readyState == 4)
	        {
	            control.innerHTML = http.responseText;
	            control.style.cursor = '';
	            control.style.textDecoration = 'none';
                if (control.addEventListener)
                {//DOM method for binding an event  - standart browserlar 
	                window.removeEventListener("click", null, true) ;
                }
                else if (control.attachEvent)
                {//IE exclusive method for binding an event 
                    window.detachEvent("onclick", null);
                }
                else if (document.getElementById)
                {//support older modern browsers 
                    control.click = null;
                }
            }
        };
    }
    catch (e)
    {}
    http.send(null);
}

function disbandSelected(maxpenalty, str1, str2)
{
    var i = 0;
    var count = 0;
    while (document.getElementById('a_b' + i + '_c') != null)
    {
        if (document.getElementById('a_b' + i + '_c').checked)
        {
            var curSize = parseInt(document.getElementById('a_b' + i + '_d').innerHTML);
            var soldierID = parseInt(document.getElementById('a_b' + i + '_e').onclick.toString().substring(document.getElementById('a_b' + i + '_e').onclick.toString().indexOf('id=') + 3, document.getElementById('a_b' + i + '_e').onclick.toString().indexOf(');') - 1));
            if (soldierID == 1 || soldierID == 15 || soldierID == 39)
                curSize = Math.ceil(curSize * 0.2);
            count += curSize;
        }
        i++;
    }
	var moralepenalty = Math.ceil(count * maxpenalty / (count + population));
	var answer = confirm(str1 + '' + moralepenalty + '' + str2);
	if (answer)
	{
		document.getElementById('JavaPostBack').value = "1";
		document.Form1.submit();
	}
}

function ChangeColorForPointRange(pos, point, minimumAttackRangeInRankings)
{
    var i = 0;
    var poscol = document.getElementById('a_b' + i + '_r');
    var pointcol = document.getElementById('a_b' + i + '_p');
    while (pointcol != null)
    {
        curpoint = parseInt(pointcol.innerHTML);
        if (curpoint > point * 1.25 || curpoint * 1.25 < point)
        {
            var paint = true;
            if (poscol != null && (parseInt(poscol.innerHTML) <= pos + minimumAttackRangeInRankings && parseInt(poscol.innerHTML) >= pos - minimumAttackRangeInRankings))
            {
                paint = false;
            }
            if (paint)
            {
                var color = document.getElementById('a_b' + i).style.color.toLowerCase();
                if (color == '#00ff00' || color == 'rgb(0, 255, 0)')
                    document.getElementById('a_b' + i).style.color = '#00aa00';
                else if (color == '#00c8ff' || color == 'rgb(0, 200, 255)')
                    document.getElementById('a_b' + i).style.color = '#0099aa';
                else if (color == '#ffff00' || color == 'rgb(255, 255, 0)')
                    document.getElementById('a_b' + i).style.color = '#aaaa00';
                else
                    document.getElementById('a_b' + i).style.color = '#aaaaaa';
            }
        }
        i++;
        pointcol = document.getElementById('a_b' + i + '_p');
        if (poscol != null)
            poscol = document.getElementById('a_b' + i + '_r');
    }
}

function ChangeColorForPointRangeAndRelations(pos, point, rels, minimumAttackRangeInRankings, dontSelectSelf)
{
    var i = 0
    var j;
    var params = rels.split(',');
    var alternating = false;
    var pointcol = document.getElementById('a_b' + i + '_p');
    var poscol = document.getElementById('a_b' + i + '_r');
    var row = document.getElementById('a_b' + i);
    var curpoint;
    while (pointcol != null)
    {
        curpoint = parseInt(pointcol.innerHTML);
        if (curpoint > point * 1.25 || curpoint * 1.25 < point)
        {
            var paint = true;
            if (poscol != null && parseInt(poscol.innerHTML) <= pos + minimumAttackRangeInRankings && parseInt(poscol.innerHTML) >= pos - minimumAttackRangeInRankings)
                paint = false;
            if (paint)
            {
                var color = row.style.color.toLowerCase();
                if (color == '#00ff00' || color == 'rgb(0, 255, 0)')
                    row.style.color = '#00aa00';
                else if (color == '#00c8ff' || color == 'rgb(0, 200, 255)')
                    row.style.color = '#0099aa';
                else if (color == '#ffff00' || color == 'rgb(255, 255, 0)')
                    row.style.color = '#aaaa00';
                else
                    row.style.color = '#aaaaaa';
            }
        }
        var paramcol = document.getElementById('a_b' + i + '_u');
        if (!dontSelectSelf)
        {
			if (params[0] == paramcol.innerHTML)
				row.style.backgroundColor = '#000000';
		}
        for (j = 1; j < params.length; j += 2)
        {
            if (params[j] == paramcol.innerHTML)
            {
                if (row.className == "RoMGridItemStyle")
                    alternating = true;
                else
                    alternating = false;
                if (params[j + 1] == '1')
                {
                    if (alternating)
                        row.style.backgroundColor = '#567256';
                    else
                        row.style.backgroundColor = '#4F6C4F';
                }
                else if (params[j + 1] == '2')
                {
                    if (alternating)
                        row.style.backgroundColor = '#57627C';
                    else
                        row.style.backgroundColor = '#4F5B75';
                }
                else if (params[j + 1] == '4')
                {
                    if (alternating)
                        row.style.backgroundColor = '#7C5457';
                    else
                        row.style.backgroundColor = '#744E50';
                }
                else if (params[j + 1] == '0')
                {
                    if (alternating)
                        row.style.backgroundColor = '#7C7264';
                    else
                        row.style.backgroundColor = '#756B5D';
                }
            }
        }
        i++;
        pointcol = document.getElementById('a_b' + i + '_p');
        if (poscol != null)
            poscol = document.getElementById('a_b' + i + '_r');
        row = document.getElementById('a_b' + i);
    }
}

function ChatGlobalKeyPress(e, sending, sent, notsent)
{
    var keynum;
    if(window.event)
        keynum = e.keyCode;
    else
        keynum = e.which;
    if (keynum == 13)
    {
        document.getElementById("Event").innerHTML = sending;
        http.open("POST", "handlerchat.ashx?send=1&chatid=" + document.getElementById("ChatID").value + "&rnd=" + Math.random(), true);
        http.onreadystatechange = function()
        {
            if (http.readyState == 4)
            {
                if (http.status == 200)
                {
                    if (http.responseText != "0")
                    {
                        document.getElementById("Event").innerHTML = sent;
                        document.getElementById("GlobalMessage").value = "";
                    }
                    else
                    {
                        document.getElementById("Event").innerHTML = notsent;
                    }
                }
                else
                {
                    document.getElementById("Event").innerHTML = notsent;
                }
            }
        };
        http.send(document.getElementById("GlobalMessage").value);
        return false;
    }
    else
        return true;
}

function CheckForChat(error, join, leave)
{
    http.open("GET", "handlerchat.ashx?lastid=" + document.getElementById("LastID").value + "&chatid=" + document.getElementById("ChatID").value + "&rnd=" + Math.random(), true);
    http.onreadystatechange = function()
    {
        if (http.readyState == 4)
        {
            if (http.status == 200)
            {
                if (http.responseText.length > 0)
                {
                    var params = http.responseText.split(';');
                    var resultstring = "";
                    document.getElementById("LastID").value = params[0];
                    var updatelist = "0";
                    var lastuserstring = "";
                    for (var i = 1; i < params.length - 1; i += 2)
                    {
                        if (params[i] == "0")
                        {
                            resultstring += "<font style=\"color: #00ff00; font-weight: bold;\">" + params[i + 1] + "" + join + "</font><br>";
                            updatelist = "1";
                            lastuserstring = params[i + 1];
                        }
                        else if (params[i] == "1")
                        {
                            resultstring += "<font style=\"color: #00ff00; font-weight: bold;\">" + params[i + 1] + "" + leave + "</font><br>";
                            updatelist = "1";
                            lastuserstring = params[i + 1];
                        }
                        else
                        {
                            resultstring += "<font style=\"color: #fafad2; font-weight: bold;\">" + params[i] + ":</font> " + params[i + 1] + "<br>";
                            lastuserstring = params[i];
                            playChatNotificationSound()
                        }
                    }
                    if (resultstring.length > 0)
                    {
                        document.getElementById("GlobalArea").innerHTML = document.getElementById("GlobalArea").innerHTML + resultstring;
                        document.getElementById("ErrorCount").value = 0;
                        document.getElementById("GlobalArea").scrollTop += 400;
                        if (!oldFocusState && lastuserstring.length > 0)
                        {
                            if (document.title.indexOf('|') > 0)
                            {
                                document.title = lastuserstring + document.title.substring(document.title.indexOf('|') - 1, document.title.length);
                            }
                            else
                            {
                                document.title = lastuserstring + " | " + document.title;
                            }
                        }
                    }
                    
                    if (updatelist == "1")
                    {
                        http.open("GET", "handlerchat.ashx?list=1&chatid=" + document.getElementById("ChatID").value + "&rnd=" + Math.random(), true);
                        http.onreadystatechange = function()
                        {
                            if (http.readyState == 4)
                            {
                                if (http.status == 200)
                                {
                                    var params = http.responseText.split(';');
                                    var resultstring = "";
                                    for (var i = 0; i < params.length - 1; i++)
                                        resultstring += "<font style=\"color: #fafad2; font-weight: bold;\">" + params[i] + "</font><br>";
                                    document.getElementById("GlobalUsers").innerHTML = resultstring;
                                }
                            }
                        };
                        http.send(null);
                    }
                }
                else
                    document.getElementById("Event").innerHTML = error;
            }
            else
            {
                if (parseInt(document.getElementById("ErrorCount").value) > 2)
                    location.replace("handlerchat.ashx?chatid=" + document.getElementById("ChatID").value + "&rnd=" + Math.random());
                else
                {
                    document.getElementById("Event").innerHTML = error;
                    document.getElementById("ErrorCount").value = parseInt(document.getElementById("ErrorCount").value) + 1;
                }
            }
        }
    };
    http.send(null);
}

function SwitchChat(kingdomid)
{
    var chatid;
    if (kingdomid)
    {
        chatid = kingdomid;
    }
    else
    {
        var list = document.getElementById('ChatRooms');
        chatid = list.options[list.selectedIndex].value;
    }
    http.open("GET", "handlerchat.ashx?newchatid=" + chatid + "&chatid=" + document.getElementById("ChatID").value + "&rnd=" + Math.random(), true);
    http.onreadystatechange = function()
    {
        if (http.readyState == 4)
        {
            if (http.status == 200)
            {
                if (http.responseText.length > 0)
                {
                    var oldchatid = document.getElementById("ChatID").value;
                    var control;
                    if (chatid[0] == 'k')
                    {
                        control = document.getElementById("SwitchK");
                        control.style.cursor = '';
                        control.style.textDecoration = 'none';
                        if (control.addEventListener)
                        {//DOM method for binding an event  - standart browserlar 
                            control.removeEventListener("click", null, true) ;
                        }
                        else if (control.attachEvent)
                        {//IE exclusive method for binding an event 
                            control.detachEvent("onclick", null);
                        }
                        else if (document.getElementById)
                        {//support older modern browsers 
                            control.click = null;
                        }
                    }
                    
                    if (oldchatid[0] == 'k')
                    {
                        control = document.getElementById("SwitchK");
                        control.style.cursor = 'pointer';
                        control.style.textDecoration = 'underline';
                        if (control.addEventListener)
                        {//DOM method for binding an event  - standart browserlar 
                            control.addEventListener("click", function() { SwitchChat(oldchatid.substring(1, oldchatid.length)); }, false);
                        }
                        else if (control.attachEvent)
                        {//IE exclusive method for binding an event 
                            control.attachEvent("onclick", function() { SwitchChat(oldchatid.substring(1, oldchatid.length)); });
                        }
                        else if (document.getElementById)
                        {//support older modern browsers 
                            control.click = function() { SwitchChat(oldchatid); };
                        }
                    }
                    
                    document.getElementById("LastID").value = http.responseText;
                    document.getElementById("ChatID").value = chatid;
                    document.getElementById("GlobalArea").innerHTML = "";
                    document.getElementById("GlobalUsers").innerHTML = "";
                    document.getElementById("ErrorCount").value = 0;
                }
            }
            else
                document.getElementById("Event").innerHTML = error;
        }
    };
    http.send(null);
}

var ischatwindowfocused = true
function ChatFocus(ownerID)
{
	ischatwindowfocused = true
    switch (ownerID)
    {
        case 1:
            focus1 = true;
            break;
        case 2:
            focus2 = true;
            break;
        case 3:
            focus3 = true;
            break;
        case 4:
            focus4 = true;
            break;
        case 5:
            focus5 = true;
            break;
        case 6:
            focus6 = true;
            break;
        case 7:
            focus7 = true;
            break;
        case 8:
            focus8 = true;
            break;
        case 9:
            focus9 = true;
            break;
    }
}

function ChatBlur(ownerID)
{
	ischatwindowfocused = false
    switch (ownerID)
    {
        case 1:
            focus1 = false;
            break;
        case 2:
            focus2 = false;
            break;
        case 3:
            focus3 = false;
            break;
        case 4:
            focus4 = false;
            break;
        case 5:
            focus5 = false;
            break;
        case 6:
            focus6 = false;
            break;
        case 7:
            focus7 = false;
            break;
        case 8:
            focus8 = false;
            break;
        case 9:
            focus9 = false;
            break;
    }
}

function CheckChatFocus(error, join, leave)
{
    var atLeast1Focus = false;
    if (focus1 || focus2 || focus3 || focus4 || focus5 || focus6 || focus7 || focus8 || focus9)
        atLeast1Focus = true;
    if (atLeast1Focus != oldFocusState)
    {
        oldFocusState = atLeast1Focus;
        clearInterval(interval);
        if (atLeast1Focus)
        {
            interval = window.setInterval("CheckForChat('" + error + "', '" + join + "', '" + leave + "')", 2000);
            if (document.title.indexOf('|') > 0)
            {
                document.title = document.title.substring(document.title.indexOf('|') + 2, document.title.length);
            }
        }
        else
        {
            interval = window.setInterval("CheckForChat('" + error + "', '" + join + "', '" + leave + "')", 20000);
        }
    }
}

function ChangeColorForKingdomEvents()
{
    var i = 0;
    while (document.getElementById('a_b' + i + '_e') != null)
    {
        var id = parseInt(document.getElementById('a_b' + i + '_e').getAttribute('name'));
        if (id == 38)
            document.getElementById('a_b' + i + '_e').style.color = '#ff0000';
        else if (id == 14)
            document.getElementById('a_b' + i + '_e').style.color = '#ffffff';
        else if (id == 6 || id == 7)
            document.getElementById('a_b' + i + '_e').style.color = '#00c8ff';
        else if (id == 10 || id == 11 || id == 12 || id == 13 || id == 15 || id == 16 || id == 18 || id == 19 || id == 26 || id == 27)
            document.getElementById('a_b' + i + '_e').style.color = '#00ff00';
        else
            document.getElementById('a_b' + i + '_e').style.color = '#ffff00';
        i++;
    }
}

function SelectAll(nameFirstPart)
{
    var i = 0;
    while (document.getElementById(nameFirstPart + '' + i + '_c') != null)
    {
        document.getElementById(nameFirstPart + '' + i + '_c').checked = true;
        i++;
    }
}

function GetHandler(controlid, url)
{
    var control = document.getElementById(controlid);
    if(control == null) control = controlid
    try
    {
        http.open("GET", url + "&rand=" + Math.random(), true);
        http.onreadystatechange = function()
        {
	        if (http.readyState == 4)
	        {

				control.innerHTML = http.responseText;
				control.style.cursor = '';
				control.style.textDecoration = 'none';
				if (control.addEventListener)
				{//DOM method for binding an event  - standart browserlar 
					control.removeEventListener("click", null, true) ;
				}
				else if (control.attachEvent)
				{//IE exclusive method for binding an event 
					control.detachEvent("onclick", null);
				}
				else if (document.getElementById)
				{//support older modern browsers 
					control.click = null;
				}
				control.onclick = '';
            
                slideRealmMap()
            }
        };
    }
    catch (e)
    {}
    http.send(null);
}

function slideRealmMap()
{
	// sliding realmmap5.swf since it's position is absolute
	var realmmapdiv = document.getElementById('realmmapdiv')
	if(realmmapdiv != null)
	{
		realmmapdivobject.style.top = '' + findY(document.getElementById('LiteralControlFlash')) + 'px'
	}
}

function GetHandlerWithConfirmation(controlid, url, confirmationText)
{
	if(confirm(confirmationText))
		GetHandler(controlid, url)
}

function GetHandlerFromTableToTarget(control, url, targetid)
{
    if(targetid == 'LabelInfoTable' && url.indexOf('handlergen.ashx?type=12&var1=') != -1){
        // GetHandlerFromTableToTarget(this, 'handlergen.ashx?type=12&var1={0}&var2={1}', 'LabelInfoTable')"
        var params = url.split('&')
        SendDataToFlashMovie(params[1].substr(5))
    }
    try
    {
        http.open("GET", url + "&rand=" + Math.random(), true);
        http.onreadystatechange = function()
        {
	        if (http.readyState == 4)
	        {
				document.getElementById(targetid).innerHTML = http.responseText;
				var row = control.parentNode.parentNode;
				var table = row.parentNode;
				var rows = table.getElementsByTagName("tr");
				for (var i = 0; i < rows.length; i++)
				{
					if (rows[i].name != null)
					{
						rows[i].style.backgroundColor = rows[i].name;
						rows[i].style.fontWeight = '';
						rows[i].style.color = '#FFFFFF';
						rows[i].name = null;
						var cols = rows[i].getElementsByTagName("td");
						for (var j = 0; j < cols.length; j++)
						{
							cols[j].style.fontWeight = '';
						}
					}
				}
				row.name = row.style.backgroundColor;
				row.style.backgroundColor = '#000000';
				row.style.color = '#DAA520'
				row.style.fontWeight = 'bold';
            }
            
        };
    }
    catch (e)
    {}
    http.send(null);
}

function SendTime()
{
    try
    {
        http.open("GET", "handlergencommon.ashx?rand=" + Math.random() + "&type=2&cmin=" + document.getElementById('clientMinutes').value, true);
    }
    catch (e)
    {}
    http.send(null);
}

function AskForTutorial(confirmstring)
{
    var confirmresult = confirm(confirmstring);
    if (confirmresult)
        location.replace("tutorialbegin.aspx");
}

function LeaveTutorial(confirmstring)
{
    var confirmresult = confirm(confirmstring);
    if (confirmresult)
        location.replace("overall.aspx?tutorialleave=1");
}

function getSWF(movieName)
{
    if (navigator.appName.indexOf("Microsoft") != -1)
    {
        return window[movieName];
    }
    else
    {
        if (document[movieName] == null)
            return null
        else if (document[movieName].length != undefined)
            return document[movieName][1];
        else
            return document[movieName];
    }
}

function SendDataToFlashMovie(data)
{
    var swf = getSWF('realmmap')
    if(swf != null)
        swf.sendTextToFlash(data)
}

function updateResources()
{
    parent.frames['resources'].getResources()
}

function addHelpToAttributeTableRow(i, helpText)
{
    var tableRealmAttributesObject = document.getElementById('TableRealmAttributes')
    var row = tableRealmAttributesObject.insertRow(i*2+1)
    row.insertCell(-1)
    row.cells[0].innerHTML = helpText
    row.cells[0].style.color = '#00FF00';
    row.cells[0].colSpan = 3
    row.style.display = 'none';

    var questionCellObject = tableRealmAttributesObject.rows[i*2].cells[0]
    var helpSpan = document.createElement('span');
    questionCellObject.appendChild(helpSpan);
    helpSpan.innerHTML = '[?]';
    helpSpan.style.fontSize = '8pt';
    helpSpan.style.textDecoration = 'underline';
    helpSpan.style.cursor = 'pointer';
    helpSpan.onclick = function()
    {
        if (row.style.display == '')
            row.style.display = 'none';
        else
        {
            if(!GetHelpHandler(row.cells[0], row))
                row.style.display = ''
        }
    }
}

function GetHelpHandler(control, invisibleControl)
{
    if(control.innerHTML.indexOf('handlerhelptext.ashx?type=') != -1)
    {
        try
        {
            http.open("GET", control.innerHTML, true)
            http.onreadystatechange = function()
            {
	            if (http.readyState == 4)
	            {
	                control.innerHTML = http.responseText
	                if (invisibleControl != null) invisibleControl.style.display = ''
                }
            };
        }
        catch (e)
        {return false}
        http.send(null)
        return true
    }
    return false
}

function addHelpToAttributeTableRows()
{
    for(var i=0;i<7;i++) addHelpToAttributeTableRow(i,'handlerhelptext.ashx?type=' + (i+2))
}

function disableControl(id)
{
	var control = document.getElementById(id)
	control.disabled = true
}

function playChatNotificationSound(id)
{
	if (!ischatwindowfocused && document.getElementById('CheckBoxPlayChatNotification').checked)
	{
		// do not put file in a folder otherwise firefox cannot play it
		document.getElementById('dummyspan').innerHTML="<embed src='chat_notification.wav' autostart=true hidden=true loop=false width=0 height=0>"
	}
}


function showInfoBox(e,text)
{
	var box = document.getElementById('infoboxid')
	var textbox = document.getElementById('infoboxtextid')
	var table = document.getElementById('infoboxtableid')
	box.style.display = ''
	
	var posx, posy
	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
	}
	box.style.left = posx + 10
	box.style.top = posy + 10
	
	textbox.innerHTML = text
	
	if (table != null)
	{
		table.style.width = (textbox.offsetWidth + 4) + 'px'
	}
	else
	{
		table.style.width = '150px'
	}
}

function hideInfoBox()
{
	var box = document.getElementById('infoboxid')
	box.style.display = 'none'
}

function showAdvisors()
{
	document.getElementById('labelAdvisors').style.display = 'none'
	document.getElementById('PanelAdvisors').style.display = ''
	
	slideRealmMap()
}

function selectTableColumn(tableid, columnno)
{
	var table = document.getElementById(tableid)
	var hasCheckedElement = false
	for (var i = 1; i < table.rows.length; i++)
	{
		if(table.rows[i].style.display != 'none')
			if(table.rows[i].cells[columnno].childNodes[0].checked)
				hasCheckedElement = true
	}
	if (hasCheckedElement)
	{
		for (var i = 1; i < table.rows.length; i++)
		{
			if(table.rows[i].style.display != 'none')
			{
				
				if(table.rows[i].cells[columnno].childNodes[1]) // if a tristate checkbox
				{
					while(table.rows[i].cells[columnno].childNodes[0].checked == true)
						table.rows[i].cells[columnno].childNodes[1].onclick()
				}
				else // dom checkbox
				{
					table.rows[i].cells[columnno].childNodes[0].checked = false
				}
			}
		}
	}
	else
	{
		for (var i = 1; i < table.rows.length; i++)
		{
			if(table.rows[i].style.display != 'none')
			{
				
				if(table.rows[i].cells[columnno].childNodes[1]) // if a tristate checkbox
				{
					while(table.rows[i].cells[columnno].childNodes[0].checked == false)
						table.rows[i].cells[columnno].childNodes[1].onclick()
				}
				else // dom checkbox
				{
					table.rows[i].cells[columnno].childNodes[0].checked = true
				}
			}
		}
	}
}

function toggleControlVisibility(controlID)
{
	var control = document.getElementById(controlID)
	
	if (control.style.display == '')
		control.style.display = 'none'
	else
		control.style.display = ''
	
}