// This is used to handle differences between Netscape and IE
if(document.all && !document.getElementById) {
    document.getElementById = function(id) {
         return document.all[id];
    }
}

/******************************************************************
 * global variables and init
 *******************************************************************/
var df0;
var readySubmit=true;
/******************************************************************
 * Installs the global error-handler
 *******************************************************************/
// window.onerror = errorHandler;

function errorHandler()
{
	return true;
}
var alertTO=1500000;

function alertSessionTO()
{
	curTime = new Date();
	alert("\t"+curTime.toLocaleString()+NLS_StandardSessionExpire)
}
function changeAdvertising(screen) {
	if (parent.LogoFrame.changeImg) {
		if (parent.LogoFrame.isBannerLoaded && parent.LogoFrame.isBannerLoaded==true) {
			parent.LogoFrame.changeImg(screen);
		}
	}
}

function changeDisplay(as_display)
{
// Hide the drop downs so they don't show through the pop up window.
var lobj_collection = document.getElementsByTagName("SELECT");

if (as_display == null)
	as_display = "visible";
for (var i = 0; i < lobj_collection.length; i++) 
lobj_collection[i].style.visibility = as_display;
}

function checkForMoreThanOneDecimal(myfield, chr, idx)
{
	if (chr == '.') {
		var totalentry = myfield.value;
		var isthereadecimal = totalentry.indexOf('.');
		if (isthereadecimal > -1 && idx != isthereadecimal)
		{
			alert(NLS_StandardTooManyDecimals);
			myfield.focus();
			return false;
		}
	}
	return true;
}
function checkSubmit() {
	if ( readySubmit ) {
		readySubmit=false;
		cmReady=false;
		if (parent.MenuFrame) {
			parent.MenuFrame.cmReady=false;
		}
		return true;
	} else {
		alert(NLS_StandardFormProcessing);
		return false;
	}
}

function clearMainMenu() {
	//The following hides main menu submenus if open. This is to fix issue with main menubar becoming inactive.
 	if (self.name != "MenuFrame" && parent.MenuFrame && parent.MenuFrame.cmTimeOut && parent.MenuFrame.cmTimeOut != null) {
  		parent.MenuFrame.clearTimeout(parent.MenuFrame.cmTimeOut);
  	}
	if (self.name != "MenuFrame" && parent.MenuFrame && parent.MenuFrame.cmHideSub && parent.MenuFrame.cmHideSub != null) {
		parent.MenuFrame.eval(parent.MenuFrame.cmHideSub);
	}
}

function clearSubmit() {
	readySubmit = true;
	cmReady = true;
	if (parent.MenuFrame) {
		parent.MenuFrame.cmReady = true;
	}
}
/******************************************************************
 * closethis()
 * 
 * Allows the user to select whether or not a print has completed
 * so that the window will close
 *******************************************************************/
function closethis(timeout)
{
	if (confirm(NLS_StandardIsPrintingComplete))
	{
		window.close();
	}
	else
	{
		if (!timeout) {
			timeout = 60000
		}
		setTimeout('closethis('+timeout+');', timeout);
	}
}

function getDateSeperator() {
	var sep = "/";
	for (i=0;i<theDateFormat.length;i++) {
		var c = theDateFormat.charAt(i);
		if (c != 'M' && c != 'd' && c != 'y') {
			sep = c;
			break;
		}
	}
	return sep;
}

function getDateElementIndex(element, sep) {
	var idx = 0;
	for (i=0;i<theDateFormat.length;i++) {
		var c = theDateFormat.charAt(i);
		if (c == element) {
			break;
		}
		if (c == sep) {
			idx++;
		}
	}
	return idx;
}

function dateConvert(date) {
	var monthDays = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
	var newDate = -1;
	var sep = getDateSeperator();
	var monthIdx = getDateElementIndex('M',sep);
	var dayIdx = getDateElementIndex('d',sep);
	var yearIdx = getDateElementIndex('y',sep);

	if (date != null) {
		if (date.length==10) {
			var dtElem = date.split(sep);
			var mm=(dtElem[monthIdx]*1)-1;
			var dd=dtElem[dayIdx]*1;
			var yyyy=dtElem[yearIdx]*1;
			if (mm < 0 || mm > 11 || dd < 1 || dd > monthDays[mm] || yyyy > 9999) {
				newDate = -1;
			}
			else {	
				newDate = new Date(yyyy, mm, dd);
			}
		}
		else if (date.length==0) {
			newDate = 0;
		}
	}
	else {
		newDate = 0;
	}
	return newDate;
}

function dateConvertToString(date) {
	var sep = getDateSeperator();
	var monthIdx = getDateElementIndex('M',sep);
	var dayIdx = getDateElementIndex('d',sep);
	var yearIdx = getDateElementIndex('y',sep);
	var stringDate="";
	if (date!=null) {
		var day = date.getDate();
		if (day < 10) {
			day = "0"+day;
		}
		var month = date.getMonth()+1;
		if (month < 10) {
			month = "0"+month;
		}
		var year = date.getFullYear();
		for (i=0;i<3;i++) {
			if (monthIdx == i) {
				stringDate += month;
			}
			else if (dayIdx == i) {
				stringDate += day;
			}
			else if (yearIdx == i) {
				stringDate += year;
			}
			if (i != 2) {
				stringDate += sep;
			}
		}
	}
	return stringDate;
}

function dateDiff(date1,date2) {
	var diff = 0;	
	var number = date2-date1 ;
	diff = parseInt(number / 86400000) ;
	return diff;
}

function dateRangeChk(df, dt, date) {
	var rc = false;
	var dfc = dateConvert(df);
	var dtc = dateConvert(dt);
	if (date) {
		var datec = dateConvert(date);
	}
	if (dfc != 0 && dtc != 0) {
		if (dfc <= dtc) {
			if (datec) {
				if (dfc <= datec && datec <= dtc) {
					rc = true;
				}
			}
			else {
				rc = true;
			}
		}
	} 
	return rc;
}
function dateToday() {
	var today = new Date();
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today2 = today.getTime()-today.getTime() % 1000;
	today.setTime(today2);
	return today
}

function displayAlerts() 
{
	if (window.alertsTextArray && alertsTextArray != null) {
			for (var i=0;i<alertsTextArray.length;i++) {
				var alertText = alertsTextArray[i];
				alert(alertText);
			}
			alertsTextArray = null;
	}
	if (window.jsFunctionsArray && jsFunctionsArray != null) {
			for (var i=0;i<jsFunctionsArray.length;i++) {
				var jsFunc = jsFunctionsArray[i];
				eval(jsFunc);
			}
			jsFunctionsArray = null;
	}
}

function displayComp() 
{
	alert(NLS_StandardFeatureDisabledBrowser);
}

function initjs() 
{

	var div = document.getElementById("scrollable");
	if (div && div != null) {
		var size = getWindowSize();
		var pos = findPos(div);
		div.style.height = size[1]-pos[1];
	}

	df0 = document.forms[0];
	setTimeout('alertSessionTO();', alertTO);
	if (window.initVars) {
		initVars();
	}
}

function getFieldIndex(fld)
{
	if (fld.name) {
		if (fld.name.indexOf('_') != -1) {
			parts = fld.name.split('_');
			return parts[1]*1;
		}
	}
	return -1;

}

function getFieldPrefix(fld)
{
	if (fld.name) {
		if (fld.name.indexOf('_') != -1) {
			parts = fld.name.split('_');
			return parts[0];
		}
		else {
			return fld.name;
		}
	} else { 
	    return "qqUnknownqq"
	}

}

function goConfirmExportFMG(parm,parm2) {
	if (confirm(NLS_StandardNumberItemsExport)) {
		goExport(parm,parm2);
	}
}

function goExport(parm,parm2)
{	
	submitScreenBase('', 'export', parm, parm2, 'ExportFrame');
	df0.SCRNCMD.value="";
	waitbox(0);
}

function goUserExport(parm)
{	
 	var exportType = df0.SCRNSRCE.value;
 	if (parm && parm != null) {
 		exportType = parm;
 	}

	submitScreenBase('', 'userexport', exportType, null, 'ExportFrame');
	df0.SCRNCMD.value="";
	waitbox(0);
}
function goUserExportSetup(parm)
{
 	var exportType = df0.SCRNSRCE.value;
 	if (parm && parm != null) {
 		exportType = parm;
 	}
    submitScreenToPopup('EXPORTSETUP','init',exportType,null,'DefaultUserSort',560,300,false,null);
	df0.SCRNCMD.value="";
	waitbox(0);
}
/******************************************************************
 * goPageNav(movement)
 * 
 * Performs movement, saves between moves
 *******************************************************************/
function goPageNav(movement, panel)
{
		submitScreen('', "movement", movement, panel)
}

function goPrint()
{
	if (confirm(NLS_StandardNumberItemsPrintable)) {
		submitScreen("", "print")
		df0.SCRNCMD.value="";
	}
}

function goPromo(amount)
{
	alert(NLS_StandardTotalAllowances + amount);
}

function goSC(column)
{
	submitScreen("", "SortColumn",column);
}

function goSearch()
{
	var descinput = df0.searchdesc.value;
	if (descinput.length > 0) {
		submitScreen(null,"search");
	}
	else {
		alert(NLS_ItemMasterEnterSearchWord);
	}
}

function goClearSearch()
{
	df0.searchdesc.value = "";
	submitScreen(null, "search");
}

function highLightRow(fld)
{
	if (fld != null && fld != hlField) {
		//If line is already higlighted then un-highlight
		if (hlTR != null && hlTRClass != null) {
			hlTR.className=hlTRClass;
			hlTR=null;
			hlTRClass=null;
			hlField=null;
		}
	
		switch (getFieldPrefix(fld)) {
			case 'q' :
			case 'ea' :
			case 'sp' :
			case 'it' :
			case 'iv' :
				var tempTD=fld.parentNode;
				var tempTR=tempTD.parentNode;
				hlField=fld;
				hlTR=tempTR;
				hlTRClass=tempTR.className;
				tempTR.className='rhl';
				break;
		}
	}
}

var isUp=false;
var isRevertFocus=false;
var hlTR=null;
var hlField=null;
var hlTRClass=null;
function nextField(myfield, pannel)
{
	var inc = (isUp)?-1:1;
	var idx = getFieldIndex(myfield) + inc;
	var prefix = getFieldPrefix(myfield);

	var start = 0;
	var end = 0;
	var idxFirst = df0.indexfirst;
	var idxLast = df0.indexlast;
	if (pannel != null) {
		idxFirst = eval("df0.indexfirst"+pannel);
		idxLast = eval("df0.indexlast"+pannel);
	}
	if (idxFirst != null && idxLast !=null) {
		start = idxFirst.value*1;
		end = idxLast.value*1;
	}
	else {
		nextFieldElement(myfield);
		return;
	}
	var count = end-start+1;

	for (x=0; x<count; x++) {
		if (!isUp) {
			if (idx > end) {
				alert(NLS_LastLineWrapMessage);
				idx = start;
			}
		}
		else {
			if (idx < start) {
				idx = end;
			}
		}
		var fld = eval("df0."+prefix+"_"+idx);

		if (fld != null) {
			fldType = fld.type;
			if (fldType == null || fldType == "hidden" || fld.disabled || fld.style.visibility == "hidden" || fld.readOnly)	{
				idx += inc;
			}
			else {
				fld.focus();
				highLightRow(fld);
				if (fldType != null && fldType == "text")	{
					try {
						fld.select();
					}
					catch (err) {
					}
				}
				else { //Unselect previous field if text
					fldType = myfield.type;
					if (fldType != null && fldType == "text")	{
						myfield.value=myfield.value;
					}
				}
				break;
			}
		}
		else {
			idx += inc;
		}
	}
	if (isRevertFocus) {
		isRevertFocus=false;
		myfield.focus();
		highLightRow(myfield);
		fldType = myfield.type;
		if (fldType != null && fldType == "text")	{
			myfield.select();
		}
	}
}
/******************************************************************
 * nextFieldElement(field)
 *******************************************************************/
function nextFieldElement(myfield,skip)
{
	var inc = (isUp)?-1:1;
	var idx = 0;
	var fld = null;
	var x, fldType;
	fld = df0.elements;
	if (fld != null) {
		if (fld.length) {
			for (x=0; x<fld.length; x++) {
				if (myfield == fld[x]) {
//					idx = x+1;
					idx = x+inc;
					break;
				}
			}
			if (skip != null && !isNaN(parseInt(skip)))
			{
				idx += skip;
			}
			for (x=0; x<fld.length; x++) {
				if (!isUp) {
					if (idx >= fld.length) {
						alert(NLS_LastLineWrapMessage);
						idx = 0;
					}
				}
				else {
					if (idx < 0) {
						idx = fld.length-1;
					}
				}
				fldType = fld[idx].type;
				if (fldType == null || fldType == "hidden" || fld[idx].disabled || fld[idx].style.visibility == "hidden"
					|| fldType == "button")	{
//					idx += 1;
					idx += inc;
				}
				else {
					fld = fld[idx]
					break;
				}
			}
		}
		fld.focus();
		highLightRow(fld);
		fldType = fld.type;
		if (fldType != null && fldType == "text")	{
			fld.select();
		}
		else { //Unselect previous field if text
			fldType = myfield.type;
			if (fldType != null && fldType == "text")	{
				myfield.value=myfield.value;
			}
		}
	}
}

function noContextMenu(){
	event.cancelBubble = true;
	event.returnValue = false;
	return false;
}
function noRightClick(e) {
	if (window.Event) {
		if (e.which == 2 || e.which == 3) {
			return false;
		}
	} else if (event.button == 2 || event.button == 3) {
		event.cancelBubble = true;
			event.returnValue = false;
			return false;
		}
}
function oid(link, itemInfo) {
    /* Item Description Link */
    var page = 'ItemDescriptionLinkWrapper.jsp?link=' + link;
    if (itemInfo != null) { 
        //Item Info window.  URL is already validated and generated.  Go to it.
        page = link;
    }
	openWindow(page, 'ItemDesc', 500, 650, 'scrollbars=yes,resizable=yes');
}
function oiw(item) {
	openWindow("ItemView.jsp?itemNbr=" + item,null,410,450);
}
function oviw(item) {
	openWindow("vendor/VendorItemView.jsp?itemNbr=" + item,null,410,450);
}

function oimw(item) {
	openWindow("OrderFormItemMovement.jsp?itemnumber=" + item,null,340,400);
}

/******************************************************************
 * openPrintWindow()
 * 
 * Opens window for printing
 *******************************************************************/
function openPrintWindow(jsppage,disablemenubuttons)
{
	if (disablemenubuttons != null && disablemenubuttons == "true")
	{
		readySubmit=false;
		cmReady=false;
		parent.MenuFrame.cmReady=false;
	}
	
	var newWindow = window.open(jsppage+"?jspcommand=print",null,"scrollbars=yes,resizable=yes");
}


function openSearchWindow(itemMaster)
{
	var itemMasterOnly = false;
	if (itemMaster!=null) {
		itemMasterOnly = true;
	}
	var screenSource = df0.SCRNSRCE.value;
	openWindow('AdvancedSearch.jsp?SCRNSRCE=' + screenSource +"&ITEMMASTERONLY="+itemMasterOnly,'SearchCrit',420,500);
}

function openAdvancedSortWindow()
{
	var screenSource = df0.SCRNSRCE.value;
	openWindow('AdvancedSort.jsp?SCRNSRCE=' + screenSource ,'SortCrit',200,500);
}
/********************************************************
* openWindow
*********************************************************/
function openWindow(url,name,height,width,extraverbiage,returnhandle) 
{
 	var size = "";
   	var xPos = 0;
   	var yPos = 0;
	var vExtra = ",scrollbars=yes,resizable=yes";
	var attr, newOpenedWindow;
	if (url == null)
		url = "";

	if (extraverbiage != null) {
		vExtra += ", " + extraverbiage;
	}	
	if (height != null && width != null && height > 0 && width > 0) {
    	yPos = (screen.availHeight / 2) - (height / 2);
    	xPos = (screen.availWidth / 2) - (width / 2);
 		size = "height=" + height +", width=" + width + ", left=" + xPos + ", top=" + yPos;
 	}

	attr = size + ", alwaysRaised=yes" + vExtra;
	
	if (vExtra != "" || size != "") {
		newOpenedWindow = window.open(url, name, attr);
	}
	else {
		newOpenedWindow = window.open(url, name);
	}
	newOpenedWindow.focus();
	if (returnhandle)
		return newOpenedWindow;
}

function preventScreenRefresh(e) {
	var chr;
	var keychar;
	if (window.event) {
		chr = window.event.keyCode;
		altKeyPressed = window.event.altKey;
		if (window.event.altKey) {
			// [Back arrow] || [Forward arrow]
			if ((chr == 37) || (chr == 39)) {
				//alert("[ALT] + ([Back arrow] or [Forward arrow]) keys pressed!");
				return false;
			}
		}
		// [CTRL]
		if (window.event.ctrlKey)	{
			// R
			if (chr == 82)	{
				//alert("[CTRL] pressed!");
				return false;
			}
		}
		// [F5]
		if (chr == 116)	{
			//alert("[F5] pressed!");
			window.event.keyCode=0;
			return false;
		}
		return true;
	}
}
/******************************************************************
 * printthis()
 * 
 * Brings up 'printer' dialogue box
 *******************************************************************/
function printthis(timeout)
{
	if (!timeout) {
		timeout = 30000
	}
	window.print();
// setTimeout('closethis('+timeout+');', timeout);
}

function reenableMenusAfterPrintWindowLoads() {
	var win = window.opener;
	if (win != null)
	{
		win.parent.MenuFrame.readySubmit=true;
		win.parent.MenuFrame.cmReady=true;			
		win.parent.ContentFrame.readySubmit=true;
		win.parent.ContentFrame.cmReady=true;			
	}
	return;
}

function setCheckBoxRange(myfield, pannel)
{
	var fldType = myfield.type;
	if (fldType == null || fldType != "checkbox")	{
		return;
	}
	var checked = myfield.checked;
// var inc = (isUp)?-1:1;
	var inc = -1;
	var idx = getFieldIndex(myfield) + inc;
	var prefix = getFieldPrefix(myfield);

	var start = 0;
	var end = 0;
	var idxFirst = df0.indexfirst;
	var idxLast = df0.indexlast;
	if (pannel != null) {
		idxFirst = eval("df0.indexfirst"+pannel);
		idxLast = eval("df0.indexlast"+pannel);
	}
	if (idxFirst != null && idxLast !=null) {
		start = idxFirst.value*1;
		end = idxLast.value*1;
	}
	else {
		return;
	}
	var count = idx-start+1;

	for (x=0; x<count; x++) {
//		if (!isUp) {
		if (inc == 1) {
			if (idx > end) {
				idx = start;
			}
		}
		else {
			if (idx < start) {
				idx = end;
			}
		}
		var fld = eval("df0."+prefix+"_"+idx);

		if (fld != null) {
			fldType = fld.type;
			if (fldType == null || fldType != "checkbox" || fld.disabled || fld.style.visibility == "hidden" || fld.readOnly)	{
				idx += inc;
			}
			else {
				if (fld.checked == checked)	{
					break;
				}
				fld.checked = checked;
				var tempTD=fld.parentNode;
				var tempTR=tempTD.parentNode;
				if (checked) {
					tempTR.className='rhl';
				}
				else {
					if (idx%2 == 0) {
						tempTR.className='re';
					}
					else {
						tempTR.className='ro';
					}
				}
				idx += inc;
			}
		}
		else {
			idx += inc;
		}
	}
}

function setFocus(fieldName, select)
{
	if (select == null) {
		select = 1;
	}
	var field = eval('df0.'+fieldName);
	if (field != null) {
		if (field.type != "hidden") {
			field.focus();
			highLightRow(field);
		}
		if (select ==1 && field.type == "text") {
			field.select();
		}
	}
	else if (df0.indexfirst && df0.indexlast) {
		var start = df0.indexfirst.value;
		var end = df0.indexlast.value;
		for ( var i=start; i<=end; i++ ) {
			field = eval('df0.'+fieldName+'_'+i);
			if (field && field != null) {
				var fldType = field.type;
				if (fldType == null || fldType == "hidden" || field.disabled || field.style.visibility == "hidden" || field.readOnly)	{
					continue;
				}
				field.focus();
				highLightRow(field);
				if (select ==1 && field.type == "text") {
					field.select();
				}
				break;
			}
		}
		
	}
}
/******************************************************************
 * submit screen functions
 *******************************************************************/
function submitJSP(jsp, cmd, opt1, opt2) {
	if(checkSubmit()) {
		waitbox(1);
		if (jsp) {
			df0.action=jsp;
		}
		df0.SCRNCMD.value=cmd;
		df0.SCRNOPT1.value=opt1;
		df0.SCRNOPT2.value=opt2;
		df0.method="POST";
		df0.target="_top";
		df0.submit();
	}
}

function submitScreen(screenNext, cmd, option, option2) 
{
	clearMainMenu();
	if(checkSubmit()) 
	{
		submitScreenBase(screenNext, cmd, option, option2);
	}
}

function submitScreenBase(screenNext, cmd, option, option2, targ, menu, scrnfrme)
{
	df0 = document.forms[0];
	waitbox(1);

	df0.target="ContentFrame";
	df0.SCRNFRME.value="Content";
	if (screenNext) {
		df0.SCRNDEST.value=screenNext;
	}
	else {
		df0.SCRNDEST.value=df0.SCRNSRCE.value;
	}
	if (cmd) {
		df0.SCRNCMD.value=cmd;
	}
	if (option && option != null) {
		df0.SCRNOPT1.value=option;
	}
	if (option2 && option2 != null) {
		df0.SCRNOPT2.value=option2;
	}
	if (targ && targ != null) {
		df0.target=targ;
		if (!scrnfrme || scrnfrme == null)
			df0.SCRNFRME.value=targ;
		else
			df0.SCRNFRME.value=scrnfrme;
	}
	if (menu && menu!=null) {
		if (df0.SCRNMENU) {
			df0.SCRNMENU.value=menu;
		}
	}
	df0.action=ServletPath;
	df0.method="POST";
	df0.submit();
}
function submitScreenMain(screenNext, cmd, option, option2) 
{
	clearMainMenu();
	var cf = parent.ContentFrame;
	var n = cf.document.forms[0].SCRNSRCE.value;
	if(checkSubmit()) 
	{
		if ((n == "ORDERFORM" || n =="ITEMREL" || n == "ITEMSUB" || n == "QUICKADD" || n =="PLACEORDER")
			&& (cmd =="createorder" || screenNext =="IMPORTOR" || screenNext == "IMPORTSC"))
		{
			alert(NLS_StandardPleaseExitOrder);
			readySubmit=true;
			cmReady=true;
			parent.MenuFrame.cmReady=true;
			return;
		}
		submitScreenBase(screenNext, cmd, option, option2,"","main");
	}
}
function submitScreenParent(screenNext,cmd,opt1,opt2) {
	clearMainMenu();
	if(checkSubmit())
	{
		submitScreenBase(screenNext, cmd, opt1,opt2, window.opener.name,null,"Content");
		window.opener.waitbox(1);
	}
}
function submitScreenTop(screenNext, cmd, option, option2, menu) 
{
	if(checkSubmit()) 
	{
		submitScreenBase(screenNext, cmd, option, option2, "_top", menu);
	}
}

function trim(string) {
	if (string != null) {
		var re = /^\s\s*(.*)\s*\s$/;
		var temp = string.replace(re,"$1");
		if (temp == " ") {
			return "";
		} else {
			return temp;
		}
	}
	else {
		return "";
	}
}

function submitScreenToPopup(screenNext, cmd, option, option2, popupwinname, width, height, enable, menu) 
{
	if(checkSubmit()) 
	{
			var name,frameWidth,frameHeight;
			if (popupwinname && popupwinname != null)
				name = popupwinname;
			else
				name = "popupwin";
			if (self.innerWidth)
			{
				frameWidth = self.innerWidth;
				frameHeight = self.innerHeight;
			}
			else if (document.documentElement && document.documentElement.clientWidth)
			{
				frameWidth = document.documentElement.clientWidth;
				frameHeight = document.documentElement.clientHeight;
			}
			else if (document.body)
			{
				frameWidth = document.body.clientWidth;
				frameHeight = document.body.clientHeight;
			}
			else {
				frameWidth = screen.width;
				frameHeight = screen.height;
			}
			if (!width)
				width = (frameWidth*8)/10;
			if (!height)
				height = (frameHeight*8)/10;
			var left = (frameWidth-width)/2;
			var top = (frameHeight-height)/2;
			var win = openWindow("",name,height,width,null,true);
			submitScreenBase(screenNext, cmd,option,option2,name,menu,"Content");
			win.scroll(0,0);	//this is avoiding an apparent IE issue where the new window doesn't repaint
			if (enable) {
				readySubmit=true;
				cmReady=true;
				parent.MenuFrame.cmReady=true;
			}
			waitbox(0);
	}
}

function unload() {
	if (window.opener.readySubmit != null) {
		window.opener.readySubmit=true;
		window.opener.cmReady=true;
		window.opener.parent.MenuFrame.cmReady=true;
	}
}

function upC(field)
{
	field.value = field.value.toUpperCase();
}

function valField(fld, checkLength) 
{
	var val = fld.value;
	var type = fld.type;
	if (val != null && val.length && type != null && type == 'text') {
		for (var x=0; x<val.length; x++) {
			if (!validateKey(val.charAt(x), fld, x)) {
				fld.value=fld.defaultValue;
// fld.select();
				fld.focus();
				return false
			}
			if (checkLength != null && checkLength == true) {
				var val2 = trim(val);
				if (val2.length <=0) {
					alert(NLS_RequiredFieldNotBlank);
					fld.focus();
					return false
				}
			}
		}
	}
	else if (checkLength != null && checkLength == true) {
		if (val == null || trim(val).length <= 0) {
			alert(NLS_RequiredFieldNotBlank);
			fld.focus();
			return false
		}
	}

	if (fld.id == "date") {
		if (dateConvert(fld.value) <= 0) {
//			fld.select();
			fld.focus();
			alert(NLS_StandardInvalidDate+theDateFormat);
			fld.value=fld.defaultValue;
			removeCalendar();
			return false
		}
	}
	if (fld.id == "de") {
		if (dateConvert(fld.value) < 0) {
//			fld.select();
			fld.focus();
			alert(NLS_StandardInvalidDate+theDateFormat);
			fld.value=fld.defaultValue;
			removeCalendar();
			return false
		}
	}
	if (window.specialProcessing) {
		return specialProcessing(fld);
	}
	else {
		return true;
	}
}
// key press validation
function validateKey(key, field, idx)
{
	var type = field.id;
	if (type == "") {
		return true;
	}
	var validationString = "";
	var vsAlpha = NLS_ValidationAlpha;
	var vsNumeric = NLS_ValidationNumeric;
	var vsSpecial = NLS_ValidationSpecial;
	var vsLimited = NLS_ValidationLimited;
	var vsSpace = " ";
	switch (type) {
		case 'an' :
			validationString = vsAlpha + vsNumeric + "- ";
			break;
		case 'alphanumericnospace' :
			validationString = vsAlpha + vsNumeric + "-";
			break;
		case 'email' :
			//this list is from RFC 2822: http://tools.ietf.org/html/rfc2822#section-3.2.4
			validationString = vsAlpha + vsNumeric + "!#$%&'*+-/=?^_`{|}~@.";
			break;	
		case 'ans' :
		case 'alphanumericspecialchars' :
			validationString = vsAlpha + vsNumeric + vsSpecial;
			break;			
		case 'anl' :
			validationString = vsAlpha + vsNumeric + vsLimited;
			break;			
		case 'anss' :
			validationString = vsAlpha + vsNumeric + vsSpecial +vsSpace;
			break;			
		case 'a' :
		case 'alpha' :
			validationString = vsAlpha;
			break;
		case 'n' :
		case 'numeric' :
			validationString = vsNumeric;
			break;
		case 'nd' :
			validationString = vsNumeric + ".";
			break;
		case 'date' :
		case 'de' :
			validationString = vsNumeric + getDateSeperator();
			break;
		case 'delimiter' :
			validationString = "@*~#$%^,+=|";
			break;
		case 's' :
			validationString = " ";
			break;
		case 'wh' :
			validationString = vsAlpha + vsNumeric + ",.<:>!@#$%^&*()~`[];?/=+_ ";
			break;
		case 'search' :
			validationString = vsAlpha + vsNumeric + "-=[];,./~!@#$^&*()_+{}|:<>? ";
			break;
		default :
			validationString = "";
	}

	if ((validationString).indexOf(key) > -1) {
		if (type == 'nd') {
			return (checkForMoreThanOneDecimal(field,key,idx));
		}
		if (window.valSpecial) {
			return valSpecial(field, key);
		}
		else {
			return true;
		}
	}
	else {
		var message=NLS_StandardFieldEntryInvalid;
		switch (type) {
			case 'an' :
				message +=NLS_StandardAlphaNumeric;		
				break;	
			case 'alphanumericnospace' :
			case 'email' :
				message +=NLS_StandardAlphaNumericNoSpaces;		
				break;	
			case 'alphanumericspecialchars' :
				message+=NLS_StandardAlphaNumericList+vsSpecial;
				break;			
			case 'nd' :
				message+=NLS_StandardNumeric;		
				break;
			case 'n' :
				message+=NLS_StandardNumericNoDecimal;		
				break;
			case 'date' :
			case 'de' :
				message+=NLS_StandardDate+theDateFormat;
				break;
			case 'delimiter' :
				message+= "@*~#$%^,+=|";
				break;
			case 'space' :
				message+=NLS_StandardCheckbox;		
				break;
			case 'search' :
				message+=NLS_StandardAlphaNumericSpecialList;
				break;
			default :
				message+=NLS_StandardValidOnly;
		}
		alert(message);
		if (window.event) {
			window.event.keyCode=0;
		}
		return false;
	}
}

/*************************************************************************************
* vdb(fld, e) Validate onKeyDown in the body
*
* param     fld  - input field
*           e    - event
**************************************************************************************/
function vdb(fld, e)
{
	fld = 	e.target ? e.target : event.srcElement;
	var chr;
	var keychar;
	var rc = true;

	if (window.event) {
		chr = window.event.keyCode;
	}
	else {
		chr = e.which;
	}
	keychar = String.fromCharCode(chr);
// alert("key: "+keychar+"; chr: "+chr);
	if (chr == 8) { //backspace
		if (fld == null || fld.type != "text") {
			if (window.event) {
				window.event.keyCode = 0;
			}
			else {
				e.cancelBubble = true;
				e.returnValue = false;
				return false;
			}
		}
	}
	else if (chr == 36 || chr == 38 || chr == 40 || chr == 33 || chr == 34) {
		var shiftKeyFlag=false;
		if (e != null) {
			shiftKeyFlag=e.shiftKey;
		}

		if (window.event) {
			window.event.keyCode = 0;
		}

		if (fld != null && fld.name != null) {
			rc = valField(fld);
		}

		if (chr == 40 || chr == 38) {
			if (rc && fld.type != null && fld.type != "select-one" && fld.type != "select-multiple") {
				if (chr == 40) {
					//Down Arrow
					isUp=false;
				}
				else  {
					//Up Arrow
					isUp=true;
				}
				if (shiftKeyFlag) {
					nextField(fld, 'left');
				}
				else {
					if (valEnter) {
						valEnter(fld);
					}
					else {
						nextField(fld);
					}
				}
			}
		}
		else if (chr == 33 && rc) {
			if (df0.navbutton) {
				//PageDown button
				if (shiftKeyFlag) {
					goPageNav('down','left',true);
				}
				else {
					goPageNav('down',null,true);
				}
			}
		}
		else if (chr == 34 && rc) {
			if (df0.navbutton) {
				//PageUp button
				if (shiftKeyFlag) {
					goPageNav('up','left',true);
				}
				else {
					goPageNav('up',null,true);
				}
			}
		}
		else if (chr == 36) {
			//Home key
			window.location.hash = '#pagemenutop';
		}
	}	
	else if (chr == 49) {	//1
		var ctrlKeyFlag=false;

		if (e != null) {
			ctrlKeyFlag=e.ctrlKey;
		}
		if (ctrlKeyFlag) {
			setFocus('searchdesc');
			return false;
		}
	}	
	return rc;
}

/*************************************************************************************
* vk(fld, e) Validate onKeyPress
*
* param     fld  - input field
*           e    - event
**************************************************************************************/
function vk(fld, e)
{
	var chr;
	var keychar;

	if (window.event) {
		chr = window.event.keyCode;
	}
	else {
		chr = e.which;
	}
	keychar = String.fromCharCode(chr);
	if (chr == 8 || chr == 0) {	
		return true;
	}
	else if (chr == 13) {
		// the enter key was pressed
		isUp=false;
		if (window.valEnter) {
			if (window.event) {
				window.event.keyCode = 0;
			}
			return valEnter(fld);
		}
		return true;
	}	
	return (validateKey(keychar, fld));
}

function vok(fld, e)
{
	var fldClicked = 	e.target ? e.target : event.srcElement;
	highLightRow(fldClicked)
}

// Loading message on/off
function waitbox(onoff)
{
	var temp = document.getElementById('waitbox');
	if (temp) {
		if (onoff == 1) {
			temp.style.visibility="visible";
			changeDisplay("hidden");
		}
	  	else {
			temp.style.visibility="hidden";
			changeDisplay("visible");
			displayAlerts();
		}
	}
}

/******************************************************************
 * validate the value is between the low and high values passed in
 *******************************************************************/
function numericTest(value, lowValue, highValue) {

	pattern = /^[0-9]*$/;
	if(pattern.test(value)==false) {
    	alert(NLS_NumberValid);
		return true;
    }

    else if (lowValue > value || highValue < value) {
	    alert(NLS_NumberOutOfRange);
		return true;
    }

}

function formatDate(month, day, year, format) {
	if (month < 10) month = '0'+month;
	if (day < 10) day = '0'+day;
	return format.replace(/MM/,month).replace(/dd/, day).replace(/yyyy/, year);
}

function getDateForCalendar(v) {
	var yi = theDateFormat.indexOf('y');
	var di = theDateFormat.indexOf('d');
	var mi = theDateFormat.indexOf('M');
	var y = v.substring(yi,yi+4);
	var m = v.substring(mi,mi+2);
	var d = v.substring(di,di+2);
	var o = y+m+d;
	return o;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft, curtop];
}

function dateSelected(month, day, year, format, fieldName) {
	if (month) {
		var v = formatDate(month,day,year,format);
		var fld = eval("df0."+fieldName);
		fld.value = v;
		if (fld.onchange) {
  			fld.onchange();
  		}
	}
	var node = document.getElementById("califrame");
	node.parentNode.removeChild(node);
}

function openCalendar(target, fieldName, startDate, endDate, validDates, pickup, calendarTop, calendarLeft) {
	var parms = "fieldname="+fieldName;
	parms += "&date="+getDateForCalendar(eval("df0."+fieldName).value);
	if (startDate) {
		if (startDate.length > 8) {
			parms += "&startdate="+getDateForCalendar(startDate);
		}
		else {
			return;
		}
	} 
	if (endDate) {
		parms += "&enddate="+getDateForCalendar(endDate);
	}
	if (validDates && !pickup) {
		parms += "&dates="+validDates;
	}
	var iframe = document.createElement("iframe");
	iframe.src = "PopupCalendar.jsp?"+parms;
	iframe.width = "300px";
	iframe.height = "300px";
	iframe.scrolling = "no";
	iframe.style.position = "absolute";
	iframe.style.zIndex = "9999";
	iframe.name = "califrame";
	iframe.id = "califrame";
	if (calendarTop && calendarLeft) { 
		iframe.style.left = calendarLeft;
		iframe.style.top = calendarTop;
	} else {
		var pos = findPos(target);
		iframe.style.left = pos[0];
		iframe.style.top = pos[1];
	}  
	document.getElementsByTagName("body")[0].appendChild(iframe);
}

function reloadCalendar(target, fieldName, startDate, endDate, validDates) {
	var iframe = document.getElementById('califrame');
	if (iframe != null) {
		var pickup = df0.pos?df0.pos.checked:false;
		var calendarPos = eval("df0."+fieldName);
		var calendarLeft = iframe.style.left;
		var calendarTop = iframe.style.top;
		iframe.parentNode.removeChild(iframe);
		openCalendar(target, fieldName, startDate, endDate, validDates, pickup, calendarTop, calendarLeft);
	}
}

function removeCalendar() { 
	var iframe = document.getElementById('califrame');
	if (iframe != null) {
		iframe.parentNode.removeChild(iframe);
	}
}

/******************************************************************
 * checkMinMaxOrder - check the min/max order quanitity
 *******************************************************************/
 function checkMinMaxOrder(fld) 
 {
 	var userValue = parseInt(fld.value);
 	
 	// Repeating digits check
 	repeatingDigitsCheck(fld);
 	
 	// Max check
 	var maxName = "mx_" + getFieldIndex(fld);
 	var maxOrderQty = document.getElementById(maxName);
 	if (maxOrderQty != null && maxOrderQty.value > 0) {
 		var maxValue = parseInt(maxOrderQty.value);
 		if (userValue > maxValue) {
 			//User ordered too many items, give user an alert
 			var maxOrderAction = document.getElementById("maxQtyAction").value;
 			if (maxOrderAction == 'W') {
 	 			return confirm(NLS_MaxOrderQuantityReached + " " + NLS_MaxOrderQuantityAmount + " " + maxValue+"\n"+NLS_SelectOKCancel);
 			}
 			// Determine whether to change value or not
 			else if (maxOrderAction == 'E') {
 	 			alert(NLS_MaxOrderQuantityReached + " " + NLS_MaxOrderQuantityAmount + " " + maxValue);
 			    //In case of flag error, reset input to valid amount
 				fld.value = fld.defaultValue;
 				fld.focus();
 				return false;
 			}
 			else {
 				return true;
 			}
 		}
 	}	
 	
 	//Min check
 	var minName = "mi_" + getFieldIndex(fld);
 	var minOrderQty = document.getElementById(minName);
 	if (minOrderQty != null && minOrderQty.value > 0) {
 		var minValue = parseInt(minOrderQty.value);
 		if (userValue > 0 && userValue < minValue) {
 			//User ordered too few items, just change user's input quantity.  No warnings given
 			fld.value = minValue;
 			fld.focus();
 			return false;
 		}
 	}	
 	
 	return true;
 }

/*
logwin = window.open("","jsLogWin");
logwin.document.open('text/plain');
logwin.document.write("<br>**** JavaScript Log *****");

function jslog(msg){
	var curdate = new Date();
	if (logwin && logwin.document) {
		logwin.document.write("\n<br>"+curdate.getDate()+" "+curdate.getHours()+":"+curdate.getMinutes()+":"+curdate.getSeconds()+"."+curdate.getTime().toString().substring(10)+"  "+msg)
	}
}
*/

/******************************************************************
 * rounding - ensure pricing is shown in proper dollars & cents
 *******************************************************************/
function round2Decimals(amount) { 

    //Round to second decimal
    var totalAmount = amount*1;
	totalAmount = totalAmount * 100;
	totalAmount = Math.round(totalAmount);
	totalAmount = totalAmount / 100;
			
	// ensure 2 decimal places
	var strAmount = String(totalAmount);
	index = strAmount.lastIndexOf(".");
	if (index == -1) {
		strAmount = strAmount + ".00";
	}
	else if (index == strAmount.length - 1) {
		strAmount = strAmount + "00";
	}
	else if (index == strAmount.length - 2) {
		strAmount = strAmount + "0";
	}
			
	// Truncate any characters beyond the second digit after the decimal point
	if (index != -1 && (strAmount.length > (index + 3))) {
		strAmount = strAmount.substring(0,(index+3));
	}
	return strAmount;
}

function round3Decimals(amount) { 

    //Round to third decimal
    var totalAmount = amount*1;
	totalAmount = totalAmount * 1000;
	totalAmount = Math.round(totalAmount);
	totalAmount = totalAmount / 1000;
	
	// Ensure 3 decimal places
	var strAmount = String(totalAmount);
	index = strAmount.lastIndexOf(".");
	if (index == -1) {
		strAmount = strAmount + ".000";
	}
	else if (index == strAmount.length - 1) {
		strAmount = strAmount + "000";
	}
	else if (index == strAmount.length - 2) {
		strAmount = strAmount + "00";
	}
	else if (index == strAmount.length - 3) {
		strAmount = strAmount + "0";
	}
	return strAmount;
}

function clearText(field){
	if (field.defaultValue == field.value) {
		field.value = "";
	}
}

function refreshMainMenu() {
	if (df0.SCRNCMD.value == null || df0.SCRNCMD.value == '') {
		window.opener.parent.ContentFrame.clearSubmit();
		window.opener.parent.ContentFrame.submitScreenTop(window.opener.parent.ContentFrame.document.forms[0].SCRNSRCE.value);
	}
}

//Standard guide function to warn another user is editing the same standard guide
function confirmEdit(page, standardGuideNumber) {
	if (confirm(NLS_StandardGuideEditConfirmation)) {
		submitScreen(page, "init", standardGuideNumber, 'confirmEdit');
	}
}

//Standard guide function to warn user standard guide version is old and changes could have occurred since checked-out
function confirmChanges(page, standardGuideNumber) {
	if (confirm(NLS_StandardGuideChangeConfirmation)) {
		//User wants to continue making changes to an old version of the standard guide
		submitScreen(page, "init", standardGuideNumber, 'confirmChanges');
	} else {
		//User wants all their changes removed and start over with edits
		submitScreen(page, "init", standardGuideNumber, 'removeChanges');
	}
}

function getWindowSize() {

	var myWidth = 0, myHeight = 0;
	
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight-42;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight-25;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight-25;
	}
	
	return [myWidth, myHeight];

}

function findPos(obj) {

	var curleft = curtop = 0;
	
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
	
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	
	}
	
	return [curleft, curtop];
}

function repeatingDigitsCheck(fld) { 
	//Repeating digits check
	var repeatingDigitsTurnedOn = df0.repeatingDigits;
	if (repeatingDigitsTurnedOn && repeatingDigitsTurnedOn.value == "true") { 
		if (repeatingDigits(fld.value)) { 
			if (!confirm(NLS_RepeatingDigitsCheck)) {		
				fld.value = fld.defaultValue;
				fld.focus();
				return false;
			}
		}	
	}
}

function repeatingDigits(realValue) { 
	var replacedValue = realValue.replace(/([0-9])\1/g,'$1');
	if (realValue == replacedValue) {
		return false;
	} else { 
		return true;
	}
}
