// variavel de deteccao do browser

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// variavel de deteccao do browser


// inicio trava tela
function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); }
      else { // qualquer caracter...
        return true;
      }
    }
    else {
      return true;
    }
  }

function retorna_dimensoes(){
	var xScroll, yScroll;
//	xScroll = document.documentElement["scrollWidth"];
//	yScroll = document.documentElement["scrollHeight"];

//	xScroll = document.body.scrollWidth;
//	yScroll = document.body.scrollHeight;

	try{
		xScrollb = document.documentElement["scrollWidth"];
		yScrollb = document.documentElement["scrollHeight"];

		xScroll = document.documentElement["offsetWidth"];
		yScroll = document.documentElement["offsetHeight"];

//	debug("xscroll="+xScroll+" yscroll="+yScroll+" xscrollb="+xScrollb+" yscrollb="+yScrollb)

		if(xScrollb>xScroll) xScroll=xScrollb;
		if(yScrollb>yScroll) yScroll=yScrollb;

//	debug(yScroll);

	} catch (e) { debug(e); }

	return Array(xScroll,yScroll);
}

function aguarde() {
	valores=retorna_dimensoes();	

	/*selects=document.getElementsByTagName("select");
	for(i=0; i<selects.length; i++) selects[i].style.visibility="hidden";*/

	travatela1=document.getElementById("trava_tela");
	travatela1.style.width="100%";
	travatela1.style.height=parseInt(valores[1])+"px";
	travatela1.style.display="";
	
	reposiciona("foto_grande");
}

tm="";
function reposiciona(a) {
	quadro=document.getElementById(a);
	quadro.style.display="";

	valores=retorna_dimensoes();
	topo1=document.documentElement["clientHeight"];

	IpopTop=(topo1-quadro.offsetHeight)/2;

	quadro.style.top=(IpopTop+document.documentElement["scrollTop"])+"px";

	tm=setTimeout("reposiciona('"+a+"')",100);
}

// trava tela fim!

function mostra_foto_nome(t) {
	
	var	img	= document.getElementById("recebe_foto");
	img.src="imgs/aguarde.gif";
	aguarde();	
	img.src="imgs/up/"+t;	
}

function mostra_foto(t) {
	var anterior;
	var proximo;
	var foto = vetor_imagem[t];
	var foto_ante = vetor_imagem[t-1];
	var foto_prox = vetor_imagem[t+1];
	
	var ante_disabled 	= '';
	var ante_cursor		= 'pointer';
	var ante_evento		= '';
	var prox_disabled 	= '';
	var prox_cursor		= 'pointer';
	var prox_evento		= '';	
	
	img=document.getElementById("recebe_foto");
	img.src="imgs/aguarde.gif";	
	
	aguarde();
	
	if (t > 0){
		anterior = parseInt(t) - 1;
		}else{
			anterior = quant_fotos;
			/*ante_disabled 	= '_disabled';
			ante_cursor		= 'default';
			ante_evento		= '';*/
	}
	
	if (t < quant_fotos){
		proximo =  parseInt(t) + 1;
		}else{
			proximo = 0;
			/*prox_disabled 	= '_disabled';
			prox_cursor		= 'default';
			prox_evento		= '';*/
	}	
	
	var scroll_imagem = document.getElementById('scroll_imagem');
	img.src="imgs/up/"+foto;
	scroll_imagem.innerHTML = "<img src=\"imgs/bt_anterior"+ante_disabled+".gif\" style=\"cursor:"+ante_cursor+"\" onclick=\"javascript:abre_foto('"+anterior+"')\" />"+ 
	            "<img src=\"imgs/bt_proxima"+prox_disabled+".gif\" style=\"cursor:"+prox_cursor+"\" onclick=\"javascript:abre_foto('"+proximo+"')\" />";	
	
}

function abre_foto(t){
	
	var anterior;
	var proximo;
	var foto = vetor_imagem[t];
	var foto_ante = vetor_imagem[t-1];
	var foto_prox = vetor_imagem[t+1];
	
	var ante_disabled 	= '';
	var ante_cursor		= 'pointer';
	var ante_evento		= '';
	var prox_disabled 	= '';
	var prox_cursor		= 'pointer';
	var prox_evento		= '';
	
	img=document.getElementById("recebe_foto");

	img.src="imgs/aguarde.gif";
	
	if (t > 0){
		anterior = parseInt(t) - 1;
		}else{
			anterior = quant_fotos;
			/*ante_disabled 	= '_disabled';
			ante_cursor		= 'default';
			ante_evento		= '';*/
	}
	
	if (t < quant_fotos){
		proximo =  parseInt(t) + 1;
		}else{
			proximo = 0;
			/*prox_disabled 	= '_disabled';
			prox_cursor		= 'default';
			prox_evento		= '';*/
	}	
	
	var scroll_imagem = document.getElementById('scroll_imagem');

	img.src="imgs/up/"+foto;
	scroll_imagem.innerHTML = "<img src=\"imgs/bt_anterior"+ante_disabled+".gif\" style=\"cursor:"+ante_cursor+"\" onclick=\"javascript:abre_foto('"+anterior+"')\" />"+ 
	            "<img src=\"imgs/bt_proxima"+prox_disabled+".gif\" style=\"cursor:"+prox_cursor+"\" onclick=\"javascript:abre_foto('"+proximo+"')\" />";
}

function fecha_aguarde() {
	
	selects=document.getElementsByTagName("select");
	for(i=0; i<selects.length; i++) selects[i].style.visibility="";
	
	document.getElementById("trava_tela").style.display="none";
	document.getElementById("foto_grande").style.display="none";
	clearTimeout(tm);
}

// AJAX

function getAjax(){
	
	var Ajax = null;
	
	// Trata as exceções até conseguir cria o objeto ajax
	
	try{
		// Tenta criar objeto ajax para os browsers mais recentes como Firefox, e Opera
		ajax = new XMLHttpRequest(); // ajax p firefox opera e navegadores recentes
		}catch(ee){
		
		try{
			// Tenta criar ajax para algumas versões do Microsoft Internet Explorer
			ajax = new ActiveXObject("Msxml2.XMLHTTP"); // IE
		}catch(e){
		
			try{
				// Tenta criar ajax para algumas versões do Microsoft Internet Explorer
				ajax = new ActiveXObject("Microsoft.XMLHTTP"); // IE
		
			}catch(E){
				// Browser utilizado não aceita ajax, o objeto não é criado
				ajax = false;
			}
		}
			
	}
	
	return ajax;
}
	function MandaEmailRevisao(){
		var div_mensagem 	= document.getElementById('div_mensagem');
		var div_form	 	= document.getElementById('div_form');
		var campos = 				"agenda_nome="+
									document.getElementById('agenda_nome').value+
									"&agenda_email="+
									document.getElementById('agenda_email').value+
									"&agenda_telefone="+
									document.getElementById('agenda_telefone').value+
									"&agenda_celular="+
									document.getElementById('agenda_celular').value+
									"&agenda_placa="+
									document.getElementById('agenda_placa').value+
									"&agenda_km="+
									document.getElementById('agenda_km').value+
									"&agenda_horario="+
									document.getElementById('agenda_horario').value+
									"&agenda_data="+
									document.getElementById('agenda_data').value+
									"&agenda_obs="+
									document.getElementById('agenda_obs').value;
									
		AjaxMailRevisao = getAjax();
		
		if (BrowserDetect.browser == 'Explorer'){
			var top_px = 500;
			}else{
				var top_px = 480;
		}		
	
		if (AjaxMailRevisao != null) {
			AjaxMailRevisao.open("POST", "includes/inc_servicos_agenderevisao_mail.php", true);
			
			AjaxMailRevisao.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			AjaxMailRevisao.setRequestHeader("Content-length", campos.length);
			AjaxMailRevisao.setRequestHeader("Connection", "close");
			
			AjaxMailRevisao.onreadystatechange = function(){
			
				if (AjaxMailRevisao.readyState == 4 ){
					if (AjaxMailRevisao.responseText == 'enviou'){
						nome 	= document.getElementById('agenda_nome');
						email 	= document.getElementById('agenda_email');
						telefone= document.getElementById('agenda_telefone');
						celular = document.getElementById('agenda_celular');
						placa 	= document.getElementById('agenda_placa');
						km 		= document.getElementById('agenda_km');
						horario = document.getElementById('agenda_horario');
						data	= document.getElementById('agenda_data');
						concessionaria	= document.getElementById('agenda_concessionaria');
						obs 	= document.getElementById('agenda_obs');
						
						nome.value  			='';
						email.value 			='';
						telefone.value  		='';
						celular.value			='';
						placa.value  			='';
						km.value  				='';
						horario.value  			='';
						data.value  			='';
						concessionaria.value 	= "";
						obs.value  		='';
						
						div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:"+top_px+"px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Contato efetuado com êxito!";						
						}else if (AjaxMailRevisao.responseText == 'campovazio'){
							div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:"+top_px+"px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Preencha os dados corretamente antes de enviar.";
						}else if(AjaxMailRevisao.responseText == 'naoenviou'){
							div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:"+top_px+"px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Não foi possível enviar o email.";
					}
				}				
				div_mensagem.style.display='block';
				div_form.style.display = 'none';
			}
			AjaxMailRevisao.send(campos);
		}
	}

	function MandaEmailContato(){
		var div_mensagem 	= document.getElementById('div_mensagem');
		var div_form	 	= document.getElementById('div_form');
		
		campos = 					"contato_nome="+
									document.getElementById('contato_nome').value+
									"&contato_email="+
									document.getElementById('contato_email').value+
									"&contato_telefone="+
									document.getElementById('contato_telefone').value+
									"&contato_endereco="+
									document.getElementById('contato_endereco').value+
									"&contato_numero="+
									document.getElementById('contato_numero').value+
									"&contato_bairro="+									
									document.getElementById('contato_bairro').value+
									"&contato_cidade="+
									document.getElementById('contato_cidade').value+
									"&contato_estado="+
									document.getElementById('contato_estado').value+
									"&contato_concessionaria="+
									document.getElementById('contato_concessionaria').value+
									"&contato_departamento="+
									document.getElementById('contato_departamento').value+									
									"&contato_mensagem="+
									document.getElementById('contato_mensagem').value;
		
		AjaxMailContato = getAjax();
		if (AjaxMailContato != null) {
			AjaxMailContato.open("POST", "includes/inc_contato_mail.php", true);
			AjaxMailContato.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			AjaxMailContato.setRequestHeader("Content-length", campos.length);
			AjaxMailContato.setRequestHeader("Connection", "close");			
			AjaxMailContato.send(campos);
			AjaxMailContato.onreadystatechange = function(){
			
				if (AjaxMailContato.readyState == 4 ){
					if (AjaxMailContato.responseText == 'enviou'){
						nome 			= document.getElementById('contato_nome');
						email 			= document.getElementById('contato_email');
						telefone		= document.getElementById('contato_telefone');
						endereco 		= document.getElementById('contato_endereco');
						numero 			= document.getElementById('contato_numero');
						bairro 			= document.getElementById('contato_bairro');
						cidade 			= document.getElementById('contato_cidade');
						estado 			= document.getElementById('contato_estado');
						concessionaria	= document.getElementById('contato_concessionaria');
						departamento 	= document.getElementById('contato_departamento');
						mensagem 		= document.getElementById('contato_mensagem');
						
						nome.value				= "";
						email.value 			= "";
						telefone.value			= "";
						endereco.value 			= "";
						numero.value 			= "";
						bairro.value 			= "";
						cidade.value 			= "";
						estado.value 			= "";
						concessionaria.value	= "";
						departamento.value 		= "";
						mensagem.value 			= "";
						
						div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:430px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Contato efetuado com êxito!";						
						}else if (AjaxMailContato.responseText == 'camposvazio'){
							div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:430px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Preencha os dados corretamente antes de enviar.";
						}else if(AjaxMailContato.responseText == 'naoenviou'){
							div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:430px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Não foi possível enviar o email."
						}
				}
				div_mensagem.style.display='block';
				div_form.style.display = 'none';
			}
		}
	}
	
	
	function submit_form_revisao() {
		var nome 	= document.getElementById('agenda_nome');
		var email 	= document.getElementById('agenda_email');
		var telefone= document.getElementById('agenda_telefone');
		var celular = document.getElementById('agenda_celular');
		var placa 	= document.getElementById('agenda_placa');
		var km 		= document.getElementById('agenda_km');
		var horario = document.getElementById('agenda_horario');
		var data	= document.getElementById('agenda_data');
		var obs 	= document.getElementById('agenda_obs');
		var div_mensagem 	= document.getElementById('div_mensagem');
		var div_form	 	= document.getElementById('div_form');
		
		//alert(BrowserDetect.browser);
		
		if (BrowserDetect.browser == 'Explorer'){
			var top_px = 500;
			}else{
				var top_px = 480;
		}
		
				
		if (nome.value == '' || email.value == ''  || telefone.value=='' || celular.value=='' || placa.value=='' || 
			km.value=='' || horario.value=='' || data.value=='' || obs.value==''){
			div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:"+top_px+"px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Preencha todos os campos antes de enviar.";
			div_mensagem.style.display='block';
			div_form.style.display = 'none';
			}else{
				div_mensagem.innerHTML = "<b>enviando:</b> <img src=\"imgs/enviando.gif\" />";				
				div_mensagem.style.display='block';
				div_form.style.display = 'none';
				MandaEmailRevisao();
		}
	}
	
	function submit_form_contato() {
		var nome 			= document.getElementById('contato_nome');
		var email 			= document.getElementById('contato_email');
		var telefone		= document.getElementById('contato_telefone');
		var endereco 		= document.getElementById('contato_endereco');
		var numero 			= document.getElementById('contato_numero');
		var bairro 			= document.getElementById('contato_bairro');
		var cidade 			= document.getElementById('contato_cidade');
		var estado 			= document.getElementById('contato_estado');
		var concessionaria	= document.getElementById('contato_concessionaria');
		var departamento 	= document.getElementById('contato_departamento');
		var mensagem 		= document.getElementById('contato_mensagem');
		var div_mensagem 	= document.getElementById('div_mensagem');
		var div_form	 	= document.getElementById('div_form');
		
		if (nome.value == '' || email.value == ''  || telefone.value=='' || endereco.value=='' || numero.value=='' || bairro.value=='' || cidade.value=='' || estado.value=='' || concessionaria.value=='' || departamento.value=='' || mensagem.value=='' ){
			div_mensagem.innerHTML = "<div style=\"position:absolute; left:523px; top:430px;\"><img style=\"cursor:pointer\" onclick=\"mostra_div('div_mensagem');mostra_div('div_form')\" src=\"imgs/bt_fechar_div.gif\" alt=\"fechar\" /></div>"+"Preencha todos os campos antes de enviar.";
			div_mensagem.style.display='block';
			div_form.style.display = 'none';
			}else{
				div_mensagem.innerHTML = "<b>enviando:</b> <img src=\"imgs/enviando.gif\" />";				
				div_mensagem.style.display='block';
				div_form.style.display = 'none';
				MandaEmailContato();
		}
	}	

	function mostra_div(show){
		var el1 = document.getElementById(show);
		if (el1.style.display == 'none'){
			el1.style.display = 'block';
			}else{
				el1.style.display = 'none';
		}
	}
// AJAX


// formulario semi novos

function GeraOptionModelos(){
	ApagaOptions('modelo');
	ApagaOptions('anofab');
	var marca = document.getElementById('fabricante').options[document.getElementById('fabricante').selectedIndex].value;
	var carregando = document.getElementById('atualizando');
	var camposdebusca = document.getElementById('campos_de_busca');
	camposdebusca.style.display = 'none';
	carregando.style.display = 'block';
	AjaxModelo = getAjax();
	if (AjaxModelo != null) {
		AjaxModelo.open("GET", "xml/modelos.php?idmarca="+marca, true);
		AjaxModelo.send(null);
		AjaxModelo.onreadystatechange = function(){		
			
			if (AjaxModelo.readyState == 4 ){
				if (AjaxModelo.responseXML){
					processXMLModelo(AjaxModelo.responseXML);
					}else{
						//alert('erro');
						camposdebusca.style.display = 'block';
						carregando.style.display = 'none';
						selecao_automoveis = document.getElementById('selecao_automoveis');						
						
				}
			}
		}
	}
	
	AjaxAnoFab = getAjax();
	if (AjaxAnoFab != null) {
		AjaxAnoFab.open("GET", "xml/anofab.php?campo=marca&id="+marca, true);
		AjaxAnoFab.send(null);
		AjaxAnoFab.onreadystatechange = function(){
			
			if (AjaxAnoFab.readyState == 4 ){
				if (AjaxAnoFab.responseXML){
					processXMLAnoFab(AjaxAnoFab.responseXML);
					camposdebusca.style.display = 'block';
					carregando.style.display = 'none';
					}else{
						//alert('erro');
						//processXML(Ajax.responseXML);
						camposdebusca.style.display = 'block';
						carregando.style.display = 'none';						
				}
			}
		}
	}
	BuscaSeminovos(0);
	
	
}

function GeraOptionAno(){
	ApagaOptions('anofab');
	var modelo = document.getElementById('modelo').options[document.getElementById('modelo').selectedIndex].value;
	var carregando = document.getElementById('atualizando');
	var camposdebusca = document.getElementById('campos_de_busca');
	camposdebusca.style.display = 'none';
	carregando.style.display = 'block';
	AjaxAnoFab = getAjax();
	if (AjaxAnoFab != null) {
		AjaxAnoFab.open("GET", "xml/anofab.php?campo=modelo&id="+modelo, true);
		AjaxAnoFab.send(null);
		AjaxAnoFab.onreadystatechange = function(){
			
			if (AjaxAnoFab.readyState == 4 ){
				if (AjaxAnoFab.responseXML){
					processXMLAnoFab(AjaxAnoFab.responseXML);
					camposdebusca.style.display = 'block';
					carregando.style.display = 'none';
					}else{
						//alert(AjaxAnoFab.responseText);
						//processXML(AjaxAnoFab.responseXML);
						camposdebusca.style.display = 'block';
						carregando.style.display = 'none';
				}
			}
		}
	}
	BuscaSeminovos(0);
	//}
}

function ApagaOptions(select){
	
	var selectbox = document.getElementById(select);
	for(i=selectbox.options.length-1;i>=1;i--){
		//if(selectbox.options[i].selected)
		selectbox.remove(i);
	} 	
}

function processXMLModelo(obj){
	ApagaOptions('modelo');
	ApagaOptions('anofab');
	selectbox = document.getElementById('modelo');
  	//pega a tag modelo
  	var dataArray   = obj.getElementsByTagName("modelo");
  
  	//total de elementos contidos na tag modelo
  	if(dataArray.length > 0) {
     	//percorre o arquivo XML paara extrair os dados
     	for(var i = 0 ; i < dataArray.length ; i++) {
        	var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var id    =  item.getElementsByTagName("id")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
		    	//atribui um ID a esse elemento
		    	novo.setAttribute("id", "opcoes");
				//atribui um valor
		    	novo.value = id;
				//atribui um texto
		    	novo.text  = descricao;
				//finalmente adiciona o novo elemento
				selectbox.options.add(novo);
	 	}
  	}
}

function processXMLAnoFab(obj){
	ApagaOptions('anofab');	
	selectbox = document.getElementById('anofab');
  	//pega a tag anofab
  	var dataArray   = obj.getElementsByTagName("anofab");
  
  	//total de elementos contidos na tag cidade
  	if(dataArray.length > 0) {
     	//percorre o arquivo XML paara extrair os anofab
     	for(var i = 0 ; i < dataArray.length ; i++) {
        	var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var id    		=  item.getElementsByTagName("id")[0].firstChild.nodeValue;
			var descricao 	=  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
		    	//atribui um ID a esse elemento
		    	novo.setAttribute("id", "opcoes");
				//atribui um valor
		    	novo.value = id;
				//atribui um texto
		    	novo.text  = descricao;
				//finalmente adiciona o novo elemento
				selectbox.options.add(novo);
	 	}
  	}
}
function BuscaSeminovos(pagina){
	var marca  = document.getElementById('fabricante').options[document.getElementById('fabricante').selectedIndex].value;
	var modelo = document.getElementById('modelo').options[document.getElementById('modelo').selectedIndex].value;
	var anofab = document.getElementById('anofab').options[document.getElementById('anofab').selectedIndex].value;
	
	//if (marca != '' || modelo != '' || anofab != '' ){
	//alert ('passou');
		BuscaVeiculosSeminovos(marca,modelo,anofab,pagina);
		//}else{
			//alert('prencha pelo menos 1 campo');			
	//}
}

function BuscaVeiculosSeminovos(marca,modelo,anofab,pagina){
	var carregando = document.getElementById('atualizando2');
	var bloco_seminovos = document.getElementById('bloco_seminovos');
	var div_paginacao = document.getElementById('div_paginacao');
	var encontrado_automoveis = document.getElementById('encontrado_automoveis');

	encontrado_automoveis.style.display = 'none';
	bloco_seminovos.style.display = 'none';
	div_paginacao.style.display = 'none';
	carregando.style.display = 'block';	
	var AjaxSeminovos = getAjax();
	if (AjaxSeminovos != null) {
		AjaxSeminovos.open("GET", "xml/veiculos_seminovos.php?marca="+marca+"&modelo="+modelo+"&anofab="+anofab+"&pagina="+pagina, true);
		AjaxSeminovos.send(null);
		AjaxSeminovos.onreadystatechange = function(){
			
			if (AjaxSeminovos.readyState == 4 ){
				if (AjaxSeminovos.responseXML){
					processXMLVeivulosSeminovos(AjaxSeminovos.responseXML);
					encontrado_automoveis.style.display = 'block';
					bloco_seminovos.style.display = 'block';
					div_paginacao.style.display = 'block';
					carregando.style.display = 'none';
					}else{
						bloco_seminovos.style.display = 'block';
						div_paginacao.style.display = 'block';
						carregando.style.display = 'none';						
						quant_seminovos = document.getElementById('quant_seminovos');
						selecao_automoveis = document.getElementById('selecao_automoveis');
						quant = "<b>Encontrados:</b> 0 veículos";
						selecao = "Todos os automóveis";
						quant_seminovos.innerHTML = quant;
						selecao_automoveis.innerHTML = '';						
				}
			}
		}
	}		
}

function BuscaVeiculosSeminovosID(idveiculo){
	AjaxSeminovos = getAjax();
	if (AjaxSeminovos != null) {
		AjaxSeminovos.open("GET", "xml/veiculos_seminovos_id.php?idveiculo="+idveiculo, true);
		AjaxSeminovos.send(null);
		AjaxSeminovos.onreadystatechange = function(){
			
			if (AjaxSeminovos.readyState == 4 ){
				if (AjaxSeminovos.responseXML){
					//alert(AjaxSeminovos.responseXML);
					processXMLVeivulosSeminovosID(AjaxSeminovos.responseXML);
					}else{
						quant_seminovos = document.getElementById('quant_seminovos');
						selecao_automoveis = document.getElementById('selecao_automoveis');
						quant = "<b>Encontrados:</b> 0 veículos";
						selecao = "Todos os automóveis";
						quant_seminovos.innerHTML = quant;
						selecao_automoveis.innerHTML = '';						
				}
			}
		}
	}		
}

function processXMLVeivulosSeminovos(obj){

	var quant_seminovos = document.getElementById('quant_seminovos');
	var selecao_automoveis = document.getElementById('selecao_automoveis');
	var div_paginacao = document.getElementById('div_paginacao');
  	//pega a tag anofab
  	var dataArray   = obj.getElementsByTagName("dados");
  	
  	prim_disabled 	= '';
  	ante_disabled 	= '';
  	prox_disabled 	= '';
  	ulti_disabled 	= '';
  	prim_cursor		= 'pointer';
  	ante_cursor		= 'pointer';
  	prox_cursor		= 'pointer';
  	ulti_cursor		= 'pointer';
 	
  	
  	if(dataArray.length > 0) {
     	//percorre o arquivo XML para extrair os dados
     	for(var i = 0 ; i < dataArray.length ; i++) {
        	var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var quant 	=  item.getElementsByTagName("quant")[0].firstChild.nodeValue;
			var selecao	=  item.getElementsByTagName("selecao")[0].firstChild.nodeValue;
			var primeiro=  item.getElementsByTagName("primeiro")[0].firstChild.nodeValue;
			var anterior=  item.getElementsByTagName("anterior")[0].firstChild.nodeValue;
			var proximo	=  item.getElementsByTagName("proximo")[0].firstChild.nodeValue;
			var ultimo	=  item.getElementsByTagName("ultimo")[0].firstChild.nodeValue;
			var pag_atual=  item.getElementsByTagName("pag_atual")[0].firstChild.nodeValue;
			var pag_max	=  item.getElementsByTagName("pag_max")[0].firstChild.nodeValue;
			
		  	prim_evento 	= "onclick=\"BuscaSeminovos("+primeiro+")\"";
		  	ante_evento 	= "onclick=\"BuscaSeminovos("+anterior+")\"";
		  	prox_evento 	= "onclick=\"BuscaSeminovos("+proximo+")\"";
		  	ulti_evento 	= "onclick=\"BuscaSeminovos("+ultimo+")\"";			
			
			if(pag_atual == pag_max){
			  	prox_disabled 	= '_disabled';
			  	ulti_disabled 	= '_disabled';				
				prox_cursor		= 'default';
  				ulti_cursor		= 'default';
  				prox_evento		= '';
  				ulti_evento		= '';
			}
			
			if(pag_atual == 1){
			  	prim_disabled 	= '_disabled';
			  	ante_disabled 	= '_disabled';				
				prim_cursor		= 'default';
  				ante_cursor		= 'default';
  				prim_evento		= '';
  				ante_evento		= '';  				
			}			
			
			if (quant == 0 || quant > 1){
				quant = "<b>Encontrados:</b> "+ quant +" veículos";
				}else{
					quant = "<b>Encontrado:</b> "+ quant +" veículo";
			}
			quant_seminovos.innerHTML = quant;
			selecao_automoveis.innerHTML = selecao;
	 	}
  	}
  
	document.getElementById('encontrado_automoveis').style.display='block';
  	
  	var bloco_seminovos = document.getElementById('bloco_seminovos');
  	var dataArray   = obj.getElementsByTagName("seminovo");
  	//total de elementos contidos na tag seminovo
  	
  	if(dataArray.length > 0) {
     	//percorre o arquivo XML paara extrair os anofab
     	divs = "";
     	for(var i = 0 ; i < dataArray.length ; i++) {
        	var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var id    	=  item.getElementsByTagName("id")[0].firstChild.nodeValue;
			var marca 	=  item.getElementsByTagName("marca")[0].firstChild.nodeValue;
			var modelo 	=  item.getElementsByTagName("modelo")[0].firstChild.nodeValue;
			var preco	=  item.getElementsByTagName("preco")[0].firstChild.nodeValue;
			var anofab	=  item.getElementsByTagName("anofab")[0].firstChild.nodeValue;
			var anomod 	=  item.getElementsByTagName("anomod")[0].firstChild.nodeValue;
			var imagem 	=  item.getElementsByTagName("imagem")[0].firstChild.nodeValue;
			var km 		=  item.getElementsByTagName("km")[0].firstChild.nodeValue;
			var cor		=  item.getElementsByTagName("cor")[0].firstChild.nodeValue;
			var versao	=  item.getElementsByTagName("versao")[0].firstChild.nodeValue;
			var acessor	=  item.getElementsByTagName("acessor")[0].firstChild.nodeValue;
			var oferta	=  item.getElementsByTagName("oferta")[0].firstChild.nodeValue;
			var obs		=  item.getElementsByTagName("obs")[0].firstChild.nodeValue;

			if (acessor != '0'){
				acessor = "<b>Acessorios:</b> "+acessor+" <br />";
			}else{
				acessor = '';
			}
			
			if (obs != '<br>'){
				obs = "<b>Observações:</b> "+obs;
				}else{
					obs = '';
			}
			
			if (id == 'nenhum'){
				document.getElementById('bloco_seminovos').style.display='none';
				document.getElementById('div_paginacao').style.display='none';
				document.getElementById('selecao_automoveis').style.display='none';				
				}else{
					document.getElementById('bloco_seminovos').style.display='block';
					document.getElementById('div_paginacao').style.display='block';
					document.getElementById('selecao_automoveis').style.display='block';
					divs = divs + "<div style=\"z-index:99999px; position:absolute; margin:10px 0 0 -10px; display:"+oferta+";\"><img src=\"imgs/selo_oferta_deva.gif\"/></div>"+
						"<img src=\"imgs/linha_seminovos.gif\" style=\"margin:10px 0 10px 0;\" />"+
		                "<div style=\"float:left; margin-top:5px;\"><img style=\"cursor:pointer\" onclick=\"mostra_foto_nome('"+imagem+"')\" src='imgs/up/mini_"+imagem+"' style=\" border:1px solid #eeece2;\" /></div>"+
						"<div style=\"float:left; margin-left:10px; line-height:18px;\">"+
							"<b>Marca:</b> "+marca+"<br />"+
							"<b>Modelo:</b> "+modelo+"<br />"+
							"<b>Preço:</b> R$ "+preco+"<br />"+
							"<b>Ano / Km:</b> "+anofab+" - "+anomod+" / "+km+" km"+
		            	"</div>"+
						"<a style=\"cursor:pointer\" onclick=\"javascript:mostra_div('div_semi_novos"+id+"')\"><img src=\"imgs/bt_maisdetalhes.gif\" style=\"margin:0 0 0 334px;\" /></a>"+
						"<div id =\"div_semi_novos"+id+"\" class=\"campo_texto_seminovos\" style=\"display:none; margin-top:20px; line-height:18px;\">"+
			  		"<table width=\"385\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"+
				"<tr>"+
						"<td><img src=\"imgs/topo_div_maisdetalhes.gif\" alt=\"\" /></td>"+
				"</tr>"+
				"<tr>"+
						"<td bgcolor=\"#d6d2c1\" style=\"padding:0 5px 0 5px; line-height:18px;\">"+
							"<b>Cor:</b> "+cor+" <br />"+
							"<b>Versão:</b> "+versao+" <br />"+
							acessor+
							obs+
						"</td>"+
				"</tr>"+
				"<tr>"+
						"<td><img src=\"imgs/rodape_div_maisdetalhes.gif\" alt=\"\" /></td>"+
				"</tr>"+
					"</table>"+
					"</div>";
			
     		}

	 	}

	 	bloco_seminovos.innerHTML = divs;
	 	paginacao = "<span style=\"cursor:"+prim_cursor+"\" "+prim_evento+"><img src=\"imgs/bt_primeira"+prim_disabled+".gif\" /> </span>    <span style=\"cursor:"+ante_cursor+"\" "+ante_evento+"><img src=\"imgs/bt_anterior"+ante_disabled+".gif\" /> </span>   <span style=\"cursor:"+prox_cursor+"\" "+prox_evento+"><img src=\"imgs/bt_proxima"+prox_disabled+".gif\" /> </span>    <span style=\"cursor:"+ulti_cursor+"\" "+ulti_evento+"><img src=\"imgs/bt_ultima"+ulti_disabled+".gif\" /> </span><br /><br /> <span style=\"float:right;\">Página "+pag_atual+" de "+pag_max+" </span> ";
	 	div_paginacao.innerHTML = paginacao;	 	
  	}
}

function processXMLVeivulosSeminovosID(obj){

	quant_seminovos = document.getElementById('quant_seminovos');
	selecao_automoveis = document.getElementById('selecao_automoveis');
	div_paginacao = document.getElementById('div_paginacao');
  	//pega a tag anofab
  	var dataArray   = obj.getElementsByTagName("dados");
  	if(dataArray.length > 0) {
     	//percorre o arquivo XML para extrair os dados
     	for(var i = 0 ; i < dataArray.length ; i++) {
        	var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var quant 		=  item.getElementsByTagName("quant")[0].firstChild.nodeValue;
			var selecao		=  item.getElementsByTagName("selecao")[0].firstChild.nodeValue;			
			
			if (quant == 0 || quant > 1){
				quant = "<b>Encontrados:</b> "+ quant +" veículos";
				}else{
					quant = "<b>Encontrado:</b> "+ quant +" veículo";
			}
			//quant_seminovos.innerHTML = quant;
			//selecao_automoveis.innerHTML = selecao;
	 	}
  	}  	
  
  	bloco_seminovos = document.getElementById('bloco_seminovos');
  	
  	var dataArray   = obj.getElementsByTagName("seminovo");
  	//total de elementos contidos na tag seminovo
  	
  	if(dataArray.length > 0) {
     	//percorre o arquivo XML paara extrair os anofab
     	divs = "";
     	for(var i = 0 ; i < dataArray.length ; i++) {
        	var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var id    	=  item.getElementsByTagName("id")[0].firstChild.nodeValue;
			var marca 	=  item.getElementsByTagName("marca")[0].firstChild.nodeValue;
			var modelo 	=  item.getElementsByTagName("modelo")[0].firstChild.nodeValue;
			var preco	=  item.getElementsByTagName("preco")[0].firstChild.nodeValue;
			var anofab	=  item.getElementsByTagName("anofab")[0].firstChild.nodeValue;
			var anomod 	=  item.getElementsByTagName("anomod")[0].firstChild.nodeValue;
			var imagem 	=  item.getElementsByTagName("imagem")[0].firstChild.nodeValue;
			var km 		=  item.getElementsByTagName("km")[0].firstChild.nodeValue;
			var cor		=  item.getElementsByTagName("cor")[0].firstChild.nodeValue;
			var versao	=  item.getElementsByTagName("versao")[0].firstChild.nodeValue;
			var acessor	=  item.getElementsByTagName("acessor")[0].firstChild.nodeValue;
			var oferta	=  item.getElementsByTagName("oferta")[0].firstChild.nodeValue;
			var obs		=  item.getElementsByTagName("obs")[0].firstChild.nodeValue;
			
			if (acessor != '0'){
				acessor = "<b>Acessorios:</b> "+acessor+" <br />";
			}else{
				acessor = '';
			}
			
			if (obs != '<br>'){
				obs = "<b>Observações:</b> "+obs;
				}else{
					obs = '';
			}
						
			divs = divs + "<div style=\"z-index:99999px; position:absolute; margin:10px 0 0 -10px; display:"+oferta+";\"><img src=\"imgs/selo_oferta_deva.gif\"/></div>"+
				"<img src=\"imgs/linha_seminovos.gif\" style=\"margin:10px 0 10px 0;\" />"+
                "<div style=\"float:left; margin-top:5px;\"><img style=\"cursor:pointer\" onclick=\"mostra_foto_nome('"+imagem+"')\" src='imgs/up/mini_"+imagem+"' style=\" border:1px solid #eeece2;\" /></div>"+
				"<div style=\"float:left; margin-left:10px; line-height:18px;\">"+
					"<b>Marca:</b> "+marca+"<br />"+
					"<b>Modelo:</b> "+modelo+"<br />"+
					"<b>Preço:</b> R$ "+preco+"<br />"+
					"<b>Ano / Km:</b> "+anofab+" - "+anomod+" / "+km+" km"+
            	"</div>"+
				
				"<div id =\"div_semi_novos"+id+"\" class=\"campo_texto_seminovos\" style=\"display:block; clear:left; margin-top:80px; line-height:18px;\">"+
	  		"<table width=\"385\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"+
		"<tr>"+
				"<td><img src=\"imgs/topo_div_maisdetalhes.gif\" alt=\"\" /></td>"+
		"</tr>"+
		"<tr>"+
				"<td bgcolor=\"#d6d2c1\" style=\"padding:0 5px 0 5px; line-height:18px;\">"+
					"<b>Cor:</b> "+cor+" <br />"+
					"<b>Versão:</b> "+versao+" <br />"+
					acessor+
					obs+
				"</td>"+
		"</tr>"+
		"<tr>"+
				"<td><img src=\"imgs/rodape_div_maisdetalhes.gif\" alt=\"\" /></td>"+
		"</tr>"+
			"</table>"+
			"</div>";

	 	}
	 	bloco_seminovos.innerHTML = divs;	 	
  	}
}

/*------------------------------- MAPA */
 
    var map;
    var gdir;
    var geocoder = null;
    var addressMarker;

    function initialize() {
      if (GBrowserIsCompatible()) {      
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        setDirections("belo horizonte, mg", "belo horizonte, mg", "pt_BR");
      }
    }
    
    function setDirections(fromAddress, toAddress, locale) {
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
