/**
* Verifica si existe la consola de Firebug
*/
function consoleLog(str){
	if(typeof(console)!="undefined") {
		if(console) {
			console.log(str);
		}
	}
}

//--> Classes
/**
* DivElement prototype
*/

function DivElement(){
}

DivElement.prototype.show = function(id){
	$("#"+id).show();
	$("."+id).show();
}

DivElement.prototype.hide = function(id){
	$("#"+id).hide();
	$("."+id).hide();
}

var divElement = new DivElement();
//<-- Classes


//---> Variables Globales
var sectionMap = new Object();
sectionMap.home = new Array();
sectionMap.game = new Array();
sectionMap.show = new Array();
sectionMap.downloable = new Array();
sectionMap.video = new Array();
sectionMap.promotion = new Array();
sectionMap.mobile = new Array();
sectionMap.votatoon = new Array();

sectionMap.home = ['BT_728x90','BT_300x100'];
sectionMap.game = ['BT_728x90','BT_300x100','BT_120x240'];
sectionMap.show = ['BT_728x90','BT_300x100','BT_120x240'];
sectionMap.video = ['BT_728x90','BT_300x100','BT_120x240'];
sectionMap.downloable =[ 'BT_728x90','BT_300x100','BT_120x240'];
sectionMap.promotion = ['BT_728x90','BT_300x100'];
sectionMap.mobile = ['BT_728x90','BT_300x100'];
sectionMap.votatoon = ['BT_728x90'];

var contentType = new Object();
var titleHome = "Cartoon Network 2.5";

var VIDEO_BANNER_TIME = 17000;
var SPECIAL_BANNER_TIME = 15000;

var vTimeout;
var sTimeout;


//<--- Variables Globales
	

//---> updateHTMLContainer
/*
urlFrendly Se pasa siempre, es la ruta que ademas fue al swfaddress, Puede ser una seccion "/schedule" o un contenido "/video/ben10"
name: el nombre que corresponda al contenido
contentData Si no es contenido viene un null, SI es contenido es un string formato JSON que tiene el ContentVO del delegate
navigationHistoryArr: El primer elemento es el mas viejo. el ultimo elemento es el mas nuevo, cada elemento contendra un Object con:
	name: EL nombre que corresponda a ese contenido
	friendlyUrl: url frendly del contenido
*/

/**
*pageId:String
*urlFriendly:String
*contentName:String
*contentData:Object
*navigationHistoryArr:Array
*/
function updateHTMLContainer(pageName,urlFriendly,contentName,contentData,navigationHistoryArr){
    
    //consoleLog("Se llamo a >> updateHTMLContainer() pageName:"+pageName);    
    if(pageName != "video" && pageName != "game" && pageName != "show" && pageName != "downloable"){
        hideSkyBanner();
    }
    
    if (pageName != "billboardGame" && pageName != "billboardVideo"){
        setTitle(contentName,pageName);
        hideBillboard();    
        loadBanners(contentData,pageName);
        updateRelatedContent(contentData);
        /*if (navigationHistoryArr.length > 0 ){
            updateUserFooterBox(navigationHistoryArr);
        }*/
    }
    if(pageName == "home"){
        $.each(Twitter,function (divId,twitterId){
                loadTweet("#" + divId,twitterId);
            }
        );
    }
    
}
//<--- updateHTMLContainer



//---> Manejo de Ads

function getType(contentData,pageName){
    if(contentData != null && contentData.contentType != null) {
        return contentData.contentType;
    }
    if(pageName == "votatoon") {
        return pageName;
    }
    return "home";
}

function loadBanners(contentData,pageName){

    //consoleLog("Se llamo a >> loadBanners() contentData:"+contentData);
    
    var cType = (getType(contentData,pageName));
    var hostname = window.location.hostname;

    for (var i=0;i<sectionMap[cType].length;i++){
$("#"+sectionMap[cType][i]+"_i").get(0).src="http://"+hostname+"/ads.do?section="+cType+"&bannerType="+sectionMap[cType][i].slice(3)+"&hash="+new Date().getTime();
    }
    //tiene BT_120x240
    if(sectionMap[cType][2]){
        showSkyBanner();
    };
}

function showSkyBanner(){
	$("#BT_120x240").show();
}
function hideSkyBanner(){
	$("#BT_120x240").hide();
}

/**
contentType es una enumeracion definida en un delegate
contentId es el mismo entero que viaja en los delegate
token sera un string que debe ser pasado a onBillBoardFinalized

*contentType:String
*contentId:int
*token:String
*/

function showBillboard(contentType,contentId,token) {
	clearTimeout(sTimeout);
	//consoleLog("Se llamo a >> showBillboard() contentType: " + contentType + " contentId: " + contentId + " token: " + token);
	
	//carga el contenido del billboard
	var hostname = window.location.hostname;

	$("#BT_550x320_i").get(0).src = "http://"+hostname+"/ads.do?section="+contentType+"&bannerType=550x320&hash=new Date().getTime()";

	//callback for IE
	$("#BT_550x320_i").get(0).onreadystatechange = billboardLoaded;
	//callback for FF
	$("#BT_550x320_i").get(0).onload = billboardLoaded;
	
	sTimeout = setTimeout("onBillBoardFinalized('token123')",SPECIAL_BANNER_TIME);
	
}
function billboardLoaded(){
	$("#BT_550x320").show();
}

function onBillBoardFinalized(token) {
	//consoleLog("Se llamo a >> onBillBoardFinalized() " + app);
	var app = window.document["applicationContainer"];
	app.billboardFinalized(token);
	hideBillboard();
}
/*
Esta funcion debe ocultar el billboard y descargarlo.
Es la opuesta a showBillboard.
Es necesaria porque en algunos casos, el usuario puede abandonar el contenido antes de que termine el billboard
*/
function hideBillboard() {
	$("#BT_550x320").hide();
}
//<--- Manejo de Ads




//---> Status de Usuario
/**
*status: 0 out, 1 in
*
*status:int
*userId:int
*userName:String
*/
function onUserStatusChanged(status,userId,userName) {
	//consoleLog("onUserStatusChanged:: status: " + status + " userId: " + userId + " userName: " + userName);
}
//<--- Status de Usuario



//--> Update del Footer Box
/** Actualiza el un footer box con los links que provienen del array 'navigationHistoryArr'.
*  Este Array contiene los ultimos contenidos visitados por el usuario.
*  Primero elimina el contenido del box y luego agrega los links como elementos de una lista.
*  El array tiene el mas viejo en la primer posicion y el mas nuevo en la ultima, la lista se arma
*  en forma descendente del mas nuevo al mas viejo. 		
*/
function updateUserFooterBox(navigationHistoryArr){ 
		var max = navigationHistoryArr.length;
		var box='.box01';
		
		if (max>0) {
			var list = new String("");
			for (x=max-1;x>=0;x--){
				list = list + '<li><a href=' + navigationHistoryArr[x].friendlyUrl + ' > ' + navigationHistoryArr[x].name + ':' + x +' </a></li>'
			};			
			$('.boxesContainer').children(box).children().remove();
			$('.boxesContainer').children(box).append('<ul>');
			$('.boxesContainer').children(box).children('ul').append(list);	
		}			
	}
//<-- Update del Footer Box


//--> Informacion Relacionada
function updateRelatedContent(contentData){

	if (hasRelatedContent(contentData)){		
		var container = new String("");
		var cType = new String("");
		var contentDataType = new String("");
		var contentDataName = (contentData.name) ? contentData.name : new String("");
		var contentDataShowName = (contentData.showName) ? ' | ' + contentData.showName :  new String("");
		var contentDataDescription = (contentData.description) ? contentData.description :  new String("");	

		try{
			if  (contentData.contentType) {
			cType = contentData.contentType.substr(0, 1).toUpperCase() + contentData.contentType.substr(1);
			switch (contentData.contentType) {
				case 'game': {contentDataType = contentType.game.toUpperCase()};break;
				case 'video': {contentDataType = contentType.video.toUpperCase() };break;
				case 'mobile': {contentDataType = contentType.mobile.toUpperCase().replace('ACUTE','acute')};break;
				default:  {
						contentDataType = contentType.extra.toUpperCase();
						cType = contentType.extra.substr(0, 1).toUpperCase() + contentType.extra.substr(1);		
						};break;
				}	
			}
		}
		catch(e){
			consoleLog(e);		
		}


		 
		
		container = document.getElementById('contentDescriptionTitle');
	  	container.innerHTML = '<span class="contentDescription'+ cType +'">'+ contentDataType +'</span>' + '<strong>'+ contentDataName +'</strong>' + contentDataShowName ;
		container = document.getElementById('contentDescriptionBody');
		container.innerHTML = contentDataDescription;
		$(".relatedContent").show();
		
	} else {
		container = document.getElementById('contentDescriptionTitle');
		container.innerHTML = '';
		container = document.getElementById('contentDescriptionBody');
		container.innerHTML = '';
		$(".relatedContent").hide();
	}	
}

function hasRelatedContent(contentData){
	return !(contentData == null);
}

//<-- Informacion Relacionada



//---> Carga del Juego

function loadGame(url) {
var container = document.getElementById('gameContainer_absolute_inner');
container.innerHTML  ='';
container.innerHTML  = '<iframe scrolling="no" src="'+url+'" id="gameFrame" width="600" height="400" style="border:none;visibility:visible"></iframe>';
}

function unloadGame() {
var container = document.getElementById('gameContainer_absolute_inner');
container.innerHTML  ='';
}
//<--- Carga del Juego


//---> Banner Controller Expandable
function resizeIframe(width,height){
	var id = "#BT_728x90_i";
	$(id).get(0).width = width;
	$(id).get(0).height = height;
}
//<--- Banner Controller Expandable

//---> Banner Controller Video
function videoController(type){
	clearTimeout(sTimeout);

	if (type=="videoStart"){
		vTimeout = setTimeout("onBillBoardFinalized('token123')",VIDEO_BANNER_TIME);
	}else if(type=="videoFinish"){
		clearTimeout(vTimeout);
		onBillBoardFinalized('token123');
	}else{
		consoleLog("error: no se llamo correctamente la funcion. se cierra el contenedor del BB");
		onBillBoardFinalized('token123');
	}

}
//<--- Banner Controller Video

//---> Set Title
function setTitle(contentTitle,page){
	if (page!='home')	
		document.title=contentTitle;
	else
		document.title=titleHome;
}
//<--- Set Title
