$(function(){
    
    // set-up
    
    var form = $('#product_finder').addClass('on'),
        select = form.find('select').change(selectChoose),
        pleaseChoose = select.find('option:first').remove(),
        data = [loadData()], 
        currentDepth = 0, 
        radios = [], 
        radioIndices = {channel:0, brand:1, section:2};
    
    for(var id in radioIndices){
        var radio = $('<input type="radio" id="' + id + '" name="level"/>').click(radioClick);
        select.before(radio).before('<label for="' + id + '">' + id + '</label>');
        radios[radioIndices[id]] = radio;
    }
   
    update();
    
    
    // functions
    
    function selectChoose(){
        
        var index = select.attr('selectedIndex') - 1;
        
        if(index > -1){
            
            var option = data[currentDepth][index];
            
            if(currentDepth == 2){
                window.location.href = option.val();
            }else{
                data[++currentDepth] = option.children;
                update();
            }
        }
    }
    
    function radioClick(){
     
        var element = $(this);
        var depth = radioIndices[element.attr('id')];
        
        if(depth < currentDepth){
            currentDepth = depth;
            update();
        }
    }
    
    function update(){
        
        for(var r in radios){
            
            if(r < currentDepth){
                radios[r].removeAttr('disabled').removeAttr('checked');
            }else if(r == currentDepth){
                radios[r].removeAttr('disabled').attr('checked', true);
            }else{
                radios[r].attr('disabled', true).removeAttr('checked');
            }
        }
        
        pleaseChoose.text('Please choose ' + radios[currentDepth].attr('id') + ' ...');
            
        select.empty().append(pleaseChoose);
        
        for(var o in data[currentDepth]){
            select.append(data[currentDepth][o]);
        }
        
        select.attr('selectedIndex', 0);
    }
    
    function loadData(){
    
        var options = [[]], level = 0, lastLevel = 0, parent;

        select.find('option').each(function(){
            
            var element = $(this), title = element.html(), index = title.lastIndexOf('&nbsp;');
            
            index = index < 0 ? 0 : index + 6;
            level = index / 36;
            
            if(level != lastLevel){
                
                if(level > lastLevel){
                    options[level] = parent.children = [];
                }
                
                lastLevel = level;
            }

            parent = element;
            
            title = title.substring(index);
            element.html(title);
            
            options[level].push(element);       
        });
        
        return options[0];
    }
    
});
