(function() {
  var cs;

  cs = window.CS || (window.CS = {});

  cs.Data || (cs.Data = {});

  cs.Views || (cs.Views = {});

  cs.Views.CafeLocatorView = Backbone.View.extend({
    key: 'AIzaSyBOsLgkD96w-TVD6GzX0mnMyBQRmS_CxAw',
    style: [
      {
        stylers: [
          {
            saturation: -99
          }
        ]
      }
    ],
    defaultSearchTerm: 'Type an address and press enter to search',
    events: {
      'click .intro p a': 'jumpToCity',
      'focus #search-address': 'searchEvents',
      'blur #search-address': 'searchEvents',
      'keypress #search-address': 'searchEvents'
    },
    initialize: function(options) {
      this.options = options;
      _.bindAll(this);
      this.$el = $(this.el);
      cs.CafeLocatorView = this;
      this.$('#search-address').val(this.defaultSearchTerm);
      this.loadCafes();
    },
    loadCafes: function() {
      $.ajax({
        url: "" + cs.Data.index + "cafes.json",
        dataType: 'json',
        success: this.cafesLoaded
      });
    },
    cafesLoaded: function(cafes) {
      this.cafes = cafes;
      $.ajax({
        url: "http://maps.googleapis.com/maps/api/js?key=" + this.key + "&sensor=true&callback=window.CS.CafeLocatorView.mapsApiLoaded",
        dataType: "script"
      });
    },
    mapsApiLoaded: function() {
      var _this = this;
      this.mapOptions = {
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(geoplugin_latitude(), geoplugin_longitude()),
        backgroundColor: '#e9e9e9',
        disableDefaultUI: true
      };
      this.geocoder = new google.maps.Geocoder();
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          _this.mapOptions.center = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          _this.initMap();
        }, this.initMap);
      } else {
        this.initMap();
        return;
      }
    },
    initMap: function() {
      this.map = new google.maps.Map(document.getElementById("google-layer"), this.mapOptions);
      this.map.setOptions({
        styles: this.style
      });
      _.each(this.cafes, this.addCafe);
    },
    addCafe: function(cafe, index) {
      var iconSrc, marker,
        _this = this;
      if (cafe.supremeCafe) {
        iconSrc = "" + cs.Data.templateDir + "/_/images/locator.marker.supreme.png";
      } else {
        iconSrc = "" + cs.Data.templateDir + "/_/images/locator.marker.cafe.png";
      }
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(cafe.latitude, cafe.longitude),
        map: this.map,
        title: cafe.name,
        animation: 'DROP',
        icon: new google.maps.MarkerImage(iconSrc)
      }, new google.maps.Size(27, 32), new google.maps.Point(13, 16), {
        data: cafe
      });
      google.maps.event.addListener(marker, 'click', function() {
        _this.showCafeInfo(_this.getCafeFromTitle(marker.title), marker);
      });
    },
    getCafeFromTitle: function(title) {
      var theCafe,
        _this = this;
      theCafe = -1;
      _.each(this.cafes, function(cafe) {
        if (cafe.name === title) return theCafe = cafe;
      });
      if (theCafe !== -1) return theCafe;
    },
    showCafeInfo: function(cafe, marker) {
      var $el, cafeModel, view;
      this.$('.cafe-info').remove();
      cafeModel = new Backbone.Model();
      cafeModel.set(cafe);
      view = new cs.Views.CafeLocatorInfoView({
        tagName: 'div',
        className: 'cafe-info',
        model: cafeModel,
        appModel: this.options.appModel
      });
      $el = $(view.el);
      if (cafe.supremeCafe) $el.addClass('supreme-cafe');
      this.$('#map').append($el);
      this.$el.bind('close-info', this.hideCafeInfo);
      this.map.setZoom(16);
      this.map.setCenter(marker.position);
      $('.key .cafe-types').addClass('hide');
      $('.key .methods').removeClass('hide');
      $('html, body').scrollTop(126);
    },
    hideCafeInfo: function(e) {
      $('.key .cafe-types').removeClass('hide');
      $('.key .methods').addClass('hide');
    },
    jumpToCity: function(e) {
      var $el, cities, city,
        _this = this;
      e.preventDefault();
      $el = $(e.target);
      city = $el.data('city');
      cities = [
        {
          name: "Auckland",
          lat: -36.850505,
          long: 174.747849
        }, {
          name: "Wellington",
          lat: -41.294366,
          long: 174.777288
        }, {
          name: 'Christchurch',
          lat: -43.532123,
          long: 172.63607
        }, {
          name: 'Melbourne',
          lat: -37.813174,
          long: 144.962969
        }
      ];
      _.each(cities, function(c) {
        if (c.name === city) city = c;
      });
      this.map.setCenter(new google.maps.LatLng(city.lat, city.long));
    },
    searchEvents: function(e) {
      var $el;
      $el = $(e.target);
      switch (e.type) {
        case 'focusin':
          if ($el.val() === this.defaultSearchTerm) $el.val('');
          break;
        case 'focusout':
          if ($el.val() === '') $el.val(this.defaultSearchTerm);
          break;
        case 'keypress':
          if (e.charCode === 13) {
            $el.blur();
            this.doSearch($el.val());
          }
      }
    },
    doSearch: function(term) {
      var _this = this;
      this.geocoder.geocode({
        'address': term
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          _this.map.setCenter(results[0].geometry.location);
          _this.$('.key .cafe-types').removeClass('hide');
          _this.$('.key .methods').addClass('hide');
          return _this.$('.cafe-info').remove();
        } else {
          if (status === 'ZERO_RESULTS') {
            return alert("We couldn't find anything for that search :(");
          }
        }
      });
    }
  });

}).call(this);

