<?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( 'cot/addedit', 'tipo_proc=upd&id='.$i_Id ) ?>';
}

imprimirOrdenVenta = function()
{
	window.open( '<?=buildUrl( 'cot/print2PDF', 'id='.$i_Id.'&ordennum='.$o_VTA_OrdenBN->getOrdenNum() )?>', '_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()
{
	x = confirm( "Esta seguro de Facturar la Orden?" );
    if( x )
    {
    	location.href = "<?php echo buildUrlComplet( 'vta.php/pro/addedit', 's_TipoProc=nvo&ordenno='.$o_VTA_OrdenBN->getOrdenNum() ) ?>";
    }
}

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>

<div id="content_alert" style=""></div>

<!--
<div class="shadow-sm p-3 mb-2 bg-white rounded card card-body">
    <div class="row">
        <div class="col mb-1">
            <h4 class="text-info text-nowrap mb-0"><?=$s_Titulo?></h4>
        </div>
    </div>
</div>-->

<?php if( !$readonly ){ ?>
<div class="card">
    <div class="form-row mx-0">
        <div class="col-md-4 mb-1">

            <h4 style="padding-top: 10px;" class="text-info text-nowrap mb-0"><?=$s_Titulo?></h4>

        </div>
        <div class="col-md-8 text-right">
            <!--<div class="card">-->
                <div class="card-body" style="padding: 10px;">
                    <button type="button" class="btn btn-outline-primary" onclick="location.href='<?=buildUrl( 'cot/list' ) ?>'">LISTADO</button>
                    <button type="button" class="btn btn-outline-primary" onclick="location.href='<?=buildUrl( 'cot/addedit', "tipo_proc=nvo" ) ?>'">NUEVO</button>
                    <!-- 
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="editarOrden();">Editar</button>
                        <?php if( $o_VTA_OrdenBN->getOrdenTipoId() == "2" ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="cambiarOrdenEstandar();">A Estandar</button>
                        <?php } ?>
                        <?php if( $o_VTA_OrdenBN->getOrdenTipoId() == "1" ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="cerrarOrden( 'C' );">Cerrar</button>
                        <?php } ?>
                    <?php } ?>
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_CERRADO ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="abrirOrden( 'O' );">Re-Abrir</button>
                    	<?php if( $o_VTA_OrdenBN->getOrdenTipoId() == "1" ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="facturarOrden();">Facturar</button>
                    	<?php } ?>
                    <?php } ?>
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() != VTA_OrdenBN::ESTADO_ANULADO ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="anularOrden( 'A' );">Anular</button>
                    <button type="button" class="btn btn-outline-primary" onclick="imprimirOrdenVenta();">PDF</button>
                    <?php } ?>
                    <button type="button" class="btn btn-outline-primary" onclick="copiarOrdenVenta();">Copiar</button>
                    -->
                    
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="editarOrden();">EDITAR</button>
                    <button type="button" class="btn btn-outline-primary" onclick="cambiarEstadoOrden('<?=VTA_OrdenBN::ESTADO_REVISADO?>');">REVISADO</button>
                    <?php } ?>
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_REVISADO ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="cambiarEstadoOrden('<?=VTA_OrdenBN::ESTADO_ABIERTO?>');">PENDIENTE</button>
                    <button type="button" class="btn btn-outline-primary" onclick="cambiarEstadoOrden('<?=VTA_OrdenBN::ESTADO_CERRADO?>');">APROBADO</button>
                    <?php } ?>
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_CERRADO ){ ?> <!-- APROBADO -->
                    <button type="button" class="btn btn-outline-primary" onclick="facturarOrden();">FACTURAR</button>
                    <button type="button" class="btn btn-outline-primary" onclick="cambiarEstadoOrden('<?=VTA_OrdenBN::ESTADO_ABIERTO?>');">PENDIENTE</button>
                    <!-- <button type="button" class="btn btn-outline-primary" onclick="abrirPopupRenovacion();">RENOVAR</button> -->
                    <?php } ?>
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_FACTURA ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="abrirPopupRenovacion();">RENOVAR</button>
                    <?php } ?>
                    <?php if( $o_VTA_OrdenBN->getOrdenEstado() != VTA_OrdenBN::ESTADO_ANULADO ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="imprimirOrdenVenta();">VER PDF</button>
                    <?php //if( $o_VTA_OrdenBN->getOrdenTipoClasificacionId() == VTA_OrdenBN::TIPO_PRODUCTOS_TERMINADOS ){ ?>
                    <?php if( $o_VTA_OrdenBN->getOrdenTipoComercialId() == VTA_OrdenBN::TIPO_COMERCIAL_ALQUILER ){ ?>
                    <button type="button" class="btn btn-outline-primary" onclick="imprimirValorizado();">VER VALORIZADO</button>
                    <?php } ?>
                    <button type="button" class="btn btn-outline-primary" onclick="asociarAnticipo();">ANTICIPO</button>
                    <button type="button" class="btn btn-outline-primary" onclick="abrirPopupAnulacion();">ANULAR</button>
                    <?php } ?>
                    
                    
                </div>
            <!--</div>-->
        </div>
    </div>
</div>
<?php } ?>

<br>

<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">General</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>
            <?php if( $o_VTA_OrdenBN->getOrdenTipoComercialId() == VTA_OrdenBN::TIPO_COMERCIAL_ALQUILER ){ ?>
            <!--<a class="nav-item nav-link" id="nav-renovacion-tab" data-toggle="tab" href="#nav-renovacion" role="tab" aria-controls="nav-renovacion" aria-selected="false">Renovaciones ( 0 )</a>-->
            <?php } ?>
            <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">Cobranza</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="320" <?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="320" ></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>

<br>

<div id="resultContent" style=""></div>
<div id="content_alert" style=""></div>

<?php if( $o_VTA_OrdenBN->getOrdenEstado() == VTA_OrdenBN::ESTADO_ABIERTO ){ ?>
<div class="form-row mx-0">
	<div class="form-group col-md-6">
        <?php
        if( $o_VTA_OrdenBN->getOrdenTipoClasificacionId() == VTA_OrdenBN::TIPO_PRODUCTOS_TERMINADOS )
        {
            ?>
            <button type="button" id="btnAgregarPrFinal1" class="btn btn-primary btn-sm" onclick="buscarProductoFinalPopup(1,'');">Agregar Encofrado</button>
            <button type="button" id="btnAgregarPrFinal2" class="btn btn-primary btn-sm" onclick="buscarProductoFinalPopup(2,'');">Agregar Andamio</button>
            <?php
        }
        else
        {
            ?>
            <button type="button" id="btnAgregar" class="btn btn-primary btn-sm">[+] Productos</button>
            <button type="button" id="btnAgregarSrv" class="btn btn-primary btn-sm">[-] Servicios</button>
            <button type="button" id="btnAgregarCmm" class="btn btn-primary btn-sm">[*] Comentario</button>
            
            <script>
            $( "#btnAgregar" ).click( function(){ buscarProductosPopup(); } );
            $( "#btnAgregarSrv" ).click( function(){ buscarServiciosPopup(); } );
            $( "#btnAgregarCmm" ).click( function(){ agregarComentario(); } );
            </script>
            <?php
        }
        ?>
	</div>
</div>

<?php } ?>

<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()?>">

<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>


<table cellpadding="0" cellspacing="0" width="100%" border="0" style="">
    <tr>
        <td align="center" >
            <!-- <input type="button" class="button" value="Salir" onclick="location.href='<?php echo buildUrl( 'cot/list' ) ?>'"> -->
            <div id="s_ImagenLoad" style="display: none;"><img src="<?php echo Constantes::ROOT_DIR_APP ?>web/images/progress.gif" border="0"/>&nbsp;<label class="laber req">Procesando...</label></div>
        </td>
    </tr>
</table>

<div id="content_result_grid_pl1" style="display:none;">
    <table class="grid" cellspacing="0" cellpadding="0" borde r="0" align="center" width="100%" style="border-bottom: 1px solid #999999;">
        <tbody id="content_copy_nvo">
            <tr>
                <td align="center">&nbsp;</td>
                <td align="center"><input type="text" class="text" name="IdItem" id="IdItem" value="" style="width: 85%; text-align: center;" ></td>
                <td align="" id="DescripcionCompleta">&nbsp;</td>
                <!-- <td align="center">
                    <select class="combo" name="IdLote" id="IdLote" onchange="buscarStockActual( this );" style="width: 90%;">
                    </select>
                </td> -->
                <td align="center" id="ItemStock" style="cursor:pointer; color:#2743B2; text-decoration:underline;" onclick="buscarResumenStock( $( '#content_nvo tr #IdItem' ).val() );">&nbsp;</td>
                
                <td align="center">
                    <!--<input type="text" class="text number" name="CantidadPedida" id="CantidadPedida" value="" style="width: 60%; text-align: center;" 
                                                           onkeypress="return NumCheckDecimal( event, this );">-->
                    <input type="text" class="text number" name="CantidadPedida" id="CantidadPedida" value="" style="width: 60%; text-align: center;" 
                                                           onkeypress="return NumCheckDecimal( event, this );"
                                                           onfocus="this.select()"
                                                           >
                    
                    <input type="hidden" name="CantidadPedidaUni" id="CantidadPedidaUni" value="0"/>
                </td>
                
                <!--<td align="center">
                    <input type="text" class="text number" name="CantidadPedidaUni" id="CantidadPedidaUni" value="" style="width: 60%; text-align: center;" 
                                                           onkeypress="return NumCheckEntero( event, this );">
                </td>-->
                
                <!--<td align="center" id="IdUnidad">&nbsp;</td>-->
                <td align="center">
                    <input type="text" class="text number" name="PrecioUnitario" id="PrecioUnitario" value="" readonly="readonly" 
                    									   style="width: 60%; text-align: center;" 
                                                           onkeypress="return NumCheckDecimal( event, this );">
                </td>
                <td align="center" id="AfectoImpuesto2Flag">&nbsp;</td>
                <td align="center">&nbsp;</td>
                <td align="center">
                    <input type="hidden" name="NoAfectoImpuestoVentasFlag" id="NoAfectoImpuestoVentasFlag" value=""/>
                    <input type="button" id="btnGuardar" class="button" value="Guardar" onclick="executeSaveOrderDetail( this );">
                </td>
            </tr>
        </tbody>
    </table>
</div>

<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<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
if( $o_VTA_OrdenBN->getOrdenTipoClasificacionId() == VTA_OrdenBN::TIPO_PRODUCTOS_TERMINADOS )
{
    $s_NombreFuncion = "saveOrdenProdFinal";
}
else
{
    $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 );
    
}
buscarProductoFinalPopup = function( tipo, iddet )
{
    if( tipo == 1 )
    {
    	$( "#exampleModalLongTitle" ).html( "Agregar Encofrado" );
    }
    if( tipo == 2 )
    {
    	$( "#exampleModalLongTitle" ).html( "Agregar Andamio" );
    }
    $( '#exampleModalCenter' ).modal( { show:true } );
    var s_almacen_id = $( "#IdAlmacen" ).val();
    var frameSrc = '<?=buildUrl( 'cot/prodFinal' )?>' + 'moneda_cod/<?=$o_VTA_OrdenBN->getMonedaCod()?>/IdAlmacen/' + s_almacen_id + '/i_Id/<?=$i_Id?>' + '/tipo/' + tipo + '/idprod/' + iddet;
    $( '#iframe_id' ).attr( "src", frameSrc );
}
eliminarProductoFinalPopup = function( id )
{
    x = confirm( "Esta seguro de eliminar el Sistema y sus detalles?" );
    if( x )
    {
    	blockContent( "content_result_grid1" );

        var str_serialize = "i_Id=<?=$i_Id?>&s_TipoProc=delparent&id_parent=" + id;

        executeAjaxJson
        ( 
            "<?php echo buildUrl( 'cot/'.$s_NombreFuncion ) ?>", 
            str_serialize,
            function( o_json )
            {
                if( o_json.error )
                {
                    showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                unBlockContent( "content_result_grid1" );
                executeFindDetail();
                b_GuardarItem = false;
            } 
       );
    }
}
eliminarProductoFinalDetPopup = function( id )
{
    x = confirm( "Esta seguro de eliminar este detalle?" );
    if( x )
    {
    	blockContent( "content_result_grid1" );

        var str_serialize = "i_Id=<?=$i_Id?>&s_TipoProc=deldet&id_det=" + id;

        executeAjaxJson
        ( 
            "<?php echo buildUrl( 'cot/'.$s_NombreFuncion ) ?>", 
            str_serialize,
            function( o_json )
            {
                if( o_json.error )
                {
                    showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                unBlockContent( "content_result_grid1" );
                executeFindDetail();
                b_GuardarItem = false;
            } 
       );
    }
}
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 omentario" );
    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>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->

<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- 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 Cotizaci&oacute;n</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>
<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->

<!-- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<!-- Modal 4-->
<style type="text/css">
/*#exampleModalRenovacion .modal
{
    padding: 0 !important;
}
#exampleModalRenovacion .modal-dialog {
    max-width: 70% !important;
    height: 70%;
    
}

#exampleModalRenovacion .modal-content 
{
    height: 70%;
}*/
</style>
<div class="modal fade" id="exampleModalRenovacion" tabindex="-1" role="dialog" aria-labelledby="exampleModalRenovacionTitle" aria-hidden="true">
    <!--<div class="modal-dialog modal-dialog-Renovacion" role="document">-->
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalRenovacionTitle">Renovar 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_Renovacion" src="" style="" width="99.6%" height="99%" frameborder="0"></iframe> -->
                <div id="content_Renovacion">
                    <div class="form-group">
                        <label for="txt_renovacion" class="col-form-label">D&iacute;as de Renovaci&oacute;n:</label>
                        <select class="form-control form-control-sm custom-select my-0 mr-sm-2" name="txt_renovacion" id="txt_renovacion" onchange="" >
                            <option value=""> - SELECCIONE - </option>
                            <?php for( $i=30; $i<=360; $i++ ) { ?>
                                <?php if( fmod( $i, 30 ) ){ continue; } ?>
                            <option value="<?=$i?>" > <?=$i?> D&iacute;as </option>
                            <?php } ?>
                        </select>
                    </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="copiarOrdenVenta( 'A' );">Renovar</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
abrirPopupRenovacion = function( id_item, secuencia )
{
    $( "#txt_renovacion" ).val( '' );
    $( '#exampleModalRenovacion' ).modal( { show:true } );
}
</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>
anularOrdenVenta = function()
{
    x = confirm( "Esta seguro de anular la Orden?" );
    if( x )
    {
        var strFormSerialize = "i_Id=<?=$i_Id?>";
        executeAjaxJson
        ( 
            "<?php echo buildUrl( 'cot/deleteRow' ) ?>", 
            strFormSerialize,
            function( o_json )
            {
                if( o_json.error )
                {
                    showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    return false;
                }
                location.reload();
            } 
        );
    }
}
facturarOrdenVenta = function()
{
    if( $( "#IdFormaPago" ).val() == "" )
    {
        alert( "Debe de Seleccionar la Forma de Pago para el Documento." );
        return false;
    }
    //VALIDACIO POR LOTES SELECCIONADOS
    var b_ControlSave = true;
    var a_elm_lotes = $( "#content_detail" ).find( "select[name='IdLote[]']" );
    $.each
    (
        a_elm_lotes, function( index, item )
        {
            if( $( item ).val() == "" )
            {
            	var s_descripcion_item = $( $( item ).closest( 'tr' ) ).find( 'td:eq( 2 )' ).html();
            	alert( "El Producto \"" + s_descripcion_item + "\" le falta Seleccionar el Lote. Por favor, Fijese en el Producto la Fecha de Vencimiento." )
                b_ControlSave = false;
                return false;
            }
        }
    );
    if( !b_ControlSave )
    {
        return false;
    }
    
    x = confirm( "Esta seguro de Facturar la Orden?" );
    if( x )
    {
        blockContent( "form1" );
        var strFormSerialize = "i_Id=<?=$i_Id?>";
        executeAjaxJson
        ( 
            "<?php echo buildUrl( 'cot/cerrarOrden' ) ?>", 
            strFormSerialize,
            function( o_json )
            {
                console.log( o_json );
                if( o_json.error )
                {
                	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                    unBlockContent( "form1" );
                    return false;
                }
                location.reload();
            } 
        );
    }
}
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 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;
            } 
       );
    }
}
</script>

<script>
var b_GuardarItem    = false;
var MontoTotalaPagarDocu = 0;
var SaldoTotalDocumento  = 0;

executeFindItem = function()
{
    console.log( "executeFindItem" );
    var item_code       = $( "#content_nvo tr #IdItem" ).val();
    var s_almacen_id    = $( "#IdAlmacen" ).val()
    var str_serialize   = "s_ItemId=" + item_code + "&IdAlmacen=" + s_almacen_id;
    executeAjaxJson
    ( 
        "<?php echo buildUrl( 'pro/findItem' ) ?>", 
        str_serialize,
        function( o_json )
        {
            if( o_json.error )
            {
            	showAlertBootStrap( 'content_alert', 'alert-danger', o_json.mensaje_error );
                return false;
            }
            if( o_json.result )
            {
                b_GuardarItem = true;
                $( "#content_nvo tr #DescripcionCompleta" ).html( o_json.DescripcionCompleta );
                $( "#content_nvo tr #AfectoImpuesto2Flag" ).html( o_json.NoAfectoImpuestoVentasFlag );
                $( "#content_nvo tr #IdUnidad" ).html( o_json.UnidadVenta );
                $( "#content_nvo tr #ItemStock" ).html( o_json.ItemStock );
                $( "#content_nvo tr #NoAfectoImpuestoVentasFlag" ).val( o_json.NoAfectoImpuestoVentasFlag );
                //ahora el precio de venta
                $( "#content_nvo tr #PrecioUnitario" ).val( o_json.PrecioVenta );

                //cargar el lote:
                $( "#content_nvo tr #IdLote" )[0].options.length = 0;
                if( o_json.a_Lotes )
                {
                    $.each
                    (
                        o_json.a_Lotes, function( index, item )
                        {
                        	$( "#content_nvo tr #IdLote" ).append( "<option value=" + item.IdLote + ">" + item.IdLote + " - " + item.FechaVencimiento + "</option>" );
                            //$( $( elm_sel ).closest( 'tr' ) ).find( "input[name='FechaVencimiento[]']" ).val( item.FechaVencimiento );
                            //console.log( $( $( elm_sel ).closest( 'tr' ) ).find( "select[name='IdLote[]']" ) );
                            //console.log( item );
                        }
                    );
                    $( "#content_nvo tr #IdLote" ).trigger( "change" ); //CON ESTE ENVENTO SE REGISTRA AUTOMATICAMENTE
                }
            }
        } 
    );
}
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
            }
        } 
    );
}
LimpiarValores = function()
{
    executeFindItem();
}
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  = "";
        } 
    );
}
</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();
        
        //var str_serialize = $( '#form1' ).serialize();
        //var str_serialize = "s_TipoProc=upd&CodigoBarra=" + s_CodigoBarra + "&IdCompania=" + $( "#IdCompania" ).val() + "&IdAlmacen=" + $( "#IdAlmacen" ).val() + "&IdLote=" + lote_id + "&i_Id=" + i_Id + "&CantidadPedida=" + CantidadPedida;
        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();
            } 
        );
    }
}
</script>
<script>
//ESCAPE, DETECTA EL F5, CTRL+F5
$( document ).bind
(
    'keyup', 
    function( e ) 
    {
        pr( e.which );
        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( "" );
            executeFindDetail();
        }
    }
);
</script>

<script>
executeFindDetail();
</script>

<?php if( $readonly ){ ?>
<script type="text/javascript">
$( "input[type=button]" ).each
(
    function( key, elm ) 
    {
        elm.remove();
    }
);
</script>
<?php } ?>

