/* Inicialização de variáveis. ***************************************/ var __localId = 0; var __licenca = ""; var __licenciado = ""; var __usuarioId = 0; var __codigoUsuario = ""; var __nomeUsuario = ""; var __isAdministrator = false; var __applicationCode = ""; var __applicationDescription = ""; var __functionCode = ""; var __functionDescription = ""; 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 _sistema = "CallManager"; var DialogBoxType = { Error : 0, Info : 1, Warning : 2, Process : 3 }; var DialogBoxButtons = { OkCancel : 0, YesNo : 1, Close : 2, None : 3 }; var doc = document.documentElement; doc.setAttribute('data-useragent', navigator.userAgent); /* 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; }; } // Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.com/#x15.4.4.18 if ( !Array.prototype.forEach ) { Array.prototype.forEach = function forEach( callback, thisArg ) { var T, k; if ( this == null ) { throw new TypeError( "this is null or not defined" ); } var O = Object(this); var len = O.length >>> 0; // Hack to convert O.length to a UInt32 if ( {}.toString.call(callback) !== "[object Function]" ) { throw new TypeError( callback + " is not a function" ); } if ( thisArg ) { T = thisArg; } k = 0; while( k < len ) { var kValue; if ( Object.prototype.hasOwnProperty.call(O, k) ) { kValue = O[ k ]; callback.call( T, kValue, k, O ); } k++; } }; } $.getJSONSync = function (resourceUrl) { return $.ajax({ url: resourceUrl, type: "GET", async: false }); } /* Inicialização da cultura. *****************************************/ loadGlobalize("pt-BR"); //document.onreadystatechange = function () { // if (document.readyState == "interactive") { // page_initBase(); // } // if (document.readyState == "complete") { // page_loadBase(); // } //} function OnAttrModified(mutation) { if (mutation.type == "attributes") { if (mutation.attributeName == "disabled") { EnableLabel(mutation.target, !$(mutation.target).prop("disabled")); } if (mutation.attributeName == "style") { ShowLabel(mutation.target, $(mutation.target).css("display")); } } } //******************************************************************** // 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(); $(document).ajaxSend(function(event, jqxhr, settings) { if (settings.url.indexOf("NotifyMonitor.asp") == -1) { if (getTopFrame().reportActivity != null) { getTopFrame().reportActivity(); } } }); $(document).ajaxComplete(function(event, jqxhr, settings) { if (settings.url.indexOf("NotifyMonitor.asp") == -1) { if (getTopFrame().reportActivity != null) { getTopFrame().reportActivity(); } } }); $(document).ready(function () { if (getTopFrame().reportActivity != null) { getTopFrame().reportActivity(); } if ((BrowserDetect.browser != "Mozilla" && BrowserDetect.browser != "Explorer" && BrowserDetect.browser != "Chrome" && BrowserDetect.browser != "Safari" && BrowserDetect.browser != "Firefox" && BrowserDetect.browser != "Opera") || (BrowserDetect.browser == "Explorer" && BrowserDetect.version <= 8)) { if (window.opener) { window.close(); } else { var myParent = getTopFrame(); if (myParent.location.pathname.indexOf("NavegadorNaoSuportado.aspx") == -1) { myParent.location.href = "NavegadorNaoSuportado.aspx"; } } return; } svg4everybody(); RenderFilterBoxes(); RenderComboTreeviews(); $("button.enableTheme").button(); $("div.buttonSet").buttonset(); $("select.enableTheme").selectmenu(); $.datepicker.setDefaults($.datepicker.regional["pt-BR"]); $("input.calendar").datepicker({ showOn : "button", buttonImage : "/images/icons/calendar_on16.png", buttonImageOnly : true, showButtonPanel : true, changeMonth : true, changeYear : true }); $("input.spinner").spinner({ culture : "pt-BR", create : function(event, ui) { var precision = $(this).attr("spinner-precision"); var step = $(this).attr("spinner-step"); var isCyclic = $(this).attr("spinner-cyclic") == "1"; var maxValue = $(this).attr("spinner-max-value"); var minValue = $(this).attr("spinner-min-value"); var thousandSymbol = $(this).attr("spinner-hidethousand") == "true" ? "" : "."; if (typeof precision == "undefined") { precision = "2"; } $(this).spinner({ numberFormat: parseInt(precision) > 0 ? "n" : "n0" }); if (typeof step != "undefined") { $(this).spinner({ step: Globalize.formatNumber(parseFloat(step)) }); } if (!isCyclic) { if (typeof maxValue != "undefined") { $(this).spinner({ max: Globalize.formatNumber(parseFloat(maxValue), {minimumFractionDigits: precision}) }); } if (typeof minValue != "undefined") { $(this).spinner({ min: Globalize.formatNumber(parseFloat(minValue), {minimumFractionDigits: precision}) }); } } $(this).maskMoney({ thousands: thousandSymbol, decimal: ',', allowZero: true, allowNegative: true, precision: parseInt(precision) }); }, spin : function(event, ui) { if (typeof $(this).attr("spinner-min-value") == "undefined" || typeof $(this).attr("spinner-max-value") == "undefined") return true; var val = ui.value; var precision = $(this).attr("spinner-precision"); var minValue = parseFloat($(this).attr("spinner-min-value")); var maxValue = parseFloat($(this).attr("spinner-max-value")); if (typeof precision == "undefined") { precision = "2"; } if (val > maxValue) { $(this).spinner("value", Globalize.formatNumber(minValue, {minimumFractionDigits: precision})); return false; } else if (val < minValue) { $(this).spinner("value", Globalize.formatNumber(maxValue, {minimumFractionDigits: precision})); return false; } }, change : function(event, ui) { if (typeof $(this).attr("spinner-min-value") == "undefined" || typeof $(this).attr("spinner-max-value") == "undefined") return true; var val = Globalize.parseNumber($(this).val()); var precision = $(this).attr("spinner-precision"); var minValue = parseFloat($(this).attr("spinner-min-value")); var maxValue = parseFloat($(this).attr("spinner-max-value")); if (typeof precision == "undefined") { precision = "2"; } if (val > maxValue) { $(this).spinner("value", Globalize.formatNumber(maxValue, {minimumFractionDigits: precision})); return false; } else if (val < minValue) { $(this).spinner("value", Globalize.formatNumber(minValue, {minimumFractionDigits: precision})); return false; } } }); if (document.forms.length > 0) { if (!isDOMAttrModifiedSupported()) { // Implementa o monitoramento de mudanças DOM utilizando o MutationObserver. var observer = new MutationObserver(function (mutations) { mutations.forEach(function(mutation){ if (mutation.type == "attributes") { if (mutation.attributeName == "disabled") { EnableLabel(mutation.target, !$(mutation.target).prop("disabled")); } if (mutation.attributeName == "style") { ShowLabel(mutation.target, $(mutation.target).css("display")); } } }); }); $("input, select, textarea").each(function () { observer.observe(this, { attributes: true }); }); } else { // Implementa o monitoramento de mudanças DOM utilizando o MutationEvents. document.documentElement.addEventListener('DOMAttrModified', function(e) { var elementTypes = ["input", "select", "textarea"]; if (e.attrName === "disabled" && elementTypes.indexOf(e.target.nodeName.toLowerCase()) > -1) { EnableLabel(e.target, !$(e.target).prop("disabled")); } if (e.attrName === "style" && elementTypes.indexOf(e.target.nodeName.toLowerCase()) > -1) { ShowLabel(e.target, $(e.target).css("display")); } }, false); } } if (typeof Grids !== "undefined") { Grids.OnDataError = Grid_DataError; Grids.OnDebug = Grid_Debug; Grids.OnShowMessage = Grid_ShowMessage; } // Inserção do script de rastreamento de acesso AccessTrackerScript $("body").append($(" //******************************************************************** function SelectByValue(cboComboBox, strValue) { if (cboComboBox.jquery) { cboComboBox = cboComboBox[0]; } cboComboBox.selectedIndex = -1; for(i = 0; i < cboComboBox.length; i++){ if($(cboComboBox.options[i]).val() == 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"); // // // $("#txtId).val(aProduto[7].ID); // $("#txtDescricao).val(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"); } } //******************************************************************** // 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/icons/warning16.png"; 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 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, name: String, width: Integer, height: Integer, resizable: Boolean): WindowHandler // // Onde, // url -> Endereço URL para o carregamento da nova janela; // name -> Nome da nova janela; // width -> Largura da nova janela; // height -> Altura da nova janela; // resizable -> Indica se a nova janela é redimencionavel ou não; //******************************************************************** function OpenNewWindow(url, name, width, height, resizable) { width = (width ? width : 660); height = (height ? height : 480); 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 = true } if (document.forms[0].messagePanel != undefined) { messagePanel.style.display = "none"; if (typeof(page_resize) === "function") { page_resize(); } } var popup = window.open(url, name, "toolbar=0,location=0,status=yes,menubar=0,scrollbars=0,resizable=" + (resizable ? 1 : 0) + ",width=" + width + ",height=" + height + ",top=" + top + ",left=" + left); return popup; } //******************************************************************** // 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, callbackButton1, callbackButton2) { var titulo = ""; switch (messageType) { case APPLICATION_ERROR: if (message.indexOf("ADDITIONAL INFO:") == -1) { message += "ADDITIONAL INFO:"; } 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: showProcessingPanel(); return; } var additionalInfo = "" if (message.indexOf("ADDITIONAL INFO:") > -1) { if (errorNumber != 0) { additionalInfo += "[" + errorNumber + "] "; } if (source != "") { additionalInfo += "Fonte: " + source + "
"; } additionalInfo += message.split("ADDITIONAL INFO:")[1].trim(); message = message.split("ADDITIONAL INFO:")[0].trim(); } return ShowDialogBox(message, additionalInfo, titulo, messageType, DialogBoxButtons.Close, controlToFocusId, callbackButton1, callbackButton2); } //******************************************************************** // 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, ""); } 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("", popupName, null, popupHeight); //popup.focus(); with (document.forms[0]) { var tmp1 = $(__FORMACTION).val(); var tmp2 = $(__FORMTARGET).val(); $(__FORMACTION).val("Selecao.asp?cod=" + key + "&flags=" + flags + "&othersAttributes=" + othersAttributes + "&controlId=" + controlId);// + "&sender=" + sender.id; $(__FORMTARGET).val(popupName); __doPostBack("buttonFiltro", "", false, true); $(__FORMACTION).val(tmp1); $(__FORMTARGET).val(tmp2); } } function ShowDialogBox(mensagem, additionalInfo, titulo, tipo, botoes, controlToFocusId, callbackButton1, callbackButton2) { var iconId = "info"; switch (tipo) { case DialogBoxType.Error : iconId = "error"; break; case DialogBoxType.Warning: iconId = "alert"; break; } var $icon = $(""); var $dialogBoxContent = $("
", { "class": "dialog-text-content" }) .html(mensagem); var $additionalInfoPanel = $("
", { "style": "margin-top: 20px;" }) .append($("

").html("Informações adicionais")) .append($("
").html(additionalInfo)) .accordion({ collapsible: true, heightStyle: "content", active: false }); var buttons = []; switch (typeof(botoes)) { case "number": var button1 = { click: function () { $(this).dialog("close"); if (callbackButton1) { callbackButton1(); } } }; var button2 = { click: function () { $(this).dialog("close"); if (callbackButton2) { callbackButton2(); } } }; buttons.push(button1); switch (botoes) { case DialogBoxButtons.OkCancel: button1.text = "OK"; button2.text = "Cancelar"; buttons.push(button2); case DialogBoxButtons.YesNo: button1.text = "Sim"; button2.text = "Não"; buttons.push(button2); case DialogBoxButtons.Close: button1.text = "Fechar"; break; } break; default: buttons = botoes; } var $dialogBox = $("
", { "class": "glt-dialog", "title": titulo }) .append($icon) .append($dialogBoxContent) .append(additionalInfo != "" ? $additionalInfoPanel : "") .appendTo($("body")) .dialog({ modal: true, resizable: true, width: 500, buttons: buttons, close: function (event, ui) { $(this).dialog("destroy").remove(); if ($("#" + controlToFocusId).length > 0) { $("#" + controlToFocusId).focus(); } _inProcess = false; } }); return $dialogBox; } function showProcessingPanel(containerSelector) { var $container = $("body"); var $bg = $("
", { "class": "processing-panel-bg ui-widget-overlay", "style": "z-index: 200;" }) .data("parent-position", $container.css("position")) .appendTo($container); var $panel = $("
", { "class": "processing-panel", "style": "z-index: 200;" }) .append($("", { "src": "/Content/themes/default/img/carregando.gif" })) .append($("").html("Processando... por favor aguarde.")) .appendTo($container); } function showSimpleProcessingPanel(containerSelector) { var $container = $(containerSelector); if ($container.length == 0) { $container = $("body"); } var $panel = $("
", { "class": "processing-panel", "style": "z-index: 200; width: 100%; height: 100%; background-color: transparent;" }) .append($("", { "src": "/Content/themes/default/img/carregando.gif", "style": "max-height: 32px; max-width: 32px; height: 100%" })) .appendTo($container); } function hideProcessingPanel() { $(".processing-panel").remove(); $(".processing-panel-bg").remove(); } 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(page_resize) === "function") { page_resize(); window.onresize = page_resize; } /* 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 ValidaEmail(value) { usuario = value.substring(0, value.indexOf("@")); dominio = value.substring(value.indexOf("@")+ 1, value.length); if ((usuario.length >=1) && (dominio.length >=3) && (usuario.search("@")==-1) && (dominio.search("@")==-1) && (usuario.search(" ")==-1) && (dominio.search(" ")==-1) && (dominio.search(".")!=-1) && (dominio.indexOf(".") >=1)&& (dominio.lastIndexOf(".") < dominio.length - 1)) { return true; } else { return false; } } function ValidaCPF(objCPF) { var strCPF = $(objCPF).val(); exp = /\.|\-|\//g strCPF = strCPF.toString().replace( exp, "" ); var Soma; var Resto; Soma = 0; if (strCPF.length != 11) return false; if (strCPF == "00000000000") return false; for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i); Resto = (Soma * 10) % 11; if ((Resto == 10) || (Resto == 11)) Resto = 0; if (Resto != parseInt(strCPF.substring(9, 10)) ) return false; Soma = 0; for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i); Resto = (Soma * 10) % 11; if ((Resto == 10) || (Resto == 11)) Resto = 0; if (Resto != parseInt(strCPF.substring(10, 11) ) ) return false; return true; } //valida telefone function ValidaTelefone(tel){ exp = /\(\d{2}\)\ \d{4}\-\d{4}/ if(!exp.test($(tel).val())) return false; return true; } //valida CEP function ValidaCEP(cep){ exp = /\d{2}\.\d{3}\-\d{3}/ if(!exp.test($(cep).val())) return false; return true; } function ValidaData(data) { var date = $(data).val(); var ardt = new Array; var ExpReg=new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}"); ardt = date.split("/"); erro = false; if (date.search(ExpReg)==-1) { erro = true; } else if (((ardt[1]==4)||(ardt[1]==6)||(ardt[1]==9)||(ardt[1]==11))&&(ardt[0]>30)) erro = true; else if ( ardt[1]==2) { if ((ardt[0]>28)&&((ardt[2]%4)!=0)) erro = true; if ((ardt[0]>29)&&((ardt[2]%4)==0)) erro = true; } if (erro) return false; return true; } //valida o CNPJ digitado function ValidaCNPJ(ObjCnpj){ var cnpj = $(ObjCnpj).val(); var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2); var dig1 = new Number; var dig2 = new Number; exp = /\.|\-|\//g cnpj = cnpj.toString().replace( exp, "" ); var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13))); for(i = 0; i0? (cnpj.charAt(i-1)*valida[i]):0); dig2 += cnpj.charAt(i)*valida[i]; } dig1 = (((dig1%11)<2)? 0:(11-(dig1%11))); dig2 = (((dig2%11)<2)? 0:(11-(dig2%11))); if(((dig1*10)+dig2) != digito) return false; return true; } //formatação genérica de campos function FormataCampo(evento, Mascara, strExcecoes) { if (CampoNumerico(evento, strExcecoes)) { var campo = GetElementByEvent(evento); var boleanoMascara; var Digitato = evento.keyCode; exp = /\-|\.|\/|\(|\)| /g campoSoNumeros = $(campo).val().toString().replace( exp, "" ); var posicaoCampo = 0; var NovoValorCampo=""; var TamanhoMascara = campoSoNumeros.length; if (Digitato != 8) { // backspace for(i=0; i<= TamanhoMascara; i++) { boleanoMascara = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".") || (Mascara.charAt(i) == "/")) boleanoMascara = boleanoMascara || ((Mascara.charAt(i) == "(") || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " ")) if (boleanoMascara) { NovoValorCampo += Mascara.charAt(i); TamanhoMascara++; }else { NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); posicaoCampo++; } } $(campo).val(NovoValorCampo); return true; }else { return true; } } return false; } function ConvertToDateTime(valor) { //yyyy-MM-dd HH:mm var data = new Date(parseInt(valor.substr(0, 4)), parseInt(valor.substr(5, 2)) - 1, parseInt(valor.substr(8, 2)), parseInt(valor.substr(11, 2)), parseInt(valor.substr(14, 2)), 0); return data; } function RefreshNiveis(filtrarSomenteResponsavel, filtrarUsuario, nivelKey, comando, sessao, container, tabela) { if (comando == undefined) { comando = ""; } if (sessao == undefined) { sessao = ""; } if (container == undefined) { container = "cboNivel"; } if (tabela == undefined) { tabela = "Ramal"; } var ajaxObject = new AjaxObject(container); var url = "/Scripts/RefreshNiveis.asp?comando=" + comando + "&filtrarSomenteResponsavel=" + (filtrarSomenteResponsavel ? "1" : "0") + "&filtrarUsuario=" + (filtrarUsuario ? "1" : "0") + "&nivelKey=" + nivelKey + "&sessao=" + sessao + "&comboTreeviewObject=" + container + "&tabela=" + tabela; ajaxObject.CarregaPainel(url, "Atualizando...", true); } function isDOMAttrModifiedSupported() { var element, flag; flag = false; try { element = document.createElement('input'); document.forms[0].appendChild(element); document.documentElement.addEventListener('DOMAttrModified', function () { flag = true; }, false); element.disabled = true; document.forms[0].removeChild(element); } catch(e) { flag = false; } return flag; } function EnableLabel(element, enabled) { if (element.id == "") { return; } if (typeof enabled === "undefined") { enabled = true; } if (!enabled) { $("label[for=" + element.id + "]").addClass("disabled"); if ($(element).hasClass("calendar") && !$(element).datepicker("isDisabled")) { $(element).datepicker("disable"); } if ($(element).hasClass("spinner") && !$(element).spinner("option", "disabled")) { $(element).spinner("disable"); } } else { $("label[for=" + element.id + "]").removeClass("disabled"); if ($(element).hasClass("calendar") && $(element).datepicker("isDisabled")) { $(element).datepicker("enable"); } if ($(element).hasClass("spinner") && $(element).spinner("option", "disabled")) { $(element).spinner("enable"); } } } function ShowLabel(element, display) { if (element.id == "") { return; } if (typeof display === "undefined") { display = "inline-block"; } if (display == "none") { $("label[for=" + element.id + "]").css("display", "none"); if ($(element).hasClass("calendar")) { $(element).datepicker("hide"); } if ($(element).hasClass("spinner")) { $(element).spinner("hide"); } } else { $("label[for=" + element.id + "]").css("display", "inline-block"); if ($(element).hasClass("calendar")) { $(element).datepicker("show"); } if ($(element).hasClass("spinner")) { $(element).spinner("show"); } } } function deparam(params) { var o = {}; if (!params) return o; var a = params.split('&'); for (var i = 0; i < a.length; i++) { var pair = a[i].split('='); o[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return o; } function Grid_DataError(grid, source, result, message, data) { } function Grid_Debug(grid, level, arguments) { var s = ""; if (level >= 0 && level <= 2) { for (var i = 0; i < arguments.length; i++) { s += arguments[i] + " "; } grid.ShowMessage("

Não foi possível carregar as informações solicitadas neste momento.

A conexão com o servidor foi interrompida.

Verifique sua conexão com a internet.

Verifique qualquer cabo e reinicie qualquer roteador, modem ou outro dispositivo de rede que você estiver usando.

MENSAGEM DO ERRO:
"+s+"

", 0); } return true; } function Grid_ShowMessage(grid, message) { } function btnMessage_Details_click() { if ($("#message_details").css("display") == "none") { $("#message_details").show(); $("#btnMessage_Details").html("Menos"); } else { $("#message_details").hide(); $("#btnMessage_Details").html("Mais"); } var c = $(".GMMessage").html(); Grids[0].ShowMessage(c, 0); } function btnMessage_Reload_click() { RefreshGrid(); } function ShowLoadingControl(elementId) { var loadingDiv = $("
\"Carregando...\"Carregando...
"); var element = $("#" + elementId); $("body").append(loadingDiv); loadingDiv.css("width", element.innerWidth() - 4); loadingDiv.css("height", element.innerHeight() - 4); loadingDiv.position({ of: element, my: "left top", at: "left top" }); } function HideLoadingControl(elementId) { var loadingDiv = $("#loadingDiv_" + elementId); var element = $("#" + elementId); loadingDiv.remove(); } function IndexOfById(array, id, idField) { var index = -1; if (idField == undefined) { idField = "id"; } for (var i = 0; i < array.length; i++) { var tmp = eval("array[i]." + idField); if (tmp == id) { index = i; break; } } return index; } // Nome: searchExpression // Retorna a expressão para a seleção via SearchExpression do grid // Parâmetros : selectedItems = Array com os valores dos itens selecionados // type = String com o valor que será comparado com os itens function searchExpression(selectedItems, type) { var i; var expression = ""; for (i = 0; i < selectedItems.length; i++) { if ($.isPlainObject(selectedItems[i])) { expression = expression + type +" == '" + eval("selectedItems[i]." + type) + "'"; } else { expression = expression + type +" == '" + selectedItems[i] + "'"; } if(i != selectedItems.length - 1) expression = expression + " || "; } return expression; } function AjustaCampos(grid, arrayItens, searchKey, radioTodos, radioSelecao, radioNenhum) { if (arrayItens.length == 1 && arrayItens[0] == 0) { // Nenhum if (radioNenhum != null) { radioNenhum.checked = true; } grid.SelectAllRows(0); } else if (arrayItens.length == grid.RowCount) { // Todos if (radioTodos != null) { radioTodos.checked = true; } grid.SelectAllRows(1); } else { // Selecionar if (radioSelecao != null) { radioSelecao.checked = true; } grid.SearchExpression = searchExpression(arrayItens, searchKey); grid.SearchMethod = 2; grid.DoSearch("Select", true); } } /* ------------------------------------------------------------------------ Class: autoClear Use: Clears input fields when clicked Author: Vincent Ballut Version: 1.1 Dependency: jQuery 1.9.1 ------------------------------------------------------------------------- */ (function($) { $.fn.autoClear = function() { var elements = $(this); elements.each(function() { var element = $(this); var defaultValue = element.attr('title'); element.on('focus', function() { var value = $(this).val(); if(defaultValue == value) { $(this).val(''); } $(this).addClass('focus_input'); }); element.on('blur', function() { var value = $(this).val(); if(value == '' || value == defaultValue) { $(this).val(defaultValue); $(this).removeClass('modified_input'); } else { $(this).addClass('modified_input'); } $(this).removeClass('focus_input'); }); }); }; })(jQuery); function ExibirErroCallBack(message, status) { ShowMessagePanel(0, "", status + "
" + message, APPLICATION_WARNING, ""); } function LoadBase64FromImage($imageElement, imageName) { if (typeof(imageName) === "undefined" || $.trim(imageName) === "") return; $imageElement.attr("src", "/Images/carregando.gif"); $.ajax({ url: "/Scripts/ImageConverter.asp", type: "post", data: "imageName=" + imageName, async: true, success: function (data, textStatus, jqXHR) { if (data) { $imageElement.attr("src", data); } }, error: function (jqXHR, textStatus, errorThrown) { $imageElement.hide(); } }); } var recursiveGrepResultArray = null; function recursiveGrep(array, compareFunction) { recursiveGrepResultArray = []; $.each(array, function (key, val) { recursiveFunction(val, compareFunction); }); var resultArray = recursiveGrepResultArray; recursiveGrepResultArray = null; return resultArray; } function recursiveFunction(val, comp) { if (comp(val)) { recursiveGrepResultArray.push(val); } if (val.itens instanceof Object) { $.each(val.itens, function(key, val) { recursiveFunction(val, comp); }); } } function getTopFrame() { var w = window; while (w.name != "TopFrame") { while (w.opener != null) { w = w.opener; } w = w.parent; } return w; } function getColorByApplication(applicationCode) { var palette = [ "rgb(243,178,0)", "rgb(99,47,0)", "rgb(70,23,180)", "rgb(0,193,63)", "rgb(170,64,255)", "rgb(132,117,69)", "rgb(254,124,34)", "rgb(119,185,0)", "rgb(176,30,0)", "rgb(0,106,193)", "rgb(255,152,29)", "rgb(31,174,255)", "rgb(225,183,0)", "rgb(37,114,235)", "rgb(76,74,72)", "rgb(0,130,135)", "rgb(255,46,18)", "rgb(86,197,255)", "rgb(107,105,214)", "rgb(173,16,60)", "rgb(114,0,172)", "rgb(25,153,0)", "rgb(255,29,119)", "rgb(0,216,204)", "rgb(0,163,163)" ]; var colorIndex = 0; for (var i = 0; i < applicationCode.length; i++) { colorIndex += applicationCode.charCodeAt(i); } //var colorIndex = itemData.imagem * $group.data("groupImage"); while (colorIndex > palette.length) { var sum = 0; var tmp = colorIndex.toString(); for (var i = 0; i < tmp.length; i++) { sum += parseInt(tmp[i]); } colorIndex = sum; } return palette[colorIndex - 1]; } function loadGlobalize(localeCode) { $.when( $.getJSONSync("/Scripts/cldr/supplemental/likelySubtags.json"), $.getJSONSync("/Scripts/cldr/supplemental/currencyData.json"), $.getJSONSync("/Scripts/cldr/supplemental/numberingSystems.json"), $.getJSONSync("/Scripts/cldr/supplemental/ordinals.json"), $.getJSONSync("/Scripts/cldr/supplemental/plurals.json"), $.getJSONSync("/Scripts/cldr/supplemental/timeData.json"), $.getJSONSync("/Scripts/cldr/supplemental/weekData.json"), $.getJSONSync("/Scripts/cldr/main/"+ localeCode + "/ca-gregorian.json"), $.getJSONSync("/Scripts/cldr/main/"+ localeCode + "/currencies.json"), $.getJSONSync("/Scripts/cldr/main/"+ localeCode + "/dateFields.json"), $.getJSONSync("/Scripts/cldr/main/"+ localeCode + "/numbers.json"), $.getJSONSync("/Scripts/cldr/main/"+ localeCode + "/timeZoneNames.json"), $.getJSONSync("/Scripts/cldr/main/"+ localeCode + "/units.json") ).then(function () { return [].slice.apply(arguments, [0]).map(function (result) { return result[0]; }) }).then(Globalize.load).then(function () { Globalize.locale(localeCode); }); } function GetMilisecondsForTreegrid(date) { var dateBase = new Date("1970-01-01T00:00:00.000"); return (date - dateBase); }