﻿var map = null;

function pointMap(address) {
    if (GBrowserIsCompatible()) {
        if (centerMapOnLocationName(map, address, StoreLocatorData.stores)) {
            return;
        }

        if (centerMapOnLocationName(map, address, _getFixedLocations())) {
            return;
        }

        if (address.indexOf("portugal") == -1) {
            address = address + ", portugal";
        }
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(
			address,
			function(point) {
			    if (!point) {
			        alert(address + " nÃ£o foi encontrado.");
			    } else {
			        centerMapOnLocation(map, point.lat(), point.lng());
			    }
			}
		);
    }
}

function loadMap() {

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.enableScrollWheelZoom();

        centerMap(map);
        map.addControl(new GSmallZoomControl()); // +- zoom
        map.addControl(new GMapTypeControl());
        map.addControl(new GOverviewMapControl());
        map.setMapType(G_HYBRID_MAP);

        addOverlays(map);
    }
}

function getCharCode(str, index) {
    if (str.substr(index, 1) != '%') {
        throw "Invalid argument";
    }
    return parseInt(str.substr(index + 1, 2), 16);
}

function urlDecode(text) {
    var decodedText = "";

    for (var i = 0; i < text.length; ++i) {
        var character = text.substr(i, 1);
        if (character == '%') {
            var charCode = getCharCode(text, i);

            if (charCode >= 194 && charCode <= 223) {
                charCode = (charCode - 192) * 64 + getCharCode(text, i + 3) - 128;
                i += 3;
            } else if (charCode >= 224 && charCode <= 239) {
                charCode = (charCode - 224) * 4096 + (getCharCode(text, i + 3) - 128) * 64 + getCharCode(text, i + 6) - 128;
                i += 6;
            } else if (charCode >= 240 && charCode <= 244) {
                charCode = (charCode - 240) * 262144 + (getCharCode(text, i + 3) - 128) * 4096 + (getCharCode(text, i + 6) - 128) * 64 + getCharCode(text, i + 9) - 128;
                i += 9;
            }

            character = String.fromCharCode(charCode);
            i += 2;
        }
        decodedText += character;
    }
    return decodedText;
}

function getStoreName(address) {
    return
}

function centerMap(map) {
    var storeNameParser = /^#Modelo( |%20)(.+)$/;
    var match = storeNameParser.exec(window.location.hash);
    if (match != null && match.length > 2) {
        var storeName = urlDecode(match[2]);
        if (centerMapOnLocationName(map, storeName, StoreLocatorData.stores)) {
            return;
        }
    }

    map.setCenter(new GLatLng(38.792694, -9.195342), 6);
}

function centerMapOnLocationName(map, locationName, addresses) {
    locationName = locationName.toLowerCase();

    for (var i = 0; i < addresses.length; ++i) {
        var address = addresses[i];
        if (address != null) {
            if (address.name.toLowerCase() == locationName) {
                centerMapOnLocation(map, address.latitude, address.longitude);
                return true;
            }
        }
    }
    return false;
}

function centerMapOnLocation(map, lat, lng) {
    // Check whether the point is outside of the continent
    var zoom;
    if (lat < 37 || lng < -9.5) {
        zoom = 8;
    } else {
        zoom = 11;
    }

    map.setCenter(new GLatLng(lat, lng), zoom);
}

function NamesOverlay(addresses) {
    var map = null;
    var mapPane = null;

    var labels = [];

    this.initialize = function(_map) {
        map = _map;

        mapPane = map.getPane(G_MAP_MAP_PANE);

        /*for (var i = 0; i < addresses.length; ++i) {
            var address = addresses[i];
            var label = new Fullsix.Element("span", { text: address.name, className: "Map_Label" });
            labels.push({ label: label, location: new GLatLng(address.latitude, address.longitude) });
            mapPane.appendChild(label);
        }*/
    }

    this.remove = function() {
        for (var i = 0; i < labels.length; ++i) {
            mapPane.removeChild(labels[i]);
        }
    }

    this.copy = function() {
        return new NamesOverlay(addresses);
    }

    this.redraw = function(force) {
        if (!force) {
            return;
        }

        var zoom = map.getZoom();

        for (var i = 0; i < labels.length; ++i) {
            var label = labels[i];

            if (zoom < 7) {
                label.label.style.display = "none";
            } else {
                var coordinates = map.fromLatLngToDivPixel(label.location);
                label.label.style.left = (coordinates.x + 15) + "px";
                label.label.style.top = (coordinates.y - 10) + "px";
                label.label.style.display = "inline";
                label.label.style.fontSize = Math.floor(zoom) + "px";
            }
        }
    }
}

function addOverlays(map) {
    var BaseIcon = new GIcon();
    BaseIcon.image = '/images/edp_logo.jpg';
    BaseIcon.iconSize = new GSize(15, 16);
    BaseIcon.iconAnchor = new GPoint(8, 8);
    BaseIcon.infoWindowAnchor = new GPoint(8, 8);

    for (var i = 0; i < StoreLocatorData.stores.length; ++i) {
        var address = StoreLocatorData.stores[i];

        //if (address.name == null) alert('tá null pá');
        if (address != null) {
            var html = "<h1>" + address.name + "</h1><br/>" + address.address + "<br/>" + address.postalCode;
//            if (address.phone != null && address.phone.length > 0) {
//                html += "<br/>Telefone: " + address.phone;
//            }
            html += "<h2>Horário</h2>" + address.openingHours;


            addOverlay(map, address.latitude, address.longitude, html, address.services, BaseIcon, StoreLocatorData.services);
        }
    }

    map.addOverlay(new NamesOverlay(StoreLocatorData.stores));
}

function addOverlay(map, lat, lng, html, services, icon, serviceDescriptions) {
    /*html += "<div class='services'>";
    if (services != null) {
        for (var i = 0; i < services.length; ++i) {
            var serviceIndex = services[i];
            html += "<img src='/templates/modelo/images/services/" + serviceDescriptions[serviceIndex].iconUrl + "' title='" + serviceDescriptions[serviceIndex].name + "' alt='" + serviceDescriptions[serviceIndex].name + "' />";
        }
    }
    html += "</div>";*/
    //html += '<a class="culturalEvents" href="http://modelo.fullsix.local/modelo/index.php/eventos.html#' + /*address.district +*/ '">Ver eventos culturais perto de si!</a>';

    var thisIcon = new GIcon(icon);
    markerOptions = { icon: thisIcon };
    var marker = new GMarker(new GLatLng(lat, lng));  //, markerOptions);
    GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml('<div style="height: 180px;">' + html + '</div>', { maxWidth: 250 });
    });
    map.addOverlay(marker);

}

function _getFixedLocations() {
    return [
		{ latitude: 32.74108223150125, longitude: -16.907958984375, name: 'Madeira' },
		{ latitude: 38.67264490154078, longitude: -27.2021484375, name: 'AÃ§ores' },
		{ latitude: 38.67264490154078, longitude: -27.2021484375, name: 'Acores' }
	];
}

(function() {
    var previous = window.pageLoaded; window.pageLoaded = function() {
        if (previous != null) previous();
        loadMap();
    } 
})();

