var newWindow;
var intKey;

//  MODULE-LEVEL: CAPTURE DOCUMENT KEYDOWN EVENT TO PREVENT USER FROM LOSING ENTRIES BY BACK SPACING
	if (typeof window.event != 'undefined') // IE
	  document.onkeydown = function() // IE
		{
		var t=event.srcElement.type;
		var kc=event.keyCode;
		return ((kc != 8) || ( t == 'text') || (t == 'password') || 
				 (t == 'textarea') || (t == 'password') || ( t == 'submit'))
		}
	else
	  document.onkeypress = function(e)  // FireFox/Others 
		{
		var t=e.target.type;
		var kc=e.keyCode;
		if ((kc != 8) || ( t == 'text') || (t == 'password') || 
			(t == 'textarea') || (t == 'password') || ( t == 'submit'))
			return true
		else {
//			alert('Sorry Backspace is not allowed here'); // Demo code
			return false
		}
   	}

	function navigate(strURL) {
		var intVer = 0;
		var blnOK = false;
//		alert("dirty: " + isDirty());
		if (isDirty()) {
			blnOK = confirm("Continue without saving?");
		} else {
			blnOK = true;
		}
		if (blnOK) {
			if (strURL.indexOf("calendar.php") > 0) {
//				alert("cal found in: " + strURL);
				window.document.frmCalendarLogin.submit();
			} else {
//				alert("cal not found in: " + strURL);				
				window.location.href = strURL;
			}
		}
	}

	function closePopup() {
	//  although IE allows a modal window it can't be smaller than 100 x 250 and looks unprofessional
	//  it would be nice to have the default button be "Cancel" but other than that, the normal "Confirm" box works ok
//		if (DetectBrowser() == "IE") {
//			var strHdg = "";		//encodeURI("Unsaved Changes");
//			var strMsg = encodeURI("Continue without saving?");
//			var strPost = "?heading=" + strHdg + "&message=" + strMsg;
//			var intResult = window.showModalDialog("../includes/confirm.php" + strPost, "", "dialogHeight: 100px,dialogWidth: 250px");
////			var intResult = window.showModalDialog("../includes/confirm.php" + strPost);			
////			alert("result: " + intResult);
//			switch (intResult) {
//				case 0:
//					window.close();
//					break;
//				case 1:
//					break;
//				case 2:
//					break;
//			}
//		} else {
			var intVer = 0;
			var blnOK = false;
			if (isDirty()) {
				blnOK = confirm("Continue without saving?");
			} else {
				blnOK = true;
			}
			if (blnOK) {
				window.close();
			}
//		}
	}

	function DetectBrowser() {
		var strType = '';
		if(navigator.userAgent.indexOf("Firefox")!=-1){
			strType = "FF";
		} else if (navigator.userAgent.indexOf("MSIE")!=-1) {
			strType = "IE";	
		}
		return strType;
	}
	
	function DetectIEVersion() {
		var intVer = 0;
		if (navigator.appVersion.indexOf("MSIE")!=-1) {
			var strTemp=navigator.appVersion.split("MSIE");
			intVer=parseFloat(strTemp[1]);			
		}
		return intVer;
	}

	function stripAllQuotes(strIn) {
		var strOut = strIn.replace(/'/g, "");		
		strOut = strOut.replace(/"/g, "");
		return strOut;			
	}

	function stripSingleQuotes(strIn) {
		var strOut = strIn.replace(/'/g, "");		
		return strOut;
	}

	function stripDoubleQuotes(strIn) {
		var strOut = strIn.replace(/"/g, "");		
		return strOut;
	}
	

//	function addEvent(objObject, strEventName, fnHandler) {
//	// 	DOM-compliant way to add an event listener
//	 if (objObject.addEventListener)
//	   	objObject.addEventListener(strEventName, fnHandler, false);
//	// 	IE/windows way to add an event listener
//	 else if (objObject.attachEvent)
//	   	objObject.attachEvent("on" + strEventName, fnHandler);
//	}	

	function OnClickNewWindow(relurl,height,width) {
		newWindow=window.open(relurl,"","HEIGHT="+height+",WIDTH="+width+",resizable,scrollbars,menubar,toolbar,location")
		return newWindow;
	}
	
	function OnClickNewWindowMin(relurl,height,width) {
		newWindow=window.open(relurl,"","HEIGHT="+height+",WIDTH="+width+",resizable,scrollbars,location")
		return newWindow;
	}

	function OnClickNewWindowBare(relurl,height,width) {
		newWindow=window.open(relurl,"","HEIGHT="+height+",WIDTH="+width+",resizable,scrollbars")
		return newWindow;
	}
	
	function OnClickNewWindowBareNoScroll(relurl,height,width) {
		newWindow=window.open(relurl,"","HEIGHT="+height+",WIDTH="+width+",resizable")
		return newWindow;
	}
		
	function ShowAnchorPopup(relurl,height,width) {
		newWindow=window.open(relurl,"jav","HEIGHT="+height+",WIDTH="+width+",resizable,scrollbars")
	}	

	function OnClickGetURL(relurl) {
		window.location.href=relurl
	}

	function OnKeyPressInt(event) {
		if (navigator.appName=="Netscape") {
			intKey=event.which
		} else {
			intKey=event.keyCode
		}
		status=intKey
		if (intKey>47 && intKey<58) {
			return true
		} else {
			return false
		}
	}

	function ShowHideDiv(strDivId) {
		var el = document.getElementById(strDivId);
		if (el.style.display != "none" ) {
			el.style.display = 'none';
		}
		else {
			el.style.display = 'block';
		}
	}

	function ShowHideRow(strRowId) {
		var el = document.getElementById(strRowId);
		if (el.style.display != "none" ) {
			el.style.display = 'none';
		}
		else {
			if (DetectBrowser() == "IE") {
				el.style.display = 'block';
			} else {
				el.style.display = 'table-row';
			}
		}
	}
	
	function ShowOrHideSaving(blnShow) {
		var objDiv = document.getElementById("divSaving");		
		if (!objDiv) {
			var objDiv = document.createElement("div");
			objDiv.id = "divSaving";
			objDiv.innerHTML = "<img src='../images/zpsaving.gif'>";
			objDiv.style.position = "absolute";
			objDiv.style.zindex = 10000000;

//			if (DetectBrowser() == "FF") {
//				objDiv.style.left = document.body.clientWidth / 2 + "px";
//				objDiv.style.top = document.body.clientHeight / 2 + "px";
//			} else {
//				objDiv.style.left = document.body.offsetWidth / 2 + "px";
//				objDiv.style.top = document.body.offsetHeight / 2 + "px";
//			}
			
			document.body.appendChild(objDiv);
		}
		objDiv.style.left = screen.width/2 + "px";		//document.body.offsetWidth / 2 + "px";
		objDiv.style.top = screen.height/2 + "px";		//document.body.offsetHeight / 2 + "px";		
		if (blnShow) {
//			objDiv.style.display = "block";
			objDiv.innerHTML = "<img src='../images/zpsaving.gif'>";			
		} else {
//			objDiv.style.display = "none";
			objDiv.innerHTML = "<br>";			
		}
	}
	
	function formatNumber(expr,decplaces) {
		if (expr) {
		//  strip all quotes
			var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
			while (str.length <= decplaces) {
				str = "0" + str
			}
			var decpoint = str.length - decplaces
	//		alert("return: " + str.substring(0,decpoint) + "." + str.substring(decpoint,str.length));
			if (decplaces == 0) {
				return str.substring(0,decpoint);	
			} else {
				return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
			}
		} else {
			return expr;
		}
	}

	function formatPhone(strIn) {
//		alert("format phone: " + strIn);
		var strReturn = strIn;
	//  strip all quotes
		strReturn = stripAllQuotes(strReturn);
		switch (strIn.length) {
			case 0:
				break;
			case 7:
				if (strIn.indexOf("-") == -1) {
					strReturn = strIn.substring(0,3) + "-" + strIn.substring(3,7);
				}
				break;
			case 10:
				if (strIn.indexOf("-") == -1) {
					strReturn = "(" + strIn.substring(0,3) + ") " + strIn.substring(3,6) + "-" + strIn.substring(6, 10);
				}			
				break;
			case 12:
			//  two hyphens
				if (strIn.charAt(3) == "-" && strIn.charAt(7) == "-") {
					strReturn = "(" + strIn.substring(0,3) + ") " + strIn.substring(4,7) + "-" + strIn.substring(8,12);
				}
			//  two spaces
				if (strIn.charAt(3) == " " && strIn.charAt(7) == " ") {
					strReturn = "(" + strIn.substring(0,3) + ") " + strIn.substring(4,7) + "-" + strIn.substring(8,12);
				}			
			//  two periods
				if (strIn.charAt(3) == "." && strIn.charAt(7) == ".") {
					strReturn = "(" + strIn.substring(0,3) + ") " + strIn.substring(4,7) + "-" + strIn.substring(8,12);
				}						
			//  one space - one hyphen
				if (strIn.charAt(3) == " " && strIn.charAt(7) == "-") {
					strReturn = "(" + strIn.substring(0,3) + ") " + strIn.substring(4,7) + "-" + strIn.substring(8,12);
				}						
			//  two parens
				if (strIn.charAt(0) == "(" && strIn.charAt(4) == ")") {
					strReturn = "(" + strIn.substring(1,4) + ") " + strIn.substring(5,8) + "-" + strIn.substring(8,12);
				}						
				break;
			default:
				
		}
		return strReturn;
	}

	function formatMDYDateFromJS(datX) {
		var intMonth = datX.getMonth() + 1;
		var intDate = datX.getDate();
		var intYear = datX.getFullYear();
		return intMonth + "-" + intDate + "-" + intYear;
	}
	
	function formatYMDDateFromJS(datX) {
		var intMonth = datX.getMonth() + 1;
		var intDate = datX.getDate();
		var intYear = datX.getFullYear();
		return intYear + "-" + intMonth + "-" + intDate;
	}	

	function getJSDateFromMDY(strDate) {
		var datJS;
		var intMaxDay;
	//  check for two valid delimiters
		var delim1 = strDate.indexOf("-");
		var delim2 = strDate.lastIndexOf("-");
		blnOK = (delim1 != -1 && delim1 != delim2) 
		if (blnOK) {
		//  check for valid components
			var intMonth = parseInt(strDate.substring(0, delim1), 10);
			var intDate = parseInt(strDate.substring(delim1 + 1, delim2), 10);
			var intYear = parseInt(strDate.substring(delim2 +1, strDate.length), 10);
			switch (intMonth) {
				case 2:
					if (intYear % 4 == 0) {
						intMaxDay = 29;
					} else {
						intMaxDay = 28;
					}
					break;
				case 4:
				case 6:
				case 9:
				case 11:
					intMaxDay = 30;
					break;
				default:
					intMaxDay = 31;
					break;
			}
		}
		if (intDate <= intMaxDay) {
			datJS = new Date(intYear, intMonth - 1, intDate);
		}
		return datJS;
	}
	
	function getJSDateFromYMD(strDate) {
		var datJS;
		var intMaxDay;
	//  check for two valid delimiters
		var delim1 = strDate.indexOf("-");
		var delim2 = strDate.lastIndexOf("-");
		blnOK = (delim1 != -1 && delim1 != delim2) 
		if (blnOK) {
		//  check for valid components
			var intYear = parseInt(strDate.substring(0, delim1), 10);
			var intMonth = parseInt(strDate.substring(delim1 + 1, delim2), 10);
			var intDate = parseInt(strDate.substring(delim2 +1, strDate.length), 10);
			switch (intMonth) {
				case 2:
					if (intYear % 4 == 0) {
						intMaxDay = 29;
					} else {
						intMaxDay = 28;
					}
					break;
				case 4:
				case 6:
				case 9:
				case 11:
					intMaxDay = 30;
					break;
				default:
					intMaxDay = 31;
					break;
			}
		}
		if (intDate <= intMaxDay) {
			datJS = new Date(intYear, intMonth - 1, intDate, 0, 0, 0);
		}
		return datJS;
	}
	
	function reformatDate(strIn) {
	//  strip all quotes
		var strOut = stripAllQuotes(strIn);
	//  change delimiter from / to -
		strOut = strOut.replace(/\//g,"-");
	//  check for two valid delimiters
		var delim1 = strOut.indexOf("-");
		var delim2 = strOut.lastIndexOf("-");
		var blnOK = (delim1 != -1 && delim1 != delim2) 
		if (blnOK) {
			if (strOut.length - delim2 == 3) {
				var strMonth = strOut.substring(0, delim1);
				var strDate = strOut.substring(delim1 + 1, delim2);				
				var strYear = strOut.substring(delim2 + 1, strOut.length);						
				strOut = strMonth + "-" + strDate + "-" + "20" + strYear;
			}
		}
		return strOut;
	}
	
	function getTimeZoneOffsetInMilleseconds() {
		var datX = new Date();
		var intOffset = datX.getTimezoneOffset() * 60 * 1000;		
	//  add one more hour to offset to handle DST discrepancies
		intOffset = intOffset + 60 * 60 * 1000;
		return intOffset;
	}
	
	function DaysSince1900(strDate) {
	//  this function exists bacause the date and time functions in PHP and Javascript only go back to 1970
	//  this function DOES NOT return the exact number of days since 1900 
	//  and should only to be used to assign relative values (not absolute ones) to dates
		var array = strDate.split("-");
		if (array[2]) {
			var month = parseInt(array[0]);
			var day = parseInt(array[1]);
			var year = parseInt(array[2]);
			var intDays = ((year - 1900) * 12 + month) * 31 + day;			
		}	
		return intDays;	
	}
	
	function validateGrid(objGrid) {
//		alert("validating");
		var strEntry = '';
		var arrRows = mobjGrid.getRows();
		if (arrRows.length == 0) {
			var blnOK = true;
		} else {
			var blnOK = false;
		//  get col headings into an array
			var strColHdg = new Array();
			var arrCells = mobjGrid.getRowCells(arrRows[0]);				
			for (i = 0; i < arrCells.length; i++) {
				var objField = mobjGrid.getFieldByCell(arrCells[i]);
				if (!mobjGrid.getFieldHidden(objField)) {				
					var strX = 'zpGrid' + mobjGrid.getId() + 'Col' + i + 'Title';
//					alert("strX: " + strX);
					var objColHdg = document.getElementById(strX);
//					alert("object: " + objColHdg);
					if (objColHdg) {
						var strTemp = objColHdg.innerHTML;
						var intSep1 = strTemp.indexOf(">");
						var intSep2 = strTemp.indexOf("</", intSep1);						
						strColHdg[i] = strTemp.substr(intSep1 + 1, intSep2 - intSep1 -1);
					} else {
					//  Zapatec has a bug
					//  On the TW Contacts screen there are 4 hidden cols followed by 3 frozen ones
					//  This code does not get valid col objects for the first 4 columns immediately following the 4 fixed ones
					//		but does get valid objects after that so this code substitutes the visible column number for
					//      the col heading
						strColHdg[i] = i - 3;
					}
//					alert("strColHdg i: " + strColHdg[i]);
				}
			}
		//  check each cell
			for (i = 0; i < arrRows.length; i++) {
				var arrCells = mobjGrid.getRowCells(arrRows[i]);	
			//  don't test hidden (deleted) rows (column 2 is the ISDEL field)
				if (mobjGrid.getCellValue(arrCells[2]) == "true") {
					blnOK = true;
				} else {
				//  don't validate the RecordID field so I can make it visible and not get -1 errors
					for (j = 1; j < arrCells.length; j++) {
						var objField = mobjGrid.getFieldByCell(arrCells[j]);
						if (!mobjGrid.getFieldHidden(objField)) {
							strEntry = mobjGrid.getCellValue(arrCells[j]);
							switch (mobjGrid.getFieldType(objField)) {
								case "date":
//									alert("date: " + arrCells[j].v);								
									if (strEntry == "") {
										blnOK = true;
									} else {
										blnOK = validateMDYDateJS(strEntry);
									}
									if (!blnOK) {
//										alert("Invalid date entry " + strEntry + " in row " + i + " column " + j);
										alert("Invalid date entry " + strEntry + " in column " + strColHdg[j] + " (row: " + i + ")");
									}
									break;
								case "integer":
								case "float":
			//						alert("number: " + arrCells[j].v);
									blnOK = validateNumber(strEntry);
			//						alert("OK: " + blnOK);
									if (!blnOK) {
										if (strEntry != "") {
											strEntry += " ";
										}							
//										alert("Invalid numeric entry " + strEntry + " in row " + i + " column " + j);
										alert("Invalid numeric entry " + strEntry + " in column " + strColHdg[j] + " (row: " + i + ")");										
									}						
									break;
								default:
									blnOK = true;
							}
							if (!blnOK) {
								return blnOK;
							}
						}
					}
				}
			}
		}
		return blnOK;
	}
		
	function validateMDYDateJS(strDate) {
		var blnOK;		
		var intMaxDay;
	//  check for two valid delimiters
		var delim1 = strDate.indexOf("-");
		var delim2 = strDate.lastIndexOf("-");
		blnOK = (delim1 != -1 && delim1 != delim2) 
		if (blnOK) {
		//  check for valid components
			var intMonth = parseInt(strDate.substring(0, delim1), 10);
			var intDate = parseInt(strDate.substring(delim1 + 1, delim2), 10);
			var intYear = parseInt(strDate.substring(delim2 +1, strDate.length), 10);
			switch (intMonth) {
				case 2:
					if (intYear % 4 == 0) {
						intMaxDay = 29;
					} else {
						intMaxDay = 28;
					}
					break;
				case 4:
				case 6:
				case 9:
				case 11:
					intMaxDay = 30;
					break;
				default:
					intMaxDay = 31;
					break;
			}
			blnOK = (intMonth > 0 && intMonth <= 12) && (intDate > 0 && intDate <= intMaxDay) && (intYear > 1800 && intYear < 3000);
		}
		return blnOK;
	}
	
	function validateEmailAddress(strIn) {
		var intSepPeriod = 0;
		var blnOK = false;
		if (strIn) {
			var intSepAt = strIn.indexOf("@");
			if (intSepAt > 0) {
				intSepPeriod = strIn.indexOf(".", intSepAt);
			}
			blnOK = (intSepPeriod > 0);
		}
		return blnOK;
	}
	
	function validateNumber(strIn, blnAllowZero) {
		var strTest = new String(strIn);
		var regex = /[^0-9.,]/;
		return !regex.test(strTest);
	}
	
	function displayHelp(type) {
		var strURL="../help/help.php?Type=" + type;
		OnClickNewWindowBare(strURL, 500, 750);
	}
	
	function setHelpImage(strId, strIn) {
		var objImg = document.getElementById(strId);
		if (strIn == "mouseover") {
			objImg.src = "../images/help_hover.gif";
		} else {
			objImg.src = "../images/help.gif";
		}
	}
		
	function convertRGBToHex(intRed, intGrn, ingBlue) {
		var a = GiveHex(Math.floor(intRed / 16));
		var b = GiveHex(intRed % 16);
		var c = GiveHex(Math.floor(intGrn / 16));
		var d = GiveHex(intGrn % 16);
		var e = GiveHex(Math.floor(intBlue / 16));
		var f = GiveHex(intBlue % 16);
	
		var z = a + b + c + d + e + f;
	
		return z;
	}
	
	function getHex(intX) {
		var strVal;
		if(intX == 10)
			strVal = "A";
		else
		if(intX == 11)
			strVal = "B";
		else
		if(intX == 12)
			strVal = "C";
		else
		if(intX == 13)
			strVal = "D";
		else
		if(intX == 14)
			strVal = "E";
		else
		if(intX == 15)
			strVal = "F";
		else
			strVal = "" + intX;
	
		return Value;
	}
	
	function getSelectedButton(buttonGroup) {
		var i;
		for (i = 0; i < buttonGroup.length; i++) {
			if (buttonGroup[i].checked) {
				return i;
			}
		}
		return 0
	}
	
//  following function called from rkutil.php
	function checkScreenWidthCookie(strPath) {
		var strCookieName = "screenwidth=";
		var strCookieval = "";
		var arrX = document.cookie.split(';');
		for(var i = 0; i < arrX.length; i++) {
			var c = arrX[i];
//					alert("array element: " + c);
			while (c.charAt(0)==' ') {
				c = c.substring(1,c.length);
			}
		//  this is the right cookie if this array element begins with the cookie name (i.e. indexOf == 0)
			if (c.indexOf(strCookieName) == 0) {
				strCookieVal = c.substring(strCookieName.length,c.length);
				if (parseInt(strCookieVal) != window.screen.width) {
//							alert("resetting cookie from " + strCookieVal + " to " + window.screen.width);
					var datExpir = new Date("December 31, 2023");
					var cookieExpir = "expires=" + datExpir.toGMTString();
//						 	var cookieDomain = "domain=www.mlmtaxsolutions.com/recordkeeping";	// + document.domain;							
//					var cookiePath = "path=/recordkeeping";
					var cookiePath = "path=" + strPath;					
					var cookiePair = "screenwidth="+ window.screen.width;							
					var cookieString = cookiePair + "; " + cookieExpir + "; " + cookiePath;
					document.cookie = cookieString;
				 
				//  refresh the page to read the cookie
					window.location = window.location;							
				}
			}
		}
	}
	
	function trim(strIn) {
		return strIn.replace(/^\s+|\s+$/g,"");
	}	

