var selectedListingID = null;
var map = null;

var originalZoomLevel;
var originalCenter;

var customIcons = null;
var highLightedMarkers = new Object();

var markers = new Array();
var markerLookup = new Object();
var lookupIDArray = new Array();

function setMapCenter(latitude, longitude, zoom)
{
    originalCenter = new GLatLng(parseFloat(latitude), parseFloat(longitude));
    originalZoomLevel = zoom;
}

function addAddress(markerType, markerID, name, address, type, latitude, longitude)
{ 
    //Test if google loaded
    if (typeof(GLatLng) == 'undefined')
    {
        return;
    }
    var point = new GLatLng(parseFloat(latitude), parseFloat(longitude));
    var marker = createMarker(markerType, point, name, address, type, markerID, false);    
    markers.push(marker);
    lookupIDArray.push(markerID);
    markerLookup[markerID] = marker;
}
function setIcons(imagesInfo)
{
    //Test if google loaded
    if (typeof(GIcon) == 'undefined')
    {
        return;
    }    
    customIcons = new Object();
    for (var image in imagesInfo)
    {
        var imageInfo = imagesInfo[image];                           
        var icon = new GIcon();    
        icon.image = imageInfo.image_url;
        icon.shadow = imageInfo.shadow_url;
        icon.iconAnchor = new GPoint(imageInfo.icon_anchor_x, imageInfo.icon_anchor_y);
        icon.iconSize = new GSize(imageInfo.width, imageInfo.height);
        icon.shadowSize = new GSize(imageInfo.shadow_width, imageInfo.shadow_height);        
        icon.infoWindowAnchor = new GPoint(imageInfo.info_window_anchor_x, imageInfo.info_window_anchor_y);
        var imageString = image;
        customIcons[imageString] = icon;
    }
}
function initIcons(arrowImage, arrowShadow, redImage, redShadow)
{
    //Test if google loaded
    if (typeof(GIcon) == 'undefined')
    {
        return;
    }
    if (customIcons !== null)
    {
        return;
    }
    customIcons = new Object();
    var iconBlue = new GIcon();    
    iconBlue.image = arrowImage;
    iconBlue.shadow = arrowShadow;
    iconBlue.iconSize = new GSize(14, 14);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);

    var iconRed = new GIcon(); 
    iconRed.image = redImage;
    iconRed.shadow = redShadow;  
    iconRed.iconSize = new GSize(12, 20);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);
    
    customIcons["restaurant"] = iconBlue;
    customIcons["bar"] = iconRed;
    customIcons["property"] = iconBlue;    
    customIcons["highlight"] = iconRed;
}
function createMarker(markerType, point, name, address, iconType, markerID, highlight)
{
    var lat = point.lat() + '';
    var lng = point.lng() + '';
    var lookupValue = lat + lng;
        
    //marker.getPoint().lat()
    var iconLookup = null;
    if (highlight === true)
    {
        iconLookup = iconType + '_highlight';
    }
    else
    {
        iconLookup = iconType;
    }
    var marker = new GMarker(point,{icon:customIcons[iconLookup], zIndexProcess:sendBack});
    // var marker = new GMarker(point,{icon:customIcons[iconType], zIndexProcess:sendBack, draggable: true});
    marker.markerType = markerType;
    marker.markerID = markerID;
    marker.markerName = name;
    marker.listingID = markerID;
    marker.address = address;
    marker.iconType = iconType;
    marker.highlight = highlight;
    
    //var marker = new GMarker(point, customIcons[type]);
    //{zIndexProcess:myFunction}
    var html = "<b>" + name + "</b> <br/>" + address;
    GEvent.addListener(marker, 'click', function()
    {
        //marker.openInfoWindowHtml(html);
        showInfoWindow(marker);
    });
    return marker;
}

function replaceMarker(marker, highlight)
{

    var oldMarker = marker;
    var markerType = oldMarker.markerType;    
    var markerID = oldMarker.markerID;
    var point = oldMarker.getPoint();
    var name = oldMarker.markerName;
    var address = oldMarker.address;
    var iconType = oldMarker.iconType;     
    map.removeOverlay(oldMarker);
        
    var marker = createMarker(markerType, point, name, address, iconType, markerID, highlight);    
    markers.push(marker);
    map.addOverlay(marker);
    if (highlight == true)
    {
        //marker.setImage('/Images/MapParts/red_arrow.png');
    }
    else
    {
        //marker.setImage('/Images/MapParts/map_arrow.png');
    }
        
    /*
    marker.highlight = highlight;    
    marker.setLatLng(marker.getLatLng());
    markers.push(marker);
    */
}

var currentMarkerID = null;

function focusOnAddress(id)
{
    hideInfoWindow();
    if (map)
    {
        if (currentMarkerID)
        {
            for (var i = 0; i < markers.length; i++)
            {
                //markers[i].setImage('/Images/MapParts/map_arrow.png');
                if (markers[i].markerID == currentMarkerID)
                {                    
                    replaceMarker(markers[i], false);
                    markers.splice(i, 1);                    
                    break;
                }     
            }
        }
        for (var i = 0; i < markers.length; i++)
        {            
            if (markers[i].markerID == id)
            {                
                replaceMarker(markers[i], true);
                markers.splice(i, 1);
                break;
            }     
        }
        markerLookup = new Object();
        lookupIDArray = new Array();
        for (var i = 0; i < markers.length; i++)
        {
            var markerID = markers[i].markerID;
            lookupIDArray.push(markerID);
            markerLookup[markerID] = markers[i];
        }
        
        currentMarkerID = id;
        //map.clearOverlays();                 
    }
}
function sendBack(marker, b)
{
    if (marker.highlight == false)
    {
        return GOverlay.getZIndex(marker.getPoint().lat());
    }
    else
    {
        return 9000001;
    }  
}
var subGPoints = function(a,b)
{
    return new GPoint(a.x-b.x,a.y-b.y);
};
var infowindow = null;
var infowindow_stem_up = null;
var infowindow_stem_dn = null;
var hideInfoWindow = function()
{
    if (infowindow)
    {
        if (infowindow.style)
        {
            infowindow.style.display = 'none';
            infowindow_stem_up.style.display = 'none';
            infowindow_stem_dn.style.display = 'none';    
        }
    }        
}

function initInfoWindow(marker)
{
    //We are moving the node from somewhere on the page to the map div.  The node can not begin there because it is erased apparently.
    
    infowindow = document.getElementById("infowindow");
    infowindow_stem_up = document.getElementById("infowindow_stem_up2");
    infowindow_stem_dn = document.getElementById("infowindow_stem_dn2");
    
    infowindow.parentNode.removeChild(infowindow);    
    infowindow_stem_up.parentNode.removeChild(infowindow_stem_up);    
    infowindow_stem_dn.parentNode.removeChild(infowindow_stem_dn);
        
    document.getElementById("map").appendChild(infowindow);
    document.getElementById("map").appendChild(infowindow_stem_up);
    document.getElementById("map").appendChild(infowindow_stem_dn);   
 
    var closeMapElem = document.getElementById("closeMapBtnIcon");
    if (closeMapElem)
    {
        if (Emanee)
        {
            Emanee.addEvent(closeMapElem, "click", hideInfoWindow, false);            
        }
    }
}
/*
onclick="location='<?php echo $listingPageURL; ?>';" 
				onmouseover="var elem = document.getElementById('<?php echo $id; ?>'); elem.style.backgroundColor='#E5E5E5'; elem.style.height = '88px'; elem.style.border = '3px solid black'; elem.style.margin='-3px auto 0 auto'; elem.style.cursor='pointer'; focusOnAddress('<?php echo $listingID; ?>'); " 
				onmouseout="var elem = document.getElementById('<?php echo $id; ?>'); elem.style.backgroundColor='#FFFFFF'; elem.style.margin='0 auto 0 auto'; elem.style.border = 'none'; elem.style.borderBottom = 'solid 1px #D5D5D5'; elem.style.height = '90px'; 
				focusOnAddress(null); hideInfoWindow(); "
*/
function initFocusEvents()
{
    if (lookupIDArray)
    {
        for (var i=0; i < lookupIDArray.length; i++)
        {
            var id = lookupIDArray[i];
            var focusID = document.getElementById(id);
            Emanee.addEvent(focusID, "click", hideInfoWindow, false); 
        } 
    }
}
function refocusMap()
{
    map.setCenter(originalCenter, originalZoomLevel);
}
function showInfoWindow(marker)
{
    if (marker.markerType == 'listing')
    {
        var listingID = marker.markerID;
        focusOnAddress(listingID);
        setDisplayedListing(listingID);       
    }    
}
function setDisplayedListing(listingID)
{
    var selectedListingNode = document.getElementById("selectedListingID");
    if (selectedListingNode)
    {
        var nodeName = "searchResultID" + listingID;
        var listingNode = document.getElementById(nodeName);
        // selectedListingNode.innerHTML = listingID;
        
        //Move.element('source_element','container', 'id_append_variable', 'copy');
        
        selectedListingNode.innerHTML = "";
        Move.element(nodeName, 'selectedListingID', 'selected', 'copy');
        
        // listingNode.setAttribute("class", "");
        // listingNode.className = "";
        listingNode.style.display = "none";
        selectedListingID = listingID;
    }
    if (selectedListingID !== null)
    {
        var nodeName = "searchResultID" + listingID;
        var listingNode = document.getElementById(nodeName);
        listingNode.style.display = "block";
    }
}
function initializeSelectedListing()
{    
    if (selectedListingID)
    {
        setDisplayedListing(selectedListingID);
        focusOnAddress(selectedListingID);
    }

}
function setDefaultDisplayListing(listingID)
{
    selectedListingID = listingID;    
}
// FF Native version is type sensitive so this version is also
if(!Array.indexOf)
{
    Array.prototype.indexOf = function(obj, n)
    {
        n = (n==null)?0:n;
        for(var i=n; i<this.length; i++){
            if(this[i]===obj){
                return i;
            }
        }
        return -1;
    }
}
function focusOnNextListing()
{    
    if (lookupIDArray)
    {
        var length = lookupIDArray.length;
        if (length > 0)
        {
            selectedListingID = selectedListingID + ""; // Required for FF
            var i = lookupIDArray.indexOf(selectedListingID);
            var next = i + 1;
            if (next == (length))
            {
                next = 0;
            }         
            selectedListingID = lookupIDArray[next];
        }
        focusOnAddress(selectedListingID);
        setDisplayedListing(selectedListingID);
    }
}
function focusOnPreviousListing()
{
    if (lookupIDArray)
    {
        var length = lookupIDArray.length;
        if (length > 0)
        {
            selectedListingID = selectedListingID + ""; // Required for FF
            var i = lookupIDArray.indexOf(selectedListingID); 
            var prev = i - 1;
            if (prev < 0)
            {
                prev = length - 1;
            }
            selectedListingID = lookupIDArray[prev];
        }
        focusOnAddress(selectedListingID);
        setDisplayedListing(selectedListingID);
    }
}
function load()
{        
    //Test if google loaded and the map div is available.
    var mapElem = document.getElementById("map");    
    if (typeof(GMap2) == 'undefined' || !mapElem)
    {
        return;
    }
    if (GBrowserIsCompatible())
    {        
        //var map = new GMap2(document.getElementById("map"));
        
        //mapElem must be an object.  We return above if there is no map or GMap2 is not loaded.
        map = new GMap2(mapElem);       
        
        initInfoWindow();
        
        map.enableScrollWheelZoom(); 
        map.enableDoubleClickZoom();
        
        //To remove the hybrid option
        //map.removeMapType(G_HYBRID_MAP);
        map.addMapType(G_PHYSICAL_MAP);
        //map.addControl(new GSmallMapControl());
        //map.addControl(new GLargeMapControl());
        //map.addControl(new GMapTypeControl());
        //map.addControl(new GOverviewMapControl()); //Doesn't seem to work currently
        //Use to disable the ability to drag the map to recenter.
        //map.disableDragging();
        
        var mapTypeIsSet = false;
        //if ( typeof( window[ 'foo' ] ) != "undefined" ) would work also
        if (window.Emanee_GoogleMap !== undefined && window.Emanee_GoogleMap.MapType !== undefined)
        {
            if (Emanee_GoogleMap.MapType == 'basic1')
            {
                mapTypeIsSet = true;
            }
        }
        
        if (!mapTypeIsSet)
        {
            var mapTypeControl = new GMapTypeControl();        
            var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(-5,-30));
            //var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
            map.addControl(mapTypeControl, topRight);
            
            var smallMapControl = new GSmallMapControl();
            var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(-50,0));
            map.addControl(smallMapControl, topLeft);
        }
        else
        {
            map.removeMapType(G_PHYSICAL_MAP);
            var mapTypeControl = new GMapTypeControl();        
            var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(1, 2));
            //var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
            map.addControl(mapTypeControl, topRight);
            
            var smallMapControl = new GSmallMapControl();
            var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0,0));
            map.addControl(smallMapControl, topLeft);
            
            map.addControl(new GOverviewMapControl());
        }
        
        //Must center before adding overlays
        //map.setCenter(center, 3);
        //map.setCenter(center, 10); 
        //map.setCenter(center, 13);
        
        if (markers.length == 0)
        {
            if (originalZoomLevel && originalCenter)
            {
                map.setCenter(new GLatLng(0,0),0);
                map.setZoom(originalZoomLevel);
                map.setCenter(originalCenter);
            }
        }        
        else if (markers.length > 1)
        {
            map.setCenter(new GLatLng(0,0),0);
            var bounds = new GLatLngBounds;
            
            for (var i=0; i < markers.length; i++)
            {
	            bounds.extend(markers[i].getPoint());
            }
            var boundsZoomLevel = map.getBoundsZoomLevel(bounds);
            // boundsZoomLevel = boundsZoomLevel - 2;            
            map.setZoom(boundsZoomLevel);
            //map.setZoom(map.getBoundsZoomLevel(bounds));            
            map.setCenter(bounds.getCenter());
            
            originalZoomLevel = boundsZoomLevel;
            originalCenter = bounds.getCenter();
        }
        else if (markers.length == 1)
        {
            map.setCenter(markers[0].getPoint(), 13);
        }
        //Add overlays to map:
        for (var i = 0; i < markers.length; i++)
        {
            map.addOverlay(markers[i]);
        }
        //document.getElementById("innerMapContainer").style.visibility = "";
        
        if (markers.length > 0)
        {
            initializeSelectedListing();
        }
    }
}
if (window.Emanee !== undefined)
{
    if (!Emanee_GoogleMap)
    {
        var Emanee_GoogleMap;
        (function() {
            Emanee_GoogleMap = {};
        })();
    }

    Emanee_GoogleMap.onLoad = function(func) {
        load();
    }
    Emanee_GoogleMap.onUnLoad = function(func)
    {        
        GUnload();
    }
    Emanee_GoogleMap.MapType = 'basic1';
    Emanee.addOnLoadEvent(Emanee_GoogleMap.onLoad);
    Emanee.addOnUnLoadEvent(Emanee_GoogleMap.onUnLoad);    
}

function $()
{
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++)
	{
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}
var Move =
{
    copy: function(e, target, append_name)
    {
        var eId = $(e);
        var copyE = eId.cloneNode(true);
        copyE.id = e + append_name;

        this.update_ids(copyE, append_name);

        $(target).appendChild(copyE);
    },
    element: function(e, target, append_name, type)
    {
        var eId = $(e);
        if (type == 'move')
        {
            $(target).appendChild(eId);
        }
        else if (type == 'copy')
        {
            this.copy(e, target, append_name);
        }
    },
    update_ids: function(e, append_name)
    {
        var cLength = e.childNodes.length - 1;
        for (var i = 0; cLength >= i; i++)
        {
            if (e.childNodes[i].id)
            {
                var cNode = e.childNodes[i];
                var firstId = cNode.id;
                cNode.id = firstId + append_name;
            }
            if(e.childNodes[i].childNodes.length > 0)
            {
                this.update_ids(e.childNodes[i], append_name);
            }
        }
    }
}

