/* 
   ----------------------------------------------------------------
		jQuery Extensions & Patches
   ----------------------------------------------------------------
*/

/* Non-essential behaviours for Dunelm pages */
$(function(){


	
/* 
   ----------------------------------------------------------------
		GLOBAL BEHAVIOURS
		Applied to every page
   ----------------------------------------------------------------
*/

	//*************************************************************************
	// Superfish animated navigation dropdowns + bgiframe plugin + delayed hover plugin

	$(".navigation")
		.superfish({animation : { opacity:"show" }, autoArrows:false, delay:100, speed:'fast', dropShadows:false })
		.find('ul')
			.bgIframe();

	//*************************************************************************

	/* Set the default animation style (the easing plugin has been stripped - you'll need to get a fresh copy if you want to choose another type) */
	jQuery.easing.def = "easeInOutQuad";

	/* SF 30.11.09 - commented this line of script out as it was stopping subsequent scripts from running in IE6 & 7/8 */
	/* Apply spacing to the navigation bar */
	$('#navigation').distribute({childSelector: 'a'});
	
	/* Polish on the header shortcut links, to allow the whole thing to be clickable */
	$('#shortcuts li[class!=search]')
		.hover(
			function(){$(this).addClass('hover');},
			function(){$(this).removeClass('hover');}
		)
		.click(
			//delegate the click to the link inside the basket summary
			function(){
				document.location = $('a:first', this).attr('href');
			}
		);
		
	/* Apply spacing and additional classes to progress lists */
	var progressfutureSteps = false;
	
	$('body#threeDAuthorise #checkout_container ol.progress .active a')
		.html('<span class="numeral security">&nbsp;</span> Authorisation');
	
	$('ol.progress')
		.distribute({leftChildSelector: 'a', bufferSize: 20})
		.children().each(
			function() {
				if ($(this).hasClass('active')) {
					progressfutureSteps = true;
				} else {
					if (progressfutureSteps) {
						$(this).addClass('future');
					} else {
						$(this).addClass('past');
					}
				}
			}
		);
		
	/* Dummy links should have no click behaviour */
	$('a.dummy').click(function(){return false;});
	
	/* This ensures that submenus are at least as wide as their parent menu (anything less looks weird) */
	 $('#navigation ul.sub').each(function() {
		if ($.browser.msie && $.browser.version < 8.0) {
			if ($(this).width() < $(this).parent().width()) {
				$(this)
					.css({'min-width': $(this).parent().width()});
			}
			var width = $(this).width() - 28; //Quick hack to account for padding - naughty
			$(this).find('a').css({'min-width': width});
		}
		$(this).find('a').css({'min-width': $(this).parent().width() + 12});
	 });
	
	//Hide the user feedback messages 
	$('#content > div.message').hide();
	
	/* When 'added to cart' success message is displayed, show it in the context of the cart itself */
	
	if (document.getElementById('addToCartMessage')) {
			$('#basketStatus').addClass('highlighted');
	}
	

	
/* HOME PAGE ENHANCEMENTS ---------------------------------------------------------------- */

	/* Find and initialise any slideshows (included in content spots) */
	
		if ($('#slideShow').length) {
		
		var slideShowElement =  $('#slideShow');
		
			
	if ($.browser.msie && $.browser.version == '6.0') {
			//Pick a random slide and show it:
	
			var slides = slideShowElement.children();
			var randomPick = Math.floor(Math.random()*slides.length);
			slides.hide().filter(':eq(' + randomPick + ')').show();

		} else {
		
			//We'll pull some meta data from the rel attribute on the slideShow:
			//this is because we can't include JS in the content spot itself.
			
			var metaData = slideShowElement.attr('rel');
			
			//default config
			var slideShowConfig = {
				duration: 2000,
				transition: 'fade',
				speed: 1000,
				pager:'#slideShowPager .liner'
			}
			
			//An array of the options we can set from the rel
			var availableOptions = ['transition', 'duration', 'speed']; 
			
				for (var i =0; i < availableOptions.length; i++) {
					var pattern = new RegExp(availableOptions[i] + ":([a-z0-9]+)");
					if (pattern.test(metaData)) {
						slideShowConfig[availableOptions[i]] = pattern.exec(metaData)[1];
					}
				} 
			
			//Initialise the cycle with the new options
			slideShowElement.cycle(slideShowConfig);
		}
	}
	
    //This is a workaround for category thumbnail images not being clickable within anchors...
	if ($.browser.msie) {
		$('#categorylister div.imageFrame img')
			.click(function(e){
				document.location = $(this).closest('a').attr('href');
			});
	}
	
	//Set thumbnail heights to be equal:
	/*$('ul.thumbnails', '#pagebody').each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
	})*/
	
/* PRODUCT LISTER ENHANCEMENTS ---------------------------------------------------------------- */
	
	//Auto submit 'per page' and 'sort' forms when they are changed:
	$('#resultsNavigation form select').change(function(){
		$(this).closest('form').submit();
	});
	
	//Allow the thumbnails to be big, fat clickable links:
	//$('#categorylister ul.categories > li, #productlister ul.products > li')
	//	.click(function(){
	//			document.location = $('a:first', this).attr('href'); //Send the browser to the location of the first link it finds within the thumbnail
	//	})
	
	/* SF 30.11.09 CR043 - Change color of current price if product has was price  */
	
	$('.pricingDetails .mainPrice').prev().addClass('darkerWas');
	$('.pricingDetails .darkerWas').prev().addClass('lighterWas');
	$('.pricingDetails .darkerWas').next().addClass('mainPriceHasWasPrice');


/* PRODUCT DETAILS ENHANCEMENTS ---------------------------------------------------------------- */

   //Fix the bloody alt-image clicks:
   $('#pagebody a.alternativeviewlink')
	   	.click(function(){
	   		var $target = $('#pdlargerimage');
	   		
	   		var newImagePath = $target.attr('href');
	   		var currentImagePath = $(this).attr('href');
	   		
	   		//Swap the alt into the new:
		   		$target
		   			.attr('href', currentImagePath.replace(/large/i, 'extralarge'))
		   		.find('img')
		   			.fadeTo(200, 0.01, function(){
		   				$(this)
		   					.load(function(){$(this).fadeTo(200, 1);})
		   					.attr('src', currentImagePath);
		   					
		   			});
	   			
	   		//Swap the old into the alt:
	   		$(this)
	   			.attr('href', newImagePath.replace(/extralarge/i, 'large'))
	   		.find('img')
	   			.fadeTo(200, 0.01, function(){
	   				$(this)
	   				.load(function(){$(this).fadeTo(200, 1);})
	   				.attr('src',  newImagePath.replace(/extralarge/i, 'medium'));
	   			});
	   		
	   		return false;
	   			
	   });
   
   
	//When an attribute select box has only one option, preselect it, and replace it with text
	/*$('#dropdownoptions select')
		.bind('refresh', function(){
			var options = $(this).children('option');
				if (options.length == 2) { //2 is the magic number - one 'please select' and one value - will change this to have better hooks in the markup
					//Preselect the second option
					options[1].setAttribute('selected', 'selected'); 
					//Hide the select
					//$(this).hide();
					if(!$(this).siblings('label.selectBoxSurrogate').length) {
						$(this)
							.addClass('implicit')
							.after('<label for="' + this.id + '" class="selectBoxSurrogate" title="This product has only one option for this attribute">' + $(options[1]).attr('value') + '</label>');
					} else {
						$(this).siblings('label.selectBoxSurrogate').show();
					}
				} else {
					$(this).show().siblings('label.selectBoxSurrogate').hide();
				}
		})
		.change(function(){
			if (!$(this).hasClass('implicit')) {
				$(this)
						.trigger('refresh')
					.closest('#attributeSelector')
						.find('select.implicit')
							.trigger('refresh'); //Call 'change' on all the hidden selects to ensure the price/part number updates
			}
		})
		.trigger('refresh');
	*/

	/* SF 30.11.09 CR043 - Change color of current price if product has was price  */	
	$('.detailsdisplay .additionalPricingInfo li:last-child').addClass('darkerWas');
	$('.alternativeproduct .additionalPricingInfo ul li:last-child').addClass('darkerWas');
	$('.alternativeproduct .darkerWas').parent().parent().parent().parent().addClass('priceHasWasPrice');
	$('.alternativeproduct .darkerWas').parent().parent().next().addClass('mainPriceHasWasPrice');
	$('.detailsdisplay .darkerWas').parent().parent().next().addClass('mainPriceHasWasPrice');
	$('.detailsdisplay .mainPriceHasWasPrice').parent().parent().parent().addClass('priceHasWasPrice');
	$('.priceHasWasPrice #priceelement').addClass('priceElementHasWasPrice'); /* Dorma only */
	
/* 
		RANGE DETAILS ENHANCEMENTS
   ---------------------------------------------------------------- */
   
	//Highlight the focused item in the range contents list while the user is playing with the form */
	
	$('#pagebody ul.rangeLister').each(function() {
		$('input, select', this).focus(function() {
			$(this).closest('li.rangeItem').addClass('focus').siblings().removeClass('focus');
		});
	});

	//Shunt the alt images around in the DOM
	$('#maincontent > div.imagedisplay > div.alternativeview')
		.appendTo('#maincontent > div.detailsdisplay');
		
	$('div.detailsdisplay, div.imagedisplay', 'body.rangeDetail #maincontent').wrapAll('<div id="liner"></div>');
	
   
   	/* SF 30.11.09 CR043 - Change bkg and color of current price if product has was price  */	
	$('.rangeLister .additionalPricingInfo li:last-child').addClass('darkerWas');
	$('.rangeLister .darkerWas').parent().parent().next().addClass('mainPriceHasWasPrice');
	$('.rangeLister .mainPriceHasWasPrice').parent().parent().parent().parent().addClass('formHasWasPrice');
	
/* 
		FORM ENHANCEMENTS
   ---------------------------------------------------------------- */
/* Add an 'active' class to buttons in IE during the click (simulation of the :active selector) */

	$('button, a.button', 'body')
		.mousedown(function(){
			$(this).addClass('active');
		})
		.mouseup(function(){
			$(this).removeClass('active');
		});


/* Add navigation highlights to forms */

	$('form .field input, form .field select, form .field textarea', '#pagebody').each(function(){
			var formElement = $(this);
			if (formElement.closest('td.actions').length) { //'toggle' fields within a table cell will highlight the whole row:
				formElement
				.focus(function(){
					$(this).closest('tr').addClass('rowFocus');
				})
				.blur(function(){
					$(this).closest('tr').removeClass('rowFocus');
				});
			} else { //Otherwise, just highlight the .field element
				formElement
				.focus(function(){
					$(this).closest('.field').addClass('fieldFocus');
				})
				.blur(function(){
					$(this).closest('.field').removeClass('fieldFocus');
				});
			}
		}); 
		
		
		//Collapsible panels toggle open and shut when a checkbox is selected:
		
		$('#pagebody form div.collapsiblePanel .collapseControl input[type="checkbox"]')
			.click(function(){
				var collapseTarget = $(this).closest('div.collapsiblePanel');
				
				if ($(this).attr('checked')) {
					collapseTarget.addClass('expanded').removeClass('collapsed');
				}
				else {
					collapseTarget.addClass('collapsed').removeClass('expanded');
				}
			});

/* Highlight selected check boxes and radios */
	
	$('form .field, .radiobuttons, .radio, .checkboxes, .selectionItem', '#pagebody')
		.find('input:checked')
			.closest('.field, .radiobuttons, .radio, .checkboxes, .selectionItem')
			.addClass('fieldSelected');
	
	$('#pagebody form .checkboxes input[type=checkbox]').each(function(){
		var formElement = $(this);

		if (formElement.closest('td.actions').length) { //'toggle' fields within a table cell will highlight the whole row:
			formElement.click(function(){
					var relatedLabel = $(this).closest('tr');
					if ($(this).attr('checked')) {
						relatedLabel.addClass('rowSelected');
					} else {
						relatedLabel.removeClass('rowSelected');
					}
				});
		} else {
			formElement.click(function(){
					var relatedLabel = $(this).closest('.checkboxes');
					if ($(this).attr('checked')) {
						relatedLabel.addClass('fieldSelected');
					} else {
						relatedLabel.removeClass('fieldSelected');
					}
				});
		}
		
	});
	
	$('#pagebody form input[type=radio]')
	
		.click(function(){
			var relatedElements = $(this).closest('.radiobuttons');
			
			if (!relatedElements.length) {
				relatedElements = $(this).closest('.selectionGroup').find('.selectionItem'); //Some cases where we want to contain the 'field' within another element, and siblings don't define the relationship
			}
			
			relatedElements.removeClass('fieldSelected');
			
			if ($(this).attr('checked')) {
				$(this).closest(relatedElements.selector).addClass('fieldSelected');
			}
		})
		
		.change(function(){
			if ($(this).attr('checked')) {
				$(this)
					.closest('.radiobuttons, .radio')
						.addClass('fieldSelected')
					.siblings('.radiobuttons,.radio')
						.removeClass('fieldSelected');
			
			}
		});
	
	
/* Checkboxes that enable/disable their sibling inputs: */
	$('#pagebody form input.toggleFieldset')
		.click(function(){
			if ($(this).attr('checked')) {
				$(this).closest('fieldset').removeClass('disabled').find('input').not(this).removeAttr('disabled');
			} else {
				$(this).closest('fieldset').addClass('disabled').find('input').not(this).attr('disabled', 'disabled');
			}
		});

/* 
		WISHLIST ENHANCEMENTS
   ---------------------------------------------------------------- */	
	(function(){

		var wishListForm = $('#WishListForm'); 
		var submitButton = wishListForm.find('button[type=submit]');
		var wishListCheckboxes = wishListForm.find('input[type=checkbox]');
		
		//Disable the 'add to basket' button until a selection is made:
		if ($('input[type=checkbox]:checked', wishListForm).length) {
			submitButton.removeAttr('disabled').removeClass('buttonDisabled');
		} else {
			submitButton.attr('disabled', 'disabled').addClass('buttonDisabled');
		}
		
		$('input[type=checkbox]', wishListForm).click(function(){
			if (wishListCheckboxes.filter(':checked').length) {
				submitButton.removeAttr('disabled').removeClass('buttonDisabled');
			} else {
				submitButton.attr('disabled', 'disabled').addClass('buttonDisabled');
			}
		});
		
	})();
	

/* 
		CHECKOUT ENHANCEMENTS
   ---------------------------------------------------------------- */	
	if ($('#AdvancedCartForm')) {
				$('#AdvancedCartForm input[type=radio]').change(function(){
				$(this).closest('fieldset').find('input.impliedValue').attr('value', this.value);
			});
	}
		
			//Option chooser - where a selection in a checkbox or radio button will 'tab' (show/hide) other elements in the page.
			//Good for making an initial choice, and then asking for more information. Used in the 'store or home delivery?' step.
			
			$('body.delivery_address form.optionChooser')
				.find('input[type=radio]')
					.bind('update', function(){
						if ($(this).attr('checked')) {
							var chosenPanel = $('#' + $(this).attr('value'));
							
							chosenPanel
								.parent()
								.children('div.optionChoice')
									.hide();
	
							chosenPanel.show();
							
							//Specific instances of the chooser:
							//So we can apply extra behaviour to each choice as required:
							if ($(this).attr('id') == 'deliveryChoice_storeDelivery') {
								$('#storeAddressPanel', '#ShipAddressForm').find('input[type=radio]').click();
							}//Pre-select the store address						
							
							if ($(this).attr('id') == 'deliveryChoice_homeDelivery') {
								$('.selectionItem:not(#storeAddressPanel)', '#ShipAddressForm').find('input[type=radio]').click();
							}//Pre-select the home address						
						}
					})
					.click(function(){
						$(this).trigger('update');
					});
					
				//because we move the forms around (and you can't nest forms),
				//Hijack the submit button to send the correct form.
				$('#submitDeliveryMethods')
					.click(function(){
					
					});

			//Update the storeSelectDropDown on change
			$('#checkout_container #storeSelectDropdown').change(
				function(){
					$(this).closest('form').submit();
			});
			
	//Initialise the 'delivery type' option chooser by checking for the presence of a store address panel
	var storeAddress = $('#storeAddressPanel');

	if (storeAddress.length) {
		
		//This is a bit of a dirty hack, brought about by the fact that we can't nest forms.
		//We're going to put a 'for show' clone in the right place in the document,
		//and leave a hidden original inside the form so it can be submitted.
		
		//Cache the original
		var originalAddressBlock = storeAddress;				
				
		//clone the block so we can move it in the DOM
		storeAddress = storeAddress.clone();
		
		//Hide the original
		originalAddressBlock.hide();
	
		//move the store address to the 'deliver to store' option:
		$('#choice_storeDelivery')
			.addClass('addressCards')
			.find('h2')
				.after(storeAddress)
				.html('Collect your order from the following store:');
			
			//update the text in the title:
			Cufon.refresh('#choice_storeDelivery h2');
			
			//Update the label text:
			$('#storeSelectLabel').text('Or, choose another store');
			
		//preselect the 'to store' option
		$('#deliveryChoice_storeDelivery')
			.attr('checked', 'checked')
			.trigger('update');
	}
		
		/* 	Because the 'shipping mode' count isn't available until late in the page,
				add a class to the parent of #shippingModeOverallHeader to allow separate styling */
		$('#shippingModeOverallHeader').parent().addClass('multipleModes');

/* 
		STORE LOCATOR ENHANCEMENTS
   ---------------------------------------------------------------- */	
		
		//When the user types in the postcode search field, disable the drop down
		//Otherwise, the drop down value overrides the search results.
			if ($('#storelocatorform')) {
				$('#storelocatorform input#address')
					.keyup(function(){
						if ($(this).attr('value').length) {
							$('#storeSelectDropdown').attr('disabled', 'disabled');
						} else {
							$('#storeSelectDropdown').removeAttr('disabled');
						}
					});
				
				//Onload, force enable the drop down (some browsers cache the disabled state incorrectly):
				if ($('input#address').length > 0) {
					if ($('input#address').attr('value').length) {
						$('#storeSelectDropdown').attr('disabled', 'disabled');
					} else {
						$('#storeSelectDropdown').removeAttr('disabled');
					}
				}
			}
		
/* 
		CUSTOM PRODUCTS ENHANCEMENTS
   ---------------------------------------------------------------- */	
	
	$('#pagebody .thumbnailChoice input').live("click", function(){
		if ($(this).attr('type') == 'checkbox') {
			if ($(this).attr('checked')) {
				$(this).closest('li').addClass('selected');
			} else {
				$(this).closest('li').removeClass('selected');
			}
		} else if ($(this).attr('type') == 'radio') {
			$(this).closest('li').addClass('selected').siblings().removeClass('selected');
		}
	})
	.filter(':checked').closest('li').addClass('selected'); //Pre-highlight the alrgeady selected ones

/* 
		CLEAN UPS - stuff that probably should happen on the server, but I'm outta time...
   ---------------------------------------------------------------- */	

	//remove empty results navigation from product listers
   $('#pagebody .resultsnavigation:not(:has(*)), #filters > *:not(:has(*)), #resultsNavigation:not(:has(*)), #filters > *:not(:has(*))').remove();//using not: :has to discount text nodes
   
  //Remove forced width on write review iframe:
   $('#submitReviewIframe').removeAttr('width');
});
