var messageOffset, peekValue, messageHeight, theClickerPosition;

var dialogHeightAccordingToBrowserHeight = 615;
if (jQuery(window).height() < 600) { 
	dialogHeightAccordingToBrowserHeight = (jQuery(window).height() - 50);
}

jQuery(document).ready(function() {
	/*----------------------*/
	/* Site Wide Javascript */
	/*----------------------*/
	
	// content name in content breadcrumbs should not be clickable
	jQuery('#currentPageName a').click(function(e) {
		return false;
	});
	
	// Close a dialog on mouse click outside of it.
	$('.ui-widget-overlay').live('click', function() {
		jQuery('.ui-dialog button').click();
	});

	// Close a dialog on touch outside of it.
	$('.ui-widget-overlay').live('touchend', function() {
		jQuery('.ui-dialog button').click();
	});
	
	if (navigator.platform != 'iPad' &&  navigator.platform != 'iPhone' && navigator.platform != 'iPod') {
		// Mini Basket Drop Down - normal hover function instead of click for iPad
		$('#basketDropdown').hover(showBasket, hideBasket);
	
		// Message bar slider
		// Slightly expand and hide the bar
		var messageOffset = $('#messageSlider').css('right');
		var peekValue = parseFloat(messageOffset, 10) + 5 + 'px';
		var messageHeight = $('#messageSlider').height();
		var theClickerPosition = messageHeight/2;
		
		$('#messageClicker').css({ height : messageHeight}).find('span').css({ marginTop : theClickerPosition});
		$('#messageSlider').fadeIn();
		
		function peek() {
			$('#messageSlider').animate({ right : peekValue}, {queue : false});
		}
		function aboo() {
			$('#messageSlider').animate({ right : messageOffset}, {queue : false});
		}
		// bind the peek-aboo functions
		$('#messageClicker').bind({
			mouseenter : function() {peek();},
			mouseleave : function() {aboo();}
		});
		// Mouse Over toggle to show/hide the bar. Rebinds the peek-aboo functions on close
		$('#messageClicker').mouseover(function(){
			// unbind the peekaboo effect
			$('#messageClicker').unbind('mouseleave').unbind('mouseenter').removeClass('closed');
			// Animate the menu to fly out
			$('#messageSlider').animate({ right : 0});
			// rebind the mouseleave function, to collapse the menu on mouse out		
			$('#messageSlider').bind({
				mouseleave : function() {
					aboo();
					// Rebind the peekaboo effect once the menu has collapsed
					$('#messageClicker').addClass('closed').bind({
						mouseenter : function() {peek();},
						mouseleave : function() {aboo();}
					});				
				}
			})		
		},
			function() {
			$('#messageSlider').animate({ right : messageOffset}, function() {
				$('#messageClicker')
				.bind('mouseenter', function(){peek();})
				.bind('mouseleave', function(){aboo();});
			});
		});
	}
	
	// Enable Palceholder text facility for browsers that dont natively support it
	if(!Modernizr.input.placeholder){	
		$('[placeholder]').focus(function() {
		  var input = $(this);
		  if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		  }
		}).blur(function() {
		  var input = $(this);
		  if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		  }
		}).blur();
		$('[placeholder]').parents('form').submit(function() {
		  $(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
			  input.val('');
			}
		  })
		});
	};

	// Regex constrainer for inputs - enforces an expression on phone number fields
	$('#mobile').filter_input({regex:'[0-9]'});

doRadioBoxes();
	
// Tooltip magic
var showToolTipDeliveryChannels = {
	mouseenter : function(e) {
		var messageText = jQuery(this).find('.longDescription span').text();
		if (messageText != '') {
			jQuery(this).find('.longDescription').show();
		}
	},
	mouseleave : function(e) {
		jQuery(this).find('.longDescription').hide();
	}
}

$('.deliveryChannels li').bind(showToolTipDeliveryChannels);

var showToolTip = {
	mousemove : function (e) {
		var tooltip = $(this).find('.toolTip');
		var x = e.pageX - this.offsetLeft + 10;
		var y = e.pageY - this.offsetTop + 10;
		$(tooltip).css('left', x).css('top', y).show();
	},
	mouseout : function () {
		$(this).find('.toolTip').hide();
	}	
}

// create tabs
$('.tabs').tabs();

// create date picker
$('.datePicker').datepicker({minDate : -20});
	
// Star selector
$('.unratedStars ul li').bind({
	mouseenter : function () {
		$(this).prevAll('li').addClass('starred');
		$(this).nextAll('li').removeClass('starred');
		var starText = $(this).find('span').html();
		$(this).parent().parent().find('.starLegend').html(starText);
	},
	click : function () {
		$(this).addClass('starred ratedStar').siblings('li').removeClass('ratedStar');
		$(this).prevAll('li').addClass('starred');
		$(this).parent().removeClass('norating');
	},
	mouseleave : function () {
		var unratedCheck = $(this).parent().hasClass('norating');
		var stars = $(this).parent().find('li');
		var starText = $(this).parent().parent().find('.ratedStar span').html();
		var ratedStar = $(this).siblings('.ratedStar');
		
		if (unratedCheck) {
			$(stars).removeClass('starred');
			$(this).parent().parent().find('.starLegend').html(' ');
		}
		else {			
			$(ratedStar).prevAll('li').addClass('starred');
			$(ratedStar).nextAll('li').removeClass('starred');			
			$(ratedStar).addClass('starred');
			$(this).parent().parent().find('.starLegend').html(starText);
		}
	}
})

// Search suggestions drop down
$('#searchBox').bind({
	focus : function() {
		$('#searchSuggestions').slideDown('slow','easeInOutQuart');
		basketHide(0);
	},
	blur : function() {
		$('#searchSuggestions').slideUp('slow','easeInOutQuart');
	}
});

jQuery('#basketDropdown').hover(function() {
	showBasket();
	clearTimeout( lastHideBasketID );
}, hideBasket);

jQuery('#basketButton').click(showHideBasket);



//Message bar slider
//Slightly expand and hide the bar
messageOffset = $('#messageSlider').css('right');
peekValue = parseFloat(messageOffset, 10) + 5 + 'px';
messageHeight = $('#messageSlider').height();
theClickerPosition = messageHeight/2;
$('#messageClicker').css({ height : messageHeight}).find('span').css({ marginTop : theClickerPosition});
$('#messageSlider').fadeIn();

//bind the peek-aboo functions
$('#messageClicker').bind({
	mouseenter : function() {peek();},
	mouseleave : function() {aboo();}
});
//Click toggle to show/hide the bar. Rebinds the peek-aboo functions on close
$('#messageClicker').click(function() {
	if ($('#messageSlider').find('#messageClicker').hasClass('closed') === true) {
		showLMB();
	} else {
		hideLMB();
	}
});

/*----------------*/
/* Checkout Pages */
/*----------------*/
// Load the 'add new card' tab on payment options page
var addNewCard = jQuery('#paymentCard').tabs();
jQuery('#addNewcard').click(function() { // bind click event to link
	showElement('#address-2');
	addNewCard.tabs('select', 1); // switch to third tab
	return false;
});

jQuery('#link-for-cards-1').click(function () {
	addNewCard.bind("tabsselect", function(event, ui) {
		if (ui.index == 1) {
			jQuery('#cardType').val('');
		}
	});
});

addNewCard.bind("tabsselect", function(event, ui) {
	if (ui.index == 1) {
		onCardTypeChange(false);
	}
});

// Load the 'add new billing address' tab on payment options page	
var addNewAddress = $('#billingAddress').tabs();
$('#addNewAddress').click(function() { // bind click event to link
	jQuery('#newAddressTab').trigger('click');
	return false;
});

// payment card Icon loader
var paymentCards = [
	['FraserCard', '/dimg/cardtypes_logos/frasercard.png'],
	['HOFAccountCard', '/img/cardtypes_logos/HOFa.png'],
	['Solo', '/img/cardtypes_logos/solo.png'],
	['Diners', '/img/cardtypes_logos/dinersclub.png'],
	['Maestro', '/img/cardtypes_logos/maestro.png'],
	['Visa', '/img/cardtypes_logos/visa.png'],
	['Visa Electron', '/img/logo_cardtype_electron.gif'],
	['MasterCard', '/img/cardtypes_logos/mastercard.png'],
	['Amex', '/img/cardtypes_logos/amex.png'],
	['Switch', '/img/logo_cardtype_switch.gif'],
	['Duet', '/img/logo_cardtype_duet.gif'],
	['Delta', '/img/logo_cardtype_delta.gif'],
	['Electron', '/img/logo_cardtype_electron.gif']
];		

var PayPalCardRows = $('#PayPalCardRows').hide();
var billingAddresses = $('#billingAddresses').hide()
	
$('#cardType').change( function() {
	onCardTypeChange(true);
});

$('#orderConfirmButton').attr('disabled', false);
// Agree to terms and Conditions on OrderPayment.php function
/*$('#termsandconditions').attr('checked', false);
$('#orderConfirmButton').attr('disabled', true);

$('#termsandconditions').bind({ 
	click : function () {
		var checkedBox = $('#termsandconditions').is(':checked');

		if ( !checkedBox ) {	
			$('#orderConfirmButton').attr('disabled', true);			
		}
		if ( checkedBox ) {
			$('#orderConfirmButton').attr('disabled', false);			
		}
	}
});

*/

/*----------------------------------------------*/
/* Landing Pages - Homepage, Main Section Pages 
(mens, womens, home, etc...) 					*/
/*----------------------------------------------*/

/* Centering the landing page image */
	var windowWidth, landingImageWidth, windowOffset, pageContainer, pageOffset;
/*  Set up the functions we need to get widths and offsets*/
	function getWindowWidth() {		windowWidth = jQuery(window).width(); }
	function getImageWidth() {		landingImageWidth = jQuery('#landingSlides div img').width();} 
	function getWindowOffset() {	windowOffset = (windowWidth - landingImageWidth)/2;}

	function getPageWidth() { 		pageContainer = jQuery('#pageContainer').width(); }
	function getPageOffset() {		pageOffset = (windowWidth - pageContainer)/2;}

/* Function to center the image, and offset the title buttons */
	function resizeLandingSpace() {
		getWindowWidth();
		getImageWidth();
		getWindowOffset();
		jQuery('#landingSlides div img').css({ marginLeft : windowOffset});
	
		getPageWidth();
		getPageOffset();
		jQuery('#slideshowPager li a').css({ paddingLeft : pageOffset});
	}
/* Center the image and offset the title button on page load */
	resizeLandingSpace();

/* Detect Window resize and offset the image accordingly */
	jQuery(window).resize(function() { resizeLandingSpace();	});

/* Timer */
	jQuery('#timer div').css({ width : '0'}).parent().hide();
	function startTimer() {
		jQuery('#timer div').animate({ width : '100%'}, 4000);	
	}
	function endTimer() {
		jQuery('#timer div').animate({ width : '0'}, 0);		
	}
	
/* Landing page Slideshow */
	jQuery('.slideshow div img').hide();
	jQuery('.slideshow div img:first').fadeIn(1000, function() {
		// $('#timer').fadeIn(1000);
		// $('#timer div').animate({ width : '100%'}, 6000);

		jQuery('.slideshow').cycle({ 
			fx:     'fade', 
			timeout: 5000,
			speed : 2500,
			pager:  '#slideshowPager',
			slideExpr: 'img',
			before : endTimer,
			after :  startTimer,
			pagerAnchorBuilder: function(idx, slide) { 
	        // return selector string for existing anchor 
    	    return '#slideshowPager li:eq(' + idx + ') a'; 
		    } 			
		 });
	});
	

/*---------------------*/
/* Single Product Page */
/*---------------------*/
/* Product Page Slideshow */	
	$('#productSlidesNav li').live({
		mouseenter : function () {
			$(this).siblings().animate({ opacity : '.5'}, {queue : false});
		},
		mouseleave : function () {
			$(this).siblings().animate({ opacity : '1'}, {queue : false});
		}	
	})
	
	//invoking the creation of the gallery for the product page with the images that will be shown to the visitors
	makeGallery();

/*------------------------------------*/
/* Multi facet product Catalogue Page */
/*------------------------------------*/

// Colour Selector on Multifacet Page
$('.colourSelector.bigSwatches li:not(.fullcolours)').bind({
	click : function () {
		$(this).addClass('selected').siblings().removeClass('selected');		
	}
});

configurePanels();
LHNcheckHashInit();
	
	//ensure that we will throw Coremetrics tags when we use the arrows to switch to the alternative images 
	jQuery('div#nextSlide').click(function() {
		//temp variable that will store the index of the current image that was clicked
		var currentImageIndex = null;
		
		//iterate over all of the created with the Cycle plugin li's with images and check which is the current selected and take its index
		// from the name html attribute
		$('ol#productSlidesNav > li').each(function(element){
			if($(this).hasClass("activeSlide")){
				currentImageIndex = $(this).children().attr("name");
			}
		});
		
		cMetricFunctionCallback(currentImageIndex);
	});
	
	//ensure that we will throw Coremetrics tags when we use the arrows to switch to the next or previous image
	jQuery('div#prevSlide').click(function() {
		//temp variable that will store the index of the current image that was clicked
		var currentImageIndex = null;
		
		//iterate over all of the created with the Cycle plugin li's with images and check which is the current selected and take its index
		// from the name html attribute
		$('ol#productSlidesNav > li').each(function(element){
			if($(this).hasClass("activeSlide")){
				currentImageIndex = $(this).children().attr("name");
			}
		});
		
		//invoke the coremetrics function and pass as a parameter the index of the active image
		cMetricFunctionCallback(currentImageIndex);
	});

	// Request Billing Address to saved cards without one.
	jQuery('input[name=storedOrNewCard]').click(function () {
		linkBillingAddress(jQuery(this).attr('id'));
	});
	
	// Update Cart with Quantities.
	jQuery('select.quantity').change(function () {
		jQuery('#updateCart').trigger('click');
	});
	

	// Update Saved products with Quantities.
	jQuery('select.quantitySaved').change(function () {
		jQuery('#updateWishList').trigger('click');
	});
	
	// Hide all elements that has to be hidden if JS is enabled and active if JS is disabled.
	jQuery('.hiddenSystemElementsWithJS').hide();
	
	jQuery('.productZoom').click(function(){
		makeZoom();
	});	
	
	jQuery('#zoomButton').click(function() {
		makeZoom();
	});
	
	jQuery('.wsoZoomButton').click(function(e) {
		e.preventDefault();
		var currentImageContainerID = jQuery(this).parents('.setProduct').find('.itemDesc').attr('id');
		makeZoomWSOItem(currentImageContainerID);
	});
	
	jQuery(window).resize(function() {
		if (navigator.platform != 'iPad')
			jQuery('.ui-dialog-content').dialog("option", "position", "center");
	});
	
	setUpMiniCartControls();
	
	// Checkout: Gift Message in Checkout Summary Start
	jQuery('.saveGiftMessage').hide();
	jQuery('.remainingCharacters').hide();
	jQuery('.changeGiftMessage').show();
	
	// disable all gift message textareas
	jQuery('.giftmessageEdit').attr('readonly', true);
	jQuery('.giftmessageEdit').click(function() { $(this).blur(); return false; });
	jQuery('.giftmessageEdit').blur();

	
	// bind event handler for edit gift message
	jQuery('.changeGiftMessage').bind({
		click : function () {
			jQuery(this).hide();
			jQuery(this).siblings('.giftmessageEdit').attr('readonly', false);
			jQuery(this).siblings('.giftmessageEdit').click(function() { $(this).focus(); return true; });
			jQuery('.giftmessageEdit').focus();
			jQuery(this).siblings('.saveGiftMessage, .remainingCharacters').show();
			
			return false;
		}
	});
	// bind event handler for save new gift message
	jQuery('.saveGiftMessage').live({
		click : function () {
			jQuery(this).hide();
		
			// set the action
			jQuery('#dwfrm_checkout').append("<input name=\"" + jQuery(this).attr('name') + "\" type=\"hidden\" />");
			jQuery('#dwfrm_checkout').append("<input name=\"viaAjax\" value=\"true\" type=\"hidden\" />");
			
			if (jQuery(this).siblings('.giftmessageEdit').val() != '') {
				jQuery(this).siblings('.changeGiftMessage').html('<span></span>' + editGiftMessageString);
			} else {
				jQuery(this).siblings('.changeGiftMessage').html('<span></span>' + addGiftMessageString);
			}
			
			var giftMessageText = jQuery(this).siblings('.giftmessageEdit').val();
			var lines = giftMessageText.split('\n');
			
			if (lines.length > maxLines) {
				alert(maxLinesInfo);
			}
			
			jQuery(this).siblings('.changeGiftMessage').show();
			var clickedButtone = jQuery(this);
			// perform some ajax magic to save new gift message
			jQuery.ajax({
				url: jQuery(this).parents('form').attr('action'),
				type: 'POST',
				dataType: "html",
				data: jQuery(this).parents('form').serialize(),
				async: false,
				beforeSend: function() {
					clickedButtone.siblings('.giftMessageSystemInfo').removeClass('error');
					clickedButtone.siblings('.giftMessageSystemInfo').html('Saving...').show();
				},
				success: function( data ) {
					clickedButtone.siblings('.giftMessageSystemInfo');
					clickedButtone.siblings('.giftMessageSystemInfo').html('').hide();
				},
				error: function() {
					clickedButtone.siblings('.giftMessageSystemInfo').addClass('error');
					clickedButtone.siblings('.giftMessageSystemInfo').html('Could not save the gift message.').show();
				}
			});
			
			jQuery(this).siblings('.giftmessageEdit').attr('readonly', true);
			jQuery(this).siblings('.giftmessageEdit').click(function() { $(this).blur(); return true; });
			jQuery(this).siblings('.remainingCharacters').hide();
			
			return false;
		}
	});
	
	jQuery('.placeOrder').click(function() { // When .placeOrder is clicked, check if any unsaved gift messages are left and save them first
		jQuery('.saveGiftMessage').each(function(index, element) {
			if (jQuery(element).is(':visible')) {
				jQuery(element).trigger('click');
			}
		});
	});
	
	// Checkout: Gift Message in Checkout Summary End
	
	// Checkout: Billing Step custom JS Start
	//jQuery('#orderConfirmButton').attr('disabled', true);
	jQuery('#TandCsContent').hide();
	//
	jQuery('#TandCsLink').click(function() {
		jQuery('#TandCsContent').dialog({
			autoOpen: true,
			width: 600,
			height: 500,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: jQuery('#TandCsLink').attr('href'),
					type: 'POST',
					success: function (html) {
						jQuery('#TandCsContent').html(html);
					},
					error: function (errorMsg) {
						jQuery('#TandCsContent').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	jQuery('.privacyPolicyModal').click(function() {
		jQuery('#privacyPolicyModal').html('');
		var url = jQuery(this).attr('href');
		jQuery('#privacyPolicyModal').dialog({
			autoOpen: true,
			width: 600,
			height: 615,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#privacyPolicyModal').html(html);
					},
					error: function (errorMsg) {
						jQuery('#privacyPolicyModal').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	jQuery('.pointsTransferFindOutMore').click(function() {
		jQuery('#pointsTransferFindOutMore').html('');
		var url = jQuery(this).attr('href');
		jQuery('#pointsTransferFindOutMore').dialog({
			autoOpen: true,
			width: 600,
			height: 600,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#pointsTransferFindOutMore').html(html);
					},
					error: function (errorMsg) {
						jQuery('#pointsTransferFindOutMore').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	jQuery('.COAddressFindOutMore').click(function() {
		jQuery('#COAddressFindOutMore').html('');
		var url = jQuery(this).attr('href');
		jQuery('#COAddressFindOutMore').dialog({
			autoOpen: true,
			width: 600,
			height: 615,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#COAddressFindOutMore').html(html);
					},
					error: function (errorMsg) {
						jQuery('#COAddressFindOutMore').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	jQuery('.deliveryOptionsAndPrices').click(function() {
		jQuery('#deliveryOptionsAndPrices').html('');
		var url = jQuery(this).attr('href');
		jQuery('#deliveryOptionsAndPrices').dialog({
			autoOpen: true,
			width: 600,
			height: (jQuery(window).height() < 600) ? (jQuery(window).height() - 50) : 615,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#deliveryOptionsAndPrices').html(html);
					},
					error: function (errorMsg) {
						jQuery('#deliveryOptionsAndPrices').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	jQuery('.termsDialog').click(function() {
		jQuery('#termsDialog').html('');
		var url = jQuery(this).attr('href');
		jQuery('#termsDialog').dialog({
			autoOpen: true,
			width: 600,
			height: 615,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#termsDialog').html(html);
					},
					error: function (errorMsg) {
						jQuery('#termsDialog').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	//
	jQuery('.whatIsThisDialog').click(function() {
		var url = jQuery(this).attr('href');
		jQuery('#whatIsThisDialog').dialog({
			autoOpen: true,
			width: 600,
			height: 615,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#whatIsThisDialog').html(html);
					},
					error: function (errorMsg) {
						jQuery('#whatIsThisDialog').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	jQuery('.recognitionWelcome').click(function() {
		var url = jQuery(this).attr('href');
		jQuery('#recognitionWelcome').dialog({
			autoOpen: true,
			width: 600,
			height: 615,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#recognitionWelcome').html(html);
					},
					error: function (errorMsg) {
						jQuery('#recognitionWelcome').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
	
	openDeliveryChannelDialog();
	
	jQuery('transfereeTerms').click(function() {
		
	});
	
	
	if (jQuery('input[name=billingAddressNewOrSaved]').length > 0) { 
		jQuery('input[name=billingAddressNewOrSaved]').hide();
	}
	// Checkout: Billing Step custom JS End
	
	// Checkout: Billing step gift payments box JS Start
	var useGiftCard = jQuery('#giftCards').tabs();
	jQuery('#useGiftCard').click(function() { // bind click event to link
		useGiftCard.tabs('select', 1); // switch to  tab
		return false;
	});	
	jQuery('#useVoucher').click(function() { // bind click event to link
		useGiftCard.tabs('select', 2); // switch to  tab
		return false;
	});	
	jQuery('#usePromo').click(function() { // bind click event to link
		useGiftCard.tabs('select', 3); // switch to  tab
		return false;
	});
	// Checkout: Billing step gift payments box JS Start
	
	// Insert product image data into imageInfoMap for Scene7 display
	if (jQuery('#productSlidesWrapper').length > 0) { // Check if this is a product page because it has a specific div element available
		var images = [];
		
		if (typeof variations != 'undefined') {
			if (variations != '') {
				images = extractImagesFromProductJSON(images);
			}
			else {
				images = scanGalleryForImages(images);
			}
		}
		else {
			images = scanGalleryForImages(images);
		}
		
	}
	
	
	// Ipad, Iphone, Ipod conditional functions. For instances of scrollbars (which arent native to iDevices) and the message bar (position fixed dont work :/ )
	if (navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
		// alternate plugins/functionality
		$('.ipadExpandFacet').toggle(
				function() {
					$(this).parents('.panelSlide').find('.refinementsOsScrollBar').css('max-height', '1800px');
					$(this).parents('.panelSlide').find('.refinementsOsScrollBar').css('height', 'auto');
					$(this).html('Close');
				},
				function() {
					$(this).parents('.panelSlide').find('.refinementsOsScrollBar').css('max-height', '180px');
					$(this).parents('.panelSlide').find('.refinementsOsScrollBar').css('height', 'auto');
					$(this).html('See More');			
				}	
		);	

		jQuery.each($('.ipadExpandFacet'), function(key, value) {
			var siblingRefinementsOsScrollBarMaxLength = $(this).parent().find('.refinementsOsScrollBar').css('max-height');
			siblingRefinementsOsScrollBarMaxLength = parseInt(siblingRefinementsOsScrollBarMaxLength, 10);
			var refinementsContainer = $(this).parent().find('.refinementsOsScrollBar').css('height');
			refinementsContainer = parseInt(refinementsContainer, 10);

			if (refinementsContainer < siblingRefinementsOsScrollBarMaxLength) {
				$(this).hide();
			}
		});
		
		// Mini Basket Drop Down - click function instead of hover for iPad	
		$('#basketDropdown').click(showBasket);

		if (navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
			// Remove little message bar only for iPhone and iPod.
			jQuery('#messageSlider').remove();
		}
	};
	
	
	dhtmlViewerInit();
	
	// Collect+ Order Confirmation Page JS for opening links in an overlay.
	jQuery('#collectPlusPostCodeMatrixLink').click(function () {
		jQuery('#collectPlusDialog').dialog({
			width: 875,
			height: dialogHeightAccordingToBrowserHeight,
			modal: true,
			hide: "fade",
			closeOnEscape : true, 
			buttons: [{
				text: localizeCollectPlusClose,
				click: function() {
					$(this).dialog("close");
				} 
			}]
		});

		return false;
	});
	
	var billingNewCard = jQuery('#hiddenCardRows').length;

	if(billingNewCard > 0){
		onCardTypeChange(false);
	}

	jQuery('#q').keypress(function () {
		if (jQuery(this).val() == '' || jQuery(this).val() == qPlaceHolder) {
			jQuery(this).addClass('placeHolder');
		} else {
			jQuery(this).removeClass('placeHolder');
		}
	});
});

function peek() {
	// alert('Outer peek');
	if (navigator.platform == 'iPad') {
		$('#messageSlider').animate({ width : '350px' }, {queue : false});
	} else {
		$('#messageSlider').animate({ right : peekValue}, {queue : false});
	}
}
function aboo() {
	// alert('Outer aboo');
	if (navigator.platform == 'iPad') {
		$('#messageSlider').animate({ width : '0px'}, {queue : false});
	} else {
		$('#messageSlider').animate({ right : messageOffset}, {queue : false});
	}
}
function showLMB(){
	// unbind the peekaboo effect
	$('#messageClicker').unbind('mouseleave').unbind('mouseenter').removeClass('closed');
	// Animate the menu to fly out
	if (navigator.platform == 'iPad') {
		var contentHeigh = $('#initial_content_asset_height_hidden').val();
		var contentWidth = $('#initial_content_asset_width_hidden').val();
		var rigthValue = $('#initial_content_asset_clicker_right_hidden').val();
		$('#messageSlider').animate({ right: rigthValue + 'px', width : contentWidth + 'px' });
		$('.contentAssetContent').show();
	} else {
		$('#messageSlider').animate({ right : 0});
	}
	// rebind the mouseleave function, to collapse the menu on mouse out		
	$('#messageSlider').bind({
		mouseleave : function() {
			aboo();
			// Rebind the peekaboo effect once the menu has collapsed
			$('#messageClicker').addClass('closed').bind({
				mouseenter : function() {peek();},
				mouseleave : function() {aboo();}
			});				
		}
	})		
}

function hideLMB() {
	if (typeof messageOffset == 'undefined') {
		messageOffset = '-320px';
	}
	
	jQuery('#messageClicker').addClass('closed');

	if (navigator.platform == 'iPad') {
		var contentHeigh = $('#initial_content_asset_height_hidden').val();
		var rigthValue = $('#initial_content_asset_clicker_right_hidden').val();
		$('.contentAssetContent').hide();
		$('#messageSlider').animate({ right: rigthValue, width : '0px'}, function() {
			$('#messageSlider').height(contentHeigh);
			$('#messageClicker')
			.bind('mouseenter', function(){jQuery('.contentAssetContent').show(); peek();})
			.bind('mouseleave', function(){jQuery('.contentAssetContent').hide(); aboo();});
		});
	} else {
		$('#messageSlider').animate({ right : messageOffset}, function() {
			$('#messageClicker')
			.bind('mouseenter', function(){peek();})
			.bind('mouseleave', function(){aboo();});
		});
	}
}


function setUpMiniCartControls() {
	jQuery('#basketContent .quantity').change(function() {
		var quantity = this.name.replace("item_quantity_", "");
		updateProductFromMiniCart(quantity, this.value);

		jQuery('#quantity_select_hidden_' + quantity).val(this.value);
		jQuery('#variants_selected_hidden').find("#productVariantID-" + quantity).html(this.value);
		jQuery('#products_selected_hidden').find("#productID-" + quantity).html(this.value);
		jQuery('#addToBagActionMessage').hide();
		jQuery('#rrContainer').hide();
	});
	
	jQuery('#basketContent .removeButton').click(function() {
		var itemID = this.id.replace("item_id_", "");
		removeProductFromMiniCart(itemID);

		jQuery('#quantity_select_hidden_' + itemID).remove();
		jQuery('#variants_selected_hidden').find("#productVariantID-" + itemID + "_content").remove();
		jQuery('#products_selected_hidden').find("#productID-" + itemID + "_content").remove();
		jQuery('#addToBagActionMessage').hide();
		jQuery('#rrContainer').hide();
	});
}

function showBasket() {
	jQuery('#basketDropdown').addClass("active");
	
	if (jQuery('#basketQuantity').html() != 0) {
		jQuery('#basketContent').fadeIn(200);
	}
}

function hideBasket() {
	jQuery('#basketDropdown').removeClass("active");

	if (jQuery('#basketQuantity').html() != 0) {
		jQuery('#basketContent').hide();
	}
}

function showHideBasket() {
	if (!jQuery('#basketContent').hasClass("active")) {
		showBasket();
	} else {
		hideBasket();
	}
}

function extractImagesFromProductJSON(images) {
	for (variation in variations) {
		jQuery.merge(images, variations[variation].images);
	}
	
	return jQuery.unique(images);
}

function scanGalleryForImages(images) {
	jQuery('#productSlides img').each(function (index, element) {
		images.push(element.src.split('?')[0]);
	});
	
	return images;
}

function insertImageInfoDataIntoMap(image) {
	if (typeof window.imageInfoMap == 'undefined') {
		window.imageInfoMap = {};
	}
	
	jQuery.getScript(image + '?req=ctx,javascript', function() {
		window.imageInfoMap[ image ] = getCurrImageInfo();
	});	
}

function setImageFixed(image) {
	if (typeof window.imageInfoMap == 'undefined') {
		window.imageInfoMap = {};
	}
	
	jQuery.getScript(image + '?req=ctx,javascript', function() {
		imageURL = image.split('?');
		
		//backslash is added bellow to ensure picture names that contain "image" are handled properly
		//e.g. "no_image_available"
		var imageString = imageURL[0].split('/image'); 
		imageString = imageString[1]
		
		var isRoot = imageURL[0].split(imageString);
		isRoot = isRoot[0];

		window.imageInfoMap[ image ] = getCurrImageInfo();

		var imageInfo = window.imageInfoMap[image];
		
		window.s7zoom = new SjZViewer(isRoot, imageString, 650, 532, imageInfo.width, imageInfo.height);
		
		s7zoom.setZoomStep(1);
		s7zoom.setMaxZoom(100);
	  	s7zoom.addToPage(false);
		s7zoom.setTurnTime(0.5);
		s7zoom.setTransitionTime(0.5);
		s7zoom.setBackground('0xffffff');
		s7zoom.zviewer.setWaitIconURL(staticRoot+'img/loading.gif');
		s7zoom.setWaitIconTimer('0.5,0.1');
		
		imageControls();
	});
}

function getImageToZoom() {
	var imageToZoom = jQuery('#productSlides img:visible').attr('src');
	return imageToZoom;
}

function getWSOItemImageToZoom(currentImageContainerID) {
	var imageToZoom = jQuery('#' + currentImageContainerID).find('a img').attr('src');
	return imageToZoom;
}

var imageURL;

function dhtmlViewerInit() {
	var productImage = jQuery('#productImage');
	
	if (productImage.length > 0) {	
		imageURL = productImage.attr('src');
		imageURL = imageURL.split('?');
	
		//backslash is added bellow to ensure picture names that contain "image" are handled properly
		//e.g. "no_image_available"
		var imageString = imageURL[0].split('/image'); 
		imageString = imageString[1]
		
		var isRoot = imageURL[0].split(imageString);
		isRoot = isRoot[0];
		
		var imageWidth = imageURL[1].split('wid=');
		imageWidth = imageWidth[1].split('&');
		imageWidth = imageWidth[0];


		jQuery.getScript(isRoot + imageString + '?req=ctx,javascript', function() {
			window.imageInfoMap[ isRoot + imageString ] = getCurrImageInfo();

			var imageInfo = window.imageInfoMap[isRoot + imageString];
			
			window.s7zoom = new SjZViewer(isRoot, imageString, 650, 532, imageInfo.width, imageInfo.height);
			
			s7zoom.setZoomStep(1);
			s7zoom.setMaxZoom(100);
		  	s7zoom.addToPage(false);
			s7zoom.setTurnTime(0.5);
			s7zoom.setTransitionTime(0.5);
			s7zoom.setBackground('0xffffff');
			s7zoom.zviewer.setWaitIconURL(staticRoot+'img/loading.gif');
			s7zoom.setWaitIconTimer('0.5,0.1');
			
			imageControls();
		});
		
	}
	else {
		//
	}
}

function addThumbsToZoomDialog(thumbsList) {
		
	thumbsList.empty();
	
	jQuery('#productSlidesNav li img').each(function(index, value) {
		thumbsList
			.append(jQuery('<li></li>')
				.append(
					jQuery(this).clone()
				)
			);
		

		if (jQuery(this).parent('li').hasClass('activeSlide')) {
			jQuery('#izViewThumbs li:eq(' + index + ')').addClass('activeSlide');
		} else {
			jQuery('#izViewThumbs li:eq(' + index + ')').removeClass('activeSlide');
		}
	});
}

var zoomIsSet = false;
function makeZoom() {
	
	var titleProductNameBrandName = '';
	if (jQuery('#productTitle').find('.productName').html() != '' && jQuery('#productTitle').find('.productName').html() != null) {
		titleProductNameBrandName = jQuery('#productTitle').find('.productName').html();
	}

	if (jQuery('#productTitle').find('.brandname').html() != '' && jQuery('#productTitle').find('.brandname').html() != null) {
		if (jQuery('#productTitle').find('.productName').html() != '') {
			titleProductNameBrandName += ' - ';
		}
		
		titleProductNameBrandName += jQuery('#productTitle').find('.brandname').html();
	}
	
	var zoomViewerHTML = '<div id="izViewBorder">' +
							'<img alt="Zoom" src="' + getImageToZoom() + '" style="display: none;" id="productImage">' +
							
							'<div id="izView">' +
								'<span class="trans" id="frame1"></span>' +
								'<span class="trans" id="frame2"></span>' +
							'</div>' +
							
						'</div>' +
						
						'<div id="imageController">' +
						    '<a class="silverButton zoomButton" id="zoomInButton" title="Zoom In"><span></span>Zoom In</a>' + 
						    '<a class="silverButton zoomButton" id="zoomOutButton" title="Zoom Out"><span></span>Zoom Out</a>' +
						    '<a class="silverButton zoomButton" id="resetButton" title="Reset"><span></span>Reset view</a>' +
						' <div id="imagePreviewLabel">Click and drag the main image to view in more detail.</div></div>' +
						
						'<ol id="izViewThumbs"></ol>';
	
	
	// checking for an already used zoom div 
	if (jQuery('#izViewBorder').length > 0) {
		var izViewBorder = jQuery('#izViewBorder');
	}
	else { // if does not exist create one
				
		var izViewBorder = jQuery('<div id="zoomContainer" title="' + titleProductNameBrandName + '">' +
				
									zoomViewerHTML +
									
								  '</div>').appendTo(document.body);
	}
	
	var thumbsList = jQuery('#izViewThumbs');
	
	addThumbsToZoomDialog(thumbsList);

	if (window.zoomDialog === undefined) {
		// start the dialog
		window.zoomDialog = izViewBorder.dialog({
			draggable: true,
			width: 875,
			height: 572,
			closeOnEscape: true,
			hide: "fade",
			modal: true,
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
	}
	else {
		//changes the dialog html
		jQuery('#zoomContainer').html(zoomViewerHTML);
		
		//adds thumbs to the dialog window
		thumbsList = jQuery('#izViewThumbs');
		addThumbsToZoomDialog(thumbsList);
		
		//changes the title of the dialog
		jQuery('#ui-dialog-title-zoomContainer').html(titleProductNameBrandName);
		jQuery('#ui-dialog-title-zoomContainer').attr('title', titleProductNameBrandName);
		
		window.zoomDialog.dialog('open');
	}

	// hide the guiding text when hovering the zoom
	jQuery('#izViewBorder').bind({
		mouseenter : function() {
			jQuery(this).find('#imagePreviewLabel').hide();
		},
		mouseleave : function() {
			jQuery(this).find('#imagePreviewLabel').show();
		}
	});
	
	thumbsList.find('img').click(function() {
		var thumbLink = jQuery(this).attr('src');
		
		var thumbLinkURL = thumbLink.split('?');
		
		imageURL[0] = thumbLinkURL[0];
		setImageFixed(imageURL[0]);

		jQuery.each(jQuery('#izViewThumbs li'), function () {
			jQuery(this).removeClass('activeSlide');
		});
		jQuery(this).parent().addClass('activeSlide');
	});
	

	if (!zoomIsSet) {
		dhtmlViewerInit();
		zoomIsSet = true;
	}
	else {
		var imageToZoom = getImageToZoom();
		var imageToZoomURL = imageToZoom.split('?');

		imageURL[0] = imageToZoomURL[0];
		setImageFixed(imageURL[0]);
	}
}

var zoomWSOIsSet = false;
function makeZoomWSOItem(currentImageContainerID) {
	var titleProductNameBrandName = '';
	var prodCode = jQuery('#' + currentImageContainerID).find('.productCode').html().split(":");
	prodCode = jQuery.trim(prodCode[1]);
	if (jQuery('#' + currentImageContainerID).find('.WSOProductName').html() != '' && jQuery('#' + currentImageContainerID).find('.WSOProductName').html() != null) {
		titleProductNameBrandName = jQuery('#' + currentImageContainerID).find('.WSOProductName').html();
	}

	if (jQuery('#' + currentImageContainerID).find('.WSOBrandName').html() != '' && jQuery('#' + currentImageContainerID).find('.WSOBrandName').html() != null) {
		if (jQuery('#' + currentImageContainerID).find('.WSOProductName').html() != '' && jQuery('#' + currentImageContainerID).find('.WSOProductName').html() != null) {
			titleProductNameBrandName += ' - ';
		}
		
		titleProductNameBrandName += jQuery('#' + currentImageContainerID).find('.WSOBrandName').html();
	}
	
	var zoomViewerHTML = '<div id="izViewBorder">' +
								'<input type="hidden"  id="prodCode" value="'+prodCode+'"/>'+
								'<img alt="Zoom" src="' + getWSOItemImageToZoom(currentImageContainerID) + '" style="display: none;" id="productImage">' +
								
								'<div id="izView">' +
									'<span class="trans" id="frame1"></span>' +
									'<span class="trans" id="frame2"></span>' +
								'</div>' +
								
							'</div>' +
							
							'<div id="imageController">' +
						        '<a class="silverButton zoomButton" id="zoomInButton" title="Zoom In"><span></span>Zoom In</a>' + 
						        '<a class="silverButton zoomButton" id="zoomOutButton" title="Zoom Out"><span></span>Zoom Out</a>' +
						        '<a class="silverButton zoomButton" id="resetButton" title="Reset"><span></span>Reset view</a>' +
						    ' <div id="imagePreviewLabel">Click and drag the main image to view in more detail.</div>' +
						    '</div>' ;
	
	// checking for an already used zoom div 
	if (jQuery('#izViewBorder').length > 0) {		
		var izViewBorder = jQuery('#zoomContainer');
	}
	else { // if does not exist create one		
		
		var izViewBorder = jQuery('<div id="zoomContainer" title="' + titleProductNameBrandName + '">' + 
				
										zoomViewerHTML +
				
										'</div>'
									).appendTo(document.body);
	}

	if (window.zoomDialog === undefined) {
		// start the dialog
		window.zoomDialog = izViewBorder.dialog({
			draggable: true,
			width: 875,
			height: 572,
			closeOnEscape: true,
			hide: "fade",
			modal: true,
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
	}
	else {
		//changes the dialog html
		jQuery('#zoomContainer').html(zoomViewerHTML);
		
		//changes the title of the dialog
		jQuery('#ui-dialog-title-zoomContainer').html(titleProductNameBrandName);
		jQuery('#ui-dialog-title-zoomContainer').attr('title', titleProductNameBrandName);
		
		window.zoomDialog.dialog('open');
	}

	// hide the guiding text when hovering the zoom
	jQuery('#izViewBorder').bind({
		mouseenter : function() {
			jQuery(this).find('#imagePreviewLabel').hide();
		},
		mouseleave : function() {
			jQuery(this).find('#imagePreviewLabel').show();
		}
	});

	if (!zoomWSOIsSet) {
		dhtmlViewerInit();
		zoomWSOIsSet = true;
	}
	else {
		var imageToZoom = getWSOItemImageToZoom(currentImageContainerID);
		var imageToZoomURL = imageToZoom.split('?');

		imageURL[0] = imageToZoomURL[0];
		setImageFixed(imageURL[0]);
	}
}

function makeVideo() {
 	var videoWidth = parseInt(jQuery('#videoPlayer').attr('width')) + 35;
 	var videoHeight = parseInt(jQuery('#videoPlayer').attr('height')) + 100;
    
 	jQuery('#videoPopUp').dialog({
		width: videoWidth,
		height: videoHeight,
		modal: true,
		hide: "fade",
		close: function() {
 			//HOF-5400 remove and add back the video so that the playback stops
 			var clone = jQuery('[name="videoPopupContainer"]').clone(true);
 			jQuery('[name="videoPopupContainer"]').remove();
 			jQuery('#videoPopUp').html(clone);
 		},
		closeOnEscape : true, 
		buttons: {
			"Close": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
 	
 	// Repositioning of the Video dialog after window resizing.
	$(window).smartresize(function(){  
		jQuery('#videoPopUp').dialog("option", "position", "center");
	});
}

function makeSpinView() {
	var spinViewWidth = 710;
	var spinViewHeight = 615;
	
	jQuery('#spinViewPopUp').dialog({
		width: spinViewWidth,
		height: spinViewHeight,
		modal: true,
		hide : "fade",
		closeOnEscape: true,
		buttons: {
		"Close": function() { 
			$(this).dialog("close"); 
		} 
	}
	});
}

function makeGallery() {
	jQuery('#productSlides').cycle({
		timeout: 0,
		speed : 500,
		easeIn : 'easeInQuart',
		easeOut : 'easeOutQuart',
		next:   '#nextSlide', 
		prev:   '#prevSlide',
		pager : '#productSlidesNav',
		pagerAnchorBuilder: function(idx, slide) { 
			return '<li><img class="thumb" name="' + (Number(idx)+1) + '"src="' + slide.src + '" width="54" height="72" /></li>'; 
		} 			
	});
	
	
	//ensure that we will throw Coremetrics tags when clicking on the alternative images below the big one
	$('ol#productSlidesNav li').click(function() {
		//temp variable that will store the index of the current image that was clicked
		var currentImageIndex = null;
		
		//iterate over all of the created with the Cycle plugin li's with images and check which is the current selected and take its index
		// from the name html attribute
		$('ol#productSlidesNav > li').each(function(element){
			if($(this).hasClass("activeSlide")){
				currentImageIndex = $(this).children().attr("name");
			}
		});
		
		cMetricFunctionCallback(currentImageIndex);
	});
	
	if (jQuery('ol#productSlidesNav li').length < 1) {
		jQuery('#nextSlide').hide();
		jQuery('#prevSlide').hide();
	}
	else {
		jQuery('#nextSlide').show();
		jQuery('#prevSlide').show();
	}
}

//defining the function that will invoke the throw of the coremetrics tag
function cMetricFunctionCallback(imageIndex) {
	sendProductImagesCMData("Image Alternate"+imageIndex);
}

function doRadioBoxes() {
	$('.radioBox').find('input[type=radio]:checked').parent().parent('.radioBox').addClass('current');
	
	$('.radioBox input, .radioBox select').bind({
		click : function () {
			$('.radioBox').removeClass('current');
			$(this).parents('.radioBox').addClass('current');
		}
	});
	


	// size selector 
	$('.sizeSelector').find('input[type=radio]:checked').parent().parent().addClass('checked');
	$('.sizeSelector label').append('<span class="radio"></span>');
	$('.sizeSelector input[type=radio]').css({ position : 'absolute', top : '-1000em', left : '-1000em'});
	
	$('.sizeSelector li').click(function() {
		var input = $(this).find("input[type=radio]");
		if (input.is(':checked')) {
			$(this).siblings().removeClass('checked');
			$(this).addClass('checked');
			$(this).find('input').attr('checked', true);
		}
	});
}

function onCardTypeChange(dropDownChange) {
	if (dropDownChange === true) {
		var billingAddressNewOrSaved = jQuery('input[name=billingAddressNewOrSaved]');
		$.each(billingAddressNewOrSaved, function (index, billingAddressRadio) {
			jQuery(billingAddressRadio).attr('checked', false);
		});
		jQuery('#saved-address').attr('checked', true);
	} else if (jQuery('#saved-address').attr('checked') === false && jQuery('#new-address').attr('checked') === false) {
		jQuery('#saved-address').attr('checked', true);
	}
	
	var cardtypeValue = jQuery('#cardType option:selected').val();
	if (cardtypeValue == 'Paypal') {
		// Paypal
		jQuery('#hiddenCardRows p.row, #billingAddresses').hide();
		jQuery(PayPalCardRows).fadeIn(); 
	}

	if (cardtypeValue == 'Maestro') {
		jQuery('#cardrowName, #cardrowNumber, #cardrowStartdate, #cardrowIssue,  #cardrowExpirydate, #billingAddresses').fadeIn();
		jQuery('#cvvCode').removeClass('required');
		jQuery('#cvvCode').attr('disabled', false);
		jQuery('#cardrowSecurity').fadeIn();
	} else if (cardtypeValue == 'FraserCard') {
		jQuery('#cardrowName, #cardrowNumber').fadeIn();
		jQuery('#cardrowSecurity, #cardrowIssue, #cardrowStartdate, #cardrowExpirydate').hide();
		jQuery('#cvvCode').attr('disabled', true);
		jQuery('#billingAddresses').fadeIn();
	} else if (cardtypeValue == 'HOFAccountCard') {
		jQuery('#cardrowName, #cardrowNumber, #cardrowExpirydate').fadeIn();
		jQuery('#cardrowSecurity, #cardrowIssue, #cardrowStartdate').hide();
		jQuery('#cvvCode').attr('disabled', true);
		jQuery('#billingAddresses').fadeIn();
	} else {
		// All other cards
		jQuery('#cvvCode').attr('disabled', false);
		jQuery('#cvvCode').addClass('required');
		jQuery('#cardrowName, #cardrowNumber, #cardrowExpirydate, #cardrowSecurity').fadeIn();
		if (cardtypeValue != '') {
			jQuery('#billingAddresses').fadeIn();
		}
		jQuery('#cardrowStartdate').fadeIn();
		jQuery('#cardrowIssue').hide();
	}

	if (cardtypeValue == '') {
		// no card selected
		jQuery('#hiddenCardRows p.row,  #billingAddresses').hide();
	};
}

function linkBillingAddress (id) {
	var hasLinkedAddress = jQuery('#' + id + '_hasLinkedAddress').val();
	
	if (hasLinkedAddress == 'false') {
		$('#billingAddresses').fadeIn();
	} else {
		var billingAddressNewOrSaved = $('input[name=billingAddressNewOrSaved], input[name=savedBillingAddress]');
		$.each(billingAddressNewOrSaved, function (index, billingAddressRadio) {
			jQuery(billingAddressRadio).attr('checked', false);
		});

		$('#billingAddresses').fadeOut();
	}
}

function configurePanels()
{
	// Product Thumbnail rollover in listing. Shows second image if available
	$('.productImage').bind({
		mouseenter : function () {
			var imageCount = $(this).find('img').size();
			if (imageCount > 1) {
				$(this).find('img:nth-child(1)').hide();
			}
		},
		mouseleave : function () {
			$(this).find('img:nth-child(1)').show();
		}	
	});
	
	// The clear all button, which clears any checked fields in the panels
	$('.clearall').bind({
		click : function() {
			$(this).parent().find('input').attr('checked', false).parent('label').removeClass('checked').addClass('unchecked');
		}
	});
	// reset button. Deselects all checkboxes
	$('.resetall').bind({
		click : function() {
			$('#refineControls .panel').find('input').attr('checked', false).parent('label').removeClass('checked').addClass('unchecked');
		}
	});



	// Checkbox image replacement. The actual checkbox is hidden via CSS, and this script handles the click event, which 
	// changes the state of the background image
		$('.panel label input').hide();
		$('.panel label').prepend('<span class="checkBox"></span>');

	// Add the relevant class to the parent label ie, checked or unchecked box	
	// unchecked boxes
		$('.panel input:checkbox:not(:checked, :disabled)').parent('label').addClass('unchecked');
	// checked boxes
		$('.panel input:checkbox:checked').parent('label').addClass('checked');
	// disabled boxes
		$('.panel input:checkbox:disabled').parent('label').addClass('disabled');
		
		$('.checkBoxes label').bind({
			click : function() {
				if(jQuery(this).children('a').length>0)
				{
					jQuery(this).children('a').click();
				}
			}	
		});

	// event handler for radios
		$('.radioButtons label').bind({
			click : function() {
				$(this).addClass('checked').siblings().removeClass('checked');
				$(this).find('input').attr('checked', true);
			}	
		});

		
		
	// BEGIN: behaviour of Chanel and Mac menu's
	jQuery(".accordianBrandMenu:not(.special) .panel li > a ").each(function(index, element){
		if(jQuery(this).hasClass('chosenBrandCategory')) {
			jQuery(this).parents(".panel").addClass("active");
			jQuery(this).parents(".panelSlide").css("display","block");
		}
	});
	
	// add the arrows to show open or closed panel status
	$(".accordianBrandMenu .panel h3").prepend('<span></span>');
	$(".accordianBrandMenu .active").find('.panelSlide').show();
	
	$(".accordianBrandMenu .panel h3").click(function(){
		var currentlyClickedH3 = jQuery(this);
		$(this).parent().find('.panelSlide').slideToggle('slow','easeInOutQuart');	
		$(this).parent().toggleClass("active");
		
		jQuery(".accordianBrandMenu .panel h3").each(function(index,element){
			if(currentlyClickedH3.get(0) == jQuery(this).get(0)) {
				return true;
			}

			if(jQuery(this).parent().find("a").hasClass('chosenBrandCategory')){
				return true;
			}
			
			if(jQuery(this).parent().hasClass("active")) {
				$(this).parent().find('.panelSlide').slideToggle('slow','easeInOutQuart');	
				$(this).parent().toggleClass("active");
			}
		});
	});
	
	// END: behaviour of Chanel and Mac menu's
		
	jQuery(".accordian .panel").each(function(index, element){
		if(typeof refinementsOpenedPanels == "undefined")
		{
			refinementsOpenedPanels=3;
		}
		if(index<refinementsOpenedPanels)
		{	
			jQuery(this).addClass("active");
			jQuery(this).parent().find('.panelSlide').show();				
		}
	});


	// Collapse any Panels with the class of 'active', and hide the 'clearall' button
		$(".accordian .panel:not(.active)").find('.panelSlide').hide().parent('.panel').find('.clearall').addClass("hidden");
	// Event handler for the collapse panel function, on the H2 click
		$(".accordian .panel h3").click(function(){
			$(this).parent().find('.panelSlide').slideToggle('slow', 'easeInOutQuart', function() {
				// Ipad, Iphone, Ipod conditional functions. For instances of scrollbars (which arent native to iDevices) and the message bar (position fixed dont work :/ )
				if (navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
					var refinementsOsScrollBarMaxLength = $(this).find('.refinementsOsScrollBar').css('max-height');
					refinementsOsScrollBarMaxLength = parseInt(refinementsOsScrollBarMaxLength.replace('px', ''), 10);
					var refinementsContainer = $(this).find('.refinementsOsScrollBar').css('height');
					refinementsContainer = parseInt(refinementsContainer.replace('px', ''), 10);

					if (refinementsContainer >= refinementsOsScrollBarMaxLength) {
						$(this).find('.ipadExpandFacet').show();
					} else {
						$(this).find('.ipadExpandFacet').hide();
					}
				}
			});	
			$(this).parent().toggleClass("active");
			$(this).parent('.panel').find('.clearall').toggleClass("hidden");
		});

		jQuery('#brandRefinements .accordian .panel h3').unbind('click');
		jQuery('#brandRefinements .accordian .panel h3').click(function(){
	
			var isActive = false;
			if(jQuery(this).parent().hasClass('active')){
				isActive = true;
			}
			
			jQuery.each(jQuery('#brandRefinements .accordian .active h3'), function() {
				jQuery(this).parent().find('.panelSlide').slideToggle('slow','easeInOutQuart');		
				jQuery(this).parent().removeClass("active");
				jQuery(this).parent().find('.panelSlide').hide();
			});
			
			if(!isActive){
				jQuery(this).parent().find('.panelSlide').slideToggle('slow','easeInOutQuart');	
				jQuery(this).parent().addClass("active");
				jQuery(this).parent('.panel').find('.clearall').addClass("hidden");
			}
		});
		
	// add the arrows to show open or closed panel status
		$(".accordian .panel h3").prepend('<span></span>');

		clearAllCheck();
		
		var lastBrand = "0";
		jQuery("div.leftColumn div#refineControls div.panel ul#brandListAZ a").each(function()
				{
					var toChar = jQuery(this).attr("id").charAt(jQuery(this).attr("id").length-1).toLowerCase();
					if(jQuery("#brands_"+toChar).length==0)
					{
						jQuery(this).attr("class","disabled");
						return;
					}
					if(lastBrand.charCodeAt(0)<toChar.charCodeAt(0))
					{
						lastBrand = toChar;
					}
				});
		jQuery("div.leftColumn div#refineControls div.panel a").click(
				function(e)
				{
					if(jQuery(this).attr("href")==undefined)
					{
						return false;
					}
					isCalled = true;
					var parentOfTheClickedLink = jQuery(this).parents("div.panel");
					var checkedBox = $(this).parent().hasClass('checked');
					var disabledBox = $(this).parent().hasClass('disabled');
					var selectedARefinement = jQuery(this);

								if (disabledBox) {null}
								if(checkedBox && !disabledBox) {
									$(this).parent().removeClass('checked').addClass('unchecked')
									.find('input:checked').attr('checked', false);						
								}
								if (!checkedBox && !disabledBox) {
									$(this).parent().removeClass('unchecked').addClass('checked')
									.find('input:not(:checked)').attr('checked', true);
								};
					var link = e.target + "&ajaxsearchrefinement";
					window.searchRefinementsContainer=new Array();
					jQuery("div#refineControls div.accordian div.panel").each(function()
							{
								var tempArray = new Array();
								tempArray[0]=jQuery(this).attr("id");
								tempArray[1]=jQuery(this).attr("class");
								tempArray[2]=jQuery(this).find("div.panelSlide").attr("style");
								tempArray[3]=null;
								tempArray[4]=null;
								if(jQuery(parentOfTheClickedLink).attr("id")==tempArray[0])
								{
									tempArray[3]=jQuery(this).find("div.jspPane").attr("style");
									tempArray[4]=jQuery(this).find("div.jspDrag").attr("style");
								}
								window.searchRefinementsContainer.push(tempArray);
							});
					jQuery.blockUI();
					window.LHNisCalled = true;
					
					if(jQuery(this).parents(".priceSlider").length > 0 && jQuery("div.leftColumn.interstitial").length < 1){
						return false ;
					}
					
					jQuery.ajax(
							{
								url: link,
								success: function(data)
								{
									if(data=="" || jQuery(data).find(".productListing").length < 1)
									{
										jQuery.unblockUI();
										var checkedBox = selectedARefinement.parent().hasClass('checked');
										var disabledBox = selectedARefinement.parent().hasClass('disabled');

										if (disabledBox) {null}
										if(checkedBox && !disabledBox) {
											selectedARefinement.parent().removeClass('checked').addClass('unchecked')
											.find('input:checked').attr('checked', false);						
										}
										if (!checkedBox && !disabledBox) {
											selectedARefinement.parent().removeClass('unchecked').addClass('checked')
											.find('input:not(:checked)').attr('checked', true);
										};
										jQuery('#ajaxRefinementsWarningDialog').dialog({
											autoOpen: true,
											width: 450,
											height: 150,
											modal : true,
											show: "fade",
											closeOnEscape: true,
											hide: "fade",
											buttons: {
												"Reset All": function () {
													window.location = ResetAllRefinementsURL;
												},
												"Close": function() { 
													$(this).dialog("close"); 
												}
											}
										});
										return;
									}
									jQuery("div#productSearchRefinementsAjaxContainer").html(data);
									
									var str = jQuery.param.querystring(link);
								    var url = window.location.href;
								    var hash = window.location.hash;
								    var index_of_hash = url.indexOf(hash) || url.length;
								    var hashless_url = url.substr(0, index_of_hash);
								    if ( str == "" || str=="fix&spcl&ajaxsearchrefinement") {
								    	window.location = link.replace("fix&spcl","").replace("&ajaxsearchrefinement","");
								    } else {
								    	window.location = hashless_url + '#' +  link;
								    }
								    window.LHNcurrentHashValue=window.location.hash;
								    
									configurePanels();
									jQuery("div#refineControls div.accordian div.panel").each(function()
											{
												for(var i=0;i<window.searchRefinementsContainer.length;i++)
												{
													if(window.searchRefinementsContainer[i][0]==jQuery(this).attr("id"))
													{
														jQuery(this).attr("class",window.searchRefinementsContainer[i][1]);
														jQuery(this).find("div.panelSlide").attr("style",window.searchRefinementsContainer[i][2]);
														if(window.searchRefinementsContainer[i][3]!=null)
														{
															jQuery(this).find("div.jspPane").attr("style",window.searchRefinementsContainer[i][3]);
															jQuery(this).find("div.jspDrag").attr("style",window.searchRefinementsContainer[i][4]);
														}
														break;
													}
												}
											});
									jQuery(".accordian .panel.active").find('.clearall.hidden').removeClass("hidden");
									$(".accordian .panel:not(.active)").find('.panelSlide').hide().parent('.panel').find('.clearall').addClass("hidden");
									jQuery.unblockUI();
									window.LHNisCalled = false;
								}
							}
							);
					return false;
				});
		jQuery("div.leftColumn.interstitial div#refineControls div.panel a:not(.restrictPrices)").unbind('click');
		jQuery("div.leftColumn div#refineControls div.panel ul#brandListAZ a").unbind('click');
		jQuery("div.leftColumn div#refineControls div.panel ul#brandListAZ a").click(function()
				{
					if(jQuery(this).attr("class")=="disabled")
					{
						return false;
					}
					jQuery("div.leftColumn div#refineControls div.panel ul#brandListAZ a").each(function()
							{
								if(jQuery(this).attr("class")=="current")
								{
									jQuery(this).removeAttr("class");
								}
							});
					jQuery(this).attr("class","current");
					var toChar = jQuery(this).attr("id").charAt(jQuery(this).attr("id").length-1).toLowerCase();
					if(jQuery("#brands_"+toChar).length==0)
					{
						jQuery("div.leftColumn div#refineControls div.panel ul#brandListAZ").parent().scrollTop(0);
						return false;
					}
					if(lastBrand.length==1)
					{
						jQuery("#brands_"+lastBrand).focus();
					}
					jQuery("#brands_"+toChar).focus();
					return false;
				});
		
		jQuery('#sizingBut').click(function() {
			jQuery('#newSizingDialog').dialog({
				   width: 800,
				   height: 500,
				   modal : true,
				   show: "fade",
				   closeOnEscape: true,
				   hide: "fade", 
				   buttons: {
					"Close": function() { 
						$(this).dialog("close"); 
						} 
					}
			});
			
			if(navigator.platform == 'iPad'){
				jQuery('#newSizingDialog').parents(".ui-dialog").css("left", "112px");
			}
		});

		jQuery('.oldsizingBut, #oldsizingBut').click(function() {
			var idForSizeGuide = jQuery(this).attr('id');
			idForSizeGuide = 'sizeGuideFor-'+idForSizeGuide.substr(17);
			jQuery('#'+idForSizeGuide + ',#oldSizingDialog').dialog({
					width: 850,
					height: 500,
					modal : true,
					show: "fade",
					closeOnEscape: true,
					hide: "fade",
					buttons: {
					 "Close": function() { 
						jQuery(this).dialog("close"); 
						}
					}

			});
			
			jQuery('#sizingGuide').show("fade");
			
			
			
			if(navigator.platform == 'iPad'){
				jQuery('#oldSizingDialog, .oldSizingDialog').parents(".ui-dialog").css("left", "87px");
			}			
	});
		
		jQuery('.oldsizingButton').click(function() {
			var findSizePopupSelector = jQuery(this).parent().children('.wsrSizeSelector').children(':nth-child(2)').val();
			jQuery("#" + findSizePopupSelector).dialog({
					width: 850,
					height: 500,
					modal : true,
					show: "fade",
					closeOnEscape: true,
					hide: "fade",
					buttons: {
					 "Close": function() { 
						$(this).dialog("close"); 
						}
					}
			});
			jQuery('#sizingGuide').show("fade");
			
			if(navigator.platform == 'iPad'){
				jQuery('.oldSizingDialog').parents(".ui-dialog").css("left", "87px");
			}			
	});
	isCalled = false;
	
	//WSO item's size guides
	jQuery('.wsoNewSizingBtn').click(function() {
		var currentLinkId = jQuery(this).attr('id');
		var currentDialogId = '#newSizingDialog_' + currentLinkId;
		
		jQuery(currentDialogId).dialog({
			   width: 800,
			   height: 500,
			   modal : true,
			   show: "fade",
			   closeOnEscape: true,
			   hide: "fade", 
			   buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
					} 
				}
		});
		
		if(navigator.platform == 'iPad'){
			jQuery(currentDialogId).parents(".ui-dialog").css("left", "112px");
		}
	});
	
	jQuery('.wsoOldsizingBtn').click(function() {
		var currentLinkId = jQuery(this).attr('id');
		var currentDialogId = '#oldSizingDialog_' + currentLinkId;
		
		jQuery(currentDialogId).dialog({
			   width: 800,
			   height: 500,
			   modal : true,
			   show: "fade",
			   closeOnEscape: true,
			   hide: "fade",
			   buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
					} 
				}
		});
		
		if(navigator.platform == 'iPad'){
			jQuery(currentDialogId).parents(".ui-dialog").css("left", "112px");
		}
	});
}
/**
* Checkout Billing step. Open related tab for the payment method and billing address.
*/
function checkoutBillingStepManageTabs(newOrSavedCard, selectedAddressOption) {
	var addNewCard = jQuery('#paymentCard').tabs();
	
	// Load the 'add new billing address' tab on payment options page
	var tabsArray = new Array();
	tabsArray['saved-address'] = 0;
	tabsArray['new-address'] = 1;
	var addNewAddress = jQuery('#billingAddress').tabs();
	addNewAddress.tabs('select', tabsArray[selectedAddressOption]);

	if (newOrSavedCard == 'newCard') {
		addNewCard.tabs('select', 1);
		onCardTypeChange(false);
	} else {
		addNewCard.tabs('select', 0);
	}

	var billingAddressNewOrSavedRadios = jQuery('input[name=billingAddressNewOrSaved]');
	jQuery.each(billingAddressNewOrSavedRadios, function (index, billingAddressNewOrSavedRadioButton) {
		jQuery(billingAddressNewOrSavedRadioButton).attr('checked', false);
	});

	jQuery('#' + selectedAddressOption).attr('checked', true);
	
	if (newOrSavedCard != 'newCard' && newOrSavedCard != 'payPal' && newOrSavedCard > 0) {
		linkBillingAddress('storedCard_' + newOrSavedCard);
	}
}

/**
* Checkout Billing step. Open related tab for the payment method and billing address. Works ON click.
*/
function checkoutBillingStepManageTabsOnClick(newOrSavedCard, selectedAddressOption) {
	var addNewCard = jQuery('#paymentCard').tabs();
	
	// Load the 'add new billing address' tab on payment options page
	var tabsArray = new Array();
	tabsArray['saved-address'] = 0;
	tabsArray['new-address'] = 1;
	var addNewAddress = jQuery('#billingAddress').tabs();
	addNewAddress.tabs('select', tabsArray[selectedAddressOption]);

	var billingAddressNewOrSavedRadios = jQuery('input[name=billingAddressNewOrSaved]');
	jQuery.each(billingAddressNewOrSavedRadios, function (index, billingAddressNewOrSavedRadioButton) {
		jQuery(billingAddressNewOrSavedRadioButton).attr('checked', false);
	});

	jQuery('#' + selectedAddressOption).attr('checked', true);
}

/**
* Checkout Billing step. Open Slider with GiftCard, Promocode and Vouchers.
*/

jQuery(document).ready(function(){
	
	jQuery('#promoCodesToggle').click( function () {
		jQuery('#promoCodes').slideToggle('slow', function() {
			// IE7 Fix.
			jQuery('#dwfrm_checkout_billing').find('input[type=text]').filter(':visible:first').focus();
			jQuery('#promoCodes input:first').focus();
		});
		jQuery(this).toggleClass('active');			
	})
	
});


/**
* Show Element by given information for it.
*/
function showElement(elementIdentifier) {
	if (elementIdentifier != '' && jQuery(elementIdentifier).length > 0) {
		jQuery(elementIdentifier).show();
	}
}

function LHNcheckHashInit()
{
	// Check if page is called from Back/Forward browser buttons, or when user click on a link. Should be false, when there is no user interaction.
	window.LHNcurrentHashValue=window.location.hash;
	window.LHNisCalled=false;
    var url = window.location.href;
    var hash = window.location.hash;
    hash = hash.substr(1, hash.length);
    if(hash.indexOf("ajaxsearchrefinement")!=-1)
	{
		window.LHNisCalled = true;
		window.searchRefinementsContainer = new Array();
		LHNcheckHashandRefreshProducts(hash);
	}
	setInterval(LHNcheckHash,1000);
}
//Refresh Page based on Hash string
function LHNcheckHashandRefreshProducts(aLocation) {
	curHashVal = window.location.hash;
    var url = window.location.href;
    var hash = window.location.hash;
    hash = hash.substr(1, hash.length);
    var link = hash;
	//
	if(link.indexOf("ajaxsearchrefinement")==-1)
	{
		window.location=url;
		return;
	}
	//
	jQuery.blockUI();
	jQuery.ajax(
			{
				url: link,
				success: function(data)
				{
					if(data == "") {
						
					}
					jQuery("div#productSearchRefinementsAjaxContainer").html(data);
					configurePanels();
					jQuery.unblockUI();
					jQuery("div#refineControls div.accordian div.panel").each(function()
							{
								for(var i=0;i<window.searchRefinementsContainer.length;i++)
								{
									if(window.searchRefinementsContainer[i][0]==jQuery(this).attr("id"))
									{
										jQuery(this).attr("class",window.searchRefinementsContainer[i][1]);
										jQuery(this).find("div.panelSlide").attr("style",window.searchRefinementsContainer[i][2]);
										if(window.searchRefinementsContainer[i][3]!=null)
										{
											jQuery(this).find("div.jspPane").attr("style",window.searchRefinementsContainer[i][3]);
											jQuery(this).find("div.jspDrag").attr("style",window.searchRefinementsContainer[i][4]);
										}
										break;
									}
								}
							});
					jQuery(".accordian .panel.active").find(".clearall.hidden").removeClass("hidden");
					window.LHNisCalled = false;
					window.LHNcurrentHashValue=window.location.hash;
				}
			});
}

function clearAllCheck() {
	jQuery(".refinementsOsScrollBar").each(function(index, element) {
		if (jQuery(element).find("label.checked").length > 0) {
			jQuery(element).parents('.panel').find('.clearall').show();
		} else {
			jQuery(element).parents('.panel').find('.clearall').hide();
		}
	});
	
	//shows Clear link when price slider is moved
	var sliderValues = jQuery(".priceSlider").slider( "option", "values" );
	var sliderMinValue = jQuery(".priceSlider").slider( "option", "min" );
	var sliderMaxValue = jQuery(".priceSlider").slider( "option", "max" );
	
	if(sliderValues[0] > sliderMinValue || sliderValues[1] < sliderMaxValue) {
		jQuery(".priceSlider").parents(".panel").find(".clearall").show();		
	} else {
		jQuery(".priceSlider").parents(".panel").find(".clearall").hide();
	}	
	
}

// When hash tag is changed, we need to reload the page. Back/Forward button can change the hash tag
function LHNcheckHashandRefreshProductsOnchangeURL(aLocation){
	LHNcheckHashandRefreshProducts(aLocation);
}

// Check if we have different url
function LHNcheckHash() {
	var locHash = window.location.hash;
	if(window.LHNcurrentHashValue != locHash && window.LHNisCalled == false) {
		window.LHNisCalled = true;
		var loc = window.location;
		LHNcheckHashandRefreshProductsOnchangeURL(loc);
	}
}

function openDeliveryChannelDialog(){
	jQuery('.deliveryChannelsDialog').click(function(event) {
		event.preventDefault();
		var url = jQuery(this).children('span').text();
		jQuery('#deliveryChannelsDialog').dialog({
			autoOpen: true,
			width: 600,
			height: (jQuery(window).height() < 600) ? (jQuery(window).height() - 50) : 615,
			modal : true,
			show: "fade",
			closeOnEscape: true,
			hide: "fade",
			open: function () {
				$.ajax({
					url: url,
					type: 'GET',
					success: function (html) {
						jQuery('#deliveryChannelsDialog').html(html);
					},
					error: function (errorMsg) {
						jQuery('#deliveryChannelsDialog').html('Error occurred.');
					}
				});
			},
			buttons: {
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		});
		return false;
	});
}

// Handles iPad touch and move event to update the position of the Little Message Bar.
if (navigator.platform == 'iPad') {
	function changeLMBPosition() {
		var windowPageOffsetY = window.pageYOffset;
		var windowInnerHeight = window.innerHeight;
		var messageSliderHeight = $('#messageSlider').height();
		var messageSliderNewOffset = (windowPageOffsetY + (windowInnerHeight / 2) - messageSliderHeight);
		$('#messageSlider').css('top', messageSliderNewOffset);
		return true;
	}
	
	jQuery(document).bind('touchstart', function() {
		$('#messageSlider').hide();
	});

	jQuery(document).bind('scroll', function() {
		changeLMBPosition();
	});
	
	jQuery(document).bind('touchend', function() {
		$('#messageSlider').show();
		jQuery(function () {
			if (jQuery('.contentAssetContent').is(':visible') === true) {
				hideLMB();
			}
		});
		//
		if (jQuery('#basketDropdown').length > 0 && jQuery('#basketDropdown').is(':visible')) {
			hideBasket();
		}
	});
}

//Smart Window Resize
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
   var timeout;

   return function debounced () {
       var obj = this, args = arguments;
       function delayed () {
           if (!execAsap)
               func.apply(obj, args);
           timeout = null; 
       };

       if (timeout)
           clearTimeout(timeout);
       else if (execAsap)
           func.apply(obj, args);

       timeout = setTimeout(delayed, threshold || 100); 
   };
}
	// smartresize 
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');
