/***************************************************************************************************
 * This collection of functions provide a function to update a group of turnaround labels based on an
 * array of quantities and static attributes plus the control values of attributes in the form.
 **************************************************************************************************/

/***************************************************************************************************
 * Global variables used to manage the turnaround update.
 **************************************************************************************************/
var turnaroundListReq;
var turnaroundListDom;
var finishedUpdatingTurnarounds = true;
var reloadTurnarounds = false;
var turnaround_spinner_image = new Image();
var turnaround_spacer_image = new Image();
turnaround_spinner_image.src = '/images/spinner-clear.gif';
turnaround_spacer_image.src = '/images/spacer.gif';

/***************************************************************************************************
 * This function creates an XML TurnaroundListRequest string from the controls in the form.
 **************************************************************************************************/
function getTurnaroundListRequestXML(turntable_specs,form,callback)
{
	var xml = '';

// Start the request
	xml += '<'+"?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	xml += "<maverick>\n";

// Get the base form specs
	var base_job_attribute = getAttributesFromForm(form);

// Iterate over the turntable_specs
	for (var name in turntable_specs)
	{
	// Start the request
		xml += "<TurnaroundListRequest name=\""+name+"\"";
		if (callback)
			xml += ' callback="'+callback+'"';
		xml += ">\n";

	// Add the quantity
		xml += "<Quantity>"+turntable_specs[name]['qty']+"</Quantity>\n";

	// Get the specs
		var job_attribute = base_job_attribute;
		var override = turntable_specs[name]['job_attribute'];
		for (var i in override)
		{
			if (override[i])
				job_attribute[i] = override[i];
		}

	// Add the product
		xml += "<Product>"+job_attribute['product'][0]+"</Product>\n";

	// Add the specs
		xml += getAttributeList(job_attribute);

	// End request
		xml += "</TurnaroundListRequest>\n";
	}
	xml += "</maverick>\n";

	return xml;
}

/***************************************************************************************************
 * This function initializes the spinner image (if any) for the turnaround update.
 **************************************************************************************************/
function startTurnaroundListUpdate()
{
	finishedUpdatingTurnarounds = false;
	var turnaround_spinner = document.getElementById('turnaround_chart_spinner');
	if (turnaround_spinner)
		turnaround_spinner.src = turnaround_spinner_image.src;
}

/***************************************************************************************************
 * This function cleans up the spinner image (if any) after the turnaround update.
 **************************************************************************************************/
function endTurnaroundListUpdate()
{
	finishedUpdatingTurnarounds = true;
	var turnaround_spinner = document.getElementById('turnaround_chart_spinner');
	if (turnaround_spinner)
		turnaround_spinner.src = turnaround_spacer_image.src;
}

/***************************************************************************************************
 * This function provides an interface to updateTurnaround without a callback.
 **************************************************************************************************/
function updateTurnaroundList(turntable_specs,form)
{
	updateTurnaroundListWithCallback(turntable_specs,form,null);
}

/***************************************************************************************************
 * This function uses AJAX to get turnarounds for the table using the form with a callback.
 **************************************************************************************************/
function updateTurnaroundListWithCallback(turntable_specs,form,callback)
{
	if (!finishedUpdatingTurnarounds)
	{
		reloadTurnarounds = true;
		return;
	}
	startTurnaroundListUpdate();
	var xml_request = getTurnaroundListRequestXML(turntable_specs,form,callback);
//alert(xml_request);
	var url = get_base_url()+'/xml/turnaroundList.php';
	if (window.XMLHttpRequest)
	{
	// Non-IE browsers
		turnaroundListReq = new XMLHttpRequest();
		turnaroundListReq.onreadystatechange = processStateChangeTurnaroundList;
		try {
			turnaroundListReq.open("POST", url, true);
		} catch (e) {
			alert(e);
		}
		turnaroundListReq.setRequestHeader('Content-Type', 'text/xml');
		turnaroundListReq.send(xml_request);
	}
	else if (window.ActiveXObject)
	{
	// IE
		turnaroundListReq = new ActiveXObject("Microsoft.XMLHTTP");
		if (turnaroundListReq)
		{
			turnaroundListReq.onreadystatechange = processStateChangeTurnaroundList;
			turnaroundListReq.open("POST", url, true);
			turnaroundListReq.setRequestHeader('Content-Type', 'text/xml');
			turnaroundListReq.send(xml_request);
		}
	}
}

/***************************************************************************************************
 * This function indicates whether the most recent turnaround update has finished.
 **************************************************************************************************/
function isFinishedUpdatingTurnarounds()
{
	return 	(finishedUpdatingTurnarounds && !reloadTurnarounds);
}

/***************************************************************************************************
 * This function receives the UpdateTurnaround response and updates the turnaround labels. If an error was 
 * returned and there is an error label, set it. If a callback was requested, call it after the 
 * update.
 **************************************************************************************************/
function processStateChangeTurnaroundList()
{
	if (!turnaroundListReq)
		return;
	if (turnaroundListReq.readyState == 4)
	{
	// Complete
		if (turnaroundListReq.status == 200)
		{
		// OK response
			if (typeof turnaroundListReq.responseXML != 'undefined')
				turnaroundListDom = turnaroundListReq.responseXML;
			else
				parseXMLIntoDOM(turnaroundListReq.responseText);
//alert(turnaroundListReq.responseText);
			if (!turnaroundListDom)
			{
				endTurnaroundListUpdate();
				return;
			}

		// Iterate over the turnaround array, plugging in the answers into labels
			var maverick = turnaroundListDom.getElementsByTagName('maverick')[0];
			if (!maverick)
			{
//				alert(turnaroundListReq.responseText);
				blankTurnaroundList(turntable_specs,new Array());
				endTurnaroundListUpdate();
				return;
			}
			var turnaround_response = maverick.getElementsByTagName('TurnaroundListResponse')[0];
			if (!turnaround_response)
			{
//				alert(turnaroundListReq.responseText);
				blankTurnaroundList(turntable_specs,new Array());
				endTurnaroundListUpdate();
				return;
			}
//alert(turnaroundListReq.responseText);
			var callback = turnaround_response.getAttribute('callback');
			if (callback != null && callback != '' && callback.value) callback = callback.value;
			var turnarounds = turnaround_response.getElementsByTagName('Turnaround');
			var updated = new Array();
			var len = turnarounds.length;
			for (var i=0;i<len;i++)
			{
				var turnaround = turnarounds[i];
				var element_id = turnaround.getAttribute('name');
				if (!element_id)
					continue;
				var label = getElement(element_id);
				if (!label)
					continue;
				label.innerHTML = label.innerText = turnaround.firstChild.data.replace(',','');
				updated[element_id] = 1;
				var label = getElement(element_id+'_error');
				if (!label)
					continue;
				label.innerHTML = label.innerText = '';
			}
			var errors = turnaround_response.getElementsByTagName('Error');
			var len = errors.length;
			for (var i=0;i<len;i++)
			{
				var error = errors[i];
				var element_id = error.getAttribute('name');
				if (!element_id)
					continue;
				var label = getElement(element_id+'_error');
				if (!label)
					continue;
				label.innerHTML = label.innerText = (error != null && error.firstChild != null) ? error.firstChild.data : '';
			}
			blankTurnaroundList(turntable_specs,updated);
			endTurnaroundListUpdate();

		// Check to see if it should queue another request
			var qty = (document.getElementById('quantity')) ? document.getElementById('quantity') : document.getElementById('qty');
			if (reloadTurnarounds && qty)
			{
				reloadTurnarounds = false;
				if (callback)
					updateTurnaroundListWithCallback(turntable_specs,qty.form,callback);
				else
					updateTurnaroundList(turntable_specs,qty.form);
				return;
			}

		// If there's a callback specified, look for it and run it
			if (callback)
			{
			// Look for the function (defined outside of this file, of course)
				var callback_function = self[callback];
				if (callback_function)
					callback_function();
			}
		}
	}
}

/***************************************************************************************************
 * This function blanks out the turnaround list.
 **************************************************************************************************/
function blankTurnaroundList(turntable_specs,updated)
{
// Blank out the rest
	if (typeof turntable_specs != 'undefined')
	{
		for (var element_id in turntable_specs)
		{
			if (updated[element_id] == 1)
				continue;
			var label = getElement(element_id);
			if (!label)
				continue;
			label.innerHTML = label.innerText = '';
		}
	}
}

