function validateCreditCard(ccNumb) { //v2.0
var valid = "0123456789"
var len = ccNumb.length;
var bNum = true;
var iCCN = ccNumb;
var sCCN = ccNumb.toString();
var iCCN;
var iTotal = 0;
var bResult = false;
var digit;
var temp;
        iCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
    //alert(iCCN);
for (var j=0; j<len; j++) {
temp = "" + iCCN.substring(j, j+1);
if (valid.indexOf(temp) == "-1") bNum = false;
}
if(!bNum){alert("Not a Number");}
    iCCN = parseInt(iCCN);

if(len == 0){ /* nothing, field is blank */ 
        bResult = false;
}else{
        if(len >= 15){          //15 or 16 for Amex or V/MC
                for(var i=len;i>0;i--){
                digit = "digit" + i;
                //alert(digit);

                        calc = parseInt(iCCN) % 10;     //right most digit
                        calc = parseInt(calc);
                        //alert(calc);
                        iTotal += calc;         //parseInt(cardnum.charAt(count))i:\t" + calc.toString() + " x 2 = " + (calc *2) +" : " + calc2 + "\n";
                        i--;
                digit = "digit" + i;
                //alert(digit);

                        iCCN = iCCN / 10;       // subtracts right most digit from ccNum
                        calc = parseInt(iCCN) % 10 ;    // step 1 double every other digit
                         //alert( iCCN + " " + calc);
                         calc2 = calc *2;

                        switch(calc2){
                                case 10: calc2 = 1; break;      //5*2=10 & 1+0 = 1
                                case 12: calc2 = 3; break;      //6*2=12 & 1+2 = 3
                                case 14: calc2 = 5; break;      //7*2=14 & 1+4 = 5
                                case 16: calc2 = 7; break;      //8*2=16 & 1+6 = 7
                                case 18: calc2 = 9; break;      //9*2=18 & 1+8 = 9
                                default: calc2 = calc2;                 //4*2= 8 &   8 = 8  -same for all lower numbers
                        }
                        iCCN = iCCN / 10;       // subtracts right most digit from ccNum
                        iTotal += calc2;
                }
                if ((iTotal%10)==0){
                        bResult = true;
                }else{
                        bResult = false;
                }
        }
}

  return bResult;
}

function validZip(zip)
{
   if (zip.match(/^[0-9]{5}$/)) {
     return true;
   }

   zip=zip.toUpperCase();
   if (zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
     return true;
   }

   if (zip.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
     return true;
   }

   return false;
}

function ValidatePostalCode(){
	var zip=document.frmApplication.zip
	
	if ((zip.value==null)||(zip.value=="")){
		zip.focus()
		return false
	}
	if (validZip(zip.value)==false){
		zip.focus()
		return false
	}
	return true
 }

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}

function ValidateEmailAddress(){
	var emailID=document.frmApplication.email
	
	if ((emailID.value==null)||(emailID.value=="")){
		emailID.focus()
		return false
	}
	if (echeck(emailID.value)==false){
		emailID.focus()
		return false
	}
	return true
 }



// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

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 isDate(dtStr){
        // YYYY-MM-DD
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strYear=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=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){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}

function ValidateDate(){
	var dt=document.frmApplication.bday
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }



// 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;

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 checkInternationalPhone(strPhone){
   s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidateTelephone(){
	var Phone=document.frmApplication.teleno
	
	if ((Phone.value==null)||(Phone.value=="")){
		Phone.focus()
		return false
	}
	if (checkInternationalPhone(Phone.value)==false){
		Phone.focus()
		return false
	}
	return true
 }

function its_empty(string_value) {

  // Check for the empty string and null
  if (string_value == "" || string_value == null) {
      return true
  }
  return false
}


function ValidateSSN4(){

	var ssn4 = document.frmApplication.ssn4

	if ((ssn4.value==null)||(ssn4.value=="")){
		ssn4.focus()
		return false
	}
        if (ssn4.value.length != 4){
		ssn4.focus()
                return false
        }
        if (isInteger(ssn4.value)==false){
		ssn4.focus()
                return false
        }
	return true
}



function validate(current_form) {
  
        var missing_fields = new Array()
        var total_missing = 0
  
        // check for missing fields

        for (counter = 0; counter < current_form.length; counter++) {
  
                if ((current_form[counter].type == "text" ||
                        current_form[counter].type == "textarea" ||
                        current_form[counter].type == "password") &&
                        current_form[counter].mandatory) {

                        if (its_empty(current_form[counter].value)) {
                                missing_fields[total_missing] = current_form[counter]
                                total_missing++
                        }
                }
        }

        if (total_missing > 0) {
  
                var missing_message = "Sorry, you must fill in the following " +
                       (total_missing == 1 ? " field:" : " fields:") +
                        "\n______________________________\n\n"
    
                for (counter = 0; counter < missing_fields.length; counter++) {
                        missing_message += missing_fields[counter].name + "\n"
                }
  
                missing_message += "\n______________________________\n\n" +
                            "Please fill in these fields and then resubmit the form."
                alert(missing_message)
    
                missing_fields[0].focus()
    
                return false

        } 
  

        var total_invalid = 0

        var invaliddata_message = "Sorry, the following fields have invalid values " +
                "\n______________________________\n\n"


        if (typeof current_form.email != "undefined") {
                if ( !ValidateEmailAddress( current_form.email ) ) {
                        current_form.email.focus();
                        invaliddata_message += "Your Email Address has an invalid format\n"
                        total_invalid++
                }
        }


        if (typeof current_form.zip != "undefined") {
                if ( !ValidatePostalCode( current_form.zip ) ) {
                        current_form.zip.focus();
                        invaliddata_message += "Your Zip/Postal code in not in correct format (US NNNNN / Canada ANA NAN)\n"
                        total_invalid++
                }
        }


        if (typeof current_form.bdmonth != "undefined") {
                var obox=current_form.bdmonth
                if ((obox.value==null)||(obox.value=="")){
                        obox.focus()
                        invaliddata_message += "Need to specify your Birth Date\n"
                        total_invalid++
                }
                var obox=current_form.bdyear
                if ((obox.value==null)||(obox.value=="")){
                        obox.focus()
                        invaliddata_message += "Need to specify your Birth Date\n"
                        total_invalid++
                }
                var obox=current_form.bdday
                if ((obox.value==null)||(obox.value=="")){
                        obox.focus()
                        invaliddata_message += "Need to specify your Birth Date\n"
                        total_invalid++
                }

		current_form.bday.value = current_form.bdyear.value + "-" + current_form.bdmonth.value + "-" + current_form.bdday.value
        }

        if (typeof current_form.PhoneAreaCode != "undefined") {
		current_form.teleno.value = current_form.PhoneAreaCode.value + current_form.PhoneExchangeCode.value + current_form.PhoneLastFour.value;
	}

        if (typeof current_form.teleno != "undefined") {
                if ( !ValidateTelephone( current_form.teleno ) ) {
                        current_form.teleno.focus();
                        invaliddata_message += "Your Telephone needs to be in the format of (888) 555-1212\n"
                        total_invalid++
                }
        }


        if (typeof current_form.bday != "undefined") {
                if ( !ValidateDate( current_form.bday ) ) {
                        current_form.bday.focus();
                        invaliddata_message += "Your Birth Day needs to be in the format of YYYY-MM-DD\n"
                        total_invalid++
                }
        }

        if (typeof current_form.ssn4 != "undefined") {
                if ( !ValidateSSN4( ) ) {
                        current_form.ssn4.focus();
                        invaliddata_message += "Your need to supply the last 4 digits of your Social Security Number\n"
                        total_invalid++
                }
		current_form.ssn.value = current_form.ssn4.value
        }

        if (typeof current_form.card1number != "undefined") {

                if ( !validateCreditCard( current_form.card1number.value ) ) {              
                        current_form.card1number.focus()
                        invaliddata_message += "Your Creditcard Number is Invalid\n"
                        total_invalid++
                }
        }


        if (typeof current_form.country != "undefined") {

                var obox=current_form.country
                if ((obox.value==null)||(obox.value=="")){
                        obox.focus()
                        invaliddata_message += "Need to specify your Country of Residence\n"
                        total_invalid++
                } else {

                        if ( (obox.value=="US") && (typeof current_form.ssn != "undefined") ) {
                                obox=current_form.ssn
                                if ((obox.value==null)||(obox.value=="")){
                                        obox.focus()
                                        invaliddata_message += "Social Security Number is Manditory for US apllicants\n"
                                        total_invalid++
                                }
                        }
                }
        }

        if (typeof current_form.State != "undefined") {
                var obox=current_form.State
                if ((obox.value==null)||(obox.value=="")){
                        obox.focus()
                        invaliddata_message += "Need to specify your State or Provence\n"
                        total_invalid++
                }
        }


        if (typeof current_form.acceptterms != "undefined") {
                var cbox=current_form.acceptterms
                if (!cbox.checked){
                        cbox.focus()
                        invaliddata_message += "We are unable to process this application, unless you have read and accept the terms and conditions\n"
                        total_invalid++
                }
        }


        if (typeof current_form.acceptreport != "undefined") {
                var cbox=current_form.acceptreport
                if (!cbox.checked){
                        cbox.focus()
                        invaliddata_message += "We are unable to process this application, unless you have agreed to allow us to do a credit check on you\n"
                        total_invalid++
                }
        }
   
         invaliddata_message += "\n______________________________\n\n" +
            "Please correct these fields and then resubmit the form."

        if ( total_invalid > 0 ) {
                alert(invaliddata_message)
                return false
        } 

        return true
   
  

}

