if ((window.defaultStatus)) window.defaultStatus = 'Syspec Informatica Ltda';
if ((window.title)) window.title = 'Syspec Informatica Ltda :: Sistemas WEB';

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
    if (init == true) with (navigator) {
        if ((appName == "Netscape") && (parseInt(appVersion) == 4)) {
            document.MM_pgW = innerWidth; document.MM_pgH = innerHeight; onresize = MM_reloadPage;
        }
    }
    else if (innerWidth != document.MM_pgW || innerHeight != document.MM_pgH) location.reload();
}
MM_reloadPage(true);

// Função que esconde barras de scroll (axis: "X" = horizontal; "Y" = vertical; "" ou null = os dois)
function hideScrollbar(axis) {
    if (axis == "X") {
        document.body.style.overflowX = "hidden";
    } else
        if (axis == "Y") {
        document.body.style.overflowY = "hidden";
    } else // both axis
        document.body.style.overflow = "hidden";
}

// Função devolve charCode ou KeyCode
function getKeyCode(evt) {
    evt = (evt) ? evt : event;
    if (evt.charCode) {
        return evt.charCode;
    } else if (evt.keyCode) {
        return evt.keyCode;
    } else if (evt.which) {
        return evt.which;
    } else {
        return 0;
    }
}

// Mostra KeyCode - para debug
function showKeyCode() {
    var myKeyCode = getKeyCode(event);
    alert("keycode: " + myKeyCode);
    return true;
}

function leftTrim(sString) {
    while (sString.substring(0, 1) == " ") {
        sString = sString.substring(1, sString.length);
    }
    return sString;
}

function rightTrim(sString) {
    while (sString.substring(sString.length - 1, sString.length) == " ") {
        sString = sString.substring(0, sString.length - 1);
    }
    return sString;
}

function trim(sString) {
    sString = leftTrim(sString);
    sString = rightTrim(sString);
    return sString;
}

function numbersOnly() {
    // se der Ctrl+V de algum texto ele aceita!!
    var myKeyCode = getKeyCode(event);
    // verifica se digitou só dígito
    if (myKeyCode < 48 || myKeyCode > 57) {
        if ((myKeyCode < 96 || myKeyCode > 105) && (myKeyCode == 13)) {
            return false;
        }
    }
    return true;
}

function OnlyNumbers(obj) { // isso ainda não presta!
    // verifica se digitou somente números e valida conteúdo.
    idx = 0;
    if (numbersOnly()) {
        if (obj) {
            sString = trim(obj.value);
            while (idx < sString.length) {
                str = sString.substring(idx, 1);
                if (!isNumber(str)) {
                    str = sString.substring(0, idx);
                    str = str + sString.substring(idx + 1);
                    sString = str;
                } else {
                    idx++;
                }
            }
            obj.value = sString;
        }
    }
}

function SomenteNumeros(str) {
    // retorna somente números
    var sRet = "";
    if (str) {
        sString = trim(str);
        var idx = 0;
        while (idx <= sString.length) {
            str = sString.substr(idx, 1);
            // se for numero
            if ((str >= 0) && (str <= 9)) {
                sRet = sRet + str;
            }
            idx++;
        }
        return sRet;
    } else
        return "";
}

function formataDataHora(txt) {
    if (!numbersOnly()) return false;
    // poe barra, espaço ou dois pontos nas posições corretas
    var idx = 0;
    var sRet = "";
    var strAux = "";
    if (txt) {
        sRef = SomenteNumeros(txt.value); // tira qualquer formatação
        idx = 0;
        while (idx <= sRef.length) {
            strAux = trim(sRef.substr(idx, 1));
            if (strAux.length > 0) {
                // se for a posição por adiciona separador
                // ddMMyyyyHHMMSS   dd/MM/yyyy HH:MM:SS
                // 01234567890123   01/23/4567 89:01:23
                //                  1234567890123456789 -> 19 caracteres
                sRet = sRet + strAux;
                if (idx == 1) {
                    sRet = sRet + "/";
                } else
                    if (idx == 3) {
                    sRet = sRet + "/";
                } else
                    if (idx == 7) {
                    sRet = sRet + " ";
                } else
                    if (idx == 10) {
                    sRet = sRet + ":";
                } else
                    if (idx == 12) {
                    sRet = sRet + ":";
                }
            }
            idx++;
        }
        if (sRet.length > txt.maxLength) {
            sRet = sRet.substr(0, txt.maxLength);
        }
        txt.value = sRet;
    }
    return true;
}

function number() {
    var myKeyCode = getKeyCode(event);
    // verifica se digitou só dígito ou vergula
    if ((myKeyCode < 48 || myKeyCode > 57) && myKeyCode != 44) {
        //    event.returnValue = false;
        return false;
    } else {
        return true;
    }
}

function ToUpper() {
    var myKeyCode = getKeyCode(event);
    // verifica se digitou um letra minuscula (sem ou com acento)
    if ((myKeyCode > 96 && myKeyCode < 123) || (myKeyCode > 223 && myKeyCode < 254)) {
        // altera para o código da letra maiuscula
        event.keyCode = event.keyCode - 32;
    }
    return true;
}

var downStrokeField;
function autojump_keyDown() {
    // Guarda tamanho antes do presionar teclado
    this.beforeLength = this.value.length;
    // Guarda em qual campo este evento começou
    downStrokeField = this;
}

function autojump_keyUp() {
    // Se foi neste campo e o tamanho aumentou e é maior do maxLength vai para nextField
    if ((this == downStrokeField) &&
      (this.value.length > this.beforeLength) &&
      (this.value.length >= this.maxLength)) {
        this.nextField.focus();
        if ((this.nextField.tagName == "INPUT") && (this.nextField.type == "text")) {
            // Se for do tipo input de texto pode selecionar o conteudo
            this.nextField.select();
        }
    }
    downStrokeField = null;
}

function autojump(fieldName, nextFieldName, defaultMaxLength) {
    var myForm = document.forms[document.forms.length - 1];
    var myField = myForm.elements[fieldName];
    if (nextFieldName) {
        // se tem nome do proximo campo utilize para pega campo em nextField
        myField.nextField = myForm.elements[nextFieldName];
    } else {
        // se não tem nome do campo utilize tabIndex para pega o próximo campo
        var next = myField.tabIndex;
        if (next < (document.forms[0].elements.length)) {
            myField.nextField = document.forms[0].elements[next];
        } else {
            // se não próximo tabIndex pega este campo mesmo
            myField.nextField = myField;
        }
    }

    if ((myField.maxLength == 2147483647) && (defaultMaxLength) && (defaultMaxLength > 0)) {
        myField.maxLength = defaultMaxLength;
    }

    myField.onkeydown = autojump_keyDown;
    myField.onkeyup = autojump_keyUp;
}
var novajanela;

function chamaDialog(s_pagina) {
    janela = window.open(s_pagina, "", "status=yes,menubar=no,height=600,width=800,z-lock=yes,resize=yes");
    janela.focus();
    //	return janela;
}

function chamaModalDialog(s_pagina, bl_wait_elem) {
    var origem = document;
    if (!origem.waitElementShow) {
        if (top) {
            if (top.waitElementShow) {
                origem = top;
            }
        } else
            if (opener) {
            if (opener.waitElementShow) {
                origem = opener;
            }
        }
    }
    if (!origem) origem = self;
    //if (!__IsIE)
    //  __IsIE = navigator.appName.indexOf("Internet Explorer") != -1;

    //  if (origem.waitElementShow && bl_wait_elem) origem.waitElementShow();
    //  if (waitElementShow && bl_wait_elem) waitElementShow();
    //try{
    result = chamaModalDialogConfig(s_pagina, 600, 800, -1, -1, false, true);
    /*if ((window.showModalDialog) && (!bl_ModalManual)) {
    
    result = window.showModalDialog(s_pagina, window,
    "dialogHeight: 600px; dialogWidth: 800px; " +
    "center: Yes; resizable: No; status: No;");
    }else{
    novajanela = window.open(s_pagina, "janelaDialogResult",
    "status=no,menubar=no,height=600,width=800,z-lock=yes,modal=yes");
    if (novajanela) {
	  
    }
    novajanela.focus();
    novajanela.onblur=verificaFocus;
    novajanela.focus();
    while (!novajanela.closed){
    result = novajanela.returnValue;
    }
    //result = novajanela.returnValue;
    setTimeout(verificaFocus, 500);
    setTimeout(verificaFocus, 1500);
    setTimeout(verificaFocus, 4500);
    }*/
    //}catch(e){
    //  alert("Houve uma falha ao abrir janela. Verifique se há bloqueador de popup!\n"+
    //        e.message);
    //}
    if (origem.waitElementHide && bl_wait_elem) origem.waitElementHide();
    if (waitElementHide && bl_wait_elem) waitElementHide();

    return result;
}

function chamaModalResult(objTextbox, s_pagina, bl_wait_elem) {
    // Sempre abre pesquisa do tipo informado
    //  if (waitElementShow && bl_wait_elem) waitElementShow();
    result = chamaModalDialog(s_pagina, bl_wait_elem);
    //	result = window.showModalDialog(s_pagina, "DialogBoxArguments",
    //                                  "dialogHeight: 600px; dialogWidth: 790px; " +
    //                                  "edge: Raised; center: Yes; resizable: No; status: No;");
    //  if (waitElementHide && bl_wait_elem) waitElementHide();
    if (result) {
        // Pegou resultado - volta para servidor para fazer verificação/pega dados
        objTextbox.value = result;
        return true;
    } else {
        // Cancelou pesquisa - não faz nada
        return false;
    }
}

function chamaModalDialogConfig(s_pagina, heightpx, widthpx, toppx, leftpx, resize, bl_waitElement) {
    // Verifica se vai utilizar posicionamento da janela
    if ((toppx == -1) && (leftpx == -1)) {
        s_top_left = " center: Yes;";
    } else {
        s_top_left = " dialogTop: " + toppx + "px; dialogLeft: " + leftpx + "px; center: No; ";
    }

    // Se deve, mostra bl_waitElement
    if (bl_waitElement) { if (waitElementShow) { waitElementShow() } };

    // Sempre abre pesquisa do tipo conveniado
    try {
        if (window.showModalDialog) {
            retorno = window.showModalDialog(s_pagina, window, "dialogHeight: " + heightpx + "px; dialogWidth: " + widthpx + "px; " + s_top_left + " edge: Raised; resizable: " + resize + "; status: No;");
        } else {
            novajanela = window.open(s_pagina, "janelaDialogResult",
         "status=yes,menubar=no,height=" + heightpx + ",width=" + widthpx + ",z-lock=yes,modal=yes");
            if (!novajanela) {
                alert('Bloqueador de popup pode estar habilitado, por favor desative-o!');
            }
            novajanela.focus();
            novajanela.onblur = verificaFocus;
            novajanela.focus();
            //result = novajanela.returnValue;
            setTimeout(verificaFocus, 500);
            setTimeout(verificaFocus, 1500);
            setTimeout(verificaFocus, 4500);
            while (!novajanela.closed) {
                retorno = novajanela.returnValue;
            }
        }
    } catch (e) {
        alert("Houve uma falha ao abrir janela. Favor desativar o bloqueador de pop-up!\n" +
          e.message);
    }


    //  alert(s_pagina+"\n\n"+
    //    "dialogHeight: " + heightpx + "px; dialogWidth: " + widthpx + "px; " + s_top_left + " edge: Raised; resizable: " + resize + "; status: No;");

    // Se deve, mostra bl_waitElement
    if (bl_waitElement) { if (waitElementHide) { waitElementHide() } };

    return retorno;
}

function verificaFocus() {
    if (novajanela)
        if (!novajanela.closed)
        if (novajanela.focus)
        novajanela.focus();
}

function chamaPesq(objTextbox, s_pesq_pagina, btnpesq, blLocal) {
    // Sempre abre pesquisa do tipo informado
    if (waitElementShow) waitElementShow();
    try {
        result = window.showModalDialog(s_pesq_pagina, window,
                                    "dialogHeight: 600px; dialogWidth: 790px; " +
                                    "edge: Raised; center: Yes; resizable: No; status: No;");
    } catch (e) {
        alert("Falha abrindo pagina de pesquisa." +
          "\nVerifique as permissões de execução de JavaScript do seu browser." +
          "\n\n" + e.message);
        result = false;
    }
    if (waitElementHide) waitElementHide();
    if (result) {
        // Tem resultado
        if (result == trim(objTextbox.value)) {
            // Resultado da pesquisa é igual do código que já tem no textbox - não faz nada
            return false;
        } else {
            // Pegou resultado - volta para servidor para fazer verificação/pega dados
            objTextbox.value = result;
            // "appear" = "alterapesq" significa que é um botão de pesquisa que pode causar alterações
            // Se é pesquisa de alteração (attributo) e tem a função para modificar então atualiza como modificado
            if ((btnpesq.appear == "alterapesq") && (setModificado)) {
                // Controle de mudanças
                // CPAGE em 06/03/2009 - alterado para considerar se alterações são marcados localmente
                setModificado(true, blLocal);
            };
            return true;
        }
    } else {
        // Cancelou pesquisa - não faz nada
        return false;
    }
}

function ehVazio(objTextbox) {
    return (trim(objTextbox.value).length == 0);
}

function chamaDownloadArqv(sClientFileName, sServerFileName, iFileSize, sIFrameName) {
    if (waitElementShow) waitElementShow();
    // Cria URL para a página de download
    var sScript = "DwnldArqv.aspx?ClntNm=" + sClientFileName + "&SvrNm=" + sServerFileName;
    // Se tem o tamanho passa isso também
    if (iFileSize) {
        sScript += "&Size=" + iFileSize;
    };
    // Ver se tem IFrame
    var ifDownloadFrame = document.all.namedItem(sIFrameName)
    if (sIFrameName && ifDownloadFrame) {
        // Passar a página de download para o IFrame
        ifDownloadFrame.src = sScript;
    } else {
        // Não tem IFrame Abre a janelinha do download
        var downloadArqv = window.open(sScript, "_blank", "toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,top=0,left=0,width=1,height=1");
        if (!downloadArqv) {
            // Se não abriu mostra mensagem de bloqueador de popup
            if (waitElementHide) waitElementHide();
            alert("Por favor, desative seu bloqueador de popup para este site!");
        }
    }
    if (waitElementHide) waitElementHide();
}
var d;
function viewSource(documento) {
    if (d) if (!d.closed()) d.close();
    d = window.open();
    try {
        if (!documento) {
            documento = document;
        }
        //    if(documento.location) alert(documento.location.href);
        //    if(documento.src) alert(documento.src);
        if (documento.documentElement) {
            d.document.open("text/plain").write(document.documentElement.outerHTML);
        } else {
            d.document.open("text/plain").write(documento.outerHTML);
        }
    } catch (e) {
        alert('Erro: ' + e.message);
    }
    d.focus();
}

function viewSource2() {
    if (d) if (!d.closed()) d.close();
    d = window.open();
    d.document.open("text/plain").write(document.documentElement.innerHTML);
    d.focus();
}

// funções para selecionar um linha no grid no lado do cliente
//var rowSelecionado = false;
//var originalColor;
function highlightRow(obj) {
    if (obj.selected) {
        obj.className = "tableItemSelectedHover";
    } else {
        obj.className = "tableItemHover";
    }
}
function dehighlightRow(obj) {
    if (obj.selected) {
        obj.className = "tableItemSelected";
    } else {
        if (obj.estilo_sel) {
            obj.className = obj.estilo_sel;
        } else {
            obj.className = "tableHeader";
        }
    }
}

//JCTARLA em 25/07/2007
function periodoCompleto() {
    if (getObj("tb_mes_inic") && getObj("tb_mes_final") &&
         getObj("tb_ano_inic") && getObj("tb_ano_final"))
        return ((getObj("tb_mes_inic").length = 2) &&
                    (getObj("tb_ano_inic").length = 4) &&
                    (getObj("tb_mes_final").length = 2) &&
                    (getObj("tb_ano_final").length = 4));
    else
        return false;
}

function podeInserir(ctl1, ctl2) {
    if (ctl1 == null && ctl2 == null) {
        alert("Falha ao tentar validar dados.");
        return false;
    }
    ctl1.value = trim(ctl1.value);
    ctl2.value = trim(ctl2.value);
    if ((ctl1.value.length == 0) || (!(ctl2.value >= 0))) {
        alert("Faltam dados para inserir item.");
        return false;
    }
    return true;
}
////////////
// GLUCAS //
function scrollH() {
    if (document.body.scrollTop) {
        return document.body.scrollTop;
    } else {
        if (window.pageYOffset) {
            return window.pageYOffset;
        } else {
            return 0;
        }
    }
}
function scrollW() {
    if (document.body.scrollLeft) {
        return document.body.scrollLeft;
    } else {
        if (window.pageXOffset) {
            return window.pageXOffset;
        } else {
            return 0;
        }
    }
}
//valores do scroll da pagina
//alert('H:'+scrollH()+' W:'+scrollW());

// CPAGE 06/08/2008
function scrollWindow(moveX, moveY) {
    window.scrollBy(moveX, moveY);
    return true;
}

// CPAGE 06/08/2008
function scrollBottom() {
    scrollWindow(0, 10000);
    return true;
}

// CPAGE 09/08/2008
function scrollTop() {
    scrollWindow(0, -10000);
    return true;
}

function getObj(name) {
    return document.getElementById(name);
}

function removeObj(objeto) {
    //Remove __AjaxCall_Wait existente...
    if (objeto) {
        if (objeto.parentNode) {
            objeto.parentNode.removeChild(objeto);
        }
        if (objeto.parentElement) {
            objeto.parentElement.removeChild(objeto);
        }
        objeto = null;
        return true;
    } else {
        return false;
    }
}
function newObj(tagName, id) {
    var obj = document.createElement(tagName);
    obj.setAttribute("id", id);
    return obj;
}
function addListener(element, type, expression, useCapture) {
    useCapture = useCapture || false;
    if (window.addEventListener) { // Standard
        element.addEventListener(type, expression, useCapture);
        return true;
    }
    else if (window.attachEvent) { // IE
        element.attachEvent('on' + type, expression);
        return true;
    }
    else return false;
}
function include(sFilename) {
    var novo = document.createElement("script");
    novo.setAttribute('language', 'javascript');
    novo.setAttribute('type', 'text/javascript');
    novo.setAttribute('src', sFilename);
    if (document.getElementsByTagName('body'))
        document.getElementsByTagName('body').item(0).appendChild(novo);
}

//window.onload=function(){ include('Files/AjaxCallObject.js');};
/*
var onabrir=function(){
if (!document.body) return false;
var waitElement=getObj('__AjaxCall_Wait');
if(!waitElement)
removeObj(waitElement);
waitElement=null;
include('Files/AjaxCallObject.js');
}
*/
//addListener(window, 'load', onabrir);

__AClockID = 0;
AClearIntervalForAjaxCall = function() {
    window.clearInterval(__AClockID);
    __AClockID = 0;
}

ASetIntervalForAjaxCall = function(milliSec) {
    if (__AClockID != 0)
        AClearIntervalForAjaxCall();   // __doPostBack('_ctl0','')
    __AClockID = window.setInterval("if(AJAXCbo)AJAXCbo.DoAjaxCall('__AJAX_AJAXCALLTIMER','','async')", milliSec);
}

function Refresh() {
    return (document.URL = document.URL);
}

/* Esse código deveria ser inserido na página pelo ASP.Net, automaticamente.*/
/*
function doPostBack2(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
theform = document._ctl0;
}
else{
theform = document.forms["_ctl0"];
}
if(!theform){document.forms[0];}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
*/
//  addListener(window, 'load', function(){ try{if(__doPostBack){ } } catch(e){alert('ok'); } );

function tryClose(target, ms_timeout) {
    ms_timeout = (ms_timeout ? ms_timeout : 500);
    var cmd = "if(ret" + target + "){ " +
        "  if (!ret" + target + ".closed) {" +
        "    if (ret" + target + ".document.readyState == 'complete'){" +
        "      ret" + target + ".close();" +
        "    } else {" +
        "      setTimeout(function(){tryClose('" + target + "')}, " + ms_timeout + ");" +
        "    }" +
        "  }" +
        "}";
    eval(cmd);
}

