/*
 * Christopher Keefer 2011
 * This script is responsible for all the front page specific javascript behaviours, including the logoCanvas.
 * @see controllers: home
 */
// The $(document).ready() function allows us to set code for execution as soon as DOM registration occurs
$(document).ready(function(){
drawLogo();
});

// Declare global variables
var totalStages; // Number of different elements we want to draw on top of one another in the fade in
var stage = 0; // current stage of drawing we're on
var ANIM_TIMING = 66; // 66 milliseconds/frame ~= 15 fps
var intID; // ID of the interval timer
var images = new Array(); // An Array of the images we want to draw
var lsOffset = 0; // Determines which child of #logoSwap we want to grab

function drawLogo(){
	// Try and get the canvas element, then see if we can draw to it
	var canvas = $("#logoCanvas").get(0);
	
	 if (!canvas || !canvas.getContext) {
		 console.log("Error Loading Canvas. Canvas probably not supported.");  
		 return;
		  }
	// Grab the canvas context
	var g = canvas.getContext("2d");
	// We've got six images to draw, one after the other, so totalStages = 5, since we start counting at 0.
	totalStages = 5;
	// Now declare the step - the increment which controls how fast we want each image to fade in - and
	// the x and y offsets for each image
	var step = new Array(0.10,0.10,0.25,0.25,0.25,0.05);
	var cm = ($("#logoCanvas").width()/2)-250;
	var x = new Array(cm,cm,cm,cm,cm,cm);
	var y = new Array(0,0,0,0,0,0);
	// Load the images we want to draw, and when they're loaded, start the first interval timer
	//var imageSources = new Array(hostLoc+"image/SULogoCenter.png", hostLoc+"image/SULogoWords.png");
	var imageSources = new Array(hostLoc+"image/SaneLogo/Step1-Glasses.png",
			hostLoc+"image/SaneLogo/Step2-Eyebrows.png",hostLoc+"image/SaneLogo/Step3-SmallSmile.png",
			hostLoc+"image/SaneLogo/Step4-MidSmile.png",hostLoc+"image/SaneLogo/Step5-FullSmile.png",
			hostLoc+"image/SaneLogo/Step6-Text.png");
	loadImages(imageSources, images, function(){
		g.globalAlpha = 0.0;
		var gfunk = function(){fadeInFront(g,images[0],null,x,y,step, logoSwap);};
		intID = setInterval(gfunk,ANIM_TIMING);
	});
}

/**
 * Fades in one or more images onto the specified graphics context.
 * @param g Graphics context of the canvas element we want to draw to.
 * @param image The Image we want to draw onto the canvas this time 'round.
 * @param imageData Passed from the doneFadeInYet function, null otherwise - a capture of the contents of
 * the canvas before we started drawing our (next) image into it, so that multiple images can be faded in
 * sequentially.
 * @param x X-axis coordinate for drawing our image to.
 * @param y Y-axis coordinate for drawing out image to.
 * @param step How much we want to increment the alpha by on each loop through
 * @return
 */
function fadeInFront(g, image, imageData, x, y, step, callbackFunction){
	// If the global alpha has reached a certain threshold, the fade in is done and we can skip to 
	// seeing if there are any more images we want to fade in
	if (g.globalAlpha >= 1.0){
		//console.info("Finished fade in for stage "+stage+"."); // Yay. NOTEME:This halts execution in IE9.
		clearInterval(intID); // Clear the interval timer
		doneFadeInYet(g,x,y,step,callbackFunction); // Check to see if we've finished all the drawing stages
	}else{
		g.clearRect(0,0,g.canvas.width,g.canvas.height); // Clear the canvas
		if (stage == 0){ // If we're currently drawing the very first image, then just keep on keeping on
			// If globalAlpha still has room between full opacity for our next increment, simply increment it;
			// otherwise, set globalAlpha to full opacity (this helps correct for javascript floating point
			// precision uncertainities)
			if (g.globalAlpha <= (1-step[stage])){
				g.globalAlpha += step[stage];
			}else{
				g.globalAlpha = 1.0;
			}
			g.drawImage(image,x[stage],y[stage]);
			//console.log(g.globalAlpha);
		}else{ // Otherwise, we need to first draw the imageData we were sent - thats the data grabbed from the
			// context the last time we finished the fade in, and now becomes the 'background' for our next image.
			var currentAlpha = g.globalAlpha;
			g.globalAlpha = 1.0; // preserve the current alpha and set the alpha to 1 for drawing the 'background'
			//g.putImageData(imageData,0,0); // put the old image data down
			for (var i=0;i<stage;i++){
				g.drawImage(images[i],x[i],y[i]);
			}
			g.globalAlpha = currentAlpha; // restore the alpha
			// As above
			if (g.globalAlpha <= (1-step[stage])){
				g.globalAlpha += step[stage];
			}else{
				g.globalAlpha = 1.0;
			}
			g.drawImage(image,x[stage],y[stage]); // draw out image
		}
	}
}

/**
 * This is a helper function for the fadeInFront that allows us to fade in multiple images one at a time,
 * overlaying whatever we've already finished fading in. Its a layer paradigm, without the complexity (or indeed,
 * the benefits) of actual layers.
 * @param g Graphics context of the canvas element
 * @param x X-axis position we want to draw our next image to
 * @param y Y-Axis position we want to draw our next image to
 * @param step How much we should increment the alpha by each time we loop through
 */
function doneFadeInYet(g, x, y, step, callbackFunction){
	// Check if we've iterated through as many stages as we've set - if so, we're done. If not, keep going.
	if (stage < totalStages){
		stage++;
		// Get whatever is currently on the canvas - we're going to use this as our 'background' for the next stage
		//var imageData = g.getImageData(0,0,g.canvas.width,g.canvas.height); 
		var imageData = null;
		// Set the globalAlpha back down to 0 so we can start fading in again
		g.globalAlpha = 0.0;
		// Setup a new anonymous function for the 
		var gfunk = function(){fadeInFront(g,images[stage],imageData,x,y,step,callbackFunction);};
		var ifunk = function(){intID = setInterval(gfunk,ANIM_TIMING);};
		var to = setTimeout(ifunk,500);
	}else{
		// We're done fading in our images - if the callbackFunction is set, call it
		if (callbackFunction != null){
			var to = setTimeout(callbackFunction,500);
		}
	}
}

/**
 * This function takes elements from a known div in the front page and displays them on a timer, with the 
 * ability for the user to go back or forward through these sections or click on them to go to the
 * advertised content. It is called once the fade in canvas effect is complete.
 */
function logoSwap(){
	
	var doSwap = function(){
		$('#logoContainer').children().fadeOut(500,function(){
			
			$('#logoContainer').empty().append(
					$($('#logoSwap').children().get(lsOffset)).clone(true)
				).children().hide().fadeIn(500);
			
			if (lsOffset < $('#logoSwap').children().length - 1){
				lsOffset++;
			}else{
				lsOffset = 0;
			}
			
		});
		
	};
	intID = setInterval(doSwap,5000);
	
	/*
	// Attach behaviours to the arrows under the logoSwap images
	$('#lccFirst').click(function(event){
			event.preventDefault();
			lsOffset = 0;
			doSwap();
		});
	
	$('#lccPrev').click(function(event){
			event.preventDefault();
			lsOffset -= 2;
			if (lsOffset < 0){
				lsOffset = $('#logoSwap').children().length - 1;
			}
			doSwap();
		});
	
	$('#lccNext').click(function(event){
			event.preventDefault();
			doSwap();
		});
	
	$('#lccLast').click(function(event){
			event.preventDefault();
			lsOffset = $('#logoSwap').children().length - 1;
			doSwap();
		});
		*/
	
	// Attach behaviour to the logoContainer - on hover, show the logo controls and prevent the
	// swap from advancing
	$('#logoContainer').hover(
	function(){
		
		//clearInterval(intID);
	}, 
	function(){
		//doSwap();
		//intID = setInterval(doSwap,5000);
	}).click(function(event){
		//intID = setInterval(doSwap,5000);
	});
}
