/**********************/ /**********************/
// 2007-05-06: First release
// 2009-02-17: Revision to consolidate versions
/**********************/ /**********************/

// Welcome to AJAX - slightly modified version of http://www.hunlock.com/blogs/The_Ultimate_Ajax_Object
function ajaxObject(url, callbackFunction) {
	var that = this;      
	this.updating = false;
	this.abort = function() {
		if (that.updating) {
			that.updating = false;
			that.AJAX.abort();
			that.AJAX = null;
		}
	}
	this.update = function(passData,postMethod) { 
		if (that.updating) {
			return false;
		}
		that.AJAX = null;                          
		try {
			// Firefox, Opera 8.0+, Safari
			that.AJAX = new XMLHttpRequest();
		} catch (microsoftcompatible){
			// Internet Explorer
			try {
				that.AJAX = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (microsoftlegacy){
				that.AJAX = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		if (that.AJAX == null) {                             
			return false;                               
		} else {
			that.AJAX.onreadystatechange = function() {  
				if (that.AJAX.readyState == 4) {             
					that.updating = false;                
					that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
					that.AJAX = null;                                         
				}                                                      
			}                                                        
			that.updating = new Date();                              
			if (/post/i.test(postMethod)) {
				var uri = urlCall + '?' + that.updating.getTime();
				that.AJAX.open("POST", uri, true);
				that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				that.AJAX.setRequestHeader("Content-Length", passData.length);
				that.AJAX.send(passData);
			} else {
				var uri = urlCall + '?' + passData + '&timestamp=' + (that.updating.getTime()); 
				that.AJAX.open("GET", uri, true);                             
				that.AJAX.send(null);                                         
			}              
			return true;
		}                                                                           
	}
	var urlCall = url;        
	this.callback = callbackFunction || function () { };
}

// Loading...
function mcLoading(div_name){
	document.getElementById(div_name).innerHTML = "<div class=\"mc_loading\"><img src=\"media/onsight3/loading.gif\" /></div>\n";
}

// Tabs.
function mcTabs(grouping, alias_ID){
	xmlReply = new ajaxObject("extend/onsight3/@mcator.php", mcUpdate);
	xmlReply.update("mc_fn=mc_tabs&grouping=" + grouping, "GET");
	function mcUpdate(responseText){
		document.getElementById("mc_tabs").innerHTML = responseText;
	}
	mcLoading('mc_course_info');
	mcInfo(grouping, alias_ID);
}

// Course info.
function mcInfo(grouping, alias_ID){
	xmlReply = new ajaxObject("extend/onsight3/@mcator.php", mcUpdate);
	xmlReply.update("mc_fn=mc_info&grouping=" + grouping + "&alias_ID=" + alias_ID, "GET");
	function mcUpdate(responseText){
		document.getElementById("mc_course_info").innerHTML = responseText;
	}
	mcLoading('mc_calendar');
	mcCalendar(grouping, alias_ID, new Date());
}

// Calendar.
function mcCalendar(grouping, alias_ID, diary_date){
	diary_date = mcDate(diary_date);
	xmlReply = new ajaxObject("extend/onsight3/@mcator.php", mcUpdate);
	xmlReply.update("mc_fn=mc_calendar&grouping=" + grouping + "&alias_ID=" + alias_ID + "&diary_date=" + diary_date, "GET");
	function mcUpdate(responseText){
		// Get reply.
		document.getElementById("mc_calendar").innerHTML = responseText;
	}
	mcLoading('mc_availability');
	mcAvailability(grouping, alias_ID, diary_date);
}

// Availability.
function mcAvailability(grouping, alias_ID, diary_date){
	diary_date = mcDate(diary_date);
	xmlReply = new ajaxObject("extend/onsight3/@mcator.php", mcUpdate);
	xmlReply.update("mc_fn=mc_availability&grouping=" + grouping + "&alias_ID=" + alias_ID + "&diary_date=" + diary_date, "GET");
	function mcUpdate(responseText){
		document.getElementById("mc_availability").innerHTML = responseText;
	}
}

// Other stuff.
function mcDate(diary_date){
	diary_date = new Date(diary_date == "" ? "" : Date.parse(diary_date));
	diary_date = (diary_date > new Date() ? diary_date : new Date());
	diary_date_day = diary_date.getDate();
	diary_date_month = diary_date.getMonth() + 1;
	diary_date_year = diary_date.getFullYear();
	diary_date = diary_date_year + "/" + diary_date_month + "/" + diary_date_day;
	return diary_date;
}

// Add course to booking.
function mcSubmit(form_name){
	eval('document.' + form_name + '.submit();');	
}

// Vouchers.
function mcVoucher(){
	voucher_ID = document.getElementById("voucher_ID").value;
	booking_total = document.getElementById('booking_total').value;
	xmlReply = new ajaxObject("extend/onsight3/@mcator.php", mcUpdate);
	xmlReply.update("mc_fn=mc_voucher&voucher_ID=" + voucher_ID + "&booking_total=" + booking_total, "GET");
	function mcUpdate(responseText, responseStatus, responseXML){
		document.getElementById("voucher_value").value = responseXML.getElementsByTagName("voucher_value")[0].childNodes[0].nodeValue;
		document.getElementById("voucher_description").innerHTML = responseXML.getElementsByTagName("voucher_description")[0].childNodes[0].nodeValue;
		mcTotal();
	}
}

// Card types.
function mcCard(){
	subtotal = document.getElementById("subtotal").value;
	card_type_ID = document.getElementById("card_type_ID").value;
	xmlReply = new ajaxObject("extend/onsight3/@mcator.php", mcUpdate);
	xmlReply.update("mc_fn=mc_card_type&card_type_ID=" + card_type_ID + "&subtotal=" + subtotal, "GET");
	function mcUpdate(responseText, responseStatus, responseXML){
		document.getElementById("fee_fixed").value = responseXML.getElementsByTagName("fee_fixed")[0].childNodes[0].nodeValue;
		document.getElementById("fee_percent").value = responseXML.getElementsByTagName("fee_percent")[0].childNodes[0].nodeValue;
		mcTotal();
	}
}

// Work out totals.
function mcTotal(){
	booking_total = document.getElementById('booking_total').value;
	// Voucher.
	voucher_value = document.getElementById('voucher_value').value;
	if(voucher_value > 0){
		voucher_value = voucher_value * 1;	
	} else {
		voucher_value = 0;	
	}
	// Update totals.
	subtotal = (booking_total - voucher_value);
	subtotal = subtotal >= 0 ? subtotal : 0;
	document.getElementById('subtotal').value = subtotal.toFixed(2);
	// Cards.
	fee_fixed = document.getElementById('fee_fixed').value;
	fee_percent = document.getElementById('fee_percent').value;
	if(fee_fixed > 0){
		card_surcharge = fee_fixed * 1;	
	} else if (fee_percent > 0){
		card_surcharge = (subtotal * fee_percent / 100);
	} else {
		card_surcharge = 0;	
	}
	// Work out transaction amount.
	if(subtotal > 0){
		document.getElementById('transaction_amount').value = (subtotal + card_surcharge).toFixed(2);
	} else {
		document.getElementById('transaction_amount').value = subtotal.toFixed(2);
	}
}

// Validate booking form
function mcValidate(){
	num_transaction_amount = document.mc_booking.transaction_amount.value;
	str_first_name = document.mc_booking.customer_first_name.value;
	str_surname = document.mc_booking.customer_surname.value;
	str_email = document.mc_booking.customer_email.value;
	var opt_terms;
	for (i = 0; i < document.mc_booking.booking_terms.length; i++) {
		if (document.mc_booking.booking_terms[i].checked) {
			opt_terms = document.mc_booking.booking_terms[i].value;
		}
	}
	var opt_payment_method;
	if(document.mc_booking.admin){
		for (i = 0; i < document.mc_booking.payment_method.length; i++) {
			if (document.mc_booking.payment_method[i].checked) {
				opt_payment_method = document.mc_booking.payment_method[i].value;
			}
		}
	}
	regex_name = /^[a-zA-Z]+[a-zA-Z\s\'-]*[a-zA-Z\s\'-]*$/;
	regex_email = /^[a-zA-Z0-9]+[a-zA-Z0-9\._-]*@[a-zA-Z0-9]+[a-zA-Z0-9]+[a-zA-Z0-9\._-]*\.[a-zA-Z]{2,6}$/;
	str_alert = "";
	if(document.mc_booking.admin){
		if (opt_payment_method == "protx" && opt_terms != 1){
			str_alert += "For bookings through Protx, please make sure the customer has read our terms and conditions and check the box to accept\n";
		}
		if (!opt_payment_method){
			str_alert += "Please choose a payment method\n";
		}
		if (opt_payment_method == "protx" && !regex_email.test(str_email)){
			str_alert += "Please type in a valid email address\n";
		}
		if (isNaN(num_transaction_amount)){
			str_alert += "Please verify the booking total\n";
		}
		if (opt_payment_method == "protx" && num_transaction_amount < 1){
			alert("Please choose either 'till' or 'invoice' for totals of less than £1\n");
			return false;
		}
		if (num_transaction_amount <= 0){
			if(!confirm("The total amount for this transaction is zero - is this intentional?")){
				return false;	
			}
		}
	}
	if (!regex_name.test(str_first_name)){
		str_alert += "Please type in a valid first name\n";
	}
	if (!regex_name.test(str_surname)){
		str_alert += "Please type in a valid surname\n";
	}
	if (!document.mc_booking.admin && !regex_email.test(str_email)){
		str_alert += "Please type in a valid email address\n";
	}
	if (!document.mc_booking.admin && opt_terms != 1){
		str_alert += "Please read and accept our terms and conditions to proceed\n";
	}
	if (str_alert != ""){
		window.alert(str_alert);
		return false;
	}
	return true;
}
