// TODO: zoom in "link to this page"
// TODO: paginate posts
// TODO: handle multiple locations for each post


function get_bounds(as_array) {
    var bounds = map.getBounds();
    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();
    if (!as_array)
        return sw.lat() + ',' + sw.lng()  + '/' + ne.lat() + ',' + ne.lng();
    return new Array(sw.lat(), sw.lng(), ne.lat(), ne.lng());
}

var handle_zoom = function (old_level, new_level)  {
    zoom = new_level;
    //refresh_entries();
};

var refresh_entries = function () {
    var center = map.getCenter();
    $('#map_permalink').attr('href', '/geo/entries/' + center.lat() + ',' + center.lng() + '/' + zoom + '/' + page + '/');
    var bounds = get_bounds();
    $('#entries').block('<div id="waiting"><img src="' + waiting + '" alt="Waiting for data" /></div>');
    var url = base_url + '/geo/api/v1/entries/' + bounds + '/' + page + '/';
    $('#map_feed').attr('href', '/geo/feed/entries/' + bounds + '/');
    $('#log').empty();
    $('#log').append('<p>calling <a href="' + url + '">' + url + '</a></p>');
    $.ajax({
        type: "GET",
            url: url,
            dataType: "json",
            success: entries_cb
    });
};

GMarker.prototype.icon_from_charcode = function (charcode) {
    this.setImage(media_url + '/maps/blue_Marker' + String.fromCharCode(charcode+65) + '.png');
    //this.setImage(new GIcon(G_DEFAULT_ICON, media_url + '/maps/yellow_Marker' + String.fromCharCode(charcode+65) + '.png'));
};
GMarker.prototype.get_entry_infowindow = function () {
    return '<div class="geo-infowindow"><h3>' + this.entry['title'] + '</h3><p>' + this.entry['excerpt'] + '</p><p><strong><a href="' + this.entry['url'] + '">Leggi il post originale</a></strong></p></div>'
};
GMarker.prototype.highlight_on = function () {
    this.active = true;
    $("#ul-entries li").css("background", "#ffffff");
    $("#entry-" + this.entry['id']).parents("li").css("background", "#cccccc");
};
GMarker.prototype.highlight_off = function () {
    this.active = false;
    $("#entry-" + this.entry['id']).parents("li").css("background", "#ffffff");
};
GMarker.prototype.clicked = function () {
    if (this.active) {
        this.highlight_off();
        if (!map.getInfoWindow().isHidden())
            map.closeInfoWindow();
    } else {
        this.openInfoWindowHtml(this.get_entry_infowindow(), {maxWidth:240});
        this.highlight_on();
    }
};
    
var create_marker = function(entry, charcode) {
    var marker = new GMarker(new GLatLng(entry['lat'], entry['lon']), new GIcon(G_DEFAULT_ICON, media_url + '/maps/blue_Marker' + String.fromCharCode(charcode+65) + '.png'));
    marker.entry = entry;
    marker.active = false;
    GEvent.addListener(marker, "click", marker.clicked);
    GEvent.addListener(marker, "infowindowclose", marker.highlight_off);
    return marker;
}

var entries_cb = function (result) {
    var num_entries = result['num_entries'];
    var num_entries_formatted = result['num_entries_formatted'];
    var start = result['start'];
    var end = result['end'];
    if (start > 1 && page > 0)
        $(".prev").removeClass('hidden');
    else
        $(".prev").addClass('hidden');
    if (end >= num_entries) {
        end = num_entries;
        $(".next").addClass('hidden');
    } else {
        $(".next").removeClass('hidden');
    }
    $('#geo-numbers').html('Visualizzazione articoli ' + start + "-" + end + " di " + result['num_entries_formatted']);
    $('span.control-info').html(start + "-" + end + "/" + result['num_entries_formatted']).removeClass('hidden');
    $("controls").removeClass('hidden');
    //$("#entries h2")[0].innerHTML = "I post più recenti per quest'area (" + start + "-" + end + "/" + result['num_entries'] + ")"
    var entries = result['entries'];
    //var ul_left = $('#map-entries-left');
    //var ul_right = $('#map-entries-right');
    //ul_left.empty();
    //ul_right.empty();
    var ul = $('#entries');
    ul.empty();
    // map.clearOverlays();
    var charcode = 0;
    var _markers = new Array();
    for (var i in entries) {
        var entry = entries[i];
        var entry_id = entry['id'];
        if (typeof(entry_id) != 'number')
            continue;
        var marker = markers['entry_' + entry_id];

	var lettere = new Array();
	lettere[0] = 'a';
	lettere[1] = 'b';
	lettere[2] = 'c';
	lettere[3] = 'd';
	lettere[4] = 'e';

	var li = '<div class="litem"><div class="lindex">'+lettere[i]+'</div><div class="lcontent"><h2 class="ltitle"><a title="" class="ltitlea" id="entry-' + entry_id + '" href="' + entry['url'] + '">' + entry['title'] + '</a></h2><p class="ltxt">' + entry['excerpt'] + '</p>' + entry['date_published'] + ' | <a class="vaiab" href="/metrics/blog/' + entry['blog_slug'] + '" title="Vai al blog: ' + entry['blog_name'] + '">' + entry['blog_name'] + '</a> | <a class="vaiab" href="' + entry['url'] + '">leggi il post originale</a></div></div>';



        ul.append(li);
        if (typeof(marker) != 'undefined') {
            marker.icon_from_charcode(charcode);
            marker.entry = entry;
            if (marker.active)
                marker.highlight_on();
        } else {
            marker = create_marker(entry, charcode);
            map.addOverlay(marker);
        }
        _markers['entry_' + entry_id] = marker;
        charcode++;
    }
    for (var entry_id in markers) {
        if (!_markers[entry_id])
            map.removeOverlay(markers[entry_id]);
    }
    markers = _markers;
    $('#entries').unblock();
    $('.ltitle a').bind('click', function (event) {
        var marker = markers[event.target.id.replace('-', '_')];
        if (marker)
            marker.clicked();
        return false;
    });
    //mgr.refresh();
};

/*
 * define these in the page that includes this script
 
    var media_url = '{{media_url}}';
    var base_url = '{{base_url}}';
    var lat = {{lat}};
    var lon = {{lon}};
    var zoom = {{zoom}};
    var page = {{page}};
    var markers = new Array();
 
 */

var location_name_change = function (loc_id, loc_name) {
    $("#locations a").removeClass("sel");
    if (typeof(loc_id) == 'string' && loc_id) {
        window.location.hash = "#" + loc_id;
        document.title = base_title + ' - ' + loc_name;
        $("#locations a#location_" + loc_id).addClass("sel");
	$("#headinglocalsframe").html('<h2 class="headinglocals-ajaxtitle">' + base_title + ' - ' + loc_name + '</h2>');

    } else {
        window.location.hash = '#';
        document.title = base_title;
        $("#locations a#locations_all").addClass("sel");
	$("#headinglocalsframe").html('<h2 class="headinglocals-ajaxtitle">' + base_title + '</h2>');
    }

};


var load = function () {
    if (GBrowserIsCompatible()) {
        
        $(".prev a").bind('click', function () { page--; refresh_entries(); return false; });
        $(".next a").bind('click', function () { page++; refresh_entries(); return false; });
        
        $("#locations a").click(function () {
            var loc_id = $(this).attr('id').replace('location_', '');
            if (loc_id in location_data) {
                var loc_data = location_data[loc_id];
                var loc_name = loc_data.pop();
                location_name_change(loc_id, loc_name);
                //map.setCenter(new GLatLng(parseFloat(loc_data[0]), parseFloat(loc_data[1])), parseInt(loc_data[2]));
                map.setCenter(new GLatLng(loc_data[0], loc_data[1]), loc_data[2]);
            } else {
                location_name_change();
                map.setCenter(new GLatLng(default_lat, default_lon), default_zoom);
            }
        });
        
        if (typeof(map) == 'undefined')
            map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(lat, lon), zoom);
        
        // markers = new Array();

        // events
        GEvent.addListener(map, "moveend", refresh_entries);
        GEvent.addListener(map, "zoomend", handle_zoom);
        GEvent.addListener(map, "dragstart", function () { page = 0; });
        
        // check for a location hash
        if (typeof(window.location.hash) == 'string' && window.location.hash.replace('#', '') in location_data) {
            loc_id = window.location.hash.replace('#', '');
            var loc_data = location_data[loc_id];
            var loc_name = loc_data.pop();
            location_name_change(loc_id, loc_name);
        }
        
        refresh_entries();
        // json call
        // http://localhost:8080/geo/entries/33.8339199536547,5.537109375/49.468124067331644,19.599609375/
    }
}

