/* 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) {
		$('#productList').equalHeights();
	}

/* -------------------------------------------------------------------------
		Adjustments on the homepage: */
/*
		if ($('#outerwrap.homepage').length) {
			
			//Display an animated pointer to highlight the mattress finder
			var $mattressFinderFirstStep = $('fieldset.item_1', '#ForwardMattressFinderForm');
			if ( $mattressFinderFirstStep.length) {
				
				 $mattressFinderFirstStep.append('<div id="startHerePointer">Start Here!</div>');

			    var $pointer = $('#startHerePointer').css({'top': '-90px', 'opacity': 0, 'display': 'block'});

			    $('body').one('mousemove', function(){
			        $pointer
							.pause(250)
							.animate({'top': '-50px', 'opacity': 100}, 500, 'easeOutElastic');
			    });
			}
			
		}*/

/* -------------------------------------------------------------------------
		 Adjustments on category lister pages: */
	
	

/* -------------------------------------------------------------------------
	 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, '');
				//	debugstr += this.key + ':' + this.value + ', '	
					if (group) {
						if (minimumPrices[group]) {						
							if (parseFloat(price) < parseFloat(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,
				mainImage = $('#mainimage'),
				imageContainer = $('#productimage'),
				largeImageLinks = $('#pdlargerimage, #pdlargerimagelink');
			
			//When the image finishes loading, remove its 'loading' flag	
			mainImage.bind('load', function(){
				imageContainer.removeClass('inProgress');
			});
		
			var	selectedAttributeNames = function() { 	//Loop through the selected attributes to create a string used to look up SKU pictures
					var valList = [];
					cartComponents.find('li.selectOption.selected input').each(function(){
						valList.push($(this).val());
					});
					return valList.join('_');
				},
				refreshProductImages = function() { //Update the images based on selected attr's if available
					var newImageSet = skuAlternativeImages.get(selectedAttributeNames());
					if (newImageSet) {

						//Add a 'loading' flag to the image container (setting on image directly doesn't work)
						imageContainer.addClass('inProgress');
						
						//Update the zoom links
						largeImageLinks.attr('href', newImageSet.hugeImage);
						
						//Set the new image src
						mainImage.attr('src', newImageSet.largeImage);
					}
				};
		
			cartComponents
				.addClass('unselectable').find('input[type=text]').attr('disabled', 'disabled').end()
				.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('input[type=text]').removeAttr('disabled').end()
										//.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('.quantitySelector input').bind('focus', function(){
				  //Only enable the quantity selector once a SKU is defined:
				  if ($(this).closest('.quantitySelector.unSelectable').length) {return false;}
				})
				.end()
				.find('select.attributeSelector').bind(($.browser.msie && $.browser.version < 9) ? 'propertychange' : '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:
							
  								});
  							 }
							
  						//See if there's a sku-specific image available and update the display:
  						if (typeof refreshProductImages == 'function') refreshProductImages();
						
  						//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: ';
							
  							if (minimumPrices[selectedAttName]) {
							
  								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:checked').each(function(){
					$(this).click();
				})
				
				if ($.browser.msie)
				cartComponents.find('select').each(function(){
					$(this).trigger('propertychange');						
				})
			}

			//Initialise the price description if attributes are preselected:
			//$('input:radio:checked', $productDetail).change();
		
			//Number the addToCartComponents:
			$('ol.addToCartPanel > .addToCartComponent', $productDetail).each(function(i){
				$(this).addClass('item_' + (i + 1));
			});		
		}
		
		//INitialise the sku-image for pre-selected attributes
		if (typeof refreshProductImages == 'function') refreshProductImages();
		
		//Tabify the long description panel
		$('#productDescriptivePanel').tabify();
		
		//Fetch the more info URL for this product, format, and append it to the tab
		if ($('#moreInformationPanel').length) {
			var moreInfoPanel = $('#moreInformationPanel'),
				 moreInfoURL = $('a', moreInfoPanel).attr('href');
				
			$.get(moreInfoURL, function(data, status) {
				moreInfoPanel.html(data).removeClass('placeholder');
			});
		}
	}
	
	/* 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').insertAfter('#outerwrap');
	
	/* Substitute fonts with Cufon: */
	Cufon.replace('#pagebody h1:first:not(#productName, #searchName, #categoryName, #targettedHeading), #productdetailscontainer div.alternativeproduct h2, #footer h2, #outerwrap.homepage h2, #pagebody > div.wrapper > h2, #mattressFinder h2, #basketStatusMessage h3, #basketStatusMessage h2');
};
