var gsBaseUrl = "/";

function setBaseUrl(sBaseUrl){
	gsBaseUrl = sBaseUrl;
}
function getBaseUrl() {
	return gsBaseUrl;
}
function formatUrl(sUrl){
	return (getBaseUrl() + (sUrl || ""));
}

function isEnter(){
	return (event.keyCode == 13);
}

function isEsc(){
	return (event.keyCode == 27);
}

function isLookup(){
	return (event.keyCode == 113);
}

function getIsValidDate(el, bAllowBlank){
	var d = el.value;
	var sep = "/";

	if(d == "" && bAllowBlank)
		return true;

	d = d.split(sep);

	if(d.length != 3)
		return false;

	var mon = d[0], day = d[1], yr = d[2];
	
	// check length and type of each value
	if(day.length > 2 || mon.length > 2 || yr.length > 4 || isNaN(day) || isNaN(mon) || isNaN(yr))
		return false;

	// check year
	yr = Number(yr);
	if(String(yr).length < 4)
		yr += (yr < 50) ? 2000 : 1900;
	// check month
	mon = Number(mon);
	if(mon < 1 || mon > 12)
		return false;
	// check day
	day = Number(day);
	if(day < 1 || day > getDaysInMonth(mon, yr))
		return false;
	
	// set the proper date format
	el.value = (mon + sep + day + sep + yr);
	return true;
}

// returns the number of days for a given month
function getDaysInMonth(mon, yr)  {
	var i = 31;

	if(mon==4 || mon==6 || mon==9 || mon==11)
		i = 30;
	else if(mon==2)
		i = getIsLeapYear(yr) ? 29 : 28;

	return i;
}

// check if a year is a leap year
function getIsLeapYear(yr) {
   return ((yr % 4 == 0) && (yr % 100 != 0 || yr % 400 == 0));
}

function isValidEmail(el, bAllowBlank){
	var val = trim(el);
	var i, bRet = true;

	if(val == "" && bAllowBlank)
		return true;
	
	var emails = val.split(',');
	for(var i=0;i<emails.length;i++) {
		if(!(emails[i].match(/^[\w\.-]+@[\w\.-]+\.[a-zA-Z]+$/)))
			return false;
	}

	return true;
}

String.prototype.trim = function(){
	var s = this.replace(/^\s*/, "");
	return s.replace(/\s*$/, "");
}

String.prototype.xmlEncode = function(){
	var str = this;
	var ret = "";
	var c;

	for(var i=0; i<str.length; i++) {
		c = str.charAt(i);

		if(c == '&')
			ret += "&amp;";
		else if(c == '<')
			ret += "&lt;";
		else if(c == '>')
			ret += "&gt;";
		else
			ret += c;
	}

	return ret;
}

function isValidCCNum(sNum) {
	var bRet = true;
	var sTest = sNum.replace(/-/g, "");// strip out dashes, if necessary
	
	// 16 digits
	if(sTest.length != 16 || isNaN(parseInt(sTest))) {
		bRet = false;
	}

	return bRet;
}

// validates short dates in a mm/yyyy format
function isValidShortDate(sDate) {
	var bRet = true;
	var aVals = sDate.split(DELIM_DATE);
	var iLen = aVals.length;
	
	if(iLen != 2) {
		bRet = false;
	}
	else {
		var iMo = parseInt(aVals[0]);
		var iYr = parseInt(aVals[1]);
		if(isNaN(iMo) || isNaN(iYr) || (iMo<1 || iMo>12) || (iYr<1900)) {
			bRet = false;
		}
	}
	
	return bRet;
}

function setTrimValue(el){
	return trim(el);
}

function trim(el){
	el.value = el.value.trim();
	return el.value;
}

function setFocus(el, str){
	if(str) alert(str);
	// make sure it is not hidden
	if(el.focus && el.offsetWidth > 0) el.focus();
	else if(el.scrollIntoView) el.scrollIntoView();
	if(el.select) el.select();
	return false;
}

Date.prototype.getMonthName = function(){
	var a = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	return a[this.getMonth()];
}

Date.prototype.getDateFormat = function(){
	return ((this.getMonth()+1) + "/" + this.getDate() + "/" + this.getFullYear());
}

function setDatePicker(el){
	var name = el.form.name + "[\"" + el.name + "\"]";
	var s = "<IMG SRC=\"" + getBaseUrl() + "mcimages/iconCalendar.gif\" BORDER=0 ONCLICK=getDatePicker(" + name + ") STYLE='margin-left:2px;cursor:hand;' ALT='Click to use calendar'>";
	el.insertAdjacentHTML("afterEnd", s);
}

function getDatePicker(el){
	var date = getIsValidDate(el) ? el.value : new Date().getDateFormat();
	var args = { "date" : date };

	if(showModalDialog(getBaseUrl() + "mclib/dlgDatePicker.asp", args, "dialogHeight:180px;dialogWidth:200px;resizable:no;status:no;help:no;")) {
		el.value = args.date;
		el.select();
		el.focus();
	}
}

function setDatePickers(el){
	if(el) {
		var elem = (typeof(el.length) != "undefined") ? el : [el];
		for(var i=0; i<elem.length; i++)
			setDatePicker(elem[i]);
	}
}

function getCheckedRadio(oEl){
	if(oEl) {
		var elem = (oEl.length) ? oEl : [oEl];

		for(var i=0; i<elem.length; i++) {
			if(elem[i].checked)
				return elem[i];
		}
	}
	else
		return null;
}

function getCheckedValues(oElx, sParam, sDelim) {
	var sRet = "";
	if(oElx) {
		var oEl = (oElx.length)? oElx : [oElx];
		for(var i=0; i<oEl.length; i++) {
			if(oEl[i].checked)
				sRet += ((sRet != "") ? (sDelim || "") : "") + eval("oEl[i]." + (sParam || "value"));
		}
	}
	return sRet;
}

function setArgValsFromChkItems(aArgs, oCol){
	if(oCol) {
		var rdo = getCheckedRadio(oCol);

		if(rdo) {
			var elem = getParent(rdo, "TD").all.tags("INPUT");
			var el;

			for(var i=0; i<elem.length; i++) {
				el = elem[i];

				if(el.id == "dbCol")
					aArgs[el.name] = el.value;
			}
			return true;
		}
	}
	return false;
}

function selectAll(oElx){
	if(oElx) {
		var bSel = (getCheckedValues(oElx) == "");
		var elem = (oElx.length) ? oElx : [oElx];
		
		for(var i=0; i<elem.length; i++)
			elem[i].checked = bSel;
	}
}

// checkbox funcs

function getCheckedChkBoxes(oEl) {
	var aRet = [];
	if(oEl) {
		var elem = (oEl.length) ? oEl : [oEl];
		var iLen = elem.length;

		for(var i=0; i < iLen; i++) {
			if(elem[i].checked)
				aRet[aRet.length] = elem[i];
		}
	}

	return aRet;
}

function getNumChkBoxItems(oCol) {
	var iRet = 0;
	var iLen = oCol.length;

	for(var i=0; i < iLen; i++) {
		if(oCol[i].type.toUpperCase() == "CHECKBOX" && oCol[i].checked) {
			iRet++;
		}
	}

	return iRet;
}

// makes a comma-separated list for each input in the same TD as the collection of passed elems;
// each list is stored in an associative array with keys derived from the inputs' name attrib
function setArgValsFromChkBoxItems(aArgs, oCol, sDelimRaw) {
	var bRet = false;
	var iLen = oCol.length;
	var sDelim = (sDelimRaw)? sDelimRaw : ",";
	if(iLen) {
		var elem, el;

		for(var j=0; j < iLen; j++) {
			elem = getParent(oCol[j], "TD").all.tags("INPUT");
			
			for(var i=0; i < elem.length; i++) {
				el = elem[i];

				if(el.id == "dbCol") {
					if(!aArgs[el.name]) aArgs[el.name] = "";// create if necessary
					aArgs[el.name] += (aArgs[el.name])? sDelim + el.value : el.value;
				}
			}
			bRet = true;
		}
	}
	return bRet;
}
// end checkbox funcs


function getParent(el, tag){
	while(el && el.tagName != tag)
		el = el.parentElement;
	return el;
}

function getXML(sql, sPath){
	var http = new ActiveXObject("Microsoft.XMLHTTP");
	http.Open("POST", (sPath || (getBaseUrl() + "mclib/GetXML.asp")), false);
	http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http.Send("sql=" + escape(String(sql).xmlEncode())); //debugEx(http.responseText);
	return http.responseXML;
}

function getNewXmlDOM() {
  var xmlRet = null;

  try {
	  xmlRet = new ActiveXObject("Msxml2.DOMDocument");
	  xmlRet.setProperty("SelectionLanguage", "XPath");
  }
  catch(e) {
	  try {
		  xmlRet = new ActiveXObject("Microsoft.XMLDOM");
	  }
	  catch(e) {
		  alert("Error in getNewXmlDOM(): " + e);
	  }
  }
  
  if(xmlRet != null) {
	  xmlRet.async = false;
	  xmlRet.validateOnParse = false;
  }

  return xmlRet;
}

function getXMLEx(sql){
	return getXML(sql).documentElement;
}

// custom func to ensure an empty string is returned instead of null
function getNodeAttribute(xNode, sAttrib) {
	return (xNode.getAttribute(sAttrib) || "");
}

function debug(s, type){
	with (open()) document.body["inner" + (type || "HTML")] = s;
}

var g_bDebugFlag = true;

function debugEx(sText, sParam){
	if(!g_bDebugFlag) return;

	try {
		var console = window.open("", "DebugConsole", "width=" + (screen.availWidth-30) + ",height=300,top=" + (screen.availHeight-350) + ",left=10,resizable=1,scrollbars=1");
		   
		with(console.document.body) {
			if(!console.g_bStyles) {
				console.document.title = "JM Debug Console";

				style.margin = "0 10 20 10";
				style.font = "normal 12px Lucida Console, Courier New";

				console.g_bStyles = true;
			}

			insertAdjacentText("afterBegin", "\n\n" + sText);
			insertAdjacentText("afterBegin", "\n\n------ " + " ------ window: " + this.name + " ------ param: " + sParam + " ------");
		}
	}
	catch(e) {
		//this.debug(sText, sParam);
	}
}

function setDebug(b){
	g_bDebugFlag = b;
}

document.onkeydown = function() {
	if(event.srcElement.tagName.toUpperCase() != "TEXTAREA") {
		if(isEnter()) {
			if(window.validateForm)
				validateForm();
		}
	}
}

function setDlgKeys(hFunc){
	document.onkeydown = function(){
		if(isEnter())
			hFunc(true);
		else if(isEsc())
			hFunc(false);
	}
}

// window funcs
function configWin(w, h, bCenter, sParams){
	var s = "width=" + w + ",height=" + h + ",resizable=1,scrollbars=1,";

	if(bCenter)
		s += "left=" + (screen.availWidth/2 - w/2) + ",top=" + (screen.availHeight/2 - h/2) + ",";
	
	return (s + (sParams || ""));
}
function configDlg(w, h, sParams){
	return "dialogWidth:" + w + "px; dialogHeight:" + h + "px; scrolling=no;help:no;status:no;" + (sParams || "");
}
function cfgWin(w, h, bCenter, sParams){
	return configWin(w, h, bCenter, sParams);
}
function cfgDlg(w, h, sParams){
	return configDlg(w, h, sParams);
}
function cfgWinMax(){
	return cfgWin(screen.availWidth-10, screen.availHeight-45, false, "left=0,top=0");
}
function maximize(){
	window.moveTo(0,0);
	window.resizeTo(screen.availWidth, screen.availHeight);
}
// end window funcs

// sets the cursor style of a passed element, or the body if none is passed
function setCursor(sWhich, oElRaw) {
	var oEl = (oElRaw || document.body);

	switch(sWhich) {
	case "auto","crosshair","default","hand","wait":
		break;

	default:
		sWhich = "default";
		break;
	}
	oEl.style.cursor = sWhich;
}

// passes back an array the has the name/values of the search/query part of a url
// contents are associative w/ the name as the key and index-based, too
function getUrlInfo(sUrl) {
	var aRet = [];// associative array to hold vals w/ the name as the key
	var sUrlSearch = "";
	var bHasSearch = true;

	if(sUrl) {
		var iIdx = sUrl.indexOf("?");
		if(iIdx >= 0) {
			sUrlSearch = sUrl.slice(iIdx + 1);
			if(!sUrlSearch) { bHasSearch = false; }
		}
		else { bHasSearch = false; }
	}
	else {// default to current window's location
		if(window.location.search && (window.location.search.length > 1) ) {
			sUrlSearch = window.location.search.slice(1);// the slice rids the '?' from the string
		}
		else { bHasSearch = false; }
	}

	if(bHasSearch) {
		var aTmp = sUrlSearch.split("&");// puts name/val pairs into array
		var aTmp2;
		for(var i=0; i<aTmp.length; i++) {
			aTmp2 = aTmp[i].split("=");// now make the name and val each an element in an array
			aRet[i] = aTmp2;// for index-based, each index holds array
			aRet[aTmp2[0]] = aTmp2[1];// for associative, val uses name as key
		}
	}

	return aRet;
}

// if an obj is an array, return it; otherwise put it into an array before returning it
function getAsArray(o) {
	var aRet = o;
	// special case because SELECT element has a 'length' property (for the options) even thought it's one element
	if(o.tagName && o.tagName.toUpperCase() == "SELECT") aRet = [o];
	return (aRet.length)? aRet : [aRet];
}

function getFullNameFromId(iUserIdRaw) {
	var iUserId = (typeof(iUserIdRaw) == "string")? parseInt(iUserIdRaw) : iUserIdRaw;
	var sRet = "";
	var sSql = "SELECT FirstName,LastName FROM Users WHERE UserId=" + iUserId + " FOR XML RAW";
	var xNode = getXML(sSql).documentElement.selectSingleNode("./row");
	sRet = getNodeAttribute(xNode,"FirstName") + " " + getNodeAttribute(xNode,"LastName");
	return sRet;
}

function putHtmlTemplate(xTemplate, oCont) {
	oCont.innerHTML = xTemplate.documentElement.text;
}

function cdbStr(str) {
	var s = str.trim();

	if(s == '') return "NULL";
	return "'" + s.replace(/[']/g, "''") + "'";
}

// search results funcs
function onQuickSearch() {
	scrollFirst();
}
function scrollFirst() {
	frm.txtStartRec.value = '1';
	frm.submit();
}
function scrollPrev() {
	frm.txtStartRec.value = frm.txtStartRec.value - (frm.rdoNumRecs.value * 2);
	frm.submit();
}
function scrollNext(){
	frm.submit();
}
function scrollLast() {
	frm.txtStartRec.value = frm.txtRecCount.value - frm.rdoNumRecs.value + 1;
	frm.submit();
}
function searchAgain() {
	location.href = trim(frm.txtSearchPage) + "?dest=" + trim(frm.dest) + "&title=" + trim(frm.title)
}
function sortBy(sOrderBy, sOrderByDir) {
	frm.OrderBy.value = sOrderBy;
	frm.OrderByDir.value = sOrderByDir;
	scrollFirst();
}
function verifyDelete(){
	return confirm("Are you sure you want to delete this record?");
}
// end search results funcs

function mc_beep(sSrc){
	if(window.MC_Beep && typeof(MC_Beep.src) != "undefined")
		MC_Beep.src = sSrc;
}

function mc_copy(str){
    return window.clipboardData.setData("Text", str);
}

function MC_ShowMenu(oCont, bIsOn) {
	oCont.style.display = (bIsOn)? "" : "none";
}

function showFieldsetTags(b){
	if (!document.body.removeNode) return;
	var elem = (b) ? getAsArray(window.FieldsetTemp) : document.all.tags("FIELDSET");
	var i = elem.length;

	while(i > 0) {
		i--;
		var html = elem[i].outerHTML.trim();
		html = html.substring(0, html.indexOf(">") + 1);

		if(b) {
			html = html.replace("DIV id=FieldsetTemp", "FIELDSET");
		}
		else {
			html = html.replace("FIELDSET", "DIV id=FieldsetTemp");
		}
		
		var el = document.createElement(html);
		elem[i].parentElement.insertBefore(el, elem[i]);
		el.appendChild(elem[i]);
		elem[i].removeNode(false);

		if(el.firstChild.tagName == "LEGEND") {
			if(b) {
				el.firstChild.innerHTML = el.firstChild.innerText;
			}
			else {
				el.firstChild.innerHTML = "<U><B>" + el.firstChild.innerText + "</B></U>";
			}
		}
	}
}

// lookup funcs
function findUserId(hElDest, sElName){
	var oTxtSpan = window[hElDest.name + "Text"];
	var args = findDbColValEx(oTxtSpan.innerText, "mcusers/dlgFindUsers.asp", null, 445);

	if(args) {
		hElDest.value = args[sElName];
		oTxtSpan.innerText = args.fldFirstName + " " + args.fldLastName;
	}
}

function findUserName(hElDest, sElName){
	return findDbColVal(hElDest, sElName, "mcusers/dlgFindUsers.asp", null, 445);
}

function chkMaxWin(){
	if(location.href.indexOf("showMenu=0") != -1)
		maximize();
}

function beep(sSrc){
	mc_beep(formatUrl("mclib/" + sSrc + ".wav"));
}

function showMenu(bIsOn) {
	if(window.MenuGrip) {
		MC_ShowMenu(MenuGrip, bIsOn);
		document.body.style.paddingTop = (bIsOn) ? "35px" : "10px";
	}
}

function exportCSVEx(hForm, sUrl) {
	if(hForm) {
		hForm.prevAction = hForm.action;
		hForm.prevMethod = hForm.method;

		with(hForm) {
			action = sUrl;
			method = "post";
			submit();
			method = prevMethod;
			action = prevAction;
		}
	}
}

