var _selectOpen = null;

(function($){

    $.fn.selectreplace = function(o) {

        var opts = {
            returnfalse: true
        }
        
        if (o != null)
            $.extend(opts, o);
        this.each(function() {
            var select = $(this);
            select.css('display', 'none');
            
            
            var fs = $(
                '<div id="' + (((select.attr('id') == '') ? select.attr('class') : select.attr('id')) + '-replace') + '" class="form-select">\
                    <div class="actval"><span></span></div>\
                    <div class="replace"><ul></ul></div>\
                </div>') // overall element
            var optdiv = fs.find('.replace'); // holds the list
            var optlist = optdiv.find('ul'); // list for select options
            var actval = fs.find('.actval'); // holds the actual selected value
            var actvalspan = actval.find('span');
            
            if (!select.hasClass('duplicate-select'))
                $.select.generateOptionlist(select, fs, opts);
            
            if (actvalspan.text() == '') {
                actvalspan.text(select.children(':first').text());
                select.children(':first').attr('selected', 'selected');
            }
            $(document).click(function(e) {
                if(optdiv.css('display') == 'block')
                    actval.trigger('click');
            });
            
            actval.click(function (e) {
                e.stopPropagation();

                if (optdiv.css('display') == 'block') {
                    $(document).unbind('keydown');
                    optdiv.hide();
                    _selectOpen = null;
                    optdiv.find('.bar').css('top', 0);
                    optlist.css('top', 0);
                }
                else {
                    if (select.hasClass('duplicate-select') && optlist.children().length == 0) {
                        $.select.generateOptionlist(select, fs, opts);
                        try { optdiv.simplescroller(); } 
                        catch (e) { }
                    }
                    $(document).bind('keydown', function(e){
                        $.select.keyhandler(e, optlist);
                    });
                    if (_selectOpen != null)
                        _selectOpen.trigger('click');
                    _selectOpen = $(this);
                    optdiv.show();
                }
                
            });
            
            select.after(fs);
            if (!select.hasClass('duplicate-select')) {
                try { optdiv.simplescroller(); } 
                catch (e) { }
            }
        });
        
        return this;
    }
    
    $.select = function() { }
    
    $.select.generateOptionlist = function(select, fs, opts) {
        var optdiv = fs.find('.replace');
        var optlist = optdiv.find('ul');
        var actval = fs.find('.actval');
        var actvalspan = actval.find('span');
        select.children('option').each(function() {
            var option = $(this);
            
            var txt = option.text().replace(/\*\*/, '<img src="/ecomaXL/pics/star_garantie.png" alt="Termingarantie" title="Termingarantie" width="15" height="15" />');
            
            var lia = $('<a href="' + option.val() + '" id="' + option.val() + '" class="' + option.attr('class') + '"' + (option.hasClass('external') ? ' target="_blank"' : '') + '>' + ((select.hasClass('trainingExams')) ? txt : option.text()) + '</a>')
                    .click(function() {
                        option.siblings(':selected').removeAttr('selected');
                        option.attr('selected', 'selected');
                        
                        actvalspan.text(option.text());
                        
                        if (select.hasClass('trainingExams'))
                            actvalspan.html(txt);
                        
                        if (optdiv.css('display') == 'block')
                            actval.trigger('click');
                        
                        if (select.attr('id') == 'thema' && select.siblings('#ort').length > 0) {
                            var href = $(this).attr('href').split('/');
                            href = parseInt(href[href.length - 1]);
                            var map = mapping[href];
                            var elems = $('#ort-replace .replace li');
                            elems.hide(0);
                            elems.find('#0').click().parent('li').show(0);
                            $(map).each(function() {
                                elems.find('#' + this).parent('li').show(0);
                            });
                            try {
                                $('#ort-replace .replace').simplescroller();
                            } catch(e) { }
                        }
                        return !opts.returnfalse;
                    });
            
            var optli = $('<li></li>').append(lia);
            
            if(option.attr('disabled'))
                optli.addClass('disabled');
            else {
                optli.mouseover(function(){
                    if ($(this).siblings('.hover').length > 0)
                        $(this).siblings('.hover').removeClass('hover');
                    $(this).addClass('hover');
                });
                optli.mouseout(function(){
                    $(this).removeClass('hover');
                });
            }
            
            optlist.append(optli);
        });
        
    }
    
    $.select.keyhandler = function(e, optlist) {
        e.stopPropagation();
        e.preventDefault();
        //alert(e.keyCode);
        
        if (65 <= e.keyCode && e.keyCode <= 90) {
            actElem = $.select.getElemByChar(e.keyCode, optlist);
            if (actElem == false)
                return;
            actElem.siblings('.hover').removeClass('hover');
            actElem.addClass('hover');
        }
        
        switch (e.keyCode) {
        
            case 13: // enter key
                if (optlist.find('.hover').length > 0)
                    optlist.find('.hover').find('a').trigger('click');
            break;
                
            case 27: // esc key
                actval.trigger('click');
            break;
                
            case 38: // arrow up key
                actElem = optlist.find('.hover');
                if (actElem.length == 0) 
                    actElem = optlist.children(':last');
                else {
                    actElem.removeClass('hover');
                    actElem = actElem.prev().length > 0 ? actElem.prev() : optlist.children(':last');
                }
                
                actElem = $.select.getPrevNonDisabled(actElem, optlist);
                actElem.addClass('hover');
            break;
                
            case 40: // arrow down key
                actElem = optlist.find('.hover');
                if (actElem.length == 0) 
                    actElem = optlist.children(':first');
                else {
                    actElem.removeClass('hover');
                    actElem = actElem.next().length > 0 ? actElem.next() : optlist.children(':first');
                }
                
                actElem = $.select.getNextNonDisabled(actElem, optlist);
                actElem.addClass('hover');
            break;
        }
        
        if (actElem != null && actElem != false) {
            var p = optlist.parent();
            
            bar = p.find('.bar');
            
            var mTop = (actElem.position().top + actElem.height() - p.height());
            var ntop = mTop * p.height() / optlist.outerHeight();
            
            if (ntop < 0) 
                ntop = 0;
            if (ntop + bar.height() > p.height()) 
                ntop = p.height() - bar.height();
            
            optlist.css('top', -ntop * (optlist.outerHeight() / p.height()));
            
            bar.css({
                top: ntop
            });

        }
        
        return false;
    }
    
    $.select.getElemByChar = function(key, optlist) {
        _elem = false;
        var _elems = Array();
        if (optlist.children('li.hover:not(.disabled)').length > 0 && optlist.children('li.hover:not(.disabled)').next().text().toLowerCase().charCodeAt(0) == key + 32) {
            _elem = optlist.children('li.hover:not(.disabled)').next();
        }
        else {
            optlist.children('li:not(.disabled)').each(function(){
                //console.log(($(this).text().toLowerCase().charCodeAt(0) == key + 32) + ' :: ' + $(this).text().toLowerCase().charCodeAt(0) + ' :: ' + (key + 32));
                if ($(this).text().toLowerCase().charCodeAt(0) == key + 32) 
                    if (_elem == false && !$(this).hasClass('hover')) 
                        _elem = $(this);
            });
        }
        return _elem;
    }
    
    $.select.getNextNonDisabled = function(elem, optlist) {
        while (elem.hasClass('disabled')) {
            if (elem.next().length == 0)
                elem = optlist.children(':first');
            else
                elem = elem.next();
        }
        return elem;
    }
    $.select.getPrevNonDisabled = function(elem, optlist) {
        while (elem.hasClass('disabled')) {
            if (elem.prev().length == 0)
                elem = optlist.children(':last');
            else
                elem = elem.prev();
        }
        return elem;
    }
    
    $.fn.simplescroller = function() {
        var $this = this;
        var bar = $this.find('div.bar');
        if (bar.length == 0) {
            bar = $('<div></div>').addClass('bar');
            $this.append(bar);
        }
        var uli = $this.find('ul');
        
        
        bar.show(0);
        $this.show(0);
        var h = $this.height() * $this.height() / uli.outerHeight();
        if (h < 10) h = 10;
        if (h > $this.height()) h = $this.height();
        bar.height(h).css({
            position: 'absolute',
            top: 0
        }).attr('sa', 0);
        if (uli.outerHeight() < $this.height()) {
            bar.hide(0);
        }
        $this.hide(0);
        uli.css({ position: 'relative', top: 0 });
        
        bar.mousedown(function(e) {
            $(document).mouseup(function() {
                $(document).unbind('mousemove').unbind('mouseup');
                return false;
            }).mousemove(function(e) {
                var ntop = 0;
                
                ntop = e.pageY - parseInt(bar.attr('sa')) - $this.position().top;
                if(ntop < 0)
                    ntop = 0;
                if (ntop + bar.height() > $this.height())
                    ntop = $this.height() - bar.height();
                
                uli.css('top', -ntop * (uli.outerHeight() / $this.height()));
                
                bar.css({
                    top: ntop
                });
            });
            bar.attr('sa', e.pageY - bar.offset().top);
            return false;
        });
        bar.click(function(e) { e.stopPropagation(); return false; });
        
        return this;
    }
    
})(jQuery)




