// JavaScript Document

var ventanaRadio;
function newAjax() { 
	var xmlhttp=false; 
	try { 
		// No IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e) { 
		try	{ 
			// IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { 
			xmlhttp = false; 
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest != "undefined") { 
		xmlhttp = new XMLHttpRequest(); 
	} 
	return xmlhttp; 
}

function adsBanners(id,rand, div){	
	// La función hace un request donde agrega la publicidad por medio de un código html que le regresa el archivo
	// publicidadRequest.php, esta funcion se manda llamar en cada uno de los arcchivos publicidad(N).php
	
	$('#'+div).addClass("loaderAnimacion");
	var ajax = newAjax();
	var sPost = "&id="+id;
	sPost+= "&nrand="+rand;	
	ajax.open("POST", "request/publicidadRequest.php?r="+Math.random(), true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(sPost);		
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4){	
			//document.getElementById(div).innerHTML = ajax.responseText;	
			$("#"+div).empty();
			$("#"+div).append(ajax.responseText);
			//if(callBackFn instanceof Function) setTimeout(callBackFn,0);
		}	
	}
}

function trim(cadena) {
	for(i=0; i<cadena.length; )	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	
	return cadena;
}

function validaCorreo(valor) {
	var reg = /(^[a-zA-Z0-9._-]{1,30})@([a-zA-Z0-9.-]{1,30}$)/;
	if(reg.test(valor)) {
		return true;
	} else {
		return false;
	}
}

function ventanaAudio(vars){
	window.open("escuchar.php?"+vars,"Linea_Directa_Portal","scrollbars=0,resizable=NO,width=740,height=475");
}

function ventanaVideo(vars){
	window.open("videos.php?"+vars,"Linea_Directa_Portal","scrollbars=yes,resizable=NO,width=740,height=550");
}

function enviarAmigo(vars){
	window.open("enviar.php?"+vars,"Linea_Directa_Portal","scrollbars=0,resizable=NO,width=720,height=510");
}

function get_cookie ( nombre_cookie ){
  if (document.cookie.length != 0) {
    var valor_cookie = document.cookie.match (
     '(^|;)[\s]*' +
      nombre_cookie +
      '=([^;]*)' );
      return decodeURIComponent ( valor_cookie[2] ) ;
  }
  return '' ;
}

function CerrarRadioEmergente(){
	//window.opener.location.reload();
  	/*window.opener.focus();
	$("#cintaRadio").css("display","none");*/	
	cerrarRadio();
}

function mostrarRadio(id){
	$("#cintaRadio").css("display","block");	
	ventanaRadio = window.open("escucharRadio.php?id="+id,"Radio_Linea_Directa_Portal","scrollbars=no,resizable=NO,dependent=yes,width=740,height=572");
	//console.log(ventanaRadio);
	window.name = '{"ventanaRadio2":ventanaRadio,"varRadio":ventanaRadio}';
	if(!window.access) {
		window.access = new Function('return '+ window.name)();
	}
	
	var primerVez = true;
	
	ventanaRadio.onunload = function(){
		// DOM unloaded, so the window is likely closed.
		if(primerVez == false) cerrarRadio();
		if(primerVez == true) primerVez = false;		
	}

	
	document.cookie = "radioCookie="+window.access.varRadio;
	$.ajax({
		url: "request/mostrarCintaRadio.php?id="+id,
		type: "POST",
		owner: this,
		data: "",
		success: function(res){		
			$("#cintaContenido").empty();				
			$("#cintaContenido").append(res);	
		}			
	});
}

var ven;

function cerrarRadio(){
	$("#cintaRadio").css("display","none");
	//var cerrarRadio = get_cookie("radioCookie");
	//cerrarRadio = eval('cerrarRadio');
	
	$.ajax({
		url: "request/mostrarCintaRadio.php?cerrar=si",
		type: "POST",
		owner: this,
		data: "",
		success: function(res){		
			//document.cookie = nombre_cookie + "="; max-age=0; path=/; domain=" + dominio_cookie ;
		}			
	});
	
	ven = ventanaRadio;
	ven.close();	
}

function cerrar(){	
	$("#cintaRadio").css("display","none");
}

/*********************************************** PARA MODULO DE ENCUESTAS ******************************************************/ 

function encuestaClick(valor) {
	document.getElementById("resClickeada").value = valor;
}

function encuestaClickGeneral(valor,pos) {
	document.getElementById("resClickeada"+pos).value = valor;
}

function encuestaVotar(){	
	if (document.getElementById("resClickeada").value != "") {
		var idEncuesta=document.getElementById("idEncuesta").value
		var idEncuestas=document.getElementById("idEncuestas").value
		var posEncuesta=document.getElementById("posEncuesta").value
		var idRespuesta=document.getElementById("resClickeada").value
		$.ajax({
			url: "request/encuestasDatosPortadaRequest.php",
			type: "POST",
			data: "idEncuesta="+idEncuesta+"&idEncuestas="+idEncuestas+"&posEncuesta="+posEncuesta+"&idRespuesta="+idRespuesta,
			success: function(res){		
				$("#encuestasHome").empty();				
				$("#encuestasHome").append(res);				
			}			
		});
	}
}

function encuestaVotarGeneral(pos){	
	if (document.getElementById("resClickeada"+pos).value != "") {
		var idEncuestas=document.getElementById("idEncuestas").value;
		var idEncuesta=document.getElementById("idEncuesta"+pos).value;
		var posEncuesta=document.getElementById("posEncuesta"+pos).value;
		var idRespuesta=document.getElementById("resClickeada"+pos).value;	
		$.ajax({
			url: "request/encuestasDatosGeneralRequest.php",
			type: "POST",
			data: "idEncuesta="+idEncuesta+"&posEncuesta="+posEncuesta+"&idRespuesta="+idRespuesta+"&idEncuestas="+idEncuestas,
			success: function(res){		
				$("#votarEncuestaGeneral").empty();				
				$("#votarEncuestaGeneral").append(res);				
			}			
		});
	}
}

function encuestaRecorre(nDireccion){	
	var nPosicionActual = document.getElementById("posEncuesta").value;
	var idEncuestas=document.getElementById("idEncuestas").value;
	if (nDireccion < 0) {
		if (nPosicionActual > 0){ nPosicionActual--; }
	} else {
		nPosicionActual++;
	}
	$.ajax({
		url: "request/encuestasDatosPortadaRequest.php",
		type: "POST",
		//owner: this,
		data: "idEncuestas="+idEncuestas+"&posEncuesta="+nPosicionActual,
		success: function(res){		
			$("#encuestasHome").empty();				
			$("#encuestasHome").append(res);				
		}			
	});
}
/************************* --------------------------------- ****************************************************************/ 

/***************************** LOGIN **********************************************/

function loginLD(){
	var alto = $(window).height();
	var ancho = $(window).width();
	
	
	$("#ContenidoLogin").css("height",alto+"px");
	$("#ContenidoLogin").css("width",ancho+"px");
	$("#ContenidoLogin").css("display","block");
	document.getElementById("txtNick").focus();
}

function CerrarSesion(){
	$.ajax({
		url: "request/loginRequest.php",
		type: "POST",	
		data: "code=CerrarSesion",
		success: function(res){		
			location.reload(true);				
		}			
	});
}

function Cancelar(){	
	$("#ContenidoLogin").css("display","none");
}	

function OlvidastePassword(){
			
	var nick = document.getElementById("txtNick").value;		
	if(nick == ""){
		alert("Introduzca su Nick \u00f3 Correo Electr\u00f3nico");	
		return;	
	}
	var ajax = newAjax();		
	var sPost = "&txtNick=" + document.getElementById("txtNick").value;							
	sPost += "&txtPass=" + document.getElementById("txtPass").value;	
	ajax.open("POST", "request/olvidateContrasenaRequest.php?r=" + Math.random(), true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(sPost);
	ajax.onreadystatechange = function() {		    	
		
		if (ajax.readyState == 4) {						
			if (ajax.responseText) {
				if(ajax.responseText == "procesando"){
					alert("La informaci\u00f3n esta siendo procesada, intente en 10 \u00f3 15 minutos m\u00e1s. Gracias.");
					return;
				}
				
				if(ajax.responseText == "El Usuario No Existe."){
					alert(ajax.responseText);							
				}else{
					alert("Se ha enviado un correo con tu contrase\u00f1a");				
				}
			} 
			else if(! ajax.responseText) {
				
			}				
		}				
	}					
}

	function Entrar(){		
		
		if(ValidaCampos() == false){
			alert("entra");
			return;
		}
		$("#loaderLogin").css("display","block");
		
		document.getElementById("btnEntrar").value = "Entrando...";		
		var ajax = newAjax();		
		var sPost = "&txtNick=" + document.getElementById("txtNick").value;				
		sPost += "&txtPass=" + document.getElementById("txtPass").value;	
		ajax.open("POST", "request/loginRequest.php?r=" + Math.random(), true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send(sPost);
		ajax.onreadystatechange = function() {		    	
			$("#loaderLogin").css("display","block");
			if (ajax.readyState == 4) {						
				if (ajax.responseText) {				
					
					if(ajax.responseText == "Tu Usuario o Password Son Incorrectos"){						
						alert("Usuario \u00f3 Contrase\u00f1a Incorrectos");
						$("#loaderLogin").css("display","none");
						document.getElementById("btnEntrar").value = "Entrar";	
						return;
					}else{						
						Limpiar();
						document.getElementById("btnEntrar").value = "Entrar";	
						$("#ContenidoLogin").css("display","none");						
						location.reload(true);
					}
				} 
				else if(! ajax.responseText) {
					
				}				
			}				
		}	
			
	}



	function ValidaCampos(){
		var nick = document.getElementById('txtNick').value;		
		var pass = document.getElementById('txtPass').value;
		
		if(nick == "" || pass == ""){
			alert("Debe proporcionar sus datos");
			return false;
		}			
	}
	
	function Limpiar(){
		document.getElementById("txtNick").value = "";				
		document.getElementById("txtPass").value = "";
	}

/***********************************************************************************/

/********************************DESCARGA PODCAST **********************************/

var Base64 = {};  // Base64 namespace

Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function descargaPodcast(dirPodcast){  
	
	//// Se recibe encriptado el path del XML, se le quita lo de http y se le concatena el itpc para que abra el Itunes
	var dirPod = "itpc://";
	var str = Base64.decode(dirPodcast);
	//var str = str.replace("http://", "")
	window.location = dirPod+str+'.xml';
	
}

Base64.decode = function(str, utf8decode) {
  utf8decode =  (typeof utf8decode == 'undefined') ? false : utf8decode;
  var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;
  var b64 = Base64.code;

  coded = utf8decode ? str.decodeUTF8() : str;
  
  
  for (var c=0; c<coded.length; c+=4) {  // unpack four hexets into three octets
    h1 = b64.indexOf(coded.charAt(c));
    h2 = b64.indexOf(coded.charAt(c+1));
    h3 = b64.indexOf(coded.charAt(c+2));
    h4 = b64.indexOf(coded.charAt(c+3));
      
    bits = h1<<18 | h2<<12 | h3<<6 | h4;
      
    o1 = bits>>>16 & 0xff;
    o2 = bits>>>8 & 0xff;
    o3 = bits & 0xff;
    
    d[c/4] = String.fromCharCode(o1, o2, o3);
    // check for padding
    if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
    if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
  }
  plain = d.join('');  // join() is far faster than repeated string concatenation in IE
   
  return utf8decode ? plain.decodeUTF8() : plain; 
}

/*
	AGREGADO: JORGE EDUARDO LOPEZ - 26 ENERO 2012
	FUNCION: CARGA LA PUBLICIDAD POR ZONAS DE LINEA DIRECTA
	PARAMETROS: 
		- divRenderID: ID del div donde se mostrara el banner
		- zoneID: ID de la zona de publicidad (establecidas en bannersRequest.php)
*/
function cargarPublicidad(divRenderID, zoneID) {
	$.ajax({
		type: 'POST', 
		url: "request/bannersRequest.php",
		data:"IDZona="+zoneID,
		success: function(response){			
			if(response != '') {
				$("#"+divRenderID).empty();
				$("#"+divRenderID).append(response);
			}
		}
	});
}	
