/**
 * Global js - toc:
 *
 * 00: General listeners
 * 01: Megamenu setup
 * 02: Pagination sort form control enhancement
 * 03: News Results Menu
 * 04: Trade checkout-specific
 * 05: stupid last minute hack for 'latest news' tabs required because previous developers were nincompoops and I have no time to create something more robust
 * 06: Homepage Image Rotator
 */

$(document).ready(function()
{
/**
 * 00: General listeners
 */
	$("body").addClass("js-enabled");


/**
 * 01: Megamenu setup
 */
	// grab megamenu elements
	var $menuEls = $('#navigation .submenu');
	$("ul li").removeClass("selected");

	$menuEls.each(function(i)
	{
		// first li's on megamenu are selected on rollover
		// (this will occur before IE6 iframe script, enabling iframe measurement)
		$(this).css('display', 'block');

		// over/out adds/removes class of .over here: #navigation > li upon hover (class shifts both submenu div and iframe (ie6))
		var menuOpt = $(this).find("ul.menu_opt li");
		var menuProd = $(this).find("ul.products li");
		var menuClass = $(this).find("ul li").attr("class");

		menuOpt.each(function(i)
		{
			var menuClass = $(this).attr("class");

			$(this).hover(function()
			{
				$(this).addClass('selected');
				$(this).parent().parent().find("ul li").removeClass("selected");
				$(this).parent().parent().find('ul li.'+menuClass+'').addClass("selected");
			});
		});

		$(this).parents('li').hover(function()
		{
			$(this).addClass('over');
			$("ul.menu_opt li:first-child").addClass("selected");
			$("ul.products li:first-child").addClass("selected");
		},
		function()
		{
			$(this).removeClass('over');
			$("ul li").removeClass("selected");
		});

		// keyboard handling (tabbing)
		// top level link (ie womens) - on focus, show menu, on shift-tab (backwards) hide menu
		$(this).parents('li').find('.top_level').keyup(function(event)
		{
			if (event.keyCode == 9 && document.shiftDown === true)
				$(this).parents('li').removeClass('over');
		});

		// all links within menu upon focus, show the menu (catches mouse-out followed by keyboard tabbing if focus is still within menu)
		$(this).find('a').keyup(function(event)
		{
			if (event.keyCode == 9)
				$(this).parents('.submenu').parents('li').addClass('over');
		});

		// last occuring link within a menu on tab-out, hide the menu
		$(this).find('a:last').keydown(function(event)
		{
			if (event.keyCode == 9 && document.shiftDown !== true)
				$(this).parents('.submenu').parents('li').removeClass('over');
		});

		// first occuring link within a menu on shift-tab-out, hide the menu
		$(this).find('a:first').keydown(function(event)
		{
			if (event.keyCode == 9 && document.shiftDown === true)
				$(this).parents('.submenu').parents('li').removeClass('over');
		});
	});

	// Menu Widget Variables
	var $keyLink = $('div#widget_key ul li');
	var $key = $('div#key');
	var $keyMenu = $('div#key div.key_layout');
	var $keyAge = $('div.prod_key,div.prod_key_zoom');
	var $keyZoom = $('div#key.key_zoom');
	var $prodImg = $('div.prod_img img');
	var $zoomImg = $('div#prod_zoom img');

	// Add an event on the menu widget li's
	$keyLink.each(function(i)
	{
		var keyClass = $(this).attr('class');
		var keyClassLen = keyClass.length;
		var keyVal = keyClass.slice(4, keyClassLen);
		var keyWidget = $("ul.key_widget li").length;

		$(this).hover(function()
		{
			$keyMenu.find("li").removeClass("highlight");
			$key.addClass('show');

			// Using classnames on rollover add the hightlight state
			$keyMenu.find('"#'+keyVal+'"').addClass("highlight");

			// Work out how many items in the widget and change the position accordingly
			switch (keyWidget)
			{
				case 2:
					 $keyZoom.css('left', '388px');
					 break;
				case 3:
					$keyZoom.css('left', '366px');
					break;
				case 4:
					$keyZoom.css('left', '414px');
					break;
				default: keyWidget =  $keyZoom.css('left', '318px');
			}
		},
		function()
		{
			$keyMenu.find('"#'+keyVal+'"').removeClass("highlight");
			var $menuLi = $keyMenu.find("li");

			if(!$menuLi.hasClass('highlight'))
				$keyMenu.find('"#'+ keyVal +'"').addClass("highlight");
			else
				$menuLi.removeClass('highlight');
		});

		// HiJack the menu links and update the main image based on this link
		$keyLink.find("a").each(function(i)
		{
			$(this).click(function()
			{
				var keyImg = $(this).attr("href");
				var keyId = $(this).parent().attr("id");

				if($(this).attr("id") == "tab_zoom")
				{
					$("#prod_zoom").css("display", "block");
					$(".prod_img").css("display", "none");
				}
				else
				{
					$("#prod_zoom").css("display", "none");
					$(".prod_img").css("display", "block");
				}

				$prodImg.attr("src", keyImg);

				if($(this).parents().attr("id") == "front")
				{
					imgZoo = "/images/products/1003292/1003292_front_1068_968.jpg";
					$("a#tab_zoom").attr("href", imgZoo);
					$zoomImg.attr("src", imgZoo);
				}

				if($(this).parents().attr("id") == "contents")
				{
					// alert("contentImg")
					imgZoo = "/images/products/1003292/1003292_contents_1068_968.jpg";
					$("a#tab_zoom").attr("href", imgZoo);
					$zoomImg.attr("src", imgZoo);
				}

				return false;
			});
		});

		// When the mouseleaves the menu area hide it from the user
		$keyAge.mouseleave(function()
		{
			$key.removeClass('show');
		});
	});

/**
 * 02: Pagination sort form control enhancement
 */
	$('#listing_sort')
		.find('select').change(function()
		{
			$(this).parent().submit();
		})
		.end()
		.find('input').click(function()
		{
			$(this).parents('form').submit();
		})
		.end()
		.find('button, label:not(#stock_display_toggle)')
		.css('display', 'none');

/**
 * 03: News Results Menu
 */
	var $newsMenu = $('.news_menu > ul > li > a');
	$newsMenu.each(function()
	{
		$(this).click(function(e)
		{
			var target;

			if ($(this).parent("li").hasClass("view_all"))
				target = $newsMenu;
			else
				target = $(this);

			target.parent("li").toggleClass('menu_open');

			return false;
		 });
	});

/**
 * 04: Trade checkout-specific
 */
	if ($('#cal_container').length > 0)
	{
		$( "#cal_container" ).datepicker({
			beforeShowDay: $.datepicker.noWeekends,
			altField: '#preferredDeliveryDate',
			dateFormat: 'yy-mm-dd',
			minDate: 0
		});
		$("#preferredDeliveryDate" ).attr("tabindex", "-1");
	}

	if ($('#orderUpdate .dem-scroller').length > 0)
		DEMOTIVE.scroller.init($('#orderUpdate .dem-scroller'), {scrollStyle:'unit', speed:500, behaviour:'fixed', direction:'vertical'});

/**
 * 05: stupid last minute hack for 'latest news' tabs required because previous developers were nincompoops and I have no time to create something more robust
 */
	if ($('#new_in').hasClass('over'))
		$('.new-in').show();
	else
		$('.new-in').hide();

	if ($('#best_sellers').hasClass('over'))
		$('.bestsellers').show();
	else
		$('.bestsellers').hide();

	$('#new_in a').live('click', function(e)
	{
		e.preventDefault();
		if ($('#best_sellers').hasClass('over'))
			$('#best_sellers').removeClass('over');

		$('#new_in').addClass('over');
		$('.bestsellers').hide();
		$('.new-in').show();
	});

	$('#best_sellers a').live('click', function(e)
	{
		e.preventDefault();
		if ($('#new_in').hasClass('over'))
			$('#new_in').removeClass('over');

		$('#best_sellers').addClass('over');
		$('.new-in').hide();
		$('.bestsellers').show();
	});

});

/**
 * 06: Homepage Image Rotator
 */
 /*
function slideShow()
{
	// Set the opacity of all images to 0
	$('#hero li:not(:first-child)').css({opacity: 0});

	// Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
	setInterval('gallery()', 6000);
}

function gallery()
{
	// if no IMGs have the show class, grab the first image
	var currentImg = ($('#hero ul li.show') ?  $('#hero ul li.show') : $('#hero ul li:first'));
	var currentOrd = ($('#hero ol li.show') ?  $('#hero ol li.show') : $('#hero ol li:first'));

	// Get next image, if it reached the end of the slideshow, rotate it back to the first image
	var nextImg =  ((currentImg.next().length) ? ((currentImg.next().hasClass('imgSel')) ? $('#hero ul li:first'):currentImg.next()) : $('#hero ul li:first'));

	// Get next image indicator, if it reached the end of the slideshow, rotate it back to the first image indicator
	var nextOrd =  ((currentOrd.next().length) ? ((currentOrd.next().hasClass('imgSel')) ? $('#hero ol li:first'):currentOrd.next()) : $('#hero ol li:first'));

	// Set the fade in effect for the next image, show class has higher z-index
	nextImg.css({opacity: 0}).addClass('show').animate({opacity: 1}, 1000);

	// Set the fade in effect for the next image indicator, show class has higher z-index
	nextOrd.css({opacity: 0}).addClass('show').animate({opacity: 1}, 1000);

	// Hide the currentImg image
	currentImg.animate({opacity: 0}, 1000).removeClass('show');
	currentOrd.animate({opacity: 0}, 1000).removeClass('show');
}
document.createElement('abbr');
*/

/*
	Image fader
*/

function slideShow()
{
	var images = $('#hero li'),
	//Interval
	interval = 6000,
	//Crossfade
	fade_time = 1000,
	//Length of images
	total_images = images.length,
	//Current image
	current_image = 0;

	// Hide all images except first
	images.not( images.eq(0) ).css('display', 'none');


	var infinite_loop = setInterval(function() {

		images.eq(current_image).fadeOut(fade_time);

		if(current_image == total_images -1) {
			current_image = 0;
		}else{
			current_image++;
		}

		images.eq(current_image).fadeIn(fade_time);

	}, interval);
}
