//-------------------------------- Geocoding Section ------------------------------------//
function showAddress(country, geocode, search, selector, selForm, selBox, message, srs) 
{
	//------------------------------------------------------------------------------------------------//
	//
	//	Country : text string used to limit the geocode to australia NZ
	//	geocode	: text string defining the Div that contains all the address entry divs 
	//	search	: text string defining the Div Id of INPUT element of address 
	//  selector: test string defining the Div that contains all the address selection divs
	//	selForm	: text string defining the Form element that is used to select from list of addresses
	//	selBox	: text string defining the Class name of the selForm
	//	message	: text string defining the Div of the message regarding too many points returned
	//	srs		: EPSG code for this map
	//
	//------------------------------------------------------------------------------------------------//

	pointZoom = markerZm;
	var address= document.getElementById(search).value;
	//alert (address)
	if (address == '' || address == null){alert('address = null'); return false;}
    var searchRequest = address +" "+country;
	//alert(searchRequest)
	//alert('lastAccuracy = '+ lastAccuracy)
    
	//--------------- This will get up to 10 matched addresses --------------------//        
    geocoder.getLocations(searchRequest, function (result)
    { 

		// initialise the geocoder selection boxes
		loLat=999999999; hiLat=-999999999; loLng=99999999; hiLng=-99999999;

		// Check is comboBox present and kill it off
		checkRemoveObject('combo')
		
		// Clear out any orphan markers
		if (markers) {markers.clearMarkers(); markers.addOptions({'displayInLayerSwitcher': false});}	
				
		// If all is well go and get the geocoded the address 
		if (result.Status.code == G_GEO_SUCCESS) 
		{		  
			// Loop through the results, placing markers
			var noItems = result.Placemark.length
			//if (result.Placemark.length == 10)
			//{	alert('10 or more candidates - you may need to enter more infromation to reduce the number of possible candidates');
				//document.getElementById(message).style.display='block';	
			//}
				
			// we have more than 1 address so go and build the drop down select box
			//alert('no = '+no)
			if (noItems > 1) 
			{				
					MochaUI.AddressHelpWin(country, geocode, search, selector, selForm, selBox, message, srs, result, searchRequest, noItems);								
			}
			// we only have one address so jump to it
			else if (noItems == 1)
			{
				// Only one in collection so plot it only
				var p = result.Placemark[0].Point.coordinates;
				var currentAccuracy = result.Placemark[0].AddressDetails.Accuracy;
				
				// transform geogs to google if required
				if (srs == 'EPSG:900913') 
				{	point = geogs2google(p);	}
				else
				{	point = new OpenLayers.LonLat(p[0], p[1]);	}
				
				// create the marker on the map
				var addrs = result.Placemark[0].address;				
				markers = new OpenLayers.Layer.Markers( searchRequest );
				map.addLayer(markers);
				p = decodePoint (point);
				createIcon(p[0], p[1], symbol, '40', '40');	
				
				// if parcel layer selected by user
				var tester = boundaryRequired();
		
				// either plot and move-to the single point or generate the boundary and plot move-to that
				if(tester == 'NONE' || tester == '' || currentAccuracy < 8) 
				{	map.setCenter(point, pointZoom);	return;}	
				else
				{	showBoundary('propertyControl', ""); 	}
				
			}
		}			
        //---------------------------- Decode the error status -----------------------------------//
        else
		{
            alert('Could not find "'+searchRequest+ '" ');
		}
		
   });
}


function addrAssistant(country, search, selector, selBox, message, srs, result, searchRequest, noItems)
{
	// build the select box
	var shForm = $('selForm');
	bindEvent(shForm.selFormOptions, 'change', selectAddress, 'false');

	// create each marker
	markers = new OpenLayers.Layer.Markers(searchRequest);
	map.addLayer(markers);
	

	// Ok now get all the candidate addresses as Options
	//alert('number of candidates = '+noItems)
	for (i=0; i < noItems; i++)
	{	
		var init=false;
		if (i==0){init=true}
		var addrs = result.Placemark[i].address;
		var p = result.Placemark[i].Point.coordinates;
		
		// transform geogs to spherical coords if required
		if (srs == 'EPSG:900913') 
		{
			var point = geogs2google(p);
			// decode point back into p 
			p = decodePoint(point);
		}
		else
		{	var point = new OpenLayers.LonLat(p[0], p[1]);	}

		// stepwise calculate centre of gravity of collection and zoom to it
		adjustBoundsExtent(p[1],p[0],i);
			
		// add the choices as options to the combo select element
		optionElement = document.createElement('option');
		//point = new OpenLayers.LonLat(p[0], p[1]);
		var ptr = i+1;
		
		//alert ('option value = '+addrs+" "+point);
		optionElement.text = addrs;
		optionElement.innerText = addrs;
		optionElement.value = addrs+" "+point;
		optionElement.id='searchOpt:'+ptr;
		optionElement.setAttribute('id','searchOpt:'+ptr);

		//optionElement.className='unselectedItem';	
		//bindEvent(optionElement, 'mouseover' , overOption, 'false');
		//bindEvent(optionElement, 'mouseout' , outOption, 'false');		

		// append to select box
		shForm.selFormOptions.appendChild(optionElement);

		// draw an icon at each location in collection
		createIcon(p[0],p[1], symbol, '40', '40');	
		
	}
	// finalise Select Options
	//lastAccuracy = 0;
	bounds = new OpenLayers.Bounds(loLng,loLat,hiLng,hiLat);
	// this will zoom appropriately for collection
	map.setCenter(bounds.getCenterLonLat(),map.getZoomForExtent(bounds)-1); 
	
	// write out optional message about more than 10 candidates
	if(noItems < 10)
	{	var text = 'You have found more than one candidate location for the address entered.';
		var color = 'black';}
	else
	{	var text = 'There were 10 or more candidates returned! \n You may need to enter more address infromation to reduce the number of possible candidates found.';
		var color = 'red';}
	
	//create the ne message element
	var message = document.getElementById(message);
	checkRemoveObject('moreThanTen');
		var messtext = document.createElement('div');
		messtext.style.width='100%';
		messtext.style.color = color;
		messtext.id='moreThanTen';
		messtext.setAttribute('id','moreThanTen');
		var text = document.createTextNode(text);
		messtext.appendChild(text);
	message.appendChild(messtext);
	message.style.display='block';				
}

function overOption(evt)
{
	document.getElementById(getThisId(evt)).className='selectedItem'
}
function outOption(evt)
{
	document.getElementById(getThisId(evt)).className='unselectedItem';
	//new Event.stop(evt);
}


function adjustBoundsExtent(glat, glng, number)
{
	//Convert Lat and Long to numerical values
	var lat=parseFloat(glat);
	var lng=parseFloat(glng);

	// calculate bounding box of coords	
	if (lat < loLat) {loLat=lat;}
	if (lat > hiLat) {hiLat=lat;}
	if (lng < loLng) {loLng=lng;}
	if (lng > hiLng) {hiLng=lng;}
}

function decodePoint(point)
{
	//alert('decodePoint = '+point)
	var tmpLL = point.toString();
	var tempP = tmpLL.split(',');
	var p = [];
	var lng = tempP[0].split('='); p[0] = lng[1];
	var lat = tempP[1].split('='); p[1] = lat[1];
	//alert(p)
	return p;
}
function geogs2google (p)
{
	var lonlat = new OpenLayers.LonLat(p[0], p[1]);
	var point = lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
	return point;
}
function google2geogs (p)
{
	var lonlat = new OpenLayers.LonLat(p[0], p[1]);
	var point = lonlat.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
	return point;
}

// --------------------- Create an icon at the position desired ---------------------------- //
function createIcon(lng, lat, symbol, wd, ht)
{
	var size	= new OpenLayers.Size(wd, ht);
	var offset	= new OpenLayers.Pixel(-(size.w/2), -size.h/2);
	var icon	= new OpenLayers.Icon(symbol, size, offset);	
	marker		= new OpenLayers.Marker(new OpenLayers.LonLat(lng, lat), icon);
	markers.addMarker(marker);
	resetZlevels();
	//markers.setZIndex(map.Z_INDEX_BASE['Popup'] -100)
	markers.setOpacity(0.7);
	if(document.getElementById('targetButt'))
	{
		document.getElementById('targetButt').className="hoverButton"	;
		document.getElementById('targetControl').title='hide targets at locations';
	}
	markers.events.register('click', marker, function(evt) { markers.clearMarkers(); OpenLayers.Event.stop(evt); });
	return markers;
}

// --------------- function to set map to the address selected by the user from a select box
function selectAddress (evt)
{
	var combo_Id = getThisId(evt)
	
	// Get the selected address and its location from the combo box
	var comboBox = document.getElementById(combo_Id);
	if (comboBox.selectedIndex == 0){return;}
	var fullAddr = comboBox.options[comboBox.selectedIndex].value;
	var addressParts = fullAddr.split(' lon');
	var point = 'lon'+addressParts[1];

	// decode point back into p 
	var tmpLL = point.toString();
	var tempP = tmpLL.split(',');
	var p = [];
	var lng = tempP[0].split('='); p[0] = lng[1];
	var lat = tempP[1].split('='); p[1] = lat[1];
	if (markers) {markers.clearMarkers(); markers.addOptions({'displayInLayerSwitcher': false});}	
	createIcon(p[0],p[1], symbol, '40', '40');	
	
	// push selected address into the search box
	currentAddress = addressParts[0].replace(/,/g, ' ');
	if(document.getElementById("search")){document.getElementById("search").value = currentAddress;	}
	
	// zoom to the selected address
	map.setCenter(new OpenLayers.LonLat(p[0],p[1]), pointZoom);	

}

 function searchon(selector, geocode, search, message)
 {
	if (markers) 
	{
		markers.setVisibility(false); 
		if(document.getElementById('targetButt'))
		{
			document.getElementById('targetButt').className="standardButton"	;
			document.getElementById('targetControl').title='show targets at locations';
		}
	}	
	if(document.getElementById('propertyButt'))
	 {
		document.getElementById('propertyButt').className="standardButton"	;
		document.getElementById('propertyControl').title='show boundary at address';
		if(boundary){boundary.setVisibility(false);}
	 }

	//document.getElementById(selector).style.display="none";
	document.getElementById(message).style.display='none';
	document.getElementById(geocode).style.display="block";
	document.getElementById(search).value ='';
	if(document.getElementById('search'))
	{ document.getElementById(search).value =document.getElementById('search').value;	 }
	else {document.getElementById(search).value ='';}
	
	// set the focus to the address data entry box
	document.getElementById(search).focus();
 }

// ------------------ function to check if object exists and if so remove it --------------------
function checkRemoveObject(oId)
{
	if (document.getElementById(oId))
	{	
		var obj = document.getElementById(oId);
		obj.parentNode.removeChild(obj);
		obj.value=null;
	}
}


