// 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 isNum(elm) {
    var pattern = /^[0-9]*$/;
	//alert ("isNum called for: " + elm.value);
	result = pattern.test(elm.value);
	//alert ("isNum 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;
}

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_checkworms(form) {
	// check for any scripts planted in the form fields
	var pattern = /<\s*script|object|applet|embed|form\s*>/;
	//alert("Checking for script worms");
	for (var i=0; i<form.elements.length; i++) {
		var val = form.elements[i].value, found=0;
		var uval = val.toLowerCase();
		if (pattern.test(uval)) {
			alert("Please don't try to plant scripting attacks in the form");
			form.elements[i].focus();
			return false;
			}	
			
		}
	return true;
}

function RGB_checkpass(form) {
	// check the two password fields are the same and between 6-12 alphanumeric chars characters
	var pattern = /[\w\W]{6,12}/;
	var p1, p2;
	p1 = form.password1.value;
	p2 = form.password2.value;
	//alert('Check Password called:\nP1= ' + p1 + '\nP2= ' + p2);

    if (!pattern.test(p1)) {
		alert('Password1 contains non alphanumeric characters or is not 6-12 characters long');
		form.password1.focus();
		return false;
	}
    if (!pattern.test(p2)) {
		alert('Password2 contains non alphanumeric characters or is not 6-12 characters long');
		form.password1.focus();
		return false;
	}
	if (p1.length != p2.length) {
		alert('Passwords are not the same length');
		form.password1.focus();
		return false;
	}
	if (p1 != p2) {
		alert('Passwords are not the same');
		form.password1.focus();
		return false;
	}
	//alert('passwords are OK');
	return true;
}

function RGB_checkdonation(form) {
	//var pattern = /^\d*(.\d{2})?$/;
	var pattern = /^\d*$/;
	//alert("RGB_checkdonation(form) called");
	
	// check that the donation is either from the dropdown menu or from the other box
	
	dondrop = form.donationdrop.value;
	donbox = form.donation.value;
	//alert ("Drop down=" + dondrop + "\nDonation=" + donbox);
	
	if (donbox == "") {
		// donation box is empty - make sure dropdown menu has been used
		if (dondrop == 0) {
			alert("Please enter your donation using either the from down menu or the donation box.\nThank you.");
			form.donation.focus();
			return false;
		}
		// set the donation field with the correct amount
		form.donation.value = dondrop;
		return true;
	} else {
		// check that they didn't use the drop down as well
		if (dondrop != 0) {
			if (dondrop == donbox) {return true;}
			alert("You have entered your donation using both the menu and the donation box.\nPlease use one or the other.\nThank you.");
			form.donation.focus();
			return false;
		}
		// check it is a valid amount
		if (!pattern.test(donbox)) {
			alert("The amount you have entered is not a valid amount.\nPlease enteras a whole number of puonds.\nThank you.");
			form.donation.focus();
			return false;
		}
		if (donbox < 5) {
			alert("The amount you have entered is ess than the minumum amount.\nPlease re-enter an amount of £5 or over\nThank you.");
			form.donation.focus();
			return false;
		}
		// set the donation field with the correct amount
		//form.donation.value = donbox;
	}
	
	// everything OK
	return true;			

}

function RGB_checkaccept(form) {
	// checks that the accept box has been ticked or not
	//alert("RGB_checkaccept called with value=" + form.accept.checked);
	if (!form.accept.checked) {
		return confirm('Please confirm that you have read and accepted our terms and conditions\nThank you.');
	}
	return true;
}

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('isNum')!=-1) { 
	  	 if (!isNum(elm)) errors+='- '+nm+' is not a valid  number.\n';
	  } else 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+'is not 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 == '');
}

