// JavaScript Document


function validateCurrSupplier(theForm, util) {
    var errstr = "";
    var radio_choice = false;

// alert("validateCurrSupplier : "+util);

    if (util == "gas") {
       if (theForm.CurElecSupplier.value.length == 0) {
  	     errstr += "* Current gas supplier\n";
       }	
	} else {
        if (theForm.CurElecSupplier.value.length == 0) {
  	       errstr += "* Current supplier\n";
        }
    }
    for (i=0; i<theForm.CurElecContract.length; i++) {
        if (theForm.CurElecContract[i].checked) {
	       radio_choice = true;
    	}
	}
	if (!radio_choice) {
	    errstr += "* Current contract situation\n";
	}
    if (theForm.CurElecContract[0].checked) {  // under contract
	    if (theForm.ElecExpiryDate.value.length == 0) {
            errstr += "* Contract renewal date\n";
		} else {
		    if ( !isDate(theForm.ElecExpiryDate.value)) {
			    errstr += "* invalid date: " + theForm.ElecExpiryDate.value;
				errstr += "\nFormat: DD/MM/YYYY\n";
			}
 			radio_choice = false;
	        for (i=0; i<theForm.contractdetail.length; i++) {
                if (theForm.contractdetail[i].checked) {
	                radio_choice = true;
				}
		    }
	        if (!radio_choice) {
	            errstr += "* Details of your current contract situation\n";
	        }			
        }
	}
    if (theForm.CurElecContract[1].checked) {  // no contract
 			radio_choice = false;
	        for (i=0; i<theForm.nocontractdetail.length; i++) {
                if (theForm.nocontractdetail[i].checked) {
	                radio_choice = true;
				}
		    }
	        if (!radio_choice) {
    		    errstr += "* Details of non-contractual situation\n";
	        }			
    }
	return errstr;
}

function isDate(sDate) {
   var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
     //alert ("checkdate ");
   if (re.test(sDate)) {
      var dArr = sDate.split("/");
	  var dd = dArr[0];
	  var mm = dArr[1];
	  var yyyy = dArr[2];
     // alert ("checkdate dd="+dd+" mm="+mm+" yyyy="+yyyy);

	  var usDate = dArr[1] + '/' + dArr[0] + '/' + dArr[2]; // uk -> us conversion dd/mm/yyyy -> mm/dd/yyyy
	//  alert ("usDate="+usDate);  
      var d = new Date(usDate);   // will return diff day month year for invalid dates
	  	                          
      return (d.getMonth() + 1 == mm) && (d.getDate() == dd) && (d.getFullYear() == yyyy);
   }
   else {
       return false;
   }
}

function validateSupplyDetails(theForm, util, ordertype) {

  // alert('sup'+util);                         
    errstr = '';
    if (theForm.company.value.length == 0) {
        errstr += "* Company\n";
    }
    if (ordertype == 'Order') {
        if (theForm.companyType.value == 0) {
            errstr += "* Company Type\n";
        }
        if (theForm.companyType.value == 'LTD' && theForm.companyRegNo.value.length < 6) {
            errstr += "* Ltd Company Registration Number\n";
        }
    }
    if (theForm.contact_name.value.length == 0) {
          errstr += "* Contact Name\n";
    }
    if (theForm.phone_office.value.length < 10) {
          errstr += "* Telephone\n";
    }
    // email1    
    if (theForm.email1.value.length == 0) {
         errstr += "* email\n";
    } else {
         errstr += checkEmail(theForm.email1.value);  
    }
    if (util == 'gas') {
        if (!validateMPR(theForm,false))
            errstr += '* MPR should be 7-10 digits\n';
    
       // if (theForm.totalaq.value.length == 0) {
       //       errstr += "* Annual consumption\n";
       //  }
    }
    if (theForm.supplyaddress.value.length == 0) {
           errstr += "* Supply Address\n";
    }
    if (theForm.supplypostcode.value.length == 0) {
          errstr += "* Supply Postcode\n";
    }
    else {
         errstr += checkPostcode(theForm.supplypostcode.value);
    }
    errstr += validateCurrSupplier(theForm, util);
    if (errstr != '') {
        alert("Please correct the following information: \n\n" + errstr);
        return false;
    }
    else {
        if (util == "elec" && ordertype == 'Order') {
//        errstr += validateUsage(theForm);
              return validateMPAN(theForm); 
        }
    }
    return true;
}

function validateLogin(theForm, util) {
                             
    errstr = ''; 
    if (theForm.email1.value.length == 0) {
         errstr += "* your email address\n";
    } 
    else {            
         errstr += checkEmail(theForm.email1.value);  
    }
    if (theForm.passwd.value.length == 0) {
          errstr += "* your password\n";
    }             
    if (errstr != '') {
        alert("Please correct the following information: \n\n" + errstr);
        return false;
    }
    return true;
}
    
function validateLead(theForm, util) {
                             
    errstr = ''; 
    if (theForm.company.value.length < 3) {
          errstr += "* Company\n";
    }             
    if (theForm.contact_name.value.length < 5) {
          errstr += "* Contact Name\n";
    }
    if (theForm.phone_office.value.length < 10) {
          errstr += "* Telephone\n";
    }
    if (theForm.email1.value.length < 6) {
           errstr += "* email\n";
    } else {
         errstr += checkEmail(theForm.email1.value);  
    }
    if (theForm.supplypostcode.value.length < 6) {
          errstr += "* Supply Postcode\n";
    }    
    else {
         errstr += checkPostcode(theForm.supplypostcode.value);
    }
    

 //   errstr += validateCurrSupplier(theForm, util);
    if (util == 'gas') {
       if (theForm.totalaq.value.length == 0) {
            errstr += "* Annual consumption\n";
       }
       else {
             if (checkNumeric(theForm.totalaq.value) != -1) {
                  errstr += "* Annual consumption is not numeric\n";
             }
             else {
                  if (theForm.totalaq.value.length > 8) {
                      errstr += "* Annual consumption is too large\n";
                  }
             }
       }
    }
    if (theForm.ElecExpiryDate.value.length > 0) {
        errstr += checkDate(theForm.ElecExpiryDate.value);;
    }   
    else {
        errstr += "* Please enter your contract renewal date\n";    
    }
    if (errstr != '') {
        alert("Please correct the following information: \n\n" + errstr);
        return false;
    }
    else {
        if (util == "elec") {
//        errstr += validateUsage(theForm);
              return validateMPAN(theForm); 
        }
    }
    return true;

}

function validatePostcode(theForm, util) {

// alert('POSTCODE '+theForm.supplypostcode.value);
    if (theForm.supplypostcode.value.length == 0) {
        errstr += "* Supply Postcode\n";
    }
    else {
        errstr += checkPostcode(theForm.supplypostcode.value);
    }
    if (errstr != '') {
        alert("Please correct the following information: \n\n" + errstr);
        return false;
    }
    return true;
}

// create a unique url for the form so that a previously cached page isn't loaded by browser

function forceReload(theForm, action, anchor)
{
    theForm.action = action +'&rnd=' + Math.floor(Math.random()*99999) + anchor;
    
    // alert(theForm.action);

}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year

var dtCh= "/";
var minYear=2008;
var maxYear=2020;

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 checkDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strDay=dtStr.substring(0,pos1)
    var strMonth=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    var error = "";
    
    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){
        error = "The date format should be : mm/dd/yyyy";
    }
    if (strMonth.length<1 || month<1 || month>12){
        error = "Please enter a valid month";
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        error = "Please enter a valid day";
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        error = "Please enter a valid 4 digit year between "+minYear+" and "+maxYear;
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        error = "Please enter a valid date";
    }
    return error;
}
