/*
Naehas validation logic is based on JavaScript from: 
Apache Commons Validator Framework 
This code has been modified. 
See http://jakarta.apache.org/commons/validator/ for the original source.
*/
naehas = {
	validate: function() {	
		var errors = new Array();
		var forms = document.forms;
		validateFields(naehas.requiredFields, naehas.validateRequired, errors, " is required.");
		validateFields(naehas.emailFields, naehas.validateEmail, errors, " is not a valid email address.");
		validateFields(naehas.phoneFields, naehas.validatePhone, errors, " is not a valid phone number.");	
		if(errors.length > 0) {
			errors.reverse(); // errors.push() put in reverse order of form inputs
			alert(errors.join('\n'));
			return false;
		} 
		else return true;
		
		function validateFields(fields, validator, errors, errorSuffix) {
			if(fields) {
				for(var i=0; i<fields.length; i++) {
					var fInfo = fields[i];
					var name = fInfo.name.toLowerCase();
					var label = fInfo.label;
					for(var j=0; j<forms.length; j++) {
						var form = forms[j];
						for(var k=0; k<form.length; k++) {
							var field = form.elements[k];
							if(field.name.toLowerCase() == name) {
								if(!validator(field)) {
									errors.push("'" + label + "'" + errorSuffix);
								}	
							}
						}						
					}				
				}
			}
		}
	},
    
    validatePhone: function(field) {
    	if (field.type == 'hidden' || 
            field.type == 'text' ||
            field.type == 'textarea') {
    
        	var phoneStr = field.value;
       		if (phoneStr.length == 0) {
           		return true;
       		}
       		phoneStr = naehas.trim(phoneStr);
       		var digitCount = 0;
			var specialChars = /^(\+|\(|\)|\.|-|\s)$/; // +().- whitespace
			var digitPat=/^\d$/;
			for(var i=0; i<phoneStr.length; i++) {
    			var c = phoneStr.charAt(i);
    			if(digitPat.test(c)) {
					digitCount++;
				} else if(!specialChars.test(c)) {
					return false;
				}    
       		}
       		if(digitCount < 10) {
       			return false;
       		}   
        }
        return true;
    },

/* The source for functions below are licensed to the Apache Software
 * Foundation (ASF) under one or more contributor license agreements.  
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *    http://www.apache.org/licenses/LICENSE-2.0
 */
	validateRequired: function(field) {
	
		var isValid = true;
        
		if (!naehas.isFieldPresent(field)) {
        	isValid = false;
        } 
        else if ((field.type == 'hidden' ||
			field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'file' ||
            field.type == 'radio' ||
            field.type == 'checkbox' ||
            field.type == 'select-one' ||
            field.type == 'password')) {

            var value = '';
            // get field's value
            if (field.type == "select-one") {
                var si = field.selectedIndex;
                if (si >= 0) {
                    value = field.options[si].value;
                }
            } 
            else if (field.type == 'radio' || field.type == 'checkbox') {
                if (field.checked) {
                    value = field.value;
                }
            } 
            else {
                value = field.value;
            }

            if (naehas.trim(value).length == 0) {
            	isValid = false;
            }
         } 
         else if (field.type == "select-multiple") { 
			var numOptions = field.options.length;
			lastSelected=-1;
			for(loop=numOptions-1;loop>=0;loop--) {
				if(field.options[loop].selected) {
					lastSelected = loop;
					value = field.options[loop].value;
					break;
				}
			}
			if(lastSelected < 0 || trim(value).length == 0) {
				isValid=false;
			}
         } 
         else if ((field.length > 0) && (field[0].type == 'radio' || field[0].type == 'checkbox')) {
			isChecked=-1;
			for (loop=0;loop < field.length;loop++) {
				if (field[loop].checked) {
					isChecked=loop;
					break; // only one needs to be checked
				}
			}
			if (isChecked < 0) {
				isValid=false;
			}  
        }
        return isValid;
	},	
	
	isFieldPresent: function (field) {
		var fieldPresent = true;
		if (field == null || (typeof field == 'undefined')) {
			fieldPresent = false;
		} else if (field.disabled) {
			fieldPresent = false;
		}
		return fieldPresent;
	},

    validateEmail: function(field) {
    	if (field.type == 'hidden' || 
            field.type == 'text' ||
            field.type == 'textarea') {
    
           	var emailStr = field.value;
			/**
     		  * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
     		  * http://javascript.internet.com
     		  */   
       		if (emailStr.length == 0) {
           		return true;
       		}        		
       		var checkTLD=0; // TLD checking (knownDoms) turned off by default - knownDoms list probably needs to be updated before enabling
	        var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	        var emailPat=/^(.+)@(.+)$/;
 	       	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    	  	var validChars="\[^\\s" + specialChars + "\]";
       		var quotedUser="(\"[^\"]*\")";
       		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
       		var atom=validChars + '+';
       		var word="(" + atom + "|" + quotedUser + ")";
       		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
       		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
       		var matchArray=emailStr.match(emailPat);
       		if (matchArray==null) {
           		return false;
       		}
       		var user=matchArray[1];
       		var domain=matchArray[2];
       		for (i=0; i<user.length; i++) {
           		if (user.charCodeAt(i)>127) {
               		return false;
           		}
       		}
       		for (i=0; i<domain.length; i++) {
           		if (domain.charCodeAt(i)>127) {
               		return false;
           		}
       		}
       		if (user.match(userPat)==null) {
           		return false;
       		}
       		var IPArray=domain.match(ipDomainPat);
       		if (IPArray!=null) {
           		for (var i=1;i<=4;i++) {
               		if (IPArray[i]>255) {
                   		return false;
               		}
           		}
           		return true;
       		}
    	 	var atomPat=new RegExp("^" + atom + "$");
       		var domArr=domain.split(".");
       		var len=domArr.length;
       		for (i=0;i<len;i++) {
          		if (domArr[i].search(atomPat)==-1) {
               		return false;
           		}
       		}
       		if (checkTLD && domArr[domArr.length-1].length!=2 && 
           		domArr[domArr.length-1].search(knownDomsPat)==-1) {
           		return false;
       		}
       		if (len<2) {
           		return false;
       		}
       		return true;
        }
        return true;
    },
  
	trim: function(s) {
		return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
	}
}