/* 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 */
		
		var productList = $('#productList'),
			results = productList.children('li.result')
		
			productList.equalHeights();
			
			/*
			results
				.hover(function(){
					results.removeClass('hover');
					$(this).addClass('hover');
				},
				function(){
					$(this).removeClass('hover');
				});
				*/
		
		//Tweak the values in the filter list:
		$('a', '#filters').each(function(){
			var $this = $(this),
				newText = $this.html();
				
				newText = newText.replace(' to ', ' - ');
				newText = newText.replace(/\.\d+/g, '');
				
			$this.html(newText)
		});
		
    //For IE 6 & 7, something about the product thumbnail means the click event isn't propagating...
    if ($.browser.msie && $.browser.version <= 7) {
      $('img', results).click(function(){
          window.location = $(this).closest('a').attr('href');
      });
      
    }
    
    
	}

/* -------------------------------------------------------------------------
		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: */
	
	if ($('#categorylister').length) {
		/* Move the title and breadcrumb out of the main box on product listers */
	}

/* -------------------------------------------------------------------------
	 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('#productdetailscontainer');
		
		//$('#productcode').insertAfter('#productDescriptivePanel')
		
		//$('#maincontent, #filters', 'body.browse').wrapAll('<div class="browseWrapper wrapper"></div>');
		
		var minimumPrices = {};
		if ($productDetail.not('.unavailable, .regionalUnavailable').length) {
		
			var purchaseComponent = $('#productPurchaseDetails'),
				 addToCartComponents = $('li.addToCartComponent', purchaseComponent);
		
			var helperPromptTexts = ['First', 'Next', 'Next', 'Now'];
		
			var blankSelection = true; //Flag if no attributes have been selected.
		
				 $(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 (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')
				.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');
								}
						}
				})
				.expandSelect({
					readOnly: purchaseComponent.is('.unAvailable'),
					sequenced: true
					}
				)
				.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, display: 'block'})
								//	.animate({opacity: 1, right: '-60px'}, 100);
								
						} else {
							
						
							if (typeof minimumPrices == 'object' && minimumPrices[selectedAttName]) {
								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: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)).find('label.attributeLabel').prepend('<span class="numeral">' + (i + 1) + '. </span>');
			});		
		}
		
		//INitialise the sku-image for pre-selected attributes
		if (typeof refreshProductImages == 'function') refreshProductImages();
		
		//Tabify the long description panel
		$('#productDescriptivePanel').tabify({
			'alwaysShowTabs':true
		});
		
		//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');
			});
		}
		
		//Load the deliveryu info into a tab
		if ($('#deliveryInfoPanel').length) {
			var deliveryInfoPanel = $('#deliveryInfoPanel'),
				 deliveryInfoURL = $('a', deliveryInfoPanel).attr('href');
				
			$.get(deliveryInfoURL, function(data, status) {
				deliveryInfoPanel.html(data).removeClass('placeholder');
			});
		}
		
		if (cartComponents && jQuery.browser.msie) {
			var selectedAttributes = cartComponents.find('li.selectOption.selected');

			if (selectedAttributes.length) {
				setTimeout("$('li.selectOption.selected', '#productPurchaseDetails').filter(':last').find('input').click()", 1000);
			}
		}
		
		if ($('#descriptiveAttributeSummary').length) {
			var attributes = $('#descriptiveAttributeSummary');
				attributes.find('span.value').each(function(){

					switch(this.id) {
						case 'attributeValue_Quality':
							//Polish the 'quality' readout, into 'good', 'better', best':
							$(this).addClass('scaleAttribute');
								var selectedValue = $(this).text().replace(' ', '');
									selectedValue = $.trim(selectedValue.toLowerCase());
							$(this).html('<ul class="scale">' + 
											'<li class="first good" title="Good"><span>Good</span></li>' + 
											'<li class="better" title="Better"><span>Better</span></li>' + 
											'<li class="last best" title="Best"><span>Best</span></li></ul>');
											
							$(this).find('.' + selectedValue).addClass('selected');

							
						break;
						case 'attributeValue_ComfortZone' :
						case 'attributeValue_Level' :
							//Polish the 'comfortzone' readout, into '1 (extra plush)', '2 (plush)', 3 (medium), '4 (firm)', '5 (extra plush)'
							$(this).addClass('scaleAttribute');
							var selectedValue = $(this).text().replace(' ', '');
								selectedValue = $.trim(selectedValue.toLowerCase());
							$(this).html('<ul class="scale">' + 
												'<li class="first zone1-extraplush" title="Extra plush"><span>Extra plush</span></li>' +
												'<li class="zone2-plush" title="Plush"><span>Plush</span></li>' + 
												'<li class="zone3-medium" title="Medium"><span>Medium</span></li>' + 
												'<li class="zone4-firm" title="Firm"><span>Firm</span></li>' + 
												'<li class="last zone5-extrafirm" title="Extra Firm"><span>Extra Firm</span></li></ul>');
												
							$(this).find('.' + selectedValue).addClass('selected');

						break;
					}
				});
		}
		
	}
	
	if ($('body.staticpage').length) {
			$('div.section.tabbed').tabify();
			$('div.section.expandable').expandable();
	}
	
	
	/* Salmon custom chat
	window.salmonChatHelper = {
		chatPanel: $('<div id="salmonLiveChat">' + 
						'<span class="wait">Our Bedding Consultant is typing a message&hellip;</span>' + 
						'<span class="prompt">I can help you find the right mattress for the best price. What are you looking for?</span>' + 
						'<span class="startTrigger" id="startSalmonChat">Start Chat</span>' + 
						'<span class="closeWidget">&nbsp;</span>' + 
					'</div>'),
		acceptClick: null,
		closeClick: null,
					
		originalPanel: null,
		originalAcceptClick: null,
		originalCloseClick: null,
		
		initialise: function() {
			$('body').append(salmonChatHelper.chatPanel);
			
			salmonChatHelper.chatPanel = $('#salmonLiveChat');
			salmonChatHelper.acceptClick = $('#startSalmonChat');
			salmonChatHelper.closeClick = salmonChatHelper.chatPanel.find('span.closeWidget');
			
			salmonChatHelper.acceptClick.click(function(){
				salmonChatHelper.originalAcceptClick.click();
				salmonChatHelper.close();
			});
			
			salmonChatHelper.closeClick.click(function(){
				salmonChatHelper.originalCloseClick.click();
				salmonChatHelper.close();
			});
			
		},
		close: function(){
			salmonChatHelper.chatPanel.animate({marginBottom:'-225px'}, 300, 'easeOutQuad', function(){
				salmonChatHelper.chatPanel.remove();
			});
		},
		showInvitation: function(){
			
			salmonChatHelper.originalPanel = $('div[id*="lpInviteLayer"]').hide();
			
			salmonChatHelper.originalAcceptClick = salmonChatHelper.originalPanel.find('a.lpInviteChatHrefAccept');
			salmonChatHelper.originalCloseClick = salmonChatHelper.originalPanel.find('a.lpInviteChatHrefClose');			
			
			salmonChatHelper.chatPanel.animate({marginBottom:'0px'}, 500, 'easeOutQuad', function(){
				salmonChatHelper.chatPanel.addClass('pending');
				salmonChatHelper.chatPanel.animate({marginBottom:'0px'}, 800, function(){
					salmonChatHelper.chatPanel.removeClass('pending');
					salmonChatHelper.chatPanel.animate({marginBottom:'0px'}, 200, function(){
						salmonChatHelper.chatPanel.addClass('ready');
					});
				});
			});
		}
	}
	salmonChatHelper.initialise();
	*/
	
	/* 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>');
	
	//Temp hack: Show some content instead of the mattress.com phoen number:
	//$('#phoneNumber').html('Need help choosing? <a href="#chat" title="Chat live with one of our experts.">Chat live with us</a> or call <span class="phone">1-800-327-7720</span>').slideDown(200)
	
	//Temp hack - line the pagebody:
	$('#pagebody').wrapInner('<div id="pageBodyLiner" class="liner"/>').prepend('<div id="pageBodyHeadCap"/>').append('<div id="pageBodyFootCap"/>');
	
	//The header forms:
	$('#miniStoreLocatorZipInput')
		.bind('click keydown focus', function(){
			if (!$(this).is('.dirty')) {
				$(this).addClass('dirty').val('').attr('maxlength', '5');	
			}
		})
		.blur(function(){
			if ($(this).val() == '') $(this).removeAttr('maxlength').val(this.defaultValue).removeClass('dirty');
		});
	
	//Validation for the mini store locator
	$('#miniStoreLocatorForm')
		.append('<label class="errorHelper" for="miniStoreLocatorZipInput" title="Please enter a 5 digit US zip code"></label>')
		.submit(function(){
			if ($('#miniStoreLocatorZipInput').val().length != 5 || isNaN($('#miniStoreLocatorZipInput').val()) ) {
				$('#miniStoreLocatorForm').addClass('error');
				$('#miniStoreLocatorZipInput').focus();
				return false;
			} else {
				$('#miniStoreLocatorForm').removeClass('error');
			}
		});
	
	
	
	/* 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');
};
