// 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;
}

function changeAdvertising(screen) {
	if (parent.LogoFrame.changeImg) {
		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("Too many decimals. Please enter only one decimal.");
			myfield.focus();
			return false;
		}
	}
	return true;
}
function checkSubmit() {
	if ( readySubmit ) {
		readySubmit=false;
		return true;
	} else {
		alert("Form processing. Please wait.");
		return false;
	}
}
/******************************************************************
 * closethis()
 * 
 * Allows the user to select whether or not a print has completed
 * so that the window will close
 *******************************************************************/
function closethis(timeout)
{
	if (confirm("Is printing complete?\nSelect OK to close the window you are printing.\nSelect Cancel to continue printing."))
	{
		window.close();
	}
	else
	{
		if (!timeout) {
			timeout = 60000
		}
		setTimeout('closethis('+timeout+');', timeout);
	}
}
function dateConvert(date) {
	var monthDays = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
	var newDate = -1;
	var sep = "/";
	if (date != null) {
		if (date.length==10) {
			var dtElem = date.split(sep);
			var mm=(dtElem[0]*1)-1;
			var dd=dtElem[1]*1;
			var yyyy=dtElem[2]*1;
			if (mm < 0 || mm > 11 || dd < 1 || dd > monthDays[mm] || yyyy > 2999) {
				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 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.getYear();
		if (year < 100) {
			year = "19"+year;
		}
		stringDate = ""+month+"/"+day+"/"+year;
	}
	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 displayComp() 
{
	alert("This feature is disabled due to browser incompatibilities.\nTo enable this functionality, please upgrade your browser.");
}

function initjs() 
{
	df0 = document.forms[0];
	if (window.initVars) {
		initVars();
	}
}

function getFieldIndex(fld)
{
	if (fld.name.indexOf('_') != -1) {
		parts = fld.name.split('_');
		return parts[1]*1;
	}
	else {
		return -1;
	}

}

function getFieldPrefix(fld)
{
	if (fld.name.indexOf('_') != -1) {
		parts = fld.name.split('_');
		return parts[0];
	}
	else {
		return fld.name;
	}

}

function getPopupLoading(contextPath) {
	var text = '<html><head><title>Loading...</title>\n<link rel=stylesheet href="'+contextPath+'/prodtheme/general.css" type="text/css">\n';
	text += '<script language="javascript">\n';
	text += 'function loadwaitboximage() {\n';
	text += 'img = document.getElementById("waitboximage");\n';
	text += 'if (img) { img.src = img.src;}\n}\n';
	text += '</script></head>\n<body onload="loadwaitboximage();"><div id=waitbox align=center>Loading...<br><br><img id="waitboximage" border=0 src="'+contextPath+'/prodtheme/prodimage/waitbox.gif"></div><body></html>\n';
	return text;
}

function goExport(parm)
{	
	submitScreenBase('', 'export', parm, '', 'ExportFrame');
	df0.SCRNCMD.value="";
	waitbox(0);
}
function goOrderCreate(key, isOrderByInventory)
{
	var dest = 'ORDERFORM';
	if (isOrderByInventory) {
		if (confirm("Do you want to use inventory quantities to set quantities on this order?")) {
			dest = 'ORDERBYINVENTORY';
		}
	}
	submitScreenMain(dest,'createorder','C',key)
}
/******************************************************************
 * goPageNav(movement)
 * 
 * Performs movement, saves between moves
 *******************************************************************/
function goPageNav(movement, panel, popups)
{
	if (popups)
		submitScreenPopup('', "movement", movement, panel)
	else
		submitScreen('', "movement", movement, panel)
}

function nextField(myfield, pannel)
{
	var idx = getFieldIndex(myfield) + 1;
	var prefix = getFieldPrefix(myfield);

	var start = 0;
	var end = 0;
	if (pannel != null) {
		var idxFirst = eval("df0.indexfirst"+pannel);
		var idxLast = eval("df0.indexlast"+pannel);
		start = idxFirst.value*1;
		end = idxLast.value*1;
	}
	else {
		start = df0.indexfirst.value*1;
		end = df0.indexlast.value*1;
	}
	var count = end-start+1;

	for (x=0; x<count; x++) {
		if (idx > end) {
			idx = start;
		}
		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 += 1;
			}
			else {
				fld.focus();
				if (fldType != null && fldType == "text")	{
					fld.select();
				}
				break;
			}
		}
		else {
			idx += 1;
		}
	}
}

/******************************************************************
 * nextField(field)
 *******************************************************************/
function nextFieldElement(myfield)
{
	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;
					break;
				}
			}
			for (x=0; x<fld.length; x++) {
				if (idx >= fld.length) {
					idx = 0;
				}
				fldType = fld[idx].type;
				if (fldType == null || fldType == "hidden" || fld[idx].disabled || fld[idx].style.visibility == "hidden")	{
					idx += 1;
				}
				else {
					fld = fld[idx]
					break;
				}
			}
		}
		fld.focus();
		fldType = fld.type;
		if (fldType != null && fldType == "text")	{
			fld.select();
		}
	}
}

function oiw(item, wh) {
	openWindow("ViewItem.jsp?itemNbr=" + item + "&whseNbr=" + wh,null,410,450,'scrollbars=yes');
}

/******************************************************************
 * 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);
}

function openSearchWindow()
{
	openWindow('SearchCrit.jsp','SearchCrit',400,500,'scrollbars=yes');
}

/********************************************************
* openWindow
*********************************************************/
function openWindow(url,name,height,width,extraverbiage,returnhandle) 
{
 	var size = "";
   	var xPos = 0;
   	var yPos = 0;
	var vExtra = "";
	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;
}

/******************************************************************
 * printthis()
 * 
 * Brings up 'printer' dialogue box
 *******************************************************************/
function printthis(timeout)
{
	if (!timeout) {
		timeout = 30000
	}
	window.print();
//	setTimeout('closethis('+timeout+');', timeout);
}

function setFocus(fieldName, select)
{
	if (select == null) {
		select = 1;
	}
	var field = eval('df0.'+fieldName);
	if (field != null) {
		if (field.type != "hidden") {
			field.focus();
		}
		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 != null) {
				var fldType = field.type;
				if (fldType == null || fldType == "hidden" || field.disabled || field.style.visibility == "hidden" || field.readOnly)	{
					continue;
				}
				field.focus();
				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,popups,contextPath,popupwinname,width,height,enable,menu) 
{
	if(checkSubmit()) 
	{
		if (popups) {
			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 = window.open("",name,'left='+left+',top='+top+',width='+width+',height='+height+',toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=yes');
			var win = openWindow("",name,height,width,'toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=yes',true);
			win.document.write(getPopupLoading(contextPath));
			submitScreenBase(screenNext, cmd,option,option2,name,menu,"Content");
			win.loadwaitboximage();
			win.scroll(0,0);	//this is avoiding an apparent IE issue where the new window doesn't repaint
			if (enable) {
//				enableButtons();
				readySubmit=true;
			}
			waitbox(0);
		}
		else
			submitScreenBase(screenNext, cmd, option, option2,null,menu);
	}
}
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,popups,contextPath,popupwinname) 
{
	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("Please exit your current order before creating a new one");
			readySubmit=true;
			return;
		}
		if (popups) {
			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;
			}
			var width = (frameWidth*8)/10;
			var height = (frameHeight*8)/10;
			var left = (frameWidth-width)/2;
			var top = (frameHeight-height)/2;
//			var win = window.open("",name,'left='+left+',top='+top+',width='+width+',height='+height+',toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=yes');
			var win = openWindow("",name,height,width,'toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=yes',true);
			win.document.write(getPopupLoading(contextPath));
			submitScreenBase(screenNext, cmd, option, option2,name,"main","Content");
			win.loadwaitboximage();
			win.scroll(0,0);
			waitbox(0);
		}
		else {
			submitScreenBase(screenNext, cmd, option, option2,"","main");
		}
	}
}
function submitScreenParent(screenNext,cmd) {
	if(checkSubmit()) 
	{
		submitScreenBase(screenNext, cmd, null,null, window.opener.name,null,"Content");
		window.opener.waitbox(1);
	}
}

function submitScreenPopup(screenNext,cmd,option1,option2) {
	if(checkSubmit()) 
	{
		submitScreenBase(screenNext, cmd, option1,option2, window.name,null,"Content");
	}
}
function submitScreenTop(screenNext, cmd, option, option2, menu, popups) 
{
	if(checkSubmit()) 
	{
		if (popups) {
			submitScreenBase(screenNext, cmd, option, option2, "MainWindow", menu,"_top")
			window.opener.waitbox(1);
		}
		else {
			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 unload(popups) {
	if (popups && window.opener) {
		if (window.opener.readySubmit != null) {
			window.opener.readySubmit=true;
		}
	}
}

function upC(field)
{
	field.value = field.value.toUpperCase();
}

function valField(fld) 
{
	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 (fld.id == "date") {
		if (dateConvert(fld.value) <= 0) {
//			fld.select();
			fld.focus();
			alert("Invalid date. Please enter a date in the following format:  MM/DD/YYYY");
			fld.value=fld.defaultValue;
			return false
		}
	}
	if (fld.id == "de") {
		if (dateConvert(fld.value) < 0) {
//			fld.select();
			fld.focus();
			alert("Invalid date. Please enter a date in the following format:  MM/DD/YYYY");
			fld.value=fld.defaultValue;
			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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	var vsNumeric = "0123456789";
	var vsSpecial = "`-=[];,./~!@#$%^&*()_+{}|:<>?";
	var vsSpace = " ";
	switch (type) {
		case 'an' :
			validationString = vsAlpha + vsNumeric + "- ";
			break;
		case 'alphanumericnospace' :
			validationString = vsAlpha + vsNumeric + "-";
			break;
		case 'email' :
			validationString = vsAlpha + vsNumeric + "-@._";
			break;	
		case 'alphanumericspecialchars' :
			validationString = vsAlpha + vsNumeric + vsSpecial;
			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 + "/";
			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 == 'numericdecimal') {
			return (checkForMoreThanOneDecimal(field,key,idx));
		}
		if (window.valSpecial) {
			return valSpecial(field, key);
		}
		else {
			return true;
		}
	}
	else {
		var message="The entry for this field is invalid.\n\nPlease ";
		switch (type) {
			case 'an' :
				message +="enter alphanumeric characters.";		
				break;	
			case 'alphanumericnospace' :
			case 'email' :
				message +="enter alphanumeric characters without spaces.";		
				break;	
			case 'alphanumericspecialchars' :
				message+="enter alphanumeric characters (without spaces) and/or the following characters: "+vsSpecial;
				break;			
			case 'nd' :
				message+="enter numeric characters only and/or a decimal point.";		
				break;
			case 'n' :
				message+="enter numeric characters only.";		
				break;
			case 'date' :
			case 'de' :
				message+="enter a date in the following format:  MM/DD/YYYY";
				break;
			case 'delimiter' :
				message+= "@*~#$%^,+=|";
				break;
			case 'space' :
				message+="either press the space bar to check or uncheck this checkbox,\nor click with mouse.";		
				break;
			case 'search' :
				message+="enter alphanumerics and/or -=[];,./~!@#$^&*()_+{}|:<>?";
				break;
			default :
				message+="enter valid characters only.";
		}
		alert(message);
		if (window.event) {
			window.event.keyCode=0;
		}
		return false;
	}
}

/*************************************************************************************
* vk(fld, e, popups) Validate onKeyPress
*
* param     fld  - input field
*           e    - event
**************************************************************************************/
function vk(fld, e, popups)
{
	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
		if (window.valEnter) {
			if (window.event) {
				window.event.keyCode = 0;
			}
			return valEnter(fld,popups);
		}
		return true;
	}	
	return (validateKey(keychar, fld));
}
// 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");
		}
	}
}

