// JavaScript Document

/*
Função para criar um qry string para envio via ajax
Percorre todo o formulário buscando valores
*/
function cQryString(idForm){
    q = '';
    f = document.getElementById(idForm);
    for(x = 0; x < f.elements.length; x++){
        e = f.elements[x];
        if(e.id){
            q += e.id+'=';
            switch(e.type){
                case 'checkbox':
                    q += (e.checked) ? '1' : '0';
                break;
                case 'radio':
                    q += (e.checked) ? e.value : '';
                break;
                default:
                    q += e.value;
            }
            q += '&';
        }
    }
    return q.substring(0, (q.length - 1));
}

// Retorna um array com os ids da página
function getElementsById(sId){
    var outArray = new Array();
	if(typeof(sId)!='string' || !sId){
		return outArray;
	};

	if(document.evaluate){
		var xpathString = "//*[@id='" + sId.toString() + "']"
		var xpathResult = document.evaluate(xpathString, document, null, 0, null);
		while ((outArray[outArray.length] = xpathResult.iterateNext())) { }
		outArray.pop();
	}else if(document.all){
		for(var i=0,j=document.all[sId].length;i<j;i+=1){
		outArray[i] =  document.all[sId][i];}
	}else if(document.getElementsByTagName){
		var aEl = document.getElementsByTagName( '*' );
		for(var i=0,j=aEl.length;i<j;i+=1){
			if(aEl[i].id == sId ){
				outArray.push(aEl[i]);
			};
		};
	};
	return outArray;
}

function idHidden(idValue, callBack){
    ids = getElementsById(idValue);
    for(x = 0; x < ids.length; x++){
        ids[x].style.visibility = 'hidden';
    }
    if(callBack) callBack();
}

function idShow(idValue, callBack){
    ids = getElementsById(idValue);
    for(x = 0; x < ids.length; x++){
        ids[x].style.visibility = 'visible';
    }
    if(callBack) callBack();
}
// Retorna a largura da tela
function getScreenWidth(){
    return window.innerWidth ? window.innerWidth : /* For non-IE */
        document.documentElement ? document.documentElement.clientWidth : /* IE 6+ (Standards Compilant Mode) */
        document.body ? document.body.clientWidth : /* IE 4 Compatible */
        window.screen.width; /* Others (It is not browser window size, but screen size) */
}

// Retorna a altura da tela
function getScreenHeight(){
    return window.innerHeight ? window.innerHeight : /* For non-IE */
      document.documentElement ? document.documentElement.clientHeight : /* IE 6+ (Standards Compilant Mode) */
      document.body ? document.body.clientHeight : /* IE 4 Compatible */
      window.screen.height; /* Others (It is not browser window size, but screen size) */
}

// Retorna a largura do objeto
function getDivWidth(obj){
    objNav = navigator.userAgent.toLowerCase();
    return (objNav.indexOf('firefox') != -1) ? obj.scrollWidth : obj.offsetWidth;
}

// Retorna a altura do objeto
function getDivHeight(obj){
    objNav = navigator.userAgent.toLowerCase();
    return (objNav.indexOf('firefox') != -1) ? obj.scrollHeight : obj.offsetHeight;
}

// Altera a altura do objeto
function setDivHeight(obj, newHeight){
    obj.style.height = newHeight + 'px';
}

// Altera a largura do objeto
function setDivWidth(obj, newWidth){
    obj.style.width = newWidth + 'px';
}

// Centraliza um objeto na tela
function centerElement(element, vCode){
    objDiv = document.getElementById(element);
    w  = (getScreenWidth()  / 2) - (getDivWidth(objDiv)  / 2);
    h  = (getScreenHeight() / 2) - (getDivHeight(objDiv) / 2);
    objDiv.style.top = h +  'px';
    objDiv.style.left = w + 'px';
    if(vCode){
        vCode();
    }
}

/*
Abre uma janela popUp na tela com a informação passada
*/
function popUpWindow(vMsg, vCode){
    if(!document.getElementById("popUp")){
        var objCorpo = document.getElementsByTagName("body").item(0);
        var objMsg   = document.createElement("div");
        objMsg.setAttribute("id", "popUp");
        objMsg.style.minWidth = '250px';
        objMsg.style.padding = '20px';
        objMsg.style.textAlign = 'center';
        objMsg.style.position = 'fixed';
        objMsg.style.background = '#E3EDF9';
        objMsg.style.border = '2px solid #225699';
        objMsg.style.fontSize = '12px';
        objMsg.style.fontWeight = 'bold';
        objMsg.style.visibility = 'visible';
        objMsg.style.display = 'inline';
        objMsg.style.zIndex = 100;
        objMsg.innerHTML = vMsg;
        objCorpo.appendChild(objMsg);
        centerElement("popUp", function(){
            idHidden('popUp');
            //$("#popUp").hide();
            $("#popUp").fadeIn("slow", function(){
                setTimeout(function(){
                    $("#popUp").fadeOut("slow", function(){
                        $("#popUp").remove();
                        ShadowOut(function(){
                            if(vCode){ vCode(); }
                        });
                    });
                }, 1500);
            });
        });
    }
}

// Adiciona sombra escura bloqueando a página
function ShadowIn(vCode) {
    if(!document.getElementById('sombra')){
        var objBody = document.getElementsByTagName('body').item(0);
        var objSombra = document.createElement('div');
        objSombra.setAttribute("id", "sombra");
        objSombra.style.position = 'fixed';
        objSombra.style.background = '#000';
        objSombra.style.top = '0px';
        objSombra.style.left = '0px';
        objSombra.style.width = '100%';
        objSombra.style.height = '100%';
        objSombra.style.filter = 'alpha(opacity=65)';
        objSombra.style.opacity = 0.5;
        objSombra.style.zIndex = 10;
        objSombra.style.visibility = 'visible';
        objSombra.style.display = 'inline';
        objBody.appendChild(objSombra);
        document.getElementById("sombra").focus();
        if(vCode) vCode();
    }
}


// Remove a sombra negra
function ShadowOut(vCode){
    if(document.getElementById('sombra')){
    //if(document.getElementById("sombra")){
        $("#sombra").fadeOut("slow", function(){
            $("#sombra").remove();
            if(vCode){ vCode(); }
        });
    }
}

function selectOption(selectId, selectValue){
    select = document.getElementById(selectId);
    for(x = 0; x < select.length; x++){
        if(select[x].value == selectValue){
            select[x].selected = true;
        }
    }
}

function insertSelect(retorno, tagname, selectname, idvalue, func){
    //var agt = navigator.userAgent.toLowerCase();
    var tags = retorno.getElementsByTagName(tagname);
    var select = document.getElementsByName(selectname)[0];
    select.options.length = 0;
    for(a = 0 ; a < tags.length ; a++){
        value = tags[a].childNodes[0].childNodes[0].nodeValue;
        texto = tags[a].childNodes[1].childNodes[0].nodeValue;
        selected = (value == idvalue) ? true : false;
        if(selected){
            //alert(value+' - '+texto);
        }
        var op = new Option(texto, value, selected, selected);
        select.options[a] = op;
	}
    if(func) func();
}


// Monta o select com base nos dados e consulta no banco de dados
function loadingSelect(db, table, conds, value, text, id, pid, ptxt, vfunc){
    pid = (pid) ? pid : '';
    ptxt = (ptxt) ? ptxt : '';
    var url  = '../ajax/loadingSelect.php?db='+db+'&table='+table+'&dados='+value+',';
    url += text+'&conds='+conds+'&pid='+pid+'&ptxt='+ptxt;
    if((pid != '') && (ptxt == '')){ var selid = pid; }
    mAjax(url, null, 'xml', 'get', function(rXml){
        insertSelect(rXml, table, id, selid, vfunc);
    });
}


/* Captura os dados get da url */
function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
		hash[1] = unescape(hash[1]);
		vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

function boxMsg(mensagem, callBack){
    if(!document.getElementById("boxMsg")){
        var objCorpo = document.getElementsByTagName("body").item(0);
        var objMsg   = document.createElement("div");
        objMsg.setAttribute("id", "boxMsg");
        objMsg.style.filter = 'alpha(opacity=0)';
        objMsg.style.opacity = 0;
        objMsg.style.position = 'fixed';
        objMsg.style.background = '#FFF';
        objMsg.style.border = '2px solid #225699';
        objMsg.style.visibility = 'visible';
        objMsg.style.display = 'inline';
        objMsg.style.padding = '10px';
        objMsg.style.minWidth = '350px';
        objMsg.style.textAlign = 'center';
        objMsg.style.zIndex = 100;
        objMsg.innerHTML = mensagem;
        objCorpo.appendChild(objMsg);
        centerElement("boxMsg");
        fadeIn("boxMsg", 0.5);
    }else{
        var msg = document.getElementById("boxMsg");
        msg.innerHTML = mensagem;
        centerElement("boxMsg");
    }
    if(callBack) callBack();
}



// Modifica a altura do objeto body para se ajustar a altura da tela
function resizeBody(idBody, idHeader, idFooter){
    hHeader = getDivHeight(document.getElementById(idHeader));
    hFooter = getDivHeight(document.getElementById(idFooter));
    divBody = document.getElementById(idBody);
    divBody.style.minHeight = (getScreenHeight() - (hHeader + hFooter)) + "px";
}

function cJurFin(capital, taxa, parcelas){
    var valpar = taxa / (1 - Math.pow((1 + taxa), parcelas * -1)) * capital;
    return valpar;
}

function FormataHORA(nome) {
    hora = getValue(nome);
    hora = Limp(hora);
    if (hora.length == 4) {
        if(parseInt(hora.substring(0,2)) > 23) {
            alert("Você digitou a Hora incorretamente. Digite novamente.");
            hora = "";
        } else {
            part1 = hora.substring(0,2);
            if(parseInt(hora.substring(2,4)) > 59) {
                alert("Você digitou os Minutos incorretamente. Digite novamente.");
                hora = "";
            } else {
                part2 = hora.substring(2,4);
                hora = part1 + (':') + part2;
            }
        }
    } else {
        if (hora.length > 0) {
            alert("Verifique a Hora.\nA Hora deve ser digitada com 4 dígitos.\nEx.: HH:mm (Os dois pontos são opcionais)");
            hora = "";
        }
    }
    setValue(nome, hora);
}

function FormataDATA(nome){
   DATA = getValue(nome);
   DATA = Limp(DATA);
   if(DATA.length == 8){
      if(parseInt(DATA.substring(0,2)) > 31){
         alert('Você digitou o dia incorretamente, a data foi apagada. Digite novamente');
         DATA = "";
      }
      else {
         dia = DATA.substring(0,2);
         if(parseInt(DATA.substring(2,4)) > 12){
            alert('Você digitou o mês incorretamente, a data foi apagada. Digite novamente');
            DATA = "";
         }
         else{
            mes = DATA.substring(2,4);
            ano = DATA.substring(4,8);
            if(ano > 2100 || ano < 1900){
               alert("Você digitou o ano incorretamente, a data foi apagada. Digite novamente");
               DATA = "";
            }
            else{
               tmpMes = mes -1;
               tmp = new Date(ano,tmpMes,dia);
               m = tmp.getMonth();
               if(tmpMes != m){
                  alert('Data Inválida. A Data foi apagada, digite novamente');
                  DATA = "";
               }
               else{
                  DATA = dia + ('/') + mes + ('/') + ano;
               }
            }
         }
     }
  }
   else{
      if(DATA.length > 0){
         alert('Verifique a data digitada, pois está incorreta. A data deve ser digitada com seus 8 dígitos (dd mm aaaa). Ex.: 01/01/2004 (As barras não são necessárias.)');
         DATA = "";
      }
   }
  setValue(nome, DATA);
}

function getValue(nome){
    if(document.getElementById(nome))
        return document.getElementById(nome).value
}

function setValue(nome, valor){
   obj = eval("document.forms[0]."+nome);
   obj.value = valor;
}
function Limp(c){
   qtd = c.length;
   var v = '';
   for (i=0; i < qtd; i++)
   for(t=0; t < 10; t++){
      if(c.substring(i,i+1) == t && c.substring(i,i+1) != " ") v += c.substring(i,i+1);
   }
   return(v);
}
////////////Fim Data
/////////////////////////////////////////////////////////////////////////////////////////////////
///////////Validador cnpj e cpf
var msgCPF = 'no';
var msgCNPJ = 'no';
/*
Validação do CPF através do módulo 11
*/
//função que verifica a veracidade do CPF
function VerificaCPF(nome){
   var CPF = getValue(nome); // Recebe o valor digitado no campo
   // Verifica se o campo é nulo
   if (CPF == '') {
      return false;
   }
   CPF = Limp(CPF);
   total = CPF.length;
   for(t=0; t < 10; t++){
      cont = 0;
      for(a=0; a < total; a++){
         if(CPF.substring(a,a+1)==(t+'')){
            cont++;
            if(cont == 11){
               setValue(nome, "");
               popUp('<br/>CPF INVÁLIDO');
               return false;
            }
         }
      }
   }
// Aqui começa a checagem do CPF
var POSICAO, I, SOMA, DV, DV_INFORMADO;
var DIGITO = new Array(10);
DV_INFORMADO = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado
// Desemembra o número do CPF na array DIGITO
for(I=0; I<=8; I++){
   DIGITO[I] = CPF.substr( I, 1);
}
// Calcula o valor do 10º dígito da verificação
POSICAO = 10;
SOMA = 0;
for(I=0; I<=8; I++){
   SOMA = SOMA + DIGITO[I] * POSICAO;
   POSICAO = POSICAO - 1;
}
DIGITO[9] = SOMA % 11;
if(DIGITO[9] < 2){
   DIGITO[9] = 0;
}
else{
   DIGITO[9] = 11 - DIGITO[9];
}
// Calcula o valor do 11º dígito da verificação
POSICAO = 11;
SOMA = 0;
for (I=0; I<=9; I++){
   SOMA = SOMA + DIGITO[I] * POSICAO;
   POSICAO = POSICAO - 1;
}
DIGITO[10] = SOMA % 11;
if(DIGITO[10] < 2){
   DIGITO[10] = 0;
}
else{
   DIGITO[10] = 11 - DIGITO[10];
}
// Verifica se os valores dos dígitos verificadores conferem
DV = DIGITO[9] * 10 + DIGITO[10];
if (DV != DV_INFORMADO){
   if(msgCPF == 'no') popUp('<br/>CPF INVÁLIDO');
      setValue(nome, "");
      return false;
   }
FormataCPF(nome);
return true;
}

function FormataCPF(nome){
   CPF = getValue(nome);
   CPF = Limp(CPF);
   if(CPF.length == 11){
      value = Mascara(CPF, '999.999.999-99');
      setValue(nome, value);
      msgCPF = 'no';
   }
   else{
      if(CPF.length > 0){
      alert('Verifique o CPF digitado, pois estão faltando ou sobrando números.');
      msgCPF = 'yes';
      }
      else{
         msgCPF = 'no';
      }
   }
}
//função para Limpar e deixar somente os números.
function Limp(car){
    qtd = car.length;
    var v = '';
    for (i=0; i < qtd; i++)
        for(t=0; t < 10; t++){
           if(car.substring(i,i+1) == t && car.substring(i,i+1) != " ")
                v += car.substring(i,i+1);
        }
    return(v);
}

/*
Funções para pegar o valor, e atribuir um valor ao campo q às chama.
*/
function Mascara(value, mascara){
   tmp = mascara;
   guarda = value;
   cont = 0;
   var caracter = new Array();
   var position = new Array();
   if(tmp.length > 0){
      qtd = tmp.length;
      for(i=0; i < tmp.length; i++){
         tmpValue = tmp.substring(i,i+1);
         if(tmpValue != 9){
            caracter[cont] = tmpValue;
            position[cont] = i;
            cont++;
         }
      }
   VALOR = value;
   VALOR = Limp(VALOR);
   if(VALOR.length == 0){
      VALOR = '';
   }
   else{
      var value = '';
      value += VALOR.substring(0,position[0])+caracter[0];
      car = caracter.length;
      for(j=1; j < car; j++)
      value += VALOR.substring(position[j-1]-(j-1),position[j]-j)+caracter[j];
      value += VALOR.substring(position[car-1]-(car-1), qtd);
      VALOR = value;
   }
return value;
}
return guarda;
}

//função que verifica a veracidade do CNPJ
function VerificaCNPJ(nome) {
    VALOR = getValue(nome);
    VALOR = Limp(VALOR);
    if(testaCNPJ(VALOR) == 1){
    }else{
        eval("document.forms[0]."+nome+".select()");
        if(msgCNPJ == 'no'){
            setValue(nome, '');
            popUp("<br/>CNPJ INVÁLIDO!");
            return false;
        }
    }
    FormataCNPJ(nome);
    return true;
}

//função que testa o CNPJ
function testaCNPJ(CNPJ){
   CNPJ = Limp(CNPJ);
   if(CNPJ.length != 14){return (0);}
   if(isNUMB(CNPJ) != 1) { return(0); }
   else{
      if(CNPJ == 0) { return(0); }
      else{
         g=CNPJ.length-2;
         if(RealTestaCNPJ(CNPJ,g) == 1) {
            g=CNPJ.length-1;
            if(RealTestaCNPJ(CNPJ,g) == 1) { return(1); }
            else{
               return(0);
            }
          }
          else{
             return(0);
          }
      }
   }
}
//Função que faz o teste do CNPJ
function RealTestaCNPJ(CNPJ,g){
   var VerCNPJ=0;
   var ind=2;
   var tam;
   for(f=g;f>0;f--){
      VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind;
      if(ind>8){
         ind=2;
      }
      else{
         ind++;
      }
   }
   VerCNPJ%=11;
   if(VerCNPJ==0 || VerCNPJ==1){
      VerCNPJ=0;
   }
   else{
      VerCNPJ=11-VerCNPJ;
   }
   if(VerCNPJ!=parseInt(CNPJ.charAt(g))){
      return(0);
   }
   else{
      return(1);
   }
}
/*
Função que verifica se é numero.
*/
function isNUMB(c){
   if((cx=c.indexOf(","))!=-1){
      c = c.substring(0,cx)+"."+c.substring(cx+1);
   }
   if((parseFloat(c) / c != 1)){
      if(parseFloat(c) * c == 0){
         return(1);
      }
      else{
         return(0);
      }
   }
   else{
      return(1);
   }
}

function FormataTEL(tel){
    fone = getValue(tel);
    fone = Limp(fone);
    if(fone.length == 10){
        ddd = fone.substring(0,2);
        pre = fone.substring(2,6);
        suf = fone.substring(6,10);
        mnt = '('+ddd+')'+pre+'.'+suf;
        setValue(tel,mnt);
    }else{
        if(fone.length > 0){
            alert('Verifique o telefone digitado, utilize o DDD ex:(xx)xxxx-xxxx');
            setValue(tel,'');
        }
    }
}
/*
Função para formatar o CNPJ
*/
function FormataCNPJ(nome){
   CNPJ = getValue(nome);
   CNPJ = Limp(CNPJ);
   if(CNPJ.length == 14){
      value = Mascara(CNPJ, '99.999.999/9999-99');
      setValue(nome, value);
      msgCNPJ = 'no';
   }
   else{
      if(CNPJ.length > 0){
         erroValue = ('Verifique o CNPJ digitado, pois estão faltando ou sobrando números.');
         msgCNPJ = 'yes';
      }
      else{
         msgCNPJ = 'no';
      }
  }
}
/////////////Fim
///////////////////////////////////////////////////////////////////////////////////////////////////////


/////////////Valores em dinheiro
function Limpar(valor, validos){
// retira caracteres invalidos da string
   var result = "";
   var aux;
   for(var i=0; i < valor.length; i++){
      aux = validos.indexOf(valor.substring(i, i+1));
      if(aux>=0){
         result += aux;
      }
   }
return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal){
   var tecla = teclapres.keyCode;
   vr = Limpar(campo.value,"0123456789");
   tam = vr.length;
   dec = decimal;
   if(tam < tammax && tecla != 8){
      tam = vr.length + 1 ;
   }
   if(tecla == 8 ){
      tam = tam - 1 ;
   }
   if( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105){
      if ( tam <= dec ){
         campo.value = vr ;
      }
      if((tam > dec) && (tam <= 5)){
         campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 6) && (tam <= 8)){
         campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 9) && (tam <= 11)){
         campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 12) && (tam <= 14)){
         campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 15) && (tam <= 17)){
         campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
      }
   }
}
//////////////////Fim
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////fortmat
function txtBoxFormat(objForm, strField, sMask, evtKeyPress){
      var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
      if(document.all) { // Internet Explorer
         nTecla = evtKeyPress.keyCode;
      }
      else if(document.layers){ // Nestcape
         nTecla = evtKeyPress.which;
      }
      sValue = objForm[strField].value;
       // Limpa todos os caracteres de formatação que
      // já estiverem no campo.
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( " ", "" );
      sValue = sValue.toString().replace( " ", "" );
      fldLen = sValue.length;
      mskLen = sMask.length;
      i = 0;
      nCount = 0;
      sCod = "";
      mskLen = fldLen;
      while(i <= mskLen){
         bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
         bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
         if(bolMask){
            sCod += sMask.charAt(i);
            mskLen++;
         }
         else{
            sCod += sValue.charAt(nCount);
            nCount++;
        }
        i++;
        }
     objForm[strField].value = sCod;
     if (nTecla != 8){ // backspace
        if(sMask.charAt(i-1) == "9") { // apenas números...
           return((nTecla > 47) && (nTecla < 58));
        } // números de 0 a 9
        else { // qualquer caracter...
           return true;
        }
     }
     else{
        return true;
     }
}

// Adriano Leite
/////////////////////////////////////
function enter(e, id){
    var code = e.keyCode ? e.keyCode : e.which ;
    if(code == 13){
        if(e.KeyCode){
            e.keyCode = 9;
        }else{
            document.getElementById(id).blur();
        }
    }
}

function redimensiona(div){
    if(parseInt(navigator.appVersion)>3){
        if(navigator.appName=="Netscape"){
            winW = window.innerWidth;
            winH = window.innerHeight - 134;
            document.getElementById(div).style.height = winH+'px';
        }
        if(navigator.appName.indexOf("Microsoft")!=-1){
            winW = document.body.offsetWidth;
            winH = document.body.offsetHeight;
            document.getElementById(div).style.height = '456px';
        }
    }
}
/*
function enter(){
    if(event.keyCode==13) event.keyCode=9;
}
*/

function roundNumber (rnum){
   return Math.round(rnum*Math.pow(10,2))/Math.pow(10,2);
}

function float2moeda(num){
   x = 0;
   if(num<0){
      num = Math.abs(num);
      x = 1;
   }
   if(isNaN(num)) num = "0";
      cents = Math.floor((num*100+0.5)%100);

   num = Math.floor((num*100+0.5)/100).toString();

   if(cents < 10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
         num = num.substring(0,num.length-(4*i+3))+'.'
               +num.substring(num.length-(4*i+3));   ret = num + ',' + cents;   if (x == 1) ret = ' - ' + ret;return ret;
}

function moeda2float(moeda){
   //moeda = moeda.replace(".","");
   moeda = moeda.replace(",",".");
   return parseFloat(moeda);
}

function verifica(num,acao,op,op2){
	if (num == 0){
		alert("Você não possui Permissão de Acesso!");
		if (acao == ''){
			return (false);
		}
	} else {
		if (acao != ''){
			window.open(acao,op,op2);
		}
	}
}

function criaCookie(nome,valor,dias){
    if (dias){
        var date = new Date();
        date.setTime(date.getTime()+(dias*24*60*60*1000));
        var expira = "; expires="+date.toGMTString();
    }else var expira = "";
    document.cookie = nome+"="+valor+expira+"; path=/";
}

function leCookie(nome){
    var nomeEQ = nome + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++){
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nomeEQ) == 0) return c.substring(nomeEQ.length,c.length);
    }
    return null;
}

function apagaCookie(nome){
    criaCookie(nome,"",-1);
}

String.prototype.clear = function(){
    var carac = new Array(".", "-", "/", "(", ")", ",", "*");
    var value = this;
    for(x = 0; x < carac.length; x++){
        do{
            value = value.replace(carac[x], "");
        }while(value.indexOf(carac[x]) > 0)
    }
    return value;
}


String.prototype.trim = function(){
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function limpaCookie(){
    var co = document.cookie.split(";");
    for(x=0;x<co.length;x++){
        var d  = new Date();
        apagaCookie(co[x]);
        //document.cookie = co[x]+";expires=" + d.toGMTString() + ";" + ";";
    }
}
function RetiraAcentos(Campo){
   var Acentos = "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇabcdefghijklmnopqrstuvxwyz";
   var Traducao ="AAAAAAAAAEEEEIIOOOOOOUUUUCCABCDEFGHIJKLMNOPQRSTUVXWYZ";
   var Posic, Carac;
   var TempLog = "";
   for (var i=0; i < Campo.length; i++){
        Carac = Campo.charAt (i);
        Posic  = Acentos.indexOf (Carac);
        if(Posic > -1)
            TempLog += Traducao.charAt (Posic);
        else
            TempLog += Campo.charAt (i);
    }
    return (TempLog);
}

function validaform(name){
    var formu   = document.getElementById(name);
    var eleme   = formu.elements.length;
    for(x = 0; x < eleme; x++){
        if(formu.elements[x].className == "valida"){
            if(formu.elements[x].value == ""){
                var nome_id = document.getElementById(formu.elements[x].id).title;
                var msg = "Preencha o campo "+nome_id+" corretamente.";
                popUp(msg);
                formu.elements[x].focus();
                return false;
            }
        }
    }
    var senha = "";
    var prim = false;
    for(x = 0; x < eleme; x++){
        var el = formu.elements[x];
        if((el.type == "password") && (el.name.indexOf("nova") != -1)){
            if(prim == false){
                var senha = formu.elements[x].value;
                prim = true;
            }
            if((formu.elements[x].value != senha) || (formu.elements[x].value == "")){
                popUp("Por favor! <br/>Preencha os campos de senha corretamente.<br/>");
                return false;
            }
        }
    }
}

function pausecomp(millis){
 var date = new Date();
 var curDate = null;
 do { curDate = new Date(); }
 while(curDate - date < millis);
}

function notNull(id){
    var tmp = document.getElementById(id);
    if(tmp.value == ''){
        popUp('Preencha o campo '+tmp.title+'.');
        tmp.value = '';
        window.setTimeout('setFocus("' + id + '")', 2100);
        return false;
    }
    return true;
}

function setValues(id, element){
    document.getElementById(element).value = id;
}

function showWindow(elemento){
    document.getElementById(elemento).style.opacity = valor / 10;
    document.getElementById(elemento).filter = 'alpha(opacity=' + valor * 10 + ')';
}


function executa(funcoes){
    funcoes;
}

function setAlpha(target, alpha) {
    if(alpha != null){
        target.style.filter = "alpha(opacity="+ alpha +")";
    	target.style.opacity = alpha/100;
    }
}

function fadeIn(id, time) {
    objNav = navigator.userAgent.toLowerCase();
    nro = (objNav.indexOf('firefox') != -1) ? 10 : 20;
    target = document.getElementById(id);
    alpha = 0;
    timer = (time * 1000)/50;
	var e = setInterval(
			function() {
				if (alpha >= 100)
					clearInterval(e);
                setAlpha(target, alpha);
                alpha += nro;
			}, timer);
}

function fadeOut(id, time) {
    objNav = navigator.userAgent.toLowerCase();
    nro = (objNav.indexOf('firefox') != -1) ? 10 : 20;
    target = document.getElementById(id);
	alpha = 100;
	timer = (time * 1000)/50;
    var e = setInterval(
			function() {
				if (alpha <= 0){
					clearInterval(e);
                    destroyElement(id);
                }
                if(target != null){	setAlpha(target, alpha); }
				alpha -= nro;
			}, timer);
}

function destroyElement(id){
    try{
        var objeto = document.getElementById(id);
        document.body.removeChild(objeto);
    }catch(err){ }
}

function closeElement(elemento, funcoes){
    fadeOut(elemento, 0.5);
    ShadowOut();
    if(funcoes) {
        window.setTimeout(funcoes, 1000);
    }
}

function banner_propaganda(imagem, width, height){
    window.setTimeout(function(){
        var msg = '<img id=\"imagem\" src="'+imagem+'" width="'+width+'" ';
        msg += ' height="'+height+'" style="cursor:pointer" ';
        msg += ' onclick="closeElement(\'msg\', \'\');window.open(\'http://www.redeclassmultivantagens.com.br\', \'\', \'\')" />';
        show(msg);
    },800);
}

function makeMsg(mens, func, tipo){
    if(func == '') func = 'void(0)';
    var html = "";
    html = mens;
    if(tipo){
        html+= "<div style=\"cursor:pointer; position:absolute; top:5px; right:5px;\">";
        html+= "<img onclick=\"closeElement('msg', '"+func+"')\" ";
        html+= "src=\"/imagens/botao_fechar.gif\"></div>\n";
    }
    return html;
}

function showCmd(ret, cmd){
    windowElement(ret, cmd, true);
}

function show(ret){
    windowElement(ret, ' ', true);
}

function show_refresh(ret){
    windowElement(ret, 'history.go(0)', true);
}

//Exibe Mensagem na tela por 2 segundos
function popUp(msg){
    windowElement(msg, ' ', false);
    window.setTimeout('closeElement("msg", " ")', 2000);
}

//Exibe Mensagem na tela e após 2 Segundo efetua um refresh da página
function popUpRefresh(msg){
    windowElement(msg, ' ', false);
    window.setTimeout('history.go(0)', 2000);
}

//Exibe Mensagem na tela e após 1 segundos efetua o comando configurado
function popUpCmd(msg, cmd){
    windowElement(msg, ' ', false);
    window.setTimeout(cmd, 1000);
    window.setTimeout('closeElement("msg", " ")', 2000);
}

// Cria uma janela flutuante
function windowElement(mensagem, funcao, tipo){
    if(!document.getElementById('msg')){
        var objCorpo = document.getElementsByTagName('body').item(0);
        var objMsg   = document.createElement('div');
        objMsg.setAttribute('id','msg');
        objMsg.style.filter = 'alpha(opacity=0)';
        objMsg.style.opacity = 0;
        objMsg.style.position = 'fixed';
        objMsg.style.background = '#FFF';
        objMsg.style.border = '2px solid #225699';
        objMsg.style.visibility = 'visible';
        objMsg.style.display = 'inline';
        objMsg.style.padding = '20px';
        objMsg.style.minHeight = '50px';
        objMsg.style.minWidth = '350px';
        objMsg.style.textAlign = 'right';
        objMsg.style.zIndex = 100;
        if(!tipo){
            objMsg.style.paddingLeft    = '10px';
            objMsg.style.paddingRight   = '10px';
            objMsg.style.paddingTop     = '10px';
            objMsg.style.paddingBottom  = '10px';
            objMsg.style.fontSize       = '12px';
        }
        objMsg.innerHTML = makeMsg(mensagem, funcao, tipo);
        objCorpo.appendChild(objMsg);
        centerElement('msg');
        fadeIn('msg', 0.5);
    }else{
        var msg = document.getElementById('msg');
        msg.innerHTML = makeMsg(mensagem, funcao, tipo);
        centerElement('msg');
    }
}

function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if(typeof(window.pageYOffset) == 'number'){ //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    }else if(document.body && (document.body.scrollLeft || document.body.scrollTop)){ //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
  }else if(document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop)){ //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
  }
  return [scrOfX, scrOfY];
}


/*
Captura as coordenadas do mouse e as coloca nas variáves tempX e tempY, sendo
que e é o evento que esta sendo ulizado ex: onclick, onmouseover
*/
function getCoord(e){
    var objAgt = navigator.userAgent.toLowerCase();
    if(objAgt.indexOf("msie") != -1){
        pageXY = getScrollXY();
        tempX  = event.clientX + pageXY[0];
        tempY  = event.clientY + pageXY[1];
    }
    if(objAgt.indexOf("firefox") != -1){
        tempX = e.pageX;
        tempY = e.pageY;
    }
}

/* Move a div de acordo com o Scrool, deixando a mesma sempre em exibição */
function moveDiv(id){
    var div = document.getElementById(id);
    pageXY  = getScrollXY();
    div.style.left = pageXY[0] + 'px';
    div.style.top  = pageXY[1] + 'px';
}

/* Cria uma div flutuante com base no ponteiro do mouse */
function windowMouse(mensagem, funcao, tipo){
    if(!document.getElementById('msg')){
        var objCorpo = document.getElementsByTagName('body').item(0);
        var objMsg = document.createElement('div');
        objMsg.setAttribute('id','msg');
        objCorpo.appendChild(objMsg);
        objMsg.style.filter = 'alpha(opacity=0)';
        objMsg.style.opacity = 0;
        objMsg.style.padding = '3px';
        objMsg.style.position = 'absolute';
        objMsg.style.visibility = 'visible';
        objMsg.style.display = 'inline';
        objMsg.style.minHeight = '50px';
        objMsg.style.width = '350px';
        objMsg.style.zIndex = 100;
        objMsg.innerHTML = makeMsg(mensagem, funcao, tipo);
        ew = getDivWidth(objMsg);
        eh = getDivHeight(objMsg);
        document.onclick = getCoord;
        newTop  = (tempY + eh) > getScreenHeight() ? (tempY - eh) : tempY;
        newLeft = (tempX + ew) > getScreenWidth() ? (tempX - ew) : tempX;
        objMsg.style.top  = newTop + 'px';
        objMsg.style.left = newLeft + 'px';
        fadeIn('msg', 0.5);
    }else{
        var msg = document.getElementById('msg');
        msg.innerHTML = makeMsg(mensagem, funcao, tipo);
        ew = getDivWidth(msg);
        eh = getDivHeight(msg);
        document.onclick = getCoord;
        newTop  = (tempY + eh) > getScreenHeight() ? (tempY - eh) : tempY;
        newLeft = (tempX + ew) > getScreenWidth() ? (tempX - ew) : tempX;
        msg.style.top = newTop + 'px';
        msg.style.left = newLeft + 'px';
    }

}

// Retorna o valor da cor para o input
function setColorInput(id, value){
    $("#"+id).val(value);
    $("#"+id).css("background", value);
    $("#"+id).focus();
}

function timerClose(id){
    set = setInterval(function(){
        $("#"+id).fadeOut("slow", function(){
            $("#"+id).remove();
            clearInterval(set);
        });
    }, 500);
}

function stopClose(){
    try{
        clearInterval(set);
    }catch(err){

    }

}

// Exibe Paleta de cores
function getColors(ev, input){
    getCoord(ev);
    var line = 21;
    var r  = new Array("00","33","66","99","CC","FF");
    var g  = new Array("00","33","66","99","CC","FF");
    var b  = new Array("00","33","66","99","CC","FF");
    var n  = new Array("1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
    var tc = "";
    tc += "<style>\n";
    tc += "#tColors table { border:1px solid #aaa; cursor:pointer; background:#FFF; }\n";
    tc += "#tColors tr td { border:none; width:8px; height:8px; }\n";
    tc += "</style>\n";

    tc += "<div id=\"tColors\">\n";
    tc += "<table border=\"1\" cellspacing=\"1\" cellppandig=\"1\" >\n";
    tc += "<tr>\n";
    cont = 1;
    for (i = 0; i < r.length; i++) {
    	for (j = 0; j < g.length; j++) {
    		for (k = 0; k < b.length; k++){
    			var cor = "#" + r[i] + g[j] + b[k];
                tc += "<td onclick=\"setColorInput('"+input+"', '"+cor+"');";
                tc += "closeElement('msg')\" style='background:"+cor+";' ";
                tc += "title='"+cor+"' onmouseout=\"timerClose('msg')\" ";
                tc += "onmousemove=\"stopClose()\" >&nbsp;</td>\n";
                if((cont % line) == 0) { tc += "</tr><tr>"; }
                cont++;
    		}
    	}
    }
    for(g = 0; g < n.length; g++){
        var cor = "#";
        for(i = 0; i < 6; i++) cor += n[g];
        tc += "<td onclick=\"setColorInput('"+input+"', '"+cor+"');";
        tc += "closeElement('msg')\" style='background:"+cor+";' ";
        tc += "title='"+cor+"'>&nbsp;</td>\n";
        if((cont % line) == 0) { tc += "</tr><tr>"; }
        cont++;
    }
    tc += "</table>\n";
    tc += "</div>\n";
    windowMouse(tc, '', false);
}

function setFocus(id){
    document.getElementById(id).focus();
}

function downloadme(file){
    tmp      = file.split('/');
    filename = tmp[(tmp.length - 1)];
    window.setTimeout(function(){
        url = '../../scripts/download.php?file='+filename;
        window.open(url, '', '');
        //myWindow = window.open(url, 'arquivo', 'fullscreen=no,top=0,left=0,location=no,menubar=no,resizable=no,status=no,titlebar=no,toolbar=no,width=500,height=500');
    }, 1000);

}

/*
function retCpf(retorno){
	valor = retorno.split(';');
	var cod = valor[0];
	var msg = valor[1];
	var cpf = valor[2];
	if(cod==1){	document.forms[0].cpf.value = cpf;
	}else{ document.forms[0].cpf.value = ""; }
	document.forms[0].retcpf.value = msg;
}
*/

function getArrayValues(array, string){
    arr = new Object();
    for(a = 0; a < array.length; a++){
        tmp = array[a].split(string);
        arr[tmp[0]] = tmp[1];
    }
    return arr;
}

function respCpf(string){
    values = string.split(';');
    switch(values[0]){
        case '0':
            try { var divRet = document.getElementById(values[1]); }catch(err){ }
            divRet.innerHTML = 'CPF ACEITO';
            try { var inpCpf = document.getElementById(values[2]); }catch(err){ }
            inpCpf.value = values[3];
        break;
        case '1':
            try { var divRet = document.getElementById(values[1]); }catch(err){ }
            divRet.innerHTML = 'CPF JÁ CADASTRADO';
            dados = getArrayValues(values[4].split(','), '=');

            for(c = 0; c < document.forms[0].length; c++){
                element = document.forms[0].elements[c];
                switch(element.type){
                    case "text": case "password": case "hidden": case "textarea":
                        element.value = dados[element.id];
                    break;
                    case "select-one":
                        var found = false;
                        for(x = 0; x < element.length; x++){
                            if(element.options[x].value == dados[element.id]){
                                element.options[x].selected = true;
                                found = true;
                            }
                        }
                        if(!found){
                            opc = new Option(dados[element.id], dados[element.id]);
                            element.options[element.length] = opc;
                            element.options[(element.length - 1)].selected = true;
                        }
                    break;
                    case "checkbox":
                        element.checked = (dados[element.id]) ? true : false;
                    break;
                    case "radio":
                        if(element.value == dados[element.id])
                            element.checked = true;
                    break;
                }
            }
            try { var inpCpf = document.getElementById(values[2]); }catch(err){ }
            inpCpf.value = values[3];
        break;
    }
    ShadowOut();
}

//Limpa a String inserida
function clearStr(string, conjstr){
    for(x = 0; x < conjstr.length; x++){
        string = string.replace(conjstr[x], '');
    }
    return string;
}

// Formata o telefone na máscara (xx)xxxx-xxxx
function formataFone(idFone){
    fone = document.getElementById(idFone).value;
    if(fone.length < 10){
        document.getElementById(idFone).value = "";
    }else{
        nFone = clearStr(fone, '()-');
        novo = "("+nFone.substr(0, 2)+")"+nFone.substr(2, 4)+"-"+nFone.substr(6, 4);
        document.getElementById(idFone).value = novo;
    }
}

// Verifica se o telefone e valido ddd + telefone
function verificaFone(idFone){
    fone = document.getElementById(idFone);
    if(fone.value.length < 10){
        popUp("CAMPO "+fone.title+" DIGITADO INCORRETO.<br/>POR FAVOR DIGITE DDD + TELEFONE");
        fone.value = "";
        return false;
    }else{
        formataFone(idFone);
    }
    return true;
}

// Verifica se o usuário digitou um e-mail válido
function verificaEmail(idMail){
    mail = document.getElementById(idMail);
    if(mail.value.indexOf("@") < 0){
        popUp("E-MAIL INVÁLIDO. <br/>DIGITE UM E-MAIL VÁLIDO.");
        mail.value = "";
        return false;
    }
    return true;
}

//Formata o cep na máscara xxxxx-xxx
function formataCEP(idCep){
    cep = document.getElementById(idCep);
    if(cep.value.length < 8){
        cep.value = "";
        return false;
    }else{
        cep.value = clearStr(cep.value, '-');
        novo = cep.value.substr(0, 5)+"-"+cep.value.substr(5, 3);
        cep.value = novo;
    }
    return true;
}

// Adiciona um elemento a um select
function addSelInfo(idSel, value, text){
    sel = document.getElementById(idSel);
    opc = new Option(text, value);
    sel.options[sel.length] = opc;
    sel.options[(sel.length - 1)].selected = true;
}


// Permite somente a digitação de números em um campo input text
function onlyNumbers(e){
    var tecla = (window.event) ? event.keyCode : e.which;
    if((tecla > 47 && tecla < 58) || (tecla == 0)) return true;
    else{
        if (tecla != 8) return false;
        else return true;
    }
}

function retCadastro(retAjax){
    ret = retAjax.split(";");
    popUpRefresh("<br/>" + ret[1], 'history.go(0)');
}

function seeElement(elemento){
    if(elemento.type == "checkbox"){
        if(elemento.checked) { return elemento.id+'=1'; }
        else { return elemento.id+'=0'; }
    }else{
        return elemento.id+'='+elemento.value;
    }
}

// Efetua a validação do form verificando se existe o caracter * no title
function validaForm(idForm){
    form = document.forms[0];
    for(x = 0; x < form.elements.length; x++){
        if(form.elements[x].title){
            title = form.elements[x].title;
            if(title.substr(0,1) == "*"){
                if(form.elements[x].value == ""){
                    title = title.substr(1, (title.length - 1));
                    popUp("<br/>PREENCHA O CAMPO "+title+" CORRETAMENTE.");
                    form.elements[x].focus();
                    return false;
                }
            }
        }
    }
    return true;
}

/*
function $(id){
    return document.getElementById(id);
}
*/

// Exibe as linhas que estão invisiveis
function showLine(id, show){
    div = document.getElementById(id);
    if(show){
        div.style.position   = 'relative';
        div.style.visibility = 'visible';
    }else{
        div.style.position   = 'absolute';
        div.style.visibility = 'hidden';
    }
}

function sendForm(urlSend){
    form = document.forms[0];
    qry = (urlSend.indexOf("?") > 0) ? "" : "?";
    for(x = 0; x < form.length; x++)
        if(form.elements[x].id) qry += seeElement(form.elements[x])+'&';
    qry = urlSend+"&"+qry.substring(0, (qry.length - 1));
    window.location.href = qry;
    return false;
}

function sendFormAjax(urlSend, funcRet){
    form = document.forms[0];
    qry  = urlSend.indexOf("?") > 0 ? "" : "?";
    for(x = 0; x < form.length; x++){
        if(form.elements[x].className == "valida"){
            if(form.elements[x].value == ""){
                title = form.elements[x].title;
                popUp('<br/>PREENCHA O CAMPO '+title.toUpperCase()+' CORRETAMENTE');
                form.elements[x].focus();
                return false;
            }else{
                if(form.elements[x].id) qry += seeElement(form.elements[x])+'&';
            }
        }else{
            if(form.elements[x].id) qry += seeElement(form.elements[x])+'&';
        }
    }
    qry = qry.substring(0, (qry.length - 1));
    rajax(urlSend + qry, '', '', '', funcRet);
    return false;
}

function destacaLinha(id, opc){
    var objLinha = document.getElementById(id);
    if(opc){
        objLinha.style.filter = 'alpha(opacity=65)';
        objLinha.style.opacity = 0.5;
    }else{
        objLinha.style.filter = 'alpha(opacity=100)';
        objLinha.style.opacity = 100;
    }
}

//Abre uma janela para envio do formulário de relatório
function openReport(target){
    config  = "width=682,height=650,location=no,menubar=no,rezisable=no,";
    config += "status=no,titlebar=no,scrollbars=yes,left=0,top=0";
    window.open("", target, config);
    window.setTimeout("document.forms[0].submit();", 500);
}


function ieupdate(){
    try{
        theObjects = document.getElementsByTagName("object");
        for (var i = 0; i < theObjects.length; i++) {
            theObjects[i].outerHTML = theObjects[i].outerHTML;
        }
    }catch(err){  }
}


function geraCons(url, idform, idret){
    loading('', 'rettxt');
    form    = document.getElementById(idform);
    nro     = form.elements.length;
    params  = "";
    for(x = 0; x < nro; x++){
        if(form.elements[x].id != "")
            params+= form.elements[x].id+"="+form.elements[x].value+"&";
    }
    if(params.length > 0) params = params.substr(0,(params.length - 1));
    rajax(url+'?'+params, '', idret, 'texto', '');
}



// Filipe Zeuch
//////////////////////////////
function abrejanela(evento){
    cima = screen.height-700;
    squerda = screen.width-730;
    var wnd = window.open('popUp/galeria/index.php?ev='+evento,'Galeria','toolbar=no,width=800,height=600,top='+cima/2+',left='+esquerda/2+',scrollbars=no');
}


function abrePopup(nome,ramoativ,cidade){
	local = 'popUp/lojas_conv.php?nome='+nome+'&ramoativ='+ramoativ+'&cidade='+cidade;
	largura = screen.width-100;
	altura = screen.height-100;
	window.open(local,'Conveniados','width='+largura+', height='+altura+',top=0, left=50, scrollbars=yes');
}
//////////////////fim
//////////////////////////////////////////////////////////////////////////////////////////////
