﻿var MapInstances = new Array(); 

function AddMapInstance(obj)
{
    MapInstances.push(obj);
}


function FetchMapInstance(key)
{
    for(var i=0; i<MapInstances.length; i++)
    {
        if(MapInstances[i].Key == key)
        {
            return MapInstances[i]
        }
    }
    
    return null;
}

function RunMasterGMap(mapControl, mapID,  lat, lang, zoomLevel, draggableMarker, mapType, description) 
{
   if(mapControl!=null)
   {
   
    if (GBrowserIsCompatible()) {
        
        var Center = new GLatLng(lat, lang);
       
        var currentMap = new GMap2(mapControl);
        currentMap.setCenter(Center, zoomLevel);
        currentMap.addControl(new GSmallMapControl());
        currentMap.addControl(new GMapTypeControl());
        currentMap.enableScrollWheelZoom();
        currentMap.enableContinuousZoom();
        
        var Opts = {draggable:draggableMarker};
        var MarkerDragged = false;
        
        var newMarker = new GMarker(Center, Opts);
        
        
        var mapInstance = new Array();
        
        mapInstance.Key = mapID;
        mapInstance.Description = description;
        mapInstance.Marker = newMarker;
        mapInstance.Map = currentMap; 
        
        mapInstance.Map.addOverlay(newMarker);
        
        MapInstances.push(mapInstance);
        
        if(description!=null)
        {
            GEvent.addListener(newMarker,"click", function() { SetMarkerText(mapID) });
        }
        
        if(mapType!=null)
        {
            currentMap.setMapType(mapType);   
        }
        
        if(typeof GMapListers == "function")
        {
            GMapListers(currentMap, newMarker, MarkerDragged);
        }
        
        
        
      }
   }
}

function SetMarkerText(mapID)
{
    var mapInstance = FetchMapInstance(mapID);
    
    mapInstance.Map.openInfoWindowHtml(mapInstance.Marker.getPoint(), mapInstance.Description);
}

function GMLoadMap(mapID, lat, lang, zoomLevel, draggable, mapType, description)
{
    var ele = document.getElementById(mapID);
    
    if(ele!=null)
    {
        RunMasterGMap(ele, mapID, lat, lang, zoomLevel, draggable, mapType, description);
    }
    else
    {
        setTimeout(function() 
        {
            GMLoadMap(mapID, lat, lang, zoomLevel, draggable, mapType, description);
            return;
        }, 100);  
    }
}