/* 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: //
// Descrição: Valor:
// //

//
//******************************************************************** 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 // // // // // // //
//******************************************************************** function Expande(strIdObj, strIdImg, strImgExp, strImgCol) { var panel = $("#" + strIdObj); var img = $("#" + strIdImg); if (panel.css("display") == "block") { img.attr("src", strImgCol); panel.slideUp("slow"); } else { img.attr("src", strImgExp); panel.slideDown("slow"); } /* if (document.getElementById(strIdObj).style.display == 'block'){ document.getElementById(strIdObj).style.display = 'none'; if(strIdImg != undefined) document.getElementById(strIdImg).src = strImgCol; }else{ document.getElementById(strIdObj).style.display ='block'; if(strIdImg != undefined) document.getElementById(strIdImg).src = strImgExp; } */ } //******************************************************************** // Nome: formataTimeStamp // // Função para formatar um número inteiro em uma strinf no formato "[H]:mm:ss. // // SINTAXE: // formataTimeStamp(valor: Integer): String // // Onde, // valor -> Inteiro a ser formatado; //******************************************************************** function formataTimeStamp(valor){ var intSeg = 0; var intMin = 0; var intHrs = 0; valor = Math.round(valor); intSeg = valor % 60; intMin = parseInt(valor / 60); intHrs = parseInt(intMin / 60); intMin = intMin % 60; return intHrs + ":" + (intMin.toString().length == 1 ? "0" + intMin.toString() : intMin.toString()) + ":" + (intSeg.toString().length == 1 ? "0" + intSeg.toString() : intSeg.toString()); } //******************************************************************** // Nome: ReplaceAll // // Função que substitue todas as ocorrências de uma substring numa string. // // SINTAXE: // ReplaceAll(strString: String, strFind: String, strReplace: String): String // // Onde, // strString -> String que será pesquisada; // strFind -> Substring a ser substituída; // strReplace -> Substring que será inserida no lugar de strFind. // // EXEMPLO: // var Texto1 = "Que mulher feia!"; // Texto1 = ReplaceAll(Texto1, "feia", "linda"); //******************************************************************** function ReplaceAll(strString, strFind, strReplace){ var blnChave = true; while(blnChave){ if(strString.indexOf(strFind) == -1){ blnChave = false; }else{ strString = strString.replace(strFind, strReplace); } } return strString; } //******************************************************************** // Nome: CriaObjetoXmlRequest // // Cria uma instância da classe XMLHttpRequest de acordo com o suporte do navegador. // // SINTAXE: // CriaObjetoXmlRequest() : Object; // // EXEMPLO: // var novoObjeto = new CriaObjetoXmlRequest(); //******************************************************************** function CriaObjetoXmlRequest() { var xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch(ee) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(E) { xmlhttp = false; } } } return xmlhttp; } //******************************************************************** // Nome: AjaxObject // // Classe que encapsula o objeto XMLHttpRequest para uso das funcionalidades Ajax. // // EXEMPLO: // var novoObjeto = new AjaxObject(); //******************************************************************** function AjaxObject(destinoId){ var _xmlhttp = CriaObjetoXmlRequest(); var _imagemCarregandoUrl = "../images/carregando.gif"; var _imagemCanceladoUrl = "../images/warning.gif"; this.CarregaPainel = function (url, textoCarregando, sempreCarregar) { var destino = document.getElementById(destinoId); if (!_xmlhttp) { destino.innerHTML = "Não há suporte para Ajax."; return; } if (textoCarregando == undefined) { textoCarregando = "Carregando......"; } destino.innerHTML = ""; var div = destino.appendChild(document.createElement("DIV")); div.id = "divProcessInfo"; div.style.marginLeft = "30px"; var divImagem = div.appendChild(document.createElement("DIV")); divImagem.id = "divImagem"; divImagem.style.margin = "0 auto"; divImagem.style.width = "50px"; divImagem.style.marginBottom = "10px"; var img = divImagem.appendChild(document.createElement("IMG")); img.src = _imagemCarregandoUrl; var divCarregando = div.appendChild(document.createElement("DIV")); divCarregando.id = "divCarregando"; divCarregando.style.width = "130px"; divCarregando.style.margin = "0 auto"; var text = divCarregando.appendChild(document.createElement("SPAN")); text.style.display = "block"; text.style.marginBottom = "10px"; text.innerHTML = textoCarregando; //var divCancel = div.appendChild(document.createElement("DIV")); //divCancel.id = "divCancel"; //divCancel.style.width = "48px"; //divCancel.style.margin = "0 auto"; //var cancel = divCancel.appendChild(document.createElement("BUTTON")); //cancel.className = "tiny"; //var cancelCaption = cancel.appendChild(document.createElement("span")); //cancelCaption.innerHTML = "Cancelar"; //cancel.style.fontSize = "xx-small"; //cancel.style.display = "block"; //cancel.onclick = this.Abort; var timestamp = ""; if (sempreCarregar != undefined) { if (sempreCarregar) { var now = new Date(); timestamp = "timestamp=" + now.getFullYear() + now.getMonth() + now.getDay() + now.getHours() + now.getMinutes() + now.getSeconds(); if (url.indexOf("?") > -1) { timestamp = "&" + timestamp; } else { timestamp = "?" + timestamp; } } } _xmlhttp.open("GET", url + timestamp, true); _xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate"); _xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0"); _xmlhttp.setRequestHeader("Pragma", "no-cache"); _xmlhttp.onreadystatechange = this.ReadStateChange; _xmlhttp.send(null); } this.ReadStateChange = function() { var destino = document.getElementById(destinoId); if (_xmlhttp.readyState == 4) { destino.innerHTML = ""; var status; try { //Para evitar erro c00c023f no IE9 status = _xmlhttp.status; } catch(e) { status = 0; } if (status == 200) { //Lê o conteúdo var conteudo = _xmlhttp.responseText; //Desfaz o urlencode conteudo = conteudo.replace("", ""); conteudo = unescape(conteudo); eval(conteudo); } else { var img = destino.appendChild(document.createElement("IMG")); img.src = _imagemCanceladoUrl; img.style.verticalAlign = "middle"; img.style.marginRight = "10px"; var text = destino.appendChild(document.createElement("SPAN")); if (status == 0) { text.innerHTML = "Processamento cancelado"; } else { text.innerHTML = "Erro ao processar requisição.

" + _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 + "
" : "") + message; titulo = "Erro na Aplicação"; messageType = DialogBoxType.Error; break; case APPLICATION_WARNING: titulo = "Atenção"; messageType = DialogBoxType.Warning; break; case APPLICATION_INFO: titulo = (source != "" ? source : "Informação"); messageType = DialogBoxType.Info; break; case APPLICATION_PROCESS: messageType = DialogBoxType.Process; break; } ShowDialogBox(message, titulo, messageType, DialogBoxButtons.Close, controlToFocusId); } //******************************************************************** // Nome: HideMessagePanel // // Função que esconde a mensagem na tela do usuário. // // SINTAXE: // HideMessagePanel(): void //******************************************************************** function HideMessagePanel() { HiddeDialogbox(); } //******************************************************************** // Nome: Trim // // Função que retira os espaços em branco das extremidades de uma string. // // SINTAXE: // Trim(str: String): String // // Onde, // str -> String a ser processada; // // EXEMPLO: // var myString = Trim(str); //******************************************************************** function Trim(str) { return str.replace(/^\s+|\s+$/g, ""); } //******************************************************************** // Nome: BrowserDetect // // Classe helper para identificação do navegador utilizado. // // SINTAXE: // BrowserDetect.browser : String // BrowserDetect.version : Float // BrowserDetect.OS : String // // Onde, // BrowserDetect.browser -> Nome do navegador; // BrowserDetect.version -> Versão do navegador; // BrowserDetect.OS => Nome do sistema operacional; // // EXEMPLO: // alert("Meu navegador é o " + BrowserDetect.browser + " na versão " + BrowserDetect.version); //******************************************************************** var BrowserDetect = { init: function () { this.browser = this.searchString(this.dataBrowser) || "Navegador desconhecido"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "versão desconhecida"; this.OS = this.searchString(this.dataOS) || "sistema operacional desconhecido"; }, searchString: function (data) { for (var i = 0; i < data.length; i++) { var dataString = data[i].string; var dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) != -1) return data[i].identity; } else if (dataProp) return data[i].identity; } }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index == -1) return; return parseFloat(dataString.substring(index + this.versionSearchString.length + 1)); }, dataBrowser: [ { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" }, { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, { string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" }, { prop: window.opera, identity: "Opera", versionSearch: "Version" }, { string: navigator.vendor, subString: "iCab", identity: "iCab" }, { string: navigator.vendor, subString: "KDE", identity: "Konqueror" }, { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" }, { string: navigator.vendor, subString: "Camino", identity: "Camino" }, { // for newer Netscapes (6+) string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, { // for older Netscapes (4-) string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS: [ { string: navigator.platform, subString: "Win", identity: "Windows" }, { string: navigator.platform, subString: "Mac", identity: "Mac" }, { string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, { string: navigator.platform, subString: "Linux", identity: "Linux" } ] }; BrowserDetect.init(); function isIE7() { return (BrowserDetect.browser == "Explorer" && parseInt(BrowserDetect.version) == 7); } function OpenSelectWindow(key, flags, controlId, othersAttributes) { /* Definição das Flags: ------------------------------------- Posição | Descrição ------------------------------------- 0 | Todos 1 | Seleção 2 | Intervalo 3 | Nenhum 4 | Apenas Id 5 | Persiste seleção 6 | MultiSeleção 7 | Índice da coluna que deverá preencher o campo texto -------------------------------------*/ /* var sender = GetElementByEvent(event); while (sender.nodeName.toUpperCase() != "BUTTON") { sender = sender.parentNode; } sender.disabled = true; */ if (!flags) { flags = "11100011"; } if (!controlId) { controlId = ReplaceAll(key, "Selecao_", "txt"); } if (!othersAttributes) { othersAttributes = ""; } var popupName = "popup" + ReplaceAll(CreateGuid(), "-", ""); var popupHeight = (flags.substr(1,1) == "1" ? 400 : 114); var popup = OpenNewWindow("", 480, popupHeight, popupName); popup.focus(); with (document.forms[0]) { var tmp1 = __FORMACTION.value; var tmp2 = __FORMTARGET.value; __FORMACTION.value = "Selecao.asp?cod=" + key + "&flags=" + flags + "&othersAttributes=" + othersAttributes + "&controlId=" + controlId;// + "&sender=" + sender.id; __FORMTARGET.value = popupName; __doPostBack("buttonFiltro", "", false, true); __FORMACTION.value = tmp1; __FORMTARGET.value = tmp2; } } function ShowDialogBox(mensagem, titulo, tipo, botoes, controlToFocusId) { var className; var client = document.forms["Form1"]; var uniqueKey = "_" + ReplaceAll(CreateGuid(), "-", ""); switch (tipo) { case DialogBoxType.Error: className = "error"; break; case DialogBoxType.Info: className = "info"; break; case DialogBoxType.Warning: className = "warning"; break; case DialogBoxType.Process: className = "process"; break; case DialogBoxType.AdminLogon: className = "adminlogon"; break; } // Cria a dialogbox var dialogBoxControl = client.appendChild(document.createElement("div")); dialogBoxControl.id = "dialogBoxControl" + uniqueKey; dialogBoxControl.className = "dialogBoxControl"; dialogBoxControl.setAttribute("dialogBoxType", tipo); if (tipo != DialogBoxType.Process) { _dialogBoxes[_dialogBoxes.length] = dialogBoxControl; } if (controlToFocusId != undefined) { dialogBoxControl.setAttribute("controlToFocusId", controlToFocusId); } else { dialogBoxControl.setAttribute("controlToFocusId", ""); } var dialogBoxBackground = dialogBoxControl.appendChild(document.createElement("div")); dialogBoxBackground.id = "dialogBoxBackground" + uniqueKey; dialogBoxBackground.className = "dialogBoxBackground"; var dialogBox = dialogBoxControl.appendChild(document.createElement("div")); dialogBox.id = "dialogBox" + uniqueKey; dialogBox.className = "dialogBox " + className; if (tipo == DialogBoxType.AdminLogon) { titulo = "O sistema precisa da autorização do Administrador para continuar"; } else if (tipo == DialogBoxType.Info && titulo == "") { titulo = window.title; } if (titulo != "" && tipo != DialogBoxType.Process) { var dialogBoxTitle = dialogBox.appendChild(document.createElement("h1")); dialogBoxTitle.id = "dialogBoxTitle" + uniqueKey; dialogBoxTitle.className = "dialogBoxTitle drag"; dialogBoxTitle.onmouseover = function () { __dragId = "dialogBox" + uniqueKey; } dialogBoxTitle.onselectstart = function () { return false; } var dialogBoxTitleLabel = dialogBoxTitle.appendChild(document.createElement("span")); dialogBoxTitleLabel.innerHTML = titulo; } var dialogBoxContent = dialogBox.appendChild(document.createElement("div")); dialogBoxContent.id = "dialogBox_Content" + uniqueKey; dialogBoxContent.className = "dialogBoxContent"; if (tipo == DialogBoxType.Process) { var processImage = dialogBoxContent.appendChild(document.createElement("img")); processImage.src = "../images/carregando.gif"; var processMessage = dialogBoxContent.appendChild(document.createElement("p")); processMessage.innerHTML = "Processando... por favor aguarde."; botoes = DialogBoxButtons.None; } else if (tipo == DialogBoxType.AdminLogon) { var tableForm = dialogBoxContent.appendChild(document.createElement("table")); var r0 = tableForm.insertRow(0); var c00 = r0.insertCell(0); c00.colSpan = 3; c00.innerHTML = "

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..."); }