﻿/**** Google Maps ****/
var wbLoc = null;
var gDirs = null;
var gLclSearch = null;

function loadMap() {
    var dmap = document.getElementById( "gMap" );
    if( dmap != null )
    {
        gLclSearch = new GlocalSearch();
        if (GBrowserIsCompatible()) 
        {
            var gMapObj = new GMap2(document.getElementById("gMap"));
            wbLoc = new GLatLng( 53.467804,-2.307868 );
            gMapObj.setCenter(wbLoc, 15);
            var mark = new GMarker( wbLoc );
            gMapObj.addOverlay( mark );
            mark.bindInfoWindowHtml( "<h4 style='color:#000000;'>Challenge 4 Change</h4>" );
            gMapObj.removeMapType(G_SATELLITE_MAP);
            gMapObj.addControl( new GMapTypeControl());
            gMapObj.addControl( new GLargeMapControl());
            gMapObj.addControl( new GOverviewMapControl());       
    
            var dirResult = document.getElementById( "gMapDirResults" );
            if( dirResult != null )        
                gDirs = new GDirections( gMapObj, dirResult );
                
            var gMapBtn = document.getElementById( "gMapDirections" );
            if( gMapBtn != null )
            {
                gMapBtn.onclick = function() { setDirections(); }
            }
            
            var dirStart = document.getElementById( "gMapStart" );
            if( dirStart != null )
            {
                dirStart.onkeypress = function( e ) { return checkDirReturn( e ); }
            }
        }
    }
}

function checkDirReturn( e )
{
    var charCode;
    if( e && e.which )
        charCode = e.which
    else
        charCode = event.keyCode
        
    if( charCode == 13 )
    {
        setDirections();
        return false;
    }
    else
        return true;
}

function setDirections()
{
    gLclSearch.setSearchCompleteCallback( null,
        function()
        {
            if( gLclSearch.results[0])
            {
                var lat = gLclSearch.results[0].lat;
                var lng = gLclSearch.results[0].lng;
                
                var start = new GLatLng( lat, lng );
                var dirResult = document.getElementById( "gMapDirResults" );
                dirResult.style.display = "block";
                var sStr = "from: " + start.toUrlValue() + " to: " + wbLoc.toUrlValue();
                gDirs.load( sStr );
            }
        }
    );
        
    var dirStart = document.getElementById( "gMapStart" );
    gLclSearch.execute( dirStart.value + ", UK" );
}
