//Var Defaults
var idioma = 1;
var mostrarTOPHAT = 1;
var vDominio = 'LATAM';
var GLOBAL_ENTORNO = 'live'; // Default
var KIDS_WS_RELACIONADOS_DBHOST_URL = 'http://apps.tudiscoverykids.com/nkotb2/webservices/';
var KIDS_TOPHAT_DBHOST_URL = 'http://apps.tudiscoverykids.com/tophat/';
var KIDS_TOPHAT_DBHOST_IMG_URL = 'http://ws.tudiscoverykids.com/img-host/';
var GLOBAL_ENTORNO_url = window.location.toString();
var GLOBAL_ENTORNO_partes = GLOBAL_ENTORNO_url.split('.')
var GLOBAL_ENTORNO_breadcrumb = GLOBAL_ENTORNO_partes[0].replace('http://','');
var pais = "US";
if( pais.length != 2 ) pais = 'AR';
writeCookie("pais", pais, 8760, "/"); //1 Año
writeCookie("paisOrigen", pais, 240, "/");

var channel_code = 'DKLA-SP';
if( pais == 'AR' ) channel_code = 'DKAR-SP';
else if( pais == 'MX' ) channel_code = 'DKMX-SP';


var DOCUMENT_DOMAIN = 'www.'+document.domain;
var GLOBAL_QS = getQueryString(); if(location.search) GLOBAL_QS = location.search.replace("?","&");
var _VAR_LAMP_UNO_IMPACTA_SOBRE = 1000; //1 de _VAR_LAMP_UNO_IMPACTA_SOBRE llamará a LAMP. Se usa para "quienes vieron también vieron...".

if( typeof(_NO_HISTORY) == "undefined" ) writeCookie('_HISTORY', location.href, null, '/');

//Vars entornos
if( GLOBAL_ENTORNO_breadcrumb == 'nkotb2' ){ // developer
	GLOBAL_ENTORNO = 'dev';
	KIDS_WS_RELACIONADOS_DBHOST_URL = 'http://ws.nkotb2.discovery.noblinktv.com.ar/';
	//KIDS_WS_RELACIONADOS_DBHOST_URL = 'http://apps.tudiscoverykids.com/nkotb2/webservices/';
	KIDS_WS_LOG_REPORT = 'http://ws1.tudiscoverykids.com/padres/reportes/';
	//KIDS_WS_LOG_REPORT = 'http://ws.nkotb2.discovery.noblinktv.com.ar/padres/reportes/';
	DOCUMENT_DOMAIN = 'nkotb2.discovery.noblinktv.com.ar';
	
	KIDS_TOPHAT_DBHOST_URL = 'http://admin.nkotb.discovery.bhdm.com.ar/PHPFRONT/tophat/';
	//KIDS_TOPHAT_DBHOST_IMG_URL = 'http://ws.nkotb2.discovery.noblinktv.com.ar/img-host/';
}else if( GLOBAL_ENTORNO_breadcrumb == 'www2-tudiscoverykids-com' ){ // qa
	GLOBAL_ENTORNO = 'qa';
	KIDS_WS_RELACIONADOS_DBHOST_URL = 'http://apps.tudiscoverykids.com/nkotb2/webservices/';
	KIDS_WS_LOG_REPORT = 'http://ws1.tudiscoverykids.com/padres/reportes/';
	DOCUMENT_DOMAIN = 'www2-tudiscoverykids-com.discoveryisispreview2.com';
}else if( GLOBAL_ENTORNO_breadcrumb == 'www-tudiscoverykids-com' ){ // qa
	GLOBAL_ENTORNO = 'pre-live';
	KIDS_WS_RELACIONADOS_DBHOST_URL = 'http://apps.tudiscoverykids.com/nkotb2/webservices/';
	KIDS_WS_LOG_REPORT = 'http://ws1.tudiscoverykids.com/padres/reportes/';
	DOCUMENT_DOMAIN = 'www-tudiscoverykids-com';
}else{
	GLOBAL_ENTORNO = 'live';
	KIDS_WS_RELACIONADOS_DBHOST_URL = 'http://apps.tudiscoverykids.com/nkotb2/webservices/';
	KIDS_WS_LOG_REPORT = 'http://ws1.tudiscoverykids.com/padres/reportes/';
	DOCUMENT_DOMAIN = 'www.tudiscoverykids.com';
}

/*
 * Textos / Idiomas 
*/
_TEXTOS_MESES = new Array();
_TEXTOS_MESES['ene'] = 'Enero';
_TEXTOS_MESES['feb'] = 'Febrero';
_TEXTOS_MESES['mar'] = 'Marzo';
_TEXTOS_MESES['apr'] = 'Abril';
_TEXTOS_MESES['abr'] = 'Mayo';
_TEXTOS_MESES['jun'] = 'Junio';
_TEXTOS_MESES['jul'] = 'Julio';
_TEXTOS_MESES['ago'] = 'Agosto';
_TEXTOS_MESES['sep'] = 'Septiembre';
_TEXTOS_MESES['oct'] = 'Octubre';
_TEXTOS_MESES['nov'] = 'Noviembre';
_TEXTOS_MESES['dic'] = 'Diciembre';

_TEXTOS_MESES_POR_ID = new Array();
_TEXTOS_MESES_POR_ID[1] = 'Enero';
_TEXTOS_MESES_POR_ID[2] = 'Febrero';
_TEXTOS_MESES_POR_ID[3] = 'Marzo';
_TEXTOS_MESES_POR_ID[4] = 'Abril';
_TEXTOS_MESES_POR_ID[5] = 'Mayo';
_TEXTOS_MESES_POR_ID[6] = 'Junio';
_TEXTOS_MESES_POR_ID[7] = 'Julio';
_TEXTOS_MESES_POR_ID[8] = 'Agosto';
_TEXTOS_MESES_POR_ID[9] = 'Septiembre';
_TEXTOS_MESES_POR_ID[10] = 'Octubre';
_TEXTOS_MESES_POR_ID[11] = 'Noviembre';
_TEXTOS_MESES_POR_ID[12] = 'Diciembre';

_TEXTOS_DIAS = new Array();
_TEXTOS_DIAS['sunday'] = 'Domingo';
_TEXTOS_DIAS['monday'] = 'Lunes';
_TEXTOS_DIAS['tuesday'] = 'Martes';
_TEXTOS_DIAS['wednesday'] = 'Miércoles';
_TEXTOS_DIAS['thursday'] = 'Jueves';
_TEXTOS_DIAS['friday'] = 'Viernes';
_TEXTOS_DIAS['saturday'] = 'Sábado';


_TEXTOS_CATEGORIAS = new Array();
_TEXTOS_CATEGORIAS['creatividad-y-disenos'] = 'Creatividad y diseños';
_TEXTOS_CATEGORIAS['cuerpo-y-destrezas'] = 'Cuerpo y destrezas';
_TEXTOS_CATEGORIAS['letras-y-cuentos'] = 'Letras y cuentos';
_TEXTOS_CATEGORIAS['musica'] = 'Música';
_TEXTOS_CATEGORIAS['naturaleza'] = 'Naturaleza';
_TEXTOS_CATEGORIAS['numeros-y-desafios'] = 'Números y desafíos';




$(document).ready(
	function() {
		initNavegacionPersonajes();
		$('.row-hijo .hijo-name a').click(function () { 
			$('.row-hijo').css('background-position', 'bottom left');
			$(this).parent().parent().css('background-position', 'top left');
			return false;
		});
	}
);
function limpiar(element){
	if(!$(element).attr('texto')){
		$(element).attr('texto', $(element).val());
		$(element).val('');
	}
}
function rellenar(element){	
	if($.trim($(element).val()) == ''){
		$(element).val($(element).attr('texto'));
		$(element).removeAttr('texto');
	}
}
function writeCookie(name, value, hours, path){
	if( document.domain.indexOf("bhdm") != -1 ){	
		var domain = document.domain;
	}else if( document.domain.indexOf("noblinktv") != -1 ){
		var domain = document.domain;
	}else if( document.domain.indexOf("discoveryisispreview2.com") != -1 ){
		var domain = 'discoveryisispreview2.com';
	}else if( document.domain.indexOf("tudiscoverykids.com") != -1 ){
		var domain = 'tudiscoverykids.com';
	}
	var expire = "";
	if(hours != null){
		expire = new Date((new Date()).getTime() + hours * 3600000);
		expire = "; expires=" + expire.toGMTString();
	}
	document.cookie = name + "=" + escape(value) + expire + "; path=" + path + "; domain=" + domain;
}
function readCookie(name){
	var cookieValue = "";
	var search = name + "=";
	if(document.cookie.length > 0){ 
		offset = document.cookie.indexOf(search);
		if (offset != -1){ 
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) end = document.cookie.length;
			cookieValue = unescape(document.cookie.substring(offset, end));
		}
	}
	return cookieValue;
}
function getQueryString() {
	if (location.search) return location.search.replace("?","&");
	return "";
}
function getQueryVariable(variable) {
  var query = self.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
		if( variable == 'swf'){
			salida = new String(pair[1]);
			salida2 = salida.substr(0,salida.length-4);
		}else{
			salida2 = pair[1];
		}
		return salida2;
    }
  } 
}
function guardarFavorito( seccion, elemento ){
	seccion = 'favoritos-'+seccion;
	var datos = readCookie(seccion);
	arrayTemp = datos.split("|");
	salida = '';
	var yaExistia = 0;
	var hayElemento = 0;
	for(i=0; i<arrayTemp.length; i++){
		arrayInternoTemp = arrayTemp[i].split("^");
		valor = arrayInternoTemp[1]>0? arrayInternoTemp[1]:1;
		if(elemento == arrayInternoTemp[0] ){
			valor = parseInt(valor,10) + 1;
			yaExistia = 1;
		}
		if( arrayInternoTemp[0] != '' ){
			salida += arrayInternoTemp[0] +'^'+ (valor)+ (i<(parseInt(arrayTemp.length,10)-1)?'|':'');
			hayElemento = 1;
		}
	}
	if( yaExistia == 0 ) salida += ( hayElemento == 1 ? '|' : '' ) + elemento +'^1' ;
	writeCookie(seccion, salida, 3000, "/");
	return listarFavoritos( seccion );
}
function listarFavoritos( seccion ){
	seccion = 'favoritos-'+seccion;
	return readCookie(seccion);
}
function dibujarFavoritos(){
	if( favoritosSeccion == 'juegos' ){
		var imgFavoritosRollover = '/localresources/images/juegos/misc_juegos.png';
		var contenttype = 'kids-game';
	}else{
		var imgFavoritosRollover = '/localresources/images/videos/misc_videos.png'
		var contenttype = 'video';
	}
	var favoritosGuardados = listarFavoritos(favoritosSeccion) || "";
	if( favoritosGuardados == "" ){
		$('#contenedor-modulo-favoritos-'+favoritosSeccion).hide();
		 return false;
	}
	objFavoritosGuardados = ordenarArrayToObj(favoritosGuardados);
	var hastaDondeIr = objFavoritosGuardados.length > 6 ? 6 : objFavoritosGuardados.length;
	for (i=0; i<hastaDondeIr; i++){
		paginaFavorita = objFavoritosGuardados[i].url;
			if( GLOBAL_ENTORNO == 'dev' ) URLXML = '/dni-content/content.xml';
			else URLXML =  '/kids-fe/content/?url='+paginaFavorita+'&output=xml&contenttypes='+contenttype+GLOBAL_QS;
			$.ajax({
			type: "GET",
			url: URLXML,
			dataType: "xml",
			async: false,
			success: function(xml) {
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(xml).find('promos promo title').text() || "";
					var url  = $(xml).find('promos promo url').text() || "";
					//var imagen = ''; $(xml).find('promos promo images image').each(function(){ if( imagen == '' ) imagen = $(this).text() || ""; }); // Primer imagen
					var imagen = ''; 				
					if( favoritosSeccion == 'juegos' ) imagen = $(xml).find('images image[width="149"][height="90"]').text() || "";
                    else imagen = $(xml).find('images image[width="120"][height="90"]').text() || "";					
					
					htmlOut +='    <div class="item-small">';
					htmlOut +='      <div class="img-active"><img src="'+imagen+'" alt="'+title+'" /></div>';
					htmlOut +='      <a href="'+url+'" class="img-hover"> <img src="'+imgFavoritosRollover+'" width="30" alt="" /> '+title+' </a>';
					htmlOut +='    </div>';
					$('#favoritos-contenido #preload').remove();
					$('#favoritos-contenido').append( htmlOut );
				},
			error: function(jqXHR, textStatus, errorThrown){
				//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
				}
			})
	}
}
function ordenarArrayToObj(valor) {
	var arrayTmp = valor.split("|");
	var arrayTmpFull = new Array();
	for (n=0; n<arrayTmp.length; n++) {
		var tmp_v = arrayTmp[n].split("^");
		arrayTmpFull.push({valor:parseInt(tmp_v[1],10), url:tmp_v[0]});
	}
	arrayTmpFull.sort(function(a,b){ return b.valor - a.valor;});
	return arrayTmpFull;
}
function listarHorarios(){
	if( GLOBAL_ENTORNO == 'dev' ){
		URLXML = '/dni-tvlistings/test_tvlisting.xml';
	}else{
		var fechaActual = new Date();
		var mes = (fechaActual.getMonth()+1)<10?'0'+(fechaActual.getMonth()+1):fechaActual.getMonth()+1;
		var dia = (fechaActual.getDate()<10?'0'+fechaActual.getDate():fechaActual.getDate());
		var minutosTmp = fechaActual.getMinutes();
		var modMinutos = fechaActual.getMinutes()%15;
		var minutos = modMinutos!=0?minutosTmp-modMinutos:minutosTmp;
		var hora = (fechaActual.getHours()<10?'0'+fechaActual.getHours():fechaActual.getHours());

		var fecha = dia+''+mes+''+fechaActual.getFullYear()+''+hora+''+minutos;
		
		URLXML =  '/dni-tvlistings/GetScheduleByTime?date_time='+fecha+'&country_code='+pais+'&geocode='+pais+'&channel_code='+channel_code;
	}
	$.ajax({
	type: "GET",
	url: URLXML,
	dataType: "xml",
	async: false,
	success: function(xml) {
			var htmlOut = '';
			var iHtmlOut = 0;
			$(xml).find('dni-listings get-listings-by-time channel-code time-listed-programmes programme').each(function(){
				++iHtmlOut;
				if( tvlistingVerticalCuantosListar >= iHtmlOut ){
					seriestitle = $(this).find('series-title').text() || "";
					if( seriestitle.length > 35 ) seriestitle = seriestitle.substr(0,35) + '...';
					programmedescription = $(this).find('programme-description').text() || "";
					programmeimg = $(this).find('promo images image image-path').text() || "/localresources/images/tvlisting-placeholder.png";
					starttime = $(this).find('start-time formatted').text() || "";
					if( starttime != "" ) starttime = starttime.substr(0,5);
					htmlOut +='		<div class="prog'+(iHtmlOut==1?' active':'')+'">';
					htmlOut +='			<div class="img">';
					htmlOut +='				<img src="'+programmeimg+'" alt="'+seriestitle+'" />';
					htmlOut +='			</div>';
					htmlOut +='			<div class="txt">';
					htmlOut +='				'+starttime+'hs';
					htmlOut +='				<br />';
					htmlOut +='				'+seriestitle+' ';
					htmlOut +='			</div>';
					htmlOut +='			<div class="clearFloat"></div>';
					htmlOut +='		</div>';
				}
				
			});
			$('#tvlisting-contenido #preload').remove();
			$('#tvlisting-contenido').html( htmlOut );
		},
	error: function(jqXHR, textStatus, errorThrown){
		//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
		}
	})
}
function listarHorariosPersonaje(){
	if( GLOBAL_ENTORNO == 'dev' ){
		URLXML = '/dni-tvlistings/test_tvlisting-personaje.xml';
	}else{
		URLXML =  '/dni-tvlistings/GetTransformedScheduleBySearchString?type=search&channel_code='+channel_code+'&search_string='+itemActualInstanciaTvListing+'&country_code='+pais+'&geocode='+pais;
	}
	$.ajax({
	type: "GET",
	url: URLXML,
	dataType: "xml",
	async: false,
	success: function(xml) {
			var htmlOut = '';
			var iHtmlOut = 0;
			$(xml).find('dni-listings get-listings-by-search-string search-results programme').each(function(){
				
				++iHtmlOut;
				if( iHtmlOut <= 3 ){
					date = $(this).find('date formatted').text() || "";
					starttime = $(this).find('start-time formatted').text() || ""; //alert(date.substr(3,6).toLowerCase());
					date = $(this).find('date formatted').text() || ""; mes = ''; fecha = '';
					if( date != "" ) mes = _TEXTOS_MESES[date.substr(3,6).toLowerCase()].toUpperCase();
					if( date != "" ) fecha = date.substr(0,2);
					
					date = $(this).find('date day').text() || ""; dia = '';
					date = date.toLowerCase();
					if( date != "" ) dia = _TEXTOS_DIAS[date].toUpperCase();
					if( starttime != "" ) starttime = starttime.substr(0,5);
					htmlOut +='		<div class="prog">';
					htmlOut +='			<div class="txt">';
					htmlOut +='				'+dia+' '+fecha+' de '+ mes +' '+starttime+'hs ' +  (iHtmlOut<=2?'&nbsp;&nbsp;- ':'');
					htmlOut +='			</div>';
					htmlOut +='		</div>';
				}
			});
			if( htmlOut == '' ) $('#contenedorTvLIsting').remove();
			$('#tvlisting-personaje-contenido #preload').remove();
			$('#tvlisting-personaje-contenido').html( htmlOut );
		},
	error: function(jqXHR, textStatus, errorThrown){
		//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
		}
	})
}
var dibujarJuegosRelacionados_i = 0;
function dibujarJuegosRelacionados(){
	if( yaPidioKeywordItemActual == 0 ){
		++dibujarJuegosRelacionados_i;
		if( dibujarJuegosRelacionados_i < 5 ) setTimeout('dibujarJuegosRelacionados()',1000);
	}else{
		var imgRelacionadosRollover = '/localresources/images/juegos/misc_juegos.png';
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-game.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+keywordItemActual+'&sortby=random&output=xml&contenttypes=kids-game&items=6'+GLOBAL_QS;
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(this).find('title').text() || "";
					var url  = $(this).find('url').text() || "";
					var imagen = $(this).find('images image[width="149"][height="90"]').text() || "";

					
					htmlOut +='    <div class="item-small">';
					htmlOut +='      <div class="img-active"><img src="'+imagen+'" alt="'+title+'" /></div>';
					htmlOut +='      <a href="'+url+'" class="img-hover"> <img src="'+imgRelacionadosRollover+'" width="30" alt="" /> '+title+' </a>';
					htmlOut +='    </div>';
					$('#juegos-relacionados-contenido #preload').remove();
					$('#juegos-relacionados-contenido').append( htmlOut );
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
			}
		})
	}
}
var dibujarVideosRelacionados_i = 0;
function dibujarVideosRelacionados(){
	if( yaPidioKeywordItemActual == 0 ){
		++dibujarVideosRelacionados_i;
		if( dibujarVideosRelacionados_i < 5 ) setTimeout('dibujarVideosRelacionados()',1000);
	}else{
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-video.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+keywordItemActual+'&output=xml&contenttypes=video&items=6'+GLOBAL_QS;
		var imgRelacionadosRollover = '/localresources/images/videos/misc_videos.png'
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(this).find('title').text() || "";
					var url  = $(this).find('url').text() || "";
					var imagen = $(this).find('images image[width="120"][height="90"]').text() || "";

					htmlOut +='    <div class="item-small">';
					htmlOut +='      <div class="img-active"><img src="'+imagen+'" alt="'+title+'" /></div>';
					htmlOut +='      <a href="'+url+'" class="img-hover"> <img src="'+imgRelacionadosRollover+'" width="30" alt="" /> '+title+' </a>';
					htmlOut +='    </div>';
					$('#videos-relacionados-contenido #preload').remove();
					$('#videos-relacionados-contenido').append( htmlOut );
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
			}
		})
	}
}
function pedirYSetearContentido(){
	if( seccionItemActual == 'juegos' ){
		var contenttype = 'kids-game';
	}else if( seccionItemActual == 'show' ){
		var contenttype = 'kids-show';
	}else if( seccionItemActual == 'padres' ){
		var contenttype = 'parent-article';
	}else{
		var contenttype = 'video';
	}
	var imgRelacionadosRollover = '/localresources/images/personajes/misc_personajes.png'
	if( GLOBAL_ENTORNO == 'dev' ) URLXML = '/dni-content/content.xml';
	else URLXML =  '/kids-fe/content/?url='+urlItemActual+'&output=xml&contenttypes='+contenttype+GLOBAL_QS;
	$.ajax({
	type: "GET",
	url: URLXML,
	dataType: "xml",
	async: false,
	success: function(xml) {
			$(xml).find('promos promo keywords keyword').each(function(){ if( keywordItemActual == '' ) keywordItemActual = $(this).text() || ""; }); // Primer keyword
			yaPidioKeywordItemActual = 1; // Callback
			
	},
	error: function(jqXHR, textStatus, errorThrown){
		//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
		}
	})	
}

function pedirYSetearContentidoReportesPadre(debug){
	if( seccionItemActual == 'juegos' ){
		var contenttype = 'kids-game';
	}else if( seccionItemActual == 'show' ){
		var contenttype = 'kids-show';
	}else if( seccionItemActual == 'padres' ){
		var contenttype = 'parent-article';
	}else{
		var contenttype = 'video';
	}

	//Padre / reportes
	urlItemActual = urlItemActual.replace('/padres/reportes/','/');
	urlItemActual = urlItemActual.replace('/pais/relatorios/','/');
	
	var imgRelacionadosRollover = '/localresources/images/personajes/misc_personajes.png'
	if( GLOBAL_ENTORNO == 'dev' ) URLXML = '/dni-content/content.xml';
	else URLXML =  '/kids-fe/content/?url='+urlItemActual+'&output=xml&contenttypes='+contenttype+GLOBAL_QS;
	
	if( typeof(debug) != "undefined" && debug == 1 ) console.log(URLXML+'\n');
	
	$.ajax({
	type: "GET",
	url: URLXML,
	dataType: "xml",
	async: false,
	success: function(xml) {
		$(xml).find('promos promo keywords keyword').each(function(){ 
			if( keywordItemActual == '' ) keywordItemActual = $(this).text() || ""; }); // Primer keyword
			var imagen = $(xml).find('images image[width="230"][height="132"]').text() || "";
			var descLong = $(xml).find('descLong').text() || "";
			
			if( typeof(debug) != "undefined" && debug == 1 ) console.log('SI'+imagen+'-'+descLong+'\n');
			
			yaPidioKeywordItemActual = 1; // Callback
			$(document).ready(function(){
				$('#contenedor_nombre_categoria').html(_TEXTOS_CATEGORIAS[keywordItemActual.toLowerCase()]);
				//alert(imagen)
				$('#contenedor_imagen').html('<img src="'+imagen+'" alt="" />');
				$('#contenedor_descLong').html(descLong);
			})
		},
	error: function(jqXHR, textStatus, errorThrown){
		//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
		if( typeof(debug) != "undefined" && debug == 1 ) console.log(jqXHR +'-'+ textStatus +'-'+ errorThrown)
		}
	})	
}
function pedirYSetearContentidoPersonajesEnPadres(){
	var contenttype = 'kids-show';
	urlItemActual = urlItemActual.replace('/padres/','/');
	urlItemActual = urlItemActual.replace('/pais/','/');
	var imgRelacionadosRollover = '/localresources/images/personajes/misc_personajes.png'
	if( GLOBAL_ENTORNO == 'dev' ) URLXML = '/dni-content/content.xml';
	else URLXML =  '/kids-fe/content/?url='+urlItemActual+'&output=xml&contenttypes='+contenttype+GLOBAL_QS;
	$.ajax({
	type: "GET",
	url: URLXML,
	dataType: "xml",
	async: false,
	success: function(xml) {
			$(xml).find('promos promo keywords keyword').each(function(){ if( keywordItemActual == '' ) keywordItemActual = $(this).text() || ""; }); // Primer keyword
			yaPidioKeywordItemActual = 1; // Callback
			
	},
	error: function(jqXHR, textStatus, errorThrown){
		//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
		}
	})	
}
function dibujarPersonajesRelacionados(){
	if( yaPidioKeywordItemActual == 0 ){	
		setTimeout('dibujarPersonajesRelacionados()',1000);
	}else{
		var imgRelacionadosRollover = '/localresources/images/personajes/misc_personajes.png'
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-personaje.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+keywordItemActual+'&sortby=random&output=xml&contenttypes=kids-show&items=6'+GLOBAL_QS;
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(this).find('title').text() || "";
					var url  = $(this).find('url').text() || "";
					var imagen = $(this).find('images image[width="149"][height="90"]').text() || "";
					htmlOut +='    <div class="thumb-small">';
					htmlOut +='      <div class="img-active"><img src="'+imagen+'" alt="'+title+'" /></div>';
					htmlOut +='      <a href="'+url+'" class="img-hover"> <img src="'+imgRelacionadosRollover+'" width="30" alt="" /> '+title+' </a>';
					htmlOut +='    </div>';
					$('#personajes-relacionados-contenido #preload').remove();
					$('#personajes-relacionados-contenido').append( htmlOut );
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
			}
		})
	}
}

var dibujarPadresPersonajesRelacionados_i = 0;
function dibujarPadresPersonajesRelacionados(){
	if( yaPidioKeywordItemActual == 0 ){
		++dibujarPadresPersonajesRelacionados_i;
		if( dibujarPadresPersonajesRelacionados_i < 5 ) setTimeout('dibujarPadresPersonajesRelacionados()',1000);
	}else{
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-articulos.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+keywordItemActual+'&sortby=random&output=xml&contenttypes=kids-show&items=6'+GLOBAL_QS;
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(this).find('title').text() || "";
					if( title.length > 37 ) title = title.substr(0,37) + '...';
					var url  = $(this).find('url').text() || "";
					url = url.replace('/personajes/','/padres/personajes/');
					url = url.replace('/personagens/','/pais/personagens/');
					var imagen = $(this).find('images image[width="149"][height="90"]').text() || "";
					htmlOut ='    					<div class="item-rel">';
					htmlOut +='    						<div class="item-rel-img">';
					htmlOut +='    							<a href="'+url+'" title="'+title+'"><img src="'+imagen+'" alt="'+title+'" /></a>';
					htmlOut +='    						</div>';
					htmlOut +='    						<div class="item-rel-n">';
					htmlOut +='    							<a href="'+url+'" title="'+title+'">'+title+'</a>';
					htmlOut +='    						</div>';
					htmlOut +='    					</div>';
					$('#padres-articulos-relacionados-contenido #preload').remove();
					$('#padres-articulos-relacionados-contenido').append( htmlOut );
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
			}
		})
	}
}
var dibujarPadresArticulosRelacionados_i = 0;
function dibujarPadresArticulosRelacionados(){
	if( yaPidioKeywordItemActual == 0 ){
		++dibujarPadresArticulosRelacionados_i;
		if( dibujarPadresArticulosRelacionados_i < 5 ) setTimeout('dibujarPadresArticulosRelacionados()',1000);
	}else{
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-articulos.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+keywordItemActual+'&sortby=random&output=xml&contenttypes=parent-article&items=6'+GLOBAL_QS;
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(this).find('title').text() || "";
					if( title.length > 37 ) title = title.substr(0,37) + '...';
					var url  = $(this).find('url').text() || "";
					var imagen = $(this).find('images image[width="149"][height="90"]').text() || "";
					htmlOut ='    					<div class="item-rel">';
					htmlOut +='    						<div class="item-rel-img">';
					htmlOut +='    							<a href="'+url+'" title="'+title+'"><img src="'+imagen+'" alt="'+title+'" /></a>';
					htmlOut +='    						</div>';
					htmlOut +='    						<div class="item-rel-n">';
					htmlOut +='    							<a href="'+url+'" title="'+title+'">'+title+'</a>';
					htmlOut +='    						</div>';
					htmlOut +='    					</div>';
					$('#padres-articulos-relacionados-contenido #preload').remove();
					$('#padres-articulos-relacionados-contenido').append( htmlOut );
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
			}
		})
	}
}
var dibujarPadresReportesArticulosRelacionados_i = 0;
function dibujarPadresReportesArticulosRelacionados(){
	var iHtmlOut = 0;
	if( yaPidioKeywordItemActual == 0 ){
		++dibujarPadresReportesArticulosRelacionados_i;
		if( dibujarPadresReportesArticulosRelacionados_i < 5 ) setTimeout('dibujarPadresReportesArticulosRelacionados()',1000);
	}else{
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-articulos.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+keywordItemActual+'&sortby=random&output=xml&contenttypes=parent-article&items=2'+GLOBAL_QS;
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					if( iHtmlOut < 2 ){	
						var title = $(this).find('title').text() || "";
						var descLong = $(this).find('descLong').text() || "";
						if( title.length > 37 ) title = title.substr(0,37) + '...';
						var url  = $(this).find('url').text() || "";
						var imagen = $(this).find('images image[width="149"][height="90"]').text() || "";
	
						
						htmlOut +='		<div class="row-news"><div class="l"><div class="thumb-small"><div class="img"><a href="'+url+'"><img src="'+imagen+'" alt="'+title+'" /></a></div></div></div>';
						htmlOut +='			<div class="r"><div class="tit"><a href="#">'+title+'</a></div>';
						htmlOut +='				<div class="txt"><a href="'+url+'">'+descLong+'</a></div>';
						htmlOut +='				<div class="link"><a href="'+url+'">leer más<img src="/localresources/images/padres/link-img.png" alt="'+title+'" /></a></div>';
						htmlOut +='			</div><div class="clearFloat"></div>';
						htmlOut +='        </div>';
						

						$('#padres-articulos-relacionados-contenido #preload').remove();
						$('#padres-articulos-relacionados-contenido').append( htmlOut );
					}
					iHtmlOut++;
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			//alert(jqXHR +'-'+ textStatus +'-'+ errorThrown);
			}
		})
	}
}
function dibujarJuegosPersonajesRelacionados(){
		var imgRelacionadosRollover = '/localresources/images/juegos/misc_juegos.png';
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-game.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+itemActual+'&sortby=random&output=xml&contenttypes=kids-game&items=6'+GLOBAL_QS;
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(this).find('title').text() || "";
					var url  = $(this).find('url').text() || "";
					var imagen = $(this).find('images image[width="149"][height="90"]').text() || "";
 
					
					htmlOut +='    <div class="item-small">';
					htmlOut +='      <div class="img-active"><img src="'+imagen+'" alt="'+title+'" /></div>';
					htmlOut +='      <a href="'+url+'" class="img-hover"> <img src="'+imgRelacionadosRollover+'" width="30" alt="" /> '+title+' </a>';
					htmlOut +='    </div>';
					$('#show-juegos-relacionados-contenido #preload').remove();
					$('#show-juegos-relacionados-contenido').append( htmlOut );
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			$('#show-games').remove();
			}
		})
}
function dibujarVideosPersonajesRelacionados(){
		var imgRelacionadosRollover = '/localresources/images/videos/misc_videos.png';
		if( GLOBAL_ENTORNO == 'dev' ) URLKEYWORDXML = '/dni-content/keywords-video.xml';
		else URLKEYWORDXML =  '/kids-fe/content/?keywords='+itemActual+'&output=xml&contenttypes=video&&videotype=show&items=6'+GLOBAL_QS;
		$.ajax({
		type: "GET",
		url: URLKEYWORDXML,
		dataType: "xml",
		async: false,
		success: function(xml) {
				$(xml).find('promos promo').each(function(){
					var htmlOut = '';
					var iHtmlOut = 0;
					var title = $(this).find('title').text() || "";
					var url  = $(this).find('url').text() || "";
					var imagen = $(this).find('images image[width="120"][height="90"]').text() || "";
 
					
					htmlOut +='    <div class="item-small">';
					htmlOut +='      <div class="img-active"><img src="'+imagen+'" alt="'+title+'" /></div>';
					htmlOut +='      <a href="'+url+'" class="img-hover"> <img src="'+imgRelacionadosRollover+'" width="30" alt="" /> '+title+' </a>';
					htmlOut +='    </div>';
					$('#show-video-relacionados-contenido #preload').remove();
					$('#show-video-relacionados-contenido').append( htmlOut );
				});						
			},
		error: function(jqXHR, textStatus, errorThrown){
			$('#show-videos').remove();
			}
		})
}
function callbackQuienesVieron(datos) {
	if( datos.errornum == '100' ){
		var htmlOut = '';
		var cuantosItems = 0;
		for( var i in datos.items ){
			cuantosItems++;
			htmlOut +='    <div class="item-small">';
			htmlOut +='        <div class="img-active">';
			htmlOut +='            <img src="'+ datos.items[i]['imagen'] +'" alt="'+ datos.items[i]['nombre'] +'" />';
			htmlOut +='        </div>';
			htmlOut +='        <a href="'+ datos.items[i]['url'] +'" class="img-hover" title="'+ datos.items[i]['nombre'] +'">';
			htmlOut +='            <img src="'+imgQuienesVieronRollover+'" width="40" alt="" />';
			htmlOut +='            '+ datos.items[i]['nombre'] +'';
			htmlOut +='        </a>';
			htmlOut +='    </div>';
		}
		$('#contenedor-items').html( htmlOut );
		
		if( cuantosItems < 6 ){
			guardarQuienesVieron(relacionados_pais);
		}else{
			var valorRandom = Math.floor(Math.random()*(_VAR_LAMP_UNO_IMPACTA_SOBRE+1));
			if( valorRandom == 1 ) guardarQuienesVieron(relacionados_pais);
		}
		
	}else{
		guardarQuienesVieron(relacionados_pais); // Sin contenido
	}
}
function callbackQuienLeyo(datos) {
	if( datos.errornum == '100' ){
		var htmlOut = '';
		var cuantosItems = 0;
		for( var i in datos.items ){
			cuantosItems++;
			title = datos.items[i]['nombre'];
			if( title.length > 37 ) title = title.substr(0,37) + '...';
			htmlOut +='    <div class="item-rel">';
			htmlOut +='        <div class="item-rel-img">';
			htmlOut +='            <a href="'+ datos.items[i]['url'] +'" title="'+ datos.items[i]['nombre'] +'"><img src="'+ datos.items[i]['imagen'] +'" alt="'+ datos.items[i]['nombre'] +'" /></a>';
			htmlOut +='        </div><div class="item-rel-n">';
			htmlOut +='        <a href="'+ datos.items[i]['url'] +'" title="'+ datos.items[i]['nombre'] +'">';
			htmlOut +='            '+ title +'';
			htmlOut +='        </a></div>';
			htmlOut +='    </div>';
		}
		$('#quien-leyo-contenedor-items').html( htmlOut );

		if( cuantosItems < 6 ){
			guardarQuienesVieron(relacionados_pais);
		}else{
			var valorRandom = Math.floor(Math.random()*(_VAR_LAMP_UNO_IMPACTA_SOBRE+1));
			if( valorRandom == 1 ) guardarQuienesVieron(relacionados_pais);
		}		
	}else{
		guardarQuienesVieron(relacionados_pais); // Sin contenido
	}
}
/*
 * MODAL ERROR BOX
 */
function setErrorBox(str,append){
	if( append == 1 ){
		$('#errorBoxCenterStr').append('<br>'+str);
	}else{
		$('#errorBoxCenterStr').html(''+str);
		if( str != '' ) mostrarErrorBox();
	}
	return false;
}
function mostrarErrorBox(){
	$('.notificarBox').animate({'top':'-600px'},500,function(){$('.notificarBoxOverlay').fadeOut('fast');});
	$('.errorBoxOverlay').fadeIn('fast',function(){
		$('#errorBoxLayer').animate({'top':'100px'},500);
	});
}

/*
 * MODAL NOTIFICAR BOX
 */
function setNotificarBox(str,append){
	if( append == 1 ){
		$('#notificarBoxCenterStr').append('<br>'+str);
	}else{
		$('#notificarBoxCenterStr').html(''+str);
		if( str != '' ) mostrarNotificarBox();
	}
	return false;
}
function mostrarNotificarBox(){
	$('.errorBox').animate({'top':'-600px'},500,function(){$('.errorBoxOverlay').fadeOut('fast');});
	$('.notificarBoxOverlay').fadeIn('fast',function(){
		$('#notificarBoxLayer').animate({'top':'100px'},500);
	});
}
/*
 * Ocultar boxs
 */
 
function ocultarBoxs(){
	setErrorBox('',0);
	setNotificarBox('',0);
	$('.errorBoxLayer').animate({'top':'-600px'},500,function(){$('.errorBoxOverlay').fadeOut('fast');});
	$('.notificarBoxLayer').animate({'top':'-600px'},500,function(){$('.notificarBoxOverlay').fadeOut('fast');});
}




function in_array(array,elemento){
	for(var i in array){ if(array[i]==elemento) return true;}
	return false;
}
function fechapartesvalidas(dia, mes, ano, nombre){val=parseInt(dia.value,10)+'-'+parseInt(mes.value,10)+'-'+parseInt(ano.value,10); dr=/^[ ]*[0]?(\d{1,2})[-\/\\](\d{1,2})[-\/\\](\d{4,})[ ]*$/; mc=val.match(dr);if (mc){ var td=new Date(mc[3],parseInt(mc[2])-1,mc[1]);	if (td.getDate()==parseInt(mc[1]) && td.getFullYear()==parseInt(mc[3]) && (td.getMonth()+1)==parseInt(mc[2])) return"";} return "\n* "+nombre+' es inválido.'}
function fechavalida(obj,nombre){val=obj.value; dr=/^[ ]*[0]?(\d{1,2})[-\/\\](\d{1,2})[-\/\\](\d{4,})[ ]*$/; mc=val.match(dr);if (mc){ var td=new Date(mc[3],parseInt(mc[2])-1,mc[1]); if (td.getDate()==parseInt(mc[1]) && td.getFullYear()==parseInt(mc[3]) && (td.getMonth()+1)==parseInt(mc[2])) return"";} return "\n* "+nombre+' es inválido.'}
function getEdad(anio,mes,dia){hoy=new Date();nacido=new Date(anio,mes-1,dia);if(nacido == 'Invalid Date')return -1;tiempo=hoy-nacido;unanio=1000*60*60*24*365;; tienes=parseInt(tiempo/unanio,10);return tienes;}
function soloNum( evento ){var key = evento.which || evento.keyCode; return (key <= 13 || key == 8 || (key >= 48 && key <= 57));}


/*
 * TOPHAT / BASE
 * 
*/

function topHatCargarHeaderLogin(){
	KIDS_TOPHAT_tokenUsuarioPadre = readCookie("KIDS_TOPHAT_tokenUsuarioPadre") || "";
	KIDS_TOPHAT_codigoUsuarioPadre = readCookie("KIDS_TOPHAT_codigoUsuarioPadre") || "";
	KIDS_TOPHAT_nombreUsuarioPadre = readCookie("KIDS_TOPHAT_nombreUsuarioPadre") || "";
	
	KIDS_TOPHAT_tokenUsuarioHijo = readCookie("KIDS_TOPHAT_tokenUsuarioHijo") || "";
	KIDS_TOPHAT_codigoUsuarioHijo = readCookie("KIDS_TOPHAT_codigoUsuarioHijo") || "";
	KIDS_TOPHAT_nombreUsuarioHijo = readCookie("KIDS_TOPHAT_nombreUsuarioHijo") || "";
	KIDS_TOPHAT_imagen40x40UsuarioHijo = readCookie("KIDS_TOPHAT_imagen40x40UsuarioHijo") || "";

	
	if( KIDS_TOPHAT_tokenUsuarioPadre == "" || KIDS_TOPHAT_codigoUsuarioPadre == "" || KIDS_TOPHAT_nombreUsuarioPadre == "" ){
		$('#contenedor_login_ok').hide();
		
		if( mostrarTOPHAT == 1 ){
			$('#contenedor_login_ko').show();
		}else{
			$('#contenedor_login_ko').remove();
		}
		$('#contenedor_login_usuario').html('');
	}else{
		
		if( mostrarTOPHAT == 1 ) $('#contenedor_login_ok').show();
		else $('#contenedor_login_ok').remove();
		
		$('#contenedor_login_ko').hide();
		$('#contenedor_login_usuario').html(KIDS_TOPHAT_nombreUsuarioPadre);

		//Contenedor hijo
		if( KIDS_TOPHAT_tokenUsuarioHijo == "" || KIDS_TOPHAT_codigoUsuarioHijo == "" || KIDS_TOPHAT_nombreUsuarioHijo == "" ){
			$('#contenedor_login_hijo_ok').hide();
			$('#contenedor_login_hijo_ko').show();
			$('.contenedor_bt_cambiar').hide();
			$('#contenedor_login_usuario_hijo').html(KIDS_TOPHAT_nombreUsuarioHijo);
		}else{
			$('#contenedor_login_hijo_ok').show();
			$('#contenedor_login_hijo_ko').hide();
			$('#contenedor_login_usuario_hijo').html(KIDS_TOPHAT_nombreUsuarioHijo);
			if( KIDS_TOPHAT_imagen40x40UsuarioHijo != '' ) {
				$('#contenedor_login_src_avatar').attr('src',KIDS_TOPHAT_imagen40x40UsuarioHijo);
				//alert(KIDS_TOPHAT_imagen40x40UsuarioHijo);
			}
		}
	}
}
function topHatLogout(){
	writeCookie("KIDS_TOPHAT_codigoUsuarioPadre", "", null, "/");

	writeCookie("KIDS_TOPHAT_CASTGCUsuarioPadre", "", null, "/");

	writeCookie("KIDS_TOPHAT_tokenUsuarioPadre", "", null, "/");

	writeCookie("KIDS_TOPHAT_nombreUsuarioPadre", "", null, "/");

	writeCookie("KIDS_TOPHAT_hijosUsuarioPadre", "", null, "/");	

	writeCookie("KIDS_TOPHAT_codigoUsuarioHijo", "", null, "/");

	writeCookie("KIDS_TOPHAT_nombreUsuarioHijo", "", null, "/");			

	writeCookie("KIDS_TOPHAT_tokenUsuarioHijo", "", null, "/");

	//topHatCargarHeaderLogin();

	writeCookie("KIDS_TOPHAT_return", null, null, "/");

	location.href='/users/login.shtml';
}
function topHatPreload(){
	return true;
}
$(document).ready(function(){
	topHatCargarHeaderLogin();
});


/*
 * NAV
*/
NavegacionPersonaje_items = new Array();
NavegacionPersonaje_totalItems = 0;
function initNavegacionPersonajes(){
	NavegacionPersonaje_iItems = 0;
	$('#carousel-personajes-v2 li').each(function(){
		NavegacionPersonaje_items[NavegacionPersonaje_iItems] = $(this).html();
		NavegacionPersonaje_iItems++;
		NavegacionPersonaje_totalItems++;
	});
	NavegacionPersonaje_iNav = 0;
	$('.slide-personajes div[class="items"]').each(function(){
		$(this).html(NavegacionPersonaje_items[NavegacionPersonaje_iNav]);
		NavegacionPersonaje_iNav++;
	});
}
function nextNavegacionPersonajes(){
	array_tmp = new Array();
	for(i=-1;i<(NavegacionPersonaje_totalItems-1);i++){ 
		array_tmp[i] = NavegacionPersonaje_items[i+1];
	};
	array_tmp[NavegacionPersonaje_totalItems-1] = array_tmp[-1];
	NavegacionPersonaje_items = array_tmp;
	NavegacionPersonaje_iNav = 0;
	$('.slide-personajes div[class="items"]').each(function(){
		$(this).html(NavegacionPersonaje_items[NavegacionPersonaje_iNav]);
		NavegacionPersonaje_iNav++;
	});
}
function previousNavegacionPersonajes(){
	array_tmp = new Array();
	for(i=0;i<NavegacionPersonaje_totalItems-1;i++){
		array_tmp[i+1] = NavegacionPersonaje_items[i];
	}
	array_tmp[0] = NavegacionPersonaje_items[NavegacionPersonaje_totalItems-1];
	NavegacionPersonaje_items = array_tmp;
	NavegacionPersonaje_iNav = 0;
	$('.slide-personajes div[class="items"]').each(function(){
		$(this).html(NavegacionPersonaje_items[NavegacionPersonaje_iNav]);
		NavegacionPersonaje_iNav++;
	});
}
function popup(url,ancho,alto,id,extras){
	if(navigator.userAgent.indexOf("Mac")>0){ancho=ancho+15;alto=alto+15;}
	var left = (screen.availWidth-ancho)/2;
	var top = (screen.availHeight-alto)/2;
	if(extras!=""){extras=","+extras;};
	eval(" f = window.open('"+url+"','"+id+"','width="+ancho+",height="+alto+",left="+left+",top="+top+",screenX="+left+",screenY="+top+extras+"'); f.focus();");
}
/*Scripts.js general del site anterior*/
function preload(){
	$('#contenido_preload').hide('fast',function(){
		$('#contenido').show();
		}
	);
	$('#contenedor_todo_preload').hide('fast',function(){
		$('#contenido').show();
		$('#contenido_preload').remove();
		}
	);
}
function mostrar_msj_error(obj_id){
	$('#'+obj_id).show(); 
}
function ocultar_msj_error(obj_id){
	$('#'+obj_id).hide(); 
}
function ocultar_msjs_error(){
	$('.label_mensajes_errores').hide(); 
}
function capitalize(str){ words = str.split(" ");for (i=0 ; i < words.length ; i++){testwd = words[i];firLet = testwd.substr(0,1); testwd.substr(0,1); rest = testwd.substr(1, testwd.length -1); words[i] = firLet.toUpperCase() + rest ; } return words.join(" "); }

function padresReportes_irAMisHijosYVolver(){
	writeCookie("MisHijos_DondeVolver", location.href, null, "/");
	writeCookie("KIDS_TOPHAT_return", location.href, null, "/");
	writeCookie("KIDS_TOPHAT_return_nombre", 'Área Padres > Reportes', null, "/");
	location.href = '/users/hijos.shtml';
}
function padresReportes_ValidarHijo(){
	var hijos = readCookie("KIDS_TOPHAT_hijosUsuarioPadre") || "";	
	var hijoActual = readCookie("KIDS_TOPHAT_codigoUsuarioHijo") || "";	
	var nombreHijoActual = '';
	arrayHijos1 = hijos.split(',');
	tieneHijosActual = 0;
	cuantosHijos = arrayHijos1.length;
	for( i=0; i<cuantosHijos; i++){ 
		arrayHijos2 = arrayHijos1[i].split('|');
		if( arrayHijos2.length >= 5 ){
			if( arrayHijos2[2].length == 32 ){
				if( hijoActual == arrayHijos2[0] ){
					nombreHijoActual = arrayHijos2[1];
					tieneHijosActual = 1;
				}
			}
		}
	}
	
	if( tieneHijosActual == 0 ){
		padresReportes_irAMisHijosYVolver();
	}else{
		$(document).ready(function(){$('#reportes_nombre_hijo').html(nombreHijoActual);});
	}
}

function normalizeUrlToProduction(url){
	url = url.replace('nkotb2.discovery.noblinktv/','www.tudiscoverykids.com/');
	url = url.replace('nkotb2.discovery.noblinktv.com.ar/','www.tudiscoverykids.com/');
	url = url.replace('www-tudiscoverykids-com.discoveryisispreview.com/','www.tudiscoverykids.com/');
	url = url.replace('origin-www-tudiscoverykids-com.discoveryisispreview.com/','www.tudiscoverykids.com/');

	url = url.replace('brasil.nkotb2.discovery.noblinktv/','discoverykidsbrasil.uol.com.br/');
	url = url.replace('brasil.nkotb2.discovery.noblinktv.com.ar/','discoverykidsbrasil.uol.com.br/');
	url = url.replace('discoverykidsbrasil-preprod.uol.com.br/','www.tudiscoverykids.com/');
	url = url.replace('origin-discoverykidsbrasil-preprod.uol.com.br/','www.tudiscoverykids.com/');

	return url;
}

var logReportGame_i = 0;
function logReportGame(debug){
	var usuario = readCookie('KIDS_TOPHAT_codigoUsuarioPadre') || "";
	var hijoActual = readCookie("KIDS_TOPHAT_codigoUsuarioHijo") || "";	
	if( usuario != '' && hijoActual != '' ){
		if( yaPidioKeywordItemActual == 0 ){
			++logReportGame_i;
			if( logReportGame_i < 5 ) setTimeout('logReportGame()',1000);
		}else{
			var contenido = normalizeUrlToProduction(location.href);
			//País e idioma están setteados en scripts.js
			var sexo = readCookie('KIDS_TOPHAT_sexoUsuarioHijo') || "";
			var nacimiento = readCookie('KIDS_TOPHAT_nacimientoUsuarioHijo') || "";
			var edad = 0;
			if( nacimiento.length == 10 ){
				fechaArray = nacimiento.split('-');
				edad = getEdad(fechaArray[0],fechaArray[1],fechaArray[2]);
				
			}
			if( typeof(debug) != "undefined" && debug == 1 ) console.log(KIDS_WS_LOG_REPORT + 'save-game.php?padre='+escape(usuario)+'&hijo='+escape(hijoActual)+'&contenido='+escape(contenido)+'&categoria='+escape(keywordItemActual)+'&idioma='+escape(idioma)+'&pais='+escape(pais)+'&sexo='+escape(sexo)+'&edad='+escape(edad)+'&jsoncallback=?');
			$.getJSON( KIDS_WS_LOG_REPORT + 'save-game.php?padre='+escape(usuario)+'&hijo='+escape(hijoActual)+'&contenido='+escape(contenido)+'&categoria='+escape(keywordItemActual)+'&idioma='+escape(idioma)+'&pais='+escape(pais)+'&sexo='+escape(sexo)+'&edad='+escape(edad)+'&jsoncallback=?');
		}
	}
}
