/***
	Standard/General Javascript functions
***/

function $(o) {
	if (!document.getElementById(o)) return null;
	var z = document.getElementById(o);
	return z;
}
var sResultDiv;
var sFormName;
var callbackFunction;
var globalObjElement;
var globalNoticeDiv;
var create_all_forfirstselection;
var JSONobject;

// *****************************************
function __loadContent( f,formName )
{
	sResultDiv = '__ContentArea';	
	var g = document.getElementById(sResultDiv);
	
	//** 2. sanitize the entries
	// split the params and the main/core file
	pStr = 'noframe=1';
	p = f.indexOf('&');
	if (p >= 0) {
		pStr += f.substr(p);
		f = f.substr(0,p);
	}
	if (formName) {
		pStr += '&' + getFormData(formName);
	}
	//alert('p = '+pStr+'\nf = '+f);
	var boxmsg = '<img src=\'../_sys/images/loading_circle.gif\' border=0 valign=center> Loading page, please wait ...'
	g.innerHTML = '<div id=\'msg\' align=center style= align=center \'width:100px;white-space:nowrap;padding:5px;border:#7F99BE 1px solid;background-color:#D1D9E4;\'>'+boxmsg+'</div>';
	g.style.display = 'block';
	//** 3. initiate connection
	xmlhttpPost('./?__f='+f,pStr);
	//xmlhttpPost('./?__f='+f,'noframe=1&a=100&b=200');
	//xmlhttpPost('./?__f='+f+'&'+pStr,'');
}

// *****************************************
function __loadContentWithParam( f, param, formName, divName, callbackFuncName )
{
	//alert(callbackFuncName);
	if (callbackFuncName != 'undefined' || callbackFuncName != null || callbackFuncName != '') {
		
		callbackFunction = callbackFuncName;
	}
	if (!divName) {
		sResultDiv = '__ContentArea';
	} else {
		sResultDiv = divName;
	}
	var g = document.getElementById(sResultDiv);
	
	//** 2. sanitize the entries
	// split the params and the main/core file
	pStr = 'noframe=1';
	p = f.indexOf('&');
	if (p >= 0) {
		pStr += f.substr(p);
		f = f.substr(0,p);
	}
	if (formName) {
		pStr += '&' + getFormData(formName);
	}
	if (param) {
		pStr += '&' + param;
	}
	//alert(param);
	//alert('p = '+pStr+'\nf = '+f);
	var boxmsg = '<img src=\'../_sys/images/loading_circle.gif\' border=0 valign=center> Loading page, please wait ...'
	g.innerHTML = '<div id=\'msg\' align=center style= align=center \'width:100px;white-space:nowrap;padding:5px;border:#7F99BE 1px solid;background-color:#D1D9E4;\'>'+boxmsg+'</div>';
	g.style.display = 'block';
	//** 3. initiate connection
	xmlhttpPost('./?__f='+f,pStr);
}
	
// *****************************************
function __loadTable(progname,formName,paramstr,divName,UseWrapper)
{
	//alert(divName);
	if (!divName) {
		sResultDiv = 'divTable';
	} else {
		sResultDiv = divName;
	}
	//alert(sResultDiv);
	var g = document.getElementById(sResultDiv);
	//alert(g.id);
	//g.style.border = '#7F99BE 1px solid';
	//g.style.backgroundColor = '#D1D9E4';
	
	//** 2. sanitize the entries
	var pStr;
	if (formName) pStr = getFormData(formName);
	if (paramstr) pStr = pStr + '&'+paramstr;
	//alert('pStr='+pStr);
	var boxmsg = 'Loading ....';
	//alert(g.style.display);
	g.innerHTML = '<div id=\'msg\' align=center style= align=center \'width:100px;white-space:nowrap;padding:5px;border:#7F99BE 1px solid;background-color:#D1D9E4;\'>'+boxmsg+'</div>';
	g.style.display = 'block';
	//** 3. initiate connection
	if (!UseWrapper) {
		xmlhttpPost('./'+progname+'.php',pStr);
	} else {
		pStr = 'noframe=1&'+pStr;
		xmlhttpPost('./?__f='+progname,pStr);
	}
	
}
/*****************************************************************************
 * Function: 	__loadSelection
 * Parameter:	sql_tablename 		... the sql table name which to be queried, 
 *				sql_value_column 	... the column to be retrieved and set it as the 'value' of the option
 *				sql_text_column 	... the column to be retrieved and display as the text of the option 
 *				sql_criteria 		... the criteria or the "where" clause for the sql statement 
 *				selectElement 		... the element ID of the select tag which the list to be populated 
 *				loadingNoticeDiv 	... the "please wait" or "loading" notice while waiting for process to complete
 *				callback			... optional. The callback function
 *				usewrapper			... optional. Boolean. 
 *				progname			... optional. The php script to be called
 *				dontCreateSelectionForAll ... optional. To define wether or not to have "All" as the first entry selection of the list
 * Purpose:		To construct select tag list option based on sql request
 * Return:		Void.
 */
function __loadSelection(sql_tablename, sql_value_column, sql_text_column, sql_criteria, selectElement, loadingNoticeDiv, UseWrapper, progname, dontCreateSelectionForAll)
{
	if (!progname || progname == null) {
		var progname = 'remotesql';
	}
	var useJSONflag = true;
	if (!callbackFunction) {
		callbackFunction = '__createSelection';
	}
	//alert('dontCreateSelectionForAll = '+dontCreateSelectionForAll);
	if (dontCreateSelectionForAll == null || dontCreateSelectionForAll == 'undefined') {
		dontCreateSelectionForAll = true;
	}
	create_all_forfirstselection = (!dontCreateSelectionForAll);
	//alert('create_all_forfirstselection = '+create_all_forfirstselection);
	globalObjElement = selectElement;
	globalNoticeDiv = loadingNoticeDiv;
	// prepare post or get parameters
	var pStr = '';
	pStr += 'table='+sql_tablename;
	pStr += '&value_col='+sql_value_column;
	pStr += '&text_col='+sql_text_column;
	pStr += '&criteria='+sql_criteria;
	// show any loading notice
	if (loadingNoticeDiv != null) {
		showDiv(loadingNoticeDiv);
	}
	// request from server
	if (!UseWrapper) {
		xmlhttpPost('./'+progname+'.php',pStr, useJSONflag);
	} else {
		pStr = 'noframe=1&'+pStr;
		xmlhttpPost('./?__f='+progname,pStr,useJSONflag);
	}
}
// *****************************************
function __createSelection( jsonObj )
{
	var sel = $(globalObjElement);
	sel.length = 0;
	//alert('obj len = '+jsonObj.length);
	if (create_all_forfirstselection) {
		var newOpt = document.createElement('option');
		newOpt.value = '0';
		newOpt.text = 'All';
		try {
			sel.add(newOpt, null); // standards compliant; doesn't work in IE
		} catch(ex) {
			sel.add(newOpt); // IE only
		}
	}
	for(var j=0; j < jsonObj.length; j++) {
		var newOpt = document.createElement('option');
		newOpt.value = jsonObj[j].value;
		newOpt.text = jsonObj[j].text;
		try {
			sel.add(newOpt, null); // standards compliant; doesn't work in IE
		} catch(ex) {
			sel.add(newOpt); // IE only
		}
	}
	// complete
	if (globalNoticeDiv) closeDiv(globalNoticeDiv);
	showDiv(globalObjElement);
	// reset
	globalObjElement = '';
	callbackFunction = '';
}
// *****************************************
function __loadURL(progname,formName,paramstr)
{
	//**  sanitize the entries
	var pStr;
	if (formName) pStr = getFormData(formName);
	if (paramstr) pStr = pStr + '&'+paramstr;
	//alert(pStr);
	//**  initiate connection
	location.href = './?__f='+progname+'&'+pStr;
	
}
// *****************************************
function toggleEnable(id)
{
	var t = document.getElementById(id).disabled;
	if (t) {
		document.getElementById(id).disabled = false;
	} else {
		document.getElementById(id).disabled = true;
	}
}
// *****************************************
function setEnable(id, flag)
{
	if (flag) {
		flag = false;
	} else {
		flag = true;
	}
	document.getElementById(id).disabled = flag;
}


// *****************************************
function xmlhttpPost(strURL,sQstr,expectingJSON) {
	var arequest = getTransport();
	arequest.open('POST', strURL, true);
	arequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	arequest.onreadystatechange = function() {
	    if (arequest.readyState == 4) {
	    	updatepage(arequest.responseText,expectingJSON);
	    }
	}
	arequest.send(sQstr);
}
// *****************************************
function updatepage(str,expectingJSON){
	if (expectingJSON == null || !expectingJSON) {
		//
		if (sResultDiv) {
			document.getElementById(sResultDiv).style.display = 'block';
			document.getElementById(sResultDiv).innerHTML = str;
			try {
				execJS(document.getElementById(sResultDiv));
			} catch(e) {
				try {
					setFocusDiv(sResultDiv);
				} catch (e) { }
			}
			if (callbackFunction) {
				window[callbackFunction]();
				callbackFunction = '';
			}
			
		}
		//	   
	} else {
		// receive JSON
		/*--
		alert('string received : '+str);
		str = 'JSONobject = '+ str;
    	eval(str);
		--*/
		if (!this.JSON) {
    		str = 'JSONobject = '+ str;
    		eval(str);
		} else {

			var JSONobject = JSON.parse(str);
			//alert('receive JSON '+JSONobject);
		}
		if (callbackFunction) {
			window[callbackFunction](JSONobject);
			callbackFunction = '';
		}
	}
}
// *****************************************
function checkFormMandatory(formname)
{
	var f = document.forms[formname];
	if (!f) {
		var c = document.getElementById('__ContentArea');
		//f = c.childNodes[formName];\
		var ff = document.getElementsByTagName('form');
		for(j=0;j<ff.length;j++) {
			if (ff[j].name == formname) {
				f = ff[j];
			}
		}
	}
	var ferr= 0;
	var fVal;
	var firstFld='';
	// loop through to create 'post' string
	for(j=0;j<f.length;j++) {
		if(f.elements[j].type.substr(0,6) == 'select') {
			var o = document.getElementById(f.elements[j].id);
			if (o.optional == 'no' || o.title=='mandatory') {
				fVal = f.elements[j].options[f.elements[j].selectedIndex].value;
				if (fVal == '0' || !fVal) {
					o.style.border = '#FB8404 1px solid';
					if (!firstFld) firstFld = f.elements[j].id;
						//alert(f.elements[j].name);
						ferr=1;
				} else {
					o.style.border = '#5C99DC 1px solid';
				}
			}
		}
		//
		if(f.elements[j].type != 'hidden' && 
			f.elements[j].type.substr(0,6) != 'select' &&
			f.elements[j].type != 'button') {
			fVal = f.elements[j].value;
			var o = document.getElementById(f.elements[j].id);
			if (o.optional == 'no' || o.title=='mandatory') {
				if (!fVal) {
					o.style.border = '#FB8404 1px solid';
					if (!firstFld) firstFld = f.elements[j].id;
					//alert(f.elements[j].name);
					ferr=1;
				} else {
					o.style.border = '#5C99DC 1px solid';
				}
			}
		}
	}
	return ferr;
}
/*****************************************************************************
 * Function:	__ValidateForm
 * Parameter:	form name
 * Purpose:		Check for 'required' or 'ifentered' fields.
 *				Check for format, length (min & max), alpha only.
 *				It stops and return an err msg when hit an error.
 * Return:		String. 
 *				It will return the "err" message that the field is 
 *				required or wrong format etc.
 *
 */

function __ValidateForm(formname)
{
	var elem = document.forms[formname].elements;
	var errmsg = '';
	/*
	 * validate required/mandatory fields
	 */
	var reqField = '';
	for(var j=0; j < elem.length; j++) {
		var el = elem[j];
		var isMandatory = false;
		if (el.getAttribute('required') != null) isMandatory = true;
		//alert(el.name + ' is mandatory = '+isMandatory);
		if (isMandatory) {
			var inputType = String(el.type).toLowerCase();
			//alert('input type = '+inputType+' , value len = '+el.value.length);
			if (inputType == 'text' || inputType == 'textarea' || inputType == 'hidden' || inputType == 'password') {
				if (el.value.length == 0) {
					//alert('Please fill in all fields marked with *');
					reqField = el.getAttribute('required');
					if (inputType != 'hidden') el.focus();
					break;
				}
			}
			if (inputType.substr(0,6) == 'select') {
				if (el.selectedIndex == 0) {
					//alert('Please choose from the selection list');
					reqField = el.getAttribute('required');
					el.focus();
				}
			}
		}
	}
	if (reqField.length > 0) {
		errmsg = '"'+reqField+'" is a required field!';			
		return errmsg;
	}
	/*
	 * verify field format
	 */
	var reqField = '';
	var comment = '';
	var truncate = 1;
	
	for(var j=0; j < elem.length; j++) {
		var el = elem[j];
		var needVerification = false;
		if (el.getAttribute('verify') != null) needVerification = true;
		//alert('veriy '+el.name + ' is needVerification = '+needVerification);
		
		if (needVerification && el.value.length > 0) {
			var allowchar = '';
			var allowcharlist = [];
			var inputType = String(el.type).toLowerCase();
			var verifyItems = String(el.getAttribute('verify')).split(',');
			var verifySpec = [];
			for(var i=0;i<verifyItems.length;i++) {
				var a = String(verifyItems[i]).split(':');
				verifySpec[verifySpec.length] = {'attribute':a[0], 'value':a[1]};
			}
			var formatOK = 1;
			if (inputType == 'text' || inputType == 'textarea' || inputType == 'password') {
				// loop #1 -- firstly, check if "allowchar" is specified
				for(var i=0;i<verifySpec.length;i++) {
					var spec = verifySpec[i];
					if (spec.attribute == 'allowchar') {
						allowchar = String(spec.value);
						allowcharlist = allowchar.split('');
					}
				}
				// loop #2
				for(var i=0;i<verifySpec.length;i++) {
					var spec = verifySpec[i];
					//alert('debug: spec.attribute = '+spec.attribute);
					switch (spec.attribute) {
						case 'numeric':
							///48 -- 57
							for(var n=0; n < el.value.length; n++) {
								var cval = String(el.value).charCodeAt(n);
								//alert(cval);
								if (cval < 48 || cval > 57) {
									if (allowchar.length > 0) {
										var allowcharOk = 0;
										for(var z=0; z < allowchar.length; z++) {
											if (allowchar.charCodeAt(z) == cval) {
												allowcharOk = 1;
												break;
											}
										}
										if (!allowcharOk) {
											formatOK = 0;
											comment = 'Accept only numbers, 0 thru 9.\n';
											comment += 'These characters are acceptable as well:\n';
											for(zz=0; zz < allowcharlist.length; zz++) {
												comment += '"'+allowcharlist[zz]+'" ';
											}											
											break;
										}
									} else {
										formatOK = 0;
										comment = 'Accept only numbers, 0 thru 9.';
									}
								}
							}
							break;
						case 'format':
							switch (spec.value) {
								case 'email':
									var regex1 = /^[A-Z0-9._%+-]+@[A-Z0-9_-]+\.[A-Z]{2,4}$/i;
									var regex2 = /^[A-Z0-9._%+-]+@[A-Z0-9_-]+\.[A-Z]+\.[A-Z]{2,4}$/i;
									if (el.value.search(regex1) == -1 && el.value.search(regex2) == -1) {
										formatOK = 0;
										comment = 'Invalid e-mail address format.\nAcceptable formats:\nmyname@adomain.com\nmyname@adomain.com.my';
									}
									break;
							}
							break;
						case 'sizemin':
							//alert(el.value.length + ' < '+parseInt(spec.value)+' = '+(el.value.length < parseInt(spec.value)));
							if (el.value.length < parseInt(spec.value)) {
								formatOK = 0;
								comment = 'Minimum length is '+spec.value+'\nYour entry length is '+el.value.length;
							}
							break;
						case 'sizemax':
							if (el.value.length > parseInt(spec.value)) {
								formatOK = 0;
								comment = 'Maximum length is '+spec.value+'\nYour entry length is '+el.value.length;
								if (truncate) {
									el.value = String(el.value).substring(0,parseInt(spec.value));
								}
							}
							break;
						case 'alpha':
							///97-122 (lower) .. 65 90 (upper)
							for(var n=0; n < el.value.length; n++) {
								var cval = String(el.value).charCodeAt(n);
								if ((cval < 97 || cval > 122) && (cval < 65 || cval > 90)) {
									if (allowchar.length > 0) {
										var allowcharOk = 0;
										for(var z=0; z < allowchar.length; z++) {
											if (allowchar.charCodeAt(z) == cval) {
												allowcharOk = 1;
												break;
											}
										}
										if (!allowcharOk) {
											formatOK = 0;
											comment = 'Accept only A thru Z (upper and lower case).\n';
											comment += 'These characters are acceptable as well:\n';
											for(zz=0; zz < allowcharlist.length; zz++) {
												comment += '"'+allowcharlist[zz]+'" ';
											}
											//comment += '\n['+allowchar.charCodeAt(z)+' === '+cval+']';
											break;
										}
									} else {
										formatOK = 0;
										comment = 'Accept only A to Z (upper and lower case)';
										break;
									}
								}
							}
							break;
						case 'alphanum':
							for(var n=0; n < el.value.length; n++) {
								var cval = String(el.value).charCodeAt(n);
								//alert(String(el.value).charAt(n)+' = '+cval);
								if ((cval < 97 || cval > 122) && (cval < 65 || cval > 90) && (cval < 48 || cval > 57)) {
									if (allowchar.length > 0) {
										var allowcharOk = 0;
										for(var z=0; z < allowchar.length; z++) {
											if (allowchar.charCodeAt(z) == cval) {
												allowcharOk = 1;
												break;
											}
										}
										if (!allowcharOk) {
											formatOK = 0;
											comment = 'Accept only A thru Z (upper and lower case), 0 thru 9.\n';
											comment += 'These characters are acceptable as well:\n';
											for(zz=0; zz < allowcharlist.length; zz++) {
												comment += '"'+allowcharlist[zz]+'" ';
											}
											break;
										}
									} else {
										formatOK = 0;
										comment = 'Accept only A thru Z (upper and lower case) and 0 thru 9';
										break;
									}
								}
							}
							break;
							
					}
				}
				//
				if (!formatOK) {
					reqField = el.getAttribute('required'); // must tag along with required field
					if (!reqField) reqField = el.getAttribute('ifentered');
					el.focus();
					break;
				}
				//
			}
		}
	}
	if (reqField.length > 0) {
		errmsg = '"'+reqField+'" is invalid!\n'+comment;
		return errmsg;
	}
	/*
	 * field value validation
	 */
	var reqField = '';
	var comment = '';
	for(var j=0; j < elem.length; j++) {
		var el = elem[j];
		var needValidation = false;
		if (el.getAttribute('validate') != null) needValidation = true;
		//alert(el.name + ' need validate = '+needValidation);
		if (needValidation && el.value.length > 0) {
			var inputType = String(el.type).toLowerCase();
			var validateItems = String(el.getAttribute('validate')).split(',');
			var validateSpec = [];
			//alert('val items : '+validateItems.length);
			for(var i=0;i<validateItems.length;i++) {
				var a = String(validateItems[i]).split(':');
				validateSpec[validateSpec.length] = {'attribute':a[0], 'value':a[1]};
			}
			var formatOK = 1;
			//alert(inputType);
			if (inputType == 'text' || inputType == 'textarea' || inputType == 'password') {
				for(var i=0;i<validateSpec.length;i++) {
					var spec = validateSpec[i];
					//alert(spec.attribute);
					switch (spec.attribute) {
						case 'equal':
						case '=':
							var compareValue = $(spec.value).value;
							if (el.value != compareValue) {
								formatOK = 0;
								comment = el.getAttribute('invalidmsg');
							}
							break;
						case 'lessthan':
						case '<':
							var compareValue = $(spec.value).value;
							// its the other way round than what define to be valid
							if (parseInt(el.value) >= parseInt(compareValue)) {
								formatOK = 0;
								comment = el.getAttribute('invalidmsg');
							}
							break;
						case 'greaterthan':
						case '>':
							var compareValue = $(spec.value).value;
							// its the other way round than what define to be valid
							if (parseInt(el.value) <= parseInt(compareValue)) {
								formatOK = 0;
								comment = el.getAttribute('invalidmsg');
							}
							break;
					}
				}
				if (!formatOK) {
					reqField = el.getAttribute('required'); // must tag along with required field
					if (!reqField) reqField = el.getAttribute('ifentered');
					el.focus();
					break;
				}
			}
		}
	}
	if (reqField.length > 0) {
		errmsg = '"'+reqField+'" is invalid!\n'+comment;
		return errmsg;
	}
	// done..
	return '';
	//
}
	
// *****************************************
function getFormData(formName)
{
	var f = document.forms[formName];
	if (!f) {
		var c = document.getElementById('__ContentArea');
		var ff = c.getElementsByTagName('form');
		for(j=0;j<ff.length;j++) {
			if (ff[j].name == formName) {
				f = ff[j];
			}
		}
	}
	if (!f) {
		var f = document.getElementById('fld_'+formName);
		/*
		var ff = c.getElementsByTagName('form');
		for(j=0;j<ff.length;j++) {
			if (ff[j].name == formName) {
				f = ff[j];
			}
		}
		*/
		
	}
	if (!f) {
		var c = document.getElementById('entryform');
		if (c) {
			var ff = c.getElementsByTagName('form');
			for(j=0;j<ff.length;j++) {
				if (ff[j].name == formName) {
					f = ff[j];
				}
			}
		}
	}
	if (!f) {
		var c = document.getElementById('gridBrowse');
		if (c) {
			var ff = c.getElementsByTagName('form');
			for(j=0;j<ff.length;j++) {
				if (ff[j].name == formName) {
					f = ff[j];
				}
			}
		}
	}
	if (!f) alert('form '+formName+' not found!');
	var ferr= 0;
	var fVal;
	var postStr='';
	// loop through to create 'post' string
	
	for(j=0;j<f.length;j++) {
	//
		if (f.elements[j].type != 'undefined') {
		//alert(f.elements[j].name + ' = ' + f.elements[j].type);
			if(f.elements[j].type == 'textarea' || f.elements[j].type == 'text' || f.elements[j].type == 'hidden' || f.elements[j].type == 'password') {
				fVal = f.elements[j].value + '';
				//fVal.replace(/\&/g,'&amp;');
				if (/[\&]/.exec(fVal)) {
					fVal = fVal.replace(/&/g,'and');
					//alert(fVal);
				}
				postStr += (postStr?'&':'')+f.elements[j].name+'='+(fVal);
			} else {
				// exception
				if (f.elements[j].name == 'svcnum_granted' || f.elements[j].name == 'callcontrol_granted' || f.elements[j].name == 'pin_granted' || f.elements[j].name == 'grpList') {
					// take all data !!!
					for (var i=0;i<f.elements[j].length;i++) {
						fVal = f.elements[j].options[i].value;
						postStr += (postStr?'&':'')+f.elements[j].name+'[]='+fVal;
					}
				} else {
					// begin of standard select list extraction
					if (f.elements[j].type.substr(0,6)=='select') {
						if (f.elements[j].type.substr(7,3)=='one') {
							var fIndex = (f.elements[j].selectedIndex=='undefined'?0:f.elements[j].selectedIndex);
							fVal = f.elements[j].options[fIndex].value;
							postStr += (postStr?'&':'')+f.elements[j].name+'='+fVal;
						} else {
							for (var i=0;i<f.elements[j].length;i++) {
								if (f.elements[j].options[i].selected) {
									fVal = f.elements[j].options[i].value;
									postStr += (postStr?'&':'')+f.elements[j].name+'[]='+fVal;
								}
							}
						}
					}
				}
				// end of standard select list extraction
				// begin radio
				if (f.elements[j].type == 'radio') {
					if (f.elements[j].checked) {
						fVal = f.elements[j].value;
						postStr += (postStr?'&':'')+f.elements[j].name+'='+fVal;
					}
				}
				// end radio
				// begin checkbox
				if (f.elements[j].type == 'checkbox') {
					if (f.elements[j].checked) {
						fVal = f.elements[j].value;
						postStr += (postStr?'&':'')+f.elements[j].name+'='+fVal;
					}
				}
				// end checkbox
			}
		}
	//
	}
	return postStr;
}
// *****************************************
function execJS(node)
{
    var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
    var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
    var bMoz = (navigator.appName == 'Netscape');

	if (!node) return;
	
	/* IE wants it uppercase */
	        var st = node.getElementsByTagName('SCRIPT');
	        var strExec;
	
	for(var i=0;i<st.length; i++) {
        if (bSaf) {
                strExec = st[i].innerHTML;
                st[i].innerHTML = "";
        } else if (bOpera) {
                strExec = st[i].text;
                st[i].text = "";
        } else if (bMoz) {
                strExec = st[i].textContent;
                st[i].textContent;
        } else {
                strExec = st[i].text;
                st[i].text = "";
        }
	
		try {
                var x = document.createElement("script");
                x.type = "text/javascript";
                if (bSaf || bOpera || bMoz) {
                	x.innerHTML = strExec;
                } else {
                	x.text = strExec;
                }
	            document.getElementsByTagName("head")[0].appendChild(x);
            } catch(e) {
                    alert(e);
            }
	}
}
// *****************************************
function setFocusDiv(layerName) {
	var layer = document.getElementById(layerName);
	var focusIt = layer.getElementsByTagName('a')[0];
	try{
		if (focusIt) focusIt.focus();
	} catch(e) {
		// do nothing!
	}
}
//********************************************
function getTransport() {
	var transport;
	if ( window.XMLHttpRequest )
	{
		transport = new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {
		try {
			transport = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch(err) {
			transport = new ActiveXObject('Microsoft.XMLHTTP');
		}
	}
	return transport;
}
// *****************************************
function toggleMenu(control_id) {
	toggleDisplay(control_id);
    toggleDisplay(control_id+'_link');
    toggleDisplay(control_id+'_nolink');
}
// *****************************************
function switchTreeIndicator(thespan) {
	var z = document.getElementById(thespan);
	if (z.innerHTML == '-') {
		z.innerHTML = '+';
		document.getElementById(thespan+'_expand').style.display = 'none';
		document.getElementById(thespan+'_collapse').style.display = 'inline-block';
	} else {
		z.innerHTML = '-';
		document.getElementById(thespan+'_collapse').style.display = 'none';
		document.getElementById(thespan+'_expand').style.display = 'inline-block';
	}
	
}
// *****************************************
function toggleDisplay(control_id) { 
	if( document.getElementById(control_id).style.display == "none" ) {
    	document.getElementById(control_id).style.display = "block"; 
  	} else { 
    	document.getElementById(control_id).style.display = "none"; 
    }
}
// *****************************************
function showDiv( divStub ) {
	document.getElementById(divStub).style.display = 'block';
}
function openDiv( stub ) {
	showDiv( stub );
}
// *****************************************
function closeDiv( divStub ) {
	document.getElementById(divStub).style.display = 'none';
}
function hideDiv( stub ) {
	closeDiv( stub );
}
// *****************************************
function log_out()
{
	ht = document.getElementsByTagName("body");
	ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
	//ht[0].style.filter = "progid:DXImageTransform.Microsoft.Emboss()";
	//ht[0].style.filter = "progid:DXImageTransform.Microsoft.Pixelate(maxsquare=10)";
	//ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(XRay=1)";
	//ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(Invert=1)";
	if (confirm('Are you sure you want to log out?'))
	{
		return true;
	}
	else
	{
		ht[0].style.filter = "";
		return false;
	}
}
// *****************************************
function poppage(url)
{
	//alert(url);
	newwindow=window.open(url,'_blank','height=500,width=800,scrollbars=yes');
	if (window.focus) {newwindow.focus()}
}
// *****************************************
function _gotoPage(pgnum, filterFormName, outputDivName, theScriptName)
{
	var boolUseForm = true;
	if (filterFormName == '') boolUseForm = false;
	__loadTable(theScriptName,filterFormName,'pg='+pgnum,outputDivName,boolUseForm);
}
// *****************************************
function saveDestinationTag(phone,current_tag,pin_list_fk, MaxSeq)
{
	n = prompt('Enter destination tag-name for '+phone+' :',phone);	
	if (n) {
		sResultDiv = 'scratchArea';	
		var g = document.getElementById('scratchArea');
		g.innerHTML = '<div id=\'msg\' style= align=center \'width:100px;white-space:nowrap;padding:5px;border:#7F99BE 1px solid;background-color:#D1D9E4;\'><b>Processing</b><br/>Please wait ....</div>';
		g.style.display = 'block';
		//** 2. sanitize the entries
		var pStr = 'maxseq='+MaxSeq+'&tagname='+escape(n)+'&dest='+phone+'&pin_list_fk='+pin_list_fk;
		//** 3. initiate connection
		xmlhttpPost('../../process/dodestinationtag.php',pStr);
		//
		changeDestinationTag(phone, n, MaxSeq);
	}
}

// ******************************************
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
// ******************************************
function trimAll(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
} 

// *******************************************
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// *******************************************
function setOpacity(obj,value) {
	obj.style.opacity = value/10;
	obj.style.filter = 'alpha(opacity=' + value*10 + ')';
}
/*
===========================================

	DATE UTILITY

===========================================
*/

Date.DAYS   = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

Date.MONTHS = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
]

/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return dateFormat(this, mask);
}


// return date in specified format
Date.prototype.formatOld = function (mask) {
    mask = (mask) ? mask : "dd MMM yyyy";
    
    var day         = Date.DAYS[this.getDay()];
    var date        = this.getDate();
    var month       = this.getMonth();
    var year        = this.getFullYear().toString();
    var hours       = this.getHours();
    var hours12     = (hours > 12 || hours == 0) ? Math.abs(hours - 12) : hours;
    var minutes     = this.getMinutes();
    var seconds     = this.getSeconds();
    
    preZero = function (num)    {
        return (num < 10) ? '0' + num : num;
    }
    
    var token = new Array();
    
    token['yyyy']   = year;
    token['yy']     = year.toString().substring(2, 2);
    token['y']      = token['yy'];
    
    token['MMMM']   = Date.MONTHS[month];
    token['MMM']    = Date.MONTHS[month].toString().substring(0, 3);
    token['MM']     = preZero(month+1);
    token['M']      = month+1;
    
    token['dddd']   = day;
    token['ddd']    = day.toString().substring(0, 3);
    token['dd']     = preZero(date);
    token['d']      = date;
    
    token['HH']     = preZero(hours);
    token['H']      = hours;
    
    token['hh']     = preZero(hours12);
    token['h']      = hours12;
    
    token['mm']     = preZero(minutes);
    token['m']      = minutes;
        
    token['ss']     = preZero(seconds);
    token['s']      = seconds;
    
    var stub = 0;
    for (var t in token)    {
        eval("exp = /" + t + "/g");
        mask = mask.replace(exp, "oxo" + stub + "oxo");
        stub++;
    }
    
    stub = 0;
    for (var r in token)    {
        eval("exp = /oxo" + stub + "oxo/g");
        mask = mask.replace(exp, token[r]);
    	stub++;       
    }
    
    return mask;    
}

/*
===========================================

	NUMBER FORMATING UTILITY

===========================================
*/


// return number in specified format
function NumberFormat(numbervalue, mask) {
	
    mask = (mask) ? mask : "none";
    if (mask == 'none' || mask == 'normal') mask = numbervalue;
    if (mask == 'storage') {
    	qused = numbervalue;
		qused = qused / 1024;
		if (qused < 0 || qused < 1024) {
			qused = qused.toFixed(2)+' KB';
		} else {
			if (qused > 1024) {
				qused = (qused / 1024);
				if (qused  > 1024) {
					qused = qused.toFixed(2)+' GB';
				} else {
					qused = qused.toFixed(2)+' MB';
				}
			} else {
				qused = qused.toFixed(2)+' MB';
			}
		}
		mask = qused;
	}
	if (mask == 'comma') {
		if (!numbervalue || numbervalue == null) numbervalue = 0;
		numbervalue = parseFloat(numbervalue);
		numbervalue = numbervalue.toFixed(2);
		var nStr = String(numbervalue);
		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');
		}
		mask = (x1 + x2);

	}
	if (mask == 'nodecimal') {
		if (!numbervalue || numbervalue == null) numbervalue = 0;
		numbervalue = parseInt(numbervalue);
		//numbervalue = numbervalue.toFixed(2);
		var nStr = String(numbervalue);
		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');
		}
		mask = (x1 + x2);

	}
	
    
    return mask;    
}


/*
===========================================

	STRING FORMATING UTILITY

===========================================
*/
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.crumbs = function(crumb_drops) {
	var st = '';
	var arr = this.split(',',crumb_drops);
	if (arr.length) {
		var cc = '';
		for(var z=0;z<arr.length;z++) {
			st += cc + arr[z];
			cc = ',';
		}
		if (arr.length > crumb_drops) st += ' ...';
	}
	return st;
}
