// 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 + "?tipo=" + tipo)
	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 preecheInput(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);
			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()",600);	
}
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(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 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)
	valor_aux = obj.value;
	if( valor_aux != "")
	{
		if(isFloat(valor_aux) == true)
		{
			pos = valor_aux.search(",");
			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];
						document.getElementById(id).value = valor;
					}
					else
					{
						if (vet_valor[1].length > 2)
						{
							vet_valor[1] = vet_valor[1].substring(0,2);	
							valor = formataFloatPonto(valor) + "," + vet_valor[1]
							document.getElementById(id).value = valor;
						}
						else
						{
							valor = formataFloatPonto(valor) + "," + vet_valor[1] + "0"	
							document.getElementById(id).value = valor;
						}
					}
				}
				else
				{
					valor = formataFloatPonto(valor) + ",00"; 
					document.getElementById(id).value = 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(".","")
				obj = document.getElementById(id);
				obj.value = formataFloatPonto(valor_aux) + ",00"
				
			}
		}
	}
	
}
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 = 5
		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);
}

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)
{
	if (confirm("Deseja realmente excluir o registro"))
	{
		location.href=url;	
	}
}
function fechar()
{
	close();
}
function salvar(id)
{
	document.getElementById(id).submit();	
}

function abrirMenu(wcontrole)
{
	$("#"+wcontrole).slideToggle("normal")
}

function abrirMenuSite(wcontrole){
	$("#"+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()
	
}



function iniciar()
{
	
	obj = $(".labelDet")
	
	for(i=0;i<obj.length;i++)
	{
		
		$("#"+obj[i].id).click(function () { 
			
			
			if( $("#"+$(this).attr("id").replace("mostraAjuda","ajuda")).is(":hidden"))
			{
				$("#"+$(this).attr("id").replace("mostraAjuda","ajuda")).show("normal");
			}
			else
			{
				$("#"+$(this).attr("id").replace("mostraAjuda","ajuda")).hide("normal");	 
			}
			
			
		});
		
		$("#"+obj[i].id.replace("mostraAjuda","fechar")).click(function () { 
			$("#"+$(this).attr("id").replace("fechar","ajuda")).hide("normal");
		})
		
	}	
}

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])
						objSelect = document.getElementById("estado")
						for(i=1;i<objSelect.options.length;i++)
						{
							if(objSelect.options[i].value == vetRet[3])
							{
								objSelect.options[i].selected =  true
								break
							}
						}
						
					}
				}else{
					//alert(ajax.statusText);
				}
			}
		}
		ajax.send(null);
	}	
	
}
function buscaCepVale()
{
	wcep = $("#vale_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("|")	
						$("#vale_endereco").val(vetRet[0])
						$("#vale_bairro").val(vetRet[1])
						$("#vale_cidade").val(vetRet[2])
						objSelect = document.getElementById("vale_estado")
						for(i=1;i<objSelect.options.length;i++)
						{
							if(objSelect.options[i].value == vetRet[3])
							{
								objSelect.options[i].selected =  true
								break
							}
						}
						
					}
				}else{
					//alert(ajax.statusText);
				}
			}
		}
		ajax.send(null);
	}	
	
}
function janelaExterna(url)
{
	var largura = window.width 
	var altura =  window.height
	
	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 wleft = parseInt( ( parseInt(xScroll)-1100 ) /2 )
	largura = parseInt(xScroll)-1000
	altura = yScroll
	//alert(xScroll + " - " + yScroll)
	var winDt = window.open(url,'','left='+ wleft +',width=1050,height='+ altura +',scrollbars=1,status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1');
	winDt.focus();
}

function carregaUrlExterna(){
	$(".novaJanela").click(function(){
		wurl = $(this).attr("href")
		janelaExterna(wurl)
		return false
	})
}

function produtosPagina(){
	var wurl		= $("#destino_pag").val() + "&regPag="+ $("#num_itens").val()
	location.href	= wurl
}

function selecionaFrete(tipo, valor_frete, valor_total){
	var valFrete		= valor_frete.replace(/\,/, '.')
	
	var prodDescProd	= $('[data-somaproduto]').data('somaproduto').split('|');
	var prodPreco		= prodDescProd[0].replace(',', '.');
	var prodDesc		= prodDescProd[1].replace(',', '.');
	//var prodPreco		= $('[data-somaproduto]').data('somaproduto').replace(',', '.');
	var precoProdDesc	= Number(prodPreco) * 0.9;
	
	var valor_mostragem	= ( Number(precoProdDesc) + Number(valFrete) ) - Number(prodDesc);
	
	valor_mostragem		= new String(valor_mostragem);
	valor				= new Array();
	valor[0]			= valor_mostragem.split('.');
	valor[1]			= valor[0][0];
	valor[2]			= valor[0][1];
	valor[3]			= valor[2].substring(0, 2);
	valor[4]			= valor[1]+','+valor[3];
	
	valor_mostragem		= valor[4];
	
	
	document.getElementById('totalmostra').value	= 'R$ '+(valor_mostragem);
	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()		
			}
		}
	}
	
	objFotos = $("a[rel='imgZoom']")
	for(i=0;i<objFotos.length;i++)
	{
		vetImg[i] = new Image();
		vetImg[i].src = objFotos[i].href
	}
	
	$('.imgZoom2').live('click',function(){
	//	zoomProduto2($(this).attr('name'))								 
	})
}

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
		
	}*/
}
var quantidadeProd = 0;
function selecionaCorTamanho(tipo,codigo,codProduto)
{
	
	$("#iconMensagem2").hide()
	$("#cesta_login2").slideUp("norma",function(){
			if( tipo=="C" )
			{
				var cod_tam = ""
				obj = $("#limpaSelecao")
				if( obj.length > 0 )
				{
					obj[0].checked = false	
				}
				if( $("input[name='tamanho']:checked").length > 0)
				{
					cod_tam = 	$("input[name='tamanho']:checked").val()
				}
				
				$("#tamanhos").html("<li><p>Aguarde...</p></li>")		
				$("#tamanhos").load("carrrega_cor_tamanho.asp?tipo="+tipo+"&cod_produto="+codProduto+"&codigo="+codigo+"&cod_tamanho="+cod_tam,function(){
					
					if( cod_tam > 0 )
					{
						
						$("#verificaQtd").load("carrrega_cor_tamanho.asp?tipo=E&cod_produto=" + codProduto + "&cod_cor="+ codigo + "&cod_tamanho="+cod_tam+"&codigo=1",function(){
							if( parseInt($("#verificaQtd").text()) <=0)
							{
								$("#iconMensagem strong").text( $("input[name='cor']:checked").attr("alt") + " " + $("input[name='tamanho']:checked").attr("alt") + " não disponível no momento.")
								$("#iconMensagem").slideDown("normal",function(){
									$("#cesta_login1").slideDown("normal",function(){
										$("#mensagemAviso").hide("normal",function(){
											$("#mensagemAviso").remove()
										})											   
									})
									$("#btnEnviaCesta").hide("normal")
								})
								
							}
							else
							{
								$("#btnEnviaCesta").show("normal",function(){
									$("#iconMensagem").slideUp("normal")
									$("#cesta_login1").slideUp("normal",function(){
										$("#mensagemAviso").slideUp("normal",function(){
											$("#mensagemAviso").remove()
										})											   
									})
								})						
								
							}
						})	
						
					}
					
				})
				
			}
			else
			{
				if( tipo=="T" )
				{
					var cod_cor = ""
					obj = $("#limpaSelecao")
					if( obj.length > 0 )
					{
						obj[0].checked = false	
					}
					if( $("input[name='cor']:checked").length > 0)
					{
						cod_cor = 	$("input[name='cor']:checked").val()
					}
					
					$("#cores").html("<li><p>Aguarde...</p></li>")
					$("#cores").load("carrrega_cor_tamanho.asp?tipo="+tipo+"&cod_produto="+codProduto+"&codigo="+codigo+"&cod_cor="+cod_cor,function(){
						if( cod_cor > 0 )
						{
							
							$("#verificaQtd").load("carrrega_cor_tamanho.asp?tipo=E&cod_produto=" + codProduto + "&cod_cor="+ cod_cor + "&cod_tamanho="+codigo+"&codigo=1",function(){
								if( parseInt($("#verificaQtd").text()) <=0)
								{
									$("#iconMensagem strong").text( $("input[name='cor']:checked").attr("alt") + " " + $("input[name='tamanho']:checked").attr("alt") + " não disponível no momento.")
									$("#iconMensagem").slideDown("normal",function(){
										$("#cesta_login1").slideDown("normal",function(){
											$("#mensagemAviso").hide("normal",function(){
												$("#mensagemAviso").remove()
											})											   
										})
										$("#btnEnviaCesta").hide("normal")
										
									})	
									
								}
								else
								{
									$("#btnEnviaCesta").show("normal",function(){
										$("#iconMensagem").slideUp("normal")
										$("#cesta_login1").slideUp("normal",function(){
											$("#mensagemAviso").slideUp("normal",function(){
												$("#mensagemAviso").remove()
											})											   
										})
									})
								}
							})	
							
						}
					
					})	
				}
				else
				{
					$("#tamanhos").html("<li><p>Aguarde...</p></li>")	
					$("#cores").html("<li><p>Aguarde...</p></li>")
					var wurl = "carrrega_cor_tamanho.asp?tipo=" + tipo + "&tipo_sec=T&cod_produto=" + codProduto + "&codigo="+ codProduto
					
					$("#cores").load(wurl,function(){
						wurl = "carrrega_cor_tamanho.asp?tipo="+tipo+"&tipo_sec=C&cod_produto="+codProduto+"&codigo="+codProduto
						$("#tamanhos").load(wurl)
					})
					$("#btnEnviaCesta").show("normal",function(){
						$("#iconMensagem").slideUp("normal")
						$("#cesta_login1").slideUp("normal",function(){
							$("#mensagemAviso").slideUp("normal",function(){
								$("#mensagemAviso").remove()
								$("#btnEnviaCesta").show("normal")
							})											 
						})
					})
					
					
					
				}
			}
	})
}



function verifCheck(campo1, campo2){
	if(document.getElementById(campo1).checked == true){
		document.getElementById(campo2).style.display = "";
	}else{
		document.getElementById(campo2).style.display = "none";
	}
}

function selecaoEmbalagem(codProd,pos,e)
{
	
	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;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	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;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	$("body").css("position","relative")
	var str = "<div id='fundoEmbalagem'></div>"
	$(str).css("width",pageWidth).css("height",pageHeight).appendTo("body").show("slow");
		
	
	str = "</div><div id='embalagens'><img src='imagens/loading.gif'></div>"	
	$(str).css("top",(e.pageY-100)).css("left",(e.pageX-140)).appendTo("body").slideDown("slow");	
	setTimeout(function(){ $("#embalagens").load("carrega_embalagens.asp?codigo="+codProd+"&pos="+pos) },1300)
	
	$("#fundoEmbalagem").click( function(){ $("#fundoEmbalagem").remove(); $("#embalagens").remove() } )
}
function iniciaFunctionClick()
{
	$(".clickEmb").click(function(e){
		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;
		
	//	console.log(self.innerWidth);
	//	console.log(document.documentElement.clientWidth);
	
		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;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
	//	console.log("xScroll " + xScroll)
	//	console.log("windowWidth " + windowWidth)
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		
		
		vetId = $(this).attr("id").split("_")
		wtipo = vetId[3]
				
		$("body").css("position","relative")
		var str = "<div id='fundoEmbalagem'></div>"
		$(str).css("width",pageWidth).css("height",pageHeight).appendTo("body");
		
		var idElementReferencia = $(this).attr("id")
		idElementReferencia = idElementReferencia.replace("_C","")
		idElementReferencia = idElementReferencia.replace("_E","")
		idElementReferencia = idElementReferencia.replace("_P","")
		
		str = "<div id='embalagens'><img src='imagens/loading.gif'></div>"	
		$(str).css("top",$("#"+idElementReferencia).position().top).css("left",(parseInt($("#"+idElementReferencia).position().left)+250)).appendTo("body").show();	
		
		$("#embalagens").load("carrega_opcoes_prod.asp?codigo="+vetId[1]+"&pos="+vetId[2]+"&tipo="+wtipo,function(){
			if( wtipo != "E")
			{
				$("#embalagens").css("width",380)	
			}
			$("#embalagens").slideDown("slow")																										  
		})
		
		$("#fundoEmbalagem").click( function(){ $("#fundoEmbalagem").remove(); $("#embalagens").remove() } )
	
	})	
	
	$(".titCliqueOpA,.titCliqueOpF").click(function(){
		var idElement = $(this).attr("id")
		idElement = idElement.replace("tit_","div_")
		if( $("#"+ idElement).is(":hidden") )
		{
			$("#"+ idElement).slideDown("normal")
			$(this).removeClass("titCliqueOpF")
			$(this).addClass("titCliqueOpA")
		}
		else
		{
			$("#"+ idElement).slideUp("normal")	
			$(this).removeClass("titCliqueOpA")
			$(this).addClass("titCliqueOpF")
		}
	})
}
function fecharDivEmbalagens()
{
	$("#fundoEmbalagem").remove(); 
	$("#embalagens").remove()
}
var contEnd = 0;
function selectTipoVale(pos)
{
	var idRadio = "vale_" + pos + "_tipo_2"
	var idDiv = "vale_end"
	if( $("#"+idRadio).is(':checked') == true )	
	{
		contEnd = parseInt(contEnd) + 1
		$("#"+idDiv).show("slow")
		$("#vale_"+ pos +"_email").removeClass("obrigatorio")
		$("#vale_endereco").addClass("obrigatorio")
		$("#vale_numero").addClass("obrigatorio")
		$("#vale_bairro").addClass("obrigatorio")
		$("#vale_cep").addClass("obrigatorio")
		$("#vale_cidade").addClass("obrigatorio")
		$("#vale_estado").addClass("obrigatorio")
	}
	else
	{
		contEnd = parseInt(contEnd) - 1
		if( contEnd <= 0 )
		{	
			if( contEnd < 0)
			{
				contEnd = 0;	
			}
			$("#"+idDiv).hide("slow")
			$("#vale_"+ pos +"_email").addClass("obrigatorio")
			$("#vale_endereco").removeClass("obrigatorio")
			$("#vale_numero").removeClass("obrigatorio")
			$("#vale_bairro").removeClass("obrigatorio")
			$("#vale_cep").removeClass("obrigatorio")
			$("#vale_cidade").removeClass("obrigatorio")
			$("#vale_estado").removeClass("obrigatorio")
		}
	}
}
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();
	

}
var altMax = 0
objClique = new Object()
var ultimoClique = ""
function zoomProduto(objImgZoom)
{
	
	dimensoes = verDimensoes()
	vetD = dimensoes.split("x")
	larguraTela = vetD[0]
	alturaTela = vetD[1]
	
	if( $(".fundoOpaco").length ==0)
	{
		$("<div id='fundoZoom' class='fundoOpaco'></div>").appendTo("body").hide()
		objF = document.getElementById("fundoZoom")
		objF.style.width = larguraTela + "px"
		objF.style.height = (alturaTela) + "px"
		$("#fundoZoom").show()
	}
	
	$("#fundoZoom").click(function(){
		$("#caixaZoom").remove()
		$("#img_carregando").remove()
		$("#fundoZoom").remove()		
	})
	
	if (document.all)
	{
		var wtop = parseInt(document.documentElement.scrollTop) + 30
		
	}
	else
	{
		var wtop = parseInt(window.scrollY) + 30	
	}
	var wleft = parseInt(larguraTela) / 2
	wleft = parseInt(wleft)
	
	$("<img src='imagens/loading.gif' id='img_carregando'>").css('top',wtop+100).css('left',wleft).appendTo("body").show()
	
	$("#caixaZoom").remove()
	nameElement = objImgZoom.name	
	vetId = nameElement.split("|")
	str = "<div id='caixaZoom'><img src='imagens/closelabel.gif' id='btn_fecharZoom'>"	
	if( vetId[2] == "conserto_imagens" ) 
	{
		if( vetId[3] == "A")
		{
			str += "<h4 id='tituloImgZoom'>Antes</h4>"	
		}
		else
		{
			str += "<h4 id='tituloImgZoom'>Depois</h4>"		
		}
	}
	else
	{
		str += "<h4 id='tituloImgZoom'>"+ $("h1").text() +"</h4>"
	}
	
	str += "<div id='zoomImgPrincipal'></div>"
	str += "<div id='zoomMiniaturas'></div>"	
	str +="</div>"
	
	$(str).appendTo("body").hide()
		
	vetImg = objImgZoom.src.split("/")
	
	$("#zoomMiniaturas").load("carrega_miniaturas.asp?codigo="+ vetId[1]+"&img="+vetImg[vetImg.length-1]+"&table="+vetId[2]+"&tipo="+vetId[3],function(){
		strImg = ""
		medidasImg = $("#medidas_img").val()
		vetMedidasImg = medidasImg.split("|")
		
		for(i=0;i<$("#zoomMiniaturas img").length;i++)
		{
			caminho = $("#zoomMiniaturas img:eq(" + i + ")").attr("src")
			vetMedidaImg = vetMedidasImg[i].split("x")
			if( vetId[2] == "conserto_imagens" )
			{
				strImg += "<img src='"+ caminho.replace("mini/","") +"' id='img_max_" + i + "' width='" + vetMedidaImg[0] + "' height='" + vetMedidaImg[1] + "'>"	
			}
			else
			{
				strImg += "<img src='"+ caminho.replace("produto_mini","produto_grande") +"' id='img_max_" + i + "' width='" + vetMedidaImg[0] + "' height='" + vetMedidaImg[1] + "'>"	
			}
			if( $("#zoomMiniaturas img").length > 1 )
			{
				$("#zoomMiniaturas img:eq(" + i + ")").click(function(){
					idAnterior = $("#zoomImgPrincipal img:visible").attr("id")
						idAnteriorMini = idAnterior.replace("img_max_","img_mini_")
						
						idProxima = $(this).attr("id")
						idProximaMini = idProxima 
						idProxima = idProxima.replace("img_mini_","img_max_")
						if( idProxima != idAnterior)
						{
							
							var imgProxima = new Image();
							imgProxima.src = $("#"+idProxima).attr("src")
													
							$("#"+idAnterior).animate( {'opacity':'hide'},'slow');					
							$("#"+idProxima).animate( {'opacity':'show'},'slow')
							
							$("#"+idAnteriorMini).removeClass("mini_bordaAzul")
							$("#"+idAnteriorMini).addClass("mini_bordaCinza")
							
							$("#"+idProximaMini).removeClass("mini_bordaCinza")
							$("#"+idProximaMini).addClass("mini_bordaAzul")
							
						}													  
																	  
				})
			}
		}
		$("#zoomImgPrincipal").append(strImg)
		setTimeout(function(){
			larguraImg = 400
			alturaImg = 0
			vetMedidaImg = new Array()
			for(i=0;i<$("#zoomImgPrincipal img").length;i++)
			{
				vetMedidaImg = vetMedidasImg[i].split("x")
				if( parseInt(vetMedidaImg[0]) > 400 && parseInt(larguraTela) <= 1000)	
				{
					$("#zoomImgPrincipal img:eq(" + i + ")").attr("width",400)
					porc = ( vetMedidaImg[1] * 100 ) / vetMedidaImg[0]
					alturaImgProporcional = (porc*400)/100
					$("#zoomImgPrincipal img:eq(" + i + ")").attr("height",parseInt(alturaImgProporcional))
					vetMedidaImg[0] = 400
					vetMedidaImg[1] = alturaImgProporcional 
				}
				if( parseInt(vetMedidaImg[0]) > larguraImg )
				{
					larguraImg	= vetMedidaImg[0]
				}
				
				if( parseInt(vetMedidaImg[1]) > alturaImg )
				{
					
					alturaImg	= vetMedidaImg[1]
				}
				if( vetId[2] == "conserto_imagens" )
				{
					wcaminho = 	objImgZoom.src.replace("mini/","")
				}
				else
				{
					wcaminho = 	objImgZoom.src.replace("produto_normal","produto_grande")	
				}
				
				if( $("#zoomImgPrincipal img:eq(" + i + ")").attr("src") == wcaminho )
				{
					$("#zoomImgPrincipal img:eq(" + i + ")").show()						
				}
				else
				{
					$("#zoomImgPrincipal img:eq(" + i + ")").hide()	
				}
			}
			
			for(i=0;i<$("#zoomImgPrincipal img").length;i++)
			{
				vetMedidaImg = vetMedidasImg[i].split("x")
				
				if( parseInt(vetMedidaImg[0]) > 400 && parseInt(larguraTela) <= 1000)	
				{
					wleft = (parseInt(larguraImg) - 400) / 2				
				}
				else
				{
					
					wleft = ( parseInt(larguraImg) - parseInt(vetMedidaImg[0]) ) / 2
				
				}
				wleft = parseInt(wleft)
				$("#zoomImgPrincipal img:eq(" + i + ")").css("left",wleft)
				strLeft = new String(wleft)
			}
			
			alturaCaixa = alturaImg			
			
			if( $("#zoomMiniaturas img").length > 1 )
			{
				larguraCaixa = parseInt(larguraImg)+110	
				alturaMiniatura = parseInt($("#zoomMiniaturas img").length) * 90				
				if( alturaImg < alturaMiniatura )
				{
					alturaCaixa	= alturaMiniatura
				}
			}
			else
			{
				larguraCaixa = larguraImg
				$("#zoomMiniaturas").remove()
			}
			
						
			
			alturaCaixa = parseInt(alturaCaixa) + 50
			wleft = ( parseInt(larguraTela) - larguraCaixa ) / 2
			wleft = parseInt(wleft)
			
			objCaixa = document.getElementById("caixaZoom")
			$("#zoomImgPrincipal").width(larguraImg)
			$("#zoomImgPrincipal").height(alturaImg)
			objCaixa.style.width = larguraCaixa + "px"
			objCaixa.style.height = alturaCaixa + "px"
			$("#caixaZoom").css("left",wleft).css("top",wtop)
			
			
			$("#img_carregando").remove()
			$("#caixaZoom").show("normal")
			
			wleft = parseInt(larguraCaixa) - 58
			$("#btn_fecharZoom").css('left',wleft).show()
			$("#btn_fecharZoom").click(function(){ $("#fundoZoom").click() })
			
		},1000)																
		
	})
	
	
	
	
	
	
}

function detalharSolicitacoes(codigo)
{
	
	
	$("#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("carrega_solicitacoes_prod.asp?codigo="+codigo)
		$("#bntFecharVariacao").click(function(){
			$("#bntFecharVariacao").remove()
			$("#caixaVariacoes").hide("normal",function(){
				
				$("#caixaVariacoes").remove()
			})
			
		})	
	}
}

function verDimensoes()
{
	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;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	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;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	dimensoes = pageWidth + "x" + pageHeight
	return dimensoes
} 
function finalizaSomaFrete(obj)
{
	selecao = $(obj).val()
	vetSelecao = selecao.split("_")	
	$("#textFormaPag").text(" ")
	frete = $("#valor_frete").val()
	if( vetSelecao[0] != "deposito" && vetSelecao[0] != "boleto")
	{
		
		valor = $("#"+ vetSelecao[0] +"total_"+ vetSelecao[1]).val()
				
	}
	else
	{
		if( vetSelecao[0] == "deposito" )
		{
			valor = $("#total_deposito").val()	
		}
		else
		{
			valor = $("#total_boleto").val()
		}
		
	}
	$("#textSubTotal").text("R$ "+valor)
	valor = valor.replace(",",".")		
	frete = frete.replace(",",".")
	valor = (parseFloat(valor) + parseFloat(frete)).toFixed(2)
	strValor = new String(valor)	
	strValor = strValor.replace(".",",")
	vetValor = strValor.split(",")
	if( vetValor.length > 0 )
	{
		if( vetValor[1].length ==1 )
		{
			strValor = vetValor[0] + "," + vetValor[1] + "0"		
		}
	}
	$("#textTotal").text("R$ "+strValor)

}
var exibir = false
function inicializaMenu()
{
/*	$(".menu ul li").mouseover(function(){ 
		exibir = true
		$("#subMenuOculto").remove()
		htmlMenu = $(this).find("ul").html()				
		$("<div id='subMenuOculto' style='top:"+ $(this).position().top +"px;'><ul class='menu' style='display:block;background:#f0f0f0;'>"+ htmlMenu +"</ul></div>").appendTo("body")
		$("#subMenuOculto li").show()				
		$("#subMenuOculto").mouseover(function(){ exibir = true; }).mouseout(function(){ 
			exibir = false;
			setTimeout(function(){
				if( exibir == false )
				{
					$("#subMenuOculto").remove()	
				}
			},300)
			
		});
		
		
	} ).mouseout(function(){ 
		exibir = false
		setTimeout(function(){
			if( exibir == false )
			{
				$("#subMenuOculto").remove()	
			}
		},300)
				
	})
	$(".submenu li").hide()	
*/
}

function mostraTeste()
{
var texto, tabela, titulo;
texto = document.getElementById("texto").value;
tabela = document.getElementById("tabela").value;
titulo = document.getElementById("titulo").value;
//alert("Texto: " + texto + "Tabela: " + tabela)
//window.location="http://www.casadascanetas.com.br/site/visualiza_det.asp?tabela="+tabela+"&titulo="+titulo+"&texto="+texto+""
wurl = "http://www.casadascanetas.com.br/visualiza_det.asp?tabela="+tabela+"&titulo="+titulo+"&texto="+texto+""
window.open(wurl,'','top=100,left=100,width=800,height=500,scrollbars=1,status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0');
}

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";
		document.getElementById("nome_contato").className = "obrigatorio";
		document.getElementById("data_const").className = "obrigatorio";
	}else{
		wdiv.style.display = 'none';
		document.getElementById("cnpj").className = "";
		document.getElementById("razao").className = "";
		document.getElementById("nome_contato").className = "";
		document.getElementById("data_const").className = "";
	}
	if(wdive == 'F'){
		wdiv2.style.display = 'block';
		document.getElementById("cpf").className = "obrigatorio";
		document.getElementById("data_nasc").className = "obrigatorio";
	}else{
		wdiv2.style.display = 'none';
		document.getElementById("cpf").className = "";
		document.getElementById("data_nasc").className = "";
	}
}

function mudaCateg(interesse, divId){
	wint = interesse;
	wdiv = document.getElementById(divId);
	if(wint == 5){
		wdiv.style.display = 'block';
		document.getElementById("outro_interesse").className = "obrigatorio";
	}else{
		wdiv.style.display = 'none';
		document.getElementById("outro_interesse").className = "";
	}
}

function funcoesClickFrete()
{
	$("#frete_gratis").click(function(){		
		if( $(this).is(":checked") )
		{
			$("input[name='regiao_frete']").attr("checked","checked")
		}
		else
		{
			$("input[name='regiao_frete']").attr("checked",false)	
		}
	})
	$("input[name='regiao_frete']").click(function(){
		if( $("input[name='regiao_frete']:checked").length == $("input[name='regiao_frete']").length  )
		{
			$("#frete_gratis").attr("checked","checked")
		}
		else
		{
			$("#frete_gratis").attr("checked",false)	
		}
	})
	if( $("input[name='regiao_frete']:checked").length == $("input[name='regiao_frete']").length  )
	{
		$("#frete_gratis").attr("checked","checked")
	}
	
	$("#linkRecalc").click(function(){
		if( $("input[name=tipo_frete]:checked").length > 0 )
		{
			
			location.href = $(this).attr("href") + "&tipo_frete="  + $("input[name=tipo_frete]:checked").val()
			return false
		}
		else
		{
			objFocus = $("input[name=tipo_frete]:eq(0)")
			alert("Selecione o tipo de envio")	
		}
		return false
	})
	
}
function recalculaFrete(url,tipo)
{
	wurl = url + "&tipo_frete=" + tipo;
	location.href = wurl;
}

var verificaClick = 0
function iniciaClickProduto()
{
	$("#cores label").click(function(){
		
		corVerif = new String($(this).attr("id").split("_")[1])
		$("#cor").val( $(this).find("input").val() )
		$("#corAvisoEstoque").val( $(this).find("input").val() )
		for(i=0;i<$("#tamanhos label").length;i++)
		{
			strAux = new String($("#tamanhos label:eq("+ i +")").attr("id").split("_")[1])
			
			if(	strAux.indexOf(corVerif) >= 0 )
			{
				$("#tamanhos label:eq("+ i +")").css("color","#606060").css("cursor","pointer")
				$("#tamanhos label:eq("+ i +")").find("input").attr("disabled",false)
			}
			else
			{
				$("#tamanhos label:eq("+ i +")").css("color","#AFAFAF").css("cursor","default")
				$("#tamanhos label:eq("+ i +")").find("input").attr("disabled","disabled")
				if( $("#tamanhos label:eq("+ i +")").find("input").is(":checked") )
				{
					$("#tamanhos label:eq("+ i +")").find("input").attr("checked",false)
					$("#tamanho").val("")
					$("#tamanhoAvisoEstoque").val("0")
				}
			}
		}
		if( $("#tamanhos input:checked").attr("disabled") == true )
		{
			$("#tamanhos input:checked").attr("checked",false)
		}
		if( $("#tamanhos input:checked").length == 0 )
		{
		}
		else
		{
			$("#tamanhos input:checked").parents("label").click()
		}
		
		if( verificaClick ==1 )
		{
			verificaClick = parseInt(verificaClick) + 1	
		}
		else
		{
			$("#div_alertaEstoque").remove()	
		}
		if( $("#tamanhos label").length ==0 )
		{
			$("#qtdDisponivel").val( ($(this).attr("id").split("_")[2]) )
			verQtdDisponivel()
		}
		
	})
	$("#tamanhos label").click(function(){
		$("#tamanho").val( $(this).find("input").val() )
		$("#tamanhoAvisoEstoque").val( $(this).find("input").val() )
		corVerif = new String( $("#cores input:checked").val() )
		
		if( $(this).attr("id").split("_")[1].split("-").length > 1 )		
		{
			for(i=0;i< $(this).attr("id").split("_")[1].split("-").length;i++)
			{
				if( parseInt(corVerif) == parseInt($(this).attr("id").split("_")[1].split("-")[i]) )
				{
					quantidade = $(this).attr("id").split("_")[2].split("-")[i]					
					break
				}
			}
		}
		else
		{
			quantidade = $(this).attr("id").split("_")[2]
		}
		
		$("#qtdDisponivel").val(quantidade)
		verQtdDisponivel()		
		if( verificaClick == 0 )
		{
			verificaClick += 1
			
		}
		else
		{
			$("#div_alertaEstoque").remove()	
		}
		
	})
	
	if( $("#cores input:checked").length ==0 )
	{
	}
	else
	{
		corVerif = new String($("#cores input:checked").parent().attr("id").split("_")[1])		
		for(i=0;i<$("#tamanhos label").length;i++)
		{
			strAux = new String($("#tamanhos label:eq("+ i +")").attr("id").split("_")[1])
			
			if(	strAux.indexOf(corVerif) >= 0 )
			{
				$("#tamanhos label:eq("+ i +")").css("color","#606060").css("cursor","pointer")
				$("#tamanhos label:eq("+ i +")").find("input").attr("disabled",false)
			}
			else
			{
				$("#tamanhos label:eq("+ i +")").css("color","#AFAFAF").css("cursor","default")
				$("#tamanhos label:eq("+ i +")").find("input").attr("disabled","disabled")
			}
		}
	}
	
}
function verQtdDisponivel()
{
	if( parseInt( $("#qtdDisponivel").val() ) <= 0 || ( parseInt($("#quantidade").val()) > parseInt( $("#qtdDisponivel").val() )  ))
	{
		if( $("#quantidade").val() != "" )
		{
			$("#quantidadeAvise2").val($("#quantidade").val())
			$("#quantidadeAvisoEstoque").val($("#quantidade").val())
			$("#quantidade").val($("#qtdDisponivel").val())
		}
		$("#mensagemEstoque").show("normal")											
	}
	else
	{
		$("#mensagemEstoque").hide("normal")
	}
}
