$(function() {
  $(".favorite-icon").click(function() {
    var $this = $(this);

    if($this.hasClass("active")) {
      $this.removeClass("active");
      $this.find("img").attr("src", "/images/nonfavorite.png");
    
      delete_favorite($this.attr("rel"));
    } else {
      $this.addClass("active");
      $this.find("img").attr("src", "/images/favorite.png");

      create_favorite($this.attr("rel"));
    }
    
    return false;
  });

  $(".favorite-button").click(function() {
    var $this = $(this);
    
    if($this.hasClass("active")) {
      $this.removeClass("active");
      $this.html("Lägg till på min karta");
    
      delete_favorite($this.attr("rel"));
    } else {
      $this.addClass("active");
      $this.html("Ta bort från min karta");
      
      create_favorite($this.attr("rel"));
    }
    
    return false;
  });
});

function create_favorite(company_id) {
  response = $.ajax({
    type: "post",
    url: "/foretag/" + company_id + "/favorit",
    dataType: "json",
    data: {authenticity_token: window.authenticity_token},  
    success: function(data, textStatus) {
      notice("Du la till " + data['company_name'] + " till din <a href='/karta'>karta</a>");
      $('#favorites_count').html(data['favorites_count']);
    }
  });
}

function delete_favorite(company_id) {
  $.ajax({
    type: "post",
    url: "/foretag/" + company_id + "/favorit",
    dataType: "json",
    data: {"_method": "delete", authenticity_token: window.authenticity_token},
    success: function(data, textStatus) {
      notice("Du tog bort " + data['company_name'] + " från din <a href='/karta'>karta</a>");
      $('#favorites_count').html(data['favorites_count']);
    }
  });
}