Initialiser.modules.productDetailBehaviour = function(){
	
	// ============================================================
	//	First pass: Global routines that run before the page specific stuff
	// ============================================================
	
	
	
	// ============================================================
	//	Helpers:
	// ============================================================
	
	function createSavingTag(oldPrice, newPrice, isExact) {

			 if (!oldPrice || !newPrice) return false;
			
				oldPrice = oldPrice.replace(/[^0-9\.]/gi, '');
				newPrice = newPrice.replace(/[^0-9\.]/gi, '');
				
				if (oldPrice > newPrice) {
		
					var saving = oldPrice - newPrice,
						 wholeDollars = parseInt(saving) + '',
 						 lengthClass; 
					 //Append a class corresponding to the length of the dollar price, for width sensitive graphics:
						 
					switch (wholeDollars.length) {
						case 1 :
							lengthClass = 'dollars';
						break;
						case 2 :
							lengthClass = 'tens';
						break;
						case 3 :
							lengthClass = 'hundreds';
						break;
						case 4 :
							lengthClass = 'thousands';
						break;
					 }
				
					 var centsDisplay = /\.[0-9]+$/;						 
					 if (!centsDisplay.test(saving)) saving = saving + '.00';
					 var centsModifier = saving.match(/\.00$/) ? 'zero' : '';
					
					 saving = ('<sup class="symbol">$</sup>' + saving).replace(/(\.\d+)/g, '<sup class="cents ' + centsModifier + '">$1</sup>');
				
					var saveTag;
				
					if (isExact) {
						saveTag = '<span class="promoTag saving ' + lengthClass + '">Save<strong>' + saving + '</strong></span>';
					} else {
						saveTag = '<span class="promoTag saving range ' + lengthClass + '"><span class="prefix">Up to</span> <strong>' + saving + '</strong> <span class="suffix">off!</span></span>';
					}

				return saveTag;
			}
	}
	
	function getCookie(cookie_name)	{
	  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	  if ( results )
	    return ( unescape ( results[2] ) );
	  else
	    return null;
	}
	
	var validateZip = function(zipToCheck) {
		var zipCodePattern = /^\d{5}$/;
		return zipCodePattern.test(zipToCheck);
	}
	
	
	// ------------------------------------------------------------
	// Help overlays:
	// ------------------------------------------------------------
	// Canvas for the help overlay:
	var $detailedHelpDisplay = $('<div id="detailedHelpDisplay" class="overlay"><div class="liner"><a title="Close this info window." class="closeWidget">Close</a></div></div>').appendTo('body');
	
	var $helpLinks = 	$('a.attributehelplink, a.detailedHelp, a.pdmoreinfolink').removeAttr('onclick');
	
	if (window.location.protocol == 'https:') {
			$helpLinks.each(function(){
				var URLrewite = $(this).attr('href');
					$(this).attr('href', URLrewite.replace('http:', 'https:'));
			});
	}
	
	$detailedHelpDisplay.jqm({ajax: '@href', trigger: 'a.detailedHelp, a.attributehelplink, a.pdmoreinfolink', closeClass: 'closeWidget'});
	
	
	// ============================================================
	//	Page/Section Specifics: Routines for individual sections of the site.
	// ============================================================

	
	// ------------------------------------------------------------
	// When we're on the home page:
	// ------------------------------------------------------------
	
	if ($('#outerwrap').is('.homepage')) {
		
		//Find any carousel items:
		$('div.carousel', '#pagebody').each(function(){
				var $carousel = $(this),
					$carouselNav = $carousel.find('.carouselPageNav'),
					$prevButton = $('<a class="carouselPrevious" href="" title="Previous page">Previous page</a>'),
					$nextButton = $('<a class="carouselNext" href="" title="Next page">Next page</a>');

					//Insert the navigation elements
					$carousel
						.append($nextButton)
						.append($prevButton);

					//Update the container with flags for first/last slide: to enable/disable next/prev.
					var updateControls = function() {
						var data = $carousel.data('cycle.opts');

						if (data) {
							if (data.currSlide == 0) {
								$carousel.addClass('atFirstSlide');
							} else {
								$carousel.removeClass('atFirstSlide');
							}

							if (data.currSlide == (data.slideCount - 1)) {
								$carousel.addClass('atLastSlide');
							} else {
								$carousel.removeClass('atLastSlide');
							}
						}
					}

				//Initialise the carousel
				$carousel.children('.carouselContents').cycle({
					nowrap: 0,
					timeout:0, //Don't autoplay
					fx:'scrollHorz',
					speed:240,
					easing: 'easeOutQuad',
					pager: $carouselNav,
					prev: $prevButton,
					next: $nextButton,
					after: updateControls //This callback is also fired on init, handily setting up the initial state.
				});
		});
		
	
	}

	// ------------------------------------------------------------
	// When we're on the product detail page:
	// ------------------------------------------------------------
	
	if ($('#OrderItemAddForm').length) {
		var $productDetail = $('#OrderItemAddForm');
		
		
		//When the 'add to basket' message is present:
		if ($('#basketStatusMessage').length) {
			//Mark the cart overview in the header as having a new addition:
			$('#minishopcart').addClass('newAddition');
			
			//Convert the status message in to a popup:
			var $message = $('#basketStatusMessage');
			
				$message.addClass('overlay').appendTo('body')
				
				//Append the accessories to the message:
				$('#productdetailscontainer').children('div.alternativeproduct').clone().appendTo($message.children('.liner'));
				
				$message.jqm({closeClass:'closeWidgetAlternate'}).jqmShow();
		}
		
		if ($('#wishlistStatusMessage').length) {
			//Convert the status message into a popup:
			var $message = $('#wishlistStatusMessage');
			
				$message.addClass('overlay').appendTo('body')
			
				$message.jqm({closeClass:'closeWidgetAlternate'}).jqmShow();
		}
		
		//Calculate and show the saving amount:
		if ($('#priceelement').length) {
			
			var priceElement = $('#priceelement'),
				 oldPrice = priceElement.find('.wasPrice .amount .max').text(), //Try to find a range-based price:
				 newPrice = priceElement.find('.nowPrice .amount .max').text(),
				 isRange = (!!oldPrice || !!newPrice); //if we have either price, we're dealing with a range

				//If there's no range (exact prices specified), extract just the prices:
				if (!oldPrice) oldPrice = priceElement.find('.wasPrice .amount').text();
				if (!newPrice) newPrice = priceElement.find('.nowPrice .amount').text();
				
			//$('#productdetailscontainer').prepend(createSavingTag(oldPrice, newPrice, !isRange)); //Temporarily removed while we discuss business logic:
		};
		
		//The triggers for the zipCode popUp:
		$('#checkAvailabilityComponent').jqm({
			modal: true,
			closeClass: 'closeWidget'
		});
		
		$('#checkAvailability').click(function(){
			if ($(this).closest('.addToCartComponent').is('.selectable')) {
				$('#checkAvailabilityComponent').jqmShow()
			};
		})
		
		//Save zip code and go back:
		$('a.goBack', '#checkSuccess').click(function(){
			var success = $('#checkSuccess');
			$('input[name=zipcode]', '#OrderItemAddForm').val(success.find('h2 > span.zipCode').text());
			
			if ($('#OrderItemAddForm').is('.regionalUnavailable')) {
				
			} else {
				$('#checkAvailabilityComponent').jqmHide();
			}
			
		});
		
		$('a.changeZip', '#addToCartForm').click(function(){
			
			$('#checkAvailabilityComponent').jqmShow();
		});
		
		
		if ($('#productDetailSummaryView').length) {
			//See if we can find this item in the cart:
			var detailSummary = $('#productDetailSummaryView'),
			 	 cartURL = $('a.linkToCart', detailSummary).attr('href');
		
			$.get(cartURL, function(response){
					var productId = $('#refreshProduct_productId').val(),
					exp = new RegExp('<tr id="productRow_' + productId + '_.*?</tr>', 'gim');
					response = response.replace(/(\r\n|\n|\r)/gm, ''); //nix the linebreaks that were causing false negatives
				
				var productRow = response.match(exp);
				
				if (productRow) {
					
					var storage = $('<table><tbody>' + productRow.join() + '</tbody></table>'),
						subTotalAmount = 0,
						quantityAmount = 0,
						productSummary = $('<ul class="productCartSummary"/>');

					storage.find('tr.basket_contents').each(function(){
						var $row = $(this),
							thisSubTotal = $row.find('td.total span.amountDefault').length ? parseFloat($(this).find('td.total span.amountDefault').html().replace(/[^0-9|\.]/g, '')) : 0,
							thisQuantityAmount = $row.find('td.quantity input[id*=qty]').length ? parseFloat($(this).find('td.quantity input[id*=qty]').val()) : 0,
							attributes = $row.find('ul.attributes > li > span.value'),
							attributesList = '';
							
							attributes.each(function(i){
								if ($(this).text()) attributesList += $(this).text();
								if (i < (attributes.length - 1)) attributesList += ', ';
							});
	
						if (thisQuantityAmount) {
							subTotalAmount += thisSubTotal;
							quantityAmount += thisQuantityAmount;
							
							$('body').append(attributesList);
							
							productSummary.append('<li><span class="quantity">' + thisQuantityAmount + '</span> x <span class="description">' + attributesList + '</span> <span class="price">$' + thisSubTotal + '</span></li>');
						}
					});
					
					subTotalAmount = subTotalAmount.toString()
					
					var centsModifier = subTotalAmount.match(/\.00$/) ? 'zero' : '';
					
					detailSummary
						.prepend(productSummary)
						.prepend('<h3>In your cart:</h3>')
						
					//	<span class="quantity">' + quantityAmount + '</span> in your cart, for a subtotal of <span class="amount">$' + subTotalAmount.replace(/(\.\d+)/g, '<sup class="cents ' + centsModifier + '">$1</sup>') + '</span></h3>');	
				}	 
			});
		}
		
		/* Dynamic changes to the product attribute selectors: */
		//var attributeSelectors = $('select.attributeSelector', $productDetail).change(function(){
		//	switchSkuSettings(document.OrderItemAddForm, this, '', this.id.replace(/\D/g,'')); //We retrieve the numeric index which is appended to the ID:
		//});
		
		//Submit the add to cart and add to wishlists via the check availability overlay:
    var addToCartInProgress = false;
		
		$('a.buttonAddToCart').click(function(){ //This button appears in the 'success' result of a zip code avail. check.
		  
		  if (!addToCartInProgress && !$(this).closest('.unselectable').length){
  		  addToCartInProgress = true;
		
		    $(this).addClass('buttonDisabled').find('span').text('Adding to cart...')
		    $('#checkAvailabilityComponent').addClass('checkInProgress');
		  
  			//Update the zip code:
  			var $zipCode = $productDetail.find('input[name=zipcode]'),
  			savedZip = $zipCode.val(),
  			checkedZip = $('span.zipCode', '#checkAvailabilityComponent').eq(0).text();
			
  			if (!savedZip && checkedZip) { //If the saved zip is empty, and the checked zip is not, submit the checked zip
  				$zipCode.val(checkedZip);
  			} else if ((savedZip != checkedZip) && checkedZip && !isNaN(checkedZip)) { //If the checked zip and the saved zip don't match, submit the checked zip (if it looks valid)
  				$zipCode.val(checkedZip);
  			} else {
  				//Otherwise, submit the saved zip
  			}

  			//Set the URL (was previously part of add2ShopCart)
  			$productDetail.find('input[name=URL]').val('OrderCalculate?URL=/webapp/wcs/stores/servlet/ProductDisplay');

  			//Set the action and submit the form			
  			$productDetail.attr('action', '/webapp/wcs/stores/servlet/OrderItemAdd').submit();
  		}
		});
		
		//Create a frame for use by the extra large image:
		var largeImageFrame = $('<div class="imageFrame overlay"><div class="liner"><img id="fullSizeProductImage" src=""/><a title="Close this window" class="closeWidget">Close</a></div></div>');
			 largeImageFrame.appendTo('body');
		
		//Pop-up the larger image in an overlay:
		$('a.pdlargerimage',  '#productdetailscontainer').click(function(){
			$('#fullSizeProductImage').attr('src', $(this).attr('href'));
			largeImageFrame.jqmShow();
			return false;
		});
		
		//Ajax and overlay the links to product attribute help:
	//	$('a.attributehelplink').removeAttr('onclick');
//		$detailedHelpDisplay.jqm({ajax: '@href', trigger: 'a.attributehelplink'});
		
		//Social network stuff 
		$('div.dropDownSelector').each(function(){
			var $this = $(this);
			
				$this.find('.dropToggle').click(function(){
					$this.toggleClass('dropDownSelectorActive');
					$('body').one('click', function(){
						$this.removeClass('dropDownSelectorActive')
					});
					return false;
				});
		});
		
	}
	
	// ------------------------------------------------------------
	/* Personalise the 'customer' name in the header */
	//	This changes the user's name so it links to their account page (not sign out)
	// ------------------------------------------------------------

	var $toplinks = $('#toplinks'),
		 customerName = $('#loggedInAccountName').text();
	
	if (customerName.length) {
		$('#myAccountLink > a').text('Welcome ' + customerName).show();
	} else {
	//	$('#loggedOutAccountName').hide();
	//	$toplinks.find('span.logOnLinkText').show();
	}

	
	// ------------------------------------------------------------
	/* When we're on a product or category lister page */
	// ------------------------------------------------------------
	if ($('body.browse, body.search').length) {
		var $productList = $('#productList');
		
		//Add a helpful pointer to the zip code field, if the user hasn't already used it:
		$('input#zipCode[value=""]').addClass('highlight')
		$('#prdSrchZipnAll').prepend('<p id="zipCodeHelperMessage" class="message" style="display:none">Let us know your zip code to discover which products we can deliver to your area.<span class="pointer"></span></p>');
		$('#zipCodeHelperMessage').slideDown(500);
		
		$('a.detailedHelp').removeAttr('onclick').jqm({ajax: '@href'});
		
		$('#zipCode').change(function(){
			$(this).removeClass('valid');
		});
		
		//Append the zip to the URL for the product thumbnails:
		var zipToAppend = validateZip($('#zipCode').val()) ? $('#zipCode').val() : false;
		
		if (zipToAppend) {
			$productList.find('a').each(function(){
					$(this).attr('href', function(){
						return ($(this).attr('href').indexOf('?') > -1) ? $(this).attr('href') + '&zipcode=' + zipToAppend : $(this).attr('href') + '?zipcode=' + zipToAppend;
					});
			});
		}
		
	}
	
	
	// ------------------------------------------------------------
	// When we're in the checkout
	// ------------------------------------------------------------
	if ($('body.basket, body.delivery_address, body.delivery_options, body.order_summary,  body#bodycheckout, #outerwrap.addressverify').length) {
		//Assign additional classes to the breadcrumbs:
		$('#breadcrumb li').each(function(){
			if ($(this).is('.active')) return false;
			$(this).addClass('complete');
		});
		
		//change the minishop cart's text:
		
		$('#minishopcart li.items span.minishopcartitem a').fadeOut(500, function(){
			$(this).html('Checking out&hellip;').fadeIn(500);
		});
		
		if ($('#ShipAddressForm').length) {
			var addressSelect = $('#ShipAddressForm');
			addressSelect
				.find('div.addline')
				.find('input[type=radio]')
				.click(function(){

					$(this).closest('.addline').addClass('selected')
						.siblings('.addline').removeClass('selected');
				});
		}
		
		if ($('#shippingschedule').length) {
			$('tbody td.slotAvailable input', '#shippingschedule')
			.click(
				function(){
					var td = $(this).closest('td'),
					tdCount = td.prevAll().length + 1;
					if ($(this).is(':checked')) {
						td.addClass('selected')
							.siblings().removeClass('selected')
							.closest('tr').addClass('selected')
							.siblings().removeClass('selected')
							.find('td.selected').removeClass('selected');
							
						$('thead th:nth-child('+tdCount+')', '#shippingschedule')
							.addClass('selected')
							.siblings().removeClass('selected');
					} else {
						
					}
				}
			)
			.closest('td')
			.hover(
				function(){
					var $this = $(this);
					var columnCount = $this.prevAll().length + 1;
					$this.addClass('highlighted')
						.closest('tr').addClass('highlighted');
						
				},
				function(){
					var $this = $(this);
					var columnCount = $this.prevAll().length + 1;
					$this.removeClass('highlighted')
						.closest('tr').removeClass('highlighted');
					
				});
		
			var preSelect = $('tbody input:checked', '#shippingschedule').closest('td');
			if (preSelect.length) {
				 colSelect = preSelect.prevAll().length + 1;
				
				 preSelect.addClass('selected')
					.closest('tr').addClass('selected');
				
				$('thead th:nth-child('+colSelect+')', '#shippingschedule')
					.addClass('selected');
				}
		}
		
		//Warn the user before taking them back to their cart:
		if ($('#addOfferCodeReturnToCart').length) {
			var $addOfferLink = $('#addOfferCodeReturnToCart');
			
			var targetURL = $addOfferLink.attr('href'),
				$message = $('<div class="liner"></div>');
				
				$('body').append('<div id="applyPromoCodeConfirmation" class="overlay"></div>')
				
				$message
					.append('<h3 class="messageWarning">Do you want to return to the start of the checkout process to add an offer code?</h3>')
					.append('<fieldset>' +
							      '<a title="Stay here without making changes" class="button buttonMedium goBack buttonMediumSecondary cancel"><span class="l">No, stay here</span></a>' +				
								  '<a title="Return to the start of the checkout" class="button buttonMedium buttonMediumPrimary buttonProceed" href="' + targetURL + '&highlightOfferCodeEntry=true">' +
								      '<span class="l">Yes, add offer code</span>' +
								  '</a>' +
						    '</fieldset>')
				
			$('#applyPromoCodeConfirmation').append($message);
			
				
			$addOfferLink.click(function(){
				$('#applyPromoCodeConfirmation').jqm({closeClass:'cancel'}).jqmShow();
				return false;
			});
		}
		
		
		//Highlight the offer code entry form if required:
		if ($('#PromotionCodeForm.highlighted').length) {
			$('#PromotionCodeForm.highlighted').find('#promoCode1').focus();
		}
		
		
		
		
		
		//the toggle on the 'separate address' display:
		if ($('#outerwrap.ordersubmit').length) {
			$('#separateBillingAddressSelectorToggle').click(function(){
				$('#separateBillingAddressSelector')
					.slideDown(200, function(){
						$(this).find('select')
							.focus();
					});	
					$(this).hide()
						.parent()
							.text('Billing Address');
							
				$('#separateBillingAddressSelector').after('<h2>Shipping address</h2>')
				return false;
			})
		}
	}
	
	// ------------------------------------------------------------
	// For the account section:
	// ------------------------------------------------------------

	if ($('#addressBookList').length) {
		var addBook = $('#addressBookList');
		

	}
	
	// ------------------------------------------------------------
	// For the mattress finder:
	// ------------------------------------------------------------
	if ($('#mattressFinder').length) {
		var $mattressFinder = $('#mattressFinder');
		
		//Nicer highlights on radios and labels:
		$mattressFinder
			.find('input[type=radio], input[type=checkbox]')
				.click(function(){
					var $this = $(this);
					var siblings = $this.closest('fieldset').find('input[type=' + $this.attr('type') + ']').closest('li');
					if ($this.attr('checked')) {
						if ($this.attr('type') == 'radio') siblings.removeClass('selected');
						$this.closest('li').addClass('selected');
					} else {
						$this.closest('li').removeClass('selected');
					};
				})
				.closest('li')
				.hover(
					function(){$(this).addClass('hover')},
					function(){$(this).removeClass('hover')}
				);
		
		//Auto submitting forms:
		$('fieldset.submitsWhenSelected', $mattressFinder)
			.find('input[type=radio], input[type=checkbox], select')
				.click(function(){
					$(this).closest('form').submit();
				});
				
		var promptSelectors = $('fieldset.promptSelection', $mattressFinder);
		
		promptSelectors
			.find('input[type=radio], input[type=checkbox]')
				.click(function(){
					$(this).closest('form').find('button[type=submit]').removeAttr('disabled').removeClass('buttonDisabled');
				})
			.end()
			.find('input[type=text]')
				.keyup(function(){
					if ($(this).val().length) {$(this).closest('form').find('button[type=submit]').removeAttr('disabled').removeClass('buttonDisabled')}
					else {$(this).closest('form').find('button[type=submit]').attr('disabled', 'disabled').addClass('buttonDisabled')};
				})
			.end()
			.find('select')
				.change(function(){
					$(this).closest('form').find('button[type=submit]').removeAttr('disabled').removeClass('buttonDisabled');
				});
			
			if (jQuery.browser.msie) {
					promptSelectors
						.find('label')
							.click(function(){
								var listLabel = $(this).closest('li');
								
								listLabel.siblings().removeClass('selected');
								listLabel.addClass('selected');
								
								listLabel.closest('form').find('button[type=submit]').removeAttr('disabled').removeClass('buttonDisabled');
							})
			}	
			
			//initialise the button to enabled if there's a value in the right spot:
			if (promptSelectors.find('input[type=text]').val()) promptSelectors.find('button[type=submit]').removeAttr('disabled').removeClass('buttonDisabled');
	}
	
	// ------------------------------------------------------------
	// For the store locator:
	// ------------------------------------------------------------
	
	if ($('#mapsearch').length) {
		var mapSearch = $('#mapsearch'),
			mapFrame = $('#mapFrame'),
			expandControls = $('<span id="mapSizeControls" class="collapsed" title="Larger map.">Expand/collapse map.</span>');
			
			expandControls.click(function(){

				map.savePosition();

				if (mapFrame.is('.expanded')) {
					//Collapse the map
					expandControls.addClass('collapsed').removeClass('expanded').attr('title', 'Larger map.');
					mapFrame.addClass('collapsed').removeClass('expanded');
				} else {
					//Expand the map
					expandControls.addClass('expanded').removeClass('collapsed').attr('title', 'Smaller map.');
					mapFrame.addClass('expanded').removeClass('collapsed');
				}
				
				map.checkResize();
				map.returnToSavedPosition();
			})
		
		mapSearch.after(expandControls);
		
		//Events on the driving directions links, and updating the map mode
		var directionsLinks = $('a.drivingDirections', '#storelist'),
			storeItems = $('li.store', '#storelist'),
			fromPoint = null,
			destinationPoint = null,
			getDirectionString = function(){
				return 'from:' + fromPoint + ' to:' + destinationPoint;
			}
		
		directionsLinks.click(function(){
			
			var stringExtract = /from:\s*(.+)\s*to:\s*(.+)\s*/i.exec($(this).attr('rel'));
			
			if (!fromPoint) fromPoint = stringExtract[1]; //Only use the 'from' poin in the driving directions if the user hasn't updated their manual point
				destinationPoint = stringExtract[2];
				
				
			//Load the directions stored in the link's rel attribute
			gdir.load(getDirectionString(), { "locale": "en" });
			
			//Flag this link as active
			storeItems.removeClass('active');
			$(this).closest('li.store').addClass('active');

			//Expand the map if required
			if (!mapSearch.is('.expanded')) {
				expandControls.addClass('expanded').removeClass('collapsed').attr('title', 'Larger map.');
				mapFrame.addClass('expanded').removeClass('collapsed');
			}
			
			$('#storeLocatorFeedback').html('Directions to <strong>' + $(this).closest('li.store').find('h4.storename > a').text() + '</strong>');
			
			//Flag the map frame:
			$('#mapFrame').addClass('withDirections');
			
			//Refresh the map
			map.checkResize();
			
			//Jump back to the top to show the map
			window.scroll(0,190);
			
			$('#fromAddressEntry').val(fromPoint);
			
			$('#storelocatorform').fadeOut(200, function(e){
				$('#directionUpdate').fadeIn(200);
			});
			
			return false;
		});
		
		var directionUpdateForm = $('#directionUpdate');
			directionUpdateForm.submit(function(){
				
				fromPoint = $('#fromAddressEntry').val();
				gdir.load(getDirectionString(), { "locale": "en" });
				
				return false;
			});
		
		$('#printDirectionsMap').click(function(){
			$('body').addClass('printDirections');
			window.print();
			return false;
		});
	}
	
	
	
	
	// ============================================================
	//	New page type detection: based on the safePageConfig object
	// ============================================================
	
	if (typeof safePageConfig == 'object') {
		
		switch (safePageConfig.pageName) {
			case 'DiscountDetailsDisplay' : //Displaying details of a discount or promotion
				$('#buttonBackAStep').click(function(){
					history.back(1);
					return false;
				});
		}
		
		switch (safePageConfig.pageGroup) {
		  case 'checkout' :
			  //Show a 'please wait' ticket on the checkout pages when submitting:
			  
			  //First, find the location for, and construct the message element:
			  var $checkoutForm = $('form', '#checkout_container, #basket_container'),
			      $buttonBar = $('#page_actions, #basket_actions, div.buttonBar, div.actions');

			      if ($buttonBar.length) {
			        $buttonBar.append('<div id="checkoutProgressMessage">Please wait a moment</div>');
              
              //Because Sleepys.com uses horrible links with onclick events instead of submit buttons,
  			      //we're binding a custom event which can be fired in several ways:
  			      $checkoutForm.bind('inProgress', function(){
  			        $(this).addClass('checkoutInProgress');	//When the form is submitted, flag the form as in progress. CSS will take care of the rest.
  			        $buttonBar.addClass('checkoutInProgress');
  			      });
  			      
			        $buttonBar.find('a.button').not('.buttonSecondary').click(function(){
  			        $buttonBar.addClass('checkoutInProgress');
      			    $(this).closest('form').trigger('inProgress');
			        });
			        
      			  $checkoutForm.submit(function(){
      			    $(this).trigger('inProgress');
      			  });
			      }
			  
			break;
	  }
		
	}
	
	
	
	// ============================================================
	//	Wrapping up: global routines that need to run after the page specific actions
	// ============================================================
	
	//Clear the search field when it's focused:

	$('#searchbox').focus(function(){
		var $searchBox = $(this);
		if ($searchBox.not('.changed').length) {
			$searchBox.addClass('changed').val('');
		}
	});
	
	
	$('#frmFreeTextSearchForm').submit(function(){
		var $searchBox = $('#searchbox');
		if (!$searchBox.val().length) {
			$searchBox.focus();
			return false;
		}
	});
	
	$('button.print').click(function(){
		window.print();
		return false;
	})
	
	//Initialise modal overlays and popUps:
	var triggerLinks = $('a.overlayTrigger');
	
	$('div.overlay').each(function(){
		var $this = $(this);
		if (! $this.closest('#_pureTemplateCanvas').length) {
			switch (this.id) {
				case 'quickLookDetailBox' : //Quicklook overlays
					break;
				case 'checkAvailabilityComponent' : 
					if ($this.parent().not('body')) {
						$this
							.appendTo('body');
					}		
					break;
				default: //All other overlays
					
					if ($this.parent().not('body')) {
						$this
							.appendTo('body');
					}
					$this.jqm(
						{modal: false,
						 closeClass: 'closeWidget'
						})
						.jqmAddTrigger(triggerLinks.filter('[href=#' + this.id + ']'))
						.jqmAddClose($('a.cancel', $this));
			}
		}
	});

	//If a 404 error is detected: (Can't use page identifier for this, as page name varies depending on the requested URL)
	//This is a bit of a hack - we use a link to a static page in an eSpot, and retrieve the contents at that link over AJAX.
	if ($('#errorContentLink').length) {
		var contentLink = $('#errorContentLink'),
			contentTarget = $('<div id="staticContentTarget"></div>').insertBefore(contentLink);

			contentTarget.load(contentLink.attr('href'));
			contentLink.remove();
	}

}


Initialiser.modules.browserChecks = function(){
  
  //Check for unsupported browsers:
  if ($.browser.msie && $.browser.version < 7) {
    safe.showNotificationBar('It looks like you\'re using an <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home">unsupported version of Internet Explorer</a>. Please be aware that some parts of the site might look strange or not work properly.', {barId: 'browserWarningBar-1800mattress', additionalClasses: 'warning browserWarning'})
  }
  
  //Check for IE8 compatibility mode:
  if ($.browser.msie && (document.documentMode && document.documentMode == 7)) {
    safe.showNotificationBar('It looks like you\'re using Internet Explorer in compatibility view. You should turn compatibility view off for best results. <a title="How to turn compatibility view off" href="http://answers.microsoft.com/en-us/ie/forum/ie8-windows_7/turn-off-compatibility-view/33bb7aaf-ab73-47e6-8b5d-d466162ee1cc" target="_blank">Click here</a> to learn how to do it.', {barId: 'browserWarningBar-1800mattress', additionalClasses: 'warning browserWarning'})
  }
}
