//bit dodgy - this should go in a plugin, but this is the only place it's used.
(function($) {
    $.fn.vCenter = function(options) {
        var pos = {
            sTop: function() {
                return window.pageYOffset || $.boxModel &&
                document.documentElement.scrollTop || document.body.scrollTop;
            },
            wHeight: function() {
                if ($.browser.opera || ($.browser.safari && parseInt($.browser.version) > 520)) {
                    return window.innerHeight; //Here's a patch to fix an endless loop in webkit browsers
                } else if ($.browser.safari) {
                    return window.innerHeight;
                } else {
                    return $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
                }
            }
        };
        return this.each(function(index) {
            if (index == 0) {
                var $this = $(this);
                var elHeight = $this.height();
                $this.css({
                    position: 'absolute',
                    marginTop: '0',
                    top: pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2)
                });
            }
        });
    };

})(jQuery);

//Initialise components in the Quick look details box:
	(function(){
  		
		//Initialise 'scale value' lists: These are attribute lists that show an active value in the scale of possible values
		var scaleValues = function(context) {
			var scaleLists = $('ol.scale', context);
		}
	
		var quickLook = {
				productDataURL: '/webapp/wcs/stores/servlet/PDQuickViewCmd',
				currentProductNode: null,
				productData: null,
				priceData: null,
				priceAvailable: null,
				selectionValid:true,
				priceNav: {
					rows: null,
					columns: null,
					activeRow: -1,
					activeColumn: -1,
					activeRowLabel: '',
					activeColumnLabel: '',
					rowAttributeName: '',
					columnAttributeName: ''
				},
				maskOpacity: 0.25,
				flags: {
					navInitialised: false,
					inProgress: false
				},
				defaultAttributes: {},
				userSelectedAttributes: false,
				ajaxTimeOut: function() {
					window.setTimeout(
						function(){
							quickLook
								.currentProductNode
									.removeClass('inProgress')
								.siblings()
									.removeClass('inProgress');
								
							quickLook.flags.inProgress = false;
						},
						5000);
				},
				templateCurrentRowName:null,
				templateCurrentColumnName:null,
				templateDefaultRowName:null,
				templateDefaultColumnName:null,
				templateDirectives: {
					quickLookDetailsDisplay: {
						'h3#productName a' : 'name',
						'img.productImage@src' : function(img) {
							return img.context['largeImage'];
						},
						'a.detail@href': 'url',
						'a.buttonMediumPrimary': function(avail){
							switch (avail.context['availability']) {
								case 'Online Only' :
								case 'Online, Store' :
									quickLook.priceAvailable = true;
									return '<span class="l">More information</span>';
								default:
									quickLook.priceAvailable = false;
									return '<span class="l">More information</span>';
							}
						},
						'+.@class': function(show) {
							return (show.context['showPricePerNight'] == 'true') ? 'showPricePerNight' : '';
						},
						'+.@class': function(avail) {
							switch (avail.context['availability']) {
								case 'Online Only' :
								case 'Online, Store' :
									return 'online';
								default:
									return 'inStore';
							}
						},
						'p.regionalAvailability': function(avail) {
							switch (avail.context['availability']) {
								case 'Online Only' :
								case 'Online, Store' :
									switch (avail.context['regionalAvailability']) {
										case 'available' :
											return '<span class="available">Available for delivery in <strong>' + $('#zipCode').attr('value') + '</strong>.</span>'	;							
										break;
										case 'unavailable' :
											return '<span class="unavailable">Not available for delivery in <strong>' + $('#zipCode').attr('value') + '</strong>.</span>';
										break;
										default:
											return '<span class="online">Available for purchase, subject to regional availability.</span>';
										break;
									}
								break;
								default:
									return '<span class="info instore">Available in store only. <a href="/webapp/wcs/stores/servlet/StoreLocatorView?storeId=10551&catalogId=10602&langId=-1" title="Visit our store locator">Find your nearest store</a>.</span>';
								break;
							}	
						},
						'dl.definingAttrs' : function(attr) {	
							var subCache = '';
							for (var i = 0, ii = attr.context['definingAttrs'].length; i < ii; i++) {
							
								//Name the two axii of the defining attributes price table:
								if (i == 0) quickLook.priceNav.columnAttributeName = attr.context['definingAttrs'][i].name;
								if (i == 1) quickLook.priceNav.rowAttributeName = attr.context['definingAttrs'][i].name;
							
								subCache += quickLook.templates.definingAttrs(attr.context['definingAttrs'][i]); 
							}
							return subCache;
						},
						'dl.descriptiveAttrs' : function(attr) {
							var subCache = '';
							for (var i = 0, ii = attr.context['descriptiveAttrs'].length; i < ii; i++) {
								subCache += quickLook.templates.descriptiveAttrs(attr.context['descriptiveAttrs'][i]); 
							}
							return subCache;
						},
						'dl.scaleAttrs' : function(attr) {
							var subCache = '';
							for (var i = 0, ii = attr.context['scaleAttrs'].length; i < ii; i++) {
								subCache += quickLook.templates.scaleAttrs(attr.context['scaleAttrs'][i]); 
							}
							return subCache;
						},
						'table.prices thead tr': function(ctxt) {
								//Apply the first set of defining attributes to the column headers:
								var subCache = '',
									 colHeaders = ctxt.context['definingAttrs'];
									 colHeaders = colHeaders[0];
								if (colHeaders) {
									for (var i = 0, ii = colHeaders['values'].length; i < ii; i++) {
										var colSpan = (i == 0) ? ' colspan="2"' : '';
										subCache += '<th' + colSpan + '>' + colHeaders['values'][i]['name'] + '</th>';
									}
								} else {
									subCache = '';
								}
								return subCache;
						},
						'table.prices tbody tr': {
							'price <- prices' : {
								'th' : function(ctxt){
									quickLook.templateCurrentRowName = ctxt.price.item.name;
									return ctxt.price.item.name;
								},
								'td' : {
									'priceDatum <- price.priceData' : {
										'.unitPrice' : 'priceDatum.value',
										'+.@class' : function(ctxt) {
											var priceClass = ctxt['priceDatum'].item.value ? '' : 'null';	
											
											quickLook.templateCurrentColumnName = ctxt['priceDatum'].item.name;
								
											var defaultRow, defaultCol;
											
											if (!quickLook.templateDefaultRowName) {
												
													var attrCols = ctxt.context.definingAttrs[0];
											
													for (var m = 0; m < attrCols.values.length; m++) {
														var attrColValues = attrCols.values[m];

														if (attrColValues['default']) {defaultCol = attrColValues.name}
														//quickLook.priceNav.activeColumnLabel = 
													}
											}
											
											if (ctxt.context.definingAttrs[1]) {
												var attrRows = ctxt.context.definingAttrs[1];	
												for (var n = 0; n < attrRows.values.length; n++) {
													var attrRowValues = attrRows.values[n];

													if (attrRowValues['default']) {defaultRow = attrRowValues.name};
												}
											}
										
											if (quickLook.templateCurrentRowName == defaultRow) {
												
												for (var i = 0; i < ctxt.context.definingAttrs.length; i++) {
													var attrInfo = ctxt.context.definingAttrs[i];
													for (var j = 0; j < attrInfo.values.length; j++) {
														var attrValues = attrInfo.values[j];
														if (attrValues.name == ctxt.priceDatum.item.name) {
															priceClass += attrValues['default'] ? 'default' : '';
														}
													}
												}
											}
											
											if (!quickLook.priceNav.activeRowLabel && defaultRow) quickLook.priceNav.activeRowLabel = defaultRow;
											if (!quickLook.priceNav.activeColumnLabel && defaultCol) quickLook.priceNav.activeColumnLabel = defaultCol;
												
											return priceClass;	
										}
									}
								}
							}
						}
					},
					definingAttrs: {
						'dt' : 'name',
						'dd ol.selector li' : {
							'value <- values' : {
								'.' : 'value.name',
								'+.@class' : '#{value.active} ',
								'+.@class' : '#{value.default} '
							}
						}
					},
					descriptiveAttrs: {
						'dt' : 'name',
						'dd' : 'value'
					},
					scaleAttrs: {
						'dt' : 'name',
						'dd ol.scale li' : {
							'value <- values' : {
								'.innerValue' : 'value.value',
								'.numeral' : 'value.numeral',
								'.@class' : 'value.active'
							}
						}
					}
				},
				templates: {},
				priceSelector:
				 function(context){
						//Find the data table within the context:
						quickLook.priceData = $('table.dataMatrix', context);
					
						//Create navigation for each column
						quickLook.priceNav.columns = $('dd.dataSelector', context).eq(0).addClass('columnDataSelector').find('ol > li');
						quickLook.priceNav.rows = $('dd.dataSelector', context).eq(1).addClass('rowDataSelector').find('ol > li');
						var defaultRow, defaultColumn, defaultCell;
					
						defaultCell = quickLook.priceData.find('td.default');
						
						defaultColumn = defaultCell.prevAll('td').length;
						defaultRow = defaultCell.parent('tr').prevAll().length;	
					
						attributesInvalid = false;
						
						//Set active option, or use a default:
						if (quickLook.priceNav.activeColumn != -1 && quickLook.priceNav.activeColumnLabel) {
							var activeColumn = quickLook.priceNav.columns.filter('*:contains(""' + quickLook.priceNav.activeColumnLabel + '"")').eq(0)
								if (activeColumn.length) {
									activeColumn.addClass('active');
									quickLook.priceNav.activeColumn = activeColumn.prevAll().length;
									quickLook.selectionValid = true;
								} else {
									if (!quickLook.userSelectedAttributes) {
										quickLook.priceNav.activeColumn = defaultColumn;
										quickLook.selectionValid = true;
									} else {
										attributesInvalid = true;
									}
								}
						} else {
							if (!quickLook.userSelectedAttributes) {
								quickLook.priceNav.columns.eq(defaultColumn).addClass('default active');
								quickLook.priceNav.activeColumn = defaultColumn;
								quickLook.selectionValid = true;
							} else {
								attributesInvalid = true;
							}
						}
			
						if (quickLook.priceNav.activeRow != -1 && quickLook.priceNav.activeRowLabel) {
							var activeRow = quickLook.priceNav.rows.filter('*:contains(""' + quickLook.priceNav.activeRowLabel + '"")').eq(0);
							if (activeRow.length) {
								activeRow.addClass('active');
								quickLook.priceNav.activeRow = activeRow.prevAll().length;
							} else {
								if (!quickLook.userSelectedAttributes) {
									quickLook.priceNav.activeRow = defaultRow;
								} else {
									attributesInvalid = false;
								}
							}
						} else {
							if (!quickLook.userSelectedAttributes) {													
								quickLook.priceNav.rows.eq(defaultRow).addClass('default active');
								quickLook.priceNav.activeRow = defaultRow;
							} else {								
								attributesInvalid = false;
							}
						}
						
						if (attributesInvalid) {
							$('#quickLookPriceLabel').html('<span class="warning">This product isn\'t available in the selected ' + quickLook.priceNav.rowAttributeName + ' and ' + quickLook.priceNav.columnAttributeName + '.</span>');		// (' + quickLook.priceNav.activeColumnLabel + '/' +  quickLook.priceNav.activeRowLabel + ')
							$('#quickLookPriceValue > .unitPrice').html('');
							quickLook.selectionValid = false;
						}

						//Add some formatting to the prices in the table:
							 quickLook.priceData.find('tbody td')
								.each(function(){
									//Work out the 'cents per night' cost:
									var numberOfYears = 7; //The number of years in the lifetime of the mattress:
								
									var unitPrice = $(this).children('.unitPrice').text();
								
									if (unitPrice) {
										var nightPrice = Math.round((unitPrice/(numberOfYears * 365)*100))/100; //The nightly price, expressed as cents
								
										$(this).children('.nightlyPrice').text(nightPrice);
							
										//Apply visual formatting:
										$(this).children('.unitPrice, .nightlyPrice').each(function(){
											var pricePolish = $(this).html();
											var priceSplit = pricePolish.split('.');
									
											if (priceSplit[0].length > 3) priceSplit[0] = priceSplit[0].replace(/(\d)/, '$1,')
											if (priceSplit.length > 1)
											{
												$(this).html('$' + priceSplit.join('<sup>.') + '</sup>');
											}
											else
	   										{
												$(this).html('$' + priceSplit[0]);
											}									
										});
									}
								});
					
						quickLook.priceUpdater();
					
						//Click listeners on the column navigation
						quickLook.priceNav.columns.click(function(e){
							if (e.target.nodeName != 'LI') return false;
							var target = $(e.target);
							if (target.is('.active, .disabled')) return false;
						
								target.siblings().removeClass('active');
								target.addClass('active');
															
								quickLook.priceNav.activeColumnLabel = target.text();
								quickLook.priceNav.activeColumn = target.prevAll().length;
							
								quickLook.userSelectedAttributes = true;
								quickLook.selectionValid = true;
								quickLook.priceUpdater();
						});
					
						//Click listeners on the row navigation
						quickLook.priceNav.rows.click(function(e){
						
							if (e.target.nodeName != 'LI') return false;
							var target = $(e.target);
							if (target.is('.active, .disabled')) return false;
							
								target.siblings().removeClass('active');
								target.addClass('active');
							
								quickLook.priceNav.activeRowLabel = target.text();
								quickLook.priceNav.activeRow = target.prevAll().length;
								
								quickLook.userSelectedAttributes = true;
								quickLook.selectionValid = true;
								quickLook.priceUpdater();
							
						});
				},
				priceUpdater:
				 function(){
					if (quickLook.selectionValid) {
					$('#quickLookDetailContents dl.prices:visible').fadeOut(200, function() {
					
						//Look up the price in the table, given a selected row and column:
						var priceTableBody = quickLook.priceData.find('tbody');

						var activeRow = $('tr', priceTableBody)
							.eq(quickLook.priceNav.activeRow);

						var activeCell = activeRow.children('td')
							.eq(quickLook.priceNav.activeColumn);

						//Retrieve the text labels from the selected row and column headers:
						var activeRowHeader = activeRow.children('th').text();
						var activeColumnHeader = $('#quickLookPriceData thead th').eq(quickLook.priceNav.activeColumn).text();
					
						//Update the price description with the text labels:
						if (activeRowHeader) { 
							//Show both axii names on the label (product has 2 def. attrs.)
							$('#quickLookPriceLabel').html('<span>' + activeColumnHeader + '</span>, <span>' + activeRowHeader + '</span>');
							
							//Try to find a specific image for this SKU:
  						var skuImage = quickLook.productData.skuImages[quickLook.priceNav.activeColumnLabel + '_' + quickLook.priceNav.activeRowLabel];
              if (skuImage) {
                $('img.productImage', '#quickLookDetailContents').attr('src', skuImage);
              }
              
						} else {
							//Show one axis name on the label (product has 1 def. attr.)
							$('#quickLookPriceLabel').html('<span>' + activeColumnHeader + '</span>');
						}
					
						//Check which rows (foundations, usually) the selected column (size, usually) supports. 
						//var activeColumn = priceTableBody.find('tr > *:nth-child(' + quickLook.priceNav.activeColumn + 2 + ')'); //+2 allows for the 0-based selector array, and the row header in the price table.
						var rows = priceTableBody.find('tr');
						var rowSelectors = quickLook.priceNav.rows.removeClass('disabled');

							 rows.each(function(i){

								var columns = $(this).children('td').eq(quickLook.priceNav.activeColumn);

								columns.each(function(){

									if ($(this).is('.null')) {

										//Disable this row selector
										var thisRowSelector = rowSelectors.eq(i).addClass('disabled');
										//If this is the currently selected item, switch back to the default:
										if (thisRowSelector.is('.active')) {
											thisRowSelector
												.removeClass('active')
											/*
											.siblings()
												.find('.default')
													.addClass('active');
											*/
											$('#quickLookPriceLabel').html('<span class="warning">This product isn\'t available in the selected ' + quickLook.priceNav.rowAttributeName + ' and ' + quickLook.priceNav.columnAttributeName + '.</span>');		
											return false;
										}
									}
							 });
							});

						//Retrieve the prices from the selected cell:		
						var unitPrice = activeCell.children('.unitPrice').html();
						var nightlyPrice = activeCell.children('.nightlyPrice').html();

						//update the displayed prices
						$('#quickLookPriceValue > .unitPrice').html(unitPrice);
						$('#quickLookPriceValue > .nightlyPrice > .value').html(nightlyPrice);
					
						$(this).fadeIn(200);
					});
					
					}
				
				},
				findProductDetails: 
					function(product) {
					
						product = product.closest('li.result');
						//Cache the node
						quickLook.currentProductNode = product;
					
						//Highlight the product in the grid
						product.siblings().removeClass('currentItem');
						product.addClass('currentItem inProgress');
					
						//Find the extended Product data
						quickLook.flags.inProgress = true;
						var currentZipCode = $('#zipCode').attr('value') ? $('#zipCode').attr('value') : '',
							 filteredByZip = $('#filterModeZip:checked').length,
							 rawProductData = filteredByZip ? product.find('script#' + currentZipCode + '.extendedData') : product.find('script' + '.extendedData');
							
							if (rawProductData.length) {
								quickLook.productData = JSON.parse(rawProductData.html()); //The data is in the cache
								quickLook.showProductDetails(quickLook.productData);
							} else {
								var data = product.find('a.detailsLink').attr('rel');
								
								var params = eval('({' + data + '})'); //Extract the source data from the product detail rel attribute
								
								//Pass in default values set by the page:
								$.extend(params, quickLook.defaultAttributes);
							
									if (filteredByZip) params['zipcode'] = currentZipCode; //Grab the zip code if available and addit to the hash
									params['productId'] = product.attr('id');
							
								$.get(quickLook.productDataURL, params, function(data, status) { //Retrieve the data via ajax - the element ID is used.
									try {
										quickLook.productData = JSON.parse(data); 
									} catch(err) {
										quickLook.error();
										return false;
									}
										product.append('<script type="text/html" id="' + currentZipCode + '" class="extendedData">' + data + '</script>');
										 //Cache the result:
										quickLook.showProductDetails(quickLook.productData);
								});
							}
					},
				showProductDetails: 
					function(productData) {
						
							quickLook.currentProductNode.removeClass('inProgress');
							quickLook.ajaxTimeOut();
		
							if ($('#quickLookDetailBox').is(':visible')) {
								
								//If the detail box is already shown, just re-render the interior
							
								$('#quickLookDetailBox .liner').fadeOut(200, function(){
							
									//Render the data with the contents template									
									$('#quickLookDetailContents').render(productData, quickLook.templates['quickLookDetailContents']);

									//Initialise the price selector
									if (quickLook.priceAvailable) {
										//If we're showing the item price, fire up the attribute selectors:
										$('#quickLookDetailContents').find('dl.definingAttrs dt').each(function(){
											var $this = $(this);
												 $this.text('Choose ' + $this.text());
											});
										quickLook.priceSelector('#quickLookDetailContents');
									} else {
										//Slurp the list price from the thumbnail node:
										$('#quickLookPriceLabel').html('This product is only available in store.');
										$('#quickLookPriceValue > span.unitPrice').html(quickLook.currentProductNode.find('.listingwaspriceinstore').text());
										$('#quickLookDetailContents').find('dl.definingAttrs dt').each(function(){
											var $this = $(this),
												 text = $this.text();
												 text = text.replace(/^\s+/, '');
												 text = text.replace(/\s+$/, '');
												 $this.text('Available ' + text + 's');
											});
									}
								
									//Hover enhancement for IE:
									quickLook.hoverPolish('#quickLookDetailBox');
								
									$('#quickLookDetailContents').removeClass('inProgress');
								
									$('#quickLookDetailBox .liner').fadeIn(200, function(){
											//Tidy up the 'scale' type lists:
											quickLook.scalePolish('#quickLookDetailBox');
									});
									
									if ($.browser.msie) {
										$('#quickLookDetailBox').find('a.closeWidget')
											.click(function(){
												$('#quickLookDetailBox').hide().removeClass('active').children('div').replaceWith('<div class="renderTarget"></div>');
												$('#overlayMask').fadeOut(200);
												$('body').removeClass('overlayActive');
												quickLook.flags.navInitialised = false;
											});
									}
								});
							} else {
							
								//If the box isn't shown, render the whole thing:
								//Render the data with the template
								$('#quickLookDetailBox div.renderTarget').render(productData, quickLook.templates['quickLookDetailContents']);
						
								//Initialise the price selector
								if (quickLook.priceAvailable) {
									$('#quickLookDetailContents').find('dl.definingAttrs dt').each(function(){
										var $this = $(this);
											 $this.text('Choose ' + $this.text());
										});
									//If we're showing the item price, fire up the attribute selectors:
									quickLook.priceSelector('#quickLookDetailContents');
								} else {
									//Slurp the list price from the thumbnail node:
									$('#quickLookPriceLabel').html('This product is only available in store.');
									$('#quickLookPriceValue > span.unitPrice').html(quickLook.currentProductNode.find('.listingwaspriceinstore').text());
								
									$('#quickLookDetailContents').find('dl.definingAttrs dt').each(function(){
										var $this = $(this);
											 $this.text('Available ' + $this.text() + 's');
										});
								}
		
								//Hover enhancement for IE:
								quickLook.hoverPolish('#quickLookDetailBox');
							
								//If the box isn't visible, show it:
								$('body').addClass('overlayActive');
								
								if ($.browser.msie) {
									$('#overlayMask').css({'opacity': 0, 'display':'block'}).fadeTo(200, 0.35);
									$('#quickLookDetailBox')
										.css({'position':'fixed', 'top': '50%', 'margin-top': '-140px'})
										.show()
										.find('a.closeWidget')
											.click(function(){
												$('#quickLookDetailBox').hide().removeClass('active').children('div').replaceWith('<div class="renderTarget"></div>');
												$('#overlayMask').fadeOut(200);
												$('body').removeClass('overlayActive');
												quickLook.flags.navInitialised = false;
											});
								} else {
									$('#quickLookDetailBox')
									.jqm({
										onHide: function(hash){
										
											hash.w.fadeOut(200, function(){
												hash.o.remove();
												$('#quickLookDetailBox').removeClass('active').children('div').replaceWith('<div class="renderTarget"></div>');
												$('body').removeClass('overlayActive');
												quickLook.flags.navInitialised = false;
											});
										},
										closeClass: 'closeWidget'
									})
									.jqmShow();
								}	
							}
						quickLook.flags.inProgress = false;
				
						//Update the next/previous navigation:
						if (quickLook.currentProductNode.next().length) {$('#quickLookNavigation .next').removeClass('disabled');}
						else {$('#quickLookNavigation .next').addClass('disabled');}
					
						if (quickLook.currentProductNode.prev().length) {$('#quickLookNavigation .previous').removeClass('disabled');}
						else {$('#quickLookNavigation .previous').addClass('disabled');}
					
						//Refresh the navigation (this is a bit of a hack, until I can work out how to assign jquery event handlers in PURE)
						if (!quickLook.flags.navInitialised) quickLook.quickLookNavigation();
						
					
				},
				quickLookNavigation: 
					function(){
						var navigation = $('#quickLookNavigation');
				
						navigation.find('.next')
							.unbind('click')
							.click(function(){
								if ($(this).hasClass('disabled')) return false;
							
								$('#quickLookDetailContents').addClass('inProgress');
								
								userSelectedAttributes = true;
								
								//Find the next item:
								var nextItem = $(quickLook.currentProductNode).next();
								if (nextItem.length) quickLook.findProductDetails(nextItem);
							});
					
						navigation.find('.previous')
							.unbind('click')
							.click(function(){
								if ($(this).hasClass('disabled')) return false;
							
								$('#quickLookDetailContents').addClass('inProgress');
								
								userSelectedAttributes = true;
								
								//Find the previous item:
								var previousItem = $(quickLook.currentProductNode).prev();
								if (previousItem.length) quickLook.findProductDetails(previousItem);
							});
						
						quickLook.flags.navInitialised = true;
						
				},
				thumbnailHandler:
				 function(context) {
					//handle clicks on the product thumbnails in the list 
					var grid = $(context);
				
						grid.click(function(e){
							if (quickLook.flags.inProgress) return false;
							var target = $(e.target).closest('span.quickLookTrigger');
							if (target.length) {
								quickLook.findProductDetails(target);
							}
					
						});
				
					/*grid.find('li.result a').each(function(){ //Neuter the links without trapping events (kinda ugly, but effective);
						var href = $(this).attr('href');
							$(this)
								.attr('alt', href)
								.removeAttr('href');
					})*/
				},
				scalePolish: 
					function(context) {
					
						if ($.browser.msie && $.browser.version == 6) {
							alert('stopping width calc');
							return false;
						}
					
						var hideWhenDone = false,
							 cssCache;
					
						if (!$(context).filter(':visible').length) {
							cssCache = 	$(context).css('left');
							$(context).css({
								//left:'-999em',
								display:'block'
							});
							hideWhenDone = true;
						}
					
						var scales = $('ol.scale', context);
						scales.each(function(){
					
							var scale = $(this),
								 width = scale.width();
								 kids = scale.children(),
								 kidsWidth = 0,
								 surplus = 0;
							
								if (!width) return false;
							 
								 kids.css({
									'padding-left':0,
									'padding-right':0,
									'display': 'inline' //For IE
								 });
							
								 kids.each(function(){
									kidsWidth += $(this).width();
								 });
							
								 surplus = width - (kidsWidth - 5); //-5 is a fudge factor to allow IE to mis-round the number.
							
								 if (surplus/kids.length > 0) {
								 	kids.css({
										'padding-left': (Math.floor((surplus/kids.length)/2) % 2 == 0) ?  Math.floor((surplus/kids.length)/2) : Math.floor((surplus/kids.length)/2) - 1,
										'padding-right': Math.floor((surplus/kids.length)/2)
									 });
								
									if ($.browser.msie) scale.width(width + 15); //Double fudge for stupid IE
								 }
						});
					
						if (hideWhenDone) {
							$(context).css({
								//left: cssCache,
								display:'none'
							});
						}
				},
				hoverPolish: 
					function(context) {
						var hoverTargets = $('ol.scale > li, ol.selector > li', context);
					
						hoverTargets.hover(
							function(){
								$(this).addClass('hover');
							},
							function(){
								$(this).removeClass('hover');
							}
						);
					},
				error: 
					function() {
						if ($('#quickLookDetailBox.active').length) {
							//If the detail box is already shown, just re-render the interior
						
							$('#quickLookDetailBox .liner').fadeOut(200, function(){
									$('#quickLookDetailBox .liner')
										.addClass('error')
										.html('<h3>We\'re sorry - an error occurred</h3><p>Something went wrong while fetching the product details - you can <a href="#tryAgain">try again.</p>');
							
									$(this).fadeIn(200);
							});
						} else {
							$('#overlayMask').fadeTo(100, quickLook.maskOpacity, function(){
								$('#quickLookDetailBox > .renderTarget')
									.replaceWith('<div id="quickLookDetailContents" class="quickLookDetail overlay"><div class="liner"></div><a class="closeWidget" title="Close the quick look box.">Close</a></div>')
								
								$('#quickLookDetailContents > .liner')
									.addClass('error')
									.html('<h2>We\'re sorry - something went wrong.</h2><p>We couldn\'t fetch the product\'s details - you can <a class="retry" href="#tryAgain">try again</a> or <a href="#details" class="skip">see the product on its own page</a>.</p>')
									.find('a.retry')
										.click(function(){
											quickLook.findProductDetails(quickLook.currentProductNode);
											return false;
										})
									.end()
									.find('a.skip')
										.click(function(){
											window.location = quickLook.currentProductNode.find('a').attr('alt');

											return false;
										});
							
								$('#quickLookDetailBox').fadeTo(1,0.01,function(){
									//Center the box:
								
									$(this)
										.vCenter()
										.css({'opacity': ''})
										.fadeIn(100)
										.addClass('active');
								});
						
							});
						
						}
						$('#quickLookDetailBox > .renderTarget')
							.addClass('error')
							.html('<h2>We\'re sorry - something went wrong.</h2><p>We couldn\'t fetch the product\'s details - you can <a class="retry" href="#tryAgain">try again</a> or <a href="#details" class="skip">see the product on its own page</a>.</p>')
					},
				initialise:
					function(){
						//Find, compile & extract subtemplate nodes from the quickLook template:
						$('#quickLookDetailContents div.subTemplate').each(function(){
							quickLook.templates[this.id] = $(this).children().compile(quickLook.templateDirectives[this.id]);
							$(this).remove();
						});
					
						//Render the templates and cache the results in the templates object:
						quickLook.templates['quickLookDetailContents'] = $('#quickLookDetailContents').compile(quickLook.templateDirectives.quickLookDetailsDisplay);
						
						//Insert the quickLook trigger elements:
						$('li.result', '#productList').append('<span class="quickLookTrigger" title="Quickly see more details about this product.">Quick Look</span>');
						
						if (qlConfig) {
							$.extend(quickLook.defaultAttributes, qlConfig);
						}	
						
						//Assign events on the product grid:
						quickLook.thumbnailHandler('#productList');
						
					}
		}
	
	

	Initialiser.modules.quickLook = function(){
	
	if ($('#quickLookDetailBox').length) {
		//If the box and overlay aren't children of the body, make it so:
		$('#overlayMask, #quickLookDetailBox, #quickLookDetailContents').appendTo('body');
	
		//For now, IE6 doesn't support quickLook:
		if (!($.browser.msie && $.browser.version <= 7.0)) {
			quickLook.initialise();
	
				//The close widget
				if (!$.browser.msie) {
					$('body > div.jqmOverlay, #quickLookDetailBox a.closeWidget').live('click', function(){
						$('#quickLookDetailBox').jqmHide().removeClass('active').children('div').replaceWith('<div class="renderTarget"></div>');
						$('body').removeClass('overlayActive');
						quickLook.flags.navInitialised = false;
					});
				}
	
				//The 'more information link:
				$('#quickLookDetailBox a.detail').live('click', function(){
					var link = $(this),
					href = link.attr('href');
					//Check the values from the attribute selectors:
					$('#quickLookDetailBox ol.selector').each(function(){
						var selectedAttr = $('li.active', this);
						if (!selectedAttr.length) return false;
						selectedAttr.each(function(){
							href += ('&attrValue=' + ($.trim($(this).text())));
						});
					});
					$(this).attr('href', href);
		
					//window.location = href;
				});
	
			} else {
				//This is the rest of the IE6 disable
				$('#quickLookDetailBox, #quickLookDetailContents').hide();
			
			}
		}
	}
})();
