/* Add some custom validations */

Validation.addAllThese([
  ['validate-all-selection', 'Please make a selection', function(v,elm){
        var p = elm.parentNode;
        var options = p.getElementsByTagName('SELECT');
        return $A(options).all(function(elm) {
          return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
        });
      }],
      
  ['validate-all-required', 'These are required fields.', function(v, elm) {
        var p      = elm.parentNode;
        var inputs = p.getElementsByTagName('INPUT');
        return $A(inputs).all(function(elm) {
          return !Validation.get('IsEmpty').test($F(elm));
        });
      }],
  
  ['validate-two-part-height', 'Please enter a valid height.', function (v,elm) {
        /* This expects mm dd yyyy as the order of select tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        return !Validation.get('IsEmpty').test($F(parts[0])) && !/^\s$/.test($F(parts[0])) && !Validation.get('IsEmpty').test($F(parts[1])) && !/^\s$/.test($F(parts[1]));
      }],
      
  ['validate-three-part-dob', 'Please enter a valid date of birth.', function (v,elm) {
        /* This expects mm dd yyyy as the order of tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        if (parts.length == 0) {
          parts = p.getElementsByTagName('INPUT');
        }
        
        /* Check to see that this is a valid date format */
        var valid_format = /(^0?[1-9]$)|(^1[012]$)/.test($F(parts[0])) && /(^0?[1-9]$)|(^[12][0-9]$)|(^3[01]$)/.test($F(parts[1])) && /^[0-9]{4}$/.test($F(parts[2]));
        if (valid_format == false) return valid_format;
        
        var month = $F(parts[0]) * 1 - 1;
        var day   = $F(parts[1]) * 1;
        var year  = $F(parts[2]) * 1;
        
        var is_leap_year   = ((year % 100 == 0) && (year % 400 == 0)) || ((year % 100 != 0) && (year % 4 == 0));
        var feb_days       = (is_leap_year) ? 29 : 28;
        var days_in_months = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        
        /* Check to make sure that the days doesn't exceed the day in that month */
        if (day > days_in_months[month]) return false;
        
        /* Now that we know the date is at least a valid format, check to see that the birthdate is within a sensible range */
        var oldest_age_ever = 122;
        var dob                       = new Date(year, month, day);
        var dob_of_oldest_person_ever = new Date(year + oldest_age_ever, month, day);
        
        var today = new Date();
        
        /* not_too_young */
        var not_too_young = (today - dob) >= 0;
        
        /* not_too_old */
        var not_too_old = (dob_of_oldest_person_ever - today) >= 0;
        
        return (not_too_old && not_too_young);
      }],
      
  ['validate-three-part-child-dob', 'Please enter a valid date of birth.', function (v,elm) {
        /* This expects mm dd yyyy as the order of tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        if (parts.length == 0) {
          parts = p.getElementsByTagName('INPUT');
        }
        
        /* Check to see that this is a valid date format */
        var valid_format = /(^0?[1-9]$)|(^1[012]$)/.test($F(parts[0])) && /(^0?[1-9]$)|(^[12][0-9]$)|(^3[01]$)/.test($F(parts[1])) && /^[0-9]{4}$/.test($F(parts[2]));
        if (valid_format == false) return valid_format;
        
        var month = $F(parts[0]) * 1 - 1;
        var day   = $F(parts[1]) * 1;
        var year  = $F(parts[2]) * 1;
        
        var is_leap_year   = ((year % 100 == 0) && (year % 400 == 0)) || ((year % 100 != 0) && (year % 4 == 0));
        var feb_days       = (is_leap_year) ? 29 : 28;
        var days_in_months = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        
        /* Check to make sure that the days doesn't exceed the day in that month */
        if (day > days_in_months[month]) return false;
        
        /* Now that we know the date is at least a valid format, check to see that the birthdate is within a sensible range */
        var child_max_age		= 25;
        var child_dob       = new Date(year, month, day);
        var child_age_limit = new Date(year + child_max_age, month, day);
        
        var today = new Date();
        
        /* custom error msg */
        var error_over25_msg 				= "Children over 25 cannot be insured.";
        var error_older_than_parent = "Children cannot be older than parent(s).";
        
        /* not_too_young */
        var not_too_young = (today - child_dob) >= 0;
        
        /* not_too_old */
        var not_too_old = (child_age_limit - today) >= 0;
        
        /*
         *compare child and parent
         */
        //get parent(s) dates
        var parent_date  = new Date();
        parent_date.setFullYear($F("dob1_yyyy_on"), ($F("dob1_mm_on") - 1), $F("dob1_dd_on"));
				
				if($("dob2_yyyy_on") != null && $("dob2_mm_on") != null && $("dob2_dd_on") != null ){
	        if($F("dob2_yyyy_on") != "" && $F("dob2_mm_on") != "" && $F("dob2_dd_on") != ""){
	          var spouse_date  = new Date();
	          spouse_date.setFullYear($F("dob2_yyyy_on"), ($F("dob2_mm_on") - 1), $F("dob2_dd_on"));
	        }
	        var youngest_parent  = parent_date;
	        //pick youngest parent
	        if(spouse_date){
	          var youngest_parent = (spouse_date > parent_date) ? spouse_date : parent_date;
	        }
	      }else{
	        var youngest_parent  = parent_date;
	      }
        //younger than the parent
        var not_older_than_parent = (child_dob >= youngest_parent);
        
        /* add error msgs */
        var error_siblings	= p.parentNode;
        var error_parent		= error_siblings.parentNode;
        var error_parts			= error_parent.getElementsByTagName("div");
        var error_div				= error_parts[1];
        var is_valid				= true;
        error_div.innerHTML	= "";
        if(!not_too_old && !not_older_than_parent){
        	error_div.innerHTML = error_over25_msg + "<br />" + error_older_than_parent;
        	is_valid 						= false;
      	} 
      	if(is_valid){
	      	if(!not_too_old){
	        	error_div.innerHTML = error_over25_msg;
	        	is_valid 						= false;
	        }
      	}   
      	if(is_valid){
	        if(!not_older_than_parent){
	        	error_div.innerHTML = error_older_than_parent;
	        	is_valid 						= false;
	        }
        }    	
      	error_div.style.display = (is_valid) ?  "none" : "";
      	
        return (not_too_old && not_too_young && not_older_than_parent);
      }],

  ['validate-coverage-start-date', 'Please enter a valid future date.', function (v,elm) {
        /* This expects mm dd yyyy as the order of tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        if (parts.length == 0) {
          parts = p.getElementsByTagName('INPUT');
        }

        /* Check to see that this is a valid date format */
        var valid_format = /(^0?[1-9]$)|(^1[012]$)/.test($F(parts[0])) && /(^0?[1-9]$)|(^[12][0-9]$)|(^3[01]$)/.test($F(parts[1])) && /^[0-9]{4}$/.test($F(parts[2]));
        if (valid_format == false) return valid_format;

        var month = $F(parts[0]) * 1 - 1;
        var day   = $F(parts[1]) * 1;
        var year  = $F(parts[2]) * 1;

        var is_leap_year   = ((year % 100 == 0) && (year % 400 == 0)) || ((year % 100 != 0) && (year % 4 == 0));
        var feb_days       = (is_leap_year) ? 29 : 28;
        var days_in_months = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        /* Check to make sure that the days doesn't exceed the day in that month */
        if (day > days_in_months[month]) return false;

        /* Now that we know the date is at least a valid format, check to see that the birthdate is within a sensible range */
        var coverage_date = new Date(year, month, day);

        var today = new Date();

        /* not before yesterday */
        var not_before_yesterday = (today - coverage_date) <= 0;

				/* not over three months */
        var three_months_from_now 					= new Date();
        three_months_from_now.setDate(today.getDate() + 90);
        var less_than_three_months_from_now = (coverage_date - three_months_from_now) <= 0;

        return not_before_yesterday && less_than_three_months_from_now;
      }],

  ['validate-state', 'Please enter a valid state abbreviation.', {
        pattern: /^[a-zA-Z]{2}$/,
        include: ['required']
      }],
      
  ['validate-zip', 'Please enter a valid zip code.', {
        pattern: /^\d{5}$/,
        include: ['required']
      }],
      
  ['validate-full-name', 'Please enter a first and last name.', {
        pattern: /\w+\s+\w+/,
        include: ['required']
      }],

  ['validate-mandatory-email', 'Please enter a valid email.', {
        include: ['validate-email', 'required']
      }],
      
  ['validate-weight', 'Please enter a valid weight.', {
        include: ['required', 'validate-number']
      }],

  // Phone patterns checked (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
  ['validate-phone', 'Please enter a valid phone number.', {
        pattern: /^\(?[2-9]\d{2}[\)\.-]?\s?[2-9]\d{2}[\s\.-]?\d{4}$/
      }],
      
  ['validate-three-part-phone', 'Please enter a valid phone.', function (v,elm) {
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('INPUT');
        return /^(0?[1-9])|(1[012])$/.test($F(parts[0])) && /^(0?[1-9])|([12][0-9])|(3[01])$/.test($F(parts[1])) && /^[0-9]{4}$/.test($F(parts[2]));
      }],

  ['validate-mandatory-phone', 'Please enter a valid phone number.', {
        include: ['validate-phone', 'required']
      }],
      
  ['reformat-validate-mandatory-phone', 'Please enter a valid phone number.', function (v, elm) {
        v = new FormHelper().reformatPhone(elm);
        return Validation.get('required').test(v) && Validation.get('validate-phone').test(v);
      }],
      
  ['validate-checked', 'Please check the checkbox.', {
        pattern: /^[1yY]$/,
        include: ['required']
      }],
      
  ['validate-name', 'Please use letters only (a-z) in this field.', {
        pattern: /^[a-zA-Z\s-]+$/,
        include: ['required']
      }]
]);

/* Create the FormHelper Class */
var FormHelper = Class.create();
FormHelper.prototype = {
  initialize : function() {},
  
  validateHeight : function() {
    if (Validation.get('validate-selection').test($F('insured1_height_inches'), $('insured1_height_inches'))) {
      return Validation.validate('insured1_height_inches');
    }
  },
  
  validateDateOfBirth : function() {
    if (Validation.get('validate-selection').test($F('dob1_yyyy_on'), $('dob1_yyyy_on'))) {
      return Validation.validate('dob1_yyyy_on');
    }
  },
  
  validateCityStateZip : function() {
    if (Validation.get('required').test($F('address1_zip'), $('address1_zip'))) {
      return Validation.validate('address1_zip');
    }
  },
  
  reformatPhone : function(id) {
    var phone          = $F(id);
    var clean_phone    = phone.gsub(/\D/, '');
    var phone_area     = clean_phone.substr(0,3);
    var phone_exchange = clean_phone.substr(3,3);
    var phone_station  = clean_phone.substr(6,4);
    
    var phone_formatted = "";
    if (phone_area.length > 0) phone_formatted = "(" + phone_area;
    if (phone_exchange.length > 0) phone_formatted += ") " + phone_exchange;
    if (phone_station.length > 0) phone_formatted += "-" + phone_station;
    
    $(id).value = phone_formatted;
    
    return phone_formatted;
  }
}

var formhelper = new FormHelper();