var gmarkers = [];
var maps = [];
var icons = [];
var bounds = [];
var streetViews = [];

function createIcon(image) {
    var icon = new GIcon();
    icon.image = image;
    icon.iconSize = new GSize(20, 34);
    icon.iconAnchor = new GPoint(10, 33);
    icon.infoWindowAnchor = new GPoint(10, 10);
    icons[image] = icon;
}

function resizeMap(mapID) {
    maps[mapID].checkResize();
}

function createMap(id, x, y, zoom, smallMapControl, mapTypeControl, largeMapControl) {
    var map = new GMap2(document.getElementById(id));
    map.setCenter(new GLatLng(x, y), zoom);
    map.enableContinuousZoom();
    map.enableDoubleClickZoom();
    if (smallMapControl) {
        map.addControl(new GSmallMapControl());
    }
    if (mapTypeControl) {
        map.addControl(new GMapTypeControl());
    }
    if (largeMapControl) {
        map.addControl(new GLargeMapControl());
    }
    maps[id] = map;
    bounds[id] = new GLatLngBounds();
}

function createStreetView(id, povValue, povField) {
    if (povValue == null) {
        return;
    }
    var vals = povValue.split(',');
    if (povValue.length < 2) {
        return;
    }
    var panoramaOptions = {
        latlng:new GLatLng(vals[0], vals[1])
    };
    if (vals.length > 2) {
        panoramaOptions.pov = {yaw:parseFloat(vals[2]),pitch:parseFloat(vals[3]),zoom:parseFloat(vals[4])};
    }
    streetViews[id] = new GStreetviewPanorama(document.getElementById(id), panoramaOptions);
    if (povField != null) {
        var viewChanged = function () {
            updateView(id, povField);
        };
        GEvent.addListener(streetViews[id], "yawchanged", viewChanged);
        GEvent.addListener(streetViews[id], "pitchchanged", viewChanged);
        GEvent.addListener(streetViews[id], "zoomchanged", viewChanged);
    }
    GEvent.addListener(streetViews[id], "error", handleNoFlash);
}

function updateView(id, povField) {
    var pov = streetViews[id].getPOV();
    var panoId = streetViews[id].getPanoId();
    new GStreetviewClient();
    var streetData = new GStreetviewClient().getPanoramaById(panoId, function(streetData) {
        latLng = streetData.location.latlng;
        document.getElementById(povField).value = latLng.lat() + "," + latLng.lng() + "," + pov.yaw + "," + pov.pitch + "," + pov.zoom;
    });
}

function storeView(id, fieldId) {
    var pov = streetViews[id].getPOV();
    var field = document.getElementById(fieldId);
    field.value = pov.yaw + "," + pov.pitch + "," + pov.zoom
}

function handleNoFlash(errorCode) {
    if (errorCode == "FLASH_UNAVAILABLE") {
        alert("Error: Flash doesn't appear to be supported by your browser");
    }
}


function addMarker(mapID, x, y, infoId, title, markerID, image, imageHigh, group) {
    if (image != null && icons[image] == null) {
        createIcon(image);
    }
    var point = new GLatLng(x, y);
    addMarkerWithPoint(mapID, point, infoId, title, markerID, image, imageHigh, group);
}

function addMarkerWithPoint(mapID, point, infoId, title, markerID, image, imageHigh, group) {
    if (image != null && icons[image] == null) {
        createIcon(image);
    }
    if (gmarkers[markerID] != null) {
        maps[mapID].removeOverlay(gmarkers[markerID]);
    }
    var marker = new GMarker(point, {title: title, icon:icons[image]});
    maps[mapID].addOverlay(marker);
    marker.title = title;
    marker.image = image;
    marker.imageHigh = imageHigh;
    marker.group = group;
    marker.infoNode = document.getElementById(infoId);
    if (infoId != null) {
        GEvent.addListener(marker, "click", function() {
            highlightMarker(mapID, markerID);
        });
    }
    gmarkers[markerID] = marker;
    bounds[mapID].extend(point);
    return marker;
}


function autoCenter(mapID) {
    var map = maps[mapID];
    var mapBounds = bounds[mapID];
    map.setZoom(map.getBoundsZoomLevel(mapBounds));
    var clat = (mapBounds.getNorthEast().lat() + mapBounds.getSouthWest().lat()) / 2;
    var clng = (mapBounds.getNorthEast().lng() + mapBounds.getSouthWest().lng()) / 2;
    map.setCenter(new GLatLng(clat, clng));
}

function showGroup(group, hide) {
    for (var markerID in gmarkers) {
        var marker = gmarkers[markerID];
        if (marker.group == group) {
            if (hide) {
                marker.hide();
            } else {
                marker.show();
            }
        }
    }
}

var highlighted;

function highlightMarker(mapID, markerID) {
    var gmarker = gmarkers[markerID];
    if (highlighted != null) {
        highlighted.setImage(highlighted.image);
    }
    maps[mapID].panTo(gmarker.getPoint());
    if (gmarker.imageHigh != null) {
        gmarker.setImage(gmarker.imageHigh);
    }
    gmarker.openInfoWindow(gmarker.infoNode);
    highlighted = gmarker;
}

var geocoder = null;

function findAddress(mapID, source, value, markerImage, markerImageHighlight, title, postfix, cookie) {
    if (geocoder == null) {
        geocoder = new GClientGeocoder();
    }
    if (source != null) {
        var element = document.getElementById(source);
        if (element != null) {
            value = element.value;
        }
    }
    if (value != null) {
        geocoder.getLatLng(
                value + postfix,
                function(point) {
                    if (!point) {
                        alert('Address ' + value + " not found");
                    } else {
                        if (title == null) {
                            title = value;
                        }
                        maps[mapID].setCenter(point, 13);
                        addMarkerWithPoint(mapID, point, null, title, 'Base', markerImage, markerImageHighlight, 'Base');
                        if (cookie != null) {
                            createCookie(cookie, value, 3650);
                        }
                    }
                }
                );
    }
}

function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

