// Namespace
Util = {};

/**
 * Disable all elements on a form.
 *
 * Args:
 *   formName - name of the form to disable (string).
 * Returns:
 *   Array of disabled elements (to be used with Util.reEnableForm)
 */
Util.disableForm = function(formName) {
	disabledElems = new Array();

	frmObj = document[formName]
	for(i=0; i<frmObj.length; i++) {
		frmObj.elements[i].disabled = true;
		disabledElems.push(frmObj.elements[i])
	}
	return disabledElems;
}

/**
 * Re-enable elements on a form from a array.
 *
 * Args:
 *   elems - Array of elements to re-enable
 * Returns:
 *   n/a
 */
Util.reEnableForm = function(elems) {
	for(i=0; i<elems.length; i++) {
		frmObj.elements[i].disabled = false;
	}
}

/**
 * Displays an element.
 *
 * Args:
 *   e - Element to show
 * Returns:
 *   n/a
 */
Util.show = function(e) {
	if (typeof(e) == "string") {
		e = document.getElementById(e)
	}
	
	try {
		if ( e.className.match(/hide/) ) {
			e.className = e.className.replace("hide", "")
		}
	} catch (e) {
	}
}

/**
 * Hide an element.
 *
 * Args:
 *   e - Element to hide
 * Returns:
 *   n/a
 */
Util.hide = function(e) {
	if (typeof(e) == "string") {
		e = document.getElementById(e)
	}

	try {
		if ( !e.className.match(/hide/) ) {
			e.className += " hide"
		}
	} catch (e) {
	}
}


/**
 * Go to an anchor.
 *
 * Args:
 *   a - Anchor
 * Returns:
 *   New url.
 */
Util.goAnchor = function(a) {
	var currentHref = window.location.href;
	window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#"+a;
	return window.location.href;
}


//
// Generic function for making AJAX requests. This takes a fully qualified url
// and callback function name as its arguments. The callback function should
// accept a single argument which will consist of the reponse from the server.
// An example of how its used:
//
//   item has following listener
//   onclick="javascript:make_ajax_request('##TP_CGI_URL##?action=AjaxBalance','do_update_balance');"
//
//   function then looks like this
//   function do_update_balance(balance) {
//       document.getElementById("acct_header_balance").innerHTML = balance;
//   }
//


// Due to IE's caching, we have to make the url unique each time, to ensure
// that every request made actually hits the server. We do this by appending an
// extra arg (n) onto the url with a uid and counter appended. The uid will be
// unique each time the complete page is refreshed, and the ajax_counter will
// be unique for each ajax request made without refreshing the page.
Util.ajax_counter = 0;
Util.make_ajax_request = function(url, callback, type) {
	var http_request = false;
	var type         = type || "xml";

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}
	
	if (!http_request) {
		alert('Your browser does not support this functionality.');
		return false;
	}
	url = url + "&n=" + document.ajax_uid + Util.ajax_counter++;
	http_request.open('POST', url, true);
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				switch(type) {
					case 'text':
						callback(http_request.responseText);
						break;
					default:
						callback(http_request.responseXML);
				}
			} else {
				document.errorNotif.add( document.xl.get("BSQ_TXN_AJAX_RESP_ERR") );
			}
		}
	}
	http_request.send(null);
}

/**
 * Retrieves form args from a given form and produces a URL arg string.
 * Args:
 *   frm - Form to use.
 * Returns:
 *   String in the format
 *     arg1=val1&arg2=val2&arg3=val3....
 */
Util.getFormArgs = function(frm) {
	args = new Array();
	//elms = document.forms[frm].elements;
	elms = frm.elements;
	for (e in elms) {
		if(elms[e]) {
			if (!(elms[e].name == "action")) {
				args.push( elms[e].name+"="+escape(elms[e].value) )
			}
		}
	}
	str=args.join("&");
	return str;
}

/**
 * Returns the value of the xml node.
 * Args:
 *   xmlNode  - Parent xml node
 *   name     - Name of the element to retrieve
 * Returns:
 *   String value
 */
Util.xmlValue = function(xmlNode, name, def) {
	if(
		!(
				xmlNode.getElementsByTagName(name)
			&& xmlNode.getElementsByTagName(name)[0]
		)
	) {
		if(def != null) {
			return def
		} else {
			throw name+" doesn't exist in xml doc."
		}
	}

	xn = xmlNode.getElementsByTagName(name)[0]

	var r = ''
	for(j = 0; j < xn.childNodes.length; j++) {
		r += xn.childNodes[j].nodeValue
	}
	return r;
}


/**
 * Parse the response XML in the format:
 *	<xml>
 *		<status>ERR</status>
 *		<errorMsg>ERR_MSG</errorMsg>
 *		 <data>
 *			...
 *		</data>
 *	</xml>
 * Args:
 *   xml - Xml string.
 * Returns:
 *   {status: <value>, msg: <value>, data: <value>}
 */
Util.getXML = function(xml) {
	var status = "ERR";
	errMsg = null;
	try {
		if (xml.getElementsByTagName("status")) {
			status = xml.getElementsByTagName("status")[0].childNodes[0].nodeValue
		}
	} catch(e) {
		errMsg = document.xl.get("BSQ_TXN_AJAX_RESP_ERR");
	}

	errMsg = ""
	switch(status) {
		case 'OK':
		case 'WARN':
		case 'PENDING':
			return {
				status:   status,
				msg:      Util.xmlValue(xml, "errorMsg", ""),
				data:     xml.getElementsByTagName("data")[0]
			}
		default:
			if (!errMsg) errMsg = Util.xmlValue(xml, "errorMsg", "");

			return {
				status:  'ERR',
				msg:     Util.xmlValue(xml, "errorMsg", "")
			}
	}
}


/**
 * Remove an element.
 *
 * Args:
 *   e - Element to remove
 * Returns:
 *   n/a
 */
Util.removeElem = function(id) {
	n = document.getElementById(id);
	n.parentNode.removeChild(n);
}


/**
 * Appned element to node
 *
 * Args:
 *   node - Node to append to
 *   id   - Id of the div you wish to create
 *   html - Html content
 * Returns:
 *   n/a
 */
Util.appendDiv = function(node, id, html) {
	d = document.createElement('div');
	d.setAttribute('id', id);

	d.innerHTML = html;
	node.appendChild(d);
}


/**
 * Replaces an element in a listbox
 *
 * Args:
 *   listbox  - listbox obj
 *   oldValue - value of the node to replace
 *   newValue - new value of the node
 *   newText  - new text of the node
 * Returns:
 *   n/a
 */
Util.replaceOption = function(listbox, oldValue, newValue, newText) {
	if(!listbox || !listbox.options) throw "listbox not defined";

	opts = listbox.options;
	for(i=0; i < opts.length; i++) {
		if (opts[i].value == oldValue) {
			opts[i].text  = newText;
			opts[i].value = newValue;
		}
	}
}


/**
 * Gets a parameter from the URL.
 *
 * Args:
 *   name  - name of the arg
 *   dflt  - default value
 * Returns:
 *   URL argument value
 */
Util.getURLParam = function(name, dflt) {
	name      = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var reStr = "[\\?&]"+name+"=([^&#]*)";
	var re    = new RegExp(reStr);
	var rslt  = re.exec(window.location.href);

	if(!rslt)
		return dflt;
	else
		return rslt[1];
}

