////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// validate.js - simple Formvalidierung                                       //
// (c)    : 2001 SCS Telmedia [http://www.telemedia.ch]                       //
// Date   : 02/29/2001                                                        //
// Author : Simon Wunderlin [swunderlin@telemedia.ch]                         //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// DESCRITION:                                                                //
// a very simple form validation script.                                      //
// the script provides the following functionality:                           //
//                                                                            //
//  - validate required fields (error on empty textfields)                    //
//  - validate for integer value (used for swiss ZIP codes)                   //
//  - validate EMail adresses                                                 //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// Example:                                                                   //
//                                                                            //
// the script can actually be used anywhere in the form on any event. to      //
// give you a a jumpstart, below you will see some common examples:           //
//                                                                            //
// IMPORTANT:                                                                 //
// you will have to pass the result of this script back to the form or        //
// the form is submitted on error. to do this, always user 'return' before    //
// calling the script ... see below.                                          //
//                                                                            //
// 1) used in Formtag with the event: onSubmit                                //
// <form action="whatever.cgi" method="post"                                  //
//       onsubmit="return valid.check('Sirname=required')">                   //
//   <input type="Text" value="" name="Sirname"><br>                          //
//   <input type="Submit" value="GO">                                         //
// </form>                                                                    //
//                                                                            //
// 2) used in the submit Button with the event: onclick                       //
// <form action="whatever.cgi" method="post">                                 //
//   <input type="Text" value="" name="Sirname"><br>                          //
//   <input type="Submit" value="GO"                                          //
//          onClick="return valid.check('Sirname=required')">                 //
// </form>                                                                    //
//                                                                            //
// 3) used in the any form field with whatever event                          //
// <form action="whatever.cgi" method="post">                                 //
//   <input type="Text" value="" name="Sirname"                               //
//          onBlur="return valid.check('Sirname=required')"><br>              //
//   <input type="Submit" value="GO">                                         //
// </form>                                                                    //
//                                                                            //
// 4) same as 3, but not used in the 1st form ( forms[0] )                    //
// <form action="whatever.cgi" method="post">                                 //
//   <input type="Text" value="" name="Sirname"                               //
//          onBlur="return valid.check('Sirname=required', this.form)"><br>   //
//   <input type="Submit" value="GO">                                         //
// </form>                                                                    //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// USAGE:                                                                     //
// This script generates a new Object called 'valid'.                         //
//                                                                            //
// Methods:                                                                   //
// * void valid( options String [, form [Object] )                            //
//   This is the Main function, parameter 1 takes the arguments (formfields)  //
//   to process, 2nd parameter takes the formfield, if empty, forms[0] is     //
//   used                                                                     //
//                                                                            //
// * void req( o Object )                                                     //
//   checks if field's value is not empty                                     //
//                                                                            //
// * void plz( o Object )                                                     //
//   checks if field's value is an integer                                    //
//                                                                            //
// * void email( o Object )                                                   //
//   checks if the email is in the correct format (according to RFC),         //
//   this does not provide a 100% reliable check though!                      //
//                                                                            //
// * void alphanum( o Object )                                                //
//   checks if the value is alphanumeric.                                     //
//                                                                            //
// * bool result( void )                                                      //
//   throws an alert and returns fals on error, else returns true             //
//                                                                            //
// Properties:                                                                //
// * [string] res - internally used to store the result, do NOT Change!       //                                                   //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////
// Configuration                                                              //
////////////////////////////////////////////////////////////////////////////////
valid                       = new Object();
valid.messages              = new Array();
valid.messages["required"]  = "Darf nicht leer sein!";
valid.messages["integer"]   = "Muss einen Zahlenwert enthalte (keine sonderzeichen oder Buchstaben)!";
valid.messages["email1"]    = "Ungueltige EMailadresse!";
valid.messages["email2"]    = "Ist eine ungueltige EMailadresse!";
valid.messages["alphanum"]  = "Darf nur Alphanummerische Werte enthalten! [a-z, A-Z, 0-9, _]";


////////////////////////////////////////////////////////////////////////////////
// Prototype Functions                                                        //
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// startup. this is the startup function which is used in onSubmit
// [void] f_check( options [String] )
//
function f_check( opt, whichForm ) { 
	// if no form is specified, we use the first!
	if ( !whichForm )
		whichForm = document.forms[0];

	// strip spaces from argument list
	opt = __stripSpaces( opt );
	
	// new 1-dim array with all name=action pairs
	var myArgs = opt.split(',');

	// extract the filednames and actions which shall be performed
	// syntax is : field1=action,field2=action
	//
	// supported actions:
	// plz      - checks if it is an swiss ZIP value
	// requred  - checks if field is non empty
	for (i=0; myArgs[i]; i++) {

		// seperate name from action
		val = myArgs[i].split('=');

		// make sure the action is in lower case
		val[1] = val[1].toLowerCase();
		
		// check if field exists 
		if ( !whichForm.elements[val[0]] ) {
			// if the field does not exists. throw alert ... for debuggin reasons only!
			alert('Form-filed \'' + val[0] + '\' does NOT EXIST!\n\nCheck case of formfield name!' );
			continue;
		}
		
		// and now, do what have to be done ,)
		switch (val[1]){
			case 'req' : 
			case 'required' : 
				valid.req(whichForm.elements[val[0]] );
				break;
			
			case 'int' : 
			case 'integer' : 
			case 'plz' : 
				valid.plz( whichForm.elements[val[0]] );
				break;
			
			case 'email' : 
				valid.email( whichForm.elements[val[0]] );
				break;

			case 'alphanum' : 
			case 'alphanumeric' : 
				valid.alphanum( whichForm.elements[val[0]] );
				break;

			default : 
				alert('Unsupported Action : ' + val[1]);
				return false;
		}
	}

	return valid.result();
}


////////////////////////////////////////////////////////////////////////////////
// strip whitespace - removes all spaces from a string
// [String] __stripSpaces( string [String] )
//
function __stripSpaces( str ) {
	var newval = '';
	
	// loop over any character, when ' ' do not copy to return value,
	// simple eh ?
	for (i=0; i < str.length; i++) {
		if ( str.charAt(i) != ' ' ) {
			newval = newval + str.charAt(i);
		}
	}
	
	// give it back to mom
	return newval;
}


////////////////////////////////////////////////////////////////////////////////
// check if required field is non-empty
// [void] f_required( o [Form-Object] )
//
function f_required(o) {
	if ( o.type == 'text' && o.value == '' ) {
		valid.res = valid.res + " - "+o.name+' '+valid.messages["required"]+'\n';
	}
}


////////////////////////////////////////////////////////////////////////////////
// check if field value is an integer
// [void] f_integer( o [Form-Object] )
//
function f_integer(o) {

	myValue  = o.value.toString();
	myName   = o.name;

	// ASCII Char Codes
	// 0 = 48
	// 9 = 57 
	
	for ( ix=0; myValue.length > ix; ix++ ) {
		// characters whcih are not numbers are unwanted ... 
		if ( myValue.charCodeAt( ix ) < 48 ||
		     myValue.charCodeAt( ix ) > 57 ) {
			valid.res = valid.res + ' - ' + myName.toUpperCase()
				+ ' '+valid.messages["integer"]+'\n';
			// exit loop ... ok, this is a bit crude, but works ,)
			ix = myValue.length;
		}
	}
}


////////////////////////////////////////////////////////////////////////////////
// validate emailadress
// [void] __emailchecker( o [Form-Object] )
//
function f_emailchecker(o) {

	tha_email  = o.value.toString();
	myName   = o.name;

  var err = 0;
  // check existence of "@" and "."
	// @ must be in pos>3 of string!
  if (tha_email.indexOf("@") <= 1) { 
    err = 1;
  } else {
		var at_char = tha_email.indexOf("@");
	}
  
  if (tha_email.indexOf(".") == -1) {
    err = 2;
  } else {var dot_char = tha_email.indexOf(".");}
  
  // check position of "@"
  if (err == 0) {
    if ((dot_char-2) <= at_char) {
      err = 3;
    }
  }
  
  // check position of "."
  if (err == 0) {
    if ((tha_email.length-2) <= dot_char) {
      err = 4;
    }
  }
  if ( err != 0 ) {
		if ( __stripSpaces(tha_email) == '' ) 
			valid.res = valid.res + ' - '+ valid.messages["email1"] +'\n' ;
		else 
			valid.res = valid.res +' - \''+ tha_email +'\' '+ valid.messages["email2"] +'\n' ;
	}
}


////////////////////////////////////////////////////////////////////////////////
// check for alphanumeric characters
// [void] f_alphanum( o [Form-Object] )
//
function f_alphanum(o) {
	ix=0; v = o.value.toString();
	
	// Char Codes
	// _ = 95
	// 0 = 48, 9 = 57 
	// a = 97, z = 122
	// A = 65, Z = 90
	
	while ( v.length > ix) {
		found = false;
		if ( v.charCodeAt(ix) >= 48 && v.charCodeAt(ix) <= 57 ) found=true; // 0-9
		if ( v.charCodeAt(ix) >= 65 && v.charCodeAt(ix) <= 90)  found=true; // A-Z
		if ( v.charCodeAt(ix) >= 97 && v.charCodeAt(ix) <= 122) found=true; // a-z
		if ( v.charCodeAt(ix) == 95 ) found=true; // '_'
		
		//alert(found + ': '+ v.charCodeAt(ix) + ' : '+ v.charAt(ix));
		if (!found) {
			valid.res = valid.res + " - "+o.name+' '+valid.messages["alphanum"]+'\n';
			break; // done, exit loop
		}
		ix++;
	}

}


////////////////////////////////////////////////////////////////////////////////
// internal function to determin wehther we have to throw an alert
// [void] result( o [Form-Object] )
//
function __result() {
	if (valid.res != '') {
		alert(valid.res);
		valid.res = "";
		
		// return false to stop form submission
		return false;
	}
	
	// on true, the form will be submitted
	return true;
}


////////////////////////////////////////////////////////////////////////////////
// Create Object and assign dummy functions as methods                        //
////////////////////////////////////////////////////////////////////////////////

valid.req      = f_required;
valid.plz      = f_integer;
valid.check    = f_check;
valid.alphanum = f_alphanum;
valid.email    = f_emailchecker;
valid.result   = __result;
valid.res      = "";

// end validate.js


