  // 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
		searchFor(historyData.booking, historyData.container);
	}
}

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 dataRequest = createRequest();
var countRequest = createRequest();
if (dataRequest == null || countRequest == null)
	alert("Unable to create server connections: "+dataRequest+", "+countRequest);

function requestCount(url)
{
	if (countRequest!=null && countRequest.readyState == 0)
	{
		countRequest.open("GET", url, true);
		countRequest.onreadystatechange = updateCount;
		countRequest.send(null);
	}
}

function requestData(url)
{
	if (dataRequest != null)
	{
		dataRequest.open("GET", url, true);
		dataRequest.onreadystatechange = updateData;
		dataRequest.send(null);
	
		fillFormFieldsFromUrl(url);
		updateEnglishVersion();
		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");

	if (bookingPart != null)
		bookingSearch.value = unescape(bookingPart.substr("booking=".length));
	if (containerPart != null)
		containerSearch.value = unescape(containerPart.substr("container=".length));
}

function updateEnglishVersion()
{
	var containerValue = document.getElementById("containerSearch").value;
	var bookingValue = document.getElementById("bookingSearch").value;

	var url = location.protocol+"//"+location.hostname+location.pathname
	url += "?container="+escape(containerValue)+"&booking="+escape(bookingValue);
	//Add to history
	//window.location = url; // infinite loop
	//window.history.push(url); // no such method
	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 = "releases-ajax.php?intent=COUNT&container="+escape(containerValue)+"&booking="+escape(bookingValue);
		if (url != prevCountUrl)
		{
			requestCount(url);
			prevCountUrl = url;
		}
	}
	else
		replaceText(document.getElementById("countResults"), "");

	setTimeout("getRecordCount();", 1000);
}

var prevSearchUrl = "";
function searchFor(booking, container)
{
	if (booking != "" || container != "")
	{
		var url = "releases-ajax.php?container="+escape(container)+"&booking="+escape(booking);
		if (url != prevSearchUrl)
		{
			requestData(url);
			prevSearchUrl = url;
		}
	}
}

function getSearchResults()
{
	var container = document.getElementById("containerSearch").value;
	var booking = document.getElementById("bookingSearch").value;
	
	searchFor(booking, container)
}

//Invoked right at the bottom so saved searches work.
function searchFromStartingLink()
{
	fillFormFieldsFromUrl(location);

	if (location.search != "")
	{
		getRecordCount();
		getSearchResults();
	}	
}

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";

function updateData()
{
	searchResultsElement = document.getElementById("searchResults");
	replaceText(searchResultsElement, "<span class=highlights>Searching: "+spinner[dataRequest.readyState]+"<blink>...</blink></span>");
	if (dataRequest.readyState == 4)
	{
		if (dataRequest.status == 200)
		{
			if (dataRequest.responseText == "")
			{
				noDataFound();
			}
			else
			{
				document.getElementById("noDataResponse").style.display = "none";
				var data = eval("("+dataRequest.responseText+")");
				if (data.rows.length > 0 )
				{
					// Show the instructions
					document.getElementById("searchManual").style.display = "block";
					//Show the count
					updateCountHTML(data.rowcount, false);
					//Show the query
					//var sqlQueryElement = document.getElementById("sqlQuery");
					//sqlQueryElement.innerHTML = "<p>"+data.query+"</p>";
					//sqlQueryElement.style.display = "block";
					
					//Show the data
					var gateOutValue = "";
					var html = "";
					if (data.rows.length == 0)
					{
						html +="<p class=highlights>No information could be found</p>"
					}
					else
					{
						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 = document.getElementById("searchResults");
					searchResultsElement.innerHTML = "";
					searchResultsElement.innerHTML = html;
				}
				else
				{
					searchResultsElement = document.getElementById("searchResults");
					searchResultsElement.innerHTML = "";
					document.getElementById("searchManual").style.display = "none";
					noDataFound();
				}
			}
		}
		else
			searchResultsElement.innerText = "Error processing response"+dataRequest.status;
	}
}

function noDataFound()
{
	document.getElementById("searchManual").style.display = "none";

	var container = document.getElementById("containerSearch").value;
	var noDataElement = document.getElementById("noDataResponse");
	noDataElement.innerHTML ="<p class=label>No containers or bookings similar to your request have been released or received in the last 2 months.</p>";
	noDataElement.innerHTML +="<p> Try looking on the ";
	noDataElement.innerHTML +="	<a target=new href=\"http://etrack.maersksealand.com/ats2/unreg/posttrack.jsp?thispage=unreg%2Fats_tracking_top&amp;kdo=track&amp;searchvalue=&amp;searchtype=container&amp;input_1="+container+"&amp;input_2=&amp;input_3=&amp;dummy.x=0&amp;dummy.y=0\">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>, ";
	noDataElement.innerHTML +="	<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"; 
	noDataElement.innerHTML +="	<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.";
	noDataElement.innerHTML +="</p>";
	noDataElement.style.display = "block";
}

var numberOfGateOuts = -1;
var numberOfCntrs = 0;
var prevBooking = '';

function formatDataRow(index, row, gateOutValue)
{
	var html = "";
	if (gateOutValue != row.isGateOut)
	{
		var tableHeaderHTML1 = "<table class=datatable><tbody><tr class='label'><td></td><td>Line</td><td>Container</td><td>";
		var tableHeaderHTML2 = "</td><td>Type</td><td>Category</td><td>Status</td><td>Booking</td></tr>";
		var isGateOut = (row.isGateOut=="True");
		if (!isGateOut)
		{
			// close first table
			html +="</tbody></table><br>";
			numberOfGateOuts = index-1;
			numberOfCntrs = 0;
		}
		else
		{
			// reset the gateouts
			numberOfGateOuts = -1;
		}
		html +="<span class='highlights'>Gate "+(isGateOut?"Out":"In")+"</span>("+row.booking+" requires "+row.requires+")</span>";
		html +=tableHeaderHTML1+(isGateOut?"Left":"Rcvd")+tableHeaderHTML2;
	}
	html +="<tr class='data'>";
	//html +="<td>"+(index-numberOfGateOuts)+"</td>";
	
	if (row.container == "")
	{
		html +="<td>&nbsp;</td>";
	}
	else
	{
		if (row.booking != prevBooking)
		{
			numberOfCntrs=0;
			prevBooking=row.booking;
		}
		numberOfCntrs++;
		html +="<td>"+numberOfCntrs+"</td>";
	}

	if (row.line == 'MSK')
		html +="<td><a target=new href='http://etrack.maersksealand.com/ats2/unreg/posttrack.jsp?thispage=unreg%2Fats_tracking_top&kdo=track&searchvalue=&searchtype=container&input_1="+row.container+"&input_2=&input_3=&dummy.x=0&dummy.y=0'>"+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
		html +="<td>"+row.line+"</a></td>";
	
	if (row.container == "")
	{
		html+="<td>Release Rcvd</td>";
		numberOfCntrs = 0;
	}
	else
	{
		html +="<td align=\"center\"><a href='javascript:searchFor(\"\", \""+row.container+"\");'>"+row.container+"</a>";
		// container search icons
		html +="<br><a style=\"color: white;\" href=\"/Containers/notices.html?container="+row.container+"\"><img src=\"/images/email.gif\" border=\"0\"></a><a style=\"color: white;\" href=\"/Containers/containers.html?container="+row.container+"\"><img src=\"/images/Container.gif\" border=\"0\"></a><a style=\"color: white;\" href=\"clearances.html?container="+row.container+"\"><img src=\"/images/clearances.gif\" border=\"0\"></a></td>";
	}
	html +="<td align=\"center\">"+row.moveTime.toString().substring(0,10)+"<br>"+row.moveTime.toString().substring(10,16)+"</td>";
	if (row.container == "")
	{
		html +="<td align=\"center\">"+row.requires+"</td>";
	}
	else
	{
		html +="<td align=\"center\">"+row.cntrType+"</td>";
	}
	html +="<td align=\"center\">"+row.cntrCategory+"</td>";
	html +="<td align=\"center\">"+row.cntrStatus+"</td>";
	html +="<td align=\"center\"><a href='javascript:searchFor(\""+row.booking+"\",\"\");'>"+row.booking+"</a>";
	html +="<br><a style=\"color: white;\" href=\"/Containers/notices.html?booking="+row.booking+"\"><img src=\"/images/email.gif\" border=\"0\"></a><a style=\"color: white;\" href=\"/Containers/containers.html?booking="+row.booking+"\"><img src=\"/images/Container.gif\" border=\"0\"></a></td>";
	html +="</tr>";
	return html;
}

function updateCountHTML(count, addHint)
{
	var hintText=(addHint?" <span class=usermanual>Press search to show the matches.</span>":"");
	
	if (count == "1")
		insertText = "A matching record exists."+hintText;
	else if (count == "0")
		insertText = "No matching records exist.";
	else
		insertText = count+" matching records exist."+hintText;
	replaceText(document.getElementById("countResults"), insertText);
}

var prevCount = 0; // pump priming value
function updateCount()
{
	if (countRequest.readyState == 4)
	{
		if (countRequest.status == 200)
		{
			var addHint = false;
			var insertText = "";
			var count = countRequest.responseText;

			if (count <= 60 && count > 0)
				getSearchResults();
			else
			{
				addHint = true;
				//clear the existing data
				searchResultsElement = document.getElementById("searchResults");
				searchResultsElement.innerHTML = "";
			}
			prevCount = count;
			updateCountHTML(count, addHint);
		}
		else
			replaceText(document.getElementById("countResults"), "<span class=highlights>Error Occurred: "+countRequest.status);
		countRequest = createRequest();
	}
}

setTimeout("getRecordCount();", 1000);
