// This version of site.js is required for sites running 
// TableCatalog V1.4 or greater.  The submit buttons in this version
// calls submitForm().  Previous versions called profilesearch().


/****** Customize Here *************/
var requireIntQty=true;
var fraction=1;
var qtyMessage="Please enter a whole number.  Online ordering doesn't accept fractional quantities.";
var qtyFractionMessage="You may only order in fractions of "+fraction+".  Please modify your order quantity.";
var requirePO=false;
var poFieldName="PONOONE";
var useRollup=false;		// Calculate rollup number for PONO
var poMessage="Please provide a PO number.  If you do not have an actual PO, you may enter your name."
var emailAddressMessage="Please provide an e-mail address for us to send you an order confirmation."
var pageLoadingMsg="This page is still loading.  Please wait a few moments and try again.";
var outOfStockMessage="We're sorry, but there are only ~avqty in stock. " ;
var substituteMessage="We recommend substituting item ~substItem." ;
var imageViewWidth=730;
var imageViewHeight=600;
var toolTipOffsetX=0;
var toolTipOffsetY=0;
var minOrderWarningLeft=120;
var minOrderWarningTop=70;
var calculateGrossSales=false;

/**** BEGIN Custom Functions ****/

function getDefaultPONO(sPONO, sOTYP) {
	return sPONO;
}

/**** END Custom Functions ****/

/**************************************************/
/*************************************************
 * Initialize here, but may be reset by E-Commerce 
 * application;
 ***************************************************/
 var requireEmailAddress=false;

/***************************************************
* processing=true disables any form submits.  It's
* used to prevent users from breaking their pipe by
* submitting another request before the first one
* is done processing.  This is also important when
* using incremental page loading.  The onload event
* needs to set processing=false.
*
* As of 12/2005 this is only used at Indy Fruit because
* support paging and incremental page loading.
****************************************************/
var processing=true;
/**************************************************/


var NS4 = (document.layers) ? true : false;
var IE4 = (document.all);
var firefox = (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent));  
var IE7 = (navigator.appVersion.indexOf("MSIE 7.")==-1) ? false : true;	 

// Used in findInPage()
var win = this;
var findCount   = 0;

var cancelsubmit=false;
var kerchunkEnabled = false; // StandardTableCatalog outputFormResults() 
							 // flips this to true for the catalog page
function customOnLoad(){
	processing=false;
	if (!kerchunkEnabled) placeFocus();
}

function setFractionMessage(){
	qtyFractionMessage="You may only order in fractions of "+fraction+"  Please modify your order quantity.";
	return qtyFractionMessage;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



function DLDTFocus() {
	document.UIservletForm.DLDT.value = document.UIservletForm.DLDT.value.replace("/","").replace("/","");
}
function profilesearchall() {
	if(document.UIservletForm.TEXT != null){
		document.UIservletForm["TEXT"].value="";
		searchSubmit();
	}else{
		window.location = "http://orders.oletyme.com/ppro/online?command=catalogpage&name=profile&parm=nothing";
	}
}
//function profilesearch() {
//		var searchtext = document.UIservletForm["TEXT"].value;
//		if (searchtext != "") {
//			window.location = "http://orders.oletyme.com/ppro/online?command=catalogpage&name=profile&parm=" + searchtext;
//		} else {
//			document.UIservletForm.submit();
//		}
//}

function commoditySearchChange() {
	if (document.getElementById('catalogready').value == "false") {
		// check to see if catalog retrieval is complete
		submitAjaxForHTML('http://orders.oletyme.com/ppro/online?command=commlistready.ajax', 'catalog_commodity_ready');
	} 
	if (document.getElementById('catalogready').value == "false") {
		document.getElementById('commselect1').checked = true;
		document.getElementById('commselect2').checked = false;
		alert("Your searchable catalog is being built, please try again in 30 seconds.");
		return;
	}
	if (document.getElementById('catalog_commodity_region').childNodes == null ||
				document.getElementById('catalog_commodity_region').childNodes.length == 0) {
		// Trigger request that builds catalog commodity list
		if (document.getElementById('COMMSELECTED') != null) {
			submitAjaxForHTML('http://orders.oletyme.com/ppro/online?command=populatecommlist.ajax&COMMSELECTED=' + document.getElementById('COMMSELECTED').value, 'catalog_commodity_region');
		} else {
			submitAjaxForHTML('http://orders.oletyme.com/ppro/online?command=populatecommlist.ajax', 'catalog_commodity_region');
		}
	}
	if (document.getElementById('commselect2').checked) {
		document.getElementById('profile_commodity_region').style.display = "none";
		document.getElementById('catalog_commodity_region').style.display = "inline";
	} else {
		document.getElementById('profile_commodity_region').style.display = "inline";
		document.getElementById('catalog_commodity_region').style.display = "none";
	} 
}

function commsearch() {
	if (processing==true){
		alert(pageLoadingMsg);
		return;
	}
	var sCommodity = document.getElementById('profile_comm_values').value;
	if (trim(sCommodity) == "") return;
	document.UIservletForm["parm"].value= "nothing";
	document.UIservletForm["DESC"].value= sCommodity;
	document.UIservletForm["COMM"].value= sCommodity;
	document.UIservletForm["nextCommand"].value="productsearchsubmit";
	document.UIservletForm["name"].value="profile";
	try {
		document.UIservletForm["PAGE"].value="0";
	} catch(e) { }
	document.UIservletForm.submit();
}

function searchSubmit() {
		cancelsubmit=false;
		var searchtext = document.UIservletForm["TEXT"].value;
		
		if(document.UIservletForm.searchselect != null && document.UIservletForm.searchselect[1].checked){
			catalogSearchSubmit(searchtext);
		}else{
			if(searchtext=="") searchtext="nothing";
			profilesearch(searchtext);
		}
}

function profilesearch(searchtext) {
		if (processing==true){
			alert(pageLoadingMsg);
			return;
		}
		if (searchtext == '') {
			searchtext = document.UIservletForm["TEXT"].value;
		}
		if (searchtext != "") {
			document.UIservletForm["parm"].value=searchtext;
			document.UIservletForm["nextCommand"].value="catalogpage";
			document.UIservletForm["name"].value="profile";
			try{document.UIservletForm["PAGE"].value="0";}catch(e){}
			document.UIservletForm.submit();
		}
}
function relatedunits(sDesc) {
	if (processing==true){
		alert(pageLoadingMsg);
		return;
	}
	document.UIservletForm["parm"].value= "nothing";
	document.UIservletForm["DESC"].value= sDesc;
	document.UIservletForm["UNITS"].value= "Y";
	document.UIservletForm["nextCommand"].value="productunits";
	document.UIservletForm["name"].value="profile";
	try {
		document.UIservletForm["PAGE"].value="0";
	} catch(e) { }
	document.UIservletForm.submit();
}
function profilepage(page) {
		if (processing==true){
			alert(pageLoadingMsg);
			return;
		}
		var searchtext = document.UIservletForm["TEXT"].value;
		if(searchtext=="") searchtext="nothing";
		document.UIservletForm["parm"].value=searchtext;
		document.UIservletForm["nextCommand"].value="catalogpage";
		document.UIservletForm["name"].value="profile";
		document.UIservletForm["PAGE"].value=page;
		processing=true;
		document.UIservletForm.submit();
}
function nextprofilepage(increment) {
	if(document.UIservletForm["PAGE"].value=="") document.UIservletForm["PAGE"].value="0";
	var thePage=parseInt(document.UIservletForm["PAGE"].value);
	thePage=thePage+increment;
	profilepage(thePage);

}

function commoditySearchSubmit() {
	if (processing==true){
		alert(pageLoadingMsg);
		return;
	}
	document.UIservletForm["parm"].value=document.UIservletForm["COMMSEARCH"].value;
	document.UIservletForm["nextCommand"].value="catalogpage";
	document.UIservletForm["name"].value="profile";
	document.UIservletForm["searchType"].value="comm";
	document.UIservletForm.submit();
}

function categorySearchSubmit() {
	if (processing == true){
		alert(pageLoadingMsg);
		return;
	}
	var s1 = "";
	var s2 = "";
	for (i1 = 1; i1 <= 9; i1++) {
		var s3 = document.UIservletForm["CATSEARCH" + i1].value;
		if (trim(s3) == "") continue;
		s1 = s1 + "|" + s3;
		s2 = s2 + i1; 
	}
	if (s1.length > 0) s1 = s1.substring(1); // remove first '|'
	document.UIservletForm["parm"].value=s1;
	document.UIservletForm["nextCommand"].value="catalogpage";
	document.UIservletForm["name"].value="profile";
	document.UIservletForm["searchType"].value="pmc" + s2;
	document.UIservletForm.submit();
}


function catalogSearchSubmit(searchtext) {
	if (processing==true){
		alert(pageLoadingMsg);
		return;
	}

	var text = searchtext.split(" ");
	if (text.length == 1 && !isNaN(searchtext)) {
		var length = searchtext.length;
		for (i = 0; i < (5 - length); i++){
			searchtext= "0" + searchtext;
		}		
	} else {
		for (i = 0; i < text.length; i++) {
			if (text[i].length < 3) {
				alert("Please enter at least 3 characters for your search criteria.");
				cancelsubmit = true;
				return false;
			}
		}
	}
	if (searchtext != "") {
		document.UIservletForm["DESC"].value = searchtext;
		document.UIservletForm["nextCommand"].value = "productSearchSubmit";
		processing = true;
		document.UIservletForm.submit();
	}
}
function catalogSearch() {
	window.location = "http://orders.oletyme.com/ppro/online?command=productsearch";
}
function submitForm() {
		if (processing==true){
			alert(pageLoadingMsg);
			return;
		}
		if(document.UIservletForm["nextCommand"]){
			document.UIservletForm["nextCommand"].value="";
		}
		processing=true;
		document.UIservletForm.submit();
}


function submitCatalogForm(){
	if(document.UIservletForm["nextCommand"]){
		document.UIservletForm["parm"].value="nothing";
		document.UIservletForm["nextCommand"].value="catalogpage";
		document.UIservletForm["name"].value="profile";
		
	}
	document.UIservletForm.submit();

}

function floatingMenuSearchOnEnterKey(event) {
	var code = 0;
	if (NS4){
		code = event.which;
	}else{
		code = event.keyCode;
	}
	if (code==13){
		profilesearch(document.UIservletForm['FM_PROFILESEARCH'].value);
	}

}
function searchOnEnterKey(event) {
	var code = 0;
	if (NS4){
		code = event.which;
	}else{
		code = event.keyCode;
	}
	if (code==13){
		event.keyCode=0;
		searchSubmit();
	}

}
function processEntryKeys(event, theField ) {
	if(theField.name=="ENTRYQTY"){
		submitEntryOnEnter(event, theField);
	}
	if(theField.name=="ENTRYPDNO"){
		processKeys(event);
	}
}

function submitEntryOnEnter(event, theField){
	var code = 0;
	if(!validateQuantity(theField, null)) return false;
	
	if (NS4){
		code = event.which;
	}else{
		code = event.keyCode;
	}
	if(code==13){
		submitEntryForm();
	}

}
function submitEntryForm(){
	return !cancelDuplicate()

}
function cancelDuplicate(){
	if(document.UIservletForm["cartItemList"]!=null){
		cartItems=document.UIservletForm.cartItemList.value;
		pdno=zeroPad(document.UISERVLET_ENTRY.ENTRYPDNO.value,5);
		if(cartItems.indexOf(pdno)>=0){
			return !confirm("You are adding a duplicate item to the order.");
		}
		
		
	}else{
		return false;
	}
}

function processKeys(event) {
	processKeys(event,"U&EFU&FUEU");
}
function processKeys(event, prevField) {
	var code = handleDownArrowAndEnter(event);
	if(code==38){
		if(document.UIservletForm[prevField]){
			document.UIservletForm[prevField].focus();
		}
		
	}
	return false;
}

function processCartKeys(event, currentField) {
	var code = handleDownArrowAndEnter(event);
	if(code==13 || code==40 || code==38){
		var fieldName = String(currentField.name);
		var underscorePosition = fieldName.lastIndexOf("_",fieldName.length);
		var fieldTypeName = fieldName.substring(0,underscorePosition);		 
		var index = fieldName.substr(underscorePosition+1);		 
		if(code==38){
			if(fieldTypeName == "COMMENT"){
				setFormFocus("QNTY_"+index);
			}else if(index > 0){
				index = parseInt(index) -1;
				if(setFormFocus("COMMENT_"+index) == false){
					setFormFocus("QNTY_"+index);
				}
			}
		}else if(IE7== false &&(code==13 || code==40)){	
			if(fieldTypeName == "COMMENT"){
				index = parseInt(index)+1
				setFormFocus("QNTY_"+index);
			}else {
				if(setFormFocus("COMMENT_"+index) == false){	
					index = parseInt(index)+1
					setFormFocus("QNTY_"+index);
				}
			}
		}
	}
	return false;
}

function handleDownArrowAndEnter(event){
	var code = 0;
	if (NS4 ){
		code = event.which;
		if(code==40)event.which=9;
		if(code==13)event.which=9;
	}else{
		code = event.keyCode; 
		if(IE4 || IE7){
			if(code==40)event.keyCode=9;
			if(code==13)event.keyCode=9;   
		}
	}
	return code;
}

function setFormFocus(targetName){
	if(document.UIservletForm[targetName]){
		document.UIservletForm[targetName].focus();
		document.UIservletForm[targetName].select();
		return true;
	}else{
		return false;
	}
}
/***

function remapCode(code){
	newCode=0;
	switch(code){
		case 40:
			newCode=9;
			break;
	}
	return newCode;	

}
**/

function taLimit(event) {
	var taObj = event.srcElement;
	if (taObj == null) taObj = document.UIservletForm[event.target.name]; // Netscape
	if (taObj.value.length == taObj.getAttribute('maxlength') * 1) return false;
}

function taCount(event, visCnt) { 
	var taObj = event.srcElement;
	if (taObj == null) taObj = document.UIservletForm[event.target.name]; // Netscape
	if (taObj.value.length > taObj.getAttribute('maxlength') * 1) {
		taObj.value = taObj.value.substring(0, taObj.getAttribute('maxlength') * 1);
	}
	if (visCnt) {
		visCnt.innerHTML = (taObj.getAttribute('maxlength') * 1) - taObj.value.length;
	}
}

function taCount2(visCnt, txtFieldName) { 
	var taObj = document.UIservletForm[txtFieldName];
	if (taObj.value.length > taObj.getAttribute('maxlength') * 1) {
		taObj.value = taObj.value.substring(0, taObj.getAttribute('maxlength') * 1);
	}
	if (visCnt) {
		visCnt.innerHTML = (taObj.getAttribute('maxlength') * 1) - taObj.value.length;
	}
}

function cancelPrompt(bRedirect, bMultiple) {
	var msg;
	if (bMultiple && bMultiple == true) {
		msg = "This will cancel your order for " + document.getElementById('DLDTVAL').value + ".\n \nYou may:\n   1. Click OK to confirm the action and cancel this order, or\n   2. Click the Cancel button to return to your order.";
	} else {
		msg = "This will cancel your entire order and your shopping cart will be empty!\n \nYou may:\n   1. Click OK to confirm the action and cancel your order, or\n   2. Click the Cancel button to return to your order.";
	}
	bResponse = confirm(msg);
	if (bRedirect && bRedirect == true && bResponse == true){
		var sURL="http://orders.oletyme.com/ppro/online?command=cartformsubmit&function_clear=YES";
		window.location = sURL;
	} else{
		return bResponse;
	}
}

function viewImage(imgId){
	var winLookup= open("http://orders.oletyme.com/ppro/online?command=viewImage&id="+imgId,"Viewer"+imgId,"toolbar=1,status=0,menubar=1,width="+imageViewWidth+",height="+imageViewHeight+",scrollbars=yes,resizable=yes");
}
function buildProfileUpdateCommand(prodnum){
	var name=trim(document.UIservletForm["h"+prodnum].value);
	var rExp = / /g;
	name=name.replace(rExp,"%20");
	name=name.replace(/#/g,"%23");
	retval="http://orders.oletyme.com/ppro/online?command=profielcr.create&prodnum="+prodnum+"&name="+name;
	return retval;
}
function buildProfileUpdatePopup(){
	retval= "toolbar=0,status=0,menubar=0,width=400,height=200,scrollbars=no,resizable=no,left = 312,top = 284";
	return retval;
}

function profileAdd(prodnum){
	var winLookup= open(buildProfileUpdateCommand(prodnum),(new Date).getMilliseconds(),buildProfileUpdatePopup());
}

function profileRemove(prodnum){
	var winLookup= open(buildProfileUpdateCommand(prodnum)+"&remove=yes",(new Date).getMilliseconds(),buildProfileUpdatePopup());
}
function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = / +/g;
   temp = temp.replace(obj, " ");
   if (temp == " ") { temp = ""; }
   return temp;
}
function copyToInvoice(){
	var invoiceInst=trim(document.UIservletForm["INVOICEINSTRUCTION"].value);
	var pickInst=document.UIservletForm["PICKINGINSTRUCTION"].value;
	var availableSpace=document.UIservletForm["INVOICEINSTRUCTION"].maxlength-invoiceInst.length-1;
	if (availableSpace<=1){
		alert("The Invoicing Instruction is already full.");
		return;
	}
	
	invoiceInst = invoiceInst +" "+pickInst.substr(0,availableSpace);
	document.UIservletForm["INVOICEINSTRUCTION"].value=invoiceInst;
	taCount2(myCounter2,"INVOICEINSTRUCTION");
}

function placeFocus() {
	if (document.forms.length > 0) {
	    for (x = 0; x < document.forms.length; x++) {
			var field = document.forms[x];
			for (i = 0; i < field.length; i++) {
				if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type.toString().charAt(0) == "s")) {
					if (field.elements[i].id == "txtSearch") {
						// This is used by Indy Fruit to bypass focus on the search field at the top
						continue; 
					}
					try{
						field.elements[i].focus();
						return;
					}catch(error){
						continue;
					}
	           }
	        }
        }
    }
}

function recapPrintPreview(pprosono, exceptionMsg){

	window.open("http://orders.oletyme.com/ppro/online?command=printrecap&pprosono="+pprosono+"&exception_note="+exceptionMsg,"recap","toolbar=0,status=0,menubar=0,width=730,height=600,scrollbars=yes,resizable=yes");
}
function validateCheckout(){
	if(document.UIservletForm[poFieldName]){
		var po = document.UIservletForm[poFieldName].value;
		po=trim(po); 
		if(requirePO && po==""){
			alert(poMessage);
			return false;
		}
	}
	if(document.UIservletForm["EMAL"]){
		var email = document.UIservletForm["EMAL"].value;
		email=trim(email);
		if(requireEmailAddress && email==""){
			alert(emailAddressMessage);
			return false;
		}
	}
	//document.UIservletForm.submit();
	return true;
}

function validateCartForm(){
	var isCartValid=true;
	var index=0;
	var fieldName="";
	do{
		fieldName="QNTY_"+index;
		avQtyFieldName="AVQT_"+index;
		substFieldName="SUPD_"+index;
		if(document.forms.UIservletForm[fieldName]){
			if(!validateQuantity(document.UIservletForm[fieldName], null, null, null, null, document.UIservletForm[avQtyFieldName].value ,document.UIservletForm[substFieldName].value)){
				isCartValid=false;
				break;
			}else{
				isCartValid=true;
				index++;
			}
		}else{
			break;
		}
	}while(true);
	return isCartValid;
}

function validateQuantity(qtyField, sThresholdVal, sMinQty, sMaxQty, sAvgQty, availQtyField, substItemField) {
	var qty=qtyField.value;
	var msg="";
	if (isNaN(qty)) {
		alertField(qtyField,"This is an invalid quantity.  Please correct before continuing.");
		return false;
	}
	qty = parseFloat(qty);
	if (isNaN(qty)) qty="0";
	if (availQtyField){
		var availQty=availQtyField;
		availQty=parseFloat(availQty);
		if (!isNaN(availQty)) {
			if (qty > availQty) {
				msg=outOfStockMessage;
				msg=replaceChars(msg,"~avqty",availQty);
				if(substItemField) {
					substItem = substItemField;
					substItem = trim(substItem);
					if (substItem != "") {
						msg = msg + substituteMessage
						msg=replaceChars(msg,"~substItem",substItem);
					}
				}
				alertField(qtyField,msg);
				return false;
			}
		}
	}
	if (sThresholdVal) {
		var iThresholdQty = sThresholdVal;
		iThresholdQty = parseFloat(iThresholdQty);
		if (!isNaN(iThresholdQty)) {
			if (qty >= iThresholdQty) {
				if (!confirm('Are you sure that you want to add this many items?')) {	
					qtyField.focus();
					qtyField.select();
					return false;
				}
			}
		}
	}
	if (qty > 0 && sMinQty && sMaxQty && sAvgQty) {
		var iMinQty = parseFloat(sMinQty);
		var iMaxQty = parseFloat(sMaxQty);
		if (!isNaN(iMinQty) && !isNaN(iMaxQty) && !(iMinQty == 0 && iMaxQty == 0)) {	
			if (qty <= iMinQty || qty >= iMaxQty) {
				if (!confirm('Your average order quantity is ' + sAvgQty + '.  Are you sure that you want to add ' + qty + ' items?')) {	
					qtyField.focus();
					qtyField.select();
					return false;
				}
			}
		}
	}
	var testCriteria=1;
	var message=qtyMessage;
	if(!requireIntQty){
		// note: fraction will be 0.0 if any fraction is allowed	
		testCriteria = fraction;
		message = setFractionMessage();
	}
	if ((testCriteria != 0) && (qty % testCriteria != 0)) {
		alertField(qtyField,message);
		return false;
	} else{
		return true;
	}
}

function alertField(qtyField, theMessage){
	alert(theMessage);
	qtyField.focus();
	qtyField.select();

}
function replaceChars(txt,search,replaceWith) {
	out = search; // replace this
	add = replaceWith; // with this
	temp = "" + txt; // temporary holder
	
	while (temp.indexOf(out)>-1) {
	pos= temp.indexOf(out);
	temp = "" + (temp.substring(0, pos) + add + 
	temp.substring((pos + out.length), temp.length));
	}
	return temp;
}

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

function zeroPad(value, theLength){
	for(i=value.length;i<theLength;i++){
		value="0"+value;
	}
	return value;
}
function customerLookup_popup(fieldName){
	url="http://orders.oletyme.com/ppro/online?command=customerlookup.create&CUST="+document.UIservletForm[fieldName].value+"&CUSTFLD="+fieldName;
	openWindowPlaced(url,"lookup",200,250,1,50,1,0);

}

function prodinv_popup(fieldName){
	url="http://orders.oletyme.com/ppro/online?command=prodinv.create&PROD="+document.UISERVLET_ENTRY[fieldName].value+"&FLD="+fieldName;
	openWindowPlaced(url,"lookup",200,250,1,50,1,0);

}
function customerLookup(fieldName){
	url="http://orders.oletyme.com/ppro/online?command=customerlookup.create&CUST="+document.UIservletForm[fieldName].value+"&CUSTFLD="+fieldName;
	showLookup(url,"0");

}

function prodinv(fieldName){
	url="http://orders.oletyme.com/ppro/online?command=prodinv.create&PROD="+document.UISERVLET_ENTRY[fieldName].value+"&FLD="+fieldName;
	showLookup(url,"0");

}
function showLookup(url,mainHeight){
	top.lookup.location=url;
	top.topframe.rows=mainHeight+",*";
}
function hideLookup(){
	top.topframe.rows="*,0";
	top.lookup.location="http://vegas.swc.com/producepro/demo2/blank.htm";
}

/************* For Copyright in footer *********/
Date.prototype.getFullYear = getFullYear;

function getFullYear(){
	var n = this.getYear();
	if (n < 1000) n += 1900; // needed for netscape and IE 7
	return n;
}

function insDate(){
	today = new Date();
	result = (today.getFullYear());
	document.write(result);
}

/**
 * checks all checkboxes on a document
 * depends on the type being "checkbox"
 */
function setAllCheckBoxes(state) {
   	for (i = 0; i < document.UIservletForm.elements.length; i++) {
        if (document.UIservletForm.elements[i].type == 'checkbox')
            document.UIservletForm.elements[i].checked = state;
    };
}

/**
* Implements browser Find functionality directly on page.
*/
function findInPage(str) {
	var txt, i, found;
	if (str == "")
		return false;
	if (NS4) {
		if (!win.find(str))
			while(win.find(str, false, true))
				findCount++;
		else
			findCount++;
		if (findCount == 0) alert(str + " was not found on this page."); 
	} 
	if (IE4) { 
		txt = win.document.body.createTextRange();
		for (i = 0; i <= findCount && (found = txt.findText(str)) != false; i++) { 
			txt.moveStart("character", 1); 
			txt.moveEnd("textedit"); 
		} 
		if (found) { 
			txt.moveStart("character", -1); 
			txt.findText(str); 
			txt.select(); 
			txt.scrollIntoView();
			findCount++;
		}else{
			if (findCount > 0) {
				findCount = 0;
				findInPage(str);
			}else
				alert(str + " was not found on this page."); 
		} 
	} 
	return false; 

} 
function psearch() {
		var searchtext=document.searchform["criteria"].value;
		if(searchtext.length<3){
			if(isNaN(searchtext)){
				alert("Please enter at least 3 characters for your search criteria.");
				return;
			}
		}
		if(!isNaN(searchtext)){
			var length=searchtext.length;
			for(i=0;i<(5-length);i++){
				searchtext="0"+searchtext;
			}
		}
		if (searchtext != "") {
			var url="http://orders.oletyme.com/ppro/online?command=psearch.submit&DESC="+searchtext+"&page="+psearchpage;
			openWindowCentered(url,'Search',450, 450, 'yes');
		}
}

/*********************************
** Profile Maintenance
***********************************/

function profMaintSubmit() {
		document.UIservletForm["parm"].value="";
		document.UIservletForm["nextCommand"].value="ProfileMaintenanceHandler.options";
		document.UIservletForm["name"].value="";
		document.UIservletForm.submit();
}


/**
* Allows you to blink anything on the page with an id=blink
* Example:
* 	<font id=blink>Blinking Text Here</font>
* 	<script>
* 		document.all.blink.style.color = off_color;
* 		setInterval("blink()",blink_speed);
* 	</script>
*
*/
var blink_on_color = "#FF0000";
var blink_off_color = "#FFFFFF";
var blink_onoff = 1;
var blink_speed = 500;
function blink()
{
	if (blink_onoff == 1) {
		document.all.blink.style.color = blink_on_color;
		blink_onoff = 0;
	} else {
		document.all.blink.style.color = blink_off_color;
		blink_onoff = 1;
	}
}

/** BEGIN TOOLTIP JAVASCRIPT **/	
var tooltip_ID;
function resetTimeout ()
{
	try{
		window.clearTimeout(m_ID);
	} catch (ex) {}
}
function startTimeout (timeOut, iTt)
{
	tooltip_ID = window.setTimeout("document.getElementById('" + iTt + "').style.visibility='hidden';",timeOut);
}
function showToolTip(titleText, adText, iTTT, iTt)
{
	// create DIV
	document.getElementById(iTt).style.left  = 100;
	document.getElementById(iTt).style.top   = 100;
	document.getElementById(iTt).style.width = 350;
	document.getElementById(iTt).style.visibility = '';
	document.getElementById(iTt).innerHTML = "<table style='color:black;cursor:pointer;cursor:hand;font-family:verdana;font-size:8pt;' onMouseOver=resetTimeout();  cellpadding='0' cellspacing='3'><tr><td align='center' style='color:gray;font-size:7pt'>" + titleText + "</td></tr><tr><td><nobr><b style='color:darkBlue;'>"+adText+"</b></nobr></td></tr></table>";
	var oBo = cBB (iTTT);
	var oBp = cBB (document.getElementById(iTt));
	document.getElementById(iTt).style.left = oBo.r+5 + toolTipOffsetX;
	document.getElementById(iTt).style.top = oBo.t-20 + toolTipOffsetY;
}
function bx(x,y,w,h)
{
	this.l=x;
	this.r=x+w;
	this.t=y;
	this.b=y+h;
}
function cBB(o)
{
	var b=new bx(0,0,0,0);
	if(!o) return b;
	var x=0,y=0,p=o;
	while(p)
		{
		x+=p.offsetLeft;
		y+=p.offsetTop;
		p=p.offsetParent;
		}
	b.l=x;
	b.t=y;
	b.r=x+o.offsetWidth;
	b.b=y+o.offsetHeight;
	return b;
}
/** END TOOLTIP JAVASCRIPT **/
/*********** SRP Profile ************/
function displayGrossSales(mult, srp, qty, displayTarget, pkct){
	var grossSales=0;
	try{
		grossSales = ((pkct/mult)*qty)*srp;
	}catch(e){
		document.getElementById(displayTarget).innerHTML="";	
	}
	document.getElementById(displayTarget).innerHTML=formatCurrency(grossSales);	
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	}
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
/*********** END SRP Profile ************/

