// our map!
var map;

function searchcallback(results) {
  // we don't actually want to show any results on the map
  results.each(function(result){
    result.marker.remove();
  });
}

function init_poem_map(lat, lon, zoom, map_name) {
  var o_lat = lat
  var o_lon = lon;
  var o_zoom = zoom;
  
  // may need to move to the last position they were in
  var last_pos = window.cookie_man.get('map_pos_'+map_name);
  if (last_pos) {
    last_pos = last_pos.evalJSON();
    if (last_pos.orig.lat == lat && last_pos.orig.lon == lon && last_pos.orig.zoom == zoom) {
      lat = last_pos.save.lat;
      lon = last_pos.save.lon;
      zoom = last_pos.save.zoom;
    }
  }
  
  Event.observe(document, 'dom:loaded', function() {
    if (GBrowserIsCompatible()) {
      // create our map within the given element
      map = new GMap2($('world-map'));
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());

      // add the search control
      var ls = new google.maps.LocalSearch(
          {
            resultList : $('deadlist')
          , suppressInitialResultSelection : true
          , onMarkersSetCallback : searchcallback
          });
      map.addControl(ls, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,40)));

      // start with the map in the desired location (todo: make this cms editable)
      map.setCenter(new GLatLng(lat, lon), zoom);
      
      // need to know about the map being moved
      GEvent.addListener(map, "moveend", function() {
        map_move(o_lat, o_lon, o_zoom, map.getCenter().lat(), map.getCenter().lng(), map.getZoom(), map_name);
      });
    }

    // want clicking checkboxes to trigger off the search too
    $$('.pt_cb').each(function(elm){
      var cb = elm.down('input');
      Event.observe(cb, 'click', single_change);
    });

  	// deal with the select all/none button
  	if ($('all-kps'))
      Event.observe('all-kps', 'click', master_change);

    // run the standard search as soon as the page loads
    run_search();
  });  
}

function map_move(orig_lat, orig_lon, orig_zoom, lat, lon, zoom, map_name) {
  var pos = {
      orig : {lat:orig_lat, lon:orig_lon, zoom:orig_zoom}
    , save : {lat:lat, lon:lon, zoom:zoom}
  };
  var pos_str = Object.toJSON(pos).gsub(' ', '');
  // just save the final map position
  window.cookie_man.set('map_pos_'+map_name, pos_str);
}

function run_search() {
  // primitive counting system to to ensure that we don't show delayed requests
  $('req_id').value = parseInt($('req_id').value) + 1;

  var frm = $('poem_search');
  var params = Form.serialize(frm);

  // do the async submit
  var request = new Ajax.Request(frm.action,
  {
    asynchronous  : true, 
    parameters    : params, 
    onSuccess     : function(t) { window['poem_search_onSuccess'](t, frm); },
    onFailure     : function(t) { window['poem_search_onFailure'](t, frm); }
  });
}

var last_req_id = 0;
function poem_search_onSuccess(t){
  var result = t.responseJSON;
  
  // only show newer request responses
  if (result.req_id > last_req_id) {
    last_req_id = result.req_id;
    // clear out the old poems first
    map.clearOverlays();

    // now add all the new ones in
    result.poems.each(function(poem){
      add_poem(poem, result.map_type);
    });
  }
}

var gp_html_template = new Template([
    '<div class="gmap-poem">'
  , '  <div style="float:left;width:220px;height:175px;background:url(\'#{image_url}\') 0 0 no-repeat;overflow:hidden;"><a href="#{link}" style="width:230px;height:175px;display:block;"></a></div>'
  , '  <div style="float:left;margin-left:5px;">'
  , '  <h2><a href="/poems/#{id}" class="glink" title="#{title}">#{title}</a></h2>'
  , '  <p class="who"><a href="/poems/uploaded_by/#{uploader_id}" class="glink" title="#{title}"><strong>#{uploader_name}</strong></a></p>'
  , '  <p class="when">#{created_at}</p>'
  , '  <div class="view-and-share"><a href="#{link}" title="View Poem">&raquo; View poem and share</a></div>'
  , '  </div>'
  , '</div>'
].join(''));

var gp_mini_template = new Template([
    '<div class="gmap-poem">'
  , '  <div style="float:left;width:100px;height:75px;background:url(\'#{image_mini_url}\') 0 0 no-repeat;overflow:hidden;"><a href="#{link}" style="width:100px;height:75px;display:block;"></a></div>'
  , '  <div style="float:left;margin-left:5px;">'
  , '  <h2><a href="/poems/#{id}" class="glink" title="#{title}">#{title}</a></h2>'
  , '  <p class="who"><a href="/poems/uploaded_by/#{uploader_id}" class="glink" title="#{title}"><strong>#{uploader_name}</strong></a><br /></p>'
  , '  <p class="when">#{created_at}<br/></p>'
  , '  <p class="view-and-share"><a href="#{link}" title="View Poem">&raquo; View poem and share</a></p></div><div class="clear"></div>'
  , '</div>'
].join(''));

function add_poem(poem, map_type){
  // put a marker in the center
  var latlon = new GLatLng(poem.lat, poem.lon);
  
  // Create our custom marker icon
  var icon = new GIcon(G_DEFAULT_ICON);
  icon.image = '/img/icons/map_marker.png';

  var marker = new GMarker(latlon, {icon:icon});
  map.addOverlay(marker);
  
  GEvent.addListener(marker, "click", function() {
    // if (map_type == 'tall')
    //   var html = gp_html_template.evaluate(poem);
    // else
      var html = gp_mini_template.evaluate(poem);
    marker.openInfoWindowHtml(html);
  });

}




// Stuff for the search controls (keyphrases only?) - todo: build these


function single_change() {
	// check to make sure the master control is in the right position
	var master_checked = true;
  $$('.pt_cb').each(function(elm){
    var cb = elm.down('input');
		if (!cb.checked)
			master_checked = false;
  });

	// may need to flick the master control
	if (master_checked != $('all-kps').checked)
		$('all-kps').checked = master_checked;
	
	// run a new search
	run_search();
}

function master_change() {
	var dirty = false;
	var master_checked = $('all-kps').checked;
	
	// update any single controls to match the master
  $$('.pt_cb').each(function(elm){
    var cb = elm.down('input');
		if (cb.checked != master_checked) {
			cb.checked = master_checked;
			dirty = true;
		}
  });

	// run a new search if any single controls changed
	if (dirty)
		run_search();
}

