var MenuBuilder = (function()
{
	var _menu = null;
	
	function _init(config)
	{
		var url = config.jsonUrl; // Path to the json to
		_menu = $(config.container); // Container (ul) to place the menu
		
		_load(url); // Ajax load - end of init
	};
	
	function _load(url)
	{
		$.ajax ({
			type: "GET",
			url: url,
			dataType: "json",
			success: function(data) 
			{
				var data = data.menu;
				_createMenu(data);
			},
			error: function(req, status, err)
			{
				console.log("Error loading slideshow: " + err);
			}
		});
	};
	
	function _createMenu(menu)
	{
		$.each(menu, function(idx, menuItem)
		{
			var li = _buildFirstLevel(menuItem);
			_menu.append(li);
		});
		NavControl.init(_menu);
	};
	
	function _buildFirstLevel(menuItem)
	{
		var li = $('<li />'),
			anchor = $('<a />');
		
		var link = menuItem.name,
			href = menuItem.url,
			subMenu = menuItem.subMenu;
			
		li.append(anchor);
			anchor.append(link);
			anchor.attr('href', href);

		// If the submenu is not undefined, then we're creating nested menus
		if (!(subMenu == undefined)) 
		{ 
			li.append(_createSubMenu(subMenu)); 
		}
		
		// Return the first level li (and any second and third levels to be appended
		return li;
	};
	
	function _createSubMenu(menu)
	{
		var secondLevel = $('<ul />');
		$.each(menu, function(idx, menuItem)
		{
			secondLevel.append(_buildSecondLevel(menuItem));
		});
		return secondLevel;
	};
	
	function _buildSecondLevel(menuItem)
	{
		// HTML
		var li = $('<li />'),
			anchor = $('<a />');
		
		var link = menuItem.name,
			href = menuItem.url,
			subMenu = menuItem.subMenu;
			
		li.append(anchor);
			anchor.append(link);
			anchor.attr('href', href);
		
		// If the submenu is not undefined, then we're creating nested menus
		if (!(subMenu == undefined)) 
		{ 
			li.append(_createSubSubMenu(subMenu));
		}
		return li;
	};
	
	function _createSubSubMenu(menu)
	{
		var thirdLevel = $('<ul />');
		$.each(menu, function(idx, menuItem)
		{
			thirdLevel.append(_buildThirdLevel(menuItem));
		});
		return thirdLevel;
	};
	
	function _buildThirdLevel(menuItem)
	{
		var li = $('<li />'),
			anchor = $('<a />');
		
		var link = menuItem.name,
			href = menuItem.url,
			subMenu = menuItem.subMenu;
			
		li.append(anchor);
			anchor.append(link);
			anchor.attr('href', href);
		return li;
	};
	
	return {
		init: _init
	};
})();

// Nav Control
var NavControl = (function()
{
	function _init(nav)
	{
		_levels(nav);
	};
	
	function _levels(nav)
	{
		var li = nav.find('li');
		var ul = li.children('ul');
		
		ul.hide();
		li.hover(function() 
		{
			$(this).children('a').addClass('Hover');
			$(this).find('> ul').stop(true, true).slideDown(250);
		}, 
		function() 
		{
			$(this).children('a').removeClass('Hover');
			$(this).find('> ul').stop(true, true).hide();       
		});
	};
	
	return {
		init: _init
	};
})();
