/**
 * @author Brian Sutliffe
 */
$(function(){
	var imagePaths = [
		'images/carousel/mask.png',
		'images/carousel/frame1.jpg',
		'images/carousel/frame2.jpg',
		'images/carousel/frame3.jpg',
		'images/carousel/frame4.jpg'
	];
	var fallbacks = [
		null,
		'images/carousel/frame1.png',
		'images/carousel/frame2.png',
		'images/carousel/frame3.png',
		'images/carousel/frame4.png'
	];
	var alts = [
		null,
		'Work… Shopping... Yoga... Dinner with the girls... Period? What period?',
		'At last... Prince Charming. There\'s nothing like the perfect fit.',
		'Your friends. Your car. Your dog. Reliability is everything.',
		'Playtex&reg; Gentle Glide&reg; 360&deg;&trade; Tampons 360&deg; Protection&trade; Designed to Fit Your Life'
	];
	var rawImages = [];
	var maskedImages = [];
	var curFrame = 0;
	var rotationDelay = 5000;
	var animationDuration = 1000;
	
	//preload the images
	if(!!document.createElement('canvas').getContext){
		//if the browser supports the canvas tag, preload the JPEG versions
		loadImages(imagePaths, function(images){
			rawImages = images;
			initializeCarousel(images);
		});
	} else {
		//otherwise, juse use pre-masked PNGs (which are huge)
		rawImages = fallbacks;
		initializeCarousel();
	}
	
	
	function initializeCarousel(){
		//get a masked version of each image (either composed by <canvas>, or as a precomposed PNG)
		for(var x = 1, y = rawImages.length; x < y; x++){
			var masked = gentleGlide.ImageMasker.applyCanvasMask(rawImages[x], rawImages[0], 1000, 355, fallbacks[x]);
			masked.setAttribute('alt', alts[x]);
			masked.className = 'carouselFrame';
			maskedImages.push(masked);
			$('#carouselFrameHolder').append(masked);
		}
		//start the rotation
		(function(){
			showFrame(curFrame + 1, curFrame === 0);
			if(curFrame < maskedImages.length)
				setTimeout(arguments.callee, rotationDelay);
		})();
	}
	
	function showFrame(frame, immediate){
		var prevFrame = maskedImages[curFrame - 1];
		//fade in the new frame
		$(maskedImages[frame - 1]).fadeIn(immediate ? 0 : animationDuration, function(){
			$(prevFrame).hide();
		});
		if(frame === 4)
			$('#carouselBox').fadeIn(immediate ? 0 : animationDuration);
		//update the current frame
		curFrame = frame;
	}
	
	function loadImages(paths, callback){
		var images = [];
		var numComplete = 0;
		for(var x = 0, y = paths.length; x < y; x++){
			var img = loadImage(paths[x], function(){
				numComplete++;
				if(numComplete >= paths.length)
					callback.call(null, images);
			});
			images.push(img);
		}
	}
	
	function loadImage(path, callback){
		var img = new Image();
		img.onload = function() {
			if(typeof callback === 'function')
				callback.apply(this);
		}
		img.src = path;
		return img;
	}
});

