var req_fields = new Array();
var validations = new Array();

var error_replaces_intro = false;

var custom_error = false;

var fields_with_hints = new Array();











function add_req_field(fieldname, hint) {
	if (hint == null){  hint = '';  }	
	req_fields.push(new Array(fieldname, hint));	
}

function add_validation(fieldname, validation_type) {
	validations.push(new Array(fieldname, validation_type));	
}


function isEmpty(strfieldname, form, hint) {
	
	
	if (typeof(form[strfieldname].selectedIndex) != "undefined") {
		// for select element (dropdown list)
		
		if (form[strfieldname].selectedIndex > 0) {
			return false;
		} else {
			return true;
		}
		
		
	}	
	
	if (typeof(form[strfieldname].length) != "undefined")  {
		// for radio buttons
		
	    myOption = -1;
       for (i=form[strfieldname].length-1; i > -1; i--) {
         if (form[strfieldname][i].checked) {
            myOption = i; i = -1;
         }
       }
       if (myOption == -1) {
         return true;
       } else {
         return false;
	   }
		
	}
	
	
	
	if (typeof form[strfieldname].value != "undefined")  {
	// if not a set eg radio buttons
	
      strfield = form[strfieldname].value ;
	
      if (strfield == "" || strfield == null || strfield == hint)
      {
        return true;
      } else {
        return false;
	  }
	  
    }  
	
    return false;
}


function validate_field(strfieldname, form, validation_type) {
	
    if (typeof form[strfieldname].value != "undefined")  {
	  var value = form[strfieldname].value;
	  
	  switch (validation_type) {
		  case ('email') :
			  return isValidEmail(value, false);
		  case ('phone') :
			  return isValidPhone(value, false);
		  default :
		      return true
	  }
	  
	} else {
		return true; // if there is no value, then just say it is ok
    }  	
	
}


//function to check valid email address
function isValidEmail(strEmail, valid_if_empty){
	if (valid_if_empty == null) { valid_if_empty = false; }
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);   
	 
    if (valid_if_empty && strEmail == '') {
	   return true
    } else if (regex.test(strEmail) == false)  {
       return false;
    } else {
       return true; 
    }
}
//function to check valid email address
function isValidPhone(strPhonenum, valid_if_empty){
	
	return true; // not implemented yet
	
}

function validate(form) {
	
	
	var empty_req_fields = new Array(); // those fields which are empty
	var invalid_fields = new Array(); // those fields invalid for a reason other than empty
	
	for(var i = 0; i < req_fields.length; i++) {
      if (isEmpty(req_fields[i][0], form, req_fields[i][1])){
		  empty_req_fields.push(req_fields[i][0]);
	  }
	}
	
	for(i = 0; i < validations.length; i++) {
	  // only validate it if it is not an empty required field
	  if (index_of(validations[i][0], empty_req_fields) == -1) {

        if (!validate_field(validations[i][0], form, validations[i][1])){
		  invalid_fields.push(validations[i][0]);
	    }
	  }
	}
	

	
	// construct an error message
	if(empty_req_fields.length > 0 || invalid_fields.length > 0){
		
	    var  error_output = '<p class="error">';
		  
		if (custom_error) {
			error_output = custom_error;
		} else {
			
			
	
		 
		  if (empty_req_fields.length > 0) {
		
		     error_output += 'You forgot to enter your ';
		
		    for (i = 0 ; i < empty_req_fields.length ; i++) {
		  
		  	  error_output += displayName(empty_req_fields[i]);
		  
		      if (i < empty_req_fields.length - 2) {
		        error_output += ", ";
		      } else if (i < empty_req_fields.length - 1) {
		        error_output += " and ";
		      }
		    }
		 
		  } // required
		 
		 
		  if (invalid_fields.length > 0) {
		 
		 
		     if (empty_req_fields.length > 0) {
		       error_output += ", and ";
		     }
		   
		   
		     for (i = 0 ; i < invalid_fields.length ; i++) {
		  
			   error_output += displayName(invalid_fields[i]);
		
		       if (i < invalid_fields.length - 2) {
		         error_output += ", ";
		       } else if (i < invalid_fields.length - 1) {
		         error_output += " and ";
		       }
		     }
		  
		     if (invalid_fields.length > 1) {
		       error_output += " are invalid";
		     } else if (invalid_fields.length == 1) {
		       error_output += " is invalid";
		     }
		  }
		 
		 error_output += ". Message not sent.";
		
		} // end if custom error
		
		 error_output += "</p>";

		
		document.getElementById('form_error').style.display = 'block';
	    document.getElementById('form_error').innerHTML = error_output;
		
		if (error_replaces_intro) {
			 document.getElementById('intro_msg').style.display = 'none';
		}

		
		return false;

	}else {
		
		// will submit the form
		document.getElementById('form_error').style.display = 'none';
		
	    return true;
	}


}

function displayName(field_name) {
	 return field_name.replace(/_/g, " ");
}


function attachHint (elem_id, hint) {
	
	  fields_with_hints.push(elem_id);

      document.getElementById(elem_id).onfocus = function() {
		var form_element = document.getElementById(elem_id);
		var val = form_element.value;
		var hintstring = hint
		if (val == hintstring) {
		  if (jscss('check',form_element,'hint')) {
		    jscss('remove',form_element,'hint');
		  } 
		  
		  if (form_element.tagName == "TEXTAREA") {
	        form_element.innerHTML = '';
		  } else {
	        form_element.value = '';
	  	  }
		}
		 
		 
	  }
	  
      document.getElementById(elem_id).onblur = function() {
		  var form_element = document.getElementById(elem_id);
		  var val = form_element.value;
		  
		  if (val == '') {
		    if (form_element.tagName == "TEXTAREA") {
	          form_element.innerHTML = hint;
		    } else {
	          form_element.value = hint;
		    }
			
			
			if (!jscss('check',form_element,'hint')) {
		      jscss('add',form_element,'hint');
		    } 
			
		  }// if blur and empty

			
	  }  
	  
	  


}


function errorReplacesIntro(val) {
	error_replaces_intro = val;
}

function customErrorMessage(err_msg) {
	custom_error = err_msg;
	
}

function index_of(val, array) {
	for (var i = 0; i<array.length; i++) {
		if (array[i] == val) { return i; }
	}
	return -1;	
}


function applyHintClasses () {
	
	for (var i = 0; i < fields_with_hints.length ; i++) {
		      jscss('add',document.getElementById(fields_with_hints[i]),'hint');
	
	}
	
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
//  a:  action to perform.
//  o:  the object in question.
//  c1:  the name of the first class
//  c2:  the name of the second class
//  Possible actions:
//  swap:  replaces class c1 with class c2 in object o.
//  add:  adds class c1 to the object o.
//  remove:  removes class c1 from the object o.
//  check:  test if class c1 is already applied to object o and returns true or false.
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function jscss(a,o,c1,c2)
{
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}