function PrintElementID(id, pg) {
    var oPrint, oJan;
    oPrint     = window.document.getElementById(id).innerHTML;
    oJan     = window.open(pg);
    oJan.document.write(oPrint);
    oJan.history.go();
    oJan.window.print();
    oJan.close();
}


function showdiv(div) {
	if ($(div))
    $(div).style.display = 'block';
}

function hidediv(div) {
	if ($(div))
    $(div).style.display = 'none';
}

function getImg(div,id,path,title) {
	$(div).innerHTML = '<img src="'+path+'seminovos/'+id+' " alt="'+title+'" />';
}

function navNoticia() {
	function aparece() 		{ $('noticia_div_'+cont).style.display = 'block'; }
	function apareceSemi()  { $('seminovo_div_'+cont).style.display = 'block'; }
	function atualizaSemi() { Effect.Fade('seminovo_div_'+cont, {duration: 0.5, beforeSetup:apareceSemi, from: 0.0, to: 1.0} ); }
	function atualiza() 	{ Effect.Fade('noticia_div_'+cont, {duration: 0.5, beforeSetup:aparece, from: 0.0, to: 1.0} );	}
	
	var atual = cont;
	cont = cont+1;
		
	if(cont > 3) cont = 1;

	Effect.Fade('noticia_div_'+atual, {duration: 0.5, afterFinish: atualiza} );
	Effect.Fade('seminovo_div_'+atual, {duration: 0.5, afterFinish: atualizaSemi} );
}

var callFunc = function(name,video) {
	var isIE = navigator.appName.indexOf ("Microsoft") != -1;
	if(isIE) var movieID = window["FlashID_ie"];
	else var movieID = document["FlashID_ff"];

	movieID.SetVariable("_root.functionName", name);
	movieID.SetVariable("_root.video", video);
	movieID.SetVariable("_root.flag", true);
};

function navCondicao(anterior,proximo,cont,acao) {
	$('condicao_div_'+cont).style.display = 'none';
	if(acao == 'a') $('condicao_div_'+anterior).style.display = 'block';
	if(acao == 'p') $('condicao_div_'+proximo).style.display = 'block';
}

function getAcessorio(titulo,texto,img) {
	$('titulo').innerHTML 	= titulo;
	$('texto').innerHTML 	= texto;
	$('divImage').innerHTML = img;
}

function getImageLoja(img,alt) {
	var img = '<img src="'+img+'" alt="'+alt+'" title="'+alt+'" />';
	$('divImage').innerHTML = img;
}

function str_replace(haystack, needle, replacement) {
		var temp = haystack.split(needle);
	return temp.join(replacement);
}

function getImageCarro(img,serie) {
	var img = '<img src="'+img+'" alt="Série '+serie+'" title="Série '+serie+'" />';
	$('divImage').innerHTML = img;
}

function setaBlindado(fr) {
	if(fr.checked == true) $('valorBlind').value = '1';
	else				   $('valorBlind').value = '0';
}

function buscaVeiculo(localPath) {
	var url = '';
    var modelo 		= $('q').value;
    var ano 		= $('ano').value;
    var marca_id 	= $('marca_id').value;
    var de 			= $('de').value;
    var ate 		= $('ate').value;
    var blindado	= $('valorBlind').value;
    
    if(modelo != "" && modelo != "Modelo") 	url += '&modelo='+modelo;
    if(ano != "" && ano != "Ano") 			url += '&ano='+ano;
    if(marca_id != "")						url += '&marca_id='+marca_id;
    if(de != "" && de != "de $") 			url += '&de='+de;
    if(ate != "" && ate != "até $") 		url += '&ate='+ate;
    if(blindado == '1')						url += '&blindado=1';
	
	url = str_replace(url,'-','');
	url = str_replace(url,'/','');
	url = str_replace(url,'%','');
	
    window.location = localPath+'bmw-seminovos-lista-'+url;
}

function buscaNoticia(localPath) {
    var query = $('q').value;
    
    if(query != "" && query != "Palavra Chave") {
    	query = str_replace(query,'-','');
		query = str_replace(query,'/','');
		query = str_replace(query,'%','');
    	window.location = localPath+'bmw-noticias-busca-'+query;
    }
    else  alert('Digite uma palavra chave.');
}
// ------------------------------------------------
function selecionaValor(disparador,alvo,label,value, hidden, flag) {
    var campo = document.getElementById(alvo);
    var lista = document.getElementById(disparador);
    var busca_secao = document.getElementById(hidden);
    
    campo.innerHTML = label;
    busca_secao.value = value;
    lista.style.display = 'none';
    campo.parentNode.parentNode.style.position = 'static';
    
    if(flag == 'TRUE'){
        
        campoEntidade = document.getElementById('simula_campo_outra_univ');
        inputEntidade = document.getElementById('outra_universidade');
        classeEntidade = campoEntidade.className;
        
        if(label == 'Outra Entidade'){
            campoEntidade.className = "sim_campo_enable";
            inputEntidade.disabled = false;
            inputEntidade.focus();
        }
        else {
            campoEntidade.className = "sim_campo_disable";
            inputEntidade.value = "";
            inputEntidade.disabled = true;
        }
    }
}
// ------------------------------------------------
function abreSelect(field) {
    var campo = document.getElementById(field);
    campo.style.display=(campo.style.display == 'none' || campo.style.display == '')?'block':'none';
    campo.parentNode.style.position = 'relative';
}
//------------------------------------------------
function abre_diretorio() {
       window.open('?on=diretorio','revista','toolbar=0, location=0, directories=0, menubar=0, resizable=0, scrollbars=0, width=1020px, height=720px, top=0, left=0');
}
function drag_drop(id) {
   var descricao = $('descricao_'+id);
   var tbl       = $('tbl_'+id);
   var conteudo  = $('conteudo_'+id);
   var imagem    = $('seta_'+id);
   
   
   if(descricao.style.display == 'block') {
       imagem.src = 'resources/images/arrow_1.gif';
        descricao.style.display = 'none';
        conteudo.style.background = 'url(resources/images/bg_declaracao1.jpg)';
        tbl.style.color = '#002C77';
        
   } else {
     imagem.src = 'resources/images/arrow_2.gif';
     descricao.style.display = 'block';
     conteudo.style.background = '#41629A';
     tbl.style.color = '#FFFFFF';
   }
                    
}
 //--------------------------------------------------
 function busca() {
     if($('busca').value != '') 
        window.location = '?on=lista&in=busca&busca='+$('busca').value;
 }
 
 function open_info(id,img) {
    $('descricao_produto').style.display   = 'none';
    $('dados_tecnicos').style.display      = 'none';
    $('screenshots').style.display         = 'none';
    
    $(id).style.display  = 'block';
   
	if(img == '_btn_descricao')
	   $('info').innerHTML = '&nbsp; <a href="javascript:open_info(\'descricao_produto\',\'_btn_descricao\')" /><img src="resources/images/_btn_descricao_.jpg" id="_btn_descricao"/></a> <a href="javascript:open_info(\'dados_tecnicos\',\'_btn_dados_tecnicos\')" /><img src="resources/images/_btn_dados_tecnicos.jpg" id="_btn_dados_tecnicos"/></a>';
	else if(img == '_btn_dados_tecnicos') 
      $('info').innerHTML = '&nbsp; <a href="javascript:open_info(\'descricao_produto\',\'_btn_descricao\')" /><img src="resources/images/_btn_descricao.jpg" id="_btn_descricao"/></a> <a href="javascript:open_info(\'dados_tecnicos\',\'_btn_dados_tecnicos\')" /><img src="resources/images/_btn_dados_tecnicos_.jpg" id="_btn_dados_tecnicos"/></a>';
   //else  if(img == '_btn_screenshots') 
     //    $('info').innerHTML = '&nbsp; <a href="javascript:open_info(\'descricao_produto\',\'_btn_descricao\')" /><img src="resources/images/_btn_descricao.jpg" id="_btn_descricao"/></a> <a href="javascript:open_info(\'dados_tecnicos\',\'_btn_dados_tecnicos\')" /><img src="resources/images/_btn_dados_tecnicos.jpg" id="_btn_dados_tecnicos"/></a> <a href="javascript:open_info(\'screenshots\',\'_btn_screenshots\')" /><img src="resources/images/_btn_screenshots_.jpg" id="_btn_screenshots" /></a>';
      
}
//--------------------------------------------------
function scroll(position,id) {
    var timerTexto;
    var valor = 30;
    var total = 300;
    var cont = 0;
   
    if(position == 'right') {
        timerTexto =  setInterval(function () { 
	                                $(id).scrollLeft += valor;
	                                cont += valor;
	                                if(cont == total) { clearInterval(timerTexto) };
                                },10);
    }
    
    if(position == 'left') {
        timerTexto =  setInterval(function () { 
	                                $(id).scrollLeft -= valor;
	                                cont += valor;
	                                if(cont == total) clearInterval(timerTexto);
                                },10);
    }
}
//------------------------------------------------
function abreChat() {
	window.open('chat/cust_chat.php','chat','toolbar=0, location=0, directories=0, menubar=0, resizable=0, scrollbars=0, width=400px, height=490px, top=100, left=240');
}

//------------------------------------------------
function Filtra(campo) {
	var digits="ABCDEFGHIJKLMNOPQRSTUVXYWZabcdefghijklmnopqrstuvwxyz0123456789"
	var campo_temp
	
	for (var i=0;i<campo.value.length;i++){
	  campo_temp=campo.value.substring(i,i+1)
	  if (digits.indexOf(campo_temp)==-1){
	     campo.value = campo.value.substring(0,i);
	     break;
	  }
	}
}
//-------------------------------------------------
function isAlpha(valor){
	var digits="ABCDEFGHIJKLMNOPQRSTUVXYWZabcdefghijklmnopqrstuvwxyz0123456789";
	var campo_temp;
	
	var achou;
	for (var i=0;i<valor.length;i++) {
	  campo_temp=valor.substring(i,i+1)
	  if (digits.indexOf(campo_temp)==-1)
	  	achou = '1';
	}
	
	if(achou == '1') return false
	else return true;
}

//-------------------------------------------------

function abreJanela(url,pagina,detalhe) {
	window.open(url,pagina,detalhe);
}
// ------------------------------------------------
function abreSelect(field) {
	var campo = document.getElementById(field);
	campo.style.display=(campo.style.display == 'none' || campo.style.display == '')?'block':'none';
	campo.parentNode.style.position = 'relative';
}

// ------------------------------------------------
function limpaCampos(campo,padrao){
	
	var obj = document.getElementById(campo);
	obj.select();
	if (obj.value == padrao)
		obj.value = '';
	
}

// ------------------------------------------------
function restauraCampos(campo,padrao){
	
	var obj = document.getElementById(campo);
	if (obj.value == '')
		obj.value = padrao;
	
}

// ------------------------------------------------
function validaEmail(val){
	var rep=val.replace(/^[^0-9a-zA-Z_\[\]\.\-@]+$/,"");
	return(val==""||(val==rep&&(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(val))));
}

// ------------------------------------------------
function formataCampo(e,src,mask) {
	
	if(window.event) 
		_TXT = e.keyCode;
	else if(e.which)
		_TXT = e.which;
	
	if (!_TXT)
	 return false;
	 
	if(_TXT > 47 && _TXT < 58) { 
		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); 
		} 
	return true; 
	} else { 
		if (_TXT != 8) { 
			return false; 
		} 
		else { 
			return true; 
		}
	}
}

// ------------------------------------------------
function somenteNumero(e) {
	var tecla=(window.event)?event.keyCode:e.which;
	
	if ((tecla > 47) && (tecla < 58))
		return true;
	else{
		if (tecla != 8 && tecla != 0) 
			return false;
		else
			return true;
	}
}

// ------------------------------------------------
function checkCPFCNPJ(obj,tipo) {

	var cnpj = document.getElementById(obj).value;
	
	vr = cnpj;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	cnpj = vr;
	
	if (tipo == 'cnpj') {
		   soma1 = (cnpj.charAt(0) * 5) +
			   (cnpj.charAt(1) * 4) +
			   (cnpj.charAt(2) * 3) +
			   (cnpj.charAt(3) * 2) +
			   (cnpj.charAt(4) * 9) +
			   (cnpj.charAt(5) * 8) +
			   (cnpj.charAt(6) * 7) +
			   (cnpj.charAt(7) * 6) +
			   (cnpj.charAt(8) * 5) +
			   (cnpj.charAt(9) * 4) +
			   (cnpj.charAt(10) * 3) +
			   (cnpj.charAt(11) * 2);
	   resto = soma1 % 11;
	   digito1 = resto < 2 ? 0 : 11 - resto;
	   soma2 = (cnpj.charAt(0) * 6) +
			   (cnpj.charAt(1) * 5) +
			   (cnpj.charAt(2) * 4) +
			   (cnpj.charAt(3) * 3) +
			   (cnpj.charAt(4) * 2) +
			   (cnpj.charAt(5) * 9) +
			   (cnpj.charAt(6) * 8) +
			   (cnpj.charAt(7) * 7) +
			   (cnpj.charAt(8) * 6) +
			   (cnpj.charAt(9) * 5) +
			   (cnpj.charAt(10) * 4) +
			   (cnpj.charAt(11) * 3) +
			   (cnpj.charAt(12) * 2);
	   resto = soma2 % 11;
	   digito2 = resto < 2 ? 0 : 11 - resto;
	   return ((cnpj.charAt(12) == digito1) && (cnpj.charAt(13) == digito2));
	}
	else
	
		if (cnpj.length == 11)	{
		   soma1 = (cnpj.charAt(0) * 10) +
				   (cnpj.charAt(1) * 9) +
				   (cnpj.charAt(2) * 8) +
				   (cnpj.charAt(3) * 7) +
				   (cnpj.charAt(4) * 6) +
				   (cnpj.charAt(5) * 5) +
				   (cnpj.charAt(6) * 4) +
				   (cnpj.charAt(7) * 3) +
				   (cnpj.charAt(8) * 2);
		   resto = soma1 % 11;
		   digito1 = resto < 2 ? 0 : 11 - resto;
		   soma2 = (cnpj.charAt(0) * 11) +
				   (cnpj.charAt(1) * 10) +
				   (cnpj.charAt(2) * 9) +
				   (cnpj.charAt(3) * 8) +
				   (cnpj.charAt(4) * 7) +
				   (cnpj.charAt(5) * 6) +
				   (cnpj.charAt(6) * 5) +
				   (cnpj.charAt(7) * 4) +
				   (cnpj.charAt(8) * 3) +
				   (cnpj.charAt(9) * 2);
		   resto = soma2 % 11;
		   digito2 = resto < 2 ? 0 : 11 - resto;
		   return ((cnpj.charAt(9) == digito1) && (cnpj.charAt(10) == digito2));	
		}
		else 
		   return false;
	
	return true;
		   
}


function dataValida(val) {
	var reDate = /^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)?\d{2}$/;
	
	return reDate.test(val);
	//return false;
}

String.prototype.capitalize = function(){ //v1.0
return this.replace(/\w+/g, function(a){
    return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

function slideMenu(source) {
	var calc;
	
	if($(source).style.display == 'none')
		Effect.SlideDown(source, {duration:0.2});
	else 
		Effect.SlideUp(source, {duration:0.2});
}


function dica () {
	
	if($('dica_1').style.display == 'block') {
		$('dica_1').style.display = 'none';
		$('dica_4').style.display = 'block';
	}
		
	if($('dica_2').style.display == 'block') {
		$('dica_2').style.display = 'none';
		$('dica_1').style.display = 'block';
	}
	
	if($('dica_3').style.display == 'block') {
		$('dica_3').style.display = 'none';
		$('dica_2').style.display = 'block';
	}
	
	if($('dica_4').style.display == 'block') {
		$('dica_4').style.display = 'none';
		$('dica_3').style.display = 'block';
	}
	
}

function dica_prox () {
	
	if($('dica_1').style.display == 'block') {
		$('dica_1').style.display = 'none';
		$('dica_2').style.display = 'block';
	}
		
	if($('dica_2').style.display == 'block') {
		$('dica_2').style.display = 'none';
		$('dica_3').style.display = 'block';
	}
	
	if($('dica_3').style.display == 'block') {
		$('dica_3').style.display = 'none';
		$('dica_4').style.display = 'block';
	}
	
	if($('dica_4').style.display == 'block') {
		$('dica_4').style.display = 'none';
		$('dica_1').style.display = 'block';
	}
	
}

function bg1(valor) { $(valor).style.background = '#FFFFFF'; }
function bg2(valor) { if($(valor).value == '') $(valor).style.background = '#E9E9E9'; }

//funÃ§Ã£o para carregamento dinamico dos itens (AJAX)


var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var urlList = new Array();
var containerList = new Array();
var counter = 0;


function loadAjax()
{
    for (var i=0; i<arguments.length-1; i++)
    {
        urlList.push(arguments[i]);
        containerList.push(arguments[++i]);
    }

    ajaxpage(urlList[counter], containerList[counter]);
}

function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

function loadpage(page_request, containerid)
{
    if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
    {
        
        document.getElementById(containerid).innerHTML=page_request.responseText;
        counter++;
        if (counter < urlList.length)
        {
            ajaxpage(urlList[counter], containerList[counter]);
        } else
        {
            counter = 0;
            urlList = new Array();
            containerList = new Array();
        }
    }
    
    //gambiarra para fazer funcionar o lightbox. Como a funÃ§Ã£o vai ser chamada a todo momento, precisei usar o try e catch para evitar erros quando ela nÃ£o existir.
    try{
        myLytebox.updateLyteboxItems()
    }
    catch(e){
    //se der erro, nÃ£o faz nada....
    }
}


function OnlyNumbers(e) {

    if (window.event) //IE
    {
    tecla = e.keyCode;
    }

   else if (e.which) //FF
   {
    tecla = e.which;
   }
    //teclas dos numemros(0 - 9) de 48 a 57
   //techa==8 Ã© para permitir o backspace funcionar para apagar
    
       if ( (tecla >= 48 && tecla <= 57)||(tecla == 8 ) ) {
               return true;
          }
          else {
               return false;
          }
}


// FunÃ§Ã£o para retirar os espaÃ§os em branco do inÃ­cio e do fim da string.
function Trim(strTexto)
{
    // SubstitÃºi os espaÃ§os vazios no inicio e no fim da string por vazio.
    return strTexto.replace(/^\s+|\s+$/g, '');
}

// FunÃ§Ã£o para validaÃ§Ã£o de CEP.
function IsCEP(strCEP, blnVazio)
{

    // Caso o CEP nÃ£o esteja nesse formato ele Ã© invÃ¡lido!
    var objER = /^[0-9]{5}-[0-9]{3}$/;

    strCEP = Trim(strCEP)
    if(strCEP.length > 0)
        {
            if(objER.test(strCEP))
                return true;
            else
                return false;
        }
    else
        return false;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function clear_form_elements(form) {
	 
  $(form).find(':input').each(function() {
	 switch(this.type) {
	   case 'password':
	   case 'select-multiple':
	   case 'select-one':
	   case 'text':
	   case 'textarea':
  	   $(this).val('');
     break;
  	 case 'checkbox':
  	 //case 'radio':
  	   this.checked = false;
  	}
	});
	 
} 
