var readOnlyText = "[Please select Course and Location]";
		
var requiredFields = [ "txtCompany", "txtContactName", "txtAccountName", "txtContactEmail", "txtAccountEmail", "txtPostStreet", "txtPostCity", "txtPostCode", "txtContactPhone", "txtContactFax", "txtAccountPhone", "txtAccountFax" ];
var emailFields = [ "txtContactEmail", "txtAccountEmail" ];

var courseDetails = {};

var fieldDescriptions = {
	'txtCompany' : 'Company Name',
	'txtContactName' : 'Name (Contact Person)',
	'txtAccountName' : 'Name (Accounts Payable)',
	'txtContactEmail' : 'Email (Contact Person)',
	'txtAccountEmail' : 'Email (Accounts Payable)',
	'txtPostStreet' : 'Street (Postal Address)',
	'txtPostCity' : 'City (Postal Address)',
	'txtState' : ' State (Postal Address)',
	'txtPostCode' : 'Post Code (Postal Address)',
	'txtContactPhone' : 'Phone (Contact Person)',
	'txtContactFax' : 'Fax (Contact Person)',
	'txtAccountPhone' : 'Phone (Accounts Payable)',
	'txtAccountFax' : 'Fax (Accounts Payable)'
};

var emailPattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

function persistState()
{
	window.location.hash = $('txtLocation').value + "|" + $('txtCourseDetails').value + "|" + $('txtDates').value;
}

var initCourse = null;
var initDate = null;

function loadState()
{
	var state = window.location.hash.split("|");
	if (state.length > 0)
	{
		var locid = null;
		var cid = null;
		var dt = null;
		
		if(Prototype.Browser.IE)
			locid = state[0].substring(1); //strip hash
		else
			locid = state[0];
		if (state.length >= 2)
			cid = state[1];
			
		if (state.length == 3)
			dt = state[2];	
		
		initCourse = cid;
		initDate = dt;
		setSelectedValue($('txtLocation'), locid);
	}
}

function validateEmail(value)
{
	return value.match(emailPattern);
}

function setFormValue(field, value)
{
	$(field).value = value;
}

function getFormValue(field)
{
	return $(field).value;
}

function notNullOrEmpty(value)
{
	return value && value.length > 0;
}

function flagInvalid(field)
{
	if(!Element.hasClassName(field, 'textbox-invalid'))
		Element.toggleClassName(field, 'textbox-invalid');
}

function resetFormValidState()
{
	for(var i = 0; i < requiredFields.length; i++)
	{
		Element.toggleClassName(requiredFields[i], 'textbox');
	}
	
	for(var i = 0; i < emailFields.length; i++)
	{
		Element.toggleClassName(emailFields[i], 'textbox');
	}
}

function clearCourseFields()
{
/*
	$("txtCourseDetails").value = readOnlyText;
	$("txtCourseCode").value = readOnlyText;
	$("scheduleid").value = "";
	$("txtPrice").value = readOnlyText;
	$("txtTime").value = readOnlyText;
	$("txtDates").value = readOnlyText;
	$("txtLocation").value = readOnlyText;
*/
}

function countParticipants()
{
	var count = 0;
	for(var i = 1; i <= 6; i++)
	{
		var el = "participant" + i;
		var fld = $(el);
		if(fld && notNullOrEmpty(fld.value))
			count++;
	}
	return count;
}

function validate() 
{
	var messages = [];
	var valid = true;
	resetFormValidState();
	var cid = $("scheduleid").value;
	if(!notNullOrEmpty(cid))
	{
		messages.push("No course selected");
	}
	
	for(var i = 0; i < requiredFields.length; i++)
	{
		if(!notNullOrEmpty(getFormValue(requiredFields[i])))
		{
			flagInvalid(requiredFields[i]);
			var fldName = fieldDescriptions[requiredFields[i]];
			messages.push(fldName + ": Field is required");
		}
	}
	
	for(var i = 0; i < emailFields.length; i++)
	{
		var f = $(emailFields[i]);
		if(f)
		{
			if(!validateEmail(f.value))
			{
				flagInvalid(emailFields[i]);
				var fldName = fieldDescriptions[emailFields[i]];
				messages.push(fldName + ": Not a valid email");
			}
		}
	}
	
	var count = countParticipants();
	if(count == 0)
		messages.push("Please enter at least one particiant");
	
	if(messages.length > 0)
		alert("Some fields entered are invalid. Please correct them\n\n" + messages.join("\n"));
	else
		$("btnSubmit").disabled = true;
		
	return messages.length == 0;
}

function updateSubmissionState() {
	var validCourse = isValidCourseChoice();
	if(validCourse && $("chkAgree").checked)
		$("btnSubmit").disabled = false;
	else
		$("btnSubmit").disabled = true;
}

function reloadCaptcha() {
	$("captcha").src = 'securimage/securimage_show.php?' + Math.random();
	return false;
}

var LOCID_NZ = "5";
var NULL_VALUE = "-1";
var OPT_LOADING = '<option value="'+NULL_VALUE+'" selected="selected">Loading ...</option>';

function onLocationChanged() {
	var locid = $('txtLocation').value;
	if(locid != NULL_VALUE)
	{
		if(locid == LOCID_NZ) {
			$('txtState').value = "";
			$('txtState').disabled = true;
			if(!$('txtState').hasClassName('textbox-disabled'))
				$('txtState').toggleClassName('textbox-disabled');
		} else {
			$('txtState').disabled = false;
			if($('txtState').hasClassName('textbox-disabled'))
				$('txtState').toggleClassName('textbox-disabled');
		}
		$('txtCourseDetails').update(OPT_LOADING);
		new Ajax.Request('register_helper.php', {
			method: 'post',
			parameters: { 
				action: 'GETCOURSES',
				locationid: locid
			},
			onSuccess: function (transport) { 
				courseDetails = transport.responseText.evalJSON();
				setCourseOptions();
			},
			onFailure: function (transport) {
				alert(transport.responseText);
			}
		});
	}
}

function setCourseOptions() {
	var select = $('txtCourseDetails');
	select.update("");
	var options = [];
	for (var cid in courseDetails) {
		var opt = document.createElement("option");
		opt.value = courseDetails[cid].id;
		opt.text = courseDetails[cid].description;
		options.push(opt);
	}
	
	for (var i = 0; i < options.length; i++) {
		select.options.add(options[i]);
	}
	
	if (options.length > 0)
	{
		if(initCourse) {
			setSelectedValue(select, initCourse);
			initCourse = null;
			onCourseChanged();
		} else {
			select.selectedIndex = 0;
			onCourseChanged();
		}
	}
}

function setSelectedValue(sel, value) {
	if (!sel || !sel.options || sel.options.length == 0 || !value)
		return false;

	var idx = -1;
	for(var i = 0; i < sel.options.length; i++) {
		if (sel.options[i].value == value) {
			idx = i;
			break;
		}
	}
	if (idx == -1)
		return false;

	sel.selectedIndex = idx;
	return true;
}

function onCourseChanged() {
	var locid = $('txtLocation').value;
	var cid = $('txtCourseDetails').value;
	if(locid != NULL_VALUE && cid != NULL_VALUE)
	{
		$('txtTime').value = courseDetails[cid].time;
		$('txtPrice').value = courseDetails[cid].price + " (" + courseDetails[cid].currency + ")";
		$('txtDisclaimer').innerHTML = "*" + courseDetails[cid].disclaimer;
	
		$('txtDates').update(OPT_LOADING);
		new Ajax.Request('register_helper.php', {
			method: 'post',
			parameters: {
				action: 'GETDATES',
				locationid: locid,
				courseid: cid
			},
			onSuccess: function (transport) {
				$('txtDates').update(transport.responseText);
				if (initDate) {
					setSelectedValue($('txtDates'), initDate);
					initDate = null;
					onScheduleChanged();
				} else {
					onScheduleChanged();
				}
				updateSubmissionState();
				updateTotal();
			},
			onFailure: function (transport) {
				alert(transport.responseText);
			}
		});
	}
}

function onScheduleChanged() {
	var dt = $('txtDates').value;
	if (dt != NULL_VALUE) {
		$('scheduleid').value = dt;
	} else {
		$('scheduleid').value = null;
	}
}

function onAgreementChecked() {
	updateSubmissionState();
	persistState();
}

function isValidCourseChoice() {
	var locid = $('txtLocation').value;
	var cid = $('txtCourseDetails').value;
	var eventid = $('txtDates').value;
	return locid != NULL_VALUE && cid != NULL_VALUE && eventid != NULL_VALUE;
}

function applyInitialValues() {
	onScheduleChanged();
	updateSubmissionState();
}

function updateTotal() {
	var cid = $('txtCourseDetails').value;
	if(courseDetails[cid]) {
		var currency = courseDetails[cid].currency;
		var price = parseFloat(courseDetails[cid].price.substr(1));
		var count = 0;
		for(var i = 1; i < 7; i++) {
			var el = "participant" + i;
			if($(el).value.length > 0)
				count++;
		}
		$('lblTotal').innerHTML = "$" + (count * price) + " (" + currency + ")";
	}
}

function reloadCaptcha() {
	$('captcha').src = "securimage/securimage_show.php?sid=" + Math.random();
	$('captcha_code').value = "";
}

window.onload = function() {
	applyInitialValues();
	clearCourseFields();
	onLocationChanged();
	if (window.location.hash.length > 0)
		loadState();
	var url = $('captcha').src;
	if (url.length == 0)
		reloadCaptcha();
};

