function createRequest()
{
	var request = null;
	try{
		request = new XMLHttpRequest();
	}catch(microsoft){
		try{
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(othermicrosoft){
			try{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(failed){
				request = null;
			}
		}
	}
	if (request == null)
		alert("Unable to proceed due to failure to create 'Request' object");
	return request;
}

// Get on with creating it already...
var containerRequest = createRequest();
var countRequest = createRequest();
if (containerRequest == null || countRequest == null)
	alert("Unable to create server connections: "+containerRequest+", "+countRequest);

var spinner = new Array(5);
spinner[0]="Creating Connection";
spinner[1]="Send Request";
spinner[2]="Processing Request";
spinner[3]="Receiving Response";
spinner[4]="Processing Response";

  // initialize RSH
  dhtmlHistory.initialize();
  
  // add ourselves as a listener for history
  // change events
  dhtmlHistory.addListener(handleHistoryChange);
  
  // determine our current location so we can
  // initialize ourselves at startup
  var initialLocation = 
                dhtmlHistory.getCurrentLocation();
  
  // if no location specified, use the default
  if (initialLocation == null)
    initialLocation = "location1";

/** A function that is called whenever the user
    presses the back or forward buttons. This
    function will be passed the newLocation,
    as well as any history data we associated
    with the location. */
function handleHistoryChange(newLocation,
                             historyData) {
	if (historyData != null)
	{
		//replaceText(document.getElementById("sqlQuery"), historyData.toString());
  		// use the history data to update our UI
		//alert("Search booking: "+historyData.booking+", container: "+historyData.container);
		searchFor(historyData.booking, historyData.container);
	}
}

var requestInProgress = false;

function requestContainerCount(url)
{
	if (countRequest.readyState == 0 && !requestInProgress)
	{
		requestInProgress = true;
		countRequest.open("GET", url, true);
		countRequest.onreadystatechange = updateCount;
		countRequest.send(null);
	}
}

function requestContainerData(url)
{
	if (!requestInProgress)
	{
		requestInProgress = true;
//		alert("requestContainerData("+url+")");
		containerRequest.open("GET", url, true);
		containerRequest.onreadystatechange = updateData;
		containerRequest.send(null);
	
		fillFormFieldsFromUrl(url);
		updateEnglishVersion();
		
		if (document.getElementById("searchManual")!=null)
			document.getElementById("searchManual").style.display = "none";
	}
}

function fillFormFieldsFromUrl(url)
{
	var currentlySearchingFor = (new String(url)).split("#")[0];
	var bookingPart = new String(currentlySearchingFor.match("booking=[^&]*"));
	var containerPart = new String(currentlySearchingFor.match("container=[^&]*"));
	var bookingSearch = document.getElementById("bookingSearch");
	var containerSearch = document.getElementById("containerSearch");
	//alert(unescape(containerPart.substr("container=".length)));
	
	if (bookingPart != null && bookingSearch != null)
		bookingSearch.value = unescape(bookingPart.substr("booking=".length));
	if (containerPart != null && containerSearch != null)
		containerSearch.value = unescape(containerPart.substr("container=".length));
}

function updateEnglishVersion()
{
	var containerSearch = document.getElementById("containerSearch");
	var bookingSearch = document.getElementById("bookingSearch");
	if (containerSearch==null||bookingSearch==null)
		return;
		
	var containerValue = containerSearch.value;
	var bookingValue = bookingSearch.value;

	if (containerValue==null)
		containerValue="";
	if (bookingValue==null)
		bookingValue="";

	var url = location.protocol+"//"+location.hostname+location.pathname
	url += "?container="+escape(containerValue)+"&booking="+escape(bookingValue);

	//Add to history
	var data = new Object();
	data.booking = bookingValue;
	data.container = containerValue;
	dhtmlHistory.add(bookingValue+":"+containerValue, data);//RSH method
	
	var englishVersion = "<p>Information Requested for <a href="+url+">Containers whose ";
	if (containerValue != "" && bookingValue != "")
		englishVersion += "Container no. is like '"+containerValue+"' and Booking is like '"+bookingValue+"'";
	else
	{
		if (containerValue != "")
			englishVersion += "Container no. is like '"+containerValue+"'";
		if (bookingValue != "")
			englishVersion += "Booking is like '"+bookingValue+"'";
	}
	englishVersion += "</a></p>";

	replaceText(document.getElementById("searchRequested"), englishVersion);
}

var prevCountUrl = "";
function getRecordCount()
{
	var containerValue = document.getElementById("containerSearch").value;
	var bookingValue = document.getElementById("bookingSearch").value;
	
	if (bookingValue != "" || containerValue != "")
	{
		var url = "containers-ajax.php?intent=COUNT&container="+escape(containerValue)+"&booking="+escape(bookingValue);
		if (url != prevCountUrl)
		{
			//document.getElementById("sqlQuery").innerHTML = url;
			//document.getElementById("sqlQuery").display = "block";
			if (!requestInProgress)
			{
				//alert("Count: "+url);
				requestContainerCount(url);
				prevCountUrl = url;
			}
		}
	}
	else
		replaceText(document.getElementById("countResults"), "&nbsp;");	

	setTimeout("getRecordCount();", 1000);
}

var prevSearchUrl = "";
function searchFor(booking, container)
{
	//document.getElementById("containerSearch").value = container;
	//document.getElementById("bookingSearch").value = booking;

	//getRecordCount();
	if (booking != "" || container != "")
	{
		var url = "containers-ajax.php?container="+escape(container)+"&booking="+escape(booking);
		if (url != prevSearchUrl)
		{
			if (requestInProgress)
			{
				//alert("Delayed search for "+url);
				setTimeout("searchFor(\""+booking+"\", \""+container+"\");",100);
			}
			else
			{
				//alert("Perform search for "+url);
				requestContainerData(url);
				prevSearchUrl = url;
			}
		}
	}
}

function getSearchResults()
{
	var container = document.getElementById("containerSearch").value;
	var booking = document.getElementById("bookingSearch").value;
	
	//alert("Search: "+container+", "+booking);
	searchFor(booking, container)
}

//Invoked right at the bottom so saved searches work.
function searchFromStartingLink()
{
	//alert(location);
	fillFormFieldsFromUrl(location);

	if (location.search != "")
	{
		getRecordCount();
		getSearchResults();
	}
}

function updateData()
{
	searchResultsElement = document.getElementById("searchResults");
	if (searchResultsElement!=null)
	{
		replaceText(searchResultsElement, "<span class=highlights>Searching Containers: "+spinner[containerRequest.readyState]+"<blink>...</blink></span>");
		if (containerRequest.readyState == 4)
		{
			if (containerRequest.status == 200)
			{
				searchResultsElement.innerHTML = "";
				if (containerRequest.responseText == "")
				{
					document.getElementById("searchManual").style.display = "none";
	
					var container = document.getElementById("containerSearch").value;
					var noDataElement = document.getElementById("noDataResponse");
					noDataResponse ="<p class=label>No containers or bookings similar to your request have been released or received in the last 2 months.</p>";
					noDataResponse +="<p> Try looking on the ";
					noDataResponse +="	<a target=new href=\"http://etrack.maerskline.com/link/?page=page_tracking3_trackSimple\">Maersk</a><a href='mailto:tracking@maersk.com?subject=Please%20send%20me%20e-mails%20tracking%20this%20container&amp;body=Sending%20this%20e-mail%20will%20cause%20the%20Maersk%20tracking%20system%20to%20send%20you%20e-mails%20tracking%20container%20"+container+"'><img border=0 src=/images/email.gif title=\"Register for Email Tracking with Maersk\"></a>, ";
					noDataResponse +="	<a target=new href=\"http://www.tasmanorient.com/tracking/TraceCargoResults.asp?RowCount=1&amp;chkDisplayContainer1=ON&amp;Container1="+container+"&amp;Back=QuickTrace.asp\">TOL</a>, and"; 
					noDataResponse +="	<a target=new href='http://trlweb1.tranzrail.co.nz/servlet/OntracDirect/?_IVJ_ServiceHandlerName=TRL.OntracDirect.servlet.StartupView&amp;txtCRN=&amp;txtTUID="+container+"&amp;btnTrace=Trace'>TranzRail</a> sites.";
					noDataResponse +="</p>";
					noDataElement.innerHTML = noDataResponse;
					noDataElement.style.display = "block";
				}
				else
				{
					document.getElementById("noDataResponse").style.display = "none";
				
					//check for fatal errors in the query
					var fatalError = containerRequest.responseText.match(/Fatal error/);
					if (fatalError!=null)
					{
						replaceText(searchResultsElement, "<b>Sorry but a fatal error occurred.  Try reducing the number of containers in your request or contact Port Taranaki for assistance.</b>");
						replaceText(document.getElementById("errorData"),containerRequest.responseText);
					}
					else
					{
						//alert(containerRequest.responseText);
						var data = eval("("+containerRequest.responseText+")");
						if (data.rows.length > 0 )
						{
							// Show the instructions
							// actually no-one seems to mind so don't bother.
							//document.getElementById("searchManual").style.display = "block";
							
							var gateOutValue = "";
							var html = "";
							for (var i = 0; i < data.rows.length; i++)
							{
								html+=formatDataRow(i, data.rows[i], gateOutValue);
								gateOutValue = data.rows[i].isGateOut;
							}
							html +="</tbody></table>";
							searchResultsElement.innerHTML = html;
						}
						else
							document.getElementById("searchManual").style.display = "none";
					}
				}
			}
			else
				searchResultsElement.innerText = "Error processing response"+containerRequest.status;
				
			requestInProgress = false;
		}
	}
}

function formatDataRow(index, row, gateOutValue)
{
	var html = "";
	if (index == 0)
	{
		var tableHeaderHTML = "<table class=datatable><tr class=label><td rowspan=2>Line</td><td rowspan=2>Container</td><td rowspan=2>Moved</td><td rowspan=2>Move</td><td rowspan=1 colspan=2>Voyage</td><td rowspan=2>Cleared</td><td rowspan=2>Type</td><td rowspan=2>Category</td><td rowspan=2>Status</td><td rowspan=2>Weight<br><span class=smaller>(inc. tare)</span></td><td rowspan=2>Dwell Time</td><td rowspan=2>Booking</td></tr><tr class=label><td>In</td><td>Out</td></tr>";
		html +=tableHeaderHTML;
	}
	html +="<tr class='data'>";
	if (row.line == 'MSK')
	{
		html +="<td><a target=new href='http://etrack.maerskline.com/appmanager/maerskline/public?_nfpb=true&portlet_trackSimple_1_actionOverride=%2Fportlets%2Ftracking3%2Ftrack%2FtrackSimple%2FtrackSimple&_windowLabel=portlet_trackSimple_1&_pageLabel=page_tracking3_trackSimple&portlet_trackSimple_1wlw-select_key:{pageFlow.trackSimpleForm.type}=CONTAINERNUMBER&portlet_trackSimple_1{pageFlow.trackSimpleForm.numbers}="+row.container+"'>"+row.line+"</a></td>";	
	}
	else if (row.line == 'TOL')
		html +="<td><a target=new href='http://www.tasmanorient.com/tracking/TraceCargoResults.asp?RowCount=1&chkDisplayContainer1=ON&Container1="+row.container+"&Back=QuickTrace.asp'>"+row.line+"</a></td>";
	else if (row.line == 'ZIM')
		html +="<td><a target=new href='http://www.goldstarline.com/Tracing.aspx?hidSearch=true&hidFromHomePage=false&hidSearchType=2&id=166&l=4&rb=ConNum&textContainerNumber="+row.container+"&submit=Show+Moves'>GSL</a></td>";
	else if (row.line == 'COS')
		html +="<td><a target=new href='http://www.coscon.com/ebusiness/service/cargo/trackbycont.do;jsessionid=Kw1MZWC525HNhVLUE8GahdY6W21pwCn0hkvOPoCdhiE878El2wth!1009385563?type=bycont&cont="+row.container+"'>COS</a></td>";
		//http://www.coscon.com/ebusiness/service/cargo/trackbycont.do;jsessionid=Kw1MZWC525HNhVLUE8GahdY6W21pwCn0hkvOPoCdhiE878El2wth!1009385563?type=bycont&cont=CAXU3107104
	else
		html +="<td>"+row.line+"</a></td>";
		
	if (row.container == "")
		html +="<td align=\"center\">None Assigned</td>";
	else
	{
		html +="<td align=\"center\"><a href='javascript:searchFor(\"\", \""+row.container+"\");'>"+row.container+"</a>";
		// container search icons
		html +="<br><a style=\"color: white;\" href=\"notices.html?container="+row.container+"\"><img src=\"/images/email.gif\" border=\"0\"></a>";
		html +="<a style=\"color: white;\" href=\"releases.html?container="+row.container+"\"><img src=\"/images/release.gif\" border=\"0\"></a>";
		html +="<a style=\"color: white;\" href=\"containers.html?container="+row.container+"\"><img src=\"/images/Container.gif\" border=\"0\"></a>";
		// container clearance icons
		if (row.clearanceState == 'ALL')
			html +="<a style=\"color: white;\" href=\"clearances.html?container="+row.container+"\"><img src=\"/images/clearancesCleared.gif\" border=\"0\"></a></td>";
		else if (row.clearanceState == 'SOME')
			html +="<a style=\"color: white;\" href=\"clearances.html?container="+row.container+"\"><img src=\"/images/clearances.gif\" border=\"0\"></a></td>";
		else
			html +="<a style=\"color: white;\" href=\"clearances.html?container="+row.container+"\"><img src=\"/images/clearancesNone.gif\" border=\"0\"></a></td>";
	}

	if (row.moveTime != undefined)
		html +="<td>"+row.moveTime.toString().substring(0,10)+"<br>"+row.moveTime.toString().substring(10,16)+"</td>";
	else
		html +="<td></td>";
		
	
	if (row.moveType != "Left via Rail")
		html +="<td>"+row.moveType+"</td>";
	else
		html +="<td><a target='_new' href='http://www.kiwirail.co.nz/index.php?page=ontrac-direct&OntracPage=index.php?page=ontrac-direct&cmd=location&containerOrWagon="+row.container+"'>"+row.moveType+"</a></td>";
		
	html +="<td>"+row.inVoyage+"</td>";
	html +="<td>"+row.outVoyage+"</td>";
	html +="<td>"
	if (row.moveType != undefined)
	{
		if (row.moveType.indexOf("Arrived", 0) > -1
		|| row.moveType.indexOf("Yard", 0) > -1)
		{
			html +="<span style='color: "+(row.customs!=""?"black'>"+row.customs:"red'>Customs")+"</span> ";
			if (row.cntrCategory == "Import")
			{
				html +="<span style='color: "+(row.maf!=""?"black'>"+row.maf:"red'>MAF")+"</span> ";
				html +="<span style='color: "+(row.mqsnp!=""?"black'>"+row.mqsnp:"red'>MQSNP")+"</span> ";
				html +="<span style='color: "+(row.lineOperatorRelease!=""?"black'>"+row.lineOperatorRelease:"red'>"+row.line)+"</span> ";
			}
		}
	}
	html +="</td>";
	html +="<td>"+row.cntrType+"</td>";
	html +="<td>";
	switch (row.cntrCategory)
	{
		case "I": html += "Import"; break;
		case "E": html += "Export"; break;
		case "M": html += "Empty"; break;
		case "R": html += "Restow"; break;
		case "S": html += "Straight-Thru"; break;
		case "T": html += "Tranship"; break;
		default: html += row.cntrCategory;
	}
	html +="</td>";
	html +="<td>";
	switch (row.cntrStatus)
	{
		case "F": html += "Full"; break;
		case "E": html += "Empty"; break;
		default: html += row.cntrStatus;
	}
	html += "</td>";
	html +="<td>"+row.cntrWeight+"</td>";
	if ((row.cntrCategory == "Export" && row.dwellTime >= 15)
	|| (row.cntrCategory == "Import" && row.dwellTime >= 8))
		html +="<td align=\"center\" style='color: red;'>"+row.dwellTime+"</td>";
	else
		html +="<td align=\"center\">"+row.dwellTime+"</td>";
	if (row.booking != "")
	{
		html +="<td align=\"center\"><a href='javascript:searchFor(\""+row.booking+"\",\"\");'>"+row.booking+"</a>";
		html +="<br><a style=\"color: white;\" href=\"notices.html?booking="+row.booking+"\"><img src=\"/images/email.gif\" border=\"0\"></a>";
		html +="<a style=\"color: white;\" href=\"releases.html?booking="+row.booking+"\"><img src=\"/images/release.gif\" border=\"0\"></a>";
		html +="<a style=\"color: white;\" href=\"containers.html?booking="+row.booking+"\"><img src=\"/images/Container.gif\" border=\"0\"></a></td>";
	}
	html +="</tr>";
	return html;
}

var prevCount = 0; // pump priming value
function updateCount()
{
	if (countRequest.readyState == 4)
	{
		if (countRequest.status == 200)
		{
			var insertText = "";
			var count = countRequest.responseText;
			if (count == '')
				count = 0;
				
			if (count <= 60 && count > 0)
			{
				getSearchResults();
			}
			else
			{
				searchResultsElement = document.getElementById("searchResults");
				searchResultsElement.innerHTML = "";
				updateEnglishVersion();
			}
			prevCount = count;

			if (count == "1")
				insertText = "A matching record exists.";
			else if (count == "0")
				insertText = "No matching records exist.";
			else
				insertText = count+" matching records exist.";
			replaceText(document.getElementById("countResults"), insertText);
		}
		else
			replaceText(document.getElementById("countResults"), "<span class=highlights>Error Occurred: "+countRequest.status+" - "+countRequest.getResponseHeader("Status"));
		countRequest = createRequest();
		
		RequestInProgress = false;
	}
}

