//Javascript Form Validation
//Author: H Glenn Hatfield
//Date: 13 April 2005

/**
 * In another file, set up the validation_array by calling the function AddValidationField(formName,fieldName,regex,error_div);
 * The above variable definitions should be specified after this file is loaded.
 */

var validation_array = new Array();
var fieldIndex = 0;
var error_count = 0;
var show_errors = true;

var field_bg_error = "#aa0022";
		field_bg_error = "#E6919A";
var field_bg_default = "white";
var field_color_error = "";
var highlight_method = false;

//var border_color_default = "#404040 1px solid";
var border_color_default = "#7f9db9 1px solid";
var border_color_error = "#aa0022 2px solid";
var outline_method = false;

var focus_first = true;
var focused_first = false;
var all_errors_array = new Array();

function Validate( formName ) {

  if(!validation_array)
  	return false;
  if(formName == 'all' || formName == ''){
    __clear_errors_all();
    return __validate_all();
  }
  if(!validation_array[formName]){
    return false;
  }
  __clear_errors(formName);
  var retVal = __validate_form(formName);
  return retVal;
}

function HideErrors() {
	show_errors = false;
}

function ShowErrors() {
	show_errors = true;
}

// wrapper for AddValidationFieldReal, the field value must match the pattern
function AddValidationField(formName, fieldName, regex, error_div, required){
	var not = 0;
	AddValidationFieldReal(formName, fieldName, regex, error_div, required, not);
}

// wrapper for AddValidationFieldReal, the field value must not match the pattern
function AddValidationFieldNot(formName, fieldName, regex, error_div, required){
	var not = 1;
	AddValidationFieldReal(formName, fieldName, regex, error_div, required, not);
}

// the real AddValidationField. Needs to know if the pattern should match, or if the pattern is not allowed.
function AddValidationFieldReal(formName, fieldName, regex, error_div, required, not){
  if(formName == '' || fieldName == '' || error_div == '') {alert('Invalid Call to AddValidationField'); return false;}
  if(!validation_array[formName]){
    validation_array[formName] = new Array();
  }
  if(!validation_array[formName][fieldName]){
    validation_array[formName][fieldName] = new Array();
  }

  if(!validation_array[formName][fieldName]['not'])
  	validation_array[formName][fieldName]['not'] = Array();
  validation_array[formName][fieldName]['not'][ validation_array[formName][fieldName]['not'].length  ] = not;

  // array of regex so a field can be checked for more than one thing. only make the array if it doesn't exist
  if(!validation_array[formName][fieldName]['regex'])
  	validation_array[formName][fieldName]['regex'] = Array();
  validation_array[formName][fieldName]['regex'][ validation_array[formName][fieldName]['regex'].length  ] = regex;

  // array of error_divs so a field can can have two different msgs to go with the regexes.
  if(!validation_array[formName][fieldName]['error_div'])
  	validation_array[formName][fieldName]['error_div'] = Array();
  validation_array[formName][fieldName]['error_div'][ validation_array[formName][fieldName]['error_div'].length  ] = error_div;

  if(typeof (required)=='undefined')required = true;
  validation_array[formName][fieldName]['required'] = required;
  return true;
}

function ClearAll(formName){
  if(validation_array[formName]){
    __clear_errors(formName);
  }
}

function Clear(formName,fieldName){
  __clear_error(formName,fieldName);
}

/*
 * Reset() will set validation_array to be an empty array, ready to be repopulated
 *
 */
function Reset(){
  validation_array = new Array();
}
 /***********************************************************
 * The functions that follow should not be called directly. *
 * Only call the Validate() function.                       *
 ***********************************************************/

function __clear_error(formName,fieldName){

	error_count = 0;
	// true to disable, false to enable
	focused_first = true;
	if (!validation_array[formName] || !validation_array[formName][fieldName] || !validation_array[formName][fieldName]['error_div'] || !validation_array[formName][fieldName]['error_div'].length) {
		return;	//this isn't a field
	}
	var errorDiv;
	var size = validation_array[formName][fieldName]['error_div'].length;
	var i = 0;
	while(i < size) {
		errorDiv = document.getElementById( validation_array[formName][fieldName]['error_div'][i] );
		if(errorDiv){
   	 		errorDiv.style.display = "none";
  		}

		if( highlight_method && show_errors == true )  {
			el = document.forms[ formName ].elements[ fieldName ];
			if( el && el.style ) {
				el.style.background = field_bg_default;
				el.style.color = "black";
			}
		}

		if( outline_method && show_errors == true )  {
			el = document.forms[ formName ].elements[ fieldName ];
			if( el && el.style ) {
				el.style.border = border_color_default;
			}
		}
		i++;
	}
}

function __clear_errors(formName){
  for (var field in validation_array[formName]){
    __clear_error(formName, field);
  }
}

function __validate_all(){
  for( var i in validation_array)
  {
    if ( !__validate_form(validation_array[i]) )return false;
  }
  return true;
}

function __validate_form( formName ){

	all_errors_array = new Array();

  var retVal = true;
  if(!document.forms[formName]) return false;
  for( var field in validation_array[formName] ){
    if( validation_array[formName][field]['required']){
      if( !__validate_field( formName, field ) ){
        error_count++;
        retVal = false;
        if(validation_array[formName][field]['error_div'][fieldIndex]){
          var errorDiv = document.getElementById(validation_array[formName][field]['error_div'][fieldIndex] );
          if (errorDiv) {
            if( show_errors == true ) {
            	var msg = '';
            	msg = '<span style="cursor:pointer; color:#AA0022; font-size:14px;" onclick="notice(document.forms[\''+formName+'\'].elements[\''+field+'\']);">' + errorDiv.innerHTML + '</span>';
            	all_errors_array.push(msg);
              errorDiv.style.display = "block";
            }
          }
          var el = document.forms[ formName ].elements[ field ];
          if( highlight_method && show_errors == true ) {
            if( el && el.style ) {
              el.style.background = field_bg_error;
              el.style.color = field_color_error;
            }
          }
          if( outline_method && show_errors == true ) {
            if( el && el.style ) {
              el.style.border = border_color_error;
            }
          }
          if( focus_first && !focused_first ) {
          	focused_first = true;
						el.focus();
          }
        }
      }
    }
  }
  enumerate_errors( document.getElementById('errors') );
  return retVal;
}

function notice( field ) {
	field.focus();
}

function enumerate_errors( dest_div ) {
	if(!dest_div) {
		return;
	}
	dest_div.innerHTML = '';
	if( all_errors_array.length < 1 ) {
		return;
	}
	var i = 0;
	var str = 'Please correct the folling errors:<br />';
	while( i < all_errors_array.length ) {
		str += all_errors_array[i] + "<br />";
		i++;
	}
	dest_div.innerHTML = str + "<br />";

}

function __validate_field( formName, fieldName ){
  var re='';
  if(!document.forms[formName][fieldName]) return false;
  if(document.forms[formName][fieldName].type){
    switch(document.forms[formName][fieldName].type){
      case 'select-one':
        return (document.forms[formName][fieldName].selectedIndex > 0);
        break;
      case 'checkbox':
        return document.forms[formName][fieldName].checked;
        break;
      case 'hidden':
      case 'password':
      case 'textarea':
      case 'text':

      	var i = 0;
      	var numChecks = validation_array[formName][fieldName]['regex'].length;
      	var result;
      	var notContain;
      	var ret;
 				while(i < numChecks ) {

					// after we return we need to know which error_div to show if there is more than one.
					fieldIndex = i;

					notContain = validation_array[formName][fieldName]['not'][i];
					//alert(numChecks + ' not ' + notContain + ' ' + document.forms[formName][fieldName].value );
 					re = new RegExp(validation_array[formName][fieldName]['regex'][i]);
 					if( notContain) {
        		result = !document.forms[formName][fieldName].value.match(re);
        	} else {
        		result = document.forms[formName][fieldName].value.match(re);
        	}

        	// multi check fields need more work
        	if( numChecks > 1 ) {

        		// must decide if it is good or bad, not just return teh result
        		if( !!result ) {
        			ret = 'good';
        			// it is good, so if it is the last check for this field, return it.
        			if( (i + 1) == numChecks) {
        				//alert( 'last check, is good');
        				return ret;
        			}
        		// it is bad, stop other checks and return the error
        		} else {
        			ret = '';
        			// alert('found bad ' + fieldIndex);
        			return ret;
        		}

					// single check field can just return
        	} else {
        		return result;
        	}

 					i++;
 				}
 				break;

      case 'radio':
        re = new RegExp(validation_array[formName][fieldName]['regex']);
        return document.forms[formName][fieldName].value.match(re);
        break;
    }
  }else{
    for( var i = 0; i < document.forms[formName][fieldName].length; ++i){
      if(document.forms[formName][fieldName][i].checked) return true;
    }
    return false;
  }
  return false;
}

