$.fn.extend({
insertAtCaret: function(myValue){
  this.each(function(i) {
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
 }
});

function addUrltoNote(content) {
  var newContent = "\n" + content + "\n";
  $("#note_body").insertAtCaret(newContent);
}

$(document).ready(function() {

  $('img.img-link').click(function(){
    $("div#design-image").load("/admin/designs/"+$(this).attr('name')+"/designimage");
  });

  $(".update-trigger").change(function(){
    $(".spinner").show();
    var path = $(this).attr("ref");
    $.post(path, {new_value: $(this).val()}, function(data) {
      $(".spinner").hide();
      $('#note_body').val(data);
      $('#note_sent_to_designer').attr("checked", "checked");
      $.scrollTo($('#note_sent_to_designer'));
    }, 'text');
  });

  $(".update-priority").change(function(){
    var redirect_to = $(this).attr("data:redirect-to");
    var callback = function(data) {
      location.href = redirect_to;
    };
    $.post($(this).attr("ref"), { new_value: $(this).val()}, callback, 'text');
  });

  $(".highlight").effect("highlight", {}, 1500);


  $('div.note').each(function(index, note){
    $(note).editable($(note).attr("rel"), { loadurl: $(note).attr("rel"), type:  "textarea", method: "PUT", onblur: "submit" });
  });

  $('.textarea-insert').live('click', function() {
      addUrltoNote($(this).attr("href"));
      return false;
  });

  $('.textarea-insert-image').live('click', function() {
      addUrltoNote('!' + $(this).attr("href") + '!');
      return false;
  });

});
