var centerOfUSC = new GLatLng(34.021844, -118.286018);
var HOUSE_IMAGE = "images/home.png";
var map;
var directions;
var homeAddr="";
var homeMarker;
var placeData;
var currentplace;
var currentdist;
var bounds = new GLatLngBounds();

var houseIcon = new GIcon(G_DEFAULT_ICON);
houseIcon.image = HOUSE_IMAGE;
houseIcon.iconSize = new GSize(32,28);
houseIcon.iconAnchor = new GPoint(16,28);

$(document).ready(function() {
	// Map Setup
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));  
		map.setCenter(centerOfUSC, 10);
		var ctrlPosn = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,15));
		map.addControl(new GMapTypeControl());// pass stdCtrlPosn as 2nd arg to move to lower right
		map.addControl(new GSmallMapControl());
		directions = new GDirections();
		addFuclaOverlay();
	}
	
	// Settings - Home - Cookie
	$("#settings_home_button").click(function(){
		$.cookie('Green Cuisine Home Address', $("#settings_home").val(), { expires: 365 });
	});
	
	var chome = $.cookie('Green Cuisine Home Address');
	if(chome != null && chome != "") {
		$("#settings_home").val(chome)
		plotHome(chome);
	}
});

function addFuclaOverlay() {
  var corner1 = new GLatLng(34.065014, -118.454504);
  var corner2 = new GLatLng(34.078398, -118.434849);
  var ucla_bounds = new GLatLngBounds(corner1, corner2);
  var fucla_image = "images/fucla.png";
  var overlay = new GGroundOverlay(fucla_image,ucla_bounds);
  map.addOverlay(overlay);
}

function updatePlaces(jsonStr) {
  for (i in placeData) {
    placeData[i].removeMarker();
  }
  placeData = eval(jsonStr);
  for (i in placeData) {
    //need all of the following functions to be defined for each place. this is where creating a class called Place or Restaurant would probably have been a better choice...
    placeData[i].addMarker = addMarker;
    placeData[i].showPlaceInfo = showPlaceInfo ;
    placeData[i].setDist = setDist;
    placeData[i].setTime = setTime;
    placeData[i].removeMarker = removeMarker;
    placeData[i].getTravelCost = getTravelCost;
    placeData[i].getTravelCO2 = getTravelCO2;
    placeData[i].getAddress = getAddress;
    //need to actually execute some of them
    if (placeData[i].lat == 0 || placeData[i].lng == 0) //which should never happen, because if it did, it would be eliminated before it got to me. but just in case
    {
      var geocoder = new GClientGeocoder();
      place = placeData[i];
      geocoder.getLatLng(place.getAddress(), function(latLng) {
        place.lat = latLng.lat();
        place.lng = latLng.lng();
      });
    }
    placeData[i].addMarker();
    placeData[i].setDist();
    placeData[i].setTime();
  }
  map.setCenter(bounds.getCenter());
  level = map.getBoundsZoomLevel(bounds);
  map.setZoom(level);
}

function getAddress() {
  return this.address1+", "+this.address2;
}

function getTravelCost() {
  var mpg = document.getElementById("settings_mpg").value;
  var gasCost = document.getElementById("settings_dpg").value;
  return currentdist*gasCost / mpg;
}
function getTravelCO2() {
  var CO2pg = document.getElementById("settings_cpg").value;//how many pounds of CO2 is released per gallon of gas?
  var mpg = document.getElementById("settings_mpg").value;
  return currentdist / mpg * CO2pg;
}

function addMarker() {
  var place = this;
  var address = place.getAddress();
  icon = new GIcon(G_DEFAULT_ICON);
  var cost = place.green.length;
  //icon.image = "images/"+cost+"bucks.png";
  icon.image = "images/dollar"+cost+".png";
  icon.iconSize = new GSize(21, 36);
  icon.iconAnchor = new GPoint(10, 36);
  latLng=new GLatLng(place.lat, place.lng);
  bounds.extend(latLng);
  var newMarker = new GMarker(latLng, icon);
  place.marker = newMarker;
  map.addOverlay(newMarker);
  GEvent.addListener(newMarker, "click", function() {
    place.showPlaceInfo();
    //todo: 'activate' corresponding object in list
  });
}

function removeMarker() {
  map.removeOverlay(this.marker);
}
function showPlaceInfo() {
  var place = this;
  currentplace = place;
  var html = "";
  if (place.website)
  {
    var target = document.getElementById("setting_target");
    html += '<b>Name:</b> <a href="'+place.website+'" target="'+target+'">'+place.name+'</a><br />';
  }
  else
  {
    html += "<b>Name:</b> "+place.name+"<br />";
  }
  if (place.phone != "") html += "<b>Phone: </b>"+place.phone+"<br />";
  if (place.hours != "") html += "<b>Hours: </b>"+place.hours+"<br />";
  if (place.specialties != "") html += "<b>Specialties: </b>"+place.specialties+"<br />";
  html += "<b>Address: </b>"+place.getAddress() + "<br />";
  place.marker.openInfoWindowHtml(html);
  if (homeAddr != "") { //should be controlled so it's always either a valid geocode-able address, or an empty string
    var query = "from: "+homeAddr+" to: "+place.getAddress();
    //place.marker.openInfoWindow("Please wait...");
    GEvent.addListener(directions, "load", function() {
      //var place = this;
      //this never shows in the console!!!!!!
      //console.log(place);
      var dist = (directions.getDistance().meters / 1609.344);
      currentdist = dist;
      var time = directions.getDuration().html; //string, e.g. "about 45 mins"
      var travelCost = getTravelCost();
      var emissions = getTravelCO2()
      html += "<b>Distance:</b> "+dist.toFixed(2)+" miles <br />";
      html += "<b>Time: </b>"+time+"<br />";
      html += "<b>Directions: </b><a target=\"_blank\" href=\"http://maps.google.com/maps?q=" + homeAddr + " to " + currentplace.getAddress() + "\">via Google Maps</a><br />";
      if (!isNaN(travelCost))
        html += "<b>Gas cost:</b> $"+travelCost.toFixed(2)+"<br />";
      if (!isNaN(emissions))
        html += "<b>CO<sub>2</sub> Emissions:</b> "+emissions.toFixed(2)+" pounds"+"<br />";
      currentplace.marker.openInfoWindowHtml(html);
    });
    directions.load(query);
  }
  else
  {
    html += "<br />To calculate travel data, click on the Settings tab and fill in all the fields.";
    place.marker.openInfoWindowHtml(html);
  }    
}

function setDist() {
  var place = this;
  var query = "from: "+homeAddr+" to: "+place.address;
  directions.load(query);
  var dist;
  GEvent.addListener(directions, "load", function() {
    place.dist = directions.getDistance().meters / 1609.344;
  });
}
function setTime() {
  var place = this;
  var query = "from: "+homeAddr+" to: "+place.getAddress();
  directions.load(query);
  var dist;
  GEvent.addListener(directions, "load", function() {
    place.time = directions.getDuration().html;
  });
}

function plotHome(inputStr) {
  if (inputStr=="")
  {
    changeHomeValid();
    if (homeMarker)
      map.removeOverlay(homeMarker);
    homeAddr="";
  }
  else {
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(inputStr, function(latLng) {
      if (!latLng) {
        changeHomeInvalid();
      }
      else {
        changeHomeValid();
        homeAddr = inputStr;
        if (homeMarker)
          map.removeOverlay(homeMarker);
        homeMarker = new GMarker(latLng, {'icon': houseIcon});
        map.addOverlay(homeMarker);
        map.panTo(latLng);
      }
    });
  }
}

function showInfoById(id) { //gets id # of a restaurant, and calls showPlaceInfo() for that restaurant
  for (i in placeData)
  {
    if (placeData[i].id == id)
      placeData[i].showPlaceInfo();
  }
}

function addressIsValid() {document.getElementById("settings_home_result").value = 'true';}
function addressIsInvalid() {document.getElementById("settings_home_result").value = 'false';}
function addressIsBlank() {addressIsValid();}