$(function(){
	$('#coloroptions li').click(function(){
		swapColorOption(this.title);
	});
	$('#productoptions select.colors').change(function(){
		swapColorOption(this.options[this.selectedIndex].value);
	});
	$("a.zoom").jqzoom({
		zoomWidth: 300,
		zoomHeight: 300,
		position: "left"
	});
});

function swapColorOption(color){
	var img = $('#productpreview');
	var a = img.parent('a.zoom');
	var src = img.attr('src');
	var href = a.attr('href');
	img.attr('src', src.substr(0, src.lastIndexOf('/')) + "/" + color.toLowerCase()+ '.jpg');
	a.attr('href', href.substr(0, href.lastIndexOf('/')) + "/" + color.toLowerCase()+ '_full.jpg');
	var sel = $('#productoptions select.colors');
	if(sel[0]){
		var reg = new RegExp('^'+color+'.*');
		for(var i=0; i< sel[0].options.length; i++)	if(sel[0].options[i].value.match(reg)) sel[0].options[i].selected = true;
	}
	$('#productdescription span.color').html(color);
}


$(function(){
	var delay = 3500; /* Delay between animations */
	var fade = 1000; /* Duration of fade in animation */
	var curLayer = 'random'; /* start from layer number */
	var zIndex = 3; /* z-index value. layers will use this value +/- 1 either side */
	/**
	 * Get childNode elements to be cycled though. Initialize with lowest zindex and 0 opacity.
	 */
	var layers = $('#slideshow a').children().each(function(){
		$(this).css({zIndex: zIndex, opacity:0});
	});
	if(layers.length){
		// start random position
		if(curLayer == 'random') curLayer = Math.floor(Math.random()* layers.length);
		/**
		 * Bring Layer to front and Fade in Animation with callback to cycleLayers.
		 */
		var fadeInLayer = function(i){
			$(layers[i]).css({zIndex:zIndex+1}).animate({'opacity':1}, fade, cycleLayers);
		}
		/**
		 * Calculate next image, current image and previous image and layer zindex and opacity accordingly
		 */
		var cycleLayers = function(){
			var l = layers.length, c = curLayer;
			$(layers[c<=0?l-1:c-1]).css({opacity:0, zIndex:zIndex-1});
			$(layers[c=curLayer=c>=l?0:c]).css({opacity:1,zIndex:zIndex});
			setTimeout(function(){ fadeInLayer(c+1==l?0:c+1); ++curLayer;}, delay);
		}
		/**
		 * Start the cycle layer process.
		 */
		cycleLayers();
	}
	
});

