
$(function () {
    
    initMap();
    addMarkers(markers);
    $("#river_input").autocomplete("/river/ajax/");
    
});


var map;

function initMap() {
    // Initialises the map
    map = new GMap2($("#map")[0]);
    map.addControl(new GSmallMapControl());
    map.addControl(new MapKeyControl());
    showUK();
    // Move the attribution to the top
    // Currently breaks where bubbles appear
    var attrib = $("#map")[0].childNodes[2];
    //attrib.style.bottom = "370px";
    //attrib.style.top = "2px";
    addWhiteOverlay();
    addRiversOverlay();
}

function showUK() { 
    // Center on the UK
    var center = new GLatLng(53, -2);
    map.setCenter(center, 6);
}

var marker_sets = {mp: [], individual: [], organisation: []};

function markerImportance(marker, dummy) {
    return marker.importance;
}

function addMarker(lat, lng, html, type) {
    // Adds a new marker to the map.
    
    // Get the point
    var point = new GLatLng(lat, lng);
    
    // Make a new marker
    if (type == "mp") {
        icon = mpIcon;
        importance=3000;
    } else if (type == "organisation") {
        icon = organisationIcon;
        importance=2000;
    } else {
        icon = individualIcon;
        importance=1000;
    }
    marker = new GMarker(point, {icon: icon,zIndexProcess:markerImportance});
    // Set the importance (equivalent to the CSS z-index) of the marker. 
    // Higher valued markers will sit above lower ones.
    // The z-index for the marker will be requested by calling markerImportance() which returns
    // importance attribute of the marker (that function can be called anything as can the attribute).
    marker.importance = importance;
    
    // Make a window popup.
    GEvent.addListener(marker, 'click', function(){ 
        this.openExtInfoWindow(
            map,
            "front-window",
            html,
            {beakOffset: 3}
        );
    });
    
    GEvent.addListener(map, 'zoomend', function () {
        var zoom = map.getZoom();
        if (zoom > 7) {
            map.setZoom(7);
        } else if (zoom < 5) {
            map.setZoom(5);
        }
    });

    map.addOverlay(marker);
    
    // Remember it
    marker_sets[type].push(marker);
}

function addMarkers(markers) {
    for (var i in markers) {
        var marker = markers[i];
        addMarker(marker.lat, marker.lng, marker.html, marker.type);
    }
}

// Shows a set, e.g. 'mp'
function showSet(name) {
    for (var i in marker_sets[name]) {
        map.addOverlay(marker_sets[name][i]);
    }
}

// Hides a set, e.g. 'individual'
function hideSet(name) {
    for (var i in marker_sets[name]) {
        map.removeOverlay(marker_sets[name][i]);
    }
}


/////// Rivers overlay /////////

function addRiversOverlay() {
    var boundaries = new GLatLngBounds(new GLatLng(49.8,-7.5), new GLatLng(60.1,2));
    var rivers = new GGroundOverlay("/static/images/rivers_overlay.gif", boundaries);
    map.addOverlay(rivers);
}

function addWhiteOverlay() {
    var myCopyright = new GCopyrightCollection("© ");
    var tilelayer = new GTileLayer(myCopyright);
    tilelayer.getTileUrl = function() { return "/static/images/tile_white.png"; };
    tilelayer.isPng = function() { return true;};
    tilelayer.getOpacity = function() { return 1; }
    var myTileLayer = new GTileLayerOverlay(tilelayer);
    map.addOverlay(myTileLayer);
}

/////// Map key control ////////
var doHideKey;

function MapKeyControl() {}
MapKeyControl.prototype = new GControl();

// Creates the main DIVs.
MapKeyControl.prototype.initialize = function(map) {
    // 'Key' tab
    var container = document.createElement("div");
    container.id = "key-tab";
    map.getContainer().appendChild(container);
    // Inside that, stick a currently-invisible key div
    var key = $("<ul id='key-main'></ul>");
    // Make the entries
    var types = {individual: "Individuals", mp:"MPs / Lords", organisation: "Organisations"};
    for (var type in types) {
        var title = types[type];
        var li = $("<li class='" + type + "'>" + title + "</li>");
        var input = $("<img class='checkbox' src='/static/images/box_checked.png' />");
        input[0].marker_set = type;
        input[0].on = true;
        li.prepend(input)
        key.append(li);
        input.click(function () {
            this.on = !this.on;
            if (this.on) {
                this.src = '/static/images/box_checked.png';
                li.innerHTML = "foo";
                showSet(this.marker_set);
            } else {
                this.src = '/static/images/box_unchecked.png';
                hideSet(this.marker_set);
            }
        });
        $(li).bind('mouseout',function(){doHideKey=true;setTimeout('hideKey()',10);}) // Hide key after a short delay
        $(li).bind('mouseover',function(){doHideKey=false;}) // Block a hide if moved to another key item (hence the need for the delay)
    }
    container.appendChild(key[0]);
    // Clicking the button should make the key show and hide
    key.hide();
    $(container).toggle(function () {
        $(key).fadeIn("fast");
    }, function () {
        $(key).fadeOut("fast");
    });
    // Stop clicks on the key making it disappear
    $(key).click(function (ev) { return false; });
    return container;
}

function hideKey() {
    if (doHideKey) {
        $('ul#key-main').fadeOut("fast"); // Moused off all the key item (not just from one to another)
        $('div#key-tab').trigger("click"); // Toggle the button so that the next click is show
    }
}

// Appear near the bottom-right 
MapKeyControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 0));
}
