(function () {
    var S = {
        defaults: {
            absolutePosition: false
        },

        getDefaults: function () {
            for (key in S.defaults) {
                if (!S[key]) {
                    S[key] = S.defaults[key];
                    if (S.options && S.options[key]) S[key] = S.options[key];
                }
            }
        },

        autoWidth: function (event) {
            myE = event || window.event;
            if (!this.isOpen) this.selectedIndex = Math.max(0, this.selectedIndex);
            this.style.width = "auto";
            if (myE.type == "mousedown" && !this.isOpen) this.focus();
            this.isOpen = true;
        },

        staticWidth: function (event) {
            myE = event || window.event;
            if (this.selectedIndex == this.myIndex && myE.type == "change") {
                this.selectedIndex = Math.max(0, this.selectedIndex);
            } else {
                this.style.width = this.w;
                this.isOpen = false;
            }
            this.myIndex = this.selectedIndex;
        },

        initSelectFix: function () {
            S.getDefaults();
            var mySelects = document.getElementsByTagName("select");
            for (var x = 0, mySelect; mySelect = mySelects[x]; x++) {
                mySelect.w = mySelect.offsetWidth;
                mySelect.parW = mySelect.parentNode.offsetWidth;
                mySelect.parH = mySelect.parentNode.offsetHeight;
                mySelect.style.width = "auto";
                afterW = mySelect.offsetWidth;
                if (mySelect.style.display == 'none') { mySelect.w = mySelect.parW; afterW = mySelect.w + 1; }                
                mySelect.style.width = mySelect.w;
                if (mySelect.w < afterW) {
                    mySelect.onmousedown = S.autoWidth;
                    mySelect.onfocus = S.autoWidth;
                    mySelect.onblur = S.staticWidth;
                    mySelect.onchange = S.staticWidth;

                    mySelect.isOpen = false;
                    mySelect.myIndex = -1;

                    if (S.absolutePosition) {
                        mySelect.style.position = "absolute";
                        mySelect.parentNode.style.position = "relative";
                        mySelect.parentNode.style.width = mySelect.parW;
                        mySelect.parentNode.style.height = mySelect.parH;
                    }
                }

            }
        },

        init: function () {
            /* IE only -- so just attachEvent */
            if (window.attachEvent && !window.opera) window.attachEvent("onload", this.initSelectFix);
        }
    }

    window['selectFix'] = S;
})();

selectFix.init();
