﻿var mapWindow;
var mapDisplay;
var gLocalSearch;

function displayGoogleMapPanel(control, postcode) {
    if (!mapWindow) {
        mapWindow = new Ext.Window({
            layout:'fit',
            width:580,
            height:590,
            closeAction:'hide',
            plain: true
        });
        
        mapWindow.html = '<div id="google-map" style="width: 563px; height: 555px;"></div>';
    }
    mapWindow.title = "Event location";
    mapWindow.show(control);
    
    if (!mapDisplay) {
        var mapOptions = new Object();
        mapOptions.size = new GSize(563, 555);
        
        mapDisplay = new GMap2(document.getElementById("google-map"), mapOptions);
        mapDisplay.addControl(new GLargeMapControl());
        
        // Start off at the center of the UK
        mapDisplay.setCenter(new GLatLng(54.162434, -3.647461), 13);
    }
    
    if (!gLocalSearch) {
        gLocalSearch = new GlocalSearch();
        gLocalSearch.setCenterPoint(mapDisplay);
        gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
    }
    
    // Search for the postcode
    gLocalSearch.execute(postcode);
}

function OnLocalSearch() {
    if (!gLocalSearch.results) {
        alert("Could not find postcode");
        return;
    }
    
    // Use the first search result and make a lat/long out of it
    var address = gLocalSearch.results[0];
    var point = new GLatLng(parseFloat(address.lat), parseFloat(address.lng));
    mapDisplay.setCenter(point, 13);
    
    var marker = new GMarker(point);
    mapDisplay.addOverlay(marker);
    marker.openInfoWindow(address.html.cloneNode(true));
}
