// 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,
			$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:		'/flash/home/home.swf',
					width:		$featured.width(),
					height:		$featured.height(),
					flashvars:	{},
					params:		{}
				});
			}

			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;
					}
				}
				
			}
		}


		/**
		* 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
						$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.product.colour),
								size:		$('<p />').addClass('size').text(data.product.size),
								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?'));
		});


		/**
		* 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');
		}


		/**
		* 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);
		});
	};
}