﻿(function ($) {
    $.fn.CustomFieldDropDowns = function (settings) {

        var optionTag = '<option></option>';
        var config = $.extend({}, $.fn.CustomFieldDropDowns.defaults, settings);

        return this.each(function () {
            var $this = $(this);

            (function () {
                var methods = {
                    initialize: function () {
                        if ($this.children().size() != 0 && config.addPrompt) {
                            $this.prepend($(optionTag)
                            .attr("value", "")
                            .text(config.promptText));

                            $this.find('option:eq(1)').removeAttr('selected');
                            $this.find('option:eq(0)').attr('selected', 'selected');
                        }

                        if (config.autoSelectIfOne && $this.children().size() == 1)
                            $this.find('option:eq(0)').attr('selected', 'selected');
                        else if(config.autoSelectIfOne && config.addPrompt && $this.children().size() == 2)
                            $this.find('option:eq(1)').attr('selected', 'selected');
                    }
                };

                methods.initialize();

            })();
        });
    }

    $.fn.CustomFieldDropDowns.defaults = {
        promptText: '-- Select --',
        addPrompt: true,
        autoSelectIfOne: true
    }
})(jQuery);
