/*
	COMENTÁRIO
*/
var idVideoComent = null;
function exec_login(id){
	idVideoComent = id
	if(validaForm(gid('floginid')) && validaMail('login_email')){
		var arquivo = 'login_comentario.php?email='+gid('login_email').value+'&pw='+gid('login_pw').value;
		abre_xml(arquivo,'resposta_login','');										
	}
	
}
function resposta_login(resp){
	if(resp == 'OK'){
		abre_video(idVideoComent);
	}else{
		alert("Não foi possível realizar o login.\nVerifique seus dados.");
	}
}

function vote_video(idvideo){
	var objVote = document.getElementById("numvoto");
	var valvote = objVote.options[objVote.selectedIndex].value;
	var arquivo = 'setvote.php?id='+idvideo+'&vote='+valvote
	abre_xml(arquivo,'resposta_vote','');
}
function resposta_vote(val){
	if(val == '0'){
		alert("Você já votou nesse video.");
	}else{
		alert("Voto computado com sucesso.");	
	}
}
function area_comentar(){
	if (gete('comunidade_lista_comentarios').style.display=='none')
	{
		gete('comunidade_area_comentario').style.display='none';
		gete('comunidade_lista_comentarios').style.display='block';
	}
	else
	{
		gete('comunidade_area_comentario').style.display='block';
		gete('comunidade_lista_comentarios').style.display='none';
	}
}
var id_video_global=0;
function comentar(id_video){
	id_video_global=id_video;
	var comentario_texto = gete("comentario_texto").value;
	if (comentario_texto.length==0) {alert("Por favor, preencha o comentário.");}
	else if (comentario_texto.length>250) {alert("Por favor, reduza o tamanho do seu comentário para que ele tenha no máximo 250 caracteres.");}
	else {
		var arquivo = 'salvar_comentario.php?id='+id_video+'&mensagem='+comentario_texto;
		abre_xml(arquivo,'resposta_comentar','');
	}
}
function resposta_comentar(val){
	if(val == '0'){
		alert("Comentário não foi salvo.");
	}else{
		alert("Comentário foi salvo com sucesso.");
		gete('comunidade_lista_comentarios').innerHTML='<div id="comunidade_lista_comentarios"><div class="caixa_pontilhada"><div class="hr1"> </div><div class="video_area_texto">Aguarde...</div></div></div>';
		area_comentar();
		gete("comentario_texto").value = '';
		abre_xml('lista_comentario.php?id_video='+id_video_global,'resposta_lista_comentario','');
	}
}
function listComentariospaginado(page){
	abre_xml('lista_comentario.php?id_video='+idVideoComent+'&page='+page,'resposta_lista_comentario','');
}

function resposta_lista_comentario(val) {
	gete('comunidade_lista_comentarios').innerHTML=val;
}
function spam(id_video,id_comentario){
	var arquivo = 'comentario_spam.php?id='+id_video+'&id_comentario='+id_comentario;
	abre_xml(arquivo,'resposta_spam','');
}
function resposta_spam(val){
	if(val == '0'){
		alert("A denúncia de SPAM não foi enviada, tente novamente.");
	}else{
		alert("A denúncia de SPAM foi enviada com sucesso e será avaliada. Obrigado!");
	}
}

/*
	COMENTÁRIO
*/

function show_reg(flag){
//#texto_competi, #texto_premios
    var div1, div2, imgswap;
    if(flag == 1){
        div1 = '#texto_competi';
        div2 = '#texto_premios';
    }else{
        div1 = '#texto_premios';
        div2 = '#texto_competi';
    }   

    $(div1).fadeOut("normal", function callback() {
        $(div2).fadeIn("normal")
    });    
}
function gid(id){
    return document.getElementById(id)
}

 
function validaLinksSend(eu){
	var filter_youtube  = /^http:\/\/(\w+\.)?youtube.com\/watch/;
	var filter_vimeo  = /^http:\/\/(\w+\.)?vimeo.com/;

    for(var ff=1;ff<=pos_atual;ff++){
        eval("var tmpcmp = eu.url"+ff);
    
    	if (tmpcmp.value != 'http://' && !filter_youtube.test(tmpcmp.value) && !filter_vimeo.test(tmpcmp.value)){
    		alert("Insira nos campos abaixo a URL dos seus vídeos que estão no Vimeo ou Youtube.");
    		tmpcmp.focus();
             
            return false;
        }
    } 
    return true;
}

function validaTamanho(e,t,i){
    if(parseInt(e.value) < t){
        alert("O video deve ter no mínimo "+t+"px de "+((i=='w')?"Largura (Width)":"Altura (Height)")+".");
        e.focus(); 
        return false;
    }
    return true;
}
function newsValue(obj)
{
	if(obj.value=="Cadastre-se aqui")
	{
		obj.value="";
	}
	else if (obj.value=="")
	{
		obj.value="Cadastre-se aqui";
	}
}

/* Validação */
	function validaMail (emailId){
		var email = document.getElementById(emailId);
		if(email.value!=""){
			if (email.value.indexOf("@") <= 0 || email.value.indexOf(".") <= 0){
				alert("Formato do email inválido.")
				email.focus()
				return (false);
			}
		}
		return (true);
	}

function validaForm(f){
	for (i=0 ; i<f.length ; i++){        
		e = f.elements[i];
		str = e.title.split(";");
		//if (e.title=="Campo Obrigatório" && e.value == ""){
		if (str[1]=="Campo Obrigatório" && e.value == ""){
			alert("O campo "+str[0]+" deve ser preenchido");
			e.focus();
			return (false);
		} 
		e = null;
	}
	return(true);
}
function validaSenha(f){
    if(f.senha.value != f.confsenha.value){
           alert("A confirmação de senha digitada, não é igual a senha.");
           f.confsenha.focus();
           return false; 
    }
    return true;
}
function validaSenhaEdit(f){
    if(f.senha.value != ""){
        if(f.senha.value != f.confsenha.value){
               alert("A confirmação de senha digitada, não é igual a senha.");
               f.confsenha.focus();
               return false; 
        }
    }   
    return true;
}
function validaDate(objId){
	var reDate = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	var obj    = document.getElementById(objId);
	var pStr   = obj.value;
	if (pStr != "" && !reDate.test(pStr)) {
		alert(pStr + " não é uma data válida.");
		obj.focus();
		return false;
	}
	return true;
}

function validaVivo(obj){

    if(obj.cliente_vivo.checked == true){
        if(obj.nome_vivo.value == ""){
            alert("O Campo Nome Cliente Vivo é obrigatório.");
            obj.nome_vivo.focus();
            return false;
        }
        if(obj.numero_vivo.value == ""){
            alert("O Campo Número Cliente Vivo é obrigatório.");
            obj.numero_vivo.focus();
            return false;
        }    
    }
    //try{}catch(e){alert(e.description)}    
    return true;
}
function showVivo (obj){
    if(obj.checked == true){
        gid('mostra_vivo').style.display = '';
    }else{
        gid('mostra_vivo').style.display = 'none';
    }

}

var re_dt = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
function valDate(s_date) {
		// check format
		if (!re_dt.test(s_date))
			return false;
		// check allowed ranges	
		if (RegExp.$1 > 31 || RegExp.$2 > 12)
			return false;
		// check number of day in month
		var dt_test = new Date(RegExp.$3, Number(RegExp.$2-1), RegExp.$1);
		if (dt_test.getMonth() != Number(RegExp.$2-1))
			return false;
		return true;
}
function validaData(obj){
        if(!valDate(obj.datef.value)){
            alert("O Campo Data de realização está com uma data inválida.");
            obj.datef.focus();
            return false;
        }  
        return true; 
}

function mudaDivInsc(obj){
    if(obj.value == 0){
        gid('mostra_online').style.display = '';
        gid('mostra_correio').style.display = 'none';
    }else{
        gid('mostra_online').style.display = 'none';
        gid('mostra_correio').style.display = '';
    }
}

function validaCount(obj, max, campo){
        if(countwords(obj.value) > max){
            alert("O Campo "+campo+" deve ter no máximo "+max+" palavras.");
            obj.focus();
            return false;
        }  
        return true; 
}
function countwords(w){
    var y=w;
    var r = 0;
    a=y.replace(/\s/g,' ');
    a=a.split(' ');
    return a.length;
} 

function onlyNumbers(evt) {
  var charCode = (evt.which) ? evt.which : evt.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

function validaCompetPasso2(obj){

    if(obj.subscriptionType[0].checked){
        if(
            !gid('fileType01').checked &&
            !gid('fileType02').checked &&
            !gid('fileType03').checked &&
            !gid('fileType04').checked &&
            !gid('fileType05').checked &&
            !gid('fileType06').checked            
        ){
            alert("Selecione um Tipo de Vídeo");
            gid('fileType01').focus();
            return false;
        }
        if(gid('videoFile').value == "" && gid('videoId').value == 0){
            alert("Selecione um arquivo de vídeo");
            gid('videoFile').focus();
            return false;
        }        
        
        
    }else{
        if(
            !gid('fileType07').checked &&
            !gid('fileType08').checked &&
            !gid('fileType09').checked &&
            !gid('fileType10').checked
        ){
            alert("Selecione um Tipo de Vídeo");
            gid('fileType07').focus();
            return false;s
        }    
    }
    if(gid('fotoFile').value == "" && gid('temfotoreali').value == "" ){
        alert("Selecione uma foto do realizador.");
        gid('fotoFile').focus();
        return false;     
    }  
    
    if(obj.dimW.value == "" || obj.dimH.value == ""){
        alert("Digite as Dimensões do Video.");
        obj.dimW.focus();
        return false;     
    }      
    if(gid('still0') != null && gid('still0').value == ""){
        alert("Selecione pelo menos uma imagem de still.");
        gid('still0').focus();
        return false;     
    }         
    return true;
}


function validaMidias(obj){
    if(gid('fotoFile').value == "" && gid('temfotoreali').value == "" ){
        alert("Selecione uma foto do realizador.");
        gid('fotoFile').focus();
        return false;     
    }  
    
    if(gid('still0') != null && gid('still0').value == ""){
        alert("Selecione pelo menos uma imagem de still.");
        gid('still0').focus();
        return false;     
    }         
    return true;
}

	function validaAutorizacaoCompet(f){
		var a1 = document.getElementById('a1');
		var a3 = document.getElementById('a3');
		var a4 = document.getElementById('a4');
		var a5 = document.getElementById('a5');
		var a6 = document.getElementById('a6');
		if(!(a1.checked && a3.checked && a4.checked && a5.checked && a6.checked)){
			alert("Confira as Autorizações e Confirmações. Algumas delas são obrigatórias para a inscrição.");
			return false;
		}
		return true;
	}

	function validaAutorizacaoMidia(f){
		var a1 = document.getElementById('a1');
		var a3 = document.getElementById('a3');

		if(!(a1.checked && a3.checked)){
			alert("Confira as Autorizações e Confirmações. Algumas delas são obrigatórias para a inscrição.");
			return false;
		}
		return true;
	}
function delObj(page){
	//confirmation="Do you want to confirm the deletion";
	confirmation="Você deseja realmente excluir?";
	if(confirm(confirmation)){
	window.location=page;
	}
}

function delImg(id){
	delObj('del_img.php?id='+id);
}
function delStill(videoId,stillId){
	delObj('del_still.php?videoId='+videoId+'&stillId='+stillId);
}
function delStillMidia(videoId,stillId){
	delObj('del_still_midia.php?videoId='+videoId+'&stillId='+stillId);
}

function delVideoData(videoId){
	delObj('video_del.php?id='+videoId);
}

function mostraJava(obj){
    if(obj.value == "JAVA"){
        gid('divjava').style.display = '';
    }else{
        gid('divjava').style.display = 'none';
    }

}


	function validaFinalForm(f){
		var a1 = document.getElementById('a1');
		var a3 = document.getElementById('a3');
		var a4 = document.getElementById('a4');
		var a5 = document.getElementById('a5');
		var a6 = document.getElementById('a6');
		if(!(a1.checked && a3.checked && a4.checked && a5.checked && a6.checked)){
			alert("Confira as Autorizações e Confirmações. Algumas delas são obrigatórias para a inscrição.");
			return false;
		}
		return validaForm(f);
	}
  
function envia_newsletter()
{
	regexp_email=/^[a-z0-9\-](\.?\w)*(\-?\w)*@[a-z0-9\-]+(\.[a-z0-9]+)*(\.[a-z0-9]{2,4})$/i;
	var d=document.cad_newsletter;
	if (!regexp_email.test(d.cadnews.value)) {alert("Por favor, informe um e-mail válido.");d.cadnews.focus();return false;}
	else {
		abre_xml('newsletter.php?email='+d.cadnews.value,'retorna_newsletter','');
		d.cadnews.value='aguarde...';
	}
	return false;
}
function retorna_newsletter(retorno)
{
	if (retorno=='sucesso')
		alert('Seu e-mail foi cadastrado com sucesso.');
	else
		alert(retorno);

	var d=document.cad_newsletter;
	d.cadnews.value='Cadastre-se aqui';
}
function gete(xid) { 
	return document.getElementById(xid); 
}

function abre_xml(link,funcao,extra) {
	var xmlhttp=0; 
	var texto='';
	var erro=false;
	try { 
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
	}
	catch (e) { 
		try {
				xmlhttp=new XMLHttpRequest(); 
			}
		catch (e) {
			erro=true;
			alert("Devido a versao do seu browser ser antiga, voce nao conseguirá realizar esta operação");
		} 
	}
	if (!erro) { 
		var rd=new Date();
		xmlhttp.open("GET",link+((link.indexOf('?')>0)?'&':'?')+'rd='+rd.getTime(),true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				var txt=xmlhttp.responseText.replace(/[\r\t\n]/g,'').replace(/'/g,"\\\'");
				eval(funcao+"('"+txt+((extra!='')?"','"+extra:"")+"')");
			}
		} //function
		xmlhttp.send(null);
	}
}
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	curleft += obj.x;
	return curleft;
}
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	curtop += obj.y;
	return curtop;
}
/*
	Lightbox
*/
var fadeto=0.55;
function abre_video(id_video)
{
	idVideoComent = id_video;
	window.scrollTo( 0, 0 );
	$('#mascara_box')[0].style.background="#000";
	fadeto=0.8;
	abre_ligth_box('video_detalhe.php?id_video='+id_video,719); //719
}
function abre_video_en(id_video)
{
	idVideoComent = id_video;
	window.scrollTo( 0, 0 );
	$('#mascara_box')[0].style.background="#000";
	fadeto=0.8;
	abre_ligth_box('video_detalhe_en.php?id_video='+id_video,719); //719
}
function abre_info_prog(pginfo){
	window.scrollTo( 0, 0 );
	$('#mascara_box')[0].style.background="#000";
	fadeto=0.8;
	abre_ligth_box('lightbox/'+pginfo,441); //441
}
function abre_ligth_box(arquivo,largura){
	var altura=($('#corpo')[0].offsetHeight)+28; //28
	$('#mascara_box')[0].style.width="100%";
	$('#mascara_box')[0].style.height=altura+"px";
	$('#mascara_box').fadeTo("fast", fadeto);
	$('#mascara_box')[0].style.display="block";

	var esq_box=parseInt((findPosX($('#corpo')[0]) + ($('#corpo')[0].offsetWidth/2)) - (largura/2) );
	$('#conteudo_box')[0].className="";
	$('#conteudo_box')[0].style.height="0px";
	$('#conteudo_box')[0].innerHTML='';
	$('#conteudo_box')[0].style.width=largura+"px";
	$('#conteudo_box')[0].style.left=esq_box+"px";

	abre_xml(arquivo,'resposta_light_box','');

	// Tirando os selects (pau no IE)
	var selects=document.getElementsByTagName('select');
	for (var xc=0;xc<selects.length;xc++)
		selects[xc].style.visibility="hidden";
}
function resposta_light_box(conteudo)
{
	$('#conteudo_box').slideDown('fast', function() {
		$('#conteudo_box')[0].className="semfundo";
		$('#conteudo_box')[0].style.height="auto";
		$('#conteudo_box')[0].innerHTML=conteudo;
	});
}
function fecha_ligth_box(){
	$('.video_area_video')[0].style.visibility="hidden";
	$('#conteudo_box').slideUp(800, function() {
		$('#mascara_box').fadeTo("fast", 0, function () {$('#mascara_box')[0].style.display="none";
		// Voltando os selects (pau no IE)
		var selects=document.getElementsByTagName('select');
		for (var xc=0;xc<selects.length;xc++)
			selects[xc].style.visibility="visible";
		});
	});
}
/* ********************************
		TOOLTIP 
*********************************** */
var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = getMouseXY;
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
  if (IE) {
    tempX = event.clientX + scrollLeft();
    tempY = event.clientY + scrollTop();
  } else {
    tempX = e.pageX;
    tempY = e.pageY;
  }  
  if (tempX < 0){tempX = 0;}
  if (tempY < 0){tempY = 0;}  
  return true;
}
function mouse_fora_menu()
{
	var posx=findPosX(gete('link_mnu'));
	var posy=findPosY(gete('link_mnu'));
	var xfinal=posx+getElementWidth(gete('link_mnu'));
	var yfinal=posy+getElementHeight(gete('link_mnu'));
	return (tempX < posx || tempX > xfinal || tempY < posy || tempY > yfinal);
}
function close_menu()
{
	if (mouse_fora_menu())
		gete('link_mnu').style.display='none';
}
function mostra_menu(content,menu)
{
	gete('link_mnu').innerHTML=content;
	if (gete('link_mnu').style.display=='none' || gete('link_mnu').style.display=='')
		gete('link_mnu').style.display='block';
	gete('link_mnu').style.width='115px';
	if (menu==3 || menu==6)
		gete('link_mnu').style.width='auto';
	if (menu && menu!=6)
	{
		gete('link_mnu').style.left=(retorna_left()-8)+'px';
		gete('link_mnu').style.top=(retorna_top()-8)+'px';
	}
	else
	{
		gete('link_mnu').style.left=(retorna_left()+8)+'px';
		gete('link_mnu').style.top=(retorna_top()+8)+'px';
	}
}
function retorna_left()
{
	var sizes=window_size();
	var posx=tempX;
	var cwid=getElementWidth(gete('link_mnu'));
	var xfinal=posx+cwid;
	if (xfinal>((sizes[0]+scrollLeft())-18))
		return posx-(cwid-12);
	else
		return posx;
}
function retorna_top()
{
	var sizes=window_size();
	var posy=tempY;
	var chei=getElementHeight(gete('link_mnu'));
	var yfinal=posy+chei;
	if (yfinal>((sizes[1]+scrollTop())-18))
		return posy-(chei-12);
	else
		return posy;
}
function scrollLeft()
{
	if (IE)
		return ((!document.documentElement.scrollLeft)?document.body.scrollLeft:document.documentElement.scrollLeft);
	else
		return window.pageXOffset;
}
function scrollTop()
{
	if (IE)
		return ((!document.documentElement.scrollTop)?document.body.scrollTop:document.documentElement.scrollTop);
	else
		return window.pageYOffset;
}
function getElementHeight(Elem) {
	return Elem.offsetHeight;
}

function getElementWidth(Elem) {
	return Elem.offsetWidth;
}
function window_size()
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return new Array(myWidth, myHeight);
}
/* ********************************
		FIM TOOLTIP 
*********************************** */