/**
 * Plugin Name ajaxifyForms
 * Version: 0.1
 * @requires jQuery v1.2.3
 *
 * Copyright (c) 2008 Seth House
 * Released under the GNU General Public License 3
 * http://www.gnu.org/licenses/gpl.html
 *
 *
 * @description Bind to a form to replace the normal submission with an Ajax submission.
 *
 *
 * @example $('form').ajaxifyForms();
 * @description Bind the submit event for all forms on the page
 *
 * @example $('someElement').ajaxifyForms({ optionName: 'option-value'});
 * @description Invoke the plugin with a non-default option
 *
 * @exmaple $.fn.ajaxifyForms.defaults.optionName = 'option-value';
 * @description Override default option globally
 *
 * @example $.fn.ajaxifyForms.completed = function(responseText){}
 * @description Override the default completion action
 *
 * @example $.fn.ajaxifyForms.success = function(responseText){}
 * @description Override the default success action
 *
 * @example $.fn.ajaxifyForms.failure = function(responseText){}
 * @description Override the default failure action
 *
 *
 *
 * @type jQuery
 *
 * @name ajaxifyForms
 *
 * @cat Plugins/Ajax
 *
 * @author Seth House/seth@eseth.com
 */

(function($) {
    $.fn.ajaxifyForms = function(options) {
        // debug(this);

        var opts = $.extend({}, $.fn.ajaxifyForms.defaults, options);

        return this.each(function() {
            var $this = $(this);
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            $this.submit(function(e){
                e.preventDefault();

                $.ajax({
                    dataType: 'json',
                    type: $this.attr('method'),
                    url: $this.attr('action'),
                    data: $this.serialize(),
                    success: $.fn.ajaxifyForms.completed
                });

            });
        });
    };


    // Private function for debugging
    function debug($obj) {
        if (window.console && window.console.log)
            window.console.log('Debugging output!');
    };


    // Completion callback (overridable)
    $.fn.ajaxifyForms.completed = function(response){
        if (response.success){
            $.fn.ajaxifyForms.success(response);
        } else {
            $.fn.ajaxifyForms.failure(response);
        }
    };

    // Success function (overridable)
    $.fn.ajaxifyForms.success = function(response){
        // do nothing
    };

    // Failure function (overridable)
    $.fn.ajaxifyForms.failure = function(response){
        // FIXME: need to clear out old errors first
        $.each(response.errors, function(i, val){
            $('#'+ i).before('<ul class="errorlist"><li>'+ val +'</li></ul>');
        });
    };
})(jQuery);
