$(document).ready(function() {
	initBanners();
});



var count = null;
var last_count = null;
var total_banners = 4;
var delay = 10;
var data = null;
var first_run = true;
var timer_expired = false;
var banners = null;

function initBanners() {
	banners = new Array();
	$('#banner_wrapper').hide();
	count = Math.floor(Math.random()*5);
	loadData();
}

function firstRun() {
	first_run = false;
	$('#banner_wrapper').html(data);
	$('#banner_wrapper').fadeIn('slow');
	setTimer();
}

function loadData() {
	data = null;
	
	if(banners[count] != undefined) {
		data = banners[count];
	} else {
		last_count = count;
		$.ajax({
			url: '/app/webroot/banners/b'+(count+1)+'.php',
			success: function (d) {
				data = d;
				banners[last_count] = d;
				dataReady();
			},
			error: function (e) {
				$('#banner_wrapper').html('not availble');
			}
		});
	}
	if(count < total_banners) {
		count++;
	} else {
		count = 0;
	}
}

function dataReady() {
	if(first_run) {
		firstRun();
	}
	if(timer_expired) {
		switchBanner();
	}
}

function setTimer() {
	timer_expired = false;
	window.setTimeout('timerReady()', delay*1000);
}

function timerReady() {
	timer_expired = true;
	if(data != null) {
		switchBanner();
	}
}

function switchBanner() {
	$('#banner_wrapper').fadeOut('slow', function () {
		$('#banner_wrapper').html(data);
		$('#banner_wrapper').fadeIn('slow');
	});
	loadData();
	setTimer();
}
