var map;
var icon = new GIcon();
var to_htmls = [];
var from_htmls = [];
var htmls = [];
var gmarkers = [];
var x = 0
var gdir


var request;
var bounds = new GLatLngBounds();
var baseIcon = new GIcon();
baseIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
baseIcon.iconSize = new GSize(12, 20);
baseIcon.iconAnchor = new GPoint(6, 20);


//baseIcon.image = "images/mapIcon.png";
//baseIcon.iconSize = new GSize(76, 63);
//baseIcon.iconAnchor = new GPoint(38, 63);
baseIcon.infoWindowAnchor = new GPoint(6, 20);

baseIcon.imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0]; 
baseIcon.transparent = "mapIcons/mm_20_transparent.png";

var icons=[];

	

function addMarker(point, title, iconStr, infoUrl, x) {
   bounds.extend(point);
   var icon = baseIcon;
   var marker = new GMarker(point, icon);
 	gmarkers.push(marker);
   marker.type = iconStr; 
   
/* Code with directions      

htmls[x] ='<div style="height:160px"><img src="images/googlemap.jpg" width="220" height="97" alt="The Milky Way" style="border:1px solid #848484;" /><br />The Milky Way Adventure Park, Clovelly,<br /> Bideford, EX39 5RY Tel:01237 431 255<br />For directions, enter your postcode below:' +
           '<form action="javascript:getDirections()" style="padding:0;margin:0;">' +
           '<input type="text" style="width:100px;border:1px solid;" SIZE=10 MAXLENGTH=12 name="saddr" id="saddr" value="" />' +
           '<INPUT value="Get Directions" TYPE="SUBMIT" style="width:75px;height:20px;font-size:10px;margin-left:5px">' +
           '<input type="hidden" id="daddr" value="'+title+"@"+ point.lat() + ',' + point.lng() + 
           '"/></div>';*/


        htmls[x] ='<div style="height:150px"><img src="images/googlemap.jpg" width="220" height="125" alt="The Milky Way" /><br />The Milky Way Adventure Park, Clovelly,<br /> Bideford, EX39 5RY Tel: 01237 431 255<br /></div>';
		   
		   
GEvent.addListener(marker, "click", function () {
      marker.openInfoWindowHtml( htmls[x], {maxurl:infoUrl});
   });
  
   map.addOverlay(marker);


}

 function getDirections() {
	 
        var saddr = document.getElementById("saddr").value
        var daddr = document.getElementById("daddr").value
        
        var localSearch = new GlocalSearch();
			localSearch.setSearchCompleteCallback(null, 
			function() {
				if (localSearch.results[0])
				{		
					resultLat = localSearch.results[0].lat;
					resultLng = localSearch.results[0].lng;
					point = new GLatLng(resultLat,resultLng);
                    LtLng = String(resultLat+","+resultLng)
                    saddr = String(saddr + "@" + LtLng)
					setDirections(saddr, daddr, "en")
					}else{
					alert("Postcode not found!");
				}
			});	
		
		localSearch.execute(saddr + ", UK");
       
      }

      function myclick(x) {
        gmarkers[x].openInfoWindowHtml(htmls[x]);
      }

      function tohere(x) {
        gmarkers[x].openInfoWindowHtml(to_htmls[x]);
      }
      function fromhere(x) {
        gmarkers[x].openInfoWindowHtml(from_htmls[x]);
      }
      
 
function createRequest() {
	var ajaxRequest;
	try
	{
		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}		
		catch (e1)
		{
			try
			{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
				catch (e2)
				{
					ajaxRequest = new XMLHttpRequest();
				}
		}
	
	return ajaxRequest;
}


function usePointFromPostcode(postcode, callbackFunction, pCode, cl, propUrl,x) {
var localSearch = new GlocalSearch();
			localSearch.setSearchCompleteCallback(null, 
			function() {
			if (localSearch.results[0])
				{		
					var resultLat = localSearch.results[0].lat;
					var resultLng = localSearch.results[0].lng;
					var point = new GLatLng(resultLat,resultLng);
					var ajax_connection = createRequest();
					ajax_connection.open('get', "includes/cache.asp?postcode=" + postcode + "&latitude=" + resultLat + "&longitude=" + resultLng);
					ajax_connection.send(null);
					callbackFunction(point, pCode, cl, propUrl,x);
				}else{
					alert("Postcode not found!");
				}
			});	
		
		localSearch.execute(postcode + ", UK");
}

function placeMarkerAtPoint(point)
{
	var marker = new GMarker(point,icon);
	map.addOverlay(marker);
}

function setCenterToPoint(point)
{
	map.setCenter(point, 17);
}
 function createMarker(point,html,infoUrl) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html, {maxUrl:infoUrl});
        });
        return marker;
      }
function showPointLatLng(point)
{
	alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}
function addOverlayMap(point, propHTML, propURL) {
	map.addOverlay(createMarker(point, propHTML , propURL));
}

function mapLoad() {
	if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
		map.addControl(new GMapTypeControl ());
		map.addControl(new GSmallMapControl());
		map.enableContinuousZoom()
		map.enableScrollWheelZoom()
		map.setCenter(new GLatLng(50.981682,-4.393888), 12, G_NORMAL_MAP);
		//map.setCenter(new GLatLng(50.466356,-3.515453), 15, G_SATELLITE_MAP);
		gdir = new GDirections(map, document.getElementById("directions")); 
        GEvent.addListener(gdir, "load", onGDirectionsLoad); 
        GEvent.addListener(gdir, "error", handleErrors);    
		//var point = new GLatLng(parseFloat(50.460182), parseFloat(-3.519616));
		var point = new GLatLng(parseFloat(50.981682), parseFloat(-4.393888));
		var propUrl = "";
		var propHTML = String("The Milky Way");
		var pCode = String("EX39 5RY");
		addMarker(point, "The Milky Way", 'red', propUrl, 1)	
		//map.addControl(new GOverviewMapControl(null)); 
	}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function addUnLoadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
	  window.onunload = func;
	} else {
	  window.onunload = function() {
	    oldonunload();
	    func();
	  }
	}
}

function setDirections(fromAddress, toAddress, locale) { 
      gdir.load("from: " + fromAddress + " to: " + toAddress, 
                { "locale": locale }); 
    } 
function onGDirectionsLoad(){ 
          enteredPostcode = document.getElementById("saddr").value;
            document.getElementById("directions").innerHTML = '<a href="http://maps.google.com/maps?f=d&hl=en&geocode=8926868973704302352,50.985721,-4.381399&time=&date=&ttype=&saddr=' + enteredPostcode + '&daddr=Clovelly,+Bideford,+Devon+EX39+5RY,+UK&mra=pi&mrcr=0&sll=50.985721,-4.381399&sspn=0.003415,0.007231&ie=UTF8&z=10&om=1&pw=2" target="_blank"><img src="images/print.gif" width="19" height="16" alt="print directions" border="0" style="margin-bottom:-4px;" /> Print Directions</a>'
	  map.closeInfoWindow();
    } 


    function handleErrors(){ 
       if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) 
         alert("Either the \"To\" or \"From\" geographic location cannot be found.\nPlease use a postal code or recognised city instead.\nThe postal code for St Thomas Church is NE1 7PF.\nError code: " + gdir.getStatus().code); 
       else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) 
         alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code); 

       else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) 
         alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code); 

       else if (gdir.getStatus().code == G_GEO_BAD_KEY) 
         alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code); 

       else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) 
         alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code); 

       else alert("An unknown error occurred."); 

    }        

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);