// Global Variables
var images;
var ratio = 641 / 997;
var imagesContainer;
var imageWidth;
var imageHeight;
var movementDistance = 500; // in pixels
var movementTime = 15000; // in milliseconds

$(window).load(function(){
	/**
	 * Set up home page slider
	 */
	imagesContainer = $("#home-images-slider");
	
	imagesContainer.cycle({
		fx: "scrollRight",
		cleartypeNoBg: true,
		speed: 800,
		timeout: 7000
	});
	
	$(window).resize(resize);
	
	// Load external stylesheet to support resizing the sliding images (cycle plugin)
	$("head").append('<link href="css/style2.css" rel="stylesheet">');
	
	setUpRibbon();
	moveLeft();
	setInterval("moveLeft()", movementTime);
//});
//$(document).ready(function () {	

	// Handle scaling by height
	$(window).resize(function() {
		if($(document.body).height() > $(window).height()) {
			/*curheight	windowheight
			curwidth	desiredwidth
			
			curheight*desiredwidth = curwidth*windowheight
			desiredwidth = curwidth*windowheight/curheight*/
			
			var container = $(".container");
			
			var newContainerWidth = container.width()*$(window).height()/container.height();
			//console.log('needs new width: ('+newContainerWidth+')');
			$(".container").width(newContainerWidth);
		}
    });
    $(window).trigger('resize');
});

//  Resize function. Primarily used for the sliding home images
function resize(){
	imagesContainer.height(imagesContainer.width() * ratio);
}

/**
 * Group of functions used to show the scrolling ribbon
 */
 
// Initiate the ribbon
function setUpRibbon(){
	imageWidth = $("#ribbon img:first").width();
	//console.log('imageWidth:'+imageWidth);
	imageHeight = $("#ribbon img:first").height();
	
	var objects = $("#ribbon img");
	for (var i = 0; i < objects.length; i++){
		$(objects[i]).css('left', i * imageWidth);
	}
	$("#ribbon").width(imageWidth * objects.length).height(imageHeight);
}

// The call to animate the ribbon
function moveLeft(){
	checkVisible();
	$("#ribbon img").animate({
		left: '-=' + movementDistance + 'px'
	},
	movementTime,
	'linear');
}

// Determines if the first ribbon image is off screen.
// If yes, then the first image is removed and placed at the end. 
// It's "left" CSS property is re-calculated to ensure proper placement.
function checkVisible(){
	var first = $("#ribbon img:first");
	var ribbonArea = $("#ribbon");
	if (first.offset().left + imageWidth < ribbonArea.offset().left){
		//console.log("swapping image to "+(first.next().position().left + imageWidth));
		first.css("left", first.next().position().left + imageWidth);
		first.remove().appendTo("#ribbon");
	}
}

