/* Inicialização de variáveis. ***************************************/ var __localId = 0; var __licenca = ""; var __licenciado = ""; var __usuarioId = 0; var __codigoUsuario = ""; var __nomeUsuario = ""; var __isAdministrator = false; var __functionCode = ""; var __success = true; var APPLICATION_ERROR = 1; //Message type var APPLICATION_WARNING = 2; //Message type var APPLICATION_INFO = 3; //Message type var APPLICATION_PROCESS = 4; //Message type var _controlToFocus = null; //Controle para focalizar após o fechamento de um DialogBox. var _inProcess = false; //Indicativo de processamento de página. var _dialogBoxes = new Array(); var DialogBoxType = { Error : 0, Info : 1, Warning : 2, Process : 3, AdminLogon : 4 }; var DialogBoxButtons = { OkCancel : 0, YesNo : 1, Close : 2, None : 3 }; var doc = document.documentElement; doc.setAttribute('data-useragent', navigator.userAgent); /* Inicialização de eventos. *****************************************/ addEvent(window, "load", initDragDrop); /* Extensões de classes nativas **************************************/ // Adição da propriedade 'indexOf' para o tipo Array. if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (obj, fromIndex) { if (fromIndex == null) { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex, j = this.length; i < j; i++) { if (this[i] === obj) return i; } return -1; }; } //******************************************************************** // Nome: SetInnerText() // // Escrve o conteúdo de um elemento caso ele esteja definido. // // SINTAXE: // SetInnerText (id: String, text: String) : void // // Onde, // id -> Id do elemento; // text -> conteúdo para o elemento; //******************************************************************** function SetInnerText(id, text) { var obj = document.getElementById(id); if (obj != undefined) { obj.innerHTML = text; } } //******************************************************************** // Nome: __doPostBack() // // Função que causa um postback na página atual. // // SINTAXE: // __doPostBack (eventTarget: String, eventTarget: String, isNotButton: Boolean, popWindow: WindowHandler) : void // // Onde, // eventTarget -> (Opcional) Id do elemento que causa o postbak; // eventTarget -> (Opcional) Argumentos a serem passados para o postbak; // isNotButton -> (Opcional) Indica se o elemento causador do postback é, ou nã, um botão; // isPopup -> (Opcional) Indica se o postback abrirá, ou não, uma janela popup. Caso positivo, a mensagem de 'processando' não é exibida; //******************************************************************** function __doPostBack(eventTarget, eventArgument, isNotButton, isPopup) { var theform = document.forms["Form1"]; if (isNotButton == undefined) { isNotButton = false; } theform.__EVENTTARGET.value = eventTarget.split("$").join(":"); if (eventArgument == undefined) eventArgument = ""; theform.__EVENTARGUMENT.value = eventArgument; theform.__POSTBACK.value = "S"; var acao = 0; switch (eventTarget) { case "ToolbarItemIncluir": case "ToolbarItemAlterar": case "ToolbarItemExcluir": if (eventTarget == "ToolbarItemAlterar") acao = 1; else if (eventTarget == "ToolbarItemExcluir") acao = 2; var params = GetQueryStringParams(); theform.action = theform.__FORMACTION.value.split("?")[0] + "?cod="+ params["cod"] + "&acao=" + acao + "&id=" + eventArgument; break; default: theform.action = theform.__FORMACTION.value; break; } theform.target = theform.__FORMTARGET.value; if (!isPopup) { ShowMessagePanel("", "", "", APPLICATION_PROCESS); } if (isIE7() || isNotButton) { theform.submit(); } } //******************************************************************** // Nome: NewOption // // Procedimento de inserção de um valor (option) num combobox. // // SINTAXE: // NewOption (objComboBox: Object, vntValor: Variant, strDescricao: String) // // Onde, // objComboBox -> Objeto combo box; // vntValor -> Valor da opção; // strDescricao -> Descrição da opção; // // EXEMPLO: //
//******************************************************************** function NewOption(objComboBox, vntValor, strDescricao) { var objOption = new Option(strDescricao, vntValor); objComboBox.options[objComboBox.length] = objOption; } //******************************************************************** // Nome: ClearOptions // // Procedimento que limpa num combobox. // // SINTAXE: // ClearOptions (objComboBox: Object) // // Onde, // objComboBox -> Objeto combo box; // // EXEMPLO: // //******************************************************************** function ClearOptions(objComboBox){ for(var item = objComboBox.length; item >= 0; item--){ objComboBox.options[item] = null; } } //******************************************************************** // Nome: SelectByValue // // Procedimento para selecionar uma opção num ComboBox pelo seu valor. // // SINTAXE: // SelectByValue(cboComboBox: ComboBox, strValue: String) // // Onde, // cboComboBox -> ComboBox que irá sofre influência do procedimento; // strValue -> Valor da opção que será selecionada // // EXEMPLO: // //******************************************************************** function SelectByValue(cboComboBox, strValue) { cboComboBox.selectedIndex = -1; for(i = 0; i < cboComboBox.length; i++){ if(cboComboBox.options[i].value == strValue){ cboComboBox.selectedIndex = i; break; } } } //******************************************************************** // Nome: CriaRegistro // // Esta função cria um registro com duas propriedades: ID e Descricao. // // SINTAXE: // CriaRegistro (vntId: Variant, strDescricao: Variant) // // Onde, // vntId -> Valor da propriedade ID; // strDescricao -> Valor da propriedade Descricao; // // // EXEMPLO: // var aProduto = new Array(10); // // aProduto[1] = new CriaRegistro(3, "Produto01"); // ... // aProduto[10] = new CriaRegistro(23, "Produto10"); // // // frmProduto.txtId.value = aProduto[7].ID; // frmProduto.txtDescricao.value = aProduto[7].Descricao; //******************************************************************** function CriaRegistro(vntId, strDescricao){ this.ID = vntId; this.Descricao = strDescricao; } //******************************************************************** // Nome: CampoNumerico // // Procedimento que obriga a entrada de somente valores numéricos num campo texto, // com exceção do "." e do "-" para campos de CPF, CEP, CNPJ, etc. // // SINTAXE: // CampoNumerico (evnEvento: Event, strEscecoes: String) // // Onde, // evnEvento -> Evento da tecla pressionada; // strExcecoes -> String contendo os caracteres permitidos. // // EXEMPLO: // // // BUG CONHECIDO: // Ao utilizarmos o evento onKeyPress, alguns navegadores atribuirão o keycode 46 // tanto para o caracter [.] quanto para a tecla [DEL] o que impossibilita // um tratamento diferente para essas duas teclas. // Uma forma de resolver seria utilizar o evento onKeyDown que atribute, para todos // os navegadores, o keycode 190 para [.]. O problema é que, ao utilizar este evento, // na combinação [SHIFT + .], é retornado o keycode da tecla [SHIFT] (keycode = 16) e // do caracter [.] (keycode = 190) em vez do keycode do resultado da combinação // ([>] ponto-e-vírgula, para alguns layouts de teclados). // Até se achar uma solução melhor, convenciona-se utilizar o evento onKeyPress e // bloquear, por padrão, o keycode 46. Desse modo, a tecla [DEL] não funcionará // para alguns navegadores, tendo de ser contornado pela tecla [BACKSPACE] (keycode = 8). //******************************************************************** function CampoNumerico(evnEvento, strExcecoes){ var blnRetorno = false; var tecla = (evnEvento.keyCode ? evnEvento.keyCode : evnEvento.which); if ((tecla > 47 && tecla < 58) || (tecla == 8) || (tecla > 34 && tecla < 41) || (tecla == 16)) { //numeros de 0 a 9, Backspace, Setas, Home, End, Shift return true; } else if (strExcecoes != undefined) { for(var i = 0; i < strExcecoes.length; i++) { if (tecla == strExcecoes.charCodeAt(i)) { return true; } } } return false; } //******************************************************************** // Nome: Expande // // Função para expandir/recolher uma table ou span. // // SINTAXE: // Expande (strIdObj: String[, strIdImg: String, strImgExp: String, strImgCol: String]) // // Onde, // strIdObj -> Id do objeto a ser modificado; // strIdImg -> Opcional. Id da imagem a ser modificada; // strImgExp -> Opcional. Imagem exibida quando expandido; // strImgCol -> Opcional. Imagem exibida quando encolhido; // // EXEMPLO: //// // Opção 01 // // // |
" + _xmlhttp.responseText + "
"; } } } } this.Abort = function() { if (_xmlhttp) { _xmlhttp.abort(); } } } //******************************************************************** // Nome: addEvent // // Função que atacha uma função a um evento do objeto especificado. A função atachada recebe automaticamente // um parametro contendo o evento disparado. // // SINTAXE: // addEvent(obj: Object, evType: String, fn: EventHandler): void // // Onde, // obj -> Objeto a ser atachado o evento; // evType -> Nome do evento (sem o 'on'. Ex.: 'click', 'mouseover'); // fn -> Handler da função a ser disparada pelo evento. // // EXEMPLO: // addEvent(document.getElementById("painel"), "click", painel_click); //******************************************************************** function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, true); } else if (obj.attachEvent) { obj.attachEvent('on' + evType, fn); } } //******************************************************************** // Nome: GetElementByEvent // // Função que retorna o elemento que disparou o evento. // // SINTAXE: // GetElementByEvent(evt: Event): Object // // Onde, // evt -> Evento disparado; // // EXEMPLO: // var el = getElementByEvent(evt); //******************************************************************** function GetElementByEvent(evt) { var el; if (evt.srcElement) { el = evt.srcElement; } else { el = evt.target; } return el; } //******************************************************************** // Nome: GetNameFunction // // Função que retorna o nome de uma função pelo seu ponteiro. // // SINTAXE: // GetNameFunction(theFunction: Handler): String // // Onde, // theFunction -> Ponteiro para a função; //******************************************************************** function GetNameFunction(theFunction) { var text = theFunction.toString(); text = text.substr(0, text.indexOf("(")).replace("function", ""); text = ReplaceAll(text, " ", ""); return text; } //******************************************************************** // Nome: EscreveInf // // Função que retorna o nome de uma função pelo seu ponteiro. // // SINTAXE: // GetNameFunction(theFunction: Handler): String // // Onde, // theFunction -> Ponteiro para a função; //******************************************************************** function EscreveInf(id, value) { var infoRow = document.getElementById(id + "Info"); var infoValue = document.getElementById(id + "Value"); if (value != "") { infoValue.innerHTML = value; if (document.all) infoRow.style.display = "block"; else infoRow.style.display = "table-row"; } else { infoRow.style.display = "none"; } } //******************************************************************** // Nome: OpenNewWindow // // Função que abre e retorna uma janela popup. // // SINTAXE: // OpenNewWindow(url: String, width: Integer, height: Integer, name: String, resizable: Boolean): WindowHandler // // Onde, // url -> Endereço URL para o carregamento da nova janela; // width -> Largura da nova janela; // height -> Altura da nova janela; // name -> Nome da nova janela; // resizable -> Indica se a nova janela é redimencionavel ou não; //******************************************************************** function OpenNewWindow(url, width, height, name, resizable) { var sw = document.body.offsetWidth; var sh = document.body.offsetHeight; var winX = (document.all) ? window.screenLeft : window.screenX; var winY = (document.all) ? window.screenTop : window.screenY; var top = winY + parseInt((sh / 2) - (height / 2)); var left = winX + parseInt((sw / 2) - (width / 2)); if (name == undefined) { name = ""; } if (resizable == undefined) { resizable = 0 } if (document.forms[0].messagePanel != undefined) { messagePanel.style.display = "none"; ResizeWindow(); } return window.open(url, name, "toolbar=0,location=0,status=yes,menubar=0,scrollbars=0,resizable=" + resizable + ",width=" + width + ",height=" + height + ",top=" + top + ",left=" + left); } //******************************************************************** // Nome: IsChildOf // // Função que indica se um elemente é filho de outro através de N graus de parentesco. // // SINTAXE: // IsChildOf(elChild: Object, elParent: Object): Boolean // // Onde, // elChild -> Elemento a ser verificado; // elParent -> Possivel elemento pai; //******************************************************************** function IsChildOf(elChild, elParent) { var result = false; try { if (elChild.parentNode != null) { if (elChild.parentNode == elParent) { result = true; } else { result = IsChildOf(elChild.parentNode, elParent); } } } catch (ex) { alert(ex); } return result; } //******************************************************************** // Nome: ShowMessagePanel // // Função que exibe uma mensagem na tela do usuário. // // SINTAXE: // ShowMessagePanel(errorNumber: Integer, source: String, message: String, messageType: Integer, controlToFocus: Object): void // // Onde, // errorNumber -> Numero do erro (Para mensagens de erro); // source -> Fonte do erro (Para mensagens de erro). Caso o tipo da mensagem seja uma informação (messageType = APPLICATION_INFO), // este parâmetro é utilizado como título do DialogBox; // message -> Conteúdo da mensagem; // messageType -> Tipo da mensagem que poderá ser: // APPLICATION_ERROR - para mensagens de erro; // APPLICATION_WARNING - para alertas do sistema; // APPLICATION_INFO - para informações avulsos; // APPLICATION_PROCESS - para mensagens de processamento; // controlToFocus -> (Opcional) Controle que receberá foco após o fechamento da DialogBox; //******************************************************************** function ShowMessagePanel(errorNumber, source, message, messageType, controlToFocusId) { var titulo = ""; switch (messageType) { case APPLICATION_ERROR: message = (source != "" ? "Fonte: " + source + "Para continuar, informe abaixo a senha do Administrador do sistema.
"; var r1 = tableForm.insertRow(1); var c10 = r1.insertCell(0); c10.rowSpan = 2; var pwdImage = document.createElement("img"); pwdImage.src = "../images/icoPassword49x49.gif"; c10.appendChild(pwdImage); var c11 = r1.insertCell(1); c11.className = "labelCell"; var labelUsuario = document.createElement("label"); labelUsuario.innerHTML = "Usuario:"; c11.appendChild(labelUsuario); var c12 = r1.insertCell(2); c12.className = "valueCell"; c12.innerHTML = "Administrador"; var r2 = tableForm.insertRow(2); var c21 = r2.insertCell(0); c21.className = "labelCell"; var labelPwd = document.createElement("label"); labelPwd.htmlFor = "txtPassword"; labelPwd.innerHTML = "Senha:"; c21.appendChild(labelPwd); var c22 = r2.insertCell(1); c22.className = "valueCell"; var pwd = document.createElement("input"); pwd.name = "txtPassword"; pwd.id = "txtPassword"; pwd.type = "password"; c22.appendChild(pwd); pwd.onkeypress = function (evt) { var tecla; if (!evt) evt = event; tecla = (evt.keyCode ? evt.keyCode : evt.which); if (tecla == 13) { // tecla ENTER. __doPostBack("buttonCommand1", "", true); if (evt.keyCode) { evt.keyCode = 0; } else { evt.which = 0; } return false; } } SetFocus(pwd); botoes = DialogBoxButtons.OkCancel; } else { dialogBoxContent.innerHTML = "" + mensagem + "
"; } if (botoes != DialogBoxButtons.None) { var dialogBoxFooter = dialogBox.appendChild(document.createElement("div")); dialogBoxFooter.id = "dialogBox_Footer" + uniqueKey; dialogBoxFooter.className = "dialogBoxFooter"; var button1 = dialogBoxFooter.appendChild(document.createElement("button")); button1.id = "buttonCommand1" + uniqueKey; switch (botoes) { case DialogBoxButtons.OkCancel: button1.innerHTML = "OK"; break; case DialogBoxButtons.YesNo: button1.innerHTML = "Sim"; break; case DialogBoxButtons.Close: button1.innerHTML = "Fechar"; break; } if (botoes == DialogBoxButtons.Close) addEvent(button1, "click", HiddeDialogbox); else button1.onclick = function () { __doPostBack("buttonCommand1"); } SetFocus(button1); if (botoes != DialogBoxButtons.Close) { var button2 = dialogBoxFooter.appendChild(document.createElement("button")); button2.id = "buttonCommand2" + uniqueKey; switch (botoes) { case DialogBoxButtons.OkCancel: button2.innerHTML = "Cancelar"; break; case DialogBoxButtons.YesNo: button2.innerHTML = "Não"; break; } addEvent(button2, "click", HiddeDialogbox); } } //Centraliza o DialogBox. var clientHeight = client.offsetHeight; var clientWidth = client.offsetWidth; var dialogBoxHeight = dialogBox.offsetHeight; var dialogBoxWidth = dialogBox.offsetWidth; dialogBox.style.top = parseInt((clientHeight / 2) - (dialogBoxHeight / 2)) + "px"; dialogBox.style.left = parseInt((clientWidth / 2) - (dialogBoxWidth / 2)) + "px"; } function HiddeDialogbox(evt) { if (!evt) { evt = event; } var el = GetElementByEvent(evt); var uniqueKey = ""; if (el.id.indexOf("_") > -1) { uniqueKey = "_" + el.id.split("_")[1]; } var controlToFocusId = ""; var dialogBoxControl = document.getElementById("dialogBoxControl" + uniqueKey); if (dialogBoxControl != null) { for (var i = 0; i < _dialogBoxes.length; i++) { if (_dialogBoxes[i] == dialogBoxControl) _dialogBoxes.splice(i, 1); } controlToFocusId = dialogBoxControl.getAttribute("controlToFocusId"); document.forms["Form1"].removeChild(dialogBoxControl); _inProcess = false; if (controlToFocusId != "") { SetFocus(document.getElementById(controlToFocusId)); } } } function initDragDrop() { __dragX = 0; // cursor X __dragY = 0; // cursor Y __dragId = ""; // ID do el. a ser movido __dragging = false; // true se há um el. sendo movido addEvent(document.body, "mousedown", __dragDown); addEvent(document.body, "mousemove", __dragMove); addEvent(document.body, "mouseup", __dragUp); } function __dragMove(e) { if (typeof __dragging == "undefined" || !__dragging) return; e = e ? e : window.event; __dragEl.style.left = (e.clientX - __dragX) + "px"; __dragEl.style.top = (e.clientY - __dragY) + "px"; } function __dragDown(e) { e = e ? e : window.event; __dragEl = document.getElementById(__dragId) || null; var _target = document.all ? e.srcElement : e.target; while (_target != null && !(/drag/.test(_target.className))) { _target = _target.parentNode; } if (_target == null) return; if (!__dragEl || !(/drag/.test(_target.className))) return; __dragX = e.clientX - __dragEl.offsetLeft; __dragY = e.clientY - __dragEl.offsetTop; __dragging = true; } function __dragUp() { __dragging = false; } function IsEmail(email) { var exclude = /[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/; var check = /@[\w\-]+\./; var checkend = /\.[a-zA-Z]{2,3}$/; email = ReplaceAll(email, ",", ";"); var emails = email.split(";"); var isValid = true; for (var i = 0; i < emails.length; i++) { var mailAddress = Trim(emails[i]); if (((mailAddress.search(exclude) != -1) || (mailAddress.search(check)) == -1) || (mailAddress.search(checkend) == -1)) { isValid = false; break; } } return isValid; } function CreateGuid() { // OBS: Esta função não gera um guid verdadeiro. // Apenas para fins de evitar simular um identificador único. var S4 = function () { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }; return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); } function DoSetFocus() { if (_controlToFocus != null) { if (_controlToFocus.offsetHeight > 0) { _controlToFocus.focus(); _controlToFocus = null; } } } function SetFocus(control) { _controlToFocus = control; if (document.getElementById("cliente")) { if (document.getElementById("cliente").style.visibility == "visible") { DoSetFocus(); } } } function Page_Loaded() { if (typeof(ResizeWindow) == typeof(Function)) { ResizeWindow(); window.onresize = ResizeWindow; } /*AJUSTES DE VISIBILIDADE PARA MELHORAR RENDERIZAÇÃO*/ if (document.getElementById("cliente")) { document.getElementById("cliente").style.visibility = 'visible'; } /* AJUSTES DO FOCO NOS CONTROLES */ DoSetFocus(); } function GetQueryStringParams() { var querystring = location.search.replace("?", "").split("&"); var queryObj = {}; for (var i = 0; i < querystring.length; i++) { var name = querystring[i].split("=")[0]; var value = querystring[i].split("=")[1]; queryObj[name] = value; } return queryObj; } function RefreshNiveis(filtrarSomenteResponsavel, filtrarUsuario, nivelKey, comando, sessao, container) { if (comando == undefined) { comando = ""; } if (sessao == undefined) { sessao = ""; } if (container == undefined) { container = "cboNivel"; } var ajaxObject = new AjaxObject(container); var url = "../ScriptsLibrary/RefreshNiveis.asp?comando=" + comando + "&filtrarSomenteResponsavel=" + (filtrarSomenteResponsavel ? "1" : "0") + "&filtrarUsuario=" + (filtrarUsuario ? "1" : "0") + "&nivelKey=" + nivelKey + "&sessao=" + sessao; ajaxObject.CarregaPainel(url, "Atualizando..."); }