$(document).bind("mapFormLoaded", null, function() {
  initMaps()

  $("#map-form").unbind().submit(function () {
    findLocalPlaces();
    return false
  })
});

var map;
var geocoder;

function initMaps() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("screen"));
    map.addMapType(G_PHYSICAL_MAP);
    map.setCenter(new GLatLng(38, -100), 3, G_NORMAL_MAP);
    map.setUIToDefault();
    geocoder = new GClientGeocoder()
  }
}

function findLocalPlaces() {
  hideError();
  map.clearOverlays();

  zip = $("#zipcode").val();
  // if it's a valid zipcode
  if (/\d{5}([\-]\d{4})?/.test(zip)) {
    // extract zip from string and match only first zip found
    zip = zip.match(/\d{5}([\-]\d{4})?/g).toString().substring(0, 5);

    $.ajax({
      type: "GET",
      url: "/ajax/zipcode/" + zip,
      dataType: "json",
      success: function(json) {
        lat = json.latitude;
        lng = json.longitude;
        loc = new GLatLng(lat, lng);
        map.setCenter(loc, 11, G_NORMAL_MAP);

        //getting locations in the area by lat lng
        getByLatLng(lat, lng);
      }
    })
  } else if (/^[A-Za-z. '-]+([,])?[ ]{1}[a-zA-Z]{2}$/.test(zip)) {
    geocoder.getLatLng(zip, function(point) {
      if (!point) {
        showError();
      } else {
        //getting locations in the area by lat lng
        getByLatLng(point.lat(), point.lng());
      }
    })
  } else {
    showError()
  }
}

function showError() {
  $("#zipcode").css({
    "backgroundColor": "#c00"
  })
}

function hideError() {
  $("#zipcode").css({
    "backgroundColor": "#fff"
  })
}

function addDataToMap(places) {
  var locations = new Array();

  $(places).each(function() {
    var details = "<div class='name'>" + this["site_name"] + "</div>";
  
    var address = "";
    if (this["street"] || this["city"] || this["state"] || this["zip"] || this["phone"]) {
      details += "<div class='address'>";
      if (this["street"].replace(/^\s+|\s+$/g,"")) {
        details += this["street"] + "<br />";
        address += this["street"] + ", ";
      }
      if (this["city"].replace(/^\s+|\s+$/g,"")) {
        details += this["city"] + ", ";
        address += this["city"] + ", ";
      }
      if (this["state"].replace(/^\s+|\s+$/g,"")) {
        details += this["state"] + " ";
        address += this["state"] + " ";
      }
      if (this["zip"].replace(/^\s+|\s+$/g,"")) {
        details += this["zip"];
        address += this["zip"];
      }
      if (this["phone"].replace(/^\s+|\s+$/g,"")) {
        details += "<br />" + this["phone"];
      }
      details += "</div>";
    }

    details += "<div class='activities'>";
    if (this["forest"] == 1) details += "<div class='forest'></div>";
    if (this["water"] == 1)  details += "<div class='water'></div>";
    if (this["walk"] == 1)   details += "<div class='hike'></div>";
    if (this["bike"] == 1)   details += "<div class='bike'></div>";
    if (this["fish"] == 1)   details += "<div class='fish'></div>";
    if (this["camp"] == 1)   details += "<div class='camp'></div>";
    details += "</div>";
    
    details += "<div class='tools'>";
    if (this["hasEvents"]) {
      details += "<a href='/ajax/dialog/events?id=" + this["nf_id"] + "' onclick='return loadDetails(this)' class='events'>Events</a> / ";
    }
    details += "<a href='/ajax/dialog/place?id=" + this["id"] + "' onclick='return loadDetails(this)' class='place'>Details</a> / ";
    details += "<a href='http://maps.google.com/maps?daddr=" + encodeURIComponent(address) + "' class='directions' target='_blank'>Get Directions</a>";
    details += "</div>";

    var bubble = "<div class='bubble'>" + details + "</div>";

    loc = new GLatLng(this["latitude"], this["longitude"]);
    locations.push(loc);

    var marker = new GMarker(loc);
    marker.bindInfoWindow(bubble);
  
    map.addOverlay(marker);
  });

  return locations
}

function getByLatLng(lat, lng) {
  $(".message").html("<img src='/images/ajax-loader.gif' alt='Searching...' /> Searching...");

  $.ajax({
    type: "POST",
    url: "/ajax/places/locations",
    dataType: "json",
    data: {
      "lat": lat,
      "lng": + lng,
      "range": $("#range").val()
    },
    success: function(json) {
      $(".message").html("Total locations: " + json.locations.length).show();

      seconds = 0;
      var timer = setInterval(function () {
        seconds++;
        if (seconds < 5) {
          clearInterval(timer);
          $(".message").fadeOut("normal", function() {
            $(this).html("")
          })
        }
      }, 1000);

      var locations = new Array();
      var places = new Array();
      $.each(json.locations, function(index, place) {
        places.push(place)
      });

      var locations = addDataToMap(places);

      zoomToFit(map, locations);
    }
  })
}

function zoomToFit(map, points) {
  if (points.length == 0) {
    return false
  }
  var bounds = new GLatLngBounds();
  for (var i=0; i< points.length; i++) {
    bounds.extend(points[i])
  }
  map.setZoom(map.getBoundsZoomLevel(bounds));
  map.setCenter(bounds.getCenter())
}

function loadDetails(C) {
  $.IEevent(function () {
    buildDialogs(C, null, true, {})
  });
  return false
}
