/**
 * @author Frederick J Richart
 * @version $Revision: 1.8 $ $Date: 2010/08/15 17:43:12 $ * 
 * @requires xdom.js
 * 
 * Performs AJAX operations on behalf of the forms used
 * on the Fred's Used Websites functionality.  This is implemented as
 * a class to minimize namespace impact.  
 */
function UserAjaxEngine() { 
	this.Zindex = 0;
	this.Registry = new Array();
	this.TimeoutControl = new Array();
	this.otherOnLoad = window.onload;
	window.onload = this.onPageLoad;
	this.otherOnUnload = window.onunload;
	window.onunload = this.onPageUnload;
}
UserAjaxEngine.prototype = {
	/**
	 * Execute this when page unloads. Note - can't use "this" keyword here because calls are in the window environment
	 */
	onPageUnload : function() {	
		if (UserAjax.otherOnUnload) UserAjax.otherOnUnload();
	},
	/**
	 * Execute this when page loads.  Note - can't use "this" keyword here because calls are in the window environment
	 */
	onPageLoad : function() {
		if (UserAjax.otherOnLoad) UserAjax.otherOnLoad();
		for(var i=0; i<UserAjax.Registry.length; i++) {
			var r = UserAjax.Registry[i];
			if (r.onPageLoad)
				r.onPageLoad();
		}
	},
	/**
	 * Add an to the onLoad Registry
	 */
	addOnLoad : function(object) {
		this.Registry.push(object);
	}
}
UserAjax = new UserAjaxEngine();
/**
 * ServiceTotal object for managing payment vs. service totals on the payment dialog
 */
 function ServiceTotal(num) {
 	this.numServices = num;
 	this.serviceCheckBoxes = new Array();
 	this.serviceAmounts = new Array();
 	UserAjax.addOnLoad(this);
 }
 ServiceTotal.prototype = {
 	onPageLoad : function() {
		var c, a, d;
		c = this.serviceTotal = document.getElementById("serviceTotalAmount");
		if (!c) return;
		xdom_findAssociatedLabel(c, false);
		xdom_setOnsubmitEvent(c, this);
		xdom_setFormsubmitHandler(c);
		c = this.differenceAmount = document.getElementById("differenceAmount");
		if (!c) return;
		this.checkTotal = this.setBlur("paymentTotalAmount");
		c = this.extraCheckBox = this.setClick("extra_service_checked");
		a = this.extraAmount = this.setBlur("extra_service_amt_paid");
		d = document.getElementById("extra_service_description");
		if (!d) return;
		a.checkControl = c;
		c.amountControl = a;
		a.descriptionControl = d;
		for (var i=1; i<=this.numServices; i++) {
			c = this.serviceCheckBoxes[i] = this.setClick("service_id" + i);
			a = this.serviceAmounts[i] = this.setBlur("payment_amt_id" + i);
			a.checkControl = c;
			c.amountControl = a;
		}
		this.recompute();
	},
 	setClick : function(id) {
 		var e = document.getElementById(id);
 		xdom_setOnclickEvent(e, this);
 		return e;
 	},
 	setBlur : function(id) {
 		var e = document.getElementById(id);
 		xdom_setOnblurEvent(e, this);
 		return e;
 	},
 	getAmount : function(e) {
 		if (!e.checkControl) return 0.0;
  		if (e.checkControl.checked) {
  			e.disabled = false;
  			if (e.descriptionControl) e.descriptionControl.disabled = false;
 			var v = parseFloat(e.value);
 			if (isNaN(v)) v = 0.0;
 			return v;
 		}
 		e.disabled = true;
 		if (e.descriptionControl) e.descriptionControl.disabled = true;
 		return 0.00;
 	},
 	recompute : function() {
 		if (!this.serviceTotal || !this.differenceAmount) return 0;
 		var total = 0.00;
 		total += this.getAmount(this.extraAmount);
 		for (var i=1; i<=this.numServices; i++) {
 			total += this.getAmount(this.serviceAmounts[i]);
 		}
 		total = parseFloat(this.serviceTotal.value = total.toFixed(2));
 		var check = parseFloat(this.checkTotal.value);
 		if (isNaN(check)) check = 0.00
 		this.differenceAmount.value = (check - total).toFixed(2);
 		this.checkTotal.value = check.toFixed(2);
 		return (check - total);
 	},
 	onElementBlur : function(e) {
 		this.recompute();
 		return true;
 	},
 	onElementClick : function(e) {
 		this.recompute();
 		return true;
 	},
 	onElementSubmit : function(e) {
 		var d = this.recompute();
 		if (d != 0) {
 			xdom_setElementFailState(e, false, "Service total must match Check Amount!");
 			return false;
 		}
 		return true;
 	}
 }
// Requires cookie.js, xdom.js, aes.js
/**
 * Submits the xlinks form to login to a site Control Panel
 * @param id unique id assigned to this form
 */
function xlinks_submit(id, requestURL) {
	var form = document.getElementById(id);
	form.requestURL = requestURL;
	form.masterkey = user_get_password_key(form);
	if (form.masterkey) return xlinks_submit_master(form);
	return false;
}
function xlinks_submit_master(form) {
	var sitekey = form.key.value;
	if (sitekey) return xlinks_submit_key(form, sitekey);
	return  user_get_site_key(form);
}
function xlinks_submit_key(form, sitekey) {
	form.pass.value = AESDecryptCtr(sitekey, form.masterkey, 256, true)
	form.submit();
}
function user_get_password_key(form, requestURL) {
	// Open cookie and return key if it exists
	var fuwdata = new Cookie(document, "fuwdata", 175200);
	if (fuwdata.load() && fuwdata.key) return fuwdata.key;
	
	// Key doesn't exist.  Need to get password and generate key.
	var controlElement = form;
	controlElement.fuwdata = fuwdata;
	var rawpw = prompt("The master key has not been set for this browser.  Please enter the password that unlocks the site keys", "");
	if (!rawpw) return false;
	// Server class becomes XdomAjaxUserPasswordHashReply
	var xdomAjax = new XdomAjax(controlElement, "UserPasswordHash", form.requestURL);

	// This runs in the context of the XdomAjax class and handles the response
	xdomAjax.controlHandler = function(response) {
		var form = this.controlElement;
		var ok = this.err == "0";
		if (ok && this.errmsg) {
			var masterkey = this.errmsg;
			form.masterkey = masterkey;
			form.fuwdata.key = masterkey;
			form.fuwdata.store();
			// alert("Key set to " + masterkey);
			// Continue the form submission
			xlinks_submit_master(form);
		}
	};
	var action = 'xdomExtension=user';
	var post = 'passwd=' + encodeURIComponent(rawpw);
	xdomAjax.sendRequest(action, post);
	return false; // Completion of link will happen after server response
}
function user_get_site_key(form) {
	var site = form.user.value;
	controlElement = form;
	var rawpw = prompt("The encrypted password for this site is not yet stored.  Please enter the Control Panel password for site account '"+site+"'", "");
	if (!rawpw) return false;
	var sitekey = AESEncryptCtr(rawpw, form.masterkey, 256, true);
	form.key.value = sitekey;
	// Server class becomes XdomAjaxUserSetSiteKeyReply
	var xdomAjax = new XdomAjax(controlElement, "UserSetSiteKey", form.requestURL);
	// This runs in the context of the XdomAjax class and handles the response
	xdomAjax.controlHandler = function(response) {
		var form = this.controlElement;
		var ok = this.err == "0";
		if (ok && this.errmsg) {
			// alert("Key set to " + this.errmsg);
			xlinks_submit_key(form, form.key.value);
		}
	};
	var action = 'xdomExtension=user&site=' + encodeURIComponent(site);
	var post = 'key=' + sitekey;
	xdomAjax.sendRequest(action, post);
	return false;  // Completion of link will happen after server response
}
function server_command_submit(form, requestURL, host, site) {
	var command = form.commandInput.value;
	if (!command) return false;
	// if (host) requestURL = "http://" + host + requestURL;
	var xdomAjax = new XdomAjax(form, "UserExecuteServerCommand", requestURL);
	xdomAjax.controlHandler = function(response) {
		var form = this.controlElement;
		var ok = this.err == "0";
		var s = this.errmsg ? this.errmsg : "(no output)\n";
		if (!ok) s = "Command returned ERROR!\n" + s;
		var div = document.getElementById('commandOutput');
		div.innerHTML += this.errmsg;
		div.scrollTop = div.scrollHeight;
		form.commandInput.value = "";
	};
	var action = 'xdomExtension=user';
	var post = 'cmd=' + encodeURIComponent(command);
	if (host) post += '&relayHost=' + host;
	if (site) post += '&relaySite=' + site;
	xdomAjax.sendRequest(action, post);
	return false;
}
function server_command_keypress(field, e, requestURL, host, site) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	if (keycode == 13) {
		server_command_submit(field.form, requestURL, host, site);
		return false;
	}
	return true;
}
function xlinks_select_user(e, event) {
	var idstr = "selectUser=" + e.value;
	var a, t, s = window.location.search, d = "?", n = "";
	if (s.substr(0,1) == "?") s = s.substr(1);
	a = s.split("&");
	for(var i in a) {
		t = a[i];
		if (t == "") continue;
		if (t.substr(0,11) == "selectUser=") continue;
		n += d + t;
		d = "&";
	}
	n += d + idstr;
	window.location.search = n;
}
