// Author: Thomas Høi - it-arkitekterne.dk
//netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

// The singleton MAP.
var map = null;
var nonMapHeight = null;
var mapElement = null;
var sidebarElement = null;
var urlPrefix = "";
var generalNote = null; // Array of note lines

function resizeFunction() {
    // TODO [tho] - Remove the width its not used.
    resizeMap(mapElement, 200, nonMapHeight, sidebarElement);
}


function initilizeMap(mapId, sidebarId, usedHeight, defaultMarker, selectedMarker, minLat, maxLat, minLng, maxLng) {
    mapElement = document.getElementById(mapId);
    sidebarElement = document.getElementById(sidebarId)
    nonMapHeight = usedHeight;

    itaSelectedIcon.image = selectedMarker;
    itaMarkerIcon.image = defaultMarker;

    resizeFunction();
    window.onresize = resizeFunction;

    if (GBrowserIsCompatible()) {
        map = new GMap2(mapElement);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
        map.addControl(new GOverviewMapControl());

        map.enableContinuousZoom();
        map.enableDoubleClickZoom();
        map.enableScrollWheelZoom();
        map.enableInfoWindow();

        new ItaMapManager(map, salesOrg, sidebarElement, minLat, maxLat, minLng, maxLng).show();
        findSiteAndCenter();
    }

    var commonElement = document.getElementById("common");
    if (commonElement && generalNote) {
        if (this.generalNote.length > 0) {
            var html = "<b>" + localizedText.openingHoursGeneralNote + "</b><br />";
            for (var i = 0; i < this.generalNote.length; i++) {
                html += this.generalNote[i] + "<br />";
            }
        }
        commonElement.innerHTML = html;
    }

}

/*
 * resizeMap resizes the element used to hold the google map.
 * Parameters:
 *    mapElement - The element holding the google map.
 *    usedWidth - Number of pixel used for left and right bar elements.
 *    usedHeight - Number of pixels used for header and footer elements
 */
function resizeMap(mapElement, usedWidth, usedHeight, sideBarElement) {
    var width = 0, height = 0;
    if (typeof(window.innerWidth) == 'number') {
        //Non-IE
        width = window.innerWidth;
        height = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }

    var sidebarWidth = sideBarElement.clientWidth > 0 ? sideBarElement.clientWidth + 0 : usedWidth;

    //mapElement.style.width = (width - (sidebarWidth + 16)) + "px"; // 2 margin a 5px body, margin 2 x 2px
    mapElement.style.height = (height - (usedHeight + 10)) + "px";
}

function debugMapViewPort(map) {
    //noinspection JSUnresolvedFunction
    var latLngBounds = map.getBounds();
    //noinspection JSUnresolvedFunction
    alert("sw=" + latLngBounds.getSouthWest() + " ne=" + latLngBounds.getNorthEast() + " zoom=" + map.getZoom());
}

// FUnction to center and zoom
function gmapCenterAndZoom(gmap, minLat, maxLat, minLng, maxLng) {
    try {
        //noinspection JSUnresolvedFunction
        var swPoint = new GLatLng(minLat, minLng);
        //noinspection JSUnresolvedFunction
        var nePoint = new GLatLng(maxLat, maxLng);
        //noinspection JSUnresolvedFunction
        var latLngBound = new GLatLngBounds(swPoint, nePoint);
        //noinspection JSUnresolvedFunction
        var center = new GLatLng((minLat + maxLat) / 2, (minLng + maxLng) / 2);
        //noinspection JSUnresolvedFunction
        var zoom = gmap.getBoundsZoomLevel(latLngBound);
        //alert("zoom=" + zoom);
        //noinspection JSUnresolvedFunction
        gmap.setCenter(center, zoom);
    } catch (e) {
        alert(e);
    }
}

// Parses the anchor part of the url in order to find site and select it.
function findSiteAndCenter() {
    var parts = location.href.split("#");
    if (parts.length >= 2) {
        var siteWerks = parts[1];
        var site = mapManager.findSite(siteWerks);
        if (site) {
            site.select(15);
            // Select site at set the zoomlevel to 15.
        }
    }
}

// Should we debug?
var debugMap = false;

// Itegration to the facade server.
var facadeImageBaseUrl = null;
var facadeImageExtension = null;


// ---------------------------------------------------------------------------------------
// Localization

// Default locale is en.
var itaLocale = "en";

var localizedText = { };
localizedText.openingHours = "Opening hours";
localizedText.openingHoursNote = "Special opening hours";
localizedText.openingHoursGeneralNote = "General note"
// ---------------------------------------------------------------------------------------
// ItaMapManager

var mapManager = null;

// Constructs a new Manager. The min/max lat lng suggeest
function ItaMapManager(map, salesOrg, infoElement, minLat, maxLat, minLng, maxLng) {
    if (map != null) {
        this.map = map;
        this.salesOrg = salesOrg;
        mapManager = this;
        this.infoElement = infoElement;
        this.selectedSite = null;
        this.suggestedMinLat = minLat;
        this.suggestedMaxLat = maxLat;
        this.suggestedMinLng = minLng;
        this.suggestedMaxLng = maxLng;
    }
}

ItaMapManager.prototype = new ItaMapManager();

// shows the map and markers for every site.
ItaMapManager.prototype.show = function() {
    this.centerAndZoom();
    this.salesOrg.show();
}

ItaMapManager.prototype.calculateMinMax = function() {
    this.minLatitude = this.suggestedMinLat;
    this.maxLatitude = this.suggestedMaxLat;
    this.minLongitude = this.suggestedMinLng;
    this.maxLongitude = this.suggestedMaxLng;
    for (var i = 0; i < this.salesOrg.sites.length; i++) {
        var site = this.salesOrg.sites[i];
        if (this.minLatitude == null || site.lat < this.minLatitude) {
            this.minLatitude = site.lat;
        }
        if (this.maxLatitude == null || site.lat > this.maxLatitude) {
            this.maxLatitude = site.lat;
        }
        if (this.minLongitude == null || site.lng < this.minLongitude) {
            this.minLongitude = site.lng;
        }
        if (this.maxLongitude == null || site.lng > this.maxLongitude) {
            this.maxLongitude = site.lng;
        }
    }
}

ItaMapManager.prototype.centerAndZoom = function() {
    this.calculateMinMax();
    gmapCenterAndZoom(this.map, this.minLatitude, this.maxLatitude, this.minLongitude, this.maxLongitude);
}


ItaMapManager.prototype.findSite = function(werks) {
    for (var i = 0; i < this.salesOrg.sites.length; i++) {
        var site = this.salesOrg.sites[i];
        if (site.werks == werks) {
            return site;
        }
    }
}

// ---------------------------------------------------------------------------------------
// SalesOrg

// COnstruncts a new sales org
// - vkorg - id of the organisation.
function ItaSalesOrg(vkorg) {
    if (vkorg != null) {
        this.vkorg = vkorg;
        this.sites = [];
    }
}

ItaSalesOrg.prototype = new ItaSalesOrg();

// Adds site to this sales org.
// werks - id of the site
// lat - The latitude of the site
// lng - The longitude of the site.
// name1 - The first name line
ItaSalesOrg.prototype.addSite = function(werks, lat, lng, name1) {
    var site = new ItaSite(werks, lat, lng, name1);
    this.sites.push(site);
}

ItaSalesOrg.prototype.show = function() {
    for (var i = 0; i < this.sites.length; i++) {
        this.sites[i].show();
    }
}

// ---------------------------------------------------------------------------------------------
// ItaSite

// Constructs a new Site
function ItaSite(werks, lat, lng, name1) {
    if (werks != null) {
        this.werks = werks;
        this.lat = lat;
        this.lng = lng;
        this.name1 = name1;
        //noinspection JSUnresolvedFunction
        this.latLng = new GLatLng(lat, lng);
        this.selected = false;
    }
}

ItaSite.prototype = new ItaSite();

ItaSite.prototype.show = function() {
    if (! this.gmarker) {
        this.createMarker()
    }
}

// The default icon for selected.
//noinspection JSUnresolvedFunction
var itaSelectedIcon = new GIcon();
itaSelectedIcon.image = "/map/icons/jyskmarker_selected.gif";
//noinspection JSUnresolvedFunction
itaSelectedIcon.iconSize = new GSize(20, 20)
//noinspection JSUnresolvedFunction
itaSelectedIcon.iconAnchor = new GPoint(10, 20);
//noinspection JSUnresolvedFunction
itaSelectedIcon.infoWindowAnchor = new GPoint(10, 1);
var itaSelectedMarkerOptions = { draggable: false, icon: itaSelectedIcon, title: "JYSK" };

//noinspection JSUnresolvedFunction
var itaMarkerIcon = new GIcon();
itaMarkerIcon.image = "/map/icons/jyskmarker.gif"
//noinspection JSUnresolvedFunction
itaMarkerIcon.iconSize = new GSize(20, 20)
//noinspection JSUnresolvedFunction
itaMarkerIcon.iconAnchor = new GPoint(10, 20);
//noinspection JSUnresolvedFunction
itaMarkerIcon.infoWindowAnchor = new GPoint(10, 1);

var itaDefaultMarkerOptions = { draggable: false, icon: itaMarkerIcon, title: "JYSK" };

ItaSite.prototype.createMarker = function() {
    if (this.gmarker) {
        mapManager.map.removeOverlay(this.gmarker);
    }
    //noinspection JSUnresolvedFunction
    var markerOptions = this.selected ? itaSelectedMarkerOptions : itaDefaultMarkerOptions;
    markerOptions.title = this.name1;
    this.gmarker = new GMarker(this.latLng, markerOptions);
    this.gmarker.itaMarker = this;
    var itaSite = this;
    var singleClick = true;
    var onClick = function() {
        setTimeout(function () {
            if (singleClick) {
                itaSite.select();
            }
        }, 250)
    }
    //noinspection JSUnresolvedVariable,JSUnresolvedFunction
    GEvent.addListener(this.gmarker, "click", onClick);
    //noinspection JSUnresolvedVariable,JSUnresolvedFunction
    GEvent.addListener(this.gmarker, "dblclick", function () {
        singleClick = false;
        itaSite.select();
    });


    //noinspection JSUnresolvedFunction
    mapManager.map.addOverlay(this.gmarker);

    return this.gmarker;
}


ItaSite.prototype.select = function(specificZoom) {
    var curzoom = mapManager.map.getZoom();
    var zoomIntoMinLevel = Math.min(curzoom + 3, 12)
    var zoomlevel = specificZoom ? specificZoom : Math.max(curzoom, zoomIntoMinLevel);
    mapManager.map.setCenter(this.latLng, zoomlevel);
    if (mapManager.selectedSite) {
        // There was one selected all ready - unselected and change icon
        mapManager.selectedSite.selected = false;
        mapManager.selectedSite.createMarker();
    }
    mapManager.selectedSite = this;
    this.selected = true;
    this.createMarker();
    this.loadDetails();
    changeAnchor(this.werks);
}

function changeAnchor(anchor) {
    var parts = location.href.split("#");
    var newUrl = parts[0] + "#" + anchor
    location.href = newUrl;
}

ItaSite.prototype.loadDetails = function() {
    // TODO [tho]

    // Try ad load cross domain with yahoo
    var jurl = urlPrefix + "/map/user/shop.jsp?site=" + this.werks + "&locale=" + itaLocale;
    var objTransaction = YAHOO.util.Get.script(jurl, { onSuccess: function() {
        // Nothing todo - script will show by it self.
    }});
}

var siteDetails = {};

// -- ItaOpeningHour
function ItaOpeningHour(day, opening, closing) {
    this.day = day;
    this.opening = opening;
    this.closing = closing;
}

ItaOpeningHour.prototype = new ItaOpeningHour();

ItaOpeningHour.prototype.debug = function () {
    var result = "";
    for (var property in this) {
        result += property + "=" + this[property] + " ";
    }
    return result;
}

// -- ItaSiteDetails
function ItaSiteDetails(werks, name, street, houseNo, postCode, city, country, telnr, facadeImage) {
    if (werks) {
        siteDetails[werks] = this;
        this.werks = werks;
        this.name = name;
        this.street = street;
        this.houseNo = houseNo;
        this.postCode = postCode;
        this.city = city;
        this.coutry = country;
        this.telnr = telnr;
        this.facadeImage = facadeImage;
        this.openingHours = [];
        this.openingHourNote = [];
        this.generalNote = [];
        this.openingHourUrl = null;
    }
}

ItaSiteDetails.prototype = new ItaSiteDetails();

// - Adds opening hours.
ItaSiteDetails.prototype.addOpeningHour = function(day, opening, closing) {
    var openingHour = new ItaOpeningHour(day, opening, closing);
    this.openingHours[this.openingHours.length] = openingHour;
}

ItaSiteDetails.prototype.addOpeningHourNote = function(line) {
    this.openingHourNote[this.openingHourNote.length] = line;
}

ItaSiteDetails.prototype.addGeneralNote = function(line) {
    this.generalNote[this.generalNote.length] = line;
}

ItaSiteDetails.prototype.debug = function() {
    var result = "";
    for (var property in this) {
        if (property == "openingHours") {
            result += "openingHours[";
            for (var i = 0; i < this.openingHours.length; i++) {
                result += (i > 0 ? ", " : "") + this.openingHours[i].debug;
            }
            result += "] ";
        } else {
            result += property + "=" + this[property] + " ";
        }
    }
    return result;
}


ItaSiteDetails.prototype.show = function() {
    var html = "<h2>" + this.name + "</h2>";
    html += this.street + " " + this.houseNo + "<br />";
    html += this.postCode + " " + this.city + "<br />";
    html += this.telnr + "<br />";
    if (this.facadeImage) {
        var facadeImageUrl = facadeImageBaseUrl + this.werks + "." + facadeImageExtension;
        html += "<br /><img src='" + facadeImageUrl + "' alt='facade' />";
    }
    html += "<p><b>" + localizedText.openingHours + "</b><br />";
    html += "<table class='openingHours'>";
    for (var i = 0; i < this.openingHours.length; i++) {
        html += "<tr>";
        var openingHour = this.openingHours[i];
        html += "<td>" + openingHour.day + "</td><td>" + openingHour.opening + "</td><td>" + openingHour.closing + "</td><td width='100%'> </td>";
        html += "</tr>";
    }
    html += "</table>";

    if (this.openingHourNote.length > 0) {
        html += "<br /><b>" + localizedText.openingHoursNote + "</b><br />";
        for (var i = 0; i < this.openingHourNote.length; i++) {
            html += this.openingHourNote[i] + "<br />";
        }
    }

    if (this.generalNote.length > 0) {
        html += "<br /><b>" + localizedText.openingHoursGeneralNote + "</b><br />";
        for (var i = 0; i < this.generalNote.length; i++) {
            html += this.generalNote[i] + "<br />";
        }
    }

    html += "</p>";

    mapManager.infoElement.innerHTML = html
}


