  // 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.container, historyData.direction);
	}
}

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)
{
	//use the url but discard the # section
	var currentlySearchingFor = (new String(url)).split("#")[0];
	var containerPart = new String(currentlySearchingFor.match("container=[^&]*"));
	var directionPart = unescape((new String(currentlySearchingFor.match("direction=[^&]*"))).substr("direction=".length));
	var containerSearch = document.getElementById("containerSearch");
	
	if (containerPart != null && containerPart != '')
		containerSearch.value = unescape(containerPart.substr("container=".length));
	if (directionPart != null)
	{
		//depends on the radio buttons being "id=direction"+value
		directionControl = document.getElementById("direction"+directionPart);
		directionControl.checked = true;
	}
	else
	{
		// the All button has no value so it's just "id=direction"
		directionControl = document.getElementById("direction");
		directionControl.checked = true;
	}
}

function getDirectionValue()
{
	var directionValue="";//default All option

	if (document.getElementById("directionimport").checked)
		directionValue="import";//import option
	if (document.getElementById("directionexport").checked)
		directionValue="export";//export option
	return directionValue;
}

function updateEnglishVersion()
{
	var containerValue = document.getElementById("containerSearch").value;
	var directionValue = getDirectionValue();

	var url = location.protocol+"//"+location.hostname+location.pathname
	url += "?container="+escape(containerValue)+"&direction="+escape(directionValue);

	//Add to history
	var data = new Object();
	data.direction = directionValue;
	data.container = containerValue;
	dhtmlHistory.add(directionValue+":"+containerValue, data);//RSH method

	var englishVersion = "<p>Information Requested for <a href="+url+">";
	englishVersion += directionValue+" Containers whose ";
	englishVersion += "Container no. is like '"+containerValue+"'";
	englishVersion += "</a></p>";

	replaceText(document.getElementById("searchRequested"), englishVersion);
}

var prevCountUrl = "";
function getRecordCount()
{
	var containerValue = document.getElementById("containerSearch").value;
	var directionValue = getDirectionValue();
	//document.getElementById("sqlQuery").innerHTML += "getRecordCount"+directionValue+":"+containerValue;
	
	if (containerValue != "")
	{
		var url = "clearances-ajax.php?intent=COUNT&container="+escape(containerValue)+"&direction="+escape(directionValue);
		if (url != prevCountUrl)
		{
			requestCount(url);
			prevCountUrl = url;
		}
	}
	else
		replaceText(document.getElementById("countResults"), "");

	setTimeout("getRecordCount();", 1000);
}

var prevSearchUrl = "";
function searchFor(container, direction)
{
	if (container != "")
	{
		var url = "clearances-ajax.php?container="+escape(container)+"&direction="+escape(direction);
		if (url != prevSearchUrl)
		{
			requestData(url);
			prevSearchUrl = url;
		}
	}
}

function getSearchResults()
{
	var container = document.getElementById("containerSearch").value;
	var direction = getDirectionValue();
	searchFor(container, direction);
}

//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 == "")
			{
				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 clearanced 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";
			}
			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 html = "";
					var prevContainer="";
					for (var i = 0; i < data.rows.length; i++)
					{
						if (i == 0)
						{
							var tableHeaderHTML1 = "<table class=datatable><tbody><tr class='label'><td>Container</td><td>Authority</td>";
							var tableHeaderHTML2 = "<td>Vessel</td><td>Voyage</td><td>Reference</td><td>Received</td><td>Import/<br>Export</td></tr>";
							html += tableHeaderHTML1+tableHeaderHTML2;
						}
						var container=data.rows[i].container;
						var authority=data.rows[i].authority;
						var nztransit=data.rows[i].nztransit;
						if (container != prevContainer && authority != "Customs" && nztransit != "")
						{
							html+="<tr class=data>";
							html +="<td align=\"center\"><a href='javascript:searchFor(\"\", \""+container+"\");'>"+container+"</a>";
							// container search icons
							html+="<br><a style=\"color: white;\" href=\"notices.html?container="+container+"\"><img src=\"/images/email.gif\" border=\"0\"></a><a style=\"color: white;\" href=\"containers.html?container="+container+"\"><img src=\"/images/Container.gif\" border=\"0\"></a><a style=\"color: white;\" href=\"releases.html?container="+container+"\"><img src=\"/images/releases.gif\" border=\"0\"></a></td>";
							html+="<td align=center class=highlights>Customs</td><td colspan=5 align=center class=highlights>Please present the Customs Clearance at Blyde Terminal<br><span class=usermanual>Customs will only send a clearance to "+nztransit+" for "+container+"</span></td>";
							html+="</tr>"
						}
						html+=formatDataRow(data.rows[i]);
						
						prevContainer=container;
					}
					html +="</table>";
					searchResultsElement = document.getElementById("searchResults");
					searchResultsElement.innerHTML = "";
					searchResultsElement.innerHTML = html;
				}
				else
				{
					replaceText(searchResultsElement, "<span class=highlights>Searching: NO RESULT FOUND</span>");
					document.getElementById("searchManual").style.display = "none";
				}
			}
		}
		else
			searchResultsElement.innerText = "Error processing response"+dataRequest.status;

	}
}

function formatDataRow(row)
{
	var strike ="";
	var unstrike ="";
	if (row.cancelled != "" && row.cancelled.toString().substring(0,4) != "0000")
	{
		strike="<strike>";
		unstrike="</strike>";
	}
	
	var authorityClass = "";
	if (row.action == 'HOLD')
		authorityClass +=" class='highlights'";
		
	var html = "";
	
	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>";
	html +="<a style=\"color: white;\" href=\"/Containers/containers.html?container="+row.container+"\"><img src=\"/images/Container.gif\" border=\"0\"></a>";
	html +="<a style=\"color: white;\" href=\"releases.html?container="+row.container+"\"><img src=\"/images/release.gif\" border=\"0\"></a></td>";
	html +="<td align=\"center\""+authorityClass+">"+strike+(row.authority=="ZIM"?"GSL":row.authority)+(row.action=='HOLD'?"  HOLD":"")+unstrike+"</td>";
	html +="<td>"+strike+row.vessel+unstrike+"</td>";
	html +="<td>"+strike+row.voyage+unstrike+"</td>";
	html +="<td>"+strike+row.reference+unstrike+"</td>";
	html +="<td>"+strike+row.recvTime+unstrike+"</td>";
	html +="<td align=\"center\">"+strike+row.direction+unstrike+"</td>";
	//html +="<td align=\"center\">"+strike+row.cancelled.toString().substring(0,10)+"<br>"+row.cancelled.toString().substring(10,16)+unstrike+"</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;

			document.getElementById("searchManual").style.display = "none";
			//if (count == 0)
			
			if (count > 0 && count <= 60)
				getSearchResults();
			else
			{
				addHint = true;
				//clear the existing data
				prevSearchUrl = "";
				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);
