var pb1 = null;
var matchRateBar = null;
var theAccordion = null;
var s = null;

function startup()
{
	theAccordion = new Rico.Accordion( 'accordionDiv', {panelHeight:400, expandedBg : '#B51000', hoverBg : '#B51000', collapsedBg : '#BA2C12', collapsedTextColor: '#FFF', onShowTab: accordShow, boderColor:'#D6AD94'} );
	Rico.Corner.round( 'step1', {corners:'tl bl tr br',bgColor:'#D6AD94'} );
	Rico.Corner.round( 'step2', {corners:'tl bl tr br',bgColor:'#D6AD94'} );
//	Rico.Corner.round( 'step3', {corners:'tl bl tr br',bgColor:'#D6AD94'} );
	Rico.Corner.round( 'step4', {corners:'tl bl tr br',bgColor:'#D6AD94'} );
	Rico.Corner.round( 'step5', {corners:'tl bl tr br',bgColor:'#D6AD94'} );
	pb1 = new jt_ProgressBar(document.getElementById('pbar'), 250, 15, 'bgBarRed'); 
	matchRateBar = new jt_ProgressBar(document.getElementById('matchRateBar'), 250, 15, 'bgBarRed');
}

function makeKML() {
	if (!results || !results.length) {
		alert('You need to add some data and geocode it first, see steps above.');
		return '';
	}
	var kml = '<?xml version="1.0"?>\n<kml xmlns="http://earth.google.com/kml/2.0">\n';
	kml = kml + "<Document>\n"
	for (var i=0;i<results.length;i++) {
		var rowMap = results[i];
		
		var entity = results[i][0];
		var x = results[i][1];
		var y = results[i][2];
		kml = kml + "<Placemark>\n"
		
		kml = kml + "<name>" + entity + "</name>\n";
		var desc = entity ? entity : '';
		var address = entity? entity: '';
		var html;
		desc = desc + '<img src="http://www.astuntechnology.com/staging/ajaxsearch/images/centre.gif"/>';

		kml = kml + '<description>' + desc + '</description>\n';
		kml = kml + "<Point><coordinates>" + x + "," + y + "</coordinates></Point>\n";
		kml = kml + "</Placemark>\n";
	}
	kml = kml + "</Document>\n"
	kml = kml + '</kml>\n';
	return kml;
}

function accordShow(acTab)
{
	if (acTab.titleBar.id == "geocodeResultsHeader")
	{
		if (results.length == 0)
		{
			map.PanToLatLong(51.3311662471,-0.267295896827);
		}
		else
		{
			zoomAllPoints(results);
		}
		
	}
	if (acTab.titleBar.id == "copyResultsHeader")
	{
		var sResults = atCopyBatchResults();
		document.getElementById('atCopyText').value = sResults;
		document.getElementById('formatCSV').checked = "checked";
	}
}
function atCopyBatchResults()
{
	var s = "Original Input, Entity Matched, Match Score, Longitude, Latitude\n";
	for(var i = 0; i < results.length; i++)
	{
		s+= "\"" + results[i][4] + "\"," + results[i][0] + "," + results[i][1] + "," + results[i][2] + "," + results[i][3] + "\n";
	}
	return s;
}

var detailsPanel = null;
function DisplayPopup(x,y,s)
{

// make sure we have only one panel at a time
if (detailsPanel != null)
{
	detailsPanel.Destroy();
	detailsPanel = null;
}

IOSec = new OutputEncoder();

detailsPanel = new VE_Panel("MyPanel",x+10,y+10,200,200,"blue",31,"Details",s,"","",true);

detailsPanel.onCloseClick = function(e) { detailsPanel.Hide(); };

}

function zoomAllPoints(r)
{
	if (r.length == 0)
	{	
		return;
	}

	var ar = new Array();
	for (var i=0;i<r.length;i++) 
	{
		var x = r[i][1];
		var y = r[i][2];
		ar.push(new Msn.VE.LatLong(y,x));
	}
	map.SetBestMapView(ar);
}
function atDoSingleGeocode()
{
	var raw = document.getElementById("txtRawAddress");
	if (raw.value != "")
	{
		atParseRawAddress(raw.value);
	}
	else
	{
		atSearchAddress();
	}
}
	
	function moveMapUp(num)
	{
		if (num == 50)
			return;	
		var mapObj = document.getElementById("atMap");
		mapObj.style.top = num+"px";
		num = num-5;
		setTimeout("moveMapUp("+num+")", 10);

	}
	function atHideHelp()
	{
		var dialog = document.getElementById("atDialog");
		dialog.style.visibility = "hidden";
	}
	function atShowHelp()
	{
		var title = document.getElementById("atDialogTitle");
		title.innerHTML = "Help";
		
		var frame = document.getElementById("atDialogFrame");
		frame.src = "help.html";
		
		var dialog = document.getElementById("atDialog");
		dialog.style.visibility = "visible";

	}
		function CheckStringValue(value)
		{
			if (value == null)
			{
				return "";
			}
			else
			{
				return value;
			}
				
		}
		
		function replaceAll(s, oldval, newval)
		{
			while(s.indexOf(oldval) >= 0)
			{
				s = s.replace(oldval,newval);
			}
			return s;
		}
			
		//Global variable for multiple results
		var results = new Array();
		

		//Global variable for the method called
		var method = "";
		
		//Create a new php serializer variable
		var php = new PHP_Serializer();
		
		//Display the serialized results
		JSserializerOnLoad = function(result)
		{
			switch (method)
			{
				case "parseAddress":
					var add = CheckStringValue(result['address']);
					var city = CheckStringValue(result['city']);
					var county = CheckStringValue(result['county']);
					var postcode = CheckStringValue(result['postcode']);
					var country = CheckStringValue(result['country']);
					document.getElementById('txtStreet').value = add;
					document.getElementById('txtCity').value = city;
					document.getElementById('txtCounty').value = county;
					document.getElementById('txtPostcode').value = postcode;
					document.getElementById('txtCountry').value = country;
					var sFormatted = add + ',' + city + ',' + county + ',' + postcode + ',' + country;
					//lose any double commans due to blanks
					sFormatted = replaceAll(sFormatted, ',,',',');
					var lblForm = document.getElementById("lblFormatted");
					if (lblForm != null)
					{
						lblForm.innerHTML = sFormatted;
					}
					atSearchAddress();
					break;
				case "searchFormattedAddress":
					if (!batchMode)
					{
						var sHTML = "<table id=lstResults>";
						var sCopy = "";
						results = result;
						for(var i = 0; i < result.length; i++)
						{
							sHTML += "<tr><td><a class='atResults' href='javascript: atMap.zoomTo("+ result[0]['x'] +","+ result[0]['y'] +");'>" + result[i]['EntityName'] + "</a></td></tr>";
							sCopy += result[i]['EntityName'] + "," + result[0]['x'] +","+ result[0]['y'] + "\n";
						}
						sHTML += "</table>";
						document.getElementById("atCopyText").value = sCopy;
					}
					else
					{
					/*****************************************************************************************************************************************/
						if (result != null)
						{
							if (result.length > 0)
							{
								var x = result[0]['x'];
								var y = result[0]['y'];
								var s = result[0]['EntityName'];
								var score = result[0]['score'];
								if ((x != null) && (y != null) && (s != null))
								{
									//the results array will be used in the showPoints
									results.push(new Array(s,x,y,score,currentAddress));
									var val = "Address: " + currentAddress + "\n";
									val += "\n Matched to";
									val += "\n " + s;
									val += "\n Longitude:" + x;
									val += "\n Latitude:" + y;
									val += "\n Score:" + score;
									
									val = "<DIV onclick='alert(\""+currentAddress+"\");'>+</DIV>";
									
									map.AddPushpin(batchNumber, y,x, 10, 10, "pin", val, 1000);
									batchMatched++;
								}
								
							}
						}
						atParseRawAddresses(document.getElementById('txtInput').value, batchNumber);
					}
					break;
				case "searchFormattedAddresses":
					
					//alert('Array Length: ' + result.length);
					
					var sMessage = "";
					//Show all the arrays
					for (i=0; i<result.length; ++i)
					{
						sMessage += 'Array No: ' + (i+1) + Chr$(12);
						sMessage += 'Entity Name: ' + result[i]['EntityName'];
						sMessage += 'x: ' + result[i]['x'];
						sMessage += 'y: ' + result[i]['y'];
						sMessage += 'score: ' + result[i]['score'];
						alert(sMessage);
						sMessage = "";
					}
					break;
				case "getMapImage":
//					alert('mapView => x: ' + result['mapView']['x']);
//					alert('mapView => y: ' + result['mapView']['y']);
//					alert('mapView => minX: ' + result['mapView']['minX']);
//					alert('mapView => minY: ' + result['mapView']['minY']);
//					alert('mapView => maxX: ' + result['mapView']['maxX']);
//					alert('mapView => maxY: ' + result['mapView']['maxY']);
//					alert('mapView => zoom: ' + result['mapView']['zoom']);
//					alert('url: ' + result['url']);
					
					//Set the image URL
					//HERE TRYING OBJECT ORIENTATED APPROACH
					//document.getElementById('mapImage').src = result['url'];
					
					//atMap.update(result);
					break;
			}
			
		}

		function showProgressBarDialog()
		{
			var dialog = document.getElementById("atProgressBarDialog");
			dialog.style.top = "30px";
			dialog.style.left = "50px";
			dialog.style.visibility = "visible";
		}
		function hideProgressBarDialog()
		{
			batchRunning = false;
			var dialog = document.getElementById("atProgressBarDialog");
			dialog.style.visibility = "hidden";
		}
		function atStartBatchGeocoding(addresses, i)
		{
			if (results.length > 0)
			{
				if (maxReached)
				{
					alert("You've reached the maximum");
					maxReached = true;
					stopBatchGeocoding();
					return;
				}	
				if (confirm('Clear the previous results?'))
				{
					/*
					document.getElementById("addressResults").length = 0;
					*/
					map.ClearPushpins();
					results.length = 0;
				}
			}
			disablePage();
			batchRunning = true;
			atParseRawAddresses(addresses, i);
			showProgressBarDialog();
			
		}
		
		var batchMode = false;
		var batchNumber = 0;
		var batchMatched = 0;
		var batchRunning = false;
		var currentAddress = "";
		var maxRecs = 20;
		var maxReached = false;
		function atParseRawAddresses(addresses, i)
		{
			if (!batchRunning)
				return;

			if (i >= maxRecs)
			{
				alert("You can only geocode up to " + maxRecs + " records at a time");
				maxReached = true;
				stopBatchGeocoding();
				return;
			}
							
			method = "parseAddress";
			batchMode = true;
			//now go through and split everything and start searching.
			//addresses.replace('"','');
			addresses = replaceAll(addresses,'"','');
			addresses = replaceAll(addresses,"'",'');
			var adds = addresses.split("\n");
			var tot = adds.length-1;

			if (i < tot)
			{
				batchNumber++;
				var totPct = (batchNumber / tot)
				pb1.setPercent(totPct);

				var mRate = batchMatched / batchNumber;
				matchRateBar.setPercent(mRate);
				
				var lblProgress = document.getElementById("lblProgress");
				lblProgress.innerHTML = "Searching " + batchNumber + " of " + (tot) + " (" + batchMatched + " matched)";
				
				var s = escape(adds[i]);
				s = replaceAll(s,'%0A','');
				s = replaceAll(s,'%0D','');
				currentAddress = unescape(s);
				document.getElementById("lblInput").innerHTML = currentAddress;
				parseAddress(currentAddress);
			}
			else
			{
				stopBatchGeocoding();
			}
			
		}
		
		function stopBatchGeocoding()
		{
//			batchNumber = 0;
//			batchMatched = 0;
				
			//here is where we will open the next 'Step Panel'
			theAccordion.showTabByIndex(2, true);
			enablePage();
		}
		
/* Enable / Disable the page also with a escape key checl*/
		function disablePage()
		{
			document.onkeyup = escapeKeyCheck;
			var dis = getDisableDIV();
			docwidth = '5000';
			docheight = '5000';
			//opera Netscape 6 Netscape 4x Mozilla 
			if (window.innerWidth || window.innerHeight){ 
				docwidth = window.innerWidth; 
				docheight = window.innerHeight; 
			} 
			//IE Mozilla 
			if (document.body.clientWidth || document.body.clientHeight){ 
				docwidth = document.body.clientWidth; 
				docheight = document.body.clientHeight; 
			} 
			dis.style.width = docwidth+"px";// "5000px";
			dis.style.height = docheight+"px"; //"5000px";
			dis.style.visibility = "visible";
/*
			var list = document.getElementById("addressResults");
			if (list != null)
			{
				list.setAttribute("disabled",true);
			}
*/
		}
		
		function enablePage()
		{
			var dis = getDisableDIV();
			dis.style.visibility = "hidden";
			if (this.sandTimer != null)
			{
				this.sandTimer.style.visibility = "hidden";
			}
/*
			var list = document.getElementById("addressResults");
			if (list != null)
			{
				list.disabled = '';
			}
*/
			hideProgressBarDialog();
		}
		
		function escapeKeyCheck(e) 
		{
			var KeyID = (window.event) ? event.keyCode : e.keyCode;
			if (KeyID == 27)
			{
				enablePage();
				if (this.sandTimer != null)
				{
					this.sandTimer.style.visibility = "hidden";
				}
			}
		}
		
		function getDisableDIV()
		{
			//look for the DIV - if it doesn't exist then create
			var disDiv = document.getElementById("atDisablePage");
			return disDiv;			
		}		
		
		function showResults()
		{
			atMap.showPoints(results);
		}
		
		//Test function to search for an array of formatted addresses
		function atSearchAddress()
		{
					//Set the method variable
			method = "searchFormattedAddress";
			
			var address = new Array();
			
			//so we know if we have anything
			var haveValue = false;
			//The address to search on
			var txtBox = document.getElementById("txtStreet");
			if (txtBox.value != "")
			{
				address['address'] = txtBox.value;
				haveValue = true;
			}
			//The city to search on
			txtBox = document.getElementById("txtCity");
			if (txtBox.value != "")
			{
				haveValue = true;
				address['city'] = txtBox.value;
			}

			//The county to search on
			txtBox = document.getElementById("txtCounty");
			if (txtBox.value != "")
			{
				address['county'] = txtBox.value;
				haveValue = true;
			}
						
			//The postcode to search on
			txtBox = document.getElementById("txtPostcode");
			if (txtBox.value != "")
			{
				address['postcode'] = txtBox.value;
				haveValue = true;
			}

			//The country to search on
			txtBox = document.getElementById("txtCountry");
			if (txtBox.value != "")
			{
				address['country'] = txtBox.value;
				haveValue = true;

			}

			if (haveValue)
			{
			var recordcount = 10;
			var threshold = 0.85;
			var coordsys = 1;
			//Call the web service & get the results
			searchFormattedAddress(address, lk, recordcount, threshold, coordsys);

			}
			else
			{
				if (!batchMode)
				{
					alert("Please enter an address to search for in the text boxes above");
				}
			}
		}
		function atParseRawAddress(rawAddress)
		{
			method = "parseAddress";
			
			//rawaddress = '40 Burgess Road, Southampton, UK, SO17 3RE';
			
			parseAddress(rawAddress);
			
			
		}

		
		function atGetMapImage(i)
		{
			
			method = 'getMapImage';
			var vals = null;
			if (i == null)
			{
				vals = results[document.getElementById("lstResults").selectedIndex];
			}
			else
			{
				vals = results[i];
			}
			
			atMap.zoomTo(vals['x'],vals['y'],atMap.mapView.zoom);
			
/*			var params = new Array();
			params['x'] = vals['x'];
			params['y'] = vals['y'];
			params['zoom'] = atMap.mapView.zoom;
			params['source'] = 1; //0 - web service chooses, 1 - MapPoint, 2 - MapServer
			params['width'] = atMap.width; //400
			params['height'] = atMap.height; //400
			//alert(atMap.width);
			//Serialize the array to pass to php
			arr = php.serialize(params);
						
			//Call the web service and get the results
			getMapImage(arr);	
*/
		}
		

		//takes a string "xcoord,ycoord" and zooms to that location
		function zoomToXYString(s)
		{
			if (s != "0,0")
			{
				var a = s.split(',');
				atMap.zoomTo(a[0],a[1]);
			}
		}
		
		
		/****************************************************************************** PROGRESS BAR *********************************/
		/**
 * jt_ProgressBar.js - Progress Bar widget
 *
 * @version 29 Apr 2005
 * @author  Joseph Oster, wingo.com
 */

jt_ProgressBar = function(parent, width, fontSize, barClass) {
  // constructor for Progress Bar object; 'width' and 'fontSize' in pixels
  this.pixels = width;
  this.outerDIV = document.createElement("div");
  this.outerDIV.style.border = "1px solid #000000";
  this.outerDIV.style.background = "#FFFFFF";
  this.outerDIV.style.fontFamily = "Arial,Verdana";
  this.outerDIV.style.fontSize = fontSize + "px";
  this.outerDIV.style.width = (width + 2) + "px";
  this.outerDIV.style.textAlign = "left";
  parent.appendChild(this.outerDIV);

  this.fillDIV = document.createElement("div");
  this.fillDIV.style.textAlign = "right";
  this.fillDIV.style.overflow = "hidden";
  this.fillDIV.innerHTML = "x";
  this.fillDIV.style.width = "0px";
  if (barClass) this.fillDIV.className = barClass;
  else {
    this.fillDIV.style.background = "#00008b";
    this.fillDIV.style.border = "1px solid #FFFFFF";
    this.fillDIV.style.color = "#FFFFFF";
    }
  this.outerDIV.appendChild(this.fillDIV);
  }
var lk = 'bu0660-6101-1790';
jt_ProgressBar.prototype.setPercent = function(pct) {
  // expects 'pct' values between 0.0 and 1.0
  var fillPixels;
  if (pct < 1.0) fillPixels = Math.round(this.pixels * pct);
  else { // avoid round off error
    pct = 1.0;
    fillPixels = this.pixels;
    }
  this.fillDIV.innerHTML = Math.round(100 * pct) + "%";
  this.fillDIV.style.width = fillPixels + "px";
  }