// *** CROSS-BROWSER COMPATIBILITY ***

var isDOM = (document.getElementById ? true : false); 
var isIE4 = ((document.all && !isDOM) ? true : false);
var isNS4 = (document.layers ? true : false);
var isNS6=document.getElementById && (navigator.appName=="Netscape")?true:false;
var isDyn = (isDOM || isIE4 || isNS4 || isNS6 );

function getRef(id)
{
 if (isDOM) return document.getElementById(id);
 if (isIE4) return document.all[id];
 if (isNS4) return document.layers[id];
}
function getSty(id)
{

 return (isNS4 ? getRef(id) : getRef(id).style);
 
} 
function addRM()
{
var rm_input = rm_input_list.split(',');
var table= getRef('raw_mat');
if(typeof(table) == "object")
	{
	var row = table.insertRow(table.rows.length);
	var rowCount = table.rows.length;
	if(rowCount > 1)
		{
		var rm_count = rowCount - 1;
		}
	else
		{
		var rm_count=1
		}
		
		var cell = row.insertCell(0)
		var str2 = "<input type=\"hidden\"  name=\""
		str2+= "added_rawMaterialId_"+rm_count;
		str2+="\">"
		str2 += "<input type=\"text\" size=\"20\" id=\"reportNavy\" name=\""
		str2+="added_rawMaterialName_"+rm_count;
		str2+="\" onFocus=\"runChk= true;\"  onBlur=\"runChk=false;\" onKeyPress=\" checkRM(this.value,this)\"";
		str2+="\">"
		cell.innerHTML=str2
		
	for(var i=1; i < rm_input.length+1; i++)
		{
		var j=i-1
		var cell = row.insertCell(i)
		var str="<input type=\"text\" size=\"6\" id=\"reportNavy\" name=\"added_"
		str+= rm_input[j]+"_"+rm_count;
		if(rm_input[j] == "formulationPercent")
			{
			str+= "\" onChange=\"calcUseHighLow(this)\" ";
			}
		else
			{
			str+="\""
			}
		str+=">";
		cell.innerHTML = str;
		
		}
		
	}
}

function checkRM(thisValue,thisField)
{
var val_length = 0;
if(key_press(event.keyCode))
	{
	var thisKey = String.fromCharCode(window.event.keyCode)
	var val_length = thisValue.length
	
	}

if(val_length >0)
	{
	//Get id field name
	var full_field_name = thisField.name;
	// Break down into components (if new entry then "added" then raw_material_name then row id)
	// else if existing then raw_material_name then prod_raw_material_id
	var tmpNames = full_field_name.split('_');
	
	if(tmpNames.length > 2)
		{
		var raw_material_id_fieldname = "added_rawMaterialId_"+tmpNames[2].toString();
		}
	else
		{
		var raw_material_id_fieldname = "rawMaterialId_"+tmpNames[1].toString();
		}
	
	var loopCounter=0;
	for(var a=0; a < rm_array.length; a++)
		{
		
		var newVal= thisValue+thisKey
		var thisRM = rm_array[a][1];
		
		
		var rm_part = thisRM.substring(0,val_length+1)
		//alert("rm_part ="+rm_part+" and thisValue= "+newVal)
		if (rm_part == newVal)
			{
			var thisRMid = rm_array[a][0];
			window.event.returnValue=false;
			//alert(raw_material_id)
			var raw_material_id_field = eval("document.productChg[\'"+raw_material_id_fieldname+"\']");
			raw_material_id_field.value =thisRMid;
			thisField.value="";
			thisField.value=thisRM;
			thisField.select();
			var range = document.selection.createRange();
			
			range.moveStart('character',val_length+1);
			range.select();
			
			
			break;
			}
		else
			{
			loopCounter=loopCounter+1;
			}
		}
	if(loopCounter == rm_array.length)
		{
		
		runChk= false;
		}
	}
}

function key_press(key)
{
	var keyChar= String.fromCharCode(key)
	re = /[A-Za-z0-9]+$/
	return(re.test(keyChar) )
	
}

function calcUseHighLow(thisField)
{
/* This is raw_use_high and raw_use_low values are calculated 
on an onChange event in the formulation value
thisField refers to formulation_percent field.
*/
var prodHighField = document.productChg.use_high;
var prodLowField = document.productChg.use_low;

/*If we know fieldname then we can determine*/
//Get id field name
var useHigh = false;
var useLow=false;
var error = false;
	var full_field_name = thisField.name;
	var rmFormulation = thisField.value;
	if(rmFormulation.length==0)
		{
		error = true;
		}
	if(prodHighField.value.length == 0 || prodLowField.value.length == 0)
		{
		error = true;
		}
	if(!error)
		{	
		// Break down into components (if new entry then "added" then formulation_percent then row id)
		// else if existing then formulation_percent then prod_raw_material_id
		var tmpNames = full_field_name.split('_');
		var tmpStore=new Array();
		
		if(tmpNames.length > 2)
			{
			// A new entry eg added_formulationPercent_1
			// break middle value into its components eg raw use high
			var tmpStore = tmpNames[1].split('_');
			var rmLowField = 	eval("document.productChg[\'added_rawUseLow_"+tmpNames[2]+"\']");
			var rmHighField = 	eval("document.productChg[\'added_rawUseHigh_"+tmpNames[2]+"\']");
			}
		else
			{
			// An existing entry thats being modified
			var tmpStore = tmpNames[0].split('_');
			var rmLowField = 	eval("document.productChg[\'rawUseLow_"+tmpNames[1]+"\']");
			var rmHighField = 	eval("document.productChg[\'rawUseHigh_"+tmpNames[1]+"\']");
			}
		/*var str2="rmLowField ="+rmLowField;
			str2+="\nrmHighField= "+rmHighField;
			str2+="\nrmFormulation= "+rmFormulation;
			str2+="\nprodLowField.value = "+prodLowField.value;
			str2+="\nprodHighField.value= "+prodHighField.value;
			alert(str2)*/
		var rawLowVal = (prodLowField.value * rmFormulation)/10000;
		var rawHighVal = (prodHighField.value * rmFormulation)/10000;
		rmLowField.value=	rawLowVal;
		rmHighField.value= 	rawHighVal;
				
		}
}

function addOption(sel,value,text){

sel.options[sel.options.length] = new Option(text, value);
sel.options[sel.options.length-1].selected=true;
}

function getSty(id)
{

 return (isNS4 ? getRef(id) : getRef(id).style);
 
} 


function addUses(use_id,use_name)
{
var currentUses = document.productChg.prodUseID;
var currentUseNames = document.productChg.thisUseName;
if(currentUses.value == 0)
	{
	// Never been added to before
	currentUses.value="";
	//empty the field
	currentUses.value=use_id
	currentUseNames.value=use_name;
	}
else
	{
	var newClassList = currentUses.value.toString();
	var  tmp = newClassList.split(',');
	var idKnown = false;
	for(var i=0;i<tmp.length; i++)
		{
		if(use_id== tmp[i])
			{
			idKnown=true;
			}
		}
	if (idKnown)
		{
		alert('This Product Use is already associated with that product.')
		}	
	else
		{
		currentUses.value=newClassList+","+use_id
		currentUseNames.value+=','+use_name;
		}
	}
}
function openhelpWindow(menuAction,helpAction)
{
var openAction="dsp_helpFunction.cfm?menuAction="+menuAction+"&helpAction="+helpAction;
submitWindow = open(openAction,'helpWindow', 'width=300,height=300,toolbar=0,location=0,directories=0,status=0,menuBar=0,scrollBars=0,resizable=0' );

}
var callerFieldName= null
function openWin(winOption,updateField)
{
//alert(returnPage)

callerFieldName=updateField;

var openAction="appProdIndex.cfm?app_ProdAction="+winOption+"&insWindow=true&updatefield="+updateField;
submitWindow = open(openAction,'test', 'width=600,height=600,toolbar=0,location=0,directories=0,status=0,menuBar=1,scrollBars=0,resizable=0' );

}


function validateForm(){
//alert(document.orchardDetails.SURNAME.value.length)
var formComplete= true;
var responseMsg = "";
var receiveFocus =""

/*
if(document.orchardDetails.MAF_CODE.value.length == 0){
	formComplete = false; 
	responseMsg+="You must enter a MAF Code\n\n";
	receiveFocus="MAF_CODE";
};
*/


if(responseMsg.length > 0){alert(responseMsg); eval("document.orchardDetails."+receiveFocus+".focus()");}
return(formComplete) 

}
function validateSearch()
{
var result = true;
var responseMsg = "";
var receiveFocus =""	
if(document.search_form.cas.value.length == 0)
	{
		if(document.search_form.supplier_id.value.length == 0  )
			{
			responseMsg+="You must enter a CAS number or a Supplier with each search\n\n";
			receiveFocus="cas";
			result = false;
			}
	}
if(!result)
	{
		alert(responseMsg)
		eval("document.search_form."+receiveFocus+".focus()");
	}
return(result)
}
//----------------------------- IsValidDate ------------------------------------
function isValidDate(datestr)
{
// Check that a date string is a valid date in dd/mm/yyyy format.
var dateparts, checkdate, checkstr
	
	if (typeof (datestr) != "string") { return false; };
	// Date should have 3 elements - separated by / chars
	dateparts = datestr.split('/');

	if (dateparts.length != 3) { return false; };
	// Date elements should be numeric
	if (isNaN(Number(dateparts[0])) || 
    	isNaN(Number(dateparts[1])) || 
		isNaN(Number(dateparts[2])))
	{
		return false;
	};

	dateparts[0] = Number(dateparts[0]);
	dateparts[1] = Number(dateparts[1]) - 1;
	dateparts[2] = Number(dateparts[2]);
	// Date elements should form a valid date.
	// Note: getMonth() returns 0..11 (where 0 = Jan, ..., 11 = Dec)
	checkdate = new Date(dateparts[2], dateparts[1], dateparts[0]);

	if ((checkdate.getDate() != dateparts[0]) ||
    	(checkdate.getMonth() != dateparts[1]) ||
		(checkdate.getFullYear() != dateparts[2]))
	{
		return false;
	};

	return true;
};
function chkdate(objName) {
			
			   var strDatestyle = "EU";  //European date style;       dd/mm/yyyy
			
			var strDate;
			var strDateArray;
			var strDay;
			var strMonth;
			var strYear;
			var intday;
			var intMonth;
			var intYear;
			var err = 0;
			var booFound = false;
			var datefield = objName;
			var strSeparatorArray = new Array("/");
			var intElementNr;
			strDate = objName;
			
			if (strDate.length < 8) {
			 return false;
			}
			
			for (intElementNr = 0; intElementNr < strSeparatorArray.length;
			intElementNr++) {
			
			if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			 strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			 if (strDateArray.length != 3) {
			  err = 1;
			  return false;
			 }
			 else {
			  strDay = strDateArray[0];
			  strMonth = strDateArray[1];
			  strYear = strDateArray[2];
			//  alert("strDay is "+strDay+"\n strMonth is "+strMonth+"\n stYear is "+strYear)
			 }
			booFound = true;
			}
			}
			
			if (booFound == false) {
			if (strDate.length>5) {
			 strDay = strDate.substr(0, 2);
			 strMonth = strDate.substr(2, 2);
			 strYear = strDate.substr(4);
			}
			}
			
			if (strYear.length != 4) {
			return false;
			}
			// US style
			if (strDatestyle == "US") {
			strTemp = strDay;
			strDay = strMonth;
			strMonth = strTemp;
			}
			
			intday = parseInt(strDay, 10);
			if (isNaN(intday)) {
			 return false;
			}
			
			intMonth = parseInt(strMonth, 10);
			if (isNaN(intMonth)) {
			 err = 3;
			return false;
			}
			
			intYear = parseInt(strYear, 10);
			//  alert("intday is "+intday+"\n intMonth is "+intMonth+"\n intYear is "+strYear)
			if (isNaN(intYear)) {
			
			 return false;
			}
			else{

				if(intYear < 1901){
				alert("That year is not recognised. Please enter a four digit code!")
				return false;
				}
			}
			// Return to date form
			// Date can not be greater than current date
			 // alert("intday is "+intday+"\n intMonth is "+intMonth+"\n intYear is "+strYear)
			// Due to Javascript crazy input requirements for Date object
			// Months are inputed from 0 to 11 so the month value of December is 11
			intMonth = intMonth-1;
			treatedDate = new Date(intYear,intMonth,intday)
			currentDate = new Date()
			//alert("Input Date is "+treatedDate)
			//alert("Current Date is "+currentDate)
			if(treatedDate < currentDate)
				{
				//alert("Future Dates are not permitted")
				return false
				}
				
			if (intMonth>12 || intMonth<0) {
			 return false;
			}
			
			if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 ||
			intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 ||
			intday < 1)) {
			 return false;
			 }
			if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11)
			&& (intday > 30 || intday < 1)) {
			 return false;
			 }
			
			if (intMonth == 2) {
			 if (intday < 1) {
			 return false;
			 }
			 if (LeapYear(intYear) == true) {
			  if (intday > 29) {
			  return false;
			  }
			 }
			 else {
			  if (intday > 28) {
			  return false;
			  }
			 }
			}
			 return true
			}
			
			function LeapYear(intYear) {
			if (intYear % 100 == 0) {
			 if (intYear % 400 == 0) {return true;}
			 }
			else {
			 if ((intYear % 4) == 0) {return true;}
			 }
			return false;
			}
function SearchTask(){
   			var dataOk = true;
			var retMsg = "Problems Encountered:\n\n"
			var FormObj = document.search_form
		if ( FormObj.HerdId.value == "") {
			dataOk = false;
			retMsg += "A Herd ID must be entered\n" }
		if ( FormObj.HerdId.value.length != 7) {
			dataOk = false;
			retMsg += "A Herd ID must be 7 characters\n" }
			
		if (dataOk){
		    		return true;
		    		}   
		 		else {
					retMsg += "\n\nData NOT Submitted."
		   			alert(retMsg);
		    		return false;
		   	}   	
		}

   		function validateTask(){
   			var dataOk = true;
			var retMsg = "Problems Encountered:\n\n"
			var FormObj = document.login_form
			
		if ( FormObj.userid.value == "") {
			dataOk = false;
			retMsg += "A Login Name must be entered\n" }
			
		if ( FormObj.passwd.value == "" ) {
			dataOk = false;
			retMsg += "A Password must be entered\n" }
			
		if (dataOk){
		    		return true;
		    		}   
		 		else {
					retMsg += "\n\nData NOT Submitted."
		   			alert(retMsg);
		    		return false;
		   	}   	
		}