var objBrow,LAST_ERR_VALUE="";
var ERRO=REPET_ERR=false;
var LAST_FIELD=CURRENT_FIELD=LAST_ERR_FIELD=null;
var SZ_DATE=8,
SZ_CEP=8,
SZ_MONEY=10,
SZ_CONTACORRENTE=6,
SZ_AGENCIA=4,
SZ_FLOAT=10,
SZ_CPF=11,
SZ_CNPJ=14,
SZ_CPF_CNPJ=SZ_CNPJ,
SZ_MONTH_YEAR=6,
SZ_TIME=4,
MAX_VALUE=9999999.99;

function bloqueiaEnter(ev) {
	if (ev.keyCode==13) {
		ev.returnValue=false;
		}
}

function simulaClickOnEnter(ev,field_button) {
	if (ev.keyCode==13) {
		ev.returnValue=false;
		field_button.click();
		}
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

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_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_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];}
}


// description: draggable modal windows
// coding: softcomplex.com
// data: 09/21/2007

var N_BASEZINDEX =10000;
var RE_PARAM = /^\s*(\w+)\s*\=\s*(.*)\s*$/;

// this function makes the document numb to the mouse events by placing the transparent layer over it

function do_nothing() {
    return;
}

function f_putScreen (b_show) {
	if (b_show == null && !window.b_screenOn)
		return;

	if (!b_show) {
		//window.b_screenOn = false;
		if (e_screen) {
            e_screen.style.display = 'none';

            // attach event
            if (document.removeEventListener) {
                document.removeEventListener('mousemove', f_dragProgress, false);
                window.removeEventListener('resize', f_putScreen, false);
                window.removeEventListener('scroll', f_putScreen, false);
            }
            if (window.detachEvent) {
                document.detachEvent('onmousemove', f_dragProgress);
                window.detachEvent('onresize', f_putScreen);
                window.detachEvent('onscroll', f_putScreen);
            }
            else {
                document.onmousemove = do_nothing;
                window.onresize = do_nothing;
                window.onscroll = do_nothing;
            }
            document.body.removeChild(e_screen);
            window.e_screen = null;
        }
        return;
	}

	// create the layer if doesn't exist
	if (window.e_screen == null) {
        window.e_screen = document.createElement("div");
		e_screen.innerHTML = "&nbsp;";
		document.body.appendChild(e_screen);

		e_screen.style.position = 'absolute';
		e_screen.id = 'eScreen';

		// attach event
		if (document.addEventListener) {
			document.addEventListener('mousemove', f_dragProgress, false);
			window.addEventListener('resize', f_putScreen, false);
			window.addEventListener('scroll', f_putScreen, false);
		}
		if (window.attachEvent) {
			document.attachEvent('onmousemove', f_dragProgress);
			window.attachEvent('onresize', f_putScreen);
			window.attachEvent('onscroll', f_putScreen);
		}
		else {
			document.onmousemove = f_dragProgress;
			window.onresize = f_putScreen;
			window.onscroll = f_putScreen;
		}
	}

	// set properties
	var a_docSize = f_documentSize();
	e_screen.style.left = a_docSize[2] + 'px';
	e_screen.style.top = a_docSize[3] + 'px';
	e_screen.style.width = a_docSize[0] + 'px';
	e_screen.style.height = a_docSize[1] + 'px';
	e_screen.style.zIndex = N_BASEZINDEX + a_windows.length * 2 - 1;
	e_screen.style.display = 'block';
}

// returns the size of the document
function f_documentSize () {

var n_scrollX = 0,
	n_scrollY = 0;

	if (typeof(window.pageYOffset) == 'number') {
		n_scrollX = window.pageXOffset;
		n_scrollY = window.pageYOffset;
	}
	else if (document.body && (document.body.scrollLeft || document.body.scrollTop )) {
		n_scrollX = document.body.scrollLeft;
		n_scrollY = document.body.scrollTop;
	}
	else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		n_scrollX = document.documentElement.scrollLeft;
		n_scrollY = document.documentElement.scrollTop;
	}

	if (typeof(window.innerWidth) == 'number')
		return [window.innerWidth, window.innerHeight, n_scrollX, n_scrollY];
	if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
		return [document.documentElement.clientWidth, document.documentElement.clientHeight, n_scrollX, n_scrollY];
	if (document.body && (document.body.clientWidth || document.body.clientHeight))
		return [document.body.clientWidth, document.body.clientHeight, n_scrollX, n_scrollY];
	return [0, 0];
}

function f_dialogOpenDiv (divToShow, s_title, s_features) {
    if (!window.a_windows)
		window.a_windows = [];

	// parse parameters
	var a_featuresStrings = s_features.split(',');
	var a_features = [];
	for (var i = 0; i < a_featuresStrings.length; i++)
		if (a_featuresStrings[i].match(RE_PARAM))
			a_features[String(RegExp.$1).toLowerCase()] = RegExp.$2;

	// create element for window
	var n_nesting = a_windows.length;

	var e_window = divToShow;
    e_window.style.display='block';
    e_window.style.position = 'absolute';
    _op_left=getAbsPos(divToShow.offsetParent,"Left");
    _op_top=getAbsPos(divToShow.offsetParent,"Top");
    _op_left=0;
    _op_top=0;
    var n_width  = a_features.width  ? parseInt(a_features.width)  : 300;
	var n_height = a_features.height ? parseInt(a_features.height) : 200;
	var a_docSize = f_documentSize ();
	e_window.style.left = ((a_features.left ? parseInt(a_features.left) : ((a_docSize[0] - n_width)  / 2) + a_docSize[2])- _op_left) + 'px';
	e_window.style.top  = ((a_features.top  ? parseInt(a_features.top)  : ((a_docSize[1] - n_height) / 2) + a_docSize[3])- _op_top) + 'px';
    e_window.style.zIndex = N_BASEZINDEX + a_windows.length * 2 + 2;
    e_window.offsetParent.style.position="static";

      var flashes = [];
    flashes = document.getElementsByTagName("object");
    for (var f=0; f < flashes.length; f++){
        if(!isTagInsideDiv(divToShow, flashes[f])){
            flashes[f].style.visibility = "hidden";
        }
    }

    var select = [];
    flashes = document.getElementsByTagName("select");
    for (var f=0; f < flashes.length; f++){
        if(!isTagInsideDiv(divToShow, flashes[f])){
            flashes[f].style.visibility = "hidden";
        }
    }

//    e_window.innerHTML = divToShow.innerHTML;
//	document.body.appendChild(e_window);
	a_windows[n_nesting] = e_window;

    // put the screen
	f_putScreen(true);
}

function isTagInsideDiv(div, obj){

    if(div.id == null || div.id == undefined || div.id == ''
            || obj == null || obj == undefined){
        return false;
    }

    if(obj.id == div.id){
        return true;
    }

    return isTagInsideDiv(div, obj.parentNode);
}

function f_dialogOpen (s_url, s_title, s_features) {
	if (!window.a_windows)
		window.a_windows = [];

	// parse parameters
	var a_featuresStrings = s_features.split(',');
	var a_features = [];
	for (var i = 0; i < a_featuresStrings.length; i++)
		if (a_featuresStrings[i].match(RE_PARAM))
			a_features[String(RegExp.$1).toLowerCase()] = RegExp.$2;

	// create element for window
	var n_nesting = a_windows.length;

	var e_window = document.createElement("div");
	e_window.style.position = 'absolute';
	var n_width  = a_features.width  ? parseInt(a_features.width)  : 300;
	var n_height = a_features.height ? parseInt(a_features.height) : 200;
	var a_docSize = f_documentSize ();
	e_window.style.left = (a_features.left ? parseInt(a_features.left) : ((a_docSize[0] - n_width)  / 2) + a_docSize[2]) + 'px';
	e_window.style.top  = (a_features.top  ? parseInt(a_features.top)  : ((a_docSize[1] - n_height) / 2) + a_docSize[3]) + 'px';
	e_window.style.zIndex = N_BASEZINDEX + a_windows.length * 2 + 2;

      var flashes = [];
    flashes = document.getElementsByTagName("object");
    for (var f=0; f < flashes.length; f++){
        flashes[f].style.visibility = "hidden";
    }

    var select = [];
    flashes = document.getElementsByTagName("select");
    for (var f=0; f < flashes.length; f++){
        flashes[f].style.visibility = "hidden";
    }

    var iframes = [];
    iframes = document.getElementsByTagName("iframe");
    for (var f=0; f < iframes.length; f++){
        iframes[f].style.visibility = "hidden";
    }

    e_window.innerHTML =
		'<table border="0" class="' +
		(a_features.css ? a_features.css : 'dialogWindow') +
		'" style="z-index:10;"><tr><td><iframe id="ifrm" frameBorder="0" name="'+s_title+'" style = "border:0 solid black" scrolling="' + (a_features.scrollbars ? a_features.scrollbars : "no")  + '" width="' + n_width +
		'" height="' + n_height +
		(s_url!=''?'" src="' + s_url + '"':'')+'>  </iframe></td></tr></table>';
//    alert(e_window.innerHTML);
	document.body.appendChild(e_window);
    var txt = document.createTextNode(" ");
    document.body.appendChild(txt);

    a_windows[n_nesting] = e_window;

    // put the screen
	f_putScreen(true);
}

function f_dialogCloseDiv () {

	var n_nesting = a_windows.length - 1;

    a_windows[n_nesting].style.display='none';
	a_windows[n_nesting] = null;
	a_windows.length = n_nesting;

    var flashes = [];
    flashes = document.getElementsByTagName("object");
    for (var f=0; f < flashes.length; f++){
        flashes[f].style.visibility = "visible";
    }

    var select = [];
    flashes = document.getElementsByTagName("select");
    for (var f=0; f < flashes.length; f++){
        flashes[f].style.visibility = "visible";
    }
    // move the screen

    f_putScreen(n_nesting);

}

function f_dialogClose () {

	var n_nesting = a_windows.length - 1;

    a_windows[n_nesting].style.display='none';
    // destroy element
	if (a_windows[n_nesting].removeNode)
		a_windows[n_nesting].removeNode(true);
	else if (document.body.removeChild)
		document.body.removeChild(a_windows[n_nesting]);
	a_windows[n_nesting] = null;
	a_windows.length = n_nesting;

    var flashes = [];
    flashes = document.getElementsByTagName("object");
    for (var f=0; f < flashes.length; f++){
        flashes[f].style.visibility = "visible";
    }

    var select = [];
    flashes = document.getElementsByTagName("select");
    for (var f=0; f < flashes.length; f++){
        flashes[f].style.visibility = "visible";
    }

    var iframes = [];
    iframes = document.getElementsByTagName("iframe");
    for (var f=0; f < iframes.length; f++){
        iframes[f].style.visibility = "visible";
    }

    // move the screen

    f_putScreen(n_nesting);

}


// drag'n'drop functions
function f_dragStart (s_name, e_event) {
	if (!e_event && window.event) e_event = window.event;

	// save mouse coordinates
	window.n_mouseX = e_event.clientX;
	window.n_mouseY = e_event.clientY;
	window.e_draggedWindow = window.a_windows[s_name];
	return false;
}
function f_dragProgress (e_event) {
	if (!e_event && window.event) e_event = window.event;
	if (!e_event || window.e_draggedWindow == null) return;

	var n_newMouseX = e_event.clientX;
	var n_newMouseY = e_event.clientY;

	window.e_draggedWindow.style.left = (parseInt(window.e_draggedWindow.style.left) - window.n_mouseX + n_newMouseX) + 'px';
	window.e_draggedWindow.style.top  = (parseInt(window.e_draggedWindow.style.top)  - window.n_mouseY + n_newMouseY) + 'px';

	window.n_mouseX = n_newMouseX;
	window.n_mouseY = n_newMouseY;
}

function f_dragEnd () {
	window.e_draggedWindow = null;
}

// end draggable modal windows


function linkexterno(pagina) {
	window.open("../comum/linkexterno.jsp?pagina="+pagina,"","top=0,left=0,width=800,height=400,menubar=yes, toolbar=yes,status=yes, resizable=yes,scrollbars=yes,location=yes")
}

function validarTexto(campo,nomecampo) {
	if(campo.value=="") {
		alert("Por favor, preencha o campo "+nomecampo);
		campo.focus();
		return false;
		}
	else
		return true;
}

function validarSelect(campo,nomecampo) {
	if(campo.value=="") {
		alert("Por favor, escolha uma opção no campo "+nomecampo);
		campo.focus();
		return false;
		}
	else
		return true;
}

function validarRadio(campo,nomecampo) {
	var preenchido=false;
	var i;
	for(i=0;i<campo.length;i++) {
		if(campo[i].checked)
			preenchido=true;
	}
					
	if(!preenchido) {
		alert("Por favor, escolha uma opção no campo "+nomecampo);
		campo[0].focus();
		return false;
		}
	else
		return true;
}

function checaCPF(CPF) {
 	var i;
	var numCPF='';
	for(i=0;i<CPF.length;i++) {
		if(!isNaN(CPF.substring(i,i+1))) {
			numCPF+=CPF.substring(i,i+1);}
	}
	CPF=numCPF
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(10)))
		return false;
	return true;
 }

function _has(s,a){
s=String(s);
if(typeof(a)=="string")return s.indexOf(a)!=-1;
else{
	for(var i=0;i<a.length;i++)if(s.indexOf(a[i])!=-1)return true;
	return false;
}
}

function trim(s){return String(s).replace(/^\s+/,"").replace(/\s+$/,"");}
function _TRIM(){
var s=0,e=this.length;
while(s<e&&this.charAt(s)==' ')s++;
while(e>0&&this.charAt(e-1)==' ')e--;
return this.slice(s,e);
}
String.prototype.trim=_TRIM;

function justNumbersStr(s){return String(s).replace(/\D*/g,"");}
function onlySameNumber(s){return isNumeric(s)&& (new RegExp("^("+s.charAt(0)+")(\\1)*$")).test(s);}

function brow(){if(typeof objBrow!="object")objBrow=new Browser();return objBrow;}

function Browser(){
this.name=this.platform="Unknown";
this.majorver=this.version=this.minorver="";
this.mozilla=false;
this.init=_Init;
this.getName=function(){return this.name};
this.getMinorver=function(){return this.minorver};
this.getMajorver=function(){return this.majorver};
this.getVersion=function(){return parseFloat(this.version,10)};
this.getPlatform=function(){return this.platform}; 
this.isIE=function(){return(this.name=="IE")};
this.isNetscape=function(){return(this.name=="Netscape")};
this.isMozilla=function(){return this.mozilla};
this.isWindows=function(){return _has(this.platform,["Windows","WinNT"])};
this.isWinNT=function(){return _has(this.platform,["WinNT","Windows NT"])};
this.isWin95=function(){return _has(this.platform,["Win95","Windows 95"])};
this.isWin98=function(){return _has(this.platform,["Win98","Windows 98"])};
this.isLinux=function(){return _has(this.platform,"Unix")};
this.isMac=function(){return _has(this.platform,"Mac");};
this.init();
}
function _Init(){
var ua=navigator.userAgent,t="",ts="",i,bv;
bv=ua.slice(0,ua.indexOf("("));
ts=ua.slice(ua.indexOf("(")+1,ua.indexOf(")")).split(";");
for(i=0;i<ts.length;i++){
	t=ts[i].trim();
	if(_has(t,["MSIE","Opera"]))bv=t;
	else if(_has(t,["X11","SunOS","Linux"]))this.platform="Unix";
	else if(_has(t,["Mac","PPC","Win"]))this.platform=t;
}
var idx=bv.indexOf("MSIE"),lo="";
if(idx>=0)bv=bv.slice(idx);
if(bv.slice(0,7)=="Mozilla"){
	lo="";
	this.name="Netscape";
	if(ua.indexOf("Gecko/")!=-1){
		if(/Netscape/.test(ua)){
			var v=/([^\/]+)\s*$/.exec(ua);
			if(v&&v.length>1)lo=v[1]+" ";
		}else{
			this.mozilla=true;
			var v=/rv:([^\)]+)\)/.exec(ua);
			if(v&&v.length>1)lo=v[1]+" ";
		}
	}
	if(lo=="")lo=bv.slice(8);
}else if (bv.slice(0,4)=="MSIE"){
	this.name="IE";lo=bv.slice(5);
}else if (bv.slice(0,27)=="Microsoft Internet Explorer"){
	this.name="IE";lo=bv.slice(28);
}else if (bv.slice(0,5)=="Opera"){
	this.name="Opera";lo=bv.slice(6);
}
lo=lo.trim();
i=lo.indexOf(" ");
if(i>=0)this.version=lo.slice(0,i);
else this.version=lo;
j=this.version.indexOf(".");
if(j>=0){
	this.majorver=this.version.slice(0,j);
	this.minorver=this.version.slice(j+1);
}else this.majorver=this.version;
}


function removeCaracs(f,type){
	var vr=unformatField(f.value,type);
	if(f.value!=vr)f.value=vr;
	focusNetscape(f);
}

function formatType(f,tp,msgErr,adarg1,adarg2){
var vr=unformatField(f.value,tp);
LAST_FIELD=f;
var ret=isValidValue(vr,tp,adarg1,adarg2);
if(!ret){
	showError(tp,msgErr);
	return false;
}else f.value=getFmtValue((typeof ret=="boolean")?vr:ret,tp);
ERRO=false;
return true;
}

function focusNetscape(f){
CURRENT_FIELD=f;
var b=brow();
if(b.isNetscape()){
	if(ERRO){LAST_FIELD.focus();ERRO=false;}
}else if(b.isIE()&& parseInt(b.getMajorver(),10)>4)if(f.select)f.select();
}

function formatCamp(campo,tp,par1,par2,par3){
var ie=(brow().isIE()&&!brow().isMac()),v=brow().getVersion();

var nArg=formatCamp.arguments.length;
ERRO=false;
var vr=trim(campo.value);
if(!campo|| !vr ||vr.length==0){
//	if(/^(neg_)?(money|money2)$/.test(tp))campo.value="0,00";
	return false;
}
if(nArg==2)par1="";
if(tp=="interval"){
	if(nArg<=4) par3="";
	return formatType(campo,tp,par3,par1,par2);
}else return formatType(campo,tp,par1);
}

function validaConteudo(event,el,tp)
{
var t=(typeof event.which!="undefined"&& event.which!=null?event.which:event.keyCode),key=String.fromCharCode(t);
if(t<20)return true;
var tp_sp=/^sp_/.test(tp);
if(/^((neg_)?(numeric|float(\d{0,1})|money(\d{0,1})))$/.test(tp)){
	return isNumeric(key)||(!/numeric/.test(tp)&&key==","&&el.value.indexOf(",")==-1)||(/^neg_/.test(tp)&&key=="-" && el.value.indexOf("-")==-1);
}else if(/^(sp_)?alfanumeric$/.test(tp))
	return isAlfaNumeric(key)||(tp_sp && key==" ");
else if(/^(sp_)?textnumber$/.test(tp))
	return isTextNumber(key)||(tp_sp && key==" ");
else{
	switch(tp){
		case "email":
		case "uppercase":return true;
		case "text":return isAlfa(key)|| /[ ]/.test(key);
		case "text_entry":return isTextNumber(key)||/[\.\-\/\,=]|\s/.test(key);
        case "number": return isTextNumber(key);
        case "default":return !/'|"/.test(key);
		default:return isNumeric(key);
	}
}
}

function saltaCampo(ev,field,tp,size){
	var tc,max,nargs=saltaCampo.arguments.length;
	if(/^(neg_)?float/.test(tp))max=(nargs>3)?size:SZ_FLOAT;
	else if(/^(neg_)?money/.test(tp)){
		if(!verifyMaxValue(field.value))max=(nargs>3)?size:SZ_MONEY;
		else field.value="0,00";
	}else if(/^(date|month_year|time|cpf|cnpj|cpf_cnpj|cep|contacorrente|agencia)$/.test(tp))
		max=eval("SZ_"+tp.toUpperCase());
	else if(/^(text|text_entry|uppercase|interval|phone|(sp_)?alfanumeric|(sp_)?textnumber|default|(neg_)?numeric|email)$/.test(tp))
		max=size;
	tc=brow().isNetscape()?ev.which:ev.keyCode;
	if(String(field.value).length>=max && tc>=48){autoSkip(field);return true;}
	else return false;
}

function unformatField(valor,tipo){
	var vr=(typeof valor=="object")?valor.value:String(valor);
	var t=(arguments.length<1)?"default":String(tipo);
	if(!trim(vr)||trim(vr).length==0) return "";
	if(/^(date|month_year|time|cep|(neg_)?numeric|interval)$/.test(t))
		vr=(/^neg_/.test(t)&&vr.indexOf("-")==0?"-":"")+justNumbersStr(vr);
	else if(/^((neg_)?(float(\d{0,1})|money(\d{0,1})))$/.test(t))vr=toFloat(vr,_getNDec(t));
	else{
        if(/^(contacorrente)$/.test(t)){
            vr=justNumbersStr(vr);
            vr=repeatStr(vr,"0",SZ_CONTACORRENTE);
        }
		else if(/^(cpf|cnpj|cpf_cnpj)$/.test(t)){
			vr=justNumbersStr(vr);
			var isCPF=tipo=="cpf"||(tipo=="cpf_cnpj" && vr.length<=SZ_CPF);
			vr=repeatStr(vr,"0",isCPF?SZ_CPF:SZ_CNPJ);
			if(parseInt(vr,10)==0)vr="";
		} else if(t=="email")vr=trim(vr)
	}
	if(typeof valor=="object")valor.value=vr;
	else return vr;
}

function isValidValue(vr,tp,adarg1,adarg2){
var re,isNum=isNumeric(vr);
if(/^(cep)$/.test(tp))
	return isNum && vr.length==eval("SZ_"+tp.toUpperCase());
else if(/^(cep)$/.test(tp))
    return isNum && vr.length==eval("SZ_"+tp.toUpperCase());
else if(/^((neg_)?(float(\d{0,1})|money(\d{0,1})))$/.test(tp))
	return (!/^neg_/.test(tp)&&vr.indexOf("-")!=-1?false:isFloatNumber(vr));
else if(/textnumber$/.test(tp))
	return isTextNumber((tp.indexOf("sp_")==0)?removeStr(vr," "):vr);
else if(/text_entry$/.test(tp))
	return isTextNumber(vr.replace(/[\.\-\/\,=]|\s/g,""));
else if(/alfanumeric$/.test(tp))
	return isAlfaNumeric((tp.indexOf("sp_")==0)?removeStr(vr," "):vr);
else{
	switch(tp){
		case "time":
			switch(vr.length){
				case 1:vr="0"+vr+"00";break;
				case 2:vr+="00";break;
				case 3:vr="0"+vr+"0";break;
			}
			vr=repeatStr(vr,"0",4,"right");
			return(isNum && /^([0-1]\d[0-5]\d)|(2[0-3][0-5]\d)$/.test(vr))?vr:null;
		case "date":
			var obj=new DateValidation(vr);
			return (isNum && obj.isDate())?obj:null;
		case "month_year":
			var obj=new DateValidation("01"+vr);
			return (isNum && obj.isDate())?obj:null;
		case "text":return isAlfa(vr.replace(/[ ]/g,""));
		case "email":return isEmail(vr);
		case "cpf":return isCPF(vr);
		case "cnpj":return isCNPJ(vr);
		case "cpf_cnpj":return (vr.length <=SZ_CPF)?isCPF(vr):isCNPJ(vr);
		case "interval":
			vr=parseInt(vr,10);
			return vr>=adarg1 && vr<=adarg2;
		case "default":return !/'|"/.test(vr);
		default:return true;
	}
}
}

function isNumeric(v){return /^[0-9]+$/.test(v);}
function isAlfa(v){return /^[a-zA-ZáéíóúçãõâêôàÁÉÍÓÚÇÃÕÂÊÔÀ]+$/.test(v);}
function isAlfaNumeric(v){return /^[0-9a-zA-Z]+$/.test(v);}
function isTextNumber(v){return /^[0-9a-zA-ZáéíóúçãõâêôàÁÉÍÓÚÇÃÕÂÊÔÀ]+$/.test(v);}
function isFloatNumber(n){return /^\-?\d+(,\d+|\d*)$/.test(n);}
function isEmail(email)
{
	var v=trim(email);
	// exp1: Trata erros grosseiros (@...@ , .. , .@ , etc.)
	// exp2: Garante carac. validos e estrutura: <usuario>@<maquina>
	// exp3: Garante no minimo um ponto depois do "@" 
	var exp1= /(\@.*\@)|(.*\.\..*)|(.*\@\..*)|(^\.)|(\.$)|(\@\/)|(.*\@\-.*)|(.*\.$)/;
	var exp2= /^[_\w\d][\w\d\_\/\-\.]*\@[\d\w\-\.]+[0-9A-z]$/;
	var exp3= /.*\@.*[\.].*/;
	return(!exp1.test(v)&& exp2.test(v)&& exp3.test(v));
}

function _getNDec(t){
	var arr=t.match(/(\d+)\s*$/);
	return arr?parseInt(arr[1],10):2;
}

function invertStr(s){
	var t="",i;
	for(i=0;i<s.length;i++)t=s.charAt(i)+t;
	return t;
}

function removeStr(src,arg){
	var v=(typeof arg=="string")?[arg]:arg;
	var r="";
	for(var i=0;i<v.length;i++)r=changeStr(src,v[i],"");
	return r;
}

function repeatStr(src,str,size,orient){
	var r=String(src);
	if(!orient)orient="left";
	while(r.length < size)r=orient.toLowerCase()=="right"?(r+str):(str+r);
	return r;
}

function repeatNStr(vr,n){
var r="",i;
for(i=0;i<n;i++)r+=vr;
return r;
}

function changeStr(src,from,to)
{
	src=String(src);
	var i,li=0,lFrom= from.length,dst="";
	while((i=src.indexOf(from,li))!=-1){
		dst+=src.substring(li,i)+to;
		li=i+lFrom;
	}
	dst+=src.substring(li);
	return dst;
}

function DateValidation(d){
	this.dtSrc=d;
	this.dtValue="";
	this.isDate=_isDate;
	this.getDateValue=function() {return(this.dtValue);};
	this.getMonthDateValue=function() {return(this.dtValue.slice(3));} 
}
function _isDate(){
	var vrs=/^(0[1-9]|[1-2][0-9]|3[0-1])(0[1-9]|1[0-2])(\d{2}|19\d{2}|20\d{2})$/.exec(justNumbersStr(this.dtSrc));
	if(!vrs || vrs.length<4)return false;
	var d=parseInt(vrs[1],10),m=parseInt(vrs[2],10),a=parseInt(vrs[3],10);		
	if(a<100)a+=(a<30?2000:1900);
	if(/^(4|6|9|11)$/.test(m) && d==31)return false;
	if(m==2){
		var bissexto=(((a%4==0)&&a%100!=0)||a%400==0);
		if(d>29 ||(d==29 && !bissexto))return false;
	}
	this.dtValue=repeatStr(d,"0",2)+"/"+repeatStr(m,"0",2)+"/"+a;
	return true;
}
function DateObj(d){
	d=trim(d);
	if(!d)return;
	var t=d.length;
	if(t==10||t==8||t==6){
		this.isValid=true;
		this.srcDate=d;
		this.date=d.replace(/\//g,"");
		this.day=this.date.slice(0,2);
		this.month=this.date.slice(2,4);
		this.year=this.date.slice(4);
		var a=parseInt(this.year,10);
		if(a<100){a+=(a<30?2000:1900);this.year=String(a);}

		this.daysTo=_DaysTo;
		this.lesserThan=function(d){return Number(this.year+this.month+this.day) < Number(d.year+d.month+d.day)};
		this.biggerThan=function(d){return !this.lesserThan(d)&& !this.equal(d)};
		this.equal=function(d){return this.date==d.date.replace(/\//g,"");};
		this.biggerOrEqualThan=function(d){return this.biggerThan(d)||this.equal(d)};
		this.lesserOrEqualThan=function(d){return this.lesserThan(d)||this.equal(d)};
	}else this.isValid=false;
}
function _DaysTo(d){
	var msDay=24*60*60*1000;
	var s=new Date(this.month+"/"+this.day+"/"+this.year);
	var f=new Date(d.month+"/"+d.day+"/"+d.year);
	return Math.floor((f.getTime()-s.getTime())/msDay);
}
function isInInterval(dtIn,dtFi,pIn,pFi,msg1,msg2,msg3){
	var iDt=new DateObj(dtIn),fDt=new DateObj(dtFi);
	var iPer=new DateObj(pIn),fPer=new DateObj(pFi);
	if(!msg1||msg1=="")msg1='Data inicial maior que a data final. Digite novamente.';
	if(!msg2||msg2=="")msg2='Data inicial fora do período disponível. Digite novamente.';
	if(!msg3||msg3=="")msg3='Data final fora do período disponível. Digite novamente.';
	if(iDt.isValid&&fDt.isValid&&iPer.isValid&&fPer.isValid){
		if(fDt.lesserThan(iDt)){alert(msg1);return false;}
		else if(iDt.lesserThan(iPer)){alert(msg2);return false;}
		else if(fPer.lesserThan(fDt)){alert(msg3);return false;}
		return true;
	}
}
function isInDaysLimit(dtIn,dtFi,dias,msg){
	if(!msg)msg="O intervalo entre as datas não pode ultrapassar "+dias+(dias>1?" dias":" dia")+". Digite novamente.";
	var sDt=new DateObj(dtIn),fDt=new DateObj(dtFi);
	if(sDt.isValid && fDt.isValid){
		if((sDt.daysTo(fDt)+1)>dias){alert(msg);return false;}
		return true;
	}
}

function getFmtValue(vr,tp){
	if(tp=="cpf_cnpj")tp=(vr.length <=SZ_CPF)?"cpf":"cnpj";
	if(/^(neg_)?money/.test(tp))return fmtMoney(vr,_getNDec(tp));
	else{
		switch(tp){
			case "time":return vr.slice(0,2)+":"+vr.slice(2,4); 
            case "contacorrente":return vr.slice(0,5)+"-"+vr.slice(5,6);
			case "date":return vr.getDateValue();
			case "month_year":return vr.getMonthDateValue();
			case "cep":return vr.slice(0,5)+"-"+vr.slice(5,8);
			case "uppercase":return vr.toUpperCase();
			case "cpf":return vr.slice(0,3)+"."+vr.slice(3,6)+"."+ vr.slice(6,9)+ "-"+vr.slice(9,11);
			case "cnpj":return vr.slice(0,2)+"."+vr.slice(2,5)+"."+vr.slice(5,8)+"/"+vr.slice(8,12)+"-"+vr.slice(12,14);
            case "phone":return vr.slice(0,4)+"-"+vr.slice(4,8);
			default:return vr;
		}
	}
}
function fmtMoney(vr,ndec){
	var neg=vr.indexOf("-")==0;
	if(verifyMaxValue(vr)){ERRO=true;return "0,00";}
	vr=toFloat(vr,ndec);
	var vraux="",p,pDec=vr.indexOf(","),vrDec=vr.slice(pDec+1);
	for(var i=pDec;i>(neg?1:0);i--){
		p=i-pDec;
		if(i!=pDec&&(p%3==0))vraux+=".";
		vraux+=vr.charAt(i-1);
	}
	return (neg?"-":"")+invertStr(vraux)+","+vrDec;
}
function setMaxValue(vr){MAX_VALUE=vr;}
function verifyMaxValue(vr){return vr.length>0 &&(parseFloat(vr)>MAX_VALUE);}
function toFloat(src,ndec){
   src=trim(src);
	if(!/^\-?([0-9]|\.)*\,{0,1}[0-9]*$/.test(src)||src.charAt(0)==".")return src;
	var tam=src.length,pDec=src.indexOf(",");
	if(src.length==0)src="0";
	if(pDec==-1){
		var p=src.indexOf(".");
		if(p!=-1&&p==(tam-ndec-1))src=src.replace(/\.(\d*)$/,",$1");
		else return removeStr(src,".")+","+repeatNStr("0",ndec);
		pDec=src.indexOf(",");
	}
	src=removeStr(src,".");
	if(pDec==0)return "0"+src+repeatNStr("0",ndec+1-src.length);
	else{
		if(pDec>(tam-ndec-1))src+=repeatNStr("0",pDec-(tam-ndec-1));
		pDec=src.indexOf(",");
		return parseInt(src.slice(0,pDec),10)+src.slice(pDec,pDec+ndec+1);
	}
}


function showError(type,msgU){
ERRO=true;
var b=brow(),canShow=true;
if(typeof type=="object"){
	alert(msgU);
	focusCamp(type);
	return;
}
if(b.isIE() && parseInt(b.getMajorver(),10)<5){
	if(CURRENT_FIELD && LAST_ERR_FIELD==CURRENT_FIELD && LAST_ERR_VALUE==CURRENT_FIELD.value){
		REPET_ERR=true;
		CURRENT_FIELD.value=LAST_ERR_VALUE="";
		LAST_ERR_FIELD=null;
		canShow=false;
	}else{
		LAST_ERR_FIELD=CURRENT_FIELD;
		LAST_ERR_VALUE=(CURRENT_FIELD?CURRENT_FIELD.value:null);
		REPET_ERR=false;
	}
}
if(canShow){
	var m=". Digite novamente.";
	switch(type){
		case "date":msg="Data inválida"+m;break;
		case "time":msg="Hora inválida"+m;break;
		case "cep":msg="CEP inválido"+m;break;
		case "email":msg="E-mail incorreto"+m;break;
		case "cpf":msg="CPF inválido"+m;break;
		case "cnpj":msg="CNPJ inválido"+m;break;
		case "cpf_cnpj":msg="CPF/CNPJ inválido"+m;break;
		case "month_year":msg="Mês e ano inválidos"+m;break;
		default:msg="Valor inválido"+m;
	}
	alert((!msgU || msgU=="")?msg:msgU);
}
if(brow().isNetscape())LAST_FIELD.value="";
if(LAST_FIELD)LAST_FIELD.focus();
}
function autoSkip(field,orient){
	var ind=-1,f=field.form;
	for(i=0;i<f.elements.length;i++)
		if(field==f.elements[i]){ind=i;break;}
	focusCampByPos(f,ind,orient);
}

function focusCampByPos(fr,ind,orient){
	orient=orient?orient:"down";
	var iNext=(orient=="down"?1:-1),el;
	if((typeof fr.elements[ind+iNext])=="undefined"){
      if(ind!=-1)if(fr.elements[ind]&&fr.elements[ind].blur)fr.elements[ind].blur();
		return;
   }
	for(var i=ind+iNext;i<fr.elements.length;i+=iNext){
		el=fr.elements[i];
		if(/^(text|password|select.*|radio|checkbox.*)$/.test(el.type) && !el.disabled){el.focus();return;}
   }
	if(fr.elements[ind]&&fr.elements[ind].blur)fr.elements[ind].blur();
}

function isCNPJ(cnpj) 
{
	if(cnpj.length==0) return false;
	cnpj= trim(cnpj);
	var digs=[],i;
	for(i=0; i<14; i++)
		digs[i]= parseInt(cnpj.charAt(i),10);
	var sDig=0,soma=0,resto=0,dVer1=-1,dVer2=-1;
	var fat1=[5,4,3,2,9,8,7,6,5,4,3,2];
	var fat2=[6,5,4,3,2,9,8,7,6,5,4,3,2];
	for(var i=0; i<12; i++)
		sDig+= (digs[i]*fat1[i]);
	resto= sDig % 11;
	dVer1= (resto==0)?0:(11 - resto)%10;
	if(digs[12]==dVer1) 
	{
		sDig=resto=0;
		for(i=0;i<13;i++) 
			sDig+= (digs[i]*fat2[i]);
		resto=sDig%11;
		dVer2=(resto==0)?0:(11-resto)%10;
	}
	return digs[12]==dVer1 && digs[13]==dVer2;
}

function isCPF(cpf)
{
	var OK;
	cpf= justNumbersStr(trim(cpf));
	if(onlySameNumber(cpf)) return false;
	var size=cpf.length;
	if(size>10)
	{
		var vr=cpf.substring(0,size-2)
		var resto= getVerificationDigit(vr);
		OK= resto==parseInt(cpf.charAt(size-2));
		if(OK)
		{
			vr+=resto;
			resto=getVerificationDigit(vr);
			OK= resto==parseInt(cpf.charAt(size-1));
		}
	}
	return OK;
}

function getVerificationDigit(S)
{
	var s=0,i;
	var inv=invertStr(justNumbersStr(S));
   for(i=0;i<inv.length;i++)
        s+=(i+2)*parseInt(inv.charAt(i));
   s*=10;
   return (s%11)%10;
}

function textCounter(field, maxlimit) {
if (field.value.length > maxlimit) 
	field.value = field.value.substring(0, maxlimit);
}

function addwishlist(ref) {
	var wishlistatual=getCookie("wishlistatual");
	var newitem=ref+'||';
	if(wishlistatual!=null && wishlistatual!='') {
		if(wishlistatual.indexOf('||'+newitem)==-1) {
			wishlistatual=wishlistatual+newitem;
			register_cookie('wishlistatual',wishlistatual);
		}
	} else {
		register_cookie('wishlistatual','||'+newitem);
	}
	alert("O Carro foi adicionado à sua lista.");
}

function verwishlist() {
	var wishlistatual=getCookie("wishlistatual");
	if(wishlistatual==null || wishlistatual=='') {
		alert("Sua lista está vazia\nUse o link disponível ao lado dos anúncios\npara adicionar carros à sua lista");
	} else {
		janela=window.open("../ache/wishlist.jsp?popup=1&lista="+wishlistatual,'wishlist','top=100,left=100,width=650,height=500,scrollbars=yes');
		janela.focus();
	}
}

function getCookie(Name)
	{
	var search = Name + "=";
	if (document.cookie.length > 0)
		{
		offset = document.cookie.indexOf(search)
		if (offset != -1)
			{
			offset += search.length
			end = document.cookie.indexOf(";", offset)
			if (end == -1)
				end = document.cookie.length
			return unescape(document.cookie.substring(offset, end))
			}
		}
	}

function setCookie(name, value, expire)
	{
	document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
	}

function register_cookie(nome,valor)
	{
	var c_today = new Date();
	var c_expires = new Date();
	c_expires.setTime(c_today.getTime() + 1000*60*60*24*5);
	setCookie(nome,valor,c_expires);
	}

function checkAll(formId, cName, check ) {
    for (i=0,n=formId.elements.length;i<n;i++)
        if (formId.elements[i].name.indexOf(cName) !=-1)
            formId.elements[i].checked = check;
}
function confirma(texto,obj) {
	acao=obj.onclick;
	obj.onclick="";
	if(confirm("Você tem certeza que deseja "+texto+" ?"))
		acao.call();
	else
		obj.onclick=acao;
	return false;
}

function icarrosToogleStatus(idToToogle) {
    var elemento=MM_findObj(idToToogle);
	icarrosToogleStatusElement(elemento);
}

function icarrosToogleStatusElement(elemento) {
	if(elemento.className && elemento.className.indexOf('ativo')!=-1) {
        pos=elemento.className.indexOf('ativo');
        if(pos!=-1) {
            elemento.className=elemento.className.substring(0,pos)+elemento.className.substring(pos+5);
        }
    } else {
        elemento.className=elemento.className+" ativo";
    }
}

function icarrosShowTab(tabTitleToShow,resize) {
    var parentElement= tabTitleToShow.parentNode;
    var found=false;
    var pos=0;
    for(var i in parentElement.childNodes) {
        var elemento=parentElement.childNodes[i];
        if(elemento.className && elemento.className.indexOf('tabTitle')!=-1) {
            pos=elemento.className.indexOf('tabTitleativo');
            if(pos!=-1 && elemento!=tabTitleToShow) {
                elemento.className=elemento.className.substring(0,pos)+elemento.className.substring(pos+13);
            }
            if(elemento==tabTitleToShow) {
                found=true;
                if(pos==-1) elemento.className=elemento.className+" tabTitleativo";
            }
        } else if(elemento.className && elemento.className.indexOf('tabContent')!=-1) {
            pos=elemento.className.indexOf('tabContentativo');
            if(pos!=-1 && !found) {
                elemento.className=elemento.className.substring(0,pos)+elemento.className.substring(pos+15);
            }
            if(found) {
                found=false;
                if(pos==-1)
                    elemento.className=elemento.className+" tabContentativo";
                if(resize)
                    parentElement.style.height=(elemento.offsetTop+elemento.offsetHeight+20)+'px';
            }
        }
    }
}
function icarrosResizeTab(tabParentName) {
    var parentElement=MM_findObj(tabParentName);
    for(var i in parentElement.childNodes) {
        var elemento=parentElement.childNodes[i];
        if(elemento.className && elemento.className.indexOf('tabContentativo')!=-1) {
            parentElement.style.height=(elemento.offsetTop+elemento.offsetHeight+20)+'px';
            break;
        }
    }
}


function showFacesErrors() {
    errorElement=MM_findObj("errorMessages");
    if((errorElement.innerHTML.toLowerCase().indexOf("<ul")!=-1) || (errorElement.innerHTML.toLowerCase().indexOf("jsfmessage")!=-1)) {
        f_dialogOpenDiv(errorElement, 'Erros encontrados', 'width=500,height=300');
    }
}

function faleConosco(){
    f_dialogOpen('<%=response.encodeURL("/principal/faleconosco.jsp")%>','FaleConosco','width=400,height=375');
}
function politica(){
    f_dialogOpen('<%=response.encodeURL("/principal/politica.jsp")%>','Termodeuso','width=600,height=500,scrollbars=yes');
}
function termo(){
    f_dialogOpen('<%=response.encodeURL("/principal/termo.jsp")%>','Termodeuso','width=600,height=500,scrollbars=yes');

}
function getAbsPos(o,p){var i=0;while(o!=null){i+=o["offset"+p];o=o.offsetParent;}return i;}
function toggleElementDisplay(id){
    var element = document.getElementById(id);
    if(element.style.display == 'block'){
        element.style.display = 'none';
    }else{
        element.style.display = 'block';
    }

}


function redirectOutroFeirao(feiraoSelect){
    var url = feiraoSelect.options[feiraoSelect.selectedIndex].value;
    if(url != null && url != undefined && url != ''){
        document.location.href = '/feiraodecarros/'+url+'/index.html';
    }
}

function hideTooltip() {
	tooltip=MM_findObj('icarros_tooltip');
    if(tooltip)
        document.body.removeChild(tooltip);
}

function showTooltip(component, msg) {
    showTooltip(component, msg, '30');
}

function showTooltip(component, msg, altura) {
    hideTooltip();
    var html = 	"<div class=\"tooltip\"><div class=\"bicoesquerdo\">&nbsp;</div><div class=\"tooltipconteudo\" style=\"height:" + altura + "px;\">"+msg+"</div></div>";
	element = document.createElement("DIV");
	element.style.position="absolute";
	element.id="icarros_tooltip";
	element.style.top=(getAbsPos(component, "Top")-10)+"px";
	element.style.left=(getAbsPos(component,"Left")+component.offsetWidth +15)+"px";
	element.innerHTML=html;
	document.body.appendChild(element);
}

function positionAviso(element, component) {
	element.style.position="absolute";
	element.style.top=(component.offsetTop+55)+"px";
	element.style.left=(component.offsetLeft+component.offsetWidth +95)+"px";
	element.style.display = "block";
}


function foo(px,py,pw,ph,baseElement,fid)
{
var win = document.getElementById(this.fid);
}


function dropdown_menu_hack(el)
{
if(el.runtimeStyle.behavior.toLowerCase()=="none"){return;}
el.runtimeStyle.behavior="none";

var ie5 = (document.namespaces==null);
el.ondblclick = function(e)
{
window.event.returnValue=false;
return false;
}

if(window.createPopup==null)
{

var fid = "dropdown_menu_hack_" + Date.parse(new Date());

window.createPopup = function()
{
if(window.createPopup.frameWindow==null)
{
el.insertAdjacentHTML("AfterEnd","<iframe id='"+fid+"' name='"+fid+"' src='about:blank' frameborder='1' scrolling='no'></></iframe>");
var f = document.frames[fid];
f.document.open();
f.document.write("<html><body></body></html>");
f.document.close();
f.fid = fid;


var fwin = document.getElementById(fid);
fwin.style.cssText="position:absolute;top:0;left:0;display:none;z-index:99999;";


f.show = function(px,py,pw,ph,baseElement)
{
py = py + baseElement.getBoundingClientRect().top + Math.max( document.body.scrollTop, document.documentElement.scrollTop) ;
px = px + baseElement.getBoundingClientRect().left + Math.max( document.body.scrollLeft, document.documentElement.scrollLeft) ;
fwin.style.width = pw + "px";
fwin.style.height = ph + "px";
fwin.style.posLeft =px ;
fwin.style.posTop = py ;
fwin.style.display="block";
}


f_hide = function(e)
{
if(window.event && window.event.srcElement && window.event.srcElement.tagName && window.event.srcElement.tagName.toLowerCase()=="select"){return true;}
fwin.style.display="none";
}
f.hide = f_hide;
document.attachEvent("onclick",f_hide);
document.attachEvent("onkeydown",f_hide);

}
return f;
}
}

function showMenu()
{

function selectMenu(obj)
{
var o = document.createElement("option");
o.value = obj.value;
o.innerHTML = obj.innerHTML;
while(el.options.length>0){el.options[0].removeNode(true);}
el.appendChild(o);
el.title = o.innerHTML;
el.contentIndex = obj.selectedIndex ;
el.menu.hide();
}


el.menu.show(0 , el.offsetHeight , 10, 10, el);
var mb = el.menu.document.body;

mb.style.cssText ="border:solid 1px black;margin:0;padding:0;overflow-y:auto;overflow-x:auto;background:white;text-aligbn:center;font-family:Verdana;font-size:12px;";
var t = el.contentHTML;
t = t.replace(/<select/gi,'<ul');
t = t.replace(/<option/gi,'<li');
t = t.replace(/<\/option/gi,'</li');
t = t.replace(/<\/select/gi,'</ul');
mb.innerHTML = t;


el.select = mb.all.tags("ul")[0];
el.select.style.cssText="list-style:none;margin:0;padding:0;";
mb.options = el.select.getElementsByTagName("li");

for(var i=0;i<mb.options.length;i++)
{
mb.options[i].selectedIndex = i;
mb.options[i].style.cssText = "list-style:none;margin:0;padding:1px 2px;width/**/:100%;cursor:hand;cursorointer;white-space:nowrap;"
mb.options[i].title =mb.options[i].innerHTML;
mb.options[i].innerHTML ="<nobr>" + mb.options[i].innerHTML + "</nobr>";
mb.options[i].onmouseover = function()
{
if( mb.options.selected ){mb.options.selected.style.background="white";mb.options.selected.style.color="black";}
mb.options.selected = this;
this.style.background="#333366";this.style.color="white";
}

mb.options[i].onmouseout = function(){this.style.background="white";this.style.color="black";}
mb.options[i].onmousedown = function(){selectMenu(this); }
mb.options[i].onkeydown = function(){selectMenu(this); }


if(i == el.contentIndex)
{
mb.options[i].style.background="#333366";
mb.options[i].style.color="white";
mb.options.selected = mb.options[i];
}
}


var mw = Math.max( ( el.select.offsetWidth + 22 ), el.offsetWidth + 22 );
mw = Math.max( mw, ( mb.scrollWidth+22) );
var mh = mb.options.length * 15 + 8 ;

var mx = (ie5)?-3:0;
var my = el.offsetHeight -2;
var docH = document.documentElement.offsetHeight ;
var bottomH = docH - el.getBoundingClientRect().bottom ;

mh = Math.min(mh, Math.max(( docH - el.getBoundingClientRect().top - 50),100) );

if(( bottomH < mh) )
{

mh = Math.max( (bottomH - 12),10);
if( mh <100 )
{
my = -100 ;

}
mh = Math.max(mh,100);
}


self.focus();

el.menu.show( mx , my , mw, mh , el);
sync=null;
if(mb.options.selected)
{
mb.scrollTop = mb.options.selected.offsetTop;
}




window.onresize = function(){el.menu.hide()};
}

function switchMenu()
{
if(event.keyCode)
{
if(event.keyCode==40){ el.contentIndex++ ;}
else if(event.keyCode==38){ el.contentIndex--; }
}
else if(event.wheelDelta )
{
if (event.wheelDelta >= 120)
el.contentIndex++ ;
else if (event.wheelDelta <= -120)
el.contentIndex-- ;
}else{return true;}




if( el.contentIndex > (el.contentOptions.length-1) ){ el.contentIndex =0;}
else if (el.contentIndex<0){el.contentIndex = el.contentOptions.length-1 ;}

var o = document.createElement("option");
o.value = el.contentOptions[el.contentIndex].value;
o.innerHTML = el.contentOptions[el.contentIndex].text;
while(el.options.length>0){el.options[0].removeNode(true);}
el.appendChild(o);
el.title = o.innerHTML;
}

if(dropdown_menu_hack.menu ==null)
{
dropdown_menu_hack.menu = window.createPopup();
document.attachEvent("onkeydown",dropdown_menu_hack.menu.hide);
}
el.menu = dropdown_menu_hack.menu ;
el.contentOptions = new Array();
el.contentIndex = el.selectedIndex;
el.contentHTML = el.outerHTML;

for(var i=0;i<el.options.length;i++)
{
el.contentOptions [el.contentOptions.length] =
{
"value": el.options[i].value,
"text": el.options[i].innerHTML
}

if(!el.options[i].selected){el.options[i].removeNode(true);i--;};
}


el.onkeydown = switchMenu;
el.onclick = showMenu;
el.onmousewheel= switchMenu;

}

/* DETECT FLASH PLAYER */

// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var requiredMajorVersion = 8;
var requiredMinorVersion = 0;
var requiredRevision = 0;

var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

function flashMe(id,src,width,height,wmode,vreturn,vmap){
	vreturn = (!(vreturn == undefined || vreturn == ''));
	vmap = (!(vmap == undefined || vmap == ''));
    url = src.split("?");
    if(url.length>2) {
        url[1]=url[1]+'?'+url[2];
    }
    var content;

    if(hasRightVersion){
		content = '<OBJECT id="'+id+'" codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" height="'+height+'" width="'+width+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" VIEWASTEXT>';
		content += '<PARAM NAME="Movie" VALUE="'+url[0]+'">';
		if(wmode!=""){
			content += '<PARAM NAME="WMode" VALUE="'+wmode+'">';
		}
		content += '<PARAM NAME="swLiveConnect" VALUE="true">';
		content += '<PARAM NAME="AllowScriptAccess" VALUE="sameDomain">';
        if(url[1]!=""){
            content += '<PARAM NAME="FlashVars" VALUE="'+url[1]+'">';
		}
		content += '<EMBED MAYSCRIPT name="'+id+'" src="'+url[0]+'" AllowScriptAccess="sameDomain" quality="high" bgcolor="#FFFFFF" WIDTH="'+width+'" HEIGHT="'+height+'" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"\n';
		if(url[1]!=""){
			content += ' FlashVars="'+url[1]+'"';
		}
		if(wmode!=""){
			content += ' wmode="'+wmode+'"';
		}
		content += ' contenteswLiveConnect="true"></EMBED>';
		content += '</OBJECT>';
	} else {
		gif = src.replace(/swf\//,"imagens/");
		gif = gif.replace(/.swf/,".gif");
		if(vmap){
			content = '<img src="'+gif+'" width="'+width+'" height="'+height+'" border="0" useMap="#'+id+'map" />';
		} else {
			content = '<a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW" target="_blank"><img src="'+gif+'" width="'+width+'" height="'+height+'" border="0" /></a>';
		}
	}
	if(!vreturn){
		document.write(content);
	} else {
		return content;
	}
}

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "sameDomain";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';
  		str += '> </embed>';
    }

    document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "id":
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

function showMensagem(nomeHtml, nomeModal, largura, altura, scroll){
    var x = largura != null ? parseInt(largura) : 400;
    var y = altura != null ? parseInt(altura) : 300;
    var settings = 'width=' + x + ',height=' + y + (scroll ? ',scrollbars=yes' : '');
    f_dialogOpen('../elementos/' + nomeHtml + '.html', nomeModal, settings);
}

function validaCartao(campo) {
    if(campo.value.length>0 && !checkCreditCard(campo.value,null)) {
        alert("Cartão invalido. Por favor, digite novamente");
        campo.value='';
        campo.focus();
    }
}

function showIfHasPositiveValue(campo,toShow) {
    var valor=campo.options[campo.selectedIndex].value;
    toShowArray=toShow.split(",");
    for (var c in toShowArray) {
        try {
            if(parseInt(valor)>0)
                MM_findObj(toShowArray[c]).style.display="block";
            else
                MM_findObj(toShowArray[c]).style.display="none";
            } catch (e) {}
    }
}

function setFromIframe(iframestr, divstr, ifdattempts) {
    var doc = MM_findObj(iframestr).contentWindow.document.body.innerHTML;
    var divobj=MM_findObj(divstr);
    if(ifdattempts>0 && (doc.length<20 || divobj.innerHTML!=doc)) {
        if(doc.length>=20)
            divobj.innerHTML=doc;
        setTimeout("setFromIframe('"+iframestr+"','"+divstr+"',"+(ifdattempts-1)+");",1000);
    }
}

function addFacebookLikePlugin(compId, url){
    var strPluginBase = "http://www.facebook.com/plugins/like.php?href=" +
        url + "&layout=button_count&show_faces=false&action=like&colorscheme=light";
    var f = document.createElement("iframe");
    f.setAttribute("src", strPluginBase);
    f.setAttribute("scrolling", "no");
    f.setAttribute("allowtransparency", "true");
    f.frameBorder = 0;
    f.style.width = "90px";
    f.style.height = "22px";
    f.style.border = "0";
    f.style.overflow = "hidden";
    writePlugin(compId, f);
}

function addFacebookLikeWithCountPlugin(compId, url){
    var strPluginBase = "http://www.facebook.com/plugins/like.php?href=" +
        url + "&layout=button_count&show_faces=false&action=like&colorscheme=light";
    var f = document.createElement("iframe");
    f.setAttribute("src", strPluginBase);
    f.setAttribute("scrolling", "no");
    f.setAttribute("allowtransparency", "true");
    f.frameBorder = 0;
    f.style.width = "95px";
    f.style.height = "25px";
    f.style.border = "0";
    f.style.overflow = "hidden";
    writePlugin(compId, f);
}

function addTwitterPlugin(compId, url, texto, via){
    var head = document.getElementsByTagName('head')[0];
    var js = document.createElement("script");
    js.setAttribute("type", "text/javascript");
    js.setAttribute("src", "http://platform.twitter.com/widgets.js");
    head.appendChild(js);
    var link = document.createElement("a");
    link.setAttribute("href", "http://twitter.com/share");
    link.setAttribute("data-url", url);
    link.setAttribute("data-text", texto);
    link.setAttribute("data-via", via);
    link.className = "twitter-share-button";
    writePlugin(compId, link);
}

function addGoogleBuzz(compId, url){
    var head = document.getElementsByTagName('head')[0];
    var js = document.createElement("script");
    js.setAttribute("type", "text/javascript");
    js.setAttribute("src", "http://www.google.com/buzz/api/button.js");
    head.appendChild(js);
    var link = document.createElement("a");
    link.setAttribute("href", "http://www.google.com/buzz/post");
    link.setAttribute("data-url", url);
    link.setAttribute("data-button-style", "small-count");
    link.setAttribute("data-locale", "pt_BR");
    link.className = "google-buzz-button";
    writePlugin(compId, link);
}

function addGooglePlusOne(compId, url){
    var head = document.getElementsByTagName('head')[0];
    var js = document.createElement("script");
    js.setAttribute("type", "text/javascript");
    js.setAttribute("src", "http://apis.google.com/js/plusone.js");
    head.appendChild(js);
    writePluginInnerHtml(compId, '<g:plusone size="medium" count="true" lang="pt-BR" href="' + url + '"></g:plusone>');
}

function writePlugin(compId, element){
    var comp = MM_findObj(compId);
    if(comp != null && element != null) {
        comp.appendChild(element);
    }
}

function writePluginInnerHtml(compId, strElement){
    var comp = MM_findObj(compId);
    if(comp != null && (strElement != null && strElement.length > 0)) {
        comp.innerHTML = strElement;
    }
}

function salvaInteracaoCadastral(userId, interacaoOrd) {
    (new Image()).src = '/Icarros/interacaoUsuario/iu.gif?u=' + userId + "&i=" + interacaoOrd;
}

function MM_formtCep(e,src,mask) {
    if(window.event) {
        _TXT = e.keyCode;
    }
    else if(e.which) {
        _TXT = e.which;
    }
    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;
        }
    }
}

/*
 * openPopup
 * Opens a new window with given URL, name and properties.
 * @param url which page to display in the new window.
 * @param name name of the new window
 * @param properties string of properties
 */
function openPopup(url, name, properties)
{
 if (null != url)
 {
 var popupWin = window.open(url, name, properties);
 if (null != popupWin) popupWin.focus();
 }
}

function closeWarning(tipo){
    var b = brow();
    var w = MM_findObj("warns");
    if(w != null){
        var wm = MM_findObj('d_' + tipo);
        if(!b.isIE()){
            fadeOut(wm, 500);
        } else {
            var parent = wm.parentNode;
            parent.removeChild(wm);
        }
    }
}

function addWarningMessage(tipo, mensagem){
    var m = MM_findObj("wrn_div_" + tipo);
    var hasMessageBox = (m != null && m != 'undefined');
    if(!hasMessageBox){
        createWarningMessageBox(tipo);
    }
    var mList = MM_findObj('wrnContentMessages_' + tipo);
    var li = document.createElement("li");
    li.setAttribute('id', 'wrn_msg_' + tipo + '_' + mList.childNodes.length);
    li.innerHTML = mensagem;
    mList.appendChild(li);
    for(var i = 0; i < mList.childNodes.length; i++){
        mList.childNodes[i].className = (i == 0 && mList.childNodes.length > 1) ? 'primeiro' : (i == mList.childNodes.length - 1) ? 'ultimo' : '';
    }
    if(hasMessageBox){
        fadeIn(li, 1000);
    } else {
        fadeIn(MM_findObj('wrn_div_' + tipo), 1000);
    }
}

function createWarningMessageBox(tipo){
    var w = MM_findObj("warns");
    if(w != null){
        var div = document.createElement("div");
        div.setAttribute('id', 'd_' + tipo);
        div.innerHTML = '<div id="wrn_div_' + tipo + '" class="boxwarning ' + tipo + '"><div class="top"><div class="topleft"></div><div class="topright"></div></div><div class="conteudo"><span class="icon iconm"></span><span class="icon iconc" onclick="javascript:closeWarning(\'' + tipo + '\');" >&nbsp;</span><div id="wrnContent_' + tipo + '"><ul id="wrnContentMessages_' + tipo + '" class="listavertical"></ul></div><div class="clearer">&nbsp;</div></div><div class="bottom"><div class="bottomleft"></div><div class="bottomright"></div></div><div class="clearer">&nbsp;</div></div>';
        w.appendChild(div);
    }
}

function fadeIn(campo, duracao){
    campo.style.display = 'block';
    fade(campo, duracao, 0, 100);
}

function fadeOut(campo, duracao){
    fade(campo, duracao, 100, 0);
}

function fade(cmp, duracao, alfaInicial, alfaFinal) {
    var i = (alfaFinal >= alfaInicial ? 2 : -2);
    var fn = setInterval(
        function() {
            if ((i > 0 && alfaInicial >= alfaFinal) || (i < 0 && alfaInicial <= alfaFinal)) {
                clearInterval(fn);
                if(i < 0 && alfaInicial <= alfaFinal){
                    var parent = cmp.parentNode;
                    parent.removeChild(cmp);
                }
            }
            cmp.style.filter = "alpha(opacity=" + (alfaInicial * 3) + ")";
            cmp.style.opacity = alfaInicial / 100;
            alfaInicial += i;
        }, (duracao / 50)
    );
}

function atualizarInfoUsuario(nome, id, seg, isPJ){

    var infousuario = document.getElementById('infousuario');

    if(infousuario == null) return true;

    var lnkMenu = '';
    var txtMenu = '';
    var logado = (nome != null && nome != '');

    while(infousuario.hasChildNodes()) infousuario.removeChild(infousuario.firstChild);

    lnkMenu = (logado) ? ((isPJ) ? 'Portal Revenda' : 'Meu ' + seg) : 'Login';

    if(logado){

        if(id != null && id != ''){
            nome = '<img id="pic" src="https://graph.facebook.com/' + id + '/picture" /> ' + nome;
        }

        txtMenu = '<strong>' + nome + '</strong> <a href="javascript:popMenu();" class="primeiro">' + lnkMenu + '<span id="acesso-menupf"></span></a>';
        txtMenu += '<div id="menupf" style="display: none; visibility: hidden;"><ul>';
        if(isPJ){
            txtMenu += '<li><a href="../adesao/index.jsp" title="Revendedor" rel="nofollow">Portal Revenda</a></li>';
            txtMenu += '<li><hr /></li>';
        }
        txtMenu += '<li><a href="../autenticacao/myicarros.jsf" rel="nofollow">Meu ' + seg + '</a></li>';
        txtMenu += '<li><hr /></li>';
        txtMenu += '<li><a href="javascript:logout();" title="Sair">Sair</a></li>';
        txtMenu += '</ul></div>';

    } else {
        txtMenu = '<a href="../autenticacao/myicarros.jsf" rel="nofollow" id="acesso">' + lnkMenu + '</a> | <a href="#" onclick="loginFacebook(' + logado + ');" title="Facebook Connect" rel="nofollow" class="facebook-link">Login com Facebook</a> | <a href="../adesao/index.jsp" title="Revendedor" rel="nofollow">Portal Revenda</a>';
    }

    var txt = document.createElement('span');
    txt.innerHTML = txtMenu;
    infousuario.appendChild(txt);
}

function popMenu(){
    var menu = document.getElementById("menupf");
    if(menu.style.visibility == 'hidden'){
        menu.style.visibility = 'visible';
        menu.style.display = 'block';
    } else {
        menu.style.visibility = 'hidden';
        menu.style.display = 'none';
    }
}

function reloadPageAfterLogin() {
    window.location.reload();
}

function logout(){
    window.actionAfterLogin='reloadPageAfterLogin()';
    var protocol = window.location.protocol;
    if(protocol.indexOf(':') > -1) protocol = protocol.substr(0, protocol.indexOf(':'));
    f_dialogOpen('/autenticacao/logout.jsf?gscheme='+protocol+'&out=true', 'logout', 'width=700,height=300');
    atualizarInfoUsuario(null, null, '', false);
}

function loadFacebook(fb_callback) {
    var divRoot = document.getElementById('fb-root');
    if(divRoot == null){
        divRoot = document.createElement('div');
        divRoot.setAttribute('id', 'fb-root');
        document.body.appendChild(divRoot);
    }

    var js, id = 'facebook-jssdk';
    if (document.getElementById(id) == null) {

        js = document.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/pt_BR/all.js";
        document.getElementsByTagName('head')[0].appendChild(js);

        window.fbAsyncInit = function() {
            var channelFile = location.protocol + '//' + location.host + '/principal/fb_channel.html';
            FB.init({appId: '190284357726945', status: true, cookie: true, xfbml: true, oauth: true, channelUrl: channelFile});
            _ga.trackFacebook();
            if(typeof(fb_callback)!='undefined'){
                fb_callback();
            }
            return;
        };
    }

    if(typeof(fb_callback)!='undefined' || (FB!=null && FB!='undefined')){
        fb_callback();
    }
}

function loginFacebook(logado){
    if(!logado){

        loadFacebook(function (){

            FB.login(function(response){

                var protocol = window.location.protocol;
                protocol = protocol.substr(0, protocol.length-1);

                if(response.authResponse){

                    if(autenticarFacebook(response.authResponse.accessToken, protocol,true)){
                        console.log("acessando...");
                    }

                } else {
                    _close_popup();
                }
            }, {scope: 'email,user_location'});

        });
    }
    //if(!logado) f_dialogOpen("/autenticacao/inlinelogon.jsf?from=loginFacebook&tipo=apenaslogin&logado="+logado, 'login', 'width=350,height=295');
}
