/**
 * AJAX form plugin for jQuery
 *
 * @copyright  Copyright (c) 2009 Jan Marek
 * @license    MIT
 * @link       http://nettephp.com/cs/extras/ajax-form
 * @version    0.1
 */

jQuery.fn.extend({
    ajaxSubmit: function (formEl, e, callback) {
        var form;
        var sendValues = {};

        // submit button
        if (this.is(":submit")) {
            form = this.parents("form");
            sendValues[this.attr("name")] = this.val() || "";

        // form
        } else if (this.is("form")) {
            form = this;

        // invalid element, do nothing
        } else {
            return null;
        }

        // validation
        if (form.get(0).onsubmit && !form.get(0).onsubmit()) return null;

        // get values
        var values = form.serializeArray();

        for (var i = 0; i < values.length; i++) {
            var name = values[i].name;

            // multi
            if (name in sendValues) {
                var val = sendValues[name];

                if (!(val instanceof Array)) {
                    val = [val];
                }

                val.push(values[i].value);
                sendValues[name] = val;
            } else {
                sendValues[name] = values[i].value;
            }
        }
       
        // send ajax request
        var ajaxOptions = {
            url: form.attr("action"),
            data: sendValues,
            type: form.attr("method") || "get"
        };

        if (callback) {
            ajaxOptions.success = callback;
        }


        /* MultiFileUpload */
        var emptyQueue = true;
        var form = $(form);
        var multipleFileUploadFields = $(".MultipleFileUpload", form);
        var uploadersInQueue = multipleFileUploadFields.length;
        
        if(uploadersInQueue>0){
            multipleFileUploadFields.each(function(i){
                var uploadify = $(".uploadify[id]",this);
                if(uploadify.uploadifySettings("queueSize")>0){
                    emptyQueue = false;
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    uploadify.uploadifyUpload();
                    uploadify.bind("uploadifyAllComplete",function(){
                        uploadersInQueue--;
                        if(uploadersInQueue===0){
                            return jQuery.ajax(ajaxOptions);
                        }
                    });
                } else uploadersInQueue--;
            });
        }
        
        if (emptyQueue == true) {
            return jQuery.ajax(ajaxOptions);
        }
    }
});



$("form.ajax").live("submit", function (e) {
    $(this).ajaxSubmit(this, e);
    return false;
});

/*$("form.ajax :submit, form .ajax:submit").live("click", function (e) {
    $(this).ajaxSubmit(this, e);
    return false;
});*/

