// private functions
function debug(o) {
	if(window.console && window.console.log) {
		window.console.log(o);
	}
}

var addthis_config = {
	data_use_flash:	false,
	ui_offset_top:	5,
	ui_offset_left:	0
};

if(typeof jQuery !== 'undefined') {
	jQuery.noConflict();
	jQuery(document).ready(function($) {
		var $body, $content, $header,
			$featured,
			$products,
			$zoom, $zoomImg,
			$scroll,
            $map,
			$video, $videoAudio, $videoAudioActive, $videoAudioSection, manTip,
			$getTheLook,
			$addressBilling, $addressDelivery,
			$signinRegister,
			$addressManagement,
			$productToggle,
			$cleanDirty,
			$inAction,
			$quantityForm,
			$miniCart, $justAdded, $extraOffer,
			scroll		= true,
			flash		= true,
			zoom		= true,
			getTheLook	= true,
			scrollbar	= true,
			lightbox	= true,
			checkbox	= true,
			datepicker	= true,
			init		= {
				jqZoom:	function(){}
			};

		$body				= $('body').addClass('jquery');
		$content			= $('#content');
		$header				= $('#header');
		$featured			= $('#featured');
		$products			= $('div.products');
		$zoom				= $('#zoom a:first');
		$zoomImg			= $zoom.children('img');
		$scroll				= $content.find('div.scroll');
		$video				= $content.find('div.video');
		$videoAudio			= $('#audio-video');
		$getTheLook			= $('#get-the-look');
		$addressBilling		= $('#billing-details');
		$addressDelivery	= $('#delivery-details');
		$signinRegister		= $('#signin-register');
		$addressManagement	= $('#address-management');
		$productToggle		= $('div.product-toggle');
		$cleanDirty			= $('div.extra p.toggle');
		$inAction			= $('#in-action');
		$quantityForm		= $('table.basket tr.hproduct td.quantity form');
		$miniCart			= $('#mini-cart');
		$justAdded			= $('#just-added');
		$extraOffer			= $('#extra-offer');

		/**
		* Carousel
		* @uses carousel()
		* @uses jCarouselLite()
		* @see http://www.gmarwaha.com/jquery/jcarousellite/
		*/
		if(typeof scroll !== 'undefined' && scroll === true && $.fn.carousel && $.fn.jCarouselLite) {
			$body.addClass('has-scroll');

			var carouselOptions = {
				speed:			750,
				auto:			5000,
				circular:		true,
				pagination:		false,
				arrows:			true,
				visible:		3,
				start:			0,
				scroll:			1
			};

			if($body.is('.homepage')) {
				carouselOptions.visible	= 4;
				carouselOptions.scroll	= 4;
			}

			$products.filter('.scroller').children('ul').carousel(carouselOptions);
		}


		/**
		* Flash
		* @uses flash()
		* @see http://jquery.thewikies.com/swfobject/
		*/
		if(typeof flash !== 'undefined' && flash === true && $.fn.flash &&
			$.flash.available === true && typeof $.flash.version === 'object' && $.flash.version.major > 7) {
			$body.addClass('has-flash');

			if($featured.length === 1) {
				$featured.empty().flash({
					swf:		$('body').is('.tv_deal') ? '/flash/tv/tv.swf' : '/flash/home/home.swf',
					width:		$featured.width(),
					height:		$featured.height(),
					flashvars:	{},
					params:		{
						AllowScriptAccess: 'always'
					}
				});
			}

			if($video.length === 1 && $video.is('[id]')) {
				// get the type of video
				$videoAudioActive	= $videoAudio.find('ul.nav li.active');
				$videoAudioSection	= $videoAudioActive.closest('div[id]');

				if($videoAudioActive.length === 1) {
					manTip	= {
						name:	$videoAudioActive.children('a').text(),
						mp3:	$video.find('a[href$=.mp3]').attr('href'),
						id:		$video.attr('id').replace('play-', '')
					};

					switch($videoAudioSection.attr('id').toLowerCase()) {
						case 'audio':
							$video.empty().flash({
								swf:		'/flash/man-tips/audio-player.swf',
								width:		$video.width(),
								height:		$video.height(),
								flashvars:	{
									audioName: manTip.name,
									audioPath: manTip.mp3
								},
								params:		{}
							}).removeClass('no-flash');
							break;

						case 'video':
							$video.empty().flash({
								swf:		'/flash/man-tips/preloader.swf',
								width:		$video.width(),
								height:		$video.height(),
								flashvars:	{
									movieName: manTip.name,
									moviePath: '/flash/man-tips/' + manTip.id + '.swf'
								},
								params:		{}
							}).removeClass('no-flash');
							break;
					}
				}
				
			}
		}

		if($.fn.colorbox) {
			$body.addClass('has-lightbox');

			var $dealerHide			= $('#dealerDirections, #dealerSearchInfo, #dealerSearchForm, #dealerSearchResults'),
				$featuredDealer		= $('#features-participating-dealer'),
				$findaDealer		= $('#find-a-dealer, .find-a-dealer');

			$dealerHide.hide();
			$featuredDealer.find('a').colorbox({
				opacity: 0.9
			}, function(){
				dealerMapLoad(jQuery);
			});

			$findaDealer.bind('click', function (event) {
				var $postcode = $('#find-dealer-postcode'),
					html = [], h = 0;

				if ($postcode.length === 0) {
					$postcode = $('<div />').attr('id', 'find-dealer-postcode').hide()

					html[h++] = '<form action="" method="post">';
					html[h++] = '<div class="formField">';
					html[h++] = '<label id="postcodeSearchLabel" for="city">Please enter your postcode</label>';
					html[h++] = '<input type="text" autocomplete="off" id="postcodeSearch" maxlength="100" name="txtQuery" />';
					html[h++] = '</div>';
					html[h++] = '<div class="formSubmit">';
                    html[h++] = '<input type="submit" class="enter" title="Search" id="searchButton" value="Go" />';
                    html[h++] = '</div>';
					html[h++] = '</form>';

					$postcode.append(html.join('')).appendTo('#container');
					$postcode.bind('submit', function (event) {
						//ClickGeocode();
                        //console.log("here");
						flashDealerPopup();
						event.preventDefault();
						$postcode.hide();
					});
				}
                var t,r, b;
                if(event.currentTarget.tagName == "P"){
                   t = $(event.currentTarget).offset().top + 12;
                   r = 7;
                   b = "1px solid #F37021" 
                }else{
                   t = $(event.currentTarget).offset().top + 15;
                   r = 27;
                   b = "none";
                }

                $postcode.css('top', t + 'px').css('right', r + 'px').css('border',b);

				$postcode.show();

				event.preventDefault();
			});

			flashDealerPopup = function () {
                $.colorbox({
                    opacity: 0.9,
                    href:"/dealer_map"
                }, function(){
                    dealerMapLoad(jQuery);
                });
				//$featuredDealer.find('a').trigger('click');
			}
		}


		/**
		* Zoom
		* @uses jqzoom()
		* @see http://www.mind-projects.it/projects/jqzoom/
		*/
		if(typeof zoom !== 'undefined' && zoom === true && $.fn.jqzoom && $zoom.length === 1) {
			init.jqZoom = function() {
				$zoom.jqzoom({
					zoomType:		'standard',
					position:		'top',
					xOffset:		0,
					yOffset:		0,
					zoomWidth:		$zoomImg.width(),
					zoomHeight:		$zoomImg.height(),
					title:			false
				});
				
				$('#zoom').bind('mouseenter', function(){
					$(this).addClass('hover');
				}).bind('mouseleave', function(){
					$(this).removeClass('hover');
				});
				$zoomImg.css({height: $zoomImg.attr('height') + 'px', width: $zoomImg.attr('width') + 'px'});
			};
			
			// preload all the instances which can be used in zoom
			if($body.is('.product-detail')) {
				if($cleanDirty.length === 1) {
					jQuery.preloadImages(
						$zoom.attr('href').replace(/\/zoom\/(dirty\/)?/, '/zoom/'),
						$zoom.attr('href').replace(/\/zoom\/(dirty\/)?/, '/zoom/dirty/'),
						$zoom.attr('href').replace(/\/zoom\/(dirty\/)?/, '/main/'),
						$zoom.attr('href').replace(/\/zoom\/(dirty\/)?/, '/main/dirty/')
					);
				}
				else {
					jQuery.preloadImages(
						$zoom.attr('href').replace(/\/zoom\/(dirty\/)?/, '/zoom/'),
						$zoom.attr('href').replace(/\/zoom\/(dirty\/)?/, '/main/')
					);
				}
			}
			else {
				jQuery.preloadImages(
					$zoom.attr('href').replace(/\/zoom\/(dirty\/)?/, '/zoom/')
				);
			}

			$body.bind('preloadImages', function(){
				$body.addClass('has-zoom');
				init.jqZoom();
				$('<p />').addClass('zoomIn').text('Zoom in').insertAfter($zoom);
			});
		}


		/**
		* Gallery Slider
		* @uses roundabout()
		* @see http://fredhq.com/projects/roundabout/
		*/
		if(typeof getTheLook !== 'undefined' && getTheLook === true && $.fn.roundabout) {
			$body.addClass('has-the-look');

			var $roundaboutUl,
				roundaboutLis		= [],
				roundaboutI			= 0,
				roundaboutArrows	= ['Previous', 'Next'],
				roundaboutAutoPlay,
				roundaboutAutoPlayInterval,
				roundaboutAutoPlayStop = false,
				roundaboutAutoPlayTimeOut = 7500;

			$.each(roundaboutArrows, function(i, val) {
				roundaboutLis[roundaboutI++] = '<li class="' + val.toLowerCase() + '">';
				roundaboutLis[roundaboutI++] = '<a href="#' + val.toLowerCase() + '">';
				roundaboutLis[roundaboutI++] = val;
				roundaboutLis[roundaboutI++] = '</a>';
				roundaboutLis[roundaboutI++] = '</li>';
			});

			$roundaboutUl = $('<ul />').addClass('roundabout-pagination');
			$roundaboutUl.append(roundaboutLis.join('')).appendTo($getTheLook);

			$getTheLook.children('ul.slider').roundabout({
				duration:		1200,
				minOpacity:		0.2,
				minScale:		0.5,
				btnNext:		$getTheLook.selector + ' li.next a',
				btnPrev:		$getTheLook.selector + ' li.previous a',
				clickToFocus:	true,
				startingChild:	$getTheLook.children('ul.slider').children('li.default').index()
			}).bind('blur', function(event){
				$roundaboutUl.hide().find('a').blur();
				$getTheLook.find('div.items').css({bottom: '-120px'}).removeClass('default');
			}).bind('focus', function(event){
				$roundaboutUl.fadeIn(500);
				$(event.target).find('div.items').animate({bottom: '37px'}, 300);
			}).hover(
				function() {
					clearInterval(roundaboutAutoPlayInterval);
				},
				function() {
					if(roundaboutAutoPlayStop === false) {
						roundaboutAutoPlayInterval = roundaboutAutoPlay();
					}
				}
			);

			roundaboutAutoPlay = function() {
				return setInterval(function() {
					$getTheLook.children('ul.slider').roundabout_animateToNextChild();
				}, roundaboutAutoPlayTimeOut);
			};
			roundaboutAutoPlayInterval = roundaboutAutoPlay();

			// stop the auto play when clicked
			$($getTheLook.selector + ' li.next a').add($getTheLook.selector + ' li.previous a').bind('click', function(event){
			  roundaboutAutoPlayStop = true;
				clearInterval(roundaboutAutoPlayInterval);
			});
		}


		/**
		* Lightbox
		* @uses lightBox()
		* @see http://leandrovieira.com/projects/jquery/lightbox/
		*/
		if(typeof lightbox !== 'undefined' && lightbox === true && $.fn.lightBox) {
			$body.addClass('has-lightbox');
			$inAction.find('a').lightBox({
				overlayBgColor:	'#000',
				overlayOpacity:	0.8,
				imageLoading:	'/css/img/lightbox/loading.gif',
				imageBtnClose:	'/css/img/lightbox/close.gif',
				imageBtnPrev:	'/css/img/lightbox/previous.gif',
				imageBtnNext:	'/css/img/lightbox/next.gif',
				imageBlank:		'/css/img/lightbox/btn-next.gif'
			});
		}


		/**
		* Datepicker
		* @uses datePicker()
		* @uses date()
		* @see http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/index.html
		*/
		if(typeof datepicker !== 'undefined' && datepicker === true && $.fn.datePicker && typeof Date === 'function') {
			Date.format = 'dd-mm-yyyy';
			$('div.calendar-picker input').datePicker({
				startDate:		'01/01/2000',
				displayClose:	true,
				clickInput:		true
			});
		}


		/**
		* Adding to cart
		* Post using AJAX and show "Just Added" popup
		*/
		$('form[action*=cart_add][method=post]').bind('submit.cartAdd', function(event){
			var $$, $buyDiv, method, action, $appendTo, animateOptions;

			$$			= $(this);
			$buyDiv		= $$.find('input:submit.button.buy').parent('div');
			method		= $$.attr('method');
			action		= $$.attr('action');
			//$appendTo	= $body;
			$appendTo	= $header;

			$.ajax({
				url:		action,
				type:		method,
				data:		$$.serialize(),
				cache:		false,
				dataType:	'json',
				success:	function(data){
					if(typeof data === 'object' && typeof data.success !== true) {
						var justAddedHtml;

						// update mini cart information
						$miniCart
							.find('span.items').text(data.cart.items).end()
							.find('span.total').text(data.cart.total);

						// add feedback to button
						if($buyDiv.is(':not(.added)')) {
							$buyDiv.addClass('added').append('<span />')
								.children('span').addClass('added').hide().fadeIn(500);
						}

						if($justAdded.length > 0) {
							$justAdded.find('a.close').trigger('click');
						}

						// add the "just added" box
						var legsize = '';
						if(data.variant.leg_size.length > 0) {
							legsize = ' / ' + data.variant.leg_size;
						}
						
						$justAdded		= $('<div />').attr('id', 'just-added');
						justAddedHtml	= {
							hproduct:	{
								wrapper:	$('<div />').addClass('hproduct'),
								img:		$('<img />').addClass('photo').attr({height: 75, width: 75, alt: data.product.product_title + '' + data.product.colour, src: data.product.imageSrc}),
								heading:	$('<h3 />').addClass('fn').text(data.product.product_title),
								colour:		$('<p />').addClass('colour').text(data.variant.colour),
								size:		$('<p />').addClass('size').text(data.variant.size + legsize),
								quantity:	$('<p />').addClass('quantity').text('Qty ' + data.quantity)
							},
							price:		$('<p />').addClass('price').text('£' + data.price),
							close:		$('<a />').addClass('close').text('Close').attr('href', '#close')
						};

						justAddedHtml.hproduct.wrapper
							.append(justAddedHtml.hproduct.img)
							.append(justAddedHtml.hproduct.heading)
							.append(justAddedHtml.hproduct.colour)
							.append(justAddedHtml.hproduct.size)
							.append(justAddedHtml.hproduct.quantity);
							
						$justAdded
							.append(justAddedHtml.hproduct.wrapper)
							.append(justAddedHtml.price)
							.append(justAddedHtml.close);

						if($appendTo.is('body')) {
							var offsetTop = $(window).scrollTop(); // $$.offset().top
							animateOptions = {
								open:	{animate: {left: 0}, options: {duration: 300}},
								close:	{animate: {left: -300}, options: {duration: 300}}
							};
							$justAdded.css({top: offsetTop, left: animateOptions.close.animate.left}).data('animateOptions', animateOptions);
							$appendTo.append($justAdded);
						}
						else {
							animateOptions = {
								open:	{animate: {bottom: 0}, options: {duration: 300}},
								close:	{animate: {bottom: -150}, options: {duration: 300}}
							};
							$justAdded.css({bottom: animateOptions.close.animate.bottom}).data('animateOptions', animateOptions);
							$appendTo.append($justAdded);
						}
						
						$justAdded.animate(animateOptions.open.animate, animateOptions.open.options.duration, function(){
							$justAdded.find('a.close').animate({delay: 1}, 4000, function(event) {
								$(this).trigger('click');
								$buyDiv.children('span.added').fadeOut(300, function(){
									$(this).remove();
									$buyDiv.removeClass('added');
								});
							});
						});
					}
				}
			});

			$$.find('input:submit').blur();
			event.preventDefault();
		}).find('input:submit.button.buy').wrap('<div />').parent().addClass('buy');


		/**
		* Close / Remove "just added" box
		*/
		$justAdded.find('a.close').live('click', function(event){
			var $$, $div;

			$$		= $(event.target);
			$div	= $$.closest('div[id]');

			if(typeof $div.data('animateOptions') === 'object') {
				$div.animate($div.data('animateOptions').close.animate, $div.data('animateOptions').close.options.duration, function(){
					$div.remove();
				});
			}

			event.preventDefault();
		});


		/**
		* Submit quantities on basket
		*/
		$quantityForm.find('select').bind('change.quantity', function(event){
			$(event.target).closest('form').trigger('submit');
		});


		/**
		* FAQ / News Show & Hide
		*/
		$content.find('.collapse').bind('click', {duration: 500}, function(event){
			var $$, $trigger, $toggle;

			$$			= $(event.target);
			$trigger	= $$.closest('.trigger');
			$toggle		= $trigger.parent().find('.toggle');

			if($trigger.length === 1) {
				$toggle.slideToggle(event.data.duration);
				$$.blur();
				event.preventDefault();
			}
		}).find('.trigger').wrapInner('<a href="#" />');


		/**
		* Download radio / button
		*/
		$content.find('#download .sizes')
				.addClass('sizes-download')
				.append('<p class="button download"><a href="#">Download</a></p>')
				.find('li').each(function(i){
					var $$, $a, text, href, idAttr,
						$radio, $label;

					$$		= $(this);
					$a		= $$.children('a');
					text	= $a.text();
					href	= $a.attr('href');
					idAttr	= 'download-' + i;

					$radio	= $('<input type="radio" name="download" id="' + idAttr + '"' + ((i === 0) ? ' checked="checked"' : '') + ' />').val(href);
					$label	= $('<label />').text(text).attr('for', idAttr);

					$$.empty().append($radio).append($label);
				})
				.end().find('p.button').bind('click', function(event){
					var $$, $download, $radio;

					$$			= $(event.target).closest('a');
					$download	= $$.closest('#download');
					$radio		= $download.find('input:radio[checked]');

					window.location.href = $radio.val();

					event.preventDefault();
					$$.blur();
				});
				
				
		/**
		* Sign in radio switch
		*/
		var $signinRegisterExisting = $('#customer-existing');
		var $signinRegisterPassword = $signinRegister.find('div.password');
		$signinRegister.filter(':has(div.radio)').find('#password').bind('keypress', function(event){
			var $$, val;

			$$	= $(this);
			val	= $$.val();

			if(val.length >= 1) {
				$signinRegisterExisting.attr('checked', true);
			}
		}).end().find('input:radio').bind('click', function(event){
			var $$, val;

			$$	= $(event.target);
			val	= $$.val();

			if(val === 'new') {
				//hide the password box
				$signinRegisterPassword.slideUp();
			}
			else if(val === 'existing') {
				//show the password box
				$signinRegisterPassword.slideDown();
			}
		});
		


		/**
		* Delivery address toggle
		*/
		var $addressDeliveryLabel, $addressDeliveryCheckbox,
			$addressDeliveryToggle, $addressDeliveryShowHide;

		$addressDeliveryLabel		= $('<label />').attr('for', 'toggle-delivery-checkbox').text('My shipping address is different to my billing address');
		$addressDeliveryCheckbox	= $('<input type="checkbox" />').attr('id', 'toggle-delivery-checkbox').attr('name', 'toggle-delivery-checkbox').attr('checked', false);
		$addressDeliveryToggle		= $('<div />').attr('id', 'toggle-delivery').addClass('checkbox');
		$addressDeliveryShowHide	= $addressDelivery.children('div').not('#' + $addressDeliveryToggle.attr('id')).wrapAll('<div />').parent().addClass('toggle');

		$addressDeliveryToggle.append($addressDeliveryCheckbox).append($addressDeliveryLabel);
		$addressDeliveryShowHide.before($addressDeliveryToggle);

		$addressDeliveryCheckbox.bind('click', function(event){
			if($addressDeliveryCheckbox.is(':checked')) {
				$addressDeliveryShowHide.slideDown();
			}
			else {
				$addressDeliveryShowHide.slideUp();
			}
		}).closest('form').bind('submit', function(event){
			if($addressDeliveryCheckbox.is(':not(:checked)')) {
				$addressBilling.find('input').each(function(i){
					var $$, val, id, newId;

					$$		= $(this);
					val		= $$.val();
					id		= $$.attr('id');
					newId	= id.replace('billing', 'delivery');

					$('#' + newId).val(val);
				});
			}
		});


		/**
		* Select create new address, show new address fields
		*/
		$('.address-select', $content).find('div > input:radio').bind('click', function(event){
			var $$, val, name, $show;

			$$		= $(event.target);
			val		= $$.val();
			name	= $$.attr('name');
			$show	= $$.closest('fieldset').children('fieldset');

			if((name === 'use_new' || name === 'del_use_new') && val === '1') {
				$show.slideDown();
			}
			else {
				$show.slideUp();
			}
		});


		/**
		* Fade in offers
		*/
		if(typeof offers === 'object' && offers.length > 1) {
			$extraOffer.wrap('<div class="offers" />');
			$.each(offers, function(i, offer){
				if($extraOffer.text() !== offer) {
					var $p = $('<p />').text(offer).hide();
					$extraOffer.parent().append($p);
				}
			});
			window.setInterval(function(){
				var $offers, $visible, $next;

				$offers		= $extraOffer.parent();
				$visible	= $offers.find('p:visible');
				$next		= $visible.next('p');

				if($next.length === 0) {
					$next = $offers.children('p:first');
				}
				$visible.fadeOut(300, function(){
					$next.fadeIn(300);
				});

			}, 5000);

		}


		/**
		* Switch between clean / dirty
		*/
		$cleanDirty.bind('click.cleanDirty', function(event){
			var $$, $p, $a, old, change;

			$$		= $(event.target).closest('a');
			$p		= $$.closest('p');
			$a		= $p.children('a');

			old		= {
				href:	$zoom.attr('href'),
				src:	$zoomImg.attr('src'),
				url:	$a.attr('href')
			};
			change	= {
				href:	old.href.replace('dirty/', ''),
				src:	old.src.replace('dirty/', ''),
				url:	old.url.replace('dirty', '')
			};

			if($$.length === 1) {
				if($p.is('.clean-on')) {
					// the image is currently dirty, switch to clean version
					$p.removeClass('clean-on').addClass('get-dirty');
					$a.text('Get Dirty');
					change.url += 'dirty';
				}
				else {
					$p.removeClass('get-dirty').addClass('clean-on');
					$a.text('Clean On');
					change.href		= change.href.replace('/zoom/', '/zoom/dirty/');
					change.src		= change.src.replace('/main/', '/main/dirty/');
				}

				$zoom.attr('href', change.href);
				$zoomImg.attr('src', change.src);
				$a.attr('href', change.url);

				$$.blur();
				event.preventDefault();
			}
		});


		/**
		* Product toggle
		*/
		$productToggle.find('h2')
			.wrapInner('<a />').children('a').attr('href', '#toggle')
			.bind('click.productToggle', function(event){
				var $$, $div, $toggle, id, data;

				$$			= $(event.target).closest('a');
				$div		= $$.closest('div.product-toggle');
				$toggle		= $div.find('div.toggle');
				id			= $div.attr('id');
				data		= {
					active:	'active'
				};

				if($toggle.is(':hidden')) {
					$toggle.show().addClass(data.active);
					$productToggle.find('div.toggle').not($toggle).hide().removeClass(data.active);
					window.location.hash = id;
				}
				else {
					$toggle.hide().removeClass(data.active);
					window.location.hash = '';
				}

				$$.blur();
				event.preventDefault();
		});
		$('<p />').addClass('lede')
				  .text('Select a category which you wish to edit the products for.')
				  .insertBefore($productToggle.eq(0));


		/**
		* Submit default address
		*/
		$addressManagement.find('input:radio').bind('click', function(event){
			var $$, $form;

			$$		= $(this);
			$form	= $$.closest('form');

			if($$.is(':checked')) {
				$form.submit();
			}
		});


		/**
		* Confirm remove forms
		*/
		$('form.remove').bind('submit', function(event){
			return (confirm('Are you sure?'));
		});


		// cms auto-submit
		$('#order_status, #order select, .order-detail-update select').bind('change', function(event){
			$(event.target).closest('form').get(0).submit();
		});

		// cms order table
		$('#order table .details').prepend('<a />').children('a').attr('href', '#show').text('Show detail').bind('click', function(event){
			var $$, $div;

			$$		= $(event.target);
			$div	= $$.next('div');

			if($div.is(':hidden')) {
				$div.slideDown(); $$.text('Hide detail');
			}
			else {
				$div.slideUp(); $$.text('Show detail');
			}
			

			$$.blur();
			event.preventDefault();
		}).next('table').wrap('<div />').show().parent().hide();


		/**
		* Custom Scrollbar
		* @uses jScrollPane()
		* @uses mousewheel() (optional)
		* @see http://www.kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html
		* --------------------------------------------------------------------------------------------------
		*/
		if(typeof scrollbar !== 'undefined' && scrollbar === true && $.fn.jScrollPane && (!$.browser.msie || ($.browser.version > 6))) {
			$body.addClass('has-scroll');

			$scroll.jScrollPane({
				scrollbarWidth:		16,
				scrollbarMargin:	0,
				showArrows:			true
			});
		}


		/**
		* Custom Checkbox / Radio
		* @uses checkbox()
		* --------------------------------------------------------------------------------------------------
		*/
		if(typeof checkbox !== 'undefined' && checkbox === true && $.fn.checkbox) {
			$('#alternatively input:radio').checkbox({
				cls:	'custom-radio',
				empty:	'/css/img/misc/empty.gif'
			}).closest('div.radio').addClass('custom-radio');
		}


		/**
		* Rating
		* @uses rating()
		* @see http://www.fyneworks.com/jquery/star-rating/
		* --------------------------------------------------------------------------------------------------
		*/
		if($.fn.rating) {
			var $review = $('#add-review'),
				$ul = $review.find('ul'), $radio = $ul.find('input');

			$ul.replaceWith($radio);
			$radio.rating();
		}


		/**
		* Replace Multimap Telephone number
		
		var replaceTelephone = setInterval(function(){
			var $telephone = $('#store_locator').contents().find('td:contains(0845 66 515 99)');
			if($telephone.length > 0) {
				clearInterval(replaceTelephone);
				$telephone.text('For assistance please call 0115 938 9000')
			}
		}, 500);
		*/
	});

	// Flash External Interface
	jQuery.fn.callFlash = function(callback, variables, prefix) {
		var $$, dom, data = 0;
		$$ = jQuery(this);
		if($$.length === 1) {
			dom = $$.get(0);
			if($$.attr('id').length > 0) {
				dom = document.getElementById($$.attr('id')); // safer
			}
			if(typeof prefix === 'string') {
				callback = prefix + callback.charAt(0).toUpperCase() + callback.substr(1);
			}
			if(typeof dom !== 'undefined' && typeof dom[callback] === 'function') {
				data = dom[callback](variables);
			}
		}
		return data;
	};

	// Preload images
	jQuery.preloadImages = function() {
		var total	= arguments.length,
			loaded	= 0;
			
		jQuery.each(arguments, function(i){
			jQuery('<img />').bind('load', function(){
				loaded++;
				if(loaded === total) {
					jQuery('body').trigger('preloadImages');
				}
			}).attr('src', this);
		});
	};
	
	//Hover for size images
	if(jQuery('.product-detail .size-image a')) {
		var a = jQuery('.product-detail .size-image a');
		
		jQuery('.product-detail .size-image a').each(function(){
			var link = jQuery(this);
			link.hover(function(e){
				var wrapperInner = link.find('.mark');
				wrapperInner.addClass('custom-radio-hover');
			},
			function(e){
				var wrapperInner = link.find('.mark');
				wrapperInner.removeClass('custom-radio-hover');
			});
		});
	}

}


/******
 * Dealer map
 ******/

if(typeof jQuery !== 'undefined') {
    var map = null,
		bbox = null,
		dealers = null,
        drivingStart = '',
		viewBoundaries = null;

        var dealerMapLoad = function($) {
            $map	= $('#dealer-map');

            if(typeof $map !== 'undefined' && $map.length>0){
                jQuery('#dealerDirections, #dealerSearchInfo, #dealerSearchFormNoResults, #dealerSearchResults').hide();
                map = new Microsoft.Maps.Map($map[0], {
                    credentials: "AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx",
                    showDashboard:false,
                    mapTypeId: Microsoft.Maps.MapTypeId.road
                });

                Microsoft.Maps.Events.addHandler(map,"viewchangestart",function(){
                    if(jQuery('#infoBox').length>0){  
                        jQuery('#infoBox')[0].style.visibility = "hidden";
                    }
                });
            }

            if(jQuery('#postcodeSearch').length>0 && jQuery('#postcodeSearch').val().length>0){
                //console.log('here');
                jQuery('#txtQuery').val(jQuery('#postcodeSearch').val());

		        ClickGeocode();
            }
        };



		function ClickGeocode(credentials)
		{
            map.entities.clear(); 
            jQuery('#dealerSearchForm').hide();
            jQuery('#dealerDirections').hide();
            jQuery('#dealerDirectionsContainer').hide();
            jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
            jQuery('#dealerDirectionsDirections').hide();
		   map.getCredentials(MakeGeocodeRequest);
		}

        function MakeRouteRequest(result){
			if (result &&
				   result.resourceSets &&
				   result.resourceSets.length > 0 &&
				   result.resourceSets[0].resources &&
				   result.resourceSets[0].resources.length > 0) 
			{
                var d = dealers[jQuery('#endID').val()];
                var request =  "http://dev.virtualearth.net/REST/V1/Routes?wp.0=";
                request += result.resourceSets[0].resources[0].point.coordinates[0] + ",";
                request += result.resourceSets[0].resources[0].point.coordinates[1] + "&wp.1="
                request += d.Latitude + "," 
                request += d.Longitude 
                request += "&optimize=distance&routePathOutput=Points&output=json&jsonp=RouteCallback&key=AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx";

                CallRestService(request);
            }
        }
	
        function GetRouteMap() {
            drivingStart = jQuery('#start').val();
            map.entities.clear(); 
            jQuery('#dealerDirections').hide()
            jQuery('#dealerDirectionsContainer').hide()
            jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
            jQuery('#dealerDirectionsDirections').hide();
            if (drivingStart != '' && drivingStart != "Enter address here") {
                var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + escape(drivingStart + ', UK') + "?output=json&jsonp=MakeRouteRequest&key=AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx";
                jQuery('dealerDirections').hide();
			    CallRestService(geocodeRequest);
            }
		}

        function showSearchForm(){
                jQuery('#dealerDirections, #dealerSearchInfo, #dealerSearchForm, #dealerSearchResults').hide();
                jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
                jQuery('#dealerDirectionsContainer').html('');
                jQuery('#dealerSearchFooter').hide();
                jQuery('#dealerSearchForm').show();
                jQuery('#txtQuery').select();
        }

		function MakeGeocodeRequest(credentials)
		{
            var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + escape( jQuery('#txtQuery').val() + ', UK') + "?output=json&jsonp=GeocodeCallback&key=" + credentials;
			CallRestService(geocodeRequest);
		}

            function ShowDrivingDirectionsForm(id) {
                ShowDirectionsView();
                jQuery('#endID').attr('value', id);
                jQuery('#endText').html(dealers[id].Name + "<br />DIRECTIONS");
            }

            function ShowDrivingDirectionsFormByShapeIndex(i) {
                ShowDrivingDirectionsForm(i);
            }

            function RouteCallback(result){
                if(typeof result.resourceSets === "undefined" ||
                    result.resourceSets.length == 0 ||
                    typeof result.resourceSets[0].resources === "undefined" ||
                    result.resourceSets[0].resources.length == 0 )
                {
                    
                    
                    
                    jQuery('#dealerDirectionsContainer').html('');
                    jQuery('#dealerDirectionsNoResults').show();  // make sure error is hidden
                    jQuery('#start').select();
                    return;
                }
                
                var route = result.resourceSets[0].resources[0]; 
                var bbox = route.bbox; 
                viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(
                new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3])); map.setView({ bounds: viewBoundaries });
                var totalTime = route.travelDuration; 
                var timeUnit = route.durationUnit; 
                var totalDistance = route.travelDistance; 
                var distanceUnit = route.distanceUnit;
               
                ShowTurns(route);
            // Draw the route
                var routeline = route.routePath.line;
                var routepoints = new Array();
                for (var i = 0; i < routeline.coordinates.length; i++){
                    routepoints[i] = new Microsoft.Maps.Location(
                        routeline.coordinates[i][0],
                        routeline.coordinates[i][1]
                    );
                }
                // Draw the route on the map
                
                var routeshape = new Microsoft.Maps.Polyline(
                    routepoints, {
                        strokeColor: new Microsoft.Maps.Color(200, 0, 0, 200)
                });

                map.entities.push(routeshape);
            }

            function ShowTurns(route) {
                var leg = (route == null) ? route : route.routeLegs[0];
                var turns;
                var turn = null;  // The itinerary leg
                var legDistance = null;  // The distance for this leg
            

                if (route != null)
                    turns = '<div class="tripDetails">Trip: ' + route.travelDistance.toFixed(1) + ' miles' + ', ' + GetTime(route.travelDuration) + '</div>';
                    
                    
                if (leg != null) {

                    turns += '<ol>';

                    jQuery(leg.itineraryItems).each(function(i,turn) {
                        turns += '<li><span class="step">' + (i + 1) + '</span>' + turn.instruction.text;

                        legDistance = turn.travelDistance;

                        // So we don't show 0.0 for the arrival
                        if (legDistance > 0) {
                            // Round distances to 1/10ths
                            turns += '<br /><span class="distance">' + legDistance.toFixed(1) + ' miles</span>';
                        }
                        turns += '</li>';
                    });

                    turns += '</ol>';
                    jQuery('#endText').html(jQuery('#endText').html() +"<p id=\"startp\">Start: "+jQuery('#start').val()+"</p>");
                    jQuery('#dealerDirections').show()
                    jQuery('#dealerDirectionsContainer').html(turns).show();
                    jQuery('#dealerDirectionsForm').hide();
                    jQuery('#dealerDirectionsFooter').show();
                    jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
                    jQuery('#dealerDirectionsDirections').show();
                }
                else {
                    jQuery('#dealerDirectionsContainer').html('');
                    jQuery('#dealerDirectionsNoResults').show();  // make sure error is hidden
                    jQuery('#dealerDirectionsForm').show();
                    jQuery('#start').select();
                }

            }

            function GetTime(time) {
                seconds = time % 60;
                time = Math.floor(time / 60);
                minutes = time % 60;
                hours = Math.floor(time / 60);

                if(hours > 0){
                    return (hours + " hour(s), " + minutes + " min");
                }

                return (minutes + " min");
            }
        
            ShowDirectionsView = function() {
                jQuery('#dealerDirections, #dealerSearchInfo, #dealerSearchForm, #dealerSearchResults').hide();
                jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
                jQuery('#dealerDirectionsFooter').hide();  // make sure error is hidden
                jQuery('#dealerDirectionsContainer').html('');
                jQuery('#dealerDirections').show();
				jQuery('#dealerDirectionsForm').show();//Laura Fix 29-07-211
                jQuery('#start').select();
            }
            


        function QueryAPIRequest(lat,lng,credentials){
            jQuery.getJSON(
              "/search.php",
              {lat:lat,lng:lng, dist:75,site:(jQuery('body').is('.tv_deal')?'redTop':'scruffs')},
              function(data) {
                  dealers = data.d.results;
                  var list = '<ol>';
                  var minLat = null;
                  var maxLat = null;
                  var minLng = null;
                  var maxLng = null;

                  if(dealers.length <= 0){
                    jQuery('#dealerSearchResults, #dealerSearchResultsNoResults').show();
                    jQuery('#dealerSearchResultsContainer').hide();
			        map.setView({ bounds: bbox});
                    return;
                  }

                  jQuery(dealers).each(function(index,dealer){
                      list += "<li id=\"dealer_"+dealer.EntityID+"\"><h3><a href=\"javascript: ZoomToPoint("+index+")\" >" + dealer.Name + "</a></h3>";
                      list += "<p>" + dealer.AddressLine + "</p>"
                      list += "<p>"+ dealer.PrimaryCity+" "+dealer.PostalCode +"</p>";
                      list += "<strong>"+dealer.Phone + "</strong>";
                      list += "<a class=\"getDirections\" href=\"javascript: ShowDrivingDirectionsFormByShapeIndex("+index+")\">Get Directions</a>"; 
			            var location = new Microsoft.Maps.Location(dealer.Latitude, dealer.Longitude);
        			    var pin = new Microsoft.Maps.Pushpin(location,{"icon":"/css/img/misc/marker.gif","width":40,"height":40});
                        pin.title = dealer.Name;
                        pin.description = "<p>" + dealer.AddressLine + "</p><p>"+ dealer.PrimaryCity+" "+dealer.PostalCode +"</p><strong>"+dealer.Phone + "</strong>";

        				Microsoft.Maps.Events.addHandler(pin, 'click', displayEventInfo);

                        
                        minLat = (minLat==null || minLat>dealer.Latitude)?dealer.Latitude:minLat;
                        minLng = (minLng==null || minLng>dealer.Longitude)?dealer.Longitude:minLng;

                        maxLat = (maxLat==null || maxLat<dealer.Latitude)?dealer.Latitude:maxLat;
                        maxLng = (maxLng==null || maxLng<dealer.Longitude)?dealer.Longitude:maxLng;

        			    map.entities.push(pin);
                  });
                  list += '</ol>';



                  jQuery('#dealerSearchResultsNoResults').hide();
                  jQuery('#dealerSearchResults, #dealerSearchResultsContainer').show();
                  var s = jQuery('#txtQuery').val().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
                  
//                  jQuery('#dealerSearchResultsContainer').html("<div id=\"resultsHeader\">Search results for: <strong>"+s+"</strong><a class=\"change\" onclick=\"showSearchForm()\" href=\"javascript:void(0)\" >Change</a><br /></div>"+ list);
                  jQuery('#dealerSearchResultsContainer').html(list);
                        
                  borderX =  ((maxLng - minLng) * 1.01)/2
                  borderY =  ((maxLat - minLat) * 1.01)/2


                  var mapBoundsTL = new Microsoft.Maps.Location(minLat-borderX, minLng-borderY);
                  var mapBoundsBR = new Microsoft.Maps.Location(maxLat+borderX, maxLng+borderY);

			      viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(mapBoundsTL, mapBoundsBR);
			      map.setView({ bounds: viewBoundaries});
              }
            );
        }

        function ZoomToPoint(index){
            var d = dealers[index];
            var tp = null;
            for(var i = 0; i<map.entities.getLength(); i++){
                p = map.entities.get(i)
                if(p.toString() == "[Pushpin]" && d.Latitude==p.getLocation().longitude && d.Longitude==p.getLocation().latitude){
                    p.setOptions({"visible":true});
                    tp = p;
                }else{
                    p.setOptions({"visible":false});
                }
            }
            var handlerid = null;
            handlerid = Microsoft.Maps.Events.addHandler(map,"viewchangeend",function(){
                ShowInfo(tp);
                Microsoft.Maps.Events.removeHandler(handlerid);
            });
            map.setView({"center":tp.getLocation(), "zoom":16});

        }

        function ZoomFromPoint(){
            for(var i = 0; i<map.entities.getLength(); i++){
                p = map.entities.get(i)
                if(p.toString() == "[Pushpin]"){
                    p.setOptions({"visible":true});
                }
            }

			map.setView({ bounds: viewBoundaries});
        }
		
        function changeView(view){
			switch(view){
				case 'birdseye':
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.birdseye});
					break;
				case 'road':
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.road});
					break;
				case 'aerial':
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.aerial});
					break;
				default:
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.road});
					break;
			}
        }

		function CallRestService(request) 
		{
			var script = document.createElement("script");
			script.setAttribute("type", "text/javascript");
			script.setAttribute("src", request);
			document.body.appendChild(script);
		}
  
		function GeocodeCallback(result) 
		{
			if (result &&
				   result.resourceSets &&
				   result.resourceSets.length > 0 &&
				   result.resourceSets[0].resources &&
				   result.resourceSets[0].resources.length > 0) 
			{
			    bbox = result.resourceSets[0].resources[0].bbox;
                map.entities.clear(); 
				Microsoft.Maps.Pushpin.prototype.title = null;
				Microsoft.Maps.Pushpin.prototype.description = null;

                QueryAPIRequest(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1],'AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx');
			}
		}

		function displayEventInfo(e) {
			if (e.targetType = "pin") {
                var t = e.target;
                for(var i = 0; i<map.entities.getLength(); i++){
                    p = map.entities.get(i)
                    if(p == t){
                        p.setOptions({"visible":true});
                        tp = p;
                    }else{
                        p.setOptions({"visible":false});
                    }
                }
                var handlerid = null;
                handlerid = Microsoft.Maps.Events.addHandler(map,"viewchangeend",function(){
                    ShowInfo(tp);
                    Microsoft.Maps.Events.removeHandler(handlerid);
                });

                map.setView({"center":tp.getLocation(), "zoom":16});
                ShowInfo(e.target);
			}
		}


		function ShowInfo(pin) {
              var pix = map.tryLocationToPixel(pin.getLocation(), Microsoft.Maps.PixelReference.control);
              var infoboxTitle = document.getElementById('infoboxTitle');
              infoboxTitle.innerHTML = pin.title;
              var infoboxDescription = jQuery('#infoboxDescription');
              infoboxDescription.html(pin.description);
              var infobox = document.getElementById('infoBox');
              if(infobox){
                  infobox.style.top = (pix.y - 60) + "px";
                  infobox.style.left = (pix.x + 5) + "px";
                  infobox.style.visibility = "visible";
                  document.getElementById('dealer-map').appendChild(infobox);
              }
		}

		function closeInfoBox() {
			  var infobox = document.getElementById('infoBox');
              ZoomFromPoint();
			  infobox.style.visibility = "hidden";
		}


	jQuery(document).ready(function($) {
		dealerMapLoad(jQuery);
	});
        
    
	$('#accordion1').accordionza({
		autoPlay: true,
		captionDelay: 100,
		captionEasing: 'easeOutBounce',
		captionHeight: 40,
		captionHeightClosed: 10,
		navKey: true,
		slideDelay: 5000
	});
        
     
}


/*****
 * End Dealer map
 *****/

