DBHOST_URL = 'http://origin-apps.tudiscoverykids.com/youtube/';
//DBHOST_URL = 'http://admin.nkotb.discovery.bhdm.com.ar/PHPFRONT/ponle_un_final_al_cuento/';
idioma = 1;
seccion = ''; //reseteada en donde es necesario, ej, index.shtml
/*
//DEBUG
writeCookie("usuario", "", null, "/");
writeCookie("token", "", null, "/");
*/

totalEtapas = new Array();
totalEtapas[2] = 62;
totalEtapas[4] = 62;
totalEtapas[8] = 62;
totalEtapas[16] = 62;

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;
    }
  } 
}
/*
EJ:
$(document).ready(function(){
	seguridad('listarVideos()');
})
*/

function validarRegionYEtapa(video, region, etapa){
	/*totalEtapas = totalEtapas[region];
	$.getJSON( DBHOST_URL + 'validar_si_puede_juegar_etapa.php?video='+video+'&region='+region+'&etapa='+etapa+'&totalEtapas='+totalEtapas+'&token='+escape(token)+'&jsoncallback=?', function(datos){
		if( datos.ok == '0' ) location.href = '/ponle_un_final_al_cuento/?No_puede_jugar_este_juego';
		else return true;
	});
	*/
}
function seguridad( verificar_youtube ){
	var token = getCookieToken();
	if( token == "" ){
		location.href = '/ponle_un_final_al_cuento/login.shtml?return='+escape(location.href);
		return false;
	}	
	$.getJSON( DBHOST_URL + 'esta_logueado.php?token='+escape(token)+'&jsoncallback=?', function(datos){
		if( datos.errornum == '400' ) location.href = '/ponle_un_final_al_cuento/login.shtml';
		writeCookie("usuario", datos.codigo, null, "/");
		writeCookie("usuarioNombre", datos.displayname, null, "/");
		writeCookie("usuarioVideos", datos.videos, null, "/");		
		//$(document).ready(function(){$('#contenedor_header_nombre_usuario').html(datos.displayname);})
		if(verificar_youtube==1) chequear_youtube();
		return true;
		//if( callback != '' ) eval(callback);
	});
	return true;
}

function preload(){
	$('#contenido_preload').hide('fast',function(){
		$('#contenido').show();
		}
	);	
}

function chequear_youtube(){
	var yt_token = readCookie('yt_token') || '';
	var yt_user = readCookie('yt_user') || '';
	if( yt_token == '' || yt_user == ''){
		$(document).ready(function(){location.href = 'https://www.google.com/accounts/AuthSubRequest?next=http%3A%2F%2Fapps.tudiscoverykids.com%2Fyoutube%2Fget_token.php&scope=https://gdata.youtube.com&secure=1&session=1';})
		//$(document).ready(function(){location.href = 'https://www.google.com/accounts/AuthSubRequest?next=http%3A%2F%2Fadmin.nkotb.discovery.bhdm.com.ar%2FPHPFRONT%2Fponle_un_final_al_cuento%2Fget_token.php&scope=http://gdata.youtube.com&secure=1&session=1';})
	}
}


function getCookieToken(){
	token = readCookie('CASTGC') || "";
	if( token == 'none' || token == '' ) return '';
	token = unescape(token);
	token = token.replace(/\#\w*/gi, '');
	token = token.replace(/\#\%23*/gi, '');
//	alert(token)
	return token;
}

function login(email, password, returnPath){
	$.getJSON( DBHOST_URL + 'login.php?email='+ escape(email) +'&password='+ escape(password) +'&jsoncallback=?', function(datos){
		if( datos.errornum == '400' ){
			ocultar_msj_error('login_preload_label');
			mostrar_msj_error('login_no_usuario_label');
		}
		if( datos.errornum == '100' ){
			writeCookie("usuario", datos.codigo, null, "/");
			writeCookie("CASTGC", datos.token, null, "/");
			writeCookie("usuarioNombre", datos.displayname, null, "/");
			writeCookie("usuarioVideos", datos.videos, null, "/");	
			if(returnPath=='' || returnPath=='undefined'){
				location.href = 'index.shtml';
			}else{
				location.href = returnPath;	
			}
		}
	});
}

function registrar(displayname, password, nombre, apellido, sexo, email, pais, optins, optout){
	$.getJSON( DBHOST_URL + 'registrar.php?nombre='+escape(nombre)+'&apellido='+escape(apellido)+'&sexo='+escape(sexo)+'&email='+escape(email)+'&pais='+escape(pais)+'&displayname='+escape(displayname)+'&password='+escape(password)+'&jsoncallback=?', function(datos){
		if( datos.errornum == '400' ){
			ocultar_msj_error('formulario_preload_label');
			$('#formulario_no_usuario_label').html(datos.error);
			//$('#formulario_no_usuario_label').html(datos.error+'<hr>'+datos.url);	
			mostrar_msj_error('formulario_no_usuario_label');
		}
		
		//alert(datos.codigo+'-'+datos.token);
		if( datos.errornum == '100' ){
			writeCookie("usuario", datos.codigo, null, "/");
			writeCookie("CASTGC", datos.token, null, "/");
			writeCookie("usuarioNombre", datos.displayname, null, "/");
			writeCookie("usuarioVideos", ',0,', null, "/");				
			location.href = 'cuento.shtml?r=gRf3'+datos.token+'S23t-w21'; //Rand
		}
	});
}
function logout(){
	var usuario = readCookie('usuario') || "";
	var token = getCookieToken();
	if( usuario == "" || token == "" ){
		location.href = '/ponle_un_final_al_cuento/login.shtml';
		return true;
	}
	$.getJSON( DBHOST_URL + 'logout.php?usuario='+escape(usuario)+'&token='+escape(token)+'&jsoncallback=?', function(datos){
		//if( datos.errornum == '300' )
		deleteCookie("usuarioNombre", "", "/");
		deleteCookie("usuarioVideos", "", "/");
		deleteCookie("usuario", "", "/");
		deleteCookie("CASTGC", "none", "/");
		location.href = '/ponle_un_final_al_cuento/login.shtml';
		return true;
	});
}
function deleteCookie(name, value, path){
	var domain = document.domain;
	expire = "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = name + "=" + escape(value) + expire + "; path=" + path + "; domain=" + domain;
}

function listarVideos(cuento, pagina){
	$('#contenedor_videos').html( '<center><img src="/ponle_un_final_al_cuento/images/preload.gif" width="32" height="32" vspace="80"></center>' );
	$.getJSON( DBHOST_URL + 'videos_listar.php?cuento='+cuento+'&pagina='+pagina+'&jsoncallback=?', function(datos){
		if( datos.errornum == '400' ){
			var mensaje = $('#mensaje_sin_videos').html();
			//$('#contenido_videos').html( mensaje );	
			$('#contenido_videos').html( '' );		
		}
		paginaStr = new String(self.location);
		if( paginaStr.indexOf("cuento.shtml") == -1 ){
			html = '<table width="670" align="center" border="0" cellpadding="0" cellspacing="0" ><tr><td><img src="/ponle_un_final_al_cuento/images/tit_otros_finales.gif" vspace="14"><div style="clear:both"></div>';
		}else{
			html = '<table width="670" align="center" border="0" cellpadding="0" cellspacing="0" ><tr><td><img src="/ponle_un_final_al_cuento/images/tit_finales.gif" vspace="14"><div style="clear:both"></div>';	
		}
		var hayContenidos = 0;
		for(var i in datos.videos){
			hayContenidos = 1;
			//html += '<div style="width:120px; margin-right:10px; float:left;"><a id="video-url-'+datos.videos[i]['video']+'" href="final.html?cuento='+cuento+'&final='+datos.videos[i]['video']+'&feature=featured"><img title="" src="http://i1.ytimg.com/vi/'+datos.videos[i]['video']+'/default.jpg" class="vimg120" qlicon="'+datos.videos[i]['video']+'" alt="">'+datos.videos[i]['duracion']+' seg | '+datos.videos[i]['titulo']+'</a></div>';
			
			html +='<div style="width:320px; margin-right:10px; margin-bottom:15px; float:left;"><table width="275" border="0" cellpadding="0" cellspacing="0" ><tr><td width="80"><div style="width:120px; height:72px; border:1px solid #999999; padding:1px;"><div style="width:120px; height:72px; overflow:hidden;"><a href="final.shtml?cuento='+datos.videos[i]['cuento']+'&final='+datos.videos[i]['id']+'"><img src="http://i3.ytimg.com/vi/'+datos.videos[i]['video']+'/default.jpg" width="120" border="0"></a></div></div></td>';
			html +='<td width="10"><img src="/images/1x1.gif" width="10"></td>';
			html +='<td style="color:#FFFFFF; font-size:12px!important; font-weight:normal!important;" valign="top">';
			html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.videos[i]['cuento']+'&final='+datos.videos[i]['id']+'" style="color:#636363!important;"><strong>'+datos.videos[i]['titulo']+'</strong></a></div>';
			html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.videos[i]['cuento']+'&final='+datos.videos[i]['id']+'" style="color:#636363!important;">'+datos.videos[i]['nombre_hijo']+'</a></div>';
			html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.videos[i]['cuento']+'&final='+datos.videos[i]['id']+'" style="color:#636363!important;">'+datos.videos[i]['pais']+'</a></div>';
			html +='<a href="final.shtml?cuento='+datos.videos[i]['cuento']+'&final='+datos.videos[i]['id']+'" style="color:#636363!important;">'+datos.videos[i]['duracion']+'</a>';
			html +='</td></tr></table></div>';	
	
		}



		html += '</td></tr></table><div style="clear:both; height:10px;"></div><table width="676" border="0" cellspacing="0" cellpadding="0" align="center"><tr>';
	
		if( pagina > 1 ) html += '<td width="50%"><a href="javascript:listarVideos('+cuento+','+(pagina-1)+')"><img src="/ponle_un_final_al_cuento/images/bt_anterior.gif" width="83" height="14" alt="Anterior" title="Anterior" border="0" /></a></td>';
		else html += '<td width="50%"><img src="/ponle_un_final_al_cuento/images/bt_anterior_off.gif" width="83" height="14" alt="Anterior" title="Anterior" border="0" /></td>';
		
		if( pagina < datos.paginas ) html += '<td width="50%" align="right"><a href="javascript:listarVideos('+cuento+','+(pagina+1)+')"><img src="/ponle_un_final_al_cuento/images/bt_siguiente.gif" width="87" height="14" alt="Siguiente" title="Siguiente" border="0" /></a></td>';
		else html += '<td width="50%" align="right"><img src="/ponle_un_final_al_cuento/images/bt_siguiente_off.gif" width="87" height="14" alt="Siguiente" title="Siguiente" border="0" /></td>';
		
		html += '</tr></table><div style="clear:both; height:10px;"></div>';
		
		
		if( hayContenidos == 1 ) $('#contenedor_videos').html( html );	
		//else  $('#contenedor_videos').html( 'No hay finales a este cuento' );	
		else  $('#contenedor_videos').html( '' );	
	});
}

function listarVideosTop15MejorRankeados(){
	$('#contenedor_videos').html( '<center><img src="/ponle_un_final_al_cuento/images/preload.gif" width="32" height="32" vspace="80"></center>' );
	$.getJSON( DBHOST_URL + 'mejor_rankeados_listar.php?idioma='+idioma+'&jsoncallback=?', function(datos){
		if( datos.errornum == '400' ){
			var mensaje = $('#mensaje_sin_videos').html();
			$('#contenido_videos').html( '' );		
		}
		
		


		var hayContenidos = 0;
		var iCuantos = 0;
		for(var i in datos.items){
			hayContenidos = 1;
			iCuantos++;
			if( iCuantos == 1 ){
				html = '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/'+datos.items[i]['video']+'&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+datos.items[i]['video']+'&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>';
				$('#contenedor_video').html(html); 
				$('#breadcrumb_final').html(datos.items[i]['titulo']); 
				hastaVotado = datos.items[i]['contador'];
				setearDespintarRank();
				html = '<table width="670" align="center" border="0" cellpadding="0" cellspacing="0" ><tr><td><img src="/ponle_un_final_al_cuento/images/tit_otros_finales.gif" vspace="14"><div style="clear:both"></div>';
			}else{
				html +='<div style="width:320px; margin-right:10px; margin-bottom:15px; float:left;"><table width="275" border="0" cellpadding="0" cellspacing="0" ><tr><td width="80"><div style="width:120px; height:72px; border:1px solid #999999; padding:1px;"><div style="width:120px; height:72px; overflow:hidden;"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'"><img src="http://i3.ytimg.com/vi/'+datos.items[i]['video']+'/default.jpg" width="120" border="0"></a></div></div></td>';
				html +='<td width="10"><img src="/images/1x1.gif" width="10"></td>';
				html +='<td style="color:#FFFFFF; font-size:12px!important; font-weight:normal!important;" valign="top">';
				html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#636363!important;"><strong>'+datos.items[i]['titulo']+'</strong></a></div>';
				html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#636363!important;">'+datos.items[i]['nombre_hijo']+'</a></div>';
				html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#636363!important;">'+datos.items[i]['pais']+'</a></div>';
				html +='<a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#636363!important;">'+datos.items[i]['duracion']+'</a>';
				html +='</td></tr></table></div>';	
			}
	
		}



		html += '</td></tr></table><div style="clear:both; height:10px;"></div>';
		
		
		if( hayContenidos == 1 ) $('#contenedor_videos').html( html );	
		//else  $('#contenedor_videos').html( 'No hay finales a este cuento' );	
		else  $('#contenedor_videos').html( '' );	
	});
}

function eliminarVideo(video, nombre){
	var mensaje = $('#mensaje_borrar_video').html();	
	mensaje = mensaje.replace('%nombre%',nombre);
	if( confirm(mensaje) ){  
		var usuario = readCookie('usuario');
		var token = getCookieToken();
		$.getJSON( DBHOST_URL + 'videos_borrar.php?video='+escape(video)+'&usuario='+escape(usuario)+'&token='+escape(token)+'&jsoncallback=?', function(datos){
			if( datos.errornum == '100' ){
				location.href = 'index.shtml';
			}
		});
	}else{
		return false;	
	}
}
function agregarVideo(videoId, videoTitulo, videoDuracion, nombreHijo, cuentoId){
	var usuario = readCookie('usuario');
	var pais = readCookie('pais');
	var token = getCookieToken();
//	$.getJSON( DBHOST_URL + 'videos_registrar.php?usuario='+escape(usuario)+'&token='+escape(token)+'&nombre='+escape(nombre)+'&avatar='+escape(avatar)+'&edad='+escape(edad)+'&sexo='+escape(sexo)+'&optins='+escape(optins)+'&optout='+escape(optout)+'&jsoncallback=?', function(datos){
	
	$('#tabla_form_video').hide();
	$('#tabla_form_video_preload').show();
	
	$.getJSON( DBHOST_URL + 'video_registrar.php?video='+escape(videoId)+'&duracion='+escape(videoDuracion)+'&titulo='+escape(videoTitulo)+'&nombre_hijo='+escape(nombreHijo)+'&usuario='+escape(usuario)+'&token='+escape(token)+'&cuento='+escape(cuentoId)+'&jsoncallback=?', function(datos){
		if( datos.errornum == '100' ){
			$('#tabla_form_video_preload').hide();
			$('#tabla_form_video_gracias').show();
		}
		
		if( datos.errornum == '300' ){
			$('#tabla_form_video_preload').hide();
			$('#tabla_form_video_gracias').show();
			//$('#tabla_form_video_repetido').show();
		}
	});
}
function modificarVideo(video, nombre, edad, avatar, sexo ){
	var usuario = readCookie('usuario');
	var pais = readCookie('pais');
	var token = getCookieToken();
	$.getJSON( DBHOST_URL + 'videos_actualizar.php?pais='+escape(pais)+'&video='+escape(video)+'&usuario='+escape(usuario)+'&token='+escape(token)+'&nombre='+escape(nombre)+'&avatar='+escape(avatar)+'&edad='+escape(edad)+'&sexo='+escape(sexo)+'&jsoncallback=?', function(datos){
		if( datos.errornum == '400' ){
			ocultar_msj_error('formulario_preload_label');
			mostrar_msj_error('formulario_no_usuario_label');
		}
		if( datos.errornum == '100' ){
			ocultar_msj_error('formulario_contenido');
			var html = $('#formulario_usuario_ok').html();
			html = html.replace('%usuario%',nombre);
			$('#formulario_usuario_ok').html( html );
			mostrar_msj_error('formulario_usuario_ok');
			ocultar_msj_error('formulario_contenido');
			ocultar_msj_error('formulario_preload_label');
		}
	});
}
function setearValores(video){
	var usuario = readCookie('usuario');
	var token = getCookieToken();
	$.getJSON( DBHOST_URL + 'videos_listar.php?usuario='+escape(usuario)+'&token='+escape(token)+'&jsoncallback=?', function(datos){
		if( datos.errornum == '300' ) location.href = '/ponle_un_final_al_cuento/login.shtml';
		if( datos.errornum == '400' ){
			var mensaje = $('#mensaje_sin_videos').html();
			//$('#contenido_videos').html( mensaje );	
			$('#contenido_videos').html( '' );	
		}
		var html = '';
		var existeVideo = 0;
		for(var i in datos.videos){
			if( datos.videos[i]['codigo'] == video ){
				existeVideo = 1;
				$('#nombre').val(datos.videos[i]['nombre']);
				$("#sexo").children("option[@value="+datos.videos[i]['sexo']+"]").attr("selected",true);
				$("#edad").children("option[@value="+datos.videos[i]['edad']+"]").attr("selected",true);
			}
		}
		if( existeVideo == 0 ) location.href = 'index.shtml';
	});
}


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 getVideosMejorRankeados(){
	//$('#contenedor_videos_mejor_rankeados').html('<center><br /><br /><br /><img src="/ponle_un_final_al_cuento/images/preload_verde.gif" /></center>'); 
	$.getJSON( DBHOST_URL + 'mejor_rankeados_listar.php?idioma='+idioma+'&jsoncallback=?', function(datos){
		var html = '<table width="275" border="0" cellpadding="0" cellspacing="0" >';

		for(var i in datos.items){
			html +='<tr><td width="80" height="54"><div style="width:80px; height:48px; overflow:hidden;"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'"><img src="http://i3.ytimg.com/vi/'+datos.items[i]['video']+'/default.jpg" width="80" border="0"></a></div></td>';
			html +='<td width="10"><img src="/images/1x1.gif" width="10"></td>';
			html +='<td style="color:#FFFFFF; font-size:12px!important; font-weight:normal!important;">';
			html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#FFF!important;"><strong>'+datos.items[i]['titulo']+'</strong></a></div>';
			html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#FFF!important;">'+datos.items[i]['nombre_hijo']+'</a></div>';
			html +='<a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#FFF!important;">'+datos.items[i]['duracion']+'</a>';
			html +='</td></tr>';
		}
		html += '</table>';
		$('#contenedor_videos_mejor_rankeados').html(html); 
	});
}

function getVideosMasVistos(){
	//$('#contenedor_videos_mas_vistos').html('<center><br /><br /><br /><img src="/ponle_un_final_al_cuento/images/preload_verde.gif" /></center>'); 
	$.getJSON( DBHOST_URL + 'mas_vistos_listar.php?idioma='+idioma+'&jsoncallback=?', function(datos){
		var html = '<table width="208" border="0" cellpadding="0" cellspacing="0" >';

		for(var i in datos.items){
			html +='<tr><td width="80" height="54"><div style="width:80px; height:48px; overflow:hidden;"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'"><img src="http://i3.ytimg.com/vi/'+datos.items[i]['video']+'/default.jpg" width="80" border="0"></a></div></td>';
			html +='<td width="10"><img src="/images/1x1.gif" width="10"></td>';
			html +='<td style="color:#636363; font-size:12px!important; font-weight:normal!important;">';
			html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#636363!important;"><strong>'+datos.items[i]['titulo']+'</strong></a></div>';
			html +='<div style="height:16px; overflow:hidden"><a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#636363!important;">'+datos.items[i]['nombre_hijo']+'</a></div>';
			html +='<a href="final.shtml?cuento='+datos.items[i]['cuento']+'&final='+datos.items[i]['id']+'" style="color:#636363!important;">'+datos.items[i]['duracion']+'</a>';
			html +='</td></tr>';
		}
		html += '</table>';
		$('#contenedor_videos_mas_vistos').html(html); 
	});
}

function getCuentosListado(){
	//html = '<center><a href="/ponle_un_final_al_cuento/cuento.shtml?cuento=1"><img src="/ponle_un_final_al_cuento/images/cuentos_th_1_lanzamiento.jpg" width="696" height="119" border="0"></a><div style="height:20px; clear:both;"></div></center>';
	
	//html = '<center><img src="/ponle_un_final_al_cuento/images/destacado_2cuentos.gif" width="696" height="120" border="0" usemap="#MapImagenCuentos"><map name="MapImagenCuentos"><area shape="rect" coords="11,4,323,117" href="/ponle_un_final_al_cuento/cuento.shtml?cuento=1"><area shape="rect" coords="381,4,689,117" href="/ponle_un_final_al_cuento/cuento.shtml?cuento=2"></map><div style="height:20px; clear:both;"></div></center>';
	//$('#contenedor_cuentos').html(html); 
	//return true; // Lanzamiento
	
	$.ajax({
		type: "GET",
		url: "xml/cuentos.xml",
		dataType: "xml",
		success: function(xml) {
			html = '<table width="698" align="center" border="0" cellpadding="0" cellspacing="0"><tr>';
			var i = 0;
			$(xml).find('cuento').each(function(){
				i++;							
				var cuentoId = $(this).attr('id');
				var nombre = $(this).attr('nombre')
				var th = $(this).attr('th')
				
				if( i == 1 ) alineacion = ' width="215" align="left" class="cuentosOff2" onmouseover="this.className=\'cuentosOn\'" onmouseout="this.className=\'cuentosOff2\'" style="padding-left:10px;" ';
				if( i == 2 ) alineacion = ' width="215" align="left" class="cuentosOff2" onmouseover="this.className=\'cuentosOn2\'" onmouseout="this.className=\'cuentosOff2\'" style="padding-left:38px;" ';
				if( i == 3 ) alineacion = ' width="182" class="cuentosOff" onmouseover="this.className=\'cuentosOn2\'" onmouseout="this.className=\'cuentosOff\'" style="padding-left:38px;" ';
				
				html += '<td '+alineacion+' valign="top" ><a href="cuento.shtml?cuento='+cuentoId+'"><img src="'+th+'" border="0"></a><br><div style="width:177px;"><a href="cuento.shtml?cuento='+cuentoId+'">'+nombre+'</a></div></td>';
				if( i == 3 ){
					i = 0;
					html += '</tr><tr><td colspan="3" height="20">&nbsp;</td></tr><tr>';
				}
			});
			html += '</tr></table>';
			$('#contenedor_cuentos').html(html); 
		}
	});
}


function getVideoDetalle(){
	var codigo = getQueryVariable('final') || '';
	if( codigo == '' ){ history.back(); return false;}
	var resultado = '';
	$.ajax({
	  url: DBHOST_URL + 'video_listar.php',
	  data: 'codigo='+escape(codigo)+'',
	  dataType: 'jsonp',
	  jsonp:'jsoncallback',
	  async: false,
	  success: function(datos){
		if( datos.errornum == '400' ){
			 location.href = 'index.shtml';
		}else{
			html = '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/'+datos.video+'&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+datos.video+'&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>';
			$('#contenedor_video').html(html); 
			$('#breadcrumb_final').html(datos.titulo); 
			hastaVotado = datos.ranking;
			setearDespintarRank();
		}		
	  }	  
	});	
	return resultado;
}
function getCuentoDetalle(cual){
	$.ajax({
		type: "GET",
		url: "xml/cuentos.xml",
		dataType: "xml",
		async:false,
		success: function(xml) {
			html = '';
			$(xml).find('cuento[id='+cual+']').each(function(){
				var video = $(this).contents('video').text();
				html = video;
			});
		
			$('#contenedor_cuento').html(html); 
			//document.writeln('<script language="JavaScript" type="text/javascript" src="http://admin.brightcove.com/js/BrightcoveExperiences.js"></'+'script>');
			//return false;		
			brightcove.createExperiences();
		}
	});
}
function breadcrumbCuento(cual){
	$.ajax({
		type: "GET",
		url: "xml/cuentos.xml",
		dataType: "xml",
		success: function(xml) {
			html = '';
			$(xml).find('cuento[id='+cual+']').each(function(){
				var cuentoId = $(this).attr('id');
				var nombre = $(this).attr('nombre');
				var th = $(this).attr('th');
				html += '<a href="/ponle_un_final_al_cuento/cuento.shtml?cuento='+cuentoId+'">'+nombre+'</a>';
			});
			$('#breadcrumb_cuento').html(html); 
		}
	});
}


/* Mas vistos mejor rankeados*/
function pintar( hasta ){
	$('#contenedor_star .imagen_star').attr({src: starOff});
	for(i=1;i<=hasta;++i){
		$('#contenedor_star #imagen_star_'+i).attr({src: starOn });
	}
}
function despintar(){
	for(i=1;i<=hasta;++i) $('#contenedor_star #imagen_star_'+i).attr({src: starOff });
	for(i=1;i<=hastaVotado;++i)	$('#contenedor_star #imagen_star_'+i).attr({src: starOn });
}
function votar(cuanto){
	var codigo = getQueryVariable('final') || '';
	if( codigo == '' ){ history.back(); return false;}	
	$('#contenedor_star').html('<img src="/ponle_un_final_al_cuento/images/tit_votar.gif" align="absmiddle"><img src="/ponle_un_final_al_cuento/images/rank_'+cuanto+'.gif" align="absmiddle"  />');
	//$.get('_ajax_votar.php?codigo='+cual+'&rating='+cuanto);
	$.getJSON( DBHOST_URL + 'mejor_rankeados_guardar.php?item='+ escape(codigo) +'&ranking='+ escape(cuanto) +'&idioma='+ escape(idioma) +'&jsoncallback=?', function(datos){} );
}
function masVistosGuardar(cuento){
	var codigo = getQueryVariable('final') || '';
	if( codigo == '' ){ history.back(); return false;}		
	//$('#contenedor_star').html('<img src="/ponle_un_final_al_cuento/images/tit_votar.gif" align="absmiddle"><img src="/ponle_un_final_al_cuento/images/rank_'+cuanto+'.gif" align="absmiddle"  />');
	//$.get('_ajax_votar.php?codigo='+cual+'&rating='+cuanto);
	$.getJSON( DBHOST_URL + 'mas_vistos_guardar.php?item='+ escape(codigo) +'&idioma='+ escape(idioma) +'&jsoncallback=?', function(datos){} );
}
function setearDespintarRank(){
	$(".contenedor_star").each(
		function(){
			$(this).hover(function(){return false;}, function (){despintar(hastaVotado);});
			despintar(hastaVotado);
		}
	);
}




function cargarVideosYoutube(pagina){
	var paginado = 10;
	//$('#contenedor_videos').html('Cargando...');
	$('#contenedor_videos').html( '<center><img src="/ponle_un_final_al_cuento/images/preload.gif" width="32" height="32" vspace="80"></center>' );
	
	//DBHOST_URL = 'http://apps.tudiscoverykids.com/youtube/';
	$.getJSON( DBHOST_URL + 'get_videos.php?token='+escape(yt_token)+'&user='+escape(yt_user)+'&pagina='+pagina+'&paginado='+paginado+'&jsoncallback=?', function(datos){
		if( datos.errornum == '300' ) location.href = '/ponle_un_final_al_cuento/login.shtml';
		if( datos.errornum == '400' ){
			var mensaje = $('#mensaje_sin_videos').html();
			//$('#contenido_videos').html( mensaje );	
			$('#contenido_videos').html( '' );	
		}
		var html = '';
		if( datos.errornum == '100' ){
			total = datos.total;
			html = '<div style="width:675px;">';
			for(var i in datos.videos){
				html += '	<div style="float:left; width:337px;margin-top:20px; " align="left">';
				html += '		<table border="0" cellspacing="0" cellpadding="0" width="100%">';
				html += '			<tr>';
				html += '				<td align="left" width="125"><div style="width:120px; height:72px; border:1px solid #999999; padding:1px;"><div style="width:120px; height:72px; overflow:hidden;"><a href="#" onclick="mostrarFormularioVideo(\''+datos.videos[i]['codigo']+'\',\''+datos.videos[i]['duracion_texto']+'\');"><img src="'+datos.videos[i]['thumb']+'" border="0" width="120" /></a></div></div></td>';
				html += '				<td align="left" valign="top" class="texto_cuentos" style="padding-left:4px">';
				html += '					<a href="#" onclick="mostrarFormularioVideo(\''+datos.videos[i]['codigo']+'\',\''+datos.videos[i]['duracion_texto']+'\');"><strong>'+datos.videos[i]['nombre']+'</strong><br />'+datos.videos[i]['duracion_texto']+'</a>';
				html += '				</td>';
				html += '			</tr>';
				html += '		</table>';
				html += '    </div>';
			}
			html += '</div>';
			html += '<div style="clear:both; height:10px;"></div>';
			
			if( total > (pagina*paginado) || pagina > 1){
				html += '<div style="width:675px;">';
				
				if( pagina > 1 ){
					html += '<div style="float:left"><a href="javascript:cargarVideosYoutube('+(parseInt(pagina)-1)+');" title="Anterior"><img src="/ponle_un_final_al_cuento/images/bt_anterior.gif" width="83" height="14" alt="Anterior" title="Anterior" border="0" /></a></div>';
				}else{
					html += '<div style="float:left"><img src="/ponle_un_final_al_cuento/images/bt_anterior_off.gif" width="83" height="14" alt="Anterior" title="Anterior" border="0" /></div>';					
				}
				
				if( total > (pagina*paginado) ){
					html += '<div style="float:right"><a href="javascript:cargarVideosYoutube('+(parseInt(pagina)+1)+');" title="Siguiente"><img src="/ponle_un_final_al_cuento/images/bt_siguiente.gif" width="87" height="14" alt="Siguiente" title="Siguiente" border="0" /></a></div>';
				}else{
					html += '<div style="float:right"><img src="/ponle_un_final_al_cuento/images/bt_siguiente_off.gif" width="87" height="14" alt="Siguiente" title="Siguiente" border="0" /></div>';
				}
				
				html += '</div>';
				html += '<div style="clear:both; height:10px;"></div>';
			}
			
			html += '<center>Para subir otro video haz clic <a href="http://www.youtube.com/my_videos_upload" target="_blank">aqu&iacute;</a></center>';
			html += '<div style="clear:both; height:10px;"></div>';
			
		}else if( datos.errornum == '400' ){ //El usuario no tiene videos
			html = 'No hemos encontrado videos en tu cuenta de Youtube.<br />';
			html += 'Si deseas puedes subir uno haciendo clic <a href="http://www.youtube.com/my_videos_upload" target="_blank">aqu&iacute;</a>';
		}
		
		$('#contenedor_videos').html( html );
	});
}

function mostrarFormularioVideo(video, duracion){
	//alert(video+'--'+duracion);
	var swf_video = '';
	swf_video += '        <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="425" height="344">';
	swf_video += '          <param name="movie" value="http://www.youtube.com/v/'+video+'">';
	swf_video += '          <param name="quality" value="high"><param name="bgcolor" value="#f2f2f2">';
	swf_video += '          <embed src="http://www.youtube.com/v/'+video+'" bgcolor="#f2f2f2" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="425" height="344"></embed>';
	swf_video += '        </object>';
	
	var html = '';
	html += '<table border="0" cellpadding="0" cellspacing="0" align="center" width="513" bgcolor="#ffffff">';
	html +=	'	<tr>';
	html +=	'		<td align="right" height="35" valign="middle" style="background-image:url(/ponle_un_final_al_cuento/images/bg_head_caja.gif);background-repeat:no-repeat;background-position:top left;"><a href="javascript:cerrarFormularioVideo();" title="CERRAR"><img src="/ponle_un_final_al_cuento/images/bt_cerrar_caja.gif" width="32" height="33" border="0" hspace="10" alt="CERRAR" title="CERRAR" /></a></td>';
	html +=	'	</tr>';
	html += '</table>';
	html +=	'<table border="0" cellpadding="0" cellspacing="0" align="center" width="513" bgcolor="#ffffff" id="tabla_form_video_preload" style="display:none;">';
	html += '	<tr>';
	html += '		<td align="center"><img src="/ponle_un_final_al_cuento/images/preload.gif" width="32" height="32" vspace="80"></td>';
	html += '	</tr>';
	html += '</table>';
	html +=	'<table border="0" cellpadding="0" cellspacing="0" align="center" width="513" bgcolor="#ffffff" id="tabla_form_video_gracias" style="display:none;">';
	html += '	<tr>';
	html += '		<td align="center"><img src="/ponle_un_final_al_cuento/images/tx_agregar_video_gracias.gif" width="351" height="51" vspace="20"></td>';
	html += '	</tr>';
	html += '	<tr><td height="15"></td></tr>';
	html += '	<tr>';
	html += '		<td align="center"><a href="cuento.shtml?cuento='+cuento+'"><img src="/ponle_un_final_al_cuento/images/bt_ir_listado.gif" width="234" height="36" border="0" /></a></td>';
	html += '	</tr>';
	html += '</table>';
	html +=	'<table border="0" cellpadding="0" cellspacing="0" align="center" width="513" bgcolor="#ffffff" id="tabla_form_video">';
	html += '	<tr>';
	html += '		<td align="center">'+swf_video+'</td>';
	html += '	</tr>';
	html += '	<tr><td height="15"></td></tr>';
	html += '	<tr>';
	html += '		<td align="center"><form id="formVideo" name="formVideo" style="margin:0">';
	html += '		<input type="hidden" name="cuento" id="cuento" value="'+cuento+'" />';
	html += '		<input type="hidden" name="video" id="video" value="'+video+'" />';
	html += '		<input type="hidden" name="duracion" id="duracion" value="'+duracion+'" />';
	html +=	'		<table width="488" height="85" border="0" cellspacing="0" cellpadding="0" style="background-image:url(/ponle_un_final_al_cuento/images/bg_caja_agregar_video.gif);background-repeat:no-repeat;background-position:top left;">';
	html += '			<tr><td height="14"></td></tr>';
	html += '			<tr>';
	html += '				<td width="167" align="right" height="25" valign="middle"><img src="/ponle_un_final_al_cuento/images/tx_titulo.gif" width="55" height="11" alt="TITULO" title="TITULO" /></td>';
	html += '				<td width="10">&nbsp;</td>';
	html += '				<td align="left"><div class="input_caja"><input type="text" name="titulo" id="titulo" maxlength="250" /></div></td>';
	html += '				<td rowspan="3" align="center" valign="middle"><a href="javascript:validarFormularioVideo();"><img src="/ponle_un_final_al_cuento/images/bt_grabar.gif" width="100" height="48" border="0" /></a></td>';
	html += '			</tr>';
	html += '			<tr><td height="5"></td></tr>';
	html += '			<tr>';
	html += '				<td align="right" height="25" valign="middle"><img src="/ponle_un_final_al_cuento/images/tx_nombre_hijo.gif" width="151" height="11" alt="NOMBRE DE TU HIJO" title="NOMBRE DE TU HIJO" /></td>';
	html += '				<td>&nbsp;</td>';
	html += '				<td align="left"><div class="input_caja"><input type="text" name="nombre_hijo" id="nombre_hijo" maxlength="250" /></div></td>';
	html += '			</tr>';
	html += '			<tr><td height="5"></td></tr>';
	html += '			<tr>';
	html += '				<td colspan="4" valign="top" align="left" height="115" style="padding:0 20px 0 20px;" class="texto_caja_legales"><label><input type="checkbox" name="legales" id="legales" value="1" />Acepto las reglas y regulaciones</label><br />Si no haz le&iacute;do las reglas y regulaciones todav&iacute;a, haz clic <a href="reglas.zip">aqu&iacute;</a>.</td>';
	html += '			</tr>';
	html += '			<tr><td></td></tr>';
	html += '		</table></form></td>';
	html += '	</tr>';
	html += '</table>';
	html += '<table border="0" cellpadding="0" cellspacing="0" align="center" width="513" bgcolor="#ffffff">';
	html +=	'	<tr>';
	html +=	'		<td align="right" height="17" valign="middle" style="background-image:url(/ponle_un_final_al_cuento/images/bg_footer_caja.gif);background-repeat:no-repeat;background-position:top left;"></td>';
	html +=	'	</tr>';
	html += '</table>';
	
	
	
	$('body').prepend('<div id="backgroundFormularioVideo" class="formularioVideo" style="display:none;position:absolute;top:0;left:0;z-index:1000;background-color:#000;width:100%;"></div><div id="formularioVideo" class="formularioVideo" style="display:none;position:absolute;top:0;left:0;z-index:1001;width:100%;padding-top:150px;">'+html+'</div>');
	$('#backgroundFormularioVideo').css('height',$(document).height());
	$('#backgroundFormularioVideo').css('opacity',0.8);
	$('.formularioVideo').show();

}

function cerrarFormularioVideo(){
	$('.formularioVideo').remove();
}

