<%#= encoding: utf-8 %>
$(function() {
  var content_holder, content;
  var selector = 'a[contenteditable="true"]';
  // prevent clicks inside editable area to fire
  // a click event on the body
  // and therefor saving our content before we even edit it
  
$(".nav-tabs").find(".icons-pencil").click(function(){
  $(this).css({
    "display" : "none"
  })
  $(this).next().attr("contenteditable",true).addClass("edit");
  // $(selector).click(function(e) {
  //   e.stopPropagation();
  // });
  
  // initialize the "save" function
  $(selector).focus(function(e) {
    content_holder = $(this);
    content   = content_holder.html();
    // one click outside the editable area saves the content
    $(selector).keypress( function(e) {
      // but not if the content didn't change
      //alert('out!!');
  if(e.keyCode == 13){ 
     $(".nav-tabs>li>a").removeClass("edit");
     $(this).prev(".icons-pencil").css({
      "display" : "block"
     })
      e.preventDefault();
      // if ($(e.target).is(selector) || content == content_holder.html()) {
      //   return;
      // }
      
      $.ajax({
        url: content_holder.data('edit-url'),
        type: 'POST',
        dataType: 'json',
        data: { body: content_holder.html() },
        success: function(json) {
          $(selector).attr("contenteditable",false)
          alert("<%= I18n.t('update.success_') %>");
          //content_holder.effect('highlight', {'color': '#0f0'}, 3000);
        },
        error: function() {
          alert("<%= I18n.t('update.fail') %>");
          //content_holder.effect('highlight', {'color': '#f00'}, 3000);
          content_holder.html(content);
        }
      });
    }
    });
  });
});
});