/**
*
*	Home.js
* Developed by Jim Hill at Wiseguy Digital
*
*/
var timer = 0;
var timerInterval = 12000;
var $j = jQuery.noConflict();
var activeBox = 1;

var boxContent = new Array();

// Load in the external JSON file
function loadJson()
{
	$j.getJSON("/index/home-adverts-json",
	function(data){
		$j.each(data.entries, function(i,item){
			boxContent[i+1] = new Array();
			boxContent[i+1]['image'] = item.image;
			boxContent[i+1]['content'] = item.content;
		});
	
		// Create the boxes and add ids to the list items
		createBoxes();
		// set the timer
		setTimer();
		// When clicking the buttons
		$j('#home-header-tab-nav a').click(onButtonPress);
		
	});
	
}

// Initially create three extra boxes withink the parent using jQuery 
// to save the individual images into
function createBoxes()
{
	// Give the first box an ID
	$j('#home-header-advert-container .home-header-advert').attr('id', 'advert-1');
	// Add the extra 3 containers
	for (var n = 2; n <= 4; n++) {
		$j('#home-header-advert-container').append('<div id="advert-' + n + '" class="home-header-advert"><div class="home-header-advert-left">' + boxContent[n]['content'] +'</div><div class="home-header-advert-right">' + boxContent[n]['image'] + '</div></div>');
		$j('#advert-' + n).hide();
	}
}

// This function starts the swap box process
function nextBox()
{
	swapBox();
}

// The main function for swapping the boxes
// If there is no box number submitted then
// it will calculate the next box in the sequence
function swapBox(boxNum)
{
	var showBox;
	var hideBox;
	
	hideBox = activeBox;
	
	// Automated box number
	if (!boxNum) {
		if (activeBox == 4) {
			showBox = 1;
		} else {
			showBox = activeBox + 1;
		}
	}
	// If there is a box number set by the button 
	else 
	{
		showBox = boxNum;
	}
		
	$j('#advert-' + hideBox).fadeTo('fast', 0, function(){
		$j('#advert-' + showBox).fadeTo(0, 0); 
		$j('#advert-' + showBox).css('display', 'block');
		$j('#advert-' + showBox).fadeTo('slow', 1); 
	});
	
	// Change the status of the buttons
	for (var n = 1; n <= 4; n++) {
		$j('#tab-' + n).attr('class', '');
		if (n == 1) $j('#tab-' + n).attr('class', 'first-tab');
		if (n == 4) $j('#tab-' + n).attr('class', 'last-tab');
	}
	$j('#tab-' + showBox).attr('class', 'active-tab');
	if (showBox == 1) $j('#tab-' + showBox).attr('class', 'first-tab active-tab');
	if (showBox == 4) $j('#tab-' + showBox).attr('class', 'last-tab active-tab');
	
	// Set the current activeBox
	activeBox = showBox;
	
}

// On button clicked
function onButtonPress(e)
{
	var str = $j(this).parent().attr('id');
	var boxNum = parseInt(str.substring(str.length-1, str.length));
	timerInterval = 30000;
	swapBox(boxNum);
	setTimer();
	timerInterval = 12000;
	e.preventDefault();
}

// Reset the timer
function setTimer()
{
	clearInterval(timer);
	timer = setInterval('nextBox()', timerInterval);
}

/**
* Now the document is ready to go
*/
$j(document).ready(function($)
{
	// AJAX
	loadJson();	

});