// declare globals
var map;
var radar = $('<img />').attr('src', 'images/radar.gif');

function goHome() {
  $('#mainAreaId').load('map.php', function() {
    initialize(39.571822, -95.712891, 4);
  });
}

$(document).ready(function() {
  $('#addressInput').example("Enter any location in the world! (ex: 'san francisco', 'mexico', 'york, pa', 'dublin', etc)");
  goHome();
});

function createMarker(point, content, type) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(content);
  });
  return marker;
}

function getChurches(map) {
  map.clearOverlays();
  var zoom = map.getZoom();
  if (zoom < 11) {
    $("#numberChurches").html("");
    $("#zoomStatus").html("Zoom in more to see Churches!");
    map.clearOverlays();
    return 0;
  } 
  $("#zoomStatus").html("");
  $("#numberChurches").html("Number of Churches on map: ");
  $("#numberChurches").append(radar);
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var north = northEast.lat();
  var south = southWest.lat();
  var east = northEast.lng();
  var west = southWest.lng();
  var url = "phpsqlGenxml.php?north=" + north + "&south=" + south + "&east=" + east + "&west=" + west;
  GDownloadUrl(url, function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var website = markers[i].getAttribute("website");
      if (website.length > 0) {
        website = "<a href='" + website + "'>" + website + "</a>";
      }
      var MasstimeWeekend = markers[i].getAttribute("sun");
      var MasstimeWeekday = markers[i].getAttribute("week");
      if (MasstimeWeekend.length < 1) { MasstimeWeekend = "None in database"; }
      if (MasstimeWeekday.length < 1) { MasstimeWeekday = "None in database"; }
      var content = "<a style='float: left; font-weight: bold;'>" + markers[i].getAttribute("name") + "</a>";
      content += "<a style='float: right;'><b>Diocese: </b>" + markers[i].getAttribute("dio") + "&nbsp;&nbsp;&nbsp;</a><br />";
      content += markers[i].getAttribute("address") + "<br />\n";
      content += markers[i].getAttribute("city") + ", " + markers[i].getAttribute("st") + " "  + markers[i].getAttribute("zip") + "<br />\n";
      content += markers[i].getAttribute("phone") + "<br />\n";
      content += website  + "<br />\n";
      content += "<b>Weekend Mass:</b><br />" + MasstimeWeekend + "<br />\n";
      content += "<b>Weekday Mass:</b><br />" + MasstimeWeekday + "<br />\n";
      if (markers[i].getAttribute("hday").length > 0) {
        content += "<b>Holyday Mass:</b><br />" + markers[i].getAttribute("hday") + "<br />\n";
      }
      if (markers[i].getAttribute("con").length > 0 ) { 
        content += "<b>Confessions:</b><br />" + markers[i].getAttribute("con") + "<br />\n";
      }
      if (markers[i].getAttribute("ado") !== undefined) {
        content += "<b>Adoration:</b><br />" + markers[i].getAttribute("ado") + "<br />\n";
      }
      if (markers[i].getAttribute("dev") !== "") {
        content += "<b>Devotions:</b><br />" + markers[i].getAttribute("dev")  + "<br />\n";
      }
      content += "<br /><b>Last Update:</b> &nbsp;" + markers[i].getAttribute("Udate");
      if (markers[i].getAttribute("dir") !== "") {
        content += "<br /><br /><b>Directions: </b>" + markers[i].getAttribute("dir");
      }
      var type = markers[i].getAttribute("type");
      var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                              parseFloat(markers[i].getAttribute("lng")));
      var marker = createMarker(point, content, type);
        map.addOverlay(marker);
    }
    var totalRows = markers.length;
    if (totalRows == 100) { 
      totalRows = totalRows + "<a style='color: red;'> Maximum number of Churches shown!</a>";
    }
    $("#numberChurches").html("Number of Churches on map: " + totalRows);
  });
}

function initialize(centerLat, centerLng, zoomStart) {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    if (centerLat === undefined) {
      centerLat = 41.5056;
    }
    if (centerLng === undefined) {
      centerLng = -81.6511;
    }
    
    map.setCenter(new GLatLng(centerLat, centerLng), zoomStart);
    geocoder = new GClientGeocoder();
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GScaleControl());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    getChurches(map);
    // repopulate the map when stuff moves
    GEvent.addListener(map, "dragend", function () {
	getChurches(map);
    });
    GEvent.addListener(map, "zoomend", function () {
	getChurches(map);
    });
  }
}

function showAddress(address) {
  if (geocoder == undefined) {
    return 0; 
  }
  geocoder.getLocations(address, function(response) { 
    map = new GMap2(document.getElementById("map_canvas"));
    if (!response || response.Status.code != 200) {
      alert("Sorry, we were unable to geocode that address");
    } else {
      var tabAccuracy = [2,4,6,10,12,13,16,16,17];
      place = response.Placemark[0];
      accuracy = place.AddressDetails.Accuracy;
      point = new GLatLng(place.Point.coordinates[1],
                          place.Point.coordinates[0]);
      marker = new GMarker(point);
      map.addOverlay(marker);
      marker.openInfoWindowHtml(place.address + '<br>' + '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
      map.setCenter(point, tabAccuracy[accuracy]);
      geocoder = new GClientGeocoder();
      map.addControl(new GLargeMapControl3D());
      map.addControl(new GScaleControl());
      map.addControl(new GMapTypeControl());
      map.enableScrollWheelZoom();
      getChurches(map);
      // repopulate the map when stuff moves
      GEvent.addListener(map, "dragend", function () {
        getChurches(map);
      });
      GEvent.addListener(map, "zoomend", function () {
        getChurches(map);
      });
    }	
  });
}
