$(document).ready(function(){
	
	// Main menu: Fix
	
	$('#main-menu li ul').css('display','block'); // in css: d:n to polish rendering
	
	$('#main-menu > ul > li > ul')
		.wrap('<div class="level2"></div>')
		.find('li:first-child')
			.addClass('first')
			.end()
		.find('> li > ul')
			.wrap('<div class="level3"></div>');


});

// INIT
$(document).ready(function(){	
    

    // Drop down menu
    $('#main-menu').each(function(){
        var $menu = $(this),
            $li = $('li:has(>div)', this);

        $li.each(function(){
            var $box = $('>div', this),
                time = null; 
            
            if($box.is('.level3')){
                var par = $box.closest('.level2');
                $box.show();
                var w = par.width();
                var h = par.height();
                $box.hide();
            }
                        
            $(this).hover(
                function(){
                    $(this).addClass('hover');
                    if($box.is('.level2')){
                        time = clearTimeout(time);
                        $('.level2', $menu).stop().hide().css({'width':'', 'height':''});
                        $box.show();
                        $box.find('div').css('position', 'absolute');
                    }
                    else if($box.is('.level3')){
                        $('.level3', par).hide();
                        $box.show();
                        par.stop().animate({
                            'width': w + $box.width(),
                            'height': Math.max(h, $box.height()) + 10 +  $(this).position().top
                        }, 250);
                    }
                    else{
                        time = clearTimeout(time);
                        $('.level2', $menu).stop().hide().css({'width':'', 'height':''});
                        $box.show();
                    }  
                }, 
                function(){
                    $(this).removeClass('hover');
                    if($box.is('.level2')){
                        time = clearTimeout(time);
                        time = setTimeout(function(){ 
                            $box.stop().hide().css({'width':'', 'height':''});
                        }, 100) 
                    }
                    else{
                        $box.hide();
                        par.stop().animate({
                            'width': w,
                            'height': h
                        }, 250);
                        
                    } 
                }
            );    
        
        }); 
    });
       
    // SUGGEST
    var Suggest = function(element){
        this.arr = element.map(function(){
            return {
                text: this.text,
                search: this.text.toLowerCase(),
                url: this.value
            };
        }).get().sort();
    };
    
    Suggest.prototype.getList = function(search){
        var newArr = [];
        var re =  new RegExp("^"+search);
        
        for(var i = this.arr.length, j = 0; i--;){
            if(re.test(this.arr[j].search))
            {
                newArr.push(this.arr[j]);
            }
            j++;
        }  
        
        // GENERATE HTML FORM ARR
        var list = '';
        
        for(var i = newArr.length, j = 0; i--;){
            if(j==0){
                list = list + '<li class="first"><a href="'+newArr[j].url+'">'+newArr[j++].text+'</a></li>';
            }
            else{
                list = list + '<li><a href="'+newArr[j].url+'">'+newArr[j++].text+'</a></li>';
            }
        } 
        
        return list == '' ? '' : '<ul class="reset">'+ list + '</ul>';   
    };
    
    $('#search-box').each(function(){
        
        var $search = $(this),
            $box = $('.suggest-box', this),
            $input = $('#searchText', this).attr('autocomplete', 'off'),
            suggest = new Suggest($('#suggest-list option', this)),
            blur = true,
            val = null,
            timer = null,
            index = -1,
            size = 0;
        
        $input.bind('focus blur keydown test', function(e){
            
            switch(e.type){
                case 'focus' :
                    var $this = $(this);
                    $this.trigger('test'); 
                    timer = setTimeout(function(){
                        $this.trigger('test'); 
                        timer = setTimeout(arguments.callee, 400);
                    }, 400);
                    $box.show();
                    break;
                    
                case 'blur' :
                    
                    if(blur){
                        $box
                            .hide()
                            .find('li')
                                .removeClass('active')
                        index = -1;
                        timer = clearTimeout(timer);
                        $search.find(':submit:first').focus();
                    }
                    break;
                    
                case 'test' :
                    var actualVal = this.value.toLowerCase();
                    if(val !== actualVal){
                        val = actualVal;
                        if(actualVal){
                            list = suggest.getList(actualVal);
                            $box
                                .find('.reset')
                                    .remove()
                                    .end()
                                .prepend(list)
                            
                            size = $box.find('li').size();
                        }
                        else{
                            $box
                                .find('.reset')
                                    .remove();
                                    
                            size = 0;
                        }
                        index = -1;
                    }
                    break;  
                    
                case 'keydown' :
                    // press arrow down
                    if(e.keyCode == 40)
	        		{
	        		    var i = index;
	        		    
	        		    if (i == (size-1)){
                            i = -1;
                            $box.find('li').removeClass('active')
                        }
                        else{
                            i = (i == -1) ? 0 : i + 1;
                            $box.find('li').removeClass('active').eq(i).addClass('active');  
                        }

                        index = i; 
                        
                        return false;	
	        		}
	        		
	        		// press arrow up
	        		else if(e.keyCode == 38 )
	        		{
		        	    var i = index;

                        if (i == 0){
                            i = -1;
                            $box.find('li').removeClass('active')
                        }
                        else{
                            i = (i == -1) ? (size-1) : i - 1;
                            $box.find('li').removeClass('active').eq(i).addClass('active');  
                        }  
                        
                        index = i;
                        
                        return false;
		        	} 
		        	
		        	// press tab
		        	else if(e.keyCode == 9 && !blur){
                        blur = true;
                        $(this).trigger('blur');
                        return false;
                    }
		        	
		        	// press enter
		        	else if(e.keyCode == 13 && index != -1){
                        window.location = $box.find('li.active a').attr('href');
                        return false;
                    }
            } 
        });
        
        $box.bind('mouseover mouseenter mouseleave', function(e){
            switch(e.type){
                case 'mouseover' :
                    var li = $(e.target).closest('li');
                    if(li.size()){
                        var all = $box.find('li');
                        var i = all.index(li);
                        all.removeClass('active').eq(i).addClass('active');
                        index = i;
                    }
                    break;
                
                case 'mouseenter' :
                    blur = false;
                    break; 
                
                case 'mouseleave' :
                    blur = true;
                    break; 
            }
        });
    });
    

});
	
