/* Based on: Travis Beckham ::
http://www.squidfingers.com | http://www.podlob.com
Based on: Manzi Olivier :: http://www.imanzi.com/
Based on: jgw (jgwang@csua.berkeley.edu )/ */

function checkCapsLock( e ) 
{
	var myKeyCode=0;
	var myShiftKey=false;

	// Internet Explorer 4+
	if ( document.all ) 
	{
		myKeyCode=e.keyCode;
		myShiftKey=e.shiftKey;
	} // Netscape 4
	else if ( document.layers ) 
	{
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;
	} // Netscape 6
	else if ( document.getElementById ) 
	{
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;
	}

	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) 
	{
		alert( errormsg[100] );
	} // Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on 
	else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) 
	{
		alert( errormsg[100] );
	}
}


function CalcKeyCode(aChar)
{
	var character = aChar.substring(0,1);
	var code = aChar.charCodeAt(0);
	return code;
}


function checkNumber(val) 
{
	var strPass = val.value;
	var strLength = strPass.length;
	var lchar = val.value.charAt((strLength) - 1);
	var cCode = CalcKeyCode(lchar);


	/* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */

	if (cCode < 48 || cCode > 57 ) 
	{
    	var myNumber = val.value.substring(0, (strLength) - 1);
    	val.value = myNumber;
  	}
  	return false;
}

// returns true if the string is empty
function isEmpty(str)
{
	return (str == null) || (str.length == 0);
}

// returns true if the string is a valid email
function isEmail(str)
{
 	if(isEmpty(str)) 
 		return false;
	
 	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
  
 	return re.test(str);
}

// returns true if the string only contains characters A-Z or a-z
function isAlpha(str)
{
	var re = /[^a-zA-Z]/g
	if (re.test(str)) 
		return false;
  
	return true;
}

// returns true if the string only contains characters 0-9
function isNumeric(str)
{
	var re = /[\D]/g
	if (re.test(str)) 
		return false;
  
	return true;
}

// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str)
{
	var re = /[^a-zA-Z0-9]/g
	if (re.test(str)) 
		return false;
  
	return true;
}

// returns true if the string's length equals "len"
function isLength(str, len)
{
	return str.length == len;
}

// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max)
{
	return (str.length >= min)&&(str.length <= max);
}

// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(str)
{
	var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
  
	return re.test(str);
}

// returns true if the string is a US zip code formatted as...
// 00000, 00000-0000
function isZip(str)
{
	var re = /^\d{5}([\-]\d{4})?$/
  
	return re.test(str);
}

// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
function isDate(str)
{
	var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/
	if (!re.test(str)) 
		return false;
  
	var result = str.match(re);
  	var y = parseInt(result[3]);
 	var m = parseInt(result[1],10);
  	var d = parseInt(result[2],10);
  	if(m < 1 || m > 12 || y < 1900 || y > 2100) 
  		return false;
  	
  	if(m == 2)
  	{
    	var days = ((y % 4) == 0) ? 29 : 28;
  	}
  	else if(m == 4 || m == 6 || m == 9 || m == 11)
  	{
     	var days = 30;
  	}
  	else
  	{
    	var days = 31;
  	}
  
  	return (d >= 1 && d <= days);
}

// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2)
{
	return str1 == str2;
}

// returns true if "str1" is the same as the value of "id2"
function isFieldMatch(str1, id2)
{
	var other = document.getElementById(id2);
  
	return str1 == other.value;
}

// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
// NOT USED IN FORM VALIDATION
function isWhitespace(str)
{
	var re = /[\S]/g
	if (re.test(str)) 
		return false;
  
	return true;
}

// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
// NOT USED IN FORM VALIDATION
function stripWhitespace(str, replacement)
{
	if (replacement == null) 
		replacement = '';
  
	var result = str;
	var re = /\s/g
	if(str.search(re) != -1)
	{
    	result = str.replace(re, replacement);
 	}
 	
  	return result;
}

function hasValue(t, v)
{
	switch(t)
	{
		case 'text':
		case 'password':
		case 'textarea':
		case 'file':
		{
			return ((v.length != 0) ? true : false);
		}
		break;
		default:
		{
			if(t.indexOf('select') != -1)
			{
				return ((v == "0" ||  v == 0) ? false : true);
			}
			
			// unevaluated types - considered value-less
			return false;
		}
	}
}

// returns nulls if url is valid else the error message
function isURL(urlStr)
{
	if (urlStr.indexOf(" ")!=-1)
	{
		return "Spaces are not allowed in a URL";
	}
	
	urlStr=urlStr.toLowerCase();
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var atom=validChars + '+';
	var urlPat=/^http:\/\/(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
	var matchArray=urlStr.match(urlPat);
	
	if (matchArray==null)
	{
		return "The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s";
	}
	
	var user=matchArray[2];
	var domain=matchArray[3];
	
	for (i=0; i<user.length; i++) 
	{
		if (user.charCodeAt(i)>127) 
		{
			return "This domain contains invalid characters.";
		}
	}
	
	for (i=0; i<domain.length; i++) 
	{
		if (domain.charCodeAt(i)>127) 
		{
			return "This domain name contains invalid characters.";
		}
	}
	
	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 "The domain name does not seem to be valid.";
		}
	}
	/**
	if (domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) 
	{
		return "The address must end in a well-known domain or two letter " + "country.";
	}
	**/
	return "";
}

// validate the form
function validateForm(f, preCheck, newClass, alerttype)
{
	// djs : added apre (alpha pre)/pre and apost/post 
	var apre  = 'Validation Error Detected\n' +
		  '------------------------------------\t\n';
	var apost = '------------------------------------\t\n' +
		  'Please re-enter and submit again.';
	
	var pre   = '<h2>Validation Error Detected</h2>' +
			  '<table class="errors" align="center" cellpadding="0" cellspacing="0">';
	var post  = '</table>' +
			  '<h3>Please re-enter and submit again.</h3>';
	
	var postField = ":\t";
	
	var errors  = '';
	var errorsa = '';
  
	// djs : set defaults
	if(newClass  == null) 
		newClass  = 'required';
	
	if(alerttype == null) 
		alerttype = 2;
	
	// djs : set defaults
	if(preCheck != null) 
		errors += preCheck;
	
	var i,e,t,n,v,y,o;

  	for(i=0, y=0; i < f.elements.length; i++)
  	{
            e = f.elements[i];
            v = e.value;		// djs: set v here
            t = e.type;
            o = ((e.optional == null || e.optional == 'undefined') ? false : e.optional);

            // djs: skip if optional unless there's a value
            if(o && !(hasValue(t, v))) 
                    continue;

            // djs : don't choke on <fieldset> and <legend> tags
            var tn = e.tagName.toLowerCase();
            if(tn == "fieldset" || tn == "legend") 
                    continue;
        
            if(e.disabled) 
                    continue;
            // djs : end
        
            if(e.errLabel != null && e.errLabel != "undefined")
            {
                n = e.errLabel + postField;
            }
            else
            {
                n = e.id + postField;
            }

            //  v = e.value;
            if(t == 'text' || t == 'password' || t == 'textarea')
            {
                if(isEmpty(v))
                {
                    errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[1] + '</td></tr>';
                    errorsa += n+errormsg[1]+'\n';
                    e.className=newClass;
                    continue;
                }
                else 
                {
                    e.className='checkit';
                }

                /** 
                if(v == e.defaultValue)
                {
                        errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[2]+ '</td></tr>';
                        errorsa += n+errormsg[2]+'\n';
                        e.className=newClass;
                        continue;
                }
                else 
                {
                        e.className='checkit';
                } 
                **/

                if(e.isAlpha)
                {
                    if(!isAlpha(v))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[3]+ '</td></tr>';
                            errorsa += n+errormsg[3]+'\n';
                            overlib('eaaaa');
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isNumeric)
                {
                    if(!isNumeric(v))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[4]+ '</td></tr>';
                            errorsa += n+errormsg[4]+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isAlphaNumeric)
                {
                    if(!isAlphaNumeric(v))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[5]+ '</td></tr>';
                            errorsa += n+errormsg[5]+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isEmail)
                {
                    if(!isEmail(v))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + v + '</td><td>' + errormsg[6]+ '</td></tr>';
                            errorsa += n+errormsg[6]+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isLength != null)
                {
                    var len = e.isLength;
                    if(!isLength(v,len))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[7]+ len + '</td></tr>';
                            errorsa += n+errormsg[7]+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isLengthBetween != null)
                {
                    var min = e.isLengthBetween[0];
                    var max = e.isLengthBetween[1];
                    if(!isLengthBetween(v,min,max))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[8] + min + '-' + max + '</td></tr>';
                            errorsa += n+errormsg[8] + min + '-' + max + '\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isPhoneNumber)
                {
                    if(!isPhoneNumber(v))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + v + '</td><td>' + errormsg[9]+ '</td></tr>';
                            errorsa += n+errormsg[9]+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isZip)
                {
                    if(!isZip(v))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + v + '</td><td>' + errormsg[15] + '</td></tr>';
                            errorsa += n + errormsg[15] + '\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isDate)
                {
                    if(!isDate(v))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + v + '</td><td>' + errormsg[10]+ '</td></tr>';
                            errorsa += n+errormsg[10]+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isURL)
                {
                    // djs ; just run the check function once instead of 3 times
                    var resURL = isURL(v);
                    if(resURL != "")
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + v + '</td><td>' + resURL + '</td></tr>';
                            errorsa += n + resURL + '\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isMatch != null)
                {
                    if(!isMatch(v, e.isMatch))
                    {
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[11]+ '</td></tr>';
                            errorsa += n+errormsg[11]+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }

                if(e.isFieldMatch != null)
                {
                    if(!isFieldMatch(v, e.isFieldMatch))
                    {
                            var other = document.getElementById(e.isFieldMatch);
                            var fmerror = errormsg[14].replace('{1}', n);
                            fmerror = fmerror.replace('{0}', other.errLabel);
                            errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + fmerror + '</td></tr>';
                            errorsa += n+fmerror+'\n';
                            e.className=newClass;
                            continue;
                    }
                    else 
                    {
                            e.className='checkit';
                    }
                }
            } // if for text | password | textarea end
    
	    if(t.indexOf('select') != -1)
	    {
	    	if(isEmpty(e.options[e.selectedIndex].value))
	    	{
		        errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[12]+ '</td></tr>';
		        errorsa += n+errormsg[12]+'\n';
		        e.className=newClass;
		        continue;
	      	}
	      	else 
	      	{
	        	e.className='checkit';
	      	}
	    }

	    if(t == 'select-one')
	    {
	    	if(e.options[e.selectedIndex].value <= 0)
	    	{
		        errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[12]+ '</td></tr>';
		        errorsa += n+errormsg[12]+'\n';
		        e.className=newClass;
		        continue;
	      	}
	      	else 
	      	{
	        	e.className='checkit';
	      	}
	    }
	    
	    if(t == 'file')
	    {
	    	if(isEmpty(v))
	    	{
		        errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[13]+ '</td></tr>';
		        errorsa += n+errormsg[13]+'\n';
		        e.className=newClass;
		        continue;
	      	}
	      	else 
	      	{
	        	e.className='checkit';
	      	}
	      	
	      	if(e.isLengthBetween != null)
	      	{
	      		var min = e.isLengthBetween[0];
	        	var max = e.isLengthBetween[1];
	        	if(!isLengthBetween(v,min,max))
	        	{
			        errors  += '<tr class="' + ((y++%2)?'odd':'even') + '"><td class="left">' + n + '</td><td>' + errormsg[8] + min + '-' + max + '</td></tr>';
			        errorsa += n+errormsg[8] + min + '-' + max + '\n';
			        e.className=newClass;
			        continue;
	      		}
	      		else 
	      		{
	        		e.className='checkit';
	      		}
	      	}
	    } 
 	}
  
	div = document.getElementById('errordiv');
	if(errors != '') 
	{
		if(alerttype == '2' || alerttype == '3') 
		{
			errorsa  = apre + errorsa;
			errorsa += apost;
			errors   = pre + errors;
			errors  += post;
			//    alert(errorsa);
			Dialog.alert(errors, {windowParameters: {width:320, className: "alphacube"}})
		}
		
		if(alerttype == '1' || alerttype == '3') 
		{
			return dispErr(errors, div);
		}
	}
  
	// djs : next line -- test before using div object
	if(div != "undefined" && div != null)
		div.style.display="none";

	return errors == '';
}

dispErr = function(error, divo) 
{
	divo.style.display="block";
	divo.innerHTML = error;
	return false;
}


/*
The following elements are not validated...

button   type="button"
checkbox type="checkbox"
hidden   type="hidden"
radio    type="radio"
reset    type="reset"
submit   type="submit"

All elements are assumed required and will only be validated for an
empty value or defaultValue unless specified by the following properties.

isEmail = true;          // valid email address
isAlpha = true;          // A-Z a-z characters only
isNumeric = true;        // 0-9 characters only
isAlphaNumeric = true;   // A-Z a-z 0-9 characters only
isLength = number;       // must be exact length
isLengthBetween = array; // [lowNumber, highNumber] must be between lowNumber and highNumber
isPhoneNumber = true;    // valid phone number. See "isPhoneNumber()" comments for the formatting rules
isZip = true;			 // djs: added - valid zip code
isDate = true;           // valid date. See "isDate()" comments for the formatting rules
isURL = true;			 // valid URL construction. See "isURL()".
isMatch = string;        // must match string
optional = true;         // element will not be validated

alerttype = 0            // no error msg
alerttype = 1            // error msg in div
alerttype = 2            // error msg in alert
alerttype = 3            // error msg in div and alert
*/

//============================

// error msg depends on the language
var errormsg = new Array();
errormsg[0]   = ' Select at least one checkbox!';
errormsg[1]   = ' cannot be empty!';
errormsg[2]   = ' cannot use the default value!';
errormsg[3]   = ' can only contain characters A-Z a-z!';
errormsg[4]   = ' can only contain characters 0-9!';
errormsg[5]   = ' can only contain characters A-Z a-z 0-9!';
errormsg[6]   = ' is not a valid email!';
errormsg[7]   = ' character number must be less than ';
errormsg[8]   = ' number of characters must be between ';
errormsg[9]   = ' is not a valid US phone number!';
errormsg[10]  = ' is not a valid date!';
errormsg[11]  = ' does not match!';
errormsg[12]  = ' needs an option selected!';
errormsg[13]  = ' needs a file to upload!';
errormsg[14]  = ' Fields "{0}" and "{1}" don\'t match!';
errormsg[15]  = ' is not a valid US zip code!';
errormsg[16]  = ' File name should be between zero and 64 characters!';
errormsg[99]  = ' All form information will be erased!';
errormsg[100] = ' Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

