/* FUNCTIONS FOR THE ASYNC FLIGHT LIVE PRICE */
function getResult()
{
	var xmlhttp=false;
	try 
	{
		xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
	} 
	catch (e) 
	{
		try 
		{
			xmlhttp = new
			ActiveXObject('Microsoft.XMLHTTP');
		} 
		catch (E)
		{
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
	{
		xmlhttp = new XMLHttpRequest();
	}
	xmlhttp.onreadystatechange=function() 
	{
		if (xmlhttp.readyState == 4  && xmlhttp.status == 200) 
		{ 
			var content = xmlhttp.responseXML;
			var root = content.documentElement;
			
			if(!root || (root.nodeName == 'Errors' && root.hasChildNodes()))
			{
				nds=root.childNodes;
				var len = nds.length;
				
				for (var i = 0; i < len; i++)
				{	
					if(nds[i].nodeName == 'ErrorMessage')
					{
						url = nds[i].getAttribute("Error");
					}
				}
				

				alert('Unfortunately, the flight you selected is no longer available.\nPress Ok to go back to the Flight Results page.');
				setTimeout(redirectToFlightResults(url),1000);	
			}
			
			
			for (var i = document.getElementById('price_breakdown_live_price').rows.length - 1; i >= 0; i--)
			{
				document.getElementById('price_breakdown_live_price').tBodies[0].deleteRow(i);
			}

				
			if(root.hasChildNodes()) 
			{
				nds=root.childNodes;
				var len = nds.length;
				var NumberOfAdults = 0;
				var NumberOfChildren = 0;
				var total = 0;
				for (var i = 0; i < len; i++)
				{	
					if(nds[i].nodeName == 'Details')
					{
						addRowPriceBreakDown('price_breakdown_live_price', nds[i].getAttribute("PriceDescription"), nds[i].getAttribute("UnitCostPence"), nds[i].getAttribute("Quantity"));
					}
					else if(nds[i].nodeName == 'TravelDetails')
					{
						if (document.getElementById('flight_operator'))
						{
							if (nds[i].getAttribute("OperatorLogo"))
							{
								document.getElementById('flight_operator').innerHTML = '<img src="' + nds[i].getAttribute("OperatorLogo") + '" alt="' + nds[i].getAttribute("OperatorName") + '" />';
							}
							else
							{
								document.getElementById('flight_operator').innerHTML = nds[i].getAttribute("OperatorName");
							}
						}				
					}
					else if(nds[i].nodeName == 'Passengers')
					{
						NumberOfAdults = nds[i].getAttribute("NumberOfAdults") * 1; // Ensure it is an integer
						NumberOfChildren = nds[i].getAttribute("NumberOfChildren") * 1; // Ensure it is an integer
						NumberOfInfants = nds[i].getAttribute("NumberOfInfants") * 1; // Ensure it is an integer
					}
					else if(nds[i].nodeName == 'DepartureDateString')
					{
						document.getElementById('traveldetails').tBodies[0].rows[2].cells[1].innerHTML 
							= '<strong>'+ nds[i].getAttribute("Value") + '</strong>';
					}
					else if (nds[i].nodeName == 'ReturnDateString')
					{
						document.getElementById('traveldetails').tBodies[0].rows[3].cells[1].innerHTML 
							= '<strong>'+ nds[i].getAttribute("Value") + '</strong>';
					}
					else if (nds[i].nodeName == 'TotalCostPounds')
					{
						total = nds[i].getAttribute("Value") * 1; // Ensure it is an integer
					}
				}
				
				addRowTotal('price_breakdown_live_price', 'Total:', total);
				updateTotalHoliday(total, NumberOfAdults, NumberOfChildren);
			}
			
			document.getElementById('updating_live_price_message').style.display = 'none';
			document.getElementById('updating_live_price_message_outer').style.height = '0px';
		}
	}
	var hash = getUrlVars();
	var itinerary_id = hash['itinerary_id'];
	var url = '/fetch_opts.php?mode=async_flight';
	document.getElementById('updating_live_price_message').style.display = 'block';
	xmlhttp.open('GET', url, true);
	xmlhttp.send(null)
	return;
}

function getUrlVars()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
return vars;
}

function redirectToFlightResults(url)
{
	if(!url)
	{
		var urlPart = getUrlVars();
		var packagetype = urlPart['packagetype'];
		var departure = urlPart['departure']; 
		var arrival = urlPart['arrival'];
		var duration = urlPart['duration'];
		var airporttocode = urlPart['airporttocode'];
		var airportfromcode = urlPart['airportfromcode'];
		var noint = urlPart['noint'];
		
		window.location.href = '/packagetype='+packagetype+'&departure='+departure+'&arrival='+arrival+'&duration='+duration+'&airporttocode='+airporttocode+'&airportfromcode='+airportfromcode+'&depvariance='+3
	}
	else
	{
		window.location.href = url;	
	}
}

// Adds rows to pricebreakdown table
function addRowPriceBreakDown(tblId, name, price, quantity)
{
	if (price == 0) // Ignore 0 prices
	{
		return true;
	}
	
	var tblBody = document.getElementById(tblId).tBodies[0];
	var newRow = tblBody.insertRow(-1);
	var newCell;
	
	newCell = newRow.insertCell(0);
	newCell.className = 'price_breakdown_label';
	newCell.appendChild(document.createTextNode(name));
		
	newCell = newRow.insertCell(-1);
	newCell.className = 'price_breakdown_price';
	newCell.appendChild(document.createTextNode('£' + (price / 100).toFixed(2) + '(x' + quantity + ')'));
	
}

// Adds the total row to the pricebreakdown table
function addRowTotal(tblId, name, total)
{
	var tblBody = document.getElementById(tblId).tBodies[0];
	var newRow = tblBody.insertRow(-1);
	var newCell;
	
	cell = newRow.insertCell(-1);
	cell.innerHTML = '&nbsp;';
	/* cell.className = 'price_breakdown_dash'; */
	
	cell = newRow.insertCell(-1);
	cell.innerHTML = '&nbsp;';
	/* cell.className = 'price_breakdown_dash'; */
	
	cell = newRow.insertCell(-1);
	/* cell.className = 'price_breakdown_total'; */
	cell.innerHTML = '&nbsp;'; 
	
	newRow = tblBody.insertRow(-1);
			
	cell = newRow.insertCell(-1);
	cell.className = 'price_breakdown_total';
	cell.innerHTML = '<strong>' + name + '</strong>';
		
	cell = newRow.insertCell(-1);
	cell.className = 'price_breakdown_total';
	cell.innerHTML = '<strong>£' + total.toFixed(2) + '</strong>';
		
	cell = newRow.insertCell(-1);
	cell.className = 'price_breakdown_total';
	cell.innerHTML = '&nbsp;'; 
}

// Updates the Total Holiday (looping through the accommodation units and adding the total to the accom price) 
// To calculate the correct hotel price, we have to pass through numberOfAdults, numberOfChildren
function updateTotalHoliday(flight_price, NumberOfAdults, NumberOfChildren)
{
	var hotel_room_type_num = 0; k = 0;
	var accommPrice;
	var holidayPrice;
	var array;
	
	for (var hotel_num = 0; document.getElementById('accomm_price_per_person_'+hotel_num+'_'+hotel_room_type_num); hotel_num++)
	{
		while (document.getElementById('accomm_price_per_person_'+hotel_num+'_'+hotel_room_type_num))
		{
			accommPrice = document.getElementById('accomm_price_per_person_'+hotel_num+'_'+hotel_room_type_num).value;
			accommPrice = accommPrice * (NumberOfAdults + NumberOfChildren);
			holidayPrice = (accommPrice + flight_price).toFixed(2);
 			document.getElementById('total_cost_text_live_price_'+hotel_num+'_'+hotel_room_type_num).innerText = '£' + holidayPrice; // IE
			document.getElementById('total_cost_text_live_price_'+hotel_num+'_'+hotel_room_type_num).textContent = '£' + holidayPrice; // Everyone else

			hotel_room_type_num++;
		}
		
		// Not the best...Set up a hidden field with the value price_breakdown_loading, when the page loaded overwrite the value to price_breakdown
		// When someone clicks the select accomm button, checks the value of the field. 
		document.getElementById('price_breakdown_checking').value = 'price_breakdown';
		
		// Prepare for next hotel
		hotel_room_type_num = 0;
	}
}