//
 function test() { //v3.0
   alert('onload success');
}

//Add the getFullYear function to the Date class
Date.prototype.getFullYear = function() {
	var year = this.getYear();
	if( year < 1000 ) year += 1900;
	return year;
}
// Today's date
var Today = new Date();
  
//Here validation functions are 'defined' in tests
// each definitiion consists of setting a name in tests and assigning a function object to it
var tests = new Object();
tests["lt"] = function(lval,rval) { return lval < rval; };
tests["gt"] = function(lval,rval) { return lval > rval; };
tests["ne"] = function(lval,rval) { return lval != rval; };
tests["eq"] = function(lval,rval) { return lval == rval; };
tests["match"] = function(lval,rval) { 
                              if (lval.match(rval)) {  
                              	return true;
                              } 
                              return false;
};
tests["nomatch"] = function(lval,rval) { return !(tests["match"](lval,rval)); };
tests["sqldate_gt"] = function(lval,rval) {
	//this test is a little different than the others.
	// lval should be a string representation of a date
	// rval is a number if years to be greater than
	
	var ldate = valid_SQLDate(lval);
	
	if( ldate ) {
		ldate.setYear(ldate.getFullYear() + rval);
		
		if (ldate.getTime() < Today.getTime()) return true;
	}
	
	return false;
};
//Here error messages for the user are set.  There should be one defined
// for each test so that a meaningful message can be presented to the user
var message = new Object();
message["lt"] = "Please type an entry that is less than '";
message["gt"] ="Please type an entry that is greater than '";
message["ne"] = "Please type an entry that is not equal to '";
message["eq"] = "Nope, that's not it. Try again. '";
message["match"] = "Sorry but the value you typed for that field appears to be in incorrect format";
message["nomatch"] = "Please type an entry that is not like '";
message["sqldate_gt"] = "Date entered is invalid in this context '";
message["default"] = "Invalid entry for field";// might as well have a default just in case

// this will hold the messages displayed to the user when form validation detects bad/missing
// input for forms
var formInvalidMessages = new Object();

// Function : validate
// Purpose : validate a form field according to the test array passed
//                  as second parameter
// Parameters: forField = the field to validate ( i.e. test )
//                      test_array = an array of test names to execute and the
//                                           values to test forField against
function validate(formField,test_array) {
    
    var result = true;
    var failed_test;
	
	// loop through the array of tests, find the name of the 'test' object
	//  defined above, and then call with the first arg being the form field
	//  and the second the value to test against.
	//  each element of test_array contain pairs:
	//           name - the name of the function to execute ( in double quotes )
	//           value - the value to test the form field against
	// this is not unlike an array of function pointers in C/C++ or Mothod objects
	// in Java
    for( var i = 0; i < test_array.length; ++i ) {
        result = result && tests[test_array[i].name](formField.value,test_array[i].value);
        if( !result ) {
            failed_test = i;
            break;
        }
    }

    if ( !result)
    {
        if(message[test_array[i].name] == null ) {
            alert(message["default"]);// just in case a message for the test is not defined
        } else {
                 if (test_array[i].name == "match")
                   {
                     alert(message[test_array[i].name]);
                   }
                 else
                   {
                    alert(message[test_array[i].name] + test_array[i].value + "'");
                   }
              }
        formField.focus();
        result = false;
    }
	
    return result;
}

function validate_onSubmit(form) {
	var result = true;
	var temp = "";
	var element,element_name,e_type;
	
	// assume submitted form values ARE valid
	formInvalid = false;
	var messages = new Array();
	
	for ( element_name in form ) {
		
		//just in case wrap getting the element in a try/catch block.  
		//  it can fail and throw an exception
		try {
			element = form[element_name];
		} catch ( exception ) {
			//alert("Couldn't get element for name " + elemment_name);
		}
    		
    		var msg_name = element_name.replace(/\s/g,'_');
    		msg_name = msg_name.replace(/\W/g,'\$');
    		
    		//alert(msg_name);
    		//element might not have type defined ( it could happen )
    		// so try to get the type in a try/catch block
    		try {
    			e_type = element.type;
    		} catch ( exception ) {
    			continue;
    		}
    		
    		if( e_type == "hidden" ) continue;
    		//right now it seems radio buttons have a type of 'void' in some browsers
    		// this catches that situation
    		//if( e_type === void 0 ) e_type = "radio";
    		if( e_type === void 0 ) continue;//not going to even try undefined elements
    		
    		switch ( e_type) {
    			case "hidden" : break;
    			case "button" : break;
    			//case "checkbox" : break;
    			case "file" : break;
    			case "password" : break;
    			/*case "radio" : 
    					if( __radioInvalid(element) ) {
    						formInvalid = true;
    						try{
    							messages.push( self.window.formInvalidMessages[element_name] );
    						} catch(exception) {
    							messages.push( "a radio button selection was not made.");
    						}
    					}
    					break;
    			*/
    			case "reset" : break;
    			case "text" : ;
    			case "textarea" : ;
    			case "select-multiple" : ;
    			case "select-one" :
    					if( element.value == "" ) { 
    						
    						try{
    							if( self.window.formInvalidMessages[msg_name] != null ) { //make sure a message is actually defined
    								messages.push( self.window.formInvalidMessages[msg_name] );
    								formInvalid = true;
    							}
    						} catch(exception) {
    							messages.push( "a required selection or entry was not made.");
    						}
    					}
    					break;
    			case "submit" : break;
    			default : break;
    		}

	}
	if( formInvalid ) {
		var message = "The Form could not be submitted due to the follow problems :\n";
		for( var iter = 0; iter < messages.length; ++iter ) {
			message += "        " + messages[iter] + "\n";
		}
		alert(message);
		return false;
	} else {
		//alert("Form is valid");
		form.submit();
		return true;
	}
}

// dollarValue() - formats a value as a dollar amount.  
//                         code grabbed off the web.
function dollarValue(n) {
  var Bstr = "";
  var b = n * 100;
  var c = Math.round(b);
  var Astr = c.toString();
  var Alength = Astr.length;
  if (Alength <= 2) Bstr = Bstr + ".";
  var dot = Alength - 3;
  var counter = 0;
    while (counter < Alength ){
      Bstr = Bstr + Astr.charAt(counter);
      if (counter == dot) Bstr = Bstr + ".";
      counter = counter + 1;
    }
  var d = Bstr;
  return d;
}

// add() - takes the value from a form input field ( only support by checkbox right now )
//             and adds/subtracts it from the forms 'total' field
function add(formField) {

    var result = new Number();

    if( formField.checked ) {
        result = parseFloat(formField.form.total.value) + parseFloat(formField.value);
    } else {
        result = parseFloat(formField.form.total.value) - parseFloat(formField.value);
    }
    if( (result <= 0) || isNaN(result)) {
		formField.form.total.value = 0.0;
    } else {
    	formField.form.total.value = dollarValue(result);
    }
}

//Function: valid_SQLDate( dateString )
//Purpose: test if a string is in the form of a valid
//                date in the form YYYY-MM-DD
//Return: Date object
function valid_SQLDate( dateString ) {
	var DateAsArray = dateString.match(/^(\d{4})\-(\d{1,2})\-(\d{1,2})$/);
	
	if( DateAsArray ) {
		//check that 2nd and 3rd entries are valid numbers
		 if (Number(DateAsArray[2]) && Number(DateAsArray[3]))
      return new Date(DateAsArray[1], DateAsArray[2] - 1, DateAsArray[3]);
	}
	
	return DateAsArray; //if we get here DateAsArray is null
}

//Function: valid_USDate( dateString )
//Purpose: test if a string is in the form of a valid
//                date in the form MM-DD-YYYY
//Return: Date object
function valid_USDate( dateString ) {
	var DateAsArray = dateString.match(/^(\d{1,2})\-(\d{1,2})\-(\d{4})$/);
	
	if( DateAsArray ) {
		//check that 2nd and 3rd entries are valid numbers
		 if (Number(DateAsArray[2]) && Number(DateAsArray[3]))
      return new Date(DateAsArray[1], DateAsArray[2] - 1, DateAsArray[3]);
	}
	
	return DateAsArray; //if we get here DateAsArray is null
}
//Function: __radioInvalid( formRadioElementArray )
//Purpose:  check to make sure one of the radio buttons for the selection
//                was set
//NOTE: this isn't currently working due to differences in JavaScript
//            implementations.
function __radioInvalid( formRadioElementArray ) {
	
	//return false;
	var invalid = true;
	
	//right now it appear radio buttons type property
	// is set to void, which causes problems. so this
	// try/catch block check for a length property, which
	// all radio button sets have.  
	try {
		var temp = formRadioElementArray.length;
	} catch ( exception ) {
		return false;
	}
	
	for( var iter = 0; iter < formRadioElementArray.length; ++iter ) {
		try {
		 if( formRadioElementArray[iter].checked ) invalid = false;
		} catch ( exception ) {
			invalid = false;
		}
	}
	return invalid;
}

/****************************************************
 AntiSpambotMailto() - Documentation and encoder at:
    http://www.kenric.com/AntiSpambotMailto.html

Copyright (c) 2002 by Kenric L. Ashe - www.kenric.com - All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer. 

Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution. 

Neither the name of the Kenric.com nor the names of its contributors may 
be used to endorse or promote products derived from this software without 
specific prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/


function AntiSpambotMailto(codelist, description, atagattr) {
	var thiscode, thischar;
	var CodeString = new String(codelist);
	var CodedArray = CodeString.split('|');
	var L = CodedArray.length;
	var AddrDecoded = "";

	for (var x=0; x < L; x++) {
		thiscode = CodedArray[x];
		thischar = String.fromCharCode( thiscode - L );
		AddrDecoded += thischar;
	}
	atagattr = atagattr ? ' ' + atagattr : '';
	if (!description) description = AddrDecoded; // if no description supplied, display email address
	var strOutput = '<a href="mailto:'+AddrDecoded+'"' + atagattr+'>' + description + '</a>';
	document.write(strOutput);
}


