<?php use_helper( 'UrlFunctions' ); ?>
<?php use_helper( 'IncludePartial' ); ?>
<?php use_helper( 'UtilFunctions' ); ?>
<style type="text/css">
.ui-dialog .ui-dialog-titlebar-close
{
    position: absolute;
    right: .3em;
    top: 50%;
    width: 20px;
    margin: -10px 0 0 0;
    padding: 1px;
    height: 20px;
    background-position: -96px -128px;
    /*background-image: url("images/ui-icons_056b93_256x240.png");*/
    background-image: url("<?=Constantes::ROOT_DIR_APP?>web/css/jquery/themes/start_1.12.1/images/ui-icons_056b93_256x240.png");
}
</style>
<style>
  .ui-autocomplete-loading { background: white url("<?php echo Constantes::ROOT_DIR_IMG ?>common/progress.gif") right center no-repeat; }
</style>
<style>
.header { background-color: #E1E1E1; color: #444444; font-family: Arial,Helvetica,sans-serif; font-size: 11px; font-weight: bold; }
.pager { background-color: #F4F4F4; background-image: none; border-bottom: thin solid #999999; }
</style>
<style type="text/css">
.marcoTabActive {
  /*background:#F1F1F1 none repeat scroll 0 0;*/
  background:#A3C1E0 none repeat scroll 0 0;  font-family:Geneva, Arial, Helvetica, sans-serif;  font-size:14px;  border-top-width: 1px;
  border-right-width: 1px;  border-left-width: 1px;  border-top-style: solid;  border-right-style: solid;  border-left-style: solid;  border-top-color: #999999;
  border-right-color: #999999;  border-left-color: #999999;  font-weight: bold;  /*color:#990000;*/
}
.label { color: #444444; }
.lblSmall { color: #8D8D8D; font-size: 10px; padding-right: 8px; }
</style>
<style>
.codigoItem{ color: blue; text-decoration: underline; cursor: pointer; }
.codigoItem:hover{ text-decoration: none; cursor: pointer; }
</style>
<script>
editarOrden = function()
{
    location.href = '<?php echo buildUrl( 'pto/addedit', 'tipo_proc=upd&id='.$i_Id ) ?>';
}
imprimirOrdenVenta = function()
{
	window.open( '<?=buildUrl( 'cot/print2PDF', 'id='.$i_Id.'&ordennum='.$o_VTA_OrdenBN->getOrdenNum() )?>', '_BLANK' );
}
verComprobantePDF = function()
{
    window.open( '<?=buildUrl( 'pro/printPDF', 'i_Id='.$o_VTA_OrdenBN->getObjectVTADocumento()->getIdConcat() )?>', '_BLANK' );
    //window.open( '<?=buildUrl( 'pto/verSorteoPDF', 'i_Id='.$o_VTA_OrdenBN->getObjectVTADocumento()->getIdConcat() )?>', '_BLANK' );
}
imprimirValorizado = function()
{
	window.open( '<?=buildUrl( 'cot/valorizadoPDF', 'id='.$i_Id.'&ordennum='.$o_VTA_OrdenBN->getOrdenNum() )?>', '_BLANK' );
}
cambiarEstadoOrden = function( estado_orden )
{
    x = confirm( "Esta seguro de cambiar el Estado de la Orden?" );
    if( x )
    {
        realizarAjaxCambioEstado( estado_orden );
    }
}
realizarAjaxCambioEstado = function( estado_orden )
{
    blockContent( 'content_result_grid1' );
    var str_serialize = "id=<?=$i_Id?>&estado=" + estado_orden;
    if( $( "#txt_anulacion" ).val() != "" )
    {
    	str_serialize += "&motivo_anulacion=" + $( "#txt_anulacion" ).val();
    }
    executeAjaxJson
    (
        "<?php echo buildUrl( 'cot/cambiarEstadoOrden' ) ?>",
        str_serialize,
        function( o_json )
        {
            if( o_json.error )
            {
            	unBlockContent( 'content_result_grid1' );
                showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                return false;
            }
            location.reload();
        }
    );
}
anularOrden = function( estado_orden )
{
    x = confirm( "Esta seguro de Anular la Orden?" );
    if( x )
    {
        if( ( $( "#txt_anulacion" ).val() ) == "" )
        {
        	showAlertBootStrap( 'resultContent', 'alert-danger', "Debe de ingresar el motivo de Anulaci&oacute;n." );
            return false;
        }
    	realizarAjaxCambioEstado( estado_orden );
    }
}
cerrarOrden = function( estado_orden )
{
    x = confirm( "Esta seguro de Cerrar la Orden?" );
    if( x )
    {
    	realizarAjaxCambioEstado( estado_orden );
    }
}
abrirOrden = function( estado_orden )
{
    x = confirm( "Esta seguro de Abrir la Orden?" );
    if( x )
    {
        realizarAjaxCambioEstado( estado_orden );
    }
}
cambiarOrdenEstandar = function ()
{
    x = confirm( "Esta seguro de convertir la Orden en Estandar?" );
    if( x )
    {
        blockContent( 'content_result_grid1' );
        var str_serialize = "id=<?=$i_Id?>";
        if( $( "#" ) )
        executeAjaxJson
        (
            "<?php echo buildUrl( 'cot/convertirOrdenEstandar' ) ?>",
            str_serialize,
            function( o_json )
            {
                unBlockContent( 'content_result_grid1' );
                if( o_json.error )
                {
                	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                location.href = "<?php echo buildUrl( 'cot/detailVta', "i_Id=" ) ?>" + o_json.id_orden;
            }
        );
    }
}
copiarOrdenVenta = function()
{
    x = confirm( "Esta seguro de copiar la Orden?" );
    if( x )
    {
        blockContent( 'content_result_grid1' );
        var dias_alquiler = trim( $( "#txt_renovacion" ).val() );
        if( dias_alquiler == "" )
        {
            alert( "Por favor seleccione los dias para Renovar." );
            return false;
        }
        var str_serialize = "id=<?=$i_Id?>&dias_alquiler=" + dias_alquiler;
        executeAjaxJson
        (
            "<?php echo buildUrl( 'cot/copiarOrdenVenta' ) ?>",
            str_serialize,
            function( o_json )
            {
                //pr( o_json );
                unBlockContent( 'content_result_grid1' );
                if( o_json.error )
                {
                	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                //location.href = "<?php echo buildUrl( 'cot/detailVta', "i_Id=" ) ?>" + o_json.id;
                window.open( '<?php echo buildUrl( 'cot/detailVta', "i_Id=" ) ?>'  + o_json.id, '_BLANK' );
            }
        );
    }
}
facturarOrden = function(event) {
    if (event) event.preventDefault();
    blockContent('content_result_grid1');
    blockContent('nav-tabContent');
    var datos = $('#content_form_tesoreria').find('input, select').serialize();
    executeAjaxJson(
        "<?= buildUrl('pto/generarComprobante', '') ?>",
        "orden_id=<?=$i_Id?>&txt_orden=<?=$o_VTA_OrdenBN->getOrdenNum()?>&" + datos,
        function(o_json) {
            unBlockContent('content_result_grid1');
            unBlockContent('nav-tabContent');
            if (o_json.error) {
                showAlertBootStrap('content_alert', 'alert-danger', o_json.mensaje_error);
                return;
            }
            var nombreArchivo = 'boleta_' + o_json.id_concat + '.pdf';
            var token = o_json.token;
            var flagImpresion = o_json.impresion;
			var urlPDF = 'https://panaderialamud.com/sisventas/vta.php/pro/printPDFFlask?i_Id=' + o_json.id_concat;
			
			const flaskUrl = 'http://localhost:5000/print' +
				'?nombre=' + encodeURIComponent(nombreArchivo) +
				'&flagImpresion=' + encodeURIComponent(flagImpresion) +
				'&url=' + encodeURIComponent(urlPDF);
			//
            fetch(flaskUrl)
                .then(res => res.json())
                .then(resp => {
                    if (resp.ok) {
                        console.log("Proceso exitoso:", resp);
                        location.href = "<?= buildUrl('pto/list') ?>";
                    } else {
                        console.error("Error impresión:", resp.error);
                        showAlertBootStrap('content_alert', 'alert-danger', "Error impresión: " + resp.error);
                    }
                })
                .catch(err => {
                    console.error("Error al comunicar con servidor impresión:", err);
                    showAlertBootStrap('content_alert', 'alert-danger', "No se pudo comunicar con el servidor local de impresión.");
                });
        }
    );
}
/* facturarOrden = function() {
    blockContent('content_result_grid1');
    blockContent('nav-tabContent');
    var datos = $('#content_form_tesoreria').find('input, select').serialize();
    executeAjaxJson(
        "<?php echo buildUrl('pto/generarComprobante', '') ?>",
        "orden_id=<?=$i_Id?>&txt_orden=<?=$o_VTA_OrdenBN->getOrdenNum()?>&" + datos,
        function(o_json) {
            unBlockContent('content_result_grid1');
            unBlockContent('nav-tabContent');
            if (o_json.error) {
                showAlertBootStrap('content_alert', 'alert-danger', o_json.mensaje_error);
                return false;
            }
            // URL PDF generado en remoto
            //var urlPDF = 'https://lym-corporacion.com' + '<?//=buildUrl("pro/printPDF","i_Id=")?>' + o_json.id_concat;
            var nombreArchivo = 'boleta_' + o_json.id_concat + '.pdf';
			var token = o_json.token;
			var flagImpresion = o_json.impresion;
			//var idBoleta = o_json.id_concat;
            //console.log("URL PDF:", urlPDF);
			//console.log("Token recibido:", token);
            // Llamar servidor local//
            //fetch('http://localhost:5000/print?url=' + encodeURIComponent(urlPDF) + '&nombre=' + encodeURIComponent(nombreArchivo))
            fetch('http://localhost:5000/print?token=' + encodeURIComponent(token) + '&nombre=' + encodeURIComponent(nombreArchivo)  + '&flagImpresion=' + encodeURIComponent(flagImpresion))
                .then(res => res.json())
                .then(resp => {
                    if (resp.ok) {
                        console.log("Proceso exitoso:", resp);
                        location.reload();
                    } else {
                        console.error("Error impresión:", resp.error);
                        showAlertBootStrap('content_alert', 'alert-danger', "Error impresión: " + resp.error);
						//location.reload();
                    }
                })
                .catch(err => {
                    console.error("Error al comunicar con servidor impresión:", err);
                    showAlertBootStrap('content_alert', 'alert-danger', "No se pudo comunicar con el servidor local de impresión.");
                });
            return false;
        }
    );
} */
asociarAnticipo = function()
{
	x = confirm( "Esta seguro de generar un Anticipo por la Orden?" );
    if( x )
    {
    	location.href = "<?php echo buildUrlComplet( 'vta.php/pro/addedit', 's_TipoProc=nvo&anticipo=1&ordenno='.$o_VTA_OrdenBN->getOrdenNum() ) ?>";
    }
}
</script>
<input type="hidden" name="i_Id" id="i_Id" value="<?=$i_Id?>">
<input type="hidden" name="TypeSub" id="TypeSub" value="0">
<input type="hidden" name="IdAlmacen" id="IdAlmacen" value="<?=$o_VTA_OrdenBN->getAlmacenDespacho()?>">
<input type="hidden" name="IdCompania" id="IdCompania" value="<?=$o_VTA_OrdenBN->getCiaCod()?>">
<br>
<div class="form-row mx-0">
	<div class="col-md-2 mb-1">
        <button type="button" class="btn btn-danger btn-lg btn-block" onclick="location.href='<?=buildUrl( 'pto/list' ) ?>'">SALIR</button>
    </div>
    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_FACTURA ){ ?>
        <?php if( $o_VTA_OrdenBN->getObjectVTADocumento()->getCobranzaEstado() == VTA_DocumentoBN::ESTADO_COB_PENDIENTE ){ ?>
            <div class="col-md-2 mb-1">
                <button type="button" class="btn btn-success btn-lg btn-block" onclick="mostrarModal2();">COBRAR</button>
            </div>
        <?php } ?>
        <div class="col-md-2 mb-1">
            <button type="button" class="btn btn-info btn-lg btn-block" onclick="verComprobantePDF();">VER PDF</button>
        </div>
    <?php } ?>
    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
    <div class="col-md-2 mb-1">
        <button type="button" class="btn btn-secondary btn-lg btn-block" onclick="editarOrden();">EDITAR</button>
    </div>
    <!--
    <div class="col-md-2 mb-1">
        <button type="button" class="btn btn-success btn-lg btn-block" onclick="facturarOrden();">FACTURAR</button>
    </div>
    -->
    <div class="col-md-2 mb-1">
        <button type="button" class="btn btn-info btn-lg btn-block" onclick="imprimirOrdenVenta();">VER PDF</button>
    </div>
    <div class="col-md-2 mb-1">
        <button type="button" class="btn btn-warning btn-lg btn-block" onclick="abrirPopupAnulacion();">ANULAR</button>
    </div>
    <div class="col-md-2 mb-1">
        <button type="button" class="btn btn-primary btn-lg btn-block" onclick="buscarProductosPopup();">BUSCAR PRODUCTOS</button>
    </div>
    <?php } ?>
</div>
<br>
<script>
    collapseContentTab = function( elm )
    {
        var elms    = $( elm ).find( "svg" );
        var elm_sel = elms.first();
        if( $( elm ).hasClass( "active" ) )
        {
            if( $( "#nav-tabContent" ).is( ":visible" ) )
            {
                $( elm_sel ).removeClass( "fa-angle-down" );
                $( elm_sel ).addClass( "fa-angle-right" );
                $( "#nav-tabContent" ).collapse( 'hide' );
            }
            else
            {
                $( elm_sel ).removeClass( "fa-angle-right" );
                $( elm_sel ).addClass( "fa-angle-down" );
                $( "#nav-tabContent" ).collapse( 'show' );
            }
        }
        else
        {
            if( !$( "#nav-tabContent" ).is( ":visible" ) )
            {
                $( elm_sel ).removeClass( "fa-angle-right" );
                $( elm_sel ).addClass( "fa-angle-down" );
                $( "#nav-tabContent" ).collapse( 'show' );
            }
            else
            {
                $( elm_sel ).removeClass( "fa-angle-right" );
                $( elm_sel ).addClass( "fa-angle-down" );
            }
        }
    }
</script>
<div id="content_alert" style=""></div>
<div class="form-row mx-0">
    <div class="col-md-12">
        <div class="card" id="" style="background-color: #F5F6FF;">
            <div class="card-body" style="padding: 10px;">
                <div class="table-responsive">
                    <nav>
                        <div class="nav nav-tabs" id="myTab" role="tablist">
                            <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true" onclick="collapseContentTab( this );">General <i class="fas fa-angle-down" onclick=""></i> </a>
                            <!--<a class="nav-item nav-link" id="nav-file-tab" data-toggle="tab" href="#nav-file" role="tab" aria-controls="nav-file" aria-selected="false">Archivos</a>-->
                            <!--<a class="nav-item nav-link" id="nav-proyecto-tab" data-toggle="tab" href="#nav-proyecto" role="tab" aria-controls="nav-proyecto" aria-selected="false">Proyecto <?/*=$o_VTA_PrsProyectosBN?'( <i class="fas fa-check"></i> )':'( <i class="fas fa-times"></i> )'*/?> </a>-->
                            <a class="nav-item nav-link" id="nav-cobra-tab" data-toggle="tab" href="#nav-cobra" role="tab" aria-controls="nav-cobra" aria-selected="false" onclick="collapseContentTab( this );">Cobranza <i class="fas fa-angle-right" onclick=""></i></a>
                            <!--<a class="nav-item nav-link" id="nav-comenta-tab" data-toggle="tab" href="#nav-comenta" role="tab" aria-controls="nav-comenta" aria-selected="false">Comentario</a>-->
                            <!--<a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Log</a>-->
                        </div>
                    </nav>
                </div>
                <div class="tab-content" id="nav-tabContent">
                    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
                        <div class="" style="border-left: 1px solid rgba(0,0,0,.125); border-right: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125);">
                            <iframe width="100%" frameborder="0" align="middle" id="iframe_formpago"  class="embed-responsive-item" src=""  <?php if( $o_VTA_OrdenBN->getOrdenTipoId() == "1" ){ ?> height="370" <?php }else{ ?> height="220" <?php } ?> ></iframe>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="nav-file" role="tabpanel" aria-labelledby="nav-file-tab">
                        <div class="" style="border-left: 1px solid rgba(0,0,0,.125); border-right: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125);">
                            <iframe width="100%" frameborder="0" align="middle" id="iframe_file"  class="embed-responsive-item" src="" height="320" ></iframe>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="nav-proyecto" role="tabpanel" aria-labelledby="nav-proyecto-tab">
                        <div class="" style="border-left: 1px solid rgba(0,0,0,.125); border-right: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125);">
                            <iframe width="100%" frameborder="0" align="middle" id="iframe_proyecto"  class="embed-responsive-item" src="" height="320" ></iframe>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="nav-renovacion" role="tabpanel" aria-labelledby="nav-renovacion-tab">
                        <div class="" style="border-left: 1px solid rgba(0,0,0,.125); border-right: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125);">
                            <iframe width="100%" frameborder="0" align="middle" id="iframe_renovacion"  class="embed-responsive-item" src="" height="320" ></iframe>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="nav-cobra" role="tabpanel" aria-labelledby="nav-cobra-tab">
                        <div class="" style="border-left: 1px solid rgba(0,0,0,.125); border-right: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125);">
                            <iframe width="100%" frameborder="0" align="middle" id="iframe_cobra"  class="embed-responsive-item" src="" height="220" ></iframe>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="nav-comenta" role="tabpanel" aria-labelledby="nav-comenta-tab">
                        <div class="" style="border-left: 1px solid rgba(0,0,0,.125); border-right: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125);">
                            <iframe width="100%" frameborder="0" align="middle" id="iframe_comenta"  class="embed-responsive-item" src="" height="320" ></iframe>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
                        <div class="" style="border-left: 1px solid rgba(0,0,0,.125); border-right: 1px solid rgba(0,0,0,.125); border-bottom: 1px solid rgba(0,0,0,.125);">
                            <iframe width="100%" frameborder="0" align="middle" id="iframe_log"  class="embed-responsive-item" src="" height="320" ></iframe>
                        </div>
                    </div>
                </div>
                <script type="text/javascript">
                $( '#myTab a' ).on
                (
                    'click', function ( e )
                    {
                        pr( $( e.currentTarget ).attr( "aria-controls" ) );
                        var id_content = $( e.currentTarget ).attr( "aria-controls" );
                        if( id_content == "nav-home" )
                        {
                            $( '#iframe_formpago' ).attr( "src", "<?=buildUrl( 'cot/listOrdFco', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                        }
                        if( id_content == "nav-file" )
                        {
                            $( '#iframe_file' ).attr( "src", "<?=buildUrl( 'cot/buscarFile', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                        }
                        if( id_content == "nav-proyecto" )
                        {
                            $( '#iframe_proyecto' ).attr( "src", "<?=buildUrl( 'cot/proyectos', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                        }
                        if( id_content == "nav-renovacion" )
                        {
                            $( '#iframe_renovacion' ).attr( "src", "<?=buildUrl( 'cot/renovaciones', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                        }
                        if( id_content == "nav-cobra" )
                        {
                            $( '#iframe_cobra' ).attr( "src", "<?=buildUrl( 'cot/cotiCobranza', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                        }
                        if( id_content == "nav-comenta" )
                        {
                            $( '#iframe_comenta' ).attr( "src", "<?=buildUrl( 'cot/cotiComentario', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                        }
                        if( id_content == "nav-profile" )
                        {
                            $( '#iframe_log' ).attr( "src", "<?=buildUrl( 'cot/buscarLog', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                        }
                        e.preventDefault()
                        $( this ).tab( 'show' );
                    }
                );
                //tab por defecto
                $( '#iframe_formpago' ).attr( "src", "<?=buildUrl( 'cot/listOrdFco', "ord_id={$o_VTA_OrdenBN->getOrdenId()}&ord_num={$o_VTA_OrdenBN->getOrdenNum()}" ) ?>" );
                </script>
                <div class="dropdown-divider"></div>
                <div id="resultContent" style=""></div>
                <div id="content_alert" style=""></div>
                <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
                <style type="text/css">
                    .ui-autocomplete-row
                    {
                        padding:0px;
                        background-color: #f4f4f4;
                        border-bottom:1px solid #ccc;
                        font-weight:bold;
                    }
                    .ui-autocomplete-row:hover
                    {
                        background-color: #ddd;
                    }
                </style>
                <div class="d-flex justify-content-center pt-2 pb-2">
                    <div class="input-group input-group-lg">
                        <input type="text" class="form-control input-lg" placeholder="Buscar Productos" aria-label="Username" aria-describedby="basic-addon2" autocomplete="off" name="txtBuscarProd" id="txtBuscarProd" onfocus="this.select();">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon2"><i class="fas fa-search" onclick=""></i></span>
                        </div>
                    </div>
                </div>
                <script>
                    $( '#txtBuscarProd' ).autocomplete
                    (
                        {
                            source: "<?=buildUrl( 'pto/autocompleteProductos' )?>",
                            minLength: 2,
                            select: function( event, ui )
                            {
                                asignarValores( ui.item.value );
                                setTimeout
                                (
                                    function(  )
                                    {
                                        $( 'body' ).trigger( { type: 'keyup', which: 27 } );
                                    },
                                    500
                                );
                            }
                        }
                    ).data( 'ui-autocomplete' )._renderItem = function( ul, item )
                    {
                        /*pr( "-------------------------" );
                        pr( ul );
                        pr( item );
                        pr( "-------------------------" );*/
                        return $( "<li class='ui-autocomplete-row'></li>" )
                            .data( "item.autocomplete", item )
                            .append( item.label )
                            .appendTo( ul );
                    };
                    $( "#txtBuscarProd" ).keypress
                    (
                        function( e )
                        {
                            //if( e.which == 32 ){ return false; }
                            if( e.which == 13 )
                            {
                                blockContent( 'content_detail' );
                                executeAjaxJson
                                (
                                    "<?php echo buildUrl( 'cot/saveOrdenVtaDetail' ) ?>",
                                    "s_TipoProc=codigo_barras&i_Id=&IdAlmacen=" + $( "#IdAlmacen" ).val() + "&CodigoBarras=" + $( e.currentTarget ).val() + "&i_Id=<?=$i_Id?>",
                                    function( o_json )
                                    {
                                        unBlockContent( 'content_detail' );
                                        if( o_json.error )
                                        {
                                            //showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                                            return false;
                                        }
                                        executeFindDetail();
                                        b_GuardarItem = false;
                                        id_adicional  = "";
                                        //$( "#btnAgregarCmm" ).focus();
                                        $( "#nav-home-tab" ).focus()
                                        setTimeout
                                        (
                                            function(  )
                                            {
                                                $( 'body' ).trigger( { type: 'keyup', which: 27 } );
                                            },
                                            500
                                        );
                                    }
                                );
                                return false;
                            }
                            return true;
                        }
                    );
                </script>
                <?php } ?>
                <style type="text/css">
                .table td
                {
                    vertical-align: middle;
                }
                </style>
                <div id="content_result_grid1">
                    <table class="table table-bordered">
                        <thead id="">
                            <tr>
                                <th width="2%"  align="center" scope="col"><b>No</b></th>
                                <th width="10%" align="center" scope="col"><b>C&oacute;digo</b></th>
                                <th width="20%" align="" scope="col"><b>Descripci&oacute;n</b></th>
                                <th width="8%" align="center" scope="col"><b>Stock</b></th>
                                <th width="8%" align="center" scope="col"><b>Cant.Pedida</b></th>
                                <th width="8%" align="center" scope="col"><b>Precio</b></th>
                                <th width="8%" align="center" scope="col"><b>IGV</b></th>
                                <th width="8%" align="center" scope="col"><b>Total</b></th>
                                <th width="5%" align="center" scope="col">&nbsp;</th>
                            </tr>
                        </thead>
                        <tbody id="content_nvo">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
<div class="form-row mx-0 pt-2">
    <div class="col-md-4">
        &nbsp;
    </div>
    <div class="col-md-8" id="content_form_tesoreria">
        <div class="card" id="" style="background-color: #F5F6FF;">
            <div class="card-body" style="padding: 10px;">
                <div class="form-group">
                    <table>
                        <tr>
                            <td>
                                <div class="form-row p-1 mx-0">
                                    <div class="col-md-12">
                                        <label for="FormaPago" class="col-form-label">Condici&oacute;n de Pago:</label>
                                        <select class="form-control custom-select my-0 mr-sm-2" name="FormaPago" id="FormaPago" onchange="eventoFormaPago();" required>
                                            <option value="008"> CONTADO </option>
                                            <!--<option value="016"> CREDITO </option>-->
                                        </select>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="form-row p-1 mx-0">
                                    <div class="col-md-12 text-center" id="content_btn_metodos">
                                        <label style="display: block;" for="" class="col-form-label">&nbsp;</label>
                                        <button type="button" class="btn btn-primary btn-sm" id="BtnAgregarMetodo" onclick="agregarContentMetodo();"> + Metodo </button>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="col-md-12">
                                    <label class="col-form-label" for="IdMoneda">VUELTO</label>
                                    <input type="text" class="form-control text-center font-weight-bold" name="txtMontoCambio" id="txtMontoCambio" value="" readonly >
                                </div>
                            </td>
                            <td>
                                <div class="col-md-12">
                                    <label class="col-form-label" for="IdMoneda">PENDIENTE</label>
                                    <input type="text" class="form-control text-center font-weight-bold" name="txtPendientePago" id="txtPendientePago" value="" readonly >
                                </div>
                            </td>
                            <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
                            <td>
                                <div class="col-md-12">
									<!--<label class="col-form-label" for="IdMoneda">&nbsp;</label>-->
                                    <button type="button" class="btn btn-success btn-lg btn-block" onclick="facturarOrden();">FACTURAR</button>
									<div class="form-check form-check-lg d-flex align-items-center" id="impresionAutomatica">
										<input class="form-check-input input-form-style-CAL" type="checkbox" name="FlagImpresion" id="FlagImpresion" <?php if( $o_SEG_UsuarioOpcionesBN->getFlagImpresion() ){ echo "checked"; } ?> onchange="editImpresionAutomatica( this )" >
										<label class="form-check-label" for="FlagImpresion">
											Impresión Automática
										</label>
									</div>
								</div>
                            </td>
							<!--<td>
                                <div class="col-md-12">
                                    <label class="col-form-label" >&nbsp;</label>
									<div class="form-check form-check-lg d-flex align-items-center">
										<input class="form-check-input input-form-style-CAL" type="checkbox" name="FlagImpresion" id="FlagImpresion" <?php if( $o_SEG_UsuarioOpcionesBN->getFlagImpresion() ){ echo "checked"; } ?> >
										<label class="form-check-label" for="FlagImpresion">
											Impresión Automática
										</label>
									</div>
                                </div>
                            </td>-->
                            <?php } ?>
                        </tr>
                    </table>
                </div>
                <div class="form-group card">
                    <div class="form-row p-1 mx-0" id="content_cuota_lst">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
    <?php } ?>
<script>
    eventoFormaPago = function()
    {
        var FormaPagoCod = $( "#FormaPago" ).val();
        if( FormaPagoCod == "008" )
        {
            $( "#content_cuota_lst" ).show();
            $( "#content_btn_metodos" ).show();
            $( "#content_btn_cuotas" ).hide();
            $( "#content_cuota_lst" ).html( "" );
            $( "#FechaVencimiento" ).val( "<?=date( "Y-m-d" )?>" );
            //agregarContentMetodo();
        }
        if( FormaPagoCod == "016" )
        {
            $( "#content_btn_metodos" ).hide();
            $( "#content_btn_cuotas" ).show();
            //$( "#content_cuota_lst" ).html( "" );
            $( "#content_cuota_lst" ).hide();
            //agregarContentCuota();
        }
    }
    calcularMontoFinal = function()
    {
        blockContent( 'content_form_tesoreria' );
        //voy a consultar el valor nuevo del total a pagar desde la base de datos
        var i_Id = '<?=$i_Id?>';
        var str_serialize = "OrdenId=" + i_Id + "&TipoProc=buscatTotalaPagar";
        executeAjaxJson
        (
            "<?php echo buildUrl( 'cot/requestOrden' ) ?>",
            str_serialize,
            function( o_json )
            {
                if( o_json.error )
                {
                    $( elm_sel ).val( CantidadRef );
                    showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                var totalaPagar = floatval( o_json.totalapagar );
                $( "#txtPendientePago" ).val( totalaPagar );
                $( "#txtMontoCambio" ).val( 0 );
                $( "#content_cuota_lst" ).html( "" );
                if( totalaPagar > 0 )
                {
                    agregarContentMetodo();
                    realizarCalculosxPagar();
                }
                unBlockContent( 'content_form_tesoreria' );
            }
        );
    }
    realizarCalculosxPagar = function()
    {
        var MensaleAlert     = "";
        var MontoAplicar     = 0;
        var ErrorMontoMayor  = false;
        var SumaMontoAplicar = 0;
        var Descontando      = MontoTotalaPagarDocu;
        var a_Valores        = {};
        var a_elm = $( "#content_cuota_lst" ).find( ".ContentMetodoPagoClass" );
        try
        {
            $.each
            (
                a_elm, function( index, item )
                {
                    var MetodoPagoClass = $( item ).find( ".MetodoPagoClass" );
                    var Select          = $( item ).find( ".MontoApliClass" );
                    var Id              = $( MetodoPagoClass ).val().trim();
                    if( a_Valores.hasOwnProperty( Id ) )
                    {
                        //throw new Error( "Se encontro metodo de pago duplicado." );
                        //ErrorMontoMayor = true;
                        //return false;
                    }
                    a_Valores[Id] = Id;
                    pr( a_Valores );
                    MontoAplicar = floatval( $( Select ).val() );
                    if( isNaN( MontoAplicar ) )
                    {
                        MontoAplicar = 0;
                    }
                    SumaMontoAplicar = SumaMontoAplicar + MontoAplicar;
                    Descontando      = Descontando - MontoAplicar;
                    if( MontoAplicar > MontoTotalaPagarDocu )
                    {
                        if( Id !== "1" )
                        {
                            ErrorMontoMayor = true;
                            throw new Error( "Solo se permite dar vuelto cuando al metodo EFECTIVO." );
                        }
                    }
                    if( Descontando < 0 )
                    {
                        if( Id !== "1" )
                        {
                            ErrorMontoMayor = true;
                            throw new Error( "La suma total a aplicar es mayor al total a pagar." );
                        }
                    }
                }
            );
        }
        catch ( error )
        {
            ErrorMontoMayor = true;
            MensaleAlert = error.message;
            pr( error.message );
        }
        if( ErrorMontoMayor )
        {
            showAlertBootStrap( 'content_alert', 'alert-danger', MensaleAlert );
            //var Select = $( "#content_det_cobra" ).find( ".active" ).find( ':input[type=text]:first' );
            var elm_last = $( "#content_cuota_lst" ).find( ".ContentMetodoPagoClass" ).last();
            var Select = $( elm_last ).find( ".MontoApliClass" );
            pr( Select );
            $( Select ).val( 0 );
        }
        if( SumaMontoAplicar <= MontoTotalaPagarDocu )
        {
            $( "#txtPendientePago" ).val( redondear( MontoTotalaPagarDocu - SumaMontoAplicar, 2 ) );
            $( "#txtMontoCambio" ).val( 0 );
        }
        else
        {
            $( "#txtPendientePago" ).val( 0 );
            $( "#txtMontoCambio" ).val( redondear( SumaMontoAplicar - MontoTotalaPagarDocu, 2 ) );
        }
    }
    agregarContentMetodo = function()
    {
        var a_Elm = $( "#content_cuota_lst" ).find( ".CuotaMontoClass" );
        var i_IdConcat = a_Elm.length + 1;
        var ContentId = "content_cuota_" + i_IdConcat;
        var DeudaTotal = floatval( $( "#txtPendientePago" ).val() );
        //validacion, que el saldo total a pagar sea mayor a 0
        if( DeudaTotal <= 0 )
        {
            showAlertBootStrap( 'content_alert', 'alert-danger', "El saldo PENDIENTE a pagar es 0" );
            return false;
        }
        $( "#content_cuota_lst" ).append( `
                            <div class="col-md-12 mb-3 ContentMetodoPagoClass" id="` + ContentId + `">
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close" onclick="eliminarContentCuota( '` + ContentId + `' );">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                                <div class="card" style="background-color: lightblue;">
                                    <div class="form-row p-1 mx-0">
                                        <div class="col-md-4">
                                            <label for="" class="col-form-label">Metodo Pago</label>
                                            <select class="form-control form-control-sm MetodoPagoClass" id="MetodoPago_` + i_IdConcat + `" name="MetodoPago[]">
                                                <?php foreach ( FCO_TipoPagoFN::selectActivos() as $o_FCO_TipoPagoBN) { ?>
                                                    <?php if( $o_FCO_TipoPagoBN->getIdTipoPago() == 4 ){ continue; } ?>
                                                    <option value="<?=$o_FCO_TipoPagoBN->getIdTipoPago()?>"> <?=$o_FCO_TipoPagoBN->getNombre()?> </option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label for="" class="col-form-label">Referencia</label>
                                            <input type="text" style="text-align: center; font-weight: bold;" class="form-control form-control-sm ReferenciaClass" id="ReferenciaPago_` + i_IdConcat + `" name="ReferenciaPago[]" value="" onfocus="this.select();" onblur="realizarCalculosxPagar()" autocomplete="off" >
                                        </div>
                                        <div class="col-md-4">
                                            <label for="" class="col-form-label">Monto</label>
                                            <input type="text" style="text-align: center; font-weight: bold;" class="form-control form-control-sm MontoApliClass" id="MontoAplicado_` + i_IdConcat + `" name="MontoAplicado[]" value="` + DeudaTotal + `" onfocus="this.select();" onblur="realizarCalculosxPagar()" autocomplete="off" >
                                        </div>
                                    </div>
                                </div>
                            </div>
                                `
        );
        realizarCalculosxPagar();
    }
    eliminarContentCuota = function( Name )
    {
        $( "#" + Name ).remove();
        $( "#BtnAgregarCuota" ).focus();
        realizarCalculosxPagar();
    }
	function editImpresionAutomatica( chk ){
        blockContent( "impresionAutomatica" );
		let valueChecked;
		if( chk.checked ){
			valueChecked = 1;
		}else{
			valueChecked = 0;
		}
		$.ajax({
			url: '<?php echo buildUrl("pto/editImpresionAutomatica", "") ?>',
			type: 'POST',
			data: { ValueChecked: valueChecked },
			success: function(response) {
				unBlockContent("impresionAutomatica");
			}
		});
	}
    eventoFormaPago();
</script>
<?php if( !$readonly ){ ?>
        <br><br><br>
<footer style="background-color: #F5F6FF; ">
<!--    <nav class="navbar navbar-expand-md navbar-dark " style="background-color: #F5F6FF; display: inline-block;">-->
        <div class="form-row mx-0">
            <div class="col-md-8 mb-1">
                <div class="form-row mx-0">
                    <div class="col-md-6">
                        <h4 style="padding-top: 10px;" class="text-info text-nowrap mb-0"><?=$s_Titulo?></h4>
                    </div>
                    <div class="col-md-6">
                        <h4 style="padding-top: 10px;" class="text-info text-nowrap mb-0"><?=$s_Titulo2?></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-4 mb-1 text-right">
                <?php if( myUser::getUser()->getObjectCompania()->getOpeCierreCaja() ){ ?>
                    <?php if( $b_ControlCaja ){ ?>
                        <h4 style="padding-top: 10px;" class="text-info text-nowrap mb-0"><?=$DesCajaSelect?> - <?=$DescTurnoSelect?></h4>
                    <?php }else{ ?>
                        <button type="button" class="form-control btn btn-primary" onclick="aperturarCaja();"> Aperturar Caja </button>
                    <?php } ?>
                <?php } ?>
            </div>
        </div>
<!--    </nav>-->
</footer>
<?php } ?>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<style type="text/css">
#exampleModalCenter .modal
{
    padding: 0 !important;
}
#exampleModalCenter .modal-dialog {
    max-width: 95% !important;
    height: 90%;
    /*  padding: 0;
    margin: 0;*/
}
#exampleModalCenter .modal-content
{
    /*border-radius: 0 !important;*/
    height: 90%;
}
</style>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- Modal 1-->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Buscar Producto</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <iframe id="iframe_id" src="" style="zoom:0.60;" width="99.6%" height="99.6%" frameborder="0"></iframe>
            </div>
            <!--<div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>-->
        </div>
    </div>
</div>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<?php
$s_NombreFuncion = "saveOrdenVtaDetail";
?>
<script type="text/javascript">
var prod_final_tipo = "";
var id_adicional = "";
var Controler    = "";
buscarProductosPopup = function()
{
    $( "#exampleModalLongTitle" ).html( "Buscar Producto" );
    $( '#exampleModalCenter' ).modal( { show:true } );
    var s_almacen_id = $( "#IdAlmacen" ).val();
    var frameSrc = '<?=buildUrl( 'pro/listItem' )?>?moneda_cod=<?=$o_VTA_OrdenBN->getMonedaCod()?>&IdAlmacen=' + s_almacen_id + '&module=vta.php/cot&i_Id=<?=$i_Id?>&controler=' + Controler;
    if( id_adicional != "" )
    {
        frameSrc += "&id_adicional=" + id_adicional;
    }
    $( '#iframe_id' ).attr( "src", frameSrc );
}
buscarServiciosPopup = function()
{
	$( "#exampleModalLongTitle" ).html( "Buscar Servicios" );
    $( '#exampleModalCenter' ).modal( { show:true } );
    var s_almacen_id = $( "#IdAlmacen" ).val();
    var frameSrc = '<?=buildUrl( 'pro/listServices' )?>' + 'moneda_cod/<?=$o_VTA_OrdenBN->getMonedaCod()?>/IdAlmacen/' + s_almacen_id + '/module/cot/i_Id/<?=$i_Id?>';
    $( '#iframe_id' ).attr( "src", frameSrc );
}
ocultarModal = function( name_modal )
{
    $( '#' + name_modal ).modal( 'hide' );
}
</script>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- Modal 2-->
<style type="text/css">
#exampleModalScrollable .modal
{
    padding: 0 !important;
}
#exampleModalScrollable .modal-dialog
{
    max-width: 95% !important;
    height: 90%;
}
#exampleModalScrollable .modal-content
{
    /*border-radius: 0 !important;*/
    height: 90%;
}
</style>
<div class="modal fade" id="exampleModalScrollable" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true">
    <!--<div class="modal-dialog modal-dialog-scrollable" role="document">-->
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalScrollableTitle"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <iframe id="iframe_precios" src="" style="" width="99.6%" height="99%" frameborder="0"></iframe>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
                <!--<button type="button" class="btn btn-primary">Save changes</button>-->
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
agregarComentario = function()
{
 	$( "#exampleModalScrollableTitle" ).html( "Agregar Comentario" );
    var frameSrc = '<?=buildUrl( 'cot/agregarComentario', "id=$i_Id&id_item=" )?>';
    $( '#iframe_precios' ).attr( "src", frameSrc );
    $( '#exampleModalScrollable' ).modal( { show:true } );
}
abrirListaPrecios = function( id_item, secuencia )
{
    $( "#exampleModalScrollableTitle" ).html( "Lista de Precios" );
    var frameSrc = '<?=buildUrl( 'cot/listPrecio', "id=$i_Id&id_item=" )?>' + id_item + "/secuencia/" + secuencia;
    $( '#iframe_precios' ).attr( "src", frameSrc );
    $( '#exampleModalScrollable' ).modal( { show:true } );
}
abrirPopupDescuento = function()
{
    $( "#exampleModalScrollableTitle" ).html( "Agregar Descuento" );
    var frameSrc = '<?=buildUrl( 'cot/listDescuento', "id=$i_Id&id_item=" )?>';
    $( '#iframe_precios' ).attr( "src", frameSrc );
    $( '#exampleModalScrollable' ).modal( { show:true } );
}
</script>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
    <style type="text/css">
        #exampleModalImagenItem .modal
        {
            padding: 0 !important;
        }
        #exampleModalImagenItem .modal-dialog {
            max-width: 40% !important;
            height: 70%;
        }
        #exampleModalImagenItem .modal-content
        {
            height: 43%;
        }
    </style>
    <div class="modal fade" id="exampleModalImagenItem" tabindex="-1" role="dialog" aria-labelledby="exampleModalImagenItemTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalImagenItemTitle">Imagen</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <iframe id="iframe_imagen_item" src="" style="" width="99.6%" height="99%" frameborder="0"></iframe>
                </div>
            </div>
        </div>
    </div>
<script>
    mostrarImagenItem = function( id_item )
    {
        $( "#exampleModalImagenItemTitle" ).html( "Imagen" );
        var frameSrc = '<?=buildUrlComplet( 'mst.php/item/mostrarImagen', "id_item=" )?>' + id_item;
        $( '#iframe_imagen_item' ).attr( "src", frameSrc );
        $( '#exampleModalImagenItem' ).modal( { show:true } );
    }
</script>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- Modal 3-->
<style type="text/css">
/*#exampleModalAnulacion .modal
{
    padding: 0 !important;
}
#exampleModalAnulacion .modal-dialog {
    max-width: 70% !important;
    height: 70%;
}
#exampleModalAnulacion .modal-content
{
    height: 70%;
}*/
</style>
<div class="modal fade" id="exampleModalAnulacion" tabindex="-1" role="dialog" aria-labelledby="exampleModalAnulacionTitle" aria-hidden="true">
    <!--<div class="modal-dialog modal-dialog-Anulacion" role="document">-->
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalAnulacionTitle">Anular Orden</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- <iframe id="iframe_anulacion" src="" style="" width="99.6%" height="99%" frameborder="0"></iframe> -->
                <div id="content_anulacion">
                    <div class="form-group">
                        <label for="txt_anulacion" class="col-form-label">Comentario:</label>
                        <textarea class="form-control" id="txt_anulacion" name="txt_anulacion"></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-primary" onclick="anularOrden( 'A' );">Anular</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
abrirPopupAnulacion = function( id_item, secuencia )
{
    //var frameSrc = '<?=buildUrl( 'cot/ordenAnulacion', "id=$i_Id&id_item=" )?>' + id_item + "/secuencia/" + secuencia;
    //$( '#iframe_precios' ).attr( "src", frameSrc );
    $( "#txt_anulacion" ).val( '' );
    $( '#exampleModalAnulacion' ).modal( { show:true } );
}
</script>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
    <!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
    <!--APERTURA DE CAJA-->
    <style type="text/css">
        #exampleModalCenter3 .modal
        {
            padding: 0 !important;
        }
        #exampleModalCenter3 .modal-dialog
        {
            max-width: 95% !important;
            height: 90%;
        }
        #exampleModalCenter3 .modal-content
        {
            /*border-radius: 0 !important;*/
            height: 90%;
        }
    </style>
    <div class="modal hide fade" id="exampleModalCenter3" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle2" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLongTitle2">Aperturar Caja</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <iframe id="iframe_id2" src="" style="zoom:0.60" width="99.6%" height="99.6%" frameborder="0"></iframe>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
                    <!--<button type="button" class="btn btn-primary">Save changes</button>-->
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        aperturarCaja = function()
        {
            $( '#iframe_id2' ).attr( "src", "<?=buildUrlComplet( 'tsr.php/caja/aperturarCaja' )?>" );
            $( '#exampleModalCenter3' ).modal( { show:true } );
        }
        recargarPagina = function()
        {
            location.reload();
        }
        cerrarPopupBootstrap = function()
        {
            $( '#exampleModalCenter3' ).modal( 'hide' );
        }
    </script>
    <!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<?=crearPopupResumenStock( array( "name_function"=>"buscarResumenStock" ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog", "iframe_id"=>"myIframe", "popup_title"=>"Buscar Item", "modal"=>true ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog2", "iframe_id"=>"myIframe2", "popup_title"=>"Lista de Precios", "popup_width"=>"900", "popup_height"=>"300", "modal"=>true ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog3", "iframe_id"=>"myIframe3", "popup_title"=>"Ingreso de Descuento", "popup_width"=>"400", "popup_height"=>"200", "modal"=>true ) )?>
<?=crearFuentePopupIframe( array( "div_id"=>"dialog4", "iframe_id"=>"myIframe4", "popup_title"=>"Buscar Producto", "modal"=>true ) )?>
<script>
</script>
<script>
buscarStockActualxLinea = function( elm_sel )
{
    var item_id = $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='IdItem[]']" ).val();
    var lote_id = $( $( elm_sel ).closest( 'tr' ) ).find( "select[name='IdLote[]']" ).val();
    var str_serialize = "TipoProc=getStockActual&IdItem=" + item_id + "&IdCompania=" + $( "#IdCompania" ).val() + "&IdAlmacen=" + $( "#IdAlmacen" ).val() + "&IdLote=" + lote_id;
    executeAjaxJson
    (
        "<?php echo buildUrl( 'cot/request' ) ?>",
        str_serialize,
        function( o_json )
        {
            if( o_json.error )
            {
            	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                return false;
            }
            if( o_json.result )
            {
                $( $( elm_sel ).closest( 'tr' ) ).find( 'td:eq( 4 )' ).html( o_json.StockActual );
                //$( $( elm_sel ).closest( 'tr' ) ).find( "input[name='FechaVencimiento[]']" ).val( o_json.FechaVencimientoLote );
                //setTimeout( '$( $( global_elm ).closest( "tr" ) ).find( "input[name=\'Cantidad[]\']" ).focus();', 50 );
                actualizarLotexLinea( elm_sel );
            }
        }
    );
}
actualizarLotexLinea = function( elm_sel )
{
	var item_id   = $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='IdItem[]']" ).val();
    var lote_id   = $( $( elm_sel ).closest( 'tr' ) ).find( "select[name='IdLote[]']" ).val();
    var i_Id      = <?=$i_Id?>;
    var IdAlmacen = $( "#IdAlmacen" ).val();
    var Secuencia = $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='Secuencia[]']" ).val();
    var str_serialize = "TipoProc=actualizarLotexLinea&IdItem=" + item_id + "&IdCompania=" + $( "#IdCompania" ).val() + "&IdAlmacen=" + $( "#IdAlmacen" ).val() + "&IdLote=" + lote_id + "&i_Id=" + i_Id + "&Secuencia=" + Secuencia;
    executeAjaxJson
    (
        "<?php echo buildUrl( 'cot/request' ) ?>",
        str_serialize,
        function( o_json )
        {
            if( o_json.error )
            {
            	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                return false;
            }
        }
    );
}
actualizarCantidadxLinea = function( elm_sel )
{
    var item_code       = $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='IdItem[]']" ).val();
    var CantidadPedida  = elm_sel.value;
    var CantidadRef     = $( elm_sel ).attr( "cantref" );
    //var lote_id         = $( $( elm_sel ).closest( 'tr' ) ).find( "select[name='IdLote[]']" ).val();
    var lote_id         = "";
    var Secuencia       = $( $( elm_sel ).closest( 'tr' ) ).find( "input[name='Secuencia[]']" ).val();
    var i_Id            = <?=$i_Id?>;
    var IdAlmacen       = $( "#IdAlmacen" ).val();
    if( CantidadPedida != CantidadRef )
    {
        blockContent( "content_result_grid1" );
        var str_serialize = "s_TipoProc=upddet&IdCompania=" + $( "#IdCompania" ).val() + "&IdAlmacen=" + $( "#IdAlmacen" ).val() + "&IdLote=" + lote_id + "&i_Id=" + i_Id + "&Secuencia=" + Secuencia + "&CantidadPedida=" + CantidadPedida + "&IdItem=" + item_code;
        executeAjaxJson
        (
            "<?php echo buildUrl( 'cot/'.$s_NombreFuncion ) ?>",
            str_serialize,
            function( o_json )
            {
                if( o_json.error )
                {
                    $( elm_sel ).val( CantidadRef );
                    showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                unBlockContent( "content_result_grid1" );
                executeFindDetail();
                b_GuardarItem = false;
                setTimeout( 'calcularMontoFinal();', 100 );
            }
       );
    }
}
</script>
<script>
var b_GuardarItem = false;
var MontoTotalaPagarDocu = 0;
var SaldoTotalDocumento  = 0;
buscarStockActual = function( elm_sel )
{
    var item_id = $( "#content_nvo tr #IdItem" ).val();
    var lote_id = $( "#content_nvo tr #IdLote" ).val();
    var str_serialize = "TipoProc=getStockActual&IdItem=" + item_id + "&IdCompania=" + $( "#IdCompania" ).val() + "&IdAlmacen=" + $( "#IdAlmacen" ).val() + "&IdLote=" + lote_id;
    executeAjaxJson
    (
        "<?php echo buildUrl( 'pro/request' ) ?>",
        str_serialize,
        function( o_json )
        {
            console.log( o_json );
            if( o_json.error )
            {
            	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                return false;
            }
            if( o_json.result )
            {
            	$( "#content_nvo tr #ItemStock" ).html( o_json.StockActual );
            	$( "#content_nvo tr #CantidadPedida" ).val( 1 );
                //setTimeout( '$( "#content_nvo tr #CantidadPedida" ).focus();', 50 );
                //setTimeout( '$( "#content_nvo tr #CantidadPedida" ).val( 1 );', 60 );
            	setTimeout( '$( "#content_nvo tr #btnGuardar" ).click();', 20 );           //AQUI SE EMULA CLICK GUARDAR
            }
        }
    );
}
openPopup = function()
{
    //se recupera el id del almacen seleccionado.
    var s_almacen_id = $( "#IdAlmacen" ).val();
    console.log( s_almacen_id );
    $( '#myIframe' ).attr( 'src', '<?=buildUrl( 'pro/listItem' )?>' + 'moneda_cod/<?=$o_VTA_OrdenBN->getMonedaCod()?>/IdAlmacen/' + s_almacen_id );
    $( '#dialog' ).dialog( 'open' );
}
asignarValores = function( id_item, item_descripcion )
{
    ocultarModal( "exampleModalCenter" );
    var i_Id        = $( "#i_Id" ).val();
    var IdAlmacen   = $( "#IdAlmacen" ).val();
    str_serialize = "s_TipoProc=nvodet&i_Id=" + i_Id + "&IdAlmacen=" + IdAlmacen + "&IdItem=" + id_item;
    if( id_adicional != "" )
    {
    	str_serialize += "&id_adicional=" + id_adicional;
    }
    blockContent( 'content_detail' );
    executeAjaxJson
    (
        "<?php echo buildUrl( 'cot/'.$s_NombreFuncion ) ?>",
        str_serialize,
        function( o_json )
        {
            unBlockContent( 'content_detail' );
            if( o_json.error )
            {
            	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                return false;
            }
            executeFindDetail();
            b_GuardarItem = false;
            id_adicional  = "";
            setTimeout( 'calcularMontoFinal();', 100 );
        }
    );
}
</script>
<script>
validacionPrecio = function( v_PrecioValue )
{
    if( v_PrecioValue == "" )
    {
        alert( "Precio vacia." );
        return false;
    }
    if( !$.isNumeric( v_PrecioValue ) )
    {
        alert( "Precio no valida." );
        return false;
    }
    var f_Precio = parseFloat( v_PrecioValue );
    if( f_Precio <= 0 )
    {
        alert( "El Precio ingresado no es valida." );
        return false;
    }
    return true;
}
validacionCantidad = function( v_CantValue )
{
    if( v_CantValue == "" )
    {
        alert( "Cantidad vacia." );
        return false;
    }
    if( !$.isNumeric( v_CantValue ) )
    {
        alert( "Cantidad no valida." );
        return false;
    }
    i_Cant = parseInt( v_CantValue );
    if( i_Cant < 1 )
    {
        alert( "La cantidad ingresada no es valida." );
        return false;
    }
    return true;
}
/*executeSaveOrderDetail = function( elm_sel )
{
    if( b_GuardarItem )
    {
        var str_serialize = $( $( elm_sel ).closest( 'tr' ) ).find( "input, select" ).serialize();
        var i_Id = '<?=$i_Id?>';
        var IdAlmacen       = $( "#IdAlmacen" ).val();
        str_serialize += "&i_Id=" + i_Id + "&s_TipoProc=nvo&IdAlmacen=" + IdAlmacen;
        console.log( str_serialize );
        executeAjaxJson
        (
            "<?php echo buildUrl( 'cot/saveOrdenVtaDetail' ) ?>",
            str_serialize,
            function( o_json )
            {
                if( o_json.error )
                {
                	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                executeFindDetail();
                b_GuardarItem = false;
            }
        );
    }
    else
    {
        alert( "No se puede guardar." );
    }
}*/
executeFindDetail = function()
{
    <?php if( $o_VTA_OrdenBN->getOrdenTipoClasificacionId() == VTA_OrdenBN::TIPO_PRODUCTOS_TERMINADOS ){ ?>
    executeFindDetailPFinal();
    return false;
    <?php } ?>
    blockContent( "content_result_grid1" );
    var i_Id     = <?=$i_Id?>;
    var a_Params = [];
    a_Params.push( "i_Id=" + i_Id );
    executeAjaxUpdater
    (
        "content_result_grid1",
        "<?php echo buildUrl( 'cot/findDetailVta' ) ?>",
        a_Params.join( "&" ),
        function( response )
        {
            //pr( response );
        }
    );
}
executeFindDetailPFinal = function()
{
    blockContent( "content_result_grid1" );
    var i_Id     = <?=$i_Id?>;
    var a_Params = [];
    a_Params.push( "i_Id=" + i_Id );
    executeAjaxUpdater
    (
        "content_result_grid1",
        "<?php echo buildUrl( 'cot/findProdFinal' ) ?>",
        a_Params.join( "&" ),
        function( response )
        {
            //pr( response );
        }
    );
}
executeDeleteDetail = function( i_Id )
{
    /*x = confirm( "Esta seguro de eliminar el detalle?" );
    if( x )
    {*/
        a_Params = [];
        a_Params.push( "i_Id=" + i_Id );
        executeAjaxJson
        (
            "<?=buildUrl( 'cot/deleteDetailVta' )?>",
            a_Params.join( "&" ),
            function( o_json )
            {
                if( o_json.error )
                {
                	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return true;
                }
                executeFindDetail();
                setTimeout( 'calcularMontoFinal();', 100 );
            }
        );
    //}
}
</script>
<?php if( $o_VTA_OrdenBN->getOrdenEstado() != VTA_OrdenBN::ESTADO_ANULADO ){ ?>
<script>
//ESCAPE, DETECTA EL F5, CTRL+F5
$( document ).bind
(
    'keyup',
    function( e )
    {
        if( e.which === 116 ) { }
        if( e.which === 82 && e.ctrlKey ) { }
        if( e.which === 119 ) { }
        if( e.which === 107 ){ buscarProductosPopup(); } // tecla +
        if( e.which === 109 ){ buscarServiciosPopup(); } // tecla -
        if( e.which === 27 ) //ESCAPE
        {
            //$( "#content_nvo" ).html( "" );
            $( "#txtBuscarProd" ).val( "" );
            $( "#txtBuscarProd" ).focus();
            executeFindDetail();
        }
    }
);
</script>
<?php } ?>
<script>
executeFindDetail();
$( "#nav-tabContent" ).collapse( 'show' );
setTimeout
(
    function()
    {
        $( "#nav-home-tab" ).trigger( "click" );
        $( "#txtBuscarProd" ).focus();
    },
    500
);
<?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
calcularMontoFinal();
<?php } ?>
</script>
<?php if( $readonly ){ ?>
<script type="text/javascript">
$( "input[type=button]" ).each
(
    function( key, elm )
    {
        elm.remove();
    }
);
</script>
<?php } ?>