<?php
session_start();
if( $_SESSION["user"] == "" || $_SESSION["passwd"] == "" || $_SESSION["admin"] == false ) {
   mysqli_close($conn);
   header("Location: index.php");
}


include_once('db_config.php');

$Title    = "Ingreso de Asientos";
$Desde  = isset($_POST['desde']) ? $_POST["desde"]  : "";
$Hasta  = isset($_POST['hasta']) ? $_POST["hasta"]  : "";
$nroAsiento  = isset($_POST['nroAsiento']) ? $_POST["nroAsiento"] : "";
$scroll  = isset($_POST['scroll']) ? $_POST["scroll"] : "";
$Inicio = $_SESSION["inicio"];
$Fin = $_SESSION["fin"];
$element_id = "";
$Descripcion = $_SESSION["Descripcion_Ejercicio"];

if( empty($Desde) ) {        
   if( $_SESSION["Desde"] != "" ) $Desde = $_SESSION["Desde"];
   else $Desde = date("01-01-Y");   
}

if( empty($Hasta) ) {        
   if( $_SESSION["Hasta"] != "" ) $Hasta = $_SESSION["Hasta"];
   else $Hasta = date("31-12-Y");   
}

$Ejercicio = $_SESSION["ID_Ejercicio"];

$_SESSION["Desde"] = $Desde;
$_SESSION["Hasta"] = $Hasta;
$D = substr( $Desde, 6, 4 ) . "/" . substr( $Desde, 3, 2 ) . "/" . substr( $Desde, 0, 2 );
$H = substr( $Hasta, 6, 4 ) . "/" . substr( $Hasta, 3, 2 ) . "/" . substr( $Hasta, 0, 2 ); 

$Fecha = "";

if( empty($LastDay) ) {       
   $LastDay = date("d/m/Y"); 
}

$_SESSION["Date"] = $LastDay;

include 'headerImpuestos.php'; 
?>

<style>
.dropdown-content {
  overflow-x: hidden;
}

#therow {
   background-color: white; 
}

#workflow:hover {
   background-color: #cfd8dc; 
  background-color: #16a2d6;
  color: white;
}

.data {
   margin-top: 0; 
   margin-bottom: 0;                       
   padding-left: 5%;
}


.margin {
   margin-top: 0; 
   margin-bottom: 0; 
}

.margin-label {
   margin-top: 5px; 
}

input[type=select]:disabled + label,
input[type=select]:disabled,
input[type=textarea]:disabled,
input[type=textarea] + label,
textarea.materialize-textarea:disabled + label, 
input[type=text] + label,
input[type=text]:disabled + label {
   color: black;
}

textarea.materialize-textarea:disabled,
input[type=text]:disabled {
   color: #303030;
   color: black;
}

input:not([type]):disabled, input:not([type])[readonly="readonly"],
input[type=text]:not(.browser-default):disabled,
input[type=text]:not(.browser-default)[readonly="readonly"],
input[type=password]:not(.browser-default):disabled,
input[type=password]:not(.browser-default)[readonly="readonly"],
input[type=email]:not(.browser-default):disabled,
input[type=email]:not(.browser-default)[readonly="readonly"],
input[type=url]:not(.browser-default):disabled,
input[type=url]:not(.browser-default)[readonly="readonly"],
input[type=time]:not(.browser-default):disabled,
input[type=time]:not(.browser-default)[readonly="readonly"],
input[type=date]:not(.browser-default):disabled,
input[type=date]:not(.browser-default)[readonly="readonly"],
input[type=datetime]:not(.browser-default):disabled,
input[type=datetime]:not(.browser-default)[readonly="readonly"],
input[type=datetime-local]:not(.browser-default):disabled,
input[type=datetime-local]:not(.browser-default)[readonly="readonly"],
input[type=tel]:not(.browser-default):disabled,
input[type=tel]:not(.browser-default)[readonly="readonly"],
input[type=number]:not(.browser-default):disabled,
input[type=number]:not(.browser-default)[readonly="readonly"],
input[type=search]:not(.browser-default):disabled,
input[type=search]:not(.browser-default)[readonly="readonly"],
textarea.materialize-textarea:disabled,
textarea.materialize-textarea[readonly="readonly"] {
  color: black;
  border-bottom: 1px dotted rgba(0, 0, 0, 0.42);
}

input:not([type]):disabled + label,
input:not([type])[readonly="readonly"] + label,
input[type=text]:not(.browser-default):disabled + label,
input[type=text]:not(.browser-default)[readonly="readonly"] + label,
input[type=password]:not(.browser-default):disabled + label,
input[type=password]:not(.browser-default)[readonly="readonly"] + label,
input[type=email]:not(.browser-default):disabled + label,
input[type=email]:not(.browser-default)[readonly="readonly"] + label,
input[type=url]:not(.browser-default):disabled + label,
input[type=url]:not(.browser-default)[readonly="readonly"] + label,
input[type=time]:not(.browser-default):disabled + label,
input[type=time]:not(.browser-default)[readonly="readonly"] + label,
input[type=date]:not(.browser-default):disabled + label,
input[type=date]:not(.browser-default)[readonly="readonly"] + label,
input[type=datetime]:not(.browser-default):disabled + label,
input[type=datetime]:not(.browser-default)[readonly="readonly"] + label,
input[type=datetime-local]:not(.browser-default):disabled + label,
input[type=datetime-local]:not(.browser-default)[readonly="readonly"] + label,
input[type=tel]:not(.browser-default):disabled + label,
input[type=tel]:not(.browser-default)[readonly="readonly"] + label,
input[type=number]:not(.browser-default):disabled + label,
input[type=number]:not(.browser-default)[readonly="readonly"] + label,
input[type=search]:not(.browser-default):disabled + label,
input[type=search]:not(.browser-default)[readonly="readonly"] + label,
textarea.materialize-textarea:disabled + label,
textarea.materialize-textarea[readonly="readonly"] + label {
  color: rgba(0, 0, 0, 0.42);
  color: black;
  font-size: 0.9rem;
}

/* Text inputs */
input:not([type]),
input[type=text]:not(.browser-default),
input[type=password]:not(.browser-default),
input[type=email]:not(.browser-default),
input[type=url]:not(.browser-default),
input[type=time]:not(.browser-default),
input[type=date]:not(.browser-default),
input[type=datetime]:not(.browser-default),
input[type=datetime-local]:not(.browser-default),
input[type=tel]:not(.browser-default),
input[type=number]:not(.browser-default),
input[type=search]:not(.browser-default),
textarea.materialize-textarea {
  font-size: 14px;
  color: blue;
}

input:not([type]):focus,
input[type=text]:not(.browser-default):focus,
input[type=password]:not(.browser-default):focus,
input[type=email]:not(.browser-default):focus,
input[type=url]:not(.browser-default):focus,
input[type=time]:not(.browser-default):focus,
input[type=date]:not(.browser-default):focus,
input[type=datetime]:not(.browser-default):focus,
input[type=datetime-local]:not(.browser-default):focus,
input[type=tel]:not(.browser-default):focus,
input[type=number]:not(.browser-default):focus,
input[type=search]:not(.browser-default):focus,
textarea.materialize-textarea:focus {
  font-size: 15px;
  color: blue;
}


.input-field > label {
  font-size: 0.9rem;
}


.btn:hover, .btn-large:hover, .btn-small:hover {
    background-color: #2bbbad;
    background-color: #0F7095;
}

.dropdown-content li > a, .dropdown-content li > span,
.input-field {
   font-size: 14px !important;
}
.select-wrapper input.select-dropdown,
.select-dropdown dropdown-trigger {
   font-size: 14px !important;
//   line-height: 1;
   height: 2.3rem;
}

.select-dropdown.dropdown-content li.selected:hover {
    background-color: rgba(0, 0, 0, 0.03);
    color: black;
}

.select-dropdown.dropdown-content li:hover {
    background-color: rgba(0, 0, 0, 0.08);
    background-color: #16a2d6;
    color: white;
}
.dropdown-content li > a, .dropdown-content li > span {
    color: inherit;
}
.page-content li li {
    list-style-type: circle;
    list-style-type: none;
}

/*
.open {
    background: url('images/details_open.png') no-repeat center center;
    cursor: pointer;
}
.close {
    background: url('images/details_close.png') no-repeat center center;
}
*/

.myDisabled {
   color: blue !important;
   font-size:13px !important;
   height: 35px  !important;
}
.myEnabled {
   color: blue !important;
//   opacity: 0.8;
   font-size:13px !important;
   height: 35px  !important;
}
.myError {
   color: red !important;
   font-size:13px !important;
   height: 35px  !important;
   font-weight: bold !important;
}

//#detalles { height: 95% !important ; }

.modal-content {
   background-color:white !important;
   border: none;
}

.datepicker-table td {
    border: none;
}

.modal {
 overflow-y:inherit;
 }

.input-field {
   margin-top:12px;
   margin-bottom:12px;
}

.rowh {
   height: 25px !important;
}
.data {
   padding-left:0;
}
.cliente {
    cursor: pointer;
}
.red {
   color:red !important;
}
.yellow {
   color:#009688 !important;
}
.activetr {
   background-color: rgb( 0, 0, 0, 0.2 ) !important;
   background-color: rgb( 255, 210, 77, 1 ) !important;

}

.row {
   width: 100% !important;

}
</style>



   <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <div id="content">
  <div class="container" style="width:90%" >
<!--    <div style="height: 15px;"></div> -->
    <div class="col l9 m12 s12">
      <div class="page-content">
<!--        <div style="height:20px;"></div> -->
 <?php
         $date = date_create($D);
         $D1 = date_format($date, 'd-m-Y');

         $date = date_create($H);
         $H1 = date_format($date, 'd-m-Y');

         echo "<div class='row'>";
         echo "<div class='input-field col s12 red-text text-darken-4' style='font-size:15pt; text-decoration: underline;'>" . $Descripcion . "</div>";;
         echo "</div>";
         echo "<form id='asterisco' action='asientos.php' method='post'>";
         echo "<div class='row'>";
         echo "<div class='input-field col s2'>";
         echo "<label for='desde'>Desde</label>";
//       echo "<input id='desde' type='date' class='datepicker' data-value='" . $D . "' onChange='onChange(this);'>";
         echo "<input id='desde' type='text' class='datepicker' value='" . $D1 . "' onChange='onChange(this);'>";

         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<label for='hasta'>Hasta</label>";
         echo "<input id='hasta' type='text' class='datepicker' value='" . $H1 . "' onChange='onChange(this);'>";
         echo "</div>";
         echo "<div class='input-field col s3'>";
         echo "<button onclick='Submit();' class='btn waves-effect waves-light btn col s3' style='margin-top:5px; margin-left:30px; width:130px;' name='action'>Visualizar</button>";
         echo "</div>";
?>
          </row>  
          </form>
          <a onclick='newAsiento();' class='btn-floating btn-large waves-effect waves-light red' style='float:right; margin-right: 10px; margin-top:15px;'><i class='material-icons'>add</i></a>
           <div style="height:70px;"></div>
        </div>  

<style>
th {
 font-weight: normal;
 color: white;
}
#movimiento, ul li:hover, ul li a:hover, ul li a:focus {
 background-color: #eceff1;
}
</style>
<?php
  $isData = false;

  $sql = "select sql_no_cache id, Fecha, Asiento, Concepto, Debe, Haber, Estado, Asiento_Ordenado from asientos where fecha>='"  . $D . "' and fecha<='" . $H . "' and asientos.Borrado=0 and ejercicio='" . $Ejercicio . "' order by fecha, asiento_ordenado";
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {

    $Total_SinIVA = 0;
    $Total_IVA = 0;
    $Total_Ret = 0;
    $Total_Importe = 0;
    $isData = true;

    echo "<table id='detail' class='highlight' style='color:grey; font-weight:normal;'>";
    echo "<thead>";
      echo "<tr style='background-color: #007FFF; color:white;'>";
//      echo "<tr class='grey lighten-2' >";
        echo "<th style='width:2%;'>&nbsp</th>";
        echo "<th class='col s1' style='width: 10%; border-radius: 0;'>Fecha</th>";
        echo "<th class='col s1right-align' style='width: 9%; border-radius: 0;'>N&uacute;mero</th>"; 
        echo "<th class='col s2' style='width: 14%; border-radius: 0;'>Estado</th>"; 
        echo "<th class='col s4' style='width: 24%; border-radius: 0;' >Detalle</th>"; 
        echo "<th class='col s1 right-align' style='border-radius: 0;' >Debe</th>"; 
        echo "<th class='col s1 right-align' style='border-radius: 0;' >Haber</th>"; 
        echo "<th class='col s2 right-align' style='width: 14%; border-radius: 0;' >Saldo</th>"; 
        echo "<th style='width:3%;'>&nbsp</th>"; 
      echo "</tr>"; 
     echo "</thead>"; 
     echo "<tbody />"; 
     echo "</table>"; 
     echo "<tr>";
     echo "<td>";
     echo "<div id='therow' class='row' style='width: 100%; margin-left: 0px;'>"; 
     echo "<ul id='lista' class='collapsible' data-collapsible='accordion'>";
     $element_id = "";
    while($row = $result->fetch_assoc()) {

      $date = date_create($row["Fecha"]);
      $formatted = date_format($date, 'd-m-Y');

      $Oper[0] = $Oper[1] =  $Oper[2] =  $Oper[3] =  $Oper[4] =  $Oper[5] =  $Oper[6] = $Oper[7] = $Oper[8] = "";
      switch( $row["Estado"] ) {
         case 2:  $Op = "Abierto";  $Oper[1] = "selected"; break;
         case 3:  $Op = "Cerrado";  $Oper[2] = "selected"; break;
         default: $Op = ""; break; 
      }
      $ID   = $row["id"];
      $Debe = $row["Debe"];
      $Haber = $row["Haber"];
      $Saldo = $row["Saldo"];
      $Asiento = $row["Asiento"];
      $Asiento_Ordenado = $row["Asiento_Ordenado"];

      if( ( $a = $Asiento_Ordenado ) == 0 ) $a = $Asiento;

      echo "<li id='" . $ID . "' class='lista'>";
      if( $a == $nroAsiento ) {
         $active = " active";
         $element_id = $ID;
      }
      else $active = "";
      echo "<div class='collapsible-header" . $active . "' id='invoices'>";
         echo "<div class='row'>";
         echo "<div id='fechaAsiento" . $ID . "' class='col s2' style='width: 10%;'>" . $formatted . "</div>";
         echo "<div id='nroAsiento" . $ID . "' class='col s1 right-align' style='width: 8%;'>" . $a . "</div>"; 
         echo "<div class='col s1' style='width: 10%;'>" . $Op . "</div>";
         echo "<div id='desc" . $ID . "' class='col s4' style='width: 34%;'>" . $row["Concepto"] . "</div>";
         echo "<div class='col s1 right-align' style='width: 12%;'>" . number_format ( $Debe, 2, ',' ,  '.' ) . "</div>";
         echo "<div class='col s1 right-align' style='width: 12%;'>" . number_format ( $Haber, 2, ',' ,  '.' ) . "</div>";
         echo "<div class='col s2 right-align' style='width: 12%;'>" . number_format ( $Saldo, 2, ',' ,  '.' ) . "</div>";
         echo "<div hidden id='iidAsiento" . $ID . "'>" . $row["id"] . "</div>"; 
//         echo "<input type='hidden' id='iinumAsiento' value='" . $row["Asiento"] . "'>"; 
//         echo $row["id"] . "<br/>";
         echo "</div>";

      echo "</div>";
      echo "<div id='detail' class='collapsible-body col s12'>";

         /* --- Cargo Movimientos --- */
         $sql = "select sql_no_cache movimientos.id as id, asiento, movimiento, movimientos.cuenta, denominacion, debe, haber from movimientos left join cuentas on cuentas.cuenta=movimientos.cuenta where asiento=" . $row["Asiento"] . " and movimientos.borrado=0 order by movimiento";
         $result1 = $conn->query($sql);
         $Debe = $Haber = 0;
         echo "<ul id='movimientos' >";
         echo "<div class='row amber lighten-1' style='margin-bottom:0px;'>";
         echo "<div class='input-field col' style='width:2%;'>&nbsp</div>";
         echo "<div class='input-field col s1 underline right-align offset-1'>Movimiento</div>";
         echo "<div class='input-field col s2 underline'>Cuenta</div>"; 
         echo "<div class='input-field col s4 underline'>Denominacion</div>"; 
         echo "<div class='input-field col s2 underline right-align'>Debe</div>"; 
         echo "<div class='input-field col s2 underline right-align' style='margin-bottom:10px;'>Haber</div>"; 
         echo "</div>";
         if ($result1->num_rows > 0) {
             while($row1 = $result1->fetch_assoc()) {
               $Debe  += $row1["debe"];
               $Haber += $row1["haber"];
               $mID   = $row1["id"];
               echo "<li id='" . $mID . "' class='listamov' >";
               echo "<div class='row data'>";
               echo "<div class='input-field col' style='width:1%;'>&nbsp</div>";
               echo "<div id='mMov" . $mID . "' class='input-field col s1 right-align offset-1' readonly='readonly'>" . $row1["movimiento"] . "</div>";
               echo "<div id='mCuenta" . $mID . "' class='input-field col s2'>" . $row1["cuenta"] . "</div>"; 
               echo "<div id='mDenom" . $mID . "' class='input-field col s4'>" . $row1["denominacion"] . "</div>"; 
               echo "<div id='mDebe" . $mID . "' class='input-field col s2 right-align'>" . number_format( $row1["debe"], 2, ',' ,  '.' )  . "</div>"; 
               echo "<div id='mHaber" . $mID . "' class='input-field col s2 right-align'>" . number_format( $row1["haber"], 2, ',' ,  '.' )  . "</div>"; 
               echo "<input type='hidden' id='idMov" . $mID . "'' value='" . $mID . "'>"; 
               echo "<input type='hidden' id='idAsiento" . $mID . "' value='" . $row["id"] . "'>"; 
               echo "<input type='hidden' id='numAsiento" . $mID . "' value='" . $row["Asiento"] . "'>"; 
               echo "<input type='hidden' id='ifechaAsiento" . $mID . "' value='" . $row["Fecha"] . "'>"; 
               echo "</div>";
               echo "</li>";
            }
         }
         else {
               $mID   = $row["id"];    // Id del asiento
               echo "<li id='" . $mID . "' class='listamov' modo='sin_mov' >";
//               echo "<li id='sin_mov' class='listamov' >";
               echo "<div class='row data'>";
               echo "<div id='nuevoM' class='input-field col s4' readonly='readonly'>Sin Movimientos</div>";
               echo "<input type='hidden' id='idMov" . $mID . "'' value=''>"; 
               echo "<input type='hidden' id='idAsiento" . $mID . "' value='" . $row["id"] . "'>"; 
               echo "<input type='hidden' id='numAsiento" . $mID . "' value='" . $row["Asiento"] . "'>"; 
               echo "<input type='hidden' id='ifechaAsiento" . $mID . "' value='" . $row["Fecha"] . "'>"; 
               echo "</div>";
               echo "</li>";
         }
         echo "<div class='row data amber lighten-1'>";
         echo "<div class='input-field col' style='width:27px;'>&nbsp</div>";
         echo "<div class='input-field col s2 right-align offset-s7'>" . number_format ( $Debe, 2, ',' ,  '.' ) . "</div>"; 
         echo "<div class='input-field col s2 right-align' style='margin-bottom:10px;'>" . number_format ( $Haber, 2, ',' ,  '.' ). "</div>"; 
         echo "</div>";
         echo "</ul>";
      echo "</div>";
      echo "</li>"; 
    }
   } 
   mysqli_close($conn);
   echo "<div id='dropEmpresa' style='float: right;'>";
   echo "<ul id='dropdownEmpresa' class='dropdown-client' style='z-index:10; display:none;'>";
   echo "</ul>"; 
   echo "</div>";
   echo "<ul id='dropdownMenu' class='dropdown-content' hidden='hidden'>";
     echo "<li id='l1' onclick='listClick(this);'><a><i class='material-icons left'>delete</i>Borrar</a></li>"; 
     echo "<li id='l2' onclick='listClick(this);'><a><i class='material-icons left'>mode_edit</i>Editar</a></li>"; 
     echo "<li id='l4' onclick='listClick(this);'><a><i class='material-icons left'>content_copy</i>Copiar</a></li>"; 
     echo "<li class='divider'></li>"; 
     echo "<li id='l3' onclick='listClick(this);'><a><i class='material-icons left'>add</i>Nuevo</a></li>"; 
   echo "</ul>";
?>        
   </div>
<!--
   <a id='new' onclick='newAsiento();' class='btn-floating btn-large waves-effect waves-light red' style='float:right; margin-right: 10px; margin-top:15px;'><i class='material-icons'>add</i></a>
-->
   <div style="height:100px;"></div>
   </div>
   </div>

  <!-- Modal Structure -->
<style>
.modal { width: 75% !important ; max-height: 85% !important } /* increase the width and height! */
</style>

  <div id="modal-movimiento" class="modal modal-footer">
    <div class='modal-content'>
 <?php
         echo "<div class='row data'>";
         echo "<div class='input-field col s1 right-align'></div>";
         echo "<div id='mov-title' class='offset-s1' style='font-size: 1.3em; padding-bottom: 30px;'>Nuevo Movimiento</div>";
         echo "</div>";
         echo "<div class='row data'>";
         echo "<div style='height:10px;'></div>";
         echo "<div class='input-field col s1 right-align'></div>";

         echo "<div class='input-field col s1 right-align'>";
         echo "<input id='inumero' type='text' value='' placeholder=' ' class='right-align'>";
         echo "<label class='active' for='inumero' readonly>Numero</label>";
         echo "</div>";

         echo "</div>";
         echo "<div style='height: 10px;'></div>";
         echo "<div class='row data'>";
         echo "<div class='input-field col s1 margin-label'></div>";
         echo "<div class='input-field col s2 margin'>";
         echo "<input id='icuenta' type='text' value='' placeholder=' ' onChange='onChange(this);'>";
         echo "<label class='active' for='icuenta'>Cuenta</label>";
         echo "</div>";
         echo "<div class='input-field col s4 margin'>";
         echo "<input id='idenom' type='text' value='' placeholder=' ' disabled>";
         echo "<label class='active' for='idenom'>Denominacion</label>";
         echo "</div>";
         echo "<input type='hidden' id='iid' value=''>"; 
         echo "</div>";

         echo "<div class='row data'>";
         echo "<div class='input-field col s1 right-align margin-label'></div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='idebe' type='text' class='right-align' placeholder=' 'style='height: 2em;' value='0.00' onChange='onChange(this);'>";
         echo "<label class='active' for='idebe'>Debe</label>";
         echo "</div>";

         echo "<div class='input-field col s2'>";
         echo "<input id='ihaber' type='text' class='right-align' placeholder=' 'style='height: 2em;' value='0.00' onChange='onChange(this);'>";
         echo "<label class='active' for='ihaber'>Haber</label>";
         echo "</div>";
         echo "</div>";

         echo "<input type='hidden' id='iID' value=''>"; 
         echo "<input type='hidden' id='iAsiento' value=''>"; 
         echo "<input type='hidden' id='iFechaAsiento' value=''>"; 
         echo "<input type='hidden' id='inumAsiento' value=''>"; 

         echo "<div id='idropCuentas' style='float: right;'>";
         echo "<ul id='idropdownCuentas' class='dropdown-client' style='z-index:10; display:none;'>";
         echo "</ul>"; 
         echo "</div>";
?>
    </div>
    <div style='height: 25px;'></div>
    <div class="modal-footer">
      <a onclick="Cancel();" class="modal-action modal-close waves-effect waves-green btn-flat ">Cancelar</a>
      <a onclick="Accept();" id='updateBtn' class="waves-effect waves-green btn-flat  disabled hide">Actualizar</a> 
    </div>
    <div style='height: 10px;'></div>
  </div>
  <!-- End Modal -->

<!--  Modal Asientos -->
<?php
  echo "<div id='modal-asiento' class='modal modal-footer' >";
    echo "<div class='modal-content'>";
         echo "<div class='row data'>";
         echo "<div class='input-field col s1'></div>";
         echo "<div id='asiento-title' style='font-size: 1.3em; padding-bottom: 20px;'>Nuevo Asiento</div>";
         echo "</div>";

         echo "<div class='row data'>";
         echo "<div class='input-field col s2 offset-s1'>";
         echo "<label for='fechaAsiento'>Fecha</label>";
         echo "<input id='fechaAsiento' type='text' value='' placeholder=' ' onChange='onChange(this);'>";
         echo "</div>";
         echo "</div>";

         echo "<div class='row data'>";
         echo "<div class='input-field col s6 offset-s1'>";
         echo "<input id='descAsiento' type='text' value='' placeholder=' ' onChange='onChange(this);'>";
         echo "<label class='active' for='descAciento'>Descripcion</label>";
         echo "</div>";
         echo "</div>";

         echo "<div class='row data'>";
         echo "<div class='input-field col s4 offset-s1'>";
             echo "<select id='tipo_asiento'>"; 
             echo "<option value='0' selected>Normal</option>";
             echo "<option value='2'>Apertura</option>";
             echo "<option value='1'>Cierre</option>";
             echo "</select>"; 
         echo "<label>Tipo de Asiento</label>"; 
         echo "</div>"; 
         echo "<input type='hidden' id='xAsiento' value=''>"; 
         echo "</div>"; 


    echo "</div>";   // modal-content
//    echo "<div style='height: 25px;'></div>"; 
    echo "<div class='modal-footer'>"; 
      echo "<a onclick='Cancel();' class='modal-action modal-close waves-effect waves-green btn-flat'>Cancelar</a>"; 
      echo "<a onclick='AcceptAsiento();' id='asientoBtn' class='waves-effect waves-green btn-flat disabled hide'>Actualizar</a>"; 
    echo "</div>"; 
    echo "<div style='height: 10px;'></div>"; 
  echo "</div>";  // modal-asiento
  // <!-- End Modal -->

  echo "<div id='modal-fecha' class='modal modal-footer' >";
    echo "<div class='modal-content'>";
         echo "<div class='row data'>";
         echo "<div class='input-field col s2'>";
         echo "<label for='fechaas'>Fecha</label>";
         echo "<input id='fechaas' type='text' class='datepicker' value=''>";
         echo "</div>";
         echo "</div>";
    echo "</div>";   // modal-content
  echo "</div>";  // modal-fecha

?>

   <script type="text/javascript" src="js/jquery.min.js"></script>
   <script type="text/javascript" src="js/jquery.form.js"></script> 
   <script type="text/javascript" src="materialize/1.0.0/js/materialize.min.js"></script>
   <script src="js/numeral.min.js"></script>
   <script src="js/jquery.maskedinput.min.js" type="text/javascript"></script>
<style>
.dropdown-client {
   background-color: white;
   opacity: 1;
   overflow-y: auto;
   border-bottom: 1px solid #d0d0d0;
   box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}
ul.dropdown-client li {
   line-height:3em;
   height:3em;
   vertical-align: middle;
   color: #009688;
   min-height: 3em;
   text-align: left;
   padding: 0px 16px;
}
ul.dropdown-client li:hover {
 background-color:#90a4ae;
}
</style>
<script>

   var keyTimeout;
   var newflag = false;
   var searchflag = 0;
   var found = false;
   var inlista = false;             // Lista de Asientos = false
   var ID = "";
   var nroAsiento = "";
   var fechaAsiento = "";
   var edit = false;
   var mov  = false;
   var lastDate = <?php echo json_encode($LastDay); ?>;

   // Post to the provided URL with the specified parameters.
   function post(path, parameters) {
      var form = $('<form></form>');

       form.attr("method", "post");
       form.attr("action", path);

       $.each(parameters, function(key, value) {
           var field = $('<input></input>');
           field.attr("type", "hidden");
           field.attr("name", key);
           field.attr("value", value);
           form.append(field);
       });

       // The form needs to be a part of the document in
       // order for us to be able to submit it.
       $(document.body).append(form);
      form.submit();
   };

  $(document).ready(function() {
     var scroll = <?php echo(json_encode($scroll)); ?>;

      $('.dropdown-trigger').dropdown({
         "hover": true,
         "constrainWidth": false,
         "coverTrigger": false
      });


    $('.collapsible').collapsible({
         accordion : false,
         onOpenStart: function(el) { captureAsiento(el); } 
    });

//    $('select').material_select();
    $('select').formSelect();

    $('.modal').modal({dismissible: false, outDuration: 0, startingTop: '4%', endingTop: '10%', 
                  onOpenStart: function(el) { modalOpen(el); }
    });

    $('.datepicker').datepicker({
       selectMonths: true, // Creates a dropdown to control month
       selectYears: 15, // Creates a dropdown of 15 years to control year
       months: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
       monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
       weekdays: [ 'Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado' ],
       weekdaysShort: [ 'Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab' ],
       weekdaysLetter: [ 'D', 'L', 'M', 'M', 'J', 'V', 'S' ],
       today: 'Hoy',
       clear: 'Borrar',
       cancel: 'Cerrar',
       format: 'dd-mm-yyyy',
       formatSubmit: 'yyyy-mm-dd'
    });

     $(window).scroll(function () {
         $( "#dropdownCuentas" ).css( "top", $(document).scrollTop() - 80 );
     });

      jQuery(function($){
          $("#icuenta").mask("99999999",{placeholder:" ", autoclear: false});
          $("#fechaAsiento").mask("99/99/9999",{placeholder:" ", autoclear: false});
      });

   
      // Asientos
      $( ".lista" ).contextmenu(function(ev) {

          if( inlista == true  ) {
               ev.preventDefault();
               return;
         }
          
          if( $( "#dropdownMenu" ).hasClass( "active" ) ) {
               ev.preventDefault();
               $( "#dropdownMenu" ).removeClass( "active" );
               $( "#dropdownMenu" ).css( "opacity", 0 );
               $( "#dropdownMenu" ).css( 'display', 'none' );
               inlista = false;
               return;
          }

          ev.preventDefault();
          $( "#dropdownMenu" ).attr( "option", ev.currentTarget.id );
          $( "#dropdownMenu" ).addClass( "active" );
          $( "#dropdownMenu" ).css( "opacity", 1 );
          $( "#dropdownMenu" ).css( 'display', 'inline-block' );
          $( "#dropdownMenu" ).css( "width", "200" );
          $( "#dropdownMenu" ).css( "color", "#009688" );
          $( "#dropdownMenu" ).css( "position", "absolute" );
          $( "#dropdownMenu" ).css( "vertical-align", "top" );

          $( "#dropdownMenu" ).css( "top", ev.pageY - 120 );
          $( "#dropdownMenu" ).css( "left", "65%" );
          $( "#dropdownMenu" ).css( 'margin', '0 0 15px 0' );
          $( "#dropdownMenu" ).css( 'line-height', '3em' );
      });

      // Lista Movimientos
      $( ".listamov" ).contextmenu(function(ev) {
          if( ev.currentTarget.innerText == "Sin Movimientos" ) {
//          if( ev.currentTarget.id == "sin_mov" ) {
             $("#l1").attr("hidden","hidden");
             $("#l2").attr("hidden","hidden");

          }
          else {
             $("#l1").removeAttr("hidden");
             $("#l2").removeAttr("hidden");
          }
          inlista = true;
          if( $( "#dropdownMenu" ).hasClass( "active" ) ) {
               ev.preventDefault();
               $( "#dropdownMenu" ).removeClass( "active" );
               $( "#dropdownMenu" ).css( "opacity", 0 );
               $( "#dropdownMenu" ).css( 'display', 'none' );
               inlista = false;
               return;
          }

          ev.preventDefault();
          $( "#dropdownMenu" ).attr( "option", ev.currentTarget.id );
          $( "#dropdownMenu" ).addClass( "active" );
          $( "#dropdownMenu" ).css( "opacity", 1 );
          $( "#dropdownMenu" ).css( 'display', 'inline-block' );
          $( "#dropdownMenu" ).css( "width", "200" );
          $( "#dropdownMenu" ).css( "color", "#009688" );
          $( "#dropdownMenu" ).css( "position", "absolute" );
          $( "#dropdownMenu" ).css( "vertical-align", "top" );

          $( "#dropdownMenu" ).css( "top", ev.pageY - 120 );
          $( "#dropdownMenu" ).css( "left", "65%" );
          $( "#dropdownMenu" ).css( 'margin', '0 0 15px 0' );
          $( "#dropdownMenu" ).css( 'line-height', '3em' );
      });

//      $("html, body").animate({ scrollTop: $("#new").scrollTop() }, 1000);

         if( scroll == "1" ) {

            var element_id = <?php echo(json_encode($element_id)); ?>;
            ScrollElement(element_id);
         }
//         if( scroll == "1" ) ScrollBottom();
  });   


   function captureAsiento(el) {

//      var ida = el.attr('id');
      var ida = el.id;
      nroAsiento = $("#nroAsiento" + ida ).html(); 
      fechaAsiento = $("#fechaAsiento" + ida ).html(); 
      
      $('#movimientos li').on('click', function(mid) {

          if( $( "#dropdownMenu" ).hasClass( "active" ) ) {
            $( "#dropdownMenu" ).removeClass( "active" );
            $( "#dropdownMenu" ).css( "opacity", 0 );
            $( "#dropdownMenu" ).css( 'display', 'none' );
            inlista = false;
         }

         var id = mid.currentTarget.id;
         var name = "#mCuenta" + id;

         var mmov = $("#mMov" + id).html();
         var cuenta = $("#mCuenta" + id).html();
         var denom = $("#mDenom" + id).html();

         var debe = $("#mDebe" + id).html();
         var haber = $("#mHaber" + id).html();

         debe = debe.replace('.','');
         haber = haber.replace('.','');

         debe = parseFloat(debe.replace(',','.'));
         haber = parseFloat(haber.replace(',','.'));

         $("#mov-title").html('Modificar Movimiento');
         $("#inumero").val(mmov);
         $("#icuenta").val(cuenta);
         $("#idenom").val(denom);
         $("#idebe").val(numeral(debe).format('0,0.00'));
         $("#ihaber").val(numeral(haber).format('0,0.00'));
         $("#iID").val(id);
         $("#inumAsiento").val(nroAsiento);

         console.log( "iID: " + id );

         $("#inumero").prop("readonly",true);
         $("#idenom").prop("readonly",true);

         /*
         if( debe > 0 ) {
            $("#idebe").prop("readonly",false);
            $("#ihaber").prop("readonly",true);
         }
         else {
            $("#idebe").prop("readonly",true);
            $("#ihaber").prop("readonly",false);
         } */

         edit = true;
         mov  = true;
         newMovimiento();
      });   
   }

   function newAsiento() {
      console.log( "ASIENTO!" );
      edit = false;
      mov  = false;
      $("#fechaAsiento").val('');
      $("#descAsiento").val('');

      $('#modal-asiento').modal('open');
      $("#fechaAsiento").focus();
   }

   function editAsiento() {
      console.log( "ASIENTO!" );
      var fecha = $("#fechaAsiento").val();
      var desc = $("#descAsiento").val();
      var tipo = $("#tipo_asiento").val();

//      console.log( fecha );
//      console.log( desc );
//      console.log( tipo );
      edit = true;
      mov  = false;
      $('#modal-asiento').modal('open');
      $("#fechaAsiento").focus();
   }


   function copyAsiento(el) {
      console.log( "COPY ASIENTO!" );
      $('#modal-fecha').modal('open');
      $("#fechaas").focus();
   }

   function newMovimiento() {

      $('#modal-movimiento').modal('open');
   }


   function ipopulateCuentas(key) {

      var cuenta = $.trim(key);
      $('#idropdownCuentas').empty();
      $.ajax({
          type: "POST",
          url: "recvCuentas.php",
          data: { 'key': cuenta },
              success: function(data){

                  var msg = JSON.parse(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#idropdownCuentas").append($("<li></li>").val(msg[i].option).html(msg[i].option + " " + msg[i].denominacion));
                  }
                  if( msg.length == 1 ) {
                     cuenta = msg[0].option;
                     $.ajax({
                         type: "POST",
                         url: "getCuenta.php",
                         data: { 'key': cuenta  },
                             success: function(data){
                                var msg = JSON.parse(data);
                       
                                $('#icuenta').val(msg.cuenta); 
                                $('#idenom').val(msg.denominacion); 
                                $( "#idebe" ).focus();
                           }
                    });
                  }
                  else {
                     if( msg.length > 0 ) {
                        ishowCuentas();
                        $( "#idropdownCuentas" ).focus();
                        searchflag = 2;
                     }
                     else {
                        Materialize.toast('No hay cuentas que comiencen con ese numero', 3000, 'rounded') 
                        hideCuentas();
                        $( "#icuenta" ).focus();
                     }
                  }
              }
      });
   }

   function ScrollBottom() {
      var $target = $('html,body'); 
      $target.animate({scrollTop: $target.height()}, 0);
   }

   function ScrollElement(element_id) {
      console.log(  "scroll to: " + element_id );
      var e = document.getElementById(element_id);
      if (!!e && e.scrollIntoView) {
          e.scrollIntoView();
      }
   }

   function ishowCuentas() {
      $( "#idropdownCuentas" ).addClass( "active" );
      $( "#idropdownCuentas" ).css( "opacity", 1 );
      $( "#idropdownCuentas" ).css( 'display', 'inline-block' );
      $( "#idropdownCuentas" ).css( "width", "35%" );
      $( "#idropdownCuentas" ).css( "height", "15%" );
      $( "#idropdownCuentas" ).css( "height", "90%" );
      $( "#idropdownCuentas" ).css( "color", "#009688" );
      $( "#idropdownCuentas" ).css( "position", "absolute" );
      $( "#idropdownCuentas" ).css( "vertical-align", "top" );

      var size = $(document).scrollTop();
      $( "#idropdownCuentas" ).css( "top", $(window).scrollTop() - 80 );
      $( "#idropdownCuentas" ).css( "top", "20" );
      $( "#idropdownCuentas" ).css( "left", "63%" );
      $( "#idropdownCuentas" ).css( 'margin', '0 0 15px 0' );
      $( "#idropdownCuentas" ).css( 'line-height', '3em' );
      $( "#icuenta" ).removeClass( "invalid" );

      $('#idropdownCuentas li').on('click', function() {

            found = false;
            var key = $(this).val();
            var fieldname = "";

            fieldname = '#icuenta';
            var name = $(this).html(); 
            $( fieldname ).val(name); 

            $.ajax({
                type: "POST",
                url: "getCuenta.php",
                data: { 'key': key  },
                    success: function(data){
                       var msg = JSON.parse(data);
                       
                       $('#icuenta').val(msg.cuenta); 
                       $('#idenom').val(msg.denominacion); 
                       found = true;
                     }
           });
           ihideCuentas();
      });   
   }

   function ihideCuentas() {
      $( "#idropdownCuentas" ).removeClass( "active" );
      $( "#idropdownCuentas" ).css( "opacity", 0 );
      $( "#idropdownCuentas" ).css( 'display', 'none' );
   }

   function modalOpen() {

      if( mov == true ) {
          $("#icuenta").on('keyup', function() {
               var cuenta = this.value;
               if( keyTimeout != undefined ) clearInterval(keyTimeout); 
               keyTimeout = setTimeout(function() {
                  clearInterval(keyTimeout); 

                  if( cuenta.length > 0 ) {
                     ipopulateCuentas(cuenta);
                  }
               },1300);
         });   
         $("#icuenta").focus();
      }
   }

   function enableBtn() {

      $( "#updateBtn" ).removeClass( "hide" )
      $( "#updateBtn" ).removeClass( "disabled" )
   }

   function normalizeDate( fecha ) {
      var normal = fecha.substr(6,4) + fecha.substr(3,2) + fecha.substr(0,2);
      return normal;
   }

   function onChange(element) {

      var inicio = <?php echo(json_encode($Inicio)); ?>;
      var fin = <?php echo(json_encode($Fin)); ?>;

      switch( element.id ) {
         case "desde":
         case "hasta":
            if( normalizeDate( element.value ) < normalizeDate( inicio ) || normalizeDate( element.value ) > normalizeDate( fin ) ) {
               Materialize.toast('Las fechas deben estar comprendidas dentro del ejercicio activo', 3000, 'rounded') 
            }
            break;

         case "fechaAsiento":
            console.log( normalizeDate( element.value ) );
            if( normalizeDate( element.value ) < normalizeDate( inicio ) || normalizeDate( element.value ) > normalizeDate( fin ) ) {
               $( "#updateBtn" ).removeClass( "hide" )
               $( "#updateBtn" ).removeClass( "disabled" )
               Materialize.toast('La fecha debe estar comprendida dentro del ejercicio activo', 3000, 'rounded') 
               $("#fechaAsiento").focus();
            }
            else {
               $("#asientoBtn" ).removeClass( "hide" )
               $("#asientoBtn" ).removeClass( "disabled" )
            }
            break;


         case "descAsiento":
            $("#asientoBtn" ).removeClass( "hide" )
            $("#asientoBtn" ).removeClass( "disabled" )
            break;

         case "icuenta":
         case "idebe":
         case "ihaber":
         /*
            var debe = numeral($("#idebe").val()).format('0,0.00' );
            var haber = numeral($("#ihaber").val()).format('0,0.00' );

            console.log( "1.1 "  + debe );
            console.log( "1.2 "  + haber );

//            debe = debe.replace(',','');
//            haber = haber.replace(',','');

            debe = debe.replace(/,/g, "")
            haber= haber.replace(/,/g, "")

            console.log( "1.3 "  + debe );
            console.log( "1.4 "  + haber );

            $("#idebe").val(debe);
            $("#ihaber").val(haber);
*/

            $("#idebe").val(numeral($("#idebe").val()).format('0,0.00' ));
            $("#ihaber").val(numeral($("#ihaber").val()).format('0,0.00' ));
            enableBtn();
            break;

         default:
            break;
      }
   }

   function AcceptAsiento() {
      var mode = "append_asiento";
      
      /* Alta  Asiento */
      var fecha = $("#fechaAsiento").val();
      var desc = $("#descAsiento").val();
      var tipo = $("#tipo_asiento").val();
      var id = $("#xAsiento").val();

      if( fecha == "  /  /    " ) {
         Materialize.toast('Debe indicar una fecha', 3000, 'rounded') 
         return;
      }

      if( desc == "" ) {
         Materialize.toast('Debe indicar un concepto', 3000, 'rounded') 
         return;
      }

      /* Fecha, Numero de Asiento, Nro. Mov, Observaciones */
      if( edit == true ) mode = "edit_asiento";
      else mode = "append_asiento";

      var fechaFormatted = normalizeDate( fecha )
      console.log( fecha );
      console.log( fechaFormatted );
      console.log( desc );
      console.log( id );

//      post("updateAsiento.php", { mode: mode, fecha: fechaFormatted, desc: desc, idAsiento: id  });  // Cambiar

      if( edit == true ) {
         $.ajax({
             type: "POST",
             url: "updateAsiento.php",
             data: { 'mode': mode, 'fecha': fechaFormatted, 'desc': desc, 'idAsiento': id  },
                 success: function(data){
                                 var msg = JSON.parse(data);
                                 if( msg != undefined ) {
                                    console.log( msg.status );
                                    post("asientos.php", {});  // Cambiar
                                 }    
                        }   
         });
      }
      else {
         $.ajax({
             type: "POST",
             url: "updateAsiento.php",
             data: { 'mode': mode, 'fecha': fecha, 'desc': desc, 'tipo_asiento': tipo  },
                 success: function(data){
                                 var msg = JSON.parse(data);
                                 if( msg != undefined ) {
                                    console.log( msg.status );
                                    post("asientos.php", {nroAsiento: msg.nro, scroll: "1" });  // Cambiar
                                 }    
                        }   
         });
      }
      $('#modal-asiento').modal('close');
      inlista = false;
   }


   function Accept() {

      /* Actualizar Movimiento y Asiento */
      var mode = "";
      var id = $("#iID").val();              // Id del movimiento en modificacion
      var cuenta = $("#icuenta").val();
      var debe = parseFloat($("#idebe").val().replace(/,/g,''));
      var haber = parseFloat($("#ihaber").val().replace(/,/g,''));
      console.log( "1: " + debe );
      console.log( "2: " + haber );

      var tipo = "0";

      if( cuenta == "" ) {
         Materialize.toast('Debe indicar un numero de cuenta', 3000, 'rounded') 
         return;
      }

      if( debe == 0 && haber == 0 ) {
         Materialize.toast('Debe indicar algun importe en el Debe o en el Haber', 3000, 'rounded') 
         return;
      }

      var numAsiento = $("#inumAsiento" + id).val();
      var idAsiento = $("#idAsiento" + id).val();
//      var fecha = $("#fechaAsiento" + id).val();
      var fecha = $("#ifechaAsiento" + id).val();


      if( mov == true ) {
         if( edit == true ) {
              mode = "update_mov";
         }
         else {
            mode = "append_mov";
            asiento = 0;
            idAsiento = $("#iAsiento").val();
            fecha = $("#iFechaAsiento").val();
            numAsiento = $("#inumAsiento").val();

            fecha = $("#iFechaAsiento").val();
            console.log( "idAsiento --> " + idAsiento );
            console.log( "idnumAsiento --> " + numAsiento );
            console.log( "iFechaAsiento --> " + fecha );
         }
      }
      else {
         if( edit == true ) {
            mode = "update_asiento";
         }
         else {
            mode = "append_asiento";
         }
      }

      console.log( "nroAsiento: " + nroAsiento );
      console.log( "idAsiento: " + idAsiento );
      console.log( mode );
      console.log( cuenta );
      console.log( debe );
      console.log( haber );
      console.log( id );
      console.log( "Fecha Asiento: " + fecha );

      /* Fecha, Numero de Asiento, Nro. Mov, Observaciones */
      $.ajax({
          type: "POST",
          url: "updateAsiento.php",
          data: { 'mode': mode, 'cuenta': cuenta, 'debe': debe, 'haber': haber, 'numero': nroAsiento, 'id': id, 'fechaAsiento': fecha, 'idAsiento': idAsiento, 'tipo_asiento': tipo },
              success: function(data){
                              var msg = JSON.parse(data);
                              if( msg != undefined ) {
                                 console.log( msg.status );
                                 post("asientos.php", {nroAsiento: nroAsiento, scroll: "1" });  // Cambiar
                              }    
                       }
      });
      $('#modal-movimiento').modal('close');
      inlista = false;
   }

   function Cancel() {
      console.log( "CANCEL!" );
      edit = false;
      mov  = false;
      inlista = false;
   }

   function listClick(el) {
      var mode = "";

      $( "#dropdownMenu" ).removeClass( "active" );
      $( "#dropdownMenu" ).css( "opacity", 0 );
      $( "#dropdownMenu" ).css( 'display', 'none' );

      var li = $( "#dropdownMenu" ).attr( "option" );
      edit = false;

      switch( el.id ) {

         // Copy
         case "l4":
//            copyAsiento(el);

//            post("copyAsiento.php", {idAsiento: li });  // Cambiar
            $.ajax({
            type: "POST",
                url: "copyAsiento.php",
                data: { 'idAsiento': li }, 
                        success: function(data){ 
                                    console.dir( data );
                                    var msg = JSON.parse(data);
                                    if( msg != undefined ) {
                                        console.log( msg.status );
                                         console.log( "COPY!" );
                                         post("asientos.php", "");
                                    }    
                        }
            });
            break;

         // Delete
         case "l1":
            var numAsiento = $("#numAsiento" + li).val();
            var idAsiento = $("#idAsiento" + li).val();
            if( inlista == true ) {
               console.log( "Delete Movimiento: " + li );
               mode = "delete_mov";
            }
            else {
               console.log( "Delete Asiento: " + li );
               mode = "delete_asiento";
            }
            console.log( "idAsiento: " + $("#idAsiento" + li).val() );
            console.log( "numAsiento: " + $("#numAsiento" + li).val() );
            $.ajax({
            type: "POST",
                url: "updateAsiento.php",
                data: { 'mode': mode, 'id': li, 'numero': numAsiento, 'idAsiento': idAsiento }, 
                                    success: function(data){ 
                                        var msg = JSON.parse(data);
                                        if( msg != undefined ) {
                                           console.log( msg.status );
                                           console.log( "DELETE!" );
                                           post("asientos.php", "");
                                        }    
                                    }
            });
            break;

         // Edit
         case "l2":
            edit = true;
            ID = li;
            if( inlista == true ) {
               // Modificar movimiento
               var id = li;

               var name = "#mCuenta" + id;
               var mmov = $("#mMov" + id).html();
               var cuenta = $("#mCuenta" + id).html();
               var denom = $("#mDenom" + id).html();
               var debe = $("#mDebe" + id).html();
               var haber = $("#mHaber" + id).html();

               $("#mov-title").html('Modificar Movimiento');
               $("#inumero").val(mmov);
               $("#icuenta").val(cuenta);
               $("#idenom").val(denom);
               $("#idebe").val(debe);
               $("#ihaber").val(haber);

               $("#inumero").prop("readonly",true);
               $("#idenom").prop("readonly",true);

               /*
               if( debe > 0 ) {
                  $("#idebe").prop("readonly",false);
                  $("#ihaber").prop("readonly",true);
               }
               else {
                  $("#idebe").prop("readonly",true);
                  $("#ihaber").prop("readonly",false);
               }
               */
               mov = true;
               newMovimiento();
            }
            else {
               // Modificar asiento
//               console.log( $('ul#lista').find('li div.collapsible-header #fechaAsiento' + li )[0].innerText );
//               console.log( $('ul#lista').find('li div.collapsible-header #desc' + li )[0].innerText );
               var fecha = $('ul#lista').find('li div.collapsible-header #fechaAsiento' + li )[0].innerText;
               var desc = $('ul#lista').find('li div.collapsible-header #desc' + li )[0].innerText;
               var id = $('ul#lista').find('li div.collapsible-header #iidAsiento' + li )[0].innerText;

               console.log( ">>> " + id );
               $("#fechaAsiento").val(fecha);
               $("#descAsiento").val(desc);
               $("#xAsiento").val(id);
//               $("#tipo_asiento").val();


               mov = false;
               editAsiento();
//               $( li ).trigger( 'click' );
            }
            break;

         // New
         case "l3":
            ID = li;
            edit = false;

            var idAsiento = $("#idAsiento" + li).val();
            var numAsiento = $("#numAsiento" + li).val();
            var fechaAsiento = $("#ifechaAsiento" + li).val();

            console.log( "0. " + li );
            console.log( "1. " + idAsiento );
            console.log( "2. " + numAsiento );
            console.log( "3. " + fechaAsiento );

            if( inlista == true ) {

               // Nuevo Movimiento
               $("#mov-title").html('Nuevo Movimiento');
               $("#inumero").val("");
               $("#icuenta").val("");
               $("#idenom").val("");
               $("#idebe").val("");
               $("#ihaber").val("");

               $("#iAsiento").val(idAsiento);
               $("#iFechaAsiento").val(fechaAsiento);
               $("#inumAsiento").val(numAsiento);

               /*
               $("#inumero").prop("readonly",true);
               $("#idenom").prop("readonly",true);

               $("#idebe").prop("readonly",false);
               $("#ihaber").prop("readonly",false);
               */
               mov = true;
               newMovimiento();
            }
            else {
               // Nuevo asiento
               mov = false;
            }
            break;
      }
//      inlista = false;
   }      

</script>
</body>
</html>

