// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
//
// Update Jun 2006: minor improvements to variable names and layout
// ----------------------------------------------------------------------
// Modifications for GetBlueMA
// Modifier: Patrick Demasco
//  - Added support for checking arrays of checkable buttons (e.g., radio buttons

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread

// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}


// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;  

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem.firstChild) 
  	return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text) 
  	return true;  // infofield is wrong type of node  

  if (emptyString.test(valfield.value)) {
    if (required) {
      msg (infofield, "error", "Required");  
      setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) 
  	return stat;

  msg (infofield, "warn", "");  
  return true;
}

// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "error", "Invalid e-mail address");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "warn", "Unusual e-mail address");
  else
    msg (infofield, "warn", "");
  return true;
}


// --------------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validateTelnr  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/  ;
  if (!telnr.test(tfld)) {
    msg (infofield, "error", "Invalid number");
    setfocus(valfield);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (infofield, "error", "" + numdigits + " digits - too short");
    setfocus(valfield);
    return false;
  }

  if (numdigits>14)
    msg (infofield, "warn", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (infofield, "warn", "Only " + numdigits + " digits - check if correct");
    else
      msg (infofield, "warn", "");
  }
  return true;
}

// --------------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// --------------------------------------------

function validateAge    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (infofield, "error", "Not a valid age");
    setfocus(valfield);
    return false;
  }

  if (tfld>=200) {
    msg (infofield, "error", "Not a valid age");
    setfocus(valfield);
    return false;
  }

  if (tfld>110) msg (infofield, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (infofield, "warn", "Bit young for this, aren't you?");
    else        msg (infofield, "warn", "");
  }
  return true;
}


// --------------------------------------------
//             validateCheckableButtons
// Validate an array of checkable buttons (e.g., radio buttons) to insure that 
// one is checked
// Returns true if OK 
// --------------------------------------------
function validateCheckableButtons(valfieldArray, infofield)
{

	if (!document.getElementById) 
		return true;  // not available on this browser - leave validation to the server

	var elem = document.getElementById(infofield);
  	if (!elem.firstChild) 
  		return true;  // not available on this browser 

  	if (elem.firstChild.nodeType != node_text) 
  		return true;  // infofield is wrong type of node  

	if(valfieldArray.length == 0)
		return true;

	for (var i = 0; i < valfieldArray.length; i++) 
	{
	

        	if (valfieldArray[i].checked)
		{

		 	msg (infofield, "warn", "");  
			return true;
		}
	}

  	
	msg (infofield, "error", "Required");  
	//valfieldArray[0].focus();
     	setfocus(valfieldArray[0]);
      	return false;
   
}

function CensusData(coverageType, dobMonth, dobDay, dobYear, zip)
{
	this.coverageType = coverageType;
	this.dobMonth = dobMonth;
	this.dobDay = dobDay;
	this.dobYear = dobYear;
	this.zip = zip;
}

// Because of the way that newmediagateway wants form elements named, we must unfortunately 
// get controls by walking through the control array
function QuoteFormControls(formElements)
{
	var index=0;

	this.SubmitDate = formElements[index++];
	this.UseBrokerYes = formElements[index++];
	this.UseBrokerNo = formElements[index++];
	this.ExistingAccountYes = formElements[index++];
	this.ExistingAccountNo = formElements[index++];
	this.FirstName = formElements[index++];
	this.LastName = formElements[index++];
	this.Company= formElements[index++];
	this.Address= formElements[index++];
	this.Address2= formElements[index++];
	this.City= formElements[index++];
	this.State= formElements[index++];
	this.ZipCode= formElements[index++];
	this.Phone= formElements[index++];
	this.Ext= formElements[index++];	
	this.Email = formElements[index++];
	this.Sic = formElements[index++];
	this.IndustryType = formElements[index++];
	this.TotalEmployeeCount = formElements[index++];
	this.EligibleEmployeeCount = formElements[index++];

	this.employeeCensusArray = new Array();
	for(var i = 0; i != 9; ++i)
	{
		var coverageType = formElements[index++];
		var dobMonth = formElements[index++];
		var dobDay = formElements[index++];
		var dobYear = formElements[index++];
		var zip = formElements[index++];
		var censusItem = new CensusData(coverageType, dobMonth, dobDay, dobYear, zip);
		this.employeeCensusArray[i] = censusItem
	}
	this.OutOfStateYes = formElements[index++];
	this.OutOfStateNo = formElements[index++];

	this.PlanHmo = formElements[index++];
	this.PlanPpo = formElements[index++];
	this.PlanNotSure = formElements[index++];

	this.ProductMedical = formElements[index++];
	this.ProductDental = formElements[index++];
	this.ProductLifeStdEtc = formElements[index++];

	this.ContactPhone = formElements[index++];
	this.ContactEmail =  formElements[index++];

}

function validateHasExistingAccount(controls)
{
	var existingAccountArray = new Array();
	existingAccountArray[0] = controls.ExistingAccountYes;
	existingAccountArray[1] = controls.ExistingAccountNo;
	return validateCheckableButtons(existingAccountArray , 'inf_existing_account');

}

function ValidateHasExistingAccountControl()
{
	var controls = new QuoteFormControls( document.forms.enter_contact.elements);
	return validateHasExistingAccount(controls);
}


function validateWorkingWithBroker(controls)
{
	var useBrokerArray= new Array();
	useBrokerArray[0] = controls.UseBrokerYes;
	useBrokerArray[1] = controls.UseBrokerNo;
	return validateCheckableButtons(useBrokerArray , 'inf_use_broker');

}

function ValidateWorkingWithBrokerControl()
{
	var controls = new QuoteFormControls( document.forms.enter_contact.elements);
	return validateWorkingWithBroker(controls);
}



function validatEmpOutOfState(controls)
{

	var outOfStateArray= new Array();
	outOfStateArray[0] = controls.OutOfStateYes;
	outOfStateArray[1] = controls.OutOfStateNo;
	return validateCheckableButtons(outOfStateArray , 'inf_out_of_state');
}

function ValidateEmpOutOfStateControl()
{
	var controls = new QuoteFormControls( document.forms.enter_contact.elements);
	return validatEmpOutOfState(controls);
}

function validatePlanChoice(controls)
{
	var planArray= new Array();
	planArray[0] = controls.PlanHmo;
	planArray[1] = controls.PlanPpo;
	planArray[2] = controls.PlanNotSure;
	return validateCheckableButtons(planArray , 'inf_plan');

}
function ValidatePlanChoiceControl()
{
	var controls = new QuoteFormControls( document.forms.enter_contact.elements);
	return validatePlanChoice(controls);
}



function validateProductChoice(controls)
{
	var productArray= new Array();
	productArray[0] = controls.ProductMedical;
	productArray[1] = controls.ProductDental;
	productArray[2] = controls.ProductLifeStdEtc;
	return validateCheckableButtons(productArray , 'inf_product');

}
function ValidateProductChoiceControl()
{
	var controls = new QuoteFormControls( document.forms.enter_contact.elements);
	return validateProductChoice(controls);
}

function validateContactChoice(controls)
{
	var contactArray= new Array();
	contactArray[0] = controls.ContactPhone;
	contactArray[1] = controls.ContactEmail;
	return validateCheckableButtons(contactArray , 'inf_contact_preference');

}
function ValidateContactChoiceControl()
{
	var controls = new QuoteFormControls( document.forms.enter_contact.elements);
	return validateContactChoice(controls);
}

// TODO: here because it makes working with the Javascript debugger easier - will move back to form
function validateOnSubmit() 
{ 
	var elem;
	var errs=0;

	var controls = new QuoteFormControls( document.forms.enter_contact.elements);
	
	
	// Set date field
	var currentTime = new Date()
	var month = currentTime.getMonth() + 1
	var day = currentTime.getDate()
	var year = currentTime.getFullYear()
	var dateStr = year;
	dateStr += "/";
	if(month < 10)
		dateStr += "0";
	dateStr += month;
	dateStr += "/";
	if(day < 10)
		dateStr += "0";
	dateStr += day;
	controls.SubmitDate.value = dateStr;
	

	// execute all element validations in reverse order, so focus gets
	// set to the first one in error.



	if(!validateContactChoice(controls))
		errs +=1;



	if(!validateProductChoice(controls))
		errs +=1;
	


	if(!validatePlanChoice(controls))	
		errs +=1;
	


	if(!validatEmpOutOfState(controls))
		errs +=1;
	
	
	var eligibleEmployeeCount = controls.EligibleEmployeeCount.selectedIndex +1;
	for(var i = 0; i != eligibleEmployeeCount; ++i)
	{
		var infoFieldName = "inf_employee_census_";
		infoFieldName += (i+1);
		
	
		
		var selectControl = controls.employeeCensusArray[i].coverageType;
		if (selectControl.selectedIndex == 0) 
		{
			errs += 1; 
			continue;
		}

		if (!validatePresent(controls.employeeCensusArray[i].dobMonth, infoFieldName )) 
		{

			errs += 1; 
			continue;
		}

		if (!validatePresent(controls.employeeCensusArray[i].dobDay, infoFieldName )) 
		{

			errs += 1; 
			continue;
		}
	
		if (!validatePresent(controls.employeeCensusArray[i].dobYear, infoFieldName )) 
		{

			errs += 1; 
			continue;
		}
	
		if (!validatePresent(controls.employeeCensusArray[i].zip, infoFieldName )) 
		{
	
			errs += 1; 
			continue;
		}
		
 
	
	}


	if (!validatePresent(controls.IndustryType, 'inf_industry_type')) 
		errs += 1; 
	if (!validateEmail  (controls.Email, 'inf_email', true)) 
		errs += 1; 
	if (!validateTelnr(controls.Phone,   'inf_phone', true)) 
		errs += 1; 
	if (!validatePresent(controls.ZipCode,   'inf_zip')) 
		errs += 1; 
	if (!validatePresent(controls.City,   'inf_city')) 
		errs += 1; 
	if (!validatePresent(controls.Address,   'inf_address')) 
		errs += 1; 
	if (!validatePresent(controls.Company,   'inf_company_name')) 
		errs += 1; 
	if (!validatePresent(controls.LastName,   'inf_last_name')) 
		errs += 1; 
	if (!validatePresent  (controls.FirstName, 'inf_first_name')) 
		errs += 1; 


	if(!validateHasExistingAccount(controls))
		errs +=1;

	if(!validateWorkingWithBroker(controls))
		errs +=1;







	if (errs>1)  
		alert('There are fields which need correction before sending');
    
	if (errs==1) 
		alert('There is a field which needs correction before sending');

	return (errs==0);
};
  
  function updateCensus(valField)
  {
	if (!document.getElementById) 
    	return;  // not available on this browser - leave validation to the server
		
 	var index = valField.selectedIndex;
	
	var i;
	for(i= 0; i != 9; ++i)
	{
		var row_num = i+1;
		var row_name = "census_row_" + row_num;
		var censusRow = document.getElementById(row_name);
		if(i <= index)
			censusRow.style.display = "";
		else
			censusRow.style.display = "none";
	}
  }
		
		
 

