$(document).ready(function() {

	// Primary nav
	$('#primary-nav li').hover(function() {
		var ul = $(this).find('> ul');
		if(ul.size()>0) {
			$(this).find('> a').addClass('hover');
			ul.css('display', 'block');
		}
	}, function() {
		var ul = $(this).find('> ul');
		if(ul.size()>0) {
			$(this).find('> a').removeClass('hover');
			ul.css('display', 'none');
		}
	});
	$('#primary-nav a[rel=nofollow]').click(function() {
		return false;
	});

	// Form errors
	if(self.location.search.match(/formerror=1/)) {
		$('<div id="form-errors"></div>').html('<p>Please complete all required fields</p>').insertAfter($('#primary-nav'));
	}

	// Display all sale prices
	$('input[rel=sale-price]').each(function(i, el) {
		var e = $(el);
		if(e.val()>0 && e.val()!='') {
			var span = e.parent('li').find('span');
			span.addClass('sale-price').html("<em>"+span.html()+'</em> <strong>$'+e.val()+'</strong>');
			e.parent('li').find('img.sale').show();
		}
	});
	var salePinProduct = $('#product-options img');
	$('#product-price span.sale').each(function(i, el) {
		var e = $(el);
		if(e.html()=='$0' || e.html()=='$') {
			e.hide();
			salePinProduct.hide();
		}
		else {
			e.show();
			e.prev('.reg').addClass('on-sale');
			salePinProduct.show();
		}
	});

	// Show colour swatches
	// Brackets are replaced with hyphens, so make sure this replacement is
	// present in the swatch filenames.
	var colopt = $('#product-options select[name=COLOR (please select one)]');
	if(colopt.size()>0) {
		var swatches = $('<ol id="swatches"></ol>');
		colopt.find('option').each(function(i, el) {
			var col = $(el).val();
			var scol = col.replace(/[\(\)]/ig, '-');
			var node = $('<li><div><img src="/swatches/'+scol+'.jpg" width="25" height="29" /></div><span></span></li>');
			node.find('span').html(col);
			node.appendTo(swatches);
		});
		swatches.appendTo($('#product-detail-wrap .col0'));
	}

	// Alter js action on the "keep shopping" button in the checkout area.
	// If out of stock, go back 1 page, otherwise go to homepage
	$('div.ys_pageActions li.ys_first input.ys_primary').attr('onclick', '').click(function(ev) {
		if($('ul#ys_warningMessages').size()>0) {
			window.history.go(-1);
		}
		else {
			self.location = 'http://www.cool-jams.com/';
		}
		return false;
	});

	// Hide all missing images
	$('img').each(function(i, el) {
		el = $(el);
		if(el.attr('src')=='') el.remove();
	});
});
