/*************************************************************************
* Basket Scripts                                                         *
*************************************************************************/

(function ($)
{
	/**
	 * Add a product to the basket
	 *
	 * This function uses an AJAX call to add the specified product option to the basket
	 *
	 * @param integer The product option ID
	 * @param integer The quantity.  Defaults to 1.
	 */
	basketAddProduct = function (productOptionId, quantity)
	{
		if (quantity === undefined)
			quantity = 1;
			
		
		// Display "loading..." div
		$.modal("<div><h1>Loading...</h1></div>");
		
		// Make AJAX request
		$.ajax({
			url: ROOT + '/basket-ajax/', 
			data: { action: 'add', poid: productOptionId, quantity: quantity }, 
			success: basketAddSuccess,
			error: basketAddError,
			cache: false,
			dataType: 'json'
			});
	}

	/**
	 * Remove a product from the basket
	 *
	 * This function uses an AJAX call to remove the specified product option from the basket
	 *
	 * @param integer The product option ID
	 * @param integer The quantity.  Defaults to 1.
	 */
	basketRemoveProduct = function (productOptionId, quantity)
	{
		if (quantity === undefined)
			quantity = 1;

		// Display "loading..." div
		$.modal("<div><h1>Loading...</h1></div>");
		
		// Make AJAX request
		$.ajax({
			url: ROOT + '/basket-ajax/', 
			data: { action: 'remove', poid: productOptionId, quantity: quantity }, 
			success: basketAddSuccess,
			error: basketAddError,
			cache: false,
			dataType: 'json'
			});
	}

	/**
	 * Add a discount voucher to the basket
	 *
	 * @param string The voucher code
	 */
	basketAddDiscountVoucher = function (code)
	{
	}
	
	/**
	 * AJAX callback if request succeeds
	 */
	basketAddSuccess = function (data)
	{
		// Hide "loading..." div
		$.modal.close();
		
		// Update basket contents
		$('#basket').html(data.basketHtml);
		
		// Show popup
		$('#basket-popup').html(data.popupHtml).fadeIn('def');
		window.setTimeout(function() { $('#basket-popup').fadeOut('def') }, 5000);
		
		// Track the event in google analytics
		pageTracker._trackPageview(ROOT + '/basket-ajax/');
	}
	
	/**
	 * AJAX callback if request fails
	 */
	basketAddError = function (request, textStatus, errorThrown)
	{
		// Hide "loading..." div
		$.modal.close();
		
		// Display error message
		$.modal("<div><h1>Failed to update basket: " + textStatus + "</h1><br><pre>" + request.responseText + "</pre></div>");
	}
	
	productPopup = function(productId, colourId)
	{
		var product = products[productId];
		if (!product)
		{
			alert('Unknown product :' + productId);
			return;
		}
		// Set up the popup data
		$('#buy-popup-title').html(product['name']);
		if (product['sizeGuide'])
			$('#buy-popup-size-guide').html(sizeGuides[product['sizeGuide']]);
		else
			$('#buy-popup-size-guide').html('');
		
		$('#buy-popup-colour-img').attr('src', ASSETS + '/images/0-0--BasicTPSwatch-name-' + colours[colourId]['name'].toLowerCase() + '.gif-size-18x18.gif');
		$('#buy-popup-colour').html(colours[colourId]['name']);
		if (product['discountPrice'])
		{
			$('#buy-popup-price').html('&pound;' + product['discountPrice']);
			$('#buy-popup-old-price').html(' was <span style="text-decoration: line-through;">&pound;' + product['price'] + '</span>');
			var percent = Math.round(100 - 100 / product['price'] * product['discountPrice']);
			$('#buy-popup-offer').html(' Save ' + percent + '%');
		}
		else
		{
			$('#buy-popup-price-line').html('&pound;' + product['price']);
		}
		
		
		
		var sel = document.getElementById('buy-popup-size');
		sel.innerHTML = '';
		
		var image = productId;
		jQuery.each(product['variations'], function (variationId, variation)
			{
				if (variation['c'] != colourId)
					return;
				
				if (typeof variation['i'] != 'undefined')
					image = productId + '_' + variation['i'];
				
				// Todo: select preferred size by default
				sel.options[sel.options.length] = new Option(sizes[variation['s']] + ' (' + variation['k'] + ')', variationId, false, false);
			}
			);
		
		$('#buy-popup-img').attr('src', ASSETS + '/images/0-' + image + '--BasicTP-size-130x176.jpg');
		
		// Display the popup
		$("#buy-popup").modal();
	}
	
	popupBuy = function()
	{
		var sizeSel = document.getElementById('buy-popup-size');
		var variationId = sizeSel.options[sizeSel.selectedIndex].value;
		var quantitySel = document.getElementById('buy-popup-quantity');
		var quantity = quantitySel.options[quantitySel.selectedIndex].value;

		$.modal.close();
		
		basketAddProduct(variationId, quantity);
		
		return false;
	}
	
	initProductTabs = function()
	{
		jQuery('#features-tab').hide();
		jQuery('#reviews-tab').hide();
	}
	
	hideProductTab = function(tab)
	{
		jQuery('#' + tab + '-tab').hide();
		jQuery('#' + 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');

			
		jQuery('#' + tab + '-tab').show();
		jQuery('#' + tab + '-button').addClass('product-tab-button-active');
	}
	
	showBigImage = function(id)
	{
		var src = jQuery.$$('#' + id).attr('src').replace(/\d+x\d+/, '421x572');
		var img = jQuery.$$('#big-image img');
		
		img.attr('src', ASSETS + '/generic/px.gif');
		setTimeout(function() { img.attr('src', src); }, 50);
		
		jQuery.$$('#big-image').modal();
		return false;
	}
	
	/* Main Menu */
	
	initMainMenu = function()
	{
		jQuery('#main-menu .mainMenu-level-1 > li ').each(function()
		{
			var elt = jQuery(this);
			
			// Don't do anything for items with no sub-menu
			if (!elt.children('ul').length)
				return;
			
			// IE6 hack
			var maxWidth = jQuery('#main-menu .mainMenu-level-1').width();
			var menuOffset = jQuery('#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 = jQuery(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 = jQuery(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 = jQuery(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)
						{
							jQuery(nextMenu).children('ul').css('display', 'block');
							menuVisible = nextMenu;
							nextMenu = false;
						}
						else
						{
							menuVisible = false;
						}
					}, 250);
					
				}
				else
				{
					nextMenu = false;
				}
				
			});
		});
		
		var containerWidth = jQuery('#main-menu').width();

		//alert(containerWidth);
		
		jQuery('#main-menu .mainMenu-level-2').each(function()
		{
			/*var elt = jQuery(this);
			var width = elt.width();
			var left = parseInt(elt.css('left'), 10);
			
			alert(elt.css('left'));
			
			alert('Width: ' + width + '\r\nLeft: ' + left);
			
			if (left + width > containerWidth)
				elt.css('left', containerWidth - width);*/
		});
	}

})(jQuery);

jQuery('document').ready(initMainMenu);
menuTimers = {}
nextMenu = false;		// The next menu to be shown after the current one disappears
menuVisible = false;	// The currently visible menu
