var comHTTPS = "https://";
var semHTTPS = "http://";
var semHTTPSComum = "ssComum";
var comHTTPSComum = "ssComum";
var rootPath = "www.webmotors.com.br/";

var pagamentoPath = comHTTPS+rootPath + "PagamentoOnline/";
var realPagPath = comHTTPS+rootPath + "RealPag/";
var sitePath = rootPath + "WebMotors/";
var backOfficePath = comHTTPS+rootPath + "BackOfficeUI/";
var fotosPath = comHTTPS+rootPath + "_fotos/";
var bannerPath = comHTTPS+rootPath + "_banner/";

var textoTelefone;
expireDate = new Date;
expireDate.setDate(expireDate.getDate()+365);
 
function openPopUpCentro(url, vwidth, vheight){

    
	/* banner aymore */
	//alteração feita para corrigir o popup versões na busca
	if(!(vwidth == 333))
		vheight = 155;
	
	if (url.indexOf('Canal') == '-1' )
	{
		//alteração feita para corrigir o popup versões na busca
		if(!(vwidth == 333))
			vwidth = 282;
		if(!(vheight==380))
		    vheight = 255;		
	}
	//alteração feita para corrigir o popup versões na busca
	if(!(vheight==380))
		vwidth = 282;
	
	//pega a resolução do visitante
	w = screen.width;
	h = screen.height;
	

	
	
	//divide a resolução por 2, obtendo o centro do monitor
	meio_w = w/2;
	meio_h = h/2;

	//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
	altura2 = vheight/2;
	largura2 = vwidth/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;
		
	window.open(url,'','toolbar=0,menubar=0,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2 + ',scroolbar=0');
}
function openPopUpCentroSemScroll(url, vwidth, vheight){
	//pega a resolução do visitante
	w = screen.width;
	h = screen.height;

	//divide a resolução por 2, obtendo o centro do monitor
	meio_w = w/2;
	meio_h = h/2;
	
	//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
	altura2 = vheight/2;
	largura2 = vwidth/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;

	window.open(url,'','toolbar=0,menubar=0,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2 + ',scroolbar=0');
}
function openPopUpCentroScroll(url, vwidth, vheight){
	//pega a resolução do visitante
	w = screen.width;
	h = screen.height;
	
	//divide a resolução por 2, obtendo o centro do monitor
	meio_w = w/2;
	meio_h = h/2;

	//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
	altura2 = vheight/2;
	largura2 = vwidth/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;
	
	window.open(url,'','resizable = yes ,status=yes,toolbar=no,menubar=no,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2 + ',scrollbars=yes');
}
function openPopUpCentroScrollCompleto(url, vwidth, vheight) {
    //pega a resolução do visitante
    w = screen.width;
    h = screen.height;

    //divide a resolução por 2, obtendo o centro do monitor
    meio_w = w / 2;
    meio_h = h / 2;

    //diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
    altura2 = vheight / 2;
    largura2 = vwidth / 2;
    meio1 = meio_h - altura2;
    meio2 = meio_w - largura2;

    window.open(url, '', 'location = yes,resizable = yes ,status=yes,toolbar=yes,menubar=yes,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2 + ',scrollbars=yes');
}
function setDetail(field)
	{
		var modulo_index=0;
		for(i=0;i<document.frmModuloUi.modulo.length;i++){
			if(document.frmModuloUi.modulo[i].checked == true){
				modulo_index = i;	
			}	
		}
		var detail = new String(field.value).split("|");
		document.frmModuloUi.index.value = modulo_index;
		field.checked = true;
		return false;
	}
	
function checkLengthTextArea(cp,len){
	if (cp.value.length > len){
	    cp.value = cp.value.substring(0, len);
	    return false;
    }else
    return true;
}
function copiaValor(origem,destino)
{
	if (document.getElementById(origem) != null && document.getElementById(destino) != null);
		document.getElementById(destino).value = document.getElementById(origem).value;
}		
function copiaTexto(origem, destino)
{
	if (document.getElementById(origem)!= null && document.getElementById(destino)!= null)
		document.getElementById(destino).value = document.getElementById(origem).options[document.getElementById(origem).selectedIndex].text;
}
function noPostBack(sNewFormAction)
{
	document.forms[0].action = sNewFormAction;
	document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
	document.forms[0].submit();
}
function orderByRefresh(sTipo)
{
	document.forms[0].hOrdenacao.value = sTipo;
	document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
	document.forms[0].submit();
}
function removerMinhaListaAnuncioMoto(valor) 
{
	refreshMinhaListaAnuncioMoto('E',valor,'Moto');
}

function adicionarMinhaListaAnuncioMoto(valor)
{
	refreshMinhaListaAnuncioMoto('I',valor, 'Moto');
}
function refreshMinhaListaAnuncioMoto(operacao,valor,tipoVeiculo)
{
	if (!document.createElement) {return true};
	var IFrameDoc; // our IFrame object
	
	var URL = semHTTPS + sitePath + semHTTPSComum + "/pgAtualizandoMinhaLista/pgAtualizandoMinhaLista.aspx?operacao=" + operacao + "&valor=" + valor + "&tipoVeiculo=" + tipoVeiculo;

	if (!IFrameObj && document.createElement) {
		try {
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id','RSIFrame'+valor);
			tempIFrame.style.border='0px';
			tempIFrame.style.width='0px';
			tempIFrame.style.height='0px';
			IFrameObj = document.body.appendChild(tempIFrame);
			
			if (document.frames) {
				IFrameObj = document.frames['RSIFrame'+valor];
			}
		} catch(exception) {
			iframeHTML='<iframe id="RSIFrame'+valor + '" style="';
			iframeHTML+='border:0px;';
			iframeHTML+='width:0px;';
			iframeHTML+='height:0px;';
			iframeHTML+='"><\/iframe>';
			document.body.innerHTML+=iframeHTML;
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('RSIFrame'+valor);
			IFrameObj.document.location.replace = function(location) {
				this.iframe.src = location;
			}
		}
	}
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		setTimeout('refreshMinhaListaAnuncio('+ operacao + ',' + valor + ')',100);
		return false;
	}
	
	if (IFrameObj.contentDocument) {
		// For NS6
		IFrameDoc = IFrameObj.contentDocument; 
	} else if (IFrameObj.contentWindow) {
		// For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	} else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	} else {
		return true;
	}
	IFrameDoc.location.replace(URL);	
	return false;
}
function enviar(valor,url)
{
	if (document.getElementById('hidFilter') != null)
		document.getElementById('hidFilter').value = "";
		
	if (document.getElementById('hidBlock') != null)
		document.getElementById('hidBlock').value = "";
	
	if (document.getElementById('hidCurPage') != null)
		document.getElementById('hidCurPage').value = "1";
		
	if (document.getElementById('hidBlock') != null)
		document.getElementById('hidBlock').value = "";
		
	if (document.getElementById('hidCurBlock') != null)
		document.getElementById('hidCurBlock').value = "0";
	
	if (document.getElementById('hidNavigation') != null)
		document.getElementById('hidNavigation').value = "";
	
	document.forms[0].hbusca.value = valor;
	noPostBack(url);
}
function copiaValor(origem,destino)
{
	if (document.getElementById(origem) != null && document.getElementById(destino) != null);
		document.getElementById(destino).value = document.getElementById(origem).value;
}
function CopiaRadio(origem, destino)
{
	if (document.getElementById(origem).checked)
		document.getElementById(destino).value = document.getElementById(origem).value;
}
function copiaTexto(origem, destino)
{
	if (document.getElementById(origem) != null && document.getElementById(destino) != null)
		if (document.getElementById(origem).selectedIndex != -1)
			document.getElementById(destino).value = document.getElementById(origem).options[document.getElementById(origem).selectedIndex].text;
}
function bindAno(control,valorSelecionado)	
{
	j=0;
	date = new Date();
	ano = date.getFullYear();
	obj = document.getElementById(control);
	
	obj.options[0] = new Option('', '');
	
	for (i=ano+1;i>1939;i--)
	{
		j++;
		obj.options[j] = new Option(i, i);
		
		if (i == valorSelecionado)
			obj.options[j].selected = true;
	}
}

function getCookie(cookieName) 
{
  thisCookie = document.cookie.split('; ')
  for (i = 0; i < thisCookie.length; i++) 
  {
	 if (cookieName == thisCookie[i].split('=')[0]) 
         {
         	return thisCookie[i].split('=')[1];
	 }	

  }
  return 0;
}

function delAnuncio(valor) 
{
   if (getCookie('ListaWebMotors')  != 0)
   {
	var cookieValor=getCookie('ListaWebMotors');
	document.cookie = 'ListaWebMotors='+cookieValor+';expires=' + expireDate.toGMTString();
   }

}
var IFrameObj; // our IFrame object
function removerMinhaListaAnuncio(valor) 
{
	refreshMinhaListaAnuncio('E',valor);
}
function adicionarMinhaListaAnuncio(valor) 
{
	refreshMinhaListaAnuncio('I',valor);
}

function detalheAnuncio(sNewFormAction,codidoAnuncio)
{
	document.getElementById('hidCodAnuncio').value = codidoAnuncio;
	noPostBack(sNewFormAction);
}

function refreshMinhaListaAnuncio(operacao,valor) 
{
	if (!document.createElement) {return true};
	var IFrameDoc; // our IFrame object
	
	var URL = semHTTPS + sitePath + semHTTPSComum + "/pgAtualizandoMinhaLista/pgAtualizandoMinhaLista.aspx?operacao=" + operacao + "&valor=" + valor;

	if (!IFrameObj && document.createElement) {
		try {
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id','RSIFrame'+valor);
			tempIFrame.style.border='0px';
			tempIFrame.style.width='0px';
			tempIFrame.style.height='0px';
			IFrameObj = document.body.appendChild(tempIFrame);
			
			if (document.frames) {
				IFrameObj = document.frames['RSIFrame'+valor];
			}
		} catch(exception) {
			iframeHTML='<iframe id="RSIFrame'+valor + '" style="';
			iframeHTML+='border:0px;';
			iframeHTML+='width:0px;';
			iframeHTML+='height:0px;';
			iframeHTML+='"><\/iframe>';
			document.body.innerHTML+=iframeHTML;
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('RSIFrame'+valor);
			IFrameObj.document.location.replace = function(location) {
				this.iframe.src = location;
			}
		}
	}
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		setTimeout('refreshMinhaListaAnuncio('+ operacao + ',' + valor + ')',100);
		return false;
	}
	
	if (IFrameObj.contentDocument) {
		// For NS6
		IFrameDoc = IFrameObj.contentDocument; 
	} else if (IFrameObj.contentWindow) {
		// For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	} else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	} else {
		return true;
	}
	IFrameDoc.location.replace(URL);	
	return false;
}

function clickTelefone(link,codigo,descricao,placa,cor,telefone) {
	// Rotina para contagem de clicks em paralelo //
	/*if (document.referrer.indexOf('https:') != -1)
		document.getElementById(link).innerHTML = "<img src='" + comHTTPS + sitePath + "outros/gravaTelefone.asp?codusado=" + codigo + "' width='1' height='1'>"
	else
		document.getElementById(link).innerHTML = "<img src='" + semHTTPS + sitePath + "outros/gravaTelefone.asp?codusado=" + codigo + "' width='1' height='1'>"*/
	//
	
	if (!document.createElement) {return true};
	var IFrameDoc; // our IFrame object
	
	if (document.referrer.indexOf('https:') != -1)
		var URL = comHTTPS + sitePath + "ssComum/pgClickTelefone/pgClickTelefone.aspx?link=" + link + "&CodigoAnuncio=" + codigo + "&DescricaoVeiculo=" + descricao +"&PlacaVeiculo="+placa+"&Cor="+cor+"&telefone=" + telefone;
	else
		var URL = semHTTPS + sitePath + "ssComum/pgClickTelefone/pgClickTelefone.aspx?link=" + link + "&CodigoAnuncio=" + codigo + "&DescricaoVeiculo=" + descricao +"&PlacaVeiculo="+placa+"&Cor="+cor+"&telefone=" + telefone;

	if (!IFrameObj && document.createElement) {
		try {
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id','RSIFrame');
			tempIFrame.style.border='0px';
			tempIFrame.style.width='0px';
			tempIFrame.style.height='0px';
			IFrameObj = document.body.appendChild(tempIFrame);
			
			if (document.frames) {
				IFrameObj = document.frames['RSIFrame'];
			}
		} catch(exception) {
			iframeHTML='<iframe id="RSIFrame'+valor + '" style="';
			iframeHTML+='border:0px;';
			iframeHTML+='width:0px;';
			iframeHTML+='height:0px;';
			iframeHTML+='"><\/iframe>';
			document.body.innerHTML+=iframeHTML;
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
			IFrameObj.document.location.replace = function(location) {
				this.iframe.src = location;
			}
		}
	}
	
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		setTimeout('clickTelefone(' + link + ','+ codigo + ',' + descricao + ',' + placa + ',' + cor + ',' + telefone + ')',10);
		return false;
	}
	
	if (IFrameObj.contentDocument) {
		// For NS6,
		IFrameDoc = IFrameObj.contentDocument; 
	} else if (IFrameObj.contentWindow) {
		// For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	} else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	} else {
		return true;
	}
	IFrameDoc.location.replace(URL);	
	return false;
}
function exibeTelefone(link, texto, erro)
{
	if (erro != "")
		document.getElementById('lblErro').innerHTML = erro;
	else
		document.getElementById(link).innerHTML = texto;
}

function exibeMensagem(operacao, mensagem)
{
	switch (operacao)
	{
		case 'I':
			__doPostBack('lnkMinhaLista', '')
			break;
		case 'E':
			__doPostBack('lnkRemoverMinhaLista', '')
			break;
		default:
			document.getElementById('lblErro').innerHTML = mensagem;
			break;
	}
}
function reload(img)
{
	var reload;
	reload = document.getElementById(img).src;
	document.getElementById(img).src = '';
	document.getElementById(img).src = reload;
}
function setValueDiv(name,valor)
{
	var label = document.getElementById(name);
	if (label != null) label.innerHTML = valor;
}
function setVisibilityDiv(name,valor)
{
	var label = document.getElementById(name);	
	if (label != null) 
	{ 
	 label.style.visibility=valor;
	 if (valor=='hidden')
		label.style.display='none';
	else
		label.style.display='';

	}
}


// FUNÇÃO QUE COLOCA O BANNER SKY
function banner(id){
	if (screen.width>=1024){
		return '<scr'+'ipt>MaestroAd(' + id + ');</scr'+'ipt>';
	}else{
		return '';
	}
}
function ContaCaracteres(campo,cont,tam){
   //intCaracteres = 200 - document.formadd.comentario.value.length;
   var intCaracteres;
   intCaracteres = tam - campo.value.length;
   if (intCaracteres > 0) {
      //document.formadd.caracteres.value = intCaracteres;
      cont.value = intCaracteres;
      return true;
   }
   else {
      //document.formadd.caracteres.value = 0;
      cont.value = 0;
      //document.formadd.comentario.value = document.formadd.comentario.value.substr(0,200)
      campo.value = campo.value.substr(0,tam);
      return false;
   }
}
// chamada para abrir PopUp de Video e Foto Animada
function openPopUpCentroVideoFotoAnimada(url, tipo){
	/*	tipo = 1 video, 2 foto animada, 
		areaSite = C Clone, W WebMotors, P Patrocinador, S SiteAutomatico, F Feirao  */

	vwidth = 370;
	vheight = 450;
	
	// foto animada
	if (tipo != null && tipo == "2")
		var vheight = 440;
	
	var qs = new Querystring(url);
	// Quando for Clone.
	if (url.indexOf('areaSite') != '-1' && qs.get("areaSite") != null && qs.get("areaSite") == "W")
	{
		var vwidth = 500;
		var vheight = 610;

		// foto animada
		if (tipo != null && tipo == "2")
			var vheight = 599;
	}
		
	//pega a resolução do visitante
	w = screen.width;
	h = screen.height;
	
	//divide a resolução por 2, obtendo o centro do monitor
	meio_w = w/2;
	meio_h = h/2;

	//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
	altura2 = vheight/2;
	largura2 = vwidth/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;
		
	window.open(url,'','toolbar=0,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2);
}
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Array();
	this.get=Querystring_get;
	this.set=Querystring_set;
	this.queryStr=GerarQueryString;
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
	// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		var item = new Option(name, value);
		this.params[this.params.length] = item;
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
    var value=null;
    for (i=0; i<this.params.length; i++)
    {
        if (this.params[i].text==key)
        {
            value = this.params[i].value;
            break;
        }
    }
	if (value==null) value=default_;
	
	return value
}

function Querystring_set(key, value) {
	// This silly looking line changes UNDEFINED to NULL
	var inserir = true;
	var name = unescape(key);
	var valor = unescape(value);
    for (i=0; i<this.params.length; i++)
    {
        if (this.params[i].text==name)
        {
            inserir = false;
            this.params[i].value = valor;
            break;
        }
    }
	
	if (inserir)
	{
		var item = new Option(name, value);
		this.params[this.params.length] = item;
	}
}

function GerarQueryString()
{
    var queryStr = "";
    for (i=0; i<this.params.length; i++)
    {
        queryStr += (queryStr == "") ? "?" : "&";
        queryStr += this.params[i].text+"="+this.params[i].value;
    }
    return queryStr;
}

/*************************************************************************
        funcao que representa um link
        recebe como parametro document.getElementById('idAncora')
        usado no log de aba do detalhe do comprar
**************************************************************************/
function Ancora(anc)
{
	var querystr;
	
    this._ancora = anc;
    if (this._ancora.href == null) return;
    
    if ((this._ancora.href.indexOf("?") == null) ||
        (this._ancora.href.indexOf("?") == -1))
    {
		querystr = '';
		this.pagina = this._ancora.href;
    }
    else
    {
		querystr = this._ancora.href.substring(this._ancora.href.indexOf("?")+1,this._ancora.href.length);
		this.pagina = this._ancora.href.substring(0, this._ancora.href.indexOf("?"));
	}
    this._querystring = new Querystring(querystr);
    this._alterarURL = AlterarURL;
}

function AlterarURL()
{
    this._ancora.href = this.pagina+this._querystring.queryStr();
}

function EsqueceuSuaSenha(formID, divID, urlEnviar, secao)
{
	tb_showThickbox('Esqueceu' + divID, semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgEsqueceuSuaSenha/pgEsqueceuSuaSenha.aspx?secao=' + secao + '&pagina=' + urlEnviar + 'TB_iframe=true&amp;width=730&amp;height=332&amp;inlineId=' + divID, false, formID);
}

function VerTelefoneAnuncio(formID, divID, tipoVeiculo, codigoAnuncio, local, novoUsado, canal, anuncioInativo) {
    if (anuncioInativo == null)
        tb_showThickbox('VerTelefone', semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgVerTelefone/pgVerTelefone.aspx?TipoVeiculo=' + tipoVeiculo + '&CodigoAnuncio=' + codigoAnuncio + '&Local=' + local + '&novoUsado=' + novoUsado + '&Canal=' + canal + 'TB_iframe=true&amp;width=271&amp;height=314&amp;inlineId=' + divID, false, formID, 'no');
    else
        tb_showThickbox('VerTelefoneInativo', '#TB_inline?width=270&amp;height=135&amp;inlineId=modalAnuncioInativoTelefoneLocalizacao', false, 'frmUI');
}

function VerVideoLightbox(formID, divID, codigoAnuncio, tipo, areaSite, canal, permiteFinanciamento)
{
	/*	tipo = Carro
		tipo = Moto
		areaSite = C Clone, W WebMotors, P Patrocinador, S SiteAutomatico, F Feirao  */

    var vwidth = 354;
	var vheight = 487;

	var queryString = '?cod=' + codigoAnuncio + '&tipo=' + tipo + '&areaSite=' + areaSite + '&canal=' + canal + '&financiamento=' + permiteFinanciamento;
	var urlAbrir = semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgVideo/pgVideo.aspx' + queryString + 'TB_iframe=true&amp;width=' + vwidth + '&amp;height=' + vheight + '&amp;inlineId=' + divID;
	
	tb_showThickbox('VerVideo', urlAbrir, false, formID);
}

function VerFotoAnimadaLightbox(formID, divID, codigoAnuncio, tipo, areaSite, canal, permiteFinanciamento)
{
	/*	tipo = Carro
		tipo = Moto
		areaSite = C Clone, W WebMotors, P Patrocinador, S SiteAutomatico, F Feirao  */

    var vwidth = 354;
	var vheight = 488;

	var queryString = '?cod=' + codigoAnuncio + '&tipo=' + tipo + '&areaSite=' + areaSite + '&canal=' + canal + '&exibirVideo=S' + '&financiamento=' + permiteFinanciamento;
	var urlAbrir = semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgFotoAnimada/pgFotoAnimada.aspx' + queryString + 'TB_iframe=true&amp;width=' + vwidth + '&amp;height=' + vheight + '&amp;inlineId=' + divID;
	
	tb_showThickbox('VerFotoAnimada', urlAbrir, false, formID);
}

function PreviaFotoAnimadaLightbox(formID, divID, codigoAnuncio, codigoArquivo, tipo, areaSite, canal)
{
	/*	tipo = Carro
		tipo = Moto
		areaSite = C Clone, W WebMotors, P Patrocinador, S SiteAutomatico, F Feirao  */

	var vwidth = 350;
	var vheight = 455;

	var queryString = '?cod=' + codigoAnuncio + '&codArquivo=' + codigoArquivo + '&tipo=' + tipo + '&areaSite=' + areaSite + '&canal=' + canal + '&exibirAnimacao=S';
	var urlAbrir = semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgFotoAnimada/pgFotoAnimada.aspx' + queryString + 'TB_iframe=true&amp;width=' + vwidth + '&amp;height=' + vheight + '&amp;inlineId=' + divID;
	
	tb_showThickbox('VerFotoAnimada', urlAbrir, false, formID);
}

function PreviaFotoAnimadaLightboxExemplo(formID, divID, codigoAnuncio, codigoArquivo, tipo, areaSite, canal) {
    /*	tipo = Carro
    tipo = Moto
    areaSite = C Clone, W WebMotors, P Patrocinador, S SiteAutomatico, F Feirao  */

    var vwidth = 459;
    var vheight = 404;

    var queryString = '?cod=' + codigoAnuncio + '&codArquivo=' + codigoArquivo + '&tipo=' + tipo + '&areaSite=' + areaSite + '&canal=' + canal + '&exibirAnimacao=S';
    var urlAbrir = semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgFotoAnimada/pgFotoAnimadaPrevia.aspx' + queryString + 'TB_iframe=true&amp;width=' + vwidth + '&amp;height=' + vheight + '&amp;inlineId=' + divID;

    tb_showThickbox('VerFotoAnimada', urlAbrir, false, formID);
}

function VerCidadesLightbox(formID, divID, uf, travarEstado, campoUF, campoCidade)
{	
	tb_showThickbox('VerCidades', semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgCidades/pgCidades.aspx?uf=' + uf + '&travarEstado=' + travarEstado + '&campoUF=' + campoUF + '&campoCidade=' + campoCidade + 'TB_iframe=true&amp;width=402&amp;height=371&amp;inlineId=' + divID, false, formID);
}

function DenunciarAnuncioLightbox(formID, divID, codigoAnuncio, tipoVeiculo)
{
	tb_showThickbox('Denunciar' + divID, semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgDenunciar/pgDenunciar.aspx?codigoAnuncio=' + codigoAnuncio + '&tipoVeiculo=' + tipoVeiculo + 'TB_iframe=true&amp;width=404&amp;height=405&amp;inlineId&amp;inlineId=' + divID, false, formID);
}

function ComparacaoMercadoLightbox(formID, divID, codigoAnuncio, tipoVeiculo) 
{
    if (tipoVeiculo == '1')
        tb_showThickbox('Comparacao' + divID, semHTTPS + sitePath + '/Compra/carrosDetalheComparacaoMercado/carros-detalhe-comparacao-mercado.aspx?cod=' + codigoAnuncio + '&tipo=' + tipoVeiculo + 'TB_iframe=true&amp;width=665&amp;height=460&amp;inlineId&amp;inlineId=' + divID, false, formID);
    else
        tb_showThickbox('Comparacao' + divID, semHTTPS + sitePath + '/Compra/motosDetalheComparacaoMercado/motos-detalhe-comparacao-mercado.aspx?cod=' + codigoAnuncio + '&tipo=' + tipoVeiculo + 'TB_iframe=true&amp;width=665&amp;height=460&amp;inlineId&amp;inlineId=' + divID, false, formID);
}
function MateriasRelacionadasLightbox(formID, divID, codigoAnuncio, tipoVeiculo) 
{
    if (tipoVeiculo == '1')
        tb_showThickbox('MateriasRelacionadas' + divID, semHTTPS + sitePath + '/Compra/carrosDetalheMateriasRelacionadas/carros-detalhe-materias-relacionadas.aspx?cod=' + codigoAnuncio + '&tipo=' + tipoVeiculo + 'TB_iframe=true&amp;width=554&amp;height=426&amp;inlineId&amp;inlineId=' + divID, false, formID);
    else
        tb_showThickbox('MateriasRelacionadas' + divID, semHTTPS + sitePath + '/Compra/motosDetalheMateriasRelacionadas/motos-detalhe-materias-relacionadas.aspx?cod=' + codigoAnuncio + '&tipo=' + tipoVeiculo + 'TB_iframe=true&amp;width=554&amp;height=426&amp;inlineId&amp;inlineId=' + divID, false, formID);
}

function MapaLocalizacaoLightbox(formID, divID, codigoAnuncio, tipoVeiculo, CarroMotoTipo, anuncioInativo) {
    if (CarroMotoTipo == '1') {
        if (anuncioInativo == null)
            tb_showThickbox('Localizacao' + divID, semHTTPS + sitePath + '/Compra/carrosDetalheLocalizacao/carros-detalhe-localizacao.aspx?cod=' + codigoAnuncio + '&tipo=' + tipoVeiculo + 'TB_iframe=true&amp;width=548&amp;height=477&amp;inlineId&amp;inlineId=' + divID, false, formID);
        else
            tb_showThickbox('VerLocalizacaoInativo', '#TB_inline?width=270&amp;height=135&amp;inlineId=modalAnuncioInativoTelefoneLocalizacao', false, 'frmUI');
    }
    else {
        if (anuncioInativo == null)
            tb_showThickbox('Localizacao' + divID, semHTTPS + sitePath + '/Compra/motosDetalheLocalizacao/motos-detalhe-localizacao.aspx?cod=' + codigoAnuncio + '&tipo=' + tipoVeiculo + 'TB_iframe=true&amp;width=548&amp;height=477&amp;inlineId&amp;inlineId=' + divID, false, formID);
        else
            tb_showThickbox('VerLocalizacaoInativo', '#TB_inline?width=270&amp;height=135&amp;inlineId=modalAnuncioInativoTelefoneLocalizacao', false, 'frmUI');
    }
}

function EnviarParaUmAmigoVia(formID, divID, codigosAnunciosCarros, codigosAnunciosMotos, secao, pagina)
{
    tb_showThickbox('EnviarParaUmAmigo' + divID, semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgIndiqueUmAmigo/pgIndiqueUmAmigo.aspx?secao=' + secao + '&CodigosAnunciosCarros=' + codigosAnunciosCarros + '&CodigosAnunciosMotos=' + codigosAnunciosMotos + '&pagina=' + pagina + 'TB_iframe=true&amp;width=374&amp;height=470&amp;inlineId=' + divID, false, formID);
}

function LocalidadePopupGoogleMaps(formID, divID, codigoAnuncio, EnderecoOrigem)
{
	tb_showThickbox('GoogleMaps', semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgLocalizacaoGoogleMap/pgLocalizacaoGoogleMap.aspx?Id=' + codigoAnuncio + '&endOrigem=' + EnderecoOrigem + 'TB_iframe=true&amp;width=620&amp;height=500&amp;inlineId=' + divID, false, formID);
}

function adicionarEvento(object, attachMetod, attachFunction)
{
	if(object.attachEvent)
	{
		object.attachEvent(attachMetod,attachFunction);
	}
	else if(object.addEventListener)
	{
		object.addEventListener(attachMetod.replace('on',''),attachFunction,false);
	}
	else
	{
		eval(object+'.'+attachMetod+'='+attachFunction);
	}
}

/****************************************************
Metodo utilizado para disparar evento de javascript
ex:	disparar o onchange de uma combo
    no atributo object enviar document.getElementById(combo)
    no attachMetod enviar 'change'
    fireEvent funciona no IE 
    dispatchEvent funciona no FireFox
****************************************************/
function dispararEvento(object, attachMetod)
{
	if (object != null)
	{
		if(object.fireEvent)
		{
			var oEvent = 'on'+attachMetod;
			object.fireEvent(oEvent);
		}
		else if(object.dispatchEvent)
		{
			var oEvent = document.createEvent('HTMLEvents');
			oEvent.initEvent(attachMetod,true,true);
			object.dispatchEvent(oEvent);
		}
	}
}

function selecionarItemCombo(combo, valor)
{
	var i = 0;
	
	for (i = 0; i < combo.options.length; i++)
	{
		if (combo.options[i].value == valor)
		{
			combo.selectedIndex = i;
			dispararEvento(combo, 'change');
			break;
		}
	}
}

function AjudaEditarFoto()
{
	tb_showThickbox('Ajuda editar foto', semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgAjudaEditarFoto/pgAjudaEditarFoto.aspx?TB_iframe=true&amp;width=675&amp;height=323&amp;inlineId=Ajudaeditarfoto', false, 'frmUI');
}

function EsqueceuSeuEmail(formID, divID, urlEnviar, secao)
{
	tb_showThickbox('EsqueceuSenha-' + divID, comHTTPS + sitePath + comHTTPSComum + '/ssPopup/pgEsqueceuSeuEmail/pgEsqueceuSeuEmail.aspx?secao=' + secao + '&pagina=' + urlEnviar + 'TB_iframe=true&amp;width=356&amp;height=177&amp;inlineId=' + divID, false, formID);
}

function AjudaEditarFotoVender()
{
	tb_showThickbox('Ajuda editar foto', comHTTPS + sitePath + comHTTPSComum + '/ssPopup/pgAjudaEditarFoto/pgAjudaEditarFoto.aspx?TB_iframe=true&amp;width=675&amp;height=323&amp;inlineId=Ajudaeditarfoto', false, 'aspnetForm');
}

function ComoAnunciar()
{
	tb_showThickbox('Ajuda como anunciar', semHTTPS + sitePath + semHTTPSComum + '/ssPopup/pgComoAnunciar/pgComoAnunciar.aspx?TB_iframe=true&amp;width=675&amp;height=323&amp;inlineId=Ajudaeditarfoto', false, 'frmUI');
}


function addBannerMaestro(id){
	if (screen.width>=1024){
		return '<scr'+'ipt>MaestroAd(' + id + ');</scr'+'ipt>';
	}else{
		return '';
	}
}

// detalhe do carro e moto
function acertarLink(idAncora, item)
{
	var anc = new Ancora(document.getElementById(idAncora));
	var valorQueryStr = anc._querystring.get("aba");
	if (valorQueryStr == null || valorQueryStr == "")
	    valorQueryStr = item;
	else
	{
	    var inserir = true;
	    var itensSel = valorQueryStr.split(',');
	    valorQueryStr = "";
	    for (i=0; i<itensSel.length; i++)
	    {
	        valorQueryStr += (valorQueryStr=="" ? "" : ",")+itensSel[i];
	        if (itensSel[i] == item)
	            inserir = false;
	    }
	    if (inserir)
	        valorQueryStr += (valorQueryStr=="" ? "" : ",")+item;
	}
    anc._querystring.set("aba", valorQueryStr);
    anc._alterarURL();
}

function TrocarAbaDetalhe(objSumir, objAparecer, objClassOn, objClassOff, codigoAnuncio, chave, tipo, hdn, ancoraLocalizacao, ancoraMateriais, ancoraComparacao)
{
	objSumir.style.display = "none";
	objAparecer.style.display = "";
	objClassOn.className = "on";
	objClassOff.className = "off";
	if (hdn.value == "true")
	{
		if (codigoAnuncio != null &&
		    codigoAnuncio != '' &&
		    chave != null &&
		    chave != '')
		{
			if (tipo == 'C')
				WebmotorsInserirLogAbaDetalheCarro(codigoAnuncio, chave);
			else
				WebmotorsInserirLogAbaDetalheMoto(codigoAnuncio, chave);
				
			hdn.value = "false";
			
			if (ancoraLocalizacao != null)
				acertarLink(ancoraLocalizacao.id, chave);
			if (ancoraComparacao != null)
				acertarLink(ancoraComparacao.id, chave);
			if (ancoraMateriais != null)
				acertarLink(ancoraMateriais.id, chave);
		}
	}
}
// detalhe do carro
function BannerSiteDireto(url){window.open('http://' +  url );}
function BannerEstoqueDireto(site, codigo, tipoAnuncio, tipoVeiculo)
{
	if (tipoVeiculo == 'C')
		document.location.href = semHTTPS + sitePath + 'compra/carrosResultado/carros-resultado.aspx?codRevendedor='+codigo;
	if (tipoVeiculo == 'M')
		document.location.href = semHTTPS + sitePath + 'compra/motosResultado/motos-resultado.aspx?codRevendedor='+codigo;
}
function BannerSiteAutomaticoDireto(url){window.open(url);}		

function ImprimirAnuncio(hdnCodigoAnuncio, hdnTipoAnuncio, tipo)
{	
    var anuncio = document.getElementById(hdnCodigoAnuncio).value;
    var tipoAnuncio = document.getElementById(hdnTipoAnuncio).value;
    var url ;
    if (tipo == 'C')
		url = semHTTPS + sitePath + 'compra/_popups/imprimir-anuncio-carro.aspx?cod=' + anuncio + '&tipo=' + tipoAnuncio;   
    else
		url = semHTTPS + sitePath + 'compra/_popups/imprimir-anuncio-moto.aspx?cod=' + anuncio + '&tipo=' + tipoAnuncio;
    UTIL.popup.open(url, {width:612, height:450});
}

function WebmotorsInserirAnuncioMinhaLista_Pagina(msg)
{
    if (msg == "sucesso")
        tb_showThickbox('Salvar em Minha Lista', '#TB_inline?width=254&amp;height=160&amp;inlineId=modalAnuncioSalvo', 'modalAnuncioSalvo', null);
    else if (msg == "limite")
        tb_showThickbox('Salvar em Minha Lista', '#TB_inline?width=254&amp;height=160&amp;inlineId=modalAnuncioNaoSalvo', 'modalAnuncioNaoSalvo', null);
    else
        alert("Ocorreu erro no momento de salvar o an" + String.fromCharCode(250) + "ncio na sua lista.");
}

function MostrarMensagemQuantidadeExcedida()
{
    tb_showThickbox('Quantidade Excedida', '#TB_inline?width=270&amp;height=170&amp;inlineId=modalQuantidadeExcedida&amp;fecharmodal=N', 'modalQuantidadeExcedida', null);
}

function MostrarMensagemQuantidadeExcedidaMobile() {
    document.getElementById('qtdMaxima').style.display = 'block';
    document.getElementById('qtdMaxima').style.position = 'relative';
    document.getElementById('SemResultado').style.visibility = 'hidden';
}

function exibirMsgAnuncianteNaoAceitaTroca()
{
    tb_showThickbox('Incluir', '#TB_inline?width=270&amp;height=135&amp;inlineId=modalTroca', false, 'frmUI');
}

//Verifica o total de caracteres digitado na proposta
function contaChar(obj){ 
    var total = 1000;
    var tam = 0;
    if (obj != null)
	    tam = obj.value.length;
    str="";  
    str=str+tam;
    var restante = document.getElementById('Restante');
    restante.innerHTML = total - str;
    if (tam > total){  
	    restante.innerHTML = 0;
    } 
} 
function SetImage(img, imgPrincipal)
{
	path = document.getElementById(img).src;
	path = path.replace('pequena', 'grande');
	document.getElementById(imgPrincipal).src = path;
}
function SomenteNumeros(e) {
    if (e.charCode == 8 || e.charCode == 37 || e.charCode == 39)
        return;

    if (!(e.charCode >= 48 && e.charCode <= 57)) {
        e.preventDefault();
        e.stopPropagation();
    }
}

function GerarHtmlPaginaPreviewTabela(id, html, vwidth, vheight)
{ w = screen.width; h = screen.height; meio_w = w / 2; meio_h = h / 2; altura2 = vheight / 2; largura2 = vwidth / 2; meio1 = meio_h - altura2; meio2 = meio_w - largura2; var novaJanela = window.open('', 'preview' + id, 'resizable = yes ,status=yes,toolbar=no,menubar=no,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2 + ',scrollbars=yes'); novaJanela.document.write('<html><body>' + html + '</body></html>'); }
