var DLG_CALENDAR = "center:yes; dialogHeight:210px; dialogWidth:144px; help:no; resizable:yes; status:no; title:no";  
var DLG_TEXT_EDIT = "center:yes; dialogHeight:800px; dialogWidth:730px; help:no; resizable:yes; status:no; title:no";  

var aMonth = new Array('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC');

String.prototype.lPad = function (n,c) {if (c == null) {c = " ";} var i; var a = this.split(''); for (i = 0; i < n - this.length; i++) {a.unshift (c)}; return a.join('')}
String.prototype.rPad = function (n,c) {if (c == null) {c = " ";} var i; var a = this.split(''); for (i = 0; i < n - this.length; i++) {a.push (c)}; return a.join('')}

function StripPin(pin) {
	var re = new RegExp(gStripRegexString, "g"); 
	//Note: gStripRegexString must be defined on a caller's ASPX page as: 
	//var gStripRegexString="<%=Akanda.Teeam.Pin.StripRegexString%>";
	var ret = pin.replace(re, "");
	return ret;	
}

function SetInputMask(inp, mask) {
	if (mask == null) return;
	var l = mask.length;
	if (l < 1) return;
	if (inp.name == null) inp = eval(inp);
	inp.size = l-1;
	inp.maxLength = l;
	inp.Mask = mask;
	inp.ErrorMessage = "Invalid Input"; 
	inp.PromptChar = "_"; 
	inp.onkeydown = new Function("return al_MaskedTextBox_doKeyDown(this,event)"); 
	inp.onmouseup = new Function("return al_MaskedTextBox_doMouseUp(this,event)"); 
	inp.oncontextmenu = new Function("return false"); 
	inp.onblur = new Function("return al_MaskedTextBox_doBlur(this)"); 
	inp.onkeypress = new Function("return al_MaskedTextBox_doKeyPress(this,event)"); 
	inp.onfocus = new Function("return al_MaskedTextBox_doFocus(this)"); 
	inp.ondragenter = new Function("return false"); 
	inp.onselect = new Function("return al_MaskedTextBox_doSetCaretPosition(this)");
	
	ApplyMask2Value(inp);
}

function ApplyMask2Value(c) {
	var prom = c.PromptChar;
	var s = c.value.replace(prom, " ");
	c.value = "";
	al_MaskedTextBox_doFocus(c);
	var mv = c.value;
	var ar = mv.split("");
	var N = ar.length;
	var n = 0;
	for (var i=0; i<N; i++) {
		var ch = ar[i];
		if (ch == prom) {
			n++; //count prompts
		} else {
			s = s.replace(ch, ""); //remove all mask symbols
		}	
	}
	if (s.length != n) {
		if (s.length < n) s = s.lPad(n);
	}	
	var k = 0;
	for (var i=0; i<N; i++) {
		if (ar[i] == prom) ar[i] = s.charAt(k++);
	}
	c.value = ar.join("");
}


function ApplyMask2Value_old(c) {
	if (c.Mask == null) return;
	if (c.Mask != "90:00") return; //for now only supports "90:00" mask, TBD
	var v = trim(c.value);
	var l = v.length;
	if (l < 1) return;
	if (l < 3) {
		v = "0:" + v;
	} else {
		if (l < 4) v = " " + v;
		v = v.substr(0,2) + ":" + v.substr(2);
	}	
	c.value = v;
}

function OpenIMEdit(param) {
	var url = "../Maintain/SelectTransForEdit.aspx?frameset=1&" + param;
	var dlg = "center:yes; dialogHeight:500px; dialogWidth:500px; help:no; resizable:yes; status:no; title:no";
	var iMUrl = window.showModalDialog(url, null, dlg);
	if (iMUrl != null) {
		var s = "fullscreen=no, titlebar=no, location=no, menubar=no, toolbar=no, resizable=yes, scrollbars=yes, status=yes, titlebar=yes"; 
		window.open(iMUrl, null, s);
	}
}

function Xml_GetNodesTotal(nodeList) {
	if (nodeList == null) return 0;
	var sum = 0;
	for (var i=0; i<nodeList.length; i++) {
		if(nodeList[i]) {
			var v = parseFloat(nodeList[i].text);
			if (isNaN(v)) v = 0;
			sum += v;
		}
	}
	return sum;
}

function GetRelativeUrl(url, depth) {
	if (url == null) url = location.href;
	if (url.toLowerCase().indexOf(location.pathname.toLowerCase()) != 0) return url;
	if (depth == null) depth = 2;
	var ar = url.split("/");
	var N = ar.length - depth;
	var res = "";
	for (var i=ar.length-1; i>=N; i--) {
		if (res == "") {
			res = ar[i];
		} else {	
			res = ar[i] + "/" + res;
		}	
	}
	res = "../" + res;
	return res;
}

function ExpColSectionSimple(img) {
	var row = img.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
	var sect = row.nextSibling;
	if (sect == null) return;
	if (img.exp) {
		img.exp = false;
		sect.style.display = "block";
		img.src = img.src.replace("Expand", "Collapse");
	} else {
		img.exp = true;
		sect.style.display = "none";
		img.src = img.src.replace("Collapse", "Expand");
	}

}

function GetAbsoluteUrl(url, depth) {
	if (url == null) url = location.href;
	if (depth == null) depth = 2;
	var ar = url.split("/");
	var N = ar.length - depth;
	var res = "";
	for (var i=0; i<N; i++) {
		if (res == "") {
			res = ar[i];
		} else {
			res += "/" + ar[i];
		}	
	}
	return res;
}

function getBaseURL() {
	var ret = unescape(location.href).replace(unescape(location.pathname), "").split('?')[0];
	return ret;
}

function QSEncode(s) {
	var ret = s.replace(/\=/g, "%3d").replace(/\?/g, "%3f").replace(/\&/g, "%26");
	return ret;
}

function TruncateMultipleSpaces(s) {
	//replace multiple spalce with a single space
	var ret = s.replace(/\s+/g, " ");
	return ret;
}

function TruncateFormMultipleSpaces(frm) {
	var els = frm.elements;
	for (var i=els.length-1; i>=0; i--) {
		var el = els[i];
		switch (el.type) {
			case "text" :
			case "hidden" :
				el.value = TruncateMultipleSpaces(el.value);
				break;
		}
	}
}

function SetSessionValue(key, val) {
	var pars = SoapBuildInputParam("key", key);
	pars += SoapBuildInputParam("val", val);
	var res = SoapInvokeService(WS_TRANS_SERVICE, "SetSession", pars, true);
}

function PopupHelp(url) { 
	var x = 0, y = 0; // default values 
	var width = 0, height = 0; // default values 
	if (document.all) { 
		y = window.screenTop; 
		height=document.body.clientHeight-5; 
		var deltax=0.20*(document.body.clientWidth); 
		x = window.screenLeft+deltax; 
		width=document.body.clientWidth-deltax+10; 
	} 
	var popup = window.open(url,'popup','width='+width+',height='+height+',top='+y+',left='+x+',resizable=yes'); 
} 

function GetRowNumber(r) {
	var tbl = r.parentElement.parentElement;
	var rws = tbl.rows;
	for (var i=0; i<rws.length; i++) {
		var rw = rws[i];
		if (rw == r) {
			return i;
		}
	}
	return -1;
}

function showHelp(module) {
	var DLG_SETMYHELP = "dialogHeight:700px;dialogWidth:800px;status:yes;toolbar:no;menubar:no;location:no;resizable:yes;scroll:yes;titlebar:no";
	var isDefault = document.all.hdDefHelp;
	if (isDefault && isDefault.value == "0") {
		var fileName = document.all.hdThisFile;
		if (fileName)
			window.showModelessDialog("../Help/HelpDialog.aspx?page=" + fileName.value, null, DLG_SETMYHELP);		
	}
	else {
		if(module)
			PopupHelp('../Help/Help.aspx?module='+module);
		else
			PopupHelp('../Help/Help.aspx');
	}
}

function FindInArray(ar, val) {
	var N = ar.length;
	for (var i=0; i<N; i++) {
		if (ar[i] == val) return i;
	}
	return -1;
}




function EditTextDialog(text, width, height) {
	if (width == null) width = "400px";
	if (height == null) height = "400px";
	var url = "../Forms/DlgTextEdit.aspx";
	var dlg = "center:yes; dialogHeight:" + height + "; dialogWidth:" + width + "; help:no; resizable:yes; status:no; title:no";  
	var o = new Object();
	o.innerHTML = text;
	var ret = window.showModalDialog(url, o, dlg);
	return ret;
}

function SetBtnDisabled(btn, mode, noDisable) {
	if (btn.length != null) btn = document.all(btn);
	if (btn == null) return;
	try {
	if (mode && noDisable == true) {
		//skip
	} else {
		btn.disabled = mode;
	}
	//btn.style.filter = (mode) ? "progid:DXImageTransform.Microsoft.emboss()" : ""; 
	btn.style.filter = (mode) ? "alpha(opacity='40')" : "";
	} catch(e) {}
}

function ShowAttributes(el) {
	var s = el.tagName + "\n";
	for (var i=0; i<el.attributes.length; i++) {
		var at = el.attributes[i]; 
		if (at.value != null && at.value != "" && at.value != "null") { 
			s += at.name + "=" + at.value + "\n";
		}	
	} 
	alert(s);
}

function GetToday() {
	var d = new Date();
	return d.getDate()+ "-" + aMonth[d.getMonth()] + "-" + d.getYear();
}

function GetYear() {
	var d = new Date();
	return d.getYear();
}

function FormatDateDb(val) {
	if (val == null || val.length < 6) return null;
	val = val.toUpperCase();
	var fmt = 0;
	if (val.indexOf('-') > 0) {
		fmt = 1;
	} else {
		if (val.indexOf('/') > 0) fmt = 2;
	}
	var aDate, d, m, y;
	try {
	switch (fmt) {
		case 0 : //MMDDYYYY
			m = new Number(val.substr(0,2));
			d = new Number(val.substr(2,2));
			y = parseInt(val.substr(4,4),10);
			break;
		case 2 : //MM/DD/YYYY
			aDate = val.split('/');
			m = new Number(aDate[0]);
			d = new Number(aDate[1]);
			y = parseInt(aDate[2].substr(0,4),10);
			break;			
		case 1 : //DD-MON-YYYY'
			aDate = val.split('-');
			d = new Number(aDate[0]);
			m = GetMonth(aDate[1]);
			m++;
			y = parseInt(aDate[2].substr(0,4),10);
			break;
	}
	} catch(e) {
		return null;
	}
	if (y < 100) {
		if (y < 20) {
			y += 2000;
		} else {
			y += 1900;
		}
	}
	
	if (isNaN(m) || m<1 || m>12 || isNaN(d) || d<1 || d>31 || isNaN(y) || y<1000 || y>10000) return null;
	
	var sDate = m + "/" + d + "/" + y;
	var dt = new Date(sDate);
	if (dt.getDate() != d) return null;
	
	if (d<10) d = "0" + d;
	var ret = d + "-" + aMonth[m-1] + "-" + y; 
	return ret;
}
	


function Date2Number(val) {
	if (val == null || val.length < 5) return 0;
	val = val.toUpperCase();
	var fmt = 0;
	try {
	if (val.indexOf('-') > 0) {
		fmt = 1;
	} else {
		fmt = 0;
	}
	var aDate, d, m, y;
	switch (fmt) {
		case 0 : //MM/DD/YYYY
			aDate = val.split('/');
			m = parseInt(aDate[0]);
			d = parseInt(aDate[1]);
			y = parseInt(aDate[2].substr(0,4));
			break;			
		case 1 : //DD-MON-YYYY'
			aDate = val.split('-');
			d = parseInt(aDate[0]);
			m = GetMonth(aDate[1]);
			y = parseInt(aDate[2].substr(0,4));
			break;
	}
	var ret = (10000*y - 10000000) + 100*m + d;
	return ret;
	} 
	catch(e) {
		//alert('Exception occurred');
		return 0;
	}
}

function GetMonth(val) {
	var N = aMonth.length;
	val = val.toUpperCase();
	for (var i=0; i<N; i++) {
		var m = aMonth[i];
		if (m == val) return i;
	}
	return 0;
}

function EnforceCollection(el) {
	if (el == null) return null;
	if (el.length) {
		return el; //ok, it's already a collection
	} else {
		//make it collection:
		var ar = new Array();
		ar[0] = el;
		return ar;
	}	
}

function PickDate(elName, showInput, title, upperCase) {
	var el = null;
	if (elName == null && event != null && event.srcElement != null) {
		el = event.srcElement.previousSibling;
		if (el.tagName != "INPUT") el = el.previousSibling;
	} else {
		el = document.all(elName);
	}
	/*	
	if (!el) {
		alert('Document element not found: "' + elName + '"');
		return "";
	}
	*/
	var val = (el == null) ? "" : el.value;
	var opt = DLG_CALENDAR;
	if (showInput) {
		val += "~" + ((title == null) ? "" : title);
		opt = opt.replace(/dialogHeight:[0-9]+px;/, "dialogHeight:280px;");
	}
	var ret = window.showModalDialog("../Common/calendar.htm", val, opt);
	if (ret) {
		if (upperCase) ret = ret.toUpperCase();
		el.value = ret;
		el.focus();
	}
	return ret;
}

function trim(s) {
	return s.replace(/^\s*|\s*$/g,"");
}

function trimValue(el) {
	el.value = trim(el.value);
}

function replaceAll(s, s1, s2)
{
	while(s.indexOf(s1) != -1)
	{
		s = s.replace(s1, s2);
	}
	return s;
}


var lastWinName = "pop";
function debugPrint(s, title, msg, err, winName) {
	if (!winName) winName = lastWinName;
	var ww = open("", winName);
	try {
	 if (title) {
		title = "<h2><font color=red>" + title + "</font></h2>";
		ww.document.write(title + msg + '<br><div id="errPointer" style="font-size:10px; color:blue; font-family: Courier New, 10px;  width:100%"></div><hr color=red>');
	 }	
	 ww.document.write('<div id="htmlSource" style="color:black; width:100%"></div>');
	 ww.document.close();
	} catch(e) {
		lastWinName = winName + "1";
		debugPrint(s, title, msg, err, lastWinName); //correct - possible infinite error handling loop :TODO:
		return;
	} finally {
		//return;
	}
	if (title && err) {
		ww.document.all("errPointer").innerText = err;
	}
	ww.document.all("htmlSource").innerText = s;
	ww.focus();
}

function ShowListTip(sel, codeShown) {
	var k = sel.selectedIndex;
	if (k >= 0) {
		var opt = sel.options[k];
		var s = (codeShown || (opt.text.indexOf(":") >= 0)) ? opt.text : opt.value + ": " + opt.text;
		window.status = s;
	}
}


function OverBtn(btn) {
	btn.oldBorder = btn.style.border;  
	btn.style.border='white 1px outset';
}

function OutBtn(btn) {	
	btn.style.border = btn.oldBorder;
}

function ReplaceUrl(url, par, val) {
	var ret;
	var pp = par + "=" + val;
	var ar = url.split('?');
	if (ar.length > 2) {
		alert("Invalid URL: " + ar.length + " '?' symbols:\n" + url); 
		return url;
	}
	if (ar.length > 1) {
		var qs = ar[1];
		var k = qs.indexOf(par + "=");
		var k3 = k + par.length + 1;
		if (k < 0) {
			ret = ar[0] + "?" + qs + "&" + pp;
		} else {
			var v;
			var k2 = qs.indexOf('&', k);
			if (k2 < 0) {
				v = qs.substring(k3, qs.length);
			} else {
				v = qs.substring(k3, k2);
			}
			ret = ar[0] + "?" + qs.replace(par + "=" + v, pp);
		}
	} else {
		ret = url + "?" + pp;
	}
	return ret;
}




//list key-in
var gKeyedString = "";
var gKeyStringReset = null;
var keyInResetTimeout = 700;
var keyInKey = "keyinvalue";

function KeyListValue(list, section) {
	if (event.altKey) return; 
	var code = event.keyCode;
	if (code == 9 && section != null) {
		ExpandSection(section);
		return;
	}
	
	if (code == 46) { //Del 
		if (list.options.length > 0 && list.options[0].value == "") list.selectedIndex = 0;
		return;
	}
	
	if (code != 8 && (code <= 40 || code > 255) ) {
		//alert(code); //TODO: key code is not the same as String.fromCharCode
		ResetKeyedString(list);
		return;
	}
	
	if (code == 110) code = 46; //"dot" on numeric pad
	else if (code >= 112 && code <=123) return; //F-keys
	else if (code > 175) code = code - 144;	//"dot" has code 190 instead of 46 (46 is on numeric pad)
	else if (code > 95) code = code - 48; //numeric pad

	//alert(code + ":" + String.fromCharCode(code));
	
	//alert(list.selectedIndex);
	//event.cancelBubble = true;
	window.clearTimeout(gKeyStringReset);
	gKeyStringReset = window.setTimeout("ResetKeyedString(frmMain." + list.name + ")", keyInResetTimeout);
	//window.status = event.keyCode;

	if (gKeyedString.length < 1) {
		list.lastSelIndex = list.selectedIndex;
		list.match = false;
	}
	
	if (code == 8) { 
		window.event.cancelBubble = true;
		window.event.returnValue = false;
		var N = gKeyedString.length;
		if (N > 0) {
			gKeyedString = gKeyedString.substr(0, N-1);
		}
	} else {
		var ch = String.fromCharCode(code).toUpperCase();
		gKeyedString += ch;
	}
	window.status = gKeyedString;
	ShowKeyedValue(list, gKeyedString)
	//alert(list.selectedIndex);
	//window.setTimeout("SetPrevious(frmMain." + list.name + ")", keyInTimeout);
}

function ShowKeyedValue(list, val) {
	try {
	  //alert(list.maxwidth); 
	  if (val.length > list.maxwidth) return; // to prevent uncontroled the list width increasing when you hold a key.
	} catch(e) {}
	var N = list.options.length - 1;
	var o = list.options[N];
	if (o.value != "keyinvalue") {
		var opt = new Option(val, keyInKey);
		list.options.add(opt);
	} else {
		o.text = val;
	}
	list.selectedIndex = N;
}

function SetPrevious(list) {
	if (list.lastSelIndex != null) list.selectedIndex = list.lastSelIndex;
	list.match = false;
}

function ResetKeyedString(list) {
	SelectListItemByValue(list, gKeyedString);
	gKeyedString = "";
	if (list == null || list.options == null) return;
	var N = list.options.length - 1;
	var o = list.options[N];
	if (o.value == keyInKey) {
		list.options.remove(N);
	}
}

function SelectListItemByValue(list, val) {
	if (list == null || val == "") return;
	var opts = list.options;
	if (opts == null) return;
	var N = opts.length;
	list.match = false;
	for (var i=0; i<N; i++) {
		var opt = opts[i];
		var v = opt.value;
		if (v.indexOf(val) == 0) {
			var exact = (v == val);
			if (!list.match || exact) { 
				list.selectedIndex = i;
				list.lastSelIndex = i;
				if (exact) {
					ShowListTip(list, true);
					return;
				}	
				list.match = true;
			}
		}
	}
	if (!(list.match)) SetPrevious(list);
	ShowListTip(list, true);
	return;
}


function blinkIt() {
 if (!document.all) return;
 else {
   for(i=0; i < document.all.tags('blink').length; i++){
      s=document.all.tags('blink')[i];
      s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
   }
 }
}

//used with onkeypress handler:
function CheckKeyInteger() {
	var k = event.keyCode;
	if (k < 48 || k > 57) {
		event.returnValue = false;
	}	
}

function CheckKeyFloat() {
	var k = event.keyCode;
	if (k != 45 && k != 46 && (k < 48 || k > 57)) {
		event.returnValue = false;
	}	
}

function EnforceUpperCase(el) {
	if (el == null) el = event.srcElement;
	var code = event.keyCode;
	if (code > 96) {
		event.keyCode = code - 32;
	}
	//event.returnValue = false;
}

function GetElementIndex(el) {
	var all = document.all(el.id);
	if (all == null) all = document.all(el.name);
	if (all == null) return -1;
	for (var i=all.length-1; i>=0; i--) {
		if (all[i] == el) return i;
	}
	return -1;
}

function GetElementByIndex(name, index) {
	var all = document.all(name);
	if (all == null || all.length == null) return null;
	return all[index];
}


function SetTempCookie(name, value) {
	var cook = name + "=" + value;
	document.cookie = cook;
}


function GetCookie(name) {
	var prefix = name + "="
	var source = source = document.cookie;
	var startIndex = source.indexOf(prefix)
	if (startIndex < 0) return null;
	var endIndex = source.indexOf(";", startIndex + prefix.length);
	if (endIndex < 0) endIndex = source.length;
	var ret = source.substring(startIndex + prefix.length, endIndex);
	if (ret == null) ret = '';
	return ret;
}

function OpenNewWin(para,h,w,l,t,features) {
	if ((l!='') && (t!='') && (features!='')) {
		window.open(para, "", "resizable=yes,scrollbars=yes,height=" + h + ",width=" + w + ",left=" + l + ",top=" + t + ",features=" + features);
	}
	else window.open(para, "", "resizable=yes,scrollbars=yes,height=" + h + ",width=" + w + ",left=200,top=70");
	return;
}


//----------------------------------------------------
// NAVIGATION CONTROL
//----------------------------------------------------

//----- Prompt Box, works for IE ONLY
/*
// msgbox constants for javascript, if you want to use them: 
var vbOKOnly=0, vbOKCancel=1, vbAbortRetryIgnore=2, vbYesNoCancel=3, vbYesNo=4, vbRetryCancel=5
var vbCritical=16, vbQuestion=32, vbExclamation=48, vbInformation=64
var vbDefaultButton1=0, vbDefaultButton2=256, vbDefaultButton3=512, vbDefaultButton4=768
*/

var strMsgboxPath = '..\\Script\\'; 
var vbOK=1, vbCancel=2, vbAbort=3, vbRetry=4, vbIgnore=5, vbYes=6, vbNo=7;
function msgbox(prompt, buttons, title, helpfile, context){
	if(!window.showModalDialog){	
		//return 'Error: This web browser does not support window.showModalDialog';	
		return MsgBox(pompt, vbYesNoCancel);
	}

	// guess at height (based on # of line-breaks) 
	var h = 2;
	if(prompt.search(/\r\n/g)!=-1){h = prompt.match(/\r\n/g).length+1;}
	h = 110 + (h*12.5);	// base-110px + 12.5px/line

	// guess at width (based on longest line's char-count)
	var w = 30;
	if(prompt.search(/[^\r\n]*[\r\n]?/gm)!=-1){
		var lines = prompt.match(/[^\r\n]*[\r\n]?/gm);
		for(var l=0; l<lines.length; l++){
			if(lines[l].length>w){w=lines[l].length};
		}
	}
	w-=30;
	if(w<0){w=0};
	w = 220 + (w*7.5);	// base 210px + 7.5px/char
	
	var strFeatures = 'dialogHeight:' + h + 'px; dialogWidth:' + w + 'px; scroll:no; status:no; help:no; resizable:no;';
	//return showModalDialog(strMsgboxPath + 'msgBox.htm?' + new Date(), arguments, strFeatures);	// debug ver
	return showModalDialog(strMsgboxPath + 'msgBox.htm', arguments, strFeatures);	// fast live ver
}
//----- Prompt Box, works for IE ONLY


