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
}

function isDate3(sDate) {
	var scratch = new Date(sDate);
	if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date") {
		return false;
	} else {
		return true;
	}
}

function isDate(dtStr){
	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("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

//------------------------------------------------------------------------------------------
//CLEARS ALL ELEMENTS OF A FORM
//------------------------------------------------------------------------------------------	
function ClearForm (val){
	var theForm = val
	for(i=0; i<theForm.elements.length; i++){
		var myelement = theForm.elements[i]
		var mytype = myelement.type
		if (mytype == 'select-one') {
			myelement.selectedIndex = 0
		}
		if ((mytype == 'text') || (mytype == 'textarea') || (mytype == 'file')) {
			myelement.value=''
		}
		if ((mytype == 'radio') || (mytype == 'checkbox')) {
			myelement.checked=false
		}
	}
}
function MakeAllUpper(val){
	var theForm = val
	for(i=0; i<theForm.elements.length; i++){
		var myelement = theForm.elements[i]
		var myvalue = myelement.value
		var mytype = myelement.type
		if ((mytype == 'text') || (mytype == 'textarea') || (mytype == 'file')) {
			myvalue = myvalue.toUpperCase()
			myelement.value=myvalue
		}
	}
}
//-------------------------------------------------------------------
//IsDate() - checks for date
//-------------------------------------------------------------------
function isDate2(dateStr) {

//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?

if (matchArray == null) {
//alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
return false;
}

month = matchArray[1]; // p@rse date into variables
day = matchArray[3];
year = matchArray[5];

if (month < 1 || month > 12) { // check month range
//alert("Month must be between 1 and 12.");
return false;
}

if (day < 1 || day > 31) {
//alert("Day must be between 1 and 31.");
return false;
}

if ((month==4 || month==6 || month==9 || month==11) && day==31) {
//alert("Month "+month+" doesn`t have 31 days!")
return false;
}

if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day==29 && !isleap)) {
//alert("February " + year + " doesn`t have " + day + " days!");
return false;
}
}
return true; // date is valid
}






function checkstate(objMe){
	var me = objMe.options[objMe.selectedIndex]
	if ((me.value == '')&&(me.text != '')) {
		objMe.selectedIndex = 0;
		alert('please select a valid state');
		return;
	}
}

function displayopacity(h,w){
//	h = f_clientHeight();
//	w = f_clientWidth();
	
	if (document.body.clientWidth != null){
		w = document.body.clientWidth;
	}else if (document.documentElement != null){
		w = document.documentElement.clientWidth;
	}else if (window.innerWidth != null){
		w = window.innerWidth;
	}

	if (document.documentElement != null){
		h = document.documentElement.clientHeight;
	}else if (document.body.clientHeight != null){
		h = document.body.clientHeight;
	}else if (window.innerHeight != null){
		h = window.innerHeight;
	}	

	//alert(document.documentElement.clientHeight + '-' + document.body.clientHeight + '-' + document.body.clientHeight + '--' + h);

	document.getElementById("hideall").style.display = 'inline';
//	document.getElementById("hideall").style.height = (h-80) + "px";
//	document.getElementById("hideall").style.width = w + "px";
}

function hideopacity(){
	document.getElementById("hideall").style.display = 'none';
//	document.getElementById("hideall").style.height = "0px";
//	document.getElementById("hideall").style.width = "0px";
}

//------------------------------------------------------------------------------------------
//USED FOR THE TOOL TIP
//------------------------------------------------------------------------------------------
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
var myWidth = 0; myHeight = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }

function ShowToolTip(d,text){
	if(self.pageYOffset) {
		rX = self.pageXOffset;
		rY = self.pageYOffset;
		}
	else if(document.documentElement && document.documentElement.scrollTop) {
		rX = document.documentElement.scrollLeft;
		rY = document.documentElement.scrollTop;
		}
	else if(document.body) {
		rX = document.body.scrollLeft;
		rY = document.body.scrollTop;
		}
	if(document.all) {
		cX += rX; 
		cY += rY;
		}
	
	document.getElementById("tooltip").style.display = 'inline';
	document.getElementById("tooltiptext").innerHTML = text;
	
	document.getElementById("tooltip").style.left = (cX+5) + "px";
	document.getElementById("tooltip").style.top = (cY-25) + "px";
}

function HideToolTip(){
	document.getElementById("tooltiptext").innerHTML = '';
	document.getElementById("tooltip").style.display = 'none';
}

// cross browser functions
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function decode(str) {
     return unescape(str.replace(/\+/g, " "));
}
//------------------------------------------------------------------------------------------
//POPULATE A PARTICULAR FIELD ON THE SCREEN WITH A SPCIFIC VALUE
//------------------------------------------------------------------------------------------	
function populatefield(myfield,myvalue) {
	document.getElementById(myfield).value = myvalue;
}

//------------------------------------------------------------------------------------------
//ALTERNATIVE FOR VBScript LTRIM() RTRIM() FUNCTIONS
//------------------------------------------------------------------------------------------	
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
}

function trimAll(sString) 
	{
	while (sString.substring(0,1) == ' ')
		{
		sString = sString.substring(1, sString.length);
		}
	while (sString.substring(sString.length-1, sString.length) == ' ')
		{
		sString = sString.substring(0,sString.length-1);
		}
	return sString;
}


//------------------------------------------------------------------------------------------
//USED TO COUNT THE NUMBER OF CHACTERS LEFT IN A TEXTAREA.
//------------------------------------------------------------------------------------------
function textCounter(field,cntfield,maxlimit) {
	if (document.getElementById(field).value.length > maxlimit) // if too long...trim it!
		document.getElementById(field).value = document.getElementById(field).value.substring(0, maxlimit);
	else
	document.getElementById(cntfield).innerHTML = maxlimit - document.getElementById(field).value.length;
	}
	
//------------------------------------------------------------------------------------------
//ALTERNATIVE FOR VBScript LEFT() AND RIGHT()
//------------------------------------------------------------------------------------------	
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

//------------------------------------------------------------------------------------------
//REPLACE SUBSTRING
//------------------------------------------------------------------------------------------	

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

//------------------------------------------------------------------------------------------
//CHECK A FORM FOR REQUIRED FIELDS.  ADDITIONAL CHECKS CAN BE MADE
//ON AN INDIVIDUAL PAGE WITH pagecheck();
//
//Looks for these attribute:
//lowercase: true if needs to be lowercase
//required: true if must be filled in
//elemtype: numeric, text, date (will check the validity of the type only, not he contents - this should be done in pagecheck(); )
//friendlyname: a friendly name to display
//------------------------------------------------------------------------------------------	
function makemeupper(objMe){
	val = trim(objMe.value)
	objMe.value = val.toUpperCase()
}

var dochecksubmit = false
function CheckForm(myform,action) {
	//action: 1=confirm & submit, 2=submit, 3=do not submit 
	var theForm = myform
	var alertReqText = '';
	var alertDataText = '';
	var strText = '';
	var i = 0;
	var illegalChars = /[\W_]/; // allow only letters and numbers
	var illegalChars2= /[\(\)\<\>\,\;\s\:\\\"\[\]]/;
	var illegalcharsforall = /[\%\&\<\>\'\"\(\)\[\]\{\}\^\$\/\\\;\,\:]/;

	for(i=0; i<theForm.elements.length; i++){
		var checkillegalchars = 'false'
		var r = 0
		var myelement = theForm.elements[i]
		var mytype = myelement.type
		var val = trim(myelement.value)
		var req = myelement.getAttribute('required')
		var lower = myelement.getAttribute('lowercase')
		var elemtype = myelement.getAttribute('elemtype')
		var friendlyname = myelement.getAttribute('friendlyname')
		var reference = myelement.getAttribute('reference')
		var toupper = myelement.getAttribute('upper')
		checkillegalchars = myelement.getAttribute('chkillegal')
		
		if (checkillegalchars == 'true'){
			if (val.match(illegalcharsforall)) {
				alertDataText = alertDataText + '     ' + friendlyname + ' - Please remove any characters other than letters, numbers, spaces or underscores \n'
				myelement.style.background = '#FFE1E1';
			}
		}
		
		if (toupper == 'true') {
			val = val.toUpperCase()
			myelement.value=val
		}
		
		if (req == 'true') {
			switch (mytype) {
			case "checkbox":
				if (myelement.checked != true) {
					alertReqText = alertReqText + ' ' + friendlyname + ' \n'
					if (isObject(document.getElementById('spn' + myelement.name)) ==true) {
						document.getElementById('spn' + myelement.name).style.background = '#FFE1E1';
						}
				}
				else {
					myelement.style.background = 'white';
				}
				break;		
			default:
				if (val.length ==0) {
					alertReqText = alertReqText + '  ' + friendlyname + ' \n'
					myelement.style.background = '#FFE1E1';
				}
				else {
					myelement.style.background = 'white';
				}
				break;
			}
		}
		else {
			if (mytype != 'button') {
				myelement.style.background = 'white';
			}
		}
		
		

			switch (elemtype) {
				case "date":
					if (val != '') {
						if (!isDate2(val)) {
							alertDataText = alertDataText + '     ' + friendlyname + ' must be in the format mm\dd\yyyy \n'
							myelement.style.background = '#FFE1E1';
						}
					}
					break;
				case "number":
					if ((!IsNumeric(val)) && (val != '')){
						alertDataText = alertDataText + '     ' + friendlyname + ' is not a number \n'
						myelement.style.background = '#FFE1E1';
					}
					break;
				case "password":
					if (val.length < 6) {
						if (val != '') {
							alertDataText = alertDataText + '     ' + friendlyname + ' must be longer than 6 characters \n'
							myelement.style.background = '#FFE1E1';
						}
					}
					break;
				case "email":
					//((val.indexOf(".") > 0) && (val.indexOf("@") > 0) && (val.length > 4)) {}
					var emailFilter=/^.+@.+\..{2,3}$/;
					var illegalChars= /[\(\)\<\>\,\;\s\:\\\"\[\]]/;
				    if (((!(emailFilter.test(val))) || (val.match(illegalChars))) && (val != '')) { 
						alertDataText = alertDataText + '     ' + friendlyname + ' is not a valid email \n'
						myelement.style.background = '#FFE1E1';
				    }
				   	break;
				case "phone":
					var stripped = val.replace(/[\(\)\.\-\ \+]/g, '');
					if (((isNaN(parseInt(stripped))) || ((stripped.length < 10))) && (val != '')) {
						alertDataText = alertDataText + '     ' + friendlyname + ' is not a valid phone number \n'
						myelement.style.background = '#FFE1E1';
					}
					break;
				case "postalcode":
					var postalfilter = /[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d/;
					if ((reference == 'USA') || (reference == 'CAN') || (reference == 'MEX')){reference = reference}
					if ((reference!=null) && (reference.length > 1)){reference = document.getElementById(reference).value}
					
					switch (reference) {
						case "CAN":
							if ((!(val.length == 7)) || (!(postalfilter.test(val)))) {
								alertDataText = alertDataText + '     ' + friendlyname + ' is not a valid postal code for ' + reference + '\n'
								myelement.style.background = '#FFE1E1';
							}
						break;
						case "MEX":
								if ((!(val.length == 7)) || (!(postalfilter.test(val)))) {
								alertDataText = alertDataText + '     ' + friendlyname + ' is not a valid postal code ' + reference + '\n'
								myelement.style.background = '#FFE1E1';
							}
						break;
						case "USA":
							if ((!(val.length == 5)) || (!isNumeric(val))) {
								alertDataText = alertDataText + '     ' + friendlyname + ' - please use 5 digits only ' + reference + '\n'
								myelement.style.background = '#FFE1E1';
							}
						break;
					}			
			
		}
		
	}
			
	if ((alertDataText.length > 0)||(alertReqText.length > 0)) {
		if (alertDataText.length > 0){alertDataText = '\n\n FIELD ERRORS \n\n' + alertDataText}
		if (alertReqText.length > 0){alertReqText = 'REQUIRED FIELDS \n\n' + alertReqText}
		alert(alertReqText + alertDataText);
	}
	else{
		switch(action){
		case 1:
			//if(confirm('Are you sure you want to submit the form? \n\n Cancel = Make one last check. \n\n OK = I\'m good, submit the form.')){
				theForm.submit();
			//}
			break;
		case 2:
			theForm.submit();
			return true
			break;
		case 3:
			return true
			break;
		}
	}
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789,.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
