var iMap = {

    map: null,
    numMarkers: 5,
    points: [],
    markers: [],
    currentInfoWindow: null,
    

    init: function(){
        if (GBrowserIsCompatible()) {

            iMap.mapContainer = $('#map_container');
            iMap.mapCanvas = document.getElementById('map_canvas');
            iMap.mapLegend = $('#map_legend');
            iMap.mapLoader = $('#map_loading');
            iMap.mapID = $('#map_id').attr('value');
            iMap.mapInfoWindow = $('#map_popup');
            iMap.polyline = $('#map_polyline').val();

            iMap.data = eval($('#map_data').html());
            iMap.zoom = $('#map_zoom').val();

            iMap.map = new GMap2(iMap.mapCanvas);
            iMap.loading();
            iMap.mapInfoWindow.appendTo(
                iMap.map.getPane(G_MAP_FLOAT_SHADOW_PANE)
            );
            iMap.generatePoints();
            //iMap.liveLegend();

            iMap.displayPoint(iMap.markers[0], 0);

            $(document.body).unload(function(){
               GUnload();
            });
        }
    },

    generatePoints: function(){

        var avg = {lat: 0,lng: 0};
        var bounds = new GLatLngBounds();
        var markerCount = 0;
        iMap.numMarkers = iMap.data.length;
        for (var i = 0; i < iMap.numMarkers; i++) {
            var point = new GLatLng(
                iMap.data[i].lat,
                iMap.data[i].lng
            );
            bounds.extend(point);
            iMap.points[i] = point;

            if (iMap.data[i].flag == 1){
                var icon = new GIcon(G_DEFAULT_ICON);
                var marker = new GMarker(point,
                {
                    icon: icon,
                    title: $('#point-' + (i + 1) + ' .title').html()
                });
                iMap.markers[markerCount] = marker;
                iMap.map.addOverlay(marker);
                markerCount++;
            }
            
            avg.lat += point.lat();
            avg.lng += point.lng();
        }
        if (iMap.polyline == 1){
            iMap.map.addOverlay(
                new GPolyline(iMap.points, '#000', 4, 0.6, {
                    geodesic:true
                })
            );
        }

        iMap.map.setCenter(new GLatLng(
            avg.lat / iMap.numMarkers,
            avg.lng / iMap.numMarkers),
            iMap.zoom == 0
                ? iMap.map.getBoundsZoomLevel(bounds)
                : parseInt(iMap.zoom)
        );


        $(iMap.markers).each(function(i,marker){
            $('#point-' + (i+1))
            .click(function(){
                iMap.displayPoint(marker, i);
            });

            GEvent.addListener(marker, "click", function(){
                iMap.displayPoint(marker, i);
            });
        });
    },

    displayPoint: function(marker, i){
        var markerOffset = iMap.map.fromLatLngToDivPixel(marker.getLatLng());
        var center = iMap.map.getCenter();
        if (iMap.currentInfoWindow != i){
            iMap.hidePoints();
            iMap.currentInfoWindow = i;
            $('#point-'+ (i + 1) +' .content').slideDown('slow');

            var moveEnd = GEvent.addListener(iMap.map, "moveend", function(){

                $(iMap.mapInfoWindow)
                    .html('<span id="popup-controls"><b id="popup-close">close X</b></span>' +
                        '<h3 id="popup-title">' + $('#point-' + (i + 1) + ' .title').html() + '</h3>' +
                        '<div id="popup-content">' + $('#point-' + (i + 1) + ' .content').html() + '</div>'
                        )
                    .css({
                        top: markerOffset.y - 50,
                        left: markerOffset.x + 15
                    })
                    .animate({
                        opacity: "show",
                        top: markerOffset.y - 30,
                        left: markerOffset.x + 15
                    },
                    "normal"
                );

                $('#popup-close').live('click', function(){
                    iMap.hidePoints();
                });

                GEvent.removeListener(moveEnd);

            });

            iMap.map.panTo(marker.getLatLng());

            if (center == marker.getLatLng()){
                $(iMap.mapInfoWindow)
                    .html('<span id="popup-controls"><b id="popup-close">close X</b></span>' +
                        '<h3 id="popup-title">' + $('#point-' + (i + 1) + ' .title').html() + '</h3>' +
                        '<div id="popup-content">' + $('#point-' + (i + 1) + ' .content').html() + '</div>'
                        )
                    .css({
                        top: markerOffset.y - 50,
                        left: markerOffset.x + 15
                    })
                    .animate({
                        opacity: "show",
                        top: markerOffset.y - 30,
                        left: markerOffset.x + 15
                    },
                    "normal"
                );

                $('#popup-close').bind('click', function(){
                    iMap.hidePoints();
                });

                GEvent.removeListener(moveEnd);
            }

        }
        if($(iMap.mapInfoWindow).is(':hidden')) {

            $('#point-'+ (i + 1) +' .content').slideDown('slow');
            $(iMap.mapInfoWindow)
                    .html('<span id="popup-controls"><b id="popup-close">close X</b></span>' +
                        '<h3 id="popup-title">' + $('#point-' + (i + 1) + ' .title').html() + '</h3>' +
                        '<div id="popup-content">' + $('#point-' + (i + 1) + ' .content').html() + '</div>'
                        )
                    .css({
                        top: markerOffset.y - 50,
                        left: markerOffset.x + 15
                    })
                    .animate({
                        opacity: "show",
                        top: markerOffset.y - 30,
                        left: markerOffset.x + 15
                    },
                    "normal"
                );
        }
    },

    hidePoints: function(){
        iMap.mapInfoWindow.fadeOut('fast');
        iMap.mapLegend.find('.content').slideUp('fast');
    },

    loading: function(){
        iMap.mapLoader.show();
        GEvent.addListener(iMap.map, "tilesloaded", function(){
            iMap.mapLoader.fadeOut('slow');
        });
    },

    liveLegend: function(){
        var i = 0;
        window.setInterval(
            function(){
                if (i < iMap.markers.length) {
                    iMap.displayPoint(iMap.markers[i], i);
                    i++;
                } else {
                    i = 0;
                }
            },
            4000
            );
    }

}

$(document).ready(function(){

   
    iMap.init();

    $('#switch').toggle(
        function() {
            $('body').fadeTo('normal', 0, function(){
                iMap.mapContainer.attr('class','fullscreen');
                iMap.displayPoint(iMap.markers[0], 0);
                $(this).fadeTo('normal', 1);
            });
        },
        function() {
            $('body').fadeTo('normal', 0, function(){
                iMap.mapContainer.attr('class','default');
                iMap.displayPoint(iMap.markers[0], 0);
                $(this).fadeTo('normal', 1);
            });
        }
    );

});