$(document).ready(function() {	
	$('#lower').tabs();
	
	$('a.group').fancybox({
		'hideOnContentClick': false
	});
	
	$('.image-link').each(function() {
		$(this).after($(this).html()).html('');
	});
	
	$('.swatch-inactive').addClass('swatch-hide').removeClass('swatch-inactive');
	
	$('.product-thumbnail').click(function() {
		$(this).children('img').setMainImage();
	});
	
	$('.swatch').click(function() {
		if($('#select-color option[value='+$(this).attr("buy_id")+']').length)
			$('#select-color').val($(this).attr("buy_id"));
		
		$(this).setActiveColor();
	});
	
	$('#select-color').click(function() {
		$('.swatch[buy_id="'+$(this).val()+'"]').setActiveColor();
	}).trigger('click');
	
	$('.temp-hide').removeClass('temp-hide');
	
	if(document.cookie != ''){
		$.each(document.cookie.split(';'), function(index, value){
			var parts = value.split('=');
			$.each(parts, function(index2, value2){
				if(jQuery.trim(value2) == 'swatchcookie'){
					if($('.swatch[buy_id="'+parts[1]+'"]').length > 0){
						$('#select-color').val(parts[1]);
						$('.swatch[buy_id="'+parts[1]+'"]').setActiveColor();
					}
				}
			});
		});
	}
});

// Sets the main image (and surrounding link) to the 
// image of the function's caller
jQuery.fn.setMainImage = function() {
	
	$('a[rel="group_skip"]').attr("rel", $('#main-product-image').attr("rel"));	
	
	var img_src = $(this).attr("src");
	$('#main-product-image').attr("href", img_src.replace('/60/', '/700/'))
		.attr("rel", $(this).prev().attr("rel"))
		.children('img').attr("src", img_src.replace('/60/', '/375/'));
	
	$(this).prev().attr("rel", "group_skip");
	
	return $(this);
}

jQuery.fn.setActiveColor = function() {
	if($('.swatch').length) {
		var color_id = $(this).attr("color_id");

		$('p#sku').html("<strong>SKU:</strong> "+$('img.swatch[color_id="'+color_id+'"]').attr("sku"));
		
		if($('.swatch-show').attr("color_id") != color_id) {
			$('.swatch-show').removeClass('swatch-show').addClass('swatch-hide');
			$('.product-thumbnail[color_id='+color_id+']').removeClass('swatch-hide').addClass('swatch-show');
			$('.swatch-show').children('img:first').setMainImage();
		}
	}
	
	return $(this);
}

function validateSignup(thisform) {
	var colors = document.email_signup['colors[]'];
	var colorchecked = false;
	
	if(colors.length == undefined) {
		colorchecked = colors.checked;
	}
	else {
		for(i = 0; i < colors.length; i++) {
			if(colors[i].checked) {
				colorchecked = true;
			}
		}
	}
	
	if(colorchecked) return true;
	else {
		alert("Please select a color to be notified when it comes in stock.");
		return false;
	}

	if(validateForm(thisform) == false)
	{
		return false;
	}
}