var map;
var markers = [];
var descriptions = [];
var places = [];
var baseIcon = new GIcon();
baseIcon.shadow = "";
baseIcon.iconSize = new GSize(26, 31);
baseIcon.iconAnchor = new GPoint(13, 31);
baseIcon.infoWindowAnchor = new GPoint(19, 15);
baseIcon.infoShadowAnchor = new GPoint(18, 25);
$(document).ready(function(){

	//$('.help').show(); 
	
	/*
	  $("#state").ajaxError(function(event, xhr, opts, ex){
		alert(ex.message);
	  });
	*/
	  if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(40, -95), 3);
		map.addControl(new GLargeMapControl());
	  }
	  $("select#state").change(function() {
		changeState($(this).val());
	  });
	  $("#breakfast, #lunch, #dinner, #outdoors").click(function() {
		  $.getJSON("/places/state/" + $("select#state").val() + "/" + document.getElementById("breakfast").checked + "/" + document.getElementById("lunch").checked + "/" + document.getElementById("dinner").checked + "/" + document.getElementById("outdoors").checked, function(json){
		  loadMapJSON(json);
		});
	  });
});

$(document).unload(function(){
    GUnload();
});

function changeState(stateName) {  
  /*$.getJSON("/places/center/" + stateName, function(center){
    map.setCenter(new GLatLng(parseFloat(center.State.lat), parseFloat(center.State.lon)), parseInt(center.State.zoom));
  });*/
  var state_to_view = stateName;
  if(!stateName){
  	state_to_view = $("select#state").val();
  }
  $('.help').hide();
  $('#postit_message').hide();
  $.getJSON("/places/state/" + state_to_view + "/" + document.getElementById("breakfast").checked + "/" + document.getElementById("lunch").checked + "/" + document.getElementById("dinner").checked + "/" + document.getElementById("outdoors").checked, function(json){
    loadMapJSON(json);
	var zoom = map.getBoundsZoomLevel(bounds);
    map.setCenter(bounds.getCenter(), zoom);
  });
}

function getPlaceType(place) {
    if((place.breakfast === "1") || (place.lunch === "1") || (place.dinner === "1")) {
	 return "restaurant";
     } else { 
	 return "outdoors"; 
     }
}

function normalizeLatLng(lat, lng) {
    degrees_lat = Math.floor(Math.abs(lat)) 
    minutes_lat = (60 * (lat - Math.floor(lat))).toFixed(3) 
    degrees_lng = Math.floor(Math.abs(lng)) 
    minutes_lng = (60 * (lng - Math.floor(lng))).toFixed(3)

    return {"lat":{"degrees":degrees_lat, "minutes":minutes_lat}, "lng":{"degrees":degrees_lng, "minutes":minutes_lng}}
}

function createHtmlForInfoWindow(place) {
    if(!(!!place.id && !!place.name)) return ""; //shortcircuit if no name or id

    var html = '<div class="infoWindowContent">' +
               '<a class="infoWindowImage" href="#" onclick="window.open(\'/places/photo/' + place.id + '/photo.jpg\', \'\', \'width=605,height=605\'); return false;">' +
               '  <img src="/places/thumb/' + place.id + '/thumb.jpg" alt="" />' +
               '</a>' +
	   			'<span class="infoWindowTitle">' + place.name + '</span><br />';	   

    html += '<p class="infoWindowSavePlace"><a href="/places/add/'+ place.id + '" onclick="$.get(\'/places/add/'+ place.id +'\', null, function(data, textStatus) {$(\'#messages\').html(\'Successfully added.  You have \'+ data +\' <a href=\\\'/places/saved\\\'>saved place(s)</a>.\');$(\'#message_container\').show();});return false;">[save place]</a></p>';

    html += '<p class="infoWindowLinkToPlace"><a href="/places/view/' + place.id + '">[view details]</a></p>';

    latlng = normalizeLatLng(place.lat, place.lon);

    html +=   '<p class="infoWindowLatLon">' +
              ' N ' + latlng.lat.degrees + '&deg; ' + latlng.lat.minutes +
              ' W ' + latlng.lng.degrees + '&deg; ' + latlng.lng.minutes +
              '</p>';

    if (place.city && place.state && place.zip) {
      html +=   '<p class="infoWindowAddress">';

      if (place.address) {
        html +=   place.address + '<br />';
      }

      html +=   place.city + ', ' + place.state + ' ' + place.zip;

      html +=   '</p>';
    }
    if (place.description) {
      html +=   '<p class="infoWindowDescription"><strong>';
      
      if(place.breakfast > 0 || place.lunch > 0 || place.dinner > 0){
        var serves = new Array();
		if(place.breakfast > 0){
		  serves.push('Breakfast');
		}
		if(place.lunch > 0){
		  serves.push('Lunch');
		}
		if(place.dinner > 0){
		  serves.push('Dinner');
		}
		var count = serves.length;
		for(var i =0; i< count; i++){
		  html += serves[i];
		  if(i != (count - 1)){
		    // we know there's at least one more, so print a comma
		    html += ", ";
			}
          }
        html += '<br />';
        };

      
      
       html += '</strong>' + place.description + '</p>';
    }
    html +=    '</div><div style="clear: both;">&nbsp;</div>';

    return html;
}

function loadMapJSON(places) {
  markers = [];
  descriptions = [];
  map.clearOverlays();
  bounds = new GLatLngBounds();

  $("#resultsList").empty();
  for (i=0; i < places.length; i++) {
    var lat = parseFloat(places[i].Place.lat);
    var lng = parseFloat(places[i].Place.lon);
    var point = new GLatLng(lat,lng);
	bounds.extend(point);
	var title = places[i].Place.name;
    var html = createHtmlForInfoWindow(places[i].Place);
    var type = getPlaceType(places[i].Place);
    var marker = createMarker(point, title, html, type);
    map.addOverlay(marker);
    markers.push(marker);
    descriptions.push(html);
    createListResult(i, title);
  }
  $("#resultsList li").hover(function(){
    $(this).addClass("result_hvr");
  },function(){
    $(this).removeClass("result_hvr");
  });
}

function createListResult(i, title) {
    listResultLink = document.createElement("a");
    listResultLink.appendChild(document.createTextNode(title));
    $(listResultLink).attr("href", "#top");
    $(listResultLink).attr("id", "result" + i);
    $(listResultLink).click(function(){
      activeMarker = this.id.replace("result", "");
      markers[activeMarker].openInfoWindowHtml(descriptions[activeMarker]);
      $("#resultsList li").removeClass("selected");
      $(this).parent("li").addClass("selected");
      return false;
    });
    listResult = document.createElement("li");
    if (i % 2) {
      $(listResult).attr("class", "even");
    }
    listResult.appendChild(listResultLink);
    $("#resultsList").append(listResult);
}

function createMarker(point, title, html, type) {
  var markerOpts = {};
  var icon = new GIcon(baseIcon);
  icon.image = "http://10speedtraveler.com/img/icons/" + type + ".png";
  markerOpts.icon = icon;
  markerOpts.title = title;
  var marker = new GMarker(point, markerOpts);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
  });
  return marker;
}

