﻿jQuery.customSelect = {
    inputs: null,
    init: function(){
        jQuery.customSelect.inputs = $("select.custom");
        jQuery.customSelect.inputs.each(function(){            
            var obj = $(this);
            
            var s = jQuery.create("div", {"class":"select"})
                        .data("input", obj)
                        .css("width", obj.css("width"))
                        .html(obj.selectedOptions().html())
                        .bind("click", jQuery.customSelect.toggleOptions)
                        .appendTo(obj.parent());
            
            var opts = jQuery.create("div", {"class":"options"})
                            .css({
                                top:obj.position().top+21,
                                left:obj.position().left,
                                width:s.width() + 6
                            })
                            .appendTo("body");
                            
            s.data("opts", opts);
            
            $("option", obj).each(function(){
                var o = $(this);
                jQuery.create("a", {href:'#'})
                        .html(o.html())
                        .data("select", s)
                        .data("value", o.attr("value") ? o.attr("value") : o.html())
                        .bind("click", jQuery.customSelect.selectOpt)
                        .appendTo(opts);
            });
            
            obj.css({
                position: "absolute",
                top:-100,
                left:-100
            });           
            
        });              
    },
    toggleOptions: function(){        
        var obj = $(this).data("opts");
        $(".options").not(obj).hide();
        obj.toggle();
        
             
    },
    selectOpt: function(){
        var obj = $(this);
        var select = obj.data("select");
        var input = select.data("input");
        
        var oldValue = input.selectedValues();        
        
        input.selectOptions(obj.data("value"));
        
        select.html(input.selectedOptions().html());        
        obj.parent().hide();        
        
        if(input.attr("onchange") && oldValue != obj.data("value"))
            input.change();       
        
        return false;
    }
}

$().ready(function(){
    jQuery.customSelect.init();
});