<%
	/**** Pagina de login do site ****/
	Local cLCodLogin  := ""
	if type ("cCodLogin") <> "U"
		cLCodLogin := cCodLogin
	Endif
%>
<!DOCTYPE html>
<html class="fixed sidebar-left-collapsed">
	<head>
		<!-- Basic -->
		<meta charset="iso-8859-1">
		<link rel="shortcut icon" href="images/favicon.png" type="image/x-icon" />
	
		<title><%=cTitle%></title>
	
		<meta name="keywords" content="<%=cTitle%>" />
		<meta name="description" content="<%=cTitle%>">
		<meta name="author" content="SMSTI">
		<meta http-equiv="Chache-Control" content="no-cache" />
		<meta http-equiv="Expires" content="0" />
		<meta http-equiv="Pragma" content="no-cache" />
	
		<!-- Mobile Metas -->
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
	
		<!-- Web Fonts  -->
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800|Shadows+Into+Light" rel="stylesheet" type="text/css">
	
		<!-- Vendor CSS -->
		<link rel="stylesheet" href="assets/vendor/bootstrap/css/bootstrap.css" />
		<link rel="stylesheet" href="assets/vendor/font-awesome/css/font-awesome.css" />
		<link rel="stylesheet" href="assets/vendor/magnific-popup/magnific-popup.css" />
		<link rel="stylesheet" href="assets/vendor/bootstrap-datepicker/css/bootstrap-datepicker3.css" />
		<link rel="stylesheet" href="assets/vendor/bootstrap-select/css/bootstrap-select.min.css" />
	    <style> 
	    	body .btn { 
	    		white-space: nowrap !important;
	    		display: inline;
	    		overflow-y: hidden;
	    	}
	    	
		</style>
		<!-- Specific Page Vendor CSS -->
		<link rel="stylesheet" href="assets/vendor/select2/css/select2.css" />
		<link rel="stylesheet" href="assets/vendor/select2-bootstrap-theme/select2-bootstrap.min.css" />
		<link rel="stylesheet" href="assets/vendor/jquery-datatables-bs3/assets/css/datatables.css" />
		<link rel="stylesheet" href="assets/vendor/bootstrap-fileupload/bootstrap-fileupload.min.css" />
		<link rel="stylesheet" href="assets/vendor/pnotify/pnotify.custom.css" />
	
		<!-- Theme CSS -->
		<link rel="stylesheet" href="assets/stylesheets/theme.css" />
	
		<!-- Skin CSS -->
		<link rel="stylesheet" href="assets/stylesheets/skins/default.css" />
	
		<!-- Theme Custom CSS -->
		<link rel="stylesheet" href="assets/stylesheets/theme-custom.css">
	
		<!-- Head Libs -->
		<script src="assets/vendor/modernizr/modernizr.js"></script>
	    <script src="assets/vendor/style-switcher/style.switcher.localstorage.js"></script>
	
		<style>
			.flexContainer {
				display: flex;
			}
 
			.smsediticon {
				flex: 1;
			}
 
			.btedit {  /* margem e largura da imagem */
				margin-left: -45px;
				width: 47px;
			}
		</style>
	</head>
	<body>
		<section class="body">
		
			<!-- start: header -->
			<header class="header">
				<%=cHeader%>
			</header>
			<!-- end: header -->
		    
			<div class="inner-wrapper">
				<!-- start: sidebar -->
				<aside id="sidebar-left" class="sidebar-left">
				
				    <div class="sidebar-header">
				        <div class="sidebar-title">
				            Menu
				        </div>
				        <div class="sidebar-toggle hidden-xs" data-toggle-class="sidebar-left-collapsed" data-target="html" data-fire-event="sidebar-left-toggle">
				            <i class="fa fa-bars" aria-label="Toggle sidebar"></i>
				        </div>
				    </div>
						
				    <div class="nano">
				        <div class="nano-content">
				            <nav id="menu" class="nav-main" role="navigation">
				            
				                <ul class="nav nav-main">
				                    <%=cMenus%>
				                </ul>
				            </nav>
				        </div>
						
				        <script>
				            // Maintain Scroll Position
				            if (typeof localStorage !== 'undefined') {
				                if (localStorage.getItem('sidebar-left-position') !== null) {
				                    var initialPosition = localStorage.getItem('sidebar-left-position'),
				                        sidebarLeft = document.querySelector('#sidebar-left .nano-content');
				                    
				                    sidebarLeft.scrollTop = initialPosition;
				                }
				            }
				        </script>
					</div>
						
				</aside>
				<!-- end: sidebar -->
		
				<section role="main" class="content-body">
					<header class="page-header">
						<h2><%=cPagina%></h2>
					
						<div class="right-wrapper pull-right">
						</div>
					</header>
		
					<!-- start: page -->
					<section class="panel">
					<!-- <header class="panel-heading">
					</header> -->
					<div class="panel-body">
						<div class="row">
							<div class="col-lg-12">
								<section class="panel form-wizard" id="w9">
									<form action = "" method="post" class="form-horizontal" id="formOrc">
										<div class="tabs">
											<ul class="nav nav-tabs nav-justify">
												<li class="active">
													<a href="#orc-informar" data-toggle="tab" class="text-center">Or�amento</a>
												</li>
												<!--
												<li class="">
													<a href="#orc-anexos" data-toggle="tab" class="text-center">Anexos</a>
												</li>
												-->
											</ul>
													
											<div class="tab-content">
												<div id="orc-informar" class="tab-pane active">
													<!--
													<%=cVendedor%> 
													-->
													

													<!-- linha 0: dados do Or�amento -->
													<%=cFilOrc%>
													<%=cCodOrc%>

													<div class="mb-md hidden-lg hidden-xl"></div>
													<div class="mb-md hidden-lg hidden-xl"></div>

													<!-- linha 1: dados da empresa -->
													<div class="row form-group">
														<div class="col-lg-6">
															<label class="control-label">Cliente</label>
															<%=cCliente%>
														</div>

														
														<div class="col-lg-5">
															<label class="control-label">Oportunidade</label>
															<%=cOport%>
														</div>

														<div class="col-lg-1">
															<label class="control-label">Revis�o</label>
															<%=cRevOpt%>
														</div>
													
													</div>
		
																										
													<!-- linha 3: input  -->
													<div class="row form-group">	              
													 	<div class="col-lg-3">
															<label class="control-label">Tipo de Cliente</label>
															<%=cTpCliente%>
														</div>

														<div class="col-lg-2">
															<label class="control-label">Grupo de Tributa��o</label>
															<%=cGrpTrib%>
														</div>

														<div class="col-lg-5" style="display:none;">
															<label class="control-label">Tabela de Pre�o</label>
															<%=cTabela%>
														</div>

														<div class="col-lg-4">
															<label class="control-label">Contato</label>
															<%=cContato%>
														</div>

														<div class="col-lg-1">
															<label class="control-label">DDD</label>
															<%=cContDDD%>
														</div>

														<div class="col-lg-2">
															<label class="control-label">Telefone</label>
															<%=cContTel%>
														</div>
													</div>
													
													<!-- linha 4 input -->
													<div class="row form-group"> 
														<div class="col-lg-6">
															<label class="control-label">Cliente de Entrega</label>
															<%=cCliEntr%>
														</div>
														<div class="col-lg-6">
															<label class="control-label">Local de Entrega</label>
															<%=cLocalEnt%>
														</div>
													</div>

													<!-- linha 5 input -->
													<div class="row form-group"> 
													
														<div class="col-lg-6">
															<label class="control-label">Obra</label>
															<%=cObra%>
														</div>
													    
														<div class="col-lg-3">
															<label class="control-label">Status da Obra</label>	              
															<%=cStatusObra%>
														</div>

														<div class="col-lg-3">
															<label class="control-label">Previs�o de Fechamento</label>	              
															<%=cPrevFecha%>
														</div>
													</div>

													<!-- linha 6 input -->
													<div class="row form-group"> 
														<div class="col-lg-3">
															<label class="control-label">Condi��o de Pagamento</label>
															<%=cCondPag%>
														</div>
														<div class="col-lg-6">
															<label class="control-label">Intermediador</label>	    
															<%=cIntermed%>
														</div>
														<div class="col-lg-2">
															<label class="control-label">Retorno</label>	              
															<%=cRetorno%>
														</div>
													</div>
													
													<!-- linha 7 input -->
													<div class="row form-group"> 
														<div class="col-lg-2">
															<label class="control-label">Estudo Luminot�cnico</label>	              
															<%=cEstudo%>
														</div>

														<div class="col-lg-2">
															<label class="control-label">Num. Estudo</label>	              
															<%=cNumEst%>
														</div>

														<div class="col-lg-3">
															<label class="control-label">Segmento</label>	              
															<%=cSegmento%>
														</div>
														<div class="col-lg-2">
															<label class="control-label">Prospec��o</label>	              
															<%=cProsp%>
														</div>
														<div class="col-lg-3">
															<label class="control-label">Prospectado Por</label>	              
															<%=cProspPor%>
														</div>
													</div>
	

													<!-- linha 8: input  -->
													<div class="row form-group">

														<div class="col-lg-4">
															<label class="control-label">Regional</label>	              
															<%=cRegional%>
														</div>
														<div class="col-lg-4">
															<label class="control-label">Vendedor 2</label>	              
															<%=cVend2%>
														</div>
														<div class="col-lg-4">
															<label class="control-label">Vendedor 3</label>	              
															<%=cVend3%>
														</div>
													</div>

													<!-- linha 9: input  -->
													<div class="row form-group">
														<div class="col-lg-4">
															<label class="control-label">Vendedor 4</label>	              
															<%=cVend4%>
														</div>
														<div class="col-lg-4">
															<label class="control-label">Especificado por</label>	              
															<%=cEspecif%>
														</div>
														<div class="col-lg-4">
															<label class="control-label">Negociadora</label>	              
															<%=cNegociad%>
														</div>
													</div>

													<!-- linha 10: input  -->
													<div class="row form-group">
														<div class="col-lg-2">
															<label class="control-label">Validade</label>
															<%=cValidade%>
														</div>
														<div class="col-lg-2">
															<label class="control-label">Prazo de Embarque</label>
															<%=cPrazoEmb%>
														</div>
													 	<div class="col-lg-2">
															<label class="control-label">Tipo de Frete</label>
															<%=cTpFrete%>
														</div>
   
   														<div class="col-lg-2">
															<label class="control-label">% Frete</label>
															<%=cPFrete%>
														</div>
													 	<div class="col-lg-2"> 
															<label class="control-label">Valor do Frete</label>
															<%=cValFre%>
														</div>	
														<div class="col-lg-2">
															<label class="control-label">% RT</label>
															<%=cComRT%>
														</div>											
														<!--		
														<div class="col-lg-4">
															<label class="control-label">Transportadora</label>
															<%=cTransp%>
														</div>
														-->
													</div>
													
													
																									
													<!-- linha 11 input -->
													<div class="row form-group"> 
													
														<div class="col-md-5">
															<label class="control-label" for="textareaDefault">Observa��o Comercial</label>
															<textarea class="form-control" rows="3" data-plugin-maxlength="" maxlength="240" id="CJ_OBS" name="CJ_OBS" <%=Iif(!lEdit,'disabled','')%>><%=cObsCom%></textarea>
														</div>
														
														<%=cMargemCont%>
													</div>
													
													<!-- linha 12 input -->
													<div class="row form-group">
														
														
													</div>
													
													
																
													<br>		
													<br>		
		
													<!-- tabela com os produtos do or�amento -->
													<div class="table-responsive" id="ItensOrc" style="overflow-x:visible">
														<section class="panel">
															<header class="panel-heading">
																<h2 class="panel-title">Itens do Or�amento</h2>
															</header>
															<table class="table table-bordered table-striped mb-none table-hover table-condensed" id="datatable-editable" aria-describedby="datatable-details_info">
																<thead>
																	<tr>
																		<%=cOrcCabec%>
																	</tr>
																</thead>
																<tbody> 
																	<%=cOrcItens%>									
																</tbody>
															</table>
														</section>	
													</div>	
													<br>
                                                     
             										<!-- bot�es com a��es na tabela dos itens -->
													<%=cBtnItens%>

                                                    <br>
                                                    <br>
																											
													<!-- Totais -->
													<div class="col-lg-13">
														<section class="panel">
															<header class="panel-heading">
																<h2 class="panel-title">Totais do Or�amento</h2>
															</header>
															<div class="panel-body">
															
																<div class="form-inline" align="center">
																	<div class="row">
																		<div class="col-sm-12">	      
																			<label class="">Itens&nbsp;</label>               
																			<input class="form-control text-right" id="TOTAL_ITENS" name="TOTAL_ITENS"  placeholder="0,00" disabled="" type="text" value=<%=Transform(nTVlrUnit,"@E 999,999,999,999.99")%>></input>
																			
																			&nbsp;&nbsp;&nbsp;&nbsp;
																			<label class="">Impostos&nbsp;</label>
																			<input class="form-control text-right" id="TOTAL_IMP" name="TOTAL_IMP"  placeholder="0,00" disabled="" type="text" value=<%=Transform(nTImpostos,"@E 999,999,999,999.99")%>></input>
																			 
																			
																			&nbsp;&nbsp;&nbsp;&nbsp;
																			<label class="">Frete&nbsp;</label>
																			<input class="form-control text-right" id="TOTAL_FRETE" name="TOTAL_FRETE"  placeholder="0,00" disabled="" type="text" value=<%=Transform(nTFrete,"@E 999,999,999,999.99")%>></input>
																			
																			
																			&nbsp;&nbsp;&nbsp;&nbsp;
																			<label class="text-weight-extrabold">Total&nbsp;</label>
																			<input class="form-control text-right text-weight-bold" id="TOTAL_ORC" name="TOTAL_ORC" placeholder="0,00" disabled="" type="text" value=<%=Transform(nTTotal,"@E 999,999,999,999.99")%>></input>
																		</div> 
																	</div>
																	<br>
																		<!-- 
																	<div class="row">
																		<div class="col-sm-12">	      
																			<label class="">Desconto&nbsp;</label>
																			<input class="form-control text-right" id="TOTAL_ACRESC" name="TOTAL_ACRESC" placeholder="0,00" disabled="" type="text" value=<%=Transform(nTAcresc,"@E 999,999,999,999.99")%>></input>
																		 
																			<label class="">Total&nbsp;</label>
																			<input class="form-control text-right" id="TOTAL_ORC" name="TOTAL_ORC" placeholder="0,00" disabled="" type="text" value=<%=Transform(nTTotal,"@E 999,999,999,999.99")%>></input>
																		</div> 
																	</div>

																		
																	<div class="row">
																		<div class="col-sm-12">	      
																			<label class="">Comiss�o Prevista&nbsp;</label>               
																			<input class="form-control text-right" id="TOTAL_COM" name="TOTAL_COM"  placeholder="0,00" disabled="" type="text" value=<%=Transform(nTComiss,"@E 999,999,999,999.99")%>></input>
																		</div> 
																	</div>
																		-->	    
																</div>
															</div>
														</section>
													</div>
			          								
			          								<br>
			                                        <br>
													
													<div class="row form-group" align="center">
														<%=cBotoes%>
													</div>
												</div>													
												
												<!-- aba de anexos
									 			<div id="orc-anexos" class="tab-pane">
									 		   		<div class="form-group">
														<label class="col-md-3 control-label">Anexar: </label>
														<div class="col-md-9">
															<div class="fileupload fileupload-new" data-provides="fileupload">
																<div class="input-append">
																	<div class="uneditable-input">
																		<i class="fa fa-file fileupload-exists"></i>
																		<span class="fileupload-preview"></span>
																	</div>
																	<span class="btn btn-default btn-file">
																		<span class="fileupload-exists">Selecionar</span>
																		<span class="fileupload-new">Arquivo</span>
																		<input type="file" name="anexo" id="anexo" />
																	</span>
																	<a href="#" id="btnOrcUpload" class="btn btn-default fileupload-exists" data-dismiss="fileupload">Gravar</a>
																</div>
															</div>
														</div>
													</div>
													
													<div class="row mg-files" data-sort-destination data-sort-id="media-gallery" id="OrcAnexos">
             											<%=cAnexos%>
		                                            </div>
												</div>
												-->
											</div>
										</div>
									</form>			
								</section>
							</div>
						</div>
					</div>
				</section>
				

				
				<div style="display:none;">
					<form action="U_OrcUpload.apw?PR=<%=cLCodLogin%>" method="post" id="frmOrcUpload" enctype="multipart/form-data">
						<input type="hidden" name="dirOrc" value="<%=cDirOrc%>" />
					</form>
				</div>
				<footer class="panel-footer text-right">
					Desenvolvido por  <img src="images/sms.png"  />
				</footer>
			</div>		
		</section>
		<!-- end: page -->
	
		<div id="dialogRemover" class="modal-block mfp-hide">
			<section class="panel">
				<header class="panel-heading">
					<h2 class="panel-title">Exclus�o da linha</h2>
				</header>
				<div class="panel-body">
					<div class="modal-wrapper">
						<div class="modal-text">
							<p>Confirma a exclus�o desta linha?</p>
						</div>
					</div>
				</div>
				<footer class="panel-footer">
					<div class="row">
						<div class="col-md-12 text-right">
							<button id="dialogConfirm" class="btn btn-primary">Confirma</button>
							<button id="dialogCancel" class="btn btn-default">Cancela</button>
						</div>
					</div>
				</footer>
			</section>
		</div>
		    
		<div id="modalSuccess" class="modal-block modal-block-success mfp-hide">
			<section class="panel">
				<header class="panel-heading">
					<h2 class="panel-title">Success!</h2>
				</header>
				<div class="panel-body">
					<div class="modal-wrapper">
						<div class="modal-icon">
							<i class="fa fa-check"></i>
						</div>
						<div class="modal-text">
							<h4>Success</h4>
							<p>This is a successfull message.</p>
						</div>
					</div>
				</div>
				<footer class="panel-footer">
					<div class="row">
						<div class="col-md-12 text-right">
							<button class="btn btn-success modal-dismiss">OK</button>
						</div>
					</div>
				</footer>
			</section>
		</div>
		<!-- Vendor -->
		<script src="assets/vendor/jquery/jquery.js"></script>
		<script src="assets/vendor/jquery-browser-mobile/jquery.browser.mobile.js"></script>
		<script src="assets/vendor/bootstrap/js/bootstrap.js"></script>
		<script src="assets/vendor/nanoscroller/nanoscroller.js"></script>
		<script src="assets/vendor/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
		<script src="assets/vendor/bootstrap-datepicker/locales/bootstrap-datepicker.pt-BR.min.js"></script>
		<script src="assets/vendor/magnific-popup/jquery.magnific-popup.js"></script>
		<script src="assets/vendor/jquery-placeholder/jquery-placeholder.js"></script>
		<script src="assets/vendor/fuelux/js/spinner.js"></script>

		<!-- Custom -->
		<script src="custom/js/bootbox.js"></script>
		<script src="custom/js/moeda.js"></script>
	
		<!-- Specific Page Vendor -->
		<script src="assets/vendor/select2/js/select2.js"></script>
		<script src="assets/vendor/jquery-datatables/media/js/jquery.dataTables.js"></script>
		<script src="assets/vendor/jquery-datatables/extras/TableTools/js/dataTables.tableTools.min.js"></script>
		<script src="assets/vendor/jquery-datatables-bs3/assets/js/datatables.js"></script> 
		<script src="assets/vendor/jquery-datatables/media/js/jquery.dataTables.js"></script>
		<script src="assets/vendor/bootstrap-maxlength/bootstrap-maxlength.js"></script>
		<script src="assets/vendor/autosize/autosize.js"></script>
		<script src="assets/vendor/bootstrap-fileupload/bootstrap-fileupload.min.js"></script>
		<script src="assets/vendor/pnotify/pnotify.custom.js"></script>
		<script src="assets/vendor/bootstrap-select/bootstrap-select.min.js"></script>
		
		<!-- Theme Base, Components and Settings -->
		<script src="assets/javascripts/theme.js"></script>
		
		<!-- Theme Initialization Files -->
		<script src="assets/javascripts/theme.init.js"></script>
		
		<!-- Theme Custom -->
		<script src="assets/javascripts/theme.custom.js"></script> 
		
		<script src="custom/js/jquery.maskMoney.js"></script> 
		<script src="custom/js/portalMask.js"></script>
		<script type="text/javascript">
			var tblDesc = [];
			var optProd = '<%=cOptProd%>';
			var optCond = '<%=cOptCond%>';
			var optCli = '<%=cOptCli%>';
			/**
			Desabilita o enter na p�gina
			**/
			$(function () {
				$('form').bind("keypress", function (e) {
					if (e.keyCode == 13) return false;
				});
			}); 

			//Remove as op��es da tabela e adiciona o scroll		 
			$(document).ready(function () {
				$('#datatable-editable').DataTable({
					"scrollX": true,
					"ordering": false,
					"searching": false,
					"paging": false,
					"autoWidth": true,
					"info": false
				});
				$('.dataTables_length').addClass('.w-auto'); //ajusta o tamanho das colunas automaticamente
			});

		    //Formata campos de moeda
			$(function() {
			    //$('#iCK_PRCVEN01').maskMoney({thousands:'.', decimal:','});
				$('.myformato').maskMoney({thousands:'.', decimal:','}); 
				$('.percentual').maskMoney({thousands:'.', decimal:',', suffix:'%',allowNegative:true});
			})
			
			function formate() {                                        
				$('.myformato').maskMoney({thousands:'.', decimal:','});
				$('.percentual').maskMoney({thousands:'.', decimal:',', suffix:'%',allowNegative:true});
			}
			<%=cTblDesc%>
		    
		
			function sleep(ms) {
			  return new Promise(resolve => setTimeout(resolve, ms));
			}
		
			//Manipulando as colunas
			function ocultaColumn (colIndex) {
				var table = document.getElementById('datatable-editable');
				for (var r = 0; r < table.rows.length; r++)
					table.rows[r].cells[colIndex].style.display = 'none';
			}

			function mostraColumn (colIndex) {
				var table = document.getElementById('datatable-editable');
				for (var r = 0; r < table.rows.length; r++)
					table.rows[r].cells[colIndex].style.display = '';
			}
			/**
			Funcao excutada ao selecionar o cliente
			**/
			function SelCliente(){
				var cliente; 
				var lOK = false;
				var dialogCli = bootbox.dialog({
						message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Buscando dados do cliente. Aguarde...</p>',
						closeButton: false
					});
				cliente = $("#CJ_CLIENTE").val();
			    
			    //Verifica se cliente tem t�tulos em atraso
			    $.ajax({
					url: "U_GetSitCli.apw?PR=<%=cLCodLogin%>",
					type: "POST",
					data: 'cliente='+cliente,
					cache: false, 
					success: function(data){
						dialogCli.modal('hide');
						if (data.indexOf('<META HTTP-EQUIV') >= 0 ) {
							$("html").html(data);
							return;
						}
						aCli = data.split('|#|');
						if (aCli[1] != "" && aCli[1] != "::" && aCli[1].indexOf("Expires") == -1) {
							var dialog = bootbox.dialog({
							    title: 'Mensagem do Cliente',
							    message: "<p>"+aCli[1]+"</p>",
							    backdrop: true,
							    buttons: {
							        ok: {
							            label: "OK"
							        }
							    }
							});
						}

						//cliente bloqueado para comprar
						if (aCli[0] == "0"){
							
							//Bloqueia os campos para impossibilitar continuar a inclus�o
							atuModoCpo('B')
						} else {
							//Desbloqueia os campos
							atuModoCpo('D')

							$("#select2-CJ_TIPOCLI-container").html($("#CJ_TIPOCLI option[value='"+aCli[2]+"']").html());
							$("#CJ_TIPOCLI").val(aCli[2]);
							$("#CJ_GRPTRIB").val(aCli[3]);


							if (aCli[4] != ""){
								$("#CJ_CONDPAG").val(aCli[4]);
								$("#select2-CJ_CONDPAG-container").html($("#CJ_CONDPAG option[value='"+aCli[4]+"']").html());
							}
							$("#CJ_CONDPAG").removeAttr('disabled');
							
							$("#CJ_UFENT").val(aCli[5]);

							//Adiciona as op��es do cliente
							//optCli = document.querySelector("#CJ_CLIENTE").options;
							//$("#CJ_CLIINTE").append($(optCli).clone(true).removeAttr('id').attr("id","CJ_CLIINTE"));
							$("#CJ_CLIINTE").append($.parseHTML(optCli));
							$('.selectpicker').selectpicker('render');
							$('.selectpicker').selectpicker('refresh');
							
							
							$("#CJ_CLIENT").append($.parseHTML(optCli));
							$('.selectpicker').selectpicker('render');
							$('.selectpicker').selectpicker('refresh');
							$('#CJ_CLIENT').selectpicker('val', cliente);

							$("#CJ_NROPOR").focus();
						} 
					}
				});	
			}
			
			/**
			Atualiza o modo de edi��o do campo
			**/
			function atuModoCpo(cTipo){
				var aCampos = ["CJ_CLIENTE","CJ_NROPOR","CJ_XCONTAT","CJ_XCONDDD","CJ_XCONTEL","CJ_CLIENT","CJ_UFENT","CJ_OBRA","CJ_VEND6","CJ_TERMOME","CJ_CONDPAG","CJ_CLIINTE","CJ_RETORNO","CJ_LUMINOT","CJ_SEGMENT","CJ_PROPECC","CJ_REGIAO","CJ_VEND","CJ_VEND3","CJ_VEND4","CJ_CODESP","CJ_VEND7","CJ_VALIDA","CJ_PRZEMB","CJ_TPFRETE","CJ_PERCFRT","CJ_FRETE","CJ_OBS","CK_PRODUTO01"];
				var nI = 0;

				//Atualiza os campos
				for (nI = 0; nI < (aCampos.length-1) ; nI++) {
					if(cTipo == 'B'){
						$("#"+aCampos[nI]).attr("disabled","");
					} else {
						$("#"+aCampos[nI]).removeAttr('disabled');
						$("#"+aCampos[nI]).attr("disabled",false);
					}
				}
			}

			/**
			Preenche a revis�o da oportunidade
			**/
			function atuRevOpt(){
				var cOport = $("#CJ_NROPOR").val();
				var cobjOport = $("#CJ_NROPOR")[0];
				var cRevisa = cobjOport.options[cobjOport.selectedIndex].text.substr(7,2)
				var dialog = bootbox.dialog({
			        message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Buscando dados da oportunidade... Aguarde...</p>',
			        closeButton: false
			    });

				if(cOport != ""){
					$("#CJ_REVISA").val(cRevisa);
					
					$.ajax({
						url: "U_GetDadosOpt.apw?PR=<%=cLCodLogin%>",
						data: 'oportunidade='+cOport+'&revisao='+cRevisa,
						type: "POST",
						async: false,
						success:
							function(dados) {
								if (dados.indexOf('<META HTTP-EQUIV') >= 0 ) {
									$("html").html(dados);
									return;
								} else {
									if (dados.substr(0, 2) == "OK") {
										aVlr = dados.substr(5).split('|#|');
										
										//Atualiza a comiss�o
										$("#CJ_COMISTR").val(aVlr[0]);
										//Atualiza o vendedor
										$("#CJ_VEND3").append($.parseHTML(aVlr[1]));
										$('.selectpicker').selectpicker('render');
										$('.selectpicker').selectpicker('refresh');
										$("#select2-CJ_VEND3-container").html($("#CJ_VEND3 option[value='"+aVlr[2]+"']").html());

										
									} else {
										bootbox.alert("Falha ao localizar os dados da oportunidade!");
									}
								}
							}
					});

				} else {
					$("#CJ_REVISA").val("");
				}
				dialog.modal('hide');
			}

			/**
			Atualiza o valor do frete
			**/
			function atuVlrFrete(){
				var cUFEnt = $("#CJ_UFENT").val().substr(0,2)
				var cMunEnt = $("#CJ_UFENT").val().substr(3,5)
				
				if(cUFEnt != ""){
				
					$.ajax({
						url: "U_GetPerFrt.apw?PR=<%=cLCodLogin%>",
						data: 'uf='+cUFEnt+'&mun='+cMunEnt,
						type: "POST",
						async: false,
						success:
							function(frete) {
								if (frete.indexOf('<META HTTP-EQUIV') >= 0 ) {
									$("html").html(frete);
									return;
								} else {
									//Atualiza o frete
									$("#CJ_PERCFRT").removeAttr("disabled");
									$("#CJ_PERCFRT").val(frete);
								}
							}
					});
				}
			}

			/**
			Valida o estudo
			**/
			function vldEstudo(){
				var cEstudo = $("#CJ_LUMINOT").val();
				if(cEstudo == "1"){
					$("#CJ_REGLUMI").removeAttr('disabled');
				} else {
					$("#CJ_REGLUMI").val("");
					$("#select2-CJ_REGLUMI-container").html($("#CJ_REGLUMI option[value='']").html());
					$("#CJ_REGLUMI").attr("disabled","");
				}
			}

			/**
			Valida a prospec��o
			**/
			function vldProspec(){
				var cProspec = $("#CJ_PROPECC").val();
				if(cProspec == "S"){
					$("#CJ_PROSCOD").removeAttr('disabled');
				} else {
					$("#CJ_PROSCOD").val("");
					$("#select2-CJ_PROSCOD-container").html($("#CJ_PROSCOD option[value='']").html());
					$("#CJ_PROSCOD").attr("disabled","");
				}
			}

			/**
			Valida o campo prospectado por
			**/
			function vldProsPor(){
				var cProspec = $("#CJ_PROPECC").val();
				var cProsPor = $("#CJ_PROSCOD").val();

				if(cProspec == "S" && cProsPor == ""){
					bootbox.alert("Informe o campo Prospectado Por!")
				} 
				if (cProspec == "N"){
					$("#CJ_PROSCOD").val("");
					$("#select2-CJ_PROSCOD-container").html($("#CJ_PROSCOD option[value='']").html());
					$("#CJ_PROSCOD").attr("disabled","");
				}
			}
			
			/**
			Busca os produtos a partir da tabela de pre�o
			**/
			function selProd(){
				var tabpreco;
				var cliente;
				var item;
				
				cliente = $("#CJ_CLIENTE").val();
				tabpreco = $("#CJ_TABELA").val();
			 	item = $("#PROXIMO").val();
			 	
			 	$.ajax({
					url: "U_GetProdutos.apw?PR=<%=cLCodLogin%>",
					data: 'cliente='+cliente+'&tabela='+tabpreco,
					type: "POST",
					async: false,
					success:
						function(produtos) {
							if (produtos.indexOf('<META HTTP-EQUIV') >= 0 ) {
								$("html").html(produtos);
								return;
							}
							
							if ( produtos == "" ) {
								bootbox.alert('N�o foram encontrados produtos para a tabela de pre�o '+tabpreco+'!');
								$("#CJ_TABELA").focus();
							}
							else {
								//Bloqueia a edi��o do campo de tabela
								$("#CJ_TABELA").attr("disabled","");
								
							 	//Preenche o select dos produtos
							 	$("#CK_PRODUTO"+item).append($.parseHTML(produtos));
							 	$('.selectpicker').selectpicker('render');
			   	    			$('.selectpicker').selectpicker('refresh');
							 	optProd = produtos;
							}
						}
				});
			}
						
			
			/**
			Busca as condi��es de pagamento dispon�veis de acordo com a modalidade
			**/
			function condPag(){
				var modali = $("#CJ_XMODALI").val();
			 	var dialogTab = bootbox.dialog({
			        message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Buscando condi��es de pagamento... Aguarde...</p>',
			        closeButton: false
			    });
			    	
			 	$.ajax({
					url: "U_GetCondPgto.apw?PR=<%=cLCodLogin%>",
					data: 'modali='+modali,
					type: "POST",
					async: false,
					success:
						function(condicao) {
							if (condicao.indexOf('<META HTTP-EQUIV') >= 0 ) {
								$("html").html(condicao);
								return;
							}
							
							if ( condicao == "" ) {
								bootbox.alert('Falha ao localizar as condi��es de pagamento para esta modalidade!');
								document.getElementById('CJ_CONDPAG').innerText = null;
								$('.selectpicker').selectpicker('render');                  
			   	    			$('.selectpicker').selectpicker('refresh'); 
			   	    			$("#CJ_XMODALI").focus();
							}
							else {
								
							 	//Preenche o select das condi��es
							 	document.getElementById('CJ_CONDPAG').innerText = null;
							 	$("#CJ_CONDPAG").append(condicao);
							 	optCond = condicao;
							    if ($("#CJ_XMODALI").val() != "") {
									$("#CJ_CONDPAG").removeAttr('disabled');
								}
								//Para cart�o habilita as op��es de parcela e bandeira
								if ($("#CJ_XMODALI").val() == "03") {
									$("#CJ_XPARC").removeAttr('disabled');
									$("#CJ_XPARC").attr("required",""); 
									$("#CJ_XPARC").attr("aria-required","true");  //torna obrigat�rio
									
									// $("#CJ_XBAND").removeAttr('disabled');
									// $("#CJ_XBAND").attr("required",""); 
									// $("#CJ_XBAND").attr("aria-required","true");  //torna obrigat�rio
									
								} else {
									$("#CJ_XPARC").attr('disabled',"");
									//$("#CJ_XBAND").attr('disabled',"");	
								}
							}
						}
				});	
				dialogTab.modal('hide');
			}
			

			/**
			Valida a condi��o de pagamento selecionada
			**/
			function vldCond(){
				var valDesc = 0;
					
				$.ajax({
					url: "U_VldCondPg.apw?PR=<%=cLCodLogin%>",
					data: 'condPgto='+$("#CJ_CONDPAG").val(),
					type: "POST",
					async: false,
					success:
						function(retorno) {
							valDesc = parseFloat(retorno);
							
							//Atualiza a vari�vel
							$("#DESCCOND").val(valDesc);
							
							if (valDesc > 0) {
								bootbox.alert("Condi��o de pagamento com desconto. Ao salvar o or�amento ser� aplicado o desconto de "+mascaraValor(valDesc.toFixed(2))+"%."); 	
							} else {
								$("#DESCCOND").val("0");
							}

							//Atualiza o valor do produto quando altera a condi��o de pagamento
							if ($('#iCK_PRCVEN01').val()!=$('#CK_PRCVEN01').val() || $("#DESCCOND").val()=="0"){
								AtuValProd();
							}
						}
				});
			}
			
			/**
			Monta a tela para selecionar o produto
			**/
			function getProduto(btPesquisa){
				var objProd = btPesquisa.closest("td").find("[autocomplete=off]");
				var cProdBusca = $("#"+objProd.attr("name")).val().toUpperCase();
				//var nItem = btPesquisa[0].id.substr(8,2);
				var nItem = objProd.attr("name").substr(10);

				$("#PROXIMO").val(nItem);

				// Usando a fun��o buscarProdutos com um callback
				buscarProdutos(cProdBusca, nItem, function (produtosEncontrados) {
					if (produtosEncontrados.length >= 1) {

						var selectOptions = '<select id="produtoSelecionado">';
						//var selectOptions = '<select data-plugin-selectTwo class="form-control populate placeholder" data-plugin-options="{ "placeholder": "Selecione...", "allowClear": false }" id="produtoSelecionado">';
						var indiceHifen;
						var selOptions = '';

						produtosEncontrados.forEach(function (produto) {								
							selectOptions += "<option value='" + produto + "'>" + produto + "</option>";

							//selOptions+= "{text: '"+produto+"',value: '"+produto+"'},";

						});

						selectOptions += "</select>";

						bootbox.dialog({
							title: 'Produtos',
							message: "<p>Selecione o produto desejado:</p>" + selectOptions,
							backdrop: false,
							size: 'large',
							buttons: {
								confirm: {
									label: 'Confirmar',
									className: 'btn-primary', 
									callback: function () {
										var produtoSelecionado = $("#produtoSelecionado").val();

										// Atualiza o campo original com o produto escolhido
										$("#CK_PRODUTO" + nItem).val(produtoSelecionado);

										// Encontra a posi��o do primeiro h?fen na string
										indiceHifen = produtoSelecionado.indexOf("-");
										//Pega apenas o codigo do produto
										produtoSelecionado = produtoSelecionado.substring(0, indiceHifen);
										//Remove espa�os vazios
										produtoSelecionado = produtoSelecionado.trim();
										//gatProduto(objProd,produtoSelecionado);											
									}
								},
								cancel: {
									label: 'Cancelar',
									className: 'btn-default', 
									callback: function () {

									}
								}
							}/*,
							callback: function (result) {
                                console.log(result);
                            	}*/

						});
						/*
						bootbox.dialog({
							title: 'Produtos',
							message: "<p>Selecione o produto desejado:</p>" + selectOptions,
							backdrop: false,
							size: 'large',
							buttons: {
								confirm: {
									label: 'Confirmar',
									className: 'btn-primary', 
									callback: function () {
										var produtoSelecionado = $("#produtoSelecionado").val();

										// Atualiza o campo original com o produto escolhido
										$("#CK_PRODUTO" + nItem).val(produtoSelecionado);

										// Encontra a posi��o do primeiro h?fen na string
										indiceHifen = produtoSelecionado.indexOf("-");
										//Pega apenas o codigo do produto
										produtoSelecionado = produtoSelecionado.substring(0, indiceHifen);
										//Remove espa�os vazios
										produtoSelecionado = produtoSelecionado.trim();
										gatProduto(objProd,produtoSelecionado);											
									}
								},
								cancel: {
									label: 'Cancelar',
									className: 'btn-default', 
									callback: function () {

									}
								}
							}
						});*/
					} else {
						// Nenhum produto encontrado
						bootbox.alert("Nenhum produto encontrado!")
					}
				});
			}
					
			/**
			Busca dados do produto a partir do c�digo ou descri��o
			**/
			function buscarProdutos(cProdBusca,item,callback){
				var cliente = $("#CJ_CLIENTE").val();
				var tabpreco = $("#CJ_TABELA").val();	
				var item = $("#PROXIMO").val();

				if (cProdBusca != ""){
					if(cliente == ""){
						bootbox.alert("Selecione o cliente para continuar!");
						return false;
					}
					$.ajax({
						url: "U_GetLikePro.apw?PR=<%=cLCodLogin%>",
						data: 'cliente=' + cliente + '&tabela=' + tabpreco + '&digit=' + cProdBusca,
						method: "POST",
						async: false,
						success: function( produtos ) {
							if (produtos.toLowerCase().indexOf('<META HTTP-EQUIV') >= 0 ||produtos.toLowerCase().indexOf("Expires") != -1) {
								$("html").html(produtos);
								callback([]); // Retorna uma lista vazia em caso de erro
							}
							
							if (produtos == "") {
								bootbox.alert('N�o foram encontrados produtos para o termo pesquisado!');
								callback([]); // Retorna uma lista vazia em caso de erro
							} else {
								$("#CK_PRODUTO" + item).empty(); // Limpa o conte�do existente

								/*
								// Preenche o select dos produtos
								$("#CK_PRODUTO" + item).empty(); // Limpa o conte�do existente
								$("#CK_PRODUTO"+item).append($.parseHTML(produtos));
							 	$('.selectpicker').selectpicker('render');
			   	    			$('.selectpicker').selectpicker('refresh');
							 	optProd = produtos;
								*/

								var selectpicker = $("<select>", {
									class: "selectpicker",
									title: "Selecione um produto"
								});
								selectpicker.append($.parseHTML(produtos));

								// Adiciona os valores dos elementos <option>  listaProdutos
								var listaProdutos = selectpicker.find('option').map(function () {
									//return $(this).val();
									////Luiz SMS - 04/01/2024
									return $(this).text();//Pegar o texto completo 
								}).get();

								$("#CK_PRODUTO" + item).append(selectpicker);
								callback(listaProdutos); // Retorna a lista de produtos encontrados
							}
						}
					});
				} else {
					bootbox.alert("Informe o produto para busca!");
				}
			}

			/**
			Busca dados do produto a partir do c�digo de barras
			**/
			function Maiuscula(cItemAtu){
				var cCodBar = $("#"+cItemAtu.attr("id")).val().toUpperCase();
				$(cItemAtu).val(cCodBar);
			}
			
			/**
			Gatilho acionado ao selecionar o produto para preencher os valores
			**/
			function gatProduto(objInput) {                                   
				var nItens = parseFloat($("#PROXIMO").val());
				var lProdOK = true
				var nItem = objInput.attr("name").substr(10);
				var dialogProd = bootbox.dialog({
			        message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Buscando dados do produto... Aguarde...</p>',
			        closeButton: false
			    });
			    
					
			    //valida a digita��o duplicada de itens
				for (i = 1; i<=nItens; i++) { 
					cItem = String(i);
					if (parseInt(i) < 10 ){cItem = "0"+String(i)};
					
					cItmOrc = $("#CK_ITEM"+cItem).val();
					
					if(cItmOrc != "x" && nItem != cItem ) { 
						if ($('#CK_PRODUTO'+cItem).val() == objInput.val()){ 
							lProdOK = false;	
							$('#CK_PRODUTO'+nItem).val("");
							$("#select2-CK_PRODUTO"+cItem+"-container").html("Selecione..."); 
						}
					}	
				}
				
				if (!lProdOK ) {
					bootbox.alert("Este item j� foi informado no or�amento!");
					dialogProd.modal('hide');
				}
				//Fim da valida��o de itens duplicados
			
				if ( ! objInput.is('[readonly]') && $.trim(objInput.val()) != "" && lProdOK ) {  
					
					jQuery.ajax({
						type: "POST",
						url: "U_GATPROD.APW?PR=<%=cLCodLogin%>",
						data: 'produto='+encodeURIComponent(objInput.val()),
						error: function (jqXHR, textStatus, error){
							dialogProd.modal('hide');
							bootbox.alert("Falha ao recuperar informa��es!");
							console.log(error);
						},
						success: function( data ) {
							var aVlr;
							var cMsgErro;
							var nItem = objInput.attr("name").substr(10);
			
			    			dialogProd.modal('hide');
			
							if (data.substr(0, 2) == "OK") {
								aVlr = data.substr(3).split('|#|');
								$("input[name='CK_UM"+nItem+"']").val(aVlr[0]);
								$.trim($("input[name='CK_PRCVEN"+nItem+"']").val(aVlr[1]));
								$.trim($("input[name='iCK_PRCVEN"+nItem+"']").val(aVlr[1]));
								$.trim($("input[name='CK_XVALICM"+nItem+"']").val(aVlr[2]));
								$.trim($("input[name='CK_XVALIPI"+nItem+"']").val(aVlr[3]));
								$.trim($("input[name='CK_XICMST"+nItem+"']").val(aVlr[4]));
								$.trim($("input[name='CK_LOCAL"+nItem+"']").val(aVlr[15]));
															
								//Input hidden
								$("input[id='ALIQ_IPI"+nItem+"']").val(aVlr[5]);
								$("input[id='ALIQ_ICMS"+nItem+"']").val(aVlr[6]);
								$("input[id='ALIQ_ST"+nItem+"']").val(aVlr[12]);
								$("input[id='BASE_IPI"+nItem+"']").val(aVlr[11]);
								$("input[id='BASE_ICMS"+nItem+"']").val(aVlr[9]);
								$("input[id='BASE_ST"+nItem+"']").val(aVlr[10]);
								$("input[id='VAL_ICMS"+nItem+"']").val(aVlr[2]);
								$("input[id='VAL_ST"+nItem+"']").val(aVlr[4]);
								$("input[id='VAL_IPI"+nItem+"']").val(aVlr[3]);
							
								$("input[id='QTD_EMB"+nItem+"']").val(aVlr[7]);
								$("input[id='CK_TES"+nItem+"']").val(aVlr[8]);
								$("input[id='GRUPO"+nItem+"']").val(aVlr[13]);
								$("input[id='QTDMIN"+nItem+"']").val(aVlr[14]);
								$("input[id='EST_DISP"+nItem+"']").val(aVlr[16]);
								
								//Limpa os inputs, caso tenha trocado o produto
								$("input[name='CK_QTDVEN"+nItem+"']").removeAttr('disabled');
								if ($("#CK_XCODBAR"+nItem).val() == ""){
									$("input[name='CK_QTDVEN"+nItem+"']").val(""); 		
								} else {
									if ($("#XCODBAR"+nItem).val() != aVlr[16] && $("#XCODBAR"+nItem).val() != aVlr[17]){
										$("#XCODBAR"+nItem).val() = "";
									}
								}						
								$("input[name='CK_VALOR"+nItem+"']").val("0,00"); 																
								
							} else {			
								
								if (data.substr(0, 4) == "ERRO") {
									cMsgErro = data.substr(5);
									bootbox.alert(cMsgErro);
									LimpaLinha(nItem);
								} else {
									cMsgErro = "Houve falha ao localizar os dados do produto. Tente novamente!"; 
									bootbox.alert(cMsgErro);
									LimpaLinha(nItem);
									// Quando ocorre erro no protheus	
									console.log(data);
								} 
							}
						}
					});
				
				} else if ($.trim(objInput.val()) == "" ) {
					LimpaLinha(nItem);
				}
			    
				return false;
			}

					
			/**
			Funcao de calculo do total do item
			**/
			function TotalItem(cItemAtu) {
				var nQuant;
				var nVlrUnit;
				var nVlrTabela;
				var nTotalUnit;
				var nICMS;
				var nICMSST;
				var nIPI;     
				var nPerDesc = 0;    
				var nValFrete;
				var nVlrTotal;
				var nBaseIPI;
				var nBaseICMS;
				var nBaseST;
				var cFaixaDesc;	
				var nPerCom = 0;
				var nValCom = 0;
				var nValDesc = 0;
				 
				cCodProd = $("#CK_PRODUTO"+cItemAtu).val();
				nQuant = parseFloat($("#CK_QTDVEN"+cItemAtu).val().replace('.',"").replace(",","."));
				nVlrTabela = $('#iCK_PRCVEN'+cItemAtu).maskMoney('unmasked')[0];
				//nVlrTabela = $('#CK_PRCVEN'+cItemAtu).maskMoney('unmasked')[0];
				//nVlrUnit = $('#iCK_PRCVEN'+cItemAtu).maskMoney('unmasked')[0];
				nValFrete = $("#CJ_FRETE").maskMoney('unmasked')[0];
				if ($('#CK_DESCONT'+cItemAtu).maskMoney('unmasked')[0] != 0){
			   		nPerDesc = $("#CK_DESCONT"+cItemAtu).maskMoney('unmasked')[0];
				}
				nVlrUnit = nVlrTabela - (nVlrTabela*(nPerDesc/100));
				nVlrTotal = nVlrTabela*nQuant;
				nTotalUnit = nVlrTotal
				nValDesc = nVlrTotal*(nPerDesc/100);
				nVlrTotal = nVlrTotal - nValDesc;
				
				
				//Tratamento para os impostos
				nICMS = $('#CK_XVALICM'+cItemAtu).maskMoney('unmasked')[0];
				nICMSST = $('#CK_XICMST'+cItemAtu).maskMoney('unmasked')[0];
				nIPI = $("#CK_XVALIPI"+cItemAtu).maskMoney('unmasked')[0];
		   		
				//Aliquotas
				nAliqIPI = parseFloat($("#ALIQ_IPI"+cItemAtu).val());
				nAliqICMS = parseFloat($("#ALIQ_ICMS"+cItemAtu).val());
				nAliqST = parseFloat($("#ALIQ_ST"+cItemAtu).val());			
			    
				//Valores Base
				nBaseIPI = parseFloat($("#BASE_IPI"+cItemAtu).val());
				nBaseICMS = parseFloat($("#BASE_ICMS"+cItemAtu).val());
				nBaseST = parseFloat($("#BASE_ST"+cItemAtu).val());
				
				//Valor do imposto
				nIPI = nBaseIPI * nQuant * (nAliqIPI /100)
				nICMS = nBaseICMS * nQuant * (nAliqICMS /100)
				nICMSST = nQuant * parseFloat($("#VAL_ST"+cItemAtu).val().replace(",","."));
				
				//nIPI = nVlrTotal*(nAliqIPI /100)
				//nICMS = nVlrTotal*(nAliqICMS /100)
				//nIPI = nQuant * parseFloat($("#VAL_IPI"+cItemAtu).val().replace(",","."));
				//nICMS = nQuant * parseFloat($("#VAL_ICMS"+cItemAtu).val().replace(",","."));
				//nICMSST = nQuant * parseFloat($("#VAL_ST"+cItemAtu).val().replace(",","."));
			

				nVlrTotal = nVlrTotal+nIPI+nICMSST;
				nTotalUnit = nVlrTotal / nQuant;
									
				//Atualiza o campo do total
				$.trim($("#CK_XVALICM"+cItemAtu).val(mascaraValor(nICMS.toFixed(2))));
				$.trim($("#CK_XVALIPI"+cItemAtu).val(mascaraValor(nIPI.toFixed(2))));
				$.trim($("#CK_XICMST"+cItemAtu).val(mascaraValor(nICMSST.toFixed(2))));
				$.trim($("#iCK_PRCVEN"+cItemAtu).val(mascaraValor(nVlrUnit.toFixed(2))));
				$.trim($("#CK_VALOR"+cItemAtu).val(mascaraValor(nVlrTotal.toFixed(2))));
				$.trim($("#CK_XPRCIMP"+cItemAtu).val(mascaraValor(nTotalUnit.toFixed(2))));
				//Atualiza o total geral
			    TotalGeral();
			}
			 
			/**
			Total Geral
			**/
			function TotalGeral() {
				var nItens = parseFloat($("#PROXIMO").val());
				var i;
				var nVlrTabela = 0;
				var nVlrUnit = 0;
				var nICMS = 0;
				var nICMSST = 0;
				var nIPI = 0;
				var nImpostos = 0;
				var nValFrete = 0;
				var nTotal = 0;
				var nAcresc = 0;
				var nDescCond = 0;
				var nQuant = 0;
				var nValCom = 0;
				var cCodProd;
				var cItmOrc;
                var nTotQuant = 0.00;
                var nSaldo = 0;
				var nTotalProm = 0
				
				for (i = 1; i<=nItens; i++) { 
					cItem = String(i); 
					if (parseInt(i) < 10 ){cItem = "0"+String(i)};
					
					cCodProd = $("#CK_PRODUTO"+cItem).val();
					cItmOrc = $("#CK_ITEM"+cItem).val();
					if(cItmOrc != "x") {
						nQuant = parseFloat($("#CK_QTDVEN"+cItem).val().replace('.',"").replace(",",".")); 
                        nTotQuant += nQuant; 
						nVlrUnit += nQuant * $('#iCK_PRCVEN'+cItem).maskMoney('unmasked')[0];
						nICMS += $('#CK_XVALICM'+cItem).maskMoney('unmasked')[0];
						nICMSST += $('#CK_XICMST'+cItem).maskMoney('unmasked')[0];
						nIPI += $("#CK_XVALIPI"+cItem).maskMoney('unmasked')[0];
						nValCom += $("#VAL_COM"+cItem).maskMoney('unmasked')[0];
						nTotal += $('#CK_VALOR'+cItem).maskMoney('unmasked')[0];
						if ($("#PROMOCAO"+cItem).val() == "1"){
							nTotalProm += $('#CK_VALOR'+cItem).maskMoney('unmasked')[0];
						}
						nSaldo += $('#SALDO'+cItem).maskMoney('unmasked')[0];
					}
				}
				nImpostos = nICMSST+nIPI; //nICMS
				nValFrete = $("#CJ_FRETE").maskMoney('unmasked')[0];
				
				/*
				//Verifica acrescimo da condi��o de pagamento
				$.ajax({
					url: "U_ValAcresc.apw?PR=<%=cLCodLogin%>",
					data: 'condPgto='+$("#CJ_CONDPAG").val()+'&valor='+nTotal,
					type: "POST",
					async: false,
					success:
						function(retorno) {
							//nAcresc = parseFloat(retorno);
							nAcresc = parseFloat(nTotal*(retorno/100))
						}
				});
				*/
				nDescCond = parseFloat((nTotal-nTotalProm)*($("#DESCCOND").val()/100)); //desconto da condi��o de pagamento
				//nDescCond = parseFloat(nTotal*($("#DESCCOND").val()/100)); //desconto da condi��o de pagamento
				nTotal =  (nTotal+nValFrete+nAcresc)-nDescCond;
				
				//Atualiza os totais   
				$("#TOTAL_QITENS").val($.trim(mascaraValor(nTotQuant.toFixed(2))));
				$("#TOTAL_ITENS").val($.trim(mascaraValor(nVlrUnit.toFixed(2))));
				$("#TOTAL_IMP").val($.trim(mascaraValor(nImpostos.toFixed(2))));
				$("#TOTAL_FRETE").val($("#CJ_FRETE").val());
				$("#TOTAL_ACRESC").val($.trim(mascaraValor(nDescCond.toFixed(2))));
				//$("#TOTAL_ACRESC").val($.trim(mascaraValor(nAcresc.toFixed(2))));
				$("#TOTAL_ORC").val($.trim(mascaraValor(nTotal.toFixed(2))));
				$("#TOTAL_COM").val($.trim(mascaraValor(nValCom.toFixed(2))));
				$("#TOTAL_SALDO").val($.trim(mascaraValor(nSaldo.toFixed(2))));
			}
			
			/**
			Atualiza o valor do produto ao trocar a condi��o de pagamento
			**/
			function AtuValProd(){
				var nItens = parseFloat($("#PROXIMO").val());
				var i;
				var nvalorcheio = 0;

				for (i = 1; i<=nItens; i++) { 
					cItem = String(i); 
					if (parseInt(i) < 10 ){cItem = "0"+String(i)};
					cItmOrc = $("#CK_ITEM"+cItem).val();
					if(cItmOrc != "x") {
						nvalorcheio = $('#CK_PRCVEN'+cItem).val();
						$('#iCK_PRCVEN'+cItem).val(nvalorcheio);
						TotalItem(cItem);
					}
				}
			}

			/**
			Verifica se a quantidade � m�ltiplo da embalagem
			**/
			function VldQtd(cItemAtu) {
				var nQuant;
				var nQtdEmb;
				var nQtdMin;
				var resto;
				cCodProd = $("#CK_PRODUTO"+cItemAtu).val();
			    var lRet = true
			    
			 	//Valida a quantidade por embalagem
			 	nQtdEmb = parseFloat($("#QTD_EMB"+cItemAtu).val());
			 	nQtdMin = $("#QTDMIN"+cItemAtu).val();
			 	nQuant = parseFloat($("#CK_QTDVEN"+cItemAtu).val().replace('.',"").replace(",","."));
				if (nQuant > 0){ 
					
					//Valida a quantidade da embalagem
					if (nQtdEmb > 0){
						if (nQuant < (nQtdEmb)){
							bootbox.alert("A quantidade deve ser m�ltiplo de "+nQtdEmb.toString()+".");
							$("#CK_QTDVEN"+cItemAtu).val("");
							lRet = false;
							return false;
						} else {
							resto = nQuant % nQtdEmb;
							if (resto != 0 ){
								bootbox.alert("A quantidade deve ser m�ltiplo de "+nQtdEmb.toString()+".");
								$("#CK_QTDVEN"+cItemAtu).val("");
							    lRet = false;
								return false;
							}
						}
					}

					var dialogProd = bootbox.dialog({
						message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Buscando dados do produto... Aguarde...</p>',
						closeButton: false
					});

					//Atualiza o pre�o de acordo com a quantidade
					jQuery.ajax({
						type: "POST",
						url: "U_GATPROD.APW?PR=<%=cLCodLogin%>",
						data: 'produto='+encodeURIComponent(cCodProd)+'&quant='+nQuant,
						error: function (jqXHR, textStatus, error){
							dialogProd.modal('hide');
							bootbox.alert("Falha ao recuperar informa��es!");
							console.log(error);
						},
						success: function( data ) {
							var aVlr;
							var cMsgErro;
							
			    			dialogProd.modal('hide');
			
							if (data.substr(0, 2) == "OK") {
								aVlr = data.substr(3).split('|#|');
								$("input[name='CK_UM"+cItemAtu+"']").val(aVlr[0]);
								$.trim($("input[name='CK_PRCVEN"+cItemAtu+"']").val(aVlr[1]));
								$.trim($("input[name='iCK_PRCVEN"+cItemAtu+"']").val(aVlr[1]));
								$.trim($("input[name='CK_XVALICM"+cItemAtu+"']").val(aVlr[2]));
								$.trim($("input[name='CK_XVALIPI"+cItemAtu+"']").val(aVlr[3]));
								$.trim($("input[name='CK_XICMST"+cItemAtu+"']").val(aVlr[4]));
								$.trim($("input[name='CK_LOCAL"+cItemAtu+"']").val(aVlr[15]));
															
								//Input hidden
								$("input[id='ALIQ_IPI"+cItemAtu+"']").val(aVlr[5]);
								$("input[id='ALIQ_ICMS"+cItemAtu+"']").val(aVlr[6]);
								$("input[id='ALIQ_ST"+cItemAtu+"']").val(aVlr[12]);
								$("input[id='BASE_IPI"+cItemAtu+"']").val(aVlr[11]);
								$("input[id='BASE_ICMS"+cItemAtu+"']").val(aVlr[9]);
								$("input[id='BASE_ST"+cItemAtu+"']").val(aVlr[10]);
								$("input[id='VAL_ICMS"+cItemAtu+"']").val(aVlr[2]);
								$("input[id='VAL_ST"+cItemAtu+"']").val(aVlr[4]);
								$("input[id='VAL_IPI"+cItemAtu+"']").val(aVlr[3]);
							
								$("input[id='QTD_EMB"+cItemAtu+"']").val(aVlr[7]);
								$("input[id='CK_TES"+cItemAtu+"']").val(aVlr[8]);
								$("input[id='GRUPO"+cItemAtu+"']").val(aVlr[13]);
								$("input[id='QTDMIN"+cItemAtu+"']").val(aVlr[14]);
								
							} else {			
								
								if (data.substr(0, 4) == "ERRO") {
									cMsgErro = data.substr(5);
									bootbox.alert(cMsgErro);
									LimpaLinha(cItemAtu);
								} else {
									cMsgErro = "Houve falha ao localizar os dados do produto. Tente novamente!"; 
									bootbox.alert(cMsgErro);
									LimpaLinha(cItemAtu);
									// Quando ocorre erro no protheus	
									console.log(data);
								} 
							}
						}
					});
					
				} else {
					bootbox.alert("Informe a quantidade!");
					lRet = false;
					return false;
				} 
				
				if (lRet == true){
					//Valida o estoque do produto
					vldEstoque(cItemAtu);
				}
				
            	//Gatilho para total do item
            	TotalItem(cItemAtu);
			}
			
			
			
			
			/**
			Verifica se existe estoque dispon�vel
			**/
			function vldEstoque(cItem){
				var produto = $("#CK_PRODUTO"+cItem).val();
				var quantidade = parseFloat($("#CK_QTDVEN"+cItem).val().replace('.',","));
				var qtd = $("#CK_QTDVEN"+cItem).val();
				var lret = true;
				var retVld = true;
				
			 	var dialogTab = bootbox.dialog({
			        message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Verificando estoque dispon�vel... Aguarde...</p>',
			        closeButton: false
			    });
			    
				$.ajax({
					url: "U_GetEstDisp.apw?PR=<%=cLCodLogin%>",
					data: 'produto='+encodeURIComponent(produto)+'&quantidade='+qtd,
					type: "POST",
					async: false,
					success:
						function(retorno) {
							if (retorno.indexOf('<META HTTP-EQUIV') >= 0 ) {
								$("html").html(retorno);
								return;
							}
							saldo = parseInt(retorno);
							$("#EST_DISP"+cItem).val(saldo);
							if ( saldo <= 0 || saldo < quantidade) {
								if(retorno < 0){
									retorno = 0
								};	 
								dialogTab.modal('hide'); 
								bootbox.alert('N�o h� saldo dispon�vel em estoque para a quantidade solicitada para o item '+produto+'! <br>O saldo atual � de '+retorno+'.');
								
								if ($('#CJ_XTPORC').val() == "1"){
									$("#CK_QTDVEN"+cItem).val(""); 
									lret = false;
									retVld = false;
								}
							}
						}
				});
				
				if (lret == true){ 
					//Habilita os campos para edi��o
					$("#CK_XPEDCLI"+cItem).removeAttr('disabled');
					$("#CK_XITEMCL"+cItem).removeAttr('disabled');
					$("#CK_DESCONT"+cItem).removeAttr('disabled');
				}      
				dialogTab.modal('hide');
				
				return retVld;
			}

			
			/**
			Limpa os valores da linha
			**/
			function LimpaLinha(cItem) {
				$("#CK_QTDVEN"+cItem).val("");
				$("#CK_LOCAL"+cItem).val("");
				$("#iCK_PRCVEN"+cItem).val("");
				$("#CK_PRCVEN"+cItem).val("");
				$("#CK_XPRCIMP"+cItem).val("");
				$("#CK_XVALIPI"+cItem).val("");
				$("#CK_XVALICM"+cItem).val("");
				$("#CK_XICMST"+cItem).val("");
				$("#CK_VALOR"+cItem).val("");
				$("#PER_COM"+cItem).val("");
				$("#VAL_COM"+cItem).val("");
				$("#CK_DESCONT"+cItem).val("");
							
				TotalGeral();	
			}

			
			/**
			Verifica se o valor digitado � maior que o valor de tabela
			**/
			function VldValor(cItemAtu) {
				var nVlrTabela = $('#CK_PRCVEN'+cItemAtu).maskMoney('unmasked')[0];
				var nVlrUnit = $('#iCK_PRCVEN'+cItemAtu).maskMoney('unmasked')[0];
				var produto = $("#CK_PRODUTO"+cItemAtu).val();
				var nValMin = 0;
				var nDescont = 0;
				var nDescMax = 0;
				var aDesc;
				var lOK = true;
				var lMostra = false;
				var dialogTab = bootbox.dialog({
					message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Verificando valores... Aguarde...</p>',
			       	closeButton: false
			       }); 
			    
				if ($('#CK_DESCONT'+cItemAtu).maskMoney('unmasked')[0] != 0){
				    nDescont = $('#CK_DESCONT'+cItemAtu).maskMoney('unmasked')[0];

					if (nDescont < -10) {
						dialogTab.modal('hide');
						bootbox.alert('O desconto negativo deve ser no m�ximo -10%!');
						$('#CK_DESCONT'+cItemAtu).val("");
						return false;	
					} 	
					
				}
				
				//Valida o valor m�ximo --retirado Lucilene 11.08.20
				//if ( lOK && nVlrUnit > nVlrTabela){ 
				//	dialogTab.modal('hide');
				//	bootbox.alert("O valor m�ximo permitido � o valor da tabela!");
				//	$("#iCK_PRCVEN"+cItemAtu).val($('#CK_PRCVEN'+cItemAtu).val());
				//	$("#iCK_PRCVEN"+cItemAtu).focus();
				//	lOK = false;
				//}
				
				//dialogTab.modal('hide');
					
				//Atualiza o valor dos impostos
				if (lOK && nDescont != 0){
					var cCodProd = $("#CK_PRODUTO"+cItemAtu).val();
					var cQuant = $("#CK_QTDVEN"+cItemAtu).val();
					//var dialogImp = bootbox.dialog({
				    //    message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Atualizando os valores dos impostos... Aguarde...</p>',
				    //    closeButton: false
			    	//	});
			    	nVlrUnit = nVlrTabela - (nVlrTabela * (nDescont/100))
					$.ajax({
						url: "U_GetImpostos.apw?PR=<%=cLCodLogin%>",
						data: 'produto='+encodeURIComponent(cCodProd)+'&prcvenda='+nVlrUnit+'&quantidade='+cQuant,
						type: "POST",
						async: false,
						error: function (jqXHR, textStatus, error){
						dialogTab.modal('hide');
						bootbox.alert("Falha ao atualizar o valor dos impostos!");
						console.log(error);
						lOK = false;
						 },
						 success: 
							function(data) {
								
								dialogTab.modal('hide');
								if (data.indexOf('<META HTTP-EQUIV') >= 0 ) {
									$("html").html(data);
									return;
								}
								
								if (data.substr(0, 2) == "OK") {
									aVlr = data.substr(3).split('|#|');
									$.trim($("input[name='CK_XVALICM"+cItemAtu+"']").val(aVlr[2]));
									$.trim($("input[name='CK_XICMST"+cItemAtu+"']").val(aVlr[4]));
									$.trim($("input[name='CK_XVALIPI"+cItemAtu+"']").val(aVlr[3]));
									$.trim($("#iCK_PRCVEN"+cItemAtu).val(mascaraValor(nVlrUnit.toFixed(2))));
									//Input hidden
									$("input[id='ALIQ_IPI"+cItemAtu+"']").val(aVlr[5]);
									$("input[id='ALIQ_ICMS"+cItemAtu+"']").val(aVlr[6]);
									$("input[id='ALIQ_ST"+cItemAtu+"']").val(aVlr[12]);
									$("input[id='CK_TES"+cItemAtu+"']").val(aVlr[8]);
									$("input[id='BASE_IPI"+cItemAtu+"']").val(aVlr[11]);
									$("input[id='BASE_ICMS"+cItemAtu+"']").val(aVlr[9]);
									$("input[id='BASE_ST"+cItemAtu+"']").val(aVlr[10]);
									$("input[id='VAL_ICMS"+cItemAtu+"']").val(aVlr[2]);
									$("input[id='VAL_ST"+cItemAtu+"']").val(aVlr[4]);
									$("input[id='VAL_IPI"+cItemAtu+"']").val(aVlr[3]);
								} else {			
									cMsgErro = "Houve falha ao atualizar os impostos. Tente novamente!"; 
									bootbox.alert(cMsgErro);
									LimpaLinha(cItemAtu);
									lOK = false;
									if (data.substr(0, 4) == "ERRO") {
										cMsgErro = data.substr(5);
									} else {
										// Quando ocorre erro no protheus	
										console.log(data);
									}
								}	
							}
					});
				}
				dialogTab.modal('hide');
				//Gatilho para total do item 
				if(lOK){
            		TotalItem(cItemAtu);
            	}
			}	
			
			
			
			/**
			Fun��o para anexar os documentos ao or�amento
			**/
			function OrcGetAnex() {
				$.ajax({  
					url: "U_OrcGetAn.apw?PR=<%=cLCodLogin%>",
					type: "POST",
					data: "fornece="+$("#fornece").val()+"&loja="+$("#loja").val(),
					cache: false, 
					success: function(html){    
						$("#InfAnexos").html(html);
							new PNotify({
								title: 'Anexar arquivo',
								text: 'Anexado com sucesso',
								type: 'success',
								icon: 'fa fa-file-o',
								cornerclass: 'ui-pnotify-sharp'
							});
						$("#arquivo").remove();
					}
				});
			}
			
			
			/**
			Funcao de valida��o do tipo de frete
			**/
			function VldFrete() {
				var cFrete;
				var tabpreco = $("#CJ_TABELA").val();

				cFrete = $("#CJ_TPFRETE").val();
				if (cFrete == 'C' || cFrete == 'F'){
					$("#CJ_FRETE").attr("required","");
					$("#CJ_FRETE").attr("aria-required","true"); 
					$("#CJ_FRETE").removeAttr('disabled');
					//$("#CJ_XTRANSP").removeAttr('disabled');
					$("#CJ_FRETE").focus();
					//$("#CJ_XTRANSP").val("");
					
					//Localiza a transportadora
					/*
					$.ajax({
						url: "U_GetTransp.apw?PR=<%=cLCodLogin%>",
						type: "POST",
						data: 'tabela='+tabpreco,
						async: false,
						success:
							function(transp) {
								if (transp.indexOf('<META HTTP-EQUIV') >= 0 ) {
									$("html").html(transp);
									return;
								}
								if ( transp != "" ) {
								 	//Preenche o campo da transportadora 
								 	document.getElementById('CJ_XTRANSP').innerText = null;
								 	$("#CJ_XTRANSP").append(transp);
								} else {
									bootbox.alert('Cliente sem transportadora cadastrada!');
									$("#CJ_TPFRETE").val("S")
									$("#select2-CJ_TPFRETE-container").html("Sem Frete")
									$("#CJ_FRETE").removeAttr("required");
									$("#CJ_FRETE").removeAttr("aria-required");
									$("#CJ_FRETE").attr("disabled","");
									$("#CJ_XTRANSP").attr("disabled","");
									$("#CJ_FRETE").val("0,00");
									$("#CJ_XTRANSP").val("");
									$("#select2-CJ_XTRANSP-container").html("Selecione uma Transportadora");
								
								}
							}	
					});
					*/
					 
					//$("#select2-CJ_XTRANSP-container").html("Selecione uma Transportadora"); 
				} 
				if (cFrete == 'S'){
					$("#CJ_FRETE").removeAttr("required");
					$("#CJ_FRETE").removeAttr("aria-required");
					$("#CJ_FRETE").attr("disabled","");
					//$("#CJ_XTRANSP").attr("disabled","");
					$("#CJ_FRETE").val("0,00");
					//$("#CJ_XTRANSP").val("");
					$("#select2-CJ_XTRANSP-container").html("Selecione uma Transportadora"); 
				}
				
				TotalGeral();
			}
			
			/**
			Valida��o do valor m�nimo de Frete
			**/
			function freteMinimo(objInput) {
				var valFre;
				var tipoFre;
				     
	            tipoFre = $("#CJ_TPFRETE").val();
	            valFre =  $("#CJ_FRETE").maskMoney('unmasked')[0];
			 	
			 	$.ajax({
					url: "U_FreteMinimo.apw?PR=<%=cLCodLogin%>",
					data: 'tipoFrete='+tipoFre,
					type: "POST",
					async: false,
					success:
						function(retorno) {
							if (retorno.indexOf('<META HTTP-EQUIV') >= 0 ) {
								$("html").html(retorno);
								return;
							}
							valMin = parseInt(retorno);
							if (tipoFre == 'C'){
								tipo = 'CIF';
							}
							else {
							 	tipo = 'FOB';
							}
							if (valFre < valMin ) {
								bootbox.alert('O valor m�nimo para frete do tipo '+tipo+' � R$'+retorno+'!');
								$("#CJ_FRETE").val(retorno);
								$("#CJ_FRETE").focus(); 
								$("#TOTAL_FRETE").val($("#CJ_FRETE").val());
								return false;
							}
							
							TotalGeral();
							
						}
				});
			}
			
			/**
			// Fun��o para ver detalhes da linha
			**/
			function detalheOrc(cItem){
			 	var msg = "";
			 	var produto = $("#CK_PRODUTO"+cItem);
				var retorno = "";
				var estoque = "";
				var dialogTab = "";

			 	if(produto.val() == ""){
			 		bootbox.alert("Selecione o produto para ver os detalhes!");
			 		return false;
			 	}
			 	
				/*
				dialogTab = bootbox.dialog({
			        message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Carregando detalhes... Aguarde...</p>',
			        closeButton: false
			    });
			    
				$.ajax({
					url: "U_GetEstGeral.apw?PR=<%=cLCodLogin%>",
					data: 'produto='+encodeURIComponent(produto.val()),
					type: "POST",
					async: false,
					success:
						function(retorno) {
							if (retorno.indexOf('<META HTTP-EQUIV') >= 0 ) {
								$("html").html(retorno);
								return;
							}
							estoque = retorno;
						}
				});
				dialogTab.modal('hide');
				*/
			 	msg = '<div class="row form-group">'
			 	msg +='	<header class="panel-heading">'
			 	msg +='		<h2 class="panel-title">Detalhes da linha</h2>'
			 	msg +='	</header>'
				msg +='	<br>'
				//Descri��o do produto 
				msg +='	<div class="row form-group">'				
				msg +='		<div class="col-lg-1"></div>'				
				msg +='		<div class="col-lg-11">'
				msg +='			<label class="control-label">Produto</label>'	              
				msg +=' 		<div class="input-group">'	
				msg +='				<input class="form-control text-left" style="width: 240%;" value="'+$("#CK_PRODUTO"+cItem).val().split('- ')[1]+'" disabled>'
				//msg +='				<input class="form-control text-left" style="width: 240%;" value="'+$(produto)[0].options[$(produto)[0].selectedIndex].text.split('- ')[1]+'" disabled>'
				msg +='			</div>'
				msg +='		</div>'
				msg +='	</div>'
				
				//% ICMS
				msg +='	<div class="row form-group">'
				msg +='		<div class="col-lg-1"></div>'				
				msg +='		<div class="col-lg-3">'
				msg +='			<label class="control-label">Aliquota ICMS</label>'	              
				msg +=' 		<div class="input-group">'	
				msg +='				<input class="form-control text-right" value="'+$("#ALIQ_ICMS"+cItem).val()+'%" disabled>'
				msg +='			</div>'
				msg +='		</div>'
				//% ICMS ST				
				msg +='		<div class="col-lg-3">'
				msg +='			<label class="control-label">Aliquota ICMS ST</label>'	              
				msg +=' 		<div class="input-group">'	
				msg +='				<input class="form-control text-right" value="'+$("#ALIQ_ST"+cItem).val()+'%" disabled>'
				msg +='			</div>'
				msg +='		</div>'
				msg +='	</div>'
				//IPI   
				msg +='	<div class="row form-group">'				
				msg +='		<div class="col-lg-1"></div>'				
				msg +='		<div class="col-lg-3">'
				msg +='			<label class="control-label">IPI</label>'	              
				msg +=' 		<div class="input-group">'	
				msg +='				<input class="form-control text-right" value="'+$("#VAL_IPI"+cItem).val()+'" disabled>'
				msg +='			</div>'
				msg +='		</div>'
				//ICMS				
				msg +='		<div class="col-lg-3">'
				msg +='			<label class="control-label">ICMS</label>'	              
				msg +=' 		<div class="input-group">'	
				msg +='				<input class="form-control text-right" value="'+$("#VAL_ICMS"+cItem).val()+'" disabled>'
				msg +='			</div>'
				msg +='		</div>'
				//ICMS ST				
				msg +='		<div class="col-lg-3">'
				msg +='			<label class="control-label">ICMS ST</label>'	              
				msg +=' 		<div class="input-group">'	
				msg +='				<input class="form-control text-right" value="'+$("#VAL_ST"+cItem).val()+'" disabled>'
				msg +='			</div>'
				msg +='		</div>'
				msg +='	</div>'
				msg +='</div>'
				
			 	if(msg != ""){
				 	bootbox.dialog({
					    title: '',
					    message: "<p>"+msg+"</p>",
					    backdrop: true,
					    buttons: {
					        ok: {
					            label: "OK"
					        }
					    }
					});
				}	
			}
			
			//Remover linha
			function removeItem(cItem){
		    	//e.preventDefault();
				//var btnRem = $(this);
				cItem = parseInt(cItem);
				
				bootbox.confirm({
			        title: "Exclus�o da linha",
			        message: "Confirma a exclus�o desta linha?",
			        buttons: {
			            cancel: {
			                label: 'Cancelar'
			            },
			            confirm: {
			                label: 'Confirmar'
			            }
			        },
			        callback: function (result) {
			            if (result){
							if (cItem < 10 ){cItem = "0"+String(cItem)};
							
							//Desabilita o bot�o
							//btnRem.attr({ 'disabled': 'disabled' });
							
							$("#CK_ITEM"+cItem).val("x");
							$("#CK_PRODUTO"+cItem).val("");
							$("#CK_QTDVEN"+cItem).val("1");
							$("#CK_LOCAL"+cItem).val("");
							$("#CK_PRUNIT"+cItem).val("0");
							$("#iCK_PRCVEN"+cItem).val("0,00");
							$("#CK_PRCVEN"+cItem).val("0,00");
							$("#CK_XVALICM"+cItem).val("0,00");
							$("#CK_XVALIPI"+cItem).val("0,00");
							$("#CK_XICMST"+cItem).val("0,00");
							$("#CK_VALOR"+cItem).val("0,00");
							$("#linha"+cItem).hide();
							
							//Atualiza o total geral
						    TotalGeral();
				    	}
			        }
			    });
		    }
			
			
			/**
			//Anexar
			**/
			$("#btnInfUpload").click(function() {
				var obAnexo = $("#anexo");
				var obArquivo = obAnexo.clone();
				
  					obArquivo.attr("id", "arquivo");
				
				$("#frmInfUpload").append(obArquivo);

				var data;
    				var contentType = "application/x-www-form-urlencoded";
    				var processData = true;
    				if ($('#frmInfUpload').attr('enctype') == 'multipart/form-data') {
        				data = new FormData($('#frmInfUpload').get(0));//seleciona classe form-horizontal adicionada na tag form do html
        				contentType = false;
        				processData = false;
    				} else {
        				data = $('#frmInfUpload').serialize();
    				}
    				$.ajax({
					data: data,
					type: $('#frmInfUpload').attr('method'),
					url: $('#frmInfUpload').attr('action'),
					contentType: contentType,
        				processData: processData,
        				success: function (response) {
            				//seu c�digo ap�s sucesso
						if( response == "Ok" ) {
							window.location.reload();
						} else {
							bootbox.alert('Erro ao carregar arquivo');
						} 
        				},
        				error: function (exr, sender) {
                			bootbox.alert('Erro ao carregar pagina');
        				}
    				});
			});
			
			//Adicionar nova linha
			$('#btAddItm').click(function(e) {
				e.preventDefault();
				var newLine = parseFloat($("#PROXIMO").val())+1;
				var nItens = parseFloat($("#PROXIMO").val());
				var linhaAtu = String(newLine);
				var lRet = true;
				var lGridOK = true;
				var btnAdd = $(this);
				var cCodProd;
				var cItmOrc;
				
				/*
				bootbox.confirm({
			        message: "Confirma a inclus�o de uma nova linha?",
			        buttons: {
			            confirm: {
			                label: 'Sim',
			                className: 'btn btn-primary'
			            },
			            cancel: {
			                label: 'N�o',
			                className: 'btn btn-default'
			            }
			        },
			        callback: function (result) {
			            if(result == true){
				         */   
							if (parseInt(linhaAtu) < 10 ){linhaAtu = "0"+String(linhaAtu)};
							
							//Desabilita o bot�o
							btnAdd.attr({ 'disabled': 'disabled' });
					 
							//Valida o Grid
							if (nItens == 99){
								lRet = false;
								
								$("#orc-informar").html();
									new PNotify({
										title: 'Quantidade m�xima',
										text: 'O or�amento atingiu a quantidade m�xima de itens. Crie um novo or�amento.',
										type: 'error',
									});      
								btnAdd.removeAttr('disabled');	
								return false;
							}		
					
							if (lRet == true) {
								for (i = 1; i<=nItens; i++) { 
									cItem = String(i);
									if (parseInt(i) < 10 ){cItem = "0"+String(i)};
									
									cCodProd = $("#CK_PRODUTO"+cItem).val();
									cItmOrc = $("#CK_ITEM"+cItem).val();
									if(cItmOrc != "x") { 
										if ($('#CK_PRODUTO'+cItem).val() == "" || $('#CK_QTDVEN'+cItem).val() == ""){
											lGridOK = false;	
										}
									}
								}
								    
								if (lGridOK == false){
									lRet = false;
									
									$("#orc-informar").html();
										new PNotify({
											title: 'Campo obrigat�rio',
											text: 'Verifique o preenchimento dos campos Produto e Quantidade antes de incluir uma nova linha!',
											type: 'error',
										});
									btnAdd.removeAttr('disabled');
									
									//For�a fechar a janela
									if (lRet == false){
										bootbox.hideAll();
									}		
									return false;	 
								}
							}
					
							//Cria a linha
			                if (lRet == true) {
								var tbl = document.getElementById('datatable-editable'), // table reference
							
					        	row = tbl.insertRow(tbl.rows.length),      // append table row
					        	i;
								
							    // insert table cells to the new row
							    for (i = 0; i < tbl.rows[0].cells.length; i++) {
							        createCell(row.insertCell(i),i,newLine,tbl.rows[0].cells.length-1);
							        //Adiciona os atributos da coluna
							        switch (i) {
									    //Quantidade
									   case 3:
									   	$('tr:last').find('td:last').attr('style','right');
									   break;
									   //Pre�o com impostos
									   case 7:
									   $('tr:last').find('td:last').attr('hidden','');
									   break;
									   //Pre�o
									   case 8:
									   $('tr:last').find('td:last').attr('hidden','');
									   break;
									   //IPI
									   case 9:
									   	$('tr:last').find('td:last').attr('hidden','');
									   break;
									   //ICMS
									   case 10:
									   	$('tr:last').find('td:last').attr('hidden','');
									   break;
									   //ICMS ST
									   case 11:
									   	$('tr:last').find('td:last').attr('hidden','');
									   break;
									   //% Desconto
									   case 12:
									   	$('tr:last').find('td:last').attr('hidden','');
									   break;
									   //% Comiss�o      
									   case 13:     
									   	$('tr:last').find('td:last').attr('hidden','');
									   break;
									   //valor comiss�o      
									   case 14:     
									   	$('tr:last').find('td:last').attr('hidden','');
									   break;
									   //pedido cliente
									   case 15:
									   $('tr:last').find('td:last').attr('style','right');
									   break;
									   //item do pedido cliente
									   case 16:
									   	$('tr:last').find('td:last').attr('style','right');
									   break;
									   
									   //TOTAL
									   case 17: 
									   	$('tr:last').find('td:last').attr('style','right');
									   break;
									}   
							    }

								// Adiciona um ouvinte de eventos usando a delega��o de eventos
								$(document).on('focusout', '[data-row] input', function () {
									// Captura o valor do campo CK_PRODUTO
									var produtoDigitado = this.value;

									// Obt�m o numero da linha associado ao campo
									var linhaAtu = $(this).data('row');

									// Chama a fun��o buscarProdutos
									buscarProdutos(produtoDigitado, function (listaProdutos) {
										// Aqui voce pode fazer algo com a lista de produtos, se necessario
									});
								});

							    //Adiciona a classe no ultimo td
								$('tr:last').find('td:last').addClass('actions');
						         
						        //Adiciona id na linha
						     	$('tr:last').attr('id','linha'+linhaAtu);
						     	$('tr:last').attr('class','odd');
						     	    
								//Atualiza a quantidade de linhas
								$("#PROXIMO").val(linhaAtu);
							
								//Habilita o bot�o para adicionar itens
								btnAdd.removeAttr('disabled'); 
								formate();
							};
/*
						};
					}
			    });
*/			  
			});
			
			// create DIV element and append to the table cell
			function createCell(cell,col,newLine,tam) {
   				var linha = String(newLine);
				
				if (parseInt(linha) < 10 ){linha = "0"+String(linha)}; 
			   	
			   	switch (col) {
				   //Item
					case 0:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_ITEM'+linha);
				     campo.setAttribute('name', 'CK_ITEM'+linha);
				   	 campo.setAttribute('class', 'form-control text-left input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('value', linha);
				   	 campo.setAttribute('type', 'text');
					break;

				   //Codigo de barras
					case 1:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_XCODBAR'+linha);
				     campo.setAttribute('name', 'CK_XCODBAR'+linha);
				   	 campo.setAttribute('class', 'form-control text-left input-block'); 
				   	 campo.setAttribute('value', '');
				   	 campo.setAttribute('type', 'text');
				   	 campo.setAttribute('onblur', 'javascript:GetProdCB("'+linha+'")');
					break;	

				   //Select do produto
				   case 2:
				      campo = document.createElement('select');
				      campo.setAttribute('class', 'selectpicker');
				      campo.setAttribute('data-live-search', 'true');
				      campo.setAttribute('data-width','300px');
				      campo.setAttribute('id', 'CK_PRODUTO'+linha);
				      campo.setAttribute('name', 'CK_PRODUTO'+linha);
				      campo.setAttribute('required','')
				      campo.setAttribute('aria-required','true')
				      campo.setAttribute('value','')
				      campo.setAttribute('onchange', 'javascript:gatProduto($(this))'); 
				      $(campo).append($.parseHTML('<option value="">Selecione...</option>'+optProd));
				      break;					
				 
				   //Quantidade
				   case 3:
				   	campo = document.createElement('input'); 
				   	campo.setAttribute('id', 'CK_QTDVEN'+linha);
				    campo.setAttribute('name', 'CK_QTDVEN'+linha);
				   	campo.setAttribute('class', 'form-control text-right only-numbers');
				   	campo.setAttribute('disabled', 'disable'); 
				   	campo.setAttribute('type', 'text');
				   	campo.setAttribute('value', ''); 
				   	campo.setAttribute('placeholder', '0'); 
				   	campo.setAttribute('onblur', 'javascript:VldQtd("'+linha+'")'); 
				   	campo.setAttribute('onkeyup', 'javascript:TotalItem("'+linha+'")'); 
				   	campo.setAttribute('required', ''); 
				   	campo.setAttribute('aria-required', 'true'); 
				   break;
				   
				   //Local
				   case 4:
				   	campo = document.createElement('input'); 
				   	campo.setAttribute('id', 'CK_LOCAL'+linha);
				    campo.setAttribute('name', 'CK_LOCAL'+linha);
				   	campo.setAttribute('class', 'form-control text-right input-block');
				   	campo.setAttribute('disabled', 'disable');  
				   	campo.setAttribute('value', '');
				   	campo.setAttribute('type', 'text');  
				    break;

					//Estoque Dispon�vel
				    case 5:
				   	campo = document.createElement('input'); 
				   	campo.setAttribute('id', 'EST_DISP'+linha);
				    campo.setAttribute('name', 'EST_DISP'+linha);
				   	campo.setAttribute('class', 'form-control text-right input-block');
				   	campo.setAttribute('disabled', 'disable');  
				   	campo.setAttribute('value', '0');
				   	campo.setAttribute('type', 'text');  
				    break;

				   	//Pre�o de tabela
					case 6:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_PRCVEN'+linha);
				     campo.setAttribute('name', 'CK_PRCVEN'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 //campo.setAttribute('type', 'text');
				   	 campo.setAttribute('value', '');
					break;
				     
				 	//Pre�o unit�rio com impostos
					case 7:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_XPRCIMP'+linha);
				     campo.setAttribute('name', 'CK_XPRCIMP'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('value', '');
					break;
				   
				   //Pre�o de venda 
				   case 8:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'iCK_PRCVEN'+linha);
				     campo.setAttribute('name', 'iCK_PRCVEN'+linha);
				   	 campo.setAttribute('class', 'form-control text-right myformato'); //money5
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('type', 'text');
				   	 campo.setAttribute('value', '');
				   	 campo.setAttribute('placeholder', '0,00');
				   	 campo.setAttribute('onblur', 'javascript:VldValor("'+linha+'")');
				   	 campo.setAttribute('onkeyup', 'javascript:TotalItem("'+linha+'")');
//				   	 campo.setAttribute('onKeyPress', 'FormataValor(this,28,event,2,".",",")');
//				   	 campo.setAttribute('onKeyPress', 'return(moeda(this,'+"'.'"+','+"','"+',event))');
					break;
				   
					//IPI
					case 9:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_XVALIPI'+linha);
				     campo.setAttribute('name', 'CK_XVALIPI'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('value', '');
				   	 campo.setAttribute('type', 'text');
					break;
				     
					//ICMS
					case 10:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_XVALICM'+linha);
				     campo.setAttribute('name', 'CK_XVALICM'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('value', '');
				   	 campo.setAttribute('type', 'text');
					break;
					
					//ICMS ST
					case 11:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_XICMST'+linha);
				     campo.setAttribute('name', 'CK_XICMST'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('value', '');  
				   	 campo.setAttribute('type', 'text');
					break;    
				     
				    //% de desconto
					case 12:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_DESCONT'+linha);
				     campo.setAttribute('name', 'CK_DESCONT'+linha);
				   	 campo.setAttribute('class', 'form-control text-right percentual');
				   	 campo.setAttribute('value', '');  
				   	 campo.setAttribute('type', 'text'); 
				   	 campo.setAttribute('maxlength', '7'); 
				   	 campo.setAttribute('placeholder', '0,00'); 
				   	 campo.setAttribute('disabled', 'disable');
				   	 campo.setAttribute('onblur', 'javascript:VldValor("'+linha+'")');
					 campo.setAttribute('onkeyup', 'javascript:TotalItem("'+linha+'")'); 		   	 
					break;  
					
				    //% de comiss�o
					case 13:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'PER_COM'+linha);
				     campo.setAttribute('name', 'PERCOM'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('value', '');  
				   	 campo.setAttribute('type', 'text');
					break; 
					
					//Valor de comiss�o
					case 14:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'VAL_COM'+linha);
				     campo.setAttribute('name', 'VAL_COM'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('type', 'text');
				   	 campo.setAttribute('value', '');  
					break; 
					
					
					//Pedido cliente
				    case 15:
				   	campo = document.createElement('input'); 
				   	campo.setAttribute('id', 'CK_XPEDCLI'+linha);
				    campo.setAttribute('name', 'CK_XPEDCLI'+linha);
				   	campo.setAttribute('class', 'form-control text-right input-block');
				   	campo.setAttribute('disabled', 'disable');  
				   	campo.setAttribute('value', '');
				   	campo.setAttribute('maxlength', '10'); 
				   	campo.setAttribute('type', 'text');  
				    break;
				    
				    //Item Pedido cliente
				    case 16:
				   	campo = document.createElement('input'); 
				   	campo.setAttribute('id', 'CK_XITEMCL'+linha);
				    campo.setAttribute('name', 'CK_XITEMCL'+linha);
				   	campo.setAttribute('class', 'form-control text-right input-block');
				   	campo.setAttribute('disabled', 'disable');  
				   	campo.setAttribute('value', '');
				   	campo.setAttribute('maxlength', '4'); 
				   	campo.setAttribute('type', 'text');  
				    break;
					
					//TOTAL
					case 17:
	 			     campo = document.createElement('input'); 
				 	 campo.setAttribute('id', 'CK_VALOR'+linha);
				     campo.setAttribute('name', 'CK_VALOR'+linha);
				   	 campo.setAttribute('class', 'form-control text-right input-block');
				   	 campo.setAttribute('disabled', 'disable'); 
				   	 campo.setAttribute('type', 'text');
				   	 campo.setAttribute('value', '');
					break;
			  
				   //A��es  
				   case 18:
				   	  //Detalhes da linha
				      campo = document.createElement('i');
				      campo.setAttribute('class', 'fa fa-info fa-lg');    
				      campo.setAttribute('Title', 'Detalhes da linha');
				      campo.setAttribute('onclick', 'detalheOrc('+"'"+linha+"'"+')');
				      cell.appendChild(campo);
					  
				      //Remover linha
				      campo = document.createElement('i');
				      campo.setAttribute('class', 'fa fa-times-circle fa-lg');    
				      campo.setAttribute('Title', 'Remover linha');
				      campo.setAttribute('onclick', 'removeItem('+"'"+linha+"'"+')');
				      break;                                                         
				      
				   //Input Padr�o     
				   default:
				   	campo = document.createElement('input'); 
				   	campo.setAttribute('class', 'form-control input-block');
				   	campo.setAttribute('disabled', 'disable');    
				}
				cell.appendChild(campo); // apenda o campo na celula da tabela
			   	
				
			   	//Adiciona as vari�veis hidden
			   	if (col == tam){  
			   	    $('.selectpicker').selectpicker('render');
			   	    //$('.selectpicker').selectpicker('refresh');
			   		campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'VAL_DESC'+linha);
				    campo.setAttribute('name', 'VAL_DESC'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);
			   	
			   		campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'ALIQ_ICMS'+linha);
				    campo.setAttribute('name', 'ALIQ_ICMS'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);

			   		campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'ALIQ_IPI'+linha);
				    campo.setAttribute('name', 'ALIQ_IPI'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);
			   					   	
			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'ALIQ_ST'+linha);
				    campo.setAttribute('name', 'ALIQ_ST'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);
			   		
			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'VAL_ICMS'+linha);
				    campo.setAttribute('name', 'VAL_ICMS'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);			   		

			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'VAL_IPI'+linha);
				    campo.setAttribute('name', 'VAL_IPI'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);			   		

			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'VAL_ST'+linha);
				    campo.setAttribute('name', 'VAL_ST'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);			   		

			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'BASE_ICMS'+linha);
				    campo.setAttribute('name', 'BASE_ICMS'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);
			   		
			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'BASE_ST'+linha);
				    campo.setAttribute('name', 'BASE_ST'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);			   		
			   		
			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'BASE_IPI'+linha);
				    campo.setAttribute('name', 'BASE_IPI'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);

			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'QTD_EMB'+linha);
				    campo.setAttribute('name', 'QTD_EMB'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);			   		
			   		
			   	 	campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'CK_TES'+linha);
				    campo.setAttribute('name', 'CK_TES'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);

					
					campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'QTDMIN'+linha);
				    campo.setAttribute('name', 'QTDMIN'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);

					campo = document.createElement('input'); 
				 	campo.setAttribute('id', 'PROMOCAO'+linha);
				    campo.setAttribute('name', 'PROMOCAO'+linha); 
				   	campo.setAttribute('type', 'hidden');
				   	campo.setAttribute('value', '0');
			   		cell.appendChild(campo);
			   	} 
			}
		    
		    //Salvar o or�amento
			$('#btSalvar').click(function() {
				var lRet = true
				var i = 0;
				var nItens = parseFloat($("#PROXIMO").val());
				var lGrid = true;
				var lGrid1 = true;
				var cCodProd;
				var cItmOrc;
				var btnSlv = $(this);     
				var cGrupo = "";
				var dialogOrc = bootbox.dialog({
			        message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Validando or�amento. Aguarde...</p>',
			        closeButton: false
			    });
				//Desabilita o bot�o
				btnSlv.attr({ 'disabled': 'disabled' });
				
				$.ajax({
					url: "U_VerSessao.apw?PR=<%=cLCodLogin%>",
					type: "POST",
					async: false,
					success:
						function(retorno) {
							if (retorno.indexOf('<META HTTP-EQUIV') >= 0 ) {
								$("html").html(retorno);
								return;
							}
							if (retorno == "nok"||retorno == ''||retorno.indexOf("Expires") != -1){
								$("#orc-informar").html();
								bootbox.alert('N�o foi poss�vel realizar a opera��o pois a sess�o foi fechada. Fa�a login novamente.');
								lRet = false;                 
								btnSlv.removeAttr('disabled');
								dialogOrc.modal('hide');
							}
						}	
				});
						
                /**    
				Valida os campos obrigatorios
				**/
				//Cliente
				if ($("#CJ_CLIENTE").val() == "") {
					lRet = false;
					
					$("#orc-informar").html();
						new PNotify({
							title: 'Campo obrigat�rio',
							text: 'Preencha o campo Cliente!',
							type: 'error',
						});                  
					btnSlv.removeAttr('disabled');
					dialogOrc.modal('hide');	
					$("#CJ_CLIENTE").focus();
				}
                
                //Tabela de pre�o
				if (lRet == true && $("#CJ_TABELA").val() == "") {
					lRet = false;
					
					$("#orc-informar").html();
						new PNotify({
							title: 'Campo obrigat�rio',
							text: 'Preencha o campo Tabela de Pre�o!',
							type: 'error',
						});                  
					btnSlv.removeAttr('disabled');
					dialogOrc.modal('hide');	
					$("#CJ_TABELA").focus();
				}
				
				//Data de Entrega
				/*
				if (lRet == true && $("#CK_ENTREG").val() == "") {
					lRet = false;
					
					$("#orc-informar").html();
						new PNotify({
							title: 'Campo obrigat�rio',
							text: 'Preencha o campo Previs�o de Faturamento!',
							type: 'error',
						});                  
					btnSlv.removeAttr('disabled');
					dialogOrc.modal('hide');	
					$("#CK_ENTREGA").focus();
				}
				*/
				
				//Condi��o de pagamento 
				if (lRet == true && $("#CJ_CONDPAG").val() == "") {
					lRet = false;
					
					$("#orc-informar").html();
						new PNotify({
							title: 'Campo obrigat�rio',
							text: 'Preencha o campo Condi��o de Pagamento!',
							type: 'error',
						});                  
					btnSlv.removeAttr('disabled');	
					dialogOrc.modal('hide');
					$("#CJ_CONDPAG").focus();
				}
				
				//cart�o de cr�dito
				if (lRet == true & $("#CJ_XMODALI").val() == "03") {
					/*
					if ($("#CJ_XPARC").val() == ""|| $("#CJ_XPARC").val() == "0") {
						lRet = false;
					
						$("#orc-informar").html();
							new PNotify({
								title: 'Campo obrigat�rio',
								text: 'Preencha o campo Parcela!',
								type: 'error',
							});                  
						btnSlv.removeAttr('disabled');
						dialogOrc.modal('hide');	
						$("#CJ_XPARC").focus();	
					} else {
						if ($("#CJ_XBAND").val() == ""){
							lRet = false;
					
							$("#orc-informar").html();
								new PNotify({
									title: 'Campo obrigat�rio',
									text: 'Preencha o campo Bandeira!',
									type: 'error',
								});                  
							btnSlv.removeAttr('disabled');
							dialogOrc.modal('hide');	
							$("#CJ_XBAND").focus();	
						}
					}*/
				} 
				if (lRet == true && $("#CJ_CONDPAG").val() != "") {
					var totalorc = $("#TOTAL_ORC").val();
					var valMin = 0;
					
					$.ajax({
						url: "U_ValMinParc.apw?PR=<%=cLCodLogin%>",
						data: 'condPgto='+$("#CJ_CONDPAG").val()+'&valor='+$("#TOTAL_ORC").val(),
						type: "POST",
						async: false,
						success:
							function(retorno) {
								valMin = parseFloat(retorno);
								if (valMin > 0) {
									bootbox.alert('Para a condi��o de pagamento escolhida o valor m�nimo permitido por parcela � de R$'+mascaraValor(valMin.toFixed(2))+'.');
									lRet = false;
									btnSlv.removeAttr('disabled');
									dialogOrc.modal('hide');
								} 
							}
					});
				}
				
				//Transportadora e frete
				if (lRet == true && ($("#CJ_TPFRETE").val() == "C" || $("#CJ_TPFRETE").val() == "F")) {
					if ($("#CJ_XTRANSP").val() == ""){
						lRet = false;
						
						$("#orc-informar").html();
							new PNotify({
								title: 'Campo obrigat�rio',
								text: 'Para frete tipo CIF e FOB deve ser informada a Transportadora!',
								type: 'error',
							});                  
						btnSlv.removeAttr('disabled');
						dialogOrc.modal('hide');	
						$("#CJ_XTRANSP").focus();
					}
				}
				
				//S�rie da nota para Or�amento Firme
				if (lRet == true && $("#CJ_XTPORC").val() == "1" && $("#CJ_XSERIEN").val() == "") {
					lRet = false;
					
					$("#orc-informar").html();
						new PNotify({
							title: 'Campo obrigat�rio',
							text: 'Preencha o campo S�rie!',
							type: 'error',
						});                  
					btnSlv.removeAttr('disabled');
					dialogOrc.modal('hide');	
					$("#CJ_XSERIEN").focus();
				}

				//Grid
				if (lRet == true) {
					for (i = 1; i<=nItens; i++) { 
						cItem = String(i);
						if (parseInt(i) < 10 ){cItem = "0"+String(i)};
						
						cCodProd = $("#CK_PRODUTO"+cItem).val();
						cItmOrc = $("#CK_ITEM"+cItem).val();
						if(cItmOrc != "x") {
							//Valida o preenchimento dos campos produto e quantidade  
							if ($('#CK_PRODUTO'+cItem).val() == "" || $('#CK_QTDVEN'+cItem).val() == ""){
								lGrid = false;	
							} 
							//Valida o preenchimento do pedido e item
							pedCli = $('#CK_XPEDCLI'+cItem).val();
							itmCli = $('#CK_XITEMCL'+cItem).val();
							if ((pedCli != "" && itmCli == "") || (pedCli == "" && itmCli != "")){
								lGrid1 = false;
							}
							
							//Valida o estoque no or�amento firme
							if( $('#CJ_XTPORC').val() == "1"){
								if(vldEstoque(cItem) == false){
									lRet = false;
									btnSlv.removeAttr('disabled');
									dialogOrc.modal('hide');
								}
							}
						}
					}
					   
					if (lGrid == false){
						lRet = false;
						
						$("#orc-informar").html();
							new PNotify({
								title: 'Campo obrigat�rio',
								text: 'Verifique o preenchimento dos campos Produto e Quantidade!',
								type: 'error',
							});
						btnSlv.removeAttr('disabled');
						dialogOrc.modal('hide');	 
					}
					
					
					if (lGrid1 == false){
						lRet = false;
						
						$("#orc-informar").html();
							new PNotify({
								title: 'Pedido / Item Cliente',
								text: 'Se informado o item ou o pedido do cliente, os dois campos devem ser preenchidos!',
								type: 'error',
							});
						btnSlv.removeAttr('disabled');
						dialogOrc.modal('hide');	 
					}  
				}
				
				
				//Valida a condi��o de pagamento
				if (lRet == true){
					dialogOrc.modal('hide');
					//Chama a valida��o do limite e submete o formul�rio
					vldOrc(btnSlv);
				
					// $.ajax({
					// 	url: "U_VldAcresc.apw?PR=<%=cLCodLogin%>",
					// 	data: 'condicao='+$("#CJ_CONDPAG").val()+'&valor='+$("#TOTAL_ORC").val()+'&modalidade='+$("#CJ_XMODALI").val()+'&grupos='+$('#GRUPOS').val()+
					// 	        '&cliente='+$("#CJ_CLIENTE").val(),
					// 	type: "POST",
					// 	async: false,
					// 	success:
					// 		function(retorno) {
					// 			if (retorno.indexOf('<META HTTP-EQUIV') >= 0 ) {
					// 				$("html").html(retorno);
					// 				return;
					// 			}
							
					// 			aRet = retorno.split('|');
					// 			cAcresc = aRet[0];
					// 			nAcresc = parseFloat(aRet[1]);
							
							
					// 			if (nAcresc > 0 ) {
					// 				bootbox.confirm({
					// 					title: "Pedido abaixo do m�nimo",
					// 					message: 'Pedido abaixo do valor m�nimo, ser� aplicado acr�scimo de '+cAcresc+'%. Deseja continuar?',
					// 					buttons: {
					// 			            cancel: {
					// 			                label: 'N�o'
					// 			            },
					// 			            confirm: {
					// 			                label: 'Sim'
					// 			            }
					// 			        },
					// 					callback: function (result) {
					// 			        	if(result){ 
					// 			        		//Atualiza a vari�vel
			        //     						$("#ACRESCIMO").val((nAcresc * -1).toString());
								        		
					// 			        		//Chama a valida��o do limite e submete o formul�rio
					// 			        		vldOrc(btnSlv);
					// 			        	}
					// 			        	else {		
					// 							btnSlv.removeAttr('disabled');
					// 						}
					// 			        }
					// 				});
					// 			} else {
					// 				//Chama a valida��o do limite e submete o formul�rio
					// 			 	vldOrc(btnSlv);
					// 			}
					// 		}
					// });					
				}		
			})	

			$('#btExcluir').click(function() {
				var lRet = true
				var i = 0;
				var lGrid = true;
				var cCodProd;
				var btnSlv = $(this);
				
				//Desabilita o bot�o
				$('#btExcluir').attr({ 'disabled': 'disabled' });
					
				objDados = {
					CJ_CLIENTE:  $('#CJ_CLIENTE').val(),
					CJ_NUM: $('#CJ_NUM').val()
					};
                    
				$.ajax({
					type: "POST",
					    url: "U_ExcOrc.apw?PR=<%=cLCodLogin%>",
					    async: false,
					    data: objDados
					    
					}).fail(function(){                                                                                                                 
					    bootbox.alert({
					        title: "Exclus�o de Or�amento",
					        message: "N�o foi poss�vel excluir o or�amento.",
					        backdrop: true,
					        callback: function (result) {
					         	btnSlv.removeAttr('disabled');   
					        }
					    });
					}).done(function(strXml) {
						if (strXml.indexOf('<META HTTP-EQUIV') >= 0 ) {
							$("html").html(strXml);
							return;
						}
				        bootbox.alert({
					        title: "Exclus�o de Or�amento",
					        message: "O or�amento "+$('#CJ_NUM').val()+" foi exclu�do com sucesso.",
					        backdrop: true,
					        callback: function (result) {
					         	document.location.href = "U_Orcamento.apw?PR=<%=cLCodLogin%>";   
					        }
					    });
				});
			})	
			
			//Valida��o do valor do frete
 			function vldOrc(btnSlv){
				vldOrc1(btnSlv);
				/*
				var tipoFre = $('#CJ_TPFRETE').val();
				var total	= $("#TOTAL_ITENS").maskMoney('unmasked')[0];
				var valMin = 0;
				
				if (tipoFre == "C") {
                    $.ajax({
					url: "U_FreteMinimo.apw?PR=<%=cLCodLogin%>",
					data: 'tipoFrete='+tipoFre,
					type: "POST",
					async: false,
					success:
						function(retorno) {
							if (retorno.indexOf('<META HTTP-EQUIV') >= 0 ) {
								$("html").html(retorno);
								return;
							}
							valMin = parseInt(retorno);
							
							if (total < valMin ) {
								bootbox.alert('O valor m�nimo de or�amento para frete do tipo CIF � R$'+retorno+'!');
								btnSlv.removeAttr('disabled');
								return false;
							} else {
								vldOrc1(btnSlv);	
							}
							
							
							
						}
					});
				} else {
					vldOrc1(btnSlv);
				}*/
			}
			
           	//Se or�amento firme e boleto, valida o limite de cr�dito dispon�vel
 			function vldOrc1(btnSlv){
 				if ( ($('#CJ_XTPORC').val() == "1") && ($('#CJ_XMODALI').val() == '01' || $('#CJ_XMODALI').val() == '06') ){ 
					var cliente = $("#CJ_CLIENTE").val();
					var total	= $("#TOTAL_ITENS").maskMoney('unmasked')[0];
					var limDisp	= 0;
					lRet = false;
					
					$.ajax({
						url: "U_GetLimCred.apw?PR=<%=cLCodLogin%>",
						data: 'cliente='+cliente+'&valor='+total, 
						cache: false, 
						type: "POST",
						async: false,
						success:
							function(retorno) {
								if (retorno.indexOf('<META HTTP-EQUIV') >= 0 ) {
									$("html").html(retorno);
									return;
								}
								// Retorno limiteDisponivel|limiteTolerancia
								var aRet = retorno.split('|');
								var limDisp = 0.00;
								var limTol  = 0.00;
								// Pega o limite de tolerancia
								if ( aRet.length > 1 ) {
									limTol= parseFloat(aRet[1]);
								}
								// Pega o limite disponivel
								if ( aRet.length > 0 ) {
									limDisp= parseFloat(aRet[0]);
								}
															
								if (total > (limTol+limDisp) ) {
						
									bootbox.alert({
										title: 'Limite de cr�dito insuficiente',
								        message: 'N�o � poss�vel salvar o or�amento.<br> Saldo dispon�vel: R$'+mascaraValor(limDisp.toFixed(2))+'.<br>Este cliente s� pode realizar compras � vista.',    //mascaraValor(limDisp.toFixed(2))
										callback: function () {
											btnSlv.removeAttr('disabled');
								  			//salvarOrc(btnSlv);
								        } 
								    });       
					
					
								} else {
								 	salvarOrc(btnSlv);
								}
								
							}
					});
				} else {
					salvarOrc(btnSlv);
				}
 			}
			
			//Submete formulario
			function salvarOrc(btnSlv){
				var numorc = "";
			
				//if (lRet == true){
					//$("#formOrc").submit();
					var dialogSlv = bootbox.dialog({
				        message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i>&nbsp;&nbsp;Salvando or�amento... Aguarde...</p>',
				        closeButton: false
				    }); 
					
					//busca os itens cadastrados
					var ITENS = ""; 
					var i = 0;
					var nItens = parseFloat($("#PROXIMO").val());
					var cCodProd;
					var cItmOrc;
					var cDescAcresc = "0";
					
					for (i = 1; i<=nItens; i++) { 
						cItem = String(i);
						if (parseInt(i) < 10 ){cItem = "0"+String(i)};
						
						cCodProd = $("#CK_PRODUTO"+cItem).val();
						cItmOrc = $("#CK_ITEM"+cItem).val();
						if(cItmOrc != "x") {
							cPrcVen = $('#CK_PRCVEN'+cItem).val(); 
							nDesc = $('#CK_DESCONT'+cItem).val();
							// let cPrcVen = $('#iCK_PRCVEN'+cItem).val();
							// // Se desconto negativo --> salva o preco de tabela original
							// if ($('#CK_DESCONT'+cItem).val().substr(0,1) == "-") {
							// 	cPrcVen = $('#CK_PRCVEN'+cItem).val();
							// }

							//Tratativa para salvar o desconto correto.
							if($("#OPCAO").val() == "3"){

								nDesc = 0;
								nVlrVenda = $("#CK_PRCVEN"+cItem).maskMoney('unmasked')[0];
								nVlrOri = $("#CK_PRCVEN"+cItem).maskMoney('unmasked')[0];
							}

							ITENS+= $('#CK_PRODUTO'+cItem).val()+';'+$('#CK_QTDVEN'+cItem).val()+';'+cPrcVen+';'+$('#CK_LOCAL'+cItem).val()+';';
							ITENS+= $('#CK_XVALIPI'+cItem).val()+';'+$('#CK_XVALICM'+cItem).val()+';'+$('#CK_XICMST'+cItem).val()+';'+$('#CK_TES'+cItem).val()+';';
							ITENS+= $('#PER_COM'+cItem).val()+';'+$('#ALIQ_ICMS'+cItem).val()+';'+$('#ALIQ_IPI'+cItem).val()+';'+$('#ALIQ_ST'+cItem).val()+';';
							ITENS+= nDesc+';'+$('#CK_XPEDCLI'+cItem).val()+';'+$('#CK_XITEMCL'+cItem).val()+';';
							ITENS+= $('#CK_XPRCIMP'+cItem).val()+';'+$('#CK_XCODBAR'+cItem).val()+'||'
						}
					}
					
				



					objDados = {
					    CJ_CLIENTE:  $('#CJ_CLIENTE').val(),
					    CJ_TABELA: $('#CJ_TABELA').val(),
					    CJ_VEND: $('#CJ_VEND').val(),
					    CJ_XTPORC: $('#CJ_XTPORC').val(),
					    CJ_TPFRETE: $('#CJ_TPFRETE').val(),
					    CJ_FRETE: $('#CJ_FRETE').val(),
					    CJ_XTRANSP: $('#CJ_XTRANSP').val(),
					    
				      	CJ_XMODALI: $('#CJ_XMODALI').val(),
				      	CJ_CONDPAG: $('#CJ_CONDPAG').val(),
						CJ_DESC1: $("#DESCCOND").val(),
					    CJ_VALIDA: $('#CJ_VALIDA').val(), 
					    CJ_XSERIEN: $('#CJ_XSERIEN').val(), 											    
					    CJ_XPESO: $('#CJ_XPESO').val(), 					    
					    CJ_XVOLUME: $('#CJ_XVOLUME').val(), 					    
					    CJ_XESPECI: $('#CJ_XESPECI').val(), 					    
					    CK_ENTREG: $('#CK_ENTREG').val(),
					   
			
					    CJ_XNOTAIN: $('#CJ_XNOTAIN').val(),
					    CJ_XMSGNF: $('#CJ_XMSGNF').val(),
					    CJ_XPARC: $('#CJ_XPARC').val(),
					    CJ_XBAND: $('#CJ_XBAND').val(),
					    CJ_NUM: $('#CJ_NUM').val(),
					    PROXIMO: $('#PROXIMO').val(), 
					    OPCAO: $('#OPCAO').val(), 
					    aItens: ITENS
					};
                    
                    
                    if($("#OPCAO").val() == "3"){
			    		msg = "O or�amento foi inclu�do com sucesso.";
			    		titulo = "Inclus�o de Or�amento";
			    		operacao = "incluir";            
			    	}
			    	if($("#OPCAO").val() == "4"){
			    		msg = "O or�amento foi alterado com sucesso.";
			    		titulo = "Altera��o de Or�amento";
			    		operacao = "alterar";
			    	}
			    	if($("#OPCAO").val() == "5"){
			    		msg = "O or�amento foi exclu�do com sucesso.";
			    		titulo = "Exclus�o de Or�amento";
			    		operacao = "excluir";
			    	}
                    
                    
					$.ajax({
					    type: "POST",
					    url: "U_SlvOrc.apw?PR=<%=cLCodLogin%>",
					    async: false,
					    data: objDados
					    
					}).fail(function(){                                                                                                                 
					    bootbox.alert({
					        title: titulo,
					        message: "N�o foi poss�vel "+operacao+" o or�amento.",
					        backdrop: true,
					        callback: function (result) {
					         	btnSlv.removeAttr('disabled');
					         	dialogSlv.modal('hide');   
					        }
					    });
					}).done(function(strXml) {
						if (strXml.indexOf('<META HTTP-EQUIV') >= 0 ) {
							$("html").html(strXml);
							return;
						}
					    if (strXml == 'erro'||strXml == ''||strXml.indexOf("Expires") != -1||strXml.indexOf("invalid") != -1){
					        if (strXml == ''){
					        	 bootbox.alert({
							        title: titulo,
							        message: "Aguarde o prazo de 3 minutos para "+operacao+" um  novo or�amento.",
							        backdrop: true,
							        callback: function (result) {
							         	btnSlv.removeAttr('disabled');
							         	dialogSlv.modal('hide');   
							        }
							    });
					        }else{
						        bootbox.alert({
							        title: titulo,
							        message: "Falha ao "+operacao+" o or�amento.",
							        backdrop: true,
							        callback: function (result) {
							         	btnSlv.removeAttr('disabled');
							         	dialogSlv.modal('hide');   
							        }
							    });
							}
						}    
					    else {
						    if($("#OPCAO").val() == "3"){     
					    		numorc = " Foi gerado o or�amento n� "+strXml+"."
					    	}
					        bootbox.alert({
						        title: titulo,
						        message: msg+numorc,
						        backdrop: true,
						        callback: function (result) {
						         	document.location.href = "U_Orcamento.apw?PR=<%=cLCodLogin%>"; 
						         	dialogSlv.modal('hide');  
						        }
						    });
					        
					    }
					});
					  
				//};
						
			}
		</script> 
	</body>
</html>