$(function(){
	/*Prepare dropdown bloc*/
	dropdownholder = new $('<div/>').attr({
		'id' : 'dropdown-holder'
	});
	dropdown = new $('<div/>').attr({
		'id' : 'dropdown-nav',
		'class' : 'content-wrapper',
		'style' : 'display:none'
	});
	blocT = new $('<div/>').attr({'class' : 't'});
	blocM = new $('<div/>').attr({'class' : 'm'});
	blocB = new $('<div/>').attr({'class' : 'b'});
	dropdown.append(blocT);
	dropdown.append(blocM);
	dropdown.append(blocB);
	dropdownholder.append(dropdown);
	$('#main-nav').after(dropdownholder);
	closeIt = 0;
	openIt = Array();
	//$('#content').css('margin-top','0');
	/*functions*/
	$('.first-level > li > a').hover(
		function(e){ /*mouseover*/
			closeIt = 0;
			var link = $(this);
			var index = link.index('.first-level > li > a');
			if(!link.hasClass('hover')){
				openIt[index] = 1;
				setTimeout(function(){
					if(openIt[index] == 1){
						$('.first-level > li a.hover').removeClass('hover');
						link.addClass('hover');
						if(dropdown.css('display') == 'none'){
							
							if(link.siblings('.second-level').length > 0){
								blocM.html(link.siblings('.second-level').clone());
								$('.first-level > li.active').addClass('behind');
								dropdown.attr({'class' : 'content-wrapper'});
								dropdown.addClass('tab'+(link.parent('li').index('.first-level > li')+1));
								$('#content').css('margin-top','-3px');
								dropdown.slideDown('normal', function(){
									$('#content').css('margin-top',0);
								});
							}
						} else {
							$('#content').css('margin-top','-3px');
							dropdown.slideUp('normal', function(){
								if(link.siblings('.second-level').length > 0 && openIt[index] == 1){
									blocM.html(link.siblings('.second-level').clone());
									dropdown.attr({'class' : 'content-wrapper'});
									dropdown.addClass('tab'+(link.parent('li').index('.first-level > li')+1));
									dropdown.slideDown('normal', function(){
										$('#content').css('margin-top',0);
									});
								}
							});
						}
					}
				}, 350);
			} else{
				closeIt = 0;
			}
		}, function(){ /*mouseout*/
			var link = $(this);
			var index = link.index('.first-level > li > a');
			openIt[index] = 0;
			closeNav();
		}
	);
	$(dropdown).hover(
		function(){ /*mouseover*/
			closeIt = 0;
		},function(){ /*mouseout*/
			closeNav();
		}
	);
	function closeNav(){
		closeIt = 1;
		setTimeout(function(){
			if(closeIt == 1){
				$('.first-level > li a.hover').removeClass('hover');
				$('#content').css('margin-top','-3px');
				dropdown.slideUp('normal', function(){
					if(closeIt == 1){
						$('#content').css('margin-top',0);
						$('.first-level > li.behind').removeClass('behind');
					}
				});
			}
		}, 400);
	}
	
	$('a.back-history').click(function(){
		history.back();
		return false;
	});
});
