﻿(function ($) {

    var egSL_methods = {
        init: function (options) {
            thisSL = this;
            var data = thisSL.data("egSL");

            if (!data) {
                if (options) {
                    thisSL.extend(thisSL.settings, options);
                }

                thisSL.data("egSL", {
                    target: thisSL,
                    settings: thisSL.settings
                });
            }

            thisSL.css("display", "none");
            var select = $("<select><option value='" + this.settings['SelectText'] + "'>" + this.settings['SelectText'] + "</option></select>");
            thisSL.children('option').clone().appendTo(select);
            var ul = $("<ul style='list-style-type:none'></ul>");
            select.change(function () {
                var sel = $(this).val();
                if (!thisSL.children('option[value="' + sel + '"]').is(':selected')) {
                    thisSL.children('option[value="' + sel + '"]').attr("selected", "selected");
                    var del = $("<span class='ui-icon ui-icon-circle-close' style='display:inline-block;'></span>");
                    del.click(function () {
                        thisSL.children('option[value="' + sel + '"]').removeAttr("selected");
                        $(this).parents('li').remove();
                    });
                    var li = $("<li>" + sel + "</li>");
                    li.append(del);
                    ul.append(li);
                }
                $(this).children('option[value="' + sel + '"]').removeAttr("selected");
            });
            thisSL.after(select);
            select.after(ul);
            this.select = select;
            this.ul = ul;
        },
        destroy: function () {
            var thisSL = this;
            data = thisSL.data("thisSL");
            if (data) {

                thisSL.removeData("thisSL");
            }
        }
    }

    $.fn.egSelectList = function (method) {

        this.select = new Object;
        this.ul = new Object;
        this.settings = {
            'SelectText': 'Make a selection...'
        };
        if (egSL_methods[method]) {
            return egSL_methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {

            return egSL_methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on egSelectList');
        }

    }
})(jQuery);
