// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

// Valid date of (mm/dd/yyyy)
function isDate(str,fieldname,found)
{
	if (found == 0) 
	{
		return true  
	} 
	else 
	{
		var dt = str
		dtStr = str.value
		var daysInMonth = DaysArray(12)
		var pos1=dtStr.indexOf(dtCh)
		var pos2=dtStr.indexOf(dtCh,pos1+1)
		var strMonth=dtStr.substring(0,pos1)
		var strDay=dtStr.substring(pos1+1,pos2)
		var strYear=dtStr.substring(pos2+1)
		strYr=strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
		if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
		}
		month=parseInt(strMonth)
		day=parseInt(strDay)
		year=parseInt(strYr)
		if (pos1==-1 || pos2==-1){
			alert("Invalid " + fieldname + ". The date format should be : mm/dd/yyyy")
			dt.focus()
			return false
		}
		if (strMonth.length<1 || month<1 || month>12){
			alert("Invalid " + fieldname + ". Please enter a valid month")
			dt.focus()
			return false
		}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			alert("Invalid " + fieldname + ". Please enter a valid day")
			dt.focus()
			return false
		}
		if (strYear.length == 2) { 
			strYear = '20' + strYear
			year = strYear 
		} 
		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			alert("Invalid " + fieldname + ". Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
			dt.focus()
			return false
		}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			alert("Invalid " + fieldname + ". Please enter a valid date")
			dt.focus()
			return false
		}
	str.value = strMonth + "/" + strDay + "/" + strYear
	return true
	}
}

// Validates length of field.  
function validateLength(myfield, size, fieldname) {
newstring=stripNum(myfield.value)	
if (myfield.value.length < size) 
	{
	alert("Invalid " + fieldname + ".  " + fieldname + " must be equal to or greater than " + size + ".")
	myfield.focus()
	return false
	} 
else 
	{ 
	return true 
	}//if not newstring
}

// Strips field of invalid characters except decimal.  User for currency.
function stripMoney(str) 
{
var newstring=""
var invalidChar = ',/;:)(*&^%$#@-+=|\}{[] '; // characters allowed in hex
for (var i = 0; i < str.length; i++ ) 
	{
		mychar=str.charAt(i)
    	if (invalidChar.indexOf(str.charAt(i))<0) 
		{
			str.replace(str.charAt(i),"")
			mychar=str.charAt(i)
			if (mychar != '.')
			{
				if (isDigits(mychar))
				newstring+=mychar 
			}
			else
				newstring+=mychar 
		} 
	} 
return newstring
}

// Validate Currency for float datatype. 
function isCurrency(str,fieldname)
{
if (notNull(str.value) && notBlank(str.value))
{
	val = stripMoney(str.value)
	var nNum = 0;			// Total numbers for currency value.
	var nDecimal = 0;		// Total times a decimal point occurs.
	var txtLen;				// Length of string passed.
	var xTxt;				// Assigned object passed.
	var decPos;				// Assigned value of numbers or positions after decimal point.
	var i;					// For forloop indexing.
	var x;					// Assigned each indivual character in string.
	// Set the xTxt variable to the object passed to this function.
	// Assign the length of the string to txtLen.
	xTxt = val
	txtLen = xTxt.length
		for(i = 0; i < txtLen; i++)
		{
			// Assign charater in substring to x.
			x = xTxt.substr(i, 1);
			if(x == ".")
				nDecimal = nDecimal + 1; // Sum total times decimal point occurs.
			else if(parseInt(x) >= 0 || parseInt(x) <= 9)
				nNum = nNum + 1; // If the character is a number sum total times a number occurs.
		} // end for
		if(nDecimal > 1)
		{
			alert("Invalid " + fieldname + ". Please only enter one decimal");
			return false;
		} // end if
		if(nDecimal == 1)
		{
			// Get the number of numbers after the decimal point in
			// the string if there is a decimal point present
			decPos = (txtLen - 1) - xTxt.indexOf(".");		
			// Floating point cannot be more then two.
			// Valid format after decimal point.
			/**********************************/
			/*   $#.##, $#.#, $.#, $#., $.##  */
			/**********************************/
			if(decPos > 2)
			{
				alert("Invalid " + fieldname + ". The decimal point you entered is not in the correct position.");
				return false;
			} // end if
		} // end if
		str.value = xTxt
		return true
	}  
else
	{
	alert("Invalid " + fieldname + ". Please enter currency.");
	str.focus()
	return false
	}            
}
// String is certain size
function isSize(str, size) {
if (str.length==size)
	return true
else
	return false
}

// Remove non digits
function stripNonDigits(str) {
var i
var newstring=""
for (i=0; i<str.length; i++ ) {
	mychar=str.charAt(i)
	if (isDigits(mychar))
		newstring+=mychar
	}
return newstring
}

// Validate number fields
function isGreater(myfield, size1, fieldname, found) 
{
	if (myfield.value > size1) 
	{
		return true
	}
	else
	{
		myfield.focus()
		alert("Invalid " + fieldname + ".  " + fieldname + " must be greater than " + size1 + ".")
		return false
	}
}

// Validate number fields
function validateNumFields(myfield, size1, size2, fieldname, format) 
{

	if (notNull(myfield.value)) 
	{
		newstring=stripNonDigits(myfield.value)	
		if (isSize(newstring,size1) || isSize(newstring, size2))
			return true
	}
	myfield.focus()
	myfield.select()
	alert("Invalid " + fieldname + ".  Please enter numeric values in the format of " + format + ".")
	return false
}

// Validate string not empty
function validateString(str,fieldname,found) 
{
	if (found == 0) 
		return true
	else
	{
		if (notNull(str.value) && notBlank(str.value))
			return true
		else 
		{
			str.focus()
			alert("The " + fieldname + " field is blank.  Please enter a " + fieldname + ".")
			return false
		}
	}
}

// Validate credit card expiration date.
function validateCCExpDate(jsyear, jsmonth, vbyear, vbmonth) {
if (jsyear.value < vbyear) 
	{ 
		jsyear.focus()
		alert("Invalid expiration year.") 
		return false
	}
	else
	{   if (jsyear.value == vbyear) 
		{ 
			if (jsmonth.value < vbmonth) 
			{ 
			jsmonth.focus()
			alert("Invalid expiration month.") 
			return false
			}
			else { return true }
		}
		else { return true }
	}
}

//Check to make sure that a field is not null
function notNull(str) 
{
	if (str.length == '0')
		return false
	else
		return true
}

//Check to make sure that a field is not blank
function notBlank(str) 
{
	for (var i=0; i<str.length; i++) 
	{
		if (str.charAt(i) != " ")
			return true
	}
return false
}
    
//Check to make sure that a field has a valid number
function isNumeric(str,fieldname,found) 
{
	if (found == 0 && str.value.length == 0)
	{
		return true  
	} 
	else 
	{
		if (notNull(str.value))
		{
			newstring=stripNum(str.value)	
			str.value = newstring 
			if (isDigits(str.value))
				return true 
			else 
			{
				alert("Invalid " + fieldname + ".  Enter numeric whole number.")
				str.focus()
				return false
			}
		}
		else 
		{
			alert("Invalid " + fieldname + ". Please enter whole number.")
			str.focus()
			return false
		}
	}
}

// Trim leading and trailing spaces
function trimString(sInString) 
{
	sInString = sInString.replace( /^\s+/g, "" );
	return sInString.replace( /^\s+/g, "" );
}

// Removes leading and trailing spaces from the passed string. 
function trim(inputString) 
{
if (typeof inputString != "string") { return inputString; }
var retValue = inputString;
var ch = retValue.substring(0, 1);
	while (ch == " ") 
	{ // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") 
	{ // Check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) 
	{ // Note that there are two spaces in the string - look for multiple spaces within the string
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
	}
	return retValue; 
} 
          
// Uppercase first letter of each sentence
function upperCase(myform)
{         
	for (var i = 0; i < myform.elements.length; i++) 
	{	
		var str = myform.elements[i].value;
		str = trim(str)
		
		if (myform.elements[i].type == 'text')
		{
			str = myform.elements[i].value.toLowerCase();
			val = str;
			newVal = '';
			val = val.split(' ');
			for(var c=0; c < val.length; c++) 
			{
				newVal += val[c].substring(0,1).toUpperCase() +
				val[c].substring(1,val[c].length) + ' ';
			}
		myform.elements[i].value = newVal
		}
		if (myform.elements[i].type == 'textarea')
		{
			
			str = myform.elements[i].value.toLowerCase();
			val = str;
			
			newVal = '';
			val = val.split(". ");
			for(var c=0; c < val.length; c++) 
			{
				newVal += val[c].substring(0,1).toUpperCase() +
				val[c].substring(1,val[c].length) + '. ';
			}
			newVal = newVal.replace("..",".")
			newVal = newVal.replace(" .","")
			val = newVal;
			newVal = '';
			val = val.split("! ");
			for(var c=0; c < val.length; c++) 
			{
				newVal += val[c].substring(0,1).toUpperCase() +
				val[c].substring(1,val[c].length) + '! ';
			}
			//newVal = newVal.replace("..",".")
			newVal = newVal.replace("!.","!")
			newVal = newVal.replace("?.","?")
			newVal = newVal.replace(" !","")
			//newVal = newVal.replace(".!","")
			//newVal = newVal.replace(".!","")
			//newVal = newVal.replace("  "," ")
		myform.elements[i].value = newVal
		}
	}
}            
                      
//US phone validation: 10 digits no illegal characters
function validatePhoneUS(str, fieldname,found)
{
	if (found == 0 && str.value.length == 0)
	{
		return true  
	} 
	else 
	{
		newstring=stripNum(str.value)	
		str.value = newstring 
		var validChar = '0123456789'; // characters allowed in hex
		var strlen = newstring.length;     
		if (strlen != 10) 
			{
				alert("Invalid " + fieldname + ".  Please enter 10 digit " + fieldname + ".")
				str.focus()
				return false
			} 
		else
			{
				for (var i = 0; i < strlen; i++ ) 
				{
		    		if (validChar.indexOf(newstring.charAt(i)) < 0) 
		    		{
		       			alert("Invalid " + fieldname + ".  Please complete " + fieldname + " number.")
		       			return false;
		       		}
		    	} 
		    	return true;
			}
		return true;
	}
}

// Strips field of invalid characters.  Use for credit cards and phone numbers.
function stripNum(str) 
{
var newstring=""
var invalidChar = ',/.;:)(*&^%$#@-+=|\}{[] '; // characters allowed in hex
for (var i = 0; i < str.length; i++ ) 
	{
		mychar=str.charAt(i)
    	if (invalidChar.indexOf(str.charAt(i))<0) 
		{
			str.replace(str.charAt(i),"")
			mychar=str.charAt(i)
			if (isDigits(mychar))
			newstring+=mychar
		} 
	} 
return newstring
}

// Validates string as Digits
function isDigits(str) 
{
var i
var newstring=""
	for (i=0; i<str.length; i++) 
	{
		mychar=str.charAt(i)
		if (mychar<"0" || mychar>"9")
			{ return false }  
	}
return true
}
     
//Select multiple: just ALL chosen
function validateComboAll(myfield, s) 
{
	var i
	if (myfield.options[0].selected)
	{
		for (i=1; i<myfield.length; i++ ) 
		{
			if ( myfield.options[i].selected)
			{ 
				myfield.options[i].selected = false 
			}
		}
		return true
	}
	return true
}

//Select multiple must be chosen
function validateCombo(myfield, s) 
{
var i
	for (i=0; i<myfield.length; i++ ) 
	{
		if ( myfield.options[i].selected)
		{
			i = myfield.length
			return true;
		}
	}
	alert("Please select a " + s + ".")
	return false
}

//Select must be chosen
function validateSelect(myfield, s) 
{
	if (myfield.options[myfield.selectedIndex].value!=-1) 
	{
		return true
	} 
	else 
	{
		alert("Please select a " + s + ".")
		myfield.focus
		return false
	}
}

//Email is valid and not empty
function isEmail(str, fieldname,found)
{
	if (found == 0 && str.value.length == 0)
	{
		return true  
	} 
	else 
	{
		var Temp     = str
		var AtSym    = Temp.value.indexOf("@")
		var Period   = Temp.value.lastIndexOf(".")
		var Space    = Temp.value.indexOf(" ")
		var Length   = Temp.value.length - 1   // Array is from 0 to length-1

		if ((AtSym < 1) ||                     // "@" cannot be in first position
	    	(Period <= AtSym+1) ||             // Must be atleast one valid char btwn "@" and "."
		   	(Period == Length ) ||             // Must be atleast one valid char after "."
	    	(Space  != -1))                    // No empty spaces permitted
		{  
			
			alert("Please enter a valid " + fieldname + ".");
			str.focus();
			str.select();
			return false;
		}   
	} 
return true 
}

//Select must be chosen
function fieldsMatch(str, str2, fieldname, found) 
{
if (found == 0 && str.value.length == 0)
	{
		return true  
	} 
	else 
	{
		if (str.value == str2.value) 
		{
			return true
		} 
		else 
		{
			alert("" + fieldname + " do not match.")
			str.focus
			return false
		}
	}
}