/* Expresões regulares de validação */
var er_email = /^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/;


/* Home - Site */
function montaNoticia(p_inicial,p_final)
{
    furl = site_url + "home/noticiaHome/";
    $.post(furl, { final: p_final, inicial: p_inicial }, retornoNoticia, "html");
}

function retornoNoticia(data)
{
	eval(data);
	$('#effect_noticia').fadeOut('def',function(){
	    try{
	        document.getElementById("noticia").innerHTML=noticias;
	        document.getElementById("pag_rodape").innerHTML=pag_proxima+pag_anterior;		
		}catch(e){}		
		$('#effect_noticia').fadeIn();
	});	       
}

function montaDestaque(indice)
{
	if(ids_dest.length > 0){
	    furl = site_url + "home/destaqueHome/";
	
		clearInterval(intervalo);
		intervalo = window.setInterval(function(){montaDestaque(indiceDestaque+1)}, tempoTroca);	
	
		indiceDestaque = indice;
		if (indiceDestaque < 0) {indiceDestaque = ids_dest.length - 1;}
		if (indiceDestaque == ids_dest.length) {indiceDestaque = 0;}
	
		var atual = ids_dest[indiceDestaque];
	
	    var img= "<a href='"+atual[2]+"'><img class='dest' name='destaque_home' src='"+atual[1]+"'/></a>"; 
	    var titulo= "<a href='"+atual[2]+"'>"+atual[0]+"</a>";
	    var pag_anterior= "<a class='set_esq mh' href='javascript:montaDestaque(indiceDestaque-1);'><img src='"+base_url+"img/seta_esq_cinza.gif' /></a>";
		var pag_proxima= "<a class='set_dir mh' href='javascript:montaDestaque(indiceDestaque+1);'><img src='"+base_url+"img/seta_dir_cinza.gif' /></a>";
	
		$('#effect_destaque').fadeOut('def',function(){
		    try{
		        document.getElementById("destaque").innerHTML=img;
		        document.getElementById("titulo").innerHTML=titulo;
		        document.getElementById("pag").innerHTML=pag_proxima+pag_anterior;		
			}catch(e){}		
			$('#effect_destaque').fadeIn();
		});	
	}		
}

/* Contato */

function ct_troca_cidades_briefing(obj){
	var id_estado=obj.options[obj.selectedIndex].value;
	
	document.f.uf_estado.value = obj.options[obj.selectedIndex].text;
	
	if (id_estado>0)
	{
		$('#cidade')[0].innerHTML='<option value="0">'+__l.contato_aguarde+'</option>';		
		
		$.ajax({
		type: "GET",
		async: true,
		data: "",
		cache: true,
		url: base_url+"contato/buscar_cidades/"+id_estado+'/nome',
		success: function(msg){
			if (msg!='' && msg.indexOf('option')>0)
			{
				var ret='<option value="0">'+__l.contato_sel_cidade+'</option>';
				ret+=msg+'';
				$('#cidade')[0].innerHTML=ret;
				resizeBlockDir();
			}
			else
				alert('Por favor, selecione o estado corretamente.');			

		}
		});
	}
}

function ct_troca_cidades(obj)
{
	var id_estado=obj.options[obj.selectedIndex].value;
	$('#area_cidades')[0].innerHTML='<select name="cidade" id="cidade"><option value="0">'+__l.contato_sel_estado+'</option></select>';
	if (id_estado>0)
	{
		$('#area_cidades').html('<select name="cidade" id="cidade"><option value="0">'+__l.contato_aguarde+'</option></select>');
				
		$.ajax({
		type: "GET",
		async: true,
		data: "",
		cache: true,
		url: base_url+"contato/buscar_cidades/"+id_estado,
		success: function(msg){ct_troca_cidades_resposta(msg);}
		});
	}
}
function ct_troca_cidades_resposta(msg)
{
	if (msg!='' && msg.indexOf('option')>0)
	{
		var ret='<select name="cidade" id="cidade"><option value="0">'+__l.contato_sel_cidade+'</option>';
		ret+=msg+'</select>';
		$('#area_cidades')[0].innerHTML=ret;
		resizeBlockDir();
	}
	else
		alert('Por favor, selecione o estado corretamente.');
} 
function ct_troca_endereco(obj)
{
	var id_filial=obj.options[obj.selectedIndex].value;
	$('#endereco_info')[0].innerHTML="";
	if (id_filial>0)
	{
		$.ajax({
		type: "GET",
		async: true,
		data: "",
		cache: true,
		url: base_url+"contato/buscar_filial_info/"+id_filial,
		success: function(msg){ct_troca_endereco_resposta(msg);}
		});
	}
}
function ct_troca_endereco_resposta(msg)
{
	if (msg!='')
	{
		var ret=msg;
		$('#endereco_info')[0].innerHTML=ret;
		resizeBlockDir();
	}
	else
		alert('Por favor, selecione a filial corretamente.');
}
function ct_fecha_msg()
{
	$("#ct_msg").slideUp("fast",function () {$("#ct_form").slideDown("normal");} );
}
function env_fecha_msg()
{
	$("#ct_msg_env").slideUp("fast",function () {$("#ct_form").slideDown("normal");} );
}

function busca_envia(lbusca)
{
	var d_b=document.f_busca;
	if (d_b.q.value.length<2 || d_b.q.value==lbusca) {alert(__l.busca_preencha);d_b.q.focus();}
	else {d_b.submit();}

	return false;
}

function inputBusca(obj, value){
    $(obj).bind("focus blur", function(e){
		if($(this).val() == value){
			$(this).val("");
		}else if($(this).val() == ""){
			$(this).val(value);
		}
    });
}


/* Galeria de Imagens */
var blockScroll = true;
var pxScroll = 70 * 6;
function initGaleria(){
	/* Seta tamanho div slide */
	$("#galeria_slide_lista").width($('#galeria_slide_container ul li').length * 70 - 10);
	
	/* Ação avança, retorna fotos */
	$("#btn_gal_esq, #btn_gal_dir").click(function() {
		if(blockScroll){
			blockScroll = false;
			var directionScroll = ($(this).attr("id") == "btn_gal_esq")?'-=':'+=';
			$('#galeria_slide_container').scrollTo( directionScroll+pxScroll, 1000, {axis:'x', onAfter:function(){blockScroll = true}} );
		}
	});	
}

/* Detalhe galeria na própria página */
function detalheGaleria(myUrl, id, isFlv,texto, tipo){
	if(id != idGal){
		
		if(isFlv == 0){
			var img = '';
			
			if(tipo != null){
				if(tipo == 'ondemand' || tipo == 'digital'){
					img  = '<table border="0" cellpadding="0" cellspacing="0" align="center">';
					if(tipo != 'digital'){
						img += '<tr><td bgcolor="#7E7378">'+((texto != undefined && texto != '')?'<div class="galeria_texto_foto">'+texto+'</div>':'')+'</td></tr>';
					}
					img += '<tr><td><div id="borda_video" class=""><img id="swf_replace" src="'+myUrl+'"></div></td></tr>';
					img += '</table>';					
				}
			}else{
				img = "<img id='swf_replace' src='"+myUrl+"' onload>";	
			}
			
			$('#block_dir').css('height', $('#block_dir').height());			
			$('#show_detalhe_galeria').fadeOut('def', function(){
				$('#borda_video').css('border','');
				$('#show_detalhe_galeria').html(img);
				$('#show_detalhe_galeria').fadeIn('def', function(){$('#block_dir').css('height','auto');resizeBlockDir();});
						
			});
		}else{
	    	var flashvarsM 		= {url:myUrl};
	    	var paramsM 		= {wmode:'opaque', allowfullscreen:"true"};
	    	var attributesM 	= {};
	    	
			$('#show_detalhe_galeria').fadeOut('def', function(){
				$('#borda_video').css('border','9px solid #7E7378');
				// $("#texto_legenda_slide").html(texto);
	    		swfobject.embedSWF(base_url+'swf/player.swf?tc='+new Date().getTime(), 'swf_replace', '492', '360', '9.0.0','expressInstall.swf', flashvarsM, paramsM, attributesM);
				$('#show_detalhe_galeria').fadeIn();			
			})    	
		}
		
	}
	idGal = id;
}



/* Função de envio do indique para um amigo */
var blockSend = false;
function envieAmigo(){

	$("#close_confirm_amigo").click(function(){
		$("#ct_msg_env").fadeOut('def', function(){
			$("#form_envie_site").fadeIn();
		});			
	});	
	
	$("#btn_enviar_amigo").click(function(){
		if(blockSend == true){
			return false;	
		}
				
		if($("#nome_meu").val().length < 2){
			alert(__l.envie_nome);
			$("#nome_meu")[0].focus();
		}else if($("#email_meu").val().length < 2){
			alert(__l.envie_email);
			$("#email_meu")[0].focus();				
		}else if(!er_email.test($("#email_meu").val())){
			alert(__l.envie_email_valido);
			$("#email_meu")[0].focus();
		}else if($("#nome_amigo").val().length < 2){
			alert(__l.envie_nome_amigo);
			$("#nome_amigo")[0].focus();
		}else if($("#email_amigo").val().length < 2){
			alert(__l.envie_email_amigo);
			$("#email_amigo")[0].focus();				
		}else if(!er_email.test($("#email_amigo").val())){
			alert(__l.envie_email_amigo_valido);
			$("#email_amigo")[0].focus();				
		}else if($("#mensagem_amigo").val().length < 2){
			alert(__l.envie_mensagem);
			$("#mensagem_amigo")[0].focus();	
		}else{
			var send_data = {
				nome_meu: $("#nome_meu").val(),
				email_meu: $("#email_meu").val(),
				nome_amigo: $("#nome_amigo").val(),
				email_amigo: $("#email_amigo").val(),	
				aceita_newsletter: ($("#aceita_newsletter").is(":checked") ? '1' : '0'),				
				url_atual: current_url,									
				mensagem_amigo: $("#mensagem_amigo").val()
			};
			
			blockSend = true;
			
			$.post(site_url+"home/enviar_amigo_send", send_data ,
				function(data){
					if(data == '1') {
						clearFormEnvie();
						$("#form_envie_site").fadeOut('def', function(){
							blockSend = false;
							$("#ct_msg_env").fadeIn();
						});								
					}else{
						alert(__l.envie_erro);
						blockSend = false;
					}
				}
			);
		}
	});
	function clearFormEnvie(){
		$("#nome_meu").val("");
		$("#email_meu").val("");	
		$("#nome_amigo").val("");							
		$("#email_amigo").val("");		
		$("#mensagem_amigo").val("");
		$("#aceita_newsletter")[0].checked = false;
	}	
}

/* Popup Intrucoes enox Expressioins */
function show_tutorial(tipo){
	/* dependent,directories,fullscreen,location,menubar,resizable,scrollbars,status,toolbar,top=200,left=400,width=200,height=200,screenX=400,screenY=200 */
	var width = 500;
	var height = 145;
	var int_windowLeft = (screen.width - width) / 2;
	var int_windowTop = (screen.height - height) / 2;	
	newwindow=window.open(site_url+'home/instrucoes/'+tipo,'popenox','height='+height+',width='+width+',top='+int_windowTop+',left='+int_windowLeft+',directories=no,fullscreen=no,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,toolbar=no');
	if (window.focus) {newwindow.focus()}
	return false;
}

/* Normaliza  tamanho do bloco direito */
function resizeBlockDir(){
	if($('#block_dir').height() <= $('#block_esq').height() && notRezise == false){
		$('#block_dir').css('height', $('#block_esq').height());
	}	
}

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/string/is-cpf [rev. #1]
String.prototype.isCPF = function(){
    var c = this;
    if((c = c.replace(/[^\d]/g,"").split("")).length != 11) return false;
    if(new RegExp("^" + c[0] + "{11}$").test(c.join(""))) return false;
    for(var s = 10, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    for(var s = 11, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    return true;
};


$(document).ready(function() {
	// Inicia Galeria
	initGaleria();

	// Envie para amigo
	$('#menu_envie').click(function(){
		$('#player_home, #home_banner_swf').css('visibility','hidden');
		abreLightbox(site_url+'home/enviar_amigo_lightbox',700,20);
	});	

	// limpa estado de contato no reload
	if(current_url.indexOf('contato') != -1){
		if($('#estado')[0] != 'undefined' && $('#estado')[0] != null)
			$('#estado')[0].selectedIndex = 0;
	}
});