var activeElementIsHide = true;
var activeElementView = false;
var activeElement = false;

function selectCountry(){
	$('#country_menu').show();
}

function showMenu(object) {

	var menu = $('.menu');
	var menuPosition = menu.position();
	var menuEndPosition = menuPosition.left + menu.width();

	var child = object.children('ul');
	var parentPosition = object.position();
	var newChildPosition = 0;

	var childWidth = 0;

	child.css('display', 'block');	
	
	$(child).children('li').each(function(){
		childWidth  += ($(this).width()+20);
	});

	if ((parentPosition.left + childWidth) > menuEndPosition) {
		newChildPosition = menuEndPosition - childWidth - 6;
	} else {
		newChildPosition = parentPosition.left + 6;
	}
	

	child.css('left', newChildPosition + 'px');
}

function showActiveElement() {
	if (activeElementView) {
		if ($('.active').hasClass('hide_active')) {
			$('.active').removeClass('hide_active');
		}
		activeElementIsHide = false;
		activeElement.children('ul').css('display', 'block');
	}
}

$(document).ready(function() {

	if ($('.active').length) {
		activeElement = $('.active');
		activeElementView = true;
		activeElementIsHide = false;
		showMenu(activeElement);
	}

	$('#country_menu').hover(function(){}, function(){
		$(this).hide();
	});
	
	$('#zoom').hover(function() {
		
	}, function() {
		$(this).css('display:none;');
	});

	$('.menu_p ul li').hover(function() {
				
		$('#zoom').css('left', $(this).position().left + 'px');
		$('#zoom').css('top', $(this).position().top - 9 + 'px');
		$('#zoom').css('display', 'block');				
		$('#zoom').html($(this).html());

		$('#menu_p_image').attr('src', 'css/cs/splash/' + $(this).children().children().attr('name') + '.jpg');
		$('#menu_p_image').focus();
		
	}, function() {});

	$('.menu ul li').hover(function() {
		if (activeElementView && !activeElementIsHide && ($(this).parent().parent().hasClass('active') || $(this).hasClass('active'))) {
			return;
		}

		if (activeElement) {
			activeElementView = false;
			activeElementIsHide = true;
			activeElement.children('ul').css('display', 'none');
			$('.active').addClass('hide_active');
		}

		showMenu($(this));
	}, function() {

		if (activeElementView && ($(this).parent().parent().hasClass('active') || $(this).hasClass('active'))) {
			return;
		}

		$(this).children('ul').css('display', 'none');

		if (activeElement) {
			activeElementView = true;
			if (activeElementIsHide) {
				setTimeout("showActiveElement()", 500);
			} else {
				showActiveElement();
			}
		}
	});
});
