/**
 * Created by: Derek Henderson, 2010
 * Modified by: Matt Hinchliffe, 09/05/2011
 *
 * TRY TO KEEP THIS FILE SYNCHRONISED WITH AQUASCUTUM GLOBAL.JS
 */

// this is a quick little hack which prevents back button caching
window.onbeforeunload = function() {};

// Array indexOf hack for IE7 and below, written by Daniel James
if (!Array.prototype.indexOf)
{
	Array.prototype.indexOf = function(obj, fromIndex)
	{
		if (fromIndex === null)
			fromIndex = 0;
		else if (fromIndex < 0)
			fromIndex = Math.max(0, this.length + fromIndex);

		for (var i = fromIndex, j = this.length; i < j; i++)
		{
			if (this[i] === obj)
				return i;
		}
		return -1;
	};
}

/**
 Mega menu
 **/
var categories = new Array();

$(function()
{
	// load nav from shortcut which is created from div in landing page
	$.get('index.cfm?page=womens-mega-menu', function(data) {categories['navWomens'] = data;});
	$.get('index.cfm?page=mens-mega-menu', function(data) {categories['navMens'] = data;});
	$.get('index.cfm?page=accessories-mega-menu', function(data) {categories['navAccessories'] = data;});
	$.get('index.cfm?page=homeware-mega-menu', function(data) {categories['navHomeware'] = data;});
	$.get('index.cfm?page=boutique-mega-menu', function(data) {categories['navBoutique'] = data;});
	$.get('index.cfm?page=experience-mega-menu', function(data) {categories['navExperience'] = data;});
	$.get('index.cfm?page=sale-mega-menu', function(data) {categories['navSale'] = data;});

	$('#topnav li').hover(function()
	{
		var navCat = $(this).attr('id').replace(/-([a-z])/,"$1");
		navCat = navCat.substring(0,3) + navCat.charAt(3).toUpperCase() + navCat.substring(4);

		$(this)
			.append(categories[navCat])
			.addClass('selected')
			.siblings()
			.removeClass('hover');

		if ($.browser.msie && $.browser.version.substr(0, 1) <= 6)
		{
			$('select,input').css('visibility', 'hidden');
			$('#topnav select,#topnav input').css('visibility', 'visible');
		}
	},
	function()
	{
		$(this)
			.removeClass('selected')
			.find('.mega-dropdown-wrapper')
			.empty()
			.remove();

		if ($.browser.msie && $.browser.version.substr(0, 1) <= 6) $('select,input').css('visibility', 'visible');
	});

	// LeftNav highlighting style
	$('.subnav li a').each(function()
	{
		if (pageLoc)
		{
			if ($(this).attr("href").indexOf(pageLoc) != "-1")
				$(this).parent().addClass("selected");
		}
	});
});

/**
 Brand tooltips
 **/
$(function()
{
	$('.brand-home-img')
		.mouseover(function()
		{
			$('.brand-hover').addClass("show");
		})
		.mouseleave(function()
		{
			$('.brand-hover').removeClass("show");
		});
});

/**
 Image captions
 - Margins animate more smoothly than heights
 **/
$(function()
{
	$('.caption').each(function()
	{
		$(this)
			.prev()
			.add($(this))
			.wrapAll('<div class="captioned"/>');
	});

	$('.captioned')
		.each(function()
		{
			var $_target = $(this).find('.caption');

			var captionPosition = {
				hide: -$_target.outerHeight() - 1,
				show: 0
			};

			$(this)
				.hover(function()
				{
					$_target
						.stop()
						.animate({ bottom: captionPosition.show }, 300);
				},
				function()
				{
					$_target
						.stop()
						.animate({ bottom: captionPosition.hide }, 300)
				});

			$_target.css('bottom', captionPosition.hide + 'px');
		});
});

/**
 Expanding FAQ lists
 **/
$(function()
{
	if (!($.browser.msie && $.browser.version.substr(0, 1) <= 6))
	{
		// remove the "return to top" links
		$('.return-to-top').each(function() {
			$(this).parent().empty().remove();
		});

		$('.faq-wrapper').addClass('faq-active');

		// grab the content of each dt and put it in the box to the right
		$('.faq-wrapper dt').each(function()
		{
			var faqId = $(this).attr('id'),
			    faqQuery = $(this).text();

			$(this)
				.removeAttr('id')
				.wrapInner('<a href="#' + faqId + '"/>')
				.wrapInner('<div class="inner-wrapper"/>')
				.next('dd')
				.attr('id', faqId)
				.wrapInner('<div class="inner-wrapper"/>')
				.children('.inner-wrapper')
				.prepend('<h3>' + faqQuery + '</h3>');
		});

		$('.faq-active dt a').click(function(e)
		{
			e.preventDefault();

			// Hide self if selected
			if ($(this).hasClass('selected'))
			{
				$(this)
					.removeClass('selected')
					.next('dd')
					.removeClass('selected');
			}
			// Hide others selected and position self
			else
			{
				var $_parent = $(this).closest('dt'),
				    $_sibling = $_parent.next('dd');

				$_parent
					.addClass('selected')
					.siblings()
					.removeClass('selected')
					.next('dd')
					.removeClass('selected');

				$_sibling.addClass('selected');

				var position = $_parent.position();

				$_sibling.css('top', (position.top-30) + 'px');

				var defPos = $_sibling.offset(),
				    defBottPos = Math.floor(defPos.top + $_sibling.find('.inner-wrapper').outerHeight()),
				    footerPos = $('#footer').offset(),
				    contentBottPos = Math.ceil(footerPos.top - 25);

				if (defBottPos > contentBottPos)
					$_sibling.css('top', position.top-(15 + (defBottPos - contentBottPos)) + 'px');

				if ($_sibling.find('.inner-wrapper').outerHeight() > $(this).closest('.faq-wrapper').outerHeight())
				{
					var defHeight = $(this).closest('.faq-wrapper').outerHeight() - 30;

					if (defHeight > 440)
						$_sibling.find('.inner-wrapper').css('height', defHeight + 'px').css('overflow-y', 'scroll');

					$_sibling.css('top', '15px');
				}
			}
		});
	}
});

/**
 Tabs
 - Grabs headers within container and turns them into a list
 **/
$.fn.tabsActivate = function()
{
	$(this).each(function()
	{
		var $_target = $(this),
		    $_tabs = $('<ul class="tabs-nav"></ul>').prependTo($_target),
		    $_links;

		if ($_target.parent().hasClass('size-guide'))
			$_links = 'h2';
		else
			$_links = 'h2, h3';

		// Create tab links
		$_target
			.addClass('tabs-active')
			.find($_links).each(function()
			{
				var href = $(this).next('div').attr('id'),
				    text = $(this).text();

				$_tabs.append('<li><a href="#' + href + '">' + text + '</a></li>');
			});

		// Select first tab and tab content
		$_target
			.find('.tabs-content')
			.children()
			.first()
			.addClass('tabs-selected');

		$_tabs
			.children()
			.first()
			.addClass('tabs-selected')
			.parent()
			.find('a')
			.click(function(e)
			{
				var $_this = $(this).parent();

				if (!$_this.hasClass('tabs-selected'))
				{
					$_this
						.addClass('tabs-selected')
						.siblings()
						.removeClass('tabs-selected');

					$(this.hash)
						.parent()
						.addClass('tabs-selected')
						.siblings()
						.removeClass('tabs-selected');
				}

				e.preventDefault();
			});
	});
};

$(function()
{
	$('.tabs-container').tabsActivate();
});

/**
 jQuery UI Accordions
 **/
$(function()
{
	$('.accordion').accordion(
	{
		header:'h4',
		autoHeight:false,
		collapsible:true,
		active:true
	});
});

/**
 basket.js
 **/
$(function()
{
	// load basket html from another page; delay creation until shopping basket link is hovered over, to reduce server load
	var dropdownBasket, showbasket = $('#ajaxCall').val(),

	// generate a random number to prevent IE from caching the AJAX call
	randomNum = Math.random();

	// a hack to ensure the minibasket doesn't show when an item is out of stock
	$('.main-prod-details p').each(function() {if ($(this).attr('class')=='error') {showbasket='false';}});

	// if the showbasket element is set to true, load and show the basket (and set the showbasket element to false).
	if (showbasket == 'true') {
		showbasket = 'false';
		$.get('index.cfm?page=shopping_bag_mini&iecachebuster='+randomNum, {cache:false}, function(data) {

			dropdownBasket = data;
			$('#basket')
				.append(dropdownBasket)
				.addClass("selected");

			$('.basket-dropdown-wrapper').delay(2000).fadeOut("slow", function() {
				$('#basket').removeClass("selected");
				$(this).empty().remove();
			});
			// drop down menu on hover
			$('#basket').hover(function() {
				if (parseInt($('#basket dd').text(), 10)>0) {
					$(this).append(dropdownBasket);
					$(this).addClass("selected");
				}
			}, function() {
				$('.basket-dropdown-wrapper').empty().remove();
				$(this).removeClass('selected');
			});
		});
	}
	else {
		// if the basket has not already been loaded, it will be loaded on the first hover over. 'true' tells the function to treat it as a hover.
		$('#basket').one('mouseover', function() {
			$.get('index.cfm?page=shopping_bag_mini&iecachebuster='+randomNum, {cache:false}, function(data) {
				dropdownBasket = data;
				$('#basket').append(dropdownBasket);
				$('#basket').addClass("selected");
				// show basket on hover
				$('#basket').hover(function() {
					if (parseInt($('#basket dd').text(), 10)>0) {
						$(this).append(dropdownBasket);
						$(this).addClass("selected");
					}
				}, function() {
					$('.basket-dropdown-wrapper').empty().remove();
					$(this).removeClass('selected');
				});
			});
		});
	}
	$('#ajaxCall').val(showbasket);
	$('#add-to-basket').submit(function() {$('#ajaxCall').val('true');});

	// Enhance basket on basket page
	$('.basket-update').each(function() {
		$(this).empty().remove();
	});
	$('.charges-details .button').empty().remove();
	$('.col-quant select,#delivery-type').change(function() {
		$('#shopping-bag').submit();
	});
});

/**
 checkout-process.js
 **/
$(function()
{
	$('#delivery-address')
		.add('#delivery-type')
		.change(function()
		{
			$(this).closest('form').submit();
		})
		.next('.button')
		.empty()
		.remove();
});

/**
 Login page
 **/
$(function()
{
	if ($('body').hasClass('login'))
	{
		$('#email')
			.focus()
			.add('#password')
			.val('');
	}
});

/**
 Product list rollovers
 - for images that have an alternate look on rollover, this script makes it happen.  For it to work, the alternate image (the 'look' image) must begin with the string 'look-'
 **/
$(function()
{
	if ($("body").hasClass("prod-list-4"))
	{
		var rolloverImgHeight = 367;

		$(".look-rollover img").each(function()
		{
			var src = $(this).attr('src'),
			    rel = $(this).attr('rel');

			// Swap any images with incorrect aspect ratio
			if (src.indexOf('6x2') > 0)
				$(this).attr('src', (src = src.replace('6x2', '4x3')));

			// Create rollovers
			if (rel.length > 1)
			{
				// Fix aspect ratio
				if (rel.indexOf('6x2') > 0)
					$(this).attr('rel', (rel = rel.replace('6x2', '4x3')));

				// Create images and hover
				$(this)
					.after('<img class="over" src="' + rel + '" width="240" height="' + rolloverImgHeight + '" />')
					.parent()
					.parent()
					.hover(function()
					{
						$(this).addClass('hover');
					},
					function()
					{
						$(this).removeClass('hover');
					})
			}
		});
	}
});

/**
 print-page.js
 jQuery print plugin by Ben Nadel, with a few modifications by Derek Henderson. Original (commented) code can be found at http://www.bennadel.com/index.cfm?dax=blog:1591.view
 **/
$.fn.print = function()
{
	if (this.size() > 1)
	{
		this.eq( 0 ).print();
		return;
	}
	else if (!this.size())
		return;

	var objDoc, tab, objFrame;

	if ($.browser.opera)
	{
		tab = window.open("", "print-preview");
		tab.document.open();
		objDoc = tab.document;
	}
	else
	{
		var strFrameName = ("printer-" + (new Date()).getTime());

		$("<iframe name='" + strFrameName + "'>")
			.css("width", "0")
			.css("height", "0")
			.css("position", "absolute")
			.css("top", "-999px")
			.css("left", "-999px")
			.appendTo($("body:first"));

		objFrame = window.frames[ strFrameName ];
		objDoc = objFrame.document;
	}

	var jStyleDiv = $("<div>").append($("link").clone());

	objDoc.open();
	objDoc.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
	objDoc.write("<html>");
	objDoc.write('<body class="' + $('body').attr('class') + '">');
	objDoc.write("<head>");
	objDoc.write("<title>");
	objDoc.write(document.title);
	objDoc.write("</title>");
	objDoc.write(jStyleDiv.html());
	objDoc.write("</head>");
	objDoc.write(this.html());
	objDoc.write("</body>");
	objDoc.write("</html>");
	objDoc.close();

	if ($.browser.opera)
	{
		tab.focus();
		window.print();
		tab.close();
	}
	else
	{
		objFrame.focus();

		if ($.browser.msie)
			window.print();
		else
			objFrame.print();

		setTimeout(function()
		{
			jFrame.remove();
		},
		(15 * 1000));
	}
};

$(function()
{
	$('.printable .main-content-wrapper').prepend('<button id="print-page">Print this page</button>');
	var printBtn = $('#print-page');
	printBtn.click(function()
	{
		$('#logo img').attr('src',function()
		{
			return this.src.replace('logo-jaeger', 'logo-jaeger-print');
		});

		$('h2,h3').each(function()
		{
			if ($(this).css('background-image') != 'none')
			{
				var replaceText = $(this).text(),
					replaceImg = $(this).css('background-image').replace(/url\(['"](.*)['"]\)/,"$1");

				$(this)
					.css('text-indent', '0').css('background-image', 'none')
					.html('<img alt="' + replaceText + '" src="' + replaceImg + '"/>');
			}
		});

		$('body').print();

		$('#logo img').attr('src', function()
		{
			return this.src.replace('logo-jaeger-print', 'logo-jaeger');
		});
		$('h2,h3').has('img').each(function()
		{
			var headerImg = $(this).children('img').attr('src'),
				headerTxt = $(this).children('img').attr('alt');

			$(this)
				.css('background-image', 'url("'+headerImg+'")')
				.css('text-indent', '-999em')
				.text(headerTxt)
				.children('img').empty().remove();
		});
	});
});

/**
 Force links to open in new windows (for quarantined pages)
 **/
$(function()
{
	$('.checkout-process #footer a, .checkout-process .grand-total a').click(function(e)
	{
		e.preventDefault();

		if (confirm('This link will open a new window'))
			window.open($(this).attr('href'), 'jaeger');
		else
			return false;
	});
});

/**
 Activate jqModal for the size guide
 **/
$(function()
{
	if ($('a.guide').length > 0)
	{
		$('body').append('<div class="lightbox size-guide"></div>');

		if($('#mens_size_guide').length) {
			//Mens size guide
			page_to_load = 'index.cfm?page=2331';
		}else{
			//Womens size guide
			page_to_load = 'index.cfm?page=1037';
		}

		$('.lightbox').load(page_to_load + ' #content', function() {
			$(this).jqm({
				overlay:40,
				overlayClass:'jqm-overlay',
				closeClass:'sg-close',
				trigger:'.guide',
				modal:true
			});

			$('.tabs-container', this).tabsActivate();

			$('.accordion', this).accordion({
				header:'h4',
				autoHeight:false,
				collapsible:true,
				active:false
			});

			$('#content', this).append('<button class="sg-close">Close</button>');

			if ($.browser.msie) {
				$('.guide').click(function() {
					$('select,input').css('visibility','hidden');
					$('.lightbox select,.lightbox input').css('visibility','visible');
				});
				$('.sg-close').click(function() {
					$('select,input').css('visibility','visible');
				});
			}
		});
	}
});

/**
 checkboxes.js
 - on details pages, if 'select all' is (un)ticked, all other checkboxes are (un)ticked. If a checkbox is unticked while 'select all' is ticked, 'select all' becomes unticked.
 **/
$.fn.boxesTicked = function()
{
	var checkboxes = $(this).closest('form').find('li input[type=checkbox]').not('#all');
	var tallyChecked = 0;

	checkboxes.each(function()
	{
		if ($(this).is(':checked'))
			tallyChecked++;
	});

	if (checkboxes.length == tallyChecked)
		$('#all').attr('checked', 'checked');
	else
		$('#all').attr('checked', '');
};

$(function()
{
	// add the 'select all' field
	var detailsFieldset = $('.looks-details-page #add-selected-to-basket').children('fieldset:first-child');
	detailsFieldset.append('<label for="select-all"></label>');
	detailsFieldset.children(':last-child').text(' Select / Deselect all items in this look');
	detailsFieldset.children(':last-child').prepend('<input type="checkbox"/>');
	detailsFieldset.children(':last-child').children(':first-child').attr('id', 'select-all');

	// tick or untick checkboxes when 'select all' is ticked
	$('#select-all, #all').change(function()
	{
		if ($(this).is(':checked'))
			$(this).closest('form').find('li input[type=checkbox]').each(function() {
				$(this).attr('checked', 'checked');
			});
		else
			$(this).closest('form').find('li input[type=checkbox]').each(function() {
				$(this).attr('checked', '');
			});
	});

	// tick 'all' if all checkboxes are ticked and untick 'all' if any checkbox is unticked
	$('#all').boxesTicked();

	// tick 'select all' if all checkboxes are ticked and untick 'select all' if any checkbox is unticked
	$('.looks-details-page li input[type=checkbox]').change(function()
	{
		var checkboxes = $(this).closest('form').find('li input[type=checkbox]');
		var tallyChecked = 0;

		checkboxes.each(function()
		{
			if ($(this).is(':checked'))
				tallyChecked++;
		});

		if (checkboxes.length == tallyChecked)
			$('#select-all').attr('checked', 'checked');
		else
			$('#select-all').attr('checked', '');
	});
});

/**
 Suits-specific functionality
 **/
$.totalPrice = function()
{
	var runningTotal=0;
	$('.suits li input[type=checkbox]').each(function() {
		if ($(this).is(':checked'))
			runningTotal += parseInt($(this).closest('li').find('.price span').text(), 10);
	});
	return runningTotal;
};

$(function()
{
	if ($('body').hasClass('suits') || $("body").hasClass("suit")) {
		var currencySymbol = $('.currency-symbol').text();
		$("div.main-prod-details ul").append('<div class="total"><dl><dt>Total price</dt><dd>'+currencySymbol+'<span></span></dd></dl></div>');

		// pre-tick all the checkboxes
		$('#select-all').attr('checked', 'checked').trigger('change');

		// adjust total price based on number of ticked checkboxes
		$('.suits div.total dd span').text($.totalPrice);
		$('.suits input[type=checkbox]').change(function() {
			$('div.total dd span').text($.totalPrice);
		});
	}
});

// suits/looks dropdown change - resubmit the suits/looks details page on change of colour or size in order to update price
$(function()
{
	if ($('body').hasClass('suits')) {
		var dsel = $('.details select');
		var reDirectURL = document.location.href.replace(/(colour|size)_[^=]+=[^&]*(&|$)/g, '').replace(/&&/, '&').replace(/&$/, '');
		if (!reDirectURL.match(/\?/)){
			reDirectURL += '?';
		}
		dsel.change(
			function () {
				if (this.value) {
					var newLocation = reDirectURL;
					dsel.each(function(){
						newLocation += '&' + this.name + '=' + this.value;
					});
					window.location=newLocation;
				}
			}
		);
	}
});

/**
 Looks Details/Suit separates pages
 **/
$(function()
{
	if ($('body').hasClass('looks-details-page'))
	{
		// create an associative array of all the categories and the IDs of their corresponding listings page
		// TODO: Create a CMS editable element to handle this and print inline.
		var arrPageID = {
			'looks-womens':					'1311',
			'looks-womens-jaeger':			'1139',
			'looks-womens-jaeger-black':	'1141',
			'looks-womens-jaeger-london':	'1136',
			'looks-womens-jaeger-by-jaeger':'1125',
			'looks-mens':					'1210',
			'looks-mens-jaeger':			'1240',
			'looks-mens-jaeger-london':		'1271',
			'looks-mens-jaeger-by-jaeger':	'1255',
			'suits-womens':					'1146',
			'suits-womens-jaeger':			'1099',
			'suits-womens-jaeger-black':	'1480',
			'suits-womens-jaeger-london':	'1132',
			'suits-womens-sale':			'1550',
			'suits-mens':					'1172',
			'suits-mens-business':			'1173',
			'suits-mens-relaxed':			'1174',
			'suits-mens-occasion':			'1175',
			'suits-mens-jaeger':			'1228',
			'suits-mens-jaeger-london':		'1259',
			'suits-mens-jaeger-by-jaeger':	'1243',
			'suits-mens-sale':				'1216',
			'suits-outlet-women':			'1438',
			'suits-outlet-men':				'1429'
		};

		var pageID = $('.scroll-wrapper').attr('id');

		$('.scrollable').load('index.cfm?page='+arrPageID[pageID]+' .products', function()
		{
			$('.products')
				.addClass('items')
				.removeClass('products');

			$('.items img').each(function()
			{
				var imgSrc = $(this).attr('src');
				imgSrc = imgSrc.replace(/([A-Za-z0-9_\.\/\:\-]*(\-suit\-|\-look\-|\-cutout\-))[A-Za-z0-9_\-]*(\.jpg)/,"$1altview$3");
				
				if (imgSrc.indexOf("altview") > -1)
					$(this).attr('src', imgSrc);
				else
					$(this)
						.closest('li')
						.remove();
			});

			$('.scrollable')
				.addClass('scrollable-active')
				.before('<a class="prev-scrollable">Previous</a><a class="next-scrollable">Next</a>')
				.scrollable({
					itemsToDisplay:4,
					items:'ul.items > li',
					next:'.next-scrollable',
					prev:'.prev-scrollable'
				});
		});
	}
});

/**
 Experience page scrollables
 - This creates a scrollable element below full size list or transforms .singleton
 **/
$(function()
{
	if ($('.experience-content-wrapper').length > 0)
	{
		// Check for a singleton class - a lone scroller with standard links
		var $_target = $('.experience-content-wrapper').first(),
		    singleton = !! $('body').hasClass('slideshow-singleton');

		// Hashbang, not zero indexed to avoid confusion
		function getHash()
		{
			return parseInt(location.hash.replace('#eq', '')) - 1 || 0;
		}

		// Change content to match hash
		function changeContent()
		{
			$_target
				.find('ul.items > li')
				.eq(getHash())
				.addClass('displayed')
				.siblings()
				.removeClass('displayed');
		}

		// Add hash change event listener (Mega nav may have anchors)
		$(window).bind('hashchange', function ()
		{
			changeContent();
		});
		
		// Create small scrollable
		var $_wrap = $('<div class="scroll-wrapper clearfix"><div class="scrollable"><ul class="items"></ul></div></div>').appendTo($_target.parent());

		// Append 'indexes' to small scrollable and remove
		$_target
			.find('.experience-index').each(function(i, v)
			{
				$_wrap
					.find('.items')
					.append('<li class="eq' + (i + 1) + '">' + $(this).html() + '</li>');

				$(this)
					.appendTo($_wrap)
					.remove();
			});

		// Scrollable options
		var opts = {
			itemsToDisplay:1,
			items:'.items li',
			next:'.next-scrollable',
			prev:'.prev-scrollable'
		};

		// If creating a new one, add extra functionality
		if (!singleton)
		{
			$_target.addClass('experience-active');
			changeContent();

			opts['initialIndex'] = getHash();

			$('.scrollable')
				.find('ul.items a')
				.click(function(e)
				{
					location.hash = $(this).parent().attr('class');

					changeContent();

					e.preventDefault();
				});
		}
		else
			$_target.remove();

		// Instantiate scrollable
		$('.scrollable')
			.before('<a class="prev-scrollable">Previous</a><a class="next-scrollable">Next</a>')
			.addClass('scrollable-active')
			.scrollable(opts);
	}
});

/**
 Video launch
 - This is crap. Just a test.
 **/
var videoLaunch = function()
{
	this.display = false;

	var self = this;

	$('<a href="#">View video</a>')
		.appendTo('.zoom-toggle')
		.click(function(e)
		{
			if (!self.display)
			{
				self.display = true;

				$('.cloud-zoom')
					.add('.mousetrap')
					.css('display', 'none')
					.after('<div id="video"></div>');

				$('#video').flash({
					swf: '/media/flash/640x360_FLVplayer.swf',
					width:480,
					height:610,
					flashvars: {
						flvpath: 'http://video.jaeger.co.uk/Jaeger_SS11_640x360_170211.flv'
					}
				});
				
				$('#video').css('display', 'block');

				$(this).text('View photos');
			}
			else
			{
				self.display = false;

				$('.cloud-zoom')
					.add('.mousetrap')
					.css('display', 'block');

				$('#video').remove();
				
				$(this).text('View video');
			}

			e.preventDefault();
		});
		
};

/**
 Details page
 - Change the main product image (and zoomed image) when an image in the scrollable is selected
 **/
$(function()
{
	if ($('body').hasClass('details-page'))
	{
		$('.scrollable')
			.addClass('scrollable-active')
			.before('<a class="prev-scrollable">Previous</a><a class="next-scrollable">Next</a>')
			.scrollable(
			{
				itemsToDisplay:4,
				items:'ul.items li',
				next:'.next-scrollable',
				prev:'.prev-scrollable'
			});

		// If link in carousel is an alternative view, switch it
		// TODO: clean this up
		$('.items a').live('click', function(e)
		{
			if ($(this).attr('href').match('images/'))
			{
				// New large image
				var mainImgSrc = $(this).attr('href'),
				    mainImgAlt = $('img', this).attr('alt'),
				    zoomedImgSrc = mainImgSrc.replace('-main', '-zoom');

				// Perform swap
				$(this).attr('href', $('#main-prod-img').attr('src'));
				$('img', this).attr('src', $('#main-prod-img').attr('src').replace('-main', '-altview')).attr('alt', $('#main-prod-img').attr('alt'));

				$('.cloud-zoom').attr('href', zoomedImgSrc);
				$('#main-prod-img').attr('src', mainImgSrc).attr('alt', mainImgAlt);

				// Reset cloud zoom
				$('.cloud-zoom').siblings().each(function()
				{
					if ($(this).hasClass('mousetrap'))
						$(this).empty().remove();
				});
				$('a.cloud-zoom').CloudZoom();

				e.preventDefault();
			}
		});
	}
});

/**
 Carousel on homepage
 **/
$(function()
{
	if ($('body').hasClass('homepage'))
	{
		var $_target = $('.homepage-images'),
		    framesInterval = 10000;

		if ($('.homepage-images li').length > 1)
		{
			// Instantiate scrollable
			$_target
				.before('<ol class="uber-links"><li class="prev"><a href="#"><img width="26" height="49" src="images/arrows/arrow-uber-left.gif" alt="Previous" /></a></li><li class="next"><a href="#"><img width="26" height="49" src="images/arrows/arrow-uber-right.gif" alt="Next" /></a></li></ol>')
				.scrollable(
				{
					circular:true,
					disabledClass:'',
					items:'.homepage-images li',
					next:'.next a',
					prev:'.prev a',
					speed:500
				});

			// Set an autoscroll
			var play = setInterval(function()
			{
				$('.next a').trigger('click');
			}, framesInterval);

			// Stop autoscroll on when mouse clicks
			$('.prev a, .next a').mousedown(function()
			{
				clearInterval(play);
			});
		}
	}
});

/**
 Boutique large scrollable
 - Overrides scrollable disabling next/prev buttons
 **/
$(function()
{
	if ($('body').hasClass('boutique'))
	{
		// replace link (which is for non-JS versions of page) with text instructions for scroller
		$('.boutique-intro p').text('To navigate simply use the arrows at the edge of the page to slide between looks.');

		if ($('.scrollable').length > 0)
		{
			var $_target = $('.scrollable'),
			    framesIndex = 0,
			    framesCount = $('.items', $_target).find('li').length - 2; // Zero index and do not count last frame

			// Instantiate price point boxes
			$.togglePricepoint();

			// Instantiate scrollable
			$_target
				.before('<ol class="uber-links"><li class="prev"><a href="#" class="disabled"><img width="26" height="49" src="images/arrows/arrow-uber-left.gif" alt="Previous" /></a></li><li class="next"><a href="#"><img width="26" height="49" src="images/arrows/arrow-uber-right.gif" alt="Next" /></a></li></ol>')
				.addClass('scrollable-active')
				.scrollable(
				{
					disabledClass: '',
					initialIndex:1,
					items:'.scrollable li',
					next:'.next a',
					prev:'.prev a',
					offset:193
				});

			// In/activate scroll buttons
			$('.prev a').click(function()
			{
				framesIndex--;

				if (framesIndex == 0)
					$(this).addClass('disabled');

				if (framesIndex < framesCount)
					$('.next a').removeClass('disabled');
			});
			$('.next a').click(function()
			{
				framesIndex++;

				if (framesIndex > 0)
					$('.prev a').removeClass('disabled');

				if (framesIndex == framesCount)
					$(this).addClass('disabled');
			});
		}
	}
});

/**
 Price point toggles
 **/
$.togglePricepoint = function()
{
	$('.pricepoint').each(function()
	{
		// Add the button to each div
		$(this).prepend('<a href="#" class="toggle"><img src="images/buttons/btn-plus.gif" width="11" height="11" alt="Expand" /></a>');

		// Set the side the box expands/collapses from
		if ($(this).hasClass('left'))
		{
			$(this).css({				
				right: ($(this).parent().width() - $(this).position().left - $(this).find('.toggle').width()) + 'px',
				left: 'auto'
			});
		}

		// Toggle on click
		$('.toggle', this)
			.click(function(e)
			{
				e.preventDefault();

				if ($(this).parent().is(':animated')) return;

				$(this).parent().css('width', 'auto');

				$(this).next('a').toggle(200, function()
				{
					$(this).parent().css('width', '160px'); /* For Chrome < 14 */
				});
			})
			.next('a')
			.css('display', 'none');
	});
};

/**
 Colour change
 - Rebuild the URL on the product detail page when the colour drop down is changed
 **/
$(function()
{
	$('.colour').change(function() {
		if ($(this).val() !== '') {
			var colourId = $(this).val(), // ID of selected colour
			    pageUrl = window.location.search, // string of URL tokens
			    pageUrlTokens = pageUrl.split('&'), // array of the different tokens in the URL
			    productId, token;

			// determine the pageid from the URL tokens
			for (token in pageUrlTokens) {
				if (pageUrlTokens.hasOwnProperty(token) && pageUrlTokens[token].indexOf('productid') != -1) {
					productId = pageUrlTokens[token].substr(pageUrlTokens[token].indexOf('=')+1);
					break;
				}
			}

			// specify the pagevarid, whether or not it is defined in the URL tokens
			if (pageUrl.indexOf('productvarid')!=-1) {
				for (token in pageUrlTokens) {
					if (pageUrlTokens.hasOwnProperty(token) && pageUrlTokens[token].indexOf('productvarid') != -1) {
						var tokenBits = pageUrlTokens[token].split('-');
						tokenBits[1] = colourId;
						pageUrlTokens[token] = tokenBits.join('-');
						break;
					}
				}
			}
			else
				pageUrlTokens.push("productvarid="+productId+'-'+colourId+"-ITM");

			// rebuild URL with new tokens
			pageUrl = pageUrlTokens.join('&');
			window.location = 'index.cfm'+pageUrl;
		}
	});
});

/**
 Clear the search term when the user clicks in the search box
 **/
$(function()
{
	var searchTerm = $("#search-keywords"),
	    searchTermVal = searchTerm.val();

	searchTerm.focus(function()
	{
		if (searchTerm.attr("value") == searchTermVal)
			$(this).attr("value", "");
	});
	searchTerm.blur(function()
	{
		if (searchTerm.attr("value") == "")
			$(this).attr("value", searchTermVal);
	});
});

