;(function($) {
    $.extend({
        values: [],
        addForm: function ( f ) {
            if (!(f === undefined)) $("#" + f).populateValues();
        },
        addItem: function ( values ) {
            var n = values.name;
            var v = values.value;
            var f = values.element;
            if (n === undefined) {alert("Invalid Name");return;}
            if (v === undefined) {
                if  ( f === undefined )
                {
                    alert("No value or element passed");
                    return;
                }
                v = $("#" + f).val();
            }
            $.values.push({name: n, value: v});
        },
        executeCommand: function( options )
        {
            // Set the command
                var command = options.command;
                if (command === undefined){ alert("No command received"); return;}
                $.addItem({name: "cmd", value: command});

            // Extend the default options
                options = $.extend({}, $.requestDefaults, options);

            // If a form has been passed through, add it's contents to the values           
                if ( ! ( options.form === undefined ) ){$.addForm( options.form );}

            // Add any extra items to the values
                if (options.extraItems){$(options.extraItems).each(function(i){$.addItem(options.extraItems[i]);});}

            // Run the request and load the relavant javascript response file executing success or error
                var responseFile = options.javascriptCommandURL + command + ".js"; 
                var responseCallBackSuccess = command + "_callback";
                // If my ajaxQueue plugin is available and we want it, use it
                if ($.queue && options.addToQueue)
                {
                    $.queue({
                        passAlong: options.passAlong,
                        url: options.controllerURL,
                        data: $.param($.values),
                        dataType: options.dataType,
                        success: function(data){
                            //$.getScript(responseFile, function (){return doSuccess(data);});
                            return eval(responseCallBackSuccess + "(data)"); 
                        },
                        error: function(a, b){
                            //return eval(responseCallBackError + "(data)");
                            myAlert("Error", "There was an error executing " + options.command, "error");
                        }
                    });
                } else {
                    $.ajax({
                        url: options.controllerURL,
                        data: $.param($.values),
                        dataType: options.dataType,
                        type: options.type,
                        success: function(data){
                            //$.getScript(responseFile, function (){doSuccess(data);});
                            if ( data.error )
                            {
                                myAlert("Error",  data.errorMessage, "error" );
                                return;
                            }
                            return eval(responseCallBackSuccess + "(data)");
                        },
                        error: function(a, b){
                            myAlert("Error", "There was an error executing " + options.command, "error");
                        }
                    });
                }
                $.values = new Array();
        }
    });

    $.requestDefaults = {
        controllerURL: "/xmlhttp/",
        javascriptCommandURL: "/javascript/commands/",
        dataType: "json",
        type: "POST"
    }

    /* Pulled from the jquery.form plugin formToArray function*/
    $.fn.extend({
        populateValues: function(semantic) {
            var a = [];
            if (this.length == 0) return a;
        
            var form = this[0];
            var els = semantic ? form.getElementsByTagName('*') : form.elements;
            if (!els) return a;
            for(var i=0, max=els.length; i < max; i++) {
                var el = els[i];
                var n = el.name;
                if (!n) continue;
        
                if (semantic && form.clk && el.type == "image") {
                    // handle image inputs on the fly when semantic == true
                    if(!el.disabled && form.clk == el)
                        $.values.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
                    continue;
                }
                var v = fieldValue(el, true);
                if (v === null) continue;
                if (v.constructor == Array) {
                    for(var j=0, jmax=v.length; j < jmax; j++)
                        $.values.push({name: n, value: v[j]});
                }
                else
                    $.values.push({name: n, value: v});
            }
        
            if (!semantic && form.clk) {
                // input type=='image' are not found in elements array! handle them here
                var inputs = form.getElementsByTagName("input");
                for(var i=0, max=inputs.length; i < max; i++) {
                    var input = inputs[i];
                    var n = input.name;
                    if(n && !input.disabled && input.type == "image" && form.clk == input)
                        $.values.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
                }
            }
        }
    });
    
    function doSuccess( data )
    {
        var foo = success( data );
        return foo;
    }

    /* Pulled from the jquery.form plugin*/
    function fieldValue(el, successful) 
    {
        var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
        if (typeof successful == 'undefined') successful = true;
    
        if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
            (t == 'checkbox' || t == 'radio') && !el.checked ||
            (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
            tag == 'select' && el.selectedIndex == -1))
                return null;
    
        if (tag == 'select') {
            var index = el.selectedIndex;
            if (index < 0) return null;
            var a = [], ops = el.options;
            var one = (t == 'select-one');
            var max = (one ? index+1 : ops.length);
            for(var i=(one ? index : 0); i < max; i++) {
                var op = ops[i];
                if (op.selected) {
                    // extra pain for IE...
                    var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                    if (one) return v;
                    a.push(v);
                }
            }
            return a;
        }
        return el.value;
    }
})(jQuery);

