// JavaScript Document

/*
This is an object oriented approach to Form Validation that works well with Serena.

To use it, you must define an array containing the id of the field, type, and alertTxt in the style as follows:
     array[i] = new inputClass(type, name, alertTxt)
	 
On submission of the form run the function validate: onsubmit="return validate(this, fields);"
    - fields is the array containing all of the inputClass objects

Current allowed values for the variable type are: "email", "text", "radio", "dropdown", "CC", "formKey", "date"
Note: the first selected index on the drpdown should be blank and intially selected
NOTE: for radio groups the id needs to be the id then a number, such as id0 and id1, the name of the set should be the id, enter the id into the name portion of the class
Note: formKey is dependent on a jpeg created bt the check Application, the variable is saved in the session variable
*/
var checkText = null;

function validateFormKey(field){
	//alert(checkText);
	with(field){
		if (checkText == value){
			return true;
		}else if (checkText == null){
			return false;
		}
	}
}

function returnFormKey(){
	
	req = zXmlHttp.createRequest();
	req.onreadystatechange = function() {
		//alert(req.readyState);
		if (req.readyState == 4){
			//only if "OK"
			//alert(req.status);
			if (req.status == 200){
				//alert(req.responseText);
				checkText = req.responseText; 
			}
		}
	};
	req.open("GET", "http://www.bigskyresort.com/check/check.aspx", true); //change this to go to the correct check page
	req.send(null);
}

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 validateDate(date){
	//alert(date);
	with(date){
		var dtStr = 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("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
}

function validateCC(ccNumb) {  // v2.0
var valid = "0123456789"  // Valid digits in a credit card number
var len = ccNumb.length;  // The length of the submitted cc number
var iCCN = parseInt(ccNumb);  // integer of ccNumb
var sCCN = ccNumb.toString();  // string of ccNumb
sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
var iTotal = 0;  // integer total set at zero
var bNum = true;  // by default assume it is a number
var bResult = false;  // by default assume it is NOT a valid cc
var temp;  // temp variable for parsing string
var calc;  // used for calculation of each digit

// Determine if the ccNumb is in fact all numbers
for (var j=0; j<len; j++) {
  temp = "" + sCCN.substring(j, j+1);
  if (valid.indexOf(temp) == "-1"){bNum = false;}
}

// if it is NOT a number, you can either alert to the fact, or just pass a failure
if(!bNum){
  /*alert("Not a Number");*/bResult = false;
}

// Determine if it is the proper length 
if((len == 0)&&(bResult)){  // nothing, field is blank AND passed above # check
  bResult = false;
} else{  // ccNumb is a number and the proper length - let's see if it is a valid card number
  if(len >= 15){  // 15 or 16 for Amex or V/MC
    for(var i=len;i>0;i--){  // LOOP throught the digits of the card
      calc = parseInt(iCCN) % 10;  // right most digit
      calc = parseInt(calc);  // assure it is an integer
      iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
      i--;  // decrement the count - move to the next digit in the card
      iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
      calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
      calc = calc *2;                                 // multiply the digit by two
      // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
      // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
      switch(calc){
        case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
        case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
        case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
        case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
        case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
        default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
      }                                               
    iCCN = iCCN / 10;  // subtracts right most digit from ccNum
    iTotal += calc;  // running total of the card number as we loop
  }  // END OF LOOP
  if ((iTotal%10)==0){  // check to see if the sum Mod 10 is zero
    bResult = true;  // This IS (or could be) a valid credit card number.
  } else {
    bResult = false;  // This could NOT be a valid credit card number
    }
  }
}

  return bResult; // Return the results
};


function validateText(field) {
	//alert(field);
	with(field){
		if (value==null||value==""){
			return false;
		}else{
			return true;
		}
	}
};

function validateEmail(field) {
	//alert(field);
	with(field) {
		apos=value.indexOf("@");
		dotpos=value.lastIndexOf(".");
		if (apos<1||dotpos-apos<2) {
			return false;
		}else{
			return true;
		}
	}
};

function validateDropdown(field) {
	//alert("DD Started");
	//alert(field.selectedIndex);
	with(field) {
		//alert(selectedIndex);
		if (selectedIndex == 0||selectedIndex == -1){
			return false;
		}else{
			return true;
		}
	}
};

function validateRadios(fieldName){
	var radioCheck = false;
	var radioSet = document.getElementsByName(fieldName);
	//alert(radioSet.length);
	
	for(j=0; j<radioSet.length; j++){
		if	(radioSet[j].checked){
			radioCheck = true;
		}
	}
	//alert(radioCheck);
	return radioCheck;
};

function inputClass(type, name, alertTxt){
	this.type = type;
	this.name = name;
	this.alertTxt = alertTxt;
}

function validate(thisform, fields){
	
	var alertTxt = "The following is required and must be filled in: \n";
	var firstError = null;
	var valid = true;
	
	for(i=0;i<fields.length;i++){
		
		//alert(fields[i].name);
		
		if(fields[i].type == "text") {
			if (!(validateText(document.getElementById(fields[i].name)))){
				alertTxt = alertTxt + "  -  " + fields[i].alertTxt + "\n";
				document.getElementById(fields[i].name).style.backgroundColor = "#99FF00";
				if (firstError == null){
					firstError = document.getElementById(fields[i].name);
				}
				valid = false;
			}else{
				document.getElementById(fields[i].name).style.backgroundColor = "#FFFFFF";
			}
		}
		if(fields[i].type == "email") {
			if (!(validateEmail(document.getElementById(fields[i].name)))){
				alertTxt = alertTxt + "  -  " + fields[i].alertTxt + "\n";
				document.getElementById(fields[i].name).style.backgroundColor = "#99FF00";
				if (firstError == null){
					firstError = document.getElementById(fields[i].name);
				}
				valid = false;
			}else{
				document.getElementById(fields[i].name).style.backgroundColor = "#FFFFFF";
			}
		}
		if(fields[i].type == "dropdown") {
			if (!(validateDropdown(document.getElementById(fields[i].name)))){
				alertTxt = alertTxt + "  -  " + fields[i].alertTxt + "\n";
				document.getElementById(fields[i].name).style.backgroundColor = "#99FF00";
				if (firstError == null){
					firstError = document.getElementById(fields[i].name);
				}
				valid = false;
			}else{
				document.getElementById(fields[i].name).style.backgroundColor = "#FFFFFF";
			}
		}
		if(fields[i].type == "radio") {
			if (!(validateRadios(fields[i].name))){
				alertTxt = alertTxt + "  -  " + fields[i].alertTxt + "\n";
				//document.getElementsByName(fields[i].name).style.backgroundColor = "#99FF00";
				/*if (firstError == null){
					firstError = document.getElementById(fields[i].name);
				}
				valid = false;*/
			}else{
				//document.getElementById(fields[i].name).style.backgroundColor = "#FFFFFF";
			}
		}
		if(fields[i].type == "CC") {
			if (!(validateCC(document.getElementById(fields[i].name).value))){
				alertTxt = alertTxt + "  -  " + fields[i].alertTxt + "\n";
				document.getElementById(fields[i].name).style.backgroundColor = "#99FF00";
				if (firstError == null){
					firstError = document.getElementById(fields[i].name);
				}
				valid = false;
			}else{
				document.getElementById(fields[i].name).style.backgroundColor = "#FFFFFF";
			}
		}
		if(fields[i].type == "formKey") {
			if (!(validateFormKey(document.getElementById(fields[i].name)))){
				alertTxt = alertTxt + "  -  " + fields[i].alertTxt + "\n";
				document.getElementById(fields[i].name).style.backgroundColor = "#99FF00";
				if (firstError == null){
					firstError = document.getElementById(fields[i].name);
				}
				valid = false;
			}else{
				document.getElementById(fields[i].name).style.backgroundColor = "#FFFFFF";
			}
		}
		if(fields[i].type == "date") {
			if (!(validateDate(document.getElementById(fields[i].name)))){
				alertTxt = alertTxt + "  -  " + fields[i].alertTxt + "\n";
				document.getElementById(fields[i].name).style.backgroundColor = "#99FF00";
				if (firstError == null){
					firstError = document.getElementById(fields[i].name);
				}
				valid = false;
			}else{
				document.getElementById(fields[i].name).style.backgroundColor = "#FFFFFF";
			}
		}
	}
	
	if (!(valid)){
		alert(alertTxt);
		firstError.focus();
	}
	return valid;
}

