﻿/*  AJAX FORM Plugin
--------------------------------------

Init method:
$('#myForm').ajaxForm();


*/

(function($) {

    //private meothod that reads all texboxes
    var R = function(ob) {

        // build main options before element iteration
        var o = $.extend({}, $.fn.ajaxForm.defaults);
        var b = {};
        var I = $("input, select, textarea", ob);

        I.each(function() {
            var T = $(this);
            var p = T.attr("type");

            //checks for form elements that do not work with val
            if (p == "checkbox") {
                b[T.attr("name")] = T.attr("checked");
            } else {
                b[T.attr("name")] = T.val();
            }

        });

        return b;
    };

    // plugin definition
    $.fn.ajaxForm = function(op) {

        // build main options before element iteration
        var _op = $.extend({}, $.fn.ajaxForm.defaults, op);

        // iterate and reformat each matched element
        return this.each(function() {
            $this = $(this);

            var F = $(this); //form element
            var o = $.meta ? $.extend({}, _op, $this.data()) : _op; // build element specific options
            var B = $(_op.submit, F); //submit button
            var u = F.attr("action"); //action method

            //removes local loader
            var rm = function() {
                $("#ajax_loader_image").remove();
            }

            //callback function
            var cb = function(d) {
                B.removeAttr("disabled"); //enables button back
                rm();
                _op.callBack(d); //callback from the options
            }

            var ec = function() {
                B.removeAttr("disabled"); //enables button back
                rm();
            }

            //button click
            B.click(function() {
                rm();
                B.attr("disabled", true).after(_op.loaderImg); //disables button to prevent double click
                _op.clickCall();
                
                $.ajax({
                    type: "POST",
                    url: u,
                    data: R(F),
                    dataType: "json",
                    success: cb,
                    error: ec
                });

                return false;
            });
        });
    };

    //obtions object
    $.fn.ajaxForm.defaults = {
        submit: "button",
        clickCall: function() { },
        loaderImg: "<img src='../../Content/images/loading.gif' id='ajax_loader_image' style='float:left' alt='loading...' />",
        callBack: function(d) { }
    };

})(jQuery);




