/**
 * navigation.js
 * 
 * This handles navigation events
 *
 * WalkerBrosFitness (http://walkerbrosfitness.com)
 * Copyright 2011
 *
 * @author: Jim Forsyth (jim@bakedigital.com)
 *
**/

$(function() {
	/* Initiate submenus */
	init_nav_submenus();
});

function init_nav_submenus() {
	/* Check for any submenus that may exist! */
	$("[id^=submenu_]").each( function() {
		/* Collect info */
		var id = $(this).attr('id'); id = id.replace("submenu_","");
		/* Apply event to navigation item */
		$("#nav_"+id).mouseover( function() { show_nav_submenu(id) } )
	});
}

function show_nav_submenu(id) {
	/* Store original class */
	var original_class = $("#nav_"+id).attr('class');
	/* Update nav class */
	$("#nav_"+id).removeClass().addClass('sel');
	/* Calculate offset */
	var margin_left = $("#nav_"+id).offset().left - $("#header").offset().left - $("#header .logo").width();
	/* Adjust submenu position correctly */
	$("#submenu_"+id).css({ 'margin-left' : margin_left })
	/* Display submenu */
	$("#submenu_"+id).show();
	/* Check when mouse leaves target area */
	$('body').mousemove( function(evt) { check_nav_mouse_position(evt,id,original_class) } );
}

function check_nav_mouse_position(evt,id,original_class) {
	/* Store nav details */
	var nav = new Object(); nav_offset = $("#nav_"+id).offset();
	nav['x'] = nav_offset.left;
	nav['y'] = nav_offset.top; 
	nav['w'] = $("#nav_"+id).width(); 
	nav['h'] = $("#nav_"+id).height(); 
	/* Store navigation submenu details */
	var submenu = new Object();
	submenu['x'] = nav['x']; submenu['y'] = nav['y']+nav['h']; submenu['w'] = $("#submenu_"+id).width(); submenu['h'] = $("#submenu_"+id).height();
	/* Retrieve mouse position */
	var mouse_x = evt.pageX; var mouse_y = evt.pageY;
	/* Mouse tracking */
	if ( mouse_x >= nav['x'] && mouse_x <= nav['x']+nav['w'] && mouse_y >= nav['y'] && mouse_y <= nav['y']+nav['h'] ) {
		/* Still over navigation - do nothing */
	} else {
		if ( mouse_x >= submenu['x'] && mouse_x <= submenu['x']+submenu['w'] && mouse_y >= submenu['y'] && mouse_y <= submenu['y']+submenu['h']+8 ) {
			/* Still over submenu - do nothing */	
		} else {
			/* Out of bounds */
			$("#submenu_"+id).hide();
			$("#nav_"+id).removeClass().addClass(original_class);
			$('body').unbind('mousemove');
		}
	}
}
