var map;
var bounds;
var searchControl;

function mapLoad() 
{

if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("price_guide_map"));
bounds = new GLatLngBounds();
map.setCenter(new GLatLng(51.49692, -0.01874), 12); 
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.enableDoubleClickZoom();
GEvent.addListener(map, "moveend", moveend);
GEvent.addListener(map, "movestart", movestart);
searchControl = new GSearchControl();
SetupSearchControl();
moveend();
}
}
/**********************************************************************/
/* A function to setup the listener for the postcode text box         */
/**********************************************************************/
function SetupSearchControl()
{ 
this.searchInput = document.getElementById("txtPostCode"); 
this.searchInput.focus();
document.getElementById("btnPostCode").onclick = method_closure(this, newSearch, []); 

var localSearch = new GlocalSearch();
var options = new GsearcherOptions();
options.setExpandMode(GSearchControl.EXPAND_MODE_CLOSED);

localSearch.setCenterPoint(map);

searchControl.addSearcher(localSearch);

searchControl.draw(document.getElementById("results"));
searchControl.setSearchCompleteCallback(this, OnSearchComplete);

// Check if we need to do an auto search to start with?
//if (this.searchInput.value != "Enter Postcode or City")
//   {
//   newSearch();
//   }
}  
/**********************************************************************/
/* The next 2 functions handle a postcode search        */
/**********************************************************************/
function newSearch () 
{ 
this.searchInput = document.getElementById("txtPostCode"); 
if (this.searchInput.value)  
{ 
	if (this.searchInput.value.length > 1) 
	{
	  // make the search UK specific
	  var search = this.searchInput.value + ", UK";
	  searchControl.execute(search); 
	}
} 
return false; 
}
function method_closure(object, method, opt_argArray) 
{ 
  return function() 
  { 
	return method.apply(object, opt_argArray); 
  } 
}  
/**********************************************************************/
/* A function to move the map after a postcode search                 */
/**********************************************************************/
function OnSearchComplete (sc, searcher) 
{
	// if we have local search results, put them on the map
	if ( searcher.results && searcher.results.length > 0) 
	{
		var result = searcher.results[0];         
		// if this is a local search result, then proceed...
		if (result.GsearchResultClass == GlocalSearch.RESULT_CLASS ) 
		{
			var latLng = new GLatLng(parseFloat(result.lat), parseFloat(result.lng));
			
			/* saftey play */
			//hideTooMany();

			// decide if postcode or city so we know what level to zoom into
			var searchString = document.getElementById("txtPostCode").value;
			var zoom = 12;
			map.setCenter(latLng, zoom);
			/* show the search marker
			if(gSearchFlag == 1) map.removeOverlay(gSearchMarker);
			var marker = new GMarker(latLng, gSearchIcon);
			gSearchMarker = marker;
			map.addOverlay(gSearchMarker);
			gSearchFlag = 1;
			 */
			/* store search result in hidden text boxes. this allows
			us to go back to the list view at this location
			document.getElementById('txtPostCode').value = searchString
			document.getElementById('txtPostCodeLat').value = latLng.lat();
			document.getElementById('txtPostCodeLon').value = latLng.lng();
			 */

		}
	}
	else
	{
	showNotFound();
	window.setTimeout(hideNotFound, 2800);
	}
 }     

/**********************************************************************/
/* A function to show the loading message                             */
/**********************************************************************/
function showNotFound()
{
var notfounddiv = document.getElementById("price_guide_not_found");
if (notfounddiv == null)
{
	alert("Sorry can't find the price_guide_not_found");
	return;
}
//div found		
notfounddiv.style.visibility="visible";
}

/**********************************************************************/
/* A function to hide the loading message                             */
/**********************************************************************/
function hideNotFound()
{
var notfounddiv = document.getElementById("price_guide_not_found");
if (notfounddiv == null)
{
	alert("Sorry can't find the price_guide_not_found");
	return;
}
//div found
notfounddiv.style.visibility="hidden";
}		
/**********************************************************************/
/* A function to get the zoom level for the search string             */
/* Logic:                                                             */
/* For town or citys (more than 2 letters) we zoom into town level    */
/* For full postcodes we zoom into street level.                      */
/* For part postcodes we zoom into town level.                        */
/**********************************************************************/
function GetZoom(searchString)
{
var zoom = 13;
var letters = 0;

// Firts decide if its a town / city. E.g. are there more than 2 letters
// at the start of the string?
for(var j=0; j<searchString.length; j++)
{
  var chr = searchString.charAt(j);
  var code = chr.charCodeAt(0);
  if((code > 64 && code<91) || (code > 96 && code<123))
  {
  letters++;
  // we've found enough so break
  if(letters > 2) break;
  }
  else
  {
  // we found a number so quit
  break;
  }
}

// have we got a town / city?
if(letters > 2) 
  zoom = 13;
// else we've got a postcode
else
{
  // is it a partial or full postcode?
  if(searchString.length > 4) zoom = 15;
  else                        zoom = 13;
}

return zoom;
}    

/**********************************************************************/
/* mapClick is called when the user clicks the map                    */
/**********************************************************************/ 
function movestart()
    {
    map.clearOverlays();
    }		
    
/**********************************************************************/
/* Moveend is called when the user finishes dragging the map. Then    */
/* we need to request XMl of all markers in view. Then remove ones    */
/* out of view, and add any that are new and in view                  */
/**********************************************************************/            	   		
function moveend()
   {
   
   if (GBrowserIsCompatible()) 
      {
	  // get the lat / long of the map
	  var latLng = map.getBounds().getCenter();
	 
	  // set the hidden text box values for alerts
	  document.getElementById('txtLat').value = latLng.lat();
	  document.getElementById('txtLon').value = latLng.lng();
	  
	  // draw a circle
	  map.clearOverlays();
	  bounds = new GLatLngBounds();
	  var centre = map.getCenter();
	  var givenRad = document.getElementById("ddlRadius").value*1;
	  drawCircle(centre, givenRad, 60);
	  fit();
	  
	  // auto click the update button
	  var button = document.getElementById('btnUpdate');
	  button.click();
      }
    else 
      {
      alert("Sorry, the Google Maps API is not compatible with this browser");
      }
   }
		   
/**********************************************************************/
/* handleMoveEnd is called when the user finishes dragging the map.   */
/* we need to request XMl of all markers in view. Then remove ones    */
/* out of view, and add any that are new and in view                  */
/**********************************************************************/           	   		
function handleMoveEnd()
     {
     
	 
     }

function fit(){
//map.panTo(bounds.getCenter()); 
//map.setZoom(map.getBoundsZoomLevel(bounds));
}


/**********************************************************************/
/* drawCircle - draws a circle at specified pos, rad, qaulity ext     */
/**********************************************************************/	
function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
    {
    // get radius into KM's as we ask user to pass in miles
    radius = radius * 1.6
    
	//calculating km/degree
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

	//Loop 
	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step)
	{
	var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + 
	(radius/lngConv * Math.sin(i * Math.PI/180)));
	points.push(pint);
	bounds.extend(pint); //this is for fit function
	}
	points.push(points[0]); // Closes the circle
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
	map.addOverlay(poly);
    }
