$(document).ready(function(){
  if($(".establishments").length > 0){
    var establishments = [];

    $.ajax({url: "/get_establishments", success: function(response){
        $(response).each(function(index,item){
          var establishment = new Establishment(item);
          establishment.init();
          establishments.push(establishment);
        });
      }
    });
  }

});

function Establishment(establishment){
  this._title = establishment.title;
  this._slug = establishment.slug;
  this._latlng = establishment.latlng;
  this._address = establishment.address;
}

Establishment.prototype = {
  _marker : null,
  _linkElement : null,
  _title : null,
  _slug : null,
  _latlng : null,
  _infowindow : null,

  init : function(){
    $(".establishmentlist").append("<li><a class='" + this._slug + "' href='" + this._slug + "'>" + this._title + "</a></li>");
    this._linkElement = $(".establishmentlist a." + this._slug);
    this._linkElement.click($.proxy(this._onlinkClickHandler, this));
    this._checkCurrent();
    this._setMarker();
  },

  _showDetails : function(data){
    $(".establishmentinfo").remove();
    $(".listwrapper").append("<div class='establishmentinfo'></div>");
      var info = "<p>" + data.postbox + "</p>" +
                "<p>Bezoekadres:<br />" + data.address + "<br />" +
                data.postalcode + " " + data.title + "<br />" +
                "T " + data.telephone + "<br />" +
                "F " + data.fax + "<br />" +
                "<a href='mailto:" + data.email +  "'>" + data.email + "</a></p>" +
                "<p><a class='showinfo' href='#'>toon op de kaart</a></p>";
    $(".establishmentinfo").html(info);
    $(".showinfo").click($.proxy(function(){
      this._openInfoWindow()}, this));
    // calculate correct position
    if (parseInt($(".establishmentinfo").css("height")) < parseInt($(".establishmentlist").css("height"))){

      // align top of the infotab with the current selected list-item.
      var selectedTopOffset = $(".establishmentlist li.selected").position().top;
      $(".establishmentinfo").css("margin-top", selectedTopOffset);

      // if the expanded infotab is against the bottom of the div, then align it with the bottom of the list.
      var listBottomOffset = $(".establishmentlist").css("height");
      var infoBottomOffset = parseInt($(".establishmentinfo").css("margin-top")) + parseInt($(".establishmentinfo").css("height") + 10);
      if(parseInt(infoBottomOffset) > parseInt(listBottomOffset)){
        var infoOffset = (parseInt(listBottomOffset) - parseInt($(".establishmentinfo").css("height")));
        $(".establishmentinfo").css("margin-top", infoOffset - 10);
      }
    }
  },

  _onlinkClickHandler : function(event){
      $(".establishmentlist li.selected").removeClass("selected");
      this._linkElement.parent().addClass("selected");
      if(event){
        event.preventDefault();
      }
      soapVariables = {
        url: "/get_establishment",
        data: "title=" + this._title,
        success: $.proxy(function(response){
          this._showDetails(response);
        }, this)
      };
      $.ajax(soapVariables);
  },

  _setMarker : function (){
    if(this._latlng){
      var lat = parseFloat(this._latlng.split(",")[0]);
      var lng = parseFloat(this._latlng.split(",")[1]);
      var latlng = new google.maps.LatLng(lat, lng);
      this._marker = new google.maps.Marker({

        position: latlng,
        map: gmap,
        title: this._title
      });
      google.maps.event.addListener(this._marker, 'click', $.proxy(function(){
        this._openInfoWindow()}, this));
    }
  },

  _openInfoWindow : function(){
    var windowtext = this._title + "<br /><br /><a href='http://maps.google.nl/?daddr=" + this._address + ", " + this._title + "'>Routebeschrijving</a>";
    this._infowindow = new google.maps.InfoWindow({
            content: windowtext
    });
    this._infowindow.open(gmap, this._marker);
    if (openmarker){
      openmarker.setMap(null);
    }
    openmarker = this._infowindow;
    openmarker.setMap(gmap);
  },

  _checkCurrent : function(){
    var establishment = document.location.href.match(/([^/]+)\/?$/)[1];
    if(establishment == this._title.toLowerCase().replace(" ", "-").replace(/[()]/g, "")){
      this._onlinkClickHandler();
    }
  }
};

