/*               VALIDATE                           */
/**
 * validation_history information (given to any function submitted for additional form processing as first argument)
 * Format of object is as follows:
 * validate_history[n][0]==element id this history entry applies to
 * validate_history[n][1]==validation type
 * validate_history[n][2]==return status of validation (true = valid/pass, false = not valid/fail)
 */

/**
 * The index of the validation arguments for a form_obj array element. This is where extra
 * options (such as the one for the regexp validation_type) can be found.
 */
 
 
 /* OVERRIDE GOOGLE AUTOFILL - DON'T HAVE THE YELLOW BACKGROUND */
   //if(window.attachEvent)    window.attachEvent("onload",setListeners);

  function setListeners(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++){
      inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
    }
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++){
      selectList[i].attachEvent("onpropertychange",restoreStyles);
      selectList[i].style.backgroundColor = "";
    }
  }

  function restoreStyles(){
    if(event.srcElement.style.backgroundColor != "")
      event.srcElement.style.backgroundColor = "";
  } 
  
  /* */

/**
 * Index of the validation element id inside the form_obj array object
 */
var validation_element_index=0;

/**
 * Index of the validation type inside the form_obj array object
 */
var validation_type_index=1;

/**
 * Index of the validation compare id inside the form_obj array object
 */
var validation_compare_index=3;//2 reserved for valid or not

/**
 * Add form validation
 * @param Array form_obj Array object which is created by this function and passed around to be used as the 'configuration' when validating
 * @param string validation_element Form object id which you wish to validate
 * @param string validation_type Type of validation you wish to do (possible values: 'required', 'regexp')
 * @param string opt[n] Additional data that may be required for validation of this object, ex: if you use regexp you will need to require the regexp string to test against here
 * ex: validation_add_obj(form_obj, 'this_form_element_id', 'regexp', 'car')
 */
function validation_add_obj(form_obj, validation_element_id, validation_type)
{
  var validation_arg_start=3; // where the defined arguments stop and the variable length type specific validation arguments start

  if(form_obj!=null && form_obj.constructor!=Array) // lets see if this is an array
  {
    alert('Error: first argument submitted to validation_add_obj() must be an array or non-initialized variable.');
    return false;
  }
  else if(form_obj==null) form_obj=new Array();

  form_obj[form_obj.length]=new Array();
  var comma = validation_element_id.indexOf(',');
  if(comma == -1)
	  form_obj[(form_obj.length-1)][validation_element_index]=validation_element_id; // record the form object ID
  else{
	  form_obj[(form_obj.length-1)][validation_element_index]=validation_element_id.substring(0,comma);
	  form_obj[(form_obj.length-1)][validation_compare_index]=validation_element_id.substring(comma+1);
  }
  form_obj[(form_obj.length-1)][validation_type_index]=validation_type; // record the validation type
  if(arguments[validation_arg_start]!=null) // do we have arguments along with this validation type?
  {
    form_obj[(form_obj.length-1)][validation_arg_index]=new Array();
    for(var i=validation_arg_start; i<arguments.length; i++) // record the arguments in a sub-array
      form_obj[(form_obj.length-1)][validation_arg_index][(i-validation_arg_start)]=arguments[i];
  }

  return form_obj;
}

/**
 * Do form validation (this is most usually invoked via the onSubmit handler for the form itself)
 * @param Array form_obj Form object array which is created using validation_add_obj()
 * @param string func Function which is used to compute the return status to the form (true/false return of this function)
 * ex: validate_form(form_obj)
 */
function validate_form(form_obj)
{
  var el, form_valid=true, regtest, ret, validation_history=new Array();

  for(var i=0; i<form_obj.length; i++) // lets run through each element and check them
  {
	el=document.getElementById(form_obj[i][validation_element_index]);
	if(el==null) // user supplied invalid element id
    {
      alert('Error: Invalid element ID [' + form_obj[i][validation_element_index] + '] - does not exist.');
      return false;
    }

    validation_history[i]=new Array(); // init the new history entry in array
    // Record the element and validation type inside history entry
    validation_history[i][0]=form_obj[i][validation_element_index];
    validation_history[i][1]=form_obj[i][validation_type_index];

	// Now lets do the specific validation required for this element
    switch(el.type)
    {
      case 'textarea':
      case 'hidden':
      case 'password':
      case 'text':
        switch(form_obj[i][validation_type_index])
        {
          case 'required':
            if(el.value!=null && el.value!='') // value is required, is it set?
              validation_history[i][2]=true; // record validation status (pass)
            else
            {
              form_valid=false; // set global return to false (fail)
              validation_history[i][2]=false; // record validation status (fail)
            }
            break;

          case 'regexp':
          case 'regex':
          case 'exp':
          case 'reg':
            regtest=new RegExp(form_obj[i][validation_arg_index][0],"i");
            if(regtest.exec(el.value)) // if pattern matches
              validation_history[i][2]=true; // record validation status (pass)
            else // if pattern does not match
            {
              form_valid=false; // set global return to false (fail)
              validation_history[i][2]=false; // record validation status (fail)
            }
            break;
		  case 'compare':
		    var elcompare=document.getElementById(form_obj[i][validation_compare_index]);
			//logIt('el:'+el.value+' elcompare:'+elcompare.value);
			if(el.value == '' || elcompare.value == '' || el.value != elcompare.value){
				//set compare field red;
				elcompare.className='error_highlight'; 
				validation_history[i][2]=false;
				form_valid=false;
			}else{
				elcompare.className=''; 
				validation_history[i][2]=true;
			}
		  	break;
	  case 'not-equal':
	      if(el.value!=form_obj[i][validation_arg_index][0])
		validation_history[i][2]=true;
	      else
		validation_history[i][2]=false;
              break;
          default:
            alert('Error: invalid validation type [' + form_obj[i][validation_type_index] + '] for element ' + el.type);
        }
        break;

      case 'radio':
      case 'checkbox':
        switch(form_obj[i][validation_type_index])
        {
          case 'required':
            if(el.checked) // value is required, is it set?
              validation_history[i][2]=true; // record validation status
            else
            {
              form_valid=false; // set global return to false (fail)
              validation_history[i][2]=false; // record validation status
            }
            break;

          default:
            alert('Error: invalid validation type [' + form_obj[i][validation_type_index] + '] for element ' + el.type);
        }
        break;

      case 'select-one':
        switch(form_obj[i][validation_type_index])
        {
          case 'regexp':
          case 'regex':
          case 'exp':
          case 'reg':
            regtest=new RegExp(form_obj[i][validation_arg_index][0],"i");
            if(regtest.exec(el.value)){ // if pattern matches
              validation_history[i][2]=false; // record validation status (pass)
			  form_valid=false;
			}else // if pattern does not match
            {
              validation_history[i][2]=true; // record validation status (fail)
            }
            break;
          
          case 'not-equal':
            if(el.value!=form_obj[i][validation_arg_index][0])
              validation_history[i][2]=true;
            else
              validation_history[i][2]=false;
            break;

          default:
            alert('Error: invalid validation type [' + form_obj[i][validation_type_index] + '] for element ' + el.type);
        }
        break;

      default:
        alert('Error: Undefined form element type [' + el.type + '] - please tell developer to fix.');
        break;
    }
  }

  if(arguments.length>1) // do we have a function to query first?
    return arguments[1](validation_history); // call the function and return its return value to parent

  return form_valid; // return the master pass/fail return status (fail==false==halt form submission)
}

function check_validation_status(hist){
  var return_val=true;

  for(var i=0; i<hist.length; i++)
  {
    if(hist[i][2]==false) // something failed
    {
      return_val=false;
      $('#'+hist[i][0]).addClass('errorColor'); // highlight the broken field
	  document.getElementById('validation_error').style.display="block"; // display error message
    }
    else
      $('#'+hist[i][0]).removeClass('errorColor'); // reset the classname on the form element
  }

  return return_val;
}










//---------------------------------------------------------------------------------------------------------


var validation_arg_index=2;
var validate;
//$(function() {                 moved to content.cfm
function initFormValidation(){
	// code to execute when the DOM is ready
	var childArray = new Array();
	$('#validation_error').hide();
	
	if(window.attachEvent) setListeners();//form validation
	
	var varType = $(document).getUrlParam("type");
	
	if(varType === 'childrensministry'){
		validate=validation_add_obj(validate,'phone','required');
		validate=validation_add_obj(validate,'home_address','required');
	}else if(varType == 'marriageform'){
		validate=validation_add_obj(validate,'husbands_name','required');
		validate=validation_add_obj(validate,'wifes_name','required');
		validate=validation_add_obj(validate,'parents_emails','required');
		validate=validation_add_obj(validate,'phone','required');
		validate=validation_add_obj(validate,'home_address','required');
	}else{
		
		validate=validation_add_obj(validate,'fname','required');
		validate=validation_add_obj(validate,'fname','not-equal','First Name');
		validate=validation_add_obj(validate,'lname','required');
		validate=validation_add_obj(validate,'lname','not-equal','Last Name');
		validate=validation_add_obj(validate,'phone','required');
		validate=validation_add_obj(validate,'phone','not-equal','Phone');
		validate=validation_add_obj(validate,'email','regexp','.+@.+\\.[a-z]+');
				
		switch(varType){
			case 'prayerrequest':
				validate=validation_add_obj(validate,'recipients','not-equal','- Select Recipients -');
				break;
			case 'growthgroup':
			case 'communitygroup':
				break;
			case 'womensbiblestudy':
				$('#numChildren').hide();
				$('#select_num_children').val('0');
				$('#select_session').val('- Select A Session -');
				validate=validation_add_obj(validate,'select_session','not-equal','- Select A Session -');
				break;
			/*case 'couplesbiblestudy':
				validate=validation_add_obj(validate,'
				break;*/
			default:
				break;
		}
	}
}
//});






/* 
  Basically, there are 2 versions of this function. The one used for form womensbiblestudy only requires 4 fields,
  and the one for childrensministry requires more fields. The divChildren doesn't show until the number of children 
  is indicated.
*/
function addChildren(numFlds){
	//var n = $("select[@name=select_num_children]").val();
	var n = $("#select_num_children").val();
	var s = "<div id='divChildren'>";
	var f = "";
	var x = 0;
	var nameFld = '';
	
	for(var i = 0; i < n; i++){
		x = i + 1;
		if(x > 1) f += ",";
		
		nameFld = "child_name_" + x;
		f += nameFld + ",";//fieldorder
		s += '<ul class="formFields children">';
		s += "<li><label for='"+nameFld+"'>Child "+x+" Name</label></li>";
		s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Name' value=''";
		s += " class='populate inputtext'/></li>";
		
		nameFld = "child_birthday_" + x;
		f += nameFld + ",";//fieldorder
		s += "<li><label for='"+nameFld+"'>Child "+x+" Birthday</label></li>";
		s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Birthday' value=''";
		s += " class='populate inputtext'/></li></ul>";
		
		nameFld = "child_allergies_" + x;
		f += nameFld + ",";//fieldorder
		s += '<ul class="formFields children">';
		s += "<li><label for='"+nameFld+"'>Child "+x+" Allergies</label></li>";
		s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Allergies' value=''";
		s += " class='populate inputtext'/></li>";
		
		nameFld = "child_special_instructions_" + x;
		f += nameFld;//fieldorder
		s += "<li><label for='"+nameFld+"'>Child "+x+" Special Instructions</label></li>";
		s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Special Instructions' value=''";
		s += " class='populate inputtext'/></li></ul>";

		if(numFlds > 2){//only add birthday and grade if parm in is > 2
			nameFld = "child_age_" + x;
			f += nameFld + ",";//fieldorder
			s += '<ul class="formFields children">';
			s += "<li><label for='"+nameFld+"'>Child "+x+" Age</label></li>";
			s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Age' value=''";
			s += " class='populate inputtext'/></li>";
			
			nameFld = "child_grade_" + x;
			f += nameFld + ",";//fieldorder
			s += "<li><label for='"+nameFld+"'>Child "+x+" Grade</label></li>";
			s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Grade' value=''";
			s += " class='populate inputtext'/></li></ul>";
			
			nameFld = "child_school_" + x;
			f += nameFld + ",";//fieldorder
			s += '<ul class="formFields children">';
			s += "<li><label for='"+nameFld+"'>Child "+x+" School</label></li>";
			s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" School' value=''";
			s += " class='populate inputtext'/></li></ul>";
			
		}
		
	}
	addEmailField(f);
	$("#divChildren").html(s);
	//$("input[@name=child_name_1]").focus();
	//alert('x:'+x+' fieldorder:'+$F('fieldorder'));
	autoPopulate.init();
}

function addEmailField(fldName){//this function writes the field that tells the email how to keep the fields in order
	//var f = $("input[@name=fieldorder]").val() + "," + fldName;
	var f = $("#fieldorder").val() + "," + fldName;
	//$("input[@name=fieldorder]").val(f);
	$("#fieldorder").val(f);
}

function addChildcare(){
	//var s = $("select[@name=select_session]").val();
	var s = $("#select_session").val();
	if(s === "Tuesday morning 9:30"){
		$('#numChildren').show();
	}else{
		//if(s == "- Select A Session -") $('#feedback').html('Please select a session');
		$('#numChildren').hide();
	}
}

function validateNews(){
	var bValid = true;
	var aVal = new Array();
	var a = new Array();
	a.push('#fname_signup','First Name');
	aVal.push(a);
	var a2 = new Array();
	a2.push('#lname_signup','Last Name');
	aVal.push(a2);
	for(var i = 0; i < aVal.length; i++){
		var el = $(aVal[i][0]).val();
		if(el == '' || el == aVal[i][1]){
			$(aVal[i][0]).addClass('errorColor');
			bValid = false;
		}else{
			$(aVal[i][0]).removeClass('errorColor');
		}
	}
	regtest=new RegExp('.+@.+\\.[a-z]+');
	var el = $('#email_signup').val();
        if(!regtest.exec(el)){// if pattern does not match
        	$('#email_signup').addClass('errorColor');
		bValid = false;
	}else{
		$('#email_signup').removeClass('errorColor');
        }
        a = undefined;
        a2 = undefined;
        aVal = undefined;
	return bValid;
}
/* 
  Basically, there are 2 versions of this function. The one used for form womensbiblestudy only requires 2 fields,
  and the one for childrensministry requires 4 fields. The divChildren doesn't show until the number of children 
  is indicated.
  UPDATED FOR MARRIAGE FORM
*/
function addChildrenMarriage(numFlds){
	//var n = $("select[@name=select_num_children]").val();
	var n = $("#select_num_children").val();
	var s = "<div id='divChildren'>";
	var f = "";
	var x = 0;
	var nameFld = '';
	
	for(var i = 0; i < n; i++){
		x = i + 1;
		if(x > 1) f += ",";
		
		nameFld = "child_name_" + x;
		f += nameFld + ",";//fieldorder
		s += '<ul class="formFields children">';
		s += "<li><label for='"+nameFld+"'>Child "+x+" Name</label></li>";
		s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Name' value=''";
		s += " class='populate inputtext'/></li>";
		alert(f);
		nameFld = "child_age_" + x;
		f += nameFld + ",";//fieldorder
		s += "<li><label for='"+nameFld+"'>Child "+x+" Age</label></li>";
		s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Age' value=''";
		s += " class='populate inputtext'/></li>";
		s += "</ul>";
		alert(f);
		if(numFlds > 2){//only add birthday and grade if parm in is > 2
			nameFld = "child_birthday_" + x;
			f += nameFld + ",";//fieldorder
			s += '<ul class="formFields children">';
			s += "<li><label for='"+nameFld+"'>Child "+x+" Allergies</label></li>";
			s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Allergies' value=''";
			s += " class='populate inputtext'/></li>";
			
			nameFld = "child_grade_" + x;
			f += nameFld + ",";//fieldorder
			s += "<li><label for='"+nameFld+"'>Child "+x+" Grade</label></li>";
			s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Grade' value=''";
			s += " class='populate inputtext'/></li>";
			s += "</ul>";
			
			nameFld = "child_info_" + x;
			f += nameFld + ",";//fieldorder
			s += '<ul class="formFields children">';
			s += "<li><label for='"+nameFld+"'>Child "+x+" Additional Info</label></li>";
			s += "<li><input type='text' id='"+nameFld+"' name='"+nameFld+"' title='Child "+x+" Additional Info' value=''";
			s += " class='populate inputtext'/></li>";
			s += "</ul>";
		}
	}
	//alert(f);
	addEmailField(f);
	$("#divChildren").html(s);
	//$("input[@name=child_name_1]").focus();
	//alert('x:'+x+' fieldorder:'+$F('fieldorder'));
	autoPopulate.init();
}