﻿
hs.showCredits = 0;
hs.graphicsDir = '/highslide/graphics/';
hs.outlineType = 'rounded-light-brown'; //rounded-white
hs.wrapperClassName = 'draggable-header no-footer';
hs.allowSizeReduction = true;
hs.preserveContent = true;
hs.align = 'center';
hs.dimmingOpacity = 0.50;
hs.dimmingDuration = 0;

var e = []; function ce(id) { if (!e[id]) { e[id] = $(id); } return e[id]; }

e['document'] = $(document);
e['document'].ready(function() { app.init();  });


var app = {

    map: null,
    slat: 46.20561651350874,
    slng: 6.124019622802734,
    szoom: 13,

    /* Max and mon coords and zoom factor for Geneva region */
    minZoom: 12,
    maxZoom: 16,
    minLat: 46.320,            //north
    maxLat: 46.120,            //south
    minLng: 5.921,             //west
    maxLng: 6.320,             //east
    arrMarkers: new Array(),
    allowedBounds: null,
    isTotoVisible: false,
    isToStay: false,
    winId: 'infoWin',
    totoX: 0,
    totoY: 0,
    boxX: 0,
    boxY: 0,
    totoWidth: 320,
    totoHeight: 320,
    curType: '',

    init: function() {

        $(window).bind('unload', function(event) { app.unLoad(); });
        $().mousemove(function(e) { app.totoX = e.pageX; app.totoY = e.pageY; });
        $('#' + this.winId).hide();

        app.initMap();
        app.refreshIcons();
        $("#accordion").accordion();
        $('input.chkType').click(function(evt) { evt.stopPropagation(); var cid = app.curType = $(this).attr('value'); if ($(this).cbchecked()) { $('#l' + cid).attr('class', 'sel'); } else { $('#l' + cid).attr('class', ''); } app.refreshPoint(); });
        //$('.accHead').click(function(evt) { app.curType = $(this).attr('id'); alert(app.curType); });
        app.refreshPoint();

        

    },

    unLoad: function() { GUnload(); },

    initMap: function() {

        if (!this.map) {
            if (GBrowserIsCompatible()) {

                this.map = new GMap2($('#venue-map').get(0));

                /* Limits the map to Geneva region */
                this.allowedBounds = new GLatLngBounds(new GLatLng(this.maxLat, this.minLng), new GLatLng(this.minLat, this.maxLng));

                /* Limits the zoom factors */
                var mapTypes = this.map.getMapTypes(); for (var i = 0; i < mapTypes.length; i++) { mapTypes[i].getMinimumResolution = function() { return app.minZoom; }; mapTypes[i].getMaximumResolution = function() { return app.maxZoom; }; }

                /* Initialize an empty map and the controller */
                this.map.setCenter(new GLatLng(this.slat, this.slng), this.szoom);
                this.map.addControl(new GLargeMapControl3D(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(240, 10)));
                this.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(240, 10)));
                this.map.clearOverlays();

                /* Checks the limits of the map when moving*/
                GEvent.addListener(this.map, 'move', function(e) { app.checkBounds(); app.onMapMove(); });

                /* Resize elements when zooming in and out*/
                GEvent.addListener(this.map, 'zoomend', function(e) { app.refreshIcons(); app.onMapMove(); });

            }
        }
    },

    refreshPoint: function() {
        var query_string = '';
        $("input.chkType:checked").each(function() { if ($(this).cbchecked()) { query_string += "&types[]=" + $(this).attr('value'); } });
        $.getJSON('/fr/poi/getPoiList.asp?pxy=toto' + query_string, function(data) { app.displayPoint(data) });
    },

    // ====== This function displays the tooltip ======
    // it can be called from an icon mousover or a side_bar mouseover
    showTooltip: function(i, e) {
        app.stopToto();
        var marker = app.arrMarkers[i];
        app.onMouseOverElement(e, marker.publicid, i, marker.html);
    },

    iSize: [20, 25, 30, 40, 45, 50],

    displayPoint: function(data) {

        //if (app.curType != '') { $('#list-' + app.curType).empty(); }
        $('.poi-list').empty();
        if (data.poi && data.poi.length > 0) {

            var curZoom = this.map.getZoom();
            //alert(curZoom - 11);
            var newIconSize = app.iSize[curZoom - 11];
            //if (newIconSize < 17) { newIconSize = 17 };

            this.arrMarkers = [];
            this.map.clearOverlays();

            for (var i = 0; i < data.poi.length; i++) {

                var toto = data.poi[i];
                var myIcon = new GIcon();

                myIcon.image = '/images/poi/pushpin-008/' + toto.image + '.png';
                myIcon.iconSize = new GSize(newIconSize, newIconSize);
                myIcon.iconAnchor = new GPoint(parseInt(newIconSize / 5), newIconSize);
                myIcon.shadow = '/images/poi/pushpin-008/shadow-40.png';
                myIcon.shadowSize = new GSize(parseInt(newIconSize * 1.5), newIconSize);
                var point = new GLatLng(toto.lat, toto.lon);

                var arrMarker = Array();
                arrMarker['id'] = toto.publicid;
                arrMarker['name'] = toto.caption;
                arrMarker['html'] = toto.description;
                arrMarker['lat'] = toto.lat;
                arrMarker['lon'] = toto.lon;
                arrMarker['zoom'] = toto.zoom;

                if ($("input.chkType[value='" + toto.type + "']").cbchecked()) {
                    var tmpHtml = '<div ';
                    if ($("input.chkType[value='" + toto.type + "']").cbchecked()) { tmpHtml += ' class="active"'; }
                    tmpHtml += ' onmouseover="app.showTooltip(' + i + ')" onmouseout="app.stopToto()" onclick="app.focusObject(' + i + ');" id="p' + toto.publicid + '">' + toto.caption + '</div>';
                    $('#list-' + toto.type).append(tmpHtml);
                    arrMarker['object'] = app.createMarker(myIcon, point, arrMarker['id'], i, arrMarker['html']);

                    this.arrMarkers[i] = arrMarker;
                    if (toto.poly) {
                        var points = toto.poly.coords;

                        var sColor = toto.poly.sColor;
                        var sWeight = toto.poly.sWeight;
                        var sAlpha = toto.poly.sAlpha;
                        var fColor = toto.poly.fColor;
                        var fAlpha = toto.poly.fAlpha;

                        if (toto.image === 'green') {
                            sColor = '1a582f'; sWeight = 1; sAlpha = 1;
                            fColor = '2d8841', fAlpha = 0.5;
                        } else if (toto.image === 'red') {
                            sColor = '8d3223'; sWeight = 1; sAlpha = 1;
                            fColor = 'a53d2e', fAlpha = 0.5;
                        } else if (toto.image === 'blue') {
                            sColor = '0f3a72'; sWeight = 1; sAlpha = 1;
                            fColor = '185190', fAlpha = 0.5;
                        }


                        for (var j = 0; j < points.length; j++) { var coords = points[j].split(','); points[j] = new GLatLng(coords[0], coords[1]); }
                        var polygon = new GPolygon(points, '#' + sColor, sWeight, sAlpha, '#' + fColor, fAlpha);
                        this.map.addOverlay(polygon);
                    }

                } else {
                    $('#list-' + toto.type).append('<div >' + toto.caption + '</div>');
                    arrMarker['object'] = null;
                    this.arrMarkers[i] = arrMarker;
                }
            }
        } else {
            this.arrMarkers = [];
            this.map.clearOverlays();
        }
    },

    focusObject: function(index) {
        if (app.arrMarkers[index].object != null) {
            //alert('Zoom : ' + app.arrMarkers[index].zoom);
            app.map.setCenter(new GLatLng(app.arrMarkers[index].lat, app.arrMarkers[index].lon), parseInt(app.arrMarkers[index].zoom, 10));
            app.showTooltip(index, null);
            app.isToStay = true;
        }
    },

    refreshIcons: function() {
        /* Only way to change the size of the marker is to rebuild'em */
        var curZoom = this.map.getZoom();
        var newIconSize = app.iSize[curZoom - 11];
        var am = this.arrMarkers;
        for (var i = 0; i < am.length; i++) {
            var curId = am[i].id;
            var curHtml = am[i].html;
            var curMarker = am[i].object;
            var curIcon = curMarker.getIcon();

            var myIcon = new GIcon();
            myIcon.image = curIcon.image;
            myIcon.iconSize = new GSize(newIconSize, newIconSize);
            myIcon.iconAnchor = new GPoint(parseInt(newIconSize / 5), newIconSize);
            myIcon.shadow = curIcon.shadow;
            myIcon.shadowSize = new GSize(parseInt(newIconSize * 1.5), newIconSize);
            myNewMarker = app.createMarker(myIcon, curMarker.getLatLng(), curId, i, curHtml);
            curMarker.remove();
            am[i].object = myNewMarker;
        }
    },

    createMarker: function(icon, point, id, index, html) {
        var marker = new GMarker(point, { draggable: false, icon: icon });

        GEvent.addListener(marker, 'click', function(e) { app.isToStay = true; /*app.onClickElement(e, id, index, html); */ });
        GEvent.addListener(marker, 'mouseover', function(e) { app.onMouseOverElement(e, id, index, html); });
        GEvent.addListener(marker, 'mouseout', function(e) { app.onMouseOutElement(e, id, index, html); });
        this.map.addOverlay(marker);
        return marker;
    },

    onMouseOverElement: function(e, id, index, html) {

        var curZoom = this.map.getZoom();
        var vhSpacing = parseInt(app.iSize[curZoom - 11] / 2, 10);

        if (app.isToStay) { app.isTotoVisible = false; app.isToStay = false; };
        if (!(app.isTotoVisible)) {


            var marker = app.arrMarkers[index].object;
            app.isTotoVisible = true;
            var posX = app.map.fromLatLngToContainerPixel(marker.getPoint()).x;
            var posY = app.map.fromLatLngToContainerPixel(marker.getPoint()).y;
            var markerX = posX; var markerY = posY;
            var mapHeight = $('#venue-map').height(); var mapWidth = $('#venue-map').width();

            $('#message').html('').fadeOut('fast');

            if (posX > 0 && posX <= mapWidth && posY > 0 && posY <= mapHeight) {

                html = '<span class="title">' + this.arrMarkers[index].name + '</span>' + html;
                $('#' + this.winId + 'cc').html(html);

                var cwidth = app.totoWidth;  //$('#' + this.winId).width(app.totoWidth).width();
                var cheight = app.totoHeight; // $('#' + this.winId).height(app.totoHeight).height();

                /* position of the map */
                var myPos = $('#venue-map').findPos();

                posX = posX + myPos.x + vhSpacing;
                posY = posY + myPos.y - vhSpacing;

                //if (html == '') { cheight = 50; }
                //$('#debug').html(vhSpacing + ' ' + posX + ':' + posY + ' | ');

                /* correct the position according to the window size */
                if ((posX + cwidth) > $(window).width()) { posX = posX - cwidth - vhSpacing };
                if ((posY + cheight) > $(window).height()) { posY = posY - cheight };


                var bClass = '';
                if (markerY < posY) { bClass += 'b'; } else { bClass += 't'; };
                if (markerX < posX) { bClass += 'r'; } else { bClass += 'l'; };
                $('#' + this.winId).css('top', posY + 'px').css('left', posX + 'px').attr('class', 'infoWin-' + bClass);
                app.isTotoVisible = true;
                $('#' + this.winId).show();



            } else {
                $('#message').html('<div class="limitOut">Ce point est hors limites de la carte.<br/>Cliquez pour voir ce point ou déplacez-vous dans la carte</div>').fadeIn('fast');
                $('#' + this.winId + 'cc').html('');
                app.isTotoVisible = false;
                $('#' + this.winId).hide();
            }

        }
    },

    onMouseOutElement: function(e, id, index, html) {
        //var myMarker = this.arrMarkers[index].object;
        app.stopToto();
    },

    onMapMove: function() {
        app.isToStay = false; app.stopToto();
    },

    stopToto: function() {
        if (!app.isToStay) {
            app.isTotoVisible = false;
            $('#' + this.winId + 'cc').html('');
            $('#' + this.winId).hide();
            $('#message').html('').fadeOut('fast');

        }
    },

    checkBounds: function() {
        if (this.allowedBounds.contains(this.map.getCenter())) { return; }; var C = this.map.getCenter(); var X = C.lng(); var Y = C.lat(); var AmaxX = this.allowedBounds.getNorthEast().lng(); var AmaxY = this.allowedBounds.getNorthEast().lat(); var AminX = this.allowedBounds.getSouthWest().lng(); var AminY = this.allowedBounds.getSouthWest().lat(); if (X < AminX) { X = AminX; } if (X > AmaxX) { X = AmaxX; } if (Y < AminY) { Y = AminY; } if (Y > AmaxY) { Y = AmaxY; } this.map.setCenter(new GLatLng(Y, X));
    }

};

