/* Re-stack some layout blocks as required: */
Initialiser.modules.layout = function(){

	/* Enhance price values by super-scripting the cents */
	$('span.amount, td.amount', '#pagebody').each(function(){
		var value = $(this).html(),
			 centsModifier = value.match(/\.00$/) ? 'zero' : '';
		$(this).html(value.replace(/(\.\d+)/g, '<sup class="cents ' + centsModifier + '">$1</sup>'));
	});

/* -------------------------------------------------------------------------
	 Adjustments on product lister pages: */
	
	if ($('#productList').length) {
		/* Move the title and breadcrumb out of the main box on product listers */
		$('#breadcrumb, #messageerror, #maincontent > h1', 'body.browse').prependTo('#pagebody');
		
		$('#productList').equalHeights();
	}
	
/* -------------------------------------------------------------------------
		 Adjustments on category lister pages: */
	
	if ($('#categorylister').length) {
		/* Move the title and breadcrumb out of the main box on product listers */
		$('#breadcrumb, #messageerror, #maincontent > h1', 'body.browse').prependTo('#pagebody');
	}

/* -------------------------------------------------------------------------
	 Adjustments on product detail pages: */

	if ($('#OrderItemAddForm').length) {
		var $productDetail = $('#OrderItemAddForm');
		
		/* Move the product name inside the detail container on product detail pages */
		//$('#productName', $productDetail).prependTo('#OrderItemAddForm div.detailsdisplay');
		
		//$('#productcode').insertAfter('#productDescriptivePanel')
		
		//$('#maincontent, #filters', 'body.browse').wrapAll('<div class="browseWrapper wrapper"></div>');
		
		if ($productDetail.not('.unavailable, .regionalUnavailable').length) {
		
			var purchaseComponent = $('#productPurchaseDetails'),
				 addToCartComponents = $('li.addToCartComponent', purchaseComponent);
		
			var helperPromptTexts = ['First', 'Next', 'Now', 'Now'];
		
			var blankSelection = true; //Flag if no attributes have been selected.
		
			var minimumPrices = {};
				 $(map.array).each(function(){ //Loop through the prices map, grouping on each attribute's common values, saving the lowest price from each group
					group = this.key.split('_')[0];
					price = this.value.price.nowPrice.replace(/[^0-9\.]/g, '')
					if (minimumPrices[group]) {
						if (price < minimumPrices[group]) minimumPrices[group] = price;
					} else {
						minimumPrices[group] = price;
					}
				 });
		
			//Bind a custom event handler to the attribute selectors, so we can force them to be selected in sequence:
			var cartComponents = $('li.addToCartComponent:visible', purchaseComponent),
				 addToCartHelpers;
		
			cartComponents
				.addClass('unselectable')
				.bind('select', function(){
				
					var component = this,
					index = addToCartComponents.index(component); //Find which group has been selected
				
					if (!$(component).is('.selected')) {
				
						addToCartHelpers.fadeOut(200);  //Hide any helpers that are showing:
					
						$(component).addClass('selected');
					
							var nextComponent = addToCartComponents.eq(index).next()
						 		 nextComponent = nextComponent.is('.attribute') ? nextComponent : nextComponent.nextAll().andSelf(); //If we're at the last attribute, enable all the following purchase components.
								 //Allow the next group to be selected
							
								if (!$(nextComponent).is('.selected')) {
									 nextComponent	
										.removeClass('unselectable')
										.addClass('selectable')
										.find('div.helperPrompt').css({opacity: 0, display: 'block'}).animate({opacity: 1, right: '-60px'}, 100); //Show the specific helper for this attribute
								
										blankSelection = false;
								} else {
									nextComponent.trigger('select');
								}
						}
				})
				.each(function(i, e){
					$(this).append('<div class="helperPrompt"><span>' + helperPromptTexts[i] + '</span></div>');
					 addToCartHelpers = $('div.helperPrompt', addToCartComponents);
				})
				.expandSelect({
					readOnly: purchaseComponent.is('.unAvailable'),
					sequenced: true
					}
				)
				.find('select.attributeSelector').change(function(){
				
					var selector = this,
						 selectedAttName = $(this).val(), 
						 attributeGroup = $(selector).closest('.attribute'),
						 priceDisplayElement = $('#priceelement li.productDetailPurchasePrice');
				
						priceDisplayElement.fadeOut(250, function(){
					
						var fullPriceDefined = switchSkuSettings(document.OrderItemAddForm, selector, '', selector.id.replace(/\D/g,'')); //We retrieve the numeric index which is appended to the ID:
					
						//Check if any of the following attributes are selected (since we do non-linear select now):
						var followingSelectors = attributeGroup.nextAll('.attribute.selectable');
							 if (followingSelectors.find('input:checked').length) {
								followingSelectors.find('select').each(function(){
								
									$(this).trigger('refresh');
									fullPriceDefined = switchSkuSettings(document.OrderItemAddForm, this, '', this.id.replace(/\D/g,'')); //We retrieve the numeric index which is appended to the ID:
							
								});
							 }
					
						//The price is re-written by switchSkuSettings, so refresh:
						priceDisplayElement = $('#priceelement li.productDetailPurchasePrice');
					
						//Initialise the price display element if required:
						if (!priceDisplayElement.length) {
							$('#priceelement').append('<ul><li class="productDetailPurchasePrice"><span class="label"></span><span class="amount"></span></li></ul>');
							priceDisplayElement = $('#priceelement li.productDetailPurchasePrice');
						}
					
						var priceLabel, priceValue;
					
						if (fullPriceDefined) {
						
							priceLabel = [];
							$('li.selectOption.selected label', $productDetail).each(function(i){
								priceLabel.push($(this).text());
							});
							priceLabel = priceLabel.join(', ');
					
							priceDisplayElement
								.children('.label').html(priceLabel);
			
							$('#addToCartForm')
								.removeClass('unselectable')
								.addClass('selectable')
								.find('div.helperPrompt')
									.css({opacity: 0, displaycoh: 'block'})
									.animate({opacity: 1, right: '-60px'}, 100);
								
						} else {
							priceLabel = selectedAttName + ' starts at';
						
							var centsModifier = minimumPrices[selectedAttName].match(/\.00$/) ? 'zero' : '';
						
							priceValue = '$' + minimumPrices[selectedAttName].replace(/(\.\d+)/g, '<sup class="cents ' + centsModifier + '">$1</sup>');
						
							priceDisplayElement
								.children('.label').html(priceLabel)
							.end()
								.children('.amount').html(priceValue);
						
							$('#addToCartForm')
								.removeClass('selectable').addClass('unselectable');
							/*
							cartComponents.filter(':not(.quantitySelector)').filter('.selectable:last')
								.find('div.helperPrompt')
									.css({opacity: 0, display: 'block'})
									.animate({opacity: 1, right: '-60px'}, 100);		
							*/
						}	
						cartComponents.find('select').each(function(){
							$(this).trigger('refresh');
						})
						priceDisplayElement.fadeIn(250, 
							function(){
								if (jQuery.browser.msie) {
									this.style.removeAttribute('filter');
									this.style.removeAttribute('opacity');
								}
							});
				
					});
				
				})
				.end()
				.eq(0)
					.removeClass('unselectable')
					.addClass('selectable');
			
			/* Dynamic changes to the product attribute selectors: */
			if (blankSelection) {
				cartComponents.eq(0)
				.find('div.helperPrompt').animate({opacity:0}, 750, function(){
					$(this).css({opacity: 0, display: 'block'}).animate({opacity: 1, right: '-60px'}, 100);
				});
			} else {
				cartComponents.find('ol.selectGroup input[type=radio][checked=checked]').click();
			}

			//Initialise the price description if attributes are preselected:
			//$('input:radio:checked', $productDetail).change();
		
			//Number the addToCartComponents:
			$('ol.addToCartPanel > .addToCartComponent:not(.quantitySelector)', $productDetail).each(function(i){
				$(this).addClass('item_' + (i + 1));
			});		
		}
		
		$('#productDescriptivePanel').tabify();
		
		if (cartComponents) {
			var selectedAttributes = cartComponents.find('li.selectOption.selected');
		
			if (selectedAttributes.length && jQuery.browser.msie) {
				setTimeout("$('li.selectOption.selected', '#productPurchaseDetails').filter(':last').find('input').click()", 1000);
			}
		}
		
	}
	
	/* Quick hack on the mattress finder */
	
	if ($('#mattressFinder h2').length) {
		var mf = $('#mattressFinder');
			var titleText = $('#mattressFinder').find('h2').html();
			$('#mattressFinder').find('h2').html(titleText.replace('perfect', '<span>perfect</span>'));
	}
	
	/* Wrap the remaining contents in another box:*/
	$('#maincontent, #filters', 'body.browse').wrapAll('<div class="browseWrapper wrapper"></div>');
	$('#maincontent, #filters', 'body.search #outerwrap.results').wrapAll('<div class="browseWrapper wrapper"></div>');
	
	/* Move the footer to top level of the end of the document */
	$('#footer').appendTo('body').wrap('<div class="footerWrapper"></div>');
	
	/* Substitute fonts with Cufon: */
	Cufon.replace('#pagebody h1:first:not(#productName, #searchName, #categoryName), #productdetailscontainer div.alternativeproduct h2, #footer h2, #outerwrap.homepage h2, #pagebody > div.wrapper > h2, #mattressFinder h2, #basketStatusMessage h3, #basketStatusMessage h2');
};