var Gmap;
var map;
var mapCL;
var directionsPanel;
var gnPropertyTypes
var directions;
var lDebugOn = true;
var lMSXML = true;
var gsXML;
var baseIcon1 = new GIcon();
var baseIcon2 = new GIcon();
var baseIcon3 = new GIcon();
var baseIcon1g = new GIcon();
var baseIcon2g = new GIcon();
var baseIcon3g = new GIcon();
var glIconsSetup = false;
var gsRoute = new String
var nCallID = 1;
var loadingControl;
var bRecalculateTable;
var sRouteText;

var MapArray;
var DirectionArray;

var m_nZoomLevel = 12;  //Zoom Level when viewing "properties near here"
var m_bNearRange = 1.5; //Range in miles from waypoint, to calculate properties near here. 

//http://code.google.com/apis/maps/documentation/reference.html

function initializeGmap(nCentreX, nCentreY, nZoom, nPropertyTypes, nMapType, nIcon) 
{
    
    
    if (GBrowserIsCompatible()) 
    {
    
    /*
    nMapType = 1 - route planner map
    nMapType = 2 - hotel "pop-up" map
    nMapType = 3 - hotel mini-map
    
    */
        bRecalculateTable = true;
        var singlePoint;

        var MapElement;
        
        MapElement = document.getElementById("map")
        
        if (MapElement == null)
        {
            return;
        }
        
        //map = new GMap2(document.getElementById("map"));
        Gmap = new GMap2(MapElement);
        
       
        
        if (nMapType == 3) 
        {
            Gmap.addControl(new GSmallMapControl());
            //Gmap.addControl(new GSmallZoomControl());
        } 
        else 
        {
            Gmap.addControl(new GLargeMapControl());
            Gmap.addControl(new GMapTypeControl());
            Gmap.addControl(new GScaleControl());
            //Gmap.addControl(new GOverviewMapControl());
        
        }

        if (isNaN(nPropertyTypes)) 
        {
            gnPropertyTypes = 5;
        } 
        else 
        {
            gnPropertyTypes = nPropertyTypes;
        }
        
        
        //Debug("initGM, PropTypes = " + gnPropertyTypes);
        //Debug("initGM, MapType = " + nMapType);

        if (isNaN(nMapType))
        {
            nMapType = 1;
        }

        if (nMapType == 1 ) 
        {
            loadingControl = new DALoadingControl();

		    Gmap.addControl(loadingControl);

            //directionsPanel = document.getElementById("route");
            //directions = new GDirections(Gmap, directionsPanel);
            
            //directions = new GDirections(Gmap);
            
            
        /*    GEvent.addListener(directions ,"load", function() 
            {
                setTimeout('customPanel(map,"map",directions,document.getElementById("route"))', 1);
            }
            
          );*/
            
		}
  

        if (isNaN(nZoom)) 
        {
            Gmap.setCenter(new GLatLng(nCentreY, nCentreX));   
//            Gmap.setCenter("Valencia, Spain");   
        }
        else 
        {
            Gmap.setCenter(new GLatLng(nCentreY, nCentreX), nZoom);   
        }

        SetupIcons();
      
        if (nMapType == 1 ) 
        {
                    
            SetXML(Gmap, false);
            
            if (gsRoute.length > 0)
            {
                addRouteToMap(false);
            }

            GEvent.addListener(Gmap, "dragend", MapMove);
            GEvent.addListener(Gmap, "zoomend", MapMove);


        }
        
        
        if (nMapType >= 2 ) 
        {
            // put a point at the passed coordinates
            singlePoint = new GLatLng(nCentreY, nCentreX);
            
            Gmap.addOverlay(createMarker(singlePoint, "", nIcon, -1));
        }
    }
}

function SetXML(pGmap, bIsMiniMap)
{
    // use the Google GXmlHttp object
    
    

    
    var oGBounds = pGmap.getBounds();
    var nThreadID;
    
    loadingControl.hide();
    loadingControl.show();
    
    //this clear all points off.
    //Gmap.clearOverlays();
        
    var sURL;
    
    //sURL = getURL(pGmap.getBounds(), bIsMiniMap);
    sURL = getURL(pGmap, bIsMiniMap);


    // Create an instance of the XML HTTP Request object
    var oXMLHTTP = new GXmlHttp.create();
    
// can't decide if this should be true or false!
    oXMLHTTP.open( "GET", sURL, true);

    nCallID++;
    nThreadID = nCallID;

    oXMLHTTP.onreadystatechange = function ()
    {

        if (oXMLHTTP.readyState == 4)
        { 
            //alert('Here Status = 4');
            gsXML = oXMLHTTP.responseText;

            UseXML(nThreadID, pGmap, bIsMiniMap);
        } 
        else
        {
            //alert('Here Status = ' + oXMLHTTP.readyState);
            
            if (nThreadID != nCallID)
            {
                oXMLHTTP.abort();
            }
        }
    }



    oXMLHTTP.send(null);

    return false;
}

function UseXML(nThisCallID, pGmap, bIsMiniMap) 
{
    //we have xml, now use it
    
    //only do this if we're on the latest call!!!
    
    if (nThisCallID == nCallID) 
    {

        try //Internet Explorer
        {
            xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async="false";
            xmlDoc.loadXML(gsXML);
        }  
        catch(e)
        {
            try // Firefox, Mozilla, Opera, etc.
            {
                parser=new DOMParser();
                xmlDoc=parser.parseFromString(gsXML,"text/xml");
            }
            catch(e)
            {
                alert(e.message);
                return;
            }
        }

        var oNodes;
        var oNode;

        oNodes = xmlDoc.getElementsByTagName("Property");

        var sLabel = new String;
        var sPropertyName = new String;        
        var snRef = new String;
        var nX = new Number;
        var nY = new Number;
        var point;
        var nGroup = new Number;
        var nIcon = new Number;
        
        var sPictureURL = new String;


        for ( i=0; i<oNodes.length; i++ ) 
        {
        
            
        
            oNode = oNodes[i];
                  
            //get the details for this node       
            
            // I don't like refering to fields using numbers, but it's the only way I can find at the moment
            
            nX = oNode.getElementsByTagName("value")[0].firstChild.nodeValue;
            nY = oNode.getElementsByTagName("value")[1].firstChild.nodeValue;
            snRef = oNode.getElementsByTagName("value")[2].firstChild.nodeValue;
            nIcon = Number(oNode.getElementsByTagName("value")[3].firstChild.nodeValue);
            nGroup = Number(oNode.getElementsByTagName("value")[4].firstChild.nodeValue);
            sPropertyName = oNode.getElementsByTagName("value")[5].firstChild.nodeValue;
            
            
            
            if (nGroup == 0) 
            { 
                // This is an individual property
                if (bIsMiniMap ==false)
                {
                    if (nIcon == 1)
                    {
                        // this is a(n) hotel
                        sLabel = "<h3>" + sPropertyName + "</h3>";
                        sLabel += "<a href=" + '"' + "/hotel_details.asp?hotelID=";
                        sLabel += snRef + '"' ;
                        sLabel += ' target="_blank" ';
                        sLabel += ">View more details</a>";
                        sLabel += "<br />Page will open in a new window";
                        //sLabel += '<script type="text/javascript">alert("hello");</script>';
                    } 
                    else
                    {
                                            
                        // this is self-catering
                        
                        sPictureURL = oNode.getElementsByTagName("value")[6].firstChild.nodeValue;                                                
                        sLabel = '<div class="bubble" style="height:140px; width: 240px">';                        
                        sLabel += "<h3>Self-catering property " + sPropertyName + "</h3>";
                        if(sPictureURL!='no-image'){
                          //sLabel += '<a href="http://www.interhome.co.uk/Holiday+apartment/Select/';
                          //sLabel += snRef + '/EN-GB.html?partnerID=GB359997&lCode=EN-GB" target="_blank" >';
                          sLabel += "<a href=" + '"' + "/self_catering_view.asp?nref=";
                          sLabel += snRef + '"' ;
                          sLabel += ' target="_blank" >';                                                                          
                          sLabel += '<img style="border: none; height: 80px; float: right" src="'+sPictureURL+'" />';
                          sLabel += '</a>';
                        }
                        sLabel += '<br />';
            //            sLabel += "<a href=" + '"' + "http://www.drive-alive.co.uk/self_catering_view.asp?nref=";
                        
                        // tb 2009-04-08 - update to go to Interhome?
                        //sLabel += '<a href="http://www.interhome.co.uk/Holiday+apartment/Select/';
                        //sLabel += snRef + '/EN-GB.html?partnerID=GB359997&lCode=EN-GB" ';
                        // else normal...                        
                        sLabel += "<a href=" + '"' + "/self_catering_view.asp?nref=";
                        sLabel += snRef + '"' ;
                        sLabel += ' target="_blank" ';
                        sLabel += '>View more details</a>';                        
                        sLabel += "<br />Page will open in a new window";
                        sLabel += '<div style="clear:both"></div>';                        
                        sLabel += '</div>';
                    }
                }
                else
                {
                    if (nIcon == 1)
                    {
                        sLabel = "<font style='font-size:10px;'><font style='margin-top:0px;font-weight:bold;'>" + sPropertyName + "</font><br />";
                        sLabel += "<a href=" + '"' + "/hotel_details.asp?hotelID=";
                        sLabel += snRef + '"' ;
                        sLabel += ' target="_blank" ';
                        sLabel += ">View more details</a>";
                        sLabel += "<br />Page will open in a new window";
                        sLabel += "</font>";
                    } 
                    else
                    {
                        // this is self-catering
                        sLabel = "<font style='font-size:10px;'><font style='margin-top:0px;font-weight:bold;'>Self-catering property " + sPropertyName + "</font><br />";
                        
                        // tb 2009-04-08 - update to go to Interhome
                        //sLabel += '<a href="http://www.interhome.co.uk/Holiday+apartment/Select/';
                        //sLabel += snRef + '/EN-GB.html?partnerID=GB359997&lCode=EN-GB" ';
                        // else normal..
                        sLabel += "<a href=" + '"' + "/self_catering_view.asp?nref=";
                        sLabel += snRef + '"' ;
                        sLabel += ' target="_blank" ';
                        sLabel += ">View more details</a>";
                        sLabel += "<br />Page will open in a new window";
                    }
                
                }
            }
            else
            {
                // don't use this anymore
                sLabel = "<h3>Properties in the vicinity: " + snRef + "</h3>";
                sLabel += '<a href="javascript:RepositionMap(Gmap.getInfoWindow());"';
                sLabel += ">Click to move</a>";
            }

            point = new GLatLng(nY, nX);
            
            pGmap.addOverlay(createMarker(point, sLabel, nIcon, nGroup));

            //alert(nX);
        }
    }
    loadingControl.hide();
}


function Debug(sMessage) 
{
    if (lDebugOn) 
    {
        alert("Debug: " + sMessage);    
    }
}

function getURL(pGMap, bIsMiniMap) 
{

    var oGBounds;
    var lsURL;
    var nDigits;
    
    oGBounds = pGMap.getBounds();
    
    nDigits = 6;
    
//        alert(oGBounds.getSouthWest().lat());
//        alert(oGBounds.getSouthWest().lat());
    
    lsURL = "/mapping/map-engine.asp?";
    lsURL += "nTopLeftX=" +  digitRound(oGBounds.getSouthWest().lng(), nDigits);
    lsURL += "&nTopLeftY=" + digitRound(oGBounds.getNorthEast().lat(), nDigits);
    lsURL += "&nBottomRightX=" + digitRound(oGBounds.getNorthEast().lng(), nDigits);
    lsURL += "&nBottomRightY=" + digitRound(oGBounds.getSouthWest().lat(), nDigits);
    lsURL += "&nPropertyTypes=" + gnPropertyTypes;
//    lsURL += "&nProperties=2";
    
    if (bIsMiniMap == true)
    {
        lsURL += "&nZoom=14";  //Don't cluster!!
    }
    else
    {
        lsURL += "&nZoom=" + pGMap.getZoom();
    }

    //alert(lsURL);

    return lsURL;
}


function SetupIcons() 
{
    if (glIconsSetup == false) 
    {
        // Create a base icon for all of our markers that specifies the
        // shadow, icon dimensions, etc.
//        baseIcon1.image = "/resources/mapping/mapiconpoi1.png";
        baseIcon1.image = "/resources/mapping/hotel_single_map_icon.gif";
        baseIcon1.iconAnchor = new GPoint(8, 8);
        baseIcon1.infoWindowAnchor = new GPoint(9, 2);
        //baseIcon1.infoShadowAnchor = new GPoint(18, 25);

        //baseIcon1g.image = "/resources/mapping/mapiconpoi1g.png";
        baseIcon1g.image = "/resources/mapping/hotel_group_map_icon.gif";
        baseIcon1g.iconAnchor = new GPoint(8, 8);
        baseIcon1g.infoWindowAnchor = new GPoint(9, 2);
        //baseIcon1g.infoShadowAnchor = new GPoint(18, 25);
  
        baseIcon2.image = "/resources/mapping/mapiconpoi2.png";
        baseIcon2.iconAnchor = new GPoint(8, 8);
        baseIcon2.infoWindowAnchor = new GPoint(9, 2);
        //baseIcon2.infoShadowAnchor = new GPoint(18, 25);

        baseIcon2g.image = "/resources/mapping/mapiconpoi2g.png";
        baseIcon2g.iconAnchor = new GPoint(8, 8);
        baseIcon2g.infoWindowAnchor = new GPoint(9, 2);
        //baseIcon2.infoShadowAnchor = new GPoint(18, 25);
  
//        baseIcon3.image = "/resources/mapping/mapiconpoi3.png";
        baseIcon3.image = "/resources/mapping/selfcat_single_map_icon.gif";
        baseIcon3.iconAnchor = new GPoint(8, 8);
        baseIcon3.infoWindowAnchor = new GPoint(9, 2);
        //baseIcon3.infoShadowAnchor = new GPoint(18, 25);

        //baseIcon3g.image = "/resources/mapping/mapiconpoi3g.png";
        baseIcon3g.image = "/resources/mapping/selfcat_group_map_icon.gif";                
        baseIcon3g.iconAnchor = new GPoint(8, 8);
        baseIcon3g.infoWindowAnchor = new GPoint(9, 2);
        //baseIcon3g.infoShadowAnchor = new GPoint(18, 25);
        
        glIconsSetup = true;
    }
}    

function createMarker(point, sLabel, nIcon, nGroup) 
{
    //todo - shift these out for ease of readability?
    
    //Debug("CM: " + nIcon);
    
    switch (nIcon)
    {
        case 1:
            if (nGroup == 1) 
            {
                var marker = new GMarker(point, {icon:baseIcon1g, draggable:false, bouncy:false});
            } 
            else
            {
                var marker = new GMarker(point, {icon:baseIcon1, draggable:false, bouncy:false});
            }
            break;
        case 2:
            if (nGroup == 1)
            {
                var marker = new GMarker(point, {icon:baseIcon2g, draggable:false, bouncy:false});
            }
            else
            {
                var marker = new GMarker(point, {icon:baseIcon2, draggable:false, bouncy:false});
            }
            break;
        case 3:
            if (nGroup == 1) 
            {
                var marker = new GMarker(point, {icon:baseIcon3g, draggable:false, bouncy:false});
            } 
            else 
            {
                var marker = new GMarker(point, {icon:baseIcon3, draggable:false, bouncy:false});
            }
            break;
        default:
            var marker = new GMarker(point);
            break;
    }
   
    
    if (nGroup >= 0) 
    {
        if (nGroup == 1) 
        {
            GEvent.addListener(marker, "click", function() 
            {
                RepositionMap(marker.getLatLng());
            });
        } 
        else 
        {
/*
            GEvent.addListener(marker, "mouseover", function() {
                marker.openInfoWindowHtml(sLabel);
                });
*/
            GEvent.addListener(marker, "mouseover", function() 
            {           
                marker.openInfoWindowHtml(sLabel);
            });
/*
            GEvent.addListener(marker, "mouseout", function() {
                marker.closeInfoWindow();
                });
*/                
                
        }
    }
        
    return marker;
}

function digitRound(nNumber, nDecimals) 
{
    //returns a string rounded to the number of decimals
    
    var sReturn = new String;
    var nHolding;
    var m;
    

//        alert(nNumber);

    m = Math.pow(10, nDecimals);
    
    nHolding = nNumber * m;
    
    //alert(nHolding);
    
    nHolding = Math.round(nHolding);

//        alert(2 ^ 3);

    //alert(nHolding);
    
    nHolding = nHolding / m;

//        alert(nHolding);
    
    sReturn += nHolding;
    
    var s;
    
    s = sReturn.replace(/\./g, "%2E");
    
    //sReturn.replace(/sdfasd/, /asdfasdfasE/);
           
    return s;
}


////////////////////////////////////////////////////////////////////////
/// Some testing functions
////////////////////////////////////////////////////////////////////////


function PlotDummyPoints() {
    if (GBrowserIsCompatible()) {
        var point;

        point = Gmap.getCenter();
        Gmap.addOverlay(createMarker(point, "Center of map!", 2));

        point = new GLatLng(46, 4);
        Gmap.addOverlay(createMarker(point, "Ian1", 3));

        point = new GLatLng(45, 7);
        Gmap.addOverlay(createMarker(point, "Ian2", 3));
    }
    
    return false;
}

function PlotFourCorners() {
    if (GBrowserIsCompatible()) {
        var point;
        var oBounds;
        var oPointNW;
        var oPointSW;
        var oPointNE;
        var oPointSE;
        
        oBounds = Gmap.getBounds();
        
        oPointSW = oBounds.getSouthWest() 
        oPointNE = oBounds.getNorthEast() 

        Gmap.addOverlay(createMarker(oPointSW, "SW", 4));
        Gmap.addOverlay(createMarker(oPointNE, "NE", 4));
    }
    
    return false;
}

function PlotDummyPoints2() {
    if (GBrowserIsCompatible()) {
        var point;

        point = new GLatLng(43, 4);
        Gmap.addOverlay(createMarker(point, "Ian1", 1));

        point = new GLatLng(43, 5);
        Gmap.addOverlay(createMarker(point, gsXML, 1));
    }
    
    return false;
}

////////////////////////////////////////////////////////////////////////
/// Route Planning Functions
////////////////////////////////////////////////////////////////////////

function SetRoute(sFrom, sTo, nPropertyTypes){
  //make gsRoute up from points?
  // should have already been validated on the asp page

  var localSearchFrom = new GlocalSearch();
  var localSearchTo = new GlocalSearch();

    sRouteText = "From " + sFrom + " to " + sTo;

  localSearchFrom.setSearchCompleteCallback(null, 
    function() {
      if (localSearchFrom.results[0]) {    
        var resultLatFrom = localSearchFrom.results[0].lat;
        var resultLngFrom = localSearchFrom.results[0].lng;

        //now do "to"        
        localSearchTo.setSearchCompleteCallback(null, 
          function() {
            if (localSearchTo.results[0]) {    
              var resultLatTo = localSearchTo.results[0].lat;
              var resultLngTo = localSearchTo.results[0].lng;
        
              // got from and to now.
              gsRoute = resultLatFrom + ", " + resultLngFrom + " to " + resultLatTo + ", " + resultLngTo; 

              initializeGmap(0, 0, 17, nPropertyTypes);
            } else {
              alert("Could not find location: " + sTo);
            }
          });
        localSearchTo.execute(sTo);
      } else {
        alert("Could not find location: " + sFrom);
      }
    });

    localSearchFrom.execute(sFrom);

}


function ValidateLocation_GLocal(sLocation, SuccessFunction, FailureFunction, oObject, oLabel){
  var localSearch = new GlocalSearch();

  localSearch.setSearchCompleteCallback(null, 
    function() {
      if (localSearch.results[0]) {    
        SuccessFunction(oObject, oLabel);
      } else {
        FailureFunction(oObject, oLabel);
      }
    });

  localSearch.execute(sLocation);
}

//local search seems better, so this doesn't get used
function SetRoute_GeoCoder(sFrom, sTo, nPropertyTypes){
  //make gsRoute up from points?
  // should have already been validated on the asp page

  var geocoder;
  geocoder = new GClientGeocoder();

  geocoder.getLatLng(sFrom,
    function(point1) {
      if (point1) {
        //alert(point1.toString());
        // got the first point, now find the second
        geocoder.getLatLng(sTo,
          function(point2) {
            if (point2) {
              //alert(point2.toString());
              // got both points, so build gsRoute    
              //alert(point1.x);  
              gsRoute = point1.y + ", " + point1.x + " to " + point2.y + ", " + point2.x; 
              //alert(gsRoute);
              initializeGmap(0, 0, 17, nPropertyTypes);
            } else {
              alert("Could not find location: " + sTo);
            }
          });
      } else {
        alert("Could not find location: " + sFrom);
      }
    });
}


function ValidateLocation_GeoCoder(sLocation, SuccessFunction, FailureFunction, oObject, oLabel){
    
    //Debug("Validating:" + sLocation);

    var geocoder;
    geocoder = new GClientGeocoder();

    geocoder.getLatLng(sLocation,
        function(point) {
            if (point) {
                //Debug("Calling success:" + sLocation);
                //Debug("point.toString() :" + point.toString());
                SuccessFunction(oObject, oLabel);
            } else {
                //Debug("Calling failure:" + sLocation);
                FailureFunction(oObject, oLabel);
            }
        });

    //Debug("End Of Validating:" + sLocation);

}


function FindLocation(sLocation, nPropertyTypes){
    
//   Debug(sLocation);

    var geocoder;
    var mapZoomLevel;

    mapZoomLevel=12;
    if($get('mapZoomLevel').value!='') {
    	mapZoomLevel=parseInt($get('mapZoomLevel').value);
    }
    
    geocoder = new GClientGeocoder();

    gsRoute = "";
    
    geocoder.getLatLng(sLocation,
        function(point) 
        {
            if (!point) 
            {
                alert(sLocation + " not found.");
                initializeGmap(4, 50, 4, nPropertyTypes);
            }
            else 
            {
                initializeGmap(point.lng(), point.lat(), mapZoomLevel, nPropertyTypes);
            }
        });
}

function P2P(sFrom, sTo)
{

//    defineGmapObjects();

    gsRoute = sFrom + " to " + sTo;
//    Debug("from P2P - addRoutetoMap");
    alert(gsRoute);
    addRouteToMap(false);

//    Debug("PSP:" + gsRoute);
    SetXML(Gmap, false);
}

function addRouteToMap(lPreserveViewPort)
{
    directions = new GDirections(Gmap);
    
    var Params;
    
    if (document.getElementById('chkAvoidHW').checked)
    {
        Params = {"avoidHighways": true, "getSteps":true, "preserveViewport":lPreserveViewPort};
    }
    else
    {
        Params = {"avoidHighways": false,"getSteps":true, "preserveViewport":lPreserveViewPort};
    } 
    
    
    if (bRecalculateTable == true)
    {   
        GEvent.addListener(directions ,"load", function() 
        {
            setTimeout('customPanel("map","map",directions,document.getElementById("route"))', 1);
            //alert('Redone Route Table');
            Gmap.savePosition();
        });
        
        
        //CL Added 31/03/2009
        GEvent.addListener(directions ,"error", function() 
        {
            alert('Unable to create a route between the specified locations, please use your back button to change locations as required.');            
        });
        //CL Added 31/03/2009
    }
    
    directions.load(gsRoute, Params);
    
}

function SetRecalculate(bCalculate)
{
    bRecalculateTable  = bCalculate;
}

function ReDrawMap(nPropertyTypes) 
{
    //Debug("MM PT = " + nPropertyTypes);

    if (!isNaN(nPropertyTypes)) {
        gnPropertyTypes = nPropertyTypes;
    }

    //Debug("MM gnPT = " + gnPropertyTypes);
    
    MapMove();
}

function MapMove()
{

    Gmap.clearOverlays();
    if (gsRoute.length > 0)
    {
//        Debug("MapMove, addroute to map");
         
        addRouteToMap(true);
        bRecalculateTable = false;
    }
    SetXML(Gmap, false);
}


function RepositionMap(point) 
{
//    alert("yay!");
//    Gmap.panTo(infoWindow.getPoint()); 

    var nCurrentZoom;
    var nZoomIncrement;
    
    nCurrentZoom = Gmap.getZoom();
   
    if (nCurrentZoom < 4)
    {
      nZoomIncrement = 2;
    } else
    {
      if (nCurrentZoom < 7)
      {
        nZoomIncrement = 3;
      } else
      {
        if (nCurrentZoom < 11)
        {
          nZoomIncrement = 4;
        } else
        {
          nZoomIncrement = 2;
        }
      }
    }

    //alert("Current: " + nCurrentZoom + ", Increment: " + nZoomIncrement);
    
    Gmap.setCenter(point); 
//    Gmap.zoomIn();
    Gmap.setZoom(nCurrentZoom + nZoomIncrement)


// not as keen on this
//    Gmap.setCenter(point, 9); 
}



       
        
function ShowPopupMap(number, pointLat, pointLong) 
{   
    var num;
    var point;
    var elementName;
    point = new GLatLng(pointLat, pointLong);
                
    num = number;
    
    document.getElementById("PopupMap"+num).style.display = "block";          
    document.getElementById("PopupMapClose"+num).style.display = "block";
     
    elementName = "PopupMap"+num;           
    var objPopup = document.getElementById(elementName); 
 
    MapArray[num] = new GMap2(objPopup);
    
    DirectionArray[num] = new GDirections(MapArray[num]);

    var Params;

    if (document.getElementById('chkAvoidHW').checked)
    {
        Params = {"avoidHighways": true, "getSteps":true, "preserveViewport":true};
    }
    else
    {
        Params = {"avoidHighways": false,"getSteps":true, "preserveViewport":true};
    } 
             
    GEvent.addListener(DirectionArray[num] ,"load", function() 
    {              
        MapArray[num].setCenter(point);
        MapArray[num].setZoom(m_nZoomLevel);
        MapArray[num].addControl(new GScaleControl());
        MapArray[num].addControl(new GSmallZoomControl());
        //MapArray[num].disableDragging();
        SetXML(MapArray[num], true);
    });

    DirectionArray[num].load(gsRoute, Params);
}
        
function ClosePopupMap(num)
{
    document.getElementById("PopupMap"+num).style.display = "none";
    document.getElementById("PopupMapClose"+num).style.display = "none";
}

      // ============ custom direction panel ===============
      function customPanel(map,mapname,directions,div) {

        if (map == 'undefined')
        {
            return;
        }
        
        document.getElementById("RouteControlObjects").style.display = "inline";
        document.getElementById("btnResetMap").style.display = "inline";
        var html = "";
      
        // ===== local functions =====

        // === waypoint banner ===
        function waypoint(point, type, address, bTopLink) {
          //var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
          var target = "'Gmap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))'";

          html += '<table style="width:100%;border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
          html += '  <tr style="cursor: pointer;">';
          html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;"onclick='+target+'>';
          html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
          html += '    <\/td>';
          html += '    <td style="vertical-align: middle; width: 80%;" onclick='+target+'>';
          html +=        address;
          html += '    <\/td>';
          
          if (bTopLink == true)
          {
            html += '     <td style="vertical-align: middle; text-align:right;width=20%"><a href="#MapAnchor" style="vlink=#000000;alink=#000000;">Back to Top<\/a><\/td>';
          }
          else
          {
            html += '     <td style="vertical-align: middle; text-align:right;width=20%"><\/td>';
          }
          
          html += '  <\/tr>';
          html += '<\/table>';
          
         
        }

        // === route distance ===
      

        // === step detail ===
        function detail(point, num, description, dist) {
        
           if (num == null)
           {
                return;
           }
        
          //var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
          var target = "'Gmap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"));'";
          html += '<table width="100%" style="margin: 0px; padding: 0px; border-collapse: collapse;">';
          html += '  <tr style="cursor: pointer;" onclick='+target+'>';
          html += '    <td width="6%" style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
          html += '         <a href="#MapAnchor"> '+num+'. <\/a>';  
          html += '    <\/td>';
          html += '    <td  width="84%" style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top;">';
          html += '         <a href="#MapAnchor" style="text-decoration:none"> '+description+' <\/a>';
          html += '    <\/td>';
          html += '    <td   width="10%" style="color:Navy;border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
          html +=        GetDistanceText(dist) + '&nbsp;' ;
          html += '    <\/td><\/tr>';
          
          target = "'ShowPopupMap(" + num + ", " + point.lat() + ", " + point.lng() + ");'";
          
          html += '    <tr>';
          html +=        HotelsNear(point.lat(), point.lng(), num, target) ;
          html += '  <\/tr>';
          html += '  <tr><td colspan="3">';
          target = "'ClosePopupMap(" + num + ");'"; 
          html += '  <span style="display:none;text-align:right;text-decoration:underline;cursor:pointer;" OnClick='+target+' id="PopupMapClose' + num + '">Close Map<\/span>';
          html += '  <div class="PopupMap" style="display:none;margin-left:180px;margin-top:8px;margin-bottom:8px;width:430px;height:250px;background-color:blue;border:solid 1px #4510FF;" id="PopupMap' + num + '" name="PopupMap' + num + '"> ' + num + '</div>';
          
          html += '<\/td><\/tr>'
          html += '<\/table>';
          
          div.innerHTML = html;

          
        }
        

        
        function HotelsNear(Lat, Lng, num, target)
        {      
            if (num == null)
            {
                return;
            }
            
            var sURL;
            var gsXML;
 
            //sURL = getURL(Gmap.getBounds());
            
            var x = Lng;
            var y = Lat;
            sURL = "../mapping/hotel-search.asp?X="+x+ "&Y="+y+"&Type=" +gnPropertyTypes+ "&Range="+m_bNearRange;
            
            //alert(sURL);
    
            var oXMLHTTP2 = new GXmlHttp.create();


            oXMLHTTP2.open( "GET", sURL, true);

            //alert(sURL);

            oXMLHTTP2.onreadystatechange = function () 
            {

                if (oXMLHTTP2.readyState == 4)
                {                 
                    gsXML = oXMLHTTP2.responseText;
                    //Debug("XML: " + gsXML);
                    //UseXML(nThreadID); 
                    try
                    {
                        if (gsXML == 0)
                        {
                        
                            var strResult = "<td colspan='3' Style='font-size:x-small; text-align: right;'><span id='NearHere" + num + "'>";
                            strResult  += "No properties near here";
                            strResult += '    <\/span><\/td>';
                        
                            document.getElementById("NearHere" + num).innerHTML = strResult;
                        }
                        else
                        {
                            var strProperty;
                            var strResult;
                            
                            if (gsXML >1)
                                strProperty = "properties";
                            else
                                strProperty = "property";
                                 
                            //var strResult = "<td colspan='3' Style='font-size:x-small; cursor: pointer;text-align: right;' onClick='"+target+"'><span id='NearHere" + num + "'>";
                            
                                                                                                                                                    
                            var strResult = "<td colspan='3'><a Style='font-size:x-small; cursor: pointer;text-align: right;' onClick="+ target +")><span id='NearHere" + num + "'>";
                            
                            strResult  += "<u>View " + gsXML + " nearby " + strProperty + "</ul>"; 
                            strResult += '    <\/span></a><\/td>';
                        
                            //strResult = "<td onClick=alert('HI');><a Style='font-size:x-small; background-color:red; cursor: pointer' onClick=alert('hi');>Link</a></td>";
                        
                            document.getElementById("NearHere" + num).innerHTML = strResult;
                            
                        }
                    }
                    catch(e)
                    {
                    
                        
                    }
                } 
            }   
            oXMLHTTP2.send(null);  
            
            var strResult = "<td colspan='3' Style='font-size:x-small; text-align: right;'><span id='NearHere" + num + "'>";
            strResult  += "Finding properties near here...";
            strResult += '    <\/span><\/td>';
            
            return    strResult;  
        }
        
        function routeDistance(dist) 
        {
            var strSummary;
            
            strSummary = dist;
            document.getElementById("RouteSummary").innerHTML = dist;
        
        }
                
        function GetDistanceText(nDistance)
        {
            var DistanceInUnits;
            var UnitText;
            
            if (document.getElementById('radioMiles').checked == true)
            {
                DistanceInUnits = nDistance * 0.000621371192;
                UnitText =  "mi";
            }
            else
            {
                DistanceInUnits = nDistance * 0.001;
                UnitText = "km";
            }
            DistanceInUnits = Math.round(DistanceInUnits*10)/10;
            return DistanceInUnits + " " + UnitText;
        }
        
        function CostCalc(nDistance)
        {
            var sCost;
            var nCost;            
            var nCostMultiplier=0.002824753;
           
            var nCostFactor = document.getElementById('cbCostFactor').value;
            nCost = Math.round(nDistance*nCostMultiplier*10*nCostFactor)/10;
            sCost = "Approx Cost = £" + nCost;
       
            
       
            // See O:\Development\Drive-Alive\FuelCostCalc.docx
       
            return sCost;
        }
        
        function RouteDescription(strRouteText)
        {
            var strResult;

            strResult = strRouteText.replace(/, Europe/g , "");
            
            return strResult;
        }
        
        // === Copyright tag ===
        function copyright(text) {
          html += '<div style="font-size: 0.86em;">' + text + "<\/div>";
        }
        

        // === read through the GRoutes and GSteps ===

        var routeCL;

        routeCL = directions.getRoute(0);

        for (var i=0; i<directions.getNumRoutes(); i++) 
        {
            
          if (i==0)
          {
                var type="play";
          } 
          else 
          {
                var type="pause";
          }
          
          routeCL = directions.getRoute(i);
          
          var geocode = routeCL.getStartGeocode();
          var point = routeCL.getStep(0).getLatLng();
          // === Waypoint at the start of each GRoute
          waypoint(point, type, geocode.address, false);


          //HotelsNear(routeCL);

          MapArray = new Array(routeCL.getNumSteps());
          DirectionArray = new Array(routeCL.getNumSteps());
        
            //alert('Initiated Array objects');

        
          for (var j=0; j<routeCL.getNumSteps(); j++)
          {
            var step = routeCL.getStep(j);
            detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().meters);   
     
          }
          
          var strRouteDescription;
          
          strRouteDescription = RouteDescription(sRouteText.replace(/ ,/g , ", "));
          
          
          routeDistance(strRouteDescription + " :  " + GetDistanceText(routeCL.getDistance().meters)+" (about "+routeCL.getDuration().html+")  " + CostCalc(routeCL.getDistance().meters));


        }
        
        // === the final destination waypoint ===   
        var geocode = routeCL.getEndGeocode();
        var point = routeCL.getEndLatLng();
        waypoint(point, "stop", geocode.address, true);
                 
        // === the copyright text ===
        copyright(directions.getCopyrightsHtml());

        // === drop the whole thing into the target div
        div.innerHTML = html;
              

        
      } // ============ end of customPanel function ===========