﻿var map;
var mapInitialized = false;
var mapGeocoder;
var mapWindow;
var mapMarker;

function addressClick(address, info)
{
    initializeMap();
    
    if (mapMarker)
    {
        map.removeOverlay(mapMarker);
        mapMarker = null;
    }
    
    mapGeocoder.getLatLng(address, function(point) {
        var mapMarker = new GMarker(point);
        
        map.closeInfoWindow();
        map.setCenter(point, 14);
        map.addOverlay(mapMarker);
        
        if (info) {
            mapMarker.openInfoWindowTabsHtml(info);
            
            GEvent.addListener(mapMarker, 'click', function() {
		        map.closeInfoWindow();
		        mapMarker.openInfoWindowTabsHtml(info, opts);
	        });
	    }
        
        mapWindow.style.visibility = 'visible';
    });
    
    return false;
}

function closeMap()
{
    if (!mapInitialized || !mapWindow)
        return;
    
    mapWindow.style.visibility = 'hidden';
    
    return false;
}

function initializeMap()
{
    if (mapInitialized || !GBrowserIsCompatible())
        return;
    
    // Create the map container
    mapWindow = document.createElement('div');
    mapWindow.id = 'mapWindow';
    mapWindow.style.visibility = 'hidden';
    
    // Create container header
    var element = document.createElement('div');
    element.setAttribute('class', 'header');
    mapWindow.appendChild(element);
    
    // Create the closing button in the header
    var closeElement = document.createElement('a');
    closeElement.setAttribute('href', '#');
    closeElement.setAttribute('onclick', 'return closeMap()');
    closeElement.innerHTML = 'Close (X)';
    element.appendChild(closeElement);
    
    // Create container body
    element = document.createElement('div');
    element.setAttribute('class', 'body');
    mapWindow.appendChild(element);
    
    // Create the map container within the body container
    var mapElement = document.createElement('div');
    mapElement.id = 'map';
    element.appendChild(mapElement);
    
    // Create the container footer
    element = document.createElement('div');
    element.setAttribute('class', 'footer');
    mapWindow.appendChild(element);
    
    // Find the proper location and add the map container
    var page = document.getElementById('page');
    page.insertBefore(mapWindow, page.firstChild);
    
    mapGeocoder = new GClientGeocoder();
    
    map = new GMap2(mapElement);
    map.addControl(new GSmallMapControl());
    map.enableScrollWheelZoom();
    
    mapInitialized = true;
}
