// JavaScript Document
function isAlpha(elm) {
    var pattern = /^[a-zA-Z '-]*$/;
	//alert ("isAlpha called for: " + elm.value);
	result = pattern.test(elm.value);
	//alert ("isAlpha result: " + result);
    return result;
}    

function isEmail(elm) {
    var pattern = /^[a-zA-Z0-9.\_\- ]+\@[a-zA-Z0-9 \-\.\_]+\.([a-zA-Z]{2,3})$/;
	//alert("isEmail called with: " + elm);
    if (pattern.test(elm.value)) {
        return true;
    }
    else {
        return false;
    }
}    
function isPhone(elm) {
   var pattern = /([0-9 ()-])$/;
	//alert("IsPhone called with: " + elm);
    if (pattern.test(elm.value)) {
        return true;
    }
    else {
        return false;
    }
}   
 
// JavaScript Document
function checkdate(objName) {
var datefield = objName;
if (chkdate(objName) == false) {
datefield.select();
alert("That date is invalid.  Please try again.");
datefield.focus();
return false;
}
else {
return true;
   }
}
function chkdate(objName) {
//var strDatestyle = "US"; //United States date style
var strDatestyle = "EU";  //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
strDate = datefield.value;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
if (strYear.length == 2) {
strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
//alert("Valid date is: " + intday + " " + strMonthArray[intMonth-1] + " " + strYear);
datefield.value = intday + "/" + intMonth + "/" + strYear;
}
return true;
}
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}
function doDateCheck(from, to) {
if (Date.parse(from.value) <= Date.parse(to.value)) {
alert("The dates are valid.");
return true;
}
else {
if (from.value == "" || to.value == "") 
alert("Both dates must be entered.");
else 
alert("End date must occur after the Start date.");
   }
 return false;
}
//*************************************************
// Time checking
//*************************************************
function IsValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

//alert("IsValidTIme called for time: " + timeStr);

var timePat = /^(\d{1,2}):(\d{2})$/;
//var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
	return false;
	}
hour = matchArray[1];
minute = matchArray[2];
//second = matchArray[4];
//ampm = matchArray[6];

//if (second=="") { second = null; }
//if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
	//alert("Hour must be between 1 and 23.");
	return false;
	}
if (minute<0 || minute > 59) {
	//alert ("Minute must be between 0 and 59.");
	return false;
	}
return true;
}

function GetHour(timeStr) {

//alert("GetHour called for time: " + timeStr);

var timePat = /^(\d{1,2}):(\d{2})$/;
var hour, minute;
var matchArray = timeStr.match(timePat);
if (matchArray == null) {
	return -1;
	}
hour = matchArray[1];

if (hour < 0  || hour > 23) {
	//alert("Hour must be between 1 and 23.");
	return -1;
	}
return hour;
}
function GetMinute(timeStr) {

//alert("GetMinute called for time: " + timeStr);

var timePat = /^(\d{1,2}):(\d{2})$/;
var hour, minute;
var matchArray = timeStr.match(timePat);
if (matchArray == null) {
	return -1;
	}
minute = matchArray[2];

if (minute<0 || minute > 59) {
	//alert ("Minute must be between 0 and 59.");
	return -1;
	}
return minute;
}

function TimeAfter (elm1, elm2) {
	var h1,h2,m1,m2,ph1,ph2,pm1,pm2,hd,md;

// returns true if time in element 1 is after time in element 2
	
	ph1 = GetHour(elm1.value);
	pm1 = GetMinute(elm1.value);
	ph2 = GetHour(elm2.value);
	pm2 = GetMinute(elm2.value);
	
	// check that start time is before end time
	hd = ph2 - ph1;
	md = pm2 - pm1;
	
	if ((hd < 0) || ((hd == 0) && (md < 0)) ) {
		return true;
	} else {
		return false;
	}

}
//*************************************************
// Date checking
//*************************************************
function IsValidDate(dateStr) {
// Checks if time is in DD/MM/YY format.
// The seconds and AM/PM are optional.

var datePat = /^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/;

var matchArray = dateStr.match(datePat);
if (matchArray == null) {
alert("Date is not in a valid format.");
return false;
}
day = matchArray[1];
month = matchArray[2];
year = matchArray[3];

alert("Validating: " + day + "/" + month  + "/" + year);

if (day < 1  || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if  (month < 1 || month > 12 ) {
alert("Month must be between 1 and 12");
return false;
}
if (year < 0 && year > 99) {
alert ("Year must be between 0 and 99.");
return false;
}
return false;
}
//***********************
// Form checking functions
//**************************
function Chkrefperiodform(form) {
alert("Date checking called for " + form.refstart.value + " to " + form.refend.value); 

if (chkdate(form.refstart) == false) {
	alert("please enter valid start date in format: dd/mm/yy");
	form.refstart.focus();
	return false;
	} else
if (chkdate(form.refend) == false) {
	alert("please enter valid end date in format: dd/mm/yy");
	form.refend.focus();
	return false;
	}

alert("Date values: " + form.refstart.value + " to " + form.refend.value);

var datdiff = Date.parse(form.refend.value) - Date.parse(form.refstart.value);
if (datdiff <= 0){
	alert("Start Date must be before End date\nPlease check and renenter.");	
	form.refstart.focus();
	return false;
	}
var wkdiff = ((datdiff/(1000*60*60*24))+1)/7;
alert("No of weeks =" + wkdiff + "\nrefweeks = " + form.refweeks.value);
if (wkdiff != form.refweeks.value) {alert("Ref Period is not the right number of weeks"); form.refweeks.focus(); return false;}
else alert("Dates OK");	
return true;	
	
}	//end of Chkrefperiodform


function isReady(form) {
	var at = "@";
	var dot = ".";
	
	//alert("isReady called for " + form.name);
    if (form.fullname.value == "") {
        alert("Please enter your name.");
        form.fullname.focus();
        return false;
    } else
    if (isAlpha(form.fullname) == false) {
        alert("Please enter letters only for name.");
        form.fullname.focus();
        return false;
    } else
    if (form.phone.value == "") {
        alert("Please enter your contact telephone number.");
        form.phone.focus();
        return false;
    } else
    if (isPhone(form.phone) == false) {
        alert("Please enter numbers only for telephone.");
        form.phone.focus();
        return false;
    } else
    if (form.email.value == "") {
        alert("Please enter an email address.");
        form.email.focus();
        return false;
    } else
    if (isEmail(form.email) == false) {
        alert("Please enter a valid email address.");
        form.email.focus();
        return false;
    } else
	if (form.name == "bborderform") {
		if (form.bbphone.value == "") {
        	alert("Please enter your broadband telephone number.");
        	form.bbphone.focus();
        	return false;
    	} else
    	if (isPhone(form.bbphone) == false) {
        	alert("Please enter numbers only for broadband telephone number.");
        	form.bbphone.focus();
        	return false;
    	}  // end of bborderphone
	} // end of bborderform checks
	form.recipient.value = "info" + at + "redgreenblue" + dot + "co" + dot + "uk";
	//alert("Form OK. Sending to: " + form.recipient.value);
    return true;
}

function MM_callJS(jsStr) { //v2.0
  return eval(jsStr);
}

function RGB_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=RGB_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function RGB_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=RGB_validateForm.arguments;
  //alert("RGB Validateform called. Args = " + args);
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=RGB_findObj(args[i]);
    if (val) { nm=val.name; elm = val; if ((val=val.value)!="") {
		
      if (test.indexOf('isPhone')!=-1) { 
	  	 if (!isPhone(elm)) errors+='- '+nm+' is not a valid telephone number.\n';
      } else if (test.indexOf('isTime')!=-1) { 
	  	 if (!IsValidTime(val)) errors+='- '+nm+' is not a valid time. (hh:mm)\n';
      } else if (test.indexOf('isDate')!=-1) { 
	  	 if (!checkdate(elm)) errors+='- '+nm+' is not a valid date. (dd/mm/yy)\n';
      } else if (test.indexOf('isEmail')!=-1) { 
	  	 if (!isEmail(elm)) errors+='- '+nm+' must contain a valid e-mail address.\n';
	  	//p=val.indexOf('@');
        //if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } 
  if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function RGB_checktimefields(form) {
	var errors='';
	var lastPOA=0;
	
	wtype = RGB_findObj('type');
	
	if (wtype.value == 'work' || wtype.value == 'other')  {
	
		// Check start time is before end time
		stim = RGB_findObj('starttime');
		etim = RGB_findObj('endtime');
		
		if (TimeAfter(stim, etim)) {
			if (errors == '') {
				// set focus on first error field
				stim.focus();
				stim.select();
			}
			//alert('error in work time');
			errors += 'Start time is after end time\n';
		}
		
		// loop through all POA times checking them
		
		if (wtype.value == 'work') {
			
			// 19/08/2008 RGB Check all PoA times for normal driving work
			for (i = 1; i<=6; i+=1) {
				
				sPOA = RGB_findObj('sPOA'+i);
				//alert(sPOA.name+'='+sPOA.value);
				ePOA = RGB_findObj('ePOA'+i);
				//alert(ePOA.name+'='+ePOA.value);
				
				// check that the times aren't null and skip this iteration if so
				if (sPOA.value == '' && ePOA.value == '') {continue;}
				
				// check that start times isn't null and skip this iteration if so
				if ((sPOA.value == '') && (ePOA.value != '')) {
					if (errors == '') {
						// set focus on first error field
						sPOA.focus();
						sPOA.select();
					}
					errors += 'Missing starttime for '+sPOA.name+'\n';	
					continue;
				}
				
				// check that start times isn't null and skip this iteration if so
				if ((sPOA.value != '') && (ePOA.value == '')) {
					if (errors == '') {
						// set focus on first error field
						ePOA.focus();
						ePOA.select();
					}
					errors += 'Missing endtime for '+ePOA.name+'\n';	
					continue;
				}
				
			
				// Check start POAtime  is before end POA time 
				if (TimeAfter(sPOA, ePOA)) {
					if (errors == '') {
						// set focus on first error field
						sPOA.focus();
						sPOA.select();
					}
					//alert('error in POA'+i+' time');
					errors += 'Start POA'+i+' time is after end POA'+i+' time\n';
				}
		
				// Check start POAtime  isn't before Start work time 
				if (TimeAfter(stim, sPOA)) {
					if (errors == '') {
						// set focus on first error field
						sPOA.focus();
						sPOA.select();
					}
					//alert('error in POA'+i+' time');
					errors += 'Start POA'+i+' time is before start work time\n';
				}
				// Check start POAtime  isn't after end work time 
				if (TimeAfter(sPOA, etim)) {
					if (errors == '') {
						// set focus on first error field
						sPOA.focus();
						sPOA.select();
					}
					//alert('error in POA'+i+' time');
					errors += 'Start POA'+i+' time is after end work time\n';
				}
		
				// Check end POAtime  isn't before Start work time 
				if (TimeAfter(stim, ePOA)) {
					if (errors == '') {
						// set focus on first error field
						ePOA.focus();
						ePOA.select();
					}
					//alert('error in POA'+i+' time');
					errors += 'End POA'+i+' time is before start work time\n';
				}
				// Check end POAtime  isn't after end work time 
				if (TimeAfter(ePOA, etim)) {
					if (errors == '') {
						// set focus on first error field
						ePOA.focus();
						ePOA.select();
					}
					//alert('error in POA'+i+' time');
					errors += 'End POA'+i+' time is after end work time\n';
				}
				
				// check that the POA doesn't overlap the prevous one and is after it.
				if (lastPOA >= 1) {
					
					lPOA = RGB_findObj('ePOA'+lastPOA);
					
					if (TimeAfter(lPOA, sPOA)) {
						if (errors == '') {
							// set focus on first error field
							sPOA.focus();
							sPOA.select();
						}
						errors += 'POA'+i+' is before or overlaps POA'+lastPOA+'\n';
					}
				}
				// set last POA found for overlap checks next time round
				lastPOA = i;
			}
		} else if (wtype.value == 'other') {
			
			// 19/08/2008 RGB Set PoA1 to same as work time
			
			stim = RGB_findObj('starttime');
			etim = RGB_findObj('endtime');
			sPOA1 = RGB_findObj('sPOA1');
			ePOA1 = RGB_findObj('ePOA1');
			
			sPOA1.value = stim.value;
			ePOA1.value = etim.value;

		
			// 19/08/2008 RGB loop through rest of POA times clearing them 
			
			for (i = 2; i<=6; i+=1) {
				
				sPOA = RGB_findObj('sPOA'+i);
				ePOA = RGB_findObj('ePOA'+i);
				sPOA.value = "";
				ePOA.value = "";
			}
		
		}
	} else {
		
		// work type is sick, absent  or holiday
		
		stim = RGB_findObj('starttime');
		etim = RGB_findObj('endtime');
		
		stim.value = "09:00";
		etim.value = "17:00";
				
		// loop through all POA times clearing them 
			
		for (i = 1; i<=6; i+=1) {
			
			sPOA = RGB_findObj('sPOA'+i);
			ePOA = RGB_findObj('ePOA'+i);
			sPOA.value = "";
			ePOA.value = "";
		}
	
		btime = RGB_findObj('breaktime');
		btime.value = "";
	
	}
	

	if (errors !='') alert('The following error(s) occurred:\n'+errors);
	return (errors == '');	

} // end of RGB_checktimefields

function RGB_checkworktype (field) {
	
	var wt = field.value;
	//alert("worktype is: " + wt);
	stim = RGB_findObj('starttime');
	etim = RGB_findObj('endtime');
	btime = RGB_findObj('breaktime');
	
	if (wt == "sick" || wt == "holiday" || wt == "absent") {
		// set start end time to 8 hours
		stim.value = "09:00";
		stim.readOnly = true;
		etim.value = "17:00";
		etim.readOnly = true;
				
		// loop through all POA times clearing them
			
		for (i = 1; i<=6; i+=1) {
			
			sPOA = RGB_findObj('sPOA'+i);
			ePOA = RGB_findObj('ePOA'+i);
			sPOA.value = "";
			sPOA.readOnly = true;
			ePOA.value = "";
			ePOA.readOnly = true;
		}
	
		btime.value = "";
		btime.readOnly = true;

	} else if (wt == "other") {
		// 19/08/2008 RGB  for Other time make sure only the work time fields are writable
		stim.readOnly = false;
		etim.readOnly = false;
		btime.readOnly = true;
		btime.value = "";
		
		for (i = 1; i<=6; i+=1) {
			
			sPOA = RGB_findObj('sPOA'+i);
			ePOA = RGB_findObj('ePOA'+i);
			sPOA.readOnly = true;
			ePOA.readOnly = true;
		}
		stim.focus();
	} else if (wt == "work") {
		// for work time make sure all the fields are writable
		stim.readOnly = false;
		etim.readOnly = false;
		btime.readOnly = false;
		
		for (i = 1; i<=6; i+=1) {
			
			sPOA = RGB_findObj('sPOA'+i);
			ePOA = RGB_findObj('ePOA'+i);
			sPOA.readOnly = false;
			ePOA.readOnly = false;
		}
		stim.focus();
	}
		
		
	
	
} // end of RGB_checkworktype

function RGB_checkbox(form) {
	var checkstatus;
	checkstatus = form.declaration.checked;
	//alert('Checkbox called: '+ checkstatus);
	if (checkstatus) {
		form.drivhistory.value = form.drivhistory.value + "\n\r and " + form.drivtype.value + " time Declaration Downloaded";
	}
	return true;
}

