/**
 * @author Vitaly
 */

/**
 * Declare Public Variables
 */
var balloonOffset = 10;
var navTimeOut = 700;
var animationSpeed = 150;
/**
 * Declare Private Variables
 */
if (!window.currentSection) {
	var currentSection = '';
} else {
	var defaultNavItem = currentSection;
}
var currentSubNav = '';
var balloon;
var navTimer;

var sections = {
	'astareal-advantage' : [['Production', 'production.php'], ['Intellectual Property', 'intellectual-property.php']],
	'clinical-studies': [['Vision', 'vision.php'], ['Skin Health', 'skin-health.php'], ['Active Lifestyle', 'active-lifestyle.php']]
};

$(document).ready(
	function() {
		balloon = $('#main-nav-balloon');
		bindListeners();
		if (currentSection) {
			displaySubNavBalloon($('#main-nav a[href^=' + currentSection + ']'), currentSection);
		}
	}
);

function bindListeners() {
	$('#main-nav a').hover(function(/* Event */ e) {
		var elm = $(e.target);
			id = elm.attr('href').replace(/.php/i, '');
			if (sections[id]) {
				if (id !== currentSection) {
					currentSection = id;
					if (balloon.is(':visible')) {
						clearTimeout(navTimer);
						balloon.fadeOut(animationSpeed, function() {
							displaySubNavBalloon(elm, id);
						});
					} else {
						displaySubNavBalloon(elm, id);
					}
				} else {
					clearTimeout(navTimer);
				}
			}
	}, function(/* Event */ e) {
		clearTimeout(navTimer);
		if (defaultNavItem) {
			if (currentSection !== defaultNavItem) {
				navTimer = setTimeout(function() {
					balloon.fadeOut(animationSpeed, function() {
						currentSection = defaultNavItem;
						displaySubNavBalloon($('#main-nav a[href^=' + currentSection + ']'), currentSection);
					});
				}, navTimeOut);
			}
		} else {
			navTimer = setTimeout(function() {
				balloon.fadeOut(animationSpeed, function() {
					currentSection = '';
				});
			}, navTimeOut);
		}
	});
	balloon.mouseover(function(/* Event */ e) {
		if (navTimer) {
			clearTimeout(navTimer);
		}
	}).mouseout(function(/* Event */ e) {
		var elm = $(e.target);
		if (defaultNavItem) {
			if (currentSection !== defaultNavItem) {
				navTimer = setTimeout(function() {
					balloon.fadeOut(animationSpeed, function() {
						currentSection = defaultNavItem;
						displaySubNavBalloon($('#main-nav a[href^=' + currentSection + ']'), currentSection);
					});
				}, navTimeOut);
			}
		} else {
			navTimer = setTimeout(function() {
				balloon.fadeOut(animationSpeed, function() {
					currentSection = '';
				});
			}, navTimeOut);
		}
	});
}

function displaySubNavBalloon(elm, id) {
	var html = '';
	$.each(sections[id], function(index, item) {
		html += '<a href="' + item[1] + '">' + item[0] + '</a>';
	});
	balloon.children('.content').html(html);
	var top = elm.position().top + elm.height() + parseInt(elm.css('padding-top')) + balloonOffset;
	var left = elm.position().left - ((balloon.width() - elm.width()) / 2);
	balloon.css('top', top + 'px').css('left', left + 'px');
	balloon.fadeIn(animationSpeed);
}