// This file controls all the timeline stuff
// Any pages which load the main grid need this file
// It's pretty bloody complicated, so it's well commented...





// Declare var for globally accessible function (this is used by the navigation script in custom.js)
var clearGrid;

// Set global animation speed
var $animSpeed = 350;




jQuery(document).ready(function($) 
{

	// Get the first year from the posts
	firstYear = $.cookie('firstYear');
	
	// Get the last year from the posts
	lastYear = $.cookie('lastYear');
	
	// Checks what page we're on to decide whether to load or show the grid (needed for front page grid)
	currentPage = $.cookie('currentPage');
	

	
	// Check to see if the user has used the timeline already
	if(!$.cookie('currentYear')) 
	{
	
		//If not, we'll start at the beginning
		currentYear = firstYear;	
		
		// Hide the previous btn so users can't go forward in time
		$('#ctn_prev').hide();	
		
	} else {
	
		// If so, grab the cookie
		currentYear = jQuery.cookie('currentYear');

		
	};
	
	
	
	
	// Locate navigation arrows correctly
	initNavArrows()

	// This controls the navigation items and makes sure they're in the correct position
	checkYear();
	
	// Load up the content
	if(currentPage == 'Home') {
	

		showGrid();
		
		
	} else {
	
		loadGrid();
		
	};
	
		
	// Attach fading info of grid items
	gridInfo();
	
	
	
	 
	// Fade in grid info
	function gridInfo() 
	{
		
		$('.ctn_grid_item').hover(function() 
		{
		
			// Fade in text
			$(this).children().children('.ctn_grid_content').fadeIn($animSpeed); 
			
			// Fade in play button
			$(this).children('.ctn_play_btn').fadeIn($animSpeed); 
			
			// Fade out black & white bg image to reveal colour one
			
			$(this).children('.ctn_grid_image').children('.black_and_white').fadeTo($animSpeed, 0);
			
			
			//$('.black_and_white').pixastic("desaturate");
			
		},
		
		function() 
		{
		
			// Fade out content
			$(this).children().children('.ctn_grid_content').fadeOut($animSpeed); 
			
			// Fade out play btn
			$(this).children('.ctn_play_btn').fadeOut($animSpeed);
			
			// Fade b&w image back in 
			$(this).children('.ctn_grid_image').children('.black_and_white').fadeTo($animSpeed, 1);
			
		});
		
		$('.ctn_grid_image').click(function()
		{
			window.location = $(this).siblings('.click_through').attr('href');
		})
	};
	
	
	function initNavArrows() 
	{
	
		// Get window height and divide by 2 to find center
		var center_y = $(window).height()/2+100;
		
		// Align arrows to center of screen
		$("#next_prev_btns div, #next_prev_btns_single div").css('top', center_y);
	
	
	}
	
	
	
	// fixed position left/right btns
	function showNavBar() 
	{
	
		// Get window height
		var win_y = $(window).height();
	   
	   	// Get scroll position
       	var scroll_y = $(window).scrollTop();
	   
	   	// Smoothly animate arrows
     	$("#next_prev_btns div, #next_prev_btns_single div").animate({ top: (((win_y / 2) + scroll_y + 100)) + "px" }, $animSpeed );	
		
		
     };
	 
	 
	 // Timer off
     var showTimer = false;
	 
	 
     function maybeShowNavBar(evt) 
	 {
	 
       if ( showTimer ) 
	   {
	   
         clearTimeout( showTimer );
		 
       };
	   
	   // Check scroll position every 0.175 seconds
       showTimer = setTimeout( showNavBar, 175 );
	   
     };
	 
     $(window).scroll( maybeShowNavBar );
	 


	 
	 
	 
	 // ******* Start Year pagination scripts **** //
	
	
	// Next btn function
	 $('#ctn_next').click(function() 
	 {
		
		retardYear();
		
	});
	
	
	
	// Previous btn function
	$('#ctn_prev').click(function() 
	{
	
		advanceYear();	
	
	});
	
	
	
	// Keyboard left/right functions
	$(document).keydown(function(e)
	{

		if(currentPage == 'Everything') {
		
		// If right key is pressed and we're not at the end
   		if ((e.keyCode == 39) && (currentYear > lastYear)) { 

       		retardYear();
       		
       		// Add active class to give user feedback on press
       		$('#ctn_next').addClass('active');
       
       
       	// If left key is pressed and we're not at the start
    	} else if ((e.keyCode == 37) && (currentYear < firstYear)) {
    
    		advanceYear();
    		
    		// Add active class to give user feedback on press
    		$('#ctn_prev').addClass('active');
    
    	}
		
		};
		
	});
	
	
	// Remove active class when the key is up
	$(document).keyup(function(e)
	{
	
		$('#ctn_prev').removeClass('active');
		
		$('#ctn_next').removeClass('active');
	
	});
	
	
	// Retard the year
	function retardYear() {
	
		// Retard the year
		currentYear--;
		
		// Amend the year title
		$('#year h2').html(currentYear);
		
		// Retard timeline
		$('.all').children('li').children('a').removeClass('selected');
		
		$('.all').children('li').children('a#' + currentYear).addClass('selected');

		// Pretty obvious what this does...
		clearGrid();
	
	}
	
	
	// Advance the year function
	function advanceYear() {
	
	
		// Advance year
		currentYear++;
			
		// Amend title
		$('#year h2').html(currentYear);
			
		// Advance timeline selection
		$('.all').children('li').children('a').removeClass('selected');
		
		$('.all').children('li').children('a#' + currentYear).addClass('selected');
			
		clearGrid();	
	
	}
	
	
	
	
	function checkYear() 
	{
	
		//alert('First Year: ' + firstYear + ', Current Year: ' + currentYear + ', Last Year: ' + lastYear )
	
		
		// If at start then turn on next btn, turn off pervious
		 if(currentYear == firstYear) 
		 {
		 
			$('#ctn_prev').fadeOut( $animSpeed );
			
			$('#ctn_next').fadeIn( $animSpeed );
					
		};
		
		// If at a middle year turn both btns on
		if((currentYear > lastYear) && (currentYear != firstYear)) 
		{
			
			$('#ctn_prev').fadeIn( $animSpeed );
			
			$('#ctn_next').fadeIn( $animSpeed );

			//nextBtn = 'on';
		};
		
		// If at end year turn off next btn
		if(currentYear == lastYear) 
		{
			
			$('#ctn_prev').fadeIn( $animSpeed );
			
			$('#ctn_next').fadeOut( $animSpeed );
			
			
		};
		
	
		
	};
	
	
	// clearGrid - Globally available function
	clearGrid = function($clicked) 
	{
	
		// Check next/prev arrows are correct
		checkYear();
			
		if($clicked) 
		{
			// Set new title
			$('#year h2').html(currentYear);
		}
		
			
			
		// Recursively fade out grid
		// Set var so that loop doesn't call loadGrid() multiple times
		var loading = false;
		
		// Item to fade
		var $divs = $('.ctn_grid_item'), 
			
			// Set var to nothing
			div = 0; 
			
			( function()
			{ 
			
				// Do the fade on the specific div
			   	$divs.eq(div++).stop(true, true).fadeTo( $animSpeed , 0, function() 
			   	{
			   		
			   		// Only call loadGrid() if we're on the first time through
					if(!loading) 
					{
					
						loadGrid();
						loading = true;
							
					};
					
				}); 
				
				// Call itself, timeout var sets the delay between each element beginning the fade
			   	setTimeout(arguments.callee, 50);
			   
			})(); 
			
			
	};
	
	
	
	function loadGrid() 
	{
		
		// Show loading icon
		$('#loader').fadeIn( 'fast' );
		
		// Get the offset to use with the grid script
		offset = firstYear - currentYear;
	
		// Reset the counter variable
		var i = 0;
	
		
		// Preload images
		/*$('.ctn_grid_image').load('../grid/?firstYear='+firstYear+'&offset='+offset+' .ctn_grid_image img', function() 
		{ 
		
			// Get total number of items
			var n = $('.ctn_grid_image').length;
			
			// Incremeant by increament
			i++;
			
			// If all the images are loaded, then load everything else
			if(i == n) 
			{
				*/	
			
				// load up everything else
				$('#grid').load('../grid/?offset='+offset, function() 
				{ 
				
					imgLoad($("img.black_and_white")[0], function(img){
					// Remove loader
					$('#loader').fadeOut( 'fast' );
	     
					
					// Bring in grid
					showGrid();
					
					// Attatch item info
					gridInfo();
					});
					
					
				
					
					
				});
				
			//}
		//});

		
		
	};
	
	
	
	function showGrid() 
	{
	
	
			
				
			// Desaturate
			//$('.black_and_white').pixastic("desaturate");
					
			
			// Recursively fade in grid
			var $divs = $('.ctn_grid_item'), 
			
			div = 0; 
			
						
			
			
			( function()
			{ 
			
				// make sure the images are loaded before we desaturate and fade them in
				// This only needs to happen on the front page as this is the only page which doesn't ajax load
				if(currentPage == 'Home') {
				
					imgLoad($("img.black_and_white")[0], function(img){
						
						// Desaturate
							
      	
     					 
						$divs.eq(div++).stop(true, true).fadeTo( $animSpeed , 1);
						
						
					});
				
				} else {
					//$('.des').desaturate();
					$divs.eq(div++).stop(true, true).fadeTo( $animSpeed , 1); 
					
				}
				
				setTimeout(arguments.callee, 100);
				
			   
			})();
			
			
			
			//Start animation
			if(!$.browser.msie) {
			fd.ca.init();
			
			document.observe('lightview:opened', function(event) {
  				fd.ca.pause();
			});

			document.observe('lightview:hidden', function(event) {
  				fd.ca.pause();
			});		
			}	
			
	};
	
	
	function imgLoad(img, completeCallback, errorCallback){
		
		if(img!=null && completeCallback!=null){
				
			var loadWatch = setInterval(function()
				
			{
				
				if(img.complete){
				
					clearInterval(loadWatch);
					completeCallback(img);
				}
			} , 100);
		
		}else{
			
			if(typeof errorCallback=="function") errorCallback();
				
		}
	
	}

				
	
	// ******* End Year pagination scripts **** //
	

 
    function grayscaleImageIE(imgObj)
    {
        imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
    }
 
    function grayscaleImage(imgObj)
    {
        var canvas = document.createElement('canvas');
        var canvasContext = canvas.getContext('2d');
        
        var imgW = imgObj.width;
        var imgH = imgObj.height;
        canvas.width = imgW;
        canvas.height = imgH;
        
        canvasContext.drawImage(imgObj, 0, 0);
        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
        
        for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg; 
                imgPixels.data[i + 1] = avg; 
                imgPixels.data[i + 2] = avg;
            }
        }
        
        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        return canvas.toDataURL();
    } 

	
});



