var csTemplate = _.template('<li class="cs">' +
'<a href="tel:<%= phone %>"><%= name %></a>'+
'(<%= dist %> mi) <em><a href="<%= mapUrl %>" target="_blank">map</a></em></div>');
// var CarService = Class.create({
//   initialize: function(ary) {
//     this.license = ary[0]
//     this.name  = ary[1];
//     this.altName = ary[2];
//     this.street = ary[3];
//     this.city = ary[4];
//     this.zip = ary[5];
//     this.phone = ary[6];
//     this.latLng = new google.maps.LatLng(ary[7], ary[8]);
//     this.blackCar = ary[9];
//   }
// });

function CarService (ary) {
    this.license = ary[0]
    this.name  = ary[1];
    this.altName = ary[2];
    this.street = ary[3];
    this.city = ary[4];
    this.zip = ary[5];
    this.phone = ary[6];
    this.latLng = [ary[7], ary[8]];
    this.blackCar = ary[9];
    this.myDist = function(){
      var d = dist(this.latLng[0], this.latLng[1], App.myLocation[0], App.myLocation[1]);
      // Round to 2 decimals
      return Math.round(d*100)/100;
    };

    this.address = this.street + ", " + this.city + ", NY " + this.zip;
    this.mapUrl = "http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=" +
      this.name.replace(/\s+/, "+") + "+" +
      this.address.replace(/\s+/, "+") + "&ie=UTF8&hq=&hnear=" +
      this.address.replace(/\s+/, "+") + "&z=5";
    
    
    this.html = csTemplate({name : this.name,
      phone : this.phone,
      dist : this.myDist(),
      mapUrl: this.mapUrl,
      blackCar: this.blackCar});
}


// Returns the distance between any to LatLng points
function dist(lat1, lon1, lat2, lon2) {
  // var R = 6371; // km
  var R = 3963; // miles
  var dLat = (lat2-lat1) * Math.PI / 180;
  var dLon = (lon2-lon1) * Math.PI / 180
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d;
}

window.App = {

  init: function(){
    $("#toggle_blackcar:checkbox").attr('checked', App.showBlackCars());
    $("#toggle_blackcar:checkbox").change(function(){
      App.setBlackCars($(this).is(":checked"));
    });
    App.refreshLocation();
  },

  refreshLocation: function(){
    $(".info.geolocation").html('Updating your location.').show();
    var noLocation = function(){ $(".info.geolocation").html('Unable to find your location.').show()};

    if (navigator.geolocation) navigator.geolocation.getCurrentPosition(App.newLocation, noLocation)
  },
  
  newLocation: function(position){
    App.myLocation = [position.coords.latitude, position.coords.longitude];
    var nearest = App.nearest(5);
    $(".info.geolocation").hide()
    App.drawResults(nearest);
  },

  // Return the nearest +count+ car services to latLng
  nearest: function(count){
    var sortFn = function(cs) {
      return dist(App.myLocation[0], App.myLocation[1], cs[7], cs[8]);
    }
    // Initialze results with the first objects

    var carServices = _.select(window.CarServices, function(cs){
        return !cs[9];
      });
    var results = _.sortBy(carServices, sortFn).slice(0,count)
    return results;
  },

  drawResults: function(services){
    $("ul#carServices li").remove();
    var html = "";
    _.each(services, function(ary){
      var cs = new CarService(ary);
      $("ul#carServices").append(cs.html);
    });
  },
  
  showBlackCars: function(){
    return localStorage.getItem("showBlackCars");
  },
  
  setBlackCars: function(value){
    localStorage.setItem("showBlackCars", value);
  }
};

$(document).ready(function(){ App.init() });

