/**
 * Returns an object wrapper for a parameter-div jQuery object and the input in that div that stores the internal
 * parameter value (as opposed to the display field, although they may be the same).
 */
AJS.MacroBrowser.Field = function (paramDiv, input, options) {
    options = options || {};

    var setValue = options.setValue || function (value) {
        input.val(value);
    };

    input.change(options.onchange || AJS.MacroBrowser.paramChanged);

    return {
        paramDiv : paramDiv,
        input : input,
        setValue : setValue
    };
};

/**
 * ParameterFields defines default "type" logic for fields in the Macro Browser's Insert/Edit Macro form.
 *
 * Each method in this object corresponds to a parameter type as defined in the MacroParameterType enum.
 */
AJS.MacroBrowser.ParameterFields = (function ($) { return {

    /**
     * Default field for all unknown types.
     */
    "string" : function (param, options) {

        var paramDiv = AJS.clone("#macro-param-template");
        var input = $("input", paramDiv);

        if (param.required) {
            input.keyup(AJS.MacroBrowser.processRequiredParameters);
        }
        
        return AJS.MacroBrowser.Field(paramDiv, input, options);
    },

    /**
     * A checkbox - assumes not true means false, not null.
     */
    "boolean" : function (param, options) {

        var paramDiv = AJS.clone("#macro-param-checkbox-template");
        var input = $("input", paramDiv);

        options = options || {};
        options.setValue = options.setValue || function (value) {
            if (/true/i.test(value) ||
                (/true/i.test(param.defaultValue) && !(/false/i).test(value))) {
                input.attr("checked", "checked");
            }
        };

        return AJS.MacroBrowser.Field(paramDiv, input, options);
    },

    "enum" : function (param, options) {
        if (param.multiple) {
            return AJS.MacroBrowser.ParameterFields["string"](param, options);
        }

        var paramDiv = AJS.clone("#macro-param-select-template");
        var input = $("select", paramDiv);
        if (!(param.required || param.defaultValue)) {
            input.append("<option value=''> </option>");
        }
        $(param.enumValues).each(function() {
            input.append("<option value='" + this + "'>" + this + "</option>");
        });

        return AJS.MacroBrowser.Field(paramDiv, input, options);
    }
    
}; })(AJS.$);

AJS.MacroBrowser.Macros = {};