//+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
// JAVASCRIPT INCLUDE -- validate.js	
//+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
//
//  Script Author: Chris Merry  
//     
//	Description:   This script will validate any form data and enforce certain rules on the data entered via   
//				   regular expressions.		
//
//	Thanks to:	   Ben Clayton, Marc Woodhead :)													   
//
// (C) Chris Merry -- Do not copy this script in anyway without permission.  
//
//+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=

var errorTxt = "Some of the fields below are required or the information given is not valid.<BR>For more information, please move your mouse over the boxes highlighted in blue.";

var telnoRegxp = /^(^[0-9\+\(\)\- ]+)$/
var numericRegxp = /^([0-9.]+)$/;

var emailRegxp			=	/^([\w_-]+)(\.[\w_-]+)*@([\w_-]+)(\.[\w_-]*){0,1}(\.[a-zA-Z]{2,4}){1,2}$/; 
var pcodeRegxp 			=	/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {0,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/i;

var urlRegxp = /^((http|https):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i

var dateRegxp = /^([0-9]){1,2}\/{1}([0-9]){1,2}\/([0-9]){4}$/;
var timeRegxp = /^[0-9]{2}:{1}[0-9]{2}$/;
var twodigit = /^[0-9]{2}$/;
var fourdigit = /^[0-9]{4}$/;

var currencyRegxp = /^\d+(\.\d{1,2})?$/;
var passwordRegxp = /^[ a-z0-9]+$/i;
var usernameReqxp = /[a-zA-Z0-9]{6,20}/;

var ccnum = /^[\d]{4}/;
var maestro_num_1 = /^[\d]{6,8}/;
var maestro_num_2 = /^[\d]{10,15}/;
var sortcodeRegxp = /^[\d]{2}/;

var numericSCRegxp = /^[\d]{6}/;
var numericACRegxp = /^[\d]{8}/;

var Booking_Request_Flag = 0;
var errFlag = 0;
var warningFlag = 0;
var scrollheight = 0;

function verifylist(formobj,chklist){
	
	var good = new Array();
	var multiple_good = new Array();
	var alt_tags = new Array();
	var fail=0;

	var debug=0;
	var debugTxt="";

	var value="";
	for (var i=0; i<formobj.length; i++){
		var e=formobj.elements[i];

		var opt_flag = -1;
		var multi_flag = -1;

		var name = e.name;
		var val_type = chklist[name];

		if (!good[name]) good[name]=0;
		if(debug) debugTxt += "FIELD NAME: " + name;

		if(val_type){	
			if(debug) debugTxt += " - IN CHECKLIST ("+val_type+")";
			if	(isdisplayed(e)){					
				if(debug) debugTxt += " - VISIBLE\n";


				if(val_type.indexOf('opt~') != -1){
					//alert("OPTIONAL VALUE" + typ.replace(/opt_/,''));
					val_type = val_type.replace(/opt~/,'');
					opt_flag = 1;
				}

				//###############################################################
				var bits = validate_field_value(e,name,val_type,opt_flag);											// VALIDATE A SINGLE FORM ELEMENT
				good[name] = bits[0];
				alt_tags[name] = bits[1];
				//###############################################################

			}else{
				if(debug) debugTxt += " - INVISIBLE";
				good[name]=1; // hidden so say it is good													 
			}
		}else{
			if(debug) debugTxt += " - NOT IN CHECKLIST";
			good[name]=1; // not in list so say it is good													 
		}
		if(debug){
			if(good[name]){
				debugTxt += " - GOOD\n";
			}else{
				debugTxt += " - " + alt_tags[name] + " - ERROR\n";
			}
		}
	}

	if(debugTxt != '') alert(debugTxt);


	for (g in good){
		//alert("Name: "+g+"  Result: "+good[g]+"  Error txt: "+alt_tags[g]);
		if (good[g]==0){
			DispError(g,alt_tags[g]);
			fail = 1;
		}
		else if(good[g]==1){
			ClrError(g);
		}
	}

	// --- JUST FOR ESPRIT ---------------------------
	
//	var staff_select_result = check_staff_selects();
//	if(!staff_select_result && fail == 0){
//		errorTxt = "Some of the fields below are required or the information given is not valid.<br>Please ensure you have selected at least one staff member in the staff required section.";
//		fail = 1;
//	}
	// ------------------------------------------------
	
	if(!fail && Booking_Request_Flag){
		errorTxt = "The event date has already past are you sure this is correct?";
		fail = check_future_date_fields(fail);
	}
	
	if(!fail && Booking_Request_Flag){
		errorTxt = "Please ensure you have selected at least one staff member for your event.";
		fail = check_staff_members(fail);
	}


	display_error_dialogue(errorTxt,fail,1);
	return (fail)?false:true;
}


//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
//SUB FUNCTIONS
//#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

function check_staff_members(fail){
	var result = fail;
	var output_div = document.getElementById('output_container');
	if(output_div){
		var elements = output_div.getElementsByTagName("div");
		if(elements.length < 2){
			result = 1;
		}
	}
	return result;
}

function check_future_date_fields(fail){
	var day = document.getElementById('dd');
	var month = document.getElementById('mm');
	var year = document.getElementById('yyyy');
	var result = fail;
	if(day && month && year){
		//alert("Found all needed fields;");
		var today = new Date();
		var myDate = new Date;
		myDate.setDate(day.value);
		myDate.setMonth(month.value-1); // January = 0
		myDate.setFullYear(year.value);
		if(today > myDate){
			//alert("date has past!");
			var alt_tag = "This date has already passed.  Are you sure this is correct?";
			DispError('dd',alt_tag);
			DispError('mm',alt_tag);
			DispError('yyyy',alt_tag);
			result = 1;
		}
	}
	return result;
}

function check_staff_selects(){
	var name = "amount_required_";
	var val_type = "select-one";
	var cnt = 0;
	var results = new Array;
	do {
		var multi_name = name+cnt;
		var obj = document.getElementById(multi_name);
		if(obj) results = validate_field_value(obj,multi_name,val_type,0);
		if(results[0]) return true;
		cnt++;
	}	while (obj);
	return (cnt>1)?false:true;
}

function display_error_dialogue(error,fail,scroll){
	var errorDivObj = document.getElementById('form_error');
	if(errorDivObj){
		if(scroll) window.scrollTo(0,scrollheight);
		var display = (fail)?'block':'none';
		errorDivObj.style.display = display;
		errorDivObj.innerHTML = error;
	}
}

function validate_field_value(element,element_name,valtype,optional){
	var result = 0;
	var alt_tag = "";

	if(valtype != "wordcount" && valtype != "text" && valtype != 'pword'){
		value = element.value.replace(/ /g,'');
		if(valtype != "email"){
			value = value.replace(/\./g,'');
			value = value.replace(/,/g,'');
		}
	}else{
		value = element.value;
	}
	//====[ TEXT VALIDATION ]=============================================
	if (valtype=="text"){
		if ((optional != -1) && (value == '') || (value != "")&&(!isBlank(value))) {
			result=1;
		}else{
			alt_tag = "This is a required field";
		}
	}
	//====[ USERNAME VALIDATION ]=========================================
	else if(valtype == "username"){
		if (usernameReqxp.test(value) == true){
			result=1;
		}else{
			alt_tag = "Username can only contain letters and numbers and must be between 6 - 20 characters.";
		}
	}
	//====[ RADIO ]======================================================
	else if (valtype=="radio"){
		if (element.checked){
			result=1;
		}else{
			alt_tag="Please select at least one of these options";
		}
	}
	//====[ DATE ]=======================================================
	else if (valtype=="date"){
		if (dateRegxp.test(value) == true || (optional != -1 && value == '')){
			result=1; 
		}else{ 
			alt_tag = "Date format must be eg. dd/mm/yyyy";
		}
	}
	//====[ FUTURE DATE ]================================================
	else if (valtype=="futuredate"){
		// MOVED
	}
	//====[ DAY ]======================================================
	else if (valtype=="day"){
		if ((twodigit.test(value) == true && value > 0 && value <= 31) || (optional != -1 && value == '')){
			result=1; 
		}else{ 
			alt_tag = "You have entered an invalid day please ensure you have used the correct format 'dd'.";
		}
	}
	//====[ MONTH ]======================================================
	else if (valtype=="month"){
		if ((twodigit.test(value) == true && value > 0 && value < 13) || (optional != -1 && value == '')){
			result=1; 
		}else{ 
			alt_tag = "You have entered an invalid month please ensure you have used the correct format 'mm'.";
		}
	}
	//====[ YEAR ]======================================================
	else if (valtype=="year"){
		if ((fourdigit.test(value) == true && value < 3000 && value > 1900) || (optional != -1 && value == '')){
			result=1; 
		}else{ 
			alt_tag = "You have entered an invalid year please ensure you have used the correct format 'yyyy'.";
		}
	}
	//====[ TIME ]======================================================
	else if (valtype=="time"){

		if (timeRegxp.test(value) == true || (optional != -1 && value == '')){
			var bits = value.split(':');
			if(bits.length>1){
				if(bits[0] < 24){
					if(bits[1] < 60){	
						result = 1; 
					}else{
						alt_tag =  "You have entered an invalid time, minutes should be between 00-59 minutes.";					
					}
				}else{
					alt_tag =  "You have entered an invalid time, hours should be between 00-23 hours.";					
				}
			}
		}else{ 
			alt_tag = "Time format must be eg. hh:mm (24 hour format)";
		}
	}
	//====[ MINUTES ]======================================================
	else if (valtype=="mins"){
		if ((twodigit.test(value) == true && value < 60) || (optional != -1 && value == '')){
			result=1; 
		}else{ 
			alt_tag = "Entered times must be in a valid 24 hour format.";
		}
	}
	//====[ HOURS ]======================================================
	else if (valtype=="hours"){
		if ((twodigit.test(value) == true && value < 24) || (optional != -1 && value == '')){
			result=1; 
		}else{ 
			alt_tag = "Entered times must be in a valid 24 hour format.";
		}
	}
	//====[ NUMERIC ]===================================================
	else if (valtype=="numeric"){
		if (numericRegxp.test(value) == true || (optional != -1 && value == '')){
			result=1; 
		}else{
			alt_tag = "Should only contain digits eg. 1234";
		}
	}
	//====[ SORTCODE ]===================================================
	else if (valtype=="numeric_sc"){
		if (numericSCRegxp.test(value) == true || (optional != -1 && value == '')){
			result=1; 
		}else{
			alt_tag = "Sort code should contain 6 digits eg. 123456";
		}
	}
	//====[ ACCOUNT NUMBER ]===================================================
	else if (valtype=="numeric_ac"){
		if (numericACRegxp.test(value) == true || (optional != -1 && value == '')){
			result=1; 
		}else{
			alt_tag = "Account number should contain 8 digits eg. 12345678";
		}
	}
	//====[ CENTIMETERS ]===============================================
	else if (valtype=="cm"){
		value = value.replace(/cm/,'');
		if (numericRegxp.test(value) == true){
			result=1; 
		}else{
			alt_tag = "This should be a measurement value in cm   eg. 100cm";
		}
	}
	//====[ CURRENCY ]==================================================
	else if (valtype=="currency"){
		if (currencyRegxp.test(value) == true || (optional != -1 && value == '')){
			result=1; 
		}else{ 
			alt_tag = "Must contain a positive currency value eg. 10.99"; 
		}
	}
	//====[ CHECKBOX ]==================================================
	else if (valtype=="checkbox"){
		result=1;
	}
	//====[ SELECT-ONE ]================================================
	else if (valtype=="select-one"){
		if (element.value != "-1"){
			result = 1;
		}else{
			alt_tag = "Please select a value from the pulldown menu";
			result = 0;
		}
	}
	//====[ POSTCODE ]=================================================
	else if (valtype=="postcode"){
		if (pcodeRegxp.test(value) == true){
			result=1; 
		}else{ 
			alt_tag = "Please ensure the postcode you have entered is valid"; 
		}
	}
	//====[ TELEPHONE ]=================================================
	else if (valtype=="telephone"){
		value = value.replace(/ /g, '');
		if (telnoRegxp.test(value) == true){
			result=1; 
		}else{ 
			alt_tag = "Please ensure this is a valid phone number."; 
		}
	}
	//====[ WEBSITE ADDRESS ]===========================================
	else if (valtype=="http"){
		if (urlRegxp.test(value) == true){
			result=1;
		}else{
			alt_tag = "Please ensure you have entered a valid web address.";
		}
	}
	//====[ EMAIL ]=====================================================
	else if (valtype=="email"){
		if (emailRegxp.test(value) == true){
			var confObj = document.getElementById('conf_'+element_name);
			if(confObj){
				result = (confObj.value == value)?1:0;
				//good['conf_'+element_name] = result;
				alt_tag = (result)?"":"Please ensure both email address fields are the same.";
				//alt_tags['conf_'+element_name] = alt_tag;
			}else{
				alt_tag = "";
				result=1;
			}
		}else{ 
			alt_tag = "Ensure this is a valid email address eg. somebody@domain.co.uk"; 
		}
	}
	//====[ PASSWORD ]=====================================================
	else if (valtype=="pword"){
		if (passwordRegxp.test(value) == true){
			var confObj = document.getElementById('conf_'+element_name);
			if(confObj){
				result = (confObj.value == value)?1:0;
				//good['conf_'+element_name] = result;
				alt_tag = (result)?"":"Please ensure both password fields are the same.";
				//alt_tags['conf_'+element_name] = alt_tag;
			}else{
				alt_tag = "";
				result=1;
			}
		}else{ 
			alt_tag = "Please ensure your password contains both letters and numbers."; 
		}
	}
	//====[ CREDIT CARD NUMBER ]=========================================
	else if(valtype=="ccnum"){
		if (ccnum.test(value) == true){
			result=1; 
		}else{ 
			alt_tag = "Ensure your credit card number is valid.";
		}
	}
	//====[ SWICTH CARD VALIDATION ]=====================================
	else if(valtype=="maestro_num_1"){
		if (maestro_num_1.test(value) == true){ result=1; }else{ alt_tag = "Ensure this is only the first part of your card number eg. (XXXXXX) - XXXXXXXXXXX"; }
	}
	else if(valtype=="maestro_num_2"){
		if (maestro_num_2.test(value) == true){ result=1; }else{ alt_tag = "Ensure this is only the second part of your card number eg. XXXXXX - (XXXXXXXXXXX)"; }
	}
	//====[ SWITCH CARD VALIDATION ]=====================================
	else if (valtype=="sortcode"){
		if (sortcodeRegxp.test(value) == true){ result=1; }else{ alt_tag = "Ensure your sort code is valid eg. 40-10-19"; }
	}
	//====[ NO VALIDATION TYPE FOUND ]===================================
	else{
		alert('Element ('+element_name+') has unknown validation type! ('+valtype+')');
		result=1; 
	}
	return [result,alt_tag];
}

function dump(obj){
	alert(obj);
	var sd="";
	var n=0;
	for (var p in obj){
		sd += p + " = " + obj[p] + "\n";
		
		n++;
		if (n>10){
			alert(sd);
			sd="";
			n=0;
		}
	}
	alert(sd);
}

//===========================================================

function ClrError(name){
	var obj = document.getElementById(name);
	if(obj){
		if(obj.className.indexOf('_err') != -1){
			obj.className = obj.className.replace(/_err/,'');
			obj.title = "";
			obj.alt = "";
		}
	}
}

//===========================================================

function DispError(name,alt_tag){
	var obj = document.getElementById(name);
	//alert("objname="+name+" obj="+obj);
	if(obj){
		if(obj.className.indexOf('_err') == -1){
			obj.className = obj.className + "_err";
			//alert("objname="+name+" classname="+obj.className);
			//alert(alt_tag);
			if(alt_tag){
				obj.title = alt_tag;
				obj.alt = alt_tag;
			}
		}
	}
}

//=============================================================================

function isdisplayed(node){

	//This function is used to see if an INPUT is currently being displayed
	// ONLY looking for a encompassing DIV with a style including display:block or display:none
	// test with something like this:
	//       alert(isdisplayed(document.getElementById("surname")))
	var n=0;
	var fnd=0;
	while (fnd==0){
		if(n>1) { node = node.parentNode; }
		if (node){
			if (node.style){
				if (node.style.display){
					//alert(node.style.display);
					if (node.style.display=='block'){
						fnd=0;
						//return true;
					}
					if (node.style.display=='none'){
						fnd=1;
						//return false;
					}
				}
			}
		}else{
			fnd=3;
		}
		if (n>20){
			return true;
		}
		n++;
	}
	if(fnd==1){
		return false;
	}
	if(fnd==0||fnd==3){
		return true;
	}
}

//===========================================================

function submitForm(formobj,list){
	if(verifylist(formobj,list)){
		formobj.submit();
	}
}

//===========================================================

function setCheckBox(name,current,frmname){
	var checks;
	if(document.forms[frmname][name]){
		checks =document.forms[frmname][name];
		var i=-1;
		for (var x=0;x<checks.length;x++ ){
			if (checks[x].value == current) i=x;
		}
		if(i == 1){ 
			checks[i].checked=1;
		}
	}else{
		alert("setCheckBox - control not found = "+name);
	}
}	

//===========================================================

function setRadioIndex(name,current){
	var rads;
	if(document.getElementsByName(name)){
		rads=document.getElementsByName(name);
		var i=-1;
		for (var x=0;x<rads.length;x++ ){
			if (rads[x].value == current) i=x;
		}
		if(i != -1){ 
			rads[i].checked=1; 
			rads[i].click();
		}
	}else{
		alert("setRadioIndex - control not found = "+name);
	}
}	

//===========================================================

function setSelectIndex(name,current,frmname){						
	var ops;
	//alert('Set val: '+current);
	//alert('Name: ' + name + "  Current: " + current + "  Formname:" +frmname);
	if(document.forms[frmname][name]){	
		ops=document.getElementById(name).options;
		obj=document.getElementById(name);
		if(ops){
			var i=-1;
			var multi_set = current.split(',');
			//alert('Amount: '+multi_set.length);
			for (var x=0;x<ops.length;x++ ){
				for (var y=0;y<multi_set.length;y++){
					if(ops[x].value == multi_set[y]){
						ops[x].selected	= true;
						i = x;
					}
				}
			}
			if(i != -1){ 
				//ops.selectedIndex=i;
				if(obj.onchange) obj.onchange();
				ops[0].selected	= false;
			}
		}
	}else{
		alert("setSelectIndex - control not found = "+name);
	}
}
	