﻿var $j = jQuery;
var restaurantUrl;
var isFirstLoad;
var map;
var baseUrl;
var initialLatLng;

function initialize(restaurantAlias, bUrl, zoomToPoints) {
    if (GBrowserIsCompatible()) {

        isFirstLoad = true;
        map = new GMap2(document.getElementById("google-map"));
        map.enableScrollWheelZoom();
        
        restaurantUrl = restaurantAlias;
        baseUrl = bUrl;

        //                var mt = map.getMapTypes();                
        //                for (var i = 0; i != mt.length; i++) {
        //                    mt[i].getMinimumResolution = function() { return 9; }
        //                    mt[i].getMaximumResolution = function() { return 17; }
        //                }
        //
        
        map.setCenter(new GLatLng(49.8, 15.3), 7);
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl ());
        map.addControl(new GHierarchicalMapTypeControl());
        fitMap(map, zoomToPoints);                        
               
        //map.addControl(new GSmallMapControl());

        debug("loading");
        loadMap(true);
        debug("loaded");

        GEvent.addListener(map, "moveend", function() {
            //map.clearOverlays();
            if (!isFirstLoad) {
                loadMap(false);
                debug("moved")
            }
        });
    }
}

function loadMap(zoomAfterLoad) {
    var bounds = map.getBounds();
    var north = bounds.getNorthEast().lat().toString();
    var east = bounds.getNorthEast().lng().toString();
    var south = bounds.getSouthWest().lat().toString();
    var west = bounds.getSouthWest().lng().toString();

    var format = "json";
    var url = baseUrl + "/georss2.ashx?format=" + format + "&north=" + north + "&east=" + east + "&south=" + south + "&west=" + west;
    debug(url);

    GDownloadUrl(url, function(data, responseCode) {
        // To ensure against HTTP errors that result in null or bad data,
        // always check status code is equal to 200 before processing the data
        if (responseCode == 200) {
            parseJson(data, zoomAfterLoad);
        } else if (responseCode == -1) {
            //alert("Data request timed out. Please try later.");
        } else {
            //alert("Request resulted in error. Check XML file is retrievable.");
        }
    });
}

function parseJson(doc, zoomAfterLoad) {
    debug("parsing");
    //debug(doc);
    var jsonData = JSON.parse(doc);
    //var jsonData = eval("(" + doc + ")");
    debug("parsed");

    var points = [];
    var defaultIcon = createIcon(jsonData.data.defaultIcon);

    for (var i = 0; i < jsonData.data.restaurants.length; i++) {
        var bubbleContent = formatTabOne(jsonData.data.restaurants[i]);

        var icon = createIcon(jsonData.data.restaurants[i].icon);
        if (icon == null) {
            icon = defaultIcon;
        }

        var marker = createMarker(jsonData.data.restaurants[i], icon, bubbleContent);
        map.addOverlay(marker);
        if (isFirstLoad && restaurantUrl == jsonData.data.restaurants[i].url) {
            isFirstLoad = false;
            marker.openInfoWindowHtml(
                bubbleContent
            );
        }
        var latlng = new GLatLng(jsonData.data.restaurants[i].point.lat, jsonData.data.restaurants[i].point.lon);
        points.push(latlng);
    }

    if (isFirstLoad) {
        isFirstLoad = false;
    }
}

function createIcon(restaurantIcon) {
    if (restaurantIcon == null) {
        return null;
    }

    var icon = new GIcon();
    icon.image = baseUrl + restaurantIcon.url;
    icon.iconSize = new GSize(restaurantIcon.width, restaurantIcon.height);
    icon.iconAnchor = new GPoint(restaurantIcon.anchorX, restaurantIcon.anchorY);
    icon.infoWindowAnchor = new GPoint(restaurantIcon.windowAnchorX, restaurantIcon.windowAnchorY);
    return icon;
}

function createMarker(restaurant, icon, bubbleContent) {

    var title = restaurant.title;
    var marker = new GMarker(new GLatLng(restaurant.point.lat, restaurant.point.lon), { title: title, icon: icon, draggable: false });

    GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(
                bubbleContent
            );
    });

    return marker;
}

function renderMenu(dishes) {
    var html = "<table class=\"dishes\">";
    for (var i = 0; i < dishes.length; i++) {
        html += "<tr";
        if (i % 2 == 0) {
            html += " class=\"alternate\"";
        }
        html += ">";
        html += "<td class=\"dish-name\">" + dishes[i].name + "</td>";
        html += "<td class=\"dish-price\">";
        if (dishes[i].price > 0) {
            html += dishes[i].price + ",- Kč";
        } else {
            html += "&nbsp;"
        }
        html += "</td>";
        html += "</tr>";
    }
    if (dishes == null || dishes.length == 0) {
        html += "<tr class=\"alternate\"><td>Restaurace na dnešní den nevyplnila polední menu.</td></tr>";
    }
    html += "</table>";
    return html;
}

function formatTabOne(restaurant) {
    var html = "<div class=\"bubble\">";
    html += "<p><strong>" + restaurant.title + "</strong><br/>" + restaurant.street + "</p>";
    html += "<p class=\"bold\">Dnešní polední menu:</p>";
    html += renderMenu(restaurant.dishes);
    html += "<p><a href=\"http://www.polednicek.cz/" + restaurant.url + "\">detail restaurace</a></p>";
    html += "</div>";
    return html;
}

function debug(message) {
    //$j("#debug-message").append(message + "<br/>");  
}

function fitMap(map, points) {
    if (points.length == 0) {
        return;
    }
    var bounds = new GLatLngBounds();
    for (var i = 0; i < points.length; i++) {
        debug("fit i=" + i + " point: " + points[i][0] + ", " + points[i][1]);
        var latlng = new GLatLng(points[i][0], points[i][1]);        
        bounds.extend(latlng);
    }
    map.setZoom(map.getBoundsZoomLevel(bounds));
    initialLatLng = bounds.getCenter();
    map.setCenter(initialLatLng);
}

GMap.prototype.centerAndZoomOnBounds = function(bounds) {
    // make 10% bigger so all markers show completely
    var span = new GSize((bounds.maxX - bounds.minX) * 1.1, (bounds.maxY - bounds.minY) * 1.1);
    var center = new GPoint(bounds.minX + span.width / 2., bounds.minY + span.height / 2.);

    var newZoom = this.spec.getLowestZoomLevel(center, span, this.viewSize);
    if (this.getZoomLevel() != newZoom) {
        this.centerAndZoom(center, newZoom);
    } else {
        this.recenterOrPanToLatLng(center);
    }
}

function checkResizeMap() {
    map.checkResize();
    map.setCenter(initialLatLng);
}
