 // Dependencies
 // 		jquery.js >= 1.2.6
 // 		utilities.js
 //			jquery UI tabs = 3
 //			jCarouselLite = 1.0.1
 //
(function($) {
	Parser = (function() {
		function mapArrayToFields(arr, fields) {
			return $.inject(fields, {}, function(parsed, field, i) {
				parsed[field] = arr[i];
				return parsed;
			});
		}
		return {
			GROUP_MAP: {
				'R': 'Regular',
				'B': 'Big/Tall'
			},
			// from value of selected option
			parseColor: function(str) {
				str = str || '';
				var arr = str.split('|');
				if (!arr.length || arr.length < 4 || arr[0] == 'X') { return {} };
				return mapArrayToFields(arr, $.w('name code minPrice maxPrice'));},
			// from text of selected option
			parseGroup: function(str) {
				return this.GROUP_MAP[str.indexOf('.') >= 2 ? 'B' : 'R'];},
			// from text of selected option
			parseAvailability: function(str) {
				return str.charCodeAt(str.length - 1) !== 160;},
			// from value of selected option
			parseSize: function(str) {
				str = str || '';
				var arr = str.split('|');
				if (!arr.length || arr.length < 3) { return {} };
				arr[1] = arr[1].split(',');
				arr = $.flatten(arr);
				return mapArrayToFields(arr, $.w('size colorCode price length'));
			}
		};
	})();
	// Constants
	var CAROUSEL_ITEMS_VISIBLE = 4,
		CAROUSEL_TEMPLATE = ['<div class="wl-crsl-btn wl-crsl-btn-next">Next</div>','<div class="wl-crsl-btn wl-crsl-btn-prev">Prev</div>','<div class="wl-crsl">','<ul class="wl-clearfix"></ul>','</div>'].join(''),
		ALTERNATES_TEMPLATE = ['<li>','<a href="{largeImage}" class="wl-alt-image">','<img src="{thumbnailImage}" alt="{name}" />','</a>','</li>'].join(''),
		OPTION_SELECTOR_MAP = {'color': '#attrValueColor','sizeGroup': 'input[name=sizeRadio]','size': '#attrValueSize','quantity': '#qty'};
	// Globals
	var $form = null,
		$imagesContainer = null,
		selectChangeEvent = $.browser.msie ? 'propertychange' : 'change';
function initValidation() {
		function validate() {
			var errors = [];
			$.each($.w('color size'), function() {
				var $select = $form.find(OPTION_SELECTOR_MAP[this]),
					currentText = $select.find('option:selected').text(),
					currentValue = Parser['parse' + $.capitalize(this)]($select.find('option:selected').val()),
					message = null;
				if (!Parser.parseAvailability(currentText)) {
					message = 'Sorry, your ' + $.capitalize(this) + ' is unavailable right now';
				} else if (!currentValue || $.isEmptyObject(currentValue)) {
					message = 'Please select ' + $select.find('option:first').text();
				}
				if (message) { errors.push($.trim(message)); }
			});
			var	quantity = parseInt($form.find(OPTION_SELECTOR_MAP.quantity).val(), 10);
			if (isNaN(quantity) || !quantity || quantity < 0) {
				errors.push('Please enter a valid quantity');
			}
			return $.uniq(errors);
		}
function showErrors(errors) {
			errors = $.map(errors, function(e) { return '<p>' + e + '</p>'; });
			$form
				.find('.wl-validation')
					.html(errors.join(''))
					.show()
					.end()
				.find('.wl-button-cart')
					.addClass('wl-button-disabled');
		}

function hideErrors() {
			$form.find('.wl-validation').hide();
		}
function triggerValidation() {
			var isValid = !validate().length;
			$form.find('.wl-button-cart')[isValid ? 'removeClass' : 'addClass']('wl-button-disabled');
			$form.find('.wl-wishlist')[isValid ? 'removeClass' : 'addClass']('wl-wishlist-disabled');
		}
		$form
			.find('input,label')
				.bind('blur change click focusout mouseout keydown keyup mousedown', triggerValidation)
				.end()
			.find('select')
			 	.bind(selectChangeEvent + ' click blur', triggerValidation)
				.end()
			.find('.wl-button-cart, .wl-wishlist, .wl-validation')
				.hover(
					function() { 
						var errors = validate();
						if (errors.length) { showErrors(errors); }
					},
					function() { hideErrors(); }
				)
				.end()
			.submit(function(e) {
				if (validate().length) {
					e.preventDefault();
					e.stopPropagation();
					return false;
				}
			});
	}
function initOptionDependency() {	
	}
function initAvailability() {
		$form.find(OPTION_SELECTOR_MAP.size).bind(selectChangeEvent, function() {
			var $selectedOption = $(this).find('option:selected'),
				isAvailable = Parser.parseAvailability($selectedOption.text());			
				$form.find('span.wl-availabilitybig').text(isAvailable ? 'In Stock' :'Out of Stock');
			$form.find('span.wl-availability1big').text(isAvailable ? 'In Stock (US Only)' :'Out of Stock');
		});
	}
function initSwatches() {
		$form.find('a.wl-swatch').click(function(e, colorChange) {
			colorChange = typeof colorChange === 'undefined' ? true : false;
			e.preventDefault();
			var $this = $(this),
				colorName = $this.find('img').attr('alt');
			$form.find('a.wl-swatch').removeClass('wl-current');
			$this.addClass('wl-current');
			$form
				.find(OPTION_SELECTOR_MAP.color)
					.find('option')
						.attr('selected', false)
						.filter(function(index) { return $.trim($(this).text()) === colorName; })
							.attr('selected', true)
							.end()
						.end()
					.trigger(selectChangeEvent)
					.end()
				.find(OPTION_SELECTOR_MAP.quantity)
					.trigger('keyup'); // for validation
			if (colorChange) { $form.find('.wl-color-name').text(colorName); }
		});
	}
function initAlternates() {
		function setPrimaryImage(image) {
			$imagesContainer.find('div.wl-img-primary img').attr('src', image);
		}
		$imagesContainer.find('div.wl-img-alt').click(function(e) {
			e.preventDefault();
			var $target = $(e.target);
			if (!$target.is('img')) { return; }
			e.preventDefault();
			setPrimaryImage($target.parent().attr('href'));
		});
		$form.find('a.wl-swatch').click(function(e) {
			e.preventDefault();
			var colorName = $(this).find('img').attr('alt'),
				newPrimaryImage = $imagesContainer
									.find('div.wl-img-alt ul a[title=' + colorName + ']:first')
											.attr('href');
			setPrimaryImage(newPrimaryImage);
		});
	}
function initTabs() {
		$('.wl-tabs').tabs();
	}
function initCarousel() {
		var $carousel = $('.wl-crsl');
		$carousel.parent().find('.wl-crsl-btn-prev').addClass('disabled');

		if ($carousel.find('li').length > CAROUSEL_ITEMS_VISIBLE) {
			$carousel.jCarouselLite({
				visible: CAROUSEL_ITEMS_VISIBLE,circular: false,btnNext: $carousel.parent().find('.wl-crsl-btn-next'),btnPrev: $carousel.parent().find('.wl-crsl-btn-prev')
			});
		} else {
			$carousel.parent().find('div.wl-crsl-btn').addClass('wl-crsl-btn-disabled');
		}}
function initSubmits() {
		$form.find('a.wl-wishlist').click(function(e) {
			e.preventDefault();
			$form.attr('action', 'InterestItemAdd').trigger('submit');
		});}
function initSizeChart() {
		$form.find('a.wl-sizechart').click(function(e) {
			e.preventDefault();
			var link = $(this).attr('href');
			if (link === '#') { return; }
			var xPosition = 0, yPosition = 0,width = 864,height = 720;
			if (parseInt(navigator.appVersion, 10) >= 4) {xPosition = (screen.width - width) / 2;yPosition = (screen.height - height) / 2;}
			var args = ['width=' + width,'height=' + height,'location=0','menubar=0','resizable=1','scrollbars=1','status=0','titlebar=0','toolbar=0','hotkeys=0','screenx=' + xPosition,'screeny=' + yPosition,'left=' + xPosition,'top=' + yPosition].join('');
			window.open(link, 'sizeChart', args);
		});}
$(function() {
		$form = $('form.wl-product-form');
		$imagesContainer = $('div.wl-images-container');
		initValidation();
		initOptionDependency();
		initAvailability();
		initSwatches();
		initAlternates();
		initTabs();
		initCarousel();
		initSubmits();
		initSizeChart();
		// Default to the first color
		$form.find('a.wl-swatch:first').trigger('click', [false]);
	});
})(jQuery);
