//
// Globally declared variables
//
var xmlhttp;
var jsonObj = 0;
var actvObj = new Array();
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/=";

//
// Shorthand for document.getElementById
//
function gEBI(obj) {
	return document.getElementById(obj);
}

//
// Verify the readstate of an object, returns TRUE when a page has finished loading or FALSE
//
function checkReadyState() {
	return (document.readyState == 'complete');
}

//
// Generate random numbers
// Javascript doesn't come with this capability built in
//
function rand(l, u) {
	return Math.floor((Math.random() * (u-l+1))+l);
}

//
// Adds commas to integers, useful for number formatting
//
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//
// Controls the countdown timers
//
function countdown(secs, div, format, redirect, restart) {
	if (secs > 0) {
		DisplayStr = format.replace(/%%D%%/g, Math.floor((secs / 86400) % 100000));
		DisplayStr = DisplayStr.replace(/%%H%%/g, Math.floor((secs / 3600) % 24));
		DisplayStr = DisplayStr.replace(/%%M%%/g, Math.floor((secs / 60) % 60));
		DisplayStr = DisplayStr.replace(/%%S%%/g, Math.floor(secs % 60));
		document.getElementById(div).innerHTML = DisplayStr;
		setTimeout("countdown("+(secs - 1)+", '"+div+"', '"+format+"', '"+redirect+"', "+restart+")", 1000);
	} else if (restart != 'undefined' && restart != undefined) {
		DisplayStr = format.replace(/%%D%%/g, '0');
		DisplayStr = DisplayStr.replace(/%%H%%/g, '0');
		DisplayStr = DisplayStr.replace(/%%M%%/g, '0');
		DisplayStr = DisplayStr.replace(/%%S%%/g, '0');
		document.getElementById(div).innerHTML = DisplayStr;
		setTimeout("countdown("+restart+", '"+div+"', '"+format+"', '"+redirect+"', "+restart+")", 1000);
	} else {
		DisplayStr = format.replace(/%%D%%/g, '0');
		DisplayStr = DisplayStr.replace(/%%H%%/g, '0');
		DisplayStr = DisplayStr.replace(/%%M%%/g, '0');
		DisplayStr = DisplayStr.replace(/%%S%%/g, '0');
		document.getElementById(div).innerHTML = DisplayStr;

		if (redirect != 'undefined' && redirect != undefined) {
			window.location = redirect;
		}
	}
}

//
// Creates a new AJAX request element
//
function GetXmlHttpObject() {
	var xmlhttp = null;

	if(window.XMLHttpRequest){
		xmlhttp = new XMLHttpRequest();
		if(xmlhttp.overrideMimeType){
			xmlhttp.overrideMimeType('text/xml');
		}
	} else if(window.ActiveXObject){
		try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e){
			}
		}
	}

	if(!xmlhttp) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

	return xmlhttp;
}

//
// Controls the automatic updating of user statistics
//
function update_info() {

	// Send the JSON request to update the users stats
	actvObj[jsonObj] = new JSONscriptRequest('/js/update.php?obj='+jsonObj);
	actvObj[jsonObj].buildScriptTag();
	actvObj[jsonObj].addScriptTag();
	jsonObj += 1;
}

//
// Control the quick switching of the armory pages
// Prevents us from having to reload the page
//
function quick_switch_armory(disp) {
	gEBI('div_armory2').style.display = 'none';
	gEBI('div_armory3').style.display = 'none';
	gEBI('div_armory4').style.display = 'none';
	gEBI('div_armory'+disp).style.display = 'block';
	
	gEBI('img_armory2').setAttribute('src', '/images/armory/armory-02-0.gif');
	gEBI('img_armory3').setAttribute('src', '/images/armory/armory-03-0.gif');
	gEBI('img_armory4').setAttribute('src', '/images/armory/armory-04-0.gif');
	gEBI('img_armory'+disp).setAttribute('src', '/images/armory/armory-0'+disp+'-1.gif');

	gEBI('disp').value = disp;
	gEBI('results').innerHTML = null;

	for (x = 2; x <= 4; ++x) {
		for (y = 2; y <= 5; ++y) {
			try { gEBI('input_armory_'+x+'_'+y).value = ''; } catch (e) { }
			try { gEBI('input_armory_'+x+'_'+y).value = ''; } catch (e) { }
			try { gEBI('input_armory_'+x+'_'+y).value = ''; } catch (e) { }
			try { gEBI('input_armory_'+x+'_'+y).value = ''; } catch (e) { }
			try { gEBI('input_armory_'+x+'_'+y).value = ''; } catch (e) { }
		}
	}
}

//
// Toggles the help character displayed in the bottom right corner of selected pages.
// The help character opens the personal assistant popups on demand.
//
function toggle_help(option) {
	
	// Send the JSON request to toggle the help character
	actvObj[jsonObj] = new JSONscriptRequest('/js/help.php?'+option+'=true&obj='+jsonObj);
	actvObj[jsonObj].buildScriptTag();
	actvObj[jsonObj].addScriptTag();
	jsonObj += 1;
}

//
// Controls closing the personal assistant popups
//
function close_notification() {
	gEBI('overlay').style.display = 'none';
	gEBI('personal_assistant').style.display = 'none';
	gEBI('personal_assistant_info').style.display = 'none';
	gEBI('personal_assistant_close').style.display = 'none';
}

//
// Controls minimizing and maximizing the personal assistant popups
//
function personal_assistant_min_max() {
	if (gEBI('personal_assistant').offsetHeight == 325) {
		gEBI('personal_assistant').style.height = '179px';
		gEBI('personal_assistant_info').style.height = '75px';
		gEBI('personal_assistant_close').style.top = '138px';
		gEBI('personal_assistant_min_max').style.top = '138px';

		gEBI('personal_assistant').style.backgroundImage = 'url(/images/guide/guide-02.png)';
		gEBI('personal_assistant_min_max').innerHTML = '<a href="#" onClick="personal_assistant_min_max();"><img src="/images/guide/guide-maximize.png" border="0"></a>';
	} else {
		gEBI('personal_assistant').style.height = '325px';
		gEBI('personal_assistant_info').style.height = '218px';
		gEBI('personal_assistant_close').style.top = '275px';
		gEBI('personal_assistant_min_max').style.top = '275px';

		gEBI('personal_assistant').style.backgroundImage = 'url(/images/guide/guide-01.png)';
		gEBI('personal_assistant_min_max').innerHTML = '<a href="#" onClick="personal_assistant_min_max();"><img src="/images/guide/guide-minimize.png" border="0"></a>';
	}
}

//
// Check ALL for input checkboxes, found in message inbox, outbox, etc.
//
function invertAll(headerfield, checkform, mask) {
	for (var i = 0; i < checkform.length; i++) {
		if (typeof(checkform[i].name) == "undefined" || (typeof(mask) != "undefined" && checkform[i].name.substr(0, mask.length) != mask)) {
			continue;
		}

		if (!checkform[i].disabled) {
			checkform[i].checked = headerfield.checked;
		}
	}
}

//
// Faction selection higlights on registration pages
//
function select_faction(faction) {
	gEBI('faction').value = faction;
	gEBI('faction1').setAttribute('src', '/images/index/facebook-1-0.png');
	gEBI('faction2').setAttribute('src', '/images/index/facebook-2-0.png');
	gEBI('faction3').setAttribute('src', '/images/index/facebook-3-0.png');
	gEBI('faction1').style.border = 'none';
	gEBI('faction2').style.border = 'none';
	gEBI('faction3').style.border = 'none';

	gEBI('faction'+faction).setAttribute('src', '/images/index/facebook-'+faction+'-1.png');
}

//
// Calculate the estimated reward for exploiting
// Shows the low end and the high end of the reward
//
function estimate_exploiting_reward() {
	var l_reward = 0;
	var u_reward = 0;
	try { var turns1 = (gEBI('turns1').value.length) ? parseInt(gEBI('turns1').value) : 0; } catch (e) { var turns1 = 0; }
	try { var turns2 = (gEBI('turns2').value.length) ? parseInt(gEBI('turns2').value) : 0; } catch (e) { var turns2 = 0; }
	try { var turns3 = (gEBI('turns3').value.length) ? parseInt(gEBI('turns3').value) : 0; } catch (e) { var turns3 = 0; }
	try { var turns4 = (gEBI('turns4').value.length) ? parseInt(gEBI('turns4').value) : 0; } catch (e) { var turns4 = 0; }

	try {
		var type = (gEBI('type2').checked) ? 2 : 1;
	} catch (e) {
		var type = 1;
	}

	if (type == 2) {
		l_reward += turns1 * 125;
		l_reward += turns2 * 175;
		l_reward += turns3 * 225;
		l_reward += turns4 * 275;

		u_reward += turns1 * 250;
		u_reward += turns2 * 300;
		u_reward += turns3 * 350;
		u_reward += turns4 * 400;

		if (!l_reward || !u_reward) {
			gEBI('results').innerHTML = '';
		} else {
			gEBI('results').innerHTML = '<span style="color: #FFF">Estimated reward</span> '+addCommas(l_reward)+' <span style="color: #FFF">-</span> '+addCommas(u_reward)+' experience.';
		}
	} else {
		l_reward += turns1 * 8000;
		l_reward += turns2 * 13000;
		l_reward += turns3 * 18000;
		l_reward += turns4 * 24000;
		
		u_reward += turns1 * 10000;
		u_reward += turns2 * 15000;
		u_reward += turns3 * 20000;
		u_reward += turns4 * 27000;

		if (!l_reward || !u_reward) {
			gEBI('results').innerHTML = '';
		} else {
			gEBI('results').innerHTML = '<span style="color: #FFF">Estimated reward</span> $'+addCommas(l_reward)+' <span style="color: #FFF">-</span> $'+addCommas(u_reward);
		}
	}
}

//
// Calculate the estimated reward for recruiting
// Shows the low and high end of the reward
//
function estimate_recruiting_reward() {
	var l_reward = 0;
	var u_reward = 0;
	var turns = 0;

	try { var turns1 = (gEBI('turns1').value.length) ? parseInt(gEBI('turns1').value) : 0; } catch (e) { var turns1 = 0; }
	try { var turns2 = (gEBI('turns2').value.length) ? parseInt(gEBI('turns2').value) : 0; } catch (e) { var turns2 = 0; }
	try { var turns3 = (gEBI('turns3').value.length) ? parseInt(gEBI('turns3').value) : 0; } catch (e) { var turns3 = 0; }
	try { var turns4 = (gEBI('turns4').value.length) ? parseInt(gEBI('turns4').value) : 0; } catch (e) { var turns4 = 0; }

	turns += turns1;
	turns += turns2 * 2;
	turns += turns3 * 3;
	turns += turns4 * 4;
	l_reward = (turns * 1.5);
	u_reward = (turns * 2.5);

	if (!l_reward || !u_reward) {
		gEBI('results').innerHTML = '';
	} else {
		gEBI('results').innerHTML = '<span style="color: #FFF">Estimated recruits</span> '+addCommas(l_reward.toFixed(0))+' <span style="color: #FFF">-</span> '+addCommas(u_reward.toFixed(0));
	}
}

//
// Control opacity modification of an object
//
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}
function changeOpac(opacity, id) {
    var object = gEBI(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}
function shiftOpacity(id, millisec) {
    if (document.getElementById(id).style.opacity == 0) {
        opacity(id, 100, 0, millisec);
    } else {
        opacity(id, 0, 100, millisec);
    }
}

// **************************************************************************************************************************************
// JSON Request library
// **************************************************************************************************************************************
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
	
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
	this.scriptObj = document.createElement("script");

	// Add script object attributes
	this.scriptObj.setAttribute("type", "text/javascript");
	this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
	this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}