// Inicializando variaveis
var $bannerTimer = 0;
var $bannerIndex = 0;

// Objeto com banners
var $bannerList = {"banners":[{
		"title": "Produtos e Serviços",
		"url": "media/flash/banner_001.html",
		"delay": 15000
	},{
		"title": "PackDesign",
		"url": "media/flash/banner_002.html",
		"delay": 10000
	},{
		"title": "PackBio: Sacolas Oxibiodegradáveis",
		"url": "media/flash/banner_003.html",
		"delay": 20000
}]};

// jQuery
$(document).ready(function(){
	// Construindo os controles
	for(i=0;i<$bannerList.banners.length;i++){
		$controle = "<a href=\"#\"><span>"+$bannerList.banners[i].title+"</span></a>"
		$('#tv_controle').append($controle);
	}
	
	// Chama o primeiro banner
	nextBanner($bannerIndex);
	
	// Chama o proximo banner
	function nextBanner($newBannerIndex) {
		clearTimeout($bannerTimer);
		if($newBannerIndex > $bannerList.banners.length - 1) {$newBannerIndex = 0};
		$('#tv_janela').load($bannerList.banners[$newBannerIndex].url, function(){
			$bannerIndex = $newBannerIndex;
			$('#tv_controle').find('.ativo').removeClass('ativo').end().find('a').eq($newBannerIndex).addClass('ativo');
			$bannerTimer = setTimeout(function(){nextBanner($bannerIndex+1)},$bannerList.banners[$bannerIndex].delay);
		});
	}

	// Executa ao clicar no controle
	$('#tv_controle a').click(function(e){
		var $this = $(this);
		e.preventDefault();
		if (!($this.hasClass('ativo'))) {
			$newBannerIndex = $this.index();
			nextBanner($newBannerIndex);
		}
	})
});
