
(function ($)
{
	$.fn.scrollable = function()
	{
		return this.each(function()
		{
			var $this = $(this);
			var items = $this.find('.scroll-items');
			var itemsContainer = $this.find('.scroll-items-container');
			var scrollUpButton = $this.find('.scroll-up');
			var scrollDownButton = $this.find('.scroll-down');
			var currentPage = 0;
			var pageHeight = itemsContainer.height();
			itemsContainer.height(pageHeight); // Stop it shrinking if the last page is shorter
			var lastPage = Math.ceil(items.height() / pageHeight) - 1;
			
			if (!lastPage)
			{
				scrollUpButton.remove();
				scrollDownButton.remove();
				
				return;
			}
			
			// Scroll the items
			var setPage = function(i)
			{
				currentPage = i;
				
				scrollUpButton.toggleClass('disabled', !currentPage);
				scrollDownButton.toggleClass('disabled', (currentPage == lastPage));
				
				items.animate({marginTop: -pageHeight * currentPage});
			}
			
			setPage(0);
			
			// Scroll buttons
			scrollUpButton.click(function()
			{
				if ($(this).is('.disabled'))
					return;
				
				setPage(currentPage - 1);
			});
			
			scrollDownButton.click(function()
			{
				if ($(this).is('.disabled'))
					return;
				
				setPage(currentPage + 1);
			});
		});
	};
	
	productPopup = function(productId, colourId)
	{
		// Indexes into the product array
		var p = {
			name: 0,
			price: 1,
			discountPrice: 2,
			sizeGuide: 3,
			variations: 4
		};
		
		// Indexes into the variations arrays
		var v = {
			id: 0,
			stock: 1,
			sizeIndex: 2,
			colourId: 3,
			quantity: 4,
			img: 5
		};
		
		// Indexes into the colours array
		var c = {
			name: 0,
			image: 1
		};
		
		var product = products[productId];
		if (!product)
		{
			alert('Unknown product :' + productId);
			return;
		}
		// Set up the popup data
		$('#buy-popup-title').html(product[p.name]);
		if (product[p.sizeGuide])
			$('#buy-popup-size-guide').html(sizeGuides[product[p.sizeGuide]]);
		else
			$('#buy-popup-size-guide').html('');
		
		$('#buy-popup-colour-img').attr('src', ASSETS + '/images/0-0--BasicTPSwatch-name-' + colours[colourId][c.image] + '-size-18x18.gif');
		$('#buy-popup-colour').html(colours[colourId][c.name]);
		
		if (parseFloat(product[p.discountPrice]))
		{
			$('#buy-popup-price').html(currencySymbol + product[p.discountPrice]);
			$('#buy-popup-old-price').html(' was <span style="text-decoration: line-through;">' + currencySymbol + product[p.price] + '</span>');
			var percent = Math.round(100 - 100 / product[p.price] * product[p.discountPrice]);
			$('#buy-popup-offer').html(' Save ' + percent + '%');
		}
		else
		{
			$('#buy-popup-price').html(currencySymbol + product[p.price]);
			$('#buy-popup-old-price').html('');
			$('#buy-popup-offer').html('');
		}
		
		var sel = document.getElementById('buy-popup-size');
		var quantity = document.getElementById('buy-popup-quantity');
		sel.innerHTML = '';
		
		var image = productId;
		// Show sizes in order
		var selectedSize = ($('#category-sort select[name=size] :selected').val() || '').split('|')[0];
		var selectedIndex = 0;
		
		jQuery.each(sizes, function(sizeIndex, size)
		{
			for (var i = 0; i < product[p.variations].length; i++)
			{
				var variation = product[p.variations][i];
				
				if ((variation[v.colourId] != colourId) || (variation[v.sizeIndex] != sizeIndex))
					continue;
				
				if (typeof variation[v.img] != 'undefined')
					image = productId + '_' + variation[v.img];
				
				if (selectedSize == size)
					selectedIndex = sel.options.length;
				
				var stock = variation[v.stock];
				if (stock === 0)
					stock = 'Due in stock in a few days';
				else if (stock === 10)
					stock = '10+ in stock';
				else if (typeof stock === 'number')
					stock = stock + ' in stock';
				else
					stock = 'Due ' + stock;
				
				sel.options[sel.options.length] = new Option(size + ' (' + stock + ')', variation[v.id], false, false);
			}
		});
		
		sel.selectedIndex = selectedIndex;
		
		// Set the max buyable
		$(sel).change(function()
		{
			quantity.innerHTML = '';
			var variation;
			var variationId = $(sel).val();
			
			for (var i = 0; i < product[p.variations].length; i++)
			{
				if (product[p.variations][i][v.id] == variationId)
				{
					variation = product[p.variations][i];
					break;
				}
			}
			
			for (var i = 1; i <= variation[v.quantity]; i++)
				quantity.options[quantity.options.length] = new Option(i, i, false, false);
		}).change();
		
		$('#buy-popup-img').attr('src', ASSETS + '/images/0-' + image + '--BasicTP-size-140x187.jpg');
		
		// Display the popup
		$("#buy-popup").modal({close: ''});

		// Track that the user pressed 'buy'
		$.ajax({
			url: ROOT + '/track-ajax/', 
			data: { event: 'pressed_buy' }, 
			cache: false
			});
	}
	
	initProductTabs = function()
	{
		$('#features-tab').hide();
		$('#reviews-tab').hide();
	}
	
	hideProductTab = function(tab)
	{
		$('#' + tab + '-tab').hide();
		$('#' + tab + '-button').removeClass('product-tab-button-active');
	}
	
	showProductTab = function(tab)
	{
		if (tab != 'details')
			hideProductTab('details');

		if (tab != 'features')
			hideProductTab('features');
			
		if (tab != 'reviews')
			hideProductTab('reviews');

			
		$('#' + tab + '-tab').show();
		$('#' + tab + '-button').addClass('product-tab-button-active');
	}
	
	var bigImageInitialized = false;
	showBigImage = function(id)
	{
		var src = $.$$('#' + id).attr('src').replace(/\d+x\d+/, '421x572');
		var bigImage = $.$$('.big-image');
		var img = $.$$('.big-image-img');
		
		var closeImg = $.$$('.big-image-close').css('opacity', 0.6);
		
		if (!bigImageInitialized)
		{
			closeImg.hover(function()
			{
				$(this).stop().animate({opacity: 1}, {duration: 200});
			}, function()
			{
				$(this).stop().animate({opacity: 0.6});
			});
			
			bigImageInitialized = true;
			
			// Update the position of the close button so it stays on the screen
			// Use a timeout to allow the modal JS to run first
			$(window).resize(function()
			{
				setTimeout(function()
				{
					var container = $('#simplemodal-container');
					if (!container.length)
						return;
					
					var offset = parseInt(container.css('top'), 10);
					$.$$('.big-image-close').css('top', Math.max(0, -offset));
				}, 50);
			});
			
			bigImage.children().click(function() { $.modal.close(); return false; });
		}
		
		img.attr('src', ASSETS + '/generic/px.gif');
		setTimeout(function() { img.attr('src', src); }, 50);
		
		bigImage.eq(0).modal({close: ''});
		
		return false;
	}
	showModalVideo = function() {
	}
	
	/* Main Menu */
	
	initMainMenu = function()
	{
		$('#main-menu .mainMenu-level-1 > li ').each(function()
		{
			var elt = $(this);
			
			// Don't do anything for items with no sub-menu
			if (!elt.children('ul').length)
				return;
			
			// IE6 hack
			var maxWidth = 960; //$('#main-menu .mainMenu-level-1').width();
			var menuOffset = $('#main-menu .mainMenu-level-1').offset();
			
			// Let each submenu expand as wide as it wants to
			elt.children('ul').css('position', 'static').css('display', 'block').each(function()
			{
				var $this = $(this);
				$this.css('margin-left', -1000);
				
				var width = Math.min($this.width(), maxWidth);
				$this.data('width', width).css('display', 'none');
			});
			
			// Get the offset of each submenu container (<li>)
			elt.children('ul').each(function()
			{
				var $this = $(this);
				$this.data('offset', $this.parent().offset().left - menuOffset.left);
				
				$this.width($this.data('width'))
					.css('margin-left', 0)
					.css('display', 'none')
					.css('position', 'absolute');
			});
			
			// Shift the submenus left so they don't go off the screen
			elt.children('ul').each(function()
			{
				var $this = $(this);
				var width = $this.data('width');
				var offset = $this.data('offset');
				
				
				if (width + offset > maxWidth)
					$this.css('margin-left', -((width + offset) - maxWidth));
			});
			
			// Show the menu on mouseover
			elt.mouseover(function()
			{
				if (menuVisible)
				{
					if (menuVisible != this)
						nextMenu = this;
					else
						window.clearTimeout(menuTimers[elt.parent().attr('class')]);
				}
				else
				{
					elt.children('ul').css('display', 'block');
					menuVisible = this;
				}
				
			});
			
			// Hide the menu some time after mouseout
			elt.mouseleave(function()
			{
				if (menuVisible == this)
				{
					menuTimers[elt.parent().attr('class')] = window.setTimeout(function()
					{
						elt.children('ul').css('display', 'none');
						if (nextMenu)
						{
							$(nextMenu).children('ul').css('display', 'block');
							menuVisible = nextMenu;
							nextMenu = false;
						}
						else
						{
							menuVisible = false;
						}
					}, 250);
					
				}
				else
				{
					nextMenu = false;
				}
				
			});
		});
		
		var containerWidth = $('#main-menu').width();
	}
	
	scrollHomepageBrands = function()
	{
		if (typeof(homepageScrollSpeed) == 'undefined')
			homepageScrollSpeed = 0;
		
		var maxScrollSpeed = 5;
		
		if (homepageScrollInhibited)
		{
			homepageScrollSpeed /= 2;
			if (homepageScrollSpeed < 0.5)
				homepageScrollSpeed = 0;
		}
		else if (homepageScrollSpeed < maxScrollSpeed)
		{
			if (!homepageScrollSpeed)
			{
				homepageScrollSpeed = 0.5;
			}
			else
			{
				homepageScrollSpeed *= 2;
				if (homepageScrollSpeed > maxScrollSpeed)
					homepageScrollSpeed = maxScrollSpeed;
			}
		}
		
		var pos = parseFloat($.$$('#homepage-brands-container ul').css('left'));
		pos -= homepageScrollSpeed;
		
		var itemWidth = parseFloat($.$$('#homepage-brands-container ul li:first-child').css('width'));
		if (pos <= -itemWidth)
		{
			// Move the first item to last in the list
			$('#homepage-brands-container ul').append($('#homepage-brands-container ul li:first-child').remove());
			pos += itemWidth;
		}
		$('#homepage-brands-container ul').css('left', pos + 'px');
	}
	
	$(function()
	{
		// Newsletter signup link popup
		$('#newsletter-signup-link').click(function()
		{
			$('#newsletter-signup-popup').modal();
		});
		$('#newsletter-popup-close').click(function()
		{
			$.modal.close();
		});
		
		// Header links popup
		$('#header-links .header-links-list li').click(function()
		{
			var index = $(this).parent().find('li').index(this);
			$('#header-links div.header-links-popup').eq(index).modal();
		});
		
		// Close header links popups
		$('#header-links .header-links-popup-close').click(function()
		{
			$.modal.close();
		});
		
		// Hide the div containing info about terms and conditions
		$('#terms-and-conditions').hide();
		$('.header-links-popup .show-terms-conditions').click(function()
		{
			$('#terms-and-conditions').toggle(); // toggle it when the user clicks on more info
			return false;
		});
		
		// Hide the div containing information about club membership
		$('#club-information-box').hide();
		$('.header-links-popup .club-information').click(function()
		{
			$('#club-information-box').toggle(); // toggle it when the user clicks on more info
		});
		
		// Product video modal dialog popup
		/*$('#show-video-icon').click( function() {
			$('#product-video').modal({persist: false});
			return false;
		});
		
		$('#close-video-modal').click( function() {
			$.modal.close();
			return false;
		});*/
		
		
		// Remove imagelinks without links 
		$('#homepage-banners > img').remove();
		
		var banners = $('#homepage-banners a');
		var totalBanners = banners.length;
		var currentBanner = 0;
		
		if (totalBanners >= 2)
		{
			setInterval(function()
			{
				var nextBanner = currentBanner == totalBanners - 1 ? 0 : currentBanner + 1;
				
				banners.eq(currentBanner).fadeOut();
				banners.eq(nextBanner).fadeIn();
				
				currentBanner = nextBanner;
			}, 8000);
		}
		
		// Trustpilot popup
		$('#trustpilot-logo').click(function()
		{
			$('#trustpilot').modal();
		});
		
		// Change currency link / popup
		var hideChangeCurrencyTimer;
		$('#change-currency-link').click(function()
		{
			return false;
		});
		
		$('#change-currency-link, #change-currency').hover(function()
		{
			if (hideChangeCurrencyTimer)
			{
				clearTimeout(hideChangeCurrencyTimer);
				hideChangeCurrencyTimer = false;
			}
			
			$('#change-currency').slideDown();
			return false;
		}, function()
		{
			hideChangeCurrencyTimer = setTimeout(function()
			{
				$('#change-currency').slideUp();
			}, 1000);
		});
		
		// Product page scrolling thumbnails
		$('.product-image-thumbnails').scrollable();
		// Long sidebar images
		$('#sidebar-images').scrollable();
	});
	
	$(function()
	{
		// Update product page box heights
		// Make the pairs the same height
		var last;
		var productContainers = $('.product-container');
		productContainers.css('height', 'auto');
		productContainers.each(function(i)
		{
			var $this = $(this);
			
			var columns = 2;
			if ($this.hasClass('product-container-compact'))
				columns = 3;
			
			if (!(i % columns))
			{
				last = $this;
				return;
			}
			
			var height = Math.max(last.height(), $this.height());
			
			$this.height(height);
			last.height(height);
		});
	});

})(jQuery);

function updateDispatchTime()
{
	// This code assumes that the viewer is in the same time zone as the dispatch point
	// because there's no way to get the UTC offset of the dispatch point
	
	var date = new Date();
	
	// Dispatch times
	// 9am, 1pm, 3pm
	var dispatchTimes = [7, 11, 14, 16];
	var hour = date.getHours();
	var dispatchString;
	
	if (hour >= dispatchTimes[dispatchTimes.length - 1])
	{
		// Dispatch tomorrow
		dispatchString = dispatchTimes[0] + (dispatchTimes[0] < 12 ? 'am' : 'pm') + ' tomorrow';
	}
	else
	{
		// Dispatch later today
		var nextDispatchHour;
		
		for (var i = 0; i < dispatchTimes.length; i++)
		{
			if (hour < dispatchTimes[i])
			{
				nextDispatchHour = dispatchTimes[i];
				break;
			}
		}
		
		var nextDispatch = new Date(date.getFullYear(), date.getMonth(), date.getDate(), nextDispatchHour, 0, 0, 0);
		var dispatchDelta = nextDispatch.getTime() - date.getTime();
		
		// Get rid of milliseconds
		var dispatchDelta = Math.floor(dispatchDelta / 1000);
		
		var dispatchHours = Math.floor(dispatchDelta / (60 * 60));
		var dispatchMinutes = Math.floor(dispatchDelta / 60) % 60;
		
		if (dispatchHours == 0 && dispatchMinutes == 0)
			dispatchMinutes = 1;
		
		if (dispatchHours && dispatchMinutes < 10)
			dispatchMinutes = '0' + dispatchMinutes;
			
		dispatchString = dispatchMinutes + ' minute' + (dispatchMinutes != 1 ? 's' : '');
		
		if (dispatchHours)
			dispatchString = dispatchHours + ' hour' + (dispatchHours != 1 ? 's' : '') + ' ' + dispatchString;
	}
	
	jQuery('#buy-popup-dispatch-time, #dispatch-time').text(dispatchString);
}

jQuery('document').ready(initMainMenu);
jQuery(function() { 

	updateDispatchTime();
	setInterval('updateDispatchTime()', 1000 * 60);

	if (!jQuery('#homepage-brands-container').length)
		return;
	
	homepageScrollInhibited = false;
	
	jQuery('#homepage-brands-container').mouseenter(function() { homepageScrollInhibited = true; }).mouseleave(function() { homepageScrollInhibited = false; });
	
	setInterval('scrollHomepageBrands()', 50); 
	});
menuTimers = {}
nextMenu = false;		// The next menu to be shown after the current one disappears
menuVisible = false;	// The currently visible menu

