// Basic Functions
// ---------------
String.prototype.trim = function ()
{
	return this.replace(/^\s*|\s*$/g, "");
};

function StringBuffer ()
{
	this._strings_ = new Array;
	
	if (typeof this._initialized == "undefined")
	{
		StringBuffer.prototype.append = function (str)
		{
			this._strings_.push(str);
		};
		
		StringBuffer.prototype.toString = function ()
		{
			return this._strings_.join(" ");
		};
		
		StringBuffer.prototype.clear = function ()
		{
			return this._strings_.length = 0;
		};
		
		this._initialized = true;
	}
}

function printFire ()
{
   if (document.createEvent)
   {
      printfire.args =  arguments;
      var ev = document.createEvent("Events");
      ev.initEvent("printfire", false, true );
      dispatchEvent(ev);
   }
}

//
// CSS Functions
//

function formatForm ()
{
	var formInputs = getElementsByTagAndClassName('input', null, null);
	
	for (i=0; i<formInputs.length; i++) {
		var inputStyle = getNodeAttribute(formInputs[i], 'class');
					
		if (inputStyle != null)
			setElementClass(formInputs[i], formInputs[i].type + ' ' + inputStyle);
		else
			setElementClass(formInputs[i], formInputs[i].type);
	}
}

//
// DOM Functions
// 
function validate (myDOM)
{
	// Validate a DOM Object By
	// Toggling the "valid" style on the object
	
	// If the object was previously tagged
	// as invalid, remove the "invalid" tag
	removeElementClass(myDOM, "invalid");
	
	// If the object isn't already tagged
	// as valid, tag it valid
	if (!hasElementClass(myDOM, "valid"))
	{
		addElementClass(myDOM, "valid");
	}
	
	return;
}

function inValidate (myDOM)
{
	// Invalidate a DOM Object By
	// Toggling the "invalid" style on the object
	
	// If the object was previously tagged
	// as valid, remove the "valid" tag
	removeElementClass(myDOM, "valid");
	
	// If the object isn't already tagged
	// as invalid, tag it invalid
	if (!hasElementClass(myDOM, "invalid"))
	{
		addElementClass(myDOM, "invalid");
	}
	
	return;
}

function isValid (myDOM)
{
	if(hasElementClass(myDOM, "valid"))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function resetStatus (myDOM)
{
	if (hasElementClass(myDOM, "valid"))
		removeElementClass(myDOM, "valid");
			
	if(hasElementClass(myDOM, "invalid"))
		removeElementClass(myDOM, "invalid");
}

function setRequired (myDOM)
{
	// Require a DOM Object By
	// Toggling the "required" style on the object
	
	// If the object is already tagged
	// as required, do nothing
	if (!hasElementClass(myDOM, "required"))
	{
		addElementClass(myDOM, "required");
	}
		
	return;
}

function isRequired (myDOM)
{
	// Check whether a DOM Object is Required By
	// checking the "required" style on the object
	
	// If the object is already tagged
	// as required, do nothing
	return hasElementClass(myDOM, "required");
}

function setOptional (myDOM)
{
	// Make a DOM Object Optional By
	// Removing the "required" style from the object
	
	// If the object was previously tagged
	// as valid, remove the "valid" tag
	removeElementClass(myDOM, "required");
	
	return;
}

//
// Form Validation Functions
// -------------------------
var writeError = function (message)
{
	alert("Please correct the following error:\n" + message);
	
	return false;
};

function isBlankForm ()
{
	var formInputs = getElementsByTagAndClassName('input', null, $('main'));
	var isBlank = true;
	
	for (i=0; i<formInputs.length; i++)
	{
		var inputValue = formInputs[i].value.trim();
		
		if (formInputs[i].type == "text")
		{
			if (inputValue.length > 0)
				isBlank = false;
		}
		
		if (formInputs[i].type == "checkbox")
		{
			if (formInputs[i].checked == "checked" || formInputs[i].checked)
				isBlank = false;
		}
	}
	
	return isBlank;
}

function FormSnapshot ()
{
	this.items = new Array;
	
	if (typeof this._initialized == "undefined")
	{
		FormSnapshot.prototype.build = function ()
		{
			var formInputs = getElementsByTagAndClassName('input', null, $('main'));
			
			for (i=0; i<formInputs.length; i++)
			{
				switch (formInputs[i].type)
				{
					case "text":
						this.items.push(formInputs[i].value);
						break;
					
					case "checkbox":
						this.items.push(String(formInputs[i].checked));
						break;
					
					case "radio":
						this.items.push(String(formInputs[i].checked));
						break;
				}
			}
			
			var formSelects = getElementsByTagAndClassName('select', null, $('main'));
			
			for (i=0; i<formSelects.length; i++)
			{
				this.items.push(formSelects[i].value);
			}
		};
		
		FormSnapshot.prototype.compare = function ()
		{
			var formInputs = getElementsByTagAndClassName('input', null, $('main'));
			
			var compareSnapshot = new FormSnapshot();
			compareSnapshot.build();
			
			for (i=0; i<this.items.length; i++)
			{
				if (this.items[i] != compareSnapshot.items[i])
					return false;
			}
			
			return true;
		};
	}
};

// Simple - validates only the length of the entry
function Simple (entry)
{
	if (typeof entry == "undefined")
	{
		entry = "";
	}
	
	this.error = "";
	
	if (isNaN(entry))
	{
		this.input = entry.trim();
	}
	else
	{
		this.input = entry;
	}
	
	if (typeof this._initialized == "undefined")
	{
		Simple.prototype.valid = function ()
		{
			if (this.input.length > 1)
			{
				return true;
			}
			else
			{
				this.error = " is not a valid entry.";
				return false;
			}
		};
		
		this._initialized = true;
	}
}

// SimpleNumber - adds numerical validation to Simple
function SimpleNumber (entry)
{	
	this._root = new Simple (entry);
	this.input = this._root.input;
	
	if (typeof this._initialized == "undefined")
	{
		SimpleNumber.prototype.valid = function ()
		{
			if (this._root.valid)
			{
				var testPattern = /\D/g;
				return !testPattern.test(this.input);
			}
			else
			{
				return false;
			}
		};
		
		this._initialized = true;
	}
}

// Amount Field (OnlineForms) Validation
var AmountField = function (entry)
{
	this._root = new Simple (entry);
	this.input = this._root.input;
	this.error = "";
	
	if (typeof this._initialized == "undefined")
	{
		AmountField.prototype.valid = function ()
		{
			var regIllegals = /[^0-9,\.]+/g;
			var regCommas = /(,)/g;
			var regFormat = /^(\d{0,12})(\.{1}\d{0,4})?$/g;
			
			if (this.input.length < 1)
			{
				this.error = " cannot be blank.";
				return false;
			}
			
			if (regIllegals.test(this.input))
			{
				this.error = " contains illegal characters.";
				regIllegals = null;
				return false;
			}
			
			var testNumber = this.input.replace(regCommas, "");
			regCommas = null;
				
			if (!regFormat.test(testNumber))
			{
				this.error = " is not properly formatted.";
				regFormat = null;
				return false;
			}
			
			if (RegExp.$2.length < 2)
				testNumber = RegExp.$1;
			
			this.input = testNumber;
			regIllegals = null;
			regFormat = null;
			return true;
		};
	
		this._initialized = true;
	}
};

// PhoneNumber - adds specific phone number validation to SimpleNumber
function PhoneNumber (entry)
{
	this.input = entry.trim();
	this.delimeter = "-";
	this.error = "";
	
	if (typeof this._initialized == "undefined")
	{
		PhoneNumber.prototype._parsed = function ()
		{
			var parsedString = this.input.trim();
			
			parsedString = parsedString.replace(/[(\+]/g, "");
			parsedString = parsedString.replace(/[)-.]/g, " ");
			parsedString = parsedString.replace(/  /g, " ");
			
			return parsedString;
		};
		
		PhoneNumber.prototype.valid = function ()
		{
			var testString = new SimpleNumber(this._parsed().replace(/ /g, ""));
			
			if (testString.input.length > 9)
			{
				if (testString.valid())
					return true;
				else
				{
					this.error = " is not a valid phone number.";
					return false;
				}
			}
			else
			{
				this.error = " does not contain enough numbers to be a valid phone number.";
				return false;
			}
		};
		
		PhoneNumber.prototype.format = function ()
		{
			var formatString = this.parsed().replace(/ /g, this.delimeter);
			
			return formatString;
		};
		
		this._initialized = true;
	}
}

// EmailAddress - adds specific email validation to Simple
function EmailAddress (entry)
{
	this._root = new Simple (entry);
	this.input = this._root.input;
	this.error = "";
	
	if (typeof this._initialized == "undefined")
	{
		EmailAddress.prototype.valid = function ()
		{
			if (this._root.valid())
			{
				var emailFormat = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
				var result = emailFormat.test(this.input);
				
				emailFormat = null;
				
				if (result)
				{
					emailFormat = null;
					return true;
				}
				else
				{
					emailFormat = null;
					this.error = " is not a valid email address.";
					return false;
				}
			}
			else
			{
				this.error = " is not a valid email address.";
				return false;
			}
		};
		
		this._initialized = true;
	}
}

//WebAddress - adds specific URL validation to Simple
function WebAddress (entry)
{
	this._root = new Simple (entry);
	this.input = this._root.input;
	this.error = "";
	
	if (typeof this._initialized == "undefined")
	{
		EmailAddress.prototype.valid = function ()
		{
			if (this._root.valid())
			{
				var urlFormat = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
				var result = urlFormat.test(this.input);
				
				urlFormat = null;
				
				if (result)
					return true;
				else
				{
					this.error = " is not a valid web address (URL).";
					return false;
				}
			}
			else
			{
				this.error = " is not a valid web address (URL).";
				return false;
			}
		};
		
		this._initialized = true;
	}
}

//Datefield - adds specific date validation to Simple
function DateField (entry)
{
	this._root = new Simple (entry);
	this.input = this._root.input;
	this.error = "";
	
	if (typeof this._initialized == "undefined")
	{
		DateField.prototype.valid = function ()
		{
			if (this._root.valid())
			{
				var regFormat = /(0[1-9]|[1-9]{1}|1[0-2])\/(0[1-9]|[1-9]?|[12][0-9]|3[01])\/(190\d{1}|19\d{2}|200\d{1}|20\d{2}|0\d{1}|\d{2})$/g;
				var result = regFormat.test(this.input);
				
				regFormat = null;
				
				if (result)
					return true;
				else
				{
					this.error = " is not a valid date.";
					return false;
				}
			}
			else
			{
				this.error = " is not a valid date.";
				return false;
			}
		};
	
		this._initialized = true;
	}
};

// The FormEntry function defines the input entry in a form.
// The fieldEntry is the actual html input object, 
// the fieldType is a string defining the type of validation that
//	should be used on the entry
function FormEntry (fieldEntry, fieldType)
{
	if (typeof fieldType == "undefined")
	{
		this.type = "simple";
	}
	else
	{
		this.type = fieldType;
	}
	
	if (typeof fieldEntry == "undefined")
	{
		this.field = null;
		this.input = null;
	}
	else
	{
		this.field = fieldEntry;
		this.input = this.field.value;
	}
	
	this.required = false;
	this.error = "";
	
	if (typeof this._initialized == "undefined")
	{
		FormEntry.prototype.isRequired = function (required)
		{
			if (typeof required == "boolean")
			{
				this.required = required;
			}
			else
			{
				this.required = false;
			}
		}
	
		FormEntry.prototype.valid = function ()
		{
			var entryValidator;
			
			switch (this.type)
			{
				case "amount":
					entryValidator = new AmountField(this.input);
					break;
					
				case "phone":
					entryValidator = new PhoneNumber(this.input);
					break;
					
				case "email":
					entryValidator = new EmailAddress(this.input);
					break;
					
				case "url":
					entryValidator = new WebAddress(this.input);
					break;
					
				case "date":
					entryValidator = new DateField(this.input);
					break;
					
				default:
					entryValidator = new Simple(this.input);
			}
			
			if(entryValidator.valid())
				return true;
			else
			{
				this.error = this.name + entryValidator.error;
				return false;
			};
		};
		
		this._initialized = true;
	}
}


//
// Old Validation Functions
// -------------------------
	function PopUp (url) 
	{
		window.open (url, "popup", "width=800,height=600,screenX=50,screenY=50,left=50,right=50,resizable=no,status=no,toolbar=no,scrollbars=no");
	}
	
	function PopUp2 (url) 
	{
		window.open (url, "popup2", "width=640,height=480,screenX=50,screenY=50,left=50,right=50,resizable=no,status=no,toolbar=no,scrollbars=no");
	}

	function newImage(arg)
	{
		if (document.images)
		{
			rslt = new Image();
			rslt.src = arg;
			return rslt;
		}
	}

	function changeImages()
	{
		if (document.images && (preloadFlag == true))
		{
			for (var i=0; i<changeImages.arguments.length; i+=2)
			{
				document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
			}
		}
	}

	var preloadFlag = false;
	
	function preloadImages()
	{
		if (document.images)
		{
			preloadFlag = true;
		}
	}

	function formatCurrency(num) 
	{
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)) num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10) cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
			
		return (((sign)?'':'-') + '$' + num + '.' + cents);
	}

	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++) {   
		    // Check that current character isn't whitespace.
		    var c = s.charAt(i);
		    if (bag.indexOf(c) == -1) returnString += c;}
		return returnString;
	}

	function emailCheck (emailStr) 
	{
		/* The following pattern is used to check if the entered e-mail address
		fits the user@domain format.  It also is used to separate the username
		from the domain. */
		var emailPat=/^(.+)@(.+)$/;
		/* The following string represents the pattern for matching all special
		characters.  We don't want to allow special characters in the address. 
		These characters include ( ) < > @ , ; : \ " . [ ]    */
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
		/* The following string represents the range of characters allowed in a 
		username or domainname.  It really states which chars aren't allowed. */
		var validChars="\[^\\s" + specialChars + "\]";
		/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. */
		var quotedUser="(\"[^\"]*\")";
		/* The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
		/* The following string represents an atom (basically a series of
		non-special characters.) */
		var atom=validChars + '+';
		/* The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.
		Basically, a word is either an atom or quoted string. */
		var word="(" + atom + "|" + quotedUser + ")";
		// The following pattern describes the structure of the user
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
		/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");


		/* Finally, let's start trying to figure out if the supplied address is
		valid. */

		/* Begin with the coarse pattern to simply break up user@domain into
		different pieces that are easy to analyze. */
		var matchArray=emailStr.match(emailPat);
		if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't
			even fit the general mould of a valid e-mail address. */
			alert("Email address seems incorrect (check @ and .'s)");
			return false;
		}
		
		var user=matchArray[1];
		var domain=matchArray[2];

		// See if "user" is valid 
		if (user.match(userPat)==null) {
			// user is not valid
			alert("The username doesn't seem to be valid.");
			return false;
		}

		/* if the e-mail address is at an IP address (as opposed to a symbolic
		host name) make sure the IP address is valid. */
		var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null) {
			// this is an IP address
			for (var i=1;i<=4;i++) 
			{
				if (IPArray[i]>255) 
				{
					alert("Destination IP address is invalid!");
					return false;
				}
			}
			return true;
		}

		// Domain is symbolic name
		var domainArray=domain.match(domainPat);
		if (domainArray==null) 
		{
			alert("The domain name doesn't seem to be valid.");
			return false;
		}

		/* domain name seems valid, but now make sure that it ends in a
		three-letter word (like com, edu, gov) or a two-letter word,
		representing country (uk, nl), and that there's a hostname preceding 
		the domain or country. */

		/* Now we need to break up the domain to get a count of how many atoms
		it consists of. */
		var atomPat=new RegExp(atom,"g");
		var domArr=domain.match(atomPat);
		var len=domArr.length;
		if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>4) 
		{
			// the address must end in a two letter or three letter word.
			alert("The address must end in a three-letter or four-letter domain, or two letter country.");
			return false;
		}

		// Make sure there's a host name preceding the domain.
		if (len<2) 
		{
			//var errStr="This address is missing a hostname!";
			alert(errStr);
			return false;
		}

		// If we've gotten this far, everything's valid!
		return true;
	}

	function SelectDropDownItem(argDD , argValue)
	{
		var nCount = argDD.length;
		for (var p = 0; p < nCount; p++)
		{
			if (argDD[p].value == argValue)
			{
				argDD[p].selected = true;
				break;
			}
		}
	}

function IsNumeric(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 IsValidDate(argValue)
{
	return true;
}

function IsValidCIK(argValue)
{
	//CIK – ten digits numeric only
	if (!IsNumeric(argValue)){ return false;}
	return true;
}

function IsValidSSN(argValue) {
	return (argValue.search(/^[0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9][0-9][0-9]$/) != -1);
}

function IsValidIRSTIN(argValue) {
	return (argValue.search(/^[0-9][0-9]\-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/) != -1);
}

function IsValidSECCode(argValue)
{
	//CCC, Password, PMAC, PassPhrase - 8 characters long and must contain at least one digit and one of the following characters: @, #, *, or $.
	var bRet1 = (argValue.indexOf("@") > -1) || (argValue.indexOf("#") > -1) ||  (argValue.indexOf("*") > -1) || (argValue.indexOf("$") > -1);

	var bRet2 = (argValue.indexOf("@") > -1) || (argValue.indexOf("#") > -1) ||  (argValue.indexOf("*") > -1) || (argValue.indexOf("$") > -1);
	bRet2 = bRet2 || (argValue.indexOf("0") > -1) || (argValue.indexOf("1") > -1) ||  (argValue.indexOf("2") > -1) || (argValue.indexOf("3") > -1);
	bRet2 = bRet2 || (argValue.indexOf("4") > -1) || (argValue.indexOf("5") > -1) ||  (argValue.indexOf("6") > -1) || (argValue.indexOf("7") > -1);
	bRet2 = bRet2 || (argValue.indexOf("8") > -1) || (argValue.indexOf("9") > -1);
	
	return bRet1 && bRet2;
}

//Credit Card Validation
function isValidCreditCard(type, ccnum)
{
   if (type == "Visa")
   {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } 
   else if (type == "MC")
   {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } 
   else if (type == "Disc")
   {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   }
   else if (type == "AmEx")
   {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   }
   else if (type == "Diners")
   {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)) return false;
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2)
   {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2)
   {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}
//End Credit Card Validation


function checkInternationalPhone(strPhone)
{
		
	//Phone Number Validation
		// Declaring required variables
		var digits = "0123456789";
		// non-digit characters which are allowed in phone numbers
		var phoneNumberDelimiters = "()-. ";
		// characters which are allowed in international phone numbers
		// (a leading + is OK)
		var validWorldPhoneChars = phoneNumberDelimiters + ".+";
		// Minimum no of digits in an international phone no.
		var minDigitsInIPhoneNumber = 10;
		
		s=stripCharsInBag(strPhone,validWorldPhoneChars);
		return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
		
}

function openHelpWindow(url,wSize,hSize){
	if(typeof(helpWindow) != "object"){
	//alert('typeof' + hSize);
		helpWindow = window.open(url,'helpWindow','width=' + wSize + ',height=' + hSize + ',menubar=no,scrollbars=yes,resizable=1');	
	}else{
		if(!helpWindow.closed){
			//alert('closedCheck' + hSize);
			helpWindow = window.open(url,'helpWindow','width=' + wSize + ',height=' + hSize + ',menubar=no,scrollbars=yes,resizable=1');	
		}else{
			//alert('third' + hSize);
			helpWindow = window.open(url,'helpWindow','width=' + wSize + ',height=' + hSize + ',menubar=no,scrollbars=yes,resizable=1');	
		}
	}
	helpWindow.focus();
}

function hasValue(myInput)
{
	// Check an Input object for a value
	if(myInput.value.length > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// CIK Validation Function
var checkCIK = function() {
	var reCIK = /\d{10}/; // CIK number format
	
	// Is the field either required or not empty?
	// If so, continue with checks
	if((hasElementClass(this, "required")) || (this.value.length > 0))
	{
		if(reCIK.test(this.value)) {
			validate(this);
		}
		else
		{
			inValidate(this);
		}
	}
	else
	{
		resetStatus(this);
	}
};

// CCC, Password, Passphrase Validation	
var checkCCC = function() {
	var reCCC = /[a-z0-9*@$#]{8}/; // General CCC format expression
	var reNum = /[0-9]+/; // Confirm at least one number expression
	var reSpecial = /[*@$#]+/; // Confirm at least one special character expression
	
	// Is the field either required or not empty?
	// If so, continue with checks
	if((hasElementClass(this, "required")) || (this.value.length > 0))
	{
		// Check that the CCC conforms with all the format rules
		if(reCCC.test(this.value) && reNum.test(this.value) && reSpecial.test(this.value))
		{
			validate(this);
		}
		else
		{
			inValidate(this);
		}
	}
	// If the field is optional and blank, remove any validation styles
	else
	{
		resetStatus(this);
	}
	
};

//IRS Number Validation	
var checkIRS = function() {
	var errors = 0;
	
	var reIRSwDash = /\d{2}\-{1}\d{7}/; // IRS Number format with dash
	var reIRSnoDash = /\d{9}/; // IRS Number format without dash
	var reIRS = /(\d{2})(\d{7})/; // IRS Number - Splitting
	
	// Is the field either required or not empty?
	// If so, continue with checks
	if((hasElementClass(this, "required")) || (this.value.length > 0))
	{
		
		if(!reIRSwDash.test(this.value) && this.value.length > 9)
			errors += 1;
			
		if(!reIRSnoDash.test(this.value) && this.value.length < 10)
			errors += 1;
		
		if(errors == 0) {
			validate(this);
			this.value = this.value.replace(reIRS, "$1-$2");	
		}
		else
		{
			inValidate(this);
		}
	}
	else
	{
		resetStatus(this);
	}
	
};

//Email Validation		
var checkEmail = function() {
	var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
	
	if((hasElementClass(this, "required")) || (this.value.length > 0))
	{
		if(reEmail.test(this.value))
		{
			validate(this);
		}
		else
		{
			inValidate(this);
		}
	}
	else
	{
		resetStatus(this);
	}
};

// Simple Check - Validates only that field isn't blank		
var checkSimple = function() {
	// Checks the field value length, looking for any content
	// If there is content, validate the field
	if(this.value.length > 0)
	{
		validate(this);
	}
	// If the field has no content,
	// check whether or not the field is required
	else
	{
		removeElementClass(this, "valid");
		
		// If the field is required and blank,
		// invalidate it.
		if(hasElementClass(this, "required"))
		{
			inValidate(this);
		}
		// If the field is not required and blank,
		// make sure it is neither invalidated nor validated.
		else
		{
			resetStatus(this);
		}
	}
};

//Phone Validation		
var checkPhone = function() {
	// Checks the field value length, looking for any content
	// If there is content, validate the field
	if((hasElementClass(this, "required")) || (this.value.length > 0))
	{
		// Use the pre-built function to validate the field
		if(checkInternationalPhone(this.value))
		{
			validate(this);
		}
		else
		{
			inValidate(this);
		}
	}
	else
	{
		resetStatus(this);
	}
};

function stripPhone(myString)
{
	var cleanString = myString.replace(/[(]/g, "");
	var cleanString = cleanString.replace(/[)]/g, "");
	var cleanString = cleanString.replace(/[-]/g, "");
	var cleanString = cleanString.replace(/[.]/g, "");
	
	return cleanString;
}

function parsePhone(myString)
{
	var cleanNumber = stripPhone(myString);
	var parseFormula = /(\d{3})(\d{3})(\d{4})/;
	var parsedPhone = cleanNumber.replace(parseFormula, "($1) $2 - $3");
	
	return parsedPhone;
}


var checkURL = function() {
	// Checks the field value length, looking for any content
	// If there is content, validate the field
	
	if((hasElementClass(this, "required")) || (this.value.length > 0))
	{
		var myURL = doSimpleXMLHttpRequest(this.value);
		
		myURL.addCallbacks(validate(this), inValidate(this));
	}
	else
	{
		resetStatus(this);
	}
};

var checkCountry = function() {
	if(hasElementClass(this, "required"))
	{
		if(this.value > 0)
		{
			validate(this);
		}
		else
		{
			inValidate(this);
		}
	}
	else
	{
		resetStatus(this);
	}
};

function addValidation(myDom) {
	// Check for validation types (set in class)
	// and add appropriate function calls
	
	// Check for simple class
	if(hasElementClass(myDom, "simple"))
	{
		connect(myDom, 'onblur', checkSimple);
		return;
	}
	
	// Check for 'CIK' class
	if(hasElementClass(myDom, "cik"))
	{
		connect(myDom, 'onblur', checkCIK);
		return;
	}
	
	// Check for 'CCC' class
	if(hasElementClass(myDom, "ccc"))
	{
		connect(myDom, 'onblur', checkCCC);
		return;
	}
		
	// Check for 'IRS #' class				
	if(hasElementClass(myDom, "irs"))
	{
		connect(myDom, 'onblur', checkIRS);
		return;
	}
	
	// Check for 'Email' class
	if(hasElementClass(myDom, "email"))
	{
		connect(myDom, 'onblur', checkEmail);
		return;
	}
	
	// Check for 'Phone' class
	if(hasElementClass(myDom, "phone"))
	{
		connect(myDom, 'onblur', checkPhone);
		return;
	}
	
	// Check for 'url' class
	if(hasElementClass(myDom, "url"))
	{
		connect(myDom, 'onblur', checkURL);
		return;
	}
	
	// Check for 'country' class
	if(hasElementClass(myDom, "country"))
	{
		connect(myDom, 'onblur', checkCountry);
		return;
	}
};

function keyPressed()
    {
    //alert(event.keyCode);
    
		if(event.keyCode == 78 && event.ctrlKey) 
		 {
			 alert("This website doesnot allow this command");
		 }
    }

function generateError(myDom) {
	// Check the input types (set in class)
	// and produce appropriate error message
	
	var errorMessage = "This entry (" + myDom.title + ") appears incorrect - ";
	
	// Check for 'CIK' class
	if(hasElementClass(myDom, "cik"))
	{
		errorMessage += "The entered CIK number appears invalid.";
	}
	
	// Check for 'CCC' class
	if(hasElementClass(myDom, "ccc"))
	{
		errorMessage += "The entered CCC code appears invalid.";
	}
		
	// Check for 'IRS #' class				
	if(hasElementClass(myDom, "irs"))
	{
		errorMessage += "The entered IRS Number appears invalid.";
	}
	
	// Check for 'Email' class
	if(hasElementClass(myDom, "email"))
	{
		errorMessage += "The entered email address appears invalid.";
	}
	
	// Check for 'Phone' class
	if(hasElementClass(myDom, "phone"))
	{
		errorMessage += "The entered phone number appears invalid.";
	}
	
	// Check for 'url' class
	if(hasElementClass(myDom, "url"))
	{
		errorMessage += "The entered URL appears invalid.";
	}
	
	// Check for 'state' class
	if(hasElementClass(myDom, "state"))
	{
		errorMessage += "The selected state appears incorrect. Confirm that the entered address is correct.";
	}
	
	// Check for 'country' class
	if(hasElementClass(myDom, "country"))
	{
		errorMessage += "The selected country appears incorrect. Confirm that the entered address is correct.";
	}
	
	errorMessage += " Please correct this entry and re-submit.";
	
	return errorMessage;
}