PageSourceSearch

https://wwwt.connectmed.com.br/conectividade/resources/js/resource/util.js

js connectmed.com.br collected 2026-10-03 01:31:33 UTC 52,628 bytes, 1,790 lines download raw bytes

1/*
2 * Util.js
3 *
4 * Versao: 1.0.0
5 * Autor: Resource IT Solutions
6 * Data: 17/11/2011
7 *
8 * Copyright (C) 2011
9 * Resource IT Solutions.
10 * Todos os direitos reservados.
11 */
12
13function onBlurSomenteNumericos(el) {
14	$(el).val($(el).val().replace(/[^\d]/g, ','));
15}
16
17function onBlurNumericos(el) {
18	$(el).val($(el).val().replace(/[^\d]/g, ''));
19}
20
21function somenteNumeros(evt) {
22
23    var charCode = evt.keyCode ? evt.keyCode : evt.which;
24
25    if (charCode > 31 && (charCode < 48 || charCode > 57))
26        return false;
27
28    return true;
29
30}
31
32function somenteAlfanumerico(evt) {
33    var charCode = evt.keyCode ? evt.keyCode : evt.which;
34
35    if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122))
36        return false;
37
38    return true;
39}
40
41function onBlurDocumentoCnpj(el) {
42    var normalizado = normalizarCNPJ($(el).val());
43
44    if (normalizado.length > 0) {
45        $(el).val(formatarCNPJ(normalizado));
46    }
47}
48
49function normalizarDocumentoCnpj(valor) {
50    return normalizarCNPJ(valor);
51}
52
53function compararCnpj(primeiro, segundo) {
54    return normalizarCNPJ(primeiro) === normalizarCNPJ(segundo);
55}
56
57function aplicarMascaraCnpjCampo(seletor) {
58    jQuery(seletor).unbind('.cnpjAlfa').bind('blur.cnpjAlfa', function() {
59        onBlurDocumentoCnpj(this);
60    });
61}
62
63//--->Fun��o para a formata��o dos campos...<---
64function mascaraCampos(tipo, campo, teclaPress) {
65      if (window.event) {
66              var tecla = teclaPress.keyCode;
67      } else {
68              tecla = teclaPress.which;
69      }
70
71      var s = new String(campo.value);
72    // Remove todos os caracteres � seguir: ( ) / - . e espa�o, para tratar a string denovo.
73      s = s.replace(/(\.|\(|\)|\/|\-| )+/g,'');
74
75      tam = s.length + 1;
76
77      if ( tecla != 9 && tecla != 8 ) {
78              switch (tipo)
79              {
80              case 'CPF' :
81                      if (tam > 3 && tam < 7)
82                              campo.value = s.substr(0,3) + '.' + s.substr(3, tam);
83                      if (tam >= 7 && tam < 10)
84                              campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,tam-6);
85                      if (tam >= 10 && tam < 12)
86                              campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9);
87              break;
88
89              case 'CNPJ' :
90                      campo.value = formatarCNPJ(s);
91              break;
92
93              case 'TEL' :
94                      if (tam > 4)
95                    	  campo.value = s.substr(0,4) + '-' + s.substr(4, tam);
96
97              break;
98
99              case 'DATA' :
100                      if (tam > 2 && tam < 4)
101                              campo.value = s.substr(0,2) + '/' + s.substr(2, tam);
102                      if (tam > 4 && tam < 11)
103                              campo.value = s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4);
104              break;
105
106              case 'CEP' :
107                      if (tam > 5 && tam < 7)
108                              campo.value = s.substr(0,5) + '-' + s.substr(5, tam);
109              break;
110              }
111      }
112}
113
114function formatarCampoPreenchido(valorCampo, idCampo, tipo) {
115
116    // Remove todos os caracteres � seguir: ( ) / - . e espa�o, para tratar a string denovo.
117	s = valorCampo.replace(/(\.|\(|\)|\/|\-| )+/g,'');
118
119    tam = valorCampo.length + 1;
120
121    switch (tipo) {
122    	case 'CPF' :
123            $(idCampo).val(s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9));
124        break;
125
126    	case 'CNPJ' :
127    		$(idCampo).val(formatarCNPJ(s));
128        break;
129
130    	case 'TEL' :
131    		$(idCampo).val(s.substr(0,4) + '-' + s.substr(4,tam));
132        break;
133
134        case 'DATA' :
135        	$(idCampo).val(s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4));
136        break;
137
138        case 'CEP' :
139        	$(idCampo).val(s.substr(0,5) + '-' + s.substr(5, tam));
140        break;
141    }
142}
143
144//--->Fun��o para verificar se o valor digitado � n�mero...<---
145function digitos(event){
146      if (window.event) {
147              // IE
148              key = event.keyCode;
149      } else if ( event.which ) {
150              // netscape
151              key = event.which;
152      }
153      if ( key != 8 || key != 13 || key < 48 || key > 57 )
154              return ( ( ( key > 47 ) && ( key < 58 ) ) || ( key == 8 ) || ( key == 13 ) );
155      return true;
156}
157
158//adding it as a prototype object enables it to be used from any array
159Array.prototype.removeItems = function(itemsToRemove) {
160	if (!/Array/.test(itemsToRemove.constructor)) {
161		itemsToRemove = [ itemsToRemove ];
162	}
163
164	var j;
165	for (var i = 0; i < itemsToRemove.length; i++) {
166		j = 0;
167		while (j < this.length) {
168			if (this[j] == itemsToRemove[i]) {
169				this.splice(j, 1);
170			} else {
171				j++;
172			}
173		}
174	}
175};
176
177
178/**
179 * Funcao que retira todos os itens do combo.
180 * @param obj Combo
181 */
182function clearSelect(obj) {
183	$(obj).empty();
184}
185
186/**
187 * Funcao que retira dados da string conforme pattern passado.
188 * @param str String
189 * @param pattern Pattern para Regex
190 * @param newCharacter Novo caracter
191 * @returns
192 */
193function removeSpecialCharacter(str, pattern, newCharacter) {
194	var regex = new RegExp(pattern, "g");
195
196	return str.replace(regex, newCharacter);
197}
198function cleanSpecialCharacter(str) {
199	if (!$.trim(str).length == 0) {
200		return str.replace(/[\.\-_\W]+/g, "");
201	}
202	return str;
203}
204function abrirModalLoading() {
205	$('body').append('<div id="cortina" style="display:none;" class="cortina"></div>');
206	$('#cortina').show();
207	$('body').append('<div id="loading" class="loading"></div>');
208}
209
210function fecharModalLoading() {
211	$('#cortina').remove();
212	$('#loading').remove();
213}
214
215function abrirModal(modal, altura, largura, fechar) {
216	$(modal).showModal({ altura: altura, largura: largura, fechar: fechar });
217}
218
219function fecharModal(modal) {
220	$(modal).removeModal();
221}
222
223/**
224 * Funcao para realizar todo submit de formulario via jqueyr
225 * 	pois nao temos um input type="submit" e sim "links"
226 * @param formulario
227 */
228function submitForm(formulario) {
229	$(formulario).submit();
230}
231
232function submitFormAjax(formulario, divResultado, idDivBusca) {
233	abrirModalLoading();
234
235	$.ajax({
236		type: 'POST',
237		datatype: 'HTML',
238		url: $(formulario).attr('action'),
239		data: $(formulario).serialize(),
240		success: function(result) {
241			var div = $(result).find(idDivBusca).html();
242			$(divResultado).html(div);
243			fecharModalLoading();
244
245			$(divResultado).show();
246		}
247	});
248}
249
250function submitAjax(data, method, url) {
251
252	var retorno = null;
253
254	$.ajax({
255		type: method,
256		datatype: 'HTML',
257		url: url,
258		data: data,
259		async: false,
260
261		success: function(result) {
262			retorno = result;
263		}
264
265	});
266
267	return retorno;
268}
269
270function submitAjaxWithOpenModal(data, method, url, divResultado, idDivBusca, altura, largura, openModal) {
271	$.ajax({
272		type: method,
273		datatype: 'HTML',
274		url: url,
275		data: data,
276		success: function(result) {
277
278			var div = $(result).find(idDivBusca).html();
279			$(divResultado).html(div);
280			if (openModal)
281				abrirModal($(divResultado), altura, largura, 'N');
282		}
283	});
284
285}
286
287function submitAjaxWithOpenModalAndJson(data, method, url, divResultado, idDivBusca, altura, largura, openModal) {
288	$.ajax({
289		type: method,
290		url: url,
291		data: data,
292		success: function(result) {
293
294			var div = $(result).find(idDivBusca).html();
295			$(divResultado).html(div);
296			if (openModal)
297				abrirModal($(divResultado), altura, largura, 'N');
298		}
299	});
300
301}
302
303function findModalByUrl(url, divResultado, idDivBusca){
304	$.ajax({
305		type: 'GET',
306		datatype: 'HTML',
307		url: url,
308		success: function(result) {
309			var div = $(result).find(idDivBusca).html();
310			$(divResultado).html(div);
311
312			abrirModal($(divResultado), 500, 600, 'N');
313		}
314	});
315}
316
317/**
318 * Funcao que realiza a abertura e o fechamento do accordion
319 * @param object botao de abrir e fechar
320 */
321function abrirFecharAccordion(object) {
322    if ($(object).hasClass("abrir-fechar-aberto")) {
323        $(object).addClass("abrir-fechar-fechado").removeClass("abrir-fechar-aberto");
324    } else {
325        $(object).addClass("abrir-fechar-aberto").removeClass("abrir-fechar-fechado");
326    }
327    $("#dados-solicitacao").toggle("slow");
328}
329
330/**
331 * Funcao que realiza a abertura e o fechamento do accordion
332 * @param object botao de abrir e fechar
333 */
334function abrirFecharAccordionByID(object, idDiv) {
335    if ($(object).hasClass("abrir-fechar-aberto")) {
336        $(object).addClass("abrir-fechar-fechado").removeClass("abrir-fechar-aberto");
337    } else {
338        $(object).addClass("abrir-fechar-aberto").removeClass("abrir-fechar-fechado");
339    }
340    $("#" + idDiv).toggle("slow");
341}
342
343
344function abrirFecharDuvidasAccordionByID(object, idDiv) {
345    if ($(object).hasClass("abrir-fechar-aberto-duvidas")) {
346        $(object).addClass("abrir-fechar-fechado-duvidas").removeClass("abrir-fechar-aberto-duvidas");
347    } else {
348        $(object).addClass("abrir-fechar-aberto-duvidas").removeClass("abrir-fechar-fechado-duvidas");
349    }
350    $("#" + idDiv).toggle("slow");
351}
352
353/**
354 * Funcao para realizar a formatacao de numeros (valores).
355 * @param v Valor
356 * @returns Valor Formatado
357 */
358function formatarNumerosToValores(v) {
359	var _DECIMAL_POINT=',';
360
361	// primeiro retira caracteres invalidos da string "v"
362	var VALIDOS="0123456789.";
363	var vl = "", posDec, aux;
364	var vInt, vDec;
365
366	for (var i=0; i < v.length; i++) {
367		aux = VALIDOS.indexOf(v.substring(i, i+1));
368		if (aux>=0)
369			vl += v.substring(i,i+1);
370	}
371
372	posDec = vl.indexOf('.');
373
374	if( posDec >= 0 ) {
375		vInt = vl.substring(0, posDec);
376		vDec = _DECIMAL_POINT + vl.substring(posDec+1, vl.length);
377	} else {
378		vInt = vl;
379		vDec = "";
380	}
381
382	v = "";
383	n = vInt.length;
384
385	if( posDec==0 )  vInt = "0";
386
387	j = 1;
388
389	do {
390		v = vInt.substr(n-1,1) + v;
391		if (j%3==0 && n>1) {
392			v='.'+v; j = 0;
393		}
394
395		n--; j++;
396	}   while(n>0);
397
398	return( v + vDec );
399
400}
401
402function doTime() {
403	setTimeout(null, 1500);
404}
405
406function validarTipoArquivoSelecionado(modal, inputFile, inputNomeArquivo) {
407	var ext = $(inputFile).val().split('.').pop().toLowerCase();
408	var arq = inputFile.files[0];
409
410	if(arq.size > 10485760){ // valida��o para arquivo com mais de 10MB
411		abrirModal($(modal), 200, 375, 'N');
412		$("#mensagemArquivo").show();
413		$("#mensagemExtensao").hide();
414		$(inputFile).val(null);
415	}
416	
417	if(arq.size < 1024){ // valida��o para arquivo zerado inferior a 0 kb
418		infoUser().showMessage('Erro', 'Tamanho do arquivo selecionado n\u00E3o pode ser inferior a 1KB.');
419		$(inputFile).val(null);
420		return;
421	}
422	
423	
424
425	if($.inArray(ext, ['bmp','jpg','jpeg','pdf', 'tiff', 'tif']) == -1) {
426		abrirModal($(modal), 200, 375, 'N');
427		$("#mensagemArquivo").hide();
428		$("#mensagemExtensao").show();
429		$(inputFile).val(null);
430	}
431}
432
433function applyRedClass(idLabel) {
434	if(idLabel != '' && $('#' + idLabel).length != 0 && !$('#' + idLabel).hasClass('vermelho')) {
435		$('#' + idLabel).addClass('vermelho');
436	}
437}
438
439function removeRedClass(idLabel) {
440	if(idLabel != '' && $('#' + idLabel).length != 0 && $('#' + idLabel).hasClass('vermelho')) {
441		$('#' + idLabel).removeClass('vermelho');
442	}
443}
444
445function validarDadoPreenchido(idInput, idLabel) {
446
447	var valorDado = null;
448	var valido = false;
449
450	if($('#' + idInput) != undefined && $('#' + idLabel) != undefined) {
451		if($('#' + idInput).is('input')) {
452			valorDado = $('#' + idInput).val();
453		} else if($('#' + idInput).is('textarea')) {
454			valorDado = $('#' + idInput).val();
455		} else {
456			valorDado = $('#' + idInput + ' option:selected').val();
457			if(valorDado == '-1') {
458				valorDado = '';
459			}
460		}
461
462		if(valorDado != "") {
463			valido = true;
464			removeRedClass(idLabel);
465		} else {
466			applyRedClass(idLabel);
467		}
468
469	}
470
471	return valido;
472
473}
474
475function validarCPF(cpf) {
476
477    cpf = cpf.replace(/[^\d]+/g,'');
478
479    if(cpf == '') return false;
480
481    // Elimina CPFs invalidos conhecidos
482    if (cpf.length != 11 ||
483        cpf == "00000000000" ||
484        cpf == "11111111111" ||
485        cpf == "22222222222" ||
486        cpf == "33333333333" ||
487        cpf == "44444444444" ||
488        cpf == "55555555555" ||
489        cpf == "66666666666" ||
490        cpf == "77777777777" ||
491        cpf == "88888888888" ||
492        cpf == "99999999999")
493        return false;
494
495    // Valida 1o digito
496    add = 0;
497    for (i=0; i < 9; i ++)
498        add += parseInt(cpf.charAt(i)) * (10 - i);
499    rev = 11 - (add % 11);
500    if (rev == 10 || rev == 11)
501        rev = 0;
502    if (rev != parseInt(cpf.charAt(9)))
503        return false;
504
505    // Valida 2o digito
506    add = 0;
507    for (i = 0; i < 10; i ++)
508        add += parseInt(cpf.charAt(i)) * (11 - i);
509    rev = 11 - (add % 11);
510    if (rev == 10 || rev == 11)
511        rev = 0;
512    if (rev != parseInt(cpf.charAt(10)))
513        return false;
514
515    return true;
516
517}
518
519function normalizarCNPJ(cnpj) {
520    if (cnpj === null || cnpj === undefined) {
521        return '';
522    }
523    return cnpj.toString().toUpperCase().replace(/[.\/\-]/g, '').replace(/\s/g, '');
524}
525
526function charValorCnpj(caractere) {
527    return caractere.toUpperCase().charCodeAt(0) - 48;
528}
529
530function calcularDVCnpj(base) {
531    var pesos = base.length === 12
532        ? [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
533        : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
534    var soma = 0;
535
536    for (var i = 0; i < base.length; i++) {
537        soma += charValorCnpj(base.charAt(i)) * pesos[i];
538    }
539
540    var resto = soma % 11;
541    return resto < 2 ? 0 : 11 - resto;
542}
543
544function formatarCNPJ(cnpj) {
545    cnpj = normalizarCNPJ(cnpj);
546
547    if (cnpj.length !== 14) {
548        return cnpj;
549    }
550
551    return cnpj.substr(0, 2) + '.' + cnpj.substr(2, 3) + '.' + cnpj.substr(5, 3)
552        + '/' + cnpj.substr(8, 4) + '-' + cnpj.substr(12, 2);
553}
554
555function validarCNPJ(cnpj) {
556
557    cnpj = normalizarCNPJ(cnpj);
558
559    if (cnpj === '') {
560        return false;
561    }
562
563    if (cnpj.length !== 14) {
564        return false;
565    }
566
567    if (!/^[A-Z0-9]{12}[0-9]{2}$/.test(cnpj)) {
568        return false;
569    }
570
571    if (/^\d{14}$/.test(cnpj) && /^(\d)\1{13}$/.test(cnpj)) {
572        return false;
573    }
574
575    var base = cnpj.substring(0, 12);
576    var primeiroDigito = calcularDVCnpj(base);
577    var segundoDigito = calcularDVCnpj(base + primeiroDigito);
578    var digitosInformados = cnpj.substring(12);
579
580    return digitosInformados === ('' + primeiroDigito + segundoDigito);
581}
582
583function isNumber(n) {
584  return !isNaN(parseFloat(n)) && isFinite(n);
585}
586
587jQuery.fn.removeNot = function( settings ){
588	var $this = jQuery( this );
589	var defaults = {
590		pattern: /[^0-9]/,
591		replacement: ''
592	}
593	settings = jQuery.extend(defaults, settings);
594
595	$this.keyup(function(){
596		var new_value = $this.val().replace( settings.pattern, settings.replacement );
597		$this.val( new_value );
598	});
599	return $this;
600}
601
602function addCamposDivClonavel(divMaster, divClonada) {
603
604	if (divMaster == "cidAdicional") {
605		if (qtdeCidAdicional == 3) {
606			alert("Numero maximo de CIDs adicionais permitidos foi excedido");
607
608			return false;
609		}
610	}
611	if (divMaster == "procedimentos") {
612		$('#'+divMaster+' div#'+divClonada).clone(true).attr('id',divClonada+idDivProcClone).addClass('cloned').insertAfter('#'+divMaster+' div[id^='+divClonada+']:last');
613	} else if (divMaster == "anexos") {
614		$('#'+divMaster+' div[id^='+divClonada+']:last').clone(true).attr('id',divClonada+idDivDocClone).addClass('cloned').insertAfter('#'+divMaster+' div[id^='+divClonada+']:last');
615	} else if (divMaster == "materiais") {
616		$('#'+divMaster+' div#'+divClonada).clone(true).attr('id',divClonada+idDivMaterialClone).addClass('cloned').insertAfter('#'+divMaster+' div[id^='+divClonada+']:last');
617	} else if (divMaster == "cidAdicional") {
618		$('#'+divMaster+' div#'+divClonada).clone(true).attr('id',divClonada+qtdeCidAdicional).addClass('cloned').insertAfter('#'+divMaster+' div[id^='+divClonada+']:last');
619	} else if (divMaster == "medicamentos") {
620		$('#'+divMaster+' div#'+divClonada).clone(true).attr('id',divClonada+idDivMedicamentoClone).addClass('cloned').insertAfter('#'+divMaster+' div[id^='+divClonada+']:last');
621	} else if (divMaster == "tratamentos") {
622		$('#'+divMaster+' div#'+divClonada).clone(true).attr('id',divClonada+idDivTratamentoClone).addClass('cloned').insertAfter('#'+divMaster+' div[id^='+divClonada+']:last');
623	} else if (divMaster == "composicoesFaturamento"){
624		$('#'+divMaster+' div#'+divClonada).clone(true).attr('id',divClonada+idDivComposicaoClone).addClass('cloned').insertAfter('#'+divMaster+' div[id^='+divClonada+']:last');
625	}
626
627
628	$('#'+divMaster+' div[id^='+divClonada+']').each(function(e){
629		$(this).find('select').each(function(){
630    		var attrSelectName = $(this).attr('name').replace(regex, e);
631    		$(this).attr('name', attrSelectName);
632        	if ($(this).attr('id')) {
633	    		var idObject = $(this).attr('id').replace(regex, e);
634	        	$(this).attr('id', idObject);
635        	}
636    	});
637
638		if ($(this).hasClass('cloned')) {
639			$(this).find('input[type=hidden]').each(function(){
640				var attrName = $(this).attr('name').replace(regex, e);
641	        	$(this).attr('name', attrName);
642	        	if ($(this).attr('id')) {
643	        		var idObject = $(this).attr('id').replace(regex, e);
644	        		$(this).attr('id', idObject);
645	        	}
646	        	$(this).val("");
647	        });
648			$(this).find('span').each(function(){
649				if ($(this).attr('id')) {
650	        		var idObject = $(this).attr('id').replace(regex, e);
651	        		$(this).attr('id', idObject);
652	        	}
653	        });
654	 		$(this).find('input[type=text]').each(function(){
655	 			var attrName = $(this).attr('name').replace(regex, e);
656		        $(this).attr('name', attrName);
657		        if ($(this).attr('id')) {
658			        var idObject = $(this).attr('id').replace(regex, e);
659			        $(this).attr('id', idObject);
660		        }
661		        $(this).val("");
662		        if ($(this).hasClass('hasDatepicker')) {
663		        	$(this).datepicker( "destroy" );
664		    		$(this).datepicker();
665		    		$("#txtDtDiagMetastase").datepicker( "option", $.datepicker.regional[ "pt-BR" ] );
666		    		$("#txtDtDiagMetastase").datepicker( "option", "dateFormat", "dd/mm/yy" );
667		        }
668		    });
669	 		$(this).find('input[type=file]').each(function(){
670		    	var attrName = $(this).attr('name').replace(regex, e);
671			    $(this).attr('name', attrName);
672			});
673
674	 		$(this).find('input[type=radio]').each(function(){
675	        	var attrName = $(this).attr('name').replace(regex, e);
676	        	$(this).attr('name', attrName);
677		        if ($(this).attr('id')) {
678		        	var idObject = $(this).attr('id').replace(regex, e);
679				    $(this).attr('id', idObject);
680		        }
681	        	$(this).attr('selected', false);
682	        });
683
684	 		$(this).find('input[type=checkbox]').each(function(){
685	 			if ($(this).is('[name]') && $(this).attr('name') != "") {
686					var attrName = $(this).attr('name').replace(regex, e);
687		        	$(this).attr('name', attrName);
688	 			}
689		        if ($(this).attr('id')) {
690		        	var idObject = $(this).attr('id').replace(regex, e);
691				    $(this).attr('id', idObject);
692		        }
693				$(this).attr('checked', false);
694	        });
695
696	 		$(this).removeClass('cloned');
697		} else {
698			$(this).find('input[type=hidden]').each(function(){
699				var attrName = $(this).attr('name').replace(regex, e);
700	        	$(this).attr('name', attrName);
701		        if ($(this).attr('id')) {
702		        	var idObject = $(this).attr('id').replace(regex, e);
703		        	$(this).attr('id', idObject);
704		        }
705	        });
706			$(this).find('span').each(function(){
707				if ($(this).attr('id')) {
708	        		var idObject = $(this).attr('id').replace(regex, e);
709	        		$(this).attr('id', idObject);
710	        	}
711	        });
712			$(this).find('input[type=text]').each(function(){
713				var attrName = $(this).attr('name').replace(regex, e);
714	        	$(this).attr('name', attrName);
715		        if ($(this).attr('id')) {
716		        	var idObject = $(this).attr('id').replace(regex, e);
717		        	$(this).attr('id', idObject);
718		        }
719	        });
720			$(this).find('input[type=file]').each(function(){
721		    	var attrName = $(this).attr('name').replace(regex, e);
722			    $(this).attr('name', attrName);
723			});
724			$(this).find('input[type=radio]').each(function(){
725	        	var attrName = $(this).attr('name').replace(regex, e);
726	        	$(this).attr('name', attrName);
727		        if ($(this).attr('id')) {
728		        	var idObject = $(this).attr('id').replace(regex, e);
729				    $(this).attr('id', idObject);
730		        }
731	        });
732			$(this).find('input[type=checkbox]').each(function(){
733				if ($(this).is('[name]') && $(this).attr('name') != "") {
734					var attrName = $(this).attr('name').replace(regex, e);
735		        	$(this).attr('name', attrName);
736				}
737		        if ($(this).attr('id')) {
738		        	var idObject = $(this).attr('id').replace(regex, e);
739				    $(this).attr('id', idObject);
740		        }
741
742	        });
743		}
744	});
745
746	if (divMaster == "procedimentos") {
747		idDivProcClone += 1;
748	} else if (divMaster == "anexos") {
749		idDivDocClone += 1;
750	} else if (divMaster == "materiais") {
751		idDivMaterialClone += 1;
752	} else if (divMaster == "cidAdicional") {
753		qtdeCidAdicional += 1;
754	} else if (divMaster == "medicamentos") {
755		idDivMedicamentoClone += 1;
756	} else if (divMaster == "tratamentos") {
757		idDivTratamentoClone += 1;
758	} else if (divMaster == "idDivComposicaoClone"){
759		idDivComposicaoClone += 1;
760	}
761}
762
763function removeCamposDivClonavel(divMaster, divClonada) {
764	var idx = 0;
765	$('#'+divMaster+' input:checkbox:checked[name=""]').each(function(e){
766		if (divMaster == "cidAdicional") {
767			idx = e;
768		}
769
770		if ($(this).parents("#"+divClonada).length == 0) {
771			var parent = $(this).parent().parent();
772			if(divClonada == 'cloneFileUpload'){
773				var tamanho = $('#anexos div[id^=cloneFileUpload]').length;
774				if(tamanho > 1){
775					$(parent).remove();
776					$('#'+divMaster+' div[id^='+divClonada+']').each(function(e){
777						$(this).find('input[type=hidden]').each(function(){
778							var attrName = $(this).attr('name').replace(regex, e);
779							$(this).attr('name', attrName);
780							if ($(this).attr('id')) {
781								var idObject = $(this).attr('id').replace(regex, e);
782								$(this).attr('id', idObject);
783							}
784						});
785
786						$(this).find('input[type=text]').each(function(){
787							var attrName = $(this).attr('name').replace(regex, e);
788							$(this).attr('name', attrName);
789							if ($(this).attr('id')) {
790								var idObject = $(this).attr('id').replace(regex, e);
791								$(this).attr('id', idObject);
792							}
793						});
794
795						$(this).find('input[type=file]').each(function(){
796							var attrName = $(this).attr('name').replace(regex, e);
797							$(this).attr('name', attrName);
798						});
799
800						$(this).find('input[type=radio]').each(function(){
801							var attrName = $(this).attr('name').replace(regex, e);
802							$(this).attr('name', attrName);
803
804							var idObject = $(this).attr('id').replace(regex, e);
805							$(this).attr('id', idObject);
806						});
807
808						$(this).find('input[type=checkbox][name]').each(function(){
809							if ($(this).attr('name') != "") {
810								var attrName = $(this).attr('name').replace(regex, e);
811								$(this).attr('name', attrName);
812								if ($(this).attr('id')) {
813									var idObject = $(this).attr('id').replace(regex, e);
814									$(this).attr('id', idObject);
815								}
816							}
817						});
818
819					});
820
821					if (divMaster == "procedimentos") {
822						setTimeout("validarMateriaisPorProcedimento()", 1000);
823					} else if (divMaster == "materiais") {
824						atualizarValorProduto();
825					}
826
827				}
828			}else{
829				parent.fadeOut('fast', function() {
830					$(this).remove();
831
832					$('#'+divMaster+' div[id^='+divClonada+']').each(function(e){
833						$(this).find('input[type=hidden]').each(function(){
834							var attrName = $(this).attr('name').replace(regex, e);
835							$(this).attr('name', attrName);
836							if ($(this).attr('id')) {
837								var idObject = $(this).attr('id').replace(regex, e);
838								$(this).attr('id', idObject);
839							}
840						});
841
842						$(this).find('input[type=text]').each(function(){
843							var attrName = $(this).attr('name').replace(regex, e);
844							$(this).attr('name', attrName);
845							if ($(this).attr('id')) {
846								var idObject = $(this).attr('id').replace(regex, e);
847								$(this).attr('id', idObject);
848							}
849						});
850
851						$(this).find('input[type=file]').each(function(){
852							var attrName = $(this).attr('name').replace(regex, e);
853							$(this).attr('name', attrName);
854						});
855
856						$(this).find('input[type=radio]').each(function(){
857							var attrName = $(this).attr('name').replace(regex, e);
858							$(this).attr('name', attrName);
859
860							var idObject = $(this).attr('id').replace(regex, e);
861							$(this).attr('id', idObject);
862						});
863
864						$(this).find('input[type=checkbox][name]').each(function(){
865							if ($(this).attr('name') != "") {
866								var attrName = $(this).attr('name').replace(regex, e);
867								$(this).attr('name', attrName);
868								if ($(this).attr('id')) {
869									var idObject = $(this).attr('id').replace(regex, e);
870									$(this).attr('id', idObject);
871								}
872							}
873						});
874
875					});
876
877					if (divMaster == "procedimentos") {
878						setTimeout("validarMateriaisPorProcedimento()", 1000);
879					} else if (divMaster == "materiais") {
880						atualizarValorProduto();
881					}
882				});
883			}
884
885			if (divMaster == "procedimentos") {
886				var inputParent = $(parent).find('input[type=text]')[0];
887				var codigoProcedimento = $(inputParent).val();
888				$.each($('#tbodyDocumentos').find('tr'), function(i, trProcedimento){
889					$.each($(trProcedimento).find('td'), function(i, tdProcedimento){
890						var tdFinal = "";
891						var count = new Number(0);
892						if(tdProcedimento.id != null &&	tdProcedimento.id != ''){
893							$.each(tdProcedimento.innerHTML.split(', '), function(j, procedimento){
894								if(procedimento != codigoProcedimento){
895									if(count == 0){
896										tdFinal = procedimento;
897									}else{
898										tdFinal = tdFinal + ', ' + procedimento;
899									}
900									count = new Number(count)+ new Number(1);
901								}else if(procedimento == codigoProcedimento &&
902										tdProcedimento.innerHTML.split(', ').length == 1){
903									$(trProcedimento).remove();
904								}
905							});
906							$('#' + tdProcedimento.id).empty().html(tdFinal);
907						}
908					});
909				});
910				if($('#tbodyDocumentos').find('tr').length == 0){
911					$('#divDocumentos').addClass('hide');
912					$('#tbodyDocumentos').empty();
913				}
914			}
915		} else {
916			var parent = $(this).parent().parent();
917			var lastDivClone = $('#'+divMaster+' div[id^='+divClonada+']:last');
918
919			var inputParent = $(parent).find('input[type=text]')[0];
920			var inputLastDiv = $(lastDivClone).find('input[type=text]')[0];
921
922			if (divMaster == "procedimentos") {
923				var inputParent = $(parent).find('input[type=text]')[0];
924				var codigoProcedimento = $(inputParent).val();
925				$.each($('#tbodyDocumentos').find('tr'), function(i, trProcedimento){
926					$.each($(trProcedimento).find('td'), function(i, tdProcedimento){
927						var tdFinal = "";
928						var count = new Number(0);
929						if(tdProcedimento.id != null &&	tdProcedimento.id != ''){
930							$.each(tdProcedimento.innerHTML.split(', '), function(j, procedimento){
931								if(procedimento != codigoProcedimento){
932									if(count == 0){
933										tdFinal = procedimento;
934									}else{
935										tdFinal = tdFinal + ', ' + procedimento;
936									}
937									count = new Number(count)+ new Number(1);
938								}else if(procedimento == codigoProcedimento &&
939										tdProcedimento.innerHTML.split(', ').length == 1){
940									$(trProcedimento).remove();
941								}
942							});
943							$('#' + tdProcedimento.id).empty().html(tdFinal);
944						}
945					});
946				});
947				if($('#tbodyDocumentos').find('tr').length == 0){
948					$('#divDocumentos').addClass('hide');
949					$('#tbodyDocumentos').empty();
950				}
951			}else if(divClonada == 'cloneFileUpload'){
952				var idDiv = parent[0].id;
953				var tamanho = $('#anexos div[id^=cloneFileUpload]').length;
954				if(idDiv == divClonada && tamanho > 1){
955					var parent = $(this).parent().parent();
956					$(parent).remove();
957					$('#'+divMaster+' div[id^='+divClonada+']').each(function(e){
958						$(this).find('input[type=hidden]').each(function(){
959							var attrName = $(this).attr('name').replace(regex, e);
960							$(this).attr('name', attrName);
961							if ($(this).attr('id')) {
962								var idObject = $(this).attr('id').replace(regex, e);
963								$(this).attr('id', idObject);
964							}
965						});
966
967						$(this).find('input[type=text]').each(function(){
968							var attrName = $(this).attr('name').replace(regex, e);
969							$(this).attr('name', attrName);
970							if ($(this).attr('id')) {
971								var idObject = $(this).attr('id').replace(regex, e);
972								$(this).attr('id', idObject);
973							}
974						});
975
976						$(this).find('input[type=file]').each(function(){
977							var attrName = $(this).attr('name').replace(regex, e);
978							$(this).attr('name', attrName);
979						});
980
981						$(this).find('input[type=radio]').each(function(){
982							var attrName = $(this).attr('name').replace(regex, e);
983							$(this).attr('name', attrName);
984
985							var idObject = $(this).attr('id').replace(regex, e);
986							$(this).attr('id', idObject);
987						});
988
989						$(this).find('input[type=checkbox][name]').each(function(){
990							if ($(this).attr('name') != "") {
991								var attrName = $(this).attr('name').replace(regex, e);
992								$(this).attr('name', attrName);
993								if ($(this).attr('id')) {
994									var idObject = $(this).attr('id').replace(regex, e);
995									$(this).attr('id', idObject);
996								}
997							}
998						});
999
1000					});
1001				}
1002			}
1003
1004			if ($(inputParent).attr('name') != $(inputLastDiv).attr('name')) {
1005				$(parent).find('input[type=text]').each(function(e){
1006					var inputFetch = $(lastDivClone).find('input[type=text]')[e];
1007					$(this).val($(inputFetch).val());
1008				});
1009
1010				$(parent).find('input[type=hidden]').each(function(e){
1011					var inputFetch = $(lastDivClone).find('input[type=hidden]')[e];
1012					$(this).val($(inputFetch).val());
1013				});
1014
1015				$(parent).find('input[type=file]').each(function(e){
1016					var inputFetch = $(lastDivClone).find('input[type=file]')[e];
1017					$(this).val($(inputFetch).val());
1018				});
1019
1020				$(this).find('input[type=radio]').each(function(){
1021					var inputFetch = $(lastDivClone).find('input[type=radio]')[e];
1022		        	$(this).attr('selected', $(inputFetch).attr('selected'));
1023		        });
1024
1025				$(this).find('input[type=checkbox]').each(function(){
1026					var inputFetch = $(lastDivClone).find('input[type=checkbox]')[e];
1027		        	$(this).attr('checked', $(inputFetch).attr('checked'));
1028		        });
1029
1030				lastDivClone.fadeOut('fast', function() {$(this).remove();});
1031			} else {
1032				$(parent).find('input[type=text]').each(function(e){
1033					$(this).val("");
1034				});
1035
1036				$(parent).find('input[type=hidden]').each(function(e){
1037					$(this).val("");
1038				});
1039
1040				$(parent).find('input[type=file]').each(function(e){
1041					$(this).val("");
1042				});
1043
1044				$(this).find('input[type=radio]').each(function(){
1045		        	$(this).attr('selected', false);
1046		        });
1047
1048
1049				$(this).find('input[type=checkbox]').each(function(){
1050					if ($(this).attr('name') != "") {
1051						$(this).attr('checked', false);
1052					}
1053		        });
1054			}
1055		}
1056
1057		if (divMaster == "cidAdicional") {
1058			qtdeCidAdicional = qtdeCidAdicional - idx;
1059			qtdeCidAdicional = qtdeCidAdicional <= 0 ? 1 : qtdeCidAdicional ;
1060		}
1061	});
1062}
1063
1064function isBlankOrNull(value) {
1065    var retorno = true;
1066    if (typeof value != 'undefined') {
1067        retorno = $.trim(value).length == 0;
1068    }
1069	return retorno;
1070}
1071
1072/*
1073 * Converte um valor monetario para Number. Aceita os tres formatos que circulam
1074 * nas telas de recurso de glosa:
1075 *   - Number, como vem do JSON do REST                          -> 1202.64
1076 *   - String com ponto decimal e sem separador de milhar, que e
1077 *     o que o getRowData do jqGrid devolve para colunas com
1078 *     formatter:'currency'                                      -> "1202.64"
1079 *   - String em formato pt-BR, que e o texto cru da celula de
1080 *     colunas com formatter customizado e tambem o que o
1081 *     usuario digita                                            -> "R$ 1.202,64"
1082 *
1083 * Desambiguacao dos separadores: havendo ',' e '.', o ultimo a aparecer e o
1084 * decimal. Havendo apenas '.', ele e decimal, exceto quando seguido de
1085 * exatamente 3 digitos no fim ("1.202"), caso em que e separador de milhar.
1086 * A regra assume valores monetarios de 2 casas decimais.
1087 */
1088function parseCurrencyBR(valor) {
1089    if (valor === null || valor === undefined) {
1090        return 0;
1091    }
1092    if (typeof valor === 'number') {
1093        return isFinite(valor) ? valor : 0;
1094    }
1095
1096    var texto = ('' + valor).replace(/[^0-9,.\-]/g, '');
1097    var negativo = texto.indexOf('-') >= 0;
1098    texto = texto.replace(/-/g, '');
1099
1100    if (texto === '') {
1101        return 0;
1102    }
1103
1104    var ultimoPonto = texto.lastIndexOf('.');
1105    var ultimaVirgula = texto.lastIndexOf(',');
1106    var posDecimal = -1;
1107
1108    if (ultimoPonto >= 0 && ultimaVirgula >= 0) {
1109        posDecimal = Math.max(ultimoPonto, ultimaVirgula);
1110    } else if (ultimaVirgula >= 0) {
1111        posDecimal = ultimaVirgula;
1112    } else if (ultimoPonto >= 0 && !/\.\d{3}$/.test(texto)) {
1113        posDecimal = ultimoPonto;
1114    }
1115
1116    if (posDecimal >= 0) {
1117        texto = texto.substring(0, posDecimal).replace(/[.,]/g, '')
1118              + '.' + texto.substring(posDecimal + 1).replace(/[.,]/g, '');
1119    } else {
1120        texto = texto.replace(/[.,]/g, '');
1121    }
1122
1123    var numero = parseFloat(texto);
1124    if (isNaN(numero)) {
1125        return 0;
1126    }
1127    return negativo ? -numero : numero;
1128}
1129
1130/*
1131 * Formata um valor monetario em pt-BR ("R$1.202,64"). Tolera receber Number ou
1132 * String em qualquer um dos formatos aceitos por parseCurrencyBR.
1133 */
1134function formatCurrencyBR(valor) {
1135    var numero = parseCurrencyBR(valor);
1136    var negativo = numero < 0;
1137    var texto = Math.abs(numero).toFixed(2).replace('.', ',');
1138
1139    return (negativo ? '-R$' : 'R$') + texto.replace(/(\d)(?=(\d{3})+,)/g, '$1.');
1140}
1141
1142/*
1143 * Normaliza um valor monetario para a forma canonica com ponto decimal e sem
1144 * separador de milhar ("1202.64"), usada ao alimentar inputs de edicao inline.
1145 */
1146function toCurrencyInputValue(valor) {
1147    return parseCurrencyBR(valor).toFixed(2);
1148}
1149
1150function getCleanValue(value) {
1151    var retorno = true;
1152    if (typeof value != 'undefined') {
1153        retorno = $.trim(value).length == 0;
1154    }
1155    if(retorno)
1156    	return '';
1157    else
1158    	value;
1159}
1160
1161function DateUtil_format(date) {
1162    return $.datepicker.formatDate('dd/mm/yy', date)
1163}
1164
1165function somenteNumeroDecimal(objTextBox, e, index) {
1166	var sep = 0;
1167	var key = '';
1168	var i = j = 0;
1169	var len = len2 = 0;
1170	var strCheck = '0123456789';
1171	var aux = aux2 = '';
1172	if (e.which) {
1173		var whichCode = e.which;
1174	} else {
1175		var whichCode = e.keyCode;
1176	}
1177	if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8)) return true;
1178	key = String.fromCharCode(whichCode); // Valor para o código da Chave
1179	if (strCheck.indexOf(key) == -1) return false; // Chave inválida
1180	len = objTextBox.value.length;
1181	for (i = 0; i < len; i++)
1182		if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != ".")) break;
1183	aux = '';
1184	for (; i < len; i++)
1185		if (strCheck.indexOf(objTextBox.value.charAt(i)) != -1) aux += objTextBox.value.charAt(i);
1186	aux += key;
1187	if(len < index){
1188		len = aux.length;
1189		if (len == 0) objTextBox.value = '';
1190		if (len == 1) objTextBox.value = '0' + "." + '0' + aux;
1191		if (len == 2) objTextBox.value = '0' + "." + aux;
1192		if (len > 2 && len < 13) {
1193			aux2 = '';
1194			for (j = 0, i = len - 3; i >= 0; i--) {
1195				aux2 += aux.charAt(i);
1196				j++;
1197			}
1198			objTextBox.value = '';
1199			len2 = aux2.length;
1200			for (i = len2 - 1; i >= 0; i--)
1201				objTextBox.value += aux2.charAt(i);
1202			objTextBox.value += "." + aux.substr(len - 2, len);
1203		}
1204	}
1205	return false;
1206}
1207
1208function disablePast(inputId){
1209	const myInput = document.getElementById(inputId);
1210	myInput.onpaste = function(e) {
1211	   e.preventDefault();
1212	}
1213}
1214
1215function urlPathImgContext(){
1216	var currentPath = window.location.href;
1217	
1218	var prodPath = "conectividade";
1219	var localPath = "localhost:8080/conectividade";
1220	
1221	if( currentPath.indexOf( localPath ) != -1 ){
1222		return '/conectividade';
1223	}else{
1224		return '/conectividade';
1225	}
1226	
1227}
1228
1229function urlBuild(){
1230	
1231	var currentPath = window.location.href;
1232
1233	var prodPath = "conectividade";
1234	
1235	var localPath = /(localhost:)([0-9]{4})?\/(conectividade)/g;
1236		
1237	var hmlPath = "hml.connectmed.com.br";
1238	var hmlPetroPath = "hml-petrobras.connectmed.com.br";
1239
1240	var hmlProjPath = "hmlproj.connectmed.com.br";
1241	var hmlProjPetroPath = "hmlproj-petrobras.connectmed.com.br";
1242	
1243	var devPath = "dev.connectmed.com.br";
1244	var devPetroPath = "dev-petrobras.connectmed.com.br";
1245
1246	var devProjPath = "devproj.connectmed.com.br";
1247	var devProjPetroPath = "devproj-petrobras.connectmed.com.br";
1248	
1249	var preprodPath = "preprod.connectmed.com.br";
1250	var preprodPetroPath = "preprod-petrobras.connectmed.com.br";
1251	
1252	if( localPath.test( currentPath ) ){
1253		return 'http://localhost:8051';
1254		
1255	}else if(currentPath.indexOf( hmlPath ) != -1) {
1256		return 'https://hml.connectmed.com.br/Connectmed';
1257	}else if(currentPath.indexOf( hmlPetroPath ) != -1) {
1258		return 'https://hml.connectmed.com.br/Connectmed';
1259
1260	}else if(currentPath.indexOf( hmlProjPath ) != -1){
1261		return 'https://hmlproj.connectmed.com.br/Connectmed';
1262	}else if(currentPath.indexOf( hmlProjPetroPath ) != -1){
1263		return 'https://hmlproj.connectmed.com.br/Connectmed';
1264
1265	}else if(currentPath.indexOf( devPath ) != -1) {
1266		return 'https://dev.connectmed.com.br/Connectmed';
1267	}else if(currentPath.indexOf( devPetroPath ) != -1) {
1268		return 'https://dev.connectmed.com.br/Connectmed';
1269
1270	}else if(currentPath.indexOf( devProjPath ) != -1){
1271		return 'https://devproj.connectmed.com.br/Connectmed';
1272	}else if(currentPath.indexOf( devProjPetroPath ) != -1){
1273		return 'https://devproj.connectmed.com.br/Connectmed';
1274		
1275	}else if(currentPath.indexOf( preprodPath ) != -1){
1276		return 'https://preprod.connectmed.com.br/Connectmed';
1277	}else if(currentPath.indexOf( preprodPetroPath ) != -1){
1278		return 'https://preprod.connectmed.com.br/Connectmed';
1279
1280	}else{
1281		return 'https://wwwt.connectmed.com.br/Connectmed';
1282	}
1283}
1284
1285function urlBuildConnect(){
1286	
1287	var currentPath = window.location.href;
1288	
1289	var localPath = /(localhost:)([0-9]{4})?\//g;
1290		
1291	var hmlPath 	     = "hml.connectmed.com.br";
1292	var hmlPetroPath     = "hml-petrobras.connectmed.com.br";
1293
1294	var hmlProjPath 	 = "hmlproj.connectmed.com.br";
1295	var hmlProjPetroPath = "hmlproj-petrobras.connectmed.com.br";
1296
1297	var devPath 	     = "dev.connectmed.com.br";
1298	var devPetroPath     = "dev-petrobras.connectmed.com.br";
1299
1300	var devProjPath 	 = "devproj.connectmed.com.br";
1301	var devProjPetroPath = "devproj-petrobras.connectmed.com.br";
1302	
1303	var preprodPath 	 = "preprod.connectmed.com.br";
1304	var preprodPetroPath = "preprod-petrobras.connectmed.com.br";
1305	
1306	var prodPetroPath = "portaltiss.saudepetrobras.com.br";
1307	
1308	
1309	if( localPath.test( currentPath ) ){
1310		return 'http://'+(currentPath.match(localPath));
1311
1312	}else if(currentPath.indexOf( hmlPath ) != -1) {
1313		return 'https://hml.connectmed.com.br/';
1314	}else if(currentPath.indexOf( hmlPetroPath ) != -1) {
1315		return 'https://hml-petrobras.connectmed.com.br/';
1316		
1317	}else if(currentPath.indexOf( hmlProjPath ) != -1){
1318		return 'https://hmlproj.connectmed.com.br/';
1319	}else if(currentPath.indexOf( hmlProjPetroPath ) != -1){
1320		return 'https://hmlproj-petrobras.connectmed.com.br/';
1321		
1322	}else if(currentPath.indexOf( devPath ) != -1) {
1323		return 'https://dev.connectmed.com.br/';
1324	}else if(currentPath.indexOf( devPetroPath ) != -1) {
1325		return 'https://dev-petrobras.connectmed.com.br/';
1326		
1327	}else if(currentPath.indexOf( devProjPath ) != -1){
1328		return 'https://devproj.connectmed.com.br/';
1329	}else if(currentPath.indexOf( devProjPetroPath ) != -1){
1330		return 'https://devproj-petrobras.connectmed.com.br/';
1331				
1332	}else if(currentPath.indexOf( preprodPath ) != -1){
1333		return 'https://preprod.connectmed.com.br/';
1334	}else if(currentPath.indexOf( preprodPetroPath ) != -1){
1335		return 'https://preprod.connectmed.com.br/';
1336		
1337	}else if(currentPath.indexOf( prodPetroPath ) != -1){
1338		return 'https://portaltiss.saudepetrobras.com.br/';	
1339	}else{
1340		return 'https://wwwt.connectmed.com.br/';
1341	}
1342}
1343
1344function getContext(){
1345	
1346	var currentPath = window.location.href;
1347	var prodPath = "conectividade";
1348	var localPath = "localhost:8080/conectividade";
1349
1350	if( currentPath.indexOf( localPath ) != -1){
1351		return 'LOCAL';
1352	}else{
1353		return 'PROD';
1354	}
1355}
1356
1357$("#divCarregandoDialog").ajaxStop(function() {
1358    destroyAndRemoveDialogLoad("#divCarregandoDialog");
1359});
1360
1361//$.extend($.jgrid.defaults, {
1362//
1363//    ajaxGridOptions : {
1364//	beforeSend : function(xhr) {
1365//	    lastServerResponse = new Date();
1366//	    $(".loading").css("display", "none");
1367//	    informaCarregando();
1368//	},
1369//	complete : function(xhr) {
1370//	    $(".loading").css("display", "none");
1371//	    destroyAndRemoveDialogLoad("#divCarregandoDialog");
1372//	},
1373//	error : function(jqXHR, textStatus, errorThrown) {
1374//	    handleAjaxExceptions(jqXHR, textStatus, errorThrown);
1375//	    destroyAndRemoveDialogLoad("#divCarregandoDialog");
1376//	}
1377//    }
1378//});
1379
1380function simpleDisabledComponentButton($elemButton) {
1381	if($elemButton.length > 0){
1382		$elemButton.attr("disabled", "disabled");
1383		$elemButton.addClass("bt-disabled");
1384	}
1385}
1386
1387function simpleEnableComponentButton($elemButton) {
1388	if($elemButton.length > 0){
1389		$elemButton.removeAttr("disabled");
1390		$elemButton.removeClass("bt-disabled");
1391	}
1392}
1393
1394function simpleDisabledComponent($elem) {
1395	if($elem.length > 0){
1396		$elem.attr("disabled", "disabled");
1397	}
1398}
1399
1400function simpleEnableComponent($elem) {
1401	if($elem.length > 0){
1402		$elem.removeAttr("disabled");
1403	}
1404}
1405
1406$("#divCarregandoDialog").ajaxStop(function() {
1407    destroyAndRemoveDialogLoad("#divCarregandoDialog");
1408});
1409
1410function informaCarregando() {
1411	$(
1412	"<div id='divCarregandoDialog' title=''>" +
1413		"<div id='divCarregandoDialogContent' class='loading-dialog'>Por favor aguarde...<div id='divCarregandoLoad'></div></div></div>")
1414	.dialog({
1415		width : 240,
1416		height : 60,
1417		modal : true,
1418		autoOpen : true,
1419		draggable : false,
1420		resizable : false,
1421		closeOnEscape : false,
1422
1423		create : function(event, ui) {
1424			$(this).parent().css({
1425				"z-index" : 99999
1426			});
1427
1428			$(this).parent().children('.ui-helper-clearfix').hide();
1429			$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
1430
1431		}
1432
1433	});
1434}
1435function destroyCarregandoInDialog() {
1436	destroyAndRemoveDialogLoad("#divCarregandoDialogInDialog");
1437}
1438function informaCarregandoInDialog() {
1439	$(
1440			"<div id='divCarregandoDialogInDialog' title=''>" +
1441	"<div id='divCarregandoDialogInDialogContent' class='loading-dialog'>Por favor aguarde...<div id='divCarregandoInDialogLoad'></div></div></div>")
1442	.dialog({
1443		width : 240,
1444		height : 60,
1445		modal : true,
1446		autoOpen : true,
1447		draggable : false,
1448		resizable : false,
1449		closeOnEscape : false,
1450		
1451		create : function(event, ui) {
1452			$(this).parent().css({
1453				"z-index" : 99998
1454			});
1455			
1456			$(this).parent().children('.ui-helper-clearfix').hide();
1457			$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
1458			
1459		}
1460	
1461	});
1462}
1463
1464function destroyAndRemoveDialogLoad(dialogWidget) {
1465
1466	if ($(dialogWidget).length) {
1467		$(dialogWidget).dialog("destroy");
1468		$(dialogWidget).remove();
1469		 $('.ui-widget-overlay').removeClass('ui-widget-overlay');
1470		 $('.jqgrid-overlay').removeClass('jqgrid-overlay');
1471	}
1472
1473}
1474
1475function loadReport(url, download, jsonData) {
1476	informaCarregando();
1477	var strForm = "<form action='" + url + "' method='POST' id='reportForm' accept-charset='UTF-8' >";
1478	strForm = strForm + "<input type='hidden' name='filtros' value='" + jsonData + "'/>";
1479	strForm = strForm + "<input type='hidden' name='__asattachment' value='" + download + "'/>";
1480	strForm = strForm + "</form>";
1481
1482	if (download) { 
1483
1484		strForm = strForm + "<script type='text/javascript'> document.getElementById('reportForm').submit();</script>";
1485		$('#divCarregandoLoad').append(strForm);
1486		destroyAndRemoveDialogLoad("#divCarregandoDialog");
1487	} else { // is view inline ?
1488		var newWin = window.open('');
1489		newWin.document.open();
1490		newWin.document.write("<html><body>");
1491		newWin.document.write(strForm);
1492		newWin.document.write("</body><script>document.getElementById('reportForm').submit();</script>");
1493		newWin.document.write("</html>");
1494		destroyAndRemoveDialogLoad("#divCarregandoDialog");
1495	}
1496}
1497
1498function getActualContext(){
1499
1500	var currentPath = window.location.href;
1501	
1502	var prodPath = "conectividade";
1503	
1504	var localPath = "localhost:8080/conectividade";
1505
1506	var hmlPath = "hml.connectmed.com.br"
1507    var hmlPetroPath = "hml-petrobras.connectmed.com.br"
1508	
1509	var hmlProjPath = "hmlproj.connectmed.com.br"
1510	var hmlProjPetroPath = "hmlproj-petrobras.connectmed.com.br"
1511
1512	var devPath = "dev.connectmed.com.br"
1513	var devPetroPath = "dev-petrobras.connectmed.com.br"
1514			
1515	var devProjPath = "devproj.connectmed.com.br"
1516    var devProjPetroPath = "devproj-petrobras.connectmed.com.br"		
1517		
1518	var preprodPath = "preprod.connectmed.com.br"
1519	var preprodPetroPath = "preprod-petrobras.connectmed.com.br"		
1520		
1521	if( currentPath.indexOf( localPath ) != -1 ){
1522		return 'LOCAL';
1523		
1524    }else if(currentPath.indexOf( hmlPath ) != -1){
1525    	return 'HML';
1526    }else if(currentPath.indexOf( hmlPetroPath ) != -1){
1527		return 'HML_PETRO';
1528		
1529	}else if(currentPath.indexOf( hmlProjPath ) != -1){
1530		return 'HMLPROJ';
1531	}else if(currentPath.indexOf( hmlProjPetroPath ) != -1){
1532		return 'HMLPROJ_PETRO';
1533	
1534	}else if(currentPath.indexOf( devPath ) != -1){
1535    	return 'DEV';
1536    }else if(currentPath.indexOf( devPetroPath ) != -1){
1537		return 'DEV_PETRO';
1538		
1539	}else if(currentPath.indexOf( devProjPath ) != -1){
1540		return 'DEVPROJ';
1541	}else if(currentPath.indexOf( devProjPetroPath ) != -1){
1542		return 'DEVPROJ_PETRO';
1543	
1544	}else if(currentPath.indexOf( preprodPath ) != -1){
1545		return 'PREPROD';
1546	}else if(currentPath.indexOf( preprodPetroPath ) != -1){
1547		return 'PREPROD_PETRO';
1548		
1549	}else{
1550		return 'PRD';
1551	}
1552}
1553
1554function destroyAndRemoveDialog(dialogWidget) {
1555	if ($(dialogWidget).length) {
1556		$(dialogWidget).dialog("destroy");
1557		$(dialogWidget).remove();
1558	}
1559}
1560
1561function infoUser() {
1562	return $("#defaultAttention");
1563}
1564
1565/**
1566 * 
1567 * @param msg
1568 */
1569function nqmejs_showAttention(msg) {
1570	$('#defaultAttention > label').html(msg);
1571	$('#defaultAttention').fadeIn('slow');
1572	setTimeout(function(){
1573		$('#defaultAttention').fadeOut('slow');
1574	}, 10000);
1575}
1576function nqmejs_showInformation(msg) {
1577	$('#defaultInformation > label').html(msg);
1578	$('#defaultInformation').fadeIn('slow');
1579	setTimeout(function(){
1580		$('#defaultInformation').fadeOut('slow');
1581	}, 10000);
1582}
1583
1584function util_validaDatas(dataInicio, dataFim){
1585	 util_validaDatas(dataInicio, dataFim, false);
1586}
1587
1588function util_validaDatas(dataInicio, dataFim, showMessage){
1589	util_validaDatas(dataInicio, dataFim, showMessage, 30);
1590}
1591
1592function util_validaDatas(dataInicio, dataFim, showMessage, qtdMaximoDias){
1593
1594	if(dataInicio == '' || dataFim == ''){
1595		if(!isBlankOrNull(showMessage) && showMessage == true){
1596			infoUser().showMessage('Aten&#231;&#227;o', 'As duas datas devem ser preenchidas.');
1597		}
1598		return false;
1599	}
1600	
1601	var daysPassed = util_calculaData(dataInicio, dataFim);
1602	
1603	if(daysPassed < 0){
1604		if(!isBlankOrNull(showMessage) && showMessage == true){
1605			infoUser().showMessage('Aten&#231;&#227;o', 'Data de inicio deve ser maior que data fim!');
1606		}
1607		return false;
1608	}else if(daysPassed > qtdMaximoDias){
1609		if(!isBlankOrNull(showMessage) && showMessage == true){
1610			infoUser().showMessage('Aten&#231;&#227;o', 'A diferen&#231;a entre as datas n&#227;o pode ser maior que 30 dias.');
1611		}
1612		return false;
1613	
1614	}else{
1615	    return true;
1616	}
1617	
1618}
1619
1620/*
1621 * Resultado MAIOR que Zero --> Data1 é Menor que Data2
1622 * Resultado Menor que Zero --> Data1 é MAIOR que Data2
1623 * 
1624 */
1625function difDate(data1, data2) {
1626	var d1 = new Date(data1.substr(6, 4), data1.substr(3, 2) - 1, data1.substr(0, 2));
1627	var d2 = new Date(data2.substr(6, 4), data2.substr(3, 2) - 1, data2.substr(0, 2));
1628
1629	return Math.ceil((d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24);
1630}
1631
1632function util_calculaData(data1,data2){
1633	DAY = 1000 * 60 * 60  * 24
1634	var nova1 = data1.toString().split('/');
1635	Nova1 = nova1[1]+"/"+nova1[0]+"/"+nova1[2];
1636	var nova2 = data2.toString().split('/');
1637	Nova2 = nova2[1]+"/"+nova2[0]+"/"+nova2[2];
1638	
1639	var d1 = new Date(Nova1)
1640	var d2 = new Date(Nova2)
1641	var days_passed = Math.round((d2.getTime() - d1.getTime()) / DAY)
1642	
1643	console.log(days_passed);
1644	return days_passed;
1645}
1646
1647
1648function constrainPeriodBetweenDatePickers(initialDatePickerWidget, finalDatePickerWidget) {
1649	var initialDatePicker = $(initialDatePickerWidget);
1650	var finalDatePicker = $(finalDatePickerWidget);
1651
1652	initialDatePicker.datepicker("option", {
1653		beforeShow : function(input, instance) {
1654			var finalValue = finalDatePicker.val() || null;
1655			initialDatePicker.datepicker("option", "maxDate", finalValue);
1656//			$('#' + instance.id).mask("99/99/9999");
1657		}
1658
1659	});
1660
1661	finalDatePicker.datepicker("option", {
1662		beforeShow : function(input, instance) {
1663			var initialValue = initialDatePicker.val() || null;
1664			finalDatePicker.datepicker("option", "minDate", initialValue);
1665//			$('#' + instance.id).mask("99/99/9999");
1666		}
1667	});
1668	
1669}
1670
1671function openDocumento(url, nomeDialog) {
1672	$(
1673			"<div id='" + nomeDialog + "_openDoc' title='Documento'><div id='" + nomeDialog + "_openDocDialogContent'><div id='content-dialog-alert' class='content-dialog'><iframe id='iframeInterno' name='interno' style='width:100%;height:690px;' src='"
1674					+ url + "'></iframe></div></div></div>").dialog({
1675		width : 900,
1676		height : 700,
1677		modal : true,
1678		autoOpen : true,
1679		draggable : true,
1680		resizable : false,
1681		closeOnEscape : false,
1682
1683		create : function() {
1684
1685		},
1686
1687		close : function(event, ui) {
1688			destroyAndRemoveDialog(this);
1689		},
1690
1691		buttons : {
1692			"Cancelar" : function() {
1693				destroyAndRemoveDialog(this);
1694			}
1695		}
1696	});
1697}
1698
1699function validateEmail(input) {
1700//	var validRegex = "/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/";
1701//	
1702//	if (input.value.match(validRegex)) {
1703
1704	const emailRegex = new RegExp(/^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$/, "gm");
1705	
1706	if (emailRegex.test(input)) {
1707		return true;
1708	} else {
1709		return false;
1710	}
1711}
1712
1713function localStorageExpires()
1714{
1715    var toRemove = [],                      // Itens para serem removidos
1716        currentDate = new Date().getTime(); // Data atual em milissegundos
1717
1718    for (var i = 0, j = localStorage.length; i < j; i++) {
1719       var key = localStorage.key(i),
1720           value = localStorage.getItem(key);
1721
1722       // Verifica se o formato do item para evitar conflitar com outras aplicações
1723       if (value && value[0] === "{" && value.slice(-1) === "}") {
1724
1725            // Decodifica de volta para JSON
1726            var current = JSON.parse(value);
1727
1728            // Checa a chave expires do item especifico se for mais antigo que a data atual ele salva no array
1729            if (current.expires && current.expires <= currentDate) {
1730                toRemove.push(key);
1731            }
1732       }
1733    }
1734
1735    // Remove itens que já passaram do tempo
1736    // Se remover no primeiro loop isto poderia afetar a ordem,
1737    // pois quando se remove um item geralmente o objeto ou array são reordenados
1738    for (var i = toRemove.length - 1; i >= 0; i--) {
1739        localStorage.removeItem(toRemove[i]);
1740    }
1741}
1742
1743//localStorageExpires();//Auto executa a limpeza
1744
1745/**
1746 * Função para adicionar itens no localStorage
1747 * @param {string} chave Chave que será usada para obter o valor posteriormente
1748 * @param {*} valor Quase qualquer tipo de valor pode ser adicionado, desde que não falhe no JSON.stringify
1749 * @param {number} Tempo de vida em minutos do item
1750 */
1751function setLocalStorage(chave, valor, minutos)
1752{
1753    var expirarem = new Date().getTime() + (60000 * minutos);
1754
1755    localStorage.setItem(chave, JSON.stringify({
1756        "value": valor,
1757        "expires": expirarem
1758    }));
1759}
1760
1761/**
1762 * Função para obter itens do localStorage que ainda não expiraram
1763 * @param {string} chave Chave para obter o valor associado
1764 * @return {*} Retorna qualquer valor, se o item tiver expirado irá retorna undefined
1765 */
1766function getLocalStorage(chave)
1767{
1768    localStorageExpires();//Limpa itens
1769
1770    var value = localStorage.getItem(chave);
1771
1772    if (value && value[0] === "{" && value.slice(-1) === "}") {
1773
1774        // Decodifica de volta para JSON
1775        var current = JSON.parse(value);
1776
1777        return current.value;
1778    }
1779}
1780
1781function tratar_exibir_erro_loadGrid(jqXHR){
1782	destroyAndRemoveDialogLoad("#divCarregandoDialog");
1783	try{
1784		var responseTextObj = JSON.parse(jqXHR.responseText);
1785		//console.log('teste03: ', responseTextObj.message);
1786		infoUser().showMessage('Erro!', responseTextObj.message,  '', 700, 200, false);
1787	}catch(e){
1788		alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
1789	}
1790}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.