var tmr;
var tmr2;

//Loading na pagina
n = document.layers
ie = document.all

ns4 = (document.layers) ? true : false;
ie4 = (document.all) ? true : false;

function selecionar(idObjeto) {
    document.getElementById(idObjeto).select();
}

function MudarFoco(pObj) {
    try {
        if (pObj != null) {
            if (pObj.getAttribute("maxlength") != null) {
                if (pObj.getAttribute("maxlength") > 0) {
                    if (pObj.getAttribute("maxlength") == pObj.value.length) {
                        for (i = 0; i < pObj.form.elements.length; i++) {
                            if (pObj.form.elements[i].name == pObj.name) {
                                pObj.form.elements[i + 1].focus();
                            }
                        }
                    }
                }
            }
        }
    }
    catch (e) {
    }
}

function ZerarCampo(pObj) {
    if (pObj.value == '') {
        pObj.value = 0;
    }
}

function SomenteNumeros(evt) {
    var retorno = true;
    var keyCode = (evt.which) ? evt.which : event.keyCode;

    //alert("WHICH = " + keyCode.toString() + " E CHARCODE = " + evt.charCode.toString());

    if (!((keyCode > 47 && keyCode < 58)
       || keyCode == 8/* || keyCode==13*/)) {

        if (evt.which) {
            retorno = false;
        }
        else {
            event.keyCode = 0;
        }
    }

    return retorno;
}

function SomenteNumerosDecimais(pObj) {
    var keyCode = event.keyCode;

    //Bloqueia virgulas repetidas
    if ((pObj.value.indexOf(',') > -1) && (keyCode == 44)) {
        event.keyCode = 0;
    }

    //Bloqueia caracteres que nao sao numericos e nem virgulas
    if (!(keyCode > 47 && keyCode < 58) && (keyCode != 44)) {
        event.keyCode = 0;
    }
}

function AbrirPopup1(url, largura, altura) {
    topo = (screen.height / 2) - (altura / 2);
    esquerda = (screen.width / 2) - (largura / 2);

    window.open(url, "popup", 'width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,top=' + topo + ',left=' + esquerda);
}

function AbrirPopup2(url, largura, altura, scroll) {
    topo = (screen.height / 2) - (altura / 2);
    esquerda = (screen.width / 2) - (largura / 2);

    if (scroll != "1") {
        scroll = "no";
    }
    else {
        scroll = "yes";
    }

    window.open(url, "popup", 'width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scroll + ',resizable=no,top=' + topo + ',left=' + esquerda);
}

function SelecionarItemCombo(pCombo, pValor) {
    var combo = document.getElementById(pCombo);

    if (combo != null) {
        for (i = 0; i < combo.options.length; i++) {
            if (combo.options[i].value == pValor) {
                combo.selectedIndex = i;

                break;
            }
        }
    }
}

function CriaMascara(_RefObjeto, _Modelo) {
    var valorAtual = _RefObjeto.value;
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;


    // limpa a string valor atual para verificar
    // se todos os caracteres são números
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) != '#') {
            valorAtual = valorAtual.replace(_Modelo.substr(i, 1), '');
        }
    }

    // verifica se todos os caracteres são números
    for (i = 0; i < valorAtual.length; i++) {
        if (!isNaN(parseFloat(valorAtual.substr(i, 1)))) {
            valorNumerico = valorNumerico + valorAtual.substr(i, 1);
        }
    }

    // aplica a máscara ao campo informado usando
    // o modelo de máscara informado no script
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) == '#') {
            if (valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
                nIndexModelo++;
                nIndexString++;
            }
            else {
                adicionarValor = false;
            }
        }
        else {
            if (adicionarValor && valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
                nIndexString++;
            }
        }
    }

    _RefObjeto.value = valorFinal
}

function CriaMascaraAlpha(_RefObjeto, _Modelo) {
    var valorAtual = _RefObjeto.value;
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;

    // limpa a string valor atual para verificar
    // se todos os caracteres são números
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) != '#') {
            valorAtual = valorAtual.replace(_Modelo.substr(i, 1), '');
        }
    }

    // verifica se todos os caracteres são números
    for (i = 0; i < valorAtual.length; i++) {
        //if (isNaN(parseFloat(valorAtual.substr(i,1))) ||
        //    !isNaN(parseFloat(valorAtual.substr(i,1))))
        //{
        valorNumerico = valorNumerico + valorAtual.substr(i, 1);
        //}
    }

    // aplica a máscara ao campo informado usando
    // o modelo de máscara informado no script
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) == '#') {
            if (valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
                nIndexModelo++;
                nIndexString++;
            }
            else {
                adicionarValor = false;
            }
        }
        else {
            if (adicionarValor && valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
                nIndexString++;
            }
        }
    }

    _RefObjeto.value = valorFinal
}

function ExibirDiv(pObj, pVisivel) {
    if (pObj != null) {
        if (pVisivel) {
            document.getElementById(pObj).style.display = 'block';
        }
        else {
            document.getElementById(pObj).style.display = 'none';
        }
    }
}

function MudarCorLabel(pObj, pMudar) {
    if (pObj != null) {
        if (pMudar) {
            document.getElementById(pObj).style.color = '#FF0000';
        }
        else {
            document.getElementById(pObj).style.color = '#000000';
        }
    }
}

function SetarTexto(pObj, pTexto) {
    if (pObj != null) {
        document.getElementById(pObj).innerHTML = pTexto;
    }
}

function CampoDecimal(Campo, precisao) {
    var Caracteres = "0123456789,";
    var Keyascii = event.keyCode;

    var carac = String.fromCharCode(Keyascii);

    if (Caracteres.indexOf(String.fromCharCode(Keyascii)) == -1) {
        event.returnValue = 0;
        return;
    }

    if (Campo.value.indexOf(",") != -1) {
        if (carac == ",") {
            //impede mais de uma virgula
            event.returnValue = 0;
            return;
        }

        var arrChar = Campo.value.split(",")
        var x = arrChar[1];

        if (x.length >= precisao) {
            event.returnValue = 0;
            return;
        }
    }
    else {
        if (Campo.value.length < (Campo.maxLength - precisao)) {
            if (Campo.value.length == (Campo.maxLength - precisao - 1)) {
                if (carac != ",") {
                    event.returnValue = 0;
                }
            }
        }
        else {
            event.returnValue = 0;
        }
        return;
    }
}

function findPos(obj) {
    var curleft = curtop = 0;

    if (obj.offsetParent) {
        curleft = obj.offsetLeft;
        curtop = obj.offsetTop;

        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }

    return [curleft, curtop];
}

function SomenteEmail(e) {
    var keyNumber = (isIE) ? event.keyCode : e.which;
    if (
			!(
				(
					((keyNumber > 43) && (keyNumber < 58)) ||
					((keyNumber > 63) && (keyNumber < 91)) ||
					((keyNumber > 96) && (keyNumber < 123)) ||
					((keyNumber > 191) && (keyNumber < 221)) ||
					((keyNumber > 223) && (keyNumber < 253)) ||
					(keyNumber == 32) ||
					(keyNumber == 8) ||
					(keyNumber == 95)
				) &&
				(keyNumber != 168)
			)
		) {
        if (isIE) {
            event.keyCode = 0
        }
        return false;
    }
    return true;
}

function PreloadImages() {
    var d = document;

    if (d.images) {
        if (!d.MM_p) {
            d.MM_p = new Array();
        }

        var i, j = d.MM_p.length, a = 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 Bloquear_Enter() {
    var objEvent = event.srcElement;

    if (event.keyCode == 13 && objEvent.id == "") {
        // Cancela o evento default
        event.returnValue = false;
        event.cancel = true;

        //btn.click(); 
    }
}

function ForcarOnKeyPress(pObj) {
    var obj = document.getElementById(pObj);

    if (obj != null) {
        try {
            obj.onkeypress();
        }
        catch (e) {
            a = e.toString();
        }
    }
}

function currencyFormat(fld, milSep, decSep, e) {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;

    if (whichCode == 13) return true;  // Enter

    key = String.fromCharCode(whichCode);  // Get key value from key code

    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key

    len = fld.value.length;

    for (i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;

    aux = '';

    for (; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i)) != -1) aux += fld.value.charAt(i);
    aux += key;

    len = aux.length;

    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0' + decSep + '0' + aux;
    if (len == 2) fld.value = '0' + decSep + aux;

    if (len > 2) {
        aux2 = '';

        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }

        fld.value = '';
        len2 = aux2.length;

        for (i = len2 - 1; i >= 0; i--)
            fld.value += aux2.charAt(i);

        fld.value += decSep + aux.substr(len - 2, len);
    }

    return false;
}


function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

function 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_openBrWindow(theURL, winName, features) { //v2.0
    window.open(theURL, winName, features);
}

function dateDifference(strDate1, strDate2) {
    var date1 = document.getElementById(strDate1).value;
    var date2 = document.getElementById(strDate2).value;

    date1 = date1.split("/");
    date2 = date2.split("/");

    var sDate = new Date(date1[1] + "/" + date1[0] + "/" + date1[2]);
    var eDate = new Date(date2[1] + "/" + date2[0] + "/" + date2[2]);

    var daysApart = Math.abs(Math.round((sDate - eDate) / 86400000)) + 1;

    if (eDate < sDate) {
        return -1;
    }
    else {
        return daysApart;
    }
}

function Load_Page() {
    if (ie || n) {
        if (n) {
            if (document.divLoadCont != null) {
                document.divLoadCont.visibility = "hidden"
            }
        }
        else {
            if (divLoadCont != null) {
                divLoadCont.style.visibility = "hidden"
            }
        }
    }
}

function pause(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;

    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}

function trataBackSpaceMascaraValorRT(campo, event) {
    NumDig = campo.value;
    TamDig = NumDig.length;
    TamDig--;
    Contador = 0;

    if ((TamDig >= 0) && (event.keyCode == 8)) {
        numer = "";
        for (i = TamDig; (i >= 0); i--) {
            if ((parseInt(NumDig.substr(i, 1)) >= 0) && (parseInt(NumDig.substr(i, 1)) <= 9)) {
                Contador++;
                /*alert(NumDig.substr(i, 1) + " Contador " + Contador+ " numer "+ numer+ " TamDig " +TamDig + " i " + i );*/
                if ((Contador == 4) && ((TamDig - i) < 5)) {
                    numer = "," + numer;
                    Contador = 0;
                }
                else if ((Contador == 3) && ((numer.length) > 4)) {
                    numer = "." + numer;
                    Contador = 0;
                }

                numer = NumDig.substr(i, 1) + numer;

            }
        }
        if (numer == "001" || numer == "000" || numer == "002" || numer == "003" || numer == "004" || numer == "005" || numer == "006" || numer == "007" || numer == "008" || numer == "009") {
            numer = "";
        }

        if ((numer.length) == 3) {
            numer = "0," + numer;
        }

        if (getNavigatorName() == 'NETSCAPE') //Hack para FF , para a máscara funcionar corretamente
        {
            //Retira o último dígito quando tiver mais de 2 casas decimais, ex. se numer = 0,200 ficará 0,20
            if ((numer.length - (numer.indexOf(",") + 1)) > 2) {
                numer = numer.substring(0, (numer.length - 1));
            }
        }

        campo.value = numer;
    };
}

function getNavigatorName() {
    //alert(navigator.appName.toUpperCase());
    return navigator.appName.toUpperCase();
}

function mascaraValorRT(fld, milSep, decSep, e) {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    var navegador = getNavigatorName();

    //    alert(getNavigatorName());

    if (navegador != 'NETSCAPE') {
        trataBackSpaceMascaraValorRT(fld, e);
    }

    if (whichCode == 13) return true;  // Enter
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    len = fld.value.length;
    for (i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i)) != -1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0' + decSep + '0' + aux;
    if (len == 2) fld.value = '0' + decSep + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--) fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - 2, len);
    }

    return false;
}

function trataBackSpaceMascaraValorRT4CasasDecimais(campo, event) {
    NumDig = campo.value;
    TamDig = NumDig.length;
    TamDig--;
    Contador = 0;

    if ((TamDig >= 0) && (event.keyCode == 8)) {
        numer = "";
        for (i = TamDig + 1; (i >= 0); i--) {
            if ((parseInt(NumDig.substr(i, 1)) >= 0) && (parseInt(NumDig.substr(i, 1)) <= 9)) {
                Contador++;
                /*alert(NumDig.substr(i, 1) + " Contador " + Contador+ " numer "+ numer+ " TamDig " +TamDig + " i " + i );*/
                if ((Contador == 6) && ((TamDig - i) < 7)) {
                    numer = "," + numer;
                    Contador = 0;
                }
                else if ((Contador == 5) && ((numer.length) > 6)) {
                    numer = "." + numer;
                    Contador = 0;
                }

                numer = NumDig.substr(i, 1) + numer;

            }
        }
        if (numer == "00000" || numer == "00001" || numer == "00002" || numer == "00003" || numer == "00004" || numer == "00005" || numer == "00006" || numer == "00007" || numer == "00008" || numer == "00009")
            numer = "";
        if ((numer.length) == 5)
            numer = "0," + numer;

        if (numer.indexOf(",") == 1 && numer.length > 4) {
            numer = numer.substring(1, 3);

            alert("Restrito");
        }

        campo.value = numer;
    };
}

function mascaraValorRT4CasasDecimais(fld, milSep, decSep, e) {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;

    trataBackSpaceMascaraValorRT4CasasDecimais(fld, e);

    if (whichCode == 13) return true;  // Enter
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    len = fld.value.length;
    for (i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i)) != -1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0' + decSep + '000' + aux;
    if (len == 2) fld.value = '0' + decSep + '00' + aux;
    if (len == 3) fld.value = '0' + decSep + '0' + aux;
    if (len == 4) fld.value = '0' + decSep + aux;
    if (len > 4) {
        aux2 = '';
        for (j = 0, i = len - 5; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--) fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - 4, len);
    }
    return false;
}

function arredondar(valor, casas) {
    var numberField = valor;
    var rnum = numberField.value;
    var rlength = casas; // The number of decimal places to round to

    if (rnum > 8191 && rnum < 10485) //Isso devido a um BUG do Javascript
    {
        rnum = rnum - 5000;
        var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
        newnumber = newnumber + 5000;
    }
    else {
        var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    }

    return newnumber;
}

function ExisteBloqueadorPopup() {
    var mine = window.open('', '', 'width=1,height=1,left=-10,top=-10,scrollbars=no');
    var popUpsBlocked;

    if (mine != null) {
        if (mine) {
            popUpsBlocked = false
        }
        else {
            popUpsBlocked = true
        }

        mine.close();
    }
    else {
        popUpsBlocked = true
    }

    if (popUpsBlocked) {
        alert('Foi detectado que você está usando bloqueador de popup. Por favor, desabilite o bloqueador, pois algumas funcionalidades da loja dependem de popups.');
    }

    return popUpsBlocked;
}

function InserirTelefone(obj) {
    var nomeLinha = obj.id.replace('imbAdd', 'linha');
    var nomeTabela = obj.id.replace('imbAdd', 'tabelaPrincipal');
    var objLinha = document.getElementById(nomeLinha);
    var objTabela = document.getElementById(nomeTabela);
    var tabela = null;

    //Clona a tabela
    tabela = objTabela.cloneNode(true);

    //Limpa o nome dela
    tabela.setAttribute('id', '');

    //Limpa a caixa de telefone
    tabela.childNodes(0).childNodes(0).childNodes(0).childNodes(0).value = '';

    //Limpa a caixa de ramal
    tabela.childNodes(0).childNodes(0).childNodes(2).childNodes(0).value = '';

    //IdTelefone
    tabela.childNodes(0).childNodes(0).childNodes(3).childNodes(0).value = '0';

    objLinha.childNodes(1).appendChild(tabela);

    return false;
}

function RemoverTelefone(obj) {
    var nomeLinha = obj.id.replace('imbRem', 'linha');
    var objLinha = document.getElementById(nomeLinha);
    var qtdTabelas = objLinha.childNodes(1).childNodes.length;

    if (qtdTabelas > 1) {
        objLinha.childNodes(1).removeChild(objLinha.childNodes(1).childNodes(parseInt(qtdTabelas) - 1));
    }

    return false;
}

function ColetarTelefones() {
    return true;

    var hddTelefones = null;
    var tabela = null;
    var qtdTabelas = 0;
    var idTipoTelefone = 0;
    var idTelefone = 0;
    var todosTelefones = '';

    hddTelefones = document.getElementById('ctl00_ContentPlaceHolder1_hddTels');
    tabela = document.getElementById('ctl00_ContentPlaceHolder1_tblTelefones');

    //Pega o valor dos hiddens de tipo de telefone:
    //alert(tabela.rows[i].childNodes(0).getElementsByTagName('input')[0].value);

    //Retorna qtas tabelas existem de telefone dentro da linha
    //tabela.rows[i].childNodes(1).getElementsByTagName('table').length

    for (i = 0; i < tabela.rows.length; i++) {
        idTipoTelefone = tabela.rows[i].childNodes(0).getElementsByTagName('input')[0].value;
        qtdTabelas = tabela.rows[i].childNodes(1).getElementsByTagName('table').length;

        for (j = 0; j < qtdTabelas; j++) {
            telefone = tabela.rows[i].childNodes(1).childNodes(j).childNodes(0).childNodes(0).getElementsByTagName('input')[0].value;
            ramal = tabela.rows[i].childNodes(1).childNodes(j).childNodes(0).childNodes(0).getElementsByTagName('input')[1].value;
            idTelefone = tabela.rows[i].childNodes(1).childNodes(j).childNodes(0).childNodes(0).getElementsByTagName('input')[2].value;

            todosTelefones += idTipoTelefone + ';' + idTelefone + ';' + telefone + ';' + ramal + '|';
        }
    }

    hddTelefones.value = todosTelefones;

    return true;
}

function ValidarDataDigitacao(pObj) {
    if (pObj.value != "") {
        if (!Data_Valida(pObj)) {
            alert("Data inválida!");
            event.keyCode = 0;
            pObj.value = '';
            pObj.focus();
        }
    }
}

function Data_Valida(obj) {
    var data = obj.value;
    var barra1 = data.indexOf('/');
    var barra2 = data.lastIndexOf('/');
    var ano = data.substring(barra2 + 1, data.length);
    var dia = data.substring(0, barra1);
    var mes = data.substring(barra1 + 1, barra2);
    var anoMod = ano % 4;
    var mesMod = mes % 2;
    var retorno = true;

    //verifica as barras
    if ((barra1 == -1) || (barra1 == barra2)) {
        retorno = false;
    }

    // verifica se os campos dia, ano , mes são numéricos e se possuem a quantidade de caracteres suficientes
    if ((isNaN(ano)) || (isNaN(dia)) || (isNaN(mes)) || (ano < 1900) || (ano > 2200) || (mes < 1) || (mes > 12) || (dia > 31) || (dia < 1)) {
        retorno = false;
    }

    // ferifica o mes de fevereiro
    if ((((anoMod != 0) && (dia > 28)) || ((anoMod == 0) && (dia > 29))) && (mes == 2)) {
        retorno = false;
    }

    if (mesMod == 1) {
        if ((mes >= 9) && (dia > 30)) {
            retorno = false;
        }
    }
    else {
        if ((mes < 7) && (dia > 30)) {
            retorno = false;
        }
    }

    if ((retorno == false)) {
        return false;
    }
    else {
        return (true);
    }
}

function BuscarPorMarca() {
    var obj = actb(document.getElementById('ctl00$TituloLoja1$txtBusca'), descricaoMarcas);
}

function BuscarPorProduto() {
    var obj = actb(document.getElementById('ctl00$TituloLoja1$txtBusca'), descricaoProdutos);
}

function Arredondar(valor, casas) {
    //var numberField = valor;
    var rnum = valor;
    var rlength = casas; // The number of decimal places to round to

    if (rnum > 8191 && rnum < 10485) //Isso devido a um BUG do Javascript
    {
        rnum = rnum - 5000;
        var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
        newnumber = newnumber + 5000;
    }
    else {
        var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    }

    return newnumber;
}

function CalcularCartaoCreditoText(obj) {
    var lblInfoParcelamento = document.getElementById(obj.id.replace('txtValorPago', 'lblInfoParcelamento'))
    var ddlQtdParcelas = document.getElementById(obj.id.replace('txtValorPago', 'ddlQtdParcelas'))

    if (obj.value != "") {
        CalcularValorCartaoCredito(obj.value, ddlQtdParcelas.value, lblInfoParcelamento);
    }
}

function CalcularCartaoCreditoCombo(obj) {
    var lblInfoParcelamento = document.getElementById(obj.id.replace('ddlQtdParcelas', 'lblInfoParcelamento'))
    var valorDigitado = document.getElementById(obj.id.replace('ddlQtdParcelas', 'txtValorPago'))

    if (valorDigitado != "") {
        CalcularValorCartaoCredito(valorDigitado.value, obj.value, lblInfoParcelamento);
    }
}

function CalcularValorCartaoCredito(valor, parcelas, lblInfo) {
    valor = valor.replace('.', '');
    valor = valor.replace(',', '.');

    var valorDigitado = parseFloat(valor);
    var qtdParcelas = parseInt(parcelas);
    var temDizima = false;
    var valorPrimeiraParcelaDizima = 0;
    var valorDemaisParcelaDizima = 0;
    var valorParcela = 0;
    var lblInfoParcelamento = lblInfo;

    valorParcela = Arredondar((valorDigitado / qtdParcelas), 2);

    //Verifica se existe dizima periodica
    if ((valorParcela * parcelas) != valor) {
        temDizima = true;
    }

    if (temDizima) {
        valorDemaisParcelaDizima = Arredondar(valorParcela, 2);

        valorPrimeiraParcelaDizima = Arredondar(valor - (valorDemaisParcelaDizima * (parcelas - 1)), 2);

        lblInfoParcelamento.innerHTML = '<b>1x</b> de R$ ' + valorPrimeiraParcelaDizima.toString() + '<br /><b>' + (qtdParcelas - 1).toString() + 'x</b> de R$ ' + valorDemaisParcelaDizima.toString();
    }
    else {
        lblInfoParcelamento.innerHTML = '<b>' + parcelas.toString() + 'x</b> de R$ ' + valorParcela.toString();
    }
}

function CheckarCartaoCredito(obj) {
    var chkSel = document.getElementById(obj.id.replace('txtNumeroCartao', 'chkSel'));

    if (chkSel != null) {
        chkSel.checked = (obj.value.length > 0);
    }
}

function VerificarPagamentoCarrinho() {
    var retorno = false;
    var objValorHdd = document.getElementById('ctl00_ContentPlaceHolder1_hddFaltaPagar');
    var valor = objValorHdd.value.replace('.', '');
    valor = valor.replace(',', '.');

    retorno = true;

    //    if(parseFloat(valor) > 0)
    //    {
    //        alert('Ainda existe valor da compra para ser pago!');
    //    }
    //    else
    //    {
    //        retorno = true;
    //    }

    return retorno;
}

//function MudarLabelPessoaTelaLoginCadastroInicial(idObj, IdlblCNPJ, IdlblCPF) 
//{
//    MudarLabelPessoaTelaLoginCadastro(document.getElementById(idObj), IdlblCNPJ, IdlblCPF);
//}

function MudarLabelPessoaTelaLoginCadastro(obj, IdlblCNPJ, IdlblCPF, IdtxtCPFCNPJ) {
    var nomeObj = obj.id;
    var nomeTxt = null;

    txt = document.getElementById(IdtxtCPFCNPJ);

    lblCPF = document.getElementById(IdlblCPF);
    lblCNPJ = document.getElementById(IdlblCNPJ);

    if (nomeObj.indexOf('Fisica') > 0) {
        lblCPF.style.display = 'block';
        lblCNPJ.style.display = 'none';
        txt.focus();
    }
    else {
        lblCPF.style.display = 'none';
        lblCNPJ.style.display = 'block';
        txt.focus();
    }

    //    if (nomeObj.indexOf('Fisica') > 0) 
    //    {
    //        nomeLabelFisica = nomeObj.replace('rdbFisica', 'lblCPFCNPJ');
    //        
    //        nomeLabelJuridica = nomeObj.replace('rdbJuridica', 'lblCNPJ');
    //        
    //        nomeTxt = nomeObj.replace('rdbFisica', 'txtCNPJCPF');

    //        lblFisica = document.getElementById(nomeLabelFisica);
    //        lblJuridica = document.getElementById(nomeLabelJuridica); 
    //        
    //        txt = document.getElementById(nomeTxt);

    //        lblFisica.style.display = 'hidden';
    //        lblJuridica.style.display = 'none';

    //        
    //        //lbl.innerHTML = 'CPF:';
    //        txt.focus();
    //    }


    //    //    function ValidarCPF(cpf) 
    //    //{
    //    //    if (cpf == '')
    //    //    {
    //    //      return false;
    //    //    }
    //    //    
    //    //    if (cpf.length < 11 || cpf.length > 11)
    //    //    {
    //    //      return false;
    //    //    }
    //    //    
    //    //    
    //    //
    //    else 
    //    {
    //        nomeLabelFisica = nomeObj.replace('rdbFisica', 'lblCPFCNPJ');
    //        nomeLabelJuridica = nomeObj.replace('rdbJuridica', 'lblCNPJ');
    //        
    //        nomeTxt = nomeObj.replace('rdbJuridica', 'txtCNPJCPF');

    //        lblFisica = document.getElementById(nomeLabelFisica);
    //        lblJuridica = document.getElementById(nomeLabelJuridica);
    //        
    //        txt = document.getElementById(nomeTxt);

    //        lblFisica.style.display = 'none';
    //        lblJuridica.style.display = 'hidden';

    //        //lbl.innerHTML = 'CNPJ:';
    //        txt.focus();
    //    }
}



//Valida o Enter para as caixas de texto expecificadas
function LogarClick(senderName, e) {
    var keyNumber = (ie4) ? event.keyCode : e.which;
    var retorno = true;

    if (keyNumber == 13) {
        switch (senderName) {
            case "ctl00_ContentPlaceHolder1_LoginJaSouCliente1_txtEmail":
                document.getElementById('ctl00_ContentPlaceHolder1_LoginJaSouCliente1_txtSenha').focus();

                retorno = false;

                break;

            case "ctl00_ContentPlaceHolder1_LoginJaSouCliente1_txtSenha":
                document.getElementById('ctl00_ContentPlaceHolder1_LoginJaSouCliente1_btnAvancar').focus();
                document.getElementById('ctl00_ContentPlaceHolder1_LoginJaSouCliente1_btnAvancar').click();

                retorno = false;

                break;

            case "ctl00_ContentPlaceHolder1_LoginNovoCliente1_txtCNPJCPF":
                document.getElementById('ctl00_ContentPlaceHolder1_LoginNovoCliente1_imbNovoCliente').focus();
                document.getElementById('ctl00_ContentPlaceHolder1_LoginNovoCliente1_imbNovoCliente').click();

                retorno = false;

                break;

            case "ctl00_TituloLoja1_txtBusca":
                document.getElementById('ctl00_TituloLoja1_cmdBuscar').focus();
                document.getElementById('ctl00_TituloLoja1_cmdBuscar').click();

                retorno = false;

                break;
        }
    }

    return retorno;
}

//Adicionado Felipe , formata a data durante a digitação
function FormataData(Campo, teclapres) {
    var tecla = teclapres.keyCode;
    var sel;
    var vr = new String(Campo.value);

    vr = vr.replace("/", "");
    vr = vr.replace("/", "");

    tam = vr.length + 1;

    var strValidos = "0123456789"
    if (strValidos.indexOf(String.fromCharCode(tecla)) < 0 && tecla != 8 && tecla != 9) {
        teclapres.keyCode = 0;
        tecla = 0;
        return false;
    }

    if (tecla != 9 && tecla != 8) {
        if (tam > 2 && tam < 5)
            Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
        if (tam >= 5 && tam <= 10)
            Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4, 4);
        //var tfinal = new String(Campo.value);
        if (vr.length >= 7) {
            if (vr.length < 8) {
                Campo.value = Campo.value + String.fromCharCode(teclapres.keyCode);
                vr += String.fromCharCode(teclapres.keyCode);
            }
            teclapres.keyCode = 0;
            var tdata = new Date(vr.substr(2, 2) + '/' + vr.substr(0, 2) + '/' + vr.substr(4, 4));

            if (isNaN(tdata)) {
                alert("Valor de data inválido");
                return false;
            }

            if (validaData(vr)) {
                focusNext(Campo.tabIndex);
                return true;
            }

            alert("Valor de data inválido");
            return false;
        }
    }
    return false;
}

//Usada pela função FormataData
function validaData(vr) {
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");

    if (vr.length < 8) {
        return false;
    }

    if ((Math.abs(vr.substr(2, 2)) == 1 || Math.abs(vr.substr(2, 2)) == 3 || Math.abs(vr.substr(2, 2)) == 5 || Math.abs(vr.substr(2, 2)) == 7 || Math.abs(vr.substr(2, 2)) == 8 || Math.abs(vr.substr(2, 2)) == 10 || Math.abs(vr.substr(2, 2)) == 12) && (Math.abs(vr.substr(0, 2)) >= 1 && Math.abs(vr.substr(0, 2)) <= 31) && (Math.abs(vr.substr(4, 4)) >= 1900 && Math.abs(vr.substr(4, 4)) <= 2300)) {
        return true;
    }

    if ((Math.abs(vr.substr(2, 2)) == 4 || Math.abs(vr.substr(2, 2)) == 6 || Math.abs(vr.substr(2, 2)) == 9 || Math.abs(vr.substr(2, 2)) == 11) && (Math.abs(vr.substr(0, 2)) >= 1 && Math.abs(vr.substr(0, 2)) <= 30) && (Math.abs(vr.substr(4, 4)) >= 1900 && Math.abs(vr.substr(4, 4)) <= 2300)) {
        return true;
    }

    if ((Math.abs(vr.substr(2, 2)) == 2) && ((Math.abs(vr.substr(0, 2)) >= 1 && Math.abs(vr.substr(0, 2)) <= 29 && AnoBissexto(Math.abs(vr.substr(4, 4)))) || (Math.abs(vr.substr(0, 2)) >= 1 && Math.abs(vr.substr(0, 2)) <= 28 && !AnoBissexto(Math.abs(vr.substr(4, 4))))) && (Math.abs(vr.substr(4, 4)) >= 1900 && Math.abs(vr.substr(4, 4)) <= 2300)) {
        return true;
    }

    return false;
}

//Seleciona o foco do proximo controle
function focusNext(atual) {
    for (var i = 0; i < document.forms[0].elements.length; i++) {
        if (document.forms[0].elements[i].tabIndex >= (atual + 1) && document.forms[0].elements[i].style.visibility != 'hidden' && document.forms[0].elements[i].style.display != 'none') {
            try {
                document.forms[0].elements[i].focus();

                return true;
            }
            catch (ex) {
            }
        }
    }

    return false;
}

//Permite somente Numero
function soNumero(teclapress) {
    var charCode = (teclapress.which) ? teclapress.which : teclapress.keyCode;

    /*return ((charCode >= 48 && charCode <= 57) || //Numeros
    charCode == 46 || //Delete
    charCode == 8 ||  //Backspace
    (charCode >= 37 && charCode <= 40)); //Setas*/

    var tecla = charCode;
    var chars = new String("0123456789");

    if (chars.indexOf(String.fromCharCode(tecla)) < 0 &&
	    tecla != 8 &&
	    tecla != 37 &&
	    tecla != 39) {
        return false
    }
    else if (String.fromCharCode(tecla) == ".") {
        return false;
    }

    return true;
}

//Permite somente Numero
function soNumeroMoeda(teclapress) {
    var tecla = teclapress.keyCode;
    var chars = new String("0123456789,");

    if (chars.indexOf(String.fromCharCode(tecla)) < 0) {
        teclapress.keyCode = 0;
        return false;
    }

    return true;
}

function SomenteCPFCNPJ(teclapress) {
    var tecla = (teclapress.which) ? teclapress.which : teclapress.keyCode;
    var chars = new String("0123456789.-/");

    if (chars.indexOf(String.fromCharCode(tecla)) < 0 &&
	    (tecla != 8 &&
	     tecla != 37 &&
	     tecla != 39)) {
        if (ie4) {
            teclapress.keyCode = 0;
        }

        return false;
    }

    return true;
}

function AbrirImagemProduto(idProduto) {
    var largura = 700;
    var altura = 500;
    var CentroVerticalJanela = (altura / 2);
    var CentroHorizontalJanela = (largura / 2);

    var CentroVertical = (screen.availHeight / 2);
    var CentroHorizontal = (screen.availWidth / 2);

    var parametros = "height=" + altura + ",width=" + largura + ",status=no,toolbar=no,top=" + (CentroVertical - CentroVerticalJanela) + ",left=" + (CentroHorizontal - CentroHorizontalJanela) + ",menubar=no,location=no";

    var janela = window.open("VisualizarImagemProduto.aspx?id=" + idProduto, null, parametros);

    if (janela == null) //Verifica se tem bloqueador de popup
    {
        alert('Atenção! O bloqueador de Popup do seu navegador esta ativado.Desative ele para poder visualizar a Imagem.');
    }
}

function clickIE() {
    if (document.all) {
        return false;
    }
}

function clickNS(e) {
    if (document.layers || (document.getElementById && !document.all)) {
        if (e.which == 2 || e.which == 3) {
            return false;
        }
    }
}

if (document.layers) {
    document.captureEvents(Event.MOUSEDOWN);
    document.onmousedown = clickNS;
}
else {
    document.onmouseup = clickNS;
    document.oncontextmenu = clickIE;
}

document.oncontextmenu = new Function('return false'); //Desativa o menu com o clique direito do mouse   

function clearData() //Desabilita o print screen da tela
{
    //window.clipboardData.setData('text','') 
}

function deldat() //Desabilita cópia de texto da loja
{
    //    if(clipboardData)
    //    {
    //        //window.clipboardData.clearData();
    //    }
}

//setInterval("deldat();", 200);
//setInterval("window.clipboardData.clearData()",500); //Limpa o copiar e colar da janela

function Bloquear_Enter_Caixa(e) {
    var intKey = (window.Event) ? e.which : e.keyCode;

    if (intKey == 13) {
        e.which = 0;
        e.keyCode = 0;

        return false;
    }

    return true;
}

function AvancarClick(aParameter) {
    document.getElementById(aParameter).style.heigth = '0px';
    document.getElementById(aParameter).style.width = '0px';
    document.getElementById('lblAguarde').style.display = 'block';

    return true;
}

function FinalizarCadastro(obj) {
    var retorno;

    retorno = ColetarTelefones();

    if (retorno) {
        retorno = AvancarClick(obj);
    }

    return retorno;
}

function ValidarPesquisaCEP() {
    var ret = true;
    var cmbUF = document.getElementById('cmbUF');
    var cmbMunicipios = document.getElementById('cmbMunicipios');
    var txtBairro = document.getElementById('txtBairro');
    var txtLogradouro = document.getElementById('txtDescricaoLogradouro');

    if (cmbUF.value == "0") {
        alert('Selecione um estado');
        cmbUF.focus();
        ret = false;
    }

    if (cmbMunicipios.value == "0" && ret) {
        alert('Selecione um município');
        cmbMunicipios.fucus();
        ret = false;
    }

    if (txtLogradouro.value == "" && txtBairro.value == "" && ret) {
        alert('Digite o bairro ou então um endereco');

        ret = false;
    }

    return ret;
}

function CEPValido(obj) {
    var retorno = true;
    var strCep = document.getElementById(obj);

    strCep = strCep.value;
    strCep = replaceAll(strCep, '.', '');
    strCep = replaceAll(strCep, '-', '');

    if (strCep.length < 8 &&
       strCep != '') {
        alert('CEP inválido! O CEP deve ter 8 números e não pode conter traços e nem pontos.');

        return false;
    }

    return true;
}

function replaceAll(str, from, to) {
    var idx = str.indexOf(from);

    while (idx > -1) {
        str = str.replace(from, to);
        idx = str.indexOf(from);
    }

    return str;
}

function ValidarCPFCNPJTelaLoginCadastro() {
    var txt = document.getElementById('ctl00_ContentPlaceHolder1_LoginNovoCliente1_txtCNPJCPF');
    var chkFisica = document.getElementById('ctl00_ContentPlaceHolder1_LoginNovoCliente1_rdbFisica');
    var chkJuridica = document.getElementById('ctl00_ContentPlaceHolder1_LoginNovoCliente1_rdbJuridica');
    var cpfcnpj = '';
    var retorno = true;


    cpfcnpj = replaceAll(txt.value, '-', '');
    cpfcnpj = replaceAll(cpfcnpj, '.', '');
    cpfcnpj = replaceAll(cpfcnpj, '\\', '');
    cpfcnpj = replaceAll(cpfcnpj, '/', '');
    cpfcnpj = replaceAll(cpfcnpj, ' ', '');


    if (chkFisica.checked) {

        if (!ValidarCPF(cpfcnpj)) {
            alert('CPF inválido!');
            txt.focus();

            retorno = false;
        }



    }


    else if (chkJuridica.checked) {

        if (!ValidarCNPJ(cpfcnpj)) {
            alert('CNPJ inválido!');
            txt.focus();

            retorno = false;
        }
    }

    return retorno;
}

function ValidarDigitacaoCPFCNPJ(idControle, evento) {
    var retorno = false;

    retorno = LogarClick(idControle, evento);

    if (!retorno) {
        return false;
    }

    retorno = SomenteCPFCNPJ(evento);

    if (!retorno) {
        return false;
    }

    return true;
}

function ValidarCNPJ(cnpj) {
    if (cnpj.length < 14 || cnpj.length > 14) {
        return false;
    }

    var nonNumbers = /\D/;

    if (nonNumbers.test(cnpj)) {
        return false;
    }

    var a = [];
    var b = new Number;
    var c = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];

    for (i = 0; i < 12; i++) {
        a[i] = cnpj.charAt(i);
        b += a[i] * c[i + 1];
    }

    if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11 - x }

    b = 0;

    for (y = 0; y < 13; y++) {
        b += (a[y] * c[y]);
    }

    if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11 - x; }

    if ((cnpj.charAt(12) != a[12]) || (cnpj.charAt(13) != a[13])) {
        return false;
    }

    return true;
}

function ValidarCPF(cpf) {
    if (cpf == '') {
        return false;
    }

    if (cpf.length < 11 || cpf.length > 11) {
        return false;
    }

    if (((cpf.length == 11) && (cpf == 11111111111) ||
                               (cpf == 22222222222) ||
                               (cpf == 33333333333) ||
                               (cpf == 44444444444) ||
                               (cpf == 55555555555) ||
                               (cpf == 66666666666) ||
                               (cpf == 77777777777) ||
                               (cpf == 88888888888) ||
                               (cpf == 99999999999) ||
                               (cpf == 00000000000))) {
        return false;
    }

    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

    for (I = 0; I <= 8; I++) {
        DIGITO[I] = cpf.substr(I, 1);
    }

    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];
    }

    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];
    }

    DV = DIGITO[9] * 10 + DIGITO[10];
    if (DV != DV_INFORMADO) {
        return false;
    }

    return true;
}

function VerificarEnderecoEntrega() {
    var ret = false;
    var hdd = document.getElementById('ctl00_ContentPlaceHolder1_hddEED');

    if (hdd != null) {
        if (hdd.value == "False") {
            alert("Selecione um dos endereços de entrega cadastrados.\n\nCaso não tenha, cadastre um através do botão 'Novo Endereço' no final da página");
        }
        else {
            ret = true;
        }
    }

    return ret;
}

function FormataDigitacaoCNPJ(campo, tammax, teclapres) {

    var tecla = teclapres.keyCode;
    var vr = campo.value;
    vr = vr.replace("-", "");
    vr = vr.replace("/", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    tam = vr.length;

    if (tam < tammax && tecla != 13) { tam = vr.length + 1; }

    if (tecla == 13) { tam = tam - 1; }

    if (tecla == 13 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)) {
        if (tam <= 2) {
            campo.value = vr;
        }
        tam = tam - 1;
        if ((tam > 2) && (tam <= 5)) {
            campo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam);
        }
        if ((tam >= 6) && (tam <= 8)) {
            campo.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
        }
        if ((tam >= 9) && (tam <= 11)) {
            campo.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
        }
        if ((tam >= 12) && (tam <= 14)) {
            campo.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
        }

    }



    function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
        var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, nTecla;

        if (document.all) {
            nTecla = evtKeyPress.keyCode;
        }
        else if (document.layers) {
            nTecla = evtKeyPress.which;
        }

        sValue = objForm[strField].value;

        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;
        }


        function BoxFormat(objForm, strField, strfull, sMask) {
            var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, nTecla;

            sValue = strfull;

            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;
            }
        }

    }
}

function VerEbit() {
    var frmEbit = null;

    if (ie4) {
        frmEbit = document.getElementById('formebit');
    }
    else {
        frmEbit = document.formebit;
    }

    if (frmEbit != null) {
        frmEbit.submit();
    }
}

//Repeti, pois nao quero q apareca parametros JS na barra de status
function AvaliacaoEbit() {
    var frmEbit = null;

    if (ie4) {
        frmEbit = document.getElementById('formebit2');
    }
    else {
        frmEbit = document.formebit2;
    }

    if (frmEbit != null) {
        frmEbit.submit();
    }
}

function rtrim(stringToTrim) {
    return stringToTrim.replace(/\s+$/, "");
}

function ltrim(stringToTrim) {
    return stringToTrim.replace(/^\s+/, "");
}


function tipoBrowser() {
    var tb = null;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        tb = 'ie';
    }
    else {
        tb = 'mz';
    }

    return tb;
}

function fitStringToWidth(str, width, className, insereReticencias) {
    // str    A string where html-entities are allowed but no tags.  
    // width  The maximum allowed width in pixels  
    // className  A CSS class name with the desired font-name and font-size. (optional)  
    // ----  
    // _escTag is a helper to escape 'less than' and 'greater than'
    function _escTag(s) { return s.replace("<", "&lt;").replace(">", "&gt;"); }

    //Create a span element that will be used to get the width  
    var span = document.createElement("span");
    //Allow a classname to be set to get the right font-size.
    if (className) span.className = className;

    span.style.display = 'inline';
    span.style.visibility = 'hidden';
    span.style.padding = '0px';
    document.body.appendChild(span);

    var result = _escTag(str);

    // default to the whole string
    if (tipoBrowser() == 'ie') {
        span.innerText = result;
    }
    else {
        span.innerHTML = result;
    }

    // Check if the string will fit in the allowed width. NOTE: if the width  
    // can't be determinated (offsetWidth==0) the whole string will be returned.  
    if (span.offsetWidth > width) {
        var posStart = 0, posMid, posEnd = str.length, posLength;
        // Calculate (posEnd - posStart) integer division by 2 and    
        // assign it to posLength. Repeat until posLength is zero.    
        while (posLength = (posEnd - posStart) >> 1) {
            posMid = posStart + posLength;
            //Get the string from the begining up to posMid;

            if (insereReticencias) {
                if (tipoBrowser() == 'ie') {
                    span.innerText = _escTag(str.substring(0, posMid)) + '...';
                } else {
                    span.innerHTML = _escTag(str.substring(0, posMid)) + '&hellip;';
                }
            }
            else {
                if (tipoBrowser() == 'ie') {
                    span.innerText = _escTag(str.substring(0, posMid));
                }
                else {
                    span.innerHTML = _escTag(str.substring(0, posMid));
                }
            }

            // Check if the current width is too wide (set new end)
            // or too narrow (set new start)      
            if (span.offsetWidth > width) posEnd = posMid; else posStart = posMid;
        }

        if (insereReticencias) {
            if (tipoBrowser() == 'ie') {
                result = _escTag(str.substring(0, posStart)) + '...';
            } else {
                result = _escTag(str.substring(0, posStart)) + '&hellip;';
            }
        }
        else {
            result = _escTag(str.substring(0, posStart));
        }
    }

    document.body.removeChild(span);

    return result;
}

function LimitarTexto(textoPuro, quantidadeLinhas, larguraDiv, classeCSS, nomeDiv) {
    var texto = null;
    var textoOriginal = null;
    var qtdLinhas = quantidadeLinhas;
    var textoTemp = '';
    var proximoCaractere = null;

    texto = '';

    if (tipoBrowser() == 'ie') {
        textoOriginal = replaceAll(textoPuro, '&nbsp;', ' ');
    } else {
        textoOriginal = textoPuro;
    }

    for (var i = 0; i < qtdLinhas; i++) {
        if ((i + 1) == qtdLinhas) {
            textoTemp = fitStringToWidth(textoOriginal, larguraDiv, classeCSS, 0);

            textoTemp = ltrim(textoTemp);

            if (textoOriginal == textoTemp) {
                texto += textoTemp;
            }
            else {
                if (tipoBrowser() == 'ie') {
                    texto += textoTemp.substring(0, textoTemp.length - 4) + '...';
                } else {
                    texto += textoTemp.substring(0, textoTemp.length - 4) + '&hellip;';
                }
            }
        }
        else {
            textoTemp = fitStringToWidth(textoOriginal, larguraDiv, classeCSS, 0);

            proximoCaractere = textoOriginal.substr(textoTemp.length, 1);

            if (proximoCaractere == ' ') {
                textoOriginal = replaceAll(textoOriginal, textoTemp, '');

                texto += textoTemp;
            }
            else {
                textoTemp = textoTemp.substring(0, textoTemp.lastIndexOf(' ')).trim();

                textoOriginal = replaceAll(textoOriginal, textoTemp, '');

                texto += textoTemp;
            }
        }

        texto = ltrim(texto);

        if (tipoBrowser() == 'ie') {
            texto += '\n';
        }
        else {
            texto += '<br />';
        }
    }

    if (tipoBrowser() == 'ie') {
        document.getElementById(nomeDiv).innerText = texto;
    }
    else {
        document.getElementById(nomeDiv).innerHTML = texto;
    }

    return texto;
}

function TratamentoEnterCompraPorCodigo(obj, evt, IdTxtQuantidade) {

    var retorno = true;
    //var tecla = window.event.keyCode;
    var tecla = (evt.which) ? evt.which : event.keyCode;
    var txtQuantidade = document.getElementById(IdTxtQuantidade)

    //alert('TESTE');

    if (txtQuantidade != null) {
        if (tecla == 13) {
            //alert('TESTE CHARCODE = ' + tecla.toString());
            txtQuantidade.focus();

            if (evt.which) {
                retorno = false;
            }
            else {
                window.event.keyCode = 0;
            }
        }
        //        //Para FireFox
        //        else if (tecla == 13)
        //        {
        //            alert('TESTE CHARCODE = ' + tecla);
        //            evt.which = 0;
        //            txtQuantidade.focus();
        //        }
        return retorno;
    }
}


function MaxlengthJS(objText) {
    var txt = null;
    var valor = null;
    var maximo = 0;
    var tamanho = 0;

    txt = $('#' + objText.id);

    if (txt == null) {
        txt = jQuery('#' + objText.id);
    }

    valor = replaceAll(txt.val(), ',', '');
    valor = replaceAll(valor, '.', '');

    maximo = parseInt(txt.attr('tamanhomaximo'));
    tamanho = parseInt(valor.length);

    if (tamanho >= maximo) {
        window.event.keyCode = 0;

        return false;
    }

    return true;
}

function DefinirTextBoxIsentoPJ(estadoCheckbox, txt) {
    txt = document.getElementById(txt);

    if (estadoCheckbox) {
        txt.value = 'ISENTO';
        txt.disabled = true;
    }
    else {
        txt.value = '';
        txt.disabled = false;
        txt.focus();
        txt.setAttribute('disabled', 'false');
    }
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");

        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);

            if (c_end == -1) {
                c_end = document.cookie.length;
            }

            return unescape(document.cookie.substring(c_start, c_end));
        }
    }

    return "";
}

function delCookie(name) {
    path = '';
    domain = '';

    if (getCookie(name)) document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function GravarOpcaoBusca(txt) {
    setCookie('ck_busca_texto', document.getElementById(txt).value, 1);
}

function RetornarOpcaoBusca(txt) {
    document.getElementById(txt).value = getCookie('ck_busca_texto');
}

function GravarSecao(origem, destino) {
    document.getElementById(destino).value = document.getElementById(origem).value;
}

function GravarValor(obj, valor) {
    document.getElementById(obj).value = valor;
}

function lostFocus(txt, pnl, lst, e) {
    var panel = document.getElementById(pnl);
    var id = (document.activeElement.id ? document.activeElement.id : e.target.id);

    if (panel != null && id != lst && id != txt.id) {
        panel.style.display = 'none';
    }
}

function setFocusLista(lst, e) {
    var tecla = getKey(e);
    var lista = document.getElementById(lst);
    
    if (lista != null) {
        if (tecla == 40) {            
            lista.focus();
        }
    }
}

function getFocusLista(txt, lista, e) {
    var tecla = getKey(e);
    var text = document.getElementById(txt);
    
    if (text != null) {
        if ((tecla == 38 && lista.selectedIndex == 0) ||
                    (tecla == 40 && lista.selectedIndex == lista.all.length - 1)) {
            text.focus();
        }
    }
}

function getKey(e) {
    var key = null;

    if (!e) {        
        if (window.event) {
            e = window.event;
        } else {
            e = null;
        }
    }    
    
    if (e != null) {
        if (typeof (e.keyCode) == 'number') {
            key = e.keyCode;
        } else if (typeof (e.which) == 'number') {
            key = e.which;
        } else if (typeof (e.charCode) == 'number') {
            key = e.charCode;
        } else {
            return null;
        }
    }
    
    return key;
}

function setIndexLista(lista, pnl, txt, hdd, btn, e) {
    var tecla = getKey(e);
    var panel = document.getElementById(pnl);
    var text = document.getElementById(txt);
    var hidden = document.getElementById(hdd);
    var button = document.getElementById(btn);

    hidden.value = '';
    
    if (lista.length > 0) {
        if (lista.selectedIndex > -1) {
            if (tecla == 13 || tecla == 0 || tecla == 1) {                
                text.value = lista[lista.selectedIndex].text;
                hidden.value = lista[lista.selectedIndex].value;
                panel.style.display = 'none';
                
                if (button != null) {
                    button.click();
                }
            }
        }
    }
}

function AutoTab(elemento, evento) {
    var keycode = (evento.which) ? evento.which : event.keyCode;

    if (keycode != 13) {
        return;
    }

    var formulario = elemento.form;
    var els = formulario.elements;
    var x, autotab;

    len = els.length;

    for (var i = 0; i < len; i++) {
        x = els[i];

        if (elemento == x && (autotab = els[i + 1])) {
            if (autotab.focus) {
                autotab.focus();
                break;
            }
        }
    }

    //autotab.focus();

    return false;
}
