/* Description:
Every box has one numeric id, starting in 0;
Every box has at least one tab;
Every box tabs has one id, starting in 0;

Box/Tab ids for future reference:
0: Ultimas(0),Tops(1),Forum(2)
1: Horóscopo(0),Culinária(1),Beleza(2)
2: Tempo(0),Transito(1),Farmácias(2)
3: Fotos(0),Vídeos(1)
*/


//array with each box default tab to be opened if no cookie available;
var defaultTabs = [1,0,0,0];

//array with number of tabs per box;
var totalTabs = [3,3,3,2];



// LEAVE THE FOLLOWING UNCHANGED
var tabsCookieName = "CarasTabs"; //cookie name to save tabs info;
var animation = "<div class='msepblock tacenter'><img src='/i/loader.gif' alt='' width='205' height='10' class='bgred'></div>";
//check for cookie and update defaultTabs array if needed;
if (jQuery.cookie(tabsCookieName)){
	var myCookie = jQuery.cookie(tabsCookieName);
	var cookieTabs = myCookie.split("-");
	for(z=0; z<defaultTabs.length;z++){
		defaultTabs[z] = cookieTabs[z];
	}
}

// create cookie string and save the cookie.
function setTabCookie(box,tab){
	defaultTabs[box] = tab;
	var cookieValue = defaultTabs.join("-");
	jQuery.cookie(tabsCookieName, cookieValue, { expires: 30 });
}

// load tab contents if needed and show it.
function loadTab(box,tab){
	//load pub
	if (box == 0) {
		if(typeof showAdd == 'function') {
			if(jQuery.browser.msie && jQuery.browser.version > "6.0" ){
				showAdd();
			}
		}
	}

	var boxContainerPrefix = "container"+box+"-";
	var total = totalTabs[box];

	//run all tabs and deselect them
	for (i=0; i<total; i++){
		$('#'+boxContainerPrefix+i).hide();
		jQuery('#tab-'+box+"-"+i).removeClass('sel');
		jQuery('#tab-'+box+"-"+i).addClass('but');

		if (box == 3){
			jQuery('#total-'+i).hide();
			jQuery('#links-'+i).hide();
		}
	}

	//select clicked tab
	var boxContainer = $('#'+boxContainerPrefix+tab);
	jQuery('#tab-'+box+"-"+tab).addClass('sel');
	jQuery('#tab-'+box+"-"+tab).removeClass('but');

	//start loading animation
	if (box != 3){ boxContainer.html(animation); }else{ jQuery('#total-'+tab).show(); jQuery('#links-'+tab).show(); }
	boxContainer.show();

	//get box contents
	if (box != 3){
		var TimeStamp = new Date().getTime(); //avoid getting browser cached content
		var Url = '/static/boxes/box_'+box+'_'+tab+'.html?ts='+TimeStamp;
		if(box==2) Url = '/gen.pl?p=box&op='+box+':'+tab+'&ts='+TimeStamp;
		jQuery.ajax({
			type:'GET',
			url:Url,
		  success:function(data){
				boxContainer.html(data);
			}
		});
	}

	return false;
}

//button listener to detect tab button clicks
$(function() {
	$('div.tab').click(function() {
		//anytime a div.but inside a div.box_header gets clicked, if that tab isn't the selected one,
		//enable it and get it's contents
		var who = this.id.split("-");
		if (!jQuery(this).hasClass('sel')){
			loadTab(who[1],who[2]);
			setTabCookie(who[1],who[2]);
		}
		return false;
	});
});
