/*
 * ToDo:
 * 
 * move thumbs over to always show current image
 * get all headlines right
 * post content/line
 * 
 * NoScript content
 * No title param.
 * sort out all the attribute arguments.
 * share buttons
 * 	fb, twitter, etc
 *  urls
 *  ecard
 */
jQuery(document).ready(function( $ ) {

		
	var isAnimating = true;
	var Images = new Array();
	var ImagePtr = 0;
	var oldImagePtr = ImagePtr;
	
	var FrontBuffer, BackBuffer;
	
	var theImage = new Image();
	theImage.onload = onLoadFunction;
	
	
	var root = $('#kagc_carousel');
	
		var hidetitle = root.attr( 'hidetitle' ); 
		
		
		//if ( hidetitle )
			$('.entry-title').hide(); //ToDo: busted.
	
	
		var paneWidth = parseInt( root.attr( 'w' ) );
		var paneHeight = parseInt( root.attr( 'h' ) );
		var thumbsHeight = parseInt( root.attr( 'thumbsheight' ) );
		var titleHeight = 12;			// ToDo: Add this & title colour as incoming attr
		var copyrightText = '(c) Kim Aldis, all rights reserved';
	
		buildArrayList();
	
		var prev_image = addDiv( root, "kagc_image_prev" );
		var panes = addDiv( root, "kagc_panes" );	
		
			panes.width( paneWidth );
			//panes.width( paneWidth - (prev_image.outerWidth( true )*2) );
			panes.height( paneHeight );
			
			// overall width needs some forcing here, why?
			root.width( panes.outerWidth( true ) + prev_image.outerWidth( true )*2 );
			$('#kagc_content').width( root.width() - $('#kagc_content').css('padding-left').replace( 'px', '' )*2 );
			
			FrontBuffer = addCanvas( panes, "kagc_buffer", "buffer1", panes.width(), paneHeight );
			BackBuffer = addCanvas( panes, "kagc_buffer", "buffer2", panes.width(), paneHeight );
			
			UpdateImage( );
		var next_image = addDiv( root, "kagc_image_next" );
		addDivClass( root, "kagc_clearfloat" );							// clear the float left, else nothing fits any more.
			
		var panel = addDiv( root, "kagc_panel" );	
	
			var ctrls = addDiv( panel, "kagc_ctrls" );	
				var play = addDiv( ctrls, "kagc_play" );
				play.css( "margin-left", (root.outerWidth(true) - play.width())/2 );		// centre it
				
			//var info = addDiv( panel, "kagc_info" );	
			
			var thumbsBack = addDiv( panel, "kagc_thumbsprev")
			var thumbsClipper = addDiv( panel, "kagc_thumbsmain" );		// the thumbs holder and mask
				var thumbs = addDiv( thumbsClipper, "kagc_thumbs" );	// Very wide: contains the thumbs mask
			var thumbsForward = addDiv( panel, "kagc_thumbsnext");
			addDivClass( panel, "kagc_clearfloat" );					// clear the float left, else nothing fits any more.
		
	
	// set a mask to clip thumbs outside the view
	thumbsClipper.width( panel.width() - (thumbsBack.outerWidth(true) + thumbsForward.outerWidth(true) )-2 );
	
	var i=0;
	var thumbsWidth = 0;
	$('.kagc_image').each( function() {
		
		var thumbURL = $(this).attr( 'thumb');
		var x = parseInt( $(this).attr( 'thumbwidth' ) );
		var y = parseInt( $(this).attr( 'thumbheight') );
		var a = newSize( x, y, thumbsHeight );
		var caption = $(this).attr( 'caption' );
		var headline = $(this).attr( 'headline' );
		
		var id = $(this).attr( 'iid' );
		
		console.log( $(this).attr( 'iid' ) );
		thumbs.append( '<div class="kagc_thumb_frame"></div>')
		var frame = thumbs.find( '.kagc_thumb_frame').last();
		
		// force the frame to be square
		// ToDo: assumes a border attached to the image
		// we should calculate this instead
		frame.width( thumbsHeight+2 );
		frame.height( thumbsHeight+2 );
		
		frame.append( "<img id='kagc_thumb'>" );
		//frame.append( "<img id='kagc_thumb' src='" + thumbURL + "' width='" + a[0] + "' height='" + a[1] + "' i='" + i + "'>" );
		var thumb = frame.find( '#kagc_thumb').last();
		thumb.attr( "src", thumbURL );
		thumb.attr( "width", a[0] );
		thumb.attr( "height", a[1] );
		thumb.attr( "i", i );
		thumb.attr( "caption", caption );
		thumb.attr( "headline", headline );
		thumb.attr( "title", caption + "( " + id + " )" );
		
		thumb.click( function() {
			Bump( parseInt( $(this).attr( 'i' ) ) );
			UpdateImage();
			Stop();
		});		
		
		i++;
		thumbs.width( frame.outerWidth(true) *i );
	} );
	
	// put autoplay on a timer.
	window.setInterval( function() {
		if ( isAnimating ) {
			Bump( ImagePtr+1 );
			UpdateImage();
		}
	 }, 8000 );
	Hide( thumbsBack );
	 if ( root.attr( 'first' ) ) {
		var first = parseInt( root.attr( 'first' ) );					// start with this image id
		//isAnimating = false;
		ImagePtr = first;
		console.log( first );
		UpdateImage();
		Stop();
		//console.log( "Found first: " + first );
	} else {
		//first = 0;
		Play();
	}
	
	
	// ************************************************************************************* //
	// left hand nav button
	prev_image.click( function() {
		
		if ( ImagePtr == 0 )		// at start of list (remember, pointer is always one ahead )
			return;
			
		ImagePtr --;
		
		UpdateImage();
		Stop();
	});
	next_image.click( function() {
		
		if ( ImagePtr == Images.length-1 )		// at the end of images (remember, pointer is always one ahead)
			return;
			
		Bump( ImagePtr +1 );
		UpdateImage();
		Stop();
		
	});
	thumbsForward.click( function() { // right hand arrow
		
		Stop();
		
		var left = thumbs.offset().left - thumbs.parent().offset().left;
		
		var newLeft = left -  thumbsClipper.width();
		
		var newRight = newLeft + thumbs.outerWidth();
		if ( newRight < thumbsClipper.width() )
			newLeft = thumbsClipper.width() - thumbs.width();
			
		positionThumbs( newLeft );
		
	} );
	thumbsBack.click( function() {			// left hand arrow
		
		Stop();
		
		var left = thumbs.offset().left - thumbs.parent().offset().left;
		
		newLeft = left +  thumbsClipper.width();
		if ( newLeft > 0 )
			newLeft = 0;
		
		positionThumbs( newLeft );
		
	} );
	play.click( function() {
		if ( isAnimating )
			Stop();
		else
			Play();
	} );
	// *************************************************************************************** //
	function Stop() {
		isAnimating = false;
		
		// just replace 'play' with 'pause' so we don't need to calculate the full
		// path to the background image
		play.css( "background-image", play.css( "background-image" ).replace( 'pause', 'play' ) ); 
	}
	function Play() {

		isAnimating = true;
		play.css( "background-image", play.css( "background-image" ).replace( 'play', 'pause' ) ); 
	}
	function positionThumbs( at ) {
		
		if ( at == 0 ) {
			Hide( thumbsBack );
		} else {
			Show( thumbsBack );
		}
		if ( at + thumbs.width() <= thumbsClipper.width() ) {
			Hide( thumbsForward );
		} else {
			Show( thumbsForward );
		}
		
		thumbs.animate( {left: at }, 1000 );
	}
	function UpdateImage() {
		
		// ImagePtr is bumped by the onLoad function
		theImage.src=Images[ImagePtr]["url"];

	}
	function addDiv( root, name ) { 
		root.append( '<div id="' + name + '"></div>' );	
		return ( $('#' + name) );
	}
	function addDivClass( root, name ) { 
		root.append( '<div class="' + name + '"></div>' );	
		return ( $('.' + name) );
	}
	function addCanvas( root, className, idName, w, h ) {
		root.append( '<canvas class="' + className + '" id="' + idName + '" width="' + w + '" height="' + h + '"></canvas>' );	
		return ( $('#' + idName) );
	}
	function newSize( xOrg, yOrg, size ) {
		
		var x;
		var y;
		var ratio = xOrg/yOrg;
		
		if ( xOrg > yOrg ) {
			x = size;
			y = size / ratio;
			return Array( x,y,ratio );
		}
		y = size;
		x = size * ratio;
		return Array( x,y,ratio );
		
	}
	function onLoadFunction() {
		
		var thisThumb = $( ".kagc_thumb_frame:nth-child(" + (ImagePtr+1) + ")" );
		var lastThumb = $( ".kagc_thumb_frame:nth-child(" + (oldImagePtr+1) + ")" );
		
		// animate shadow. ToDo: This jumps, and the shadow animateion plugin doesn't work at all.
		thisThumb.animate( {boxShadow: '2px 2px 2px 0px #bbb'}, 1000 );
		if ( ImagePtr != oldImagePtr )
			lastThumb.animate( {boxShadow: '2px 2px 2px 0px #fff'}, 1000 );
			
		if ( ImagePtr == 0 ) {
			Hide( prev_image );
		} else {
			Show( prev_image );
		}
		if ( ImagePtr == Images.length-1 ) {
			Hide( next_image );
		} else {
			Show( next_image );
		}
		
		var BackCtx = BackBuffer[0].getContext("2d" );
		var FrontCtx = FrontBuffer[0].getContext("2d" );
		
		BackCtx.clearRect(0, 0, BackBuffer.width(), BackBuffer.height());
		
		//console.log( "Loading ---  : " + ImagePtr + ' ( old=' + oldImagePtr + ')' );
		//var x = Images[ImagePtr]['width'];
		//var y = Images[ImagePtr]['height'];
		
		
		
		// squeeze it down to make room for Headline text. If we need to.
		var Width = Images[ImagePtr]['width'];
		var Height = Images[ImagePtr]['height'];
		
		var gap = titleHeight + 4;
		if ( paneHeight - Height < gap ) {	
			var r = Height / Width;
			Height -= gap;
			Width = Height / r;
			
		}
		var x = Width;
		var y = Height;
		// centre the image
		if ( y > x ) { // portrait
			x = (paneWidth - x)/2;
			//y = 0;
		} else {		// landscape
			x=0;
			//y = (paneHeight-y)/3;
		}
		y = 0;
		
		// draw the image
		BackCtx.drawImage( theImage,x,y, Width, Height );
		
		// add a border
		BackCtx.beginPath();
		BackCtx.strokeStyle = "#000";
		BackCtx.lineWidth = 0.5;
		BackCtx.rect( x+1,y+1, Width-1, Height-1 );		
		BackCtx.stroke();
		
		
		BackCtx.textAlign = 'left';
		BackCtx.font = titleHeight + 'px sans-serif';
		BackCtx.fillStyle = '#888';
		BackCtx.fillText( thisThumb.children('#kagc_thumb').first().attr( 'headline' ), x, y + Height + titleHeight );
		
		BackCtx.textAlign = 'right';
		BackCtx.font = '9px sans-serif';
		BackCtx.fillStyle = '#888';
		BackCtx.fillText( copyrightText, x + Width, y + Height + titleHeight );

		
		FrontBuffer.fadeOut( 2000 );
		BackBuffer.fadeIn( 2000, function() {
			
			var tmp = BackBuffer; BackBuffer = FrontBuffer; FrontBuffer=tmp;
				
		} );
		
		//var thumb = thisThumb.children('#kagc_thumb').first();
		//info.html(
				//"<h4>" + thumb.attr( "headline" ) + "&nbsp;</h4>"
				 ////+ thumb.attr( "caption" )
				 //);
			    
	}
	/*
	 *  Change ImagePtr, updating oldImagePtr
	 *  @newImagePtr	{int}		new value for ImagePtr
	 *  @return			{}			none
	 */
	function Bump( newImagePtr ) {
		oldImagePtr = ImagePtr;
		ImagePtr = newImagePtr;
		if ( ImagePtr >= Images.length )		// Wrap around
			ImagePtr = 0;
	}
	function Show( e ) {
		e.animate( {opacity: 0.3}, 1000 );		// ToDo: restore to as in css here
		e.css( {cursor: 'pointer'} );
	}
	function Hide( e ) {
		e.animate( {opacity: 0.0}, 1000 );	
		e.css( {cursor: 'auto'} );
	}
	function buildArrayList() {
		$('.kagc_image').each( function() {
			var a = new Array();
			
			a["url"] = $(this).attr( 'url' );
			// adjust size of images to fit our carousel panes
			var x = parseInt( $(this).attr('width'  ));
			var y = parseInt( $(this).attr('height' ) );
			var ratio = x/y;
			
			// scale to fit pane
			//if ( x > y ) {			// x>y, scale to fit width
				x = paneWidth;			// scale to fit width
				y = x / ratio;
			//} else {				// else scale to fit height
				if ( y > paneHeight ) {
					y = paneHeight;
					x = y * ratio;
				}
			//}
			
			a["width"] = x;
			a["height"] = y;
			
			Images.push( a );
			
		});
	}

} );


