(function ($) {
  $.fn.extend({
    autogrow: function (options) {              
      options = $.extend({}, $.Autogrow.defaults, {
        rows: $(this).attr("rows") ? $(this).attr("rows") : $.Autogrow.defaults.rows,
        cols: $(this).attr("cols") ? $(this).attr("cols") : $.Autogrow.defaults.rows
        },
        options);
      return this.each(function () {
        new $.Autogrow(this, options);
      });
    }    
  });
  
  $.Autogrow = function (input, options) {
    if(options.editor) {
      $(input).after('<a href="#" onclick="return false;">Editor</a>');
      $(input).next("a").bind("click", function() { $(input).trigger("editor"); });
    }
    $(input).bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) {
      var ln = $(this).val().split("\n");
      rows = ln.length;
      for (var i=0; i < ln.length; i++) {
        rows += Math.floor(ln[i].length / options.cols);
      };
      rows = rows < options.rows ? options.rows : rows;
      $(this).attr("rows", rows);
    }).bind("editor", function () {
      var input = $(this);
      $.post("/bin/ajax/editor/form", { text: $(this).val(), data: $(this).attr("name") }, function(json) {
        var form = json.form;
        $(form).modal({          
          overlayId: "form-overlay",
          containerId: "form-container",
          closeClass: "form-close",
          onOpen: options.form.open,
          onShow: options.form.show,
          onClose: options.form.close
        });
      }, "json");
    });
  };
  
  $.Autogrow.defaults = {
    cols: 10,
    rows: 1,
    editor: true,
    form: {
      message: null,
      open: function (dialog) {
          dialog.overlay.fadeIn(200);
          dialog.container.fadeIn(200);
          dialog.data.fadeIn(200);
          $("#editor_textarea").tinymce( { script_url : '/js/tiny_mce/tiny_mce.js', theme : "advanced", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left" } );
      },
      show: function (dialog) {
          $('#form_data').submit(function (e) {                        
            return false;
          });
          $('input[name=aceptar]').click(function() {
            tinyMCE.triggerSave();
            var name = $(dialog.data).find("#text_area_input_name").val();
            var value = $(dialog.data).find("#editor_textarea").val();
            $("textarea[name=" + name + "]").val(value);
            dialog.overlay.fadeOut(200);
  	        $.modal.close();              
            return false;
          });	    
      },
      close: function (dialog) {
          dialog.overlay.fadeOut(200);
          $.modal.close();
      }
    }
  };
  
})(jQuery);

