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

var topMenuSetupComplete = false;

$(function(){
	//call the function on page load
	regBlockDisplay();
	//call the function when radio button is selected
	$('#newCustomer,#guest').click(function() {
		regBlockDisplay();
	});
	function regBlockDisplay() {
		$('#newCustomer').attr('checked') ? $('#registerBlock').slideDown('swing') : $('#registerBlock').slideUp('swing');
	}
});
function topMenuSetup() {
	if (topMenuSetupComplete) return;
	//moved the distribute function so this has styled it before we set up meganav	
	$('#navigation').distribute({childSelector: 'a'});
	//*************************************************************************
	// Superfish animated navigation dropdowns + bgiframe plugin + delayed hover plugin
		$(".navigation")
			.superfish({animation : { opacity:"show" }, autoArrows:false, delay:100, speed:'fast', dropShadows:false });
		if ($(".megamenu").length)	$(".megamenu").bgIframe();
		else	$(".navigation ul").bgIframe();
				
	//*************************************************************************
	topMenuSetupComplete = true;
}

// setting up the position and fade of the added to basket pop up, made this global as another page uses
var setuppopup = function () {
	//add the close function
	$('#addedToBasket').find('.closeAdd').click(function(){
		$('#addedToBasket').remove();
	});		
	if ($.browser.msie && $.browser.version < 7.0 && !$("#addSwatchesToBasket").length) {
		$('#addedToBasket').queue(function(){	   
		  setTimeout(function(){ 	  	 	
		    $('#addedToBasket').dequeue();
		   $('#addedToBasket').fadeIn(500, function(){$(this).addClass("pngbg")});	   	
		  }, 0 ); 
		});
	}
	else {
		 $('#addedToBasket').fadeIn(500, function(){$(this).addClass("pngbg")});
	}
	
	//hold for 5 seconds
	$('#addedToBasket').queue(function(){	 
	  setTimeout(function(){ 
	    $('#addedToBasket').dequeue();
	    //change to gif bg just before fade out as transparency issue fix
	    $('#addedToBasket').removeClass("pngbg");
	    $('#addedToBasket').fadeOut('fast');	    
	    	   
	  }, 5000 ); 
	});	
	 	
	
	
	//check for the offset of the basketstatus then position 10px below 
	var doneOffsetTest = false;
	var elemToTest = document.getElementById("basketStatus");
	leftOffset = 0;
	topOffset = 0;
	while(!doneOffsetTest) {
		leftOffset += elemToTest.offsetLeft;
		topOffset += elemToTest.offsetTop;
		if (elemToTest.offsetParent.id == "header") {
			doneOffsetTest = true;
		}
		elemToTest = elemToTest.parentNode;
	}		
	//assign it the correct left and top position		
	var basketElem = document.getElementById("basketStatus");		
	//set position relative to the basketstatus element (10px below)
	$('#addedToBasket').css("left",leftOffset+"px")
		.css("top",(topOffset+basketElem.offsetHeight+10)+"px");
}
/* Non-essential behaviours for Dunelm pages */
$(function(){
	
/* 
   ----------------------------------------------------------------
		GLOBAL BEHAVIOURS
		Applied to every page
   ----------------------------------------------------------------
*/
	// comment this line before sending live, this is for testing only
	// $('#navigation > li:gt(5)').remove();


//	console.time("topmenusetup call");
//	topMenuSetup();
//	console.timeEnd("topmenusetup call");
	//*************************************************************************
	// Superfish animated navigation dropdowns + bgiframe plugin + delayed hover plugin
	//nK moved into seperate function to speed up apparent loading times

	/* 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 */
	
	
	//lhn col/exp functions
	
	 	$(".furtherlinks").each(function(){
	 		if (!$(this).parent().find(".Expanded").length) {
	 			$(this).parent().find("ul.bottomlevel").slideToggle("fast");
	 		}
	 		else {
	 			$(this).parent().toggleClass("open");
	 		}
	 		$(this)
	 		.addClass("linkappear")
	 		.click(function(){			 		
	 			$(this)
		 		.parent().find("ul.bottomlevel")
		 		.slideToggle("fast")
		 		.end().toggleClass("open");		 	
	 		})
	 		.parent().addClass("expCol");	 	
	 	});
	
	 
	 	

	
	
	/* 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;
	
	
	
	$('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;});
	
	if (!$(".megamenu").length) {
	
		/* 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 */
	
	
	/*new version of the above function, this will display a newly styled pop up box for 5 seconds then hide*/
			
	var addedToBasketButton = document.getElementById('addedToBasket');
	if (addedToBasketButton) {	
			
			$('#basketStatus').addClass('highlighted');
			var addingToBasketj = $(addedToBasketButton);
			var thisHtml = addingToBasketj.html();
			addingToBasketj.remove();
			// we have to remove this from the original position and append 
			// it to the header as it is causing positional errors in ie6
			$('#header').append('<div id="addedToBasket">'+thisHtml+'</div>');
			
			//this function gets called from another page so have moved outside this function to a global scope
			setuppopup();			
	}
	
/* 
		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');
					}
				});
		}
		
	});
*/

	/* highlight selected fields */
	// start by highlighting already selected fields
	$('#pagebody .addressSelector input[type=radio]').each(
		function() {
			if ($(this).attr('checked') == true) {
				$(this).parents('div.deliveryAddress').addClass('fieldSelected')
			}
		}
	);
	
	// then bind function highlightFields to radios
	$('#pagebody .addressSelector input[type=radio]').bind('click', highlightFields); 

	function highlightFields() {
		var relatedElements = $('form input[type=radio]').not($(this)).parents('.field, div.deliveryAddress');
		var thisElement = $(this).parents('.field, div.deliveryAddress'); 

		thisElement.addClass('fieldSelected');
		relatedElements.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');
			}
		});


	// PLP Deal Lozenge funcionality
	$('ul.thumbnails img.dealImg').bind('click', showDeal); 

	function showDeal(event) {
		var overlay = $(this).siblings('div.dealOverlay'); 
		
		// remove alreaady displayed overlays
		$('.dealOverlayDisplayed').remove(); 

		if (overlay.text().replace(/^\s*|\s*$/g,'') != '') { 
			// make a copy of the overlay
			var overlay_copy = overlay.clone(); 
			
			// add close icon and set its position
			overlay_copy
				.prepend('<p class="close">x</p>')
				.css({position: 'absolute', left: event.pageX, top: event.pageY - overlay.height()}); 
	
			// put the overlay_copy into the body
			$('body').append(overlay_copy); 
	
			// add new classname and display it
			overlay_copy
				.addClass('dealOverlayDisplayed')
				.show(); 
	
			// bind hide function to close icon
			overlay_copy.children('p.close').bind('click', hideDeal);
		}
	}

	function hideDeal() {
		$(this).parents('div.dealOverlay').remove(); 
	}

	// remove overlay on click elsewhere in window
	$(window).bind('click', function(event) {
		if ($('div.dealOverlayDisplayed').length > 0) {
			if (!$(event.target).closest('div.dealOverlayDisplayed, img.dealImg').length) {
				$('div.dealOverlayDisplayed').remove();
			}
		}
	});

	var signInPage = document.getElementById("signInPoint");
	if (signInPage){
		$(signInPage).find("#signInSubmit").after('<span class="ajax-loader"></span>');
		$(signInPage).find(".ajax-loader").hide();
		$(signInPage).find("#RegisterEmailAddressForm").bind('submit', function(event){
			$(signInPage).find(".ajax-loader").show();
			$("#signInSubmit.buttonPrimary, #signInSubmit.actionButton").addClass("buttonDisabled").attr("disabled","disabled");
		});
	}

/* 
		CLEAN UPS
   ---------------------------------------------------------------- */	

	//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');
   
   $(document).ready(function() {
  var searchLabel = $('#CatalogSearchForm label').remove().text();
  $('#searchbox').addClass('placeholder').val(searchLabel).focus(function() {
    if (this.value == searchLabel) {
      $(this).removeClass('placeholder').val('');
    };
  }).blur(function() {
    if (this.value == '') {
      $(this).addClass('placeholder').val(searchLabel);
    };
  });
  $('#CatalogSearchForm').submit(function() {
    if ($('#searchbox').val() == searchLabel) {
      $('#searchbox').val('');
    }
  });
});
   
   
});

