var boundary = 3;
var zIndex = 1000;
var appleMobileDevice = null;
var itemUrls = [];

$(document).ready(function() {

	//are we an apple mobile device?
	if ((navigator.userAgent.match(/iPod/i)) || 
	(navigator.userAgent.match(/iPhone/i)) || 
	(navigator.userAgent.match(/iPad/i))) {
		appleMobileDevice = true;
	}
	
	//is the browser IE6 or below?
	var lteIE6 = ''
	if ($.browser.msie) {
		var version = (parseInt($.browser.version));
		if(version <= 6) {
			lteIE6 = true;
		}
	}
	
	//Don't run coverflow in IE6 or less. 
	//For all other browsers, hide images until loaded and then start coverflow.
	if(!lteIE6) {
		beforeLoaded();

		preload(function () {
		    startCoverFlow();
		});
	}
	
	function beforeLoaded() {
		$('#cfContainer').find('img').hide();
	}
	
	//handle clicks and touch events
	$('#titleBar a.next').click(function() {
		rotate('right', 1);
		return false;
	});
	
	$('#titleBar a.back').click(function() {
		rotate('left', 1);
		return false;
	});
	
	if(appleMobileDevice) {
		$('#cfContainer img').live('touchstart', clickHandler);
		$('#cfContainer img').live('click', clickHandler);
	} else { 
		$('#cfContainer img').bind('click', clickHandler);
	}
		
	function clickHandler(event) {
		var currentPosition = $(this).parents('div').data().currentPosition;
		var sequence = $(this).parents('div').data().sequence;
		var rotations = Math.abs(currentPosition);
		if (currentPosition < 0) {
			rotate('left', rotations);
			event.preventDefault();
		} else if (currentPosition > 0) {
			rotate('right', rotations);
			event.preventDefault();
		} else {
			if(appleMobileDevice){
				location.href = itemUrls[sequence];
			}else{
				return
			}
		}
	}

}); //End document ready

function preload(callback) {
    var images = $('#cfContainer').find('img');
    var loadedImages = 0;
    var totalImages = images.length;

    images.each(function () {
        // Attempt to load the images
        $(this).load(function () {
            // Add to number of images loaded and see if they are all done yet
            loadedImages++;
            if (loadedImages == totalImages) {
                // All set, perform callback
                callback();
            }
        });
        // Trigger load if images are cached in the browser.
        if (this.complete) {
            $(this).trigger('load');
        }
    });
}

function startCoverFlow() {
	var cfContainer = $('#cfContainer');
	var containerWidth = cfContainer.width();
	var covers = cfContainer.children('div');
	var numberOfCovers = cfContainer.children('div').length;
	var centerNumber = Math.round(numberOfCovers/2) - 1;
	var centerItem = covers[centerNumber];
	
	//If we're an apple mobile device, get all the urls and remove all the links. 
	//We have to do this because the touch events aren't firing as expected.
	if(appleMobileDevice) {
		$('#cfContainer div a').each(function() {
			var url = $(this).attr('href');
			itemUrls.push(url);
			$(this).children('img').unwrap();
    	});
	}
		
    //put everything in the center to start with and set up initial data		
	$('#cfContainer div').each(function(i) {
		var left = containerWidth/2 - $(this).width()/2;
		var img = $(this).find('img');
		var imgSource = img.attr('src');
		var newTop = 0;
		var cssPosition = {
			'position' : 'absolute',
			'left' : left
		}

		$(this)
		.css(cssPosition)
		.data({
			title:				null,
			currentPosition:	0,
			width:				$(this).width(),
			originalWidth:		$(this).width(),
			height:				$(this).height(),
			originalHeight:		$(this).height(),
			top:				0,
			left:				left,
			sequence:			i,
			reflection:			null
		});

		this.reflection = new Reflection(img, imgSource, 84, .35);		

		//show items and animate out from the center
		
		img.show();
		
		var title = $(this).find('img').attr('alt');
		var currentPostion = $(this).data('currentPosition');
		var sequence = $(this).data('sequence');
		var originalWidth = $(this).data('originalWidth');
		var newWidth = $(this).data('width');
		var newHeight = $(this).data('height');
		var newLeft = $(this).data('left');
		
		
		//distance to center
		currentPosition = sequence - centerNumber;

		if(currentPosition == 0) {
			$('#cfTitle').html(title);
		}

		if(Math.abs(currentPosition) <= boundary){
			if(currentPosition < 0 || currentPosition > 0) {
				newWidth = $(this).width() * (1-Math.abs(currentPosition)*.22);
				newHeight = $(this).height() * (1-Math.abs(currentPosition)*.22);
			}
		}
		
		if(currentPosition < 0 || currentPosition > 0){
			newTop = cfContainer.height()/2 - newHeight/2 - 5;
			zIndex = numberOfCovers - Math.abs(currentPosition);
		}
		
		if(currentPosition < 0){
			newLeft = Math.round(containerWidth/2 - 314 - ((Math.abs(currentPosition)-3)*newWidth/8));
		} else if(currentPosition > 0) {
			newLeft = Math.round(containerWidth - newWidth + 1 + ((Math.abs(currentPosition)-3)*newWidth/8));
		}
		
		if (Math.abs(currentPosition) > boundary) {
			newWidth = $(this).width() * .15;
			newHeight = $(this).height() * .15;
			newLeft = containerWidth/2;
			newTop = cfContainer.height()/2;
		}
		
		//don't animate if we're on an Apple Mobile Device
		if (appleMobileDevice) {
			var containerStyle = {
				'left' : newLeft,
				'top' : newTop,
				'width' : newWidth,
				'height' : newHeight,
				'z-index' : zIndex
			}
			
			var imageStyle = {
				'width' : newWidth
			}
			
			var canvasStyle = {
				'display' : 'block',
				'position' : 'absolute',
				'width' : newWidth,
				'height' : newWidth / 2.5
			}
			
			$(this).css(containerStyle);
			$(this).find('img').css(imageStyle);
			$(this).find('canvas').css(canvasStyle);
		} else {
			$(this).animate({ 
				left: newLeft,
				top: newTop,
				width: newWidth,
				height: newHeight
			}, 400 )
			.css('z-index' , zIndex);
	
			$(this).find('img').animate({
				width: newWidth
			}, 400 );
	
			//need to animate canvas separately because webkit won't constrain proportions
			$(this).find('canvas').animate({
				width: newWidth,
				height: newWidth / 2.5
			}, 400 );
		}
		
		//update data
		$(this).data('title', title);
		$(this).data('width', newWidth);
		$(this).data('height', newHeight);
		$(this).data('top', newTop);
		$(this).data('left', newLeft);
		$(this).data('currentPosition', currentPosition);

	});

}//end start coverflow

function rotate(direction, rotations) {
	var cfContainer = $('#cfContainer');
	var containerWidth = cfContainer.width();
	var numberOfCovers = cfContainer.children('div').length;
	var centerNumber = Math.round(numberOfCovers/2) - 1;
	var covers = cfContainer.children('div');
	var centerItem = covers[centerNumber];
	var lastItemLeft = $(covers[0]);
	var lastItemRight = $(covers[numberOfCovers-1]);
	var newTop = 0;
	
	for (rotations; rotations > 0; rotations--) { 
		
		var increment = 1;
		
		//if we're headed right and we're at the right most item, stop.
		if (direction == 'right' && $(lastItemRight).data('currentPosition') == 0) {
			return false;
		}
		// if we're headed left and we're at the left most item, stop.
		else if (direction != 'right' && $(lastItemLeft).data('currentPosition') == 0) {
			return false;
		}
		// otherwise, if we're headed right change the increment to -1
		else if(direction == 'right') {
			increment = -1;
		}
		
		$('#cfContainer div').each(function() {
			var currentPosition = $(this).data('currentPosition') + increment;
			var originalWidth = $(this).data('originalWidth');
			var originalHeight = $(this).data('originalHeight');
			var newWidth = originalWidth;
			var newHeight = originalHeight;
			var newLeft = $(this).data('left');
			var containerWidth = cfContainer.width();
			var title = $(this).data('title');

			//set width and height
			if(Math.abs(currentPosition) <= boundary){
				if(currentPosition < 0 || currentPosition > 0) {
					newWidth = originalWidth * (1-Math.abs(currentPosition)*.22);
					newHeight = originalHeight * (1-Math.abs(currentPosition)*.22);
				}
			} else if (Math.abs(currentPosition) > boundary) {
				newWidth = originalWidth * .25;
				newHeight = originalHeight * .25;
			}

			
			// we don't want to animate every single image, but we do need 
			// to animate a couple past the boundary so the z-indexing 
			// works out correctly.
			if (Math.abs(currentPosition) <= boundary+2) {

				//set left position
				if (Math.abs(currentPosition) <= boundary){
					if (currentPosition < 0){
						newLeft = Math.round(containerWidth/2 - 314 - ((Math.abs(currentPosition)-3)*(newWidth)/8));
					} else if (currentPosition > 0) {
						newLeft = Math.round(containerWidth - newWidth + 1 + ((Math.abs(currentPosition)-3)*(newWidth)/8));
					} else if (currentPosition == 0) {
						newLeft = containerWidth/2 - originalWidth/2;
						$('#cfTitle').html(title);
					}
				}
				
				//set top position
				if(currentPosition < 0 || currentPosition > 0){
					newTop = cfContainer.height()/2 - newHeight/2 - 5;
				} else {
					newTop = 0;
				}
				
				//don't animate on an apple mobile device
				if (appleMobileDevice) {
					//set z-index
					if (currentPosition == 0) {
						zIndex = 1000;//fix this	
					} else if (Math.abs(currentPosition) > boundary) {
						zIndex = 0;
					} else if (Math.abs(currentPosition) <= boundary) {
						zIndex = numberOfCovers - Math.abs(currentPosition);
					}
					
					var containerStyle = {
						'left' : newLeft,
						'top' : newTop,
						'width' : newWidth,
						'height' : newHeight,
						'z-index' : zIndex
					}
					
					var imageStyle = {
						'width' : newWidth
					}
					
					var canvasStyle = {
						'display' : 'block',
						'position' : 'absolute',
						'width' : newWidth,
						'height' : newWidth / 2.5
					}
					
					$(this).css(containerStyle);
					$(this).find('img').css(imageStyle);
					$(this).find('canvas').css(canvasStyle);
				} else {
					$(this).animate({ 
						left: newLeft,
						top: newTop,
						width: newWidth,
						height: newHeight
					}, 200, function(zIndex){
						//set z-index;
						if (currentPosition == 0) {
							zIndex = 1000;	
						} else if (Math.abs(currentPosition) > boundary) {
							zIndex = 0;
						} else if (Math.abs(currentPosition) <= boundary) {
							zIndex = numberOfCovers - Math.abs(currentPosition);
						}
						$(this).css('z-index', zIndex);
					});
		
					$(this).find('img').animate({
						width: newWidth
					}, 200 );
		
					$(this).find('canvas').animate({
						width: newWidth,
						height: newWidth / 2.5
					}, 200 );
				}
			} else {
				$(this).css('z-index', 0);
			}	
			
			//update data
			$(this).data('width', newWidth);
			$(this).data('height', newHeight);
			$(this).data('top', newTop);
			$(this).data('left', newLeft);
			$(this).data('currentPosition', currentPosition);
			
		});
	}
}

//start reflection
function Reflection(img, imgSource, reflHeight, opacity) {
	var	reflection, cntx, imageWidth = img.width(), imageHeight = img.height(), gradient, parent;
	parent = img.parent();
	if (!$.browser.msie) {
		img = new Image();
		img.src = imgSource;
		this.element = reflection = parent.append("<canvas class='reflection' style='position:absolute'/>").find(':last')[0];
		if (!reflection.getContext)
		{	
			return;
		}
		cntx = reflection.getContext("2d");
		try {
			$(reflection).attr({width: imageWidth, height: reflHeight});
			cntx.save();
			cntx.translate(0, imageHeight-1);
			cntx.scale(1, -1);
			cntx.drawImage(img, 0, 0, imageWidth, imageHeight);
			cntx.restore();
			cntx.globalCompositeOperation = "destination-out";
			gradient = cntx.createLinearGradient(0, 0, 0, reflHeight);
			gradient.addColorStop(0, "rgba(255, 255, 255, " + (1 - opacity) + ")");
			gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
			cntx.fillStyle = gradient;
			cntx.fillRect(0, 0, imageWidth, reflHeight);
		} catch(e) {
			return;
		}
	}
}	//END Reflection

