// Code for pre-submission validation
var errMiss;
var errFld;
var formElem; // shortcut to array of form's elements
var frm; //shortcut to form
var typeChoiceVal; //indicate value of type choice radio buttons
var expChr2 = /\w{2,}/; //word of at least 2 chars
var expPhone = /^\D*(\d{3})\D*(\d{3})\D*(\d{4})\D*$/; // 10 digit phone number with any (or no) delimiters

// ************************************************************************
function Color_OnFocus(fld) {
// set the fld's background to white (clearing any red error)
//alert("focusing in "+ fld.name);
var targ;
SetFieldErrCond(fld.name,false);
} // END Color_OnFocus

// ************************************************************************
function CkMatch(val,req,pattern)
{
if (val.length == 0) { // nothing in field
if (req)
errMiss = true; // required value missing
else
return true; // value not required
}
else {
//DBG
//alert("matching " + val + " on " + pattern);
if (val.match(pattern) != null) {
//DBG
//alert("Returning true for " + val);
return true;
}
}
return false;
} // END CkMatch

// ************************************************************************
function CkReqError(errArr,fld,len,pattern,msg)
{ // check length and pattern of field contents
if (fld.value.length >= len) {
	if (CkMatch(fld.value,true,pattern)) return;
	} 
// ERROR
SetValidErr(errArr,fld,msg);
} // END CkReqError

// ************************************************************************
function CkFormatError(errArr,fld,pattern,msg)
{
//value not required: if empty, then returns without error
if (CkMatch(fld.value,false,pattern)) return;
// ERROR
SetValidErr(errArr,fld,msg);
} // END CkFormatError

// ************************************************************************
function SetValidErr(errArr,fld,msg)
{
//marks the offending field red
//makes sure fld's onFocus is set to reset background
//records field as first error, as needed
//appends msg to errArr
// onFocus is set here rather than in HTML
// It requires a Closure Object (Javascript 1.2)
// so that the current field is passed
SetFieldErrCond(fld.name,true);
fld.onfocus= function(){Color_OnFocus(fld);};
if (errFld == null) errFld = fld;
errArr[errArr.length] = msg;
} // END SetValidErr

// ************************************************************************
function CkMinStr(errArr,name,fld,min)
{
// minimum number of chars and at least one word of 2 chars
CkReqError(errArr,fld,min,expChr2,ErrText("min",name));
} // END CkMinStr

// ************************************************************************
function CkMaxStr(errArr,name,fld,max)
{
// max number of chars
if (fld.value.length > max)
    SetValidErr(errArr,fld,ErrText("max",name));
} // END CkMaxStr

// ************************************************************************
function CkMinMaxStr(errArr,name,fld,min,max)
{
// min and max number of chars
CkMinStr(errArr,name,fld,min);
CkMaxStr(errArr,name,fld,max);
} // END CkMinMaxStr

// ************************************************************************
function CkPhone(errArr,req,fld)
{//if required, must have 10 digits with any kind of delimiters
if (CkMatch(fld.value,req,expPhone)) return true;
// ERROR
SetValidErr(errArr,fld,"Invalid Telephone: 10 digits expected. (123) 456-7890");
return false;
} // END CkPhone

// ************************************************************************
function FormatPhone(fldname)
{
var val = formElem[fldname].value;
var regResult = expPhone.exec(val);
if (regResult != null) {
	val = '(' + regResult[1] + ') ' + regResult[2] + '-' + regResult[3];
	}
else {
	alert("Invalid telephone number.");
	}
formElem[fldname].value = val;
} // END FormatPhone

// ************************************************************************
function CkEmail(errArr,req,fld)
{
// if required, must have email format
if (CkMatch(fld.value,req,/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]){2,}$/)) return true;
// ERROR
SetValidErr(errArr,fld,ErrText("email",""));
return false;
} // END CkEmail

// ************************************************************************
function CkRadio(errArr,fldname,msgfld)
{
// uses the DOM's getElementsByName which returns collection of nodes, requiring use of item()
var elements = document.getElementsByName(fldname);
var cnt = 0;
for (var i=0; i < elements.length; i++) {
  if (elements.item(i).checked) cnt++;
	}
if (cnt == 0)
	SetValidErr(errArr,elements.item(0),ErrText("radio",msgfld));
} // END CkRadio

// ************************************************************************
function ErrorTesting(fld)
{	// allowed values that trigger testing for error conditions
//alert('error testing for ' + fld.value);
	if (fld.value == "none") return true;
	if (fld.value == "error") return true;
	return false;
} // END ErrorTesting

// ************************************************************************
function formatDate(dt)
{ // using alphabetic month dd mon yyyy
return dt.getDate() + " " + getMonLetters(dt.getMonth()+1) + " " + dt.getFullYear();
} // END formatDate

// ************************************************************************
function formatNumDate(dt)
{ // using only numeric indicators yyyy-mm-dd
return dt.getFullYear() + "-" + "0" + (dt.getMonth()+1) + "-" + dt.getDate();
} // END formatNumDate

// ************************************************************************
function formatRMA(val)
{ // removes all spaces
return val.replace(/\s\s*/g,'');
} // END formatRMA

// ************************************************************************
function formatSerialNum(val)
{ // removes all spaces and removes leading zero on latest serial numbers
var sernum = val.replace(/\s\s*/g,'');
// when sernum is greater than 7 chars and first char is zero, the zero is removed
if ((sernum.length > 7) && (sernum.substring(0,1) == '0'))
	sernum = sernum.substring(1);
return sernum;
} // END formatSerialNum

// ************************************************************************
function SetFieldErrCond(fldname,hasErr)
{
// relies on DOM to set background color of a named HTML element
// OBSTACLE checkboxes and radio buttons don't have backgrounds in mozilla, instead color
// the background of the containing element (in HTML, those elements should be
// contained in a div)
var targ;
var color;

//alert('looking up error field ' + fldname);

var elements = document.getElementsByName(fldname);
if (hasErr) color = "#C4261D";
if (elements.length > 0) {
	targ = elements.item(0);
	if ((targ.type == "checkbox") || (targ.type == "radio")) {
		targ = targ.parentNode;
		if (!hasErr) color = "transparent";
//alert('parent is ' + targ.nodeName);
		}
	else {
		if (!hasErr) color = "white";
		}
	targ.style.background = color;
	}
} // END SetFieldErrCond

// ************************************************************************
function ProcessErrors(errMsgs) // only used for Eng pages; overridden for other WW
{
if (errMsgs.length > 0) {
	var errMsg = "One or more ERRORS occurred in your submission.\n";
	errMsg += "\nThe items with errors have been marked in RED.\n" +
	"Please correct the errors listed below and re-submit your information.\n";
	for(i=0;i < errMsgs.length;i++) {
		errMsg += ("\n " + errMsgs[i]);
		}
	alert(errMsg);
	ScrollToElement(errFld.name);
	return false;
}
else
	return true;

} // END ProcessErrors

// ************************************************************************
function ErrText(opt,name) // for Eng pages only; overridden for other WW
{
	switch(opt)
	{
	case "min":
		return "Invalid " + name + ": A full, valid value is required."; break;
	case "max":
		return "Invalid " + name + ": Too many characters."; break;
	case "email":
		return "Invalid Email Address: Expected value like 'john.doe@acme.com'"; break;
	case "radio":
		return name + " not set."; break;
	}
} // END ErrText

// ************************************************************************
function ScrollToElement(name)
{
// relies on DOM to scroll window so named element is near top of window
var elements = document.getElementsByName(name);
//DBG
//alert("Scrolling to " + name);
if (elements.length > 0) elements.item(0).scrollIntoView(true);
} // END SetScrollToElement

// ************************************************************************
function AddOptElem(fld,tag,val)
{
// called from SetYearOpt, SetMonOpt, SetDayOpt, SetModels, StateToRepOpt (RPP)
// called from InitStates
//alert("creating " + tag + " with val " + val);
var newOption = document.createElement('Option');
// OBSTACLE IE requires option to be added before setting tag and value
fld.options.add(newOption);
// OBSTACLE FF requires innerHTML to be use, not innerText
newOption.innerHTML = tag;
if (val == null)
	newOption.value = tag; // IE does not default value to text tag
else
	newOption.value = val;
} // AddOptElem

// ************************************************************************
function ignoreEnterKey(e)
{
// OBSTACLE
// numerous work-arounds for Enter key behavior and browser differences
if (!e) var e = window.event;
var targ = (e.target) ? e.target : e.srcElement
if (e.keyCode == 13 && targ.type != 'textarea' && targ.type != 'submit') {
	e.returnValue = false; // for MS
	if (e.preventDefault) e.preventDefault(); // for non-MS
	// not needed in this instance
	//event.cancelBubble = true; // for MS
	//if (e.stopPropagation) e.stopPropagation(); // for non-MS
	return false;
	}
return true;
} // END ignoreEnterKey

// ************************************************************************
function formInit()
{
// called from init
frm = document.forms[0];
frm.onsubmit = function() {return formValidator()};
frm.onkeypress = ignoreEnterKey;
frm.method = "POST";
frm.action = ""; // needs to be set in page's individual script
formElem = frm.elements
} // END formInit

