var xmlHttp;
var reservations_by_date = [];
var total_registrant_fields = [];
var all_dates = [];
var authid;
var total_price = '';
var no_signup = false;

function createXMLHttpRequest(which)
{
	if(window.ActiveXObject)
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	else
		xmlHttp = new XMLHttpRequest();
}

//Replaces the first child of the given element with a new text node containing new_text,
//or adds a new text node if there are no children
function set_node_text(elt_id, new_text)
{
	elt = document.getElementById(elt_id);
	
	if(!elt)
		return;
	
	newTextNode = document.createTextNode(new_text);
	
	if(elt.childNodes[0])
		elt.replaceChild(newTextNode, elt.childNodes[0]);
	else
		elt.appendChild(newTextNode);
}

/*
 * prep_for_url()
 *
 * Converts ampersand characters to URL-safe versions
 *
 * @param	string	input		The input
 * @return	string				The output
 */
function prep_for_url(input)
{
	var output = input;
	output = output.replace(/\$/g, '%24');
	output = output.replace(/&/g, '%26');
	output = output.replace(/\+/g, '%2B');
	output = output.replace(/,/g, '%2C');
	output = output.replace(/\//g, '%2F');
	output = output.replace(/:/g, '%3A');
	output = output.replace(/=/g, '%3D');
	output = output.replace(/\?/g, '%3F');
	output = output.replace(/@/g, '%40');
	output = output.replace(/\s/g, '%20');
	output = output.replace(/"/g, '%22');
	output = output.replace(/</g, '%3C');
	output = output.replace(/>/g, '%3E');
	output = output.replace(/#/g, '%23');
	output = output.replace(/%/g, '%25');
	
	return output;
}

function toggle_pchart(a_elt, pchart_elt_id)
{
	curStyle = getStyleById(pchart_elt_id, 'display');
	
	if(curStyle == 'block')
		setStyleById(pchart_elt_id, 'display', 'none');
	else
		setStyleById(pchart_elt_id, 'display', 'block');
		
	if(curStyle == 'none')
		a_elt.childNodes[0].replaceData(0, 100, "Hide price chart");
	else
		a_elt.childNodes[0].replaceData(0, 100, "Purchase tickets");
}

function submit_addl_registrants()
{
	setStyleById('addl_registrants_ajax_loader', 'display', 'block');
	setStyleById('addl_registrants_submit_controls', 'display', 'none');

	createXMLHttpRequest();
	
	var url = "index.php?module=EventStore&func=submit_addl_registrants";
	
	for(var i=0; i<all_dates.length; i++)
	{
		var did = all_dates[i];
		var num_extra_fields = total_registrant_fields[did];
		var rid = reservations_by_date[did];
		
		url = url + '&rids[]=' + rid;
		
		for(var j=0; j<num_extra_fields; j++)
		{
			var firstname = document.getElementById('addl_registrants_' + did + '_' + j + '_fn').value;
			var lastname = document.getElementById('addl_registrants_' + did + '_' + j + '_ln').value;
			var email = document.getElementById('addl_registrants_' + did + '_' + j + '_em').value;
			
			url = url + '&fn_' + rid + '[' + j + ']=' + firstname
				+ '&ln_' + rid + '[' + j + ']=' + lastname
				+ '&em_' + rid + '[' + j + ']=' + email;
		}
	}
	
	url = url + '&authid=' + authid;
	url = url + "&theme=Blank";
	
	xmlHttp.onreadystatechange = handleStateChangeSubmitAddlReg;
	xmlHttp.open("GET", url, true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send(null);
}

function skip_addl_registrants()
{
	setStyleById('payment_submit', 'display', 'block');
	self.location.hash='payment_title';
}

//Handle state changes in the XMLHttpRequest object
function handleStateChangeSubmitAddlReg()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			//Do stuff with the returned data
			if(xmlHttp.responseXML)
				finish_addl_reservation_add(xmlHttp.responseXML.documentElement);
		}
	}
}

//Handle results of call to submit_addl_registrants
function finish_addl_reservation_add(xml)
{
	var result, new_authid, error, errormsg;
	
	if(xml.getElementsByTagName('Result')[0].firstChild)
		result = parseInt(xml.getElementsByTagName('Result')[0].firstChild.nodeValue);
	
	if(xml.getElementsByTagName('AuthID')[0].firstChild)
		new_authid = xml.getElementsByTagName('AuthID')[0].firstChild.nodeValue;
		
	if(xml.getElementsByTagName('Error')[0].firstChild)
		error = xml.getElementsByTagName('Error')[0].firstChild.nodeValue;
	
	if(xml.getElementsByTagName('ErrorMsg')[0].firstChild)
		errormsg = xml.getElementsByTagName('ErrorMsg')[0].firstChild.nodeValue;
	
	//Regardless of success or failure, we need a new authid for further action
	authid = new_authid;
	
	//Success reported	
	if(result)
	{
		setStyleById('payment_submit', 'display', 'block');
		setStyleById('addl_registrants_ajax_error', 'display', 'none');
		setStyleById('addl_registrants_ajax_loader', 'display', 'none');
		setStyleById('addl_registrants_success', 'display', 'block');
		setStyleById('addl_registrants_submit', 'display', 'none');
		setStyleById('addl_registrants_submit_controls', 'display', 'none');
	}
	
	//Error reported
	else
	{
		setStyleById('addl_registrants_ajax_error', 'display', 'block');
		
		switch(error)
		{
			case 'authid':
				set_node_text('addl_registrants_ajax_errormsg', "Bad authorization code sent to the server from this form. Please try submitting the request again.");
				break;
				
			case 'create':
				set_node_text('addl_registrants_ajax_errormsg', errormsg);
				break;
		}
		
		setStyleById('addl_registrants_submit_controls', 'display', 'block');
		setStyleById('addl_registrants_ajax_loader', 'display', 'none');
		setStyleById('payment_submit', 'display', 'block');
	}
	
	self.location.hash="addl_registrants_success";
}

/*
 * submit_payment()
 *
 * Initiates an AJAX request to the EventStore back end with payment information details
 *
 * @return	void
 */

function submit_payment()
{
	//Fetch data from the form
	var cc_number = document.getElementById('cc_number').value;
	var cc_type_elt = document.getElementById('cc_type');
	var cc_type = cc_type_elt.options[cc_type_elt.selectedIndex].value;
	var cc_expiration_month_elt = document.getElementById('cc_expiration_month');
	var cc_expiration_month = cc_expiration_month_elt.options[cc_expiration_month_elt.selectedIndex].value;
	var cc_expiration_year_elt = document.getElementById('cc_expiration_year');
	var cc_expiration_year = cc_expiration_year_elt.options[cc_expiration_year_elt.selectedIndex].value;
	var cc_security_code = document.getElementById('cc_security_code').value;

	var firstname = document.getElementById('customer_firstname').value;
	var lastname = document.getElementById('customer_lastname').value;
	var company = document.getElementById('customer_company').value;
	var phone = document.getElementById('customer_phone').value;
	var fax = document.getElementById('customer_fax').value;
	var address1 = document.getElementById('customer_address1').value;
	var address2 = document.getElementById('customer_address2').value;
	var city = document.getElementById('customer_city').value;
	var postal = document.getElementById('customer_postal').value;
	var country_elt = document.getElementById('customer_country');
	var country = country_elt.options[country_elt.selectedIndex].value;
	var province_elt = document.getElementById('customer_province');
	var province = province_elt.options[province_elt.selectedIndex].value;
	
	//Update visual indicators
	var submit_elt = document.getElementById('submit2');
	var ajax_indicator = document.getElementById('payment_ajax_loader');

	ajax_indicator.style.display = 'inline';
	submit_elt.disabled = true;
	submit_elt.value = "Processing payment...";

	//Initialize the XMLHttp request
	createXMLHttpRequest();
	
	//Set up the URL
	var url = "index.php?module=EventStore&func=process_cc"
		+ "&cc_type=" + cc_type
		+ "&cc_number=" + cc_number
		+ "&cc_expiration[month]=" + cc_expiration_month
		+ "&cc_expiration[year]=" + cc_expiration_year
		+ "&cc_security_code=" + cc_security_code
		+ "&no_signup=" + no_signup
		+ "&firstname=" + firstname
		+ "&lastname=" + lastname
		+ "&company=" + company
		+ "&phone=" + phone
		+ "&fax=" + fax
		+ "&address1=" + address1
		+ "&address2=" + address2
		+ "&city=" + city
		+ "&postal=" + postal
		+ "&country=" + country
		+ "&province=" + province
		+ "&authid=" + authid
		+ "&theme=Blank";	
		
	if(allow_non_ssl)
		url = "http://" + host + "/" + url;
	else
		url = "https://" + host + "/" + url;

	//Send the request
	xmlHttp.onreadystatechange = handleStateChangeSubmitPayment;
	xmlHttp.open("GET", url, true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send(null);
}

/*
 * handleStateChangeSubmitPayment()
 *
 * Called when the xmlHttp object initialized in submit_payment() changes state. When we reach state 4, with a return code
 * of 200, invoke finish_payment().
 *
 * @return	void
 */
function handleStateChangeSubmitPayment()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			//Do stuff with the returned data
			if(xmlHttp.responseXML)
				finish_payment(xmlHttp.responseXML.documentElement);
		}
	}
}

/*
 * finish_payment()
 *
 * Parse XML response sent by back end in response to request initiated in submit_payment(). Update
 * visual indicators on the page, depending on success or failure from the server. If successful,
 * redirect to index.php?module=EventStore&func=thankyou
 *
 * @param	object		xml			The root of the XML element parsed from the result returned by the EventStore backend
 * @return	void
 */
 
function finish_payment(xml)
{
	var result, new_authid, error, errormsg;
	
	if(xml.getElementsByTagName('Result')[0].firstChild)
		result = parseInt(xml.getElementsByTagName('Result')[0].firstChild.nodeValue);
	
	if(xml.getElementsByTagName('AuthID')[0].firstChild)
		new_authid = xml.getElementsByTagName('AuthID')[0].firstChild.nodeValue;
		
	if(xml.getElementsByTagName('Error')[0].firstChild)
		error = xml.getElementsByTagName('Error')[0].firstChild.nodeValue;
	
	if(xml.getElementsByTagName('ErrorMsg')[0].firstChild)
		errormsg = xml.getElementsByTagName('ErrorMsg')[0].firstChild.nodeValue;
	
	//Regardless of success or failure, we need a new authid for further action
	authid = new_authid;
	
	//Success reported	
	if(result)
	{
		//Update visual indicators
		var submit_elt = document.getElementById('submit2');
		var ajax_indicator = document.getElementById('payment_ajax_loader');
	
		ajax_indicator.style.display = 'none';
		submit_elt.disabled = true;
		submit_elt.value = "Payment complete!";
		
		location.href = "index.php?module=EventStore&func=thankyou";
	}
	
	//Error reported
	else
	{
		//Update visual indicators
		var submit_elt = document.getElementById('submit2');
		var ajax_indicator = document.getElementById('payment_ajax_loader');
		var ajax_error_indicator = document.getElementById('ajax_error_indicator');
	
		ajax_indicator.style.display = 'none';
		submit_elt.disabled = false;
		submit_elt.value = "Authorize payment of $" + total_price;
	
		switch(error)
		{
			case 'authid':
				set_node_text('payment_ajax_indicator_errormsg', "Bad authorization code sent to the server from this form. Please try submitting the request again.");
				break;
				
			default:
				set_node_text('payment_ajax_indicator_errormsg', errormsg);
				break;
		}
		
		ajax_error_indicator.style.display = 'block';
	}
}

function preview_events(sqldate, show_more_info)
{
	content = event_details[sqldate];
	
	if(!content || content.length == 0)
		return;
	
	contentReceiver = document.getElementById('ES_event_details');
	blockContentReceiver = document.getElementById('ES_minical_details');

	if(contentReceiver)
		receiverParent = contentReceiver.parentNode;
	else
		receiverParent = null;

	if(blockContentReceiver)
		blockReceiverParent = blockContentReceiver.parentNode;
	else
		blockReceiverParent = null;

	newContentReceiver = createTag('div', 'ES_event_details', '', 'ES_event_details_container');
	newBlockContentReceiver = createTag('div', 'ES_minical_details', '', 'ES_minical_details_container');

	first_entry = content[0];

	newDateHeader = createTag('h3', '', '' ,'');
	newDateText = document.createTextNode(first_entry['pretty_date']);
	newDateHeader.appendChild(newDateText);

	newContentReceiver.appendChild(newDateHeader);
	newBlockContentReceiver.appendChild(newDateHeader);

	for(i=0; i<content.length; i++)
	{
		event_data = content[i];
	
		newDetailReceiver = createTag('div', '', '', 'ES_event_detail');
		newBlockDetailReceiver = createTag('div', '', '', 'ES_minical_detail');
		
		newBold = createTag('strong', '', '', '');
		newBlockBold = createTag('strong', '', '', '');
		
		newDetailReceiver.appendChild(newBold);
		newBlockDetailReceiver.appendChild(newBlockBold);
		
		newTimeTitleText = document.createTextNode(event_data['start_time'] + ": " + event_data['title']);
		newBlockTimeTitleText = document.createTextNode(event_data['start_time'] + ": " + event_data['title']);

		newBold.appendChild(newTimeTitleText);
		newBlockBold.appendChild(newBlockTimeTitleText);
		
		newBR = createTag('br', '', '', '');
		newBlockBR = createTag('br', '', '', '');
		
		newDetailReceiver.appendChild(newBR);
		newBlockDetailReceiver.appendChild(newBlockBR);
		
		newLink = createTag('a', '', '', '');
		newBlockLink = createTag('a', '', '', '');
		
		newLink.href = event_data['link'];
		newBlockLink.href = event_data['link'];

		if(show_more_info)
		{
			newLinkText = document.createTextNode('More Info');
			newBlockLinkText = document.createTextNode('More Info');
			
			newLink.appendChild(newLinkText);
			newBlockLink.appendChild(newBlockLinkText);
		}
		
		newDetailReceiver.appendChild(newLink);
		newBlockDetailReceiver.appendChild(newBlockLink);
		
		newContentReceiver.appendChild(newDetailReceiver);
		newBlockContentReceiver.appendChild(newBlockDetailReceiver);
	}
	
	if(receiverParent != null)
		receiverParent.replaceChild(newContentReceiver, contentReceiver);
	
	if(blockReceiverParent != null)
		blockReceiverParent.replaceChild(newBlockContentReceiver, blockContentReceiver);

	return;
}

function createTag(tag_type, tag_id, tag_name, style_class)
{
	newTag = document.createElement(tag_type);
	newTag.className = style_class;
	newTag.id = tag_id;
	newTag.name = tag_name
	
	return newTag;
}
