// JavaScript Document

function ajaxInit() {
	var req;
	try {
		 req = new ActiveXObject("Microsoft.XMLHTTP");
	} catch(e) {
		 try {
			  req = new ActiveXObject("Msxml2.XMLHTTP");
		 } catch(ex) {
		 try {
		   req = new XMLHttpRequest();
	     } catch(exc) {
	 		  alert("Esse browser não tem recursos para uso do Ajax");
	  		 req = null;
	     }
	 }
}
return req;
}

function carregaCombo(url, codigo, id) {
	//alert(url + "?codigo=" + id)
	ajax = ajaxInit();
	if(ajax) {
		ajax.open("GET",url + "?codigo=" + codigo, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					document.getElementById(id).innerHTML = ajax.responseText;
				}else{
					alert(ajax.statusText);
				}
			}
		}
		ajax.send(null);
	}
}

function preencheInput(idCodigo,idRet,tabela,campo,campoRet) 
{
	ajax = ajaxInit();
	codLoc = document.getElementById(idCodigo);
	if( (ajax) && (codLoc) && (codLoc.value != "") )
	{
		if( (tabela == "CTPCTAS") && (codLoc.value.substring(codLoc.value.length - 3,codLoc.value.length) == "000") )
		{
			alert("Atenção, plano de conta não recebe valor");
			codLoc.value = "";
			document.getElementById(idRet).value="";
		}
		else
		{
			wurl = "buscaCodigo.asp?tabela="+tabela+"&campo="+campo+"&codigo="+codLoc.value+"&campoPreenche="+campoRet;
			
			extra = document.getElementById("extra")
			if( (extra) && (extra.value != "") )
			{
				vet_extra = extra.value.split("|");
				campoExtra = vet_extra[0];
				valorCampo = document.getElementById(vet_extra[1]);
				if (valorCampo)
				{
					wurl = wurl + "&campoExtra=" + campoExtra + "&valorExtra=" + valorCampo.value
				}
			}	
			
			ajax.open("GET",wurl, true);
			objFocus = codLoc
			ajax.onreadystatechange = function()
			{
				if(ajax.readyState == 4)
				{
					if(ajax.status == 200)
					{
						retornoBusca = ajax.responseText;
						if (retornoBusca == "n_encontrado")
						{
							alert("Registro não encontrado");
							codLoc.value = "";
							document.getElementById(idRet).value="";
						}
						else
						{
							document.getElementById(idRet).value = retornoBusca;
						}								
					}else{	
						alert(ajax.statusText)
					}
				}
			}
			ajax.send(null);	
		}
	}
}

function listaResultado(parametrosBanco,id,idIns,IdDel,idLista)
{
	//vet_parametrosBanco -  
	 //0 url, 1 banco,2 campo de codigo(chave primeria),3 campo do where,4 largura div,5 margin div
	
	
	ajax = ajaxInit();
	valBusca = document.getElementById(id).value;
	if( (ajax) && (valBusca != "") )
	{
		
				
		vet_paramet = parametrosBanco.split("|");
		wurl = "buscaAutoListagem.asp?tabelaBusca=" + vet_paramet[1] + "&campoCodigo=" + vet_paramet[2] + "&campo=" + vet_paramet[3] + "&digitado="+ valBusca + "&camposIns=" + idIns + "&camposApagar=" + IdDel + "&width="+vet_paramet[4]	
		
		
		extra = document.getElementById("extra")
		if( (extra) && (extra.value != "") )
		{
			vet_extra = extra.value.split("|");
			campoExtra = vet_extra[0];
			valorCampo = document.getElementById(vet_extra[1]);
			if (valorCampo)
			{
				wurl = wurl + "&campoExtra=" + campoExtra + "&valorExtra=" + valorCampo.value
			}
		}		
		
		
		ajax.open("GET",wurl, true);
		ajax.onreadystatechange = function()
		{
			if(ajax.readyState == 4)
			{
				if(ajax.status == 200)
				{
					retornoBusca = ajax.responseText;
					if (retornoBusca == "n_encontrado")
					{
						document.getElementById(idLista).innerHTML = "";
						document.getElementById(idLista).className = "result_s_borda";
					}
					else
					{
						
						document.getElementById(idLista).innerHTML = "";
						document.getElementById(idLista).innerHTML = ajax.responseText;	
						document.getElementById(idLista).className = "result_c_borda";						
						document.getElementById(idLista).style.width = vet_paramet[4] + "px";
						document.getElementById(idLista).style.marginLeft = vet_paramet[5] + "px"; 
					}	
					
				}else
				{	
					alert(ajax.statusText)
				}
			}
		}
		ajax.send(null);		
	}	
	else
	{
		if(valBusca == "")
		{
			setTimeout ("limpaListagem()",1000 );		
		}
				
	}
}
function limpaListagem()
{
	obj = document.getElementsByTagName("div");
	for(i=0;i<obj.length;i++)
	{
		if (obj[i].className == "result_c_borda")
		{
			obj[i].innerHTML = "";
			obj[i].className = "result_s_borda";
			break;
		}
		
	}
}
function retiraFocus()
{
	setTimeout("limpaListagem()",800);	
}
function trocaPosition(idDiv)
{
	obj = document.getElementsByTagName("div");
	
	for(i=0;i<obj.length;i++)
	{
		aux = obj[i].title;
		if( (aux != idDiv) && (obj[i].title != "") )
		{
			obj[i].className = "listStatic";						
			
		}
		if( (aux == idDiv) && (obj[i].title != "") )
		{
			obj[i].className = "listRelative";
		}
		
	}	
	
}

//funções para menu suspenso
function pegaDados(codigo,controle,submenu,menu){
	conter = document.getElementById(controle).value;
	if (conter=="1"){
		h=100;
		document.getElementById(controle).value="0";
		document.getElementById(submenu).padding="0px";
		document.getElementById(submenu).style.lineHeight="0px";
		document.getElementById(submenu).style.display="none";
		
	}else{
		h=0;
		document.getElementById(controle).value="1";
		document.getElementById(submenu).style.lineHeight="normal";
		document.getElementById(submenu).style.display="";
		document.getElementById(controle).value="1";
	}
}

function checado_antigo(name, cod, id){
	
	novoCod="";
	if(document.getElementById(name).checked){
		document.getElementById(id).value += cod+"|"; 
	}
	if(document.getElementById(name).checked==false){
		valores = document.getElementById(id).value;
		document.getElementById(id).value="";
		codigos = valores.split("|");
		
		for (i=0;i<=codigos.length-2;i++){
			
			if(codigos[i] != cod){
				novoCod = novoCod+codigos[i]+"|";
				document.getElementById(id).value=novoCod;
			}
		}
	}
}

function checado(cod,obj,cont2){
	id = "cod_quartos"+cont2;
	novoCod="";
	if(obj.checked){
		document.getElementById(id).value += cod+"|"; 
	}
	if(obj.checked==false){
		valores = document.getElementById(id).value;
		document.getElementById(id).value="";
		codigos = valores.split("|");
		
		for (i=0;i<=codigos.length-2;i++){
			
			if(codigos[i] != cod){
				novoCod = novoCod+codigos[i]+"|";
				document.getElementById(id).value=novoCod;
			}
		}
	}
	verificaTipoHotel('hoteis',cont2)
}
function verificaTipoHotel(form,conta){
	key = 0
	objs = document.getElementById("hoteis"+conta).getElementsByTagName("input");
	
	for(i=0;i<objs.length;i++){
		
		if(objs[i] != null){
			if(objs[i].type == "checkbox"){			
				if(objs[i].checked==true){
					key = 1
				}
			}
		}
	}
	
	if(key == 0){
		document.getElementById("inp_busca"+conta).disabled = true;
		document.getElementById("inp_busca"+conta).style.filter ="progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)"
	}else{
		document.getElementById("inp_busca"+conta).disabled = false;
		document.getElementById("inp_busca"+conta).style.filter =""
	}
}

function isInt(id)
{
   	element = document.getElementById(id)
	var str = /^\d+$/;
	return str.test(valor_text);
}


function formatar(id, mask)
{
	src = document.getElementById(id);
	var i = src.value.length;
  	var saida = mask.substring(0,1);
  	var texto = mask.substring(i)
	if (texto.substring(0,1) != saida)
  	{
    	src.value += texto.substring(0,1);
  	}
}
function formatarFone(id)
{
	src = document.getElementById(id);
	var i = src.value.length;
	if(i==1)
	{
		src.value = "(" + src.value;
	}
	if(i==3)
	{
		src.value = src.value + ") " 
	}
	if(i==9)
	{
		src.value = src.value + "-" 
	}
	
	
}
function formatarValor(id)
{
	obj = document.getElementById(id)
	if( obj )
	{
		valor_aux = new String(obj.value);
	}
	else
	{
		valor_aux = new String(id)
	}
	
	if( valor_aux != "")
	{
		if(isFloat(valor_aux) == true)
		{
			pos = valor_aux.search(",");
			valorFinal = 0
			if(pos != -1)
			{
				vet_valor = valor_aux.split(",");
				valor = vet_valor[0];
				valor= valor.replace(".","")
				valor= valor.replace(".","")
				valor= valor.replace(".","")
				valor= valor.replace(".","")
				valor= valor.replace(".","")
				valor = valor * 100;
				valor = valor / 100;
				valor = new String(valor);	
				if(valor != "")
				{
					if (vet_valor[1].length == 2)
					{
						valor = formataFloatPonto(valor) + "," + vet_valor[1];
						valorFinal = valor;
					}
					else
					{
						if (vet_valor[1].length > 2)
						{
							vet_valor[1] = vet_valor[1].substring(0,2);	
							valor = formataFloatPonto(valor) + "," + vet_valor[1]
							valorFinal = valor;
						}
						else
						{
							valor = formataFloatPonto(valor) + "," + vet_valor[1] + "0"	
							valorFinal = valor;
						}
					}
				}
				else
				{
					valor = formataFloatPonto(valor) + ",00"; 
					valorFinal = valor;
				}
			}
			else
			{
				valor_aux= valor_aux.replace(".","")
				valor_aux= valor_aux.replace(".","")
				valor_aux= valor_aux.replace(".","")
				valor_aux= valor_aux.replace(".","")
				valor_aux= valor_aux.replace(".","")				
				valorFinal = formataFloatPonto(valor_aux) + ",00"
				
			}
			if( document.getElementById(id) )
			{
				document.getElementById(id).value = valorFinal;	
			}
			else
			{
				return valorFinal	
			}
		}
	}
	
}
function formataFloatPonto(valorParam)
{
	valor = valorParam;	
	tam_vet = parseInt(valor.length / 3)
	var vet_aux = new Array();				
	cont = 0;
	contVet = 0
	if (valor != "")
	{
		if (valor.length > 3)
		{
				
			for(i=valor.length;i>0;i--)
			{
				if( ( cont % 3 == 0)  && (cont > 0) )
				{
					vet_aux[contVet] = i;
					contVet = contVet + 1;
				}	
				cont = cont + 1
			}
			for(i=0;i<vet_aux.length;i++)
			{
				valor = valor.substring(0,vet_aux[i]) + "." + valor.substring(vet_aux[i],valor.length);				
			}
			
		}
	}
	else
	{
		valor = "0";
	}
	return valor
}

function insNumeric(obj,event)
{
    if(obj.id == "cep1")
	{
		maxLengh = 4
		if( $.browser.msie )
		{
			setTimeout(function(){
				if( obj.value.length == 5)
				{
					document.getElementById("cep2").focus();	
				}
			},300)
			
		}
		else
		{		
			if( obj.value.length == maxLengh)
			{
				document.getElementById("cep2").focus();	
			}
		}
	}
	
	var tecla = event.charCode;
    var ie = event.keyCode;
    if (!event) event = window.event;
    var code;
    if (event.keyCode) code = event.keyCode;
    else if (event.which) code = event.which; // Netscape 4.?
//se nao for número nem parentesis ou espaço
    if ((code < 48 || code > 59) && (code != 8 ) && (code != 13 ) ){      
	  event.returnValue = false;
      if (event.which){
        event.preventDefault();
      }
      return false;
    }else{
      event.returnValue = true;
      return true;
    }
 }
function insFloat(obj,event)
{
    var tecla = event.charCode;
    var ie = event.keyCode;
    if (!event) event = window.event;
    var code;
    if (event.keyCode) code = event.keyCode;
    else if (event.which) code = event.which; // Netscape 4.?
//se nao for número nem parentesis ou espaço
    if ((code < 48 || code > 59) && (code != 8 ) & (code != 44) && (code != 13 )){
      event.returnValue = false;
      if (event.which){
        event.preventDefault();
      }
      return false;
    }else{
      event.returnValue = true;
      return true;
    }
} 
function mask(_mask, val) {
	var i, mki;
	var aux="";
	
	for(i=mki=0; i<val.length; i++, mki++) {
		if(_mask.charAt(mki)=='' || _mask.charAt(mki)=='#' || _mask.charAt(i)==val.charAt(i)) {
			aux+=val.charAt(i);
		} else {
			aux+=_mask.charAt(mki)+val.charAt(i);
			mki++;
		}
	}
	return aux;
}
function mascaraNumero(obj,event,_mask)
{
    var tecla = event.charCode;
    var ie = event.keyCode;
    if (!event) event = window.event;
    var code;
    if (event.keyCode) code = event.keyCode;
    else if (event.which) code = event.which; // Netscape 4.?
//se nao for número nem parentesis ou espaço
    var strCheck = '0123456789';
	rcode = code
    key=String.fromCharCode(rcode);
	
	
	  if( code != 8 && code != 9 && code != 46 && code != 39 && code !=37 && code !=116 && code !=13 ){
	//Not a valid key
		
		if( (strCheck.indexOf(key)==-1 || (obj.value.length >= _mask.length) ) )
		{
			return false;
		}
		aux=obj.value+key;
		//window.alert(aux);
		aux=mask(_mask,aux);
		//window.alert(aux);
		obj.value=aux;	
		return false;
	 }
	 else
	 {
		
		event.returnValue = true;
      	return true; 
	 }    


 }

function isFloat(valor)
{
	var valor_text = valor;
	var str = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
	return str.test(valor_text);
}

function pegarHora(campo){
	hora = new Date;
	wHora = hora.getHours();
	wMin = hora.getMinutes();
	if(wMin < 10){
		wMin = "0" + wMin;
	}
	wSec = hora.getSeconds();
	if(wSec < 10){
		wSec = "0" + wSec;
	}
	
	//wHoraF = wHora +":"+ wMin +":"+ wSec;
	wHoraF = wHora +":"+ wMin;
	
	document.getElementById(campo).innerHTML = wHoraF;
	
	setTimeout("pegarHora('"+campo+"')",1);
}
function pegarData(){
	var nomeDia;
	data = new Date;
	dia  = data.getDay();
	mes = data.getMonth();
	ano = data.getFullYear();
	
	switch(dia){
		case 0:
			nomeDia = "Domingo";
		case 1:
			nomeDia = "Segunda-feira";
		case 2:
			nomeDia = "Terça-feira";
		case 3:
			nomeDia = "Quarta-feira";
		case 4:
			nomeDia = "Quinta-feira";
		case 5:
			nomeDia = "Sexta-feira";
		case 6:
			nomeDia = "Sábado";
	}
	
	switch(mes){
		case 0:
			nomeMes = "janeiro";
		case 1:
			nomeMes = "fevereiro";
		case 2:
			nomeMes = "março";
		case 3:
			nomeMes = "abril";
		case 4:
			nomeMes = "maio";
		case 5:
			nomeMes = "junho";
		case 6:
			nomeMes = "julho";
		case 7:
			nomeMes = "agosto";
		case 8:
			nomeMes = "setembro";
		case 9:
			nomeMes = "outubro";
		case 10:
			nomeMes = "novembro";
		case 11:
			nomeMes = "dezembro";
	}
	
	campoData = document.getElementById("data_semana");
	campoData.innerHTML = nomeDia +", "+ dia +" de "+ nomeMes +" de "+ ano +".";	
}


function janelaBusca(url,id,idIns,IdDel,largura,altura)
{
	element = document.getElementById(id)
	extra = document.getElementById("extra")
	wurl = url + "&digitado="+ element.value + "&camposIns=" + idIns + "&camposApagar=" + IdDel	
	
	if( (extra) && (extra.value != "") )
	{
		vet_extra = extra.value.split("|");
		campoExtra = vet_extra[0];
		valorCampo = document.getElementById(vet_extra[1]);
		if (valorCampo)
		{
			wurl = wurl + "&campoExtra=" + campoExtra + "&valorExtra=" + valorCampo.value
		}
	}
	
	winDt = window.open(wurl,'','top=300,left=600,width='+ largura +',height='+ altura +',scrollbars=1,status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0');
	winDt.focus();
}
function verTecla(obj,event,parametrosBanco,id,idIns,IdDel,idLista)
{
	var tecla = event.charCode;
    var ie = event.keyCode;
    if (!event) event = window.event;
    var code;
    if (event.keyCode) code = event.keyCode;
    else if (event.which) code = event.which; // Netscape 4.?
//se nao for número nem parentesis ou espaço

    if (code == 13)
	{
      	element = document.getElementById(id);
		vet_paramet = parametrosBanco.split("|");
		wurl = vet_paramet[0] + "?tabelaBusca=" + vet_paramet[1] + "&campoCodigo=" + vet_paramet[2] + "&campo=" + vet_paramet[3] + "&digitado="+ element.value + "&camposIns=" + idIns + "&camposApagar=" + IdDel	
		
		extra = document.getElementById("extra")
		if( (extra) && (extra.value != "") )
		{
			vet_extra = extra.value.split("|");
			campoExtra = vet_extra[0];
			valorCampo = document.getElementById(vet_extra[1]);
			if (valorCampo)
			{
				wurl = wurl + "&campoExtra=" + campoExtra + "&valorExtra=" + valorCampo.value
			}
		}
		
		winDt = window.open(wurl,'','top=300,left=600,width=550,height=500,scrollbars=1,status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0');
		winDt.focus();
    }
	else
	{
		setTimeout("listaResultado('"+parametrosBanco+"','"+id+"','"+idIns+"','"+IdDel+"','"+ idLista + "')",500)	
	}	
	
}
function janelaBuscaExtra(url,id,idIns,IdDel,idLista)
{
	element = document.getElementById(id)
	extra = document.getElementById("extra")
	wurl = url + "&digitado="+ element.value + "&camposIns=" + idIns + "&camposApagar=" + IdDel	
	if (extra)
	{
		vet_extra = extra.value.split("|");
		campoExtra = vet_extra[0];
		valorCampo = document.getElementById(vet_extra[1]);
		if (valorCampo)
		{
			wurl = wurl + "&campoExtra=" + campoExtra + "&valorExtra=" + valorCampo.value
		}
	}
	
	winDt = window.open(wurl,'','top=300,left=600,width=550,height=500,scrollbars=1,status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0');
	winDt.focus();
}
function janelaForm(largura,altura,url)
{
	winDt = window.open(url,'','top=300,left=150,width='+ largura +',height='+ altura +',scrollbars=1,status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1');
	winDt.focus();
}
function salvarForm()
{
	document.getElementById("form").submit();	
}
function setarValor(cod,desc)
{
	id_anterior = document.getElementById("recebemValor").value
	vet_divAnt = id_anterior.split("|")
	valorAnterior = window.opener.document.getElementById(vet_divAnt[0].value);
	if (valorAnterior != cod)
	{
		
		id_anteriorAp = document.getElementById("apagamValor").value;
		
		if (id_anteriorAp != "")
		{
			vet_divAntAp = id_anteriorAp.split("|")
			for(i=0;i<vet_divAntAp.length;i++)
			{
				element = window.opener.document.getElementById(vet_divAntAp[i]);
				
				if(element)
				{
					element.value = "";	
				}
			}
		}
	}
	window.opener.document.getElementById(vet_divAnt[0]).value = cod;
	window.opener.document.getElementById(vet_divAnt[1]).value = desc
	//window.opener.document.location.href=url;
	fechar();
}
function setarValorLista(cod,desc)
{
	id_anterior = document.getElementById("recebemValor").value
	vet_divAnt = id_anterior.split("|")
	valorAnterior = document.getElementById(vet_divAnt[0].value);
	
	if (valorAnterior != cod)
	{
		
		id_anteriorAp = document.getElementById("apagamValor").value;
		
		if (id_anteriorAp != "")
		{
			vet_divAntAp = id_anteriorAp.split("|")
			for(i=0;i<vet_divAntAp.length;i++)
			{
				element = document.getElementById(vet_divAntAp[i]);
				
				if(element)
				{
					element.value = "";	
				}
			}
		}
	}
	document.getElementById(vet_divAnt[0]).value = cod;
	document.getElementById(vet_divAnt[1]).value = desc
	//window.opener.document.location.href=url;
	limpaListagem();	
}

function inicializaForm()
{
	cod = document.getElementById("codigo")
	if(cod)
	{
		if(cod.value != "")
		{
			edit = document.getElementById("bot_editar")
			excluir = document.getElementById("bot_excluir")
			if(edit)
			{
				edit.disabled = "";
				edit.onclick = function(){editReg();}
				edit.className = "imagem_pointer";
				edit.src = urlImagem + "bt_editar.jpg";
			}
			if(excluir)
			{
				url=document.getElementById("url_det")
				excluir.disabled = "";	
				excluir.onclick = function(){excluirReg(cod.value,url.value);}
				excluir.className = "imagem_pointer";
				excluir.src = urlImagem + "bt_excluir.jpg";
			}
		}
	}
}
function excluirReg(url)
{
	urlRetornoAlert=url;
	confirm("Deseja realmente excluir o registro?")
	
}
function fechar()
{
	close();
}
function salvar(id)
{
	document.getElementById(id).submit();	
}

function abrirMenu(wcontrole)
{	
	$("#"+wcontrole).slideToggle("normal")
}

function abrirMenuSite(wcontrole)
{
	if($("#"+wcontrole).is(":hidden"))
	 {
		$("#"+wcontrole.replace("cont","img")).attr("src","http://www.meusomnovo.com.br/ver2/imagens/seta_menu_aberta.jpg")
	//	$("#"+wcontrole).slideToggle("slow")
	 }
	 else
	 {
		$("#"+wcontrole.replace("cont","img")).attr("src","http://www.meusomnovo.com.br/ver2/imagens/seta_menu.jpg") 
		//$("#"+wcontrole).slideToggle("slow")
	 }	
	$("#"+wcontrole).slideToggle("slow")
}

function abrirMenuSite2(wcontrole, wmenu, walturaIni, walturaMaxima, walfa, wopacity, wmOpacity){
	var controle = document.getElementById(wcontrole);
	var menu = document.getElementById(wmenu);
	var altura = document.getElementById(walturaIni);
	var alfa = document.getElementById(walfa);
	var opacity = document.getElementById(wopacity);
	var mOpacity = document.getElementById(wmOpacity);
	
	if(controle.value == 0){
		menu.style.display = "";
		menu.style.height = altura.value + "px";
		
		if(parseInt(altura.value) != parseInt(walturaMaxima)){
			altura.value = parseInt(altura.value) + 19;
			alfa.value = parseInt(alfa.value) + 7.15;
			opacity.value = parseFloat(opacity.value) + 0.06;
			mOpacity.value = parseFloat(mOpacity.value) + 0.06;
			
			menu.style.filter = "alpha(opacity="+alfa.value+")";
			menu.style.MozOpacity = opacity.value;
			menu.style.opacity = mOpacity.value;
			setTimeout("abrirMenuSite('"+wcontrole+"', '"+wmenu+"', '"+walturaIni+"', '"+walturaMaxima+"', '"+walfa+"', '"+wopacity+"', '"+wmOpacity+"')",0);
		}else{
			controle.value = 1;
			menu.style.filter = "alpha(opacity=100)";
			menu.style.MozOpacity = "1";
			menu.style.opacity = "1";
		}
		
	}else{
		menu.style.height = altura.value + "px";
		menu.style.filter = "alpha(opacity="+alfa.value+")";
		menu.style.MozOpacity = opacity.value;
		menu.style.opacity = mOpacity.value;
			
		if(parseInt(altura.value) == 19){
			controle.value = 0;
			alfa.value = 0;
			opacity.value = 0;
			mOpacity.value = 0;
			menu.style.display = "none";
		}else{
			altura.value = parseInt(altura.value) - 19;
			alfa.value = parseInt(alfa.value) - 7.15;
			opacity.value = parseFloat(opacity.value) - 0.04;
			mOpacity.value = parseFloat(mOpacity.value) - 0.04;
			setTimeout("abrirMenuSite('"+wcontrole+"', '"+wmenu+"', '"+walturaIni+"', '"+walturaMaxima+"', '"+walfa+"', '"+wopacity+"', '"+wmOpacity+"')",0);
		}
	}
}


function camposFile(idFoto,idLegenda,contador,acao){
	if(acao == "+"){
		if(parseInt(document.getElementById(contador).value) < 30){
			document.getElementById(contador).value = parseInt(document.getElementById(contador).value)+1;
			//document.getElementById(idFoto + document.getElementById(contador).value).style.display = "";
			document.getElementById(idLegenda + document.getElementById(contador).value).style.display = "";
			document.getElementById('botDel').style.display = "";
		}
		
		if(parseInt(document.getElementById(contador).value) == 30){
			document.getElementById('botAd').style.display = "none";
		}
	}else{
		if(parseInt(document.getElementById(contador).value) > 1){
			//
			document.getElementById('qtde' + document.getElementById(contador).value).value = "";
			document.getElementById('unid' + document.getElementById(contador).value).value = "";
			document.getElementById('cod_espec' + document.getElementById(contador).value).value = "";
			document.getElementById('descricao' + document.getElementById(contador).value).value = "";
			//
			
			//document.getElementById(idFoto + document.getElementById(contador).value).style.display = "none";
			document.getElementById(idLegenda + document.getElementById(contador).value).style.display = "none";
			document.getElementById(contador).value = parseInt(document.getElementById(contador).value)-1;
			document.getElementById('botAd').style.display = "";
		}
		
		if(parseInt(document.getElementById(contador).value) == 5){
			document.getElementById('botDel').style.display = "none";
		}
	}
}

function janelaRelatorio(wurl)
{
	var winDt = window.open(wurl,'','scrollbars=1,status=1,toolbar=1,location=0,menubar=1,directories=1,resizable=1');
	winDt.focus();
}

function horaImpressao()
{
	data_aux = new Date;
	whora = data_aux.getHours()
	wminuto = data_aux.getMinutes()
	
	dia = data_aux.getDate();
	mes = data_aux.getMonth();
	mes = parseInt(mes) + 1;
	ano = data_aux.getFullYear();
	if (dia < 10)
	{
		dia = "0" + dia;
	}
	if (mes < 10)
	{
		mes = "0" + mes;
	}
	if (whora < 10)
	{
		whora = "0" + whora;
	}
	if (wminuto < 10)
	{
		wminuto = "0" +wminuto;
	}
	
	obj = document.getElementsByTagName("span");
	
	for (i=0;i<obj.length;i++)
	{
		
		if (obj[i])
		{
			if (obj[i].className == "hora")
			{
				obj[i].innerHTML = dia + "/" + mes + "/" + ano + " " + whora + ":" + wminuto;
			}
		}
	}		
	
}



function trocaPessoa(campo1, campo2, parametrosL, parametrosD){
	var parL, parD;
	if(document.getElementByID(campo1).checked = true){
		parL = parametrosL.split("|")
	}
}

function pessoaFisica(){
	if(document.getElementById("pf").checked = true){
		document.getElementById("cxNomeFantasia").style.display = "none";
		document.getElementById("nomeFantasia").disabled = true;
		document.getElementById("nomeFantasia").className = "";
		document.getElementById("cxRazao").style.display = "none";
		document.getElementById("razao").disabled = true;
		document.getElementById("razao").className = "";
		document.getElementById("cxCNPJ").style.display = "none";
		document.getElementById("cxIE").style.display = "none";
		
		document.getElementById("cxCPF").style.display = "";
		document.getElementById("cpf").disabled = false;
		document.getElementById("cxNome").style.display = "";
		document.getElementById("nome").disabled = false;
		document.getElementById("nome").className = "obrigatorio";
	}
}

function pessoaJuridica(){
	if(document.getElementById("pj").checked = true){
		document.getElementById("cxNomeFantasia").style.display = "";
		document.getElementById("nomeFantasia").disabled = false;
		document.getElementById("nomeFantasia").className = "obrigatorio";
		document.getElementById("cxRazao").style.display = "";
		document.getElementById("razao").disabled = false;
		document.getElementById("razao").className = "obrigatorio";
		document.getElementById("cxCNPJ").style.display = "";
		document.getElementById("cxIE").style.display = "";
		
		document.getElementById("cxCPF").style.display = "none";
		document.getElementById("cpf").disabled = true;
		document.getElementById("cxNome").style.display = "none";
		document.getElementById("nome").disabled = true;
		document.getElementById("nome").className = "";
	}
}
//fim
var pos = 1
var posSite = 1
function adicionarEnd()
{
	pos = pos + 1							
	var str = "<div class='endAcesso' id='endAcesso_"+ pos +"'>"
	str += "<input type='text' name='acesso_"+ pos +"' id='acesso_"+ pos +"'>"
	str += "<img src='imagens/+-form.jpg' alt='Adicionar um endereço' title='Adicionar um endereço' id='maisEnd_"+ pos +"'>"
	str += "<img src='imagens/-_form.jpg' alt='Retirar um endereço' title='Retirar um endereço' id='retEnd_"+ pos +"' style='left:250px;'>"
	str += "</div>"
	
	$("#endAcesso").append(str)
	idImg = "#maisEnd_"+ pos ;
	$(idImg).click(function () { adicionarEnd() });
	
	idImg = "#retEnd_"+ pos ;							
	$(idImg).click(function () { retirarEnd(this.id) });
	
	$("#totalEndAcesso").attr("value",pos);
}
function retirarEnd(id)
{
	idRet = id.replace("retEnd_","")
	idRet = "#endAcesso_" + idRet 							
	$(idRet).remove()
	
}

function adicionarSecao()
{
	posSite = posSite + 1							
	var str = "<div class='endAcesso' id='siteSecao_"+ posSite +"'>"
	str += "<input type='text' name='secao_"+ posSite +"' id='secao_"+ posSite +"'>"
	str += "<img src='imagens/+-form.jpg' alt='Adicionar uma seção' title='Adicionar uma seção' id='maisSec_"+ posSite +"'>"
	str += "<img src='imagens/-_form.jpg' alt='Retirar uma seção' title='Retirar uma seção' id='retSec_"+ posSite +"' style='left:250px;'>"
	str += "<label><input type='radio' name='tipoSecao_"+ posSite +"' value='Estática' style='margin-left:68px;'> Estática</label>"
	str += "<label><input type='radio' name='tipoSecao_"+ posSite +"' value='Dinâmica' style='margin-left:33px;'> Dinâmica</label>"
	str += "</div>"
	
	$("#secoes").append(str)
	idImg = "#maisSec_"+ posSite ;
	$(idImg).click(function () { adicionarSecao() });
	
	idImg = "#retSec_"+ posSite ;							
	$(idImg).click(function () { retirarSecao(this.id) });
	
	$("#totalSecao").attr("value",posSite);

}
function retirarSecao(id)
{
	idRet = id.replace("retSec_","")
	idRet = "#siteSecao_" + idRet 							
	$(idRet).remove()
	
}


var vetFundo = new Array("url(imagens/menu-topo01b.jpg)","url(imagens/menu-topo03b.jpg)","url(imagens/menu-topo04b.jpg)");
var vetFundoSem = new Array("url(imagens/menu-topo01.jpg)","url(imagens/menu-topo03.jpg)", "url(imagens/menu-topo04.jpg)");
objIntervalRelogio = new Object()
vetRelogio = new Array()
var emailControleCesta = ""
var nomeControleCesta = ""
var controleClickSubmitEmail = false

function parametrosRelogio(horaRestante,minutoRestante,secundoRestante)
{
	this.horaRestante = horaRestante
	this.minutoRestante = minutoRestante
	this.secundoRestante = secundoRestante
}

function iniciarFuncoes()
{
	/*Controle de tipo de dado nos inputs*/
	$(".int").keypress(function(event){ insNumeric(this,event) }) 
	
	$("#setaSelecaoPais").click(function(){
		if( $("#caixaPaises").is(":hidden") )
		{
			$(this).find("img").attr("src","imagens/seta-pais-topo_inverse.png");
			$("#caixaPaises").slideDown("normal")
		}
		else
		{
			$(this).find("img").attr("src","imagens/seta-pais-topo.png");
			$("#caixaPaises").slideUp("normal")
		}
	})
	
	$(window).scroll(function() {
		if (document.all)
		{
			var wtop = parseInt(document.documentElement.scrollTop) + (parseInt($(window).height())/2)
		}
		else
		{
			var wtop = parseInt(window.scrollY) + (parseInt($(window).height())/2)	
		}
		if( $("#alteraStatus").length > 0 )
		{
			$("#alteraStatus").css("top",wtop)
		}
	});	
}

posItem = 0
function calcularPorcentagemDesc()
{
	if( $("#valor").val() != "" && 	$("#valor").val() != "")
	{
		if( parseFloat($("#valor").val()) > 0 && parseFloat($("#valor_promocional").val()) > 0 )
		{
			wvalor = $("#valor").val().replace(".","").replace(",",".")
			wvalorFinal = $("#valor_promocional").val().replace(".","").replace(",",".")						
			wporcentagem =	( (parseFloat(wvalor)-parseFloat(wvalorFinal)) * 100 ) /  parseFloat(wvalor)
			wporcentagem = wporcentagem.toFixed(2)
			strPorc = new String(wporcentagem)
			$("#valor_desconto").val(strPorc.replace(".",",") + "%")
			
		}
	}
}

function ocultaCanais(id)
{
	id_par = id;
	vet_id = id_par.split("_");
	id_element = vet_id[1];
	img = document.getElementById(id);
	div_canais = document.getElementById(id_element);
	var aux_class = div_canais.style.display;
	if (id_element == "equipe")
	{
		if (aux_class == "block")
		{
			div_canais.style.display = "none";
			img.src = "imagens/icon_mais.jpg";
			img.alt = "Mostrar"
		}
		if (aux_class == "none")
		{
			div_canais.style.display = "block";
			img.src = "imagens/icon_menos.jpg";
			img.alt = "Esconder"
			document.getElementById("colaboradores").style.display = "none";
			
		}	
	}
	else
	{
		if (aux_class == "block")
		{
			div_canais.style.display = "none";
			img.src = "imagens/img_mais.jpg";
			img.alt = "Mostrar"
		}
		if (aux_class == "none")
		{
			div_canais.style.display = "block";
			img.src = "imagens/img_menos.jpg";
			img.alt = "Esconder"			
		}
	}
}
function buscaCep()
{
	wcep = $("#cep").val();	
	wcep = wcep.replace("-","")
	ajax = ajaxInit();	
	if(ajax) {
		ajax.open("GET","busca_cep.asp?cep=" + wcep, true);
		
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					retorno = ajax.responseText;
					if( retorno != "erro" )
					{
						vetRet = retorno.split("|")	
						$("#endereco").val(vetRet[0])
						$("#bairro").val(vetRet[1])
						//$("#cidade").val(vetRet[2])
						if( $("#codigoEstado").attr("type") == "input" )
						{
							if( vetRet[3].split("-").length > 0 )
							{							
								$("#codigoEstado").val(vetRet[3].split("-")[0])
								$("#nomeEstado").val(vetRet[3].split("-")[1])							
							}
							if( vetRet[2].split("-").length > 0 )
							{							
								$("#codigoCidade").val(vetRet[2].split("-")[0])
								$("#nomeCidade").val(vetRet[2].split("-")[1])							
							}
						}
						else
						{
						
							$("#codigoCidade").val(vetRet[2].split("-")[0])
							$("#nomeCidade").val(vetRet[2].split("-")[1])
							objSelect = document.getElementById("codigoEstado")
							posItem = 0
							for(i=1;i<objSelect.options.length;i++)
							{
								if(objSelect.options[i].value == vetRet[3].split("-")[0])
								{
									$("#text_select_codigoEstado").val( objSelect.options[i].text )
									objSelect.options[i].selected =  true
									posItem = i								
									break
								}
							}
							if( posicaoVetSelect("codigoEstado") < 0 )
							{
								vetSelect[vetSelect.length] = new selecao("codigoEstado",posItem)	
								//$("#text_select_estado").val( objSelect.options[i].text )
							}
							else
							{
								
								
								vetSelect[posicaoVetSelect("codigoEstado")].posSelecao = posItem	
								//$("#text_select_estado").val( objSelect.options[i].text )
							}
						}
						
						
						
					}
				}else{
					//alert(ajax.statusText);
				}
			}
		}
		ajax.send(null);
	}	
	
}

function produtosPagina()
{
	var wurl = $("#destino_pag").val() + "&regPag="+ $("#num_itens").val()
	location.href = wurl
}
function selecionaFrete(tipo,valor_frete,valor_total){
	document.getElementById('totalmostra').value='R$ ' + valor_total;
	document.getElementById('totalenvia').value=valor_total;
	document.getElementById('freteenvia').value=valor_frete;
	document.getElementById('freteescolhido').value='R$ ' + valor_frete;
	document.getElementById('tipo_frete').value=tipo;
	
	if(document.getElementById('tipofretel')){
		document.getElementById('tipofretel').value=tipo;
		document.getElementById('valorfretel').value=valor_frete;
		document.getElementById('valortotall').value=valor_total;
	}
	document.getElementById("freteCalculado").value = "S"
}

function calculaFrete()
{
	
	if(document.getElementById("cep1").value != "" && document.getElementById("cep2").value != "")
	{
		document.getElementById('labelTotal').childNodes[0].nodeValue = "R$0,00"
		document.getElementById('valorTotal').value="";
		document.getElementById('valorFrete').value="";
		
		var  cep1 = document.getElementById("cep1").value
		var cep2 = document.getElementById("cep2").value
		var peso  = document.getElementById("peso").value
		var preco = document.getElementById("valor").value
		
		wurl = "calc_frete.asp?cep1=" + cep1 + "&cep2="+cep2 + "&peso="+ peso + "&valor=" + preco
		
		document.getElementById("calcFrete").innerHTML = "<img src='imagens/ajax-loader.gif'>"
		carregaCombo(wurl,"calcFrete")	
		
	}
	else
	{
		alert("Atenção, preencha o campo CEP")		
	}
}
function verSelecao()
{
  obj = document.getElementsByTagName("input")
  for(i=0;i<obj.length;i++)
  {
	  if( obj[i].type == "radio" && obj[i].checked == true)
	  {
		  obj[i].click();		
		  
	  }
  }
  
}
function janelaCorreios(wurl)
{
	
	winDt = window.open(wurl,'','left=100,width=800,scrollbars=1,status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1');
	winDt.focus();
	
}

var foto_atual,proxima_foto,id_foto_atual,id_label_atual;
var num_fotos = 5;
intervalo = new Object()

var arrayLink = new Array();

function mudar_foto(foto){
	
	foto = foto.replace("n","")
	id_proxima_foto = "#foto_"+foto;	
	if( id_proxima_foto != id_foto_atual)
	{
			
		$(id_foto_atual).animate( {'opacity':'hide'},'slow');
	
		$(id_proxima_foto).animate( {'opacity':'show'},'slow',function(){
			foto_atual = foto
			id_foto_atual = id_proxima_foto;			
			
		})
	}
			
}

var vetImg = new Array()
function iniciarGaleria()
{
	foto_atual = 0;
	id_foto_atual = "#foto_0";
		
	if(num_fotos > 1)
	{
		for(i=0;i<=num_fotos;i++)
		{
			idNum = "#n"+i
			$(idNum).click(function () { 
				mudar_foto(this.id)
			});
			if( i > 0 )
			{
				idAux = "#foto_"+i
				$(idAux).hide()		
			}
		}
	}
	
}

var posAnterior = 0
function mostraCor(pos){
	$("#tamanho_"+pos).show()
	obj = $("input[name='cor']")
	
	for(i=1; i<=obj.length; i++)
	{
		if( i != pos)
		{
			$("#tamanho_"+i).hide()
		}
		
	}
	//document.getElementById(campo+id).style.display = 'block';*/
	
	//$("#tamanho_"+posAnterior).hide()
	
	//$("#tamanho_"+pos).show()
	/*posAnterior = pos
	obj =  $("input[name='tamanho']")		
	for(i=0;i<obj.length;i++)
	{
		obj[i].checked = false
		
	}*/
}


function verifCheck(campo1, campo2){
	if(document.getElementById(campo1).checked == true){
		document.getElementById(campo2).style.display = "";
	}else{
		document.getElementById(campo2).style.display = "none";
	}
}

function janelaBoleto(wurl)
{

	winDt = window.open(wurl,'','left=100,width=800,scrollbars=1,status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1');

	winDt.focus();
	

}
function manipulaVariacao(tipo,posicao)
{
	if( tipo== "+" )
	{
		if( $("#variacao_descricao_"+posicao).val() != "" && $("#variacao_quantidade_"+posicao).val() != "" && $("#variacao_min_"+posicao).val() != "")
		{
			$("#vari_"+(parseInt(posicao)+1)).show()
			$("#adic_"+posicao).hide()
		}
		else
		{
			var campo = ""
			if( $("#variacao_descricao_"+posicao).val() == "")
			{
				objFocus = $("#variacao_descricao_"+posicao)
				campo = "Descrição"
			}
			else
			{
				if( $("#variacao_quantidade_"+posicao).val() == "")
				{
					objFocus = $("#variacao_quantidade_"+posicao)	
					campo = "Quantidade"
				}	
				else
				{
					objFocus = $("#variacao_min_"+posicao)
					campo = "Quantidade Mínima"
					
				}
			}
			
			alert("Preencha o campo " + campo + " para adicionar.")
		}
	}
	else
	{
		$("#vari_"+posicao).hide()
		$("#adic_"+(parseInt(posicao)-1)).show()
		$("#vari_"+posicao + " input").val("")
		
	}
}	

function carregaItensProd()
{
	$(".exibeItens").click(function(){
		idItem = $(this).attr("id")
		if( $("#"+idItem.replace("titCateg_","categ_")).is(":hidden") )
		{
			$("#"+idItem.replace("titCateg_","categ_")).slideDown()
			$("#"+idItem.replace("titCateg_","img_")).attr("src","imagens/seta_cima.jpg")
			$("#"+idItem.replace("titCateg_","img_")).attr("alt","Clique para ocultar")
			$("#"+idItem.replace("titCateg_","img_")).attr("title","Clique para ocultar")
		}
		else
		{
			$("#"+idItem.replace("titCateg_","categ_")).slideUp()
			$("#"+idItem.replace("titCateg_","img_")).attr("src","imagens/seta_baixo.jpg")
			$("#"+idItem.replace("titCateg_","img_")).attr("alt","Clique para exibir")
			$("#"+idItem.replace("titCateg_","img_")).attr("title","Clique para exibir")
		}
		
	})
}

function carregaVariacoesProd(codigo,url)
{
	
	
	$("#bntFecharVariacao").remove()	
	$("#caixaVariacoes").hide("normal",function(){
		$("#caixaVariacoes").remove()									
	})
	if( $("#caixaVariacoes").length == 0 )
	{
		$("#var_"+codigo).append("<img src='imagens/bt_fechar_lista.jpg' id='bntFecharVariacao'><div id='caixaVariacoes'></div>")
		$("#caixaVariacoes").load(url)
		$("#bntFecharVariacao").click(function(){
			$("#bntFecharVariacao").remove()
			$("#caixaVariacoes").hide("normal",function(){
				
				$("#caixaVariacoes").remove()
			})
			
		})	
	}
}
function salvarVariacao(codigo)
{
	
	if( $("#caixaVariacoes input[value='']").length ==0 )
	{
		
		var url = ""
		for(i=0;i<$("#caixaVariacoes input").length;i++)
		{
			url +=  "&codigo_"+ i +"=" + $("#caixaVariacoes input:eq("+ i +")").attr("id").split("_")[1] + "_" + $("#caixaVariacoes input:eq("+ i +")").attr("id").split("_")[2] + "_" + $("#caixaVariacoes input:eq("+ i +")").attr("id").split("_")[3] + "&quantidade_"+ i +"=" + $("#caixaVariacoes input:eq("+ i +")").val()
		}
		$("#caixaVariacoes").html("<p><strong style='color:#CC0000;'>Aguarde...</strong></p>")
		
		$("#caixaVariacoes").load("carrega_variacoes.asp?codigo="+codigo+url+"&envia=sim&itens="+i)
	}
	else
	{
		objFocus = $("#caixaVariacoes input[value='']:eq(0)")
		alert("Preencha todos os campos")
	}
}
function mudaDive(dive, divId, divId2){
	wdive = dive;
	wdiv = document.getElementById(divId);
	wdiv2 = document.getElementById(divId2);
	if(wdive == 'J'){
		wdiv.style.display = 'block';
		document.getElementById("cnpj").className = "obrigatorio";
		document.getElementById("razao").className = "obrigatorio";
	}else{
		wdiv.style.display = 'none';
		document.getElementById("cnpj").className = "";
		document.getElementById("razao").className = "";
	}
	if(wdive == 'F'){
		wdiv2.style.display = 'block';
		document.getElementById("cpf").className = "obrigatorio";
	}else{
		wdiv2.style.display = 'none';
		document.getElementById("cpf").className = "";
	}
}
function dimensoesTela()
{
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		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
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			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;
	}	
	
	
	if(yScroll <= windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
		
	}

	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
		
	dimensao = pageWidth + "x" + pageHeight
	return dimensao
}


function ocultaBarra(id)
{
	id_par = id;
	vet_id = id_par.split("_");
	id_element = vet_id[1];
	//alert(id_element)
	//img = document.getElementById(id);
	div_canais = document.getElementById(id_element);
	var aux_class = div_canais.style.display;

	if (aux_class == "block")
	{
		$("#"+id_element).slideUp("normal");
		//$("#"+vet_id[0]).css("color","#797979")		
	}
	if (aux_class == "none")
	{
		$("#"+id_element).slideDown("normal");
		//$("#"+vet_id[0]).css("color","#8e0203");
	}
	
}

function incluirCarregando(txt)
{
	
	$("#caixaCarregando").remove()
	pageWidth = dimensoesTela().split("x")[0]
	pageHeight = dimensoesTela().split("x")[1]	
	$("<div id='caixaCarregando'><img src='imagens/loading2.gif'><label></label></div>").appendTo("body").hide()
	$("#caixaCarregando label").text(txt)
	wleft = ( parseInt(dimensoesTela().split("x")[0]) - parseInt($("#caixaCarregando").width() ) ) / 2
	if (document.all)
	{
		var wtop = parseInt(document.documentElement.scrollTop) + 250
		
	}
	else
	{
		var wtop = parseInt(window.scrollY) + 250	
	}
	//wtop = ( parseInt(dimensoesTela().split("x")[1]) - parseInt( ) ) / 2	
	$("#caixaCarregando").css("left",parseInt(wleft))
	$("#caixaCarregando").css("top",wtop)
	$("#caixaCarregando").show()

}

function Banco()
{
	
	document.getElementById("extra").value = "";	
	preecheInput('codigoEstado','razao','BANCO','CODIGO','BAN_NOME')
	document.getElementById("codigoCidade").value = "";
	document.getElementById("nomeCidade").value = "";

}
function verBanco(tipo)
{
	// D - quando chama a funcao para autopreenchimento
	// N - quando a busca é por numero
	
	if(document.getElementById("codigoEstado").value == "")
	{
		obj_input = document.getElementById("nomeCidade");
		if (tipo == "N")
		{
			obj_input.value = "";
			obj_input.value = "Selecione um estado"	
			document.getElementById("codigoCidade").value = ""		
		}
		else
		{
			if (tipo == "D")
			{
				obj_input.value = "";
				obj_input.value = "Selecione um estado"
				
				obj_input.onkeypress = function(){ verBanco('D') ;}			
			}	
			else
			{
				obj_input.value = "Selecione um estado"	
			}	
		}
	}
	else
	{
		document.getElementById("extra").value = "estado|codigoEstado";
		obj_input = document.getElementById("nomeCidade");
			
		if (tipo == "N")
		{
			preecheInput('codigoCidade','nomeCidade','cidade','codigo','cidade');				
		}
		else
		{
			
			if( tipo == "D" )
			{
				return true
				//obj_input.onkeypress = function(){ verTecla(obj_input,'event','busca.asp|cidade|CODIGO|NOME|380|62','nomeCidade','codigoCidade|nomeCidade','cod_conta|conta','result_02');}		
			}	
			else
			{	
				janelaBusca('busca.asp?tabelaBusca=cidade&campoCodigo=codigo&campo=cidade&titulo_campo=Cidade','nomeCidade','codigoCidade|nomeCidade','','550','500')
				
			}
		}
	}
}




//FUNCOES DE AUTOCOMPLETAR E BUSCA

function opcoesAutoComplete(tabela,campoTabela,inputCodigo,inputText,inputExtra,campoTabelaExtra)
{
	this.tabela = tabela;	
	this.campoTabela = campoTabela;
	this.inputCodigo = inputCodigo
	this.inputText = inputText
	this.inputExtra = inputExtra;
	this.campoTabelaExtra = campoTabelaExtra;		
}
var historicoTextAutocomplete = ""
var verificaFocusInput = false
var posicaoAutocomplete = -1
objOpcoesAutocomple = new Object()
function iniciaFuncoesInputBusca()
{
	
	for(i=0;i<$("input[alt!='']").length;i++)
	{
		if( $("input[alt!='']:eq("+ i +")").attr("alt").substring(0,13) == "completeInput" )
		{
			altElement = ""
			insFuncao = false
			if( $("input[alt!='']:eq("+ i +")").attr("alt").replace("completeInput","").split(",").length >2 )
			{
				altElement = $("input[alt!='']:eq("+ i +")").attr("alt").replace("completeInput","")
				insFuncao = true
			}
			else
			{
				idReferencia = $("input[alt!='']:eq("+ i +")").attr("alt").replace("completeInput","").replace("{","").replace("}","")
				
				if( $("#" + idReferencia).length > 0)
				{
					if( $("#" + idReferencia).attr("alt").replace("autocomplete","").split(",").length >2 )
					{
						altElement = $("#" + $("input[alt!='']:eq("+ i +")").attr("alt").replace("completeInput","")).replace("autocomplete","")
						insFuncao = true
					}
				}
			}
			if( insFuncao == true )
			{
				$("input[alt!='']:eq("+ i +")").blur(function(){
					
					if( $(this).val() != "" && validaTipoDado($(this).val(),"int") )
					{
						
						setObjectAutoComplete(altElement)					
						
						$.post("paginaLoad.html",function(retornoPost){
							
							if(retornoPost.length > 0 && retornoPost!="")
							{
								if( retornoPost.substring(0,4) != "erro" )
								{
									
								}
								else
								{
									mensagemErroSessao()
								}
							}
											
						})
					}			
				})
			}	
		}
		if( $("input[alt!='']:eq("+ i +")").attr("alt").substring(0,12) == "autocomplete" )
		{
			
			altElement = ""
			insFuncao = false
			if( $("input[alt!='']:eq("+ i +")").attr("alt").replace("autocomplete","").split(",").length >2 )
			{
				insFuncao = true
			}
			else
			{
				idReferencia = $("input[alt!='']:eq("+ i +")").attr("alt").replace("autocomplete","").replace("{","").replace("}","")
				
				if( $("#" + idReferencia).length > 0)
				{
					
					if( $("#" + idReferencia).attr("alt").replace("completeInput","").replace("autocomplete","").split(",").length >2 )
					{
						insFuncao = true
					}
				}
			}
			
			if( insFuncao == true )
			{
				
				$("input[alt!='']:eq("+ i +")").keyup(function(e){
					
					if( $(this).attr("alt").replace("autocomplete","").split(",").length >2 )
					{
						objInputAutcomplete = $(this)
					}
					else
					{
						idReferencia = $(this).attr("alt").replace("autocomplete","").replace("{","").replace("}","")
						objInputAutcomplete = $("#" + idReferencia)
					}
					
					
					if( e.which != 13 && e.which != 9)
					{
						if( e.which == 38 || e.which == 40)
						{
							if( $("#autocomplete li").length > 0 )
							{
								posicaoItem = -1
								if( $("#autocomplete li").is(":hidden") )
								{
									posicaoItem = $("#autocomplete li").index($("#autocomplete li:contains('"+ $(this).val() +"')"))
									posicaoAutocomplete = -1
								}
								
								if( posicaoItem >= 0 )
								{
									$("#autocomplete li:eq("+ posicaoItem +")").removeClass("autocompleteInativo").addClass("autocompleteAtivo")
									$("#autocomplete li:gt("+ posicaoItem +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
									$("#autocomplete li:lt("+ posicaoItem +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
									posicaoAutocomplete = posicaoItem
									$("#autocomplete").show()
								}
								else
								{
									
									if( e.which == 40	)
									{
										posicaoAutocomplete = parseInt(posicaoAutocomplete) + 1								
										if( posicaoAutocomplete == $("#autocomplete li").length)
										{
											posicaoAutocomplete = 0
										}
										
									}
									else
									{
										posicaoAutocomplete = parseInt(posicaoAutocomplete) - 1				
										if( posicaoAutocomplete < 0 )
										{
											posicaoAutocomplete = parseInt($("#autocomplete li").length)-1
										}
									}
									$("#"+ objOpcoesAutocomple.inputText ).val($("#autocomplete li:eq("+ posicaoAutocomplete +")").text())
									$("#autocomplete li:eq("+ posicaoAutocomplete +")").removeClass("autocompleteInativo").addClass("autocompleteAtivo")
									$("#autocomplete li:gt("+ posicaoAutocomplete +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
									$("#autocomplete li:lt("+ posicaoAutocomplete +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
								}
							}
							else
							{
								loadAutoComplete(this)
							}
													
						}							
						else
						{
							
							if( $(this).val() != "" )
							{
								loadAutoComplete(this)	
							}
							else
							{
								$("#autocomplete").remove()
							}
							
						}		
					}
					else
					{
						e.returnValue = false;
						e.preventDefault();							
						return false;
					}		
											
					
					
				})
				$("input[alt!='']:eq("+ i +")").keypress(function(e){				
					if( e.which == 13 )
					{						
						if( $("#autocomplete li:eq("+ posicaoAutocomplete +")").is(":visible") )
						{
							$("#autocomplete li:eq("+ posicaoAutocomplete +")").click()
							e.returnValue = false;
							e.preventDefault();							
							return false;
						}
						
						
					}												 
				})
								
				
				$("input[alt!='']:eq("+ i +")").focus(function(){
					
					if( $(this).attr("alt").replace("autocomplete","").split(",").length >2 )
					{
						objInputAutcomplete = $(this)
					}
					else
					{
						idReferencia = $(this).attr("alt").replace("autocomplete","").replace("{","").replace("}","")
						objInputAutcomplete = $("#" + idReferencia)
					}					
										
					altElement = $(objInputAutcomplete).attr("alt").replace("{","").replace("}","")
					setObjectAutoComplete(altElement)
				})
				
				$("input[alt!='']:eq("+ i +")").blur(function(){ 
					//if( $("#autocomplete li").length > 0 )
					//{
						/*setTimeout(function(){
							if( $("#autocomplete li").length > 0 )
							{
								$("#autocomplete").remove() 								
							}
							
							if( historicoTextAutocomplete != "" )
							{
								$("#"+ objOpcoesAutocomple.inputText).val(historicoTextAutocomplete)
							}							
							posicaoAutocomplete = -1
							if( verificaFocusInput == true )
							{
								$("#"+ objOpcoesAutocomple.inputText).focus()
							}
							verificaFocusInput = false
						},300)*/
					//}
					//else
					//{
						//$("#autocomplete").remove() 
						//posicaoAutocomplete = -1
					//}
				  setTimeout(function(){
					  
					  if( autocompleteClickLista == false )
					  {
						 $("#autocomplete").remove()
					  }
					  
				  },300)
					
				})
			}
			
		}
	}
	
	for(i=0;i<$("button[name!='']").length;i++)
	{
		$("button[name!='']:eq("+ i +")").unbind()
		if( $("button[name!='']:eq("+ i +")").attr("name").substring(0,5) == "busca" )
		{
			funcaoClick = false
			if( $(this).attr("name").replace("busca","").split(",").length >2 )
			{
				funcaoClick = true
			}
			else
			{
				funcaoClick = true
			}
			if( funcaoClick == true )
			{
				$("button[name!='']:eq("+ i +")").click(function(){
					if( $(this).attr("name").replace("busca","").split(",").length >2 )
					{
						objInputAutcomplete = $(this)
					}
					else
					{
						idReferencia = $(this).attr("name").replace("busca","").replace("{","").replace("}","")
						objInputAutcomplete = $("#" + idReferencia)
					}
					
					
					
					altElement = $(objInputAutcomplete).attr("alt").replace("{","").replace("}","")
					
					setObjectAutoComplete(altElement)												 
				})
				
			}
		}
		
	}
	
}
autocompleteClickLista = false
function loadAutoComplete(objInput)
{
	$("#autocomplete").remove()
	autocompleteClickLista = false
	if( $("#autocomplete").length==0)
	{
		
		wleft = parseFloat($(objInput).offset().left) + 2
		wtop= parseFloat($(objInput).offset().top) //+ parseFloat($("#text_select_" + idList.replace("select_","")).css("top"))			
		wtop = parseInt($(objInput).offset().top)+parseInt($(objInput).innerHeight()) + 3
		
		$("<ul id='autocomplete'/>").appendTo("body").css("left",wleft).css("top",wtop).css("width",$(objInput).innerWidth()-5)
	}
	wurl = "buscaAutoListagem.asp?tabelaBusca="+ objOpcoesAutocomple.tabela +"&campo="+ objOpcoesAutocomple.campoTabela + "&digitado=" + $("#"+objOpcoesAutocomple.inputText).val()
	erroExtra = false
	if( objOpcoesAutocomple.campoTabelaExtra != "")
	{
		if( $("#"+objOpcoesAutocomple.inputExtra).val() != "" )
		{
			wurl += "&campoExtra=" + objOpcoesAutocomple.campoTabelaExtra + "&valorExtra=" + $("#"+objOpcoesAutocomple.inputExtra).val()
		}
		else
		{
			erroExtra = true
			objFocus = ("#"+objOpcoesAutocomple.inputExtra)
			alert("Preencha o campo " + $("#"+objOpcoesAutocomple.inputExtra).attr("title"))
		}
	}
	
	if( erroExtra == false )
	{
		$.post(wurl,function(retornoPost){
			$("#autocomplete").html(retornoPost)				 
			$("#autocomplete li").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
			$("#autocomplete li").hover(function(){
				
				posicaoAutocomplete = $("#autocomplete li").index($(this))
				$("#autocomplete li:eq("+ posicaoAutocomplete +")").removeClass("autocompleteInativo").addClass("autocompleteAtivo")
				$("#autocomplete li:gt("+ posicaoAutocomplete +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
				$("#autocomplete li:lt("+ posicaoAutocomplete +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
				
			})
			$("#autocomplete li").click(function(){
				
				verificaFocusInput = true
				autocompleteClickLista = true
				$("#"+ objOpcoesAutocomple.inputText ).val($(this).text())
				$("#"+ objOpcoesAutocomple.inputCodigo).val($(this).attr("id"))
				historicoTextAutocomplete = $(this).text()
				$("#autocomplete").remove()
			})					 
		})
	}
	/*$("#autocomplete").load(wurl,function(){
		$("#autocomplete li").hover(function(){
			
			posicaoAutocomplete = $("#autocomplete li").index($(this))
			$("#autocomplete li:eq("+ posicaoAutocomplete +")").removeClass("autocompleteInativo").addClass("autocompleteAtivo")
			$("#autocomplete li:gt("+ posicaoAutocomplete +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
			$("#autocomplete li:lt("+ posicaoAutocomplete +")").removeClass("autocompleteAtivo").addClass("autocompleteInativo")
			
		})
		$("#autocomplete li").click(function(){
			
			verificaFocusInput = true
			$("#"+ objOpcoesAutocomple.inputText ).val($(this).text())
			$("#"+ objOpcoesAutocomple.inputCodigo).val($(this).attr("id"))
			historicoTextAutocomplete = $(this).text()
			$("#autocomplete").remove()
		})
	})*/
}

function setObjectAutoComplete(altElement)
{
	
	altElement = altElement.replace("autocomplete","").replace("completeInput","").replace("busca","")
	
	if( altElement.split(",").length == 5 )
	{
		tabela = altElement.split(",")[0]
		campoTabela = altElement.split(",")[1]
		inputCodigo = altElement.split(",")[2]
		inputText = altElement.split(",")[3]
		inputExtra = altElement.replace("autocomplete","").split(",")[4].split("|")[0]
		campoTabelaExtra = altElement.replace("autocomplete","").split(",")[4].split("|")[1] 
	}
	else
	{
		tabela = altElement.split(",")[0]
		campoTabela = altElement.split(",")[1]
		inputCodigo = altElement.split(",")[2]
		inputText = altElement.split(",")[3]
		inputExtra = ""
		campoTabelaExtra = ""
	}
	
	objOpcoesAutocomple = new opcoesAutoComplete(tabela,campoTabela,inputCodigo,inputText,inputExtra,campoTabelaExtra)	
	
}
horaRestante = 0
minutoRestante = 0
secundoRestante = 0
function relogio()
{
	
	for(i=0;i<$(".hrs").length;i++)
	{
		
		vetRelogio[i].secundoRestante = parseInt(vetRelogio[i].secundoRestante) - 1
		if( vetRelogio[i].secundoRestante < 0 )
		{
			vetRelogio[i].secundoRestante = 59
			vetRelogio[i].minutoRestante = parseInt(vetRelogio[i].minutoRestante) - 1
			if(vetRelogio[i].minutoRestante < 0 )
			{
				vetRelogio[i].minutoRestante = 59
				vetRelogio[i].horaRestante = parseInt(vetRelogio[i].horaRestante) -1
				if(vetRelogio[i].horaRestante < 0 )
				{
					vetRelogio[i].horaRestante = 0
					vetRelogio[i].minutoRestante = 0
					vetRelogio[i].secundoRestante = 0
					$(".btnComprarOferta").hide()
					clearInterval(objIntervalRelogio)
				}
			}
		}
		strHora = new String(vetRelogio[i].horaRestante)
		if( strHora.length == 1)
		{
			$(".hrs:eq("+ i +")").text("0" + strHora)
		}
		else
		{
			$(".hrs:eq("+ i +")").text(vetRelogio[i].horaRestante)	
		}
		strMinuto = new String(vetRelogio[i].minutoRestante)
		if( strMinuto.length == 1)
		{
			$("#minutoRestante_" + $(".hrs:eq("+ i +")").attr("id").split("_")[1]).text("0" + strMinuto)
		}
		else
		{
			$("#minutoRestante_" + $(".hrs:eq("+ i +")").attr("id").split("_")[1]).text(vetRelogio[i].minutoRestante)
		}
		strSecundo = new String(vetRelogio[i].secundoRestante)		
		if( strSecundo.length == 1)
		{
			$("#segundoRestante_" + $(".hrs:eq("+ i +")").attr("id").split("_")[1]).text("0" + strSecundo) 
		}
		else
		{
			$("#segundoRestante_" + $(".hrs:eq("+ i +")").attr("id").split("_")[1]).text(vetRelogio[i].secundoRestante) 	
		}
	}
				
	
}









var posSelect = -1
var vetSelect = new Array();

function selecao(campo,posSelecao)
{
	this.campo = campo
	this.posSelecao = posSelecao		
		
}

fundoOption = new String()
corOption =  new String()
fundoOptionHover = new String()
corOptionHover =  new String()
var limiteItensSelect = 9
var controleSelecao = ""
var contClickCidade = 0
var idListPersonalizado = ""
function iniciaSelectPersonalizado(parametrosOptions,idConteudo)
{
	
	fundoOption = parametrosOptions[0]
	corOption = parametrosOptions[1]
	fundoOptionHover = parametrosOptions[2]
	corOptionHover =  parametrosOptions[3]
	if( idConteudo != "")
	{
		idConteudo = "#" + idConteudo + " "
	}
	
	$(idConteudo + ".caixaTextSelect").show()
	$(idConteudo + ".btnOpenSelect").show()
	$(idConteudo + ".inputSelect").show()
	$(idConteudo + ".selectPersonalizado select").hide()
	
	for(i=0;i<$(idConteudo + ".inputSelect").length;i++)
	{
				
		idElement = $(idConteudo + ".inputSelect:eq("+ i +")").attr("id").replace("text_select_","") 
		for(y=0;y<$("#"+ idElement).find("option").length;y++)
		{
			if( $("#"+ idElement).find("option:eq("+ y +")").is(":selected") )
			{
				vetSelect[vetSelect.length] = new selecao(idElement,y)	
			}
		}
		if( idElement == "codigoCidade" || idElement == "codigoCidadeHome")
		{
			
			$(idConteudo + ".inputSelect:eq("+ i +")").val("Seleção do estado obrigatória")
		}
		else
		{
			if( idElement == "codigoBairro")
			{
				
				$(idConteudo + ".inputSelect:eq("+ i +")").val("Selecione cidade")
			}
			else
			{
				$(idConteudo + ".inputSelect:eq("+ i +")").val( $("#"+ idElement).find("option:selected").text() )		
			}
		}
		//$("#"+ idElement).find("option:eq(0)").attr("selected","selected")
		
			
	}
	$(idConteudo + ".inputSelect").keydown(function(event){

		
		if( event.keyCode == 38 || event.keyCode ==40 || event.keyCode ==116 || event.keyCode ==32 || event.keyCode ==13 || event.keyCode ==27 || event.keyCode ==9)
		{
		
			if( event.keyCode == 38 || event.keyCode ==40 )
			{
				if( event.keyCode == 40 )
				{
					if( $(".listSelect:visible").length > 0 )
					{
						posSelect = parseInt(posSelect)+1
						
						if( posSelect == $(".listSelect:visible").find(".option").length)
						{
							posSelect = 0
						}
					}
					else
					{
						$(this).click()
						//$(".listSelect:visible").find(".option:eq(0)").removeClass("selectOff")
						//$(".listSelect:visible").find(".option:eq(0)").addClass("selectOn")
						idList = $(this).attr("id")
						if( posicaoVetSelect(idList.replace("text_select_","")) < 0 )
						{
							posSelect = 0
							$(".listSelect:visible").find(".option").css("background",fundoOption).css("color",corOption)
							$(".listSelect:visible").find(".option:eq(0)").css("background",fundoOptionHover).css("color",corOptionHover)
							$(this).val($(".listSelect:visible").find(".option:eq(0)").text())
						}
						else
						{
							//$("#"+idList).find(".option:eq("+ posSelect +")").removeClass("selectOff")
							//$("#"+idList).find(".option:eq("+ posSelect +")").addClass("selectOn")
							$("#"+idList.replace("text_","")).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("text_select_",""))].posSelecao +")").css("background",fundoOptionHover).css("color",corOptionHover)
							$(this).val( $("#"+idList.replace("text_","")).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("text_select_",""))].posSelecao +")").text() )   
							posSelect = vetSelect[posicaoVetSelect(idList.replace("text_select_",""))].posSelecao
						}
						
					}
				}
				else
				{
					if( $(".listSelect:visible").length > 0 )
					{
						posSelect = parseInt(posSelect)-1
						if( posSelect < 0 )
						{
							posSelect = $(".listSelect:visible").find(".option").length-1
						}	
					}
				}	
				if( $(".listSelect:visible").length > 0 )
				{
					if( parseInt(posSelect%4) ==0 )
					{
						var divOffset = $(".listSelect:visible").offset().top;
						var pOffset = $(".listSelect:visible").find(".option:eq("+ posSelect +")").offset().top;
						var pScroll = pOffset - divOffset;
						$(".listSelect:visible").animate({scrollTop: '+='  + pScroll + 'px'}, 100);
					}
					//$(".listSelect .option").removeClass("selectOn")
					//$(".listSelect .option").addClass("selectOff") 
					$(".listSelect:visible").find(".option").css("background",fundoOption).css("color",corOption)					
					//$(".listSelect:visible").find(".option:eq("+ posSelect +")").removeClass("selectOff")
					//$(".listSelect:visible").find(".option:eq("+ posSelect +")").addClass("selectOn") 
					$(".listSelect:visible").find(".option:eq("+ posSelect +")").css("background",fundoOptionHover).css("color",corOptionHover)
					idUl = $(".listSelect:visible").attr("id")
					$("#"+ idUl.replace("select_","text_select_") ).val($(".listSelect:visible").find(".option:eq("+ posSelect +")").text())
					
				}
				event.returnValue = false;
				if (event.which){
					event.preventDefault();
				}
				return false;
				
				
			}
			else
			{
				if( event.keyCode ==32 || event.keyCode ==13 )
				{
					if( posSelect >=0 )
					{
						$(".listSelect:visible").find(".option:eq("+ posSelect +")").click()
					}
					event.returnValue = false;
				  	if (event.which){
						event.preventDefault();
				 	}
				  	return false;	
					
					
				}
				else
				{
					
					if( $(".listSelect:visible").length > 0 )
					{
						idList = $(this).attr("id")
						if( posicaoVetSelect(idList.replace("text_select_","")) < 0 )
						{
							posSelect = 0						
							$(this).val($(".listSelect:visible").find(".option:eq(0)").text())
						}
						else
						{
							//$("#"+idList).find(".option:eq("+ posSelect +")").removeClass("selectOff")
							//$("#"+idList).find(".option:eq("+ posSelect +")").addClass("selectOn")						
							$(this).val( $("#"+idList.replace("text_","")).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("text_select_",""))].posSelecao +")").text() )   
						}
					}
					
					$(".caixaSelectPersonalizado").slideUp("hide",function(){ $(".caixaSelectPersonalizado").remove() })
					$("#fundoSelect").remove()	
					
				}
				
				//$(".listSelect .option").removeClass("selectOn")
				//$(".listSelect .option").addClass("selectOff")
				$(".listSelect .option").css("background",fundoOption).css("color",corOption)
			}
			
		
		}	
		else
		{
			event.returnValue = false;
			if (event.which){
			event.preventDefault();
			}
		}			
		
	});
	
	
	
	
	$(idConteudo + ".btnOpenSelect," + idConteudo + ".inputSelect").click(function(){
		controleBtnList = true
		idBtn= $(this).attr("id")
		idList = idBtn.replace("btn_","")
		idList = idList.replace("text_","")		
		
		setTimeout(function(){ $("#text_" + idList).focus() },300)
		if( $("#"+idList).length ==0 || $("#"+idList).is(":hidden") )
		{
			$("#fundoSelect").remove()
			$(".caixaSelectPersonalizado").remove()
				
			
			/*wclassUl = "listSelect" + $("#text_select_" + idList.replace("select_","")).width()
			wclassTopo = "topoSelect" + $("#text_select_" + idList.replace("select_","")).width()
			wclassRodape = "rodapeSelect" + $("#text_select_" + idList.replace("select_","")).width()*/		
			idListPersonalizado = idList
			if( idListPersonalizado != "" )
			{
				str = "<div class='caixaSelectPersonalizado' id='caixaSelectPersonalizado"+ idListPersonalizado +"'>"
			}
			else
			{
				str = "<div class='caixaSelectPersonalizado'>"	
			}
			
			
			if( $("#" + idList.replace("select_","")).find("option").length > limiteItensSelect )
			{
				str += "<div id='btnMoveSelectTopo' class='btnMoveSelectTopoDesable'></div>"	
			}
			else
			{
				str += "<div id='btnSelectTopo'></div>"	
			}
			str += "<div id='caixaConteudoSelectPersonalizado'>"			
			str += "<ul class='listSelect' id='"+ idList +"' >"			
			if( idList != "select_codigoCidadeHome")
			{			
				for(i=0;i<$("#" + idList.replace("select_","")).find("option").length;i++)
				{
					str += "<li id='op_"+ $("#" + idList.replace("select_","")).find("option:eq("+ i +")").val() +"' class='option'>"+ $("#" + idList.replace("select_","")).find("option:eq("+ i +")").text()  +"</li>"
				}
				
				
			}
			
			str += "</ul>"
			str += "</div>"
			if( $("#" + idList.replace("select_","")).find("option").length > limiteItensSelect )
			{
				str += "<div id='btnMoveSelectRodape' class='btnMoveSelectRodape'></div>"	
			}
			else
			{
				str += "<div id='btnSelectRodape'></div>"	
			}
			str += "</div>"
			wleft = parseFloat($("#text_select_" + idList.replace("select_","")).offset().left)
			wtop= parseFloat($(this).parent("div").offset().top) +parseFloat($(this).parent("div").innerHeight())	
			//wtop = parseFloat(wtop) + parseFloat($("#text_select_" + idList.replace("select_","")).innerHeight()) + 13		
			$(str).appendTo("body").css("top",wtop).css("left",wleft)
			if( $("#" + idList.replace("select_","")).find("option").length <= limiteItensSelect )
			{
				alturaCaixa = parseFloat($("#caixaConteudoSelectPersonalizado li").innerHeight()) * $("#" + idList.replace("select_","")).find("option").length				
				$("#caixaConteudoSelectPersonalizado").css("height",alturaCaixa)
			}
			
			
			$("#btnMoveSelectTopo").click(function(){ moveSelectCima() })
			$("#btnMoveSelectRodape").click(function(){ moveSelectBaixo() })
			
			
			
			idList = $("#"+idList).attr("id")
			
			$("#"+idList).slideDown("hide",function(){  				
				$("#fundoSelect").animate({
					opacity:'show',				   
					height: dimensoesTela().split("x")[1],
					width: dimensoesTela().split("x")[0]
				}, 200)
			})	
			
			
			$("<div id='fundoSelect'>&nbsp;</div>").appendTo("body").show()
			objF = document.getElementById("fundoSelect")
			objF.style.width = dimensoesTela().split("x")[0] + "px"
			objF.style.height = dimensoesTela().split("x")[1] + "px"
			$("#fundoSelect").click(function(){
				
				$(".listSelect .option").css("background",fundoOption).css("color",corOption)
				if( $(".listSelect:visible").length > 0 )
				{
					idList = $(".listSelect:visible").attr("id")
					
					if( posicaoVetSelect(idList.replace("select_","")) < 0 )
					{
						posSelect = -1
						$(".inputSelect").val($("#"+idList).find(".option:eq(0)").text())	
					}
					else
					{
						//$("#"+idList).find(".option:eq("+ posSelect +")").removeClass("selectOff")
						//$("#"+idList).find(".option:eq("+ posSelect +")").addClass("selectOn")
						$("#"+idList).find(".option:eq("+ posSelect +")").css("background",fundoOptionHover).css("color",corOptionHover)
						$("#text_"+ idList ).val( $("#"+idList).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("select_",""))].posSelecao +")").text() )   
					}
				}
				
				$(".listSelect li").unbind()
				
				$(".caixaSelectPersonalizado").slideUp("hide",function(){ $(".caixaSelectPersonalizado").remove() })												
				$("#fundoSelect").remove()
			})
			
			funcoesItensSelect(0)	
							
			
		}
		else
		{
			
			$(".caixaSelectPersonalizado").slideUp("hide",function(){ $(".caixaSelectPersonalizado").remove() })
			$("#text_"+ idList ).val( $(".listSelect:visible").find(".option:eq(0)").text() )
			
		}		
		
	})
	
}
function posicaoVetSelect(campo)
{
	campo
	if( vetSelect.length > 0 )
	{
		posVet = -1
		for(i=0;i<vetSelect.length;i++)
		{
			
			if( vetSelect[i].campo == campo )
			{
				posVet = i
				break		
			}
		}
		return posVet
	}
	else
	{
		return -1
	}
}
function funcoesItensSelect(posInicia)
{
	if( posInicia ==0 )
	{
		strIten = 	".listSelect .option"	
	}
	else
	{
		strIten = 	".listSelect .option:gt("+ posInicia +")"
	}
	
	$(strIten).css("background",fundoOption).css("color",corOption)
	$(strIten).unbind()
	$(strIten).mouseover(function(){ 
				
		$(".listSelect .option").css("background",fundoOption).css("color",corOption)				
		$(this).css("background",fundoOptionHover).css("color",corOptionHover)
		idUl = $(".listSelect:visible").attr("id")
		$("#"+ idUl.replace("select_","text_select_") ).val($(this).text())
		for(i=0;i<$(".listSelect .option").length;i++)
		{
			if( $("#" + idUl + " .option:eq("+ i +")").attr("id").split("_")[1] == $(this).attr("id").split("_")[1] )
			{
				posSelect = i
				break;
			}
		}
	} )
	$(strIten).mouseout(function(){ 				
		$(this).css("background",fundoOption).css("color",corOption)
	})
	
	idList = $("#caixaConteudoSelectPersonalizado ul").attr("id")
	if( posicaoVetSelect(idList.replace("select_","")) < 0 )
	{
		posSelect = -1				
		$("#text_"+idList).val( $(".listSelect:visible").find(".option:eq(0)").text() )	
	}
	else
	{
		posSelect = vetSelect[posicaoVetSelect(idList.replace("select_",""))].posSelecao
		//$("#"+idList).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("select_",""))].posSelecao +")").removeClass("selectOff")
		//$("#"+idList).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("select_",""))].posSelecao +")").addClass("selectOn")
		$("#"+idList).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("select_",""))].posSelecao +")").css("background",fundoOptionHover).css("color",corOptionHover)
		$("#text_"+ idList ).val( $("#"+idList).find(".option:eq("+ vetSelect[posicaoVetSelect(idList.replace("select_",""))].posSelecao +")").text() )   
	}
	
	
	$(strIten).click(function(){
											
		
		
		idSelect = $(".listSelect:visible").attr("id")
		idElement = $(this).attr("id")
		textElement = $(this).text()
		
		for(i=0;i<$(".listSelect:visible").find(".option").length;i++)
		{
			if( $(".listSelect:visible").find(".option:eq("+ i +")").attr("id").split("_")[1]	==  idElement.split("_")[1] )
			{
				posSelect = i				
				break
			}
		}
		
		for(i=0;i<$("#" + idSelect.replace("select_","")).find('option').length;i++)
		{
			
			if( $("#" + idSelect.replace("select_","")).find("option:eq(" + i + ")").val() == idElement.split("_")[1] )
			{
				
				$("#" + idSelect.replace("select_","")).find("option:eq(" + i + ")").attr("selected","selected")	
				
				$(".listSelect li").unbind()
				
				//$("#"+idSelect).slideUp("hide")
			
				$(".caixaSelectPersonalizado").slideUp("hide")
				
				$("#text_"+idSelect).val( textElement )
				$("#btn_"+idSelect).blur()
				$("#fundoSelect").remove()
				
				if( posicaoVetSelect(idSelect.replace("select_","")) < 0 )
				{
					vetSelect[vetSelect.length] = new selecao(idSelect.replace("select_",""),posSelect)				
				}
				else
				{
					
					vetSelect[posicaoVetSelect(idSelect.replace("select_",""))].posSelecao = posSelect	
				}
				controleSelecao = textElement
				if( idSelect.replace("select_","") == "codigoCidadeOferta")
				{

					$("#frmSelecaoCidade").submit()	

				}

				
				
				
				break					
			}
		}
				
		
	})
	$("#bloqueioClick").remove()
	
}

function moveSelectBaixo()
{
	$(".btnMoveSelectRodape").unbind()
	wtop = parseFloat($(".caixaSelectPersonalizado").find("ul").css("top")) - parseFloat($("#caixaConteudoSelectPersonalizado").height())	
	
	wlimit = $(".caixaSelectPersonalizado").find("ul").height()
	//wlimit = parseInt($("#cestaConteudoProdutos").height())
	if( (parseFloat(wtop)*(-1)) >= wlimit)
	{									
		//wtop = (parseFloat(wtop)*-1) - parseInt(wlimit)									
		wtop = parseFloat(wlimit) * (-1)
		$(".btnMoveSelectRodape").unbind()
		//$("#btnMoveSelectRodape").attr("src","imagens/lista_seta_baixo2.jpg").css("cursor","default")
		$("#btnMoveSelectRodape").removeClass("btnMoveSelectRodape").addClass("btnMoveSelectRodapeDesable")
	}
	verLimite = $(".caixaSelectPersonalizado").find("ul").height() - (parseFloat(wtop) * (-1))
	if( parseFloat(verLimite) < parseFloat($(".caixaSelectPersonalizado").find("ul").height()))
	{
		wtop = parseFloat(wtop) + (parseFloat($(".caixaSelectPersonalizado").find("li").height()) * 2 )	
	}
	
	idUlSelect = $(".caixaSelectPersonalizado ul").attr("id").replace("select_","")
	
	
	$(".caixaSelectPersonalizado").find("ul").animate({
		top:wtop + 'px'
	}, "hide",function(){
		
		$(".btnMoveSelectRodape").click(function(){ moveSelectBaixo() })			
		if( $("#btnMoveSelectTopo").attr("class") == "btnMoveSelectTopoDesable" )
		{
			
			$("#btnMoveSelectTopo").click(function(){
				 moveSelectCima()															 
			})
			//$("#btnMoveSelectTopo").attr("src","imagens/lista_seta_cima.jpg").css("cursor","pointer")
			$("#btnMoveSelectTopo").removeClass("btnMoveSelectTopoDesable").addClass("btnMoveSelectTopo")
		}
		verLimite = $(".caixaSelectPersonalizado").find("ul").height() - (parseFloat($(".caixaSelectPersonalizado").find("ul").css("top").replace("px","")) * (-1))
		if( parseFloat(verLimite) < parseFloat($("#caixaConteudoSelectPersonalizado").height()))
		{
			$("#btnMoveSelectRodape").unbind()			
			$("#btnMoveSelectRodape").removeClass("btnMoveSelectRodape").addClass("btnMoveSelectRodapeDesable")
		}
	
	});		
	
}
function moveSelectCima()
{
	wtop = parseFloat($(".caixaSelectPersonalizado").find("ul").css("top")) + parseFloat($("#caixaConteudoSelectPersonalizado").height())	
	if( parseFloat(wtop) > 0 )
	{
		wtop = 0		
	}
	$(".caixaSelectPersonalizado").find("ul").animate({
		top:wtop + 'px'
	}, "hide",function(){
		
		if( $("#btnMoveSelectRodape").attr("class") == "btnMoveSelectRodapeDesable" )
		{
			$("#btnMoveSelectRodape").click(function(){
				 moveSelectBaixo()															 
			})
			//$("#btnMoveSelectRodape").attr("src","imagens/lista_seta_baixo.jpg").css("cursor","pointer")
			$("#btnMoveSelectRodape").removeClass("btnMoveSelectRodapeDesable").addClass("btnMoveSelectRodape")
		}
		
		if( parseFloat(wtop) >= 0 )
		{
			wtop = 0
			$("#btnMoveSelectTopo").unbind()
			//$("#btnMoveSelectTopo").attr("src","imagens/lista_seta_cima2.jpg").css("cursor","default")
			$("#btnMoveSelectTopo").removeClass("btnMoveSelectTopo").addClass("btnMoveSelectTopoDesable")
		}
		
		
	});			
}

function calculaDataFinal(numDias)
{
	if( $("#data_inicio").val() != "" )
	{
		vetData = $("#data_inicio").val().split("/")
		if( vetData.length == 3 )
		{
			
			dia = vetData[0]
			if( dia.substring(0,1) == "0" )
			{
				dia = dia.substring(1,2)
			}
			mes = vetData[1]
			
			if( mes.substring(0,1) == "0" )
			{
				mes = mes.substring(1,2)
				
			}
			diaFinal = parseInt(dia) + parseInt(numDias)
			if( mes != 2 )
			{
				
				if( mes == 4 || mes == 6 || mes == 9 || mes == 11)
				{
					
					if( diaFinal > 30 )
					{
						$("#data_fim").val("01/"+ (parseInt(mes)+1) +"/" + vetData[2])		
					}
					else
					{
						
						$("#data_fim").val(diaFinal + "/"+  vetData[1] +"/" + vetData[2])	
					}
				}
				else
				{
					if( diaFinal > 31 )
					{
						$("#data_fim").val("01/"+ (parseInt(mes)+1) +"/" + vetData[2])		
					}
					else
					{
						$("#data_fim").val(diaFinal + "/"+  vetData[1] +"/" + vetData[2])	
					}	
				}
				
			}
			else
			{
				if( numDias <= 28 )
				{
					$("#data_fim").val(diaFinal + "/02/" + vetData[2])	
				}
				else
				{
					$("#data_fim").val("01/03/" + vetData[2])	
				}
			}
		}
	}
}

function incluirFundo(idFundo)

{

	$("#"+idFundo).remove()

	$("<div id='" + idFundo + "' class='fundoOpaco'>&nbsp;</div>").appendTo("body")	

	objF = document.getElementById(idFundo)

	objF.style.width = dimensoesTela().split("x")[0] + "px"

	objF.style.height = dimensoesTela().split("x")[1] + "px"

}


// JavaScript Document


function iniciarFuncoesPainel()
{
	
	
	
}

function fechaDivEmail(idMsg,idBarra)
{		
	ocultaBarra(idBarra);		
	$("#"+idMsg).remove();
	//$("#email").html($("#email").html()).hide()

	
	return false;		
}


function enviarIndicacoes(codOferta,tipo){		
	
	
	
	if( validaFormGeral(tipo))
	{
		$("#resultadoInd").remove()
		$("<div id='resultadoInd'/>").appendTo("#conteudoFormularios")
		if( tipo == "frm_IndicacoesAmigo")
		{								
			var wurl = 'indicacoes.asp?codOferta='+codOferta+'&tipo='+tipo+'&nome='+$('#nome').val()+'&nome_amigo='+$('#nome_amigo').val()+'&end_eletronico_seu='+$('#end_eletronico_seu').val()+'&end_eletronico_amigo='+$('#end_eletronico_amigo').val()
			var wmsg = 'Indicando amigo...'
		}
		else
		{
			var wurl = 'indicacoes.asp?codOferta='+codOferta+'&tipo='+tipo+'&loginTwitter='+$('#loginTwitter').val()+'&senhaTwitter='+$('#senhaTwitter').val()
			var wmsg = 'Postando no Twitter...'
		}
	//	alert(wurl);
		$("<div id='caixaCarregando' class='carregando'><img src='imagens/loading.gif' style='margin-right:10px;position:relative;top:3px;'><label>" +wmsg+ "</label></div>").appendTo("#resultadoInd")
		$.post(wurl,function(retornoPost){
			$("#resultadoInd").html(retornoPost)
		})
		return false
		
	}
	else
	{
		return false	
	}
	
}


function insereEmail(idForm){
	
	erroEmail = false
	if( idForm == "frm_cadastroTopo")
	{
		email = $('#end_eletronico2').val()
		cidade = $("#codigoCidade").val()
		categoria = ""		
		if( $('#codigoCidadeOferta').length > 0 )
		{
			cidade = $('#codigoCidadeOferta').val()
		}
		if( $('#end_eletronico2').val() == 'Digite seu e-mail aqui...' || $('#end_eletronico2').val() == '' || $("codigoCidade").val() == '' )
		{
			erroEmail = true	
		}
		idIns = "resultado"
	}
	else
	{
		email = $('#end_eletronicoCad').val()
		cidade = ""
		for(i=0;i<$("input[name='codigoCidade']:checked").length;i++)
		{
			if( cidade == "" )
			{
				cidade = $("input[name='codigoCidade']:checked:eq("+ i +")").val()
			}
			else
			{
				cidade += "," +  $("input[name='codigoCidade']:checked:eq("+ i +")").val()	
			}
		}
		categoria=""
		for(i=0;i<$("input[name='codigoCategoria']:checked").length;i++)
		{
			if( categoria == "" )
			{
				categoria = $("input[name='codigoCategoria']:checked:eq("+ i +")").val()
			}
			else
			{
				categoria += "," +  $("input[name='codigoCategoria']:checked:eq("+ i +")").val()	
			}
		}
		
		if( $('#end_eletronico').val() == '' )
		{
			erroEmail = true	
		}
		idIns = "resultadoCad"
		$('#end_eletronicoCad').focus()
	}
	
	if( erroEmail == false )
	{
		$("#" + idIns).empty();
		$("#btnCadastraEmailTopo").focus()
		$("<div id='caixaCarregando' class='carregando' style='margin:0 auto;'><img src='imagens/loading.gif' style='margin-right:5px;position:relative;top:3px;'><label>Enviando dados...</label></div>").appendTo("#" + idIns)
		setTimeout(function(){
			
			
			//var wurl = $("#"+idForm).attr("action")  + '&end_eletronico2='+ email
			var wurl = $("#"+idForm).attr("action")  + '&end_eletronico='+ email + "&cidade=" + cidade + "&categoria=" + categoria
			
			$("#" + idIns).load(wurl)
						   
		},2000)
	}
	else
	{
		if( $("#codigoCidade").val() == "" )
		{
			wtexto = "Selecione a sua cidade!"	
		}
		else
		{
			wtexto = "Digite seu e-mail!"		
		}
		
		$("#" + idIns).empty();
		$("<div id='caixaCarregando' class='erro' style='margin:0 auto;'><img src='imagens/icon_error.png' style='margin-right:5px;position:relative;top:3px'><label style='margin-right:5px;position:relative;top:-4px;'>"+ wtexto +"</label></div>").appendTo("#" + idIns)
	}
	
	return false;	
	
}
function abreMapa(empresa){
	
		incluirFundo('fundoCidades','')
		
		
		wleft = ( parseInt(dimensoesTela().split("x")[0]) - parseFloat(31) ) / 2
		if (document.all)
		{
			var wtop = parseInt(document.documentElement.scrollTop)
		}
		else
		{
			var wtop = parseInt(window.scrollY)
		}
		wtop = parseFloat(wtop) + ( ( parseFloat($(window).height()) - parseFloat(31) ) / 2 )
		
		$("<img src='imagens/ajax-loader.gif' id='carregando'>").css("left",wleft).css("top",wtop).css("position","absolute").css("z-index","1000").appendTo("body")
		$("<div id='caixaMapa'/>").appendTo("body").hide()
		
		//alert("mapas.asp?empresa="+empresa)
		
		$("#caixaMapa").load("mapas.asp?empresa="+empresa,function(){			
			
			
			$("#fundoCidades,#btnFecharComboCidade").click(function(){
				$("#caixaMapa").remove()
				$("#fundoCidades").remove()	
				$("#carregando").remove()
				bounds = null;
				currentMarker = null;
				mapDiv = null;
				containerDiv = null;
				clickedX = 0;
				clickedY = 0;
				isLoaded = false;
				
			})
			loadMapGadget()
																	 
		})
		return false
}


/**
 * The map object, null until script loads in.
 * @type {GMap2}
 */
var map = null;  
/**
 * The bounds of the markers once loaded in.
 * @type {GLatLngBounds}
 */
var bounds = null;
 
/**
 * The marker with currently opened info window.
 * @type {GMarker}
 */
var currentMarker = null;
 
/**
 * The dom element that the map is loaded into
 * @type {Element}
 */
var mapDiv = null;
 
/**
 * The dom element that everything is a child of.
 * @type {Element}
 */
var containerDiv = null;
 
/**
 * Position of mouse click (clientX) on map div when in static mode.
 * @type {Number}
 */
var clickedX = 0;
 
/**
 * Position of mouse click (clientY) on map div when in static mode.
 * @type {Number}
 */
var clickedY = 0;
 
/**
 * Indicates whether we've created a script tag with Maps API yet
 * @type {Boolean}
 */
var isLoaded = false;
 
 
/**
 * Called after script is asynchronously loaded in.
 * Creates the GMap2, GMarker objects and performs actions according to 
 * what the user did to trigger the map load (search, zoom, click etc).
 */
function loadMap() {
  if (GBrowserIsCompatible()) {
    mapDiv.style.background = '#FFF';
    mapDiv.style.cursor = '';
    map = new GMap2(mapDiv, {logoPassive: true});
	
    bounds = new GLatLngBounds();
    for (var i = 0; i < businesses.length; i++) {
      bounds.extend(new GLatLng(businesses[i].lat, businesses[i].lng));
    }
    var latSpan = bounds.toSpan().lat();
	boundsAux = new GLatLngBounds();
	boundsAux.extend(new GLatLng(businesses[0].lat, businesses[0].lng));
    map.setCenter(boundsAux.getCenter(), map.getBoundsZoomLevel(bounds));
 	map.enableScrollWheelZoom();
	map.setZoom(15)
	
    // The static map server gives markers more space when calculating
    // bounds and zoom level, so sometimes the API will give a higher
    // zoom level than was used by the static map server.
    // The .98 value is just a guess right now, may need tweaking.
    var newBounds = map.getBounds();
    var newLatSpan = newBounds.toSpan().lat();
    if (latSpan/newLatSpan > .90) { map.zoomOut(); }
 
    for (var i = 0; i < businesses.length; i++) {
      var marker = createMarker(i);
      var latlng = marker.getLatLng();
      var pixel = map.fromLatLngToDivPixel(latlng);
      if (Math.abs(pixel.x - clickedX) < 12 && Math.abs(pixel.y - clickedY) < 20) {
        //GEvent.trigger(marker, 'click');
      }
      map.addOverlay(marker);
    }
  }
}
 
/**
 * Zooms to the viewport that fits all the markers.
 */
function zoomToAll() {
  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}
 
/**
 * Creates a marker for the given business.
 * @param {Number} ind
 * @return {GMarker}
 */
function createMarker(ind) {
  var business = businesses[ind];
  var marker = new GMarker(new GLatLng(business.lat, business.lng));
  GEvent.addListener(marker, 'click', function() {
    marker.html = ['<b>', business.name, '</b><br>', 
                 business.street, '<br> ', business.city, ',', 
                 business.state, ' ', business.zip, '<br>',
                 business.phone, '<br><br>', 
                 '<a target="_blank" ',
                 'href="http://maps.google.com/maps?saddr=&daddr=',
                 formatAddressForMaps(business), '">Traçar Rota</a><br><br>',
                 '<a href="javascript:zoomToAll()">Exibir localização de todos os endereços</a>'].join('');
    currentMarker = marker;
    marker.openInfoWindowHtml(marker.html);
  });
  return marker;
}
 
/**
 * Formats business info into a URL-friendly version for maps url.
 * @param {Object} business
 * @return {String}
 */
function formatAddressForMaps(business) {
  var address = business.street + ' ' + business.city + ' ' + business.state + ' ' + business.zip;
  return escape(address.replace(' ', '+'));
}
 
/**
 * Convenience function for creating an element and assigning an id to it.
 * @param {String} elementType
 * @param {String} id
 * @return {Element} 
 */
function _cel(elementType, id) {
  var element = document.createElement(elementType);
  element.id = id;
  return element;
}
 
/**
 * Loads in the Maps API script. This is called after some sort of user interaction.
 * The script loads asynchronously and calls loadMap once it's in.
 */
function loadScript() {
  if (!isLoaded) {
    isLoaded = true;
    var div = document.createElement('div');
    div.className = 'message';
    div.innerHTML = 'Carregando...';
    div.style.left = (450/2 - 53) + 'px';
    div.style.top = 450/2 + 'px'; 
    mapDiv.appendChild(div);
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://maps.google.com/maps?file=api&v=2' + 
                 '&async=2&callback=loadMap&key=ABQIAAAA7WsM0_rR2th5AV6OKpMecxStc3KIUE1Onye859RRfxvhJKDdAhQHTPscjd_i2iooYhAnsV4FOKb_Kg';
    document.body.appendChild(script);
  }
}
 
/**
 * Sets up the gadget by setting CSS and click events.
 */
function loadMapGadget() {
  containerDiv = document.getElementById('container');
  mapDiv = document.getElementById('map');
 
  mapDiv.onclick = function (e) {
    clickedX = (window.event && window.event.offsetX) || e.clientX;
    clickedY = (window.event && window.event.offsetY) || e.clientY;
    loadScript(); 
  };
 
  mapDiv.style.cursor = 'pointer';
 
  var urlString = ['http://maps.google.com/staticmap?markers='];
  var markerString = [];
  //for (var i = 0; i < businesses.length; i++) {
    i = 0
	markerString.push(businesses[i].lat + ',' + businesses[i].lng + ',red');
  //}
  urlString.push(markerString.join('|'));
  urlString.push('&size=450x300&zoom=15');
  urlString.push('&key=ABQIAAAA7WsM0_rR2th5AV6OKpMecxStc3KIUE1Onye859RRfxvhJKDdAhQHTPscjd_i2iooYhAnsV4FOKb_Kg');
  mapDiv.style.background = 'url(\'' + urlString.join('') + '\')';
 
 
 item_img_des = document.createElement("img");
 
 mapDiv.appendChild(item_img_des); 
 mapDiv.style.background = "none"
 item_img_des.onload = function(){
	$("#map").height(330)
 }
 item_img_des.src = urlString.join('');
 
}

function limpar_campos(id)
{

	if( id != "")
	{
		$("#" + id + " input,#" + id + " textarea").val("")
		$("#" + id + " select").find("option:eq(0)").attr("selected","selected")
		$("#" + id + " input[type='radio'],#" + id + " input[type='checkbox']").attr("checked","")
	}
	else
	{
		$("input,textarea").val("")
		$("select").find("option:eq(0)").attr("selected","selected")
		$("input[type='radio']input[type='checkbox']").attr("checked","")	
	}
}

function showTab(id,cont){
	//alert(id)
	if(document.getElementById("tabaux"+cont).value!=""){
		document.getElementById("tab_"+document.getElementById("tabaux"+cont).value).style.borderBottom = "1px solid #4F5A75";
		document.getElementById("tab_"+document.getElementById("tabaux"+cont).value).style.backgroundImage = "url('imagens/barra_bg.jpg')";
		document.getElementById("tab_"+document.getElementById("tabaux"+cont).value).style.fontWeight = "normal";
		document.getElementById("cont_tab_"+document.getElementById("tabaux"+cont).value).style.display = "none";
		
	}
	document.getElementById("tab_"+id).style.backgroundImage = "url('imagens/barra_bg_down.jpg')";
	document.getElementById("tab_"+id).style.borderBottom = "none";
	document.getElementById("tab_"+id).style.fontWeight = "bold";
	document.getElementById("cont_tab_"+id).style.display = "";
	document.getElementById("tabaux"+cont).value = id;
}


//================================================================================
function calcIngresso(qtdA, qtdC, valorOrigA, valorA, valorOrigC, valorC, idValorFinal, totalDia, valorTotalA, valorTotalC, valorTotalDia){
	wqtdA = document.getElementById(qtdA);
	wqtdC = document.getElementById(qtdC);
	wvalorOrigA = parseFloat(document.getElementById(valorOrigA).value);
	wvalorOrigC = parseFloat(document.getElementById(valorOrigC).value);
	wvalorA = parseFloat(document.getElementById(valorA).value);
	wvalorC = parseFloat(document.getElementById(valorC).value);
	wtotalDia = document.getElementById(totalDia);
	wvalorTotalA = document.getElementById(valorTotalA);
	wvalorTotalC = document.getElementById(valorTotalC);
	wvalorTotalDia = document.getElementById(valorTotalDia);
	
	wvalorTotalA.value = Precision(wvalorOrigA, 2);
	wvalorTotalC.value = Precision(wvalorOrigC, 2);
	
	wTotal = (wqtdA.value * wvalorA) + (wqtdC.value * wvalorC);
	wTotal = Precision(wTotal, 2)
	var wstr = new String(wTotal);
	valorFinal = wstr;
		
	document.getElementById(idValorFinal).innerHTML = valorFinal.replace(".",",");
	wvalorTotalDia.value = valorFinal;
}

function altQtd(valorOrigA, valorOrigOpA, valorAltA, qtdPassA, valorOrigC, valorOrigOpC, valorAltC, qtdPassC, qtdDia, precoDia, idSubTotal, idValorFinal, totalDia, valorTotalDia){
	//wqtdDia = document.getElementById(qtdDia).value;
	wqtdDia = document.getElementById(qtdDia);
	wqtdPassA = document.getElementById(qtdPassA);
	wqtdPassC = document.getElementById(qtdPassC);
	wtotalDia = document.getElementById(totalDia);
	wvalorTotalDia = document.getElementById(valorTotalDia);
	
	for(i=1;i<=wqtdDia;i++){
		wprecoDia = document.getElementById(precoDia+i);
		
		novoValorA = Precision(parseFloat(document.getElementById(valorOrigOpA+i).value) * parseInt(wqtdPassA.value),2);
		//document.getElementById(valorOrigA+i).value = novoValorA;
		if(parseInt(wqtdPassA.value) > 0){
			document.getElementById(valorAltA+i).value = Precision(novoValorA,2);
		}else{
			document.getElementById(valorAltA+i).value = Precision(document.getElementById(valorOrigA+i).value,2);
		}
		
		novoValorC = Precision(parseFloat(document.getElementById(valorOrigOpC+i).value) * parseInt(wqtdPassC.value),2);
		//document.getElementById(valorOrigC+i).value = novoValorC;
		if(parseInt(wqtdPassC.value) > 0){
			document.getElementById(valorAltC+i).value = Precision(novoValorC,2);
		}else{
			document.getElementById(valorAltC+i).value = Precision(document.getElementById(valorOrigC+i).value,2);
		}
		
		var wSubTotal = parseFloat(novoValorA) + parseFloat(novoValorC);
		wSubTotal = Precision(wSubTotal,2);
		var wstrSub = new String(wSubTotal);
		valorSubFinal = wstrSub;
			
		document.getElementById(idSubTotal+i).innerHTML = valorSubFinal.replace(".",",");
		
		if(wprecoDia.checked == true){
			wTotal = parseFloat(novoValorA) + parseFloat(novoValorC);
			wTotal = Precision(wTotal,2);
			var wstr = new String(wTotal);
			valorFinal = wstr;
				
			document.getElementById(idValorFinal).innerHTML = valorFinal.replace(".",",");
			wvalorTotalDia.value = valorFinal.replace(".",",");
		}
	}
}

function altOp(diaOp, valorOrigA, valorOrigC, valorOrigOpA, valorOrigOpC, valorOpA, valorOpC, qtdA, qtdC, totalDia, totalOp, valorA, valorC, precoDia, subTotal, idValorFinal, valorAltA, valorAltC, contOp, valorTotalDia){
	wdiaOp = document.getElementById(diaOp);
	wqtdA = document.getElementById(qtdA);
	wqtdC = document.getElementById(qtdC);
	wtotalDia = document.getElementById(totalDia);
	wtotalOp = document.getElementById(totalOp);
	wcontOp = document.getElementById(contOp);
	wvalorTotalDia = document.getElementById(valorTotalDia);
	
	if(wdiaOp.checked == true){
		wcontOp.value++;
		for(i=1;i<=wtotalDia.value;i++){
			wvalorAltA = document.getElementById(valorAltA+i);
			wvalorAltC = document.getElementById(valorAltC+i);
			wvalorOrigA = document.getElementById(valorOrigA+i);
			wvalorOrigC = document.getElementById(valorOrigC+i);
			wvalorOrigOpA = document.getElementById(valorOrigOpA+i);
			wvalorOrigOpC = document.getElementById(valorOrigOpC+i);
			wvalorOpA = document.getElementById(valorOpA+i+"_"+wdiaOp.value);
			wvalorOpC = document.getElementById(valorOpC+i+"_"+wdiaOp.value);
			wprecoDia = document.getElementById(precoDia+i);
			wsubTotal = document.getElementById(subTotal+i);
			
			if(wcontOp.value == 1){
				wvalorA = (parseFloat(wvalorOrigA.value) * parseInt(wqtdA.value)) + (parseFloat(wvalorOpA.value) * parseInt(wqtdA.value));
				wvalorA2 = parseFloat(wvalorOrigA.value) + parseFloat(wvalorOpA.value);
			}else{
				wvalorA = (parseFloat(wvalorOrigOpA.value) * parseInt(wqtdA.value)) + (parseFloat(wvalorOpA.value) * parseInt(wqtdA.value));
				wvalorA2 = parseFloat(wvalorOrigOpA.value) + parseFloat(wvalorOpA.value);
			}
			wvalorA = Precision(wvalorA, 2);
			wvalorA2 = Precision(wvalorA2, 2);
			
			if(parseInt(wqtdA.value) > 0){
				wvalorOrigOpA.value = wvalorA2;
				wvalorAltA.value = wvalorA;
			}else{
				wvalorOrigOpA.value = Precision(parseFloat(wvalorOrigOpA.value) + parseFloat(wvalorOpA.value), 2);
				wvalorAltA.value = Precision(parseFloat(wvalorAltA.value) + parseFloat(wvalorOpA.value), 2);
				wvalorA = Precision(0, 2);
			}
			
			var wstrA = new String(wvalorOrigOpA.value);
			valorFinalA = wstrA;
			document.getElementById(valorA+i).innerHTML = valorFinalA.replace(".",",");
			
			if(wcontOp.value == 1){
				wvalorC = (parseFloat(wvalorOrigC.value) * parseInt(wqtdC.value)) + (parseFloat(wvalorOpC.value) * parseInt(wqtdC.value));
				wvalorC2 = parseFloat(wvalorOrigC.value) + parseFloat(wvalorOpC.value);
			}else{
				wvalorC = (parseFloat(wvalorOrigOpC.value) * parseInt(wqtdC.value)) + (parseFloat(wvalorOpC.value) * parseInt(wqtdC.value));
				wvalorC2 = parseFloat(wvalorOrigOpC.value) + parseFloat(wvalorOpC.value);
			}
			wvalorC = Precision(wvalorC, 2);
			wvalorC2 = Precision(wvalorC2, 2);
			
			if(parseInt(wqtdC.value) > 0){
				wvalorOrigOpC.value = wvalorC2;
				wvalorAltC.value = wvalorC;
			}else{
				wvalorOrigOpC.value = Precision(parseFloat(wvalorOrigOpC.value) + parseFloat(wvalorOpC.value), 2);
				wvalorAltC.value = Precision(parseFloat(wvalorAltC.value) + parseFloat(wvalorOpC.value), 2);
				wvalorC = Precision(0, 2);
			}
			
			var wstrC = new String(wvalorOrigOpC.value);
			valorFinalC = wstrC;
			document.getElementById(valorC+i).innerHTML = valorFinalC.replace(".",",");
			
			wvalorT = parseFloat(wvalorA) + parseFloat(wvalorC);
			wvalorT = Precision(wvalorT, 2)
			
			var wstrT = new String(wvalorT);
			valorFinalT = wstrT;
			
			wsubTotal.innerHTML = valorFinalT.replace(".",",");
						
			if(wprecoDia.checked == true){			
				document.getElementById(idValorFinal).innerHTML = valorFinalT.replace(".",",");
				wvalorTotalDia.value = valorFinalT;
			}
		}
	}else{
		wcontOp.value --;
		for(i=1;i<=wtotalDia.value;i++){
			wvalorAltA = document.getElementById(valorAltA+i);
			wvalorAltC = document.getElementById(valorAltC+i);
			wvalorOrigA = document.getElementById(valorOrigA+i);
			wvalorOrigC = document.getElementById(valorOrigC+i);
			wvalorOrigOpA = document.getElementById(valorOrigOpA+i);
			wvalorOrigOpC = document.getElementById(valorOrigOpC+i);
			wvalorOpA = document.getElementById(valorOpA+i+"_"+wdiaOp.value);
			wvalorOpC = document.getElementById(valorOpC+i+"_"+wdiaOp.value);
			wprecoDia = document.getElementById(precoDia+i);
			wsubTotal = document.getElementById(subTotal+i);
			
			if(wcontOp.value == 0){
				wvalorA = parseFloat(wvalorOrigA.value) * parseInt(wqtdA.value);
				wvalorA2 = parseFloat(wvalorOrigA.value);
			}else{
				//alert(wvalorAltA.value-(wvalorOpA.value*wqtdA.value))
				wvalorA = parseFloat(wvalorAltA.value) - (parseFloat(wvalorOpA.value) * parseInt(wqtdA.value));
				wvalorA2 = parseFloat(wvalorOrigOpA.value) - parseFloat(wvalorOpA.value);
			}
			wvalorA = Precision(wvalorA, 2);
			wvalorA2 = Precision(wvalorA2, 2);
			
			if(parseInt(wqtdA.value) > 0){
				wvalorOrigOpA.value = wvalorA2;
				wvalorAltA.value = wvalorA;
			}else{
				wvalorOrigOpA.value = parseFloat(wvalorOrigA.value);
				wvalorAltA.value = Precision(parseFloat(wvalorAltA.value) - parseFloat(wvalorOpA.value), 2);
				wvalorA = 0;
			}
			
			var wstrA = new String(wvalorOrigOpA.value);
			valorFinalA = wstrA;
			document.getElementById(valorA+i).innerHTML = valorFinalA.replace(".",",");
			
			if(wcontOp.value == 0){
				wvalorC = parseFloat(wvalorOrigC.value) * parseInt(wqtdC.value);
				wvalorC2 = parseFloat(wvalorOrigC.value);
			}else{
				wvalorC = parseFloat(wvalorAltC.value) - (parseFloat(wvalorOpC.value) * parseInt(wqtdC.value));
				wvalorC2 = parseFloat(wvalorOrigOpC.value) - parseFloat(wvalorOpC.value);
			}
			wvalorC = Precision(wvalorC, 2);
			wvalorC2 = Precision(wvalorC2, 2);
			
			if(parseInt(wqtdC.value) > 0){
				wvalorOrigOpC.value = wvalorC2;
				wvalorAltC.value = wvalorC;
			}else{
				wvalorOrigOpC.value = Precision(parseFloat(wvalorOrigC.value), 2);
				wvalorAltC.value = Precision(parseFloat(wvalorAltC.value) - parseFloat(wvalorOpC.value), 2);
				wvalorC = 0;
			}
			
			var wstrC = new String(wvalorOrigOpC.value);
			valorFinalC = wstrC;
			document.getElementById(valorC+i).innerHTML = valorFinalC.replace(".",",");
			wvalorT = parseFloat(wvalorA) + parseFloat(wvalorC);
			wvalorT = Precision(wvalorT, 2);
			
			var wstrT = new String(wvalorT);
			valorFinalT = wstrT;
			
			wsubTotal.innerHTML = valorFinalT.replace(".",",");
						
			if(wprecoDia.checked == true){
				document.getElementById(idValorFinal).innerHTML = valorFinalT.replace(".",",");
				wvalorTotalDia.value = valorFinalT;
			}
		}
	}
}
function Precision(num, nDecimals){
    var toReturn = "";
    num = "" + num;
    var pointIdx = num.indexOf('.');
    //garantir que é decimal
    if(pointIdx == -1){
        num += '.';
        pointIdx = num.indexOf('.');
    }
    var limit = pointIdx + nDecimals + 1;
    //quando se tem mais casas decimais que aquelas que se pretende
    if(num.length > limit){
        //arredondar para baixo
        if(num[limit] < '5')
        {
            for(var iter = 0; iter < limit; ++iter)
            {
                toReturn += num.charAt(iter);
            }
            return toReturn;
        }
        //arredondar para cima
        else{
            for(var iter = 0; iter < pointIdx + nDecimals; ++iter){
                toReturn += num.charAt(iter);
            }
            var lastNum = parseInt(num.charAt(pointIdx + nDecimals)) + parseInt(1);
            toReturn += lastNum;
            return toReturn;
        }
    }
    //acrescentar 0s à direita se necessário
    if(num.length < limit){
        while(num.length < limit){
            num += '0';
        }
    }
    return num;
}

function sendForm(conta,codigo,cod_dest,tipo,session,pag,vetor,secao) {
	var url
	if (vetor != ""){
		
	if(document.getElementById("inp_busca"+conta).disabled == false){
	num_noites = document.getElementById("num_noites"+conta).value 
	var_busca = ""
	if(document.getElementById("busca"+conta).value != ""){
		var_busca = document.getElementById("busca"+conta).value
	}
	
	if(session != 1){
		location.href="destinos2.asp";
	}else{
		id = "hoteis_conteudo"+conta;
		if (tipo == 1){
		}
		if (tipo == 3){
			cods = document.getElementById("cod_quartos"+conta).value;
			if(secao == "hotel"){
				url = "dadosHotel.asp?num_noites="+num_noites+"&codigo="+codigo+"&conta="+conta+"&cod_dest="+cod_dest+"&cod_quartos="+cods+"&busca="+var_busca+"&pagina_pag="+pag+"&hotel=S"
			}else{
				url = "dadosHotel.asp?num_noites="+num_noites+"&codigo="+codigo+"&conta="+conta+"&cod_dest="+cod_dest+"&cod_quartos="+cods+"&busca="+var_busca+"&pagina_pag="+pag
			}
		}

		ajax = ajaxInit();
		
		if(ajax) {   
			obj = document.getElementsByTagName("img");
			obj_inp = document.getElementsByTagName("input");
			for(i=0;i<=obj_inp.length-1;i++){
				if(obj_inp[i].id != ""){
					if(obj_inp[i].type == "image"){
						document.getElementById(obj_inp[i].id).style.filter = "gray";
					}
				}
			}
			for(i=0;i<=obj.length-1;i++){
				if(obj[i].id != ""){
					document.getElementById(obj[i].id).style.filter = "gray";
				}
			}
			
			document.getElementById("carrega").style.visibility = "visible";
			document.getElementById("conteudo").disabled = true;
			
			ajax.open("GET",url, true);
			ajax.onreadystatechange = function() {
				if(ajax.readyState == 4) {
					if(ajax.status == 200) {
						for(i=0;i<=obj.length-1;i++){
							if(obj[i].id != ""){
								//alert(obj[i].id)
								document.getElementById(obj[i].id).style.filter = "";
							}
						}
						for(i=0;i<=obj_inp.length-1;i++){
							if(obj_inp[i].id != ""){
								if(obj_inp[i].type == "image"){
									document.getElementById(obj_inp[i].id).style.filter = "";
								}
							}
						}
						document.getElementById(id).style.display= "";
						document.getElementById(id).innerHTML = ajax.responseText;
						document.getElementById("conteudo").disabled = false;
						document.getElementById("carrega").style.visibility = "hidden";
					}else{
						alert(ajax.statusText);
					}
				}
			}
			ajax.send(null);
		}
	}
	}else{
		alert("Marque algum tipo de acomodação, ou escreva o nome do hotel no campo de busca.")
	}
	}else{
	var_busca = ""
	if(document.getElementById("busca"+conta).value != ""){
		var_busca = document.getElementById("busca"+conta).value
	}
	if(session != 1){
		location.href="default.asp?secao=destinos2.asp";
	}else{
		num_noites = document.getElementById("num_noites"+conta).value 

		id = "hoteis_conteudo"+conta;
		if (tipo == 1){
		}
		if (tipo == 3){
			cods = document.getElementById("cod_quartos"+conta).value;
			if(secao == 'hotel'){
				url = "dadosHotel.asp?num_noites="+num_noites+"&codigo="+codigo+"&conta="+conta+"&cod_dest="+cod_dest+"&cod_quartos="+cods+"&busca="+var_busca+"&pagina_pag="+pag+"&hotel=S";
			}else{
				url = "dadosHotel.asp?num_noites="+num_noites+"&codigo="+codigo+"&conta="+conta+"&cod_dest="+cod_dest+"&cod_quartos="+cods+"&busca="+var_busca+"&pagina_pag="+pag;
			}
		}

		ajax = ajaxInit();
		//alert(url)
		if(ajax) {
			obj = document.getElementsByTagName("img");
			obj_inp = document.getElementsByTagName("input");
			for(i=0;i<=obj_inp.length-1;i++){
				if(obj_inp[i].id != ""){
					if(obj_inp[i].type == "image"){
						document.getElementById(obj_inp[i].id).style.filter = "gray";
					}
				}
			}
			for(i=0;i<=obj.length-1;i++){
				if(obj[i].id != ""){
					document.getElementById(obj[i].id).style.filter = "gray";
				}
			}
			document.getElementById("carrega").style.visibility = "visible";
			document.getElementById("conteudo").disabled = true;
			ajax.open("GET",url, true);
			ajax.onreadystatechange = function() {
				if(ajax.readyState == 4) {
					if(ajax.status == 200) {
						for(i=0;i<=obj.length-1;i++){
							if(obj[i].id != ""){
								//alert(obj[i].id)
								document.getElementById(obj[i].id).style.filter = "";
							}
						}
						for(i=0;i<=obj_inp.length-1;i++){
							if(obj_inp[i].id != ""){
								if(obj_inp[i].type == "image"){
									document.getElementById(obj_inp[i].id).style.filter = "";
								}
							}
						}
						document.getElementById(id).style.display= "";
						document.getElementById(id).innerHTML = ajax.responseText;
						document.getElementById("conteudo").disabled = false;
						document.getElementById("carrega").style.visibility = "hidden";
					}else{
						alert(ajax.statusText);
					}
				}
			}
			ajax.send(null);
		}
	}
	
	
	}
}

function auto_combo_promo(valor,id,conta,dataEntrada,dataDev){
	var dataI = document.getElementById(dataEntrada).value;
	var dataF = document.getElementById(dataDev).value
	
	var wdataE = document.getElementById(dataEntrada).value.split('/');
	
	wnovaDataE = wdataE[1] +'/'+ wdataE[0] +'/'+ wdataE[2];
	
	var wdataS = document.getElementById(dataDev).value.split('/');
	
	wnovaDataS = wdataS[1] +'/'+ wdataS[0] +'/'+ wdataS[2];
	
	var pDataCheckin = new Date (wnovaDataE);
	var pDataCheckout = new Date (wnovaDataS);
                
	difDias = Math.abs(Math.round((pDataCheckout-pDataCheckin)/86400000));
	
	ajax = ajaxInit();

	if(ajax) {
		ajax.open("GET","auto_combo_promo.asp?valor=" + valor + "&conta="+conta + "&dia="+difDias+"&dataI="+dataI+"&dataF="+dataF, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					document.getElementById(id+conta).innerHTML = ajax.responseText;
				}else{
					
				}
			}
   		}
		ajax.send(null);
	}
}
function auto_combo(valor,conta,url,id) {
	ajax = ajaxInit();
	//alert(codigo+" "+tipo)
	if(ajax) {
		ajax.open("GET",url+"?valor=" + valor + "&conta="+conta, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
				
					document.getElementById(id+conta).innerHTML = ajax.responseText;
					
				}else{
					
				}
			}
   		}
		ajax.send(null);
	}
}


function validaFrmAuto(conta){

	if(document.getElementById("auto_pais"+conta).value == "" || document.getElementById("auto_pais"+conta).value == "0"){
		return false;
	}
	
	if($("#auto_data_ret"+conta).value == "" || document.getElementById("auto_data_ret"+conta).value == "0"){
		alert("Data de retirada está vazio")
		return false
	}
	if($("#auto_data_dev"+conta).value == "" || document.getElementById("auto_data_dev"+conta).value == "0"){
		alert("Data de devolução está vazio")
		return false
	}
	mesRet = $("#auto_data_ret"+conta).val().split("/")[1].toString()		
	mesRet = parseInt(mesRet)-1
	objDia1 = new Date
	objDia1.setFullYear($("#auto_data_ret"+conta).val().split("/")[2],mesRet,$("#auto_data_ret"+conta).val().split("/")[0])
	
	mesDev = $("#auto_data_dev"+conta).val().split("/")[1].toString()		
	mesDev = parseInt(mesDev)-1
	objdia2 = new Date()
	objdia2.setFullYear($("#auto_data_dev"+conta).val().split("/")[2],mesDev,$("#auto_data_dev"+conta).val().split("/")[0])
	
	if(objdia2 < objDia1 ){
		objFocus = $("#auto_data_dev"+conta);
		alert("Data de devolu&ccedil;&atilde;o deve ser superior a data de retirada.");
		return false;
	}
	
	
	
	if(document.getElementById("auto_cidade_ret"+conta).value == "" || document.getElementById("auto_cidade_ret"+conta).value == "0"){
		alert("Cidade de retirada está vazio")
		return false
	}
	if(document.getElementById("auto_cidade_dev"+conta).value == "" || document.getElementById("auto_cidade_dev"+conta).value == "0"){
		alert("Cidade de devolução está vazio")
		return false
	}
	
	if(document.getElementById("auto_agencia_dev"+conta).value == "" || document.getElementById("auto_agencia_dev"+conta).value == "0"){
		alert("Agência de devolução está vazio")
		return false
	}
	if(document.getElementById("auto_agencia_ret"+conta).value == "" || document.getElementById("auto_agencia_ret"+conta).value == "0"){
		alert("Agência de retirada está vazio")
		return false
	}
	
	if(document.getElementById("auto_grupo"+conta).value == "" || document.getElementById("auto_grupo"+conta).value == "0"){
		alert("Grupo de veículo está vazio")
		return false
	}
	
	return true
}

function validaFrmByID(id,nome){
	var controle = 0;
	for (i=0;i<document.getElementsByTagName("input").length;i++){
		if (document.getElementsByTagName("input")[i].type == "radio"){
			
			if (document.getElementsByTagName("input")[i].id == id){
				
				if (document.getElementsByTagName("input")[i].checked == true){
					//alert(document.getElementsByTagName("input")[i].id+" | "+id)
					controle++;
				}
				
			}
		}
	}
	
	if (controle <= 0){
		
		alert("Selecione um "+nome);
		return false
	}
	return true;
}

var offsetfromcursorX=12 //Customize x offset of tooltip
var offsetfromcursorY=10 //Customize y offset of tooltip

var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image
var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).


var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""

var pointerobj=document.all? document.all["dhtmlpointer"] : document.getElementById? document.getElementById("dhtmlpointer") : ""

function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}


function ddrivetip(thetext, thewidth, thecolor){
	if (ns6||ie){
		if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
		if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
		tipobj.innerHTML=thetext
		enabletip=true
		return false
	}
}

function positiontip(e){
if (enabletip){
var nondefaultpos=false
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20
var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20

var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX
var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY

var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth){
	//move the horizontal position of the menu to the left by it's width
	tipobj.style.left=curX-tipobj.offsetWidth+"px"
	nondefaultpos=true
	}
	else if (curX<leftedge)
		tipobj.style.left="5px"
	else{
		//position the horizontal position of the menu where the mouse is positioned
		tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px"
		pointerobj.style.left=curX+offsetfromcursorX+"px"
}

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight){
	tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px"
	nondefaultpos=true
}
else{
	tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px"
	pointerobj.style.top=curY+offsetfromcursorY+"px"
	}
	tipobj.style.visibility="visible"
	if (!nondefaultpos)
		pointerobj.style.visibility="visible"
	else
		pointerobj.style.visibility="hidden"
	}
}
tipobj = '';

function hideddrivetip(){
	if (ns6||ie){
		enabletip=false
		tipobj.style.visibility="hidden"
		pointerobj.style.visibility="hidden"
		tipobj.style.left="-1000px"
		tipobj.style.backgroundColor=''
		tipobj.style.width=''
	}
}

//document.onmousemove=positiontip

function trMouseOver(id){
	objs = document.getElementById(id).getElementsByTagName("td");
	for (i=0;i<objs.length;i++){
		objs[i].bgColor="#F8F8F8"	
	}
}

function trMouseOut(id){
	objs = document.getElementById(id).getElementsByTagName("td");
	for (i=0;i<objs.length;i++){
		objs[i].bgColor="#FFFFFF"	
	}

}

function enviaRadio(conta) {
	id = "hoteis"+conta;
	input = document.getElementsByTagName("input");
	for (i=0;i<=input.length-1;i++){
		if(input[i].type== "radio" ){
			if(input[i].checked==true){
				cods = input[i].value;
				str_vet = cods.split("|");
				cod_hotel = str_vet[0];
				cod_quartos = str_vet[1];
				ajax = ajaxInit();
				if(ajax) {
					ajax.open("GET","enviaHotel.asp?cod_hotel=" + cod_hotel +"&cod_quartos="+cod_quartos+"&conta="+conta, true);
					ajax.onreadystatechange = function() {
						if(ajax.readyState == 4) {
							if(ajax.status == 200) {
								document.getElementById("servicos"+conta).innerHTML = ajax.responseText;
								document.getElementById(id).innerHTML ="";
								document.getElementById(id).style.display="none";
							}else{
								
							}
						}
					}
					ajax.send(null);
				}
				
			}
		}
	}

}
function check_data(){
        barras = Cadastro.data_embarque.value.split("/");
        if (barras.length == 3){
                 dia = barras[0];
                 mes = barras[1];
                 ano = barras[2];
                 resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano <= anoAtual && ano >= 1900));
               if (!resultado) {
                  alert("O formato da data deve ser (dd/mm/yyyy).");
                  Cadastro.data_embarque.focus();
                  return false;
               }
        }else{
     		 alert("O formato da data deve ser (dd/mm/yyyy).");
	         Cadastro.data_embarque.focus();
		     return false;
        }
}

function validaFrmHotel(id){
	nav = navigator.appName
	if (nav == "Microsoft Internet Explorer"){
		var varQtdAdultos = 0;
		var varQtdCriancas = 0;
		var varQtdPessoas = 0;
		var varQtdCateg = 0;
		var categorias = document.getElementById("hoteis_categs").value;
		
		if(document.getElementById("num_noites"+id).value=="0"){
			alert("Selecione a quantidade de noites.")
			return false;
		}
		categorias = categorias.split(",")
		for(i=1;i<categorias.length;i++){
			if(document.getElementById("categ"+id+"_"+i)!=null){
				if(document.getElementById("categ"+id+"_"+i).checked == true){
					varQtdCateg += 1;
					var varNumQuartos = document.getElementById("num_quartos"+id+""+categorias[i]).value;
					//alert(varNumQuartos)0
					for(j=1;j<=varNumQuartos;j++){
						if(document.getElementById(id+categorias[i]+"qtd_adultos"+j)!= null){
							if(document.getElementById(id+categorias[i]+"qtd_adultos"+j)){
								varQtdAdultos = document.getElementById(id+categorias[i]+"qtd_adultos"+j).value;
							}
							if(document.getElementById(id+categorias[i]+"qtd_criancas"+j)!=null){
								varQtdCriancas = document.getElementById(id+categorias[i]+"qtd_criancas"+j).value;
							}
							varQtdPessoas = parseInt(varQtdAdultos)+parseInt(varQtdCriancas);
							varTipoQuarto = document.getElementById(id+categorias[i]+"quarto_nome"+j).value;
							varQtdMax = parseInt(document.getElementById("quartoTipo_"+varTipoQuarto).value);
							if(varQtdPessoas<varQtdMax){
								alert("Atenção: A quantidade de pessoas selecionadas no quarto "+j+" é inferior do que o recomendado para o tipo quarto!");
								return false;
							}
							
						}
					}
					
				}			
			}
		}
		if(varQtdCateg == 0){
			alert("Escolha pelo menos uma categoria.")
			return false;
		}
		return true;
	}else{
		return true;
	}
}

function hideBaloon(){
	document.getElementById("balao").style.display = "none";

}
function enviaFrmCarro(cont,dest){
	estado = document.getElementById("estado"+cont).value;
	extra = document.getElementById("extra"+cont).value;
	
	ajax = ajaxInit();
	if(ajax) {
		document.getElementById("carrega").style.visibility = "visible";
		ajax.open("GET","dadosCarros.asp?estado="+estado+"&extra="+extra+"&cod_dest="+dest+"&conta="+cont, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					document.getElementById("cont_automoveis"+cont).innerHTML = ajax.responseText;
					document.getElementById("carrega").style.visibility = "hidden";
				}else{
					alert(ajax.statusText);
				}
			}
		}
		ajax.send(null);
	}
}

h=0;
curleft = 0;
curtop = 0;
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	
	return [curleft,curtop];
}

function carregaDiv(obj,id,id_size){
	
	var coor = findPos(obj);
	var img_size = document.getElementById(id_size).innerHTML;
	img_size = img_size.split("|");
	document.getElementById(id).style.left = coor[0]+"px";
	document.getElementById(id).style.top = coor[1]-400+"px";
	document.getElementById(id).style.display = "";
}

function marca(cont){
	categs = document.getElementById("categs"+cont).value;
	vet_categ = categs.split(",");
	for(i=1;i<vet_categ.length;i++){
		document.getElementById("categ"+cont+"_"+i).disabled = false;
	}
	
	obj_div = document.getElementById("hotel_container"+cont).getElementsByTagName("input");
	for(i=0;i<obj_div.length;i++){
		if (obj_div[i].type=="checkbox"){
			document.getElementById(obj_div[i].id).disabled=false;
		}
	}
	
	if(document.getElementById("auxi3").value!=""){
		vet = document.getElementById("auxi3").value.split(",");
		for(i=0;i<vet.length-1;i++){
			document.getElementById(vet[i]).style.display="none";
		}
		document.getElementById("auxi3").value="";
	}
	if(document.getElementById("auxi").value==""){
		document.getElementById("formHotel"+cont).style.display='';
		document.getElementById("caixa"+cont).style.border='2px dashed #516486';
		document.getElementById('auxi').value=cont;
	}else{
		if (cont != document.getElementById('auxi').value){
			categs = document.getElementById("categs"+document.getElementById('auxi').value).value;
			
			vet_categ = categs.split(",");
			for(i=1;i<vet_categ.length;i++){
				document.getElementById("categ"+document.getElementById('auxi').value+"_"+i).checked = false;
				document.getElementById("categ"+document.getElementById('auxi').value+"_"+i).disabled = true;
			}
			
			document.getElementById("caixa"+document.getElementById('auxi').value).style.border='none';
			document.getElementById("caixa"+cont).style.border='2px dashed #516486';
			document.getElementById("cod_hotel"+document.getElementById('auxi').value).checked=false;
			document.getElementById("cod_hotel"+document.getElementById('auxi').value).disabled=false;
			document.getElementById("formHotel"+document.getElementById('auxi').value).style.display='none';
			document.getElementById('formHotel'+cont).style.display='';
			document.getElementById('auxi').value=cont;
		}
	}
}

function Observacoes(id,idmais){
	if(document.getElementById(id).style.display == "none"){
		document.getElementById(id).style.display = ""
		document.getElementById(idmais).src = "imagens/ico_menos.gif"
	}else{
		document.getElementById(id).style.display = "none"
		document.getElementById(idmais).src = "imagens/ico_mais.gif"

	}
}
function exibe(id,conta){
	
	vetor = "hoteis"+conta+",voos"+conta+",automoveis"+conta+",ingressos_cont"+conta+",translados_cont"+conta;
	vetor = vetor.split(",");
	for (i = 0;i<=vetor.length-1;i++){
		
		//alert(vetor[i]+"-"+id)
		if(vetor[i]==id){
			
			if(document.getElementById(vetor[i]).style.display == "none"){
				document.getElementById(vetor[i]).style.display="";
			}else{
				document.getElementById(vetor[i]).style.display="none";
			}
		}else{
			document.getElementById(vetor[i]).style.display="none";
		}
	}
}
function hideTab(id, cont){
	
	document.getElementById("tab_"+id).style.backgroundImage = "url('imagens/barra_bg.jpg')";
	document.getElementById("tab_"+id).style.borderBottom= "1px solid  #4F5A75";
	document.getElementById("tab_"+id).style.fontWeight =  "normal";
	document.getElementById("cont_tab_"+id).style.display = "none";
	document.getElementById("tabaux"+cont).value = "";

}

function qtdCriancas(a1,a2,id,vlr){
	valor1 = parseInt(document.getElementById(a1+"quarto_nome"+a2).value);
	//alert(valor1+"-"+vlr)
	qtd_criancas = valor1-vlr;

	if(vlr != "0" ){
		
		str = "Crianças de 0 a "+document.getElementById("hotel_cod"+id).value+" anos: <select name='"+a1+"qtd_criancas"+a2+"'>";
		for(i=0;i<=10;i++){
			str += "<option value='"+i+"'>"+i+"</option>";
		}
		str += "</select> ";
		document.getElementById(a1+"id_criancas"+a2).innerHTML = str; 
	}else{
	document.getElementById(a1+"id_criancas"+a2).innerHTML = "Crianças de 0 a "+document.getElementById("hotel_cod"+id).value+" anos: <select disabled='disabled'><option>0</option></select> "; 
	}
}


		
function qtdAdultos(a1,a2,id){
	if(document.getElementById(a1+"quarto_nome"+a2).value != "0"){
		str = "Quantidade de adultos: <select onchange='qtdCriancas("+a1+","+a2+","+id+",this.value)' name='"+a1+"qtd_adultos"+a2+"' id='"+a1+"qtd_adultos"+a2+"'>";
		for(i=0;i<=parseInt(document.getElementById(a1+"quarto_nome"+a2).value);i++){
			str += "<option value='"+i+"'>"+i+"</option>";
		}
		str += "</select> ";
		document.getElementById(a1+"id_adultos"+a2).innerHTML = str; 
	}else{
		document.getElementById(a1+"id_adultos"+a2).innerHTML = "Quantidade de adultos: <select disabled='disabled'><option>0</option></select> "; 
		document.getElementById(a1+"id_criancas"+a2).innerHTML = "Crianças de 0 a "+document.getElementById("hotel_cod"+id).value+" anos: <select disabled='disabled'><option>0</option></select> "; 
	}
}
function qtdAdultos2(valor, idN, idO){
	if(valor != 0){
		document.getElementById(idN).style.display="";
		document.getElementById(idO).style.display="none";
	}else{
		document.getElementById(idN).style.display="none";
		document.getElementById(idO).style.display="";
	}
}

function qtdCriancas2(valor, idN, idO){
	if(valor > 0){
		document.getElementById(idN).style.display="";
		document.getElementById(idO).style.display="none";
	}else{
		document.getElementById(idN).style.display="none";
		document.getElementById(idO).style.display="";
	}
}
function det_categ(id){
	if (document.getElementById(id).disabled==true){
		alert("ok")
	}
	
	if(document.getElementById(id).style.display=="none"){
		document.getElementById(id).style.display="";
		document.getElementById("auxi3").value += id+",";
	}else{
		novo_value = "";
		document.getElementById(id).style.display="none"
		vet = document.getElementById("auxi3").value.split(",");
		for(i=0;i<vet.length;i++){
			if(vet[i] != id){
				novo_value += vet[i]
			}
		}
	
		document.getElementById("auxi3").value = novo_value;
	}
}

function detQuartos(len,id,id2,categHotel){
	num_quarto = "";
	str = "";
	document.getElementById("quartos_det"+id2).innerHTML = "";
	
	document.getElementById("quartos_det"+id2).style.display="";
	num = document.getElementById("num_quartos"+id2).value;
	
	aux = 5;
	for (p=1;p<=num;p++){
		
		if (p==aux){
			str += "<br>";
			aux += 4;
		}
		if (p<10){
		num_quarto = "0"+p;
		}
		str += "Quarto "+num_quarto+": <select onchange='qtdAdultos("+id2+","+p+","+id+")' name='"+id2+"quarto_nome"+p+"' id='"+id2+"quarto_nome"+p+"'>"
		str += "<option value='0'>Selecione</option>"
		for (i=0;i<=len;i++){
			quartos = document.getElementById("qt"+i+categHotel).value;
			quartos = quartos.split("|");
			str += "<option value='"+quartos[1]+"|"+quartos[2]+"'>"+quartos[0]+"</option>";
		}
		//alert("ok")
		str += "</select> ";
		str += "<span  id='"+id2+"id_adultos"+p+"'>";
		str += "Quantidade de adultos: <select disabled='disabled' name='"+id2+"qtd_adultos"+p+"'>";
		for(i=0;i<=5;i++){
			str += "<option>"+i+"</option>";
		}
		str += "</select> ";
		str += "</span> <span  id='"+id2+"id_criancas"+p+"'>";
		str += "Crianças de 0 a "+document.getElementById("hotel_cod"+id).value+" anos: <select disabled='disabled' name='"+id2+"qtd_criancas"+p+"'>";
		for(i=0;i<=5;i++){
			str += "<option>"+i+"</option>";
		}
		str += "</select></span> <br><input type='hidden' name='id_1' value='"+id2+"' /><input type='hidden' name='id_2' value='"+p+"' />";
	}
	document.getElementById("quartos_det"+id2).innerHTML = str;
}
function detQuartos2(id, total){
	for(i=1;i<=5;i++){
		document.getElementById(id+i).style.display="none";
		document.getElementById("qtd_adulto_"+i).style.display="none";
	}
	
	for(i=1;i<=total;i++){
		document.getElementById(id+i).style.display="";
		document.getElementById("qtd_adulto_"+i).style.display="";
	}
}

function insNumeric(obj,event)
{
	if(obj.id == "cep1")
	{
		maxLengh = 5
		if( $.browser.msie )
		{
			setTimeout(function(){
				if( obj.value.length == 5)
				{
					document.getElementById("cep2").focus();	
				}
			},300)
			
		}
		else
		{		
			if( obj.value.length == maxLengh)
			{
				document.getElementById("cep2").focus();	
			}
		}
	}
	
	var tecla = event.charCode;
    var ie = event.keyCode;
    if (!event) event = window.event;
    var code;
    if (event.keyCode) code = event.keyCode;
    else if (event.which) code = event.which; // Netscape 4.?
//se nao for número nem parentesis ou espaço
	if( code==13 )
	{
		event.returnValue = true;
		return true;	
	}
	else
	{
		if ((code < 48 || code > 59) && (code != 8 ) ){
		  event.returnValue = false;
		  if (event.which){
			event.preventDefault();
		  }
		  return false;
		}else{
		  event.returnValue = true;
		  return true;
		}
	}    
}
function insFloat(obj,event)
{
    var tecla = event.charCode;
    var ie = event.keyCode;
    if (!event) event = window.event;
    var code;
    if (event.keyCode) code = event.keyCode;
    else if (event.which) code = event.which; // Netscape 4.?
//se nao for número nem parentesis ou espaço
    if ((code < 48 || code > 59) && (code != 8 ) & (code != 44)){
      event.returnValue = false;
      if (event.which){
        event.preventDefault();
      }
      return false;
    }else{
      event.returnValue = true;
      return true;
    }
 } 

function isFloat(valor)
{
	var valor_text = valor;
	var str = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
	return str.test(valor_text);
}
