/*----------------------------------------------------

	JSONLOAD.JS

----------------------------------------------------*/

$(document).ready(function(){

	var bodyid = $('body').attr('id');
	
	// A. Input Hints
	//------------------------------------------------------------------------------------------	

	$('input[type="text"]').each(function(){
		if(!$(this).val()){
			this.value = $(this).attr('title');
		}
		$(this).focus(function(){
			if(this.value == $(this).attr('title')) {
				this.value = '';
			}
		});
		$(this).blur(function(){
			if(this.value == '') {
				this.value = $(this).attr('title');
			}
		});
	});
	$('textarea').each(function(){
		if(!$(this).val()){
			this.value = $(this).attr('title');
		}
		$(this).focus(function(){
			if(this.value == $(this).attr('title')) {
				this.value = '';
			}
		});
		$(this).blur(function(){
			if(this.value == '') {
				this.value = $(this).attr('title');
			}
		});
	});

	
	// B. Price Overlay
	//------------------------------------------------------------------------------------------
	
	$('#lowest-price-guarantee a').bind('click', function(){
		var text = "<h3>We Guarantee You Won't Find A Cheaper Price</h3><p>We're so confident that our prices are the lowest, <strong>we guarantee you won't find a cheaper price.</strong></p><p>UKbathrooms.com is one of the country's biggest and longest-running bathroom websites. And because we buy in large quantities and only sell through our website, that means we can offer <strong>discounts of up to 35% compared to the high street</strong>.</p><p>We're so confident in our prices, we include a <strong>lowest price guarantee with everything we sell</strong>.</p><p>In the unlikely event that you find a product cheaper, we'll happily refund the difference. Just make sure that:</p><ul><li>The product is exactly the same (we only sell high quality products that we'd use ourselves).</li><li>The product is in stock (we ensure that virtually everything on our site is in stock/available within 3 days).</li><li>The cost includes VAT and delivery (all our prices include VAT, and delivery starts at just &pound;8 &ndash; and for many larger items, it's completely free)</li></ul><p>For the full terms and conditions, please <a href='/terms-price-guarantee.html' target='_blank'>click here</a>.</p>"

		$(this).parent().append('<div id="price-overlay"><div><a id="close-overlay">x</a>'+text+'</div></div>');
		$("#price-overlay").fadeIn();
		$('#close-overlay').bind('click', function(){
			$("#price-overlay").fadeOut();									   
		});									  
	});
	
	
	// C. Added to Basket
	//------------------------------------------------------------------------------------------
		
	$('#product-added').fadeIn('slow');
	$('#product-added').bind('click', function(){
		$(this).fadeOut('slow');
	});
	
	
	// D. Table Images
	//------------------------------------------------------------------------------------------
	
	$(".tbl-img").load(function() {
    $(this).wrap(function(){
    	return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
    });
    $(this).css("opacity","0");
	
  });
	
	// E. Beat My Quote Tabs
	//------------------------------------------------------------------------------------------	
	$('.tab-container').hide();
	$('.tab-container h3').hide();
	$('.tab-container:first').show();
	$('.tab-container:first').before('<ul class="tabs"></ul>');
	$('.tab-container h3').each(function(){
		$('.tabs').append('<li><a id="nav-'+ $(this).parent().attr('id') +'">'+ $(this).html() +'</a></li>');
	});
	$('.tabs > li:first').addClass('current');
	$('.tabs a').bind('click', function(){
		$('.tab-container').hide();
		var navitem = $(this).attr('id');
		$('#'+navitem.replace("nav-","")).show();
		$('.tabs .current').removeClass('current');
		$(this).parent().addClass('current');
	});

	
	// G. Banner
	//------------------------------------------------------------------------------------------	
	if(bodyid == 'home'){
		$(function(){
			// run the code in the markup!
			eval($('#banner_container')
				.cycle({
					fx:    'scrollLeft',
					speed:  2500,
					timeout:  7000,
					pager:  '#pages',
					next:   '#next', 
					prev:   '#previous' 
			}));
		});	
		function pause(){ 
			$('#banner_container').cycle('pause');
		}
	}


	// F. Login Window
	//------------------------------------------------------------------------------------------		
	$('.link-signin').bind('click', function(ev){
		ev.preventDefault();
		if($('#signin form').is(':visible')){
			$('#signin form').fadeOut();
			$('#signin .link-signin').removeClass('open');
		}else{
			$('#signin form').fadeIn();
			$('#signin .link-signin').addClass('open');
		}
	});		


	// G. Shipping Address
	//------------------------------------------------------------------------------------------
	
	$('#shipping-address >  div').before('<p id="choose-shipping"><input name="alt_shipping" id="alt_shipping" type="checkbox" value="1" /><label for="alt_shipping">Please deliver my order to an alternate address</label></p>');
	if($('#hasshipping').val() != 'true'){
		$('#shipping-address > div').hide();
	}else{
		$('#alt_shipping').attr('checked', true);
	}
	
	$('#alt_shipping').bind('click', function(){
		if($('#shipping-address > div').is(':visible')){
			$('#shipping-address > div').fadeOut('slow');
			$('#hasshipping').val("");
		}else{
			$('#shipping-address > div').fadeIn('slow');
			$('#hasshipping').val("true");
		}
	});
	
	// H. Close Response Messages
	//------------------------------------------------------------------------------------------

	$('#msg-response').bind("click", function(){
		if(!$('#msg-response').find('a').length){
			if($('#msg-response').is(':visible')){
				$("#msg-response").slideUp();
			}
		}
	});
	if($('#msg-response').find('a').length){ $("#msg-response span").hide(); }
	
	var zIndexNumber = 100;
	$('.side-options li').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 1;
	});
	
	// I. Side Tabbed
	//------------------------------------------------------------------------------------------	
	$('#tabs-side > li').hide();
	$('#tabs-side h6').hide();
	$('#tabs-side > li:first').show();
	$('#tabs-side').before('<ul id="tabs-side-nav"></ul>');
	$('#tabs-side h6').each(function(){
		$('#tabs-side-nav').append('<li><a id="nav-'+ $(this).attr('id') +'">'+ $(this).html() +'</a></li>');
	});
	$('#tabs-side-nav > li:first').addClass('current');
	$('#tabs-side-nav a').bind('click', function(){
		$('#tabs-side > li').hide();
		var navitem = $(this).attr('id');
		$('#'+navitem.replace("nav-","")).parent().show();
		$('#tabs-side-nav .current').removeClass('current');
		$(this).parent().addClass('current');
	});

	// I. Image Enlarge
	//------------------------------------------------------------------------------------------		

	function imgEnlarge(){
		$('.img-enlarge li').each(function(){
			var src = $(this).find('img').attr('src').replace('160/160','800/600');
			var enlarge = src.replace('?square=1','');
			var title = $(this).find('h2').html();
			$(this).append('<a href="'+enlarge+'" class="product-zoom colorbox" rel="products-category" title="'+title+'">here</a>');
		});
		$(".colorbox").colorbox();
	}
	if(bodyid == 'shop-display-category'){
		imgEnlarge();
	}
	
	// J. Side Tabbed
	//------------------------------------------------------------------------------------------	
	if(bodyid == 'shop-view-product' || bodyid == 'shop-display-category' || bodyid == 'shop-view-suite' || bodyid == 'shop-reviews'){
		$(".colorbox").colorbox();		
		$(".colorbox-review").colorbox({innerWidth:500, innerHeight:450});	
		$(".colorbox-emailafriend").colorbox({innerWidth:500, innerHeight:400});	
	}	

	// K. Filtered Browsing
	//------------------------------------------------------------------------------------------	
		
	// Add loading image then Get post information, modify and ajaxify	
	function ajaxStuff(obj,paging,sorting,currentlyviewed){
		$('body').append('<div id="thinking"><div><img src="/img/ajax-loader.gif" alt="Thinking" /></div></div>');
		var formdata = $(obj).parents('form').serialize();	
		formdata = formdata + "&page="+paging;
		if(sorting != ''){
			formdata = formdata + "&price="+sorting;
		}	
		if(currentlyviewed != true){ formdata = formdata + "&lastsel="+$(obj).attr('id'); }
		//alert(formdata);
		$.ajax({
			url: "/shop/advanced-search-results.php",
			cache: false,
			type: "POST",
			data: formdata,
			success: function(html){
				$('#content').html(html);
                //$('h1').stop().css('backgroundColor','#FFFBC2');
                //$('h1').stop().animate({'backgroundColor':'#FFFFFF'}, 3000);
				reloadAfterAjax();
				$('#thinking').remove();
			}
		});
		return false;
	}
	
	
	function createSlider(){
		var minnum = parseInt($("#min-prices").val());
		var maxnum = parseInt($("#max-prices").val());
		var currmin = parseInt($("#price_low").val());
		var currmax = parseInt($("#price_high").val());
		$("#filter-price-options div").hide();
		$("#filter-price-options h4").after('<div id="slider-range"></div><span id="slider-low"></span><span id="slider-high"></span>');
		$("#slider-range").slider({
			range: true,
			min: minnum,
			max: maxnum,
			step: '5',
			values: [currmin, currmax],
			slide: function(event,ui){
				$("#slider-low").html("&pound;" + ui.values[0]);
				$("#slider-high").html("&pound;" + ui.values[1]);
			},
			stop: function(event,ui){
				$("#price_low").val(ui.values[0]);
				$("#price_high").val(ui.values[1]);
				var sorting = parseInt($('sort .current').html());
				ajaxStuff("#slider-range",1,sorting);
			}
			
		});
		$("#slider-low").html("&pound;" + $("#slider-range").slider("values",0));
		$("#slider-high").html("&pound;" + $("#slider-range").slider("values", 1));
	}
	function reloadAfterAjax(){
		// Move Filter
		if($('#content #adv-filter').length > 0){
			$('#filter-container #productfilter').html($('#content #productfilter').html());
		}
		$('#content #adv-filter').remove();
		
		// Remove Search Button
		$("#productfilter input[type=submit]").remove()
		//Fix Paging
		$('#paging a').click(function(event){
			event.preventDefault();
			var paging = $(this).html();
			var current = parseInt($(this).siblings('span.current').html());
			var sorting = $('#sort .current').html();
			if(sorting == "Bestselling"){
				//sorting = ''
			}else if(sorting == 'Price (high to low)'){
				sorting = 'high';
			}else if(sorting == 'Price (low to high)'){
				sorting = 'low';
			}
			if(paging == "Next Page"){
				paging = current+1;
			}else if(paging == 'Previous Page'){
				paging = current-1;
			}
			
			ajaxStuff('#productfilter input',paging,sorting);
			
			var $target = $('#content');
			$target = $target.length && $target || $('[name=' + target.slice(1) +']');
			if($target.length){
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 900);
			}
			return false;
		});
		
		//Fix Sort
		$('#sort a').click(function(event){
			var sorting = $(this).html();
			if(sorting == "Bestselling"){
				//sorting = ''
			}else if(sorting == 'Price (high to low)'){
				sorting = 'high';
			}else if(sorting == 'Price (low to high)'){
				sorting = 'low';
			}
			//alert(sorting);
			event.preventDefault();
			if(sorting){
				ajaxStuff('#productfilter input',1,sorting);
			}
		});
		
		// Move option to top and duplicate with deletes
		$('#productfilter > div').prepend('<fieldset id="product-filter-selected"><h4>Currently Viewing</h4></fieldset>');
		$('#product-filter-selected').hide();
		
		$('.adv-search-options').each(function(){
			var selected = "";
			var showselected = "";
			$(this).find('li input:checked').parent().each(function(){
				label = $(this).find('label').html();
				var num = label.indexOf("<span>");
				label = label.substr(0,num);
				showselected = showselected + "<span title='" + $(this).find('input').attr('id') + "'>" + trim(label) + "</span>";
				//selected = selected + "<li>" + $(this).html() + "</li>";
				//$(this).remove();				
			});
			//$(this).prepend(selected);
			if(showselected){
				$('#product-filter-selected').show();
				$('#product-filter-selected').append(showselected);
				$("#product-filter-selected span").bind('click', function(){
					var id = $(this).attr('title');
					$('#'+id).attr('checked','');
					var obj = $('#'+id);
					var sorting = parseInt($('sort .current').html());
					ajaxStuff(obj,1,sorting,true);
				});
			}
		});
			
		//Hide some options
		function hideChildren(){
			$('.adv-search-options').each(function(index){
				var children = $(this).find('li').length;
				if(children > 5){
					for(i=6;i<=children;i=i+1){
						$(this).find(' li:nth-child('+i+')').hide();
					}
					$(this).find('li:nth-child(5)').after('<li class="view-all">More Options</li>').show();
					$('.view-all').click(function(event){
						viewAllClick(this);
					});
				}
			});

		}
		hideChildren();
		
		
		
		//Show Options is just clicked
		var selected = $('#lastsel').val();
		if(selected){
			if($('#'+selected).is(':hidden')){
				var view = $('#'+selected).parent().siblings('.view-all');
				viewAllClick(view);
			}
		}
		
		function viewAllClick(obj){
			$(obj).parent().children().show();
			$(obj).parent().append('<li class="hide">Fewer Options</li>');
			$(obj).parent().children('.view-all').remove();
			$('.hide').click(function(event){
				$(obj).parent().children('.hide').remove();
				hideChildren();
			});
		}

		
		//Redesign Sort box
		function redesignSort(){
			$('#sort ul').hide();
			$('#sort').addClass('sort-dropdown');
			$('#sort h6').click(function(event){
				if($(this).siblings('ul').is(':visible')){
					$(this).siblings('ul').fadeOut();
				}else{
					$(this).siblings('ul').fadeIn();
				}
				$(document).one('click',function() {
					$('#sort ul').fadeOut();
				});
				event.stopPropagation();	
			});
			
		}
		redesignSort();
		
		
		// Bind Ajax Function [CLICK EVENT]
		$("#productfilter input").bind('click', function(){
			var sorting = parseInt($('sort .current').html());
			ajaxStuff(this,1,sorting);
		});
		
		// Create Slider
		createSlider();
		
		// Redo Image Enlargement
		imgEnlarge();
		
		$('h1').stop().css('backgroundColor','#FFFBC2');
        $('h1').stop().animate({'backgroundColor':'#FFFFFF'}, 3000);
		
	}
	function fixmenu(){
		var filter = $('#adv-filter').html()
		$('#adv-filter').remove();
		$('#main_navigation h6').remove();
		$('#man_nav').remove();
		$('#parent_nav').before('<a href="/shop/index.html" id="shop-by-category">Shop by Category</a>');
		$('#shop-by-category').click(function(event){
			event.preventDefault();
			$('#parent_nav').toggle();
			$(document).one('click',function() {
				$('#parent_nav').hide();
			});
			event.stopPropagation();
		});
		$('#parent_nav').addClass('filter-product-nav');
		$('.sub_cat').removeClass('sub_cat');
		$('#parent_nav li a').each(function(){
			var href = $(this).attr('href');
			var html = $(this).html();
			$(this).before('<a href="'+href+'">'+html+'</a>');
			$(this).remove();
		});
		$('#parent_nav ul').remove();
		$('#parent_nav').hide();
		$('#main_navigation').append(filter);
		$('#main_navigation').attr('id','filter-container');
	}
	if(bodyid == 'shop-filtered-browsing'){
		fixmenu();
		reloadAfterAjax();	
	}

	// L. New Header
	//------------------------------------------------------------------------------------------
	
	// Header Contact
	$('#hdr-contact-info').append('<div><strong>or 01765 692097</strong> We try to answer all calls within 10 seconds - and you\'ll speak to a real person, not a machine. If you\'d rather email then please <a href="/contact_us.html">get in touch</a>. <img src="/img/_team_sm.jpg" alt="The UKB Team" /></div>');
	$('#hdr-contact-info div').hide();
	$('#hdr-contact-info div').after('<a href="#">More</a>');
	$('#hdr-contact-info > a').click(function(event){
		event.preventDefault();
		if($(this).html() == 'More'){
			$('#hdr-contact-info div').slideDown('slow');
			$(this).html('Less');
			$(this).addClass('less');
		}else{
			$(this).html('More');
			$(this).removeClass('less');
			$('#hdr-contact-info div').slideUp('slow');
		}
		$(document).one('click',function() {
			$(this).html('More');
			$(this).removeClass('less');
			$('#hdr-contact-info div').slideUp('slow');
		});
		event.stopPropagation();
	});
	
	// Currencies	
	var currency = $('input[name="currency_current"]').val();
	$('#currency-form').before('<ul id="currencies"><li title="GBP">&pound;</li><li title="EUR">&euro;</li></ul>');
	$('#currencies li[title="'+currency+'"]').addClass('current');
	$('#currencies li').click(function(){
		var sel = $(this).attr('title');
		$('#currency-form input[type="submit"]').remove();
		$('#currency-form').append('<input type="hidden" name="currency" value="'+sel+'" />');
		$('#currency-form').submit();
	});
	$('#currency-form').hide();


	// M. Capture Email
	//------------------------------------------------------------------------------------------	
	$('#form-checkout #email').blur(function(){
		var email = $(this).val();
		var firstname = $('#firstname').val();
		if(firstname == 'First Name'){
			firstname = '';
		}
		$.ajax({
			url: "/include/functions.php",
			cache: false,
			type: "GET",
			data: 'email='+email+'&name='+firstname+'&storebasket=true',
			success: function(html){
				//Do Nothing
			}
		});
		return false;
	});
	

	// N. Mini Nav
	//------------------------------------------------------------------------------------------
	$('#mini-nav h6').click(function(event){
		if($(this).siblings('ul').is(':visible')){
			$(this).siblings('ul').slideUp();
		}else{
			$(this).siblings('ul').slideDown();
		}
		$(document).one('click',function() {
			$('#mini-nav h6').siblings('ul').slideUp();
		});
		event.stopPropagation();
		
		var config = {    
			sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
			interval: 200,  // number = milliseconds for onMouseOver polling interval    
			over: doOpen,   // function = onMouseOver callback (REQUIRED)    
			timeout: 200,   // number = milliseconds delay before onMouseOut    
			out: doClose    // function = onMouseOut callback (REQUIRED)    
		};
		function doOpen() {
			$('ul:first',this).css('display', 'block');
		}
		function doClose() {
			$('ul:first',this).css('display', 'none');
		}
		$("#mini-nav ul li").hoverIntent(config);
		
	});
	
	// O. In Page Links
	//------------------------------------------------------------------------------------------
		
	$('a.in-link').click(function(){  
 		if(location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname){
			var $target = $(this.hash);
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if($target.length){
				var targetOffset = $target.offset().top;
				targetOffset = targetOffset - 100;
				$('html,body').animate({scrollTop: targetOffset}, 900);
				return false;
			}
		}  
  	});


	// P. Customer Reviews
	//------------------------------------------------------------------------------------------
	if($('#customer-reviews').length > 0){
		$('#customer-reviews > li').append('<p class="review-helpful"><span>Was this review helpful to you?</span> <a href="#" class="review-btn">Yes</a> <a href="#" class="review-btn">No</a></p>');
		
		$(".review-btn").click(function() {
			var obj = this;
			var votetype = $(this).html();
			var reviewid = $(this).parents('li').attr('title');		
			$.ajax({
				url: "/include/functions.php",
				cache: false,
				type: "GET",
				data: 'votereviews=true&votetype='+votetype+'&reviewid='+reviewid,
				success: function(html){
					if(html != ''){
						//Do Nothing		
					}else{
						$(obj).parent().before('<p class="review-helpful review-thanks">Thank you for your feedback</p>');
						$(obj).parent().remove();
						$('.review-thanks').stop().css('backgroundColor','#FFFBC2');
        				$('.review-thanks').stop().animate({'backgroundColor':'#FFFFFF'}, 3000);
					}
				}
			});
			return false;
			
		});
	}
	
	
	if(bodyid == 'review-your-order'){
		doRating();
	}


	// Q. Header USP's
	//------------------------------------------------------------------------------------------
	/*if($('.staging').length > 0){*/
		if($('#top-nav').length > 0 && $('#topbar_membernav').length == 0){
			$('#top-nav').before("<ul id=\"header-usp\"><li><a href=\"#\">Fast + secure delivery</a><div class=\"usp-overlay\"><h3>Fast + secure delivery</h3><p>We dispatch all products <strong>as quickly as possible.</strong> (And we'll let you know when you order will arrive <em>before</em> you buy.)</p><p>Almost 85% of the products on our web site can be ready for dispatch within 24-48 hours of order. Most orders are delivered within 3-4 working days after you order. (Need it quicker? Please phone us and we'll do our best to help!)</p><p>Delivery costs are always clearly displayed against each product. Many items - from shower enclosures to radiators - are available with <strong>free delivery</strong>.</p><p><a href=\"/delivery.html\">Read more about delivery</a></p></div></li><li><a href=\"#\">Never beaten on price</a><div class=\"usp-overlay\"><h3>Never beaten on price</h3><p>We're so confident that our prices are the lowest, <strong>we guarantee you won't find a cheaper price.</strong></p><p>UKbathrooms.com is one of the country's biggest and longest-running bathroom websites. And because we buy in large quantities and only sell through our website, that means we can offer <strong>discounts of up to 35% compared to the high street.</strong></p><p>We're so confident in our prices, we include a lowest price guarantee with everything we sell.</p><p>In the unlikely event that you find a product cheaper, we'll happily refund the difference. Just make sure that:</p><ul><li>The product is exactly the same (we only sell high quality products that we'd use ourselves).</li><li>The product is in stock (we ensure that virtually everything on our site is in stock/available within 3 days).</li><li>The cost includes VAT and delivery (all our prices include VAT, and delivery starts at just &pound;8 - and for many larger items, it's completely free)</li></ul><p>For the full terms and conditions, please <a href='/terms-price-guarantee.html' target='_blank'>click here</a>.</p></div></li><li><a href=\"#\">No credit card fees</a><div class=\"usp-overlay\"><h3>No credit card fees</h3><p>There are no hidden extras at UKbathrooms.com.</p><p>That's why we don't charge a penny more if you want to pay by credit card (or if you order by phone).</p><p>All costs and delivery times are clearly displayed against each product - so you know the full cost before you even get to the shopping basket.</p><p>And if you're buying more than one item, you'll only pay one delivery charge (the higher of the two).</p></div></li><li><a href=\"#\">In business over 20 years</a><div class=\"usp-overlay\"><h3>In business over 20 years</h3><p>In our 20 years, we've supplied over 30,000 homes... and the Old Bailey!</p><p>Our goal has always been to sell high-quality products at discounted prices.</p><p>That's why we stock premium brands like Matki, Hansgrohe and Villeroy &amp; Boch - at discounts of up to 35%.</p><p><a href=\"about-us.html\">Find out more about UKbathrooms.com</a></p></div></li></ul>");
			$('.usp-overlay').wrapInner('<div>');
			$('.usp-overlay').children('div').prepend('<a class="close-overlay">x</a>');
			
		}
		
		$('#header-usp a').click(function(event){
			$(".usp-overlay").hide();	
			$(this).siblings('.usp-overlay').fadeIn();
			$('.close-overlay').bind('click', function(){
				$(".usp-overlay").is(':visible').fadeOut();									   
			});
			$(document).one('click',function() {
				$(".usp-overlay").hide();	
			});
			//event.preventDefault();
			event.stopPropagation();
		});
		
	/*}*/
	
	// R. Why Choose Suites
	//------------------------------------------------------------------------------------------
	/*if($('.staging').length > 0){*/
		$('#shop-view-suite #product-sidebar').prepend('<div id="why-choose-suites" class="why-choose"><h5>Why choose a suite from UKBathrooms.com?</h5><ul><li id="why-suite-1"><strong>Premium brands</strong> including Matki, Hansgrohe and Villeroy and Boch</li><li id="why-suite-2">One simple package that <strong>includes everything</strong> you\'ll need - from taps through to fixing bolts</li><li id="why-suite-3">Savings of up to <strong>45% off</strong> the RRP by buying them together</li><li id="why-suite-4"><strong>Customise your suite</strong> by swapping items - just call us on 0845 200 8503</li></ul></div>');	
		if($('#shop-display-category h1').html() == 'Bathroom Suites'){
			$('#shop-display-category #side_text').before('<div id="why-choose-suites" class="why-choose why-choose-suites-cat"><h5>Why choose a suite from UKBathrooms.com?</h5><ul><li id="why-suite-1"><strong>Premium brands</strong> including Matki, Hansgrohe and Villeroy and Boch</li><li id="why-suite-2">One simple package that <strong>includes everything</strong> you\'ll need - from taps through to fixing bolts</li><li id="why-suite-3">Savings of up to <strong>45% off</strong> the RRP by buying them together</li><li id="why-suite-4"><strong>Customise your suite</strong> by swapping items - just call us on 0845 200 8503</li></ul></div>');
		}
	/*}*/
		
		
	// S. Languages
	//------------------------------------------------------------------------------------------	
	
	var langs = new Array("french","german","italian","spanish","dutch","danish","swedish","finnish","norwegian");
	lang = $('h1').attr('class');
	if(lang in oc(langs)){
		var sel = lang;
	}else{
		var sel = 'english';
	}
	var text = $('#language-'+sel).html();
	$('.languages').prepend('<span class="language-selected ls-'+sel+'">'+text+'</span>');
	$('.languages').find('ul').addClass('languages-dropdown');
	$('.language-selected').click(function(event){
		
		var ul = $('.languages').find('ul')
		if($(ul).is(':visible')){
			$(ul).slideUp();
		}else{
			$(ul).slideDown();
		}
		$(document).click(function() {
			$(ul).slideUp();
		});
		event.stopPropagation();
		
	});
});


// 01. Reviews
//------------------------------------------------------------------------------------------	

function reviewHover(num){
	$('#add-rating img').attr('src','/img/icon_nostar.jpg');
	for (i = 1; i<=num; i++){
		$('#star-'+i).attr('src','/img/icon_star.jpg');
	}		
}
function reviewOut2(){
	window.setTimeout('ratingOut()', 1000);
}
function reviewOut(){
	$('#add-rating img').attr('src','/img/icon_nostar.jpg');
	var selected = $('.rating-num').val();
	for (i = 1; i<=selected; i++){
		$('#star-'+i).attr('src','/img/icon_star.jpg');
	}
}
function reviewDown(num){
	$('.rating-num').val(num);
}

function doRating(){

	$('.rating-num').each(function(){
		
		var ops = $(this).children('option').map(function(){return jQuery(this).html();}).get();
		
		$(this).after('<ul class="rating-list"></ul>');
		$(this).hide();
		var obj = $(this);
		$.each(ops, function(intIndex, objValue){		
			if(intIndex != ''){
				$(obj).parent().children('ul').append($( "<li><img src=\"/img/icon_nostar.png\" /></li>" ));
			}
		});
		
	});
	
	$('.rating-list li').mouseover(function(){
		$(this).siblings().children('img').attr('src','/img/icon_nostar.png');
		var src = $(this).children('img').attr('src');
		$(this).children('img').attr('src','/img/icon_star.png');
		$(this).prevAll().children('img').attr('src','/img/icon_star.png');
	});
	$('.rating-list li').mouseout(function(){
		$(this).children('img').attr('src','/img/icon_nostar.png');
		$(this).siblings().children('img').attr('src','/img/icon_nostar.png');
		var num = $(this).parent().siblings('.rating-num').val();
		if(num){
			for (i=1; i<=num; i++){
				$(this).parent().children(':nth-child('+i+')').children('img').attr('src','/img/icon_star.png');
			}
		}
	});
	$('.rating-list img').click(function(){
		$(this).attr('src','/img/icon_star.png');
		$(this).parent().prevAll().children('img').attr('src','/img/icon_star.png');
		var num = $(this).parent().index() + 1;
		$(this).parents('.rating-list').siblings('.rating-num').val(num);
	});
	
}

// 02. resetForm
//------------------------------------------------------------------------------------------

function resetForm(){

	$("input[type='text']").removeClass('input-warning');
	$('textarea').removeClass('input-warning');
	$('.warning').addClass('required');
	$('.warning').removeClass('warning');
	$('.hidden').show();
	$('#msg-response').remove();

}

// 03. inputValidator
//------------------------------------------------------------------------------------------

function inputValidator(id){
	if($('#'+id).val()=="" && id != 'security'){
		constructMessage(id);
	}else if($('#'+id).val()!="" && id == 'security'){
		if(empty == false){
			$('.new-form').prepend("<div id='msg-response'><div>Please ensure the hidden security field is empty</div></div>");
			$('#msg-response').addClass("msg-error");
			$('#msg-response').slideDown();
		}
		$('#'+id).addClass('input-warning');
		empty=true;
	}
	
}

// 04. emailValidator
//------------------------------------------------------------------------------------------

function emailValidator(obj){
	
	var emailStr = $('#'+obj).val()
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)!£$%^&*()+='#~?<>@,;:\\\\\\\"\\.\\[\\]";var validChars="\[^\\s" + specialChars + "\]";var quotedUser="(\"[^\"]*\")";var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+';var word="(" + atom + "|" + quotedUser + ")";var userPat=new RegExp("^" + word + "(\\." + word + ")*$");var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");var matchArray=emailStr.match(emailPat)
	if ((matchArray==null) && empty==false){constructMessage(obj,"Email address seems incorrect (check @ and .'s)")}
	if (empty==false){var user=matchArray [1];var domain=matchArray [2];if (user.match(userPat)==null){constructMessage(obj,"The username doesn't seem to be valid.")}}
	if (empty==false){var IPArray=domain.match(ipDomainPat);if (IPArray!=null){for (var j=1;j<=4;j++){if (IPArray[j]>255){constructMessage(obj,"Destination IP address is invalid!")}}}}
	if (empty==false){var domainArray=domain.match(domainPat);if (domainArray==null){constructMessage(obj,"The domain name doesn't seem to be valid.")}}
	if (empty==false){var atomPat=new RegExp(atom,"g");var domArr=domain.match(atomPat);var len=domArr.length;if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3){constructMessage(obj,"The address must end in a three-letter domain, or two letter country.")}}
	if ((len<2) && empty==false){constructMessage(obj,"This address is missing a hostname!")}
}

// 05. constructMessage
//------------------------------------------------------------------------------------------

function constructMessage(id,msg){

	if(!msg){
		msg = "Please ensure you have entered all the required information";
	}
	if(empty == false){
		$('.new-form').prepend("<div id='msg-response'><div>"+msg+"</div></div>");
		$('#msg-response div').addClass("msg-error");
		$('#msg-response').slideDown();
	}
	$('#'+id+' ~ span.required').addClass("warning");
	$('#'+id+' ~ span.hidden').hide();
	$('.warning').removeClass("required");
	$('#'+id).addClass('input-warning');
	empty=true;

}

// 06. formAddReview
//------------------------------------------------------------------------------------------

function formSubmitReview(){
	resetForm();
	empty = false;
	inputValidator('author');
	inputValidator('rating-num');
	inputValidator('title');
	inputValidator('review');
	inputValidator('security');
	if (empty == false){
		$('#review-form').submit();
	}
	
}

// 07. formEmailAFriend
//------------------------------------------------------------------------------------------

function formEmailAFriend(){
	resetForm();
	empty = false;
	inputValidator('from-name');
	inputValidator('to-name');
	inputValidator('to-email');
	emailValidator('to-email');
	inputValidator('security');
	if (empty == false){
		$('#friend-form').submit();
	}
}

// 08. trim
//------------------------------------------------------------------------------------------

function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

// 03. oc - object convert
//------------------------------------------------------------------------------------------
function oc(a){
	var o = {};
	for(var i=0;i<a.length;i++){
	  o[a[i]]='';
	}
	return o;
}


function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}


// LEGACY
//------------------------------------------------------------------------------------------	
	
function toggleSearchBox(){
	
	var obj = document.getElementById('search_box');
	if(obj.value == "[Enter your search here]"){
		obj.value = "";
	}else if(obj.value == ""){
		obj.value = "[Enter your search here]";
	}
}

function show_image(img){
	var target = document.getElementById("proimg_main").getElementsByTagName("img");
	var linktarget = document.getElementById("proimg_main").getElementsByTagName("a");
	for (var i = 0; i < target.length; i++) {
		target[i].src = "/images/358/358/"+img+".jpg";
		linktarget[i].href = "/images/800/800/"+img+".jpg";
		//target[i].jqimg = img;
	}
}

function showImgHover(){
	document.getElementById("img_zoom").style.display = "block";
}
function hideImgHover(){
	document.getElementById("img_zoom").style.display = "none";
}

function checkboxRestrict(obj,num){
	var box = obj.name.substr(0,obj.name.lastIndexOf('_')+1);
	var k=0,i=1;
	while(obj.form[box+i]){
		k += obj.form[box+i].checked;
		i++;
	}
	if(k > num){
		obj.checked = false;
		alert('Only ' + num + ' '+box.substr(0,box.length-1) +' baskets can be comined at one time.\nTo pick this option please unselect one of the others.');
	}
}


function popup(mylink, windowname){
	if (! window.focus)return true;
	var href;
	if (typeof(mylink) == 'string')
	   href=mylink;
	else
	   href=mylink.href;
	window.open(href, windowname, 'width=800, height=450, scrollbars=yes');
	return false;
}


var timeout	= 500;
var timein = 0;
var closetimer	= 0;
var currentSub = 0;
var opentimer = 0;


function subOpen(id){
	cancelClose();
	opentimer = window.setTimeout('subOpen2(\''+id+'\')', timein);
	timein = 500;
}

function subOpen2(id){	
	if(opentimer){
		if(currentSub) currentSub.style.display = "none";
		currentSub = document.getElementById(id);
		currentSub.style.display = "block";
		var links = document.getElementById(id).parentNode.parentNode.parentNode.getElementsByTagName("a");
		for (var i = 0; i < links.length; i++){
			links[i].id = "";
		}
		var links = document.getElementById(id).parentNode.getElementsByTagName("a");
		for (var i = 0; i < links.length; i++){
			links[i].id = "nav_hover";
		}
	}	
}

function subClose(){
	if(currentSub){
		var currentlink = document.getElementById("nav_hover");
		currentlink.id = "";
		currentSub.style.display = "none";
	}
}

function subCloseTimer(){	
	closetimer = window.setTimeout(subClose, timeout);
}

function cancelClose(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

function subCancelClose(){
	subCancelOpen()
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

function subCancelOpen(){
	if(opentimer){
		window.clearTimeout(opentimer);
		opentimer = null;
	}
}

document.onclick = subClose;


/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 J?rn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><p></p><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('p',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);

$(function() {
	$('.help-point').tooltip({ 
		track: true, 
		delay:0,
		showURL: false
	});
});

//Background Colour Animation
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(o(e){e.Y([\'G\',\'Z\',\'V\',\'Q\',\'R\',\'7\',\'S\'],o(i,d){e.5.U[d]=o(5){f(5.12==0){5.h=D(5.c,d);5.n=A(5.n)}5.c.13[d]="v("+[l.z(l.B(8((5.w*(5.n[0]-5.h[0]))+5.h[0]),4),0),l.z(l.B(8((5.w*(5.n[1]-5.h[1]))+5.h[1]),4),0),l.z(l.B(8((5.w*(5.n[2]-5.h[2]))+5.h[2]),4),0)].1g(",")+")"}});o A(7){x 6;f(7&&7.1h==17&&7.19==3)g 7;f(6=/v\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.r(7))g[8(6[1]),8(6[2]),8(6[3])];f(6=/v\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.r(7))g[u(6[1])*2.t,u(6[2])*2.t,u(6[3])*2.t];f(6=/#([a-m-k-9]{2})([a-m-k-9]{2})([a-m-k-9]{2})/.r(7))g[8(6[1],16),8(6[2],16),8(6[3],16)];f(6=/#([a-m-k-9])([a-m-k-9])([a-m-k-9])/.r(7))g[8(6[1]+6[1],16),8(6[2]+6[2],16),8(6[3]+6[3],16)];g E[e.1f(7).1i()]}o D(c,d){x 7;1a{7=e.18(c,d);f(7!=\'\'&&7!=\'14\'||e.15(c,"1b"))1c;d="G"}1d(c=c.1e);g A(7)};x E={O:[0,4,4],P:[F,4,4],T:[C,C,10],11:[0,0,0],W:[0,0,4],X:[M,K,K],1t:[0,4,4],1Y:[0,0,j],1X:[0,j,j],1j:[y,y,y],1W:[0,1Z,0],20:[22,21,H],1V:[j,0,j],1U:[1P,H,1O],1N:[4,I,0],1Q:[1R,1T,1S],24:[j,0,0],27:[2b,2c,2e],2a:[25,0,p],26:[4,0,4],28:[4,29,0],2d:[0,b,0],23:[1L,0,1M],1s:[F,N,I],1u:[1v,1w,N],1r:[J,4,4],1q:[L,1l,L],1k:[p,p,p],1m:[4,1n,1p],1o:[4,4,J],1x:[0,4,0],1y:[4,0,4],1H:[b,0,0],1G:[0,0,b],1I:[b,b,0],1J:[4,M,0],1K:[4,q,1F],1E:[b,0,b],1A:[b,0,b],1z:[4,0,0],1B:[q,q,q],1C:[4,4,4],1D:[4,4,0]}})(e);',62,139,'||||255|fx|result|color|parseInt|||128|elem|attr|jQuery|if|return|start||139|F0|Math|fA|end|function|211|192|exec||55|parseFloat|rgb|pos|var|169|max|getRGB|min|245|getColor|colors|240|backgroundColor|107|140|224|42|144|165|230|aqua|azure|borderRightColor|borderTopColor|outlineColor|beige|step|borderLeftColor|blue|brown|each|borderBottomColor|220|black|state|style|transparent|nodeName||Array|curCSS|length|do|body|break|while|parentNode|trim|join|constructor|toLowerCase|darkgrey|lightgrey|238|lightpink|182|lightyellow|193|lightgreen|lightcyan|khaki|cyan|lightblue|173|216|lime|magenta|red|violet|silver|white|yellow|purple|203|navy|maroon|olive|orange|pink|75|130|darkorange|47|85|darkorchid|153|204|50|darkolivegreen|darkmagenta|darkgreen|darkcyan|darkblue|100|darkkhaki|183|189|indigo|darkred|148|fuchsia|darksalmon|gold|215|darkviolet|233|150|green|122'.split('|'),0,{}))

//Hover Intent
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(6($){$.J.K=6(f,g){8 5={y:7,l:I,H:0};5=$.u(5,g?{v:f,z:g}:f);8 d,b,k,i;8 h=6(3){d=3.G;b=3.B};8 m=6(3,2){2.4=o(2.4);9((w.x(k-d)+w.x(i-b))<5.y){$(2).D("n",h);2.j=1;c 5.v.t(2,[3])}E{k=d;i=b;2.4=r(6(){m(3,2)},5.l)}};8 C=6(3,2){2.4=o(2.4);2.j=0;c 5.z.t(2,[3])};8 q=6(e){8 p=(e.A=="s"?e.N:e.U)||e.T;R(p&&p!=a){S{p=p.O}P(e){p=a}}9(p==a){c Q}8 3=F.u({},e);8 2=a;9(2.4){2.4=o(2.4)}9(e.A=="s"){k=3.G;i=3.B;$(2).M("n",h);9(2.j!=1){2.4=r(6(){m(3,2)},5.l)}}E{$(2).D("n",h);9(2.j==1){2.4=r(6(){C(3,2)},5.H)}}};c a.s(q).L(q)}})(F);',57,57,'||ob|ev|hoverIntent_t|cfg|function||var|if|this|cY|return|cX||||track|pY|hoverIntent_s|pX|interval|compare|mousemove|clearTimeout||handleHover|setTimeout|mouseover|apply|extend|over|Math|abs|sensitivity|out|type|pageY|delay|unbind|else|jQuery|pageX|timeout|100|fn|hoverIntent|mouseout|bind|fromElement|parentNode|catch|false|while|try|relatedTarget|toElement'.split('|'),0,{}))
