//util.js
//Copyright 2000 - EdSoft, Inc.
//Created 5/17/2000 - SPT

var isIE = (navigator.appName == "Microsoft Internet Explorer")?true:false;

var verticalHTMLImages = false;
var unescFn = unescape;

function encode(str){
	//var ret = escape(str);
	//return ret.replace(/\+/g, "%2B");
	var ret = encodeURIComponent(str);
	return ret;
}

function unencode(str){
	// A simple attempt at making UTF-8 and ISO-8859-1 special characters display correctly
	// This seems to work reliably enough for now.	
	 try {
			str2 = decodeURIComponent(str);
		} catch(e) {
			str2 = unescape(str);
		}
	return str2;
	/*
	var s = str;
	if(s.charAt(0) == '%') {
	  try {
	    s = decodeURIComponent(str.replace(/\+/g,  " "));
	  } catch(e) {
	    s = unescape(str);
	  }
	}
	return s;
	*/
}

/* Commented out because of Flex iframe issues.
 function helpFunction(){
	try{
		if(window.top.frames[2].doHelp){
			window.top.frames[2].doHelp();
			return false;
		}
		else if(window.top.frames[0].execHelp){
			window.top.frames[0].execHelp();	
			return false;
		}
	} catch(e){ }
	return true;
}

window.onhelp = helpFunction;
window.top.onhelp = helpFunction;
window.top.document.onhelp = helpFunction;
for(var i=0; i < window.top.frames.length; i++){
	window.top.frames[i].onhelp = helpFunction;
}
*/
var hideSourceCode = false;
if(hideSourceCode){
	document.onmousedown = _hideTheSource;
}

var doDebug = true;
function stepThrough(message){
	if(doDebug)
		if(!confirm(message + "\n\nContinue alerts?"))
			doDebug = false;
}

function _hideTheSource(evt){
	var el = window.event.srcElement;
	var hasContext = false;
	while(el != null && el.parentNode != null && el.parentNode != el && hasContext == false){
		if(el.oncontextmenu != null)
			hasContext = true;
		else
			el = el.parentNode;
	}
	if (!isIE && (evt.which == 3 || evt.which == 2)){
		alert("Right-click disabled");
		evt.preventBubble();
		return false;
	}
	else if (isIE && (event.button == 2 || event.button == 3)) {
		if(!hasContext){
			if(!(event.ctrlKey && event.altKey)){
				alert("Right-click disabled");
				event.cancelBubble = true;
				event.returnValue = false;
				return false;
			}
		}
	}
	return true;
}

function getCBObject(objID){
	var obj;
	if(document.layers){
		obj = document.layers['' + objID + ''];
	}else if (document.getElementById){
		obj = document.getElementById('' + objID + '');
	}
	else if (document.all){
		obj = document.all['' + objID + ''];
	}
	return obj;
}

function getCBStyleObject(objID){
	var obj;
	var msg = "no object"
		if(document.layers){
			obj = document.layers['' + objID + ''];
			msg = "document.layers[" + objID + "]";
		}
		else if (document.getElementById){
			obj = document.getElementById('' + objID + '').style;
			msg = "document.getElementById(" + objID + ").style";
		}
		else if (document.all){
			obj = document.all['' + objID + ''].style;
			msg = "document.all[" + objID + "].style";
		}
	return obj;
}

function dbg(msg, b){
//	return;	//remove me for debugging!
	var obj = document.getElementById("divDbg");
	
	if(obj == null){
		var bdy = document.getElementsByTagName("BODY");
		var obj = document.createElement("DIV");
		obj.id = "divDbg";
		obj.style.top ="500px";
		obj.style.zIndex = 100;
		
		bdy[0].appendChild(obj);
	}
	var ts = new Date();
	obj.appendChild(document.createTextNode(ts.toString() + " - " + msg));
	obj.appendChild(document.createElement("br"));
}	

function getShortDateString(){
	var tmp = (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
	return tmp;
}

function getCCYYMMDD(){
	var month = this.getMonth() + 1;
	var day = this.getDate();
	var sY = this.getFullYear();
	var sM, sD;
	if(month <10)
		sM = new String("0" + month);
	else
		sM = new String(month);
	
	if(day <10)
		sD = new String("0" + day);
	else
		sD = new String(day);
	
	return sY + sM + sD;
}

function getDaysInMonth(){
	var month = this.getMonth() + 1;
	var year = this.getFullYear();
	var daysInMonth = 0;
	
	if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month ==12)
		daysInMonth = 31;
	else if(month ==2){
		//is this a leap year
		if(year % 400 == 0)
			daysInMonth = 29;
		else if((year % 4 == 0) && (year % 100 != 0))
			daysInMonth = 29;
		else
			daysInMonth = 28;
	}
	else
		daysInMonth = 30;
		
	return daysInMonth;
}

Date.prototype.getShortDateString = getShortDateString;
Date.prototype.getCCYYMMDD = getCCYYMMDD;
Date.prototype.getDaysInMonth = getDaysInMonth;

// NOTE: please take a look at replaceCharsForXml() for possibility
// of replacement for this fixXML function.

function fixXML(xml2, noJavaScript){	
	var regExp;
	var xml = new String(xml2);
	
	regExp = /\\/g;
	xml = xml.replace(regExp, "/");
	
	if(noJavaScript != true){
		regExp = new RegExp("\r", "g");
		xml = xml.replace(regExp, "\\r");

		regExp = new RegExp("\n", "g");
		xml = xml.replace(regExp, "\\n");
	}	
	
	regExp = new RegExp("&", "g");
	xml = xml.replace(regExp, "&amp;");
	
	regExp = new RegExp("<", "g");
	xml = xml.replace(regExp, "&lt;");
	
	regExp = new RegExp(">", "g");
	xml = xml.replace(regExp, "&gt;");
	
	regExp = new RegExp("\"", "g");
	xml = xml.replace(regExp, "&quot;");
	
	return xml;
}

// This is a copy of fixXML(), but modified to correctly handle \r (Mac), 
// \r\n (Windows), and \n (Unix). All caller of fixXML should be able
// to use this function instead. Basically, this function replaces
// all variation of the new line with the \\n.

function replaceCharsForXml(xml2, noJavaScript){    
    var regExp;
    var xml = new String(xml2);
    
    regExp = /\\/g;
    xml = xml.replace(regExp, "/");
    
    if(noJavaScript != true){
        regExp = new RegExp("\r\n", "g");
        xml = xml.replace(regExp, "\\n");
        
        regExp = new RegExp("\r", "g");
        xml = xml.replace(regExp, "\\n");

        regExp = new RegExp("\n", "g");
        xml = xml.replace(regExp, "\\n");
    }   
    
    regExp = new RegExp("&", "g");
    xml = xml.replace(regExp, "&amp;");
    
    regExp = new RegExp("<", "g");
    xml = xml.replace(regExp, "&lt;");
    
    regExp = new RegExp(">", "g");
    xml = xml.replace(regExp, "&gt;");
    
    regExp = new RegExp("\"", "g");
    xml = xml.replace(regExp, "&quot;");
    
    return xml;
}

function debugOutput(str){
//	return;
	var dbgWin = window.open("", "debugWin");
	//var el = document.createTextNode(str);
	//dbgWin.document.body.appendChild(el);

	var regExp = new RegExp(">", "g");
	dbgWin.document.body.innerText = str.replace(regExp, ">\n");
	return dbgWin;
}

function debugOutput2(strArray){
//	return;
	var dbgWin = window.open("", "debugWin");
	for(var i=0; i<strArray.length; i++){
		var div = dbgWin.document.createElement("DIV");
		div.style.pageBreakAfter = "always";
		
		var regExp = new RegExp(">", "g");
		div.innerText = strArray[i].replace(regExp, ">\n");
		dbgWin.document.body.appendChild(div);
	}
}

function debugLogMessage(debugWindow, message){
	var now = new Date();
	debugWindow.document.body.appendChild(debugWindow.document.createTextNode(now.toString() + " " + message));
	debugWindow.document.body.appendChild(debugWindow.document.createElement("BR"));
}

function debugArray(theArray){
	var dbgWin = window.open("", "debugArrayWin");
	var div = dbgWin.document.createElement("DIV");
	var theTable = dbgWin.document.createElement("TABLE");
	var now = new Date();
	div.appendChild(dbgWin.document.createTextNode(now.toString()));
	div.appendChild(dbgWin.document.createElement("BR"));
	theTable.width="100%";
	theTable.border = 1;
	theTable.cellSpacing = 1;
	theTable.cellPadding = 1;
	
	div.appendChild(theTable);
	for(var i=0; i<theArray.length; i++){
		var theRow = theTable.insertRow(theTable.rows.length);
		for(var j=0; j<theArray[i].length; j++){
		
			theCell = theRow.insertCell(theRow.cells.length);
			theCell.appendChild(dbgWin.document.createTextNode(theArray[i][j]));
		}
	}
	div.appendChild(dbgWin.document.createElement("BR"));
	div.appendChild(dbgWin.document.createElement("BR"));
	
	dbgWin.document.body.appendChild(div);
	dbgWin.focus();
	return dbgWin;
}

function CBEvent(){
	if(isIE){
		this.ABORT = "onabort";
		this.BLUR = "onblur";
		this.CHANGE = "onchange";
		this.CLICK = "onclick";
		this.DBLCLICK = "ondblclick";
		this.DRAGDROP = "ondragdrop";
		this.ERROR = "onerror";
		this.FOCUS = "onfocus";
		this.KEYDOWN = "onkeydown";
		this.KEYPRESS = "onkeypress";
		this.KEYUP = "onkeyup";
		this.LOAD = "onload";
		this.MOUSEDOWN = "onmousedown";
		this.MOUSEMOVE = "onmousemove";
		this.MOUSEOUT = "onmouseout";
		this.MOUSEOVER ="onmouseover";
		this.MOUSEUP = "onmouseup";
		this.MOVE = "onmove";
		this.RESET = "onreset";
		this.RESIZE = "onresize";
		this.SELECT = "onselect";
		this.SUBMIT = "onsubmit";
		this.UNLOAD = "onunload";
	}
	else {
		this.ABORT = Event.ABORT;
		this.BLUR = Event.BLUR;
		this.CHANGE = Event.CHANGE;
		this.CLICK = Event.CLICK;
		this.DBLCLICK = Event.DBLCLICK;
		this.DRAGDROP = Event.DRAGDROP;
		this.ERROR = Event.ERROR;
		this.FOCUS = Event.FOCUS;
		this.KEYDOWN = Event.KEYDOWN;
		this.KEYPRESS = Event.KEYPRESS;
		this.KEYUP = Event.KEYUP;
		this.LOAD = Event.LOAD;
		this.MOUSEDOWN = Event.MOUSEDOWN;
		this.MOUSEMOVE = Event.MOUSEMOVE;
		this.MOUSEOUT = Event.MOUSEOUT;
		this.MOUSEOVER = Event.MOUSEOVER;
		this.MOUSEUP = Event.MOUSEUP;
		this.MOVE = Event.MOVE;
		this.RESET = Event.RESET;
		this.RESIZE = Event.RESIZE;
		this.SELECT = Event.SELECT;
		this.SUBMIT = Event.SUBMIT;
		this.UNLOAD = Event.UNLOAD;
	}
}

var EdSoftEvent = new CBEvent();


function Cookie(){
	this.crumbs = new Array();
	this.addCrumb = addCrumb;
	this.removeCrumb = removeCrumb;
	this.getCrumb = getCrumb;
	
	this.expires = new Date();
	this.path = document.URL;
	
	this.save = saveCookie;
	this.reload = reloadCookie;
	this.reload();
}

function Crumb(key, value){
	this.key = key;
	this.value = value;
}

function getCrumb(key){
	for(var i=0; i<this.crumbs.length; i++){
		if(this.crumbs[i].key == key){
			return this.crumbs[i];
		}
	}
	return null;
}

function addCrumb(key, value){
	vartheCrumb = getCrumb(key);
	if(theCrumb == null)
		theCrumb = this.crumbs[this.crumbs.length] = new Crumb(key, value);
	else
		theCrumb.value = value;
}

function removeCrumb(key){
	var prevArray = this.crumbs;
	this.crumbs = new Array();
	for (var i=0; i<prevArray.length; i++){
		if(prevArray[i].key == key){
			//do nothing
		}
		else{
			this.crumbs[this.crumbs.length] = prevArray[i];
		}
	}
}

function saveCookie(){
	var str = "";
	for(var i=0; i<this.crumbs.length; i++)
		str+=this.crumbs[i].key + "=" + escape(this.crumbs[i].value) + ";";

	str+= ((this.expires) ? "expires=" + expires.toGMTString()  + ";" : "") + 
				 ((this.path) ? "path=" + this.path + ";" : "");

	document.cookie = str;
}
   
function reloadCookie(){
	var _c = unescape(document.cookie);
	var _crumbs = _c.split(";");
	for(var i=0; i<_crumbs.length; i++){
		if(_crumbs[i] != null && _crumbs[i] != "" && _crumbs[i] != ";"){
			var tokens = _crumbs[i].split("=");
			if(tokens.length == 2){
				if(tokens[0] == "expires")
					this.expires = new Date(tokens[1]);
				else if(tokens[0] == "path")
					this.path = tokens[1];
				else{
					var cr = this.getCrumb(tokens[0]);
					if(cr != null)
						cr.value = tokens[1];
					else
						this.addCrumb(tokens[0], tokens[1]);
				}
			}
		}
	}
}

function deleteOne(item){
	/*
	if(this.length < index)
		return;
	var newAr = new Array();

	if(this.length == index)
		for(i=0; i<this.length-1; i++)
			newAr[i] = this[i];
	else
		for(i=0; i<this.length-1; i++){
			if(i >=index)
				newAr[i] = this[i+1];
			else
				newAr[i] = this[i];
		}
	return newAr;
	*/
	var index;

	if(isNaN(item))
		index = this.getIndex(item);
	else
		index = item;
	if(index < 0)
		return this;
	var newAr = new Array();

	if(this.length == index)
		for(i=0; i<this.length-1; i++)
			newAr[i] = this[i];
	else
		for(i=0; i<this.length-1; i++){
			if(i >=index)
				newAr[i] = this[i+1];
			else
				newAr[i] = this[i];
		}
	return newAr;
	
	//this.splice(index, 1);
	//return this;
}

function getIndex(value){
	for(i=0; i<this.length; i++)
		if(this[i] == value)
			return i;

	return -1;
}

function add(item){
	this[this.length] = item;
}
function _array_swap(item1, item2){
	var _i = this.getIndex(item1);
	var _j = this.getIndex(item2);
	if(_i >= 0 && _j >= 0){
		var _tmp = item1;
		this[_i] = this[_j];
		this[_j] = _tmp;
	}
}

Array.prototype.deleteOne = deleteOne;
Array.prototype.getIndex = getIndex;
Array.prototype.add = add;
Array.prototype.swap = _array_swap;

/*
function DateFormatter(date, format){
	this.date = date;
	this.format = format;
	
	this.toString = function (){
			if(this.date == null)
				return "";
				
			if(this.format == null || this.format = "")
				return this.date.toString();
					
			var tmp = this.format;
			
			if(this.format.indexOf("MM") >= 0){
				var m = this.date.getMonth() + 1;
				var str = ((m < 10) ? "0" : "") + m;
				tmp.replace(new RegExp("MM", "g"), str);
			}
			if(this.format.indexOf("DD") >= 0){
				var d = this.date.getDate();
				var str = ((d < 10) ? "0" : "") + d;
				tmp.replace(new RegExp("DD", "g"), str);	
			}
			if(this.format.indexOf("CCYY") >= 0){
				var y = this.date.getFullYear();
				var str = "" +  y;
				tmp.replace(new RegExp("CCYY", "g"), str);	
			}
			if(this.format.indexOf("YYYY") >= 0){
				var y = this.date.getFullYear();
				var str = "" +  y;
				tmp.replace(new RegExp("YYYY", "g"), str);	
			}
			if(this.format.indexOf("YY") >= 0){
				var y = this.date.getYear();
				var str = "" +  y;
				tmp.replace(new RegExp("YY", "g"), str);	
			}
			return tmp;
		}
}
*/

function loadTextAreas(){
	var arTextAreas = document.getElementsByTagName("TEXTAREA");
						
	for(var i=0; i<arTextAreas.length; i++){
		var _tmp = arTextAreas[i].getAttribute("content");
		if(_tmp != null && arTextAreas[i].value == ""){

			regExp = /\\r/g;
			_tmp = _tmp.replace(regExp, "\r");
			regExp = /\\n/g;
			_tmp = _tmp.replace(regExp, "\n");
			regExp = /\\\"/g;
			_tmp = _tmp.replace(regExp, "\"");

			arTextAreas[i].value = _tmp;
		}
	}
}

var _alphabet = null;
function createVerticalHTML(textToConvert, el){
	
	if(verticalHTMLImages == true || isIE == false){
		//initialize the alphabet if neccessary...
		if(_alphabet == null){
			_alphabet = new Alphabet();
			_alphabet.loadAlphabet();
		}
				
		for(var j = textToConvert.length - 1; j >= 0; j--){
			var _char = textToConvert.substr(j, 1).toUpperCase();
			var _img = _alphabet.images[_char];
				
			if(_img != null){
				var newImg = _img.cloneNode(false);
				el.appendChild(newImg);
				//if(newImg.height > 20)
				//	newImg.height = 10;
			}
			else
				el.appendChild(_alphabet.images["space"].cloneNode(false));
			el.appendChild(document.createElement("BR"));
		}
	}
	else{
		el.style.layoutFlow = "vertical-ideographic";
		if(el.nodeName.toLowerCase() == "td"){
			el.nowrap="true";
			el.align="right";
			el.vAlign="center";
		}
		textToConvert = textToConvert.toUpperCase();
		el.appendChild(document.createTextNode(textToConvert));
	}
}

function createVerticalContent(align, elementAr){
	if(align == null || align == "")
		align="middle";

	var arTemp = null;
	if(elementAr != null)
	{
		arTemp = elementAr;
	}
	else
	{
		arTemp = document.getElementsByTagName("*");
	}
	
		
	for(var i=0; i < arTemp.length; i++){
		
		var _tmp = arTemp[i].getAttribute("VerticalContent");
		if(_tmp != null && _tmp != ""){
			//Clear out the current content...
			while(arTemp[i].childNodes.length > 0)
				arTemp[i].removeChild(arTemp[i].childNodes[0]);
			
			arTemp[i].vAlign = align;
			arTemp[i].align = "middle";
			if(isIE){
				/*
				var length = _tmp.length;
				if(length > 10)
					length = 10;
				for(var j=0; j < length; j++){
					var chr = _tmp.charAt(j);
					var b = document.createElement("B");
					b.appendChild(document.createTextNode(chr));
					arTemp[i].appendChild(b);
					arTemp[i].appendChild(document.createElement("BR"));
				}
				*/
				arTemp[i].style.layoutFlow = "vertical-ideographic";
				arTemp[i].appendChild(document.createTextNode(_tmp));
				arTemp[i].align = "right";
				
			}
			else{
				createVerticalHTML(_tmp, arTemp[i]);
			}
		}
	}
}
	
function Alphabet(){
	this.images = new Array();
	this.makeLetter = function (theLetter, imgName){
		var img = document.createElement("IMG");
		if(theLetter == " " || theLetter == "\n" || theLetter == "\t" || theLetter == "space")
			img.src = "/images/alphabet/courier_space.gif";
		else if(imgName != null && imgName != "")
			img.src = "/images/alphabet/courier_" + imgName + ".gif";
		else
			img.src = "/images/alphabet/courier_" + theLetter + ".gif";
		this.images[theLetter] = img;
	}

	this.loadAlphabet = function (){
		for(var i=0; i < 10; i++){
			var _str = "";
			_str += i;
			this.makeLetter(_str);
		}
		this.makeLetter("A");
		this.makeLetter("B");
		this.makeLetter("C");
		this.makeLetter("D");
		this.makeLetter("E");
		this.makeLetter("F");
		this.makeLetter("G");
		this.makeLetter("H");
		this.makeLetter("I");
		this.makeLetter("J");
		this.makeLetter("K");
		this.makeLetter("L");
		this.makeLetter("M");
		this.makeLetter("N");
		this.makeLetter("O");
		this.makeLetter("P");
		this.makeLetter("Q");
		this.makeLetter("R");
		this.makeLetter("S");
		this.makeLetter("T");
		this.makeLetter("U");
		this.makeLetter("V");
		this.makeLetter("W");
		this.makeLetter("X");
		this.makeLetter("Y");
		this.makeLetter("Z");
		this.makeLetter("space");
		this.makeLetter("&", "ampersand");
		this.makeLetter("*", "asterisk");
		this.makeLetter("@", "at");
		this.makeLetter("\\", "backslash");
		//this.makeLetter("`", "backtick");
		this.makeLetter("^", "caret");
		this.makeLetter("}", "closebrace");
		this.makeLetter("{", "openbrace");
		this.makeLetter(":", "colon");
		this.makeLetter(",", "comma");
		this.makeLetter("$", "dollar");
		this.makeLetter("\"", "doublequote");
		this.makeLetter("!", "exclamationpoint");
		this.makeLetter(">", "greaterthan");
		this.makeLetter("<", "lessthan");
		this.makeLetter("(", "leftparenthesis");
		this.makeLetter(")", "closeparenthesis");
		this.makeLetter("[", "openbracket");
		//this.makeLetter("]", "closebracket");
		this.makeLetter(".", "period");
		this.makeLetter(";", "semicolon");
		this.makeLetter("'", "singlequote");
		this.makeLetter("/", "slash");
		this.makeLetter("~", "tilde");
		this.makeLetter("-", "dash");
		this.makeLetter("_", "underscore");
		this.makeLetter("+", "plus");
		this.makeLetter("=", "equals");
		this.makeLetter("#", "pound");
		this.makeLetter("%", "percent");
	}
}

function _trim(){
	var tmp = this.valueOf();
	var start = /^ */;
	tmp = tmp.replace(start, "");

	var end = /[ ]*$/;
	tmp = tmp.replace(end, "");

	return tmp;
}
String.prototype.trim = _trim;

/**
 * This function duplicates the getURLParams function
 * in ajax-base.js.
 * 
 * @param url
 * @return
 */
function getURLParams(url){
	if(url == null || url == "")
		url = window.location.href;
	
	var paramStr = "";
	try{
		paramStr = url.substring(url.indexOf("?") + 1);
	} catch(e) {}
	
	var params = new Array();
	var tmp = paramStr.split("&");
	for(var i=0; i < tmp.length; i++){
		p2 = tmp[i].split("=");
		params[p2[0]] = p2[1];
	}
	return params;
}

function getURLKeys(url) {
	if(url == null || url == "")
		url = window.location.href;
	
	var paramStr = "";
	try
	{
		paramStr = url.substring(url.indexOf("?") + 1);
	} catch(e) {}

	var keys = new Array();
	var tmp = paramStr.split("&");
	for(var i=0; i < tmp.length; i++)
	{
		p2 = tmp[i].split("=");
		keys[i] = p2[0];
	}
	return keys;
}

function centerWindow(win, width, height){
	win.resizeTo(width, height);
	win.moveTo(parseInt((screen.availWidth - width)/2), parseInt((screen.availHeight - height)/2));
	win.focus();
}

function showSavingMessage(message, doc){
	if(doc == null)
		doc = document;
	if(message == null || message == "")
		message = "Saving data... Please Wait.";
	//var div = doc.createElement("div");
	//div.innerHTML = "<br><center><b>" + message + "</b></center><br>";
	doc.body.innerHTML = "<div><br><center><b>" + message + "</b></center><br></div>";

	//doc.body.innerHTML = "";
	//doc.body.appendChild(div);
}

function wrapCDATA(val){
	return "<![CDATA[" + val + "]]>";
}

// Firefox doesn't update the innerHTML/DOM nodes automatically when user changes the value on 
// screen, e.g: if currently radio button A is selected and I select B,
// the "checked" attribute is not "transfered" from A to B automatically.
// This caused problem as described in RT Ticket #3753.
//
// Call this function (e.g: with onblur/onchange) to make sure that changes to input fields in the form will be captured
// in the DOM - not necessary in IE but is required in Firefox, etc as the DOM
// will otherwise reflect the page as it was initially.
//
// inputField : the input field OR the ID of the input field

function updateDOM(inputField) {

    // If the inputField ID string has been passed in, get the inputField object. Otherwise,
    // just use the given html element. 
    
    if (typeof inputField == "string") {
        inputField = document.getElementById(inputField);
    }

    if (inputField.type == "select-one") {
        for (var i = 0; i < inputField.options.length; i++) {
            if (i == inputField.selectedIndex) {
                inputField.options[inputField.selectedIndex].setAttribute("selected","selected");
            }
        }
    } else if (inputField.type == "text") {
        inputField.setAttribute("value",inputField.value);
    } else if (inputField.type == "textarea") {
        inputField.setAttribute("value",inputField.value);
    } else if (inputField.type == "checkbox") {
        if (inputField.checked) {
            inputField.setAttribute("checked","checked");
        } else {
            inputField.removeAttribute("checked");
        }
    } else if (inputField.type == "radio") {
        // Force the "checked" attribute transfer to happen immediately to the DOM nodes as the 
        // user is clicking the radio buttons.
        var radioNames = document.getElementsByName(inputField.name);
        for(var i = 0; i < radioNames.length; i++) {
            if (radioNames[i].checked) {
                radioNames[i].setAttribute("checked","checked");
            } else {
                radioNames[i].removeAttribute("checked");
            }
        }
    }
}

// Generates random number between the min and max range.
//
// optionalNumOfPrecisionDigits: if given, the resulting number
//   will have that many fractional digits.

function generateRandomNumber(minVal, maxVal, optionalNumOfPrecisionDigits) {

	var randVal = minVal + (Math.random() * (maxVal - minVal));
	return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(optionalNumOfPrecisionDigits);

}

var dayNames = new Array("Sun", "Mon", "Tue", "Wed", "Thurs", "Fri", "Sat");

var monthNames = new Array("Jan", "Feb", "Mar", 
        "Apr", "May", "June", "July", "Aug", "Sept", 
        "Oct", "Nov", "Dec");

// Returns local time in simple/compact format, e.g: Fri Jan 29, 12:04 PM 
// Year is not printed out to shorten the format.

function getCurrentLocalTime() {
    var d = new Date();
    var currDay = d.getDay();
    var currDate = d.getDate();
    var currMonth = d.getMonth();
    var currYear = d.getFullYear();

    var currHour = d.getHours();
    var currMin = d.getMinutes();
    var ap = "";

    if (currHour < 12) {
        ap = "AM";
    } else {
        ap = "PM";
    }

    if (currHour == 0) {
        currHour = 12;
    }
    if (currHour > 12) {
        currHour = currHour - 12;
    }
    
    if (currMin < 10) {
        currMin = '0' + currMin;
    }

    return dayNames[currDay] + " " +  monthNames[currMonth] + " " + currDate  
        + ", " + currHour + ":" + currMin + " " + ap;

}

// Given a html text input field and the number of max decimal digits,
// checks and enforces that the user do not type in more decimal digits than
// the max number. Max number is greater or equal to 1.
// Integer numbers are considered valid.
// This function will pop-up an alert and immediately return
// the keyboard focus to the same text field.
// Usage: call this in an onblur event of the text input field.
var currentlyEditedTextField = null;
var regExpWhole = new RegExp('^[0-9]*$', '');
function checkDecimalDigits(el, maxNumOfDecimalDigits) {                        
           
    el.value = el.value.trim();
    var regExpDecimal = new RegExp('^[0-9]*\.[0-9]{1,' + maxNumOfDecimalDigits + '}$', '');
    var valueNum = parseFloat(el.value); // Convert the value to float for comparing with 0 and max weight
    if((!regExpWhole.test(el.value) && !regExpDecimal.test(el.value))) {
        window.alert("Please enter an integer value or numeric value with up to " + maxNumOfDecimalDigits + " decimal points.");
        currentlyEditedTextField = el;
        // Firefox needs a split second after the alert window is closed before it can set the focus back.
        // Store the el in global variable so the setTimeout() can see it.
        setTimeout("currentlyEditedTextField.focus(); currentlyEditedTextField.select(); currentlyEditedTextField = null;", 20);                                                       
        return false;
    }

    return true;

}

