//CRIA O Objeto XMLHttpRequest
function createXMLHTTP() {
	var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
	var xmlhttp = false;
	for (var i=0; i < arrSignatures.length; i++) {
		try {
			var oRequest = new ActiveXObject(arrSignatures[i]);
			xmlhttp = oRequest;
			break;
		} catch (oError) {
		}
	}
	if(!xmlhttp && typeof XMLHttpRequest != 'undefined')
	{
		//PARA O FIREFOX
		xmlhttp = new XMLHttpRequest();
	}
	
	return xmlhttp;
}

//DECODIFICADOR DE CODIGO RECEBIDO PELO XMLHttpRequest
function URLDecode(psEncodeString)
{
  var lsRegExp = /\+/g;
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

function validaPesquisa(f)
{
	try {
		if(document.getElementById("modelo").value=="" && f.ano_de.value=="" && f.ano_ate.value=="")
		{
			alert('Favor informar pelo menos um campo de pesquisa!');
			return false;
		}
		
		//validar ano de pesquisa
		if(f.ano_de.value!="")
		{
			if(f.ano_de.value.length!=4)
			{
				alert("Ano inicial inválido!");
				f.ano_de.focus();
				return false;
			}
			
			if(f.ano_ate.value=="")
			{
				alert("Ano final não informado!");
				f.ano_ate.focus();
				return false;
			}
			else
			{
				if(f.ano_ate.value.length!=4)
				{
					alert("Ano final inválido!");
					f.ano_ate.focus();
					return false;
				}
			}
			
			//valida se ano inicial <= ano final
			if(f.ano_de.value>f.ano_ate.value)
			{
				alert("Ano final deve ser maior que o ano inicial!");
				f.ano_ate.value="";
				f.ano_ate.focus();
				return false;
			}
		}
		else
		{
			if(f.ano_ate.value!="")
			{
				if(f.ano_ate.value.length!=4)
				{
					alert("Ano final inválido!");
					f.ano_ate.focus();
					return false;
				}
				
				alert("Ano inicial não informado!");
				f.ano_de.focus();
				return false;
			}
		}
		
		document.location.href='listabusca.php?a=2&modelo='+document.getElementById('modelo').value+'&ano_de='+document.getElementById('ano_de').value+'&ano_ate='+document.getElementById('ano_ate').value+'&by=met';
		return false;
	} catch(e){ return false;}
}

//PREENCHE A LISTBOOX COM AS REVENDAS
function fu_conta_click(reve_cod, origem, veiculo)
{
	var oHTTPRequest = createXMLHTTP(); 
	oHTTPRequest.open("post", "cont_click_rev.php", true);
	oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	oHTTPRequest.send("id="+reve_cod+"&by="+origem+"&veiculo="+veiculo);
}

function setcookie(name, value, acao) {
  var curCookie = name + "=" + escape(value); 

	if (acao==true) { //cria
	  document.cookie = curCookie;
	} else {	  //exclui
	  document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}  
}


function getcookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;

  return unescape(dc.substring(begin + prefix.length, end));

}



function deletecookie(name, path, domain) {
  if (getcookie(name)) {
    document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }

}


function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

//FUNCAO UTILIZADO PARA MOVER PROXIMA FOTO
function fu_proximo(atual,var_max) {

    var aux = atual;
    aux++;

//nao deixa ultrapassar ultimo valor do vetor...
    if (aux<=var_max) {
            document.location.href = "modelocarro.php?posicao="+aux+"&total_pesquisa="+var_max;
    } else {
            aux=var_max;
    }

}

//FUNCAO UTILIZADO PARA MOVER FOTO ANTERIOR
function fu_anterior(atual, total_pesquisa) {
    var aux = atual;
        aux--;

  //nao deixa zerar
    if (aux>0) {
            document.location.href = "modelocarro.php?posicao="+aux+"&total_pesquisa="+total_pesquisa;
    } else {
            aux=1;
    }

}

function fu_rollover(name, link_imagem) {
    if (document.images) {
            document.images[name].src = link_imagem;
    }
}

function carregaCidade(id, id_div)
{
	try {
		if (id != "0" && id!="") {
			removeItensSelect(id_div);
			var o = new Option("-- Selecione a Cidade --" ,"" , false, false);
			document.getElementById(id_div).options[0] = o;
			
			var oHTTPRequest = new createXMLHTTP(); 
			oHTTPRequest.open("post", 'carrega_cidade_ajax.php', true);
			oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			oHTTPRequest.onreadystatechange=function() {
				if (oHTTPRequest.readyState==4){
					removeItensSelect(id_div);
					var o = new Option("-- Selecione a Cidade --" ,"" , false, false);
					document.getElementById(id_div).options[0] = o;
					v = oHTTPRequest.responseXML.getElementsByTagName('id'); //VALOR DO ID DA CIDADE
					t = oHTTPRequest.responseXML.getElementsByTagName('nome'); //VALOR DO NOME DA CIDADE
					for (i = 0 ; i < v.length ; i++) {			
						var o = new Option(URLDecode(t[i].firstChild.nodeValue),v[i].firstChild.nodeValue, false, false);
						document.getElementById(id_div).options[document.getElementById(id_div).options.length] = o;
					}
				}
				else
				{
					if (document.getElementById(id_div).options[0].text=="carregando.")
						document.getElementById(id_div).options[0].text = "carregando..";
					else if (document.getElementById(id_div).options[0].text == "carregando..")
						document.getElementById(id_div).options[0].text = "carregando...";
					else
						document.getElementById(id_div).options[0].text = "carregando.";
				}
			}
			oHTTPRequest.send("id=" + id);
		}
		else
		{
			removeItensSelect(id_div);
			var o = new Option("-- selecione o estado --" ,"" , false, false);
			document.getElementById(id_div).options[0] = o;
		}
	} catch(e) { alert(e); }
}
function removeItensSelect(id) {
	try {
		while (document.getElementById(id).options.length > 0) {
			document.getElementById(id).remove(document.getElementById(id).options.length-1);
		}
	} catch (e) {}
}
	
	
function fu_validar_pesquisaavancada()
{
	document.getElementById('enviar').disabled = true;
try {

	if(document.form1.modelo.value=="")
	{
		alert("Modelo do veículo obrigatório!");
		document.form1.modelo.focus();
		document.getElementById('enviar').disabled = false;
		return(false);
	}

	//validar ano de pesquisa
	if(document.form1.ano_de.value!="")
	{
		if(document.form1.ano_de.value.length!=4)
		{
			alert("Ano inicial inválido!");
			document.form1.ano_de.focus();
			document.getElementById('enviar').disabled = false;
			return false;
		}
		
		if(document.form1.ano_ate.value=="")
		{
			alert("Ano final não informado!");
			document.form1.ano_ate.focus();
			document.getElementById('enviar').disabled = false;
			return false;
		}
		else
		{
			if(document.form1.ano_ate.value.length!=4)
			{
				alert("Ano final inválido!");
				document.form1.ano_ate.focus();
				document.getElementById('enviar').disabled = false;
				return false;
			}
		}
		
		//valida se ano inicial <= ano final
		if(document.form1.ano_de.value>document.form1.ano_ate.value)
		{
			alert("Ano final deve ser maior que o ano inicial!");
			document.form1.ano_ate.value="";
			document.form1.ano_ate.focus();
			document.getElementById('enviar').disabled = false;
			return false;
		}
	}
	else
	{
		if(document.form1.ano_ate.value!="")
		{
			if(document.form1.ano_ate.value.length!=4)
			{
				alert("Ano final inválido!");
				document.form1.ano_ate.focus();
				document.getElementById('enviar').disabled = false;
				return false;
			}
			
			alert("Ano inicial não informado!");
			document.form1.ano_de.focus();
			document.getElementById('enviar').disabled = false;
			return false;
		}
	}
	
	
	//validar valores do veiculo
	if(document.form1.veicu_valorde.value!="")
	{
		
		if(document.form1.veicu_valorate.value=="")
		{
			alert("Valor final não informado!");
			document.form1.veicu_valorate.focus();
			document.getElementById('enviar').disabled = false;
			return false;
		}
		
		//valida se valor inicial <= valor final
		if(parseFloat(document.form1.veicu_valorde.value)>parseFloat(document.form1.veicu_valorate.value))
		{
			alert("Valor final deve ser maior que o valor inicial!");
			document.form1.veicu_valorate.value="";
			document.form1.veicu_valorate.focus();
			document.getElementById('enviar').disabled = false;
			return false;
		}
	}
	else
	{
		if(document.form1.veicu_valorate.value!="")
		{
			alert("Valor inicial não informado!");
			document.form1.veicu_valorde.focus();
			document.getElementById('enviar').disabled = false;
			return false;
		}
	}
	
	var cont = 0;
	var acessorios = "";
	for(k=0;k<document.form1.chk_acessorios.length;k++)
	{
		if(document.form1.chk_acessorios[k].checked)
		{
			cont++;
			if(cont==1)
				acessorios = document.form1.chk_acessorios[k].value;
			else
				acessorios = acessorios + ", " + document.form1.chk_acessorios[k].value;
		}
	}
	
	//gerando location href para evitar *PAGINA EXPIROU*
	if(document.form1.modelo.value=="" && document.form1.marca.value=="" && document.form1.estado.value=="999" && document.form1.cidade.value=="999" && document.form1.uso.value=="" && document.form1.ano_de.value=="" && document.form1.ano_ate.value=="" && document.form1.veicu_valorde.value=="" && document.form1.veicu_valorate.value=="" && document.form1.cor.value=="" && document.form1.combustivel.value=="" && document.form1.tipo.value=="")
	{
		alert("Preencha no mínimo 1(um) campo para pesquisa");
		document.form1.modelo.focus();
		document.getElementById('enviar').disabled = false;
		return false;
	}
	video = "";
	
	if(document.form1.cidade.value!="" && document.form1.cidade.value != "999")
	{
		fu_contaPesquisaCidade(document.form1.cidade.value);
	}
	
	if(document.form1.op_foto[0].checked)
		document.location.href = "listabusca.php?a=2&start=0&pesquisaAvancada=1&modelo="+document.form1.modelo.value+"&uso="+document.form1.uso.value+video+"&op_foto="+document.form1.op_foto[0].value+"&ano_de="+document.form1.ano_de.value+"&ano_ate="+document.form1.ano_ate.value+"&veicu_valorde="+document.form1.veicu_valorde.value+"&veicu_valorate="+document.form1.veicu_valorate.value+"&cor="+document.form1.cor.value+"&combustivel="+document.form1.combustivel.value+"&tipo="+document.form1.tipo.value+"&marca="+document.form1.marca.value+"&chk_acessorios="+acessorios;
	else
		document.location.href = "listabusca.php?a=2&start=0&pesquisaAvancada=1&modelo="+document.form1.modelo.value+"&uso="+document.form1.uso.value+video+"&op_foto="+document.form1.op_foto[1].value+"&ano_de="+document.form1.ano_de.value+"&ano_ate="+document.form1.ano_ate.value+"&veicu_valorde="+document.form1.veicu_valorde.value+"&veicu_valorate="+document.form1.veicu_valorate.value+"&cor="+document.form1.cor.value+"&combustivel="+document.form1.combustivel.value+"&tipo="+document.form1.tipo.value+"&marca="+document.form1.marca.value+"&chk_acessorios="+acessorios;
	
	return false;
} catch(e) { alert(e); document.getElementById('enviar').disabled = false;}
}

function fu_contaPesquisaCidade(id)
{
	try
	{
		var ohr = createXMLHTTP(); 
		ohr.open("post", "ajax_conta_cidade.php", false);
		ohr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ohr.send("id=" + id);
		//alert(URLDecode(ohr.responseText));
	}
	catch(e) { alert(e); }
}

function validaMailling(f)
{
	try
	{
		if(!validaEmail(f.email.value))
		{
			alert('Favor preencher o e-mail corretamente !');
			f.email.focus();
			return false;
		}
		
		
		return true;
	} catch(e) { alert(e); return false}
	
	return false;
}


//validacao email
function validaEmail(email) {
	try {
		er = /^[0-9a-z][0-9a-zA-Z._-]+@[a-z][-.a-z0-9]+[.][a-z]+$/;
		if (!er.test(email)) {
			return false;
		}
		return true;
	} catch (e) {}
}


function fu_valida_amigo(tela) {
	var f = tela;
	
	if (!validaEmail(f.seuemail.value)) {
		alert('Por favor, preencha o SEU EMAIL corretamente.');
		f.seuemail.focus();
		return false;
	}
	
	if (!validaEmail(f.seuamigo.value)) {
		alert('Por favor, preencha o EMAIL DO SEU AMIGO corretamente.');
		f.emailamigo.focus();
		return false;
	}	
	return true;
}

//objeto = this.value
//aceita virgula = true
function FloatValidate(objeto, aceitaVirgula, e)
{
	var key;
	var keychar;
	var keydecimal;
	var decimal=0;
	
	if(!e.keyCode)
	{
		key = e.which;
	}
	else
	{
		key = e.keyCode;
	}
	//}
	
	//alert(key);
	keychar = String.fromCharCode(key).toLowerCase();

	if(key==8 || key==9 || key==13 || key==35 || key==36 || key==37 || key==39 || key==46 || key==116)
	{
		if(!e.keyCode && keychar==".")
		{
			return false;
		}
		else
			return true;
	}
	
	for(var i=0;i<objeto.length;i++)
	{
		//alert(objeto.substr(i,1));
		if(objeto.substr(i,1)==",")
		{
			decimal = i;
		}
	}
	if(("0123456789").indexOf(keychar) > -1)
	{
		if(decimal == 0)
		{
			return true;
		}
		else
		{
			if(decimal+2>=objeto.length)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	else if((keychar==",") && (aceitaVirgula==true))
	{
		return (decimal == 0)
	}
	else
	{
		return false;
	}
}
//FUNCAO PARA MOSTRAR O TELEFONE DA REVENDA
function mostra_telefone(id, idv, f)
{
	fu_conta_click(id, 'FEI', idv);
	try
	{
		var omf = createXMLHTTP(); 
		omf.open("post", "ajax_busca_telefone.php", true);
		omf.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		omf.onreadystatechange=function() {
			if (omf.readyState==4){
				f.innerHTML = URLDecode(omf.responseText);
				f.onclick = function(){};
			}
		}
		omf.send("id=" + id);	
	}
	catch(e) { alert(e); }	
}
