// JavaScript Document

function swapLinkImg(id) {
	document.getElementById('btn'+id).src = '/assets/images/link_btn_'+id+'_on.gif'
}

function swapLinkImgBack(id) {
	document.getElementById('btn'+id).src = '/assets/images/link_btn_'+id+'.gif'
}

function swapRightLinkImg(id) {
	document.getElementById('rbtn'+id).src = '/assets/images/right_btn_'+id+'_on.gif'
}

function swapRightLinkImgBack(id) {
	document.getElementById('rbtn'+id).src = '/assets/images/right_btn_'+id+'.gif'
}

// Get the cursor position in text field for formating currency
function doGetCaretPosition (ctrl) {
	var CaretPos = 0;
	// IE Support
	if (document.selection) {
		ctrl.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -ctrl.value.length);
		CaretPos = Sel.text.length;
	} else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
		// Firefox support
		CaretPos = ctrl.selectionStart;
	}
	return (CaretPos);
}

// Set the cursor position in text field for formating currency
function setCaretPosition(ctrl, pos) {
	if(ctrl.setSelectionRange) {
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	} else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

// Adds Commas into a number e.g. 10,000
function formatCurrency(input, event) {
	var num = input.value.replace(/\,/g,'')
	var caret = doGetCaretPosition(input)
	var currentLength = input.value.length
	if(!isNaN(num)){
		if(num.indexOf('.') > -1){
			num = num.split('.');
			num[0] = num[0].toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
			if(num[1].length > 2){
				alert('You may only enter two decimals!');
				num[1] = num[1].substring(0,num[1].length-1);
			} 
			input.value = num[0]+'.'+num[1];
		} else{ 
			input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') };
			if (input.value.length < currentLength) { caret -= 1 }
			if (input.value.length > currentLength) { caret += 1 }
		} 		
	else { alert('You may enter only numbers in this field!');
		input.value = input.value.substring(0,input.value.length-1);		
	}
	setCaretPosition(input, caret)
}

// Checks if the key pressed was enter and submits form
function submitEnter(myfield,e,form) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
		
	if (keycode == 13) {
   		ajaxValidate('', form, 'all');
		return false;
	} else {
		return true;
	}
}

// Adds onblur events to day and month date elements
function addOnBlur1() {
	ajaxValidate(this, 'nomination', 'single');
}
function addOnBlur2() {
	ajaxValidate(this, 'nomination', 'single');
}

// AJAX functions for real time form validation
// form = form, inputField = individual input id on form (firstname, email, etc), extent = extent of validation (single = single inputs, all = whole form)
function ajaxValidate(inputField, form, extent) {
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Your browser does not support AJAX!");
		return;
	}
	
	var urlvars = "?form="+form+"&extent="+extent;
	var submitForm = "Y";
	
	if (extent == "all") {
		switch (form) {
			case "customer":
				var validateFields = new Array("title", "firstname", "surname", "add1", "town", "county", "postcode", "tel", "email", "instructions");				
				break;
			case "expert":
				var validateFields = new Array("title", "firstname", "surname", "clinic", "dept", "add1", "town", "county", "postcode", "tel", "email", "specialities", "fee_report_w_notes", "fee_report_wo_notes", "fee_non_attendance");
				break;
			case "nomination":
				var validateFields = new Array("title", "firstname", "surname", "add1", "town", "county", "postcode", "tel", "email", "client_title", "client_firstname", "client_surname", "client_add1", "client_town", "client_county", "client_postcode", "client_tel", "client_email", "accident_date_day", "accident_date_month", "accident_date_year", "accident_type", "specialist_required", "special_requirements", "insurer", "thirdparty_add1", "thirdparty_town", "thirdparty_county", "thirdparty_postcode", "thirdparty_tel", "thirdparty_email", "clients_records_req", "instructing_party_source_rec", "imr_source_rec", "source_rec_passed_to");
				break;
			case "contact":
				var validateFields = new Array("name", "email", "tel", "comments");
			break;
		}
		
		for (j=0;j<validateFields.length;j++) {
			urlvars += "&"+validateFields[j]+"="+document.getElementById(validateFields[j]).value;
		}		
	} else {
		var inputName = inputField.id
		var value = inputField.value;
		urlvars += "&"+inputName+"="+value
		
		// If checking source_rec_passed_to we need to include clients_records_req
		if (inputName == "source_rec_passed_to") {
			urlvars += "&clients_records_req="+document.getElementById("clients_records_req").value;
		}
		
		// If checking date of birth we need to include other 2 parameters e.g. Year entered we need to send Day and Month
		if (inputName == "accident_date_day" || inputName == "accident_date_month") {
			urlvars += "&accident_date_year="+document.getElementById("accident_date_year").value;
		}
		if (inputName == "accident_date_day" || inputName == "accident_date_year") {
			urlvars += "&accident_date_month="+document.getElementById("accident_date_month").value;
		}
		if (inputName == "accident_date_month" || inputName == "accident_date_year") {
			urlvars += "&accident_date_day="+document.getElementById("accident_date_day").value;
		}
	}
	
	var url="/validateForm.php"+urlvars;
		
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			var errorStr = xmlHttp.responseText;
			var errors = errorStr.split('##');			
			errors.splice(errors.length-1, 1);
			var formReadyToSubmit="Y";
			
			var dobValid = "";
			var dobError = "";
			
			for (i=0;i<errors.length;i++) {
				var error = errors[i].split('---');
				
				// Validate Dates seperate
				if (error[0] == "accident_date_day" || error[0] == "accident_date_month" || error[0] == "accident_date_year") {
					
					if (error[1] != 0) {
						dobValid = "N";
						dobError = error[1];
						formReadyToSubmit="N";
					} else if (dobValid != "N") {
						dobValid = "Y";
					}
					
				} else {
					// Validate Other Fields
					if (error[1] == 0) {

						document.getElementById(error[0]).className="validField";
						if (document.getElementById(error[0]+"_hint")) {
							document.getElementById(error[0]+"_hint").innerHTML="&nbsp;";
						}
						
					} else {

						document.getElementById(error[0]).className="invalidField";
						if (document.getElementById(error[0]+"_hint")) {
							document.getElementById(error[0]+"_hint").className="inputHint inputHint_invalid";
							document.getElementById(error[0]+"_hint").innerHTML="* "+error[1];
						}
						formReadyToSubmit="N";
					}
				}
			}
			
			// Handle Date Errors if they are being validated
			if (dobValid == "Y") {
				document.getElementById("accident_date_day").className="validField";
				document.getElementById("accident_date_month").className="validField";
				document.getElementById("accident_date_year").className="validField";
			} else if (dobValid == "N") {
				document.getElementById("accident_date_day").className="invalidField";
				document.getElementById("accident_date_month").className="invalidField";
				document.getElementById("accident_date_year").className="invalidField";
			}
			if (dobValid != "") {
				document.nominationForm.accident_date_day.onblur = addOnBlur1;
				document.nominationForm.accident_date_month.onblur = addOnBlur1;
			}
			
			
			if (extent=="all") {				
				if (formReadyToSubmit=="N") {
					alert('You have not filled in some fields correctly, please go back and correct the indicated fields.');
					return;
				} else {
					if (form == "customer") {
						document.customerForm.submit();
					} else if (form == "expert") {
						document.expertForm.submit();
					} else if (form == "nomination") {
						document.nominationForm.submit();
					} else if (form == "contact") {
						document.contactForm.submit();
					}
				}
			}
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);	
}

function GetXmlHttpObject() {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}