/*jslint browser: true */
/*global $ google */


var cellmap = cellmap || {};

cellmap.index = {

    // Default parameters (North America)
    // 53.1, -101.4, 4
    defaults: {
        lat: 53.1,
        lng: -101.4,
        zoom: 4
    },
    
    map_is_ready: false,
    selected_maplocation: null,

    // URL mappings; these correspond to the Django application URLs
    urls: {
        map_query: '/query/'
    },

    // The Google Map instance
    gMap: {},

    // Set up and configure the map
    setupMap: function(lat, lng, zoom) {

        if (!google.maps.BrowserIsCompatible()) {
            return;
        }

        cellmap.index.gMap = new google.maps.Map2(document.getElementById('maparea'));
        cellmap.index.selected_maplocation = null;

        // Reload last centerpoint and zoom level.
        var gmu_center = $.cookie("gmu_box_center");
        var gmu_zoom = $.cookie("gmu_box_zoom");
        if( gmu_center && gmu_zoom ) {
            var gmu_center_latlng = new google.maps.LatLng.fromUrlValue(gmu_center);
            gmu_zoom = Number(gmu_zoom)
            cellmap.index.gMap.setCenter(gmu_center_latlng, gmu_zoom);
        } else {
            // Use defaults if all parameters were not specified
            var lat = cellmap.index.defaults.lat;
            var lng = cellmap.index.defaults.lng;
            var zoom = cellmap.index.defaults.zoom;
            cellmap.index.gMap.setCenter(new google.maps.LatLng(lat, lng), zoom);
        }

        cellmap.index.gMap.addControl(new google.maps.MapTypeControl());
        cellmap.index.gMap.addControl(new google.maps.LargeMapControl());
        cellmap.index.gMap.enableScrollWheelZoom();
//        cellmap.index.gMap.disableDoubleClickZoom();
        cellmap.index.gMap.enablePinchToZoom();
        cellmap.index.gMap.enableContinuousZoom();

        // Initial update
        cellmap.index.map_is_ready = true;
        cellmap.index.updateMap(cellmap.index.gMap.getBounds());

        // Update the map on pan or zoom
        google.maps.Event.addListener(cellmap.index.gMap, 'moveend', function() {
            cellmap.index.updateMap(cellmap.index.gMap.getBounds());
        });

        // Clear selected maplocation on single map click
        google.maps.Event.addListener(cellmap.index.gMap, 'click', function(overlay, latlng, overlaylatlng) {
            if( overlay === null ) {
                cellmap.index.selectMapLocation(null);
                return false;
            }
        });
    },

    // Update the map display
    updateMap: function(bounds) {
        // bounds should be a GLatLngBounds instance
        
        if( cellmap.index.map_is_ready === false )
        {
            return;
        }

        // Save latest centerpoint and zoom level.
        var gmu_center = cellmap.index.gMap.getCenter();
        var gmu_zoom = cellmap.index.gMap.getZoom();
        $.cookie("gmu_box_center", gmu_center.toUrlValue());
        $.cookie("gmu_box_zoom", gmu_zoom );
        $.cookie("gmu_box_zoom", gmu_zoom );
        
        
        // Get Reduced bounds inside the visible area.
        var sw = bounds.getSouthWest();
        
        var gmuBox = $("#gmu");
        var transparentLegendbox = $("#transparentLegendbox");
        var topRightCorner = new google.maps.Point(gmuBox.width()-transparentLegendbox.width(), 0);
        var ne = cellmap.index.gMap.fromContainerPixelToLatLng(topRightCorner); //bounds.getNorthEast();

        // Fetch new map overlay data from server
        $.ajax({
            url: cellmap.index.urls.map_query,
            cache: false,
            dataType: 'json',
            data: {
                north: ne.lat(),
                east: ne.lng(),
                south: sw.lat(),
                west: sw.lng(),
                searchTerm: cellmap.index.getSearchTerm(),
            },
            success: function(data){
                cellmap.index.gMap.clearOverlays();
                $("#legendContents ul").empty();
                var base_index = 1;

                // Special-case: show selected map location first
                // when it's NOT in matched search results.
                if( cellmap.index.selected_maplocation ) {
                    var selected_in_results = false;
                    var merged_results = [];
                    $.merge(merged_results, data.matches);
                    $.merge(merged_results, data.other);
                    for( i in merged_results ) {
                        var m = merged_results[i];
                        if( m.url === cellmap.index.selected_maplocation.url ) {
                            selected_in_results = true;
                        }
                    }
                
                    if( selected_in_results === false ) {
                        cellmap.index.addMapLocation(cellmap.index.selected_maplocation, "selected", 0);
                    }
                    $("#legendContents ul").append("<hr />");
                }
                
                if( data.matches.length > 0 ) {
                    $.each(data.matches, function(i, val) {
                        cellmap.index.addMapLocation(val, "matches", i+base_index);
                    });
                    
                    $("#legendContents ul").append("<hr />");
                }
                
                base_index += data.matches.length;
                $.each(data.other, function(i, val) {
                    cellmap.index.addMapLocation(val, "other", i+base_index);
                });
            }
        });
    },
    
    platform_to_platform_name: {j2me:"java", celltouch:"cellmap", iphone:"iphone"},
    
    showMapLocationInfoWindow: function(maplocation) {
        var info_window_html = "<div class='map_info_bubble'>"
				+"<img src='"+maplocation.thumbnail+"' alt='' class='map_thumb'>"
				+"<h1>"+maplocation.title+"</h1>"
				+"<p>"+maplocation.location+"</p>"
				+"<p><a href='"+maplocation.url+"'>Details &gt;&gt;</a></p>"
			    +"</div>";
        maplocation.marker.openInfoWindowHtml(info_window_html);
    },
    
    selectMapLocation: function(maplocation) {
        cellmap.index.selected_maplocation = maplocation;
        cellmap.index.gMap.closeInfoWindow();
        $("#legendContents ul li").removeClass("selected");
        if( maplocation ) {
            // Show gmu info bubble.
            cellmap.index.showMapLocationInfoWindow(maplocation);

            // Hilight selected map location in list.
            var listItem = $("#"+maplocation.list_id);
            listItem.addClass("selected");
            
            // // Make sure selected location is scrolled into view.
            // var targetOffset = listItem.position().top;
            // console.log(listItem, targetOffset);
            // var legendContents = $("#legendContents");
            // legendContents.animate({scrollTop:targetOffset});
        }
    },
    
    addMapLocation: function(maplocation, list, marker_number) {
        var platform_name = cellmap.index.platform_to_platform_name[maplocation.platform];
        var icon = new GIcon();
        if( marker_number <= 9 ) {
            icon.image = "/media/assets/images/mapMarkers/"+platform_name+"_"+marker_number+".png";
            icon.shadow = "/media/assets/images/mapMarkers/shadow.png";
            icon.iconSize = new google.maps.Size(24.0, 54.0);
            icon.shadowSize = new google.maps.Size(54.0, 54.0);
            icon.iconAnchor = new google.maps.Point(13.0, 54.0);
            icon.infoWindowAnchor = new google.maps.Point(13.0, 10.0);
        } else { // dot marker
            icon.image = "/media/assets/images/mapMarkers/dot.png";
            icon.iconSize = new google.maps.Size(19.0, 19.0);
            icon.iconAnchor = new google.maps.Point(8.0, 8.0);
            icon.infoWindowAnchor = new google.maps.Point(11.0, 8.0);
        }

        var point = new google.maps.LatLng(maplocation.latitude, maplocation.longitude);
        maplocation.marker = new google.maps.Marker(point, icon);
        google.maps.Event.addListener(maplocation.marker, "click", function() {
            cellmap.index.selectMapLocation(maplocation);
            return false;
        });

        cellmap.index.gMap.addOverlay(maplocation.marker);

        if( marker_number <= 9 ) {
            var legendContentsList = $("#legendContents ul");
            maplocation.list_id = "marker_"+marker_number;
            var alternate_class = "";
            if( (marker_number%2) === 1 )
                alternate_class = "alternate_panel";
            
            var listItem = $(
                "<li id='"+maplocation.list_id+"' class='"+alternate_class+"'>"
                +"    <img src='"+maplocation.thumbnail+"' alt='' class='map_thumb' />"
                +"    <a href='#' class='map_marker'><img src='/media/assets/images/mapMarkers/"+platform_name+"_"+marker_number+".png' alt='"+platform_name+" "+marker_number+"' /></a>"
                +"    <div class='marker_contents'><h1>"+maplocation.title+"</h1>"
                +"    <p>"+maplocation.location+"</p>"
				+"    <p><a href='"+maplocation.url+"'>Details &gt;&gt;</a></p></div>"
                +"</li>");

            // Track clicks on the legendContainer marker.
            listItem.find("a.map_marker,img.map_thumb").click(function() {
                cellmap.index.selectMapLocation(maplocation);
                return false;
            });

            legendContentsList.append(listItem);
            listItem.data("maplocation", maplocation);

            if( cellmap.index.selected_maplocation
                && maplocation.url === cellmap.index.selected_maplocation.url ) {
                listItem.addClass("selected");
            }
        }
        
        if( cellmap.index.selected_maplocation
            && maplocation.url === cellmap.index.selected_maplocation.url ) {
            cellmap.index.showMapLocationInfoWindow(maplocation);
        }
    },

    setupSearchTermHandler: function() {
        var legend_searchTerm = $.cookie("legend_searchTerm");
        if( legend_searchTerm ) {
            $('#legendboxTitleBar #searchTerm').val( legend_searchTerm );
        }

        $('#legendboxTitleBar form').submit(function() {
            $.cookie("legend_searchTerm", $('#legendboxTitleBar #searchTerm').val());
            cellmap.index.updateMap(cellmap.index.gMap.getBounds());
            return false;
        });
    },
    
    getSearchTerm: function() {
        return $('#legendboxTitleBar #searchTerm').val();
    },

    initialize: function() {
        // Set up login input fields
        $('#clientLogin input.inputFieldBox').fancylogin();
        
        cellmap.index.setupSearchTermHandler();

        // Initialize map (must come after setting up the
        // SearchTermHandler, so it knows what searchTerm
        // to use on the first ajax query)
        cellmap.index.setupMap();
    }

};
