
var elSourceMarker = new Class({
    initialize: function(map,lat,long,icon,source_id) {
        var point = new GLatLng(lat,long);
        var marker = new GMarker(point,icon);
        this.marker = marker;
        this.map = map;
        this.loc = point;
        this.source_id = source_id;
        this.setVisible(1);
        marker.sm = this;
        if (source_id !== 0) {
            GEvent.addListener(this.marker,"click",function() { return this.sm.popup(); });
        }
    },
    popup: function () {
        var failure_blurb = '<div>An error occurred loading source info :(</div>';
        var l = window.location;
        var url = l.protocol + '//' + l.host + '/a/sp/' + this.source_id + '/';
        var marker = this.marker;
        var req = new Request.HTML({
            url: url,
            method: 'get',
            onSuccess: function(rt,re,rh,rjs) {
                marker.openInfoWindowHtml(rh);
            },
            onFailure: function(rt,re,rh,rjs) {
                marker.openInfoWindowHtml(failure_blurb);
            }
        }).send();
        return true;
    },
    setVisible: function (visible) {
        if (!visible && this.visible) {
            this.map.removeOverlay(this.marker);
        }
        if (visible && !this.visible) {
            this.map.addOverlay(this.marker);
        }
        this.visible = visible;
    }

});

function make_icon(path,name) {
    var icon = new GIcon();
    icon.image = path;
    icon.iconSize = new GSize(77,25);
    icon.iconAnchor = new GPoint(8, 24);
    icon.infoWindowAnchor = new GPoint(10, 1);
    icon.name = name;
    return icon;
}

function update_map() {
    var l = window.location;
    var url = l.protocol + '//' + l.host + '/a/map/';

    var req = new Request.JSON({
        url: url,
        method: 'post',
        urlEncode: false,
        headers: {"X-Content-Type": "application/json"},
        onSuccess: handle_map_json,
        onFailure: handle_map_failure
    }).send(JSON.encode({
        center: map.getCenter(), 
        zoom: map.getZoom(),
        source_type: $('source_type').value,
        day: $('day').value
    }));

    original_center = map.getCenter();
}

function handle_map_json(obj,text) {
    var sources = JSON.decode(text);
    $('results_list').empty();
    var new_items = {};
    sources.each(function(item,index) {
        new_items[item.id] = 1;
        if (!map_items[item.id]) {
           map_items[item.id] = new elSourceMarker(
               map,
               item.point[0],
               item.point[1], 
               source_icons[item.type-1], 
               item.id
           ); 
        }
        else {
            map_items[item.id].setVisible(1);
        }
        if (!$('type_'+item.type)) {
            var header = new Element(
                'h2',
                {id: 'type_' + item.type}
            ).appendText(source_icons[item.type-1].name);

            header.inject($('results_list'));
            var ul = new Element('ul',{ id: 'sources_' + item.type });
            ul.inject($('results_list'));
        }
        var link = new Element('a', {
            href: item.uri,
            events: {
                click: function() {
                    map_items[item.id].popup(); return false;
                }
            }
        }).appendText(item.name);
        var list_item = new Element('li');
        $('sources_' + item.type).grab(
            list_item.grab(link).appendText(
                ' - ' + item.distance + ' km'
            )
        );
    });
    for (var i in map_items) {
        if (!new_items[i]) {
            map_items[i].setVisible(0);
        }
    }
}

function handle_map_failure(xhr) {
    var none = new Element('p').appendText(
        "Nothing near the map.  Try zooming out, or moving the center of the map."
    );

    $('results_list').empty().grab(none);
    


}

var map;
var yourhome = new GIcon();
yourhome.image = "/images/icons/yourhome.png";
//icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
yourhome.iconSize = new GSize(77, 25);
//icon.shadowSize = new GSize(22, 20);
yourhome.iconAnchor = new GPoint(8, 24);
yourhome.infoWindowAnchor = new GPoint(10, 1);

var source_icons = []
var map_items = {};

source_icons[0] = make_icon("/images/icons/market.png","Farmers' Markets");
source_icons[1] = make_icon("/images/icons/retailer.png","Retailers");
source_icons[2] = make_icon("/images/icons/restaurant.png","Restaurants");
source_icons[4] = make_icon("/images/icons/farm.png","Farms");


