peticionamento_usuario_externo_cadastro_js.php 67.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
<?
/**
* ANATEL
*
* 01/08/2016 - criado por marcelo.bezerra@cast.com.br - CAST
*
* Funções de JS para cadastro de peticionamento de usuario externo
* Essa página é incluida na página principal do cadastro de peticionamento
*
* Documento com este mesmo nome de arquivo já foi adicionado.
*
*/

$strLinkAnexos = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_upload_anexo&id_tipo_procedimento='
		. $_GET['id_tipo_procedimento'] . '&id_orgao_acesso_externo=0');

$strLinkPrincipal = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_upload_principal&id_tipo_procedimento='
		. $_GET['id_tipo_procedimento'] . '&id_orgao_acesso_externo=0');

//Acao para upload de documento principal
$strLinkUploadDocPrincipal = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_upload_doc_principal');

//Acao para upload de documento essencial
$strLinkUploadDocEssencial = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_upload_doc_essencial');

//Acao para upload de documento complementar
$strLinkUploadDocComplementar = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_upload_doc_complementar');

//==================================================================
//saber se o documento principal é externo ou gerado
//==================================================================
$externo = $ObjTipoProcessoPeticionamentoDTO->getStrSinDocExterno();

//==================================================================
//saber se tem documento essencial configurado na parametrização
//==================================================================
$objRelTipoProcessoSeriePeticionamentoDTO = new RelTipoProcessoSeriePeticionamentoDTO();
$objRelTipoProcessoSeriePeticionamentoDTO->retTodos();
$objRelTipoProcessoSeriePeticionamentoDTO->setStrStaTipoDoc( RelTipoProcessoSeriePeticionamentoRN::$DOC_ESSENCIAL );
$objRelTipoProcessoSeriePeticionamentoDTO->setNumIdTipoProcessoPeticionamento( $objTipoProcDTO->getNumIdTipoProcessoPeticionamento() );
$objRelTipoProcessoSeriePeticionamentoRN = new RelTipoProcessoSeriePeticionamentoRN();

$arrRelTipoProcessoSeriePeticionamentoDTO = $objRelTipoProcessoSeriePeticionamentoRN->listar( $objRelTipoProcessoSeriePeticionamentoDTO );

if( is_array( $arrRelTipoProcessoSeriePeticionamentoDTO ) && count( $arrRelTipoProcessoSeriePeticionamentoDTO ) > 0 ){

	//saber se foram configurados documentos essenciais
	$temDocEssencial = true;
	
} else {
	
	//saber se foram configurados documentos essenciais
	$temDocEssencial = false;
}

//==================================================================
//saber se tem documento Complementar configurado na parametrização
//==================================================================
$objRelTipoProcessoSeriePeticionamentoDTO = new RelTipoProcessoSeriePeticionamentoDTO();
$objRelTipoProcessoSeriePeticionamentoDTO->retTodos();
$objRelTipoProcessoSeriePeticionamentoDTO->setStrStaTipoDoc( RelTipoProcessoSeriePeticionamentoRN::$DOC_COMPLEMENTAR );
$objRelTipoProcessoSeriePeticionamentoDTO->setNumIdTipoProcessoPeticionamento( $objTipoProcDTO->getNumIdTipoProcessoPeticionamento() );
$objRelTipoProcessoSeriePeticionamentoRN = new RelTipoProcessoSeriePeticionamentoRN();

$arrRelTipoProcessoSeriePeticionamentoDTO = $objRelTipoProcessoSeriePeticionamentoRN->listar( $objRelTipoProcessoSeriePeticionamentoDTO );

if( is_array( $arrRelTipoProcessoSeriePeticionamentoDTO ) && count( $arrRelTipoProcessoSeriePeticionamentoDTO ) > 0 ){

	//saber se foram configurados documentos complementares
	$temDocComplementar = true;
	
} else {
	
	//saber se foram configurados documentos complementares
	$temDocComplementar = false;
}

//TODO refatorar para utilizar controlador_ajax
$strLinkAjaxContato = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=contato_cpf_cnpj');

//Validacao de tipo de arquivos
$strSelExtensoesPrin = GerirExtensoesArquivoPeticionamentoINT::recuperaExtensoes(null,null,null,'S');
$strSelExtensoesComp = GerirExtensoesArquivoPeticionamentoINT::recuperaExtensoes(null,null,null,'N');

$strLinkAjaxChecarConteudoDocumento = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=validar_documento_principal');

?>
<script type="text/javascript">

var objAjaxContato = null;
var objPrincipalUpload = null;
var objTabelaDocPrincipal = null;

var objEssencialUpload = null;
var objTabelaDocEssencial = null;

var objComplementarUpload = null;
var objTabelaDocComplementar = null;

var objTabelaInteressado = null;

var objAutoCompletarInteressado = null;
var objLupaInteressados = null;

var docTipoEssencial = Array();

function validarQtdArquivosPrincipal(){

	try {
		objPrincipalUpload.executar();
	} catch(err) {
	    alert(" Erro: " + err);
	    console.log(err.stack);
	}
	
}

function validarUploadArquivo(numero){
	
	try {
		
		var isValido = true;

		if( numero == '1'){

		   //se a tabela existir na tela (ou seja se for doc principal do tipo externo)
		   //nao permitir adicionar mais do que 1 documento na grid	
		   var tbDocumentoPrincipal = document.getElementById('tbDocumentoPrincipal');
		   var hiddenCampoPrincipal = document.getElementById('hdnDocPrincipal');
		   
		   if( tbDocumentoPrincipal != null && 
			   tbDocumentoPrincipal != undefined ){

		    	if( hiddenCampoPrincipal != null && 
		    		hiddenCampoPrincipal != undefined &&
		    		hiddenCampoPrincipal.value != '' ){

					alert('Somente pode ter um Documento Principal.');

					document.getElementById("fileArquivoPrincipal").value = '';
					limparCampoUpload('1');

					isValido = false;
					return;
					
		 		}
			
		    }

		}
		
		//validar se selecionou nivel de acesso
		var cbHipoteseLegal = document.getElementById('hipoteseLegal'+numero);
		var cbNivelAcesso = document.getElementById('nivelAcesso'+numero);
		var strNivelAcesso = cbNivelAcesso.value;
		var strHipoteseLegal = '';

		if( cbHipoteseLegal != null && cbHipoteseLegal != undefined ){
		   strHipoteseLegal = cbHipoteseLegal.value;
		}
		
		//verificar se marcou o formato de documento
		var complemento = '';

		if(numero == '1'){ complemento = 'Principal'; }
		else if(numero == '2'){ complemento = 'Essencial'; }
		else if(numero == '3'){ complemento = 'Complementar'; }
		
		var fileArquivo = document.getElementById('fileArquivo' + complemento);
		var cbTipo = document.getElementById('tipoDocumento' + complemento);
		var strFormatoDocumento = '';
		var cbTipoConferencia = document.getElementById('TipoConferencia' + complemento);
		var strTipoConferencia = document.getElementById('TipoConferencia' + complemento).value;

		var radios = document.getElementsByName('formatoDocumento'+complemento);
		for (var i = 0, length = radios.length; i < length; i++) {

		    if (radios[i].checked) {		    
		    	strFormatoDocumento = radios[i].value;
		        break;
		    }
		}

		//validar campo Complemento
		var strTxtComplemento = document.getElementById('complemento' + complemento).value;

		//verificar se algum arquivo foi selecionado para o upload
		if( fileArquivo.value == '' ){
			   alert('Informe o arquivo para upload.');
			   isValido = false;
			   fileArquivo.focus();
			   return;
		}

		//validar campo/combo Tipo (apenas para Essencial ou Complementar)
		else if( ( numero == '2' || numero == '3' ) && ( cbTipo == undefined || cbTipo == null || cbTipo.value == '')  ){
			   alert('Informe o Tipo de Documento.');
			   isValido = false;
			   cbTipo.focus();
			   return;	
		}

		if(numero == '2'){

			docTipoEssencial.push(cbTipo.value);

			//validar campo Complemento
			if( strTxtComplemento == ""){
				   alert('Informe o Complemento do Tipo de Documento. Para mais informações, clique no ícone de Ajuda ao lado do nome do campo.');
				   isValido = false;
				   document.getElementById('complemento' + complemento).focus();
				   return;
			}
				
		}

		//validar campo Complemento
		if( strTxtComplemento == ""){
			   alert('Informe o Complemento do Tipo de Documento. Para mais informações, clique no ícone de Ajuda ao lado do nome do campo.');
			   isValido = false;
			   document.getElementById('complemento' + complemento).focus();
			   return;
		}
		
		//validar campo nivel de acesso
		else if( strNivelAcesso == ""){
		   alert('Informe o Nível de Acesso.');
		   isValido = false;
		   cbNivelAcesso.focus();
		   return;
		}

		//se informou Nivel de Acesso restrito, entao precisa informar tambem a hipotese legal
		else if( ( cbHipoteseLegal != null && cbHipoteseLegal != undefined ) && strNivelAcesso == '1' && strHipoteseLegal == ''){

			alert('Informe a Hipótese Legal.');
			isValido = false;
		   cbHipoteseLegal.focus();	
		   return;

		}

		else if( strFormatoDocumento == ''){
			alert('Informe o Formato do Documento.');
			isValido = false;
			return;
		}
		
		//se marcou formato de documento Digitalizado, verificar se selecione o tipo de conferencia
		else if( strFormatoDocumento == 'digitalizado' && strTipoConferencia == '' ){
			alert('Informe a Conferência com o documento digitalizado.');
			isValido = false;
			cbTipoConferencia.focus();
			return;
		}

		//validar tamanho do arquivo no lado server side apenas	
		if( isValido  ){

			if(numero == '1'){ objPrincipalUpload.executar(); }
			else if(numero == '2'){ objEssencialUpload.executar(); return true; }
			else if(numero == '3'){ objComplementarUpload.executar(); }
		  
		}
		
	} catch(err) {
	    alert(" Erro: " + err);
	    console.log(err.stack);
	}
	
}

//para uso em um caso excepcional do tipo essencial
function validarUploadArquivoEssencial(){
	
	try {

		var numero = '2';
		var isValido = true;
		
		//validar se selecionou nivel de acesso
		var cbHipoteseLegal = document.getElementById('hipoteseLegal'+numero);
		var cbNivelAcesso = document.getElementById('nivelAcesso'+numero);
		var strNivelAcesso = cbNivelAcesso.value;
		var strHipoteseLegal = '';

		if( cbHipoteseLegal != null && cbHipoteseLegal != undefined ){
		   strHipoteseLegal = cbHipoteseLegal.value;
		}
		
		//verificar se marcou o formato de documento
		var complemento = 'Essencial';
		var fileArquivo = document.getElementById('fileArquivo' + complemento);
		var cbTipo = document.getElementById('tipoDocumento' + complemento);
		var strFormatoDocumento = '';
		var cbTipoConferencia = document.getElementById('TipoConferencia' + complemento);
		var strTipoConferencia = document.getElementById('TipoConferencia' + complemento).value;

		var radios = document.getElementsByName('formatoDocumento'+complemento);
		for (var i = 0, length = radios.length; i < length; i++) {

		    if (radios[i].checked) {		    
		    	strFormatoDocumento = radios[i].value;
		        break;
		    }
		}

		//validar campo Complemento
		var strTxtComplemento = document.getElementById('complemento' + complemento).value;

		//verificar se algum arquivo foi selecionado para o upload
		if( fileArquivo.value == '' ){
			   //alert('Informe o arquivo para upload.');
			   alert('Deve adicionar pelo menos um Documento Essencial para cada Tipo.');
			   isValido = false;
			   fileArquivo.focus();
			   return;
		}

		//validar campo/combo Tipo (apenas para Essencial ou Complementar)
		else if( cbTipo == undefined || cbTipo == null || cbTipo.value == '' ){
			   alert('Informe o Tipo de Documento.');
			   isValido = false;
			   cbTipo.focus();
			   return;	
		}

		docTipoEssencial.push(cbTipo.value);

		//validar campo Complemento
		if( strTxtComplemento == ""){
				   alert('Informe o Complemento do Tipo de Documento. Para mais informações, clique no ícone de Ajuda ao lado do nome do campo.');
				   isValido = false;
				   document.getElementById('complemento' + complemento).focus();
				   return;
		}

		//validar campo Complemento
		if( strTxtComplemento == ""){
			   alert('Informe o Complemento do Tipo de Documento. Para mais informações, clique no ícone de Ajuda ao lado do nome do campo.');
			   isValido = false;
			   document.getElementById('complemento' + complemento).focus();
			   return;
		}
		
		//validar campo nivel de acesso
		else if( strNivelAcesso == ""){
		   alert('Informe o Nível de Acesso.');
		   isValido = false;
		   cbNivelAcesso.focus();
		   return;
		}

		//se informou Nivel de Acesso restrito, entao precisa informar tambem a hipotese legal
		else if( ( cbHipoteseLegal != null && cbHipoteseLegal != undefined ) && strNivelAcesso == '1' && strHipoteseLegal == ''){

			alert('Informe a Hipótese Legal.');
			isValido = false;
		   cbHipoteseLegal.focus();	
		   return;

		}

		else if( strFormatoDocumento == ''){
			alert('Informe o Formato do Documento.');
			isValido = false;
			return;
		}
		
		//se marcou formato de documento Digitalizado, verificar se selecione o tipo de conferencia
		else if( strFormatoDocumento == 'digitalizado' && strTipoConferencia == '' ){
			alert('Informe a Conferência com o documento digitalizado.');
			isValido = false;
			cbTipoConferencia.focus();
			return;
		}

		return isValido;
		
	} catch(err) {
	    alert(" Erro: " + err);
	    console.log(err.stack);
	}
	
}

function getStrTipoDocumento( idItem, complemento ){

	var options = document.getElementById('tipoDocumento'+complemento).options;
	var texto = '';
    for(var i=0;i < options.length;i++){
      if (options[i].value == idItem ){
    	texto = options[i].text;
        break;
      }
    }
	
	return texto;
	
}

function limparCampoUpload( numero ){

	//verificar se marcou o formato de documento
	var complemento = '';

	if(numero == '1'){ complemento = 'Principal'; }
	else if(numero == '2'){ complemento = 'Essencial'; }
	else if(numero == '3'){ complemento = 'Complementar'; }
	
	var fileArquivo = document.getElementById('fileArquivo' + complemento);

	var strFormatoDocumento = '';
	var cbNivelAcesso = document.getElementById('nivelAcesso'+numero);
	var cbTipoConferencia = document.getElementById('TipoConferencia' + complemento);
	var strTipoConferencia = document.getElementById('TipoConferencia' + complemento).value;

	var radios = document.getElementsByName('formatoDocumento'+complemento);
	for (var i = 0, length = radios.length; i < length; i++) {

	    if (radios[i].checked) {		    
	    	strFormatoDocumento = radios[i].value;
	        break;
	    }
	}
	
	if(numero == '1'){ objPrincipalUpload.executar(); }
	else if(numero == '2'){ objEssencialUpload.executar(); }
	else if(numero == '3'){ objComplementarUpload.executar(); }

	//==================================================
	//depois que o upload for executado limpar os campos
	//==================================================
	
	//limpar o campo de upload
	fileArquivo.value = '';
	
	//limpar e ocultar camposDigitalizadoEssencial (Formato Documento)
	
	for (var i = 0, length = radios.length; i < length; i++) {

		radios[i].checked = '';
	    radios[i].checked = false;		    
    
	}
	
	//document.getElementById('camposDigitalizado'+complemento).style.display = 'none';
	
	//limpar e ocultar hipotese legal ( divhipoteseLegal1 )
	if(cbNivelAcesso.getAttribute("type")!= 'hidden'){
		document.getElementById('divhipoteseLegal'+numero).style.display = 'none';
	}

	//limpar o campo Complemento
	document.getElementById('complemento'+complemento).value = '';

	//retornar a combo "Nivel de Acesso" para a primeira opçao selecionada
	if(cbNivelAcesso.getAttribute("type")!= 'hidden'){
		cbNivelAcesso.options[0].selected='selected';
	}

	//se nao for o "Principal", resetar a seleçao da combo "Tipo"
	if(numero != '1'){
		document.getElementById('tipoDocumento'+complemento).options[0].selected='selected';				
	}

	cbTipoConferencia.options[0].selected='selected';
	document.getElementById('camposDigitalizado'+complemento).style.display = 'none';
	document.getElementById('camposDigitalizado'+complemento+'Botao').style.display = 'block';
	
}

function validarQtdArquivosComplementar(){

	try {

		objComplementarUpload.executar();
		
	} catch(err) {
	    alert(" Erro: " + err);
	    console.log(err.stack);
	}
	
}

function validarQtdArquivos(){

	try {
		objUpload.executar();
	} catch(err) {
	    alert(" Erro: " + err);
	    console.log(err.stack);
	}
	
}

function validarQtdArquivosPrincipal(){

	try {
	  objPrincipalUpload.executar();
	} catch(err) {
	    alert(" Erro: " + err);
	    console.log(err.stack);
	}
}

function abrirJanelaDocumento( ){

	 <?php
	 $linkEditor = PaginaSEIExterna::getInstance()->formatarXHTML(
	 		SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=editor_peticionamento_montar&id_serie=' . $objTipoProcDTO->getNumIdSerie() ));
	 ?>
	 
	 var janelaEditor = infraAbrirJanela('','janelaEditor_<?=SessaoSEIExterna::getInstance()->getNumIdUsuarioExterno()?>',infraClientWidth(),infraClientHeight(),'location=0,status=0,resizable=1,scrollbars=1',false);

	 if (janelaEditor.location == 'about:blank'){
	      janelaEditor.location.href = '<?=$linkEditor?>';
	 }

	 janelaEditor.focus();
 
}

function receberInteressado( arrDadosInteressado, InteressadoCustomizado ){

	//antes de adicionar verificar se o interessado ja está na grid
	var strHash = document.getElementById('hdnListaInteressadosIndicados').value;
	
	//caractere de quebra de linha/registro
	var arrHash = strHash.split('¥');
	var qtdX = arrHash.length;
	  
	if( qtdX == 1 && arrHash[0] == "" ){

	  arrHash = Array();
	  arrHash[0] = strHash;
		  
	}	

	if( strHash != "") {		

		  for(var i = 0; i < qtdX ; i++ ){

			  //caractere de quebra de coluna/campo	
			  var arrLocal = arrHash[i].split('±');	
			  var idContato = arrLocal[0];

			  if( idContato == arrDadosInteressado[0]){
				 alert('O Interessado informado já foi selecionado.');
				 document.getElementById('txtCPF').value='';
				 document.getElementById('txtNomeRazaoSocial').value='';
                 return false;
		      }
			  
		  }
	  
	  }

	debugger;
	objTabelaInteressado.adicionar([ arrDadosInteressado[0], 
	                    arrDadosInteressado[1] , 
	                  	arrDadosInteressado[2] ,  
	                  	arrDadosInteressado[3], 
	                  	'' ]);

    if( InteressadoCustomizado != "") {

    	objTabelaInteressado.adicionarAcoes(
		arrDadosInteressado[0] , 
		"<a href='javascript:;' onclick=\"abrirCadastroInteressadoAlterar('" + arrDadosInteressado[0] +"', '" + arrDadosInteressado[1] +"', '"+ arrDadosInteressado[2] +"')\"><img title='Alterar Interessado' alt='Alterar Interessado' src='/infra_css/imagens/alterar.gif' class='infraImg' /></a>",
		false,
		true);
		
    } else {

    	objTabelaInteressado.adicionarAcoes(
    	  arrDadosInteressado[0] , 
    	  "", 
    	  false,
    	  true);
    }
    
	document.getElementById("txtCPF").value='';
	document.getElementById("txtCNPJ").value='';
	document.getElementById("hdnCustomizado").value='';
	document.getElementById("txtNomeRazaoSocial").value='';
	document.getElementById("hdnIdInteressadoCadastrado").value='';
	
	infraEfeitoTabelas();
	
}

function addDocumento( docCustomizado ){

	//pegar valor da combo nivel de acesso nivelAcesso1
	var nivelAcessoCombo1 = document.getElementById("nivelAcesso1");
	var txtNivelAcessoCombo1 = nivelAcessoCombo1.options[nivelAcessoCombo1.selectedIndex].text;

	//pegar valor da hipotese legal
	var hipoteseCombo1 = document.getElementById("hipoteseLegal1");
	var valorHipoteseLegal = hipoteseCombo1.options[hipoteseCombo1.selectedIndex].text;
	
	//pegar data
	var data=new Date()
	var dia=data.getDate();
	var mes=data.getMonth();
	var ano=data.getFullYear();
	dataFormatada = dia + '/' + (mes++) + '/' + ano;
	
	//pegar tamanho
	var tamanhoFormatado = "tamanho";

	//montar nome documento
	var nomeDocumento = "nm documento";
	
	// Find a <table> element with id="myTable":
	var table = document.getElementById("tbDocumentoPrincipal");

	// Create an empty <tr> element and add it to the 1st position of the table:
	var row = table.insertRow(-1);
	row.className = 'infraTrClara';
	
	// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
	
	//Nome do arquivo	
	var cell1 = row.insertCell(0);
	cell1.className = 'infraTdSetaOrdenacao';

	//Data	
	var cell2 = row.insertCell(1);
	cell2.className = 'infraTdSetaOrdenacao';

	//Tamanho	
	var cell3 = row.insertCell(2);
	cell3.className = 'infraTdSetaOrdenacao';
	
	//Documento	
	var cell4 = row.insertCell(3);
	cell4.className = 'infraTdSetaOrdenacao';
	
	//Nível de acesso	
	var cell5 = row.insertCell(4);
	cell5.className = 'infraTdSetaOrdenacao';
	
	//Ações
	var cell6 = row.insertCell(5);
	cell6.className = 'infraTdSetaOrdenacao';

	cell1.innerHTML = nomeDocumento;
	cell1.align='center';
	
	cell2.innerHTML = dataFormatada;
	cell2.align='center';

	cell3.innerHTML = tamanhoFormatado;
	cell3.align='center';
	
	cell4.innerHTML = nomeDocumento;
	cell4.align='center';
	
	cell5.innerHTML = txtNivelAcessoCombo1;
	cell5.align='center';

	if( docCustomizado != null && docCustomizado == true ){
	  cell6.innerHTML = " customizado ";
	} else {
		cell6.innerHTML = " selecionado ";
	}

	cell6.align='center';

	infraEfeitoTabelas();
	
}

function deleteRow(btn) {
  var row = btn.parentNode.parentNode;
  row.parentNode.removeChild(row);
}

function addDocumentoComplementar( docCustomizado ){

	//pegar valor da combo nivel de acesso nivelAcesso1
	var nivelAcessoCombo2 = document.getElementById("nivelAcesso2");
	var txtNivelAcessoCombo2 = nivelAcessoCombo2.options[nivelAcessoCombo2.selectedIndex].text;

	//pegar valor da hipotese legal
	var hipoteseCombo2 = document.getElementById("hipoteseLegal2");
	var valorHipoteseLegal2 = hipoteseCombo2.options[hipoteseCombo2.selectedIndex].text;
	
	// Find a <table> element with id="myTable":
	//var table = document.getElementById("tbDocumentoComplementar");
	var table = document.getElementById("tblAnexos");

	// Create an empty <tr> element and add it to the 1st position of the table:
	var row = table.insertRow(-1);
	row.className = 'infraTrClara';

	// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
	
	//Nome do arquivo	
	var cell1 = row.insertCell(0);
	cell1.align = 'center';
	cell1.className = 'infraTdSetaOrdenacao';

	//Data	
	
	var data=new Date()
	var dia=data.getDate();
	var mes=data.getMonth();
	var ano=data.getFullYear();
	data = dia + '/' + (mes++) + '/' + ano;

	var cell2 = row.insertCell(1);
	cell2.style.width = '120';
	cell2.align = 'center';
	cell2.className = 'infraTdSetaOrdenacao';

	//Tamanho	
	var cell3 = row.insertCell(2);
	cell3.align = 'center';
	cell3.className = 'infraTdSetaOrdenacao';
	
	//Documento	
	var cell4 = row.insertCell(3);
	cell4.align = 'center';
	cell4.className = 'infraTdSetaOrdenacao';
	
	//Nível de acesso	
	var cell5 = row.insertCell(4);
	cell5.align = 'center';
	cell5.className = 'infraTdSetaOrdenacao';
	
	//Ações
	var cell6 = row.insertCell(5);
	cell6.align = 'center';
	cell6.className = 'infraTdSetaOrdenacao';

	cell1.innerHTML = "NEW CELL1";
	cell2.innerHTML = data;
	cell3.innerHTML = "NEW CELL3";
	cell4.innerHTML = "NEW CELL4";
	cell5.innerHTML = txtNivelAcessoCombo2;

	if( docCustomizado != null && docCustomizado == true ){
	  cell6.innerHTML = " customizado ";
	} else {
		cell6.innerHTML = " selecionado ";
	}

	infraEfeitoTabelas();
}

function addFormatoDocumento(){
	alert('Formato documento');
}

//função de apoio para debug
function dump(obj) {

    var out = '';

    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    alert(out);

}

function validarFormulario(){
	
	//valida campo especificação
	var textoEspecificacao = document.getElementById("txtEspecificacao").value;
	var cbUF = document.getElementById("selUFAberturaProcesso");	
	var ufSelecionada = '';
	var DocPrincipalValidado = false;
	
	var selInteressados = document.getElementById("selInteressados");	

	if( cbUF != undefined && cbUF != null ){ 
		ufSelecionada = cbUF.value;
	}
	
	if( textoEspecificacao == '' ){
      alert('Informe a Especificação.');
      document.getElementById("txtEspecificacao").focus();
      return false;      
	}

	if( cbUF != undefined && cbUF != null && ufSelecionada == '' ){
	      alert('Informe a UF em que o processo deve ser aberto:');
	      cbUF.focus();
	      return false;      
	}

	if( selInteressados != undefined && selInteressados != null && selInteressados.value == '' ){
	      alert('Informe o(s) Interessado(s).');
	      selInteressados.focus();
	      return false;      
	}		 

	//aplicando validaçao de interessados informados no cenario de indicaçao por cpf ou cnpj
	var tbInteressadosIndicados = document.getElementById("tbInteressadosIndicados");	
	var hdnListaInteressadosIndicados = document.getElementById("hdnListaInteressadosIndicados");
	var optTipoPessoaFisica = document.getElementById("optTipoPessoaFisica");
	
	if( tbInteressadosIndicados != null && hdnListaInteressadosIndicados != null && hdnListaInteressadosIndicados.value == ""  ){

		alert('Informe o(s) Interessado(s).');
		optTipoPessoaFisica.focus();
	    return false;  
	}
	
	//aplicando validações relacionadas ao documento principal
	var fileArquivoPrincipal = document.getElementById('fileArquivoPrincipal');
	var complementoPrincipal = document.getElementById('complementoPrincipal');
	var nivelAcessoPrincipal = document.getElementById('nivelAcesso1');
	var hipoteseLegalPrincipal = document.getElementById('hipoteseLegal1');
		
	//validando seleçao de nivel de acesso principal e hipotese legal principal
	var tbDocumentoPrincipal = document.getElementById('tbDocumentoPrincipal');

	//se for documento principao do tipo externo, só validar complemento, 
	// nivel de acesso e hipotese legal SE a grid estiver ainda sem nenhum documento
	if( tbDocumentoPrincipal != null && 
		tbDocumentoPrincipal != undefined ){

		var hdnDocPrincipal = document.getElementById('hdnDocPrincipal').value;

		var strFormatoDocumento = '';
		var cbTipoConferencia = document.getElementById('TipoConferenciaPrincipal');
		var strTipoConferencia = document.getElementById('TipoConferenciaPrincipal').value;

		var radios = document.getElementsByName('formatoDocumentoPrincipal');
		for (var i = 0, length = radios.length; i < length; i++) {

		    if (radios[i].checked) {		    
		    	strFormatoDocumento = radios[i].value;
		        break;
		    }
		}
		
		if( hdnDocPrincipal == "" && fileArquivoPrincipal.value == ''){
			alert('Informe o Documento Principal.');
			fileArquivoPrincipal.focus();
			return false;
			
		} else if( hdnDocPrincipal == "" && complementoPrincipal.value == ''){
			alert('Informe o Complemento do Tipo de Documento. Para mais informações, clique no ícone de Ajuda ao lado do nome do campo.');
			complementoPrincipal.focus();
			return false;
			
		} else if( hdnDocPrincipal == "" && nivelAcessoPrincipal.value == ''){
			alert('Informe o Nível de Acesso.');
			nivelAcessoPrincipal.focus();
			return false;
			
		} else if( hdnDocPrincipal == "" && nivelAcessoPrincipal.value == '1' && hipoteseLegalPrincipal.value == ''){
			alert('Informe a Hipótese Legal.');
			hipoteseLegalPrincipal.focus();
			return false;
		} else if( hdnDocPrincipal == "" && strFormatoDocumento == ''){
			alert('Informe o Formato do Documento.');
			return false;
		} else if( hdnDocPrincipal == "" && strFormatoDocumento == 'digitalizado' && strTipoConferencia == '' ){
			alert('Informe a Conferência com o documento digitalizado.');
			return false;
		}

	} 

	//se for documento gerado sempre valida complemento, nivel de acesso e hipotese legal
	else {
		
		if( nivelAcessoPrincipal.value == ''){
			alert('Informe o Nível de Acesso.');
			nivelAcessoPrincipal.focus();
			return false;
			
		} else if( nivelAcessoPrincipal.value == '1' && hipoteseLegalPrincipal.value == ''){
			alert('Informe a Hipótese Legal.');
			hipoteseLegalPrincipal.focus();
			return false;
		}
		
	}

	//validar se pelo menos um doc principal foi adicionado CASO
	//a grid de doc principal exista na tela (ou seja, quando a parametrização)
	//informar doc principal do tipo Externo

	if( tbDocumentoPrincipal != null && 
		tbDocumentoPrincipal != undefined ){

		var strHashPrincipal = document.getElementById('hdnDocPrincipal').value;
		
		if( strHashPrincipal == ''){
			alert('Informe o Documento Principal.');
			document.getElementById('fileArquivoPrincipal').focus();
			return false;
		} else {
			DocPrincipalValidado = true;
		}
	} 

	//caso doc principal seja do tipo "Gerado", fazer requisição AJAX
	//para validar se usuário salvou na sessao algum conteudo para o documento
	//caso nao tenha conteudo obrigar usuario a informar
	else {

		var conteudoDocumento = "";
		
		$( document ).ready(function() {
		
			//var  formData = "";  
	   		
			$.ajax({
			    url : "<?=PaginaSEIExterna::getInstance()->formatarXHTML(SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=validar_documento_principal'))?>",
			    type: "POST",
			    //data : formData,
			    async: false,
			    success: function(data, textStatus, jqXHR)
			    {
			        conteudoDocumento = data;
			        if (data==''){
			        	alert("O documento principal deste tipo de peticionamento possui modelo previamente definido e deve ser editado diretamente no sistema. Para continuar o peticionamento, antes é necessário acessar o Editor do SEI no link “clique aqui para editar conteúdo” em frente ao campo “Documento Principal”, preencher apenas os campos pertinentes com os dados da demanda e clicar no botão “Salvar” no canto superior esquerdo do Editor.");
			        	return;
			        }else{
			        	DocPrincipalValidado=true;
			        }
			        
			    },
			    error: function (jqXHR, textStatus, errorThrown)
			    {
				   alert('Erro ao validar documento principal.'); 	
				   console.log('Erro' + textStatus);
			       return;
			    }
			});
		});
		
	}

	if (DocPrincipalValidado==true){
		
		//valida se todos os tipos essenciais contem na lista
		var comboTipoEssencial = document.getElementById('tipoDocumentoEssencial');
		
		if(comboTipoEssencial!=null){
			  var retornoUploadEssencial = false;
			  var validarTipoEssenc = true;
			  var strHashEssencial = document.getElementById('hdnDocEssencial').value;
	
			  //caractere de quebra de linha/registro
			  var arrHashEssencial = strHashEssencial.split('¥');
			  var qtdX = arrHashEssencial.length;
			  
			  if( qtdX == 1 && arrHashEssencial[0] == "" ){
	
				  arrHashEssencial = Array();
				  arrHashEssencial[0] = strHashEssencial;
				  
			  }	
			  			  
			  var local = 9;
			  var tiposIncluidos = Array();
	
			//so vai adicionar no array dos incluidos quando tem registros na grid
			  if( strHashEssencial != "") {		
			  
				  for(var i = 0; i < qtdX ; i++ ){
					  	
					  //caractere de quebra de coluna/campo	
					  var arrLocal = arrHashEssencial[i].split('±');	
					  var tipo = arrLocal[local];
		
					  if(tiposIncluidos.indexOf(tipo) <= -1){
						  tiposIncluidos.push(arrLocal[local]);
					  }
					  
				  }
			  
			  } else {
				  //grid vazia e campos de upload de essencial nao preenchidos	
				  retornoUploadEssencial = validarUploadArquivoEssencial();
	
				  if( retornoUploadEssencial != true ){
				     return false;
				  }
		      }
			  
			  var tamnhoOptions = comboTipoEssencial.options.length-1;
			  
			  if(tiposIncluidos.length == 0 || tamnhoOptions != tiposIncluidos.length){
				 validarTipoEssenc = false;
			  }
			  
		      if(!validarTipoEssenc){
		    	  alert('Deve adicionar pelo menos um Documento Essencial para cada Tipo.');
			      document.getElementById('fileArquivoEssencial').focus();
			      return false;      
		      }
		}
		 
		return true;
		
	}else{
		
		return false;

	}

	
	
}

function abrirPeticionar(){
    
    if( validarFormulario() ) {
	
         infraAbrirJanela('<?=PaginaSEIExterna::getInstance()->formatarXHTML(SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?id_tipo_procedimento=' . $_GET['id_tipo_procedimento'] .'&acao=peticionamento_usuario_externo_concluir&tipo_selecao=2'))?>',
    	             'concluirPeticionamento',
    	             770,
    	             464,
    	             '', //options
    	             false); //modal     
    } 
}

function abrirCadastroInteressadoAlterar( id, tipo, cpfcnpj){

	//charmar janela para cadastrar um novo interessado
	$('#txtNomeRazaoSocial').val('');
	$('#hdnCustomizado').val('');
	$('#hdnIdEdicao').val( id );

	<?php 
	$strLinkEdicaoPF = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?edicao=true&acao=peticionamento_interessado_cadastro&tipo_selecao=2&cpf=true&id_orgao_acesso_externo=0');
	$strLinkEdicaoPJ = SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?edicao=true&acao=peticionamento_interessado_cadastro&tipo_selecao=2&cnpj=true&id_orgao_acesso_externo=0');
	?>
	
	if( tipo == 'Pessoa Física' ){
		var str = '<?= $strLinkEdicaoPF ?>';
	}

	else if( tipo == 'Pessoa Jurídica' ){
		var str = '<?= $strLinkEdicaoPJ ?>';
	}
	
	infraAbrirJanela( str, 'cadastrarInteressado', 900, 900, '', false); //modal 
	return;
	
}

function abrirCadastroInteressado(){

	//so abrir o CPF/CNPJ tiver sido informado e NAO pertencer a um contato cadastrado
	var txtcpf = document.getElementById("txtCPF").value;
	var txtcnpj = document.getElementById("txtCNPJ").value;
	var conteudo = '';
	
	var chkTipoPessoaFisica = document.getElementById("optTipoPessoaFisica").checked;
	var chkTipoPessoaJuridica = document.getElementById("optTipoPessoaJuridica").checked;

	if( chkTipoPessoaFisica ){
		conteudo = txtcpf;
	}

	else if( chkTipoPessoaJuridica ){
		conteudo = txtcnpj;
	}
	
	if( conteudo == '' ){

		if( chkTipoPessoaFisica ){
			alert('Informe o CPF.');
			document.getElementById("txtCPF").focus();
		}

		else if( chkTipoPessoaJuridica ){
			alert('Informe o CNPJ.');
			document.getElementById("txtCNPJ").focus();
		}

		return;
	} 

	//checar se o CPF/CNPJ está no formato válido e se estiver, consultar via AJAX para tentar obter um interessado cadastrado
	else {

		if( chkTipoPessoaFisica ){
			
			ponto = txtcpf.split(".");
			traco = txtcpf.split("-");

			//cpf tem que ser valido , ter 2 pontos e um traço (ou seja, estar na mascara)
			if (!infraValidarCpf(infraTrim( txtcpf )) || (ponto.length-1) != 2 || (traco.length-1) != 1 ){
				
				alert('CPF Inválido.');
				document.getElementById('txtCPF').focus();
				document.getElementById('txtNomeRazaoSocial').value = '';
				return;
			
			}
			
		}

		else if( chkTipoPessoaJuridica ){

			ponto = txtcnpj.split(".");
			traco = txtcnpj.indexOf("-");
			barra = txtcnpj.indexOf("/");
			
			if (!infraValidarCnpj(infraTrim( txtcnpj )) || ponto.length != 3 || traco != 15 || barra != 10 ){
				
				alert('CNPJ Inválido.');
				document.getElementById('txtCNPJ').focus();
				document.getElementById('txtNomeRazaoSocial').value = '';
				return;
			
			}
			
		}

		//se chegar aqui o CPF/CNPJ está valido, entao consultar via AJAX para ver se o contato já está cadastrado
		var  formData = "cpfcnpj=" +  conteudo;  //Name value Pair
   
		$.ajax({
		    url : "<?= $strLinkAjaxContato ?>",
		    type: "POST",
		    data : formData,
		    success: function(data, textStatus, jqXHR)
		    {
		        //data - response from server
		        
		        if( data != null && data != undefined && data != ""){

				  var obj = jQuery.parseJSON( data );
				  $('#hdnIdInteressadoCadastrado').val(obj.id);
		    	  $('#txtNomeRazaoSocial').val(obj.nome);
		    	  $('#hdnCustomizado').val('');
		    	  return;
		        } 

		        else{
			      	  
					//charmar janela para cadastrar um novo interessado
					$('#txtNomeRazaoSocial').val('');
					$('#hdnCustomizado').val('');

					if( chkTipoPessoaFisica ){
						var str = '<?= SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_interessado_cadastro&tipo_selecao=2&cpf=true&cadastro=true') ?>';
					}

					else if( chkTipoPessoaJuridica ){
						var str = '<?= SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_interessado_cadastro&tipo_selecao=2&cnpj=true&cadastro=true') ?>';
					}

					infraAbrirJanela( str, 'cadastrarInteressado', 900, 900, '', false); //modal 
					return;
					
				}
		    	
		    },
		    error: function (jqXHR, textStatus, errorThrown)
		    {
		       alert('Erro' + textStatus);
		       return;
		    }
		});
				
		return;
		
	}
   	
    
}

function inicializar(){

	<? if( $objTipoProcDTO->getStrSinIIIndicacaoDiretaContato() == 'S') { ?>
	objLupaInteressados = new infraLupaSelect('selInteressados','hdnInteressados','<?=$strLinkInteressadosSelecao?>');   

	objAutoCompletarInteressado = new infraAjaxAutoCompletar('hdnIdInteressado','txtInteressado','<?=$strLinkAjaxInteressado?>');
    objAutoCompletarInteressado.limparCampo = true;
    //objAutoCompletarInteressado.tamanhoMinimo = 3;

    objAutoCompletarInteressado.prepararExecucao = function(){
      return 'extensao='+document.getElementById('txtInteressado').value;
    };
    
    objAutoCompletarInteressado.processarResultado = function(id,descricao,complemento){
      if (id!=''){
        var options = document.getElementById('selInteressados').options;

        for(var i=0;i < options.length;i++){
          if (options[i].value == id){
            self.setTimeout('alert(\'Interessado já consta na lista.\')',100);
            break;
          }
        }

        if (i==options.length){

        for(i=0;i < options.length;i++){
          options[i].selected = false;
        }

        opt = infraSelectAdicionarOption(document.getElementById('selInteressados'),descricao,id);
        objLupaInteressados.atualizar();
        opt.selected = true;
      }

      document.getElementById('txtInteressado').value = '';
      document.getElementById('txtInteressado').focus();
    }};
	<? } ?>

	<? if( $externo == "S" ) { ?>
	  //tem doc principal externo
	  carregarCamposDocPrincipalUpload();
	<? } ?>

	<? if( $temDocEssencial ) { ?>
	  //tem doc essencial
	  carregarCamposDocEssencialUpload();
	<? } ?>

	<? if( $temDocComplementar ) { ?>
	  //tem doc complementar
	  carregarCamposDocComplementarUpload();
	<? } ?>
	
	infraEfeitoTabelas();  
	document.getElementById('txtEspecificacao').focus();

	//Preenchimento com o endereço do contexto
	  objAjaxContato = new infraAjaxComplementar(null,'<?=$strLinkAjaxContato?>');
	  objAjaxContato.limparCampo = false;
	  
	  objAjaxContato.prepararExecucao = function(){
		   return 'cpfCnpj='+document.getElementById('txtCPF').value;
      }

	  objAjaxContato.processarResultado = function(arr){

		//inicio processo ajax	

	    //fim processo ajax
	  }

	  //instanciar tabela dinamica de interessados caso os objetos existam na tela	
	  var tabelaInteressadosIndicados = document.getElementById('tbInteressadosIndicados');
	  var hdnTabelaInteressadosIndicados = document.getElementById('hdnListaInteressadosIndicados');	

      if( ( tabelaInteressadosIndicados != null && tabelaInteressadosIndicados != undefined) 
    	  &&
    	  ( hdnTabelaInteressadosIndicados != null && hdnTabelaInteressadosIndicados != undefined ) ){ 
	  	
	      objTabelaInteressado = new infraTabelaDinamica('tbInteressadosIndicados','hdnListaInteressadosIndicados',false,false);
	      objTabelaInteressado.gerarEfeitoTabela=true;

	      document.getElementById("txtCPF").addEventListener("keyup", function(event) {

		      event.preventDefault();

	         if (event.keyCode == 13) {
	    	   abrirCadastroInteressado();
	           //document.getElementById("id_of_button").click();
	         }
	         
	  	  });

	      document.getElementById("txtCNPJ").addEventListener("keyup", function(event) {

		      event.preventDefault();

	         if (event.keyCode == 13) {
	    	   abrirCadastroInteressado();
	           //document.getElementById("id_of_button").click();
	         }
	         
	  	  });

      }
      
}

function getStrNivelAcesso( nivel ){
	
	if( nivel == '0'){ return 'Público'; }
	else if( nivel == '1'){ return 'Restrito'; }
	else if( nivel == '' ) { return '-'; }
}

//campo de upload de documentos principais
function carregarCamposDocPrincipalUpload(){

	try {
	
	  objPrincipalUpload = new infraUpload('frmDocumentoPrincipal','<?=$strLinkUploadDocPrincipal?>', true);

	  objPrincipalUpload.finalizou = function(arr){

      var nomeUpload = arr['nome_upload'];
      var nome = arr['nome'];
      var dataHora = arr['data_hora'];
      var tamanho = arr['tamanho'];
      var dataHoraFormatada = '<?= time() ?>';
      var tamanhoFormatado = infraFormatarTamanhoBytes(arr['tamanho']);

      //Tamanho
      var tamanhoMb = tamanho/1024/1024; 
      var tamanhoPermitidoMb = document.getElementById('hdnTamArquivoPrincipal').value.toLowerCase().replace(' mb','');
      if(tamanhoMb>tamanhoPermitidoMb){
            alert('Arquivo com tamanho maior que o permitido.'); 
            return false;
      }
		
    //concatenacao de "Tipo" e "Complemento"
	  var cbTpoPrincipal = document.getElementById('tipoDocumentoPrincipal');
	  
	//abordagem anti-XSS client side	
	  var htmlComplemento = document.getElementById('complementoPrincipal').value;
	  var escaped = $("<pre>").text(htmlComplemento).html();
      var strComplemento = escaped;	
	  
      //var strComplemento = document.getElementById('complementoPrincipal').value;	
      var documento = getStrTipoDocumento( cbTpoPrincipal.value, 'Principal' ) + ' ' + strComplemento;

      var nivelAcesso = getStrNivelAcesso( document.getElementById('nivelAcesso1').value );

      //hipoteseLegal1
      var hipoteseLegal = '';
      var cbHipotese = document.getElementById('hipoteseLegal1');
      
      if( cbHipotese != null && cbHipotese != undefined ){
    	  hipoteseLegal = cbHipotese.value;
      }
      
      var formatoDocumento = $('input[name="formatoDocumentoPrincipal"]:checked').val();
      var formatoDocumentoLbl = 'Nato-digital';
      if(formatoDocumento != 'nato'){
    	  formatoDocumentoLbl = 'Digitalizado';
      }

      //TipoConferenciaPrincipal / TipoConferenciaEssencial
      var tipoConferencia = document.getElementById('TipoConferenciaPrincipal').value;

	  objTabelaDocPrincipal.adicionar([ nome , dataHora ,  tamanhoFormatado , documento , nivelAcesso , hipoteseLegal, formatoDocumento, tipoConferencia, nomeUpload, cbTpoPrincipal.value,strComplemento,formatoDocumentoLbl, '' ]);
	  
	  var strHashPrincipal = document.getElementById('hdnDocPrincipal').value;
	  var arrHashPrincipal = strHashPrincipal.split('±');

	  <? $linkBase = PaginaSEIExterna::getInstance()->formatarXHTML(SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_download&id_tipo_procedimento=' . $_GET['id_tipo_procedimento'] . '&id_orgao_acesso_externo=0')); ?>  
	  var urlBase = "<?= $linkBase ?>";
  		
	  document.getElementById('hdnNomeArquivoDownload').value = arrHashPrincipal[0];
	  document.getElementById('hdnNomeArquivoDownloadReal').value = arrHashPrincipal[1];
	  
	  objTabelaDocPrincipal.adicionarAcoes(
		arr['nome'], 
		"", 
		//"<a href='#' onclick=\"downloadArquivo( ' "+ urlBase +"')\"><img title='Baixar anexo' alt='Baixar arquivo' src='/infra_css/imagens/download.gif' class='infraImg' /></a>",
		false,
		true);

	  //limpar campo do upload
	  document.getElementById("fileArquivoPrincipal").value = '';

	  limparCampoUpload('1');

	  //aplicando valign='middle' nas colunas  da tabela 
	  //(necessário especificamente para alinhar coluna ações)
	  var table = document.getElementById("tbDocumentoPrincipal");

	  for (var i = 0, row; row = table.rows[i]; i++) {

		   for (var j = 0, col; col = row.cells[j]; j++) {
		    col.setAttribute("valign","middle");
		   }
		     
	  }

	}

	  objPrincipalUpload.validar = function(arr){

		  //INICIO VALIDACAO EXTENSOES
		  var arrExtensoesPermitidas = [<?=$strSelExtensoesPrin?>];
		  if ( $("#fileArquivoPrincipal").val().replace(/^.*\./, '')!='' && $.inArray( $("#fileArquivoPrincipal").val().replace(/^.*\./, '') , arrExtensoesPermitidas ) == -1 ) {
			  alert("O arquivo selecionado não é permitido.\nSomente são permitidos arquivos com as extensões:\n<?=preg_replace("%'%"," ",$strSelExtensoesPrin)?> .");
			  return false;
		  }
		  //FIM VALIDACAO EXTENSOES
		  	
		  var arquivoPrincipal = document.getElementById('fileArquivoPrincipal').value;
		  var ext = (arquivoPrincipal.substring(arquivoPrincipal.lastIndexOf(".")).toLowerCase()).split('.')[1];

		  var extPermitida = false;
		  var extensoes = $('#hdnArquivosPermitidos').val();
		  var obj = JSON.parse($('#hdnArquivosPermitidos').val());

		  for (var index in obj) {

				 if(obj[index] ==  ext){
				    extPermitida = true;
				 }
		  }

		//INICIO VALIDACAO EXTENSOES  
	    if(ext != undefined && ext != '' && !extPermitida){
	        document.getElementById('fileArquivoPrincipal').value = '';
			alert('A extensão do arquivo não é permitida.');
	    }
	    //FIM VALIDACAO EXTENSOES
	    	    
	 	return extPermitida;

	  }
	  
	  //Monta tabela de anexos
	  objTabelaDocPrincipal = new infraTabelaDinamica('tbDocumentoPrincipal','hdnDocPrincipal',false,false);
	  objTabelaDocPrincipal.gerarEfeitoTabela=true;
	  
  } catch(err){
      alert(' ERRO ' + err);
  }
}

//campo de upload de documentos essenciais
function carregarCamposDocEssencialUpload(){

	  objEssencialUpload = new infraUpload('frmDocumentosEssenciais','<?=$strLinkUploadDocEssencial?>', true);

	  objEssencialUpload.finalizou = function(arr){

	  var nomeUpload = arr['nome_upload'];
      var nome = arr['nome'];
	  var data = arr['data'];
	  var dataHora = arr['data_hora'];
      var tamanho = arr['tamanho'];
      var dataHoraFormatada = '<?= time() ?>';
      var tamanhoFormatado = infraFormatarTamanhoBytes(arr['tamanho']);

      //Tamanho
      var tamanhoMb = tamanho/1024/1024; 
      var tamanhoPermitidoMb = document.getElementById('hdnTamArquivoEssencial').value.toLowerCase().replace(' mb','');
      if(tamanhoMb>tamanhoPermitidoMb){
            alert('Arquivo com tamanho maior que o permitido.'); 
            return false;
      }

      //Nome
      var linhas = document.getElementById('tbDocumentoEssencial').rows;
      var tamanhoInserido = 0;
      var tamanhoVerificar = 0;

      for (var i = 1; i < linhas.length; i++) {
		//Nome igual
		if (nome.toLowerCase().trim()==linhas[i].cells[0].innerText.toLowerCase().trim()){
			alert('Não é permitido adicionar documento com o mesmo nome de arquivo.');
            return false;
		}	
      }
      
	  //concatenacao de "Tipo" e "Complemento"
	  var cbTpoEssencial = document.getElementById('tipoDocumentoEssencial');

	  //abordagem anti-XSS client side	
	  var htmlComplemento = document.getElementById('complementoEssencial').value;
	  var escaped = $("<pre>").text(htmlComplemento).html();
      var strComplemento = escaped;	
	  	
	  //var strComplemento = document.getElementById('complementoEssencial').value;	
      var documento = getStrTipoDocumento( cbTpoEssencial.value, 'Essencial' ) + ' ' + strComplemento;
      
      var nivelAcesso = getStrNivelAcesso( document.getElementById('nivelAcesso2').value );

      var hipoteseLegal = '';
      var cbHipotese = document.getElementById('hipoteseLegal2');
      
      if( cbHipotese != null && cbHipotese != undefined ){
    	  hipoteseLegal = cbHipotese.value;
      }
      
	  //var hipoteseLegal=  ' hip legal essencial';
      var formatoDocumento = $('input[name="formatoDocumentoEssencial"]:checked').val();
      var formatoDocumentoLbl = 'Nato-digital';
      if(formatoDocumento != 'nato'){
    	  formatoDocumentoLbl = 'Digitalizado';
      }

    //TipoConferenciaPrincipal / TipoConferenciaEssencial
      var tipoConferencia = document.getElementById('TipoConferenciaEssencial').value;

      //objTabelaDocPrincipal.adicionar([ nome , dataHora ,  tamanhoFormatado , documento , nivelAcesso , hipoteseLegal, formatoDocumento, tipoConferencia, nomeUpload, cbTpoPrincipal.value, '' ]);
      objTabelaDocEssencial.adicionar([ nome , dataHora , tamanhoFormatado , documento , nivelAcesso, hipoteseLegal, formatoDocumento, tipoConferencia, nomeUpload, cbTpoEssencial.value,strComplemento, formatoDocumentoLbl, '' ]);	
      //objTabelaDocEssencial.adicionar([ nomeUpload , nomeUpload, dataHora , '4', '5', '6', '7']);		
      //objTabelaDocEssencial.adicionar([ nomeUpload , dataHora ,  tamanhoFormatado , documento , nivelAcesso , '']);
      //objTabelaDocEssencial.adicionar([ '-' , nomeUpload ,  dataHora , dataHora , tamanhoFormatado, documento, 'nivel de acesso', 'acoes' ]);
	  //objTabelaDocEssencial.adicionar([arr['nome_upload'],arr['nome'],arr['data_hora'],arr['tamanho'],infraFormatarTamanhoBytes(arr['tamanho']),'<?= time() ?>']);
	  
	  var strHashEssencial = document.getElementById('hdnDocEssencial').value;
	  var arrHashEssencial = strHashEssencial.split('±');

	  <? $linkBase = PaginaSEIExterna::getInstance()->formatarXHTML(SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_download&id_tipo_procedimento=' . $_GET['id_tipo_procedimento'] . '&id_orgao_acesso_externo=0')); ?>  
	  var urlBase = "<?= $linkBase ?>";
  		
	  document.getElementById('hdnNomeArquivoDownload').value = arrHashEssencial[0];
	  document.getElementById('hdnNomeArquivoDownloadReal').value = arrHashEssencial[1];
	  
	  objTabelaDocEssencial.adicionarAcoes(
		arr['nome'], 
		"",
		//"<a href='#' onclick=\"downloadArquivo( ' "+ urlBase +"')\"><img title='Baixar anexo' alt='Baixar arquivo' src='/infra_css/imagens/download.gif' class='infraImg' /></a>",
		false,
		true);
		  
	  document.getElementById("fileArquivoEssencial").value = '';
	  //document.getElementById('divArquivo').style.display = 'none';

	  limparCampoUpload('2');

	  var table = document.getElementById("tbDocumentoEssencial");

	  for (var i = 0, row; row = table.rows[i]; i++) {

		   for (var j = 0, col; col = row.cells[j]; j++) {
		    col.setAttribute("valign","middle");
		   }
		     
	  }
	
	  
	}

	  objEssencialUpload.validar = function(arr){

		  //INICIO VALIDACAO EXTENSOES
		  var arrExtensoesPermitidas = [<?=$strSelExtensoesComp?>];
		  if ( $("#fileArquivoEssencial").val().replace(/^.*\./, '')!='' && $.inArray( $("#fileArquivoEssencial").val().replace(/^.*\./, '') , arrExtensoesPermitidas ) == -1 ) {
			  alert("O arquivo selecionado não é permitido.\nSomente são permitidos arquivos com as extensões:\n<?=preg_replace("%'%"," ",$strSelExtensoesComp)?> .");
			  return false;
		  }
		  //FIM VALIDACAO EXTENSOES

		  var arquivoEssencial = document.getElementById('fileArquivoEssencial').value;
		  var ext = (arquivoEssencial.substring(arquivoEssencial.lastIndexOf(".")).toLowerCase()).split('.')[1];

		  var extPermitida = false;
		  
		  var obj = JSON.parse($('#hdnArquivosPermitidosEssencialComplementar').val());

		  for (var index in obj) {

				 if(obj[index] ==  ext){
				    extPermitida = true;
				 }
		  }
		  
	    if(ext != undefined && ext != '' && !extPermitida){
	        document.getElementById('fileArquivoEssencial').value = '';
			alert('A extensão do arquivo não é permitida.');
	    }
	    
	 	return extPermitida;

	  }
	  
	  //Monta tabela de anexos
	  objTabelaDocEssencial = new infraTabelaDinamica('tbDocumentoEssencial','hdnDocEssencial',false,false);
	  objTabelaDocEssencial.gerarEfeitoTabela=true;
	
}

//campo de upload de documentos essenciais
function carregarCamposDocComplementarUpload(){

	  objComplementarUpload = new infraUpload('frmDocumentosComplementares','<?=$strLinkUploadDocComplementar?>', true);

	  objComplementarUpload.finalizou = function(arr){

	  var nomeUpload = arr['nome_upload'];
      var nome = arr['nome'];
	  var data = arr['data'];
	  var dataHora = arr['data_hora'];
      var tamanho = arr['tamanho'];
      var dataHoraFormatada = '<?= time() ?>';
      var tamanhoFormatado = infraFormatarTamanhoBytes(arr['tamanho']);

      //Tamanho
      var tamanhoMb = tamanho/1024/1024; 
      var tamanhoPermitidoMb = document.getElementById('hdnTamArquivoComplementar').value.toLowerCase().replace(' mb','');
      if(tamanhoMb>tamanhoPermitidoMb){
            alert('Arquivo com tamanho maior que o permitido.'); 
            return false;
      }

      //Nome
      var linhas = document.getElementById('tbDocumentoComplementar').rows;
      var tamanhoInserido = 0;
      var tamanhoVerificar = 0;

      for (var i = 1; i < linhas.length; i++) {
		//Nome igual
		if (nome.toLowerCase().trim()==linhas[i].cells[0].innerText.toLowerCase().trim()){
			alert('Não é permitido adicionar documento com o mesmo nome de arquivo.');
            return false;
		}	
      }
      
      //concatenacao de "Tipo" e "Complemento"
	  var cbTpoComplementar = document.getElementById('tipoDocumentoComplementar');

	  //abordagem anti-XSS client side	
	  var htmlComplemento = document.getElementById('complementoComplementar').value;
	  var escaped = $("<pre>").text(htmlComplemento).html();
      var strComplemento = escaped;	
      
      var documento = getStrTipoDocumento( cbTpoComplementar.value, 'Complementar' ) + ' ' + strComplemento;

      var nivelAcesso = getStrNivelAcesso( document.getElementById('nivelAcesso3').value );

      var hipoteseLegal = '';
      var cbHipotese = document.getElementById('hipoteseLegal3');
      
      if( cbHipotese != null && cbHipotese != undefined ){
    	  hipoteseLegal = cbHipotese.value;
      }

	  var formatoDocumento = $('input[name="formatoDocumentoComplementar"]:checked').val();
	  var formatoDocumentoLbl = 'Nato-digital';
      if(formatoDocumento != 'nato'){
    	  formatoDocumentoLbl = 'Digitalizado';
      }
	  
	  var tipoConferencia = document.getElementById('TipoConferenciaComplementar').value;

      objTabelaDocComplementar.adicionar([ nome , dataHora , tamanhoFormatado , documento , nivelAcesso, hipoteseLegal, formatoDocumento, tipoConferencia, nomeUpload, cbTpoComplementar.value, strComplemento,formatoDocumentoLbl, '' ]);	
      //objTabelaDocComplementar.adicionar([ '-' , nomeUpload ,  dataHora , dataHora , tamanhoFormatado, documento, 'nivel de acesso', 'acoes' ]);
	  //objTabelaDocComplementar.adicionar([arr['nome_upload'],arr['nome'],arr['data_hora'],arr['tamanho'],infraFormatarTamanhoBytes(arr['tamanho']),'<?= time() ?>']);
	  
	  var strHashComplementar = document.getElementById('hdnDocComplementar').value;
	  var arrHashComplementar = strHashComplementar.split('±');

	  <? $linkBase = PaginaSEIExterna::getInstance()->formatarXHTML(SessaoSEIExterna::getInstance()->assinarLink('controlador_externo.php?acao=peticionamento_usuario_externo_download&id_tipo_procedimento=' . $_GET['id_tipo_procedimento'] . '&id_orgao_acesso_externo=0')); ?>  
	  var urlBase = "<?= $linkBase ?>";
  		
	  document.getElementById('hdnNomeArquivoDownload').value = arrHashComplementar[0];
	  document.getElementById('hdnNomeArquivoDownloadReal').value = arrHashComplementar[1];
	  
	  objTabelaDocComplementar.adicionarAcoes(
		arr['nome'], 
		"",
		//"<a href='#' onclick=\"downloadArquivo( ' "+ urlBase +"')\"><img title='Baixar anexo' alt='Baixar arquivo' src='/infra_css/imagens/download.gif' class='infraImg' /></a>",
		false,
		true);
		  
	  document.getElementById("fileArquivoComplementar").value = '';

	  limparCampoUpload('3');

	  var table = document.getElementById("tbDocumentoComplementar");

	  for (var i = 0, row; row = table.rows[i]; i++) {

		   for (var j = 0, col; col = row.cells[j]; j++) {
		    col.setAttribute("valign","middle");
		   }
		     
	  }
	}

	  objComplementarUpload.validar = function(arr){

		  //INICIO VALIDACAO EXTENSOES
		  var arrExtensoesPermitidas = [<?=$strSelExtensoesComp?>];
		  if ( $("#fileArquivoComplementar").val().replace(/^.*\./, '')!='' && $.inArray( $("#fileArquivoComplementar").val().replace(/^.*\./, '') , arrExtensoesPermitidas ) == -1 ) {
			  alert("O arquivo selecionado não é permitido.\nSomente são permitidos arquivos com as extensões:\n<?=preg_replace("%'%"," ",$strSelExtensoesComp)?> .");
			  return false;
		  }
		  //FIM VALIDACAO EXTENSOES

		  var arquivoComplementar = document.getElementById('fileArquivoComplementar').value;
		  var ext = (arquivoComplementar.substring(arquivoComplementar.lastIndexOf(".")).toLowerCase()).split('.')[1];

		  var extPermitida = false;
		  var listaExtensoes = $('#hdnArquivosPermitidosEssencialComplementar').val();
		  var obj = JSON.parse( listaExtensoes );

		  for (var index in obj) {

				 if(obj[index] ==  ext){
				    extPermitida = true;
				 }
		  }
		  
	    if(ext != undefined && ext != '' && !extPermitida){
	        document.getElementById('fileArquivoComplementar').value = '';
			alert('A extensão do arquivo não é permitida.');
	    }
	    
	 	return extPermitida;

	  }
	  
	  //Monta tabela de anexos
	  objTabelaDocComplementar = new infraTabelaDinamica('tbDocumentoComplementar','hdnDocComplementar',false,false);
	  objTabelaDocComplementar.gerarEfeitoTabela=true;
	
}

function carregarComponenteLupaInteressados( tipoAcao ){

   if( tipoAcao == 'S'){
	 objLupaInteressados.selecionar(900,900);
  } else if( tipoAcao == 'R'){
	 objLupaInteressados.remover();
  }
	
}

function mascaraTexto( elem, evento ){

	var formPeticionamento = document.getElementById('frmPeticionamentoCadastro');
	
	if(formPeticionamento.tipoPessoa.value == 'pf'){
		return infraMascaraCpf(elem, evento);
	} 
	else if(formPeticionamento.tipoPessoa.value == 'pj'){
		return infraMascaraCnpj(elem, evento);
	} 
	else {
      return false;
	}

}

function selecionarPF(){
	
  document.getElementById('descTipoPessoa').innerHTML = 'CPF:';
  document.getElementById('descNomePessoa').innerHTML = 'Nome:';	
  //document.getElementById('tdDescTipoPessoa').innerHTML = 'CPF';
  //document.getElementById('tdDescNomePessoa').innerHTML = 'Nome';

  document.getElementById('divSel1').style.display = 'inline';
  document.getElementById('divSel2').style.display = 'inline';

  document.getElementById('txtNomeRazaoSocial').value = '';
  document.getElementById('txtNomeRazaoSocial').style.display = 'inline';
  document.getElementById('btAdicionarInteressado').style.display = 'inline';
  
  document.getElementById('txtCPF').style.display = 'inline';
  //document.getElementById('txtCPF').style.width='80%';
  document.getElementById('txtCNPJ').value = '';
  document.getElementById('txtCNPJ').style.display = 'none';
  document.getElementById('btValidarCPFCNPJ').style.visibility = 'visible';

}

function selecionarPJ(){
	
  document.getElementById('descTipoPessoa').innerHTML = 'CNPJ:';
  document.getElementById('descNomePessoa').innerHTML = 'Razão Social:';
  //document.getElementById('tdDescTipoPessoa').innerHTML = 'CNPJ';
  //document.getElementById('tdDescNomePessoa').innerHTML = 'Razão Social';

  document.getElementById('divSel1').style.display = 'inline';
  document.getElementById('divSel2').style.display = 'inline';

  document.getElementById('txtNomeRazaoSocial').value = '';
  document.getElementById('txtNomeRazaoSocial').style.display = 'inline';
  document.getElementById('btAdicionarInteressado').style.display = 'inline';
  
  document.getElementById('txtCPF').style.display = 'none';
  document.getElementById('txtCPF').value = '';
  
  document.getElementById('txtCNPJ').style.display = 'inline';
  //document.getElementById('txtCNPJ').style.width='80%';
  document.getElementById('btValidarCPFCNPJ').style.visibility = 'visible';
  
}

function selecionarFormatoDigitalizadoEssencial(){
	document.getElementById("camposDigitalizadoEssencial").style.display='block';
	document.getElementById("camposDigitalizadoEssencialBotao").style.display='none';
}

function selecionarFormatoNatoDigitalEssencial(){
	document.getElementById("camposDigitalizadoEssencial").style.display='none';
	document.getElementById("camposDigitalizadoEssencialBotao").style.display='block';
	//retornando a combo para seu valor inicial
	document.getElementById("TipoConferenciaEssencial").selectedIndex=0;
}

function selecionarFormatoDigitalizadoComplementar(){
	document.getElementById("camposDigitalizadoComplementarBotao").style.display='none';
	document.getElementById("camposDigitalizadoComplementar").style.display='block';
	//retornando a combo para seu valor inicial
	document.getElementById("TipoConferenciaComplementar").selectedIndex=0;
}

function selecionarFormatoNatoDigitalComplementar(){
	document.getElementById("camposDigitalizadoComplementar").style.display='none';
	document.getElementById("camposDigitalizadoComplementarBotao").style.display='block';
}

function selecionarFormatoDigitalizadoPrincipal(){
	document.getElementById("camposDigitalizadoPrincipalBotao").style.display='none';
	document.getElementById("camposDigitalizadoPrincipal").style.display='block';
	//retornando a combo para seu valor inicial
	document.getElementById("TipoConferenciaPrincipal").selectedIndex=0;
}

function selecionarFormatoNatoDigitalPrincipal(){
	document.getElementById("camposDigitalizadoPrincipalBotao").style.display='block';
	document.getElementById("camposDigitalizadoPrincipal").style.display='none';
}

function returnDateTime(valor){

	valorArray = valor != '' ? valor.split(" ") : '';

	if(Array.isArray(valorArray)){
	  var data = valorArray[0]
	  data = data.split('/');
	  var mes = parseInt(data[1]) - 1; 
      var horas = valorArray[1].split(':');

      var segundos = typeof horas[2] != 'undefined' ?  horas[2] : 00;
	  var dataCompleta = new Date(data[2], mes  ,data[0], horas[0] , horas[1] , segundos);
	  return dataCompleta;
	}

	return false;
}

function OnSubmitForm() {
		
	return true;
}

function exibirAjudaCaso1(){
	alert('Para o Tipo de Processo escolhido o Interessado do processo a ser aberto somente pode ser o próprio Usuário Externo logado no sistema.'); 
}

function exibirAjudaCaso2(){
	alert('Para o Tipo de Processo escolhido é possível adicionar os Interessados do processo a ser aberto por meio da indicação de CPF ou CNPJ válidos, devendo complementar seus cadastros caso necessário.');
}

function exibirAjudaCaso3(){
	alert('Para o Tipo de Processo escolhido é possível adicionar os Interessados do processo a ser aberto a partir da base de Interessados já existente do órgão. Caso necessário, clique na Lupa "Localizar Interessados" para uma pesquisa mais detalhada ou, na janela aberta, acessar o botão "Cadastrar Novo Interessado" e em seguida selecionar o Interessado cadastrado.');
}

function exibirAjudaFormatoDocumento(){
	alert('Selecione a opção “Nato-digital” se o arquivo a ser carregado foi criado originalmente em meio eletrônico.\n\n' + 
		  'Selecione a opção “Digitalizado” somente se o arquivo a ser carregado foi produzido da digitalização de um documento em papel.');
}

function exibirAjudaComplementoTipo(){
	alert('O Complemento do Tipo de Documento é o texto que completa a identificação do documento a ser carregado, adicionando ao nome do Tipo o texto que for digitado no referido campo (Tipo "Recurso" e Complemento "de 1ª Instância" identificará o documento como "Recurso de 1ª Instância").\n\n' + 
		  'Exemplos: O Complemento do Tipo "Nota" pode ser "Fiscal Eletrônica" ou "Fiscal nº 75/2016". O Complemento do Tipo "Comprovante" pode ser "de Pagamento" ou "de Endereço".');
}

function exibirAjudaTipoDocumentoPrincipal(){
	alert('Como somente pode ter um Documento Principal, o Tipo de Documento correspondente já é previamente definido. Deve, ainda, ser complementado no campo ao lado.');
}

function exibirAjudaTipoDocumentoEssenciaisComplementares(){
	alert('Selecione o Tipo de Documento que melhor identifique o documento a ser carregado e complemente o Tipo no campo ao lado.');
}

function downloadArquivo( urlBaseDownload ){

    var actionAnterior = document.getElementById("frmPeticionamentoCadastro").action;
    var targetAnterior = document.getElementById("frmPeticionamentoCadastro").target;
    
	document.getElementById("frmPeticionamentoCadastro").action = urlBaseDownload;
	document.getElementById("frmPeticionamentoCadastro").target="_blank";
	document.getElementById("frmPeticionamentoCadastro").submit();

	document.getElementById("frmPeticionamentoCadastro").action = actionAnterior;
	document.getElementById("frmPeticionamentoCadastro").target=targetAnterior;
		
}

function concluirAssinarPeticionamento(){

	var formCadastro = document.getElementById('frmPeticionamentoCadastro');
	formCadastro.target = "concluirPeticionamento";
	formCadastro.submit();
}

window.CallParent = function() {
    concluirAssinarPeticionamento();
}

function selectNivelAcesso( idNivelAcesso, idHipoteseLegal ){

      var valorSelectNivelAcesso = document.getElementById(idNivelAcesso).value;
      
      if( valorSelectNivelAcesso == '1' ){
			//mostrar combo do nivel de acesso
    	   document.getElementById(idHipoteseLegal).selectedIndex=0;
    	   document.getElementById('div'+idHipoteseLegal).style.display='block';      
      }
      else{
           //ocultar combo do nivel de acesso e limpar a seleção da combo
    	  document.getElementById(idHipoteseLegal).selectedIndex=0;
    	  document.getElementById('div'+idHipoteseLegal).style.display='none';
    	  
      }
	
}

function adicionarInteressadoValido(){

	var txtCPF = document.getElementById("txtCPF").value;
	var txtCNPJ = document.getElementById("txtCNPJ").value;
    var txtCPFCNPJ = '';

	if( txtCPF != ""){
		txtCPFCNPJ = txtCPF;
	}

	else if( txtCNPJ != ""){
		txtCPFCNPJ = txtCNPJ;
	}
	
	var hdnCustomizado = document.getElementById("hdnCustomizado").value;
	var txtNomeRazaoSocial = document.getElementById("txtNomeRazaoSocial").value;
	var hdnIdInteressadoCadastrado = document.getElementById('hdnIdInteressadoCadastrado').value;
	var chkTipoPessoaFisica = document.getElementById("optTipoPessoaFisica").checked;
	var chkTipoPessoaJuridica = document.getElementById("optTipoPessoaJuridica").checked;
	
	//checar se o Nome / Razao Social foi preenchido
	if( txtNomeRazaoSocial == ''){

		if( chkTipoPessoaFisica ){
			alert('Antes é necessário validar o CPF.');
			return;
		}

		else if( chkTipoPessoaJuridica ){
			alert('Antes é necessário validar o CNPJ.');
			return;
		}
		
	}

	//adicionar o interessado na grid
	var arrDadosInteressadoValido = [];	
	
	if( txtCPF != ""){
		arrDadosInteressadoValido[1] = "Pessoa Física";
	}

	else if( txtCNPJ != ""){
		arrDadosInteressadoValido[1] = "Pessoa Jurídica";
	}
	
	arrDadosInteressadoValido[2] = txtCPFCNPJ;
	arrDadosInteressadoValido[3] = txtNomeRazaoSocial;
	arrDadosInteressadoValido[0] = hdnIdInteressadoCadastrado;

	var bolInteressadoCustomizado = hdnCustomizado;

	//checar se o cpf ou cnpj informado já existe na grid
	var hdnListaInteressadosIndicados = document.getElementById('hdnListaInteressadosIndicados').value;
	
	if( hdnListaInteressadosIndicados != "") {
	
		//caractere de quebra de linha
		var arrHash = hdnListaInteressadosIndicados.split('¥');
	    var quantidadeRegistro = arrHash.length;
	
		if( quantidadeRegistro == 0){

			var cpfInserido = arrDadosInteressadoValido[2];
			
			//caractere de quebra de coluna
			var arrLocal = hdnListaInteressadosIndicados.split('±');
			var cpfLocal = arrLocal[2];
			
			if( cpfInserido == cpfLocal){
			   alert('Não é permitido adicionar interessado com CPF ou CNPJ já adicionado.');
			   return;
			}
			
		} else if( quantidadeRegistro > 0 ){

			var cpfInserido = arrDadosInteressadoValido[1];
			
			for(var i = 0; i < quantidadeRegistro ; i++ ){
	
				var arrLocal = arrHash[i].split('±');
				var cpfLocal = arrLocal[2];

				if( cpfInserido == cpfLocal){
				   alert('Não é permitido adicionar interessado com CPF ou CNPJ já adicionado.');
				   return;
				}
				
			}
			
		}
	
	}
	
	receberInteressado( arrDadosInteressadoValido , bolInteressadoCustomizado );
	
}

function atualizarNomeRazaoSocial( cpfEditado , nomeEditado ){

	var table = document.getElementById("tbInteressadosIndicados");
	var linhas = table.rows;

	for ( var i = 0; row = table.rows[i]; i++ ) {

		 row = table.rows[i];

		 if( i > 0){
			  	
		   cpflinha = row.cells[2].innerHTML;
		   nomeRazaoSocialLinha = row.cells[3].innerHTML;

		   cpfEditado = '<div>' + cpfEditado + '</div>';

		   if( cpflinha == cpfEditado){
			   row.cells[3].innerHTML = '<div>' + nomeEditado + '</div>';
		   }
		   
		 }
	     
	  }	
	
}

function alterandoCPF(objeto, evt){
	document.getElementById('txtNomeRazaoSocial').value = '';
	document.getElementById('hdnIdInteressadoCadastrado').value = '';		
	return infraMascaraCpf(objeto, evt);
	
}

function alterandoCNPJ(objeto, evt){
	document.getElementById('txtNomeRazaoSocial').value = '';
	document.getElementById('hdnIdInteressadoCadastrado').value = '';		
	return infraMascaraCnpj(objeto, evt);
	
}
</script>