//=====================  Form Validation  ===========================
//
//   Brett Graf
//   version 1: 16/10/2002
//
//    Validate all required fields.
//    Generate a single windows that contains a list of all errors.
//    If no error occurs, then return true and proceed to the next page.
//
//    Assume:
//       FORM  name="form"  
//       When checking group values, each group member must be name="xxx".
//       Also, each MUST group have these hidden objects:
//               xxx_max  	- define total number of group members to check 
//               xxx_val 		- holds the group value.  Used later for processing form.
//
//	Usage:
//         	<SCRIPT SRC="/javascript/validateForm.js"></SCRIPT>
//		<SCRIPT LANGUAGE="JAVASCRIPT"></SCRIPT>
//  
//=============================================================


// message list
errors='';

//===============================  Email  ==========================

/**
 * Validate the form email address
 *
 * param		name 	- name of form object
 *
 * returns		 		- adds message to error list if an error occurs
*/
//validateEmail
function validateEmail(name) 
{ 
      var val,p;
      var txt = ' must contain a valid e-mail address.\n';

      if (document.form[name])   // item exists
      {  
         if(document.form[name].value.length < 1 || document.form[name].value == ' ') // blank value, quick exit  
		 {
                errors += '- '+ name + txt;                           
         }
         else  // check value
		 {
			val = document.form[name].value;
		    if (val.indexOf(' ') > -1) 
			{
				errors+='- '+ name +txt;
            }
            else 
			{
				p=val.indexOf('@');
                if (p<1 || p==(val.length-1)) 
					errors+='- '+ name +txt;                      
                else 
				{
                                suffix=val.indexOf('@');
                                domain=val.substring(suffix+1, val.length);
                                p=domain.indexOf('.');
                                if (p<1 || p==(domain.length-1)) 
								{
				                     errors+='- '+ name +txt;                           
                                }
                 } 
            }
         }
      }  
}
    
//=================== Single Text Items  =======================

/**
 *  Validate the form text.  Display the object name if an error occurs.
 *  Simple check to ensure length is greater > 1 and not blank.
 *
 *  param	 name 	- name of form object
 *
 *  returns	 		- adds message to error list if an error occurs
*/ 
 
function validateText(name)  
{        	
	if(document.form[name].value.length < 1 || document.form[name].value == ' ')  
		errors += '- '+ name  + '\n';
}

/**
 *  Validate the form text, and display the specified message if an error occurs.
 *  Simple check to ensure length is greater > 1 and not blank.
 *
 *  param 		name 	- name of form object
 *  param		text 		- text to display instead of form object name
 *
 *  returns				- adds message to error list if an error occurs
 */

function validateTextWithMsg(name, txt) 
{       
	if(document.form[name].value.length < 1 || document.form[name].value == ' ')  
		errors += '- '+ txt  + '\n';
}


//============================ Drop Down Lists =======================

/**
 *  Validate the drop down list
 *  Simple to check list item is not equal to "invalid" or "Invalid".
 *
 *  Requires:
 *	<OPTION value="invalid" SELECTED>Select One</OPTION> 
 *
 *  param 		selName 		- selected name
 *  param		text 		- text to display instead of form object name
 *
 *  returns			 		- adds message to error list if an error occurs
 */

function validateList(selName)
{ 
   var selObj = findObj(selName);
   if (selObj.options[selObj.selectedIndex].value == "invalid" || selObj.options[selObj.selectedIndex].value == "Invalid" ) {
      errors += '- '+ selName +'\n';
   }
}

//============================ Drop Down Lists =======================

/**
 *  Validate the drop down list, and display the specified message if an error occurs.
 *  Simple to check list item is not equal to "invalid" or "Invalid".
 *
 *  Requires:
 *	<OPTION value="invalid" SELECTED>Select One</OPTION> 
 *
 *  param 		selName 		- selected name
 *
 *  returns			 		- adds message to error list if an error occurs
 */
function validateTitleWithMsg(txt)
{ 
   if (document.form.titleID_.value == "-_Select..." ) {
      errors += '- '+ txt  + '\n';
   }
}

function validateListWithMsg(selName, txt)
{ 
   var selObj = findObj(selName);
   if (selObj.options[selObj.selectedIndex].value == "invalid" || selObj.options[selObj.selectedIndex].value == "Invalid" ) {
      errors += '- '+ txt  + '\n';
   }
}
function validateTermsWithMsg(txt)
{ 
   if (document.form.terms.checked == false) {
      errors += '- '+ txt  + '\n';
   }
}
// ====================== Groups Check: Multiple Items and Types ================

/**
 *  Verify at least one element in the group (radio, checkbox, text) is selected.
 *  Values are not retrieved.  Each item must have the same name.
 *   
 *  Requires: 
 * 	hidden form object = name_max
 * 	<INPUT type="hidden" name="name_max" value="2"> <!-- max value -->	      
 *
 *  param 		name 	- title of fields to check 
 *  param 		text 		- text to display in error message
 *
 *  returns 				- adds text message to error list if no item is selected
 */

function isGroupSelected(name,text) 
{
	// total number of group members
	max = name + "_max";
		
	// start at 1 for web developers
	for( i=0; i< document.form[max].value; i++ )   
	{   
		if (document.form[name][i].type == "radio" || document.form[name+i].type == "checkbox") 
		{	      
			if(document.form[name][i].checked)
				return true;
		}
		else if (document.form[name][i].type == "text") 
		{
			if(document.form[name][i].value.length > 0 && document.form[name][i].value != ' ') 
				return true;
		}            
	}

	return errors += '- ' + text + '\n';         
}
/**
 *  Verify at least one element in the group (radio, checkbox, text) is selected.
 *  Values are not retrieved.  Each item must have the same name.
 *   
 *  Requires: 
 * 	hidden form object = name_max
 * 	<INPUT type="hidden" name="name_max" value="2"> <!-- max value -->	      
 *
 *  param 		name 	- title of fields to check 
 *  param 		text 		- text to display in error message
 *
 *  returns 				- adds text message to error list if no item is selected
 */

function isDynamicGroupSelected(name, text) 
{
    // total number of group members
	max = name + "_max";
		
	// start at 1 for web developers
	for( i=0; i< document.form[max].value; i++ )   
	{   
		if (document.form[name+i].type == "radio" || document.form[name+i].type == "checkbox") 
		{	      
			if(document.form[name+i].checked)
				return true;
		}
		else if (document.form[name+i].type == "text") 
		{
			if(document.form[name+i].value.length > 0 && document.form[name+i].value != ' ') 
				return true;
		}            
	}

	return errors += '- ' + text + '\n';         
}

// ==================== Groups Retrieval: Multiple Items and Types ===================

/**
 *  Get the value of a group of items.  Store the value into the group value holder (name_val). 
 *  All objects must have the same name.  
 *
 *  Requires: 
 * 	hidden form object = name_max
 * 	   <INPUT type="hidden" name="name_max" value="2"> <!-- max value -->
 *
 * 	hidden form object = name_val
 * 	   <INPUT type="hidden" name="name_value" value=" "> <!-- value holder -->
 *
 *  param	 	name 	- title of group to check
 * 
 * returns 				- the holder object contains all the groups values as a single string. 
 */

function getGroupValue(name, text) 
{  
	//hold value
	holder = name + "_val";
   	holder.value = "";
   
   	// max value
	max = name + "_max";
	
	// has a group member been selected
	var valid = false;
	      
      	// start at 1 for web developers
	for( i=0; i< document.form[max].value; i++ )      
	{		
		// radio buttons & checkboxes
		if (document.form[name][i].type == "checkbox" || document.form[name][i].type == "radio") 
		{	      		      	
		      if(document.form[name][i].checked)
		      {	      
			      document.form[holder].value += document.form[name][i].value;
			      valid = true;			      
		      }
		}
		// text boxes
		else if (document.form[name][i].type == "text") 
		{
			if(document.form[name][i].value.length > 0 && document.form[name][i].value != ' ')
			{
				document.form[holder].value += document.form[name][i].value;
				valid = true;		
			}
		}		
	}

	// none selected, show error
	if (!valid) 
		return errors += '- ' + text + '\n';	
}

/**
 *  Get the value of a group of items.  Store the value into the group value holder (name_val). 
 *  All objects must have the same name.  
 *
 *  Requires: 
 * 	hidden form object = name_max
 * 	   <INPUT type="hidden" name="name_max" value="2"> <!-- max value -->
 *
 * 	hidden form object = name_val
 * 	   <INPUT type="hidden" name="name_value" value=" "> <!-- value holder -->
 *
 *  param	 	name 	- title of group to check
 * 
 * returns 				- the holder object contains all the groups values as a single string. 
 */

function getDynamicGroupValue(name, text) 
{  
	//hold value
	holder = name + "_val";
   	holder.value = "";
   
   	// max value
	max = name + "_max";
	
	// has a group member been selected
	var valid = false;
	      
      	// start at 1 for web developers
	for( i=0; i< document.form[max].value; i++ )      
	{		
		// radio buttons & checkboxes
		if (document.form[name+i].type == "radio" || document.form[name+i].type == "checkbox") 
		{	      		      	
		      if(document.form[name+i].checked)
		      {	      
			      document.form[holder].value += document.form[name+i].value;
			      valid = true;			      
		      }
		}
		// text boxes
		else if (document.form[name+i].type == "text") 
		{
			if(document.form[name+i].value.length > 0 && document.form[name+i].value != ' ')
			{
				document.form[holder].value += document.form[name+i].value;
				valid = true;		
			}
		}		
	}

	// none selected, show error
	if (!valid) 
		return errors += '- ' + text + '\n';	
}


//====================== get time =================================

/**
 * Set the current time into the specified form object.
 *  FIX: TODO
 *  param		name 	- form object name
 */

function setTime(name) 
{
   document.form[name].value = new Date();         
}

//=================== display errors ==================================

/**
  * display the errors list created from the validateForm and validateList functions
  *
  * returns 		true 		- if no error occurs
  *					false 	- if error list is not empty
  */

function displayErrors() 
{
	if (errors.length > 1) 
	{
		alert('The following field(s) are required:\n\n'+errors);		
		return false;
	}  
	else 
	{		
		return true;
	}      
}

/**
  * Clear the error list.  
  */

function clearErrors() 
{
	errors='';	 
}


//======================== UTILITY FUNCTIONS ===============================

/**
 * find the object
 * recursive call.
 */

function findObj(n, d) 
{ 
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) 
	{
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) 
		x=d.all[n]; 
	  
	for (i=0;!x&&i<d.forms.length;i++) 
			x=d.forms[i][n];
  
  	for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
		x=findObj(n,d.layers[i].document); 
		
	return x;
}

//=======   Test  =====

function test() 
{
	alert('test');	
}

function test2(val) 
{
	alert('test2: ' + val);	
}
function test3(name) 
{
	alert('test3: ' + document.form[name].value);	
}
//=======   double Input Check  =====

function validateDuplicate(initial,secondary,txt) {
if (document.form[initial].value !== document.form[secondary].value ) {
errors += '- '+ txt  + '\n';
}
}

/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

//============================ Dates =======================

/**
 *  Validate the date field
 *
 *
 *  param 		selName 	- selected name
 *  param		text 		- text to display instead of form object name
 *
 *  returns			 		- adds message to error list if an error occurs
 */

function validateDateWithMsg(name,txt) 
{    
    dtStr = document.form[name].value;
	
	if(dtStr.length != 10)  
       return errors += '- '+ txt  + '\n';

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	
	if (pos1==-1 || pos2==-1)		
		return errors += '- '+ 'The date format should be : mm/dd/yyyy' + '\n';
	
	if (strMonth.length<1 || month<1 || month>12)		
		return errors += '- '+ 'Please enter a valid month'  + '\n';
	
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
		return errors += '- '+ 'Please enter a valid day'  + '\n';
	
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear) 
		return errors += '- '+ 'Please enter a valid 4 digit year between' +minYear+' and '+maxYear  + '\n';
	
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false)
		return errors += '- '+ 'Please enter a valid date'  + '\n';		
}

/**
 *  Validate the date field if the length is not blank, else ignore
 *  If the length is greater than 0, pass to the other method to perform the error checking
 *
 *
 *  param 		selName 	- selected name
 *  param		text 		- text to display instead of form object name
 *
 *  returns			 		- adds message to error list if an error occurs
 */

function validateDateOptionalWithMsg(name,txt) 
{    
    dtStr = document.form[name].value;
	
	if(dtStr.length == 0) // blank, so ignore
       return true

	return validateDateWithMsg(name, txt);
}
//Check all checkboxes
function doCheckAll()
{
  with (document.form) {
    for (var i=0; i < elements.length; i++) {
        if (elements[i].type == 'checkbox' )
           elements[i].checked = true;
    }
  }
}

