var label_church = 'Church';
var label_masses = 'Masses';

$(document).ready (function () {
  $("div#timetable").data ("language", location.pathname.split ("/")[1]);
  if (GBrowserIsCompatible()) {
    wdm_init ();
  }
});

function xlate (key, params, callback) {
  var language = $("div#timetable").data ("language");
  params.key = key;
  params.language = language;
  $.get ("/" + language + "/data/xlate", params, callback);
}

function wdm_day_of_week () {
  return $("table#control-bar td.selected").attr ("id");
}

function wdm_relocate (map, lat, lon, zoom) {
  if (!zoom) {
    zoom = map.isLoaded () ? map.getZoom () : 14;
  }
  if (lat && lon) {
    map.setCenter (new GLatLng (lat, lon), zoom);
    $("input#location").val ("");
  } else {
    var geocoder = new GClientGeocoder ();
    geocoder.setBaseCountryCode("UK");
    var location = $("input#location").val () || "London";
    geocoder.getLatLng (location, function (point) {
      if (!point) {
        $.getJSON ("/en/search/map_search/", {"terms" : $("input#location").val ()}, function (data) {
          $.each (data, function (name, coords) {
            alert (name);
            alert (coords);
          });
        });
        $("input#location").val ("'" + location + "' not recognised");
      } else {
        map.setCenter (point, zoom);
      }
    });
  }
}

function wdm_draw_times () {
  var highlighted_church_id = $("div#timetable").data ("highlighted-church");

  $("div#timetable").empty ();
  var masstimes = $("div#timetable").data ("masstimes")[wdm_day_of_week ()];
  if (!masstimes) {
    return;
  }
  var hh24s = [];
  $.each (masstimes, function (k, v) {
    hh24s.push (k);
  });
  hh24s.sort ();

  var html = [];
  $.each (hh24s, function () {
    var d = masstimes[this];
    var hh12 = d[0];
    var churches = d[1];
    html.push ('<div id="' + this + '" class="timecode"><h2>' + hh12 + '</h2><table class="times" cellspacing="0">');
    for (c = 0; c < churches.length; c++) {
      var church = churches[c];
      html.push ('<tr><td class="church-id">' + church.id + '</td><td class="restrictions">' + church.restrictions + '</td><td class="church_name">' + church.name + '</td></tr>');
    }
    html.push ('</table></div>');
  });
  $("div#timetable").html (html.join (""));

  $("table.times tr").each (function () {
    if (highlighted_church_id == $(this).children ("td.church-id").text ()) {
      $(this).addClass ("highlighted");
    }
  });
}

function highlight_church (church_id, map) {
  data = $("div#timetable").data ("highlighted-church");
  if (data == church_id) {
    $("div#timetable").data ("highlighted-church", "");
  } else {
    $("div#timetable").data ("highlighted-church", church_id);
  }
  $("div.timecode tr").each (function () {
    if ($(this).children ("td.church-id").html () == church_id) {
      $(this).toggleClass ("highlighted");
    } else {
      $(this).removeClass ("highlighted");
    }
  });
  wdm_draw_markers (map);
}

function handle_timetable_click (event, map) {
  if ($(event.target).is ("td")) {
    var parent = $(event.target).parent ("tr");
    if (parent != undefined) {
      var church_id = $(parent).children ("td.church-id").html ();
      highlight_church (church_id, map);
    }
  }
  return false;
}

function handle_days_click (event, map) {
  $("table#control-bar td.selected").removeClass ("selected");
  $(event.target).addClass ("selected");
  wdm_draw_markers (map);
  wdm_draw_times ();
  wdm_reset_text_view (map);
  return false;
}

function wdm_draw_markers (map) {
  var marker_size = 32;
  var normal_icon = MapIconMaker.createMarkerIcon ({width:marker_size, height:marker_size, primaryColor:"#ff0000"});
  var highlit_icon = MapIconMaker.createMarkerIcon ({width:marker_size, height:marker_size, primaryColor:"#ffff00"});
  var external_icon = MapIconMaker.createMarkerIcon ({width:marker_size, height:marker_size, primaryColor:"#0000ff"});
  map.clearOverlays ();
  var bounds = map.getBounds ();
  var day = wdm_day_of_week ();

  var highlighted_church_id = $("div#timetable").data ("highlighted-church");

  //
  // For each church in the list of churches attached to
  // the right-hand timetable panel, find its lat/long
  // and plot a corresponding marker whose info text corresponds
  // to the church's name [and later to its HTML info]
  //
  $.each ($("div#timetable").data ("churches"), function (church) {
    var latitude = parseFloat (this.latitude);
    var longitude = parseFloat (this.longitude);
    var point = new GLatLng (latitude, longitude);
    var church_id = this.id;
    var church_postcode = this.postcode;
    var name = this.name;
    if (bounds.contains (point) === true)
    {
      var is_external = (this.is_external == 'Y');
      if (this.id == highlighted_church_id) {
        var icon = highlit_icon;
      } else {
        if (is_external) {
          var icon = external_icon;
          var website = this.website;
        } else {
          var icon = normal_icon;
          var website = undefined;
        }
      }
      var marker = new GMarker (point, {title : this.name, icon : icon, draggable : false});
      var tab1 = new GInfoWindowTab (label_church, this.html1);
      var tab2 = new GInfoWindowTab (label_masses, this.html2);
      GEvent.addListener (marker, "click", function () {
        if (is_external) {
          window.open ('http://' + website);
        } else {
          marker.openInfoWindowTabsHtml ([tab1, tab2], {maxWidth : 320});
        }
      });
      GEvent.addListener (marker, "dragend", function () {
        $.post ("/en/contact/send", {
          name : "Maps Update",
          email : "maps@weekdaymasses.org.uk",
          message : "Church " + name + " (" + church_id + " - " + church_postcode + ") is now at " + marker.getLatLng ().toUrlValue ()
          },
          function (html) {
            alert ("Details sent");
          }
        );
      });
      map.addOverlay (marker);
    }
  });
}

function wdm_get_data (map) {
  var language = $("div#timetable").data ("language");
  var bounds = map.getBounds ();
  var sw = bounds.getSouthWest ();
  var ne = bounds.getNorthEast ();
  var threshold = $("input#threshold").val ();
  var coords = {
   lat0 : sw.lat (), long0 : sw.lng (),
   lat1 : ne.lat (), long1 : ne.lng (),
   threshold : $("input#threshold").val ()
  };
  xlate ("map_fetching_data", {}, function (data) {
    $("p#status").attr ("class", "").addClass ("warning").html (data);
  });
  $.getJSON (
    "/" + language + "/data/churches",
    coords,
    function (data) {
      var churches = data[0];
      var masstimes = data[1];
      var n_churches = data[2];
      var area = data[3];
      $("div#timetable").data ("churches", churches);
      $("div#timetable").data ("masstimes", masstimes);
      $("div#timetable").data ("area", area);
      if (n_churches > threshold) {
        xlate ("map_threshold_exceeded", {"n_churches" : n_churches, "threshold" : threshold}, function (data) {
          $("p#status").attr ("class", "").addClass ("warning").html (data);
        });
      } else {
        $("p#status").attr ("class", "").addClass ("info");
        if (n_churches === 0) {
          xlate ("map_no_churches_found", {}, function (data) {
            $("p#status").attr ("class", "").addClass ("warning").html (data);
          });
        } else {
          xlate ("map_n_churches_found", {"n_churches" : n_churches}, function (data) {
            $("p#status").attr ("class", "").addClass ("warning").html (data);
          });
        }
      }
      wdm_reset_text_view ();
      wdm_draw_markers (map);
      wdm_draw_times ();
    }
  );
}

function wdm_reset_text_view () {
  var area = $("div#timetable").data ("area");
  var area_code = (area ? area[0] : "");
  var area_name = (area ? area[1] : "");
  if (area_code) {
    var params = {
      "area" : area_name,
      "day" : wdm_day_of_week (),
      "area_code" : area_code
    };
    xlate ("map_switch_to_text", params, function (data) {
      $("p#text-view").html (data);
    });
  } else {
    $("p#text-view").html ("");
  }
}

function wdm_init () {
  $("div#timetable").data ("language", location.pathname.split ("/")[1]);
  xlate ("label_church", {}, function (data) {
    label_church = data;
  });
  xlate ("label_masses", {}, function (data) {
    label_masses = data;
  });
  var map = new GMap2(document.getElementById("map"));
  map.enableScrollWheelZoom ();
  map.addControl (new GSmallMapControl ());
  //~ map.addControl (new GScaleControl ());
  GEvent.addListener (map, "moveend", function () {
    //
    // Avoid a redraw if the window has moved only because
    // of an open info window which has pushed it off the edge.
    //
    var info_window = map.getInfoWindow ();
    if (info_window.isHidden ()) {
      wdm_get_data (map);
    }
    var centre = map.getCenter ();
    var query = "" + $.query.set ("lat", centre.lat ()).set ("lon", centre.lng ()).set ("zoom", map.getZoom ());
    $("a#permalink").attr ("href", location.pathname + query.toString ());
    wdm_reset_text_view (map);
  });
  $("input#submit").click (function () {
    wdm_relocate (map);
    return false;
  });

  $("div#timetable").click (function (event) {
    handle_timetable_click (event, map);
  });
  $("td.day").click (function (event) {
    handle_days_click (event, map);
  });
  $("a#get-help").click (function (event) {
    if ($("div#help").css ("display") == "none") {
      $("div#timetable").hide ();
      $("div#help").show ();
      xlate ("map_links_hide_help", {}, function (data) {
        $("a#get-help").text (data);
      });
    } else {
      $("div#help").hide ();
      $("div#timetable").show ();
      xlate ("map_links_help", {}, function (data) {
        $("a#get-help").text (data);
      });
    }
  });

  var lat0 = $.query.get ("lat0");
  var lat1 = $.query.get ("lat1");
  var lon0 = $.query.get ("lon0");
  var lon1 = $.query.get ("lon1");
  if (lat0 && lat1 && lon0 && lon1) {
    var bounds = new GLatLngBounds (new GLatLng (lat0, lon0), new GLatLng (lat1, lon1));
    var centre = bounds.getCenter ();
    var lat = centre.lat ();
    var lon = centre.lng ();
    var zoom = map.getCurrentMapType ().getBoundsZoomLevel (bounds, map.getSize ());
  } else {
    var lat = $.query.get ("lat");
    var lon = $.query.get ("lon");
    var zoom = $.query.get ("zoom");
  }
  var threshold = $.query.get ("threshold");
  if (threshold) {
    $("input#threshold").val (threshold);
  }
  var day_of_week = $.query.get ("day");
  if (!day_of_week) {
    day_of_week = "K";
  }
  $("td.day").removeClass ("selected");
  $("td#"+ day_of_week).addClass ("selected");

  wdm_relocate (map, lat, lon, zoom);

  var church_id = $.query.get ("church_id");
  if (church_id) {
    highlight_church (church_id, map);
  }

}

$(document.body).unload (function () {
  if (GBrowserIsCompatible ()) {
    GUnload ();
  }
});
