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;
}


if (!window.Overview) var Overview = new Object();

Overview.Methods = {
	data: {
		refreshDelay: 40,
		timerDelay: 1,
		ajaxreq: 0,
		pull: 'js/overview.ajax.php'
	},
	chat: {
		streaming: true,
		targets: 'chatTargets',
		content: 'chatHollow',
		swappaneid: 'swap3',
		loadedchats: [],
		initchats: [],
		push: 'js/chat.send.php'
	},
	params: {
		initload: 1,
		channel: '/reign',
		loadchannel: '/reign',
		since: 1,
		limit: 20
	},
	_update: function(x) {
		var val = "";
		for (var y in x) {
			if (y == "stats") { this._update_stats(x.stats); }
			else if (y == "updateproduction") { Object.extend(this.charts, x.production || {}); }
			else if (y == "refreshme") { window.location = "overview.php"; }
			else if (y == "chat") { this._populate_chat(x.chat); }
		}
		Object.extend(this.params, x.params || {});
	},
	_refresh: function(options) {
		this._sinceUpdate = 0;
		Object.extend(this.params, options || {});
		this._stop();
		this.ajaxreq = new Ajax.Request(this.data.pull, { method: 'post', parameters: this.params, 
			onSuccess: function(ref) {
					var response = eval('(' + ref.responseText + ')');
					if (response) { this._update(response); }
					this.ajaxreq=null;
				}.bind(this),
			on404: function(ref) {
				this._sinceUpdate = this.data.refreshDelay-4;
			}.bind(this),
			onException: function(aja, exc) {
				var d = false;try { if (aja.status) 1;if (typeof aja.status == "undefined") d=true; } catch(f) { d = true; }
				if (typeof reigndebug != "undefined" && (reigndebug == 1) && !d) alert(exc.toString()+"beep: "+aja.status+" desc:"+exc.description+" msg:"+exc.message+" name:"+exc.name+" num:"+exc.number+" proto:"+exc.prototype);
				this._sinceUpdate = this.data.refreshDelay-4;
			}.bind(this)
		});
		this.params.initload = 0;
	},
	_stop: function() {
		if ((typeof this.ajaxreq!="undefined") && (this.ajaxreq != null) && (this.ajaxreq != 0)) { this.ajaxreq.abort();
			}
	},
	_populate_chat: function(cD) {
		if (cD) {
			var chatdisp = $(this.chat.content);
			if ((typeof cD.initchan!="undefined") && (typeof this.chat.initafter=="undefined")){
				this.chat.loadedchats[this.chat.loadedchats.length] = cD.initchan;
				if ($('pane'+cD.initchan)) {
					$('pane'+cD.initchan).style.display = "block";
				}
				else {
					var createchannel = document.createElement('div');
					createchannel.setAttribute('id', 'pane'+cD.initchan);
					createchannel.style.display = "block";
					$(this.chat.swappaneid).appendChild(createchannel);
				}
				c_target_sw(3, cD.initchan, $('tab-'+cD.initchan));
			}
			var initskip = new Array();
			var oldfound = cD.found;
			var cnt = 1;
			var lastpost = "";
			if ((chatdisp.scrollHeight-chatdisp.offsetHeight-chatdisp.scrollTop) < 30) { var scroll = true; } else { var scroll = false; }
			var entry = "";
			while (cD.found > 0) {
				var ard = cD.messages[cnt];
				if ((ard != "") && (ard != null)) {
					var initialize = true;
					for (var i in this.chat.loadedchats) { if (this.chat.loadedchats[i] == ard[11]) { initialize = false; } }
					if (initialize) {
						for (var i in initskip) { if (initskip[i] == ard[11]) { initialize = false; } }
						if (initialize) { initskip[initskip.length] = ard[11];this.chat.initafter = true;this.chat.initchats[this.chat.initchats.length] = ard[11];cD.found--;cnt++;continue; }
					}

					if (!document.getElementById('pane'+ard[11])) {
						var createchannel = document.createElement('div');
						createchannel.setAttribute('id', 'pane'+ard[11]);
						if (this.params.channel == ard[11]) { createchannel.style.display = "block"; }
						else { createchannel.style.display = "none"; }
						$(this.chat.swappaneid).appendChild(createchannel);
					}
					var c_win = 'pane'+ard[11];
					var c_winEl = $(c_win);
					if (avatars == 1) { var avatar = '<img src="'+ard[1]+'" style="width:50px;height:50px;"/>'; }
					else { var avatar = ''; }
					if (typeof user != 'undefined' && typeof user.type != 'undefined' && user.type != 'u') avatar = '<a href="#ez-ban" style="font-size: 9px; font-family: Verdana;" onclick="changeEZB(' + ard[2] + ');">[M]</a>&nbsp;' + avatar;
					if (lastpost != ard[2]+ard[9]) {
						lastpost = ard[2]+ard[9];
						if (ard[0] == "a") { entry = avatar+'<span class="chatTxtAct"><nobr>'+ard[12]+'&nbsp;<a href="profile.php?whois='+ard[2]+'" onclick="window.open(this.href,\'Profile\',\'left=100,top=100,width=700,height=600,toolbar=0,resizable=1,location=0,status=0,menubar=0,scrollbars=1;\');return false;" onfocus="this.blur()" class="chatTxtAct" title="'+ard[4]+' '+ard[7]+' @ '+ard[6]+'">'+ard[5]+'</a>&nbsp;</nobr></span>&nbsp;<span class="chatTxtAct chatMsg" style="padding-left:0;">'+ard[9]+'</span></div>'; }
						else { entry = avatar+'<span class="'+ard[3]+'"><nobr>'+ard[12]+' '+ard[10]+'&nbsp;<a href="profile.php?whois='+ard[2]+'" onclick="window.open(this.href,\'Profile\',\'left=100,top=100,width=700,height=600,toolbar=0,resizable=1,location=0,status=0,menubar=0,scrollbars=1;\');return false;" onfocus="this.blur()" class="'+ard[3]+'" title="'+ard[4]+' '+ard[7]+' @ '+ard[6]+'">'+ard[5]+'</a>&nbsp;'+ard[8]+':&nbsp;</nobr></span>&nbsp;<span class="chatTxt chatMsg">'+ard[9]+'</span></div>'; }
						new Insertion.Bottom(c_winEl, '<div class="chatEnt">'+entry);
						if (c_winEl.childNodes.length > 75) { c_winEl.removeChild(c_winEl.childNodes[0]); }
					}
					if (scroll && (this.params.channel == ard[11])) chatdisp.scrollTop = 9999999;
					if ((this.params.channel != ard[11]) && ($('tab-'+ard[11]).className.search('tabupdate') == -1)) $('tab-'+ard[11]).className += " tabupdate";
				}
				cnt++;
				cD.found--;
			}
			if ((cD.system != "") && (cD.system != null)) { new Insertion.Bottom($('pane'+this.params.channel), "<div style=\"width:22px;height:1px;overflow:none;float:left;\">&nbsp;</div><font style=\"color:#ff2888\">"+cD.system+"</font><br/>");if (scroll) chatdisp.scrollTop = 9999999; }
			if ((cD.error != "") && (cD.error != null)) { new Insertion.Bottom($('pane'+this.params.channel), "<div style=\"width:22px;height:1px;overflow:none;float:left;\">&nbsp;</div><font style=\"color:#ff2828\">Error: "+cD.error+"</font><br/>");chatdisp.scrollTop = 9999999; }
			if ((cD.since != "") && (cD.since != null)) { this.params.since = cD.since; }
			if (cD.fullstop == true) { this._sinceUpdate = 99; }
		}
		if (this.chat.initchats.length > 0) {
			var h = 0;
			var inittarget = 0;
			for (var iA in this.chat.initchats) {
				var j = 0;
				for (var k in this.chat.loadedchats) { if (this.chat.initchats[iA] == this.chat.loadedchats[k]) { j++;break; } }
				if (j == 0) { h++;inittarget = this.chat.initchats[iA];break; }
			}
			if (h == 0) { this.chat.initchats.length = 0;this.chat.initchats = new Array(); }
			else { this.params.initload = 1;this.params.loadchannel = inittarget;this.chat.loadedchats[this.chat.loadedchats.length] = inittarget; }
		}
		this._sinceUpdate = this.data.refreshDelay;
	},
	add_message: function() {
		var amnsg = $('msgtos').value;
		amnsg = escape(amnsg.replace("+", "%2B"));
		$('msgtos').value = "";
		this._stop();
		abc = new Ajax.Request(this.chat.push, {parameters: {channel: this.params.channel, message: amnsg},
			onSuccess: function(ref) {
				var response = eval('(' + ref.responseText + ')');
				if (response) { this._update(response); }
			}.bind(this)
			//onException: function(aja, exc) {
			//	if (reigndebug == 1) alert(exc.toString()+" desc:"+exc.description+" msg:"+exc.message+" name:"+exc.name+" num:"+exc.number+" proto:"+exc.prototype);
			//}.bind(this)
		});
		this._sinceUpdate = this.data.refreshDelay;
	},
	_update_stats: function(x) {
		for (var y in x) {
			if (y.substr(0,3) == "ov_") {
				if ($(y)) {
					if (y == 'ov_money') val = addCommas(x[y]);
					else val = x[y];
					$(y).innerHTML = val;
				}
			}
			else if (y == "objects") {
				for (var z in x[y]) {
					if ($("obj-id"+z)) {
						$("obj-id"+z).innerHTML = x[y][z]['idle'];
					}
					else if ((x[y][z]['type'] == 'Str') && ($('structures'))) { new Insertion.Bottom($('structures'), '<tr><td class="ti"><a href="javascript:void(0);" onclick="deconstruct(\''+z+'\');"style="color:#4c4c4c;">'+x[y][z]['name']+'</td><td id="obj-id'+z+'">'+x[y][z]['idle']+'</td></tr></table></div>'); }
				}
			}
		}
	},
	charts: function() { // Refactor so that this is in the format x.unit.build and x.str.build....half the lines and maintainability
		var x = this.data.charts;
		var y = 0;
		if ($('unitname') && (typeof x.unit!="undefined")) {
			y=y+1;
			if ($('unitbar').style.display == 'none') $('unitbar').style.display = 'block';
			x.unit.build = x.unit.build+this.data.timerDelay;
			var unittimeval = (x.unit.total-x.unit.build)/60;
			if (unittimeval < 1) unittimeval = "&lt;1min";
			else unittimeval = Math.ceil(unittimeval)+"mins";
			$('unitname').innerHTML = x.unit.name;
			$('unitprogress').style.width = Math.min((Math.ceil(x.unit.build/x.unit.total*10000)/100),100)+"%";
			$('unittime').innerHTML = unittimeval;
			if (x.unit.total <= x.unit.build) { $('unittime').innerHTML = "done";this._update({pane: 'production', panetype: 'unit'}, true); }
		}
		if ($('strname') && (typeof x.str!="undefined")) {
			y=y+1;
			if ($('strbar').style.display == 'none') $('strbar').style.display = 'block';
			x.str.build = x.str.build+this.data.timerDelay;
			var strtimeval = (x.str.total-x.str.build)/60;
			if (strtimeval < 1) strtimeval = "&lt;1min";
			else strtimeval = Math.round(strtimeval)+"mins";
			$('strname').innerHTML = x.str.name;
			$('strprogress').style.width = Math.min((Math.ceil(x.str.build/x.str.total*10000)/100),100)+"%";
			$('strtime').innerHTML = strtimeval;
			if (x.str.total <= x.str.build) { $('strtime').innerHTML = "done";this._update({pane: 'production', panetype: 'str'}, true); }
		}
		if ((y > 0) && ($('prodhr').style.display == 'none')) $('prodhr').style.display = 'block';
	},
	_selfTimer: function() {
		if (this.Active) {
			this._sinceUpdate = this._sinceUpdate+this.data.timerDelay;

			if (this._sinceUpdate > this.data.refreshDelay) this._refresh();
			this.charts();
		}

		var closure = this._selfTimer.bind(this);
		_timer = setTimeout( closure, (this.data.timerDelay*1000));
	},
	_init: function(params) {
		this.Active = false;
		this._sinceUpdate = this.data.refreshDelay;
		if (typeof cbar!="undefined") this.data.charts = cbar;
		Object.extend(this.params, params || {});
		if (typeof defaultchannel!="undefined") {
			this.params.channel = defaultchannel;
			this.params.loadchannel = defaultchannel;
		}
		this._selfTimer();
		this.Active = true;
	},
	start: function(params) { if (!this.Active) { this._init(params); } }
};
Object.extend(Overview, Overview.Methods);

function changeEZB(id) {
	var selectBox = $('ez-user');
	var toSelect = selectBox.select('[value="' + id + '"]')[0];
	var selectOpts = selectBox.childElements();
	for (var i = 0, l = selectOpts.length; i<l; ) {
		if (toSelect == selectOpts[i++]) {
			selectBox.selectedIndex = --i;
			break;
		}
	}
}

function c_target_sw(sid, ref, obj) {
	if ($(obj)) {
		Overview.params.channel = ref;
		if (obj.className != 'tabon') {
			alltabs = obj.parentNode.getElementsByTagName('button');
			for (var i=0,j=alltabs.length;i<j;i++) {
				alltabs[i].className = alltabs[i].className.replace("tabon", "");
			}

			obj.className = 'tabon';

			swappage = document.getElementById('swap'+sid);
			allpanes = swappage.getElementsByTagName('div');
			for (var i=0,j=allpanes.length;i<j;i++) {
				if (allpanes[i].id == "pane"+ref) { allpanes[i].style.display = "block"; }
				else if (allpanes[i].id != "") { allpanes[i].style.display = "none"; }
			}
		}
		var initialize = true;
		for (var i in Overview.chat.loadedchats) {
			if (Overview.chat.loadedchats[i] == ref) { initialize = false; }
		}
		if (initialize) { Overview.chat.initchats[Overview.chat.initchats.length] = ref; }
		$('chatHollow').scrollTop = 9999999;
	}
}



function dropdowns() {
if (x = document.getElementsByTagName("div")) {
for (var i=0,j=x.length; i<j; i++) {
	node = x[i];
	if (node.className=="dropdown") {
		node.onmouseover=function() { this.className +=" dropover"; }
		node.onmouseout=function() { this.className=this.className.replace(" dropover", ""); }
	}
}}
}
var allselects = {decwar: ['decwarselected', 'decwarvalue'], newplayer1: ['create_world', 'create_worldid'], newplayer2: ['create_nation','create_nationid']};
function selectOption(list, values) {
	if (allselects[list].length > 0) {
		$(allselects[list][0]).innerHTML = values[0];
		$(allselects[list][1]).innerHTML = values[1];
		$(allselects[list][1]).parentNode.className = $(allselects[list][1]).parentNode.className.replace(" dropover", "");
	}
}

function savePanes() {

	panestring = "aaa=bbb";
	allDrags = $$(".reignpane");
	allDrags.each(function(element) {
		var dragWidth = element.getWidth();
		var dragLoc = element.positionedOffset();
		var zIndexnum = element.getStyle('zIndex');
		var useid = element.id.substring(5);
		if (zIndexnum == null) zIndexnum = minZindex;
		panestring += "&panes["+useid+"][width]="+dragWidth+"&panes["+useid+"][hide]="+(element.visible() ? '0' : '1')+"&panes["+useid+"][zIndex]="+zIndexnum;
		panestring += "&panes["+useid+"][posY]="+dragLoc.top+"&panes["+useid+"][posX]="+dragLoc.left;
	});
	Overview._refresh({savepanes: panestring});
}

function init() {
	if (arguments.callee.done) return;arguments.callee.done = true;
	if (_timer) clearInterval(_timer);

	if (typeof dropdowns=="function") dropdowns();
	if (typeof chatload=="function") chatload();
	if ((typeof Overview.start=="function") && (typeof turnonoverview!="undefined")) Overview.start();
	Event.observe(window, 'onunload', Overview._stop);
	window.onbeforeunload = function(e) { Overview._stop(); }
	if (typeof turnonoverview!="undefined") {
		allResizers = $$(".dragSE");
		allResizers.each(function(element) {
			element.observe('mousedown', pane_BeginDrag);
		});
		allDrags = $$(".reignpane");
		allDrags.each(function(element) {
			// create all the draggables...also need to look at the one for creating a draggable of the build pane in openOrder
			element.select(".panehandle")[0].observe('mousedown', findParentToFront);
			element.observe('mousedown', findParentToFront);
			var test = new Draggable($(element.id), {handle: 'panehandle',starteffect: false,endeffect: false,onStart: paneToFront, zindex:false, snap: [5,5]});
		});
	}
};
function findParentToFront(event) {
	var k = 0,l = event.element();
	while (1) {
		if (l.id.substring(0,5) == "pane_") { paneToFront({element: l});break; }
		if (k > 50) break;
		l = l.parentNode;
		k++;
	}
}
var startDragLoc, pane_Dragging = false, pane_ResizePane, pane_ResizePaneDimensions, paneDragFrom, minZindex = 400, maxZindex = 999;
var topZindex = minZindex+1;
var allZindex = [];
function paneToFront(dragToFront) {
	var pageDrags = Draggables.drags;
	if (allZindex.length == 0) var firstRun = true;
	else var firstRun = false;
	for (var i=0,f=pageDrags.length;i<f;i++) {
		if (pageDrags[i].element.id.substring(0,5) == "pane_") { // we have a pane
			if (dragToFront.element.id == pageDrags[i].element.id) {
				if (firstRun) { var setZindex = topZindex; }
				else { var setZindex = minZindex+allZindex.length;allZindex = allZindex.without(dragToFront.element.id);allZindex.push(dragToFront.element.id); }

				pageDrags[i].element.setStyle({zIndex: setZindex});
				pageDrags[i].element.firstDescendant().setStyle({opacity: 1});
			}
			else {
				if (firstRun) { allZindex.push(pageDrags[i].element.id);var setZindex = minZindex; }
				else {
					var setZindex = 0;
					for(var j=0,m=allZindex.length;j<m;j++) { if (allZindex[j] == pageDrags[i].element.id) { setZindex = minZindex+j;break; } }
				}

				pageDrags[i].element.setStyle({zIndex: setZindex});
				pageDrags[i].element.firstDescendant().setStyle({opacity: 0.6});
			}
		}
	}
	if (firstRun) { allZindex.push(dragToFront.element.id); }
}
function paneClose(useid) {
	$(useid).hide();
}
function paneOpen(useid) {
	$(useid).show();
	paneToFront({element: $(useid)});
}
function pane_BeginDrag(event) {
	startDragLoc = event.pointer();
	paneDragFrom = Event.element(event);
	pane_ResizePane = paneDragFrom.parentNode.parentNode; // .childElements().last()
	paneDragFrom.stopObserving('mousedown', pane_BeginDrag);
	document.observe("mousemove", pane_MoveDrag).observe("mouseup", pane_EndDrag);
}
function pane_MoveDrag(event) {
	if (!pane_Dragging) {
		pane_Dragging = true;
		pane_ResizePaneDimensions = {width: pane_ResizePane.getWidth()};
	}
	var currentDragLoc = event.pointer();
	if (currentDragLoc.x != startDragLoc.x) {
		var newWidth = pane_ResizePaneDimensions.width+(currentDragLoc.x-startDragLoc.x);
		if (newWidth < 180) newWidth = 180;
		pane_ResizePane.setStyle({width: newWidth});
	}
}
function pane_EndDrag(event) {
	pane_Dragging = false;
	paneDragFrom.observe('mousedown', pane_BeginDrag);
	document.stopObserving("mousemove", pane_MoveDrag).stopObserving("mouseup", pane_EndDrag);
}

if (document.addEventListener) { document.addEventListener("DOMContentLoaded", init, false); }
if (/WebKit/i.test(navigator.userAgent)) { var _timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) { init(); } }, 20); }

/*@cc_on @*/
/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() { if (this.readyState == "complete") { init(); } };
/*@end @*/

window.onload = init; /* fail-safe */
var AJAXhold = false;
var updateTarget = "";


function createplayer_w() {
	if (!AJAXhold) {
		AJAXhold = true;
		new Ajax.Request('js/register.php', { method: 'post', parameters: {createplayer_world: 'true',worldid: $('create_worldid').value,nationid: $('create_area2').innerHTML}, 
			onSuccess: function(ref) {
					AJAXhold = false;
					var response = eval('(' + ref.responseText + ')');
					if (response) {
						if (response.success) {
							$('create_area').innerHTML = response.successmsg;
							//window.location = 'overview.php?pid='+response.success;
							window.setTimeout('window.location = "overview.php?pid='+response.success+'"', 8000);
						}
						else {
							$('create_error').innerHTML = ref.error
							alert(ref.error);
						}
					}
		}});
	}
}
function createplayer_n() {
	if (!AJAXhold) {
		AJAXhold = true;
		new Ajax.Request('js/register.php', { method: 'post', parameters: {createplayer_nation: 'true',nationid: $('create_nationid').value},
			onSuccess: function(ref) {
					AJAXhold = false;
					var response = eval('(' + ref.responseText + ')');
					if (response) {
						if (response.success) {
							//window.location = 'overview.php?pid='+response.success;
							//$('create_error').innerHTML = "under development - new round @ 10PM";
							$('create_area2').style.display = 'none';
							$('create_area2').innerHTML = $('create_nationid').value;
							$('create_area').innerHTML = response.success;
						}
						else if (response.error) {
							$('create_error').innerHTML = response.error;
						}
					}
		}});
		
	}
}


function register() {
	var signups = ['signup_account', 'signup_email', 'signup_general', 'signup_adconversion'];
	if ($('signup_agree').checked == 0) { alert('You must agree to the Service Policy to continue.'); }
	else if (!AJAXhold) {
		AJAXhold = true;
		if ($(signups[3])) var signup_adconversion = $(signups[3]).value;else var signup_adconversion = '';
		new Ajax.Request('js/register.php', { method: 'post', parameters: {signup: 'true',signup_account: $(signups[0]).value,signup_email: $(signups[1]).value,signup_adconversion: signup_adconversion}, 
			onSuccess: function(ref) {
					AJAXhold = false;
					var response = eval('(' + ref.responseText + ')');
					if (response) {
						if (response.success) { window.location = 'index.php'; }
						else {
							if ($('signup_error1')) $('signup_error1').parentNode.removeChild($('signup_error1'));
							if ($('signup_error2')) $('signup_error2').parentNode.removeChild($('signup_error2')); 
							if (response.erraccount) {
								$(signups[0]).parentNode.innerHTML += "<span style='color:red;' id='signup_error1'><br>"+response.error1+"</span>";
							}
							if (response.erremail) {
								$(signups[1]).parentNode.innerHTML += "<span style='color:red;' id='signup_error2'><br>"+response.error2+"</span>";
							}
							if ((!response.erremail) && (!response.erraccount)) {
								$(signups[2]).innerHTML += "<span style='color:yellow;' id='signup_error1'><br>"+response.error1+"</span>";
							}
						}
					}
		}});
	}
}


function openOrder() {
	if (!$('orderAvail')) {
			Overview._stop();
			new Ajax.Request('books/productionpane.php', { method: 'post', onSuccess: function(ref) {
			if (ref.responseText) { if (!$('orderAvail')) {
				new Insertion.Top($('overview_right'),ref.responseText);
				$('pane_9').setStyle({zIndex: maxZindex});
				var test = new Draggable($('pane_9'), {handle: 'panehandle',starteffect: false,endeffect: false,onStart: paneToFront, zindex:false, snap: [5,5]});
			} }
		}});
	}
	else {
		$('pane_9').show();
		$('pane_9').setStyle({zIndex: maxZindex});
	}
}


function getobjimg(id) { return '<span style="display:inline-block;display:-moz-inline-box;width:20px;height:20px;"><div style="display:block;float:left;width:20px;height:20px;background:url(\'images/objects.gif\') -'+(id*20)+'px 0px;overflow:none;margin:0;">&nbsp;</div></span>'; }


function sellUranium() {
	if (!AJAXhold) {
		var amount = parseInt(prompt("Uranium sells from 600 (10-20 ores) to 900 (100+ ores). Minimum of 10.", "0"));
		if (isNaN(amount)) { return; }
		else if (amount >= 10) {
			Overview._stop();
			new Ajax.Request('js/tasks.php', { method: 'post', parameters: {exchange_uranium: 1, exchange: amount}, onSuccess: function (ref) { AJAXhold = false;var isok = eval('(' + ref.responseText + ')');if (!isok.success) alert("Error selling uranium: "+isok.error); } });
			AJAXhold = true;
		}
	}
}

function orderObjs(objID, orID) {
	if (AJAXhold == false) {
		AJAXhold = true;
		Overview._stop();
		var d = new Ajax.Request("js/order.php", { parameters: {objID: $('oObjects').value,amount: $('oAmount').value},
			onSuccess: function(ref) {
				var response = eval('(' + ref.responseText + ')');
				if (response) {
					var append = "";
					if (response.error != null) { append = response.error; }
					if (response.success != null) {
						append = response.success;
						if ($('ov_freeland') && $('ov_land')) {
							$('ov_freeland').innerHTML = response.new_free_land;
							$('ov_peakland').innerHTML = response.new_land_peak;
						}
					}
					$('orderLoad').innerHTML = append;
					Overview._refresh({pane: 'production'});
				}
				AJAXhold = false;
			}
		});
		if ($('orderLoad')) {
			$('orderLoad').innerHTML = "Ordering . . .  Please wait.";
			$('orderAvail').style.display = 'none';
			$('orderLoad').style.display = 'block';
		}
	}
}

function cancelOrder(ID, remove) {
	if (!AJAXhold) {
		new Effect.Fade(remove, {from:1,to:0.01,duration:2,afterFinish: function(obj) { var x= new Effect.Scale(obj.element, 0, {afterFinish: function(obj2) { obj3 = obj2.element; obj3.parentNode.removeChild(obj3); }}); }});
		new Ajax.Request('/js/tasks.php', { method: 'post', parameters: {cancel_order: 1, orderid: ID}, onSuccess: function (ref) { AJAXhold = false;var isok = eval('(' + ref.responseText + ')');if (!isok.success) alert("Error canceling order: "+isok.error); } });
		AJAXhold = true;
	}
}
function deconstruct(ID, objname) {
	if (!AJAXhold) {
		var amount = parseInt(prompt("How many "+objname+" to deconstruct?", "0"));
		if (isNaN(amount)) { return; }
		else if (amount > 0) {
			Overview._stop();
			new Ajax.Request('js/tasks.php', { method: 'post', parameters: {deconstruct: 1, objectid: ID,amount: amount}, onSuccess: function (ref) { AJAXhold = false;var isok = eval('(' + ref.responseText + ')');if (!isok.success) alert("Error canceling order: "+isok.error); } });
			AJAXhold = true;
		}
	}
}


if (!window.Tooltip) { var Tooltip = new Object(); }

Tooltip.Methods = {
options: {
	default_css: true,
	margin: "0px",
	padding: "5px",
	backgroundColor: "#d6d6fc",
	color: "#000000",
	delta_x: 5,
	delta_y: 5,
	zindex: 1000,
	initiated: false,
	direction: ["bottom","left"],
	html: "[empty]"
},
initiate: function() {
	var createtooltip = document.createElement('div');
	createtooltip.setAttribute('id', 'tooltippane_1383');
	createtooltip.style.display = "none";
	createtooltip.style.position = "absolute";
	createtooltip.style.zIndex = this.options.zindex;
	document.body.appendChild(createtooltip);
	this.tool_tip = $('tooltippane_1383');
},
//element: null,

destroy: function() {
	Event.stopObserving(this.element, "mouseover", this.showTooltip);
	Event.stopObserving(this.element, "mouseout", this.hideTooltip);
},

registerEvents: function(element) {
	Event.observe(element, "mouseout", this.hideTooltip.bindAsEventListener(this));
},

showTooltip: function(element, options){ // event
	if (this.options.initiated == false) { this.initiate();this.options.initiated = true; }
	if (Element.readAttribute(element, "tooltipAdded") == null) this.registerEvents(element);
	if (this.element != $(element)) { this.options = Object.extend(this.options, arguments[1] || {}); $(this.tool_tip).innerHTML = this.options.html;this.element = $(element);Element.writeAttribute(this.element, "tooltipAdded", true); }
	// get Mouse position

	var offsetVals = this.element.cumulativeOffset();
	var mouse_x = offsetVals.left;
	var mouse_y = offsetVals.top;
	
	// decide if wee need to switch sides for the tooltip
	var dimensions = Element.getDimensions(this.tool_tip);
	var element_width = dimensions.width;
	var element_height = dimensions.height;

	if (!((element_width + mouse_x) >= ( this.getWindowWidth() - this.options.delta_x)) != !(this.options.direction[1] == "left")) { // too big for X
		mouse_x = mouse_x - element_width;
		// apply delta to make sure that the mouse is not on the tool-tip
		mouse_x = mouse_x - this.options.delta_x;
	}
	else { mouse_x = mouse_x + this.options.delta_x; }

	if (!((element_height + mouse_y) >= ( this.getWindowHeight() - this.options.delta_y)) != !(this.options.direction[0] == "top")) { // too big for Y
		mouse_y = mouse_y - element_height;
		// apply delta to make sure that the mouse is not on the tool-tip
		mouse_y = mouse_y - this.options.delta_y;
	}
	else { mouse_y = mouse_y + this.options.delta_y; }

	// now set the right styles
	this.setStyles(mouse_x, mouse_y);

	if (typeof this.fadeoutobj != "undefined") if (typeof this.fadeoutobj.cancel == "function") this.fadeoutobj.cancel();
	// finally show the Tooltip
	new Effect.Appear(this.tool_tip, {duration:0});
	//new Element.show(this.tool_tip);
},

setStyles: function(x, y){
	// set the right styles to position the tool tip
	Element.setStyle(this.tool_tip, { position:'absolute',
		top:y + "px",
		left:x + "px",
		zIndex:this.options.zindex
	});

	// apply default theme if wanted
	if (this.options.default_css) {
		Element.setStyle(this.tool_tip, { margin:this.options.margin,
			padding:this.options.padding,
			color:this.options.color,
			backgroundColor:this.options.backgroundColor,
			zIndex:this.options.zindex
		});
	}
},

hideTooltip: function(){
	this.fadeoutobj = new Effect.Fade(this.tool_tip, {fps: 30, duration: 0.5});
	//new Element.hide(this.tool_tip);
},

getWindowHeight: function(){
	var innerHeight;
	if (navigator.appVersion.indexOf('MSIE')>0) { innerHeight = document.body.clientHeight; }
	else { innerHeight = window.innerHeight; }
	return innerHeight;	
},

getWindowWidth: function(){
	var innerWidth;
	if (navigator.appVersion.indexOf('MSIE')>0) { innerWidth = document.body.clientWidth; }
	else { innerWidth = window.innerWidth; }
	return innerWidth;
}

}
Object.extend(Tooltip, Tooltip.Methods);