// JavaScript Document


function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function preloading()
{
	var myimages = new Array();
	
	for (x=0; x<preloading.arguments.length; x++)
	{
		myimages[x] = new Image();
		myimages[x].src = preloading.arguments[x];
	}
}

//função redimensiona

function getPageScroll()
{

	var yScroll;
	
	if (self.pageYOffset) 
	{
		yScroll = self.pageYOffset;
	} 
	else if(document.documentElement && document.documentElement.scrollTop)
	{ // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} 
	else if (document.body) 
	{// all other Explorers
		yScroll = document.body.scrollTop;
	}
	
	arrayPageScroll = new Array('',yScroll)
	
	return arrayPageScroll;
}
	
function getPageSize()
{
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) 
	{
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight)
	{ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	}
	else 
	{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) 
	{ // all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} 
	else if (document.documentElement && document.documentElement.clientHeight) 
	{ // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} 
	else if (document.body) 
	{ // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight)
	{
		pageHeight = windowHeight;
	}
	else 
	{
		pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth)
	{
		pageWidth = windowWidth - 18;
	} 
	else 
	{
		pageWidth = xScroll;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

function mostraImagem(img)
{
	document.getElementById('img_imagemAmplida').src = img;
	sleep(2000);
}

var Window =
{
	
	'_open': function(div,divW,divH) 
	{
	
		//sleep(1000);
		document.getElementById(div).style.display = 'block';
		document.getElementById('x_ampliafoto').style.float = 'right';
		
		/*document.getElementById(div).style.width = divW;
		document.getElementById(div).style.height = divH;
		
		alert(document.getElementById(div).style.offsetWidth+' - '+document.getElementById(div).style.Height);*/
		
		//$('#'+div).focus();
		//if (document.all)
		//var pos = evt.clientY;
		//else
		// var pos = window.pageYOffset;
		
		
		
		var pageSize = getPageSize();
		
		var objScroll = getPageScroll();
		
		//alert(objScroll[1]);
		
		var winW = pageSize[0];
		var winY = pageSize[1];
		
		//menos a largura da div
		var w = (winW - divW) / 2;
		 //menos a altura da div
		var y = (winY - divH) / 2;
		
		//var arr = getPageScroll();
		//alert(arr[1]);

			
		document.getElementById(div).style.left = w + 'px';
		document.getElementById(div).style.top = y + 'px';
		if (divH > 500)
			document.getElementById('divFlash').style.visibility = 'hidden';
	}
}

function fechaDiv(div)
{
	document.getElementById(div).style.display = 'none';
	document.getElementById('img_imagemAmplida').src = "imagens/loading.gif";
	document.getElementById('divFlash').style.visibility = 'visible';
}




function $(id){
	return document.getElementById(id);
}

function trocaA(id_div, id_botao){
	$('div_descricao').style.display = 'none';
	$('div_convidados').style.display = 'none';
	$('div_agradecimento').style.display = 'none';
	
	$('btn_descricao').src = 'imagens/bolinha.gif';
	$('btn_convidados').src = 'imagens/bolinha.gif';
	$('btn_agradecimento').src = 'imagens/bolinha.gif';
	
	$(id_div).style.display = 'block';
	$(id_botao).src = 'imagens/bolinhaV.gif';
}

/*
	função que faz um slideshow. recebe um id de uma div que irá conter o slideshow
	um string contendo o caminho das imagens
	e um intervalo de exibição das imagens
*/
function slideshow(id_div,imagens,delay,posicao){
	var array = "";
	array = imagens.split("|");	
	var nextPosicao = posicao + 1;
	if(posicao>=array.length-1) nextPosicao = 0;
	if(document.getElementById(id_div)){
		document.getElementById(id_div).innerHTML = '<img src="'+array[posicao]+'" />';
		var ftimeout = "slideshow('"+id_div+"','"+imagens+"',"+delay+","+nextPosicao+");";
		if(array.length > 1) window.setTimeout(ftimeout,delay);
	}
}


function listaAgencias(val)
{
	loadAjax('load_agencias.php?IDCIDADE='+val,'divAgencias',null,null);	
}



function valida_faleconosco(){
	if($('fnome').value==""){
		alert('Preencha o campo nome. ');
		$('fnome').focus();
		return false;
	}
	if($('femail').value==""){
		alert('Preencha o campo e-mail. ');
		$('femail').focus();
		return false;
	}
	if($('fmensagem').value==""){
		alert('Preencha o campo mensagem. ');
		$('fmensagem').focus();
		return false;
	}
}

function valida_form_novo_cliente(){
	if($('id_categoria').value==0){
		alert('Escolha um destino. ');
		$('id_categoria').focus();
		return false;
	}
	if($('nome').value==""){
		alert('Preencha o campo nome. ');
		$('nome').focus();
		return false;
	}
	if($('email2').value==""){
		alert('Preencha o campo e-mail. ');
		$('email2').focus();
		return false;
	}
	if ($('email2').value.indexOf("@") == -1 || $('email2').value.indexOf(".") == -1) {
		alert("E-mail inválido.");
		$('email2').focus();
		return false;
	}
	/*if(!validacpf($('cpf').value)){
		alert('Preencha o campo CPF com um CPF válido. ');
		$('cpf').focus();
		return false;
	}*/
	if($('rg').value==""){
		alert('Preencha o campo RG. ');
		$('rg').focus();
		return false;
	}
	if( ($('data_dia').value=="")||($('data_mes').value=="")||($('data_ano').value=="") ){
		alert('Preencha o campo Data de Nascimento. ');
		$('data_dia').focus();
		return false;
	}
	if($('endereco').value==""){
		alert('Preencha o campo Endereço. ');
		$('endereco').focus();
		return false;
	}
	if($('bairro').value==""){
		alert('Preencha o campo Bairro. ');
		$('bairro').focus();
		return false;
	}
	if($('cidade').value==""){
		alert('Preencha o campo Cidade. ');
		$('cidade').focus();
		return false;
	}
	if($('estado').value==""){
		alert('Preencha o campo Estado. ');
		$('estado').focus();
		return false;
	}
	if($('pais').value==""){
		alert('Preencha o campo País. ');
		$('pais').focus();
		return false;
	}
	
	
	if($('senha').value==""){
		alert('Preencha o campo senha. ');
		$('senha').focus();
		return false;
	}
}

function valida_form_confirma_transacao(){
	if($('nome').value==""){
		alert('Preencha o campo Convidados. ');
		$('nome').focus();
		return false;
	}
	if($('email2').value==""){
		alert('Preencha o campo E-mail. ');
		$('email2').focus();
		return false;
	}
	if ($('email2').value.indexOf("@") == -1 || $('email2').value.indexOf(".") == -1) {
		alert("E-mail inválido.");
		$('email2').focus();
		return false;
	}
	/*if(!validacpf($('cpf').value)){
		alert('Preencha o campo CPF com um CPF válido. ');
		$('cpf').focus();
		return false;
	}*/
}

function exclui_imagem(id_imagem){
	if(confirm("Você deseja excluir a foto da sua página? ")){
		post_frame.location = "excluir_foto.php?id_imagem="+id_imagem;
	}
}

function verificaValorCota(cota,minimo){
	var valor_cota = cota;
	var valor_minimo = minimo;
	
	while(valor_cota.indexOf(".")!=-1){
		valor_cota = valor_cota.replace(".","");
	}
	valor_cota = valor_cota.replace(",",".");
	
	while(valor_minimo.indexOf(".")!=-1){
		valor_minimo = valor_minimo.replace(".","");
	}
	valor_minimo = valor_minimo.replace(",",".");
	
	valor_cota = valor_cota*1;
	valor_minimo = valor_minimo*1;
	
	if(valor_cota<valor_minimo){
		alert("O valor mínimo para cota livre é de R$ " + minimo);
		return false;
	}
	return true;
	$('quantidade_cota_livre').focus();
}

//Função para formatar moeda R$
function teclas(campo,evt){
    if(((evt.keyCode < 96) || (evt.keyCode > 105)) && ((evt.keyCode < 48) || (evt.keyCode > 57)) ){
           campo.value = campo.value.replace(String.fromCharCode(evt.keyCode).toLowerCase(),"");
    }
}
function formataMoeda(campo,evt){
       // para evitar caracteres alfas.
       teclas(campo,evt);
       str = campo.value;

       while(str.search(",") != -1)
           str = str.replace(",","");
       i = 0;

       while(i< str.length){
           if(str.substr(i,1) == ".")
              str = str.replace(".","");
              i++;
       }

       part1 = str.substr(0,str.length - 2);
       while(part1.search(" ") != -1)
           part1 = part1.replace(" ","");

           part2 = str.substr(str.length - 2,2);
           res = "";
           i = part1.length;
           sob = i % 3;
           if((sob != 0) && (i > 2))
              res = part1.substr(0,sob) + ".";
           else
              res = part1.substr(0,sob);
           j = 1;
           part1 = part1.substr(sob);
           i = 0;
           while(i < part1.length){
              if(j == 3){
                 if(i + 1 == part1.length)
                    res = res + part1.substr(i-2,3);
                 else res = res + part1.substr(i-2,3) + ".";
              }
              i++;
              j = j<3?j+1:1;
           }
           campo.value = res + "," + part2;
}

function validacpf(cpf){
	var i; 
	s = cpf.replace(".","");
	s = s.replace(".","");
	s = s.replace("-","");
	$('cpf').value = s;
	var c = s.substr(0,9); 
	var dv = s.substr(9,2); 
	var d1 = 0; 
	for (i = 0; i < 9; i++){ 
		d1 += c.charAt(i)*(10-i); 
	} 
	if (d1 == 0){ 
		return false; 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(0) != d1){ 
		return false; 
	}
	  
	d1 *= 2; 
	for (i = 0; i < 9; i++){ 
		d1 += c.charAt(i)*(11-i); 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(1) != d1){ 
		return false; 
	} 
	return true; 
} 

function responde(email,nome){
		var winW;
		var winH;
		var y;
		if(document.all){
			y = document.documentElement.scrollTop;
		}else{
			y = window.pageYOffset;
		}		
		if (parseInt(navigator.appVersion)>3) {
		 if (navigator.appName=="Netscape") {
		  winW = window.innerWidth;
		  winH = window.innerHeight;
		 }
		 if (navigator.appName.indexOf("Microsoft")!=-1) {
		  winW = document.documentElement.offsetWidth;
		  winH = document.documentElement.offsetHeight;
		 }
		}
		var posx = (winW - 400) / 2;
		
		$('div_nome').innerHTML = "<strong>Nome:</strong> " + nome;
		$('div_email').innerHTML = "<strong>E-mail:</strong> " + email;
		$('email').value = email;
		
		$('div_responde_amigo').style.display = "block";
		$('div_responde_amigo').style.left = posx + "px";
	}

function abre_pagina(id,nome){
	loadAjax('pagina_cliente.php?id='+id+'&nome='+nome,'content');
}

function buscaClientes(){
	var nome = document.getElementById('nome_usr').value;
	loadAjax('busca_clientes.php?n='+nome,'content');
}

function validaBusca(){
	var campoBusca = document.frmbusca.nome_usr;
	if(campoBusca != null){
		if(campoBusca.value.length < 3){
			alert("O texto da busca deve conter no mínimo três caracteres.");
			campoBusca.focus();
		}else{
			loadAjax('busca_clientes.php?n='+document.getElementById('nome_usr').value,'content');
		}
	}
}

function openClose(){
	if($('div_fotos').style.display=="none"){
		$('div_fotos').style.display="block";
	}else{
		$('div_fotos').style.display="none";
	}
}

//AJAX GERAL
var reqs = new Array();

function uncache(url){
	var d = new Date();
	var time = d.getTime();

	if (new String(url).indexOf("?") < 0)
		strurl = "?";
	else
		strurl = "&";

	url = url + strurl + 'timecache='+time;
	return url;
	
} 

function CXMLReq(type, xmlhttp, target, func){
	this.type = type;
	this.xmlhttp = xmlhttp; 
	this.target = target;
	this.func = func;
}

function loadAjax(url, target, func, msg){
   var xhr = false;
   // native XMLHttpRequest object
	if (msg)
		mensagem = msg;
	else
		mensagem = '<div id="loading"><img src="imagens/loading.gif" width="11" height="11" style="padding-right:10px;">&nbsp;Aguarde, carregando...</div>';
    document.getElementById(target).innerHTML = mensagem;
   if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {jahDone();};
        xhr.open("GET", url, true);
        xhr.send(null);
    // IE/Windows ActiveX version
   } else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
        if (xhr) {
            xhr.onreadystatechange = function() {jahDone();};
            xhr.open("GET", uncache(url), true);
            xhr.send();
        }
   }
   
   var xmlreq = new CXMLReq('', xhr, target, func);
   reqs.push(xmlreq);
}    

function jahDone() {
	if (typeof(window['reqs']) == "undefined") return;
	// only if req is "loaded"
	for (var req=0; req<reqs.length; req++)
	{
		if (reqs[req].xmlhttp.readyState == 4) {
			// only if "OK"
			results = reqs[req].xmlhttp.responseText;
			target = reqs[req].target;
			func = reqs[req].func;
			statusText = reqs[req].xmlhttp.statusText;
			if (reqs[req].xmlhttp.status == 200 || reqs[req].xmlhttp.status == 304) {
				reqs.splice(req,1); req --;
				o = document.getElementById(target);
				o.innerHTML = results;
				if (haveJS(o))
					execJS(o);
				if (func)
					eval(func);
			} else {
				document.getElementById(target).innerHTML="jah erro:\n" + statusText;
				reqs.splice(req,1); req --;
			}
		}
	}
}

var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bMoz = (navigator.appName == 'Netscape');

function haveJS(node)
{
  var st = node.getElementsByTagName('SCRIPT');
  if (st.length > 0)
  	return true;
  else
    return false;
}

function execJS(node) 
{
  var st = node.getElementsByTagName('SCRIPT');
  var strExec;
  for(var i=0;i<st.length; i++) {
	if (bSaf) {
	  strExec = st[i].innerHTML;
	}
	else if (bMoz) {
	  strExec = st[i].textContent;
	}
	else {
	  strExec = st[i].text;
	}
	try {
	  //mostraLog('chamando isso:' + strExec);
	  eval(strExec);
	} catch(e) {
	  alert(strExec);
	  if (window.ActiveXObject)
		  alert(e.description);
	  else
	  	  alert(e);
	}
  }
}

//Função de redirecionamento de páginas
function redir(url){
	window.open(url);	
}