var map;
var icon;
var lat, lng;
var zoom;
var mapType = 0;
var mapFrameActive = false;

newImage("map-type-map-on.png"); newImage("map-type-map-off.png");
newImage("map-type-sat-on.png"); newImage("map-type-sat-off.png");
newImage("map-type-hyb-on.png"); newImage("map-type-hyb-off.png");
newImage("map-zoom-in-on.png"); newImage("map-zoom-in-off.png");
newImage("map-zoom-out-on.png"); newImage("map-zoom-out-off.png");
newImage("map-nav-up-on.png"); newImage("map-nav-up-off.png");
newImage("map-nav-down-on.png"); newImage("map-nav-down-off.png");
newImage("map-nav-left-on.png"); newImage("map-nav-left-off.png");
newImage("map-nav-right-on.png"); newImage("map-nav-right-off.png");
newImage("popup-close.png"); 



    function initMap() {
        var mapNode = document.getElementById("map");
        if (mapNode && GBrowserIsCompatible()) {
            map = createMap(mapNode);
            initPopups(map, 150);

            if (document.form.showType) {
                var type = document.form.showType.value;
                icon = getIcon(getIconType(type));
            }

            if (document.form.geoPosition) {
                var pos = document.form.geoPosition.value.split(",");
                lat = pos[0];
                lng = pos[1];
                zoom = parseInt(pos[2]);
                mapType = parseInt(pos[3]);
            }

            if (lat && lng) {
                var centerPoint = new GLatLng(lat, lng);
                map.setCenter(centerPoint, zoom, idToMapType(mapType));

                if (window.points) {
                    for (var i = 0; i < points.length; i++) {
                        map.addOverlay(createMarker(points[i], i));
                    }
                    map.addOverlay(new GPolyline(points));
                } else if ((document.form.showPoint && document.form.showPoint.value != 'true')) {
                    var marker = new GMarker(centerPoint, icon);
                    map.addOverlay(marker);
                }
            }
        }
    }

    function idToMapType(id) {
        return map.getMapTypes() [id];
    }

    function createMarker(point, index) {
        var marker = new GMarker(point, icon);
        makePopup(marker, messages[index], map);
        return marker;
    }

    function editProperties() {
        openWindow(document.getElementById("propertyAnchor").href);
    }


function createMap(mapNode) {
    if (!window.GMap2)
        return null;

    var map = new GMap2(mapNode);
    map.addControl(new VcarNavControl());
    map.addControl(new VcarZoomControl());
    map.addControl(new VcarMapTypeControl());
    return map;
}

function VcarNavControl() {
}
VcarNavControl.prototype = new GControl();
VcarNavControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    container.style.textAlign = "left";

    var upDiv = document.createElement("div");
    container.appendChild(upDiv);
    upDiv.innerHTML = "<img src='/ui/media/map-nav-up-off.png'>";
    upDiv.style.paddingLeft = "10px";
    upDiv.style.paddingBottom = "3px";
    GEvent.addDomListener(upDiv, "click", function() {
        if (window.mapFrameActive) {
            map.panBy(new GSize(0, mapFrameHeight / 2));
        } else {
            map.panDirection(0,1);
        }
    });
    GEvent.addDomListener(upDiv, "mouseover", function() { mapRollover(upDiv); });
    GEvent.addDomListener(upDiv, "mouseout", function() { mapRollout(upDiv); });

    var leftDiv = document.createElement("div");
    container.appendChild(leftDiv);
    leftDiv.innerHTML = "<img src='/ui/media/map-nav-left-off.png'>";
    leftDiv.style.display = "inline";
    leftDiv.style.paddingRight = "6px";
    GEvent.addDomListener(leftDiv, "click", function() {
        if (window.mapFrameActive) {
            map.panBy(new GSize(mapFrameWidth / 2, 0));
        } else {
            map.panDirection(1, 0);
        }
    });
    GEvent.addDomListener(leftDiv, "mouseover", function() { mapRollover(leftDiv); });
    GEvent.addDomListener(leftDiv, "mouseout", function() { mapRollout(leftDiv); });

    var rightDiv = document.createElement("div");
    container.appendChild(rightDiv);
    rightDiv.innerHTML = "<img src='/ui/media/map-nav-right-off.png'>";
    rightDiv.style.display = "inline";
    GEvent.addDomListener(rightDiv, "click", function() {
        if (window.mapFrameActive) {
            map.panBy(new GSize(-1 * mapFrameWidth / 2, 0));
        } else {
            map.panDirection(-1, 0);
        }
    });
    GEvent.addDomListener(rightDiv, "mouseover", function() { mapRollover(rightDiv); });
    GEvent.addDomListener(rightDiv, "mouseout", function() { mapRollout(rightDiv); });

    var downDiv = document.createElement("div");
    container.appendChild(downDiv);
    downDiv.innerHTML = "<img src='/ui/media/map-nav-down-off.png'>";
    downDiv.style.paddingLeft = "10px";
    downDiv.style.paddingBottom = "7px";
    GEvent.addDomListener(downDiv, "click", function() {
        if (window.mapFrameActive) {
            map.panBy(new GSize(0, -1 * mapFrameHeight / 2));
        } else {
            map.panDirection(0, -1);
        }
    });
    GEvent.addDomListener(downDiv, "mouseover", function() { mapRollover(downDiv); });
    GEvent.addDomListener(downDiv, "mouseout", function() { mapRollout(downDiv); });

    map.getContainer().appendChild(container);
    return container;
}
VcarNavControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

function VcarZoomControl() {
}
VcarZoomControl.prototype = new GControl();
VcarZoomControl.prototype.initialize = function(map) {
    var container = document.createElement("div");

    var inDiv = document.createElement("div");
    container.appendChild(inDiv);
    inDiv.innerHTML = "<img src='/ui/media/map-zoom-in-off.png'>";
    GEvent.addDomListener(inDiv, "click", function() {
        var newZoom = map.getZoom() + 1;
        if (window.checkZoom)
            if (!window.checkZoom(newZoom))
                return;
        map.setZoom(newZoom);
    });
    GEvent.addDomListener(inDiv, "mouseover", function() { mapRollover(inDiv); });
    GEvent.addDomListener(inDiv, "mouseout", function() { mapRollout(inDiv); });

    var outDiv = document.createElement("div");
    container.appendChild(outDiv);
    outDiv.innerHTML = "<img src='/ui/media/map-zoom-out-off.png'>";
    outDiv.style.paddingTop = "4px";
    GEvent.addDomListener(outDiv, "click", function() {
        var newZoom = map.getZoom() - 1;
        if (window.checkZoom)
            if (!window.checkZoom(newZoom))
                return;
        map.setZoom(newZoom);
    });
    GEvent.addDomListener(outDiv, "mouseover", function() { mapRollover(outDiv); });
    GEvent.addDomListener(outDiv, "mouseout", function() { mapRollout(outDiv); });

    map.getContainer().appendChild(container);
    return container;
}
VcarZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(17, 65));
}

var mapTypeControlId = 0;
function VcarMapTypeControl() {
}
VcarMapTypeControl.prototype = new GControl();
VcarMapTypeControl.prototype.initialize = function(map) {
    var mtcId = ++mapTypeControlId;
    var container = document.createElement("div");

    var mapDiv = document.createElement("div");
    container.appendChild(mapDiv);
    mapDiv.innerHTML = "<img src='/ui/media/map-type-map-off.png'>";
    mapDiv.style.display = "inline";
    GEvent.addDomListener(mapDiv, "click", function() {
        map.setMapType(G_NORMAL_MAP);
        mapTurnOn(mapDiv, 'map-type'+mtcId);
    });
    GEvent.addDomListener(mapDiv, "mouseover", function() { mapRollover(mapDiv); });
    GEvent.addDomListener(mapDiv, "mouseout", function() { mapRollout(mapDiv, 'map-type'+mtcId); });

    var satDiv = document.createElement("div");
    container.appendChild(satDiv);
    satDiv.innerHTML = "<img src='/ui/media/map-type-sat-off.png'>";
    satDiv.style.display = "inline";
    GEvent.addDomListener(satDiv, "click", function() {
        map.setMapType(G_SATELLITE_MAP);
        mapTurnOn(satDiv, 'map-type'+mtcId);
    });
    GEvent.addDomListener(satDiv, "mouseover", function() { mapRollover(satDiv); });
    GEvent.addDomListener(satDiv, "mouseout", function() { mapRollout(satDiv, 'map-type'+mtcId); });

    var hybDiv = document.createElement("div");
    container.appendChild(hybDiv);
    hybDiv.innerHTML = "<img src='/ui/media/map-type-hyb-off.png'>";
    hybDiv.style.display = "inline";
    GEvent.addDomListener(hybDiv, "click", function() {
        map.setMapType(G_HYBRID_MAP);
        mapTurnOn(hybDiv, 'map-type'+mtcId);
    });
    GEvent.addDomListener(hybDiv, "mouseover", function() { mapRollover(hybDiv); });
    GEvent.addDomListener(hybDiv, "mouseout", function() { mapRollout(hybDiv, 'map-type'+mtcId); });

    mapTurnOn(mapDiv, 'map-type'+mtcId);

    map.getContainer().appendChild(container);
    return container;
}
VcarMapTypeControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5));
}

// zoom diff between control and view map
var mapViewOffsetZoom = 3;
// size and pos of the frame
var mapFrameWidth = 80;
var mapFrameHeight = 60;
var mapFrameX;
var mapFrameY;

// div for the control frame
var mapFrameDiv;
// fake mode for emulating on frame click
var draggingMap = false;
var lastMouseX, lastMouseY;

function VcarPosControl() {
}
VcarPosControl.prototype = new GControl();
VcarPosControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    container.style.border = "1px solid #738c53";

    mapFrameDiv = document.createElement("div");
    container.appendChild(mapFrameDiv);
    mapFrameDiv.style.backgroundColor = "#738c53";
    mapFrameDiv.style.opacity="0.3";
    mapFrameDiv.style.filter="alpha(opacity=30)";
    mapFrameDiv.style.cursor="move";

    mapFrameDiv.style.width = mapFrameWidth + "px";
    mapFrameDiv.style.height = mapFrameHeight + "px";

    GEvent.addDomListener(container, "mousedown", function(evt) { 
        lastMouseX = getMouseX(evt);
        lastMouseY = getMouseY(evt);
        draggingMap = true;
    });
    GEvent.addDomListener(document, "mouseup", function(evt) { 
        draggingMap = false;
    });
    GEvent.addDomListener(document, "mousemove", function(evt) { 
        if (draggingMap) {
            var mouseX = getMouseX(evt);
            var mouseY = getMouseY(evt);
            var x = lastMouseX - mouseX;
            var y = lastMouseY - mouseY;
            var point = map.fromLatLngToDivPixel(map.getCenter());
            x += point.x;
            y += point.y;
            var centerPoint = map.fromDivPixelToLatLng(new GPoint(x, y));
            map.setCenter(centerPoint);
//window.status=map.getCenter();
            lastMouseX = mouseX;
            lastMouseY = mouseY;
        }
    });

    map.getContainer().appendChild(container);
    return container;
}
VcarPosControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
}


// custom popup windows

var tmpCenter;
var activeMarker = null;
var activeMessage = null;
var lastMarker = null;
var popupWinPoint = null;
var popupWin = null;
var mouseOverPopup = false;
var popupWidth = 200;

function initPopups(map, width) {
    popupWidth = width;

    // whenever it moves, save its center
    GEvent.addListener(map, "moveend", function () {
        tmpCenter = map.getCenter();
    });

    // on double click, restore to center
    GEvent.addListener(map, "dblclick", function (a,point) {
        if (point) { map.setCenter(tmpCenter); } 
        resetPopup();
    }); 

    GEvent.addListener(map, "click", clickHidePopup);
    //GEvent.addListener(map, "mouseout", hidePopup);
}

function showPopup() {
    // record last rollover
    if (!activeMarker) return;
    
    // do call back
    if (window.popupShown) {
        window.popupShown();
    }
    
    // skip duplicates
    var lat = activeMarker.getPoint().lat();
    var lng = activeMarker.getPoint().lng();
    //if (lat+":"+lng == popupWinPoint)
    //   return;
       
    if (popupWin)
        hidePopup();
        
    lastMarker = activeMarker;
    popupWin = document.createElement("div");
    popupWin.style.position = "absolute";
    popupWin.style.visibility = "hidden";
    map.getPane(G_MAP_FLOAT_PANE).appendChild(popupWin);
    popupWin.innerHTML = activeMessage;
    popupWin.style.width = popupWidth + "px";

    popupWin.onmouseover = function() {
        window.mouseOverPopup = true;
    }
    popupWin.onmouseout = function() {
        window.mouseOverPopup = false;
    }
    
    popupWinPoint = lat+":"+lng;
    
    resetPopup();
    
    popupWin.style.zIndex = "5000";
    popupWin.style.display = "";
}

function resetPopup() {
    // do call back
    if (window.popupReset) {
        window.popupReset();
    }
    if (!lastMarker) return;
    
    var infoPoint = lastMarker.getPoint();
    var c = map.fromLatLngToDivPixel(infoPoint);
    var offX = lastMarker.getIcon().iconAnchor.x;
    var offY = lastMarker.getIcon().iconAnchor.y;
    var x = c.x;
    if (x + popupWidth + 20 > map.fromLatLngToDivPixel(map.getBounds().getNorthEast()).x)
        x -= popupWidth + offX + 20;
    else 
        x += 30 - offX;
    if (x < 0)
        x = c.x - popupWidth/2;

    var size = map.getSize();
    var h = popupWin.offsetHeight;
    // img could be slow to load... if its too small, just approx
    if (h < 100) h = 240;

    // fixed to keep media from jumping;  if removed, fix size of media
    var y = c.y - 40; 

    var shift = 0;
    if (y + h > size.height) {
        y = size.height - (h + 5);
        shift++;
    }

    if (y < 0) {
        y = 5;
        shift++;
    }
    if (shift == 2)
        y = c.y + 20;

    popupWin.style.left = x + "px";
    popupWin.style.top = y + "px";

    popupWin.style.visibility = "visible";
}

function clickHidePopup() {
    if (!mouseOverPopup)
        hidePopup();
}   
    
function hidePopup() {
    if (lastMarker) {
        popupWin.parentNode.removeChild(popupWin);
        popupWinPoint = null;
        popupWin = null;
        lastMarker = null;
    }       
} 

function makePopup(marker, message, aMap) {
    message = "<div class='geoPopup'><div style='position:absolute; right:5px; top:5px;'><a href='#' onclick='hidePopup();return false'><img src='/ui/media/popup-close.png'></a></div>" + message + "</div>";
    // make it active
    GEvent.addListener(marker, "mouseover", function() {
        map = aMap;
        activeMarker = marker;
        activeMessage = message;
        // show in a bit
        setTimeout(showPopup, 200);
    });

    // make it inactive
    GEvent.addListener(marker, "mouseout", function() {
        map = aMap;
        // forget last rollover
        activeMarker = null;
        activeMessage = null;
//        setTimeout(hidePopup, 1000);
    });
}

// icon translation

    var listingIcons = new Array(
         "Drink Houses", "Things To See and Do", "Shopping", "Entertainment", "Food and Drink", "Nightlife", "Accommodation", "Visitor Information", "Sports, Health, and Fitness"
    );

    function getIconType(type) {
        for (var j=0; j < listingIcons.length; j++) {
            if (type.indexOf(listingIcons[j]) >= 0) {
                return "listing-" + listingIcons[j];
            }
        }
        return type;
    }

    function getIcon(type, anchorX, anchorY) {
        var icon = new GIcon();
        icon.iconSize = new GSize(23, 23);
        if (!anchorX) anchorX = 0;
        if (!anchorY) anchorY = 0;
        anchorX += 10;
        anchorY += 10;
        icon.iconAnchor = new GPoint(anchorX, anchorY);
        icon.infoWindowAnchor = new GPoint(5, 1);
        icon.image = '/ui/media/geo-';

        if (type == 'user')
            icon.image += 'user.png';
        else if (type == 'journal')
            icon.image += 'journal.png';
        else if (type == 'media')
            icon.image += 'media.png';
        else if (type == 'guide')
            icon.image += 'guide.png';
        else if (type == 'listing')
            icon.image += 'activity.png';

        else if (type == 'listing-Accommodation')
            icon.image += 'accommodations.png';
        else if (type == 'listing-Nightlife')
            icon.image += 'nightlife.png';
        else if (type == 'listing-Food and Drink')
            icon.image += 'dining.png';
        else if (type == 'listing-Entertainment')
            icon.image += 'events.png';
        else if (type == 'listing-Shopping')
            icon.image += 'shopping.png';
        else if (type == 'listing-Things To See and Do')
            icon.image += 'things-to-do.png';
        else if (type == 'listing-Drink Houses')
            icon.image += 'coffee.png';
        else if (type == 'listing-Visitor Information')
            icon.image += 'info.png';
        else if (type == 'listing-Sports, Health, and Fitness')
            icon.image += 'activity.png';
        else
           icon = null;
        return icon;
    }

var mapActiveButtons = new Object();
function mapTurnOn(div, key) {
    var lastDiv = mapActiveButtons[key]; 
    if (lastDiv)
        lastDiv.innerHTML = lastDiv.innerHTML.replace(/-on/, "-off");
    div.innerHTML = div.innerHTML.replace(/-off/, "-on");
    mapActiveButtons[key] = div;
}   
function mapRollover(div) {
    if (div.firstChild.src.match(/-off/))
        div.firstChild.src = div.firstChild.src.replace(/-off/, "-on");
}
function mapRollout(div, key) {
    var lastDiv = (key) ? mapActiveButtons[key] : '';
    if (div.firstChild.src.match(/-on/) && div != lastDiv)
        div.firstChild.src = div.firstChild.src.replace(/-on/, "-off");
}    

// clean up
window.onunload = function deinit() {
    try { // fails in IE sometimes
        if (window.GUnload)
            window.GUnload();
    } catch (err) { }
}
