// Images Loaded
// mit license. paul irish. 2010.
$.fn.imagesLoaded=function(c){var b=this.filter("img"),a=b.length;b.bind("load",function(){if(--a<=0){c.call(b,this)}}).each(function(){if(this.complete||this.complete===undefined){var d=this.src;this.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";this.src=d}});return this};

$(document).ready(function() {
	
	// Carousel
	
	// Only init the carousel if there are more than four items
	if ($('.chl2_w_specials .carousel li').length > 4) {
		$('.chl2_w_specials .carousel ul').jcarousel({
			wrap : 'circular',
			scroll : 4,
			itemFallbackDimension : $('.chl2_w_specials .carousel li').width(),
			initCallback : function($c) {
				$c.list.find('li').show();
			}
		});
	}
	else {
		$('.chl2_w_specials .carousel li').show();
	}
	
	// Product listing
	
	var $listByThree = $('.gridList.threeWide');
	
	// Ensure boxes have equal height
	
	if ($listByThree.length > 0) {
	
		var tallest = 0;
		
		$listByThree.each(function(k, v)
		{		        
	        $container = $(this).find('.inner');
	        
	        if (tallest < $container.height())
	        {
	            tallest = $container.height();
	        }
	        
	        $listByThree.find('.inner').css({'min-height' : tallest});
		});
	}
	
	// Vertically center images
	
	var $pImgs = $('.categoryItem img, .carousel img'),
		maxHeight = 100;
	
	// Hide images while we do some maths...
	$pImgs.css({'visibility' : 'hidden'});
	
	$pImgs.each(function(k, v)
	{
		$(this, this).imagesLoaded(function()
		{	
			var height = $(this).height();
			
			if (height < maxHeight)
			{
				var offset = Math.round((maxHeight - height) / 2) + 'px';
			
				$(this).css({'margin-top' : offset});
			}
			
	        if (k == ($pImgs.length - 1))
	        {
	        	// Reveal images
	            $pImgs.css({'visibility' : 'visible'});
	        }
		});
	});
});
