  // 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);
		fillFormFieldsFromURL(historyData.url);
		getRecordCount();
		getSearchResults();

	}
}

//Field names and associated values
var values=new Array(15);
var names=new Array(15);

names[1] = new String('line');
names[2] = new String('container');
names[3] = new String('location'); // being cunning here :)
names[4] = new String('invoyage');
names[5] = new String('outvoyage');
names[6] = new String('clearances');
names[7] = new String('type');
names[8] = new String('cntr_category');
names[9] = new String('cntr_status');
names[10] = new String('weight');
names[11] = new String('dwell_time');
names[12] = new String('booking');
names[13] = new String('size');
names[14] = new String('cntr_available');

function getValuesFromURL(url)
{
	var currentlySearchingFor, searchValue;

	currentlySearchingFor = (new String(url)).split("#")[0];

	for (var i=1;i<names.length;i++)
	{
		//set the values
		searchValue = new String(currentlySearchingFor.match(names[i]+"=[^&]*"));
		values[i] = unescape(searchValue.substr(names[i].length+1)); //+1 for the "="
		//alert(names[i]+': '+values[i]);
	}
}

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);

var requestInProgress = false;

function requestContainerCount(url)
{
	countRequest = createRequest();
	if (countRequest.readyState == 0 && !requestInProgress)
	{
		requestInProgress = true;
		countRequest.open("GET", url, true);
		countRequest.onreadystatechange = updateCount;
		countRequest.send(null);
	}
}

function requestContainerData(url)
{
	dataRequest = createRequest();
	if (dataRequest.readyState == 0 && !requestInProgress)
	{
		requestInProgress = true;
		dataRequest.open("GET", url, true);
		dataRequest.onreadystatechange = updateData;
		dataRequest.send(null);

		//fillFormFieldsFromUrl(url);
		updateEnglishVersion();
		//document.getElementById("searchManual").style.display = "none";
	}
}

function updateEnglishVersion()
{
	var url = location.protocol+"//"+location.hostname+location.pathname
	url += fillURLFromFormFields().replace(/[^?]*\?/,"?");//"?container="+escape(containerValue)+"&booking="+escape(bookingValue);

	//Add to history
	var data = new Object();
	data.url = url;
	//dhtmlHistory.add(bookingValue+":"+containerValue, data);//RSH method
	dhtmlHistory.add(escape(fillURLFromFormFields().replace(/[^?]*\?/,"?")), data);//RSH method
	
	var englishVersion = "<p>Information Requested for <a href="+url+">Containers Requested</a></p>";

	replaceText(document.getElementById("englishVersionOfSearch"), englishVersion);
}

var prevCountUrl = "";
function getRecordCount()
{
	var url = fillURLFromFormFields();
	if (url != null && url != '')
	{
		url += '&intent=COUNT';
		if (url != prevCountUrl)
		{
			//replaceText(document.getElementById("searchRequested"), '<p>'+url+'<p>');
			requestContainerCount(url);
			prevCountUrl = url;
		}
	}
	else
		replaceText(document.getElementById("countResults"), "&nbsp;");

	setTimeout("getRecordCount();", 500);
}

var prevSearchUrl = "";
function searchFor(booking, container)
{
	var url = new String('containersAdv-ajax.php?');
	var addedBooking = false;
	
	if (booking != null && booking != '')
	{
		url += 'booking='+booking;
		addedBooking = true;
	}
	
	if (container != null && container != '')
		url += (addedBooking?'&':'')+'container='+container;

	if (url != prevSearchUrl)
	{
		if (requestInProgress)
		{
			setTimeout("searchFor(\""+booking+"\",\""+container+"\");",100);
		}
		else
		{
			requestContainerData(url);
			prevSearchUrl = url;
		}
	}
}

function getSearchResults()
{
	var url = fillURLFromFormFields();
	if (url != null && url != '')
	{
		//replaceText(document.getElementById("searchRequested"), '<p>'+url+'</p>');

		if (url != prevSearchUrl)
		{
			if (requestInProgress)
			{
				//alert("listGroup("+groupid+","+targetDiv+"\")");
				setTimeout("getSearchResults()",100);
			}
			else
			{
				requestContainerData(url);
				prevSearchUrl = url;
			}
		}
	}
}

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()
{
	var searchDataElement = document.getElementById("searchData");

	searchResultsElement = document.getElementById("searchResults");
	searchSpinnerElement = document.getElementById("searchSpinner");

	replaceText(searchSpinnerElement, "<p><span class=highlights>Searching Containers: "+spinner[dataRequest.readyState]+"<blink>...</blink></span></p>");

	if (dataRequest.readyState == 4)
	{
		if (dataRequest.status == 200)
		{
			//alert(dataRequest.responseText);
			
			if (dataRequest.responseText == "")
			{
				//alert("No Results Found");
				document.getElementById("searchManual").style.display = "none";

				var container = document.getElementById("container").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>";
				replaceText(noDataElement, noDataResponse);
				noDataElement.style.display = "block";
			}
			else
			{
				//alert("Some Results Found");
				document.getElementById("noDataResponse").style.display = "none";
				if (dataRequest.responseText != "")
				{
					// get the search result table
					var theTable = document.getElementById("searchResultTable");
					//empty the table of previous results
					while (theTable.rows.length>4) //2 label rows, 1 filter, and a button
					{
						theTable.deleteRow(4);
					}

					//check for fatal errors in the query
					var fatalError = dataRequest.responseText.match(/Fatal error/);
					if (fatalError!=null)
					{
						theTableRow = theTable.insertRow(theTable.rows.length);
						theCell = theTableRow.insertCell(0);
						theCell.setAttribute('colspan', '6');
						replaceText(theCell, "Sorry but a fatal error occurred.  Try reducing the number of containers in your request or contact Port Taranaki for assistance.");
						replaceText(document.getElementById("errorData"),dataRequest.responseText);
					}
					else
					{
						var data = eval("("+dataRequest.responseText+")");
						if (data.rows.length > 0 )
						{
							//alert(""+data.rows.length+" Results Found");
							// Show the instructions
							document.getElementById("searchManual").style.display = "block";
							
							//alert("Inserting Rows");
							for (var i=0;i<data.rows.length;i++)
							{
								insertDataRow(i, data.rows[i], theTable);
							}
							
							
							// HTML Insert version that IE7 doesn't like innerHTML
							/*
							var html = "";
							for (var i = 0; i < data.rows.length; i++)
							{
								html+=formatDataRow(i, data.rows[i]);
							}
							//html +="</tbody></table>";
							//replaceText(searchResultsElement, html);
							replaceText(searchResultsElement, html);
							*/
						}
						else
							document.getElementById("searchManual").style.display = "none";
					}
				}
				replaceText(searchSpinnerElement,"");
			}
		}
		else
			searchResultsElement.innerText = "<tr><td>Error processing response"+dataRequest.status+"</td></tr>";

	}
}

function insertDataRow(index, row, theTable)
{
	var html = "";
	var theCell;
	var theTableRow = theTable.insertRow(theTable.rows.length);

	theTableRow.setAttribute('class','data');
	
	theCell = theTableRow.insertCell(0);
	
	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>";	
//		html = "<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>";
	else if (row.line == 'TOL')
		html = "<a target=new href='http://www.tasmanorient.com/tracking/TraceCargoResults.asp?RowCount=1&chkDisplayContainer1=ON&Container1="+row.container+"&Back=QuickTrace.asp'>"+row.line+"</a>";
	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>";
	else
		html = row.line;
	replaceText(theCell,html);
	
	theCell = theTableRow.insertCell(1);
	theCell.setAttribute('align','center');
	
	if (row.container == "")
		html ="None Assigned";
	else
	{
		html ="<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>";
		else if (row.clearanceState == 'SOME')
			html +="<a style=\"color: white;\" href=\"clearances.html?container="+row.container+"\"><img src=\"/images/clearances.gif\" border=\"0\"></a>";
		else
			html +="<a style=\"color: white;\" href=\"clearances.html?container="+row.container+"\"><img src=\"/images/clearancesNone.gif\" border=\"0\"></a>";
	}
	replaceText(theCell,html);
	
	html = ""
	theCell = theTableRow.insertCell(2);
	html =row.moveTime.toString().substring(0,10)+"<br>"+row.moveTime.toString().substring(10,16);
	replaceText(theCell,html);
	
	html = ""
	theCell = theTableRow.insertCell(3);	
	if (row.moveType != "Left via Rail")
		html =row.moveType;
	else
		html ="<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>";
	replaceText(theCell,html);
	
	html = ""
	theCell = theTableRow.insertCell(4);
	html =row.inVoyage;
	replaceText(theCell,html);
	
	html = ""
	theCell = theTableRow.insertCell(5);
	html =row.outVoyage;
	replaceText(theCell,html);
	
	html = ""
	theCell = theTableRow.insertCell(6);
	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> ";
		}
	}
	replaceText(theCell,html);
	
	html = ""
	theCell = theTableRow.insertCell(7);
	html =row.cntrType;
	replaceText(theCell,html);
	
	html = ""
	theCell = theTableRow.insertCell(8);
	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 += " / "
	switch (row.cntrStatus)
	{
		case "F": html += "Full"; break;
		case "E": html += "Empty"; break;
		default: html += row.cntrStatus;
	}
	replaceText(theCell,html);
	
	theCell = theTableRow.insertCell(9);
	html = ""
	switch (row.cntrAvailable)
	{
		case "AV": html += "Available(General)"; break;
		case "AI": html += "Available(Air-cooled)"; break;
		case "WAT": html += "Available(Water-cooled)"; break;
		case "DB": html += "Dairy Board Quality"; break;
		case "USA": html +=  "Dairy Board for USA"; break;
		case "NA": html +=  "Not Available"; break;
		case "AS": html += "Awaiting Survey"; break;
		case "AA": html +=  "Awaiting Approval(Structural)"; break;
		case "AAR": html +=  "Awaiting Approval(Struct/Mech)"; break;
		case "AAW": html +=  "Awaiting Approval(Wash)"; break;
		case "DM": html +=  "Damaged"; break;
		case "MD": html +=  "Major Damage"; break;
		case "SL": html += "Sale"; break;
		case "SCR": html += "Scrap"; break;
		case "OFH": html += "Offhire"; break;
		case "EVAC": html += "Evacuating"; break;
		default: html += "Other: "+row.cntrAvailable;
	}
	replaceText(theCell,html);
	
	theCell = theTableRow.insertCell(10);
	html =row.cntrWeight;
	replaceText(theCell,html);
	
	theCell = theTableRow.insertCell(11);
	theCell.setAttribute('align','center');
	if ((row.cntrCategory == "Export" && row.dwellTime >= 15)
	|| (row.cntrCategory == "Import" && row.dwellTime >= 8))
			theCell.setAttribute('style','color: red;');
	html =row.dwellTime;
	replaceText(theCell,html);
	
	theCell = theTableRow.insertCell(12);
	theCell.setAttribute('align','center');	
	html = ""
	if (row.booking != "")
	{
		html ="<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>";
	}
	replaceText(theCell,html);
}

var prevCount = 0; // pump priming value
function updateCount()
{
	if (countRequest.readyState == 4)
	{
		if (countRequest.status == 200)
		{
			var count = countRequest.responseText;
			if (count == '')
				count = 0;
				
			if (count <= 60 && count > 0)
			{
				getSearchResults();
			}
			else
			{
				searchResultsElement = document.getElementById("searchResults");
				replaceText(searchResultsElement, '');
				//updateEnglishVersion();
			}
			prevCount = count;

			var insertText = "";
			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();
	}
}

function createSelect(name, value, opts, optValues)
{
	returnSelect = "<select id="+name+" name=" + name + ">";
	for (var i = 0;i<opts.length;i++)
	{
		returnSelect = returnSelect + "<option ";
		if ((new String(value)).toUpperCase() == (new String(optValues[i])).toUpperCase()) 
			returnSelect = returnSelect + ' selected '; 
		
		returnSelect = returnSelect + "value=\"" + optValues[i] + "\">" + opts[i] + "</option>";
	}
	returnSelect = returnSelect + "</select>";
	document.write(returnSelect);
}

function fillFormFieldsFromUrl(url)
{
	getValuesFromURL(url);
	var searchElement;
	
	for (var i=1;i<names.length;i++)
	{
		//set the fields
		if (values[i] != new String(""))
		{
			searchElement = document.getElementById(names[i]);
			if (searchElement.tagName != "SELECT")
			{
				searchElement.value = values[i];
			}
			else
			{
				var opts = searchElement.options;
				if (opts != null)
				{
					for(var j=0;j<opts.length;j++)
					{
						if (new String(opts[j].value) == values[i])
							opts[j].selected = true;
					}
				}
			}
		}
	}
}

function fillURLFromFormFields()
{
	var searchElement, val;
	var urlString = new String('');
	
	for (var i=1;i<names.length;i++)
	{
		searchElement = document.getElementById(names[i]);
		var opts = searchElement.options;
		if (opts != null)
			values[i] = opts[searchElement.selectedIndex].value;
		else
			values[i] = searchElement.value;
			
		if (values[i] != null && values[i] != '')
		{
			if (urlString == '')
				urlString += 'containersAdv-ajax.php?'+names[i]+'='+escape(values[i]);
			else
				urlString += '&'+names[i]+'='+escape(values[i]);
		}
	}
	
	//replaceText(document.getElementById('searchRequested'),'<p>'+urlString+'</p>');
	return urlString;
}

//Invoked right at the bottom so saved searches work.
function searchFromStartingLink()
{
	fillFormFieldsFromUrl(location);

	if (location.search != "")
	{
		getRecordCount();
		getSearchResults();
	}	
}


