// functions.js

// Redirect to specified page/location
function goTo(page) {
	location.href = page;
}

// Submit form
function submitThis(form) {
	form.submit();
}

// Receiving List Select or Search
function receivingSelectOrSearch(form) {
	//var action = getbyid("action");
	if(getbyid("RCVNO").value != "" || getbyid("RCVSEQ").value != ""
		|| getbyid("DTRC").value != "") {
		// Set Action List to Search
		setSelection("action", "X");
	}
	
	submitThis(form);
}

// Perform Select or Search
function lookupSelectOrSearch(form) {
	var lookupType = getbyid("lookupType").value;
	var action = getbyid("action");
	if(lookupType == "lookupLot") {
		if(getbyid("LOLOT").value != "" || getbyid("LOSUPT").value != ""
			|| getbyid("LOSUPL").value != "" || getbyid("LOVAR").value != "") {
			// Set Action to Search
			action.value = "X";
		}
	}
	else if(lookupType == "lookupSupplier") {
		if(getbyid("SUSUPT").value != "" || getbyid("SUSUPL").value != ""
			|| getbyid("SUSNAM").value != "") {
			// Set Action to Search
			action.value = "X";
		}
	}
	else if(lookupType == "lookupProduct") {
		if(getbyid("PMPRD").value != "" || getbyid("PMDES").value != "") {
			// Set Action to Search
			action.value = "X";
		}
	}
	
	// One last chance if Option List is set to Search
	if(getbyid("option").value == "X") {
		// Set Action to Search
		action.value = "X";
	}
	
	// Check if user wants to Quit
	if(getbyid("option").value == "Q") {
		// Set Action to Quit
		action.value = "Q";
	}
	
	submitThis(form);
}

// Toggle Detail Line
function toggleDetailLine(rcvl) {
	var rcvlCbox = getbyid("RDRCVL_" + rcvl);
	var lineArray = getbyid("RCVLLIST").value.split(",");
	
	// Change Option/Action to 'C' for Change
	setSelection("option", "C");
	
	if(rcvlCbox.checked == true) {
		// Show Input Fields
		showIt("FLDPRD_" + rcvl);
		showIt("FLDRCVQT_" + rcvl);
		showIt("FLDQT_" + rcvl);
		showIt("FLDSUPLOT_" + rcvl);
		
		// Hide Display
		hideIt("DSPPRD_" + rcvl);
		hideIt("DSPRCVQT_" + rcvl);
		hideIt("DSPQT_" + rcvl);
		hideIt("DSPSUPLOT_" + rcvl);
	
		// Enable elements on this Detail Line
		//disOff("RDPRD_" + rcvl);
		//disOff("RCVQT_" + rcvl);
		//disOff("RQQT_" + rcvl);
		//disOff("RDSUPT_" + rcvl);
		//disOff("RDSUPL_" + rcvl);
		//disOff("RDLOT_" + rcvl);
		
		// Enable Lookups
		//disOff("LKPRD_" + rcvl);
		//disOff("LKSUP_" + rcvl);
		//disOff("LKLOT_" + rcvl);
		
		// Disable all other lines
		for(var i = 0;i < lineArray.length;i++) {
			var line = lineArray[i];
			if(line != rcvl) {
				// Uncheck Checkbox
				getbyid("RDRCVL_" + line).checked = false;
				
				// Hide Input Fields
				hideIt("FLDPRD_" + line);
				hideIt("FLDRCVQT_" + line);
				hideIt("FLDQT_" + line);
				hideIt("FLDSUPLOT_" + line);
				
				// Show Display
				showIt("DSPPRD_" + line);
				showIt("DSPRCVQT_" + line);
				showIt("DSPQT_" + line);
				showIt("DSPSUPLOT_" + line);
				
				//disOn("RDPRD_" + line);
				//disOn("RCVQT_" + line);
				//disOn("RQQT_" + line);
				//disOn("RDSUPT_" + line);
				//disOn("RDSUPL_" + line);
				//disOn("RDLOT_" + line);
		
				// Disable Lookups
				//disOn("LKPRD_" + line);
				//disOn("LKSUP_" + line);
				//disOn("LKLOT_" + line);	
			}
		}
	}
	else {
		// Hide Input Fields
		hideIt("FLDPRD_" + rcvl);
		hideIt("FLDRCVQT_" + rcvl);
		hideIt("FLDQT_" + rcvl);
		hideIt("FLDSUPLOT_" + rcvl);
		
		// Show Display
		showIt("DSPPRD_" + rcvl);
		showIt("DSPRCVQT_" + rcvl);
		showIt("DSPQT_" + rcvl);
		showIt("DSPSUPLOT_" + rcvl);		
	
		// Disable elements on this Detail Line
		//disOn("RDPRD_" + rcvl);
		//disOn("RCVQT_" + rcvl);
		//disOn("RQQT_" + rcvl);
		//disOn("RDSUPT_" + rcvl);
		//disOn("RDSUPL_" + rcvl);
		//disOn("RDLOT_" + rcvl);
		
		// Disable Lookups
		//disOn("LKPRD_" + rcvl);
		//disOn("LKSUP_" + rcvl);
		//disOn("LKLOT_" + rcvl);	
	}
}

// Enable All Detail Lines
function enableAllDetailLines() {
		var option = getbyid("option").value;
		if(option != "D" && option != "Q") {
			var line = getbyid("RCVLLIST").value;
			if(line != "") {
				var lineArray = getbyid("RCVLLIST").value.split(",");
				// Enable all other lines
				for(var i = 0;i < lineArray.length;i++) {
					var line = lineArray[i];
					// Check Checkbox
					getbyid("RDRCVL_" + line).checked = true;
			
					disOff("RDPRD_" + line);
					disOff("RCVQT_" + line);
					disOff("RQQT_" + line);
					disOff("RDSUPT_" + line);
					disOff("RDSUPL_" + line);
					disOff("RDLOT_" + line);
				}
			}
		}
}

// Sets value for given object
function setValue(idn, val) {
	getbyid(idn).value = val;
}

//hides a DIV (requires an ID)
function hideIt (idn) {
	getbyid(idn).style.display = "none";
}

//shows a DIV (requires an ID)
function showIt (idn) {
	getbyid(idn).style.display = "";
}

// Turn ON Disable Property
function disOn(idn) {
	getbyid(idn).disabled = true;
}

// Turn OFF Disable Property
function disOff(idn) {
	getbyid(idn).disabled = false;
}

// Gets an Element By ID
function getbyid(id) {
	itm = null;
	if (document.getElementById) {
		itm = document.getElementById(id);
	}
	else if (document.all) {
		itm = document.all[id];
	}
	else if (document.layers) {
		itm = document.layers[id];
	}
	return itm;
}

// Set Action for ReceivingHeaderAdd page, then submit form
function actionOptionSubmit(form) {
	var option = document.getElementById("option");
	var action = document.getElementById("action");
	action.value = option.value;
	submitThis(form);
}

// Set Lookup Action, then submit form
function lookupActionSubmit(form, lookup) {
	var action = document.getElementById("action");
	action.value = lookup;
	submitThis(form);
}

// Disable Button and Submit
function disableAndSubmit(form, e) {
	var element = document.getElementById(e);
	element.disabled = true;
	
	// Submit the form
	form.submit();
}

// Submit Form with Action change
function submitThisAction(form, a) {
	var action = document.getElementById("action");
	action.value = a;
	form.submit();
}

// Submit Form with Option change
function submitThisOption(form, o) {
	var option = document.getElementById("option");
	option.value = o;
	//alert(option.value);
	form.submit();
}

// Set focus to object
function setFocus(id) {
	var obj = document.getElementById(id);
	obj.focus();
}

// Truck Products Submit
function submitTruckProd(form, subAction) {
	var subActionField = document.getElementById("subAction");
	subActionField.value = subAction;
	form.submit();
}

// Goto Specific Weight Sample
function submitGoToWeightSample(form, action) {
	var actionField = document.getElementById("action");
	actionField.value = action;
	form.submit();
}

// Goto Next Grading Sample
function submitGradingSampleSubction(form, subaction) {
	var subActionField = document.getElementById("subAction");
	subActionField.value = subaction;
	form.submit();
}

// Accept Under Weight Sample Prompt Submit
function submitAcceptSampleWeight(form, accepted) {
	var acceptedField = document.getElementById("accepted");
	acceptedField.value = accepted;
	form.submit();
}

// Delete a grading seq line from Truck Products
function delGrdSeq(form, seqNum) {
	var subActionField = document.getElementById("subAction");
	var delGrdSeqField = document.getElementById("delGrdSeqNum");
	subActionField.value = "delGrdSeq";
	delGrdSeqField.value = seqNum;
	form.submit();
	
}

// Refresh and get Lots for Grower
function getLots(form) {
	var action = document.getElementById("action");
	action.value = "getLots";
	submitThis(form);
}

// Back to previous screen
function goBack() {
	history.back();
}

// Trim whitespace off a string
function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');

} 

// Calculate Truck Products Totals
function calcTruckProd(id) {
	var gqpal = document.getElementById("GQPAL" + id);
	var gqqtpl = document.getElementById("GQQTPL" + id);
	var gqqt = document.getElementById("GQQT" + id);
	
	if(gqpal.value == "") {
		alert("Please enter a value for #Pall");
		return false;
	}
	else if(gqqtpl.value == "") {
		alert("Please enter a value for Per Pallet");
		return false;
	}
	else {
		gqqt.innerText = gqpal.value * gqqtpl.value; 
	}
}

// Populate Select Objects in page
function populateSelect(cmd, selObjName, array) {
	var sizeObj = document.getElementById(selObjName);
	//var sizeObj = selObjName;
	
	// First clear any existing elements
	sizeObj.options.length = 0;
	
	var opt = new Option("Select...", "xxx", true, true);
	sizeObj.options[0] = opt;
	for(var v = 0;v < array.length;v++) {
		var myObj = array[v].substring(0, array[v].indexOf(","));
		var myObjSnam = array[v].substring(array[v].indexOf(",") + 1, array[v].lastIndexOf(","));
		var myCmd = array[v].substring(array[v].lastIndexOf(",") + 1, array[v].length);
		if(cmd == myCmd) {
			// Create a new Option
			opt = new Option(myObj + " - " + myObjSnam,myObj,false, false);
			sizeObj.options[sizeObj.options.length] = opt;
		}
	}
}

// Check if return from error, Set selection item
function setSelection(selObjName, item) {
	var selObj = document.getElementById(selObjName);
	if(item != "null") {
		for(var i =0;i < selObj.length;i++) {
			if(selObj.options[i].value == item) {
				selObj.selectedIndex = i;
			}
		}
	}
}

// Sends AJAX request:
function Send_AJAX_Request(program, field) {
	// pass the query the user has typed - prevent caching
	// Also, pass the id for a div to update, and the function to call to update this div.
	random_num = (Math.round((Math.random()*9)+1));

	// This is the URL of your server-side web program or script to call:
	//var myurl += "pgmtocall.pgm?task=ajaxresponse&catalog=" + encode(field.value)+ "&rand=" + random_num;
	//var myurl = "AjaxTest?action=getName&random_num=" + random_num;
	var myurl = "GetCommodity?action=getName&random_num=" + random_num;
	
	// This is the id for the html div tag to populate:
	var mydiv = "responsehtml";

	// Fire request for data and populate div:
	AJAX_Update(myurl, mydiv, Receive_AJAX_Response);
}

function send_AjaxCommodityCall() {
	random_num = (Math.round((Math.random()*9)+1));
	
	var variety = document.getElementById("VVVAR");
	//var variety = document.form1.VVVAR;

	myurl = "GetCommodity?var=" + variety.value + "&random_num=" + random_num;
	
	// Location to place commodity
	var mycommodity = "COMMODITY";
	
	AJAX_Update(myurl, mycommodity, Receive_AJAX_Response);
}

// Called from inside the function AJAX_Update:
function Receive_AJAX_Response(mydiv, response ) {
	var ret = document.getElementById(mydiv).value = response;
	//var ret = document.form1.COMMODITY.value = response;

	if(ret != "UGS0022") {
		// No error, Commodity returned OK
		// Populate our Size, Label and Pack Selects
		ret = trimString(ret);
		populateSelect(ret, "VVSIZ", sizeArray);
		populateSelect(ret, "VVLBL", labelArray);
		populateSelect(ret, "VVPACK", packArray);
		
		// Check if we should set the selected index
		setSelection("VVSIZ", vvSiz);
		setSelection("VVLBL", vvLbl);
		setSelection("VVPACK", vvPack);				
	}
	else {
	
	}
}

var _ms_AJAX_Request_ActiveX = ""; // Holds type of ActiveX to instantiate

function AJAX_Update(url, obj, func) {
	if (!url) return false;  // Don't run if missing the url parm. 
 
 	// code for Mozilla, etc.
	if (window.XMLHttpRequest) {
		var xmlhttp=new XMLHttpRequest();
	}
	
	// code for IE
	else if (window.ActiveXObject) {
		// Instantiate the latest MS ActiveX Objects
		if (_ms_AJAX_Request_ActiveX) {
			xmlhttp = new ActiveXObject(_ms_AJAX_Request_ActiveX);
		} 
	  	else {
			// loops through the various versions of XMLHTTP to ensure we're using the latest
			var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
         	for (var i = 0; i < versions.length ; i++) {
				try {
					// try to create the object
					// if it doesn't work, we'll try again
					// if it does work, we'll save a reference to the proper one to speed up future instantiations
					//alert(versions[i]);
					xmlhttp  = new ActiveXObject(versions[i]);
					if (xmlhttp){ 
						_ms_AJAX_Request_ActiveX = versions[i];
						break;
					}
				}
				catch (objException) {
                  // trap -  try next one
                 // alert(objException);
				} 
			}
		}
	}

	if (!xmlhttp) { 
		return false;
	}
	
	if (func)xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState != 4) return;
		if (xmlhttp.status == 200) {
			func(obj, xmlhttp.responseText);
		}
		else alert("An error occurred " + xmlhttp.status);
	};
    else
      xmlhttp.onreadystatechange = function() { return; }
    
		xmlhttp.open('GET', url, true);
    xmlhttp.send(null);

    if (func) {} else return xmlhttp.responseText;
    return false;
}


// If you plan on doing anything outside of North America, then you'd better encode the things you pass back and forth
// the escape() method in Javascript is deprecated -- should use encodeURIComponent if available
function encode( uri ) {
	if (encodeURIComponent) {
		return encodeURIComponent(uri);
	}

	if (escape) {
		return escape(uri);
	}
}

function decode( uri ) {
	uri = uri.replace(/\+/g, ' ');

	if (decodeURIComponent) {
		return decodeURIComponent(uri);
	}

	if (unescape) {
		return unescape(uri);
	}

	return uri;
}
