// $Header: common.js 1.14 2008/08/15 17:32:47GMT snarvaez Ready  $
// General JavaScript Routines
// Copyright(c) Sage Software, Inc. 1988-2007. All rights reserved.

// ENTER key trapping for text input fields
var nav = window.Event ? true : false;
var submitDone = false; // Used to prevent user from submitting search more than once

if (nav) {
	window.captureEvents(Event.KEYDOWN);
	window.onkeydown = NetscapeEventHandler_KeyDown;
} else {
	document.onkeydown = MicrosoftEventHandler_KeyDown;
}

function NetscapeEventHandler_KeyDown(e) {
	if (e.which == 13 && e.target.type == 'text') {
		return false;
	} else {
		return true;
	}
}

function MicrosoftEventHandler_KeyDown() {
	if (event.keyCode == 13 && event.srcElement.type == 'text') {
		return false;
	} else {
		return true;
	}
}
// end ENTER key trapping

function SetForms() {
// Set initial display of check boxes and list boxes
// This function should be placed in the body tag with the onLoad event handler
// The value of the preceding object in the form is used to set the value of the check box or list box.
// For a check box, when this value is "Y", the checked property of the check box is set to true.
// For a list box, when this value is encountered as one of the select options, the options selected property is set to true.

	var form_num = document.forms.length
	var cbTest = "checkbox"
	var lbTest = "select-one"
	if (form_num >= 0 ) {
		for (var f=0; f < form_num; f++) {
			var form = window.document.forms[f]
			for (var i=0; i < form.elements.length; i++) {
				var testval = form.elements[i].type
				if (testval == cbTest) {
					var InitVal = form.elements[i-1].value
					if (InitVal == "Y") { form.elements[i].checked = true }
				} // end of check box if
				if (testval == lbTest) {
					var InitVal = form.elements[i-1].value
					for (var o=0; o < form.elements[i].options.length; o++) {
						if (form.elements[i].options[o].value == InitVal) {
						form.elements[i].options[o].selected = true
						} // end of lb options if
					} // end of for to loop thru LB options
				} // end of list box if
			} // end of for to loop thru form elements
		} // end of for to loop thru forms
	} // end of main if
	return
} // end of function


function submitForm (thisForm, btnName, btnValue, skipRequired) {
// Generic submit a form via an HREF link tag:
// i.e. <a href="javascript:submitForm('formname','buttonname','buttonvalue')">Submit Form</a>
// or a button input tag:
// i.e. <input type="button" name="submit" value="Submit Form"
// onClick="submitForm('formname','buttonname','buttonvalue')">
// Add a <input type="hidden" name="FormIOL" value=""> field to the form to use the IOL building feature.

	retVal = true

	if (skipRequired != true) {
		retVal = CheckRequired(eval(thisForm))
	}

	if (retVal && eval("document." + thisForm + ".FormIOL")) { // if FormIOL hidden field exists
		// load form element names into CSV FormIOL field
		var formname = eval(thisForm);
		var iol = '';
		for (var i=0; i<formname.length; i++) {
			element = formname.elements[i];
			if (element.name != '') { iol += element.name + ',' }
		}

		eval("document." + thisForm + ".FormIOL.value = '" + iol + "'");
    }

	if (retVal) {
		if (btnName != "") {
			eval("document." + thisForm + "." + btnName + ".value = '" + btnValue + "'");
		}
		eval("document." + thisForm + ".submit()");
	}
}


function ValidFileName(gField, suffixExt, makeUpper) {
// Make sure a file has an extension of some sort

	var newStr = gField.value
	if (newStr.indexOf(".") < 0) {
		newStr += suffixExt
	}
	if (makeUpper == 1) {
		gField.value = newStr.toUpperCase()
	}
	if (makeUpper == 2){
		gField.value = newStr.toLowerCase()
	}
	if (makeUpper <= 0){
		gField.value = newStr
	}
}


function GetToday(gField, delim, y2kYear, yrDisp) {
// If a null value is set, replace null with today's date formatted
// with specified delimiter

	var testVar = gField.value
	if (testVar == ""){
		var thisDate = new Date()
		var toDay = thisDate.toLocaleString()
		myArray = toDay.split(" ")
		toDay = myArray[0]
		gField.value = toDay
		ValidDate(gField,delim, y2kYear, yrDisp)
	}
}


function CheckRequired(thisForm) {
// Loop through all objects of form and validate objects with ID="REQUIRED"
// and that there is a value available.

	var crLf = String.fromCharCode(13,10)
	errMsg = ""
	pass = true
	find = 0

	for (k=1; k < thisForm.length; k++){
		var tempobj = thisForm.elements[k]
		nameVal = NameToEnglish(tempobj.name)

		if (tempobj.id && tempobj.id.toUpperCase() == "REQUIRED"){
			if ((tempobj.type == "text" || tempobj.type == "textarea" || tempobj.type == "password" || tempobj.type == "hidden") && (tempobj.value == "")){
			// Check text boxes, text area boxes, and password boxes.
				pass = false
				find += 1
				errMsg += "     " + nameVal + crLf
			}
			if (tempobj.type.toString().charAt(0) == "s" && tempobj.selectedIndex <= 0){
			// Check select boxes.
				pass = false
				find += 1
				errMsg += "     " + nameVal + crLf
			}
			if (tempobj.type.toString().charAt(0) == "c" && tempobj.checked <= 0){
			// Check check boxes.
				pass = false
				find += 1
				errMsg += "     " + nameVal + crLf
			}
		}
	}
	if (find > 1){
		errMsg = "Required Fields:" + crLf + errMsg
	} else {
		errMsg = "Required Field:" + crLf + errMsg
	}
	if (pass == false){
		alert(errMsg)
	}
	return pass
}

function NameToEnglish(nameIn) {
// convert field name to psuedo English format

	nameOut = nameIn

	if (nameOut.indexOf("_")==-1) {	// no underscores, insert space before uppercase chars
		nameOut = nameOut.replace(/([A-Z])/g, " $1");
	} else {  // contains underscore(s), replace "_" with space and proper case string
		nameOut = ReplaceString(nameOut,"_"," ")
		wordArray = nameOut.split(/\s+/)
		for (c=0; c < wordArray.length; c++){
			wordArray[c] = wordArray[c].substr(0,1).toUpperCase() + wordArray[c].substr(1).toLowerCase()
		}
		nameOut = wordArray.join(" ")
	}

	// remove any spaces from beginning of string
	nameOut = nameOut.replace(/^\s*(.*)/, "$1");

	return nameOut
}

function IsRequired(gField) {
// Validate single field.

	var pass = true
	fName = FmtAlpha(gField.name,"3")
	if (gField.value == ""){
		alert(fName + " is required.")
		gField.focus()
		gField.select()
		pass = false
	}
	return pass
}

function submitSearchForm(frm, btn, requiredField, isAdvSearch) {
// Validate required field and prevent submit more than once
	var result= IsRequired(requiredField);
	if (result)
		if (!submitDone) {
			submitDone = true;
			btn.value="Wait..."
			btn.disabled= true;
			if (isAdvSearch) setTimeout('closeSearchPopUpWindow()',2000);
			frm.submit();
			result= true;
		} 
		else {
			alert ("Search is in progress, please wait.");
			result= false;
		}
	return result;
}

function closeSearchPopUpWindow() {
  document.parentWindow.name = '';
  self.close();
}

function ReplaceString(strData, lookFor, replaceWith) {
// Replace all occurances of a substring with a specified substring
// within the data object.

	newStr = ""
	var testStr = strData
	if (testStr.indexOf(lookFor) != -1) {
		myArray = testStr.split(lookFor)
		for (i=0; i < myArray.length; i++){
			if (i != myArray.length-1){
				newStr += myArray[i] + replaceWith
			} else {
				newStr += myArray[i]
			}
		}
		return newStr
	} else {
		return strData
	}
}


function FmtAlpha(strData, fmtCode) {
// Format a string to either 1-Uppercase, 2-Lowercase, or 3-Titlecase

	if (fmtCode == "1"){
		strData = strData.toUpperCase()
		return strData
	}
	if (fmtCode == "2"){
		strData = strData.toLowerCase()
		return strData
	}
	if (fmtCode == "3"){
		newStr = ""
		newStr = ReplaceString(strData,"_"," ")
		strData = newStr
		newStr = strData.toLowerCase()
		strData = newStr
		newStr = ""
		max = strData.length
		for (i=0; i < max; i++){
			if (i == 0 || strData.substr(i-1,1) == " "){
				newStr += strData.substr(i,1).toUpperCase()
			} else {
				newStr += strData.substr(i,1)
			}
		}
	}
	return newStr
}


function FmtPhone(gField) {

	var crLf = String.fromCharCode(13,10)
	testVar = gField.value
	if (testVar.length > 0){
		testVar = ReplaceString(testVar,"(","")
		testVar = ReplaceString(testVar,")","")
		testVar = ReplaceString(testVar,"-","")
		testVar = ReplaceString(testVar," ","")
		testVar = ReplaceString(testVar,".","")
		testVar = ReplaceString(testVar,"+","")
		testVar = ReplaceString(testVar,"/","")
		if (testVar.length > 10){
			return
		}
		if (testVar.length < 10 && testVar.length < 7){
			alert("An insufficient number of characters has been entered or" + crLf + "the data entered was in the wrong format.")
			gField.focus()
			gField.select()
		} else {
			if (testVar.length == 10){
				testVar = "(" + testVar.substr(0,3) + ") " + testVar.substr(3,3) + "-" + testVar.substr(6)
			}
			if (testVar.length == 7){
				testVar = testVar.substr(0,3) + "-" + testVar.substr(3,4)
			}
			gField.value = testVar
		}
	}
	return true
}

function FmtQty(gField,qtyDec,maxQty) {

	var qtyVal = gField.value;
	var regexp = / /g;
	qtyVal = qtyVal.replace(regexp,""); // remove spaces
	var regexp = /,/g;
	qtyVal = qtyVal.replace(regexp,""); // remove commas

	if (qtyVal == "") {
		qtyVal = "0";
	}

	var pass = true;
	var numVal = parseFloat(qtyVal);

	var doubledec = /\.\./g; // check for double decimals
	var singledec = /\./g; // check for multiple single decimals
	var singleCount = 0;

	singleResult = qtyVal.match(singledec);
	if (singleResult) {
		singleCount = singleResult.length
	}

	if (qtyVal.match(doubledec) || singleCount>1 || isNaN(numVal) || numVal<0) {
		alert ("Quantity must be numeric and cannot be less than zero.");
		pass = false;
	} else {
		if (numVal >= maxQty) {
			alert ("Quantity entered exceeds maximum quantity allowed.\n" +
					"Quantity has been changed to maximum allowed.");
			numVal = maxQty-1;
			pass = false;
		}
		var str = "" + Math.round(eval(numVal) * Math.pow(10,qtyDec));
		if (qtyDec > 0) { // format number with decimal
			while (str.length <= qtyDec) { str = "0" + str; }
			var decPoint = str.length - qtyDec;
			numVal = str.substring(0,decPoint) + "." + str.substring(decPoint,str.length);
		} else {
			numVal = str;
		}
		gField.value = numVal;
	}

	if (pass == false) {
		gField.focus();
		gField.select();
	}

	return pass;
}


function ValidDate(gField, delim, y2kYear, yrDisp) {
// Validate date and format date with specified delimiters. Date can be
// space, dash, period, or slash delimited. Dates are returned as
// MMDDYYYY or MMDDYY depending on the parameter passed in yrDisp.
//
//   yrDisp = C = MMDDYYYY
//   yrDisp = Y = MMDDYY

	if (gField.value == "") {
		return
	}

	// convert hyphen,space,period delimiters to specified date delimiter
	var inputStr = gField.value
	newStr = ""
	newStr = ReplaceString(inputStr,"-",delim)
	inputStr = newStr
	newStr = ReplaceString(inputStr," ",delim)
	inputStr = newStr
	newStr = ReplaceString(inputStr,".",delim)
	inputStr = newStr
	var delim1 = inputStr.indexOf(delim)
	var delim2 = inputStr.lastIndexOf(delim)
	if (delim1 != -1) {
	// there are delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,delim1),10)
		var dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)
		var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)
	} else {
	// there are no delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,2),10)
		var dd = parseInt(inputStr.substring(2,4),10)
		var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
	}
	if (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) {
	// there is a non-numeric character in one of the component values
		alert("The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, mm dd yyyy or mm-dd-yyyy.")
		gField.value = ""
		gField.focus()
		gField.select()
		return false
	}
	if (mm < 1 || mm > 12) {
	// month value is not 1 thru 12
		alert("Months must be entered between the range of 01 (January) and 12 (December).")
		gField.value = ""
		gField.focus()
		gField.select()
		return false
	}
	// validate year
	if (yyyy < 100) {
	// entered value is two digits
		if (yyyy > y2kYear) {
			yyyy += 1900
		} else {
			yyyy += 2000
		}
	}
	var today = new Date()
	// If day exceed highest day of month, set to highest day of month
	monthMax = new Array(31,31,29,31,30,31,30,31,31,30,31,30,31)
	mMax = monthMax[mm]
	if (dd > mMax){
		dd = monthMax[mm]
	}
	// Adjust day of February for leap years
	if (mm == 2 && dd >= 29) {
		dd = (((yyyy %4 == 0) && ((!(yyyy % 100 == 0)) || (yyyy % 400 == 0))) ? 29 : 28)
	}
	// Format MM and DD with preceeding "0"s
	mm = mm.toString()
	if (mm.length != 2){
		mm = "0" + mm
	}
	dd = dd.toString()
	if (dd.length != 2){
		dd = "0" + dd
	}
	// Format the year based on the yrDisp value. "Y" = 2 digit year.
	yyyy = yyyy.toString()
	if (yrDisp == "Y"){
		yyyy = yyyy.substr(2,2)
	}
	gField.value = mm + delim + dd + delim + yyyy.toString()
	return true
}


function DateIsLater(lgDate, smDate, y2kYear) {
// Check two date fields and verify that the lgDate is LATER than
// smDate, Null lgDate = last, Null smDate = first.

	quote = '"'
	if (lgDate.length < 1){
		return true
	}
	if (smDate.length < 1){
		return true
	}
	var largeDt = lgDate.value
	var smallDt = smDate.value
	pass = true
	if (largeDt.length != 10){
		delim = largeDt.substr(2,1)
		yrVar = largeDt.substr(6,2)
		mmVar = largeDt.substr(0,2)
		dyVar = largeDt.substr(3,2)
		// entered value is two digits
		if (yrVar > y2kYear){
			yrVar = 1900 + parseInt(yrVar,10)
		} else {
			yrVar = 2000 + parseInt(yrVar,10)
		}
		largeDt = mmVar + delim + dyVar + delim + yrVar
	}
	if (smallDt.length != 10){
		delim = smallDt.substr(2,1)
		yrVar = smallDt.substr(6,2)
		mmVar = smallDt.substr(0,2)
		dyVar = smallDt.substr(3,2)
		// entered value is two digits
		if (yrVar > y2kYear) {
			yrVar = 1900 + parseInt(yrVar,10)
		} else {
			yrVar = 2000 + parseInt(yrVar,10)
		}
		smallDt = mmVar + delim + dyVar + delim + yrVar
	}
	largeDt = largeDt.substr(6,4) + largeDt.substr(0,2) + largeDt.substr(3,2)
	smallDt = smallDt.substr(6,4) + smallDt.substr(0,2) + smallDt.substr(3,2)
	if (largeDt < smallDt){
		alert("The ending date must be later than or equal to the starting date.")
		lgDate.focus()
		lgDate.select()
		pass = false
	}
	return pass
}


function CheckMin(gField, minLeng) {

	quote = '"'
	pass = true
	testVal = gField.value
	if (testVal.length < minLeng){
		nameVal = gField.name
		nameVal = ReplaceString(nameVal,"_"," ")
		wordArray = nameVal.split(" ")
		for (c=0; c < wordArray.length; c++){
			wordArray[c] = wordArray[c].substr(0,1).toUpperCase() + wordArray[c].substr(1).toLowerCase()
		}
		nameVal = wordArray.join(" ")
		alert(nameVal + " requires a minimum of " + quote + minLeng + quote + " characters/numbers.")
		pass = false
		gField.focus()
		gField.select()
	}
	return pass
}


function FieldIsLarger(lgField, smField) {
// Check two fields and verify that the lgField is LARGER than
// smField.

	pass = true
	quote = '"'
	if (lgField.length < 1){return true}
		var largeFd = lgField.value
		var smallFd = smField.value
		if (largeFd < smallFd){
			alert('The ending document number must be greater than' + String.fromCharCode(13) + 'or equal to the beginning document number.')
			lgField.focus()
			lgField.select()
			pass = false
		}
	return pass
}


function PadNumStr(gField, fieldLen) {
// Add required number of padding zeros to the left to numeric strings.

	fieldVal = gField.value
	if (fieldVal.length < 1){
		return true
	}
	if (isNaN(fieldVal)){
		gField.value = fieldVal
		return true
	}
	noOfTimes = fieldLen - fieldVal.length
	for (var cntr = 1; cntr <= noOfTimes; cntr++){
		fieldVal = '0' + fieldVal
	}
	gField.value = fieldVal
	return true
}


function Mas90PadStr(gField, fieldLen) {
// Add required number of padding zeros to the left to numeric strings.
// If the value is an alphanumeric value, the field is converted to upper case.

	fieldVal = gField.value
	tmpVal = ''
	if (fieldVal.length < 1) {
		return true
	}
	if (isNaN(fieldVal)) {
		tmpVal = FmtAlpha(fieldVal,'1')
		fieldVal = tmpVal
		gField.value = fieldVal
		return true
	}
	noOfTimes = fieldLen - fieldVal.length
	for (var cntr = 1; cntr <= noOfTimes; cntr++) {
		fieldVal = '0' + fieldVal
	}
	gField.value = fieldVal
	return true
}


function CheckEmail(gField) {

	var emailVar = gField.value
	pass = true
	if (!emailVar.indexOf('@') || !emailVar.indexOf('.')){
		pass = false
	}
	if (emailVar.substr(0,emailVar.indexOf('@')) == '' || emailVar.substr(0,emailVar.indexOf('.')) == '' || emailVar.substr(emailVar.indexOf('.')+1,1) == ''){
		pass = false
	}
	if (emailVar.substr(emailVar.indexOf('@')+1,1) == '.'){
		pass = false
	}
	if (pass == false){
		alert("E-mail address entered is invalid.")
		gField.focus()
		gField.select()
	}
	return pass
}


function GoToLoc() {

	var URL = document.menu.menuoption.options[document.menu.menuoption.selectedIndex].value;
	top.location = URL;
}


function GetCookie(cookieName) {

	for (var i=0; i < bites.length; i++) {
		nextBite = bites[i].split('=')
		if (nextBite[0] == cookieName){
			return unescape(nextBite[1])
		}
	}
	return null
}


function SetCookie(cookieName, cookieValue, expireDays) {

	var expir = new Date(today.getTime() + expireDays * 24 * 60 * 60 * 1000)
	if (cookieValue != null && cookieValue != ''){
		document.cookie = cookieName + '=' + escape(cookieValue) + '; expires=' + expir.toGMTString()
	}
	bites = document.cookie.split('; ')
}


var zindex=100


function dropit2(whichone) {

	if (window.themenu&&themenu.id!=whichone.id)
		themenu.style.visibility="hidden"
		themenu=whichone
		if (document.all){
			themenu.style.left=document.body.scrollLeft+event.clientX-event.offsetX
			themenu.style.top=document.body.scrollTop+event.clientY-event.offsetY+18
			if (themenu.style.visibility=="hidden"){
				themenu.style.visibility="visible"
				themenu.style.zIndex=zindex++
			} else {
			hidemenu()
			}
		}
}


function dropit(e,whichone){

	if (window.themenu&&themenu.id!=eval(whichone).id)
		themenu.visibility="hide"
		themenu=eval(whichone)
		if (themenu.visibility=="hide")
			themenu.visibility="show"
		else
			themenu.visibility="hide"
			themenu.zIndex++
			themenu.left=e.pageX-e.layerX
			themenu.top=e.pageY-e.layerY+19
			return false
}


function hidemenu(whichone){

	if (window.themenu)
		themenu.style.visibility="hidden"
}


function hidemenu2(){

	themenu.visibility="hide"
}


// Generic function to open a Pop Up window.
// Params: URL, Width, Height
function openPopupWindow(url,winWidth,winHeight) {
	popupWinRef = window.open(url, 'popupwin',
	'width=' + winWidth + ',height=' + winHeight + ',resizable');
	popupWinOpen = 1
}


function closePopupWindow() {

	if ((popupWinOpen == 1) && (!popupWinRef.closed))
		popupWinRef.close()
}

// Global variables
// ****************
popupWinOpen = 0;
var bites = document.cookie.split('; ')
var today = new Date()


// Products and Services Templates Common Functions
function checkItems (btnflg) {
// This function insures the quantity does not excede max value / mask

	var total_items = document.ps2form.rows.value;
	var decimal = document.ps2form.form_qdec.value;
	var maximum = document.ps2form.form_qmax.value;
	var errcnt = 0;
	for (i=0; i<=total_items; i++) {
		j = fill(i,3,"0");
		if (FmtQty(eval("document.ps2form.qty_" + j),decimal,maximum) == false) {
			errcnt++;
			break;
		}
	}
	if (errcnt==0) {
		document.ps2form.submit()
	} else if (btnflg) { return false }
}


function fill (itm, num, pchr) {
// This function is used by checkItems() above

	var padding = "";
	var item = itm + "";
	var pstr = item;
	if (num > item.length) {
		for (j=0; j<=num; j++) {
			padding += pchr;
		}
	pstr = padding.substr(0, num - item.length) + item;
	}
	return pstr;
}


function selectCategory (CatCode,CatLvl) {
// This function is used when a category link is pressed

	document.ps2form.FormSelect.value = "C";
	document.ps2form.CatLvl.value = CatLvl;
	document.ps2form.cat.value = CatCode;
	document.ps2form.submit();
}


function selectItem (ItemCode,scKey) {
// This function is used when an item link or thumbnail image is pressed

	document.ps2form.FormSelect.value = "I";
	document.ps2form.ItemCode.value = ItemCode;
	document.ps2form.source.value = "ps";
	document.ps2form.k.value = scKey;
	document.ps2form.submit();
}


function browse (browseKey,browseDirection) {
// This function is used when a page number, next or previous page link is pressed

	document.ps2form.FormSelect.value = browseDirection
	document.ps2form.k.value = browseKey;
	document.ps2form.submit();
}


function submitItem (index,qdec,qmax,add_charge,btnflg) {
	// This function is used when the buy button / link is pressed on a
	// a buy button exists on each product detail row
	idx = fill(index,3,"0");
//	if (FmtQty(eval("document.ps2form.qty_" + idx),qdec,qmax) != false) {
		document.ps2form.FormSelect.value = "";
		document.ps2form.ItemIndex.value = idx;
		document.ps2form.AddCharge.value = add_charge;
		document.ps2form.submit();
//	} else if (btnflg) { return false }
}


function clearFormSubmit () {
// This function is used to clear out previous form selection values
// It is processed on the body load
// It is needed when the user presses the browser back button

	document.ps2form.FormSelect.value = "";
	document.ps2form.source.value = "";
}

// End of Products and Services Templates Common Functions
