﻿var map;
var utilmap;
var latlng_current;
var latlng_new;
var autoZooming;
var panning;
var targetZoom;
var phaseZoom;
var locs;

function showLocation(lat, lng, infoString, location) {
    autoZooming = false;
    panning = false;
    phaseZoom = false;
    // if a location has been passed then we need to geocode this location and get the co-ordinates.
    // when a location is passed we don't show the marker.
    if (location == null) {
        //getLocations();
        latlng_current = new google.maps.LatLng(lat, lng);
        buildMap(latlng_current, true, infoString);
        //buildUtilMap(latlng_current);
    }
    else {
        if (location.length > 0) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'address': location }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK)
                    if (status != google.maps.GeocoderStatus.ZERO_RESULTS)
                    buildMap(results[0].geometry.location, false, infoString);
            });
        }
    }
}

function buildMap(latlng, shouldDisplayMarker, infoString) {
    map = getMap(latlng);

    if (infoString.length > 0)
        var infowindow = new google.maps.InfoWindow({ content: infoString });

    if (shouldDisplayMarker)
        addMarker(latlng);

    setSvPanorama(latlng);

    google.maps.event.addListener(map, 'maptypeid_changed', function() { document.getElementById('hdnMapTypeId').value = map.getMapTypeId(); });

    google.maps.event.addListener(map, 'zoom_changed', function() { zoomChanged(); });
}

function buildUtilMap(latlng) {
    var umap = document.createElement("div");
    umap.setAttribute("id", "umap");
    document.body.appendChild(umap);

    var opts = {
        center: latlng,
        mapTypeId: getMapType(),
        zoom: parseInt(document.getElementById("hdnZoom").value)
    }
    utilmap = new google.maps.Map(umap, opts);

    var bounds = new google.maps.LatLngBounds;

    for (var i = 0; i < locs.length; i++) {
        bounds.extend(locs[i]);
    }

    utilmap.fitBounds(bounds);
    google.maps.event.addListener(utilmap, "idle", function() { $j("#hdnTargetZoom").val(utilmap.getZoom()); });
}

function getLocations() {
    locs = [$j("#stage div.city-picker li a").length];
    var i = 0;
    $j("#stage div.city-picker li a").each(function() {
        var c = $(this).attr("onclick").toString();
        var idx = c.indexOf('moveMap("') + 9;
        var idx_1 = c.indexOf('"', idx);
        var lat = c.substring(idx, idx_1);
        idx = c.indexOf(', ', idx_1) + 3;
        idx_1 = c.indexOf(')', idx) - 1;
        var lng = c.substring(idx, idx_1);
        var latlng = new google.maps.LatLng(lat, lng);
        locs[i] = latlng;
        i = i + 1;
    });
}

function getMap(latlng) {
    var mapControlOptions = {
        position: QualifyPosition(document.getElementById("hdnMapControlPosition").value),
        style: document.getElementById("hdnMapControlStyle").value
    }

    var navControlOptions = {
        position: QualifyPosition(document.getElementById("hdnNavigationControlPosition").value),
        style: document.getElementById("hdnNavigationControlStyle").value
    }

    var scaleControlOptions = {
        position: QualifyPosition(document.getElementById("hdnScaleControlPosition").value)
    }

    var myOptions = {
        center: latlng,
        disableDefaultUI: parseAsBoolean(document.getElementById("hdnDisableDefaultUI").value),
        mapTypeControl: parseAsBoolean(document.getElementById("hdnMapTypeControl").value),
        mapTypeControlOptions: mapControlOptions,
        mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.HYBRID] },
        mapTypeId: getMapType(),
        navigationControl: parseAsBoolean(document.getElementById("hdnNavigationControl").value),
        navigationControlOptions: navControlOptions,
        scaleControl: parseAsBoolean(document.getElementById("hdnScaleControl").value),
        scaleControlOptions: scaleControlOptions,
        streetViewControl: parseAsBoolean(document.getElementById("hdnStreetView").value),
        zoom: parseInt(document.getElementById("hdnZoom").value)
    }

    return map = new google.maps.Map(document.getElementById("map"), myOptions);
}

function addMarker(latlng) {

    var image = new google.maps.MarkerImage('/sitecore/__/_images/ef_googlemap_icon.png',
                                            new google.maps.Size(35, 43),
                                            new google.maps.Point(0, 0),
                                            new google.maps.Point(18, 41) );

    var marker = new google.maps.Marker({   position: latlng,
                                            map: map,
                                            icon: image,
                                            visible: true });

    google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); });
}

function setSvPanorama(latlng) {
    panorama = map.getStreetView();
    panorama.setPosition(latlng);
    panorama.setPov({   heading: 265,
                        zoom: 1,
                        pitch: 0 });
}

function checkSV(latlng) {
    var sv = new google.maps.StreetViewService
    sv.getPanoramaByLocation(latlng, 50, processSVData);
}

function checkSVCallback(data, status) {
    if (status == google.maps.StreetViewStatus.OK)
        return true;
    return false;
}

function parseAsBoolean(str) {
    if (str.toLowerCase() == "true")
        return true;
    return false;
}

function QualifyPosition(str) {
    switch (str.toLowerCase()) {
        case "BOTTOM":
            return google.maps.ControlPosition.BOTTOM;
        case "BOTTOM_LEFT":
            return google.maps.ControlPosition.BOTTOM_LEFT;
        case "BOTTOM_RIGHT":
            return google.maps.ControlPosition.BOTTOM_RIGHT;
        case "LEFT":
            return google.maps.ControlPosition.LEFT;
        case "RIGHT":
            return google.maps.ControlPosition.RIGHT;
        case "TOP":
            return google.maps.ControlPosition.TOP;
        case "TOP_LEFT":
            return google.maps.ControlPosition.TOP_LEFT;
        case "TOP_RIGHT":
            return google.maps.ControlPosition.TOP_RIGHT;
    }
}

function toggleStreetView() {
    var toggle = panorama.getVisible();
    if (toggle == false)
        panorama.setVisible(true);
    else
        panorama.setVisible(false);
}

function getMapType() {
    switch (document.getElementById("hdnMapTypeId").value.toUpperCase()) {
        case "ROADMAP":
            return google.maps.MapTypeId.ROADMAP;
        case "HYBRID":
            return google.maps.MapTypeId.HYBRID;
        case "SATELLITE":
            return google.maps.MapTypeId.SATELLITE;
        case "TERRAIN":
            return google.maps.MapTypeId.TERRAIN;
    }
}

function moveMap(lat, lng) {
    latlng_current = new google.maps.LatLng(document.getElementById("hdnLat").value, document.getElementById("hdnLng").value);
    latlng_new = new google.maps.LatLng(lat, lng);
    addMarker(latlng_new);

    var bounds = new google.maps.LatLngBounds();
    bounds.extend(latlng_current);
    bounds.extend(latlng_new);

    if (phaseZoom)
        zoomOut(parseInt($j("#hdnTargetZoom").val()));
    else {
        google.maps.event.addListener(utilmap, "idle", function() { google.maps.event.clearListeners(utilmap, "idle"); zoomOut(utilmap.getZoom()); });
        utilmap.fitBounds(bounds);
    }
}

function zoomOut(zoomLevel) {
    google.maps.event.addListener(map, "idle", function() { reachTargetZoom(); });
    if (phaseZoom) {
        targetZoom = zoomLevel;
        autoZooming = true;
        reachTargetZoom();
    }
    else {
        map.setZoom(zoomLevel);
    }
}

function reachTargetZoom() {
    if (phaseZoom) {
        if (autoZooming) {
            var z = map.getZoom();
            if (z > targetZoom)
                map.setZoom(z - 1);
            else {
                autoZooming = false;
                google.maps.event.clearListeners("idle");
                google.maps.event.addListener(map, "idle", function() { mapRefocusing(); });
                targetZoom = parseInt(document.getElementById('hdnZoom').value);
                panning = true;
                map.panTo(latlng_new);
            }
        }
    }
    else {
        google.maps.event.clearListeners("idle");
        google.maps.event.addListener(map, "idle", function() { mapRefocusing(); });
        window.setTimeout("map.panTo(latlng_new)", 500);
    }
}

function mapRefocusing() {

    if (phaseZoom) {
        var z = map.getZoom();
        if (autoZooming) {
            if (z < targetZoom)
                map.setZoom(z + 1);
            else {  // we've arrived at our destination
                autoZooming = false;
                latlng_current = map.getCenter();
                google.maps.event.clearListeners(map, "idle");
            }
        }
        else {
            if (panning)
                panning = false;
            autoZooming = true;
            if (z < targetZoom)
                map.setZoom(z + 1);
        }
    }
    else {
        window.setTimeout("map.setZoom(parseInt(document.getElementById('hdnZoom').value))", 500);
    }
}

function zoomChanged() {
    if (!autoZooming)
        document.getElementById('hdnZoom').value = map.getZoom();
}
