
var textFields = new Array('text','password','textarea');
var requiredMsg = "* This is a required field.";


/** FUNCTION validateField
 *
 * SUMMARY given an element (obj) determines whether it is a required field (and then either passes or fails that check)
 * and whether there is regex validation to be applied
 * 
 * RETURNS	true 	: if it passes all checks that apply to it
 * 			false	: if it fails the required or regex checks
 * 			
 * */

function validateField(obj) {
    if (obj  != null) {
   
    var validField = true;
	   
    // check to see if this is a required field
    if ((obj.getAttribute('required') != "") && (obj.getAttribute('required') != null)) {

	
	switch (obj.type) {
	  case "text" :
	  case "file":
	  case "password" :  
	  case "textarea" :
	    validField = ((obj.value != null) && (obj.value != ""));
	    break;
	  case "checkbox" :
	    validField = ((obj.value != null) && (obj.checked != false));
	    break;  
	  case "select-multiple":
	  case "select-one" :
	    validField = ((obj.selectedIndex != null) && (obj.selectedIndex != -1) && (obj.value != ""));
	    break;  
	}
	var message = (validField) ? "" : requiredMsg ;
	showMessage(obj,message);
	
    }
    
        // check to see if the field has (and matches) the regex validation requirements
    
    if ((obj.getAttribute('validation') != "") && (obj.getAttribute('validation') != null) && (in_array(obj.type,textFields))) {
	var regex = new RegExp(obj.getAttribute('validation'));
	if (!regex.test(obj.value)) {
	  validField = false;
      	  if (obj.value != "") showMessage(obj,"* " + obj.getAttribute('msg') );	 
	}
    }
 
    return validField;
}
}



/** FUNCTION showMessage
 *
 * SUMMARY given an element on the page, injects html next to the element for status messages
 * note : it inserts a temporary div only if one doesnt exist, otherwise it simply populates that div
 * 
 * PARAMS	element 	: the DOM element being referenced
 * 			msg	: the text to insert next to selected element
 * 			
 * */
 
function showMessage(element,msg) {
  if (element) {
  var obj = document.getElementById('error_' + element.id);
  if (!obj) {
     element.insertAdjacentHTML("afterEnd",'<div style="color:red" id="error_' + element.id + '" />' + msg + '</div>');
  } else {
     obj.innerHTML = msg;
  }
  }
}



/** FUNCTION validateForm
 *
 * SUMMARY given an element, parses the DOM for all children matching form elements (detected by type)
 * and validates these elements. 
 * 
 * RETURNS	true 	: if it passes all validation checks
 * 			false	: if it fails any validation checks
 * 			
 * */

function validateForm(form) {
  
  // assume that the form input is fine until proven otherwise
   var validationResult = true;
  
    //return an array of form elements
    var obj = getElementsByType('text,password,select-one,select-multiple,radio,textarea,checkbox',form);
    var radioGroups = new Array();
    
    if (obj) {

      for (var i=0;i<obj.length;i++) {

	// since radio buttons keep individual checked status, we need to interate through all radio buttons
	// from a single group to determine whether any of that group have been selected
	if (obj[i].type == "radio") {
	  if (!radioGroups[obj[i].name]) radioGroups[obj[i].name] = false;
	  if (obj[i].checked) radioGroups[obj[i].name] = true;
	} else {
	  if (!validateField(obj[i])) validationResult = false;
	} // if it's not a radio button - check it for validity
	
      }
      
      // parse the completed radio group list to display messages
      for (var radioGroup in radioGroups)
      {
		  // all radio groups are required fields!! :)
		 if (!radioGroups[radioGroup]) validationResult = false;
		  var message= (radioGroups[radioGroup]) ? "" : requiredMsg;
		  showMessage(document.getElementById(radioGroup),message);
      }

    }
    
    return validationResult;
    
}


/** FUNCTION validateThenSubmit
 *
 * SUMMARY given an element, valides the child form elements through validateForm and then submits the form
 * 
 * RETURNS	true 	: if it passes all validation checks
 * 			false	: if it fails any validation checks
 * 			
 * */

function validateThenSubmit(form)
{
   if (validateForm(form)) {
        form.submit();
        return true;
   } else {
    return false;
   }
}




validateThenAjax = function(form,div,url) {
  
  // if no URL is given, set it to post back
  //if (url === null) url = document.location.search;
  
   if (validateForm(form)) {
      var ajax = new Ajax.Updater(div, url , {onComplete:function(){ new Effect.Highlight(div);},asynchronous:true,evalScripts:true,parameters:Form.serialize(form)});
      return false;
   } else { return false; }
   
}


//Description: Search criteria is passed in, along with a list box to search for a Item. As search criteria is passed in, this function scans the list box for a matching option, it then selects the first match. If search criteria is empty then the function unselects all options. This works like the any help menu
//Precondition: field be a valued select box
//Postcondition: First match of the search criteria in 'field' is selected
function Find_Term(search,field)
{
	var pattern

	if (search.value == "") 
	{
		field.options.selectedIndex = -1;
		return;
	}
	//Use "i" to make search not case-sensitive
	pattern = new RegExp("^" + search.value, "i");

	for(var x=0; x < field.options.length; x++)
	{
		
		if (pattern.test(field.options[x].text) == true)
		{
			
			field.options[x].selected = true
			break;
			
		}
	}

}




