$.forms = function(form, opts){
  var $o = {
    callbacks: {},
    ajax_submit: true
  };

  $.extend($o, opts);

  var $obj = {
    init: function(){
      if($o.ajax_submit) $obj.bind_form_action(form);
    },
    bind_form_action: function(form){
      $(form).submit(function(e){
        e.preventDefault();
        var $this = $(this);
        var $parent = $this.parent();
        $.ajax({
          url: $this.attr("action"),
          type: $this.attr("method"),
          data: $(":input", $this).serialize(),
          success: function(r){
            $parent.html(r);
            $obj.bind_form_action($("FORM", $parent));
            if (typeof($o.callbacks.after_success)!="undefined") return $o.callbacks.after_success(r);
          },
          complete: function(request) {
            if(request.status.toString()[0]=='3'){
              if (typeof($o.callbacks.redirect)!="undefined") return $o.callbacks.redirect(request);
              window.location.href = request.getResponseHeader('Location');
            };
          }
        });
      })
    }
  }

  $obj.init();
  return form;
};

$.fn.load_form = function(url, opts){
  var $this = this;
  $.ajax({
    url: url,
    data: (typeof(opts.data) == "undefined") ? null : opts.data,
    success: function(r){
      $this.html(r).removeClass("hidden");
      $.forms($("FORM", $this), opts.form);
      $this.trigger("ajax_complete");
    }
  })
};

$.fn.ajax_dialog_form = function(opts){
  var $target = this;
  var $o = {
    ajax: {}
  };
  $.extend($o, opts);
  var $template;

  var $obj = {
    open_dialog: function(){
      $template = $target.clone();
      $template.bind("ajax_complete", function(){
        $template.dialog($o.dialog_options);
      });
      $template.load_form($o.url, $o.ajax);
    }
  };

  $obj.open_dialog();
  return $template;
}

$.fn.bind_smileys = function(prefix){
  var smiley_div =$("[smile][smile_for]", this);
  if(!smiley_div.length) return false;
  var smiley_function_name = prefix + smiley_div.attr("smile_for") + "()";
  try{
    eval(smiley_function_name);
  }
  catch ($e) {
    console.log(smiley_function_name, $e)
    };
};

$.fn.get_buttons = function(){
  var $buttons = {};
  if (this.attr("button_close")) $buttons[this.attr("button_close")] = function(){ $(this).dialog("close") }
  if (this.attr("button_submit")) $buttons[this.attr("button_submit")] = function(){ $("FORM", $(this)).submit() }
  if (this.attr("button_reset")) $buttons[this.attr("button_reset")] = function(){ $("FORM", $(this)).get(0).reset() }
  return $buttons;
};

$.fn.ajax_form = function(opts){
  return $.forms(this, opts);
};

