// Check whether string s is empty.
function isEmpty(s)
{
	return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace(s)
{
	var i;
	// whitespace characters
	var whitespace = " \t\n\r";

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

function isEmail(s)
{
	var i = 1;
  var sLength = s.length;

  // look for @
  while ((i < sLength) && (s.charAt(i) != "@")) {
		i++;
  }

	if ((i >= sLength) || (s.charAt(i) != "@")) {
		return false;
	}
	else {
	 i += 2;
	}
  // look for .
  while ((i < sLength) && (s.charAt(i) != ".")) {
		i++;
  }

// there must be at least one character after the .
	if((i >= sLength - 1) || (s.charAt(i) != ".")) {
		return false;
	}
	else {
		return true;
	}
}

function open_url(menu, opt)
{
	if(menu.selectedIndex != 0)
	{
		if (opt == 0) // current window
		{
			window.location = menu[menu.selectedIndex].value;
		}
		else if (opt == 1) // new window
		{
			window.open(menu[menu.selectedIndex].value);
		}
		else if (opt == 2) // background window
		{
			window.open(menu[menu.selectedIndex].value);
			self.focus();
		}
	}
}

function limitText(obj){ 
	var count = "800"; 
	if(obj.value.length > count){
		obj.value = obj.value.substring(0,count);
		return false;
	}
	document.getElementById("caracter").value = 800 - parseInt(obj.value.length);
	return true;
}

function limitCTRV(obj, evento){ 
	var text; 
	text = obj.value;
	var ctrl = typeof evento.modifiers == 'undefined' ?   evento.ctrlKey : evento.modifiers & evento.CONTROL_MASK;
	var v = typeof evento.which == 'undefined' ?   evento.keyCode == 86 : evento.which == 86;
	if ( ctrl && v ) { 		
		alert('Lo sentimos, no se puede pegar un texto externo');
		obj.value=text;
		return false;
	}
	return true;
}

function limitClickRigth(e) {
if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2)){
	alert('Lo sentimos, no se puede pegar un texto externo')
	return false;
}else  if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2)){
			alert('Lo sentimos, no se puede pegar un texto externo')
		}	
}

function esComentarioVacio()
{
	s = document.getElementById('edit-comment');

	if(isWhitespace(s.value))
	{
		alert('Por favor escriba su opinion en el espacio indicado.');
		s.value = '';
		s.focus();
		return false;
	}

	return true;
}

 function blshow(EL)
   {
      ELpntr=document.getElementById(EL);
      ELpntr.style.display='';
	  
	  return false;
   }
   
   function blhide(EL)
   {
      ELpntr=document.getElementById(EL);
	  ELpntr.style.display='none';
	  return false;			
   }
   function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
      return IsNumber;   
   }
   
   function HasNumbers(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=false;
   var Char;
   for (i = 0; i < sText.length && IsNumber == false; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) != -1) 
         {
         IsNumber = true;
         }
      }
      return IsNumber;   
}

function HasCharacters(sText)
{
   var ValidChars = "|��!\"#$%&/()=?'\\����*+~[]{}^` ";
   var IsNumber=false;
   var Char;
   for (i = 0; i < sText.length && IsNumber == false; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) != -1) 
         {
         IsNumber = true;
         }
      }
      return IsNumber;   
}

function verificaRegistro()
{
	nombres= document.getElementById('edit-profile-nombres').value;
	apellidos= document.getElementById('edit-profile-apellidos').value;
	dia= document.getElementById('edit-profile-fnacimiento-day').value;
	mes= document.getElementById('edit-profile-fnacimiento-month').value;
	anio= document.getElementById('edit-profile-fnacimiento-year').value;
	genero= document.getElementById('edit-profile-genero').value;
	pais= document.getElementById('edit-profile-pais-residencia').value;
	nusuario= document.getElementById('edit-name').value;
	correo= document.getElementById('edit-mail').value;
	correo1= document.getElementById('edit-conf-mail').value;
	pregunta= document.getElementById('edit-profile-pregunta-de-seguridad').value;
	respuesta= document.getElementById('edit-profile-respuesta').value;
	correoopcional= document.getElementById('edit-profile-correo-opcional').value;
	checkterminos= document.getElementById('edit-profile-terminosycondiciones').checked;
	//captcha= document.getElementById('edit-captcha-response').value;
	
	document.getElementById('mensaje-nombres').innerHTML="";
	document.getElementById('mensaje-apellidos').innerHTML="";
	document.getElementById('mensaje-fnacimiento').innerHTML="";
	document.getElementById('mensaje-genero').innerHTML="";
	document.getElementById('mensaje-pais').innerHTML="";
	document.getElementById('mensaje-ciudad').innerHTML="";
	document.getElementById('mensaje-nusuario').innerHTML="";
	document.getElementById('mensaje-correo').innerHTML='<div class="ayuda_registro"><p>El correo que usted elija, ser&aacute; el usuario que le permitir&aacute; ingresar a los servicios adicionales de nuestras p&aacute;ginas</p></div>';
	document.getElementById('mensaje-correo1').innerHTML="";
	document.getElementById('mensaje-pregunta').innerHTML="";
	document.getElementById('mensaje-respuesta').innerHTML="";
	document.getElementById('mensaje-correoop').innerHTML='<div class="ayuda_registro"><p>Un mensaje ser&aacute; enviado a este correo en caso que olvide su usuario o clave</p></div>';
	document.getElementById('mensaje-terminos').innerHTML="";
	//document.getElementById('mensaje-captcha').innerHTML="";
			
	if(isWhitespace(nombres))
	{
		document.getElementById('mensaje-nombres').innerHTML="<div class='alerta'><p>Por favor ingrese un valor para nombres</p></div>";
		location.href = "#personales";
	}
	else if(isWhitespace(apellidos))
	{
		document.getElementById('mensaje-apellidos').innerHTML="<div class='alerta'><p>Por favor ingrese un valor para apellidos</p></div>";
		location.href = "#personales";
	}
	else if(dia=="0"||mes=="0"||anio=="0")
	{
		document.getElementById('mensaje-fnacimiento').innerHTML="<div class='alerta'><p>Por favor seleccione su fecha de nacimiento</p></div>";
		location.href = "#personales";
	}
	else if(genero=="Seleccione género")
	{
		document.getElementById('mensaje-genero').innerHTML="<div class='alerta'><p>Por favor seleccione su g&eacute;nero</p></div>";
		location.href = "#personales";
	}
	else if(pais=="Seleccione país")
	{
		document.getElementById('mensaje-pais').innerHTML="<div class='alerta'><p>Por favor escoja el Pa&iacute;s de residencia</p></div>";
		location.href = "#personales";
	}
	else if(isWhitespace(nusuario))
	{
		document.getElementById('mensaje-nusuario').innerHTML="<div class='alerta'><p>Por favor ingrese un valor para Alias o Nombre de usuario</p></div>";
		location.href = "#sistema";
	}
	else if(isWhitespace(correo))
	{
		document.getElementById('mensaje-correo').innerHTML="";
		document.getElementById('mensaje-correo').innerHTML="<div class='alerta'><p>Por favor ingrese un valor para Correo Electr&oacute;nico</p></div>";
		location.href = "#sistema";
	}
	else if(!isEmail(correo))
	{
		document.getElementById('mensaje-correo').innerHTML="";
		document.getElementById('mensaje-correo').innerHTML="<div class='alerta'><p>Por favor escriba un correo v&aacute;lido</p></div>";
		location.href = "#sistema";
	}
	else if(isWhitespace(correo1))
	{
		document.getElementById('mensaje-correo').innerHTML="";
		document.getElementById('mensaje-correo1').innerHTML="<div class='alerta'><p>Por favor ingrese un valor para Confirme su correo, el cual debe ser el mismo del Correo electr&oacute;nico</p></div>";
		location.href = "#sistema";
	}
	else if(!isEmail(correo1))
	{
		document.getElementById('mensaje-correo').innerHTML="";
		document.getElementById('mensaje-correo').innerHTML="<div class='alerta'><p>Por favor escriba un correo v&aacute;lido</p></div>";
		location.href = "#sistema";
	}
	else if(correo!=correo1)
	{
		document.getElementById('mensaje-correo1').innerHTML="<div class='alerta'><p>Los correos escritos son diferentes, por favor verif&iacute;quelos</p></div>";
		location.href = "#sistema";
	}
	else if(pregunta=="Seleccione")
	{
		document.getElementById('mensaje-pregunta').innerHTML="<div class='alerta'><p>Por favor seleccione una pregunta</p></div>";
		location.href = "#contras";
	}
	else if(isWhitespace(respuesta))
	{
		document.getElementById('mensaje-respuesta').innerHTML="<div class='alerta'><p>Por favor ingrese un valor para su respuesta</p></div>";
		location.href = "#contras";
	}
	else if(!isWhitespace(correoopcional)&&!isEmail(correoopcional))
	{
		document.getElementById('mensaje-correoop').innerHTML="<div class='alerta'><p>Por favor escriba un correo v&aacute;lido</p></div>";
		location.href = "#contras";
	}
	else if(!checkterminos)
	{
		document.getElementById('mensaje-terminos').innerHTML="<div class='alerta'><p>Debe aceptar los T&eacute;rminos y Condiciones de nuestro portal</p></div>";
		location.href = "#terminos";
	}
	/*else if(isWhitespace(captcha))
	{
		document.getElementById('mensaje-captcha').innerHTML="<div class='alerta'><p>Por favor ingrese un valor para el c&oacute;digo de la im&aacute;gen</p></div>";
		location.href = "#terminos";
	}*/
	else
	{
		document.getElementById('user-register').submit()
	}
	
	
	
}

/*Encuentra la posicion de un objeto en la pagina*/
function findPos(obj)
{
	var curleft = curtop = 0;
	do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
	return [curleft,curtop];
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function splashpage() {
	var x = readCookie('activo');
	if (!x) {
		createCookie('activo','1',365);
		window.location="http://www.caracoltv.com/promocionlightbox";
	}
}

function validarRegistro() {
	var forma = document.formtitulares;
	var error;
	error = "";
	
	if (forma.email.value == "" || forma.email.value == "Ingrese su correo") {
		error += "Por favor digite su email\n";
	}

	if(error != "") {
		alert(error)
	}
	else {
		forma.action = "http://newsletters.icck.net/box.php";
		forma.submit();
	}

	return;
}

function borrarTexto() {
	document.formtitulares.email.value = "";
}

function chequeaFecha(userinput){
    var dateformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
    return dateformat.test(userinput) //returns true or false depending on userinput
}

function validarCookieInicio(accion , id_portal){
    
    switch(accion){
        //Si
        case 1:
			createCookie('TestOkSitio',id_portal,180);
			$("#favorito").hide();
        break;
        //no
        case 2:
            
			$("#favorito").hide();
        break;
        case 3:
                        createCookie('TestOkBarra_'+id_portal,'NO',1);
        break;
        
    }
    

}

function validarPortal(accion, id_portal ){

	if(accion==0 && id_portal==0){
		if(readCookie("TestOkSitio")=='2')
			document.location.href="/golcaracol";
		else{
			if(readCookie("TestOkSitio")=='1')
				document.location.href="/noticias";		
			else{
					if(readCookie("TestOkSitio")=='3')
						document.location.href="/programas";	
				}
						
		}
	}else{
		if(readCookie('TestOkBarra_'+id_portal)=='NO' || readCookie('TestOkSitio')=='1' || readCookie('TestOkSitio')=='2' || readCookie('TestOkSitio')=='3'){
			$("#favorito").hide(); 
		} 
	}
}

function share_ctv(url,text,hashtag){
		var facebook = '<a onclick="window.open(\'http://www.facebook.com/sharer/sharer.php?u='+url+'&src=sp\');">Facebook</a>';
		var twitter = '<a onclick="window.open(\'http://twitter.com/intent/tweet?source=webclient&url='+url+'&related=NoticiasCaracol,CaracolTV&hashtags='+hashtag+'&via=GolCaracol&text='+text+'\');">Twitter</a>';
		var windows = '<a onclick="window.open(\'http://www.myspace.com/Modules/PostTo/Pages/?u='+url+'&l=3&c=\');">Windows</a>';
		var delicious = '<a onclick="window.open(\'http://www.delicious.com/save?url='+url+'&notes=caracoltv&tags=caracoltv&noui=no&time=1309901643&share=yes&recipients=\');">Delicious</a>';
		var html = '';
		html = '<div class="redes-sociales">\n\
								<ul>\n\
								<li class="facebook">'+facebook+'</li>\n\
								<li class=" twitterShare">'+twitter+'</li>\n\
								<li class="windows">'+windows+'</li>\n\
								<li class="delicious">'+delicious+'</li>\n\
								</ul>\n\
					</div>';
	$('.share-ctv a').click(function(e) {
		e.preventDefault();
		var $this = $(this);
		$this.html('<a  class="sharelink" >compartir</a><div id="share" >'+html+'</div><a class="cerrar-share" onclick="cerrar(\''+url+'\');">X</a>');
	});
}
function cerrar(url){

$(".share-ctv").html('<a  class="sharelink"onclick="share_ctv(\''+url+'\');" >compartir</a>');
}
/**
 * Funcion para reproducir en los videos
 */
function miniaturas_video_noticiero(){
	$('#noticiero .recursos-relacionados a.video-miniaturas:first').addClass("activo");
	$('#noticiero .recursos-relacionados a.video-miniaturas').click(function() {
var ooyalaPlayer = document.getElementById("player");
var embede = $(this).attr("name");
ooyalaPlayer.setQueryStringParameters({embedCode:embede, autoplay:1});
$("#noticiero .recursos-relacionados a.video-miniaturas").removeClass("activo");
$(this).addClass("activo");
return false;

});
}

$(document).ready(function(){
		miniaturas_video_noticiero();
});

function videoNoticiero(playerId, eventName, eventArgs) {
	var ciecc,ttc,ecc,vc;





	switch(eventName) {

		case "embedCodeChanged":
			//creacion_titulo(eventArgs);
			ciecc=eventArgs;
			$(".titulo-ooyala").html(eventArgs.title);
		break;
		case "apiReady":
			//note: apiReady event has no eventArgs (3rd call-back parameter)

			break;

	}
}

function _ajax_playlist_video(){
  
  
  if($(".playlist-videos-total").length != 0){
   var url = '/ajax-analytics/'+idvideo;

  $.ajax({
			 type: "GET",
			 url: url,
			 cache:true,
			 success: function(data){                   
            var result = Drupal.parseJson(data);
					$(".playlist-videos-total").html(result.data);

			 }
			});
  }
}


$(document).ready(function(){
	$('#select-emision').change(function() {
		 var str = "";
          $("select option:selected").each(function () {

                str = $(this).val();
              });
							if(str != 0){
							location.href =str;
							}

	});
})

//Activa la clase al presionar el link
$(function() {
	$('.active a').click(function(e) {
		e.preventDefault();
		var $this = $(this);
		$('.horarioEmisionNoticias a').removeClass('Selected');
		$this.addClass('Selected');
	});
});


$(document).ready(function(){
	$('.id-menu a').click(function() {
		var ultimo =  $(this).attr('id');
		var pauta =  $(this).attr('rel');
			document.getElementById("video-player-uno").src="/ajax-emision/video/"+ultimo+"/"+pauta+"/1";

	});
_ajax_playlist_video();
})




