// REDIMENSIONA AS IMAGENS CASO SEJAM MAIORES QUE A LARGURA PERMITIDA DO SITE
// ----------------------------------------------------------------------------
window.onload = function() {
	RedimensionaImagens(350);
}

function RedimensionaImagens(tamanhoimg) {
  var obj = document.getElementsByTagName("div");
  for(var i = 0;i<obj.length;i++) {
    if (obj[i].className == "imgstyle") {
      var img = obj[i].getElementsByTagName("img");
      if (img[0].width > tamanhoimg) { obj[i].innerHTML = '<img src="' + img[0].src + '" width="'+ tamanhoimg +'">' + '<br><a href="' + img[0].src + '" target="_blank">Veja a imagem no tamanho original</a>'; }
    }
  }
}


//===============================================================================
//= VERIFICA NAVEGADORES ========================================================
//===============================================================================
var ua = navigator.userAgent;
var ver = parseInt( navigator.appVersion );
var opera = /opera [56789]|opera\/[56789]/i.test(ua);
var ie = !opera && /MSIE/.test(ua);
var ie6 = ie && /MSIE [0123456]/.test(ua);
var ie7 = ie && /MSIE [789]/.test(ua);
var ieBox = ie && (document.compatMode == null || document.compatMode != "CSS1Compat");
var moz = !opera && /gecko/i.test(ua);
var nn6 = !opera && /netscape.*6\./i.test(ua);

//===============================================================================
//= VERIFICA PLUGINS NO IE ======================================================
//===============================================================================
var plugins = {
	hasAcrobat:function() {
		if (!window.ActiveXObject) return false;
		try { if (new ActiveXObject('AcroPDF.PDF')) return true;} 
		catch (e) {}
		try { if (new ActiveXObject('PDF.PdfCtrl')) return true;} 
		catch (e) {}
		return false;
	},
	hasFlash:function() {
		if (!window.ActiveXObject) return false;
		try {if (new ActiveXObject('ShockwaveFlash.ShockwaveFlash')) return true;} 
		catch (e) { return false;}
	},
	hasJava:function() {
		return (!navigator.javaEnabled());
	},
	hasQuickTime:function() {
		if (!window.ActiveXObject) return false;
		try { if (new ActiveXObject('QuickTime.QuickTime')) return true;} 
		catch (e) {}
		try {if(new ActiveXObject('QuickTimeCheckObject.QuickTimeCheck')) return true;} 
		catch (e) {};
		return false;        
	},			
	hasRealPlayer:function() {
		if (!window.ActiveXObject) return false;
		var definedControls = [
			'rmocx.RealPlayer G2 Control',
			'rmocx.RealPlayer G2 Control.1',
			'RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)',
			'RealVideo.RealVideo(tm) ActiveX Control (32-bit)',
			'RealPlayer'
		];
		for (var i = 0; i < definedControls.length; i++) {
			try {if(new ActiveXObject(definedControls[i])) return true;}
			catch (e) {continue;}
		}
		return false;  
	},			
	hasShockwave:function() {
		if (!window.ActiveXObject) return false;
		try {if(new ActiveXObject('SWCtl.SWCtl')) return true;} 
		catch (e) {return false;}
	},
	hasWMP:function() {
		if (!window.ActiveXObject) return false;
		try {if(new ActiveXObject('WMPlayer.OCX')) return true;} 
		catch (e) { return false;}
	}
}



// FUNÇÃO PARA EXIBIÇÃO DE FLASHS
// ----------------------------------------------------------------------------
function ExibeFlash(elm,movie,w,h,wmode,bg) {
	if ((navigator.mimeTypes && navigator.mimeTypes['application/x-shockwave-flash']) || (ie && plugins.hasFlash())){ 
		if(wmode == "transparent") { ftransp = true; wmode = "wmode='transparent'"; } else { ftransp = false; wmode = ""; };
	
		document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+w+'" height="'+h+'">');
		if(ftransp) { document.write('<param name="wmode" value="transparent"/>'); };
		document.write('<param name="quality" value="high"/>');
		document.write('<param name="movie" value="'+movie+'"/>');
		document.write('<embed src="'+movie+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" '+wmode+' width="'+w+'" height="'+h+'"></embed>');
		document.write('</object>');
	}
	else {
		document.getElementById(elm).style.display = '';
	}
	
}


//===============================================================================
//= ABRE POP-UP CENTRALIZADO ====================================================
//===============================================================================
var win = null;
function NewWindow(mypage,myname,w,h,scroll){
	LeftPosition = parseInt((screen.width) ? (screen.width-w)/2 : 0);
	TopPosition = parseInt((screen.height) ? (screen.height-h)/2 : 0);
	settings = 'width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',noresizable,status=yes'
	win = window.open(mypage,myname,settings)
}


//===============================================================================
//= REDIMENSIONA POP-UP =========================================================
//===============================================================================
function Redimensiona(w, h) {
	//Corrige o tamanho da janela
	if (navigator.appName == "Microsoft Internet Explorer") {
		w = parseInt(w) + 10;
		h = parseInt(h) + 48;
	} else {
		w = parseInt(w) + 6;
		h = parseInt(h) + 49;
	};
	// IE 7
	var nversao = navigator.userAgent;
	var nresult = nversao.search(/\bMSIE 7.0\b/g);
	if (nresult > 0) {
		h = parseInt(h) + 30;
	};
	//
	// FIREFOX 3
	var nversao = navigator.userAgent;
	var nresult = nversao.search(/\bFirefox\/3.0\b/g);
	if (nresult > 0) {
		h = parseInt(h) + 30;
	};
	//
	window.resizeTo(w, h);
	LeftPosition =  parseInt((screen.width) ? (screen.width-w)/2 : 0);
	TopPosition =  parseInt((screen.height) ? (screen.height-h)/2 : 0);
	window.moveTo(LeftPosition,TopPosition);
	window.focus();
}


// TRABALHA COM COOKIES
// ----------------------------------------------------------------------------
function getCookieVal(inicio) {
	var fim = document.cookie.indexOf(";", inicio);
	if (fim == -1) fim = document.cookie.length;
	return unescape(document.cookie.substring(inicio, fim));
}

function getCookie(label) {
	var arg = label + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i,j) == arg) return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function setCookie(label, valor, expires) {
	document.cookie = label + "=" + escape(valor) + 
		((expires) ? "; expires=" + expires.toGMTString() : "");
}

function delCookie(label) {
	if (getCookie(label)) {
		document.cookie = label + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}


// FUNÇÃO DE CONVERSÃO DE MAIUSCULAS/MINUSCULAS
// ----------------------------------------------------------------------------
function smallCaps(obj, type) {
		type = ((typeof type != "number") || (type > 3) || (type < 1)) ? 3 : type;
		var except = ['de','do','da','das','dos','em'];
		var tam = obj.value.length;
		var txt = obj.value;
		switch (type) {
			case 1: txt = txt.toLowerCase(); break;
			case 2: txt = txt.toUpperCase(); break;
			case 3: if (tam > 0) {
								txt = txt.toLowerCase().split(' ');
								for (var x = 0; x < txt.length; x++)
									if (!inArray(txt[x],except) && (txt[x].length > 1))
										txt[x] = txt[x].substring(0,1).toUpperCase() + txt[x].substring(1,txt[x].length);
								txt = txt.join(' ');
							}; break;
		};
		obj.value = txt;
}

function inArray(txt, array) {
	var ret = false;
	for (var x=0; x<array.length; x++)
		if (array[x] == txt)
			ret = true;
	return ret;
}


// ALTERA COR DE UM OBJETO
// ----------------------------------------------------------------------------
function mudacor(prmThis,prmName)	{
	if ((window.document.all) || (window.document.getElementById))
		prmThis.className = prmName;
	else if (window.document.layers)
		prmThis.className = prmName;
}


// JUMP MENU
// ----------------------------------------------------------------------------
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}


// MENSAGEM NA BARRA DE STATUS
// ----------------------------------------------------------------------------
function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}

//===============================================================================
//= FORMULÁRIOS E BUSCAS ========================================================
//===============================================================================
var tipo = 0;

function FaleConosco() {
	tipo = 1;
	document.form1.action = "mail.asp";
	document.form1.method = "post";
}

function Newsletter() {
	tipo = 2;
	document.form1.action = "newsletter-action.asp";
	document.form1.method = "post";
}

function Busca() {
	tipo = 3;
	document.form1.action = "";
	document.form1.method = "get";
}

function AcessoRestrito() {
	tipo = 4;
	document.form1.action = "../acessorestrito/login.asp";
	document.form1.method = "post";
}

function AlterarSenha() {
	tipo = 5;
	document.form1.action = "../acessorestrito/alterar-action.asp";
	document.form1.method = "post";
}

function Cadastro() {
	tipo = 6;
	document.form1.action = "mail.asp";
	document.form1.method = "post";
}

function VFaleConosco() {
	if (!document.form1.nome.value) { alert("Por favor, informe seu nome."); document.form1.nome.focus(); return false; };
  if (!VEmail( document.form1.email.value)) { alert("O seu e-mail não é válido!\nVerifique-o novamente."); document.form1.email.focus(); return false; };
  if (!document.form1.cidade.value) { alert("Por favor, informe a cidade."); document.form1.cidade.focus(); return false; };
  if (!document.form1.mensagem.value) { alert("Você deve escrever a mensagem."); document.form1.mensagem.focus(); return false; };
  return true;
}

function VNewsletter() {
	if (!document.form1.newsnome.value) { alert("Por favor, informe seu nome."); document.form1.newsnome.focus(); return false; };
  if (!VEmail(document.form1.newsemail.value)) { alert("O seu e-mail não é válido!\nVerifique-o novamente."); document.form1.newsemail.focus(); return false; };
  return true;
}

function VBusca() {
	if (!(document.form1.busca.value.length > 1)) { alert("Informe um número maior de caracteres para busca."); document.form1.busca.focus(); return false; };
	return true;
}

function VAcessoRestrito() {
  if (document.form1.login.value == "") { alert("Por favor, informe seu Login."); document.form1.login.focus(); return false; };
  if (document.form1.senha.value == "") { alert("Por favor, informe a Senha."); document.form1.senha.focus(); return false; };
  return true;
}

function VAlterarSenha() {
  if (document.form1.asenha.value == "") { alert("Por favor, informe a Senha atual."); document.form1.asenha.focus(); return false; };
  if (document.form1.nsenha.value == "") { alert("Por favor, informe a nova Senha."); document.form1.nsenha.focus(); return false; };
  if (document.form1.csenha.value == "") { alert("Por favor, confirme a sua nova Senha."); document.form1.csenha.focus(); return false; };
  if (document.form1.nsenha.value != document.form1.csenha.value) { alert("As Senhas digitadas não coincidem."); document.form1.nsenha.focus(); return false; };
  return true;
}

function VCadastro() {
  if (document.form1.nome.value == "") { alert("Por favor, informe seu nome."); document.form1.nome.focus(); return false; };
  if (document.form1.cpf.value == "") { alert("Por favor, informe seu CPF."); document.form1.cpf.focus(); return false; };
  if (!VCPF(document.form1.cpf.value)) { alert("Por favor, informe corretamente seu CPF."); document.form1.cpf.focus(); return false; };
  if (document.form1.identidade.value == "") { alert("Por favor, informe sua identidade."); document.form1.identidade.focus(); return false; };
  if (document.form1.nascimento.value == "") { alert("Por favor, informe seu nascimento."); document.form1.nascimento.focus(); return false; };
  if (!VData(document.form1.nascimento.value)) { alert("Por favor, informe corretamente seu nascimento."); document.form1.nascimento.focus(); return false; };
  if (document.form1.mae.value == "") { alert("Por favor, informe o nome de sua mãe."); document.form1.mae.focus(); return false; };
  if (document.form1.naturalidade.value == "") { alert("Por favor, informe sua naturalidade."); document.form1.naturalidade.focus(); return false; };
  if (document.form1.endereco.value == "") { alert("Por favor, informe seu endereço."); document.form1.endereco.focus(); return false; };
  if (document.form1.numero.value == "") { alert("Por favor, informe o número de sua residência."); document.form1.numero.focus(); return false; };
  if (document.form1.bairro.value == "") { alert("Por favor, informe o bairro ."); document.form1.bairro.focus(); return false; };
  if (document.form1.cidade.value == "") { alert("Por favor, informe a cidade."); document.form1.cidade.focus(); return false; };
  if (document.form1.uf.value == "-") { alert("Por favor, selecione a UF."); document.form1.uf.focus(); return false; };
  if (document.form1.telres.value == "") { alert("Por favor, informe o telefone residencial."); document.form1.telres.focus(); return false; };
  if (document.form1.telcel.value == "") { alert("Por favor, informe o telefone celular."); document.form1.telcel.focus(); return false; };
  if (document.form1.residedesde.value == "") { alert("Por favor, informe o tempo de residência."); document.form1.residedesde.focus(); return false; };
  if (!VMesAno(document.form1.residedesde.value)) { alert("Por favor, informe corretamente o tempo de residência."); document.form1.residedesde.focus(); return false; };
  if (document.form1.ocupacao.value == "-") { alert("Por favor, selecione sua ocupação."); document.form1.ocupacao.focus(); return false; };
  if (document.form1.funcao.value == "") { alert("Por favor, informe sua função."); document.form1.funcao.focus(); return false; };
  if (document.form1.salario.value == "") { alert("Por favor, informe seu salário/renda."); document.form1.salario.focus(); return false; };
  if (document.form1.admissao.value != "") {
	  if (!VMesAno(document.form1.admissao.value)) { alert("Por favor, informe corretamente a data de admissão."); document.form1.admissao.focus(); return false; };
  };
  if (document.form1.cnpjprof.value != "") {
	  if (!VCNPJ(document.form1.cnpjprof.value)) { alert("Por favor, informe corretamente o CNPJ da empresa."); document.form1.cnpjprof.focus(); return false; };
  };
  if (document.form1.nomerefpessoal.value == "") { alert("Por favor, informe o nome de sua referência pessoal."); document.form1.nomerefpessoal.focus(); return false; };
  if (document.form1.telrefpessoal.value == "") { alert("Por favor, informe o telefone de sua referência pessoal."); document.form1.telrefpessoal.focus(); return false; };
  if (document.form1.emailc.value == "") { alert("Por favor, informe seu e-mail."); document.form1.emailc.focus(); return false; };
  if (!VEmail(document.form1.emailc.value)) { alert("Por favor, informe corretamente seu e-mail."); document.form1.emailc.focus(); return false; };
  if (document.form1.emailcalternativo.value != "") {
	  if (!VEmail(document.form1.emailcalternativo.value)) { alert("Por favor, informe corretamente seu e-mail alternativo."); document.form1.emailcalternativo.focus(); return false; };
  };
  if (document.form1.refveiculo.value == "") { alert("Por favor, informe a referência do veículo desejado."); document.form1.refveiculo.focus(); return false; };
  if (document.form1.valorentrada.value == "") { alert("Por favor, informe o valor de entrada."); document.form1.valorentrada.focus(); return false; };
  if (document.form1.prestacoes.value == "-") { alert("Por favor, selecione a quantidade de prestações desejada."); document.form1.prestacoes.focus(); return false; };
  return true;
}


function EnviaFormulario() {
	switch(tipo) {
		case 1: return VFaleConosco(); break;
		case 2: return VNewsletter(); break;
		case 3:	if (VBusca()) { document.location.href="busca.asp?busca=" + document.form1.busca.value; } break;
		case 4: return VAcessoRestrito();
		case 5: return VAlterarSenha();
		case 6: return VCadastro();
	}
	return false;
}



//===============================================================================
//= AJAX ========================================================================
//===============================================================================
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 LoadAjax(metodo, url, send, destino, loadshow, loadcontent, loaddestino, janela) {
	var ajax = ajaxInit();	
	if(ajax) {  
		if(metodo == "post") {  
				ajax.open("POST", url, true);  
				ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
		} else {
				ajax.open("GET", url + "?rnd="+ Math.random() +"&"+ send, true);  
		}
		ajax.onreadystatechange = function() { 
																if (ajax.readyState == 1) {
																	if (loadshow == 2) {
																		document.getElementById(loaddestino).innerHTML = loadcontent;
																	};
																}
																if (ajax.readyState == 4) {
																	if (ajax.status == 200) {
																		var resultado = ajax.responseText; // Coloca o retornado pelo Ajax nessa variável 
																		resultado = resultado.replace(/\+/g," "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4) 
																		resultado = unescape(resultado); // Resolve o problema dos acentos 
																		if (loadshow == 2) {
																			document.getElementById(loaddestino).innerHTML = '';
																		};
																		if (janela != 2) {
																			document.getElementById(destino).innerHTML = resultado;
																		} else {
																			opener.document.getElementById(destino).innerHTML = resultado;
																			setTimeout("window.close()", 1000);
																		};
																	};
																}
															}  
			
		if(metodo == "post") {  
			ajax.send(send);  
		} else {  
			ajax.send(null);  
		}  
	}  
}

function MostraImagens(codigo,estoque) {
	var url = 'ajx_imagens.asp';
	var send = 'cod='+codigo+'&est='+estoque;
	var destino = 'ajx-veiculosFotos'; //local de retorno do conteúdo
	var loadshow = 2; //2 = exibe    <> de 2 = não exibe loading
	var loadcontent = '<img src="../imagens/ajax-loader.gif" alt="" class="fotoMaior" />'; //conteúdo de loading
	var loaddestino = 'ajx-veiculosFotos'; //destino do conteúdo de loading
	var janela = 1; //1 = mesma janela    2 ou > = janela opener
	LoadAjax("get", url, send, destino, loadshow, loadcontent, loaddestino, janela);
}

function SimularFinanc(codigo) {
	var url = 'ajx_resultado.asp';
	financ = document.form1.financeira.value;
	entrada = document.form1.valorentrada.value;
	if (financ != "-") {
		var send = 'cod='+codigo+'&fin='+financ+'&ent='+entrada;
		var destino = 'resultado'; //local de retorno do conteúdo
		var loadshow = 1; //2 = exibe    <> de 2 = não exibe loading
		var loadcontent = ''; //conteúdo de loading
		var loaddestino = 'resultado'; //destino do conteúdo de loading
		var janela = 1; //1 = mesma janela    2 ou > = janela opener
		LoadAjax("get", url, send, destino, loadshow, loadcontent, loaddestino, janela);
	}
	else {
		alert("Selecione a Financeira");
	}
}

