/**
* ACECQA - Home page scripts.
*/

$(document).ready(function() 
	{  
		// Build buttons for the slider.
		var cells = $('#latest-news-items .article');
		slider.numCells = cells.length;
		if (slider.numCells > 0) {
			slider.currentCell = 1;
			// Add the buttons.
			var buttons = $('<ul/>').attr('id', 'slider-buttons').insertAfter('#latest-news-inner h2');
			var buttonPrev = $('<li/>').addClass('stepper previous').appendTo(buttons);
			var buttonPrevLink = $('<a/>').html('<span>previous</span>').appendTo(buttonPrev);
			for (var i=1; i<=slider.numCells; i++) {
				var li = $('<li/>').addClass('number').appendTo(buttons);
				var a = $('<a/>').attr('href', '#null').html('<span>'+i+'</span>').appendTo(li).click(
					function()
					{
						stopSlider();
						slideToCell( $(this).find('span').text());
					}
				);
			}
			var buttonNext = $('<li/>').addClass('stepper next').appendTo(buttons);
			var buttonNextLink = $('<a/>').html('<span>next</span>').appendTo(buttonNext);
		}
		// Add handlers to the steppers.
		$('#slider-buttons li.stepper a').attr('href', '#null');
		buttonPrevLink.click(
			function()
			{
				stopSlider();
				slideToPrevious();
			}
		);
		buttonNextLink.click(
			function()
			{
				stopSlider();
				slideToNext();
			}
		);
		$('#slider-buttons li:eq(1)').addClass('active');
		// Show all the cells.
		cells.css({display:'block'});
		// Start the automated slider.
		startSlider();
	}
);

// Hold some slider properties here.
var slider = {interval:5000, duration:250, running:false, animating:false, currentCell:0, numCells:0, cellWidth:210, timeout:0};

/**
* Starts the slider.
*/
function startSlider()
{
	slider.running = true; 
	slider.timeout = setInterval("slideToNext()", slider.interval);
}

/**
* Stops the slider.
*/
function stopSlider()
{
	slider.running = false; 
	clearInterval(slider.timeout);
}

/**
* Slides to a cell.
*/
function slideToCell(n)
{
	if (n != slider.currentCell && slider.animating == false) {
		slider.animating = true;
		$('#latest-news-items').animate({left:(((n-1)*slider.cellWidth)*-1)+'px'}, 
										slider.duration, 
										function() 
										{ 
											// Reset the animating value and set the current cell number.
											slider.animating = false; 
											slider.currentCell = new Number(n);
											// Start the automated slider again.
											if (slider.running == false) {
												startSlider();
											}
										});
		// Mark the appropriate marker as active.
		$('#slider-buttons li').removeClass('active');
		$('#slider-buttons li:eq('+n+')').addClass('active');
	}
}

/**
* For sliding to the previous cell.
*/
function slideToPrevious()
{
	var n = slider.currentCell - 1;
	if (n == 0) {
		n = slider.numCells;
	}
	slideToCell(n);
}

/**
* For sliding to the next cell.
*/
function slideToNext()
{
	var n = slider.currentCell + 1;
	if (n > slider.numCells) {
		n = 1;
	}
	slideToCell(n);
}
