// General purpose routines for Calculations
var calcFormId="CalculatorsForm";
var defCalcFormId="CalculatorsForm";
var elmCalcId="woodworkersCalc";
woodworkersCalc=
{
	mainElmId:'Content',
	btnCalculateElm:'btnCalculate',
	btnPrintElm:'btnPrint',
	btnClearElm:'btnClear',
	btnSubmit1Elm:'btnSubmit1',
	btnSubmit2Elm:'btnSubmit2',
	custInfoElm:'CustomerDetails',
	hideClass:'Hide',
	formTitle:'',
	orgHide:false,
	custFormList:null,
	formDate:null,
	formTime:null,
	formName:null,
	custName:null,
	custPhone:null,
	custEMail:null,
	custTrans:null,
	custNotes:null,
	firstFocus:null,
	drwPic:null,
	wasInit:false,
	//======================================================//
	// This function initializes the woodworkersCalc class	//
	// it also removes all the "Separator" text lines		//
	// which alerts the user that javascript should be		//
	// enables to use the calculator						//
	//======================================================//
	init:function()
	{
		var		calcTD, allTR, varTD
		
		if(!document.getElementById || !document.createTextNode)
		{
			return(false);
		}
		woodworkersCalc.wasInit=true;
		document.forms[calcFormId].reset();
		//	Set customerFields table
		var	varNames = new Array(	"formDate"	,"FormDate",
								 	"formTime"	,"FormTime",
									"formName"	,"FormName",
									"formTitle"	,"FormTitle",
									"custName"	,"CustName",
									"custPhone","CustPhone",
									"custEMail"	,"CustEmail",
									"custTrans"	,"CollectDeliver",
									"custNotes"	,"SpecialNotes");
		GRCValidation.init(calcFormId);
		woodworkersCalc.orgHide=woodworkersCalc.opCustInfo('status');
		woodworkersCalc.custFormList = new Array();
		if (!woodworkersCalc.getElms(elmCalcId,'',
									 varNames,woodworkersCalc.custFormList,calcFormId))
		{
			return;
		}
		woodworkersCalc.setDefaultCustDet();
		calcTD = document.getElementById(woodworkersCalc.mainElmId);
		// Check under "Caculators" TD entry
		if(calcTD)
		{
			allSep=calcTD.getElementsByTagName('p');
			for (var p=allSep.length-1; p>=0; p--)
			{
				// Check if a Separator class
				if (DOMhelp.cssjs('check',allSep[p],'Separator'))
				{
					allSep[p].parentNode.removeChild(allSep[p]);
					
				}
			}
		}
		return(true);
	},
	setDefaultCustDet:function()
	{
		var dt=new Date();
		var tm;

		with (woodworkersCalc)
		{
//			formDate.value=dt.toLocaleDateString();
//			formDate.value=('0' + dt.getDate()).substr(-2,2) + '/' + dt.getMonth() + 1 + '/' + dt.getFullYear();
//			formDate.defaultValue=formDate.value;
			
			var currentTime = new Date();
			var month = currentTime.getMonth() + 1;
			var day = currentTime.getDate();
			var year = currentTime.getFullYear();
			formDate.defaultValue= (('0' + day).substr(-2,2) + "/" + ('0' + month).substr(-2,2) + "/" + year);
			formDate.value = formDate.defaultValue;
			
			tm=dt.toLocaleTimeString();
			tm=tm.replace("gmt","");
			tm=tm.replace(" ","");
			formTime.value=tm;
			formTime.defaultValue=tm;
			formName.value=GRCValidation.getDocName();
			formName.defaultValue=formName.value;
		}
	},
	//======================================================//
	// This function finds the element with the specified ID//
	//======================================================//
	getElmById:function(elmName)
	{
		var tmpElm = null;
		
		if(document.getElementById && document.createTextNode)
		{
			tmpElm = document.getElementsByName(elmName);
			if (tmpElm.length>0)
			{
				tmpElm=tmpElm[0];	//	return only the first element found
			}
			else
			{
				tmpElm = document.getElementById(elmName);
			}
		}
		return(tmpElm);
	},
	// Add click to button
	setButtonClick:function(btnName,funcElm,funcName)
	{
		var	evalStr;

		if (woodworkersCalc.getElmById(btnName))
		{
			evalStr = 'DOMhelp.addEvent(' + 'woodworkersCalc.getElmById(\'' + btnName + '\'),\'click\',' + funcElm + '.' + funcName + ',false);';
			if (!eval(evalStr))
			{
				alert('Error assigning function ' + funcName + ' to ' + btnName + ' button.');
			}
		}
	},
	/*	Find all the elements in the list and updates the array	*/
	findElements:function(elm,varNames,formList)
	{
		var	getElmsOk=true;

		if (varNames==null)
			return(true);
		if (varNames.length!=2*Math.round(varNames.length/2))
		{
			alert('The variables/ID array size must be even');
			return(false);
		}
		for (var i = 0; i < varNames.length; i=i+2)
		{
			tmpElm = woodworkersCalc.getElmById(varNames[i+1]);
			if (tmpElm)
			{
				evalStr = elm + '.' + varNames[i] + ' = tmpElm;'
				if (!eval(evalStr))
				{
					alert('Error assigning value to ' + elm + '.' + varNames[i]);
				}
				formList[formList.length] = tmpElm;
			}
			else
			{
				getElmsOk=false;
				alert('Error getting '+varNames[i+1]+' element');
			}
		}
		return (getElmsOk);
	},
	//======================================================//
	// This function finds the element with the specified ID//
	// and updated the corrseponding variable				//
	// varNames table consists of the Variable, ID names	//
	//======================================================//
	getElms:function(elm,pformTitle,varNames,formList,pformName)
	{
		var evalStr;
		var tmpElm;
		var	getElmsOk;
		
		calcFormId=(pformName==null) ? defCalcFormId : pformName;
		if (!woodworkersCalc.wasInit)
		{
			if (!woodworkersCalc.init()) return(false);
		}
		getElmsOk=woodworkersCalc.findElements(elm,varNames,formList);
		if (getElmsOk && (elm !='woodworkersCalc'))
		{
			//	Assign "click" to calculators buttons
			with (woodworkersCalc)
			{
				var f;
				if (formList==null)
				{
					firstFocus=null;
					f=document.getElementById(pformName);
					if (f)
					{
						f=f.getElementsByTagName('INPUT');
						if (f)	firstFocus=f[0];
					}
				}
				else
				{
					firstFocus=formList[0];
					DOMhelp.addEvent(firstFocus,'change',woodworkersCalc.formWasChanged,false);
				}
				//	Locate drawing in form and update hidden field
				f=document.getElementById('DiagramFSet');
				if (f)
				{
					fp=f.getElementsByTagName('IMG');
					pp=document.getElementById('DrawingPic');
					if ((pp) && (fp))
						pp.value=fp[0].src;
						pp.defaultValue=pp.value;	//	keep value after reset form
				}
				formTitle.value=pformTitle;
				formTitle.defaultValue=formTitle.value;
				setButtonClick(btnCalculateElm,elm,'calculateForm');
				setButtonClick(btnPrintElm,elm,'printForm');
				setButtonClick(btnClearElm,elmCalcId,'clearForm');
				setButtonClick(btnSubmit1Elm,elmCalcId,'submitForm');
				setButtonClick(btnSubmit2Elm,elmCalcId,'submitForm');
				f=document.getElementById(calcFormId);
				DOMhelp.addEvent(f,'submit',woodworkersCalc.submitForm,false);
				if (orgHide)
					opCustInfo('hide');
			}
		}
		return(getElmsOk);
	},
	//======================================================//
	// This function clears a list of vriables				//
	// itemsList table consists of the elements variables	//
	//======================================================//
	resetForm:function()
	{
		document.forms[calcFormId].reset();
		if (woodworkersCalc.orgHide)
			woodworkersCalc.opCustInfo('hide');	//	Hide user info
		GRCValidation.clearAllErrors(calcFormId);
	},
	clearForm:function(e)	//	Clear the form from Button
	{
		var ff=woodworkersCalc.firstFocus;
		woodworkersCalc.resetForm();
		if (ff)		
			ff.focus();	//	Focus n first field
	},
	formWasChanged:function()
	{
		var ff=woodworkersCalc.firstFocus;
		var x;
		if (ff)
		{
			switch (ff.tagName)
			{
				case 'SELECT':
					x=ff.selectedIndex;
					break;
				default:
					x=ff.value;
			}
		}
		woodworkersCalc.resetForm();
		if (ff)
		{
			switch (ff.tagName)
			{
				case 'SELECT':
					ff.selectedIndex=x;
					break;
				default:
					ff.value=x;
			}
			ff.focus();	//	Focus n first field
		}
	},
	//======================================================//
	//======================================================//
	checkAllItems:function(itemsList)
	{
		var	allNumeric = true;
		var msg = '';
		
		for (var i = 0; i < itemsList.length; i++)
		{
			if (itemsList[i].readonly)
			{
				continue;
			}
			if (itemsList[i].value == '')
			{
				msg = msg + ((msg == '') ? '' : '\n') + ((itemsList[i].name) ? itemsList[i].name : itemsList[i].id) + ' is missing';
				allNumeric = false;
			}
			else if (isNaN(itemsList[i].value))
			{
				msg = msg + ((msg == '') ? '' : '\n') + ((itemsList[i].name) ? itemsList[i].name : itemsList[i].id) + ' should be a number';
				allNumeric = false;
			}
		}
		if (!allNumeric)
		{
			alert(msg);
		}
		return(allNumeric);
	},
	//==============================================================//
	//  This function clears the values from a list of variables	//
	//==============================================================//
	roundFract:function(numericVal,decimalPoints)
	{
		if (decimalPoints > 0)
		{
			return(Math.round(numericVal*Math.pow(10,decimalPoints))/Math.pow(10,decimalPoints));
		}
		else
		{
			return(0);
		}
	},
	//==============================================================//
	//  This function sets/returns the visible parameter of the Customer Info	//
	opCustInfo:function(req)
	{
		var	custInfo;

		custInfo = woodworkersCalc.getElmById(woodworkersCalc.custInfoElm);
		if (custInfo)
		{
			switch (req)
			{
				case 'show':
					DOMhelp.cssjs('remove',custInfo,woodworkersCalc.hideClass);
					break;
				case 'hide':
					DOMhelp.cssjs('add',custInfo,woodworkersCalc.hideClass);
					break;
				case 'status':
					return (DOMhelp.cssjs('check',custInfo,woodworkersCalc.hideClass));
					break;
				case 'switch':
					DOMhelp.cssjs(opCustInfo('status') ? 'remove' : 'add' ,custInfo,woodworkersCalc.hideClass);
					break;
				default: // Switch
					break;
			}
		}
	},
	//	This function checks if the form was calculated
	//==================================================//
	formCalculated:function(fun)
	{
		var x=GRCValidation.getFirstResult();
		if (x)
		{
			if (x.value == '')
			{
				alert("Please calculate form before " + fun);
				return(false);
			}
		}
		return(true);
	},
	// This function Displays user information and sets focus on the first field, for online submission	//
	//======================================================//
	submitForm:function(e)
	{
		var	tmpElm;

		with (woodworkersCalc)
		{
			tmpElm = getElmById(custInfoElm);
			if (!tmpElm) return;
			if (!(woodworkersCalc.formCalculated('submitting')))
			{
				DOMhelp.stopBubble(e);
				return (false);
			}
			if (!opCustInfo('status'))
			{
				if (!GRCValidation.validateForm(calcFormId))
				{
					DOMhelp.stopBubble(e);
					return (false);
				}
				document.forms[calcFormId].submit();
			}
			else
			{
				var	fn;
				setDefaultCustDet();
				opCustInfo('show');
				custName.focus();
			}
		}	//	with
		return(false);
	},
	//==============================================================//
	//  This function sets the visible parameter of the element		//
	//==============================================================//
	setVisible:function(elm,visibleValue)
	{
		if (elm)
		{
			elm.visible = visibleValue;
		}
	},
	//==============================================================//
	//  This function removes unwanted areas and open the browser	//
	//	print option												//
	//==============================================================//
	printPage:function()
	{
		if (woodworkersCalc.formCalculated('printing'))
		{
			window.print();
		}
		return(false);
	}
	
}
//DOMhelp.addEvent(window, 'load', woodworkersCalc.init, false);

