<?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 Comprobantes";
$Year   = isset($_POST['year']) ? $_POST["year"]  : "";
$Month  = isset($_POST['month']) ? $_POST['month'] : "";
$Fecha = "";
$YS2011 = "";
$YS2012 = "";
$YS2013 = "";
$YS2014 = "";
$YS2015 = "";
$YS2016 = "";
$YS2017 = "";
$YS2018 = "";
$YS2019 = "";
$update = false;

if( empty($Year) ) {        
   if( $_SESSION["Year"] != "" ) $Year = $_SESSION["Year"];
   else {
      $Year = date("Y");
   }
}
else if( $Year != $_SESSION["Year"] ) $update = true;

if( empty($Month) ) {       
   if( $_SESSION["Month"] != "" ) $Month = $_SESSION["Month"];
   else {
     $Month = date("n");
   }
}
else if( $Month != $_SESSION["Month"] ) $update = true;

$LastDay = $_SESSION["Date"];
if( empty($LastDay) ) {       
   $LastDay = date("d/m/Y"); 
}
$LDay = date("Y/m/d"); 

$_SESSION["Year"] = $Year;
$_SESSION["Month"] = $Month;
$_SESSION["Date"] = $LastDay;

$saveFecha = $Year . "/" . $Month . "/" . "01";

if( $update == true ) {
  $sql = "update ejercicios set fecha='" . $saveFecha . "' where Activa=1";
  $result = $conn->query($sql);
   mysql_free_result( $result );
}

$mode = "read";
$actualUrl = "contableComprobantes.php";
include 'contableHeader.php'; 
include 'contableConfig.php.php';
?>

<style>
/*
a.dropdown-trigger:focus {
  background-color: #16a2d6;
}
*/

.collapsible-header:focus {
//  background-color: #16a2d6;
//3  color: white;
}

.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: 10px;"></div>
    <div class="col l9 m12 s12">
      <div class="page-content">
        <div style="height:20px;"></div>
        <form id="asterisco" action="contableComprobantes.php" method="post"> 
 <?php
        echo "<div class='row'>";
include 'contableSelector.php'; 
?>              

          <button class="btn waves-effect waves-light btn col s1" style="margin-top:5px; margin-left: 30px;" type="submit" name="action" >Go!</button>
          </row>  
          </form>
          <a onclick='newInvoice()' 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;
// background-color: #007FFF;
}
</style>
<?php
  $isData = false;

  $sql = "select sql_no_cache comprobantes.id as idc, operacion, fecha, numero, Etiquetas, empresas.id as code_empresa, empresas.nombre, iva_105, iva_21, iva_27, iva_MT, ( iva_105 + iva_21 +iva_27 + iva_MT ) as sin_iva, iva, importe, retenciones, retenciones_iva, op_exentas, ( retenciones_iva + op_exentas + otras_retenciones ) as otras, importe, retenciones_ganancias from comprobantes left join empresas on empresas.id = comprobantes.cliente where year(fecha)='"  . $Year . "' and month(fecha)='" . $Month . "' and comprobantes.Borrado=0 order by fecha";
  $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' data-field='op' style='width:6%; border-radius:0;'>Op.</th>";
        echo "<th class='col s1' data-field='id' style='width:6%; border-radius:0;'>Fecha</th>"; 
        echo "<th class='col s2' data-field='numero' style='width:9%; border-radius:0;'>Numero</th>"; 
        echo "<th class='col s6' data-field='empresa' style='width:33%; border-radius:0;' >Empresa</th>"; 
        echo "<th class='col s1 right-align' data-field='sin_iva' style='width:7%; border-radius:0;' >Total s/IVA</th>"; 
        echo "<th class='col s1 right-align' data-field='con_iva' style='width:7%; border-radius: 0;' >&nbsp;IVA</th>"; 
        echo "<th class='col s1 right-align' data-field='price_total' style='width:10%; border-radius: 0;' >Importe Total</th>"; 
          */
        echo "<th class='col s1' style='width:6%; border-radius:0; background-color=#007FFF;'>Op.</th>";
        echo "<th class='col s1' style='width:6%; border-radius:0; background-color=#007FFF;'>Fecha</th>"; 
        echo "<th class='col s2' style='width:9%; border-radius:0; background-color=#007FFF;'>Numero</th>"; 
        echo "<th class='col s6' style='width:33%; border-radius:0; background-color=#007FFF;' >Empresa</th>"; 
        echo "<th class='col s1 right-align' style='width:7%; border-radius:0; background-color=#007FFF;' >Total s/IVA</th>"; 
        echo "<th class='col s1 right-align' style='width:7%; border-radius: 0; background-color=#007FFF;' >&nbsp;IVA</th>"; 
        echo "<th class='col s1 right-align' style='width:10%; border-radius: 0; background-color=#007FFF;' >Importe Total</th>"; 

        echo "<th style='width:8%;'>&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 class='collapsible' data-collapsible='accordion'>";
    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] = $Oper[9] = "";
      $multiply = 1;
      switch( $op = $row["operacion"] ) {
         case 2:  $Op = "Compra";    $Oper[1] = "selected"; $multiply = -1; break;
         case 1:  $Op = "Venta";     $Oper[0] = "selected"; break;
         case 11: $Op = "Gastos";    $Oper[10] = "selected"; break;
         case 3:  $Op = "IB";        $Oper[2] = "selected"; break;
         case 4:  $Op = "Ganancias"; $Oper[3] = "selected"; break;
         case 5:  $Op = "Ret.IVA";   $Oper[4] = "selected"; $multiply = -1; break;
         case 6:  $Op = "NC Venta";  $Oper[5] = "selected"; $multiply = -1; break;
         case 7:  $Op = "NC Compra"; $Oper[6] = "selected"; break;
         case 8:  $Op = "Cobranza";  $Oper[7] = "selected"; break;
         case 9:  $Op = "Pago a Proveedores";  $Oper[8] = "selected"; break;
         case 10:  $Op = "Otras Ret.";  $Oper[9] = "selected"; break;
         default: $Op = ""; break; 
      }
      $Importe = $row["importe"];
      $Importe_SinIVA = $row["sin_iva"];

      $IVA = $row["iva"];
      if( $op == 5 ) $IVA = $Importe; 
      $Retenciones = $row["retenciones"] + $row["otras"];

      $Total_SinIVA += ($Importe_SinIVA * $multiply);
      $Total_IVA += ($IVA * $multiply);

      echo "<li id='" . $row["idc"] . "' class='lista'>";
      echo "<div class='collapsible-header' id='invoices'>";
         echo "<div class='row'>";
         echo "<div class='col s1' style='width: 7%;'>" . $Op . "</div>";
         echo "<div class='col s1' style='width: 8%;'>" . $formatted . "</div>"; 
         echo "<div class='col s2' style='width: 10%;'>" . $row["numero"] . "</div>";
         echo "<div class='col s6' style='width: 39%;'>" . $row["nombre"] . "</div>";

         if( $multiply == 1 )  {
            echo "<div class='col s2 right-align' style='width: 10%;'>" . number_format ( $Importe_SinIVA, 2, ',' ,  '.' ) . "</div>";
            echo "<div class='col s2 right-align' style='width: 10%;'>" . number_format ( $IVA, 2, ',' ,  '.' ) . "</div>";
            echo "<div class='col s2 right-align' style='width: 10%;'>" . number_format ( $Importe, 2, ',' ,  '.' ) . "</div>";
         }
         else {
            echo "<div class='col s2 right-align' style='width: 10%; color:red;'>(" . number_format ( $Importe_SinIVA, 2, ',' ,  '.' ) . ")</div>";
            echo "<div class='col s2 right-align' style='width: 10%; color:red;'>(" . number_format ( $IVA, 2, ',' ,  '.' ) . ")</div>"; 
            echo "<div class='col s2 right-align' style='width: 10%; color:red;'>(" . number_format ( $Importe, 2, ',' ,  '.' ) . ")</div>";
         }
         echo "</div>";
      echo "</div>";
      echo "<div id='detail' class='collapsible-body col s12'>";
         echo "<div class='row data'>";
         echo "<div style='height:20px;'></div>";
         echo "<div class='input-field col s1 right-align'></div>";
         echo "<div class='input-field col s2'>";
         echo "<label for='fechac'>Fecha</label>";
         echo "<input id='fechac" . $row["idc"] . "' type='text' class='datepicker' value='" . $formatted . "'>";
         echo "</div>";
         echo "<div class='input-field col s3' style='padding-top:10px;'>";
         echo "<select id='operacion" . $row["idc"] . "' onChange='onChangeOperacion(this);'>";
         echo "<option value='' disabled selected>Seleccione</option>";
         echo "<option value='1' " . $Oper[0] . ">Venta</option>";
         echo "<option value='2' " . $Oper[1] . ">Compra</option>";
         echo "<option value='11' " . $Oper[10] . ">Gastos</option>";
         echo "<option value='3' " . $Oper[2] . ">Retenci&oacute;n IIBB</option>";
         echo "<option value='4' " . $Oper[3] . ">Retenci&oacute;n Ganancias</option>";
         echo "<option value='5' " . $Oper[4] . ">Retenci&oacute;n IVA</option>";
         echo "<option value='6' " . $Oper[5] . ">Cr&eacute;dito (Clientes)</option>";
         echo "<option value='7' " . $Oper[6] . ">Cr&eacute;dito (Proveedores)</option>";
         echo "<option value='8' " . $Oper[7] . ">Cobranza</option>";
         echo "<option value='9' " . $Oper[8] . ">Pago a Proveedores</option>";
         echo "<option value='10' " . $Oper[9] . ">Otras Retenciones</option>";
         echo "</select>";
         echo "<label>Operacion</label>";
         echo "</div>";
         echo "<div class='input-field col s3'>";
         echo "<input id='numero" . $row["idc"] . "' type='text' value='" . $row["numero"] . "'>";
         echo "<label class='active' for='numero'>Numero</label>";
         echo "</div>";
         echo "</div>";

         echo "<div style='height: 30px;'></div>";
         echo "<div class='row data'>";
         echo "<div class='input-field col s1 right-align margin-label'></div>";
         echo "<div class='input-field col s8 margin'>";
         echo "<input id='empresa_" . $row["idc"] . "' type='text' value='" . $row["nombre"] . "'>";
         echo "<label class='active' for='empresa'>Empresa</label>";
         echo "<input type='hidden' id='code_empresa" . $row["idc"] . "' value='" . $row["code_empresa"] . "'>"; 
         echo "</div>";
         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'>";

         $tc = $row["operacion"];
         if( $tc == "8" || $tc == "9" ) {
              echo "<input id='iva105" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["iva_105"] . "'>";
              echo "<label class='active' for='iva105'>Importe Abonado</label>";
         }
         else {
            echo "<input id='iva105" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["iva_105"] . "'>";
            echo "<label class='active' for='iva105'>IVA 10.5%</label>";
         }
         echo "</div>";

         echo "<div class='input-field col s2'>";
         echo "<input id='iva21" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["iva_21"] . "'>";
         echo "<label class='active recibo' for='iva21'>IVA 21%</label>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='iva27" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["iva_27"] . "'>";
         echo "<label class='active recibo' for='iva27'>IVA 27%</label>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='ivamt" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["iva_MT"] . "'>";
         echo "<label class='active recibo' for='ivamt'>Monotributo/Exentas</label>";
         echo "</div>";
         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='retenciones" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["retenciones"] . "'>";
         echo "<label id='labelRetencion' class='active' for='retenciones'>Percepcion IB</label>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='retenciones_iva" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["retenciones_iva"] . "'>";
         echo "<label id='labelPercepcionIVA' class='active' for='retenciones_iva'>Percepcion IVA</label>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='retencion_gan" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["retenciones_ganancias"] . "'>";
         echo "<label class='active' for='retencion_gan'>Retenciones Ganancias</label>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='otras_retenciones" . $row["idc"] . "' type='text' class='right-align' style='height: 2em;' value='" . $row["op_exentas"] . "'>";
         echo "<label class='active' for='otras_retenciones'>Otras Retenciones</label>";
         echo "</div>";
         echo "</div>";

         echo "<div style='height: 30px;'></div>";
         echo "<div class='row data'>";
         echo "<div class='input-field col s3 right-align margin-label'></div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='importe_iva" . $row["idc"] . "' type='text' class='right-align' style='height:2em; font-weight:600; font-size:16px;' value='0.00' readonly='readonly'>";
         echo "<label class='active recibo' for='importe_iva'>Importe IVA</label>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='importe_neto" . $row["idc"] . "' type='text' class='right-align' style='height:2em; font-weight:600; font-size:16px;' value='" . $row["retenciones"] . "' readonly='readonly'>";
         echo "<label class='active recibo' for='importe_neto'>Importe Neto</label>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<input id='total" . $row["idc"] . "' type='text' class='right-align' style='height:2em; font-weight:600; font-size:16px;' value='" . $row["op_exentas"] . "' readonly='readonly'>";
         echo "<label class='active' for='total'>Importe Total</label>";
         echo "</div>";
         echo "</div>";   // Row
         echo "<div class='row data'>";
         echo "<div class='input-field col s1 right-align margin-label'></div>";
         echo "<div class='input-field col s8'>";
//            echo "<textarea id='observaciones' class='materialize-textarea' value='" . $row["Etiquetas"] . "'></textarea>";
            echo "<textarea id='observaciones' class='materialize-textarea'>" . $row["Etiquetas"] . "</textarea>";
            echo "<label for='observaciones'>Etiquetas</label>";
         echo "</div>";
         echo "</div>";
         echo "<div id='idropEmpresa' style='float: right;'>";
         echo "<ul id='idropdownEmpresa' class='dropdown-client' style='z-index:10; display:none;'>";
         echo "</ul>"; 
         echo "</div>";

         echo "<div class='row data'>";
           echo "<div class='col s2 offset-s7'>";
           echo "<button id='updateBtn_" . $row["idc"] . "' class='waves-effect waves-light btn right disabled hide'>Actualizar</button>";
           echo "</div>";
         echo "</div>";

         echo "<div style='height:30px;'></div>";
      echo "</div>";
      echo "<input type='hidden' id='id' value='" . $row["idc"] . "'>"; 
      echo "</li>"; 

//      $Total_SinIVA += $Importe_SinIVA;
//      $Total_IVA += $IVA;
      $Total_Ret += $Retenciones;
//      $Total_Importe += $Importe;
    }
   } 

   $idsData = true;
   if( $idsData == true ) {
      echo "</ul>";
      echo "</div>";
      echo "</td>";
      echo "</tr>";
      mysql_free_result( $result );

      echo "<table id='tdetail'>";
      echo "<tfoot>";
      echo "<tr style='color:black; font-weight: 500;'>";
      echo "<td class='col s1 right-align orange lighten-2' style='width:2%;'>&nbsp;</td>";
      echo "<td class='col s1 right-align orange lighten-2' style='width: 10%;'>&nbsp;</td>";
      echo "<td class='col s1 right-align orange lighten-2' style='width: 9%;'>&nbsp;</td>"; 
      echo "<td class='col s2 right-align orange lighten-2' style='width: 14%;'>&nbsp;</td>"; 
      echo "<td class='col s4 right-align orange lighten-2' style='width: 27%;'>&nbsp;</td>"; 
      echo "<td class='col s1 right-align orange lighten-2' style='width: 10%;'>". number_format ( $Total_SinIVA, 2, ',' ,  '.' ) . "</td>"; 
      echo "<td class='col s1 right-align orange lighten-2' style='width: 10%;'>". number_format ( $Total_IVA, 2, ',' ,  '.' ) . "</td>"; 
      echo "<td class='col s2 right-align orange lighten-2' style='width: 9%;'>". number_format ( $Total_Ret, 2, ',' ,  '.' ) . "</td>"; 
      echo "<td class='col s1 right-align orange lighten-2' style='width: 9%;'>&nbsp;</td>";

      echo "</tr>";
      echo "</tfoot>";
      echo "</table>";
   }
   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 class='divider'></li>"; 
     echo "<li id='l3' onclick='listClick(this);'><a><i class='material-icons left'>add</i>Nuevo</a></li>"; 
   echo "</ul>";
?>        
   </div>
   <div style="height:100px;"></div>
   </div>
   </div>

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

 <?php
//         echo "<div id='addInvoice' class='modal modal-footer' style='height:100%;'>";
         echo "<div id='addInvoice' class='modal modal-footer'>";
         echo "<div class='modal-content'>";
            echo "<div class='row data' style='padding-left:30px; padding-right:30px;'>";
//             echo "<div class='input-field col s1 right-align'></div>";
               echo "<div class='offset-s1' style='font-size: 1.3em; padding-bottom: 30px;'>Nuevo Comprobante</div>";
            echo "</div>";

            echo "<div class='row data' style='padding-left:30px; padding-right:30px;'>";
               echo "<div style='height:10px;'></div>";
//               echo "<div class='input-field col s1 right-align'></div>";
               echo "<div class='input-field col s3'>";
                  echo "<label for='ifecha'>Fecha</label>";
                  echo "<input id='ifecha' type='text' class='datepicker' value='" . $LastDay . "' onChange='onChange(this);'>";
               echo "</div>";
               echo "<div class='input-field col s4' style='padding-top:10px;'>";
//               echo "<select id='operacion' onChange='onChange(this);'>";
               echo "<select id='operacion' onChange='onChangeOperacion(this);'>";
               echo "<option value='' disabled selected>Seleccione</option>";
               echo "<option value='1' selected>Venta</option>";
               echo "<option value='2' >Compra</option>";
               echo "<option value='11' >Gastos</option>";
               echo "<option value='3' >Retenci&oacute;n IIBB</option>";
               echo "<option value='4' >Retenci&oacute;n Ganancias</option>";
               echo "<option value='5' >Retenci&oacute;n IVA</option>";
               echo "<option value='6' >Cr&eacute;dito (Clientes)</option>";
               echo "<option value='7' >Cr&eacute;dito (Proveedores)</option>";
               echo "<option value='8' >Cobranza</option>";
               echo "<option value='9' >Pago a Proveedores</option>";
               echo "</select>";
               echo "<label>Operacion</label>";
               echo "</div>";
               echo "<div class='input-field col s4'>";
                  echo "<input id='inumero' type='text' value=''>";
                  echo "<label class='active' for='inumero'>Numero</label>";
               echo "</div>";
            echo "</div>";
            echo "<div style='height: 10px;'></div>";

            echo "<div class='row data' style='padding-left:30px; padding-right:30px;'>";
//             echo "<div class='input-field col s1 right-align margin-label'></div>";
               echo "<div class='input-field col s12 margin'>";
                  echo "<input id='iempresa' type='text' value=''>";
                  echo "<label class='active' for='iempresa'>Empresa</label>";
                  echo "<input type='hidden' id='icode_empresa' value=''>"; 
               echo "</div>";
            echo "</div>";
   
            echo "<div class='row data' style='padding-left:30px; padding-right:30px;'>";
//             echo "<div class='input-field col s1 right-align margin-label'></div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='iva105' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label id='label105' class='active' for='iva105'>IVA 10.5%</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='iva21' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label class='active  recibo' for='iva21'>IVA 21%</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='iva27' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label class='active  recibo' for='iva27'>IVA 27%</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='ivamt' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label class='active  recibo' for='ivamt'>IVA Monotributo/Exentas</label>";
               echo "</div>";
            echo "</div>";
   
            echo "<div class='row data' style='padding-left:30px; padding-right:30px;'>";
//               echo "<div class='input-field col s1 right-align margin-label'></div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='retenciones' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label class='active' for='retenciones'>Percepciones IB</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='retenciones_iva' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label id='labelPercepcionIVA2' class='active' for='retenciones_iva'>Percepciones IVA</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='retencion_gan' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label class='active' for='retencion_gan'>Retenciones Ganancias</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='otras_retenciones' type='text' class='right-align' style='height: 2em;' value='0.00' onChange='onChange(this);'>";
                  echo "<label class='active' for='otras_retenciones'>Otras Retenciones</label>";
               echo "</div>";
            echo "</div>";
            echo "<div style='height: 30px;'></div>";
   
            echo "<div class='row data' style='padding-left:30px; padding-right:30px;'>";
               echo "<div class='input-field col s3 right-align margin-label'></div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='importe_iva' type='text' class='right-align' style='height:2em; font-weight:600; font-size:16px;' value='0.00' readonly='readonly'>";
                  echo "<label class='active recibo' for='importe_iva'>Importe IVA</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='importe_neto' type='text' class='right-align' style='height:2em; font-weight:600; font-size:16px;' value='0.00' readonly='readonly'>";
                  echo "<label class='active  recibo' for='importe_neto'>Importe Neto</label>";
               echo "</div>";
               echo "<div class='input-field col s3'>";
                  echo "<input id='total' type='text' class='right-align' style='height:2em; font-weight:600; font-size:16px;' value='0.00' readonly='readonly'>";
                  echo "<label class='active' for='total'>Importe Total</label>";
               echo "</div>";
            echo "</div>";   // Row
   
            echo "<div class='row data' style='padding-left:30px; padding-right:30px;'>";
//               echo "<div class='input-field col s1 right-align margin-label'></div>";
               echo "<div class='input-field col s12'>";
                  echo "<textarea id='observaciones' class='materialize-textarea'> </textarea>";
                  echo "<label for='observaciones'>Etiquetas</label>";
               echo "</div>";
            echo "</div>";
   
            echo "<div id='mdropEmpresa' style='float: right;'>";
               echo "<ul id='mdropdownEmpresa' class='dropdown-client' style='z-index:10; display:none;'>";
               echo "</ul>"; 
            echo "</div>";
         echo "</div>";    // modal-content

         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='Accept();' class='waves-effect waves-green btn-flat '>Aceptar</a> "; 
         echo "</div>"; 
         echo "</div>"; // End Modal  
  
?>

   <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="js/materialize.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;
   color: black;
   min-height: 3em;
   text-align: left;
   padding: 0px 16px;
}
ul.dropdown-client li:hover {
 background-color:#90a4ae;
    background-color: #16a2d6;
    color: white;
}
</style>
<script>

   var keyTimeout;
   var newflag = false;
   var searchflag = 0;
   var found = false;
   var fecha;
   var numero;
   var empresa;
   var iva105;
   var iva21; 
   var iva27; 
   var ivamt; 
   var retenib;
   var reteniva;
   var otrasreten;
   var totalreten;
   var neto; 
   var total;
   var operacion;
   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() {

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


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

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

    $('#month').on('change', function() {
        Month = this.value;
        console.log( this.value )
    });   
    $('#year').on('change', function() {
        Year = this.value;
        console.log( this.value )
    });   

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

//    $('.datepicker').pickadate({
    $('.datepicker').datepicker({
       selectMonths: true, // Creates a dropdown to control month
       selectYears: 10, // Creates a dropdown of 15 years to control year
       monthsFull: [ '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' ],
       weekdaysFull: [ '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',
       close: 'Cerrar',
       format: 'dd-mm-yyyy',
       formatSubmit: 'yyyy-mm-dd'
       /*
       format: dateFormat,
       /*
       min: new Date(1935,1,1),
       onOpen: Register.OnDateOut(),
       onClose: Register.OnDateOut(),
       max: new Date(new Date().setYear(new Date().getFullYear() + 2))
         */
    });

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

      jQuery(function($){
         $("#inumero").mask("9999-99999999",{placeholder:" ", autoclear: false});
//         $("#phone").mask("(999) 999-9999");
//         $("#tin").mask("99-9999999");
//         $("#ssn").mask("999-99-9999");
      });

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

          if( $( "#dropdownMenu" ).hasClass( "active" ) ) {
               ev.preventDefault();
               $( "#dropdownMenu" ).removeClass( "active" );
               $( "#dropdownMenu" ).css( "opacity", 0 );
               $( "#dropdownMenu" ).css( 'display', 'none' );
               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' );
          $( "#empresa" ).removeClass( "invalid" );
      });

      var ld = <?php echo(json_encode($LDay)); ?>;
      console.log( "LastDay: " + ld );
      $('#ifecha').datepicker('setDate', ld );

  });   

   function Invoice(mode) {

      var id = $('#id').val();
      var fecha = $( "#fechac" + id).val(); 
      var numero = $( "#numero" + id).val();  
      var empresa = $( "#empresa_" + id).val();   
      var code_empresa = $( "#code_empresa" + id).val();   
      var iva105 = $( "#iva105" + id).val().replace(',','');   
      var iva21 = $( "#iva21" + id).val().replace(',','');    
      var iva27 = $( "#iva27" + id).val().replace(',','');    
      var ivamt = $( "#ivamt" + id).val().replace(',','');    
      var retenib = $( "#retenciones" + id).val().replace(',','');    
      var reteniva = $( "#retenciones_iva" + id).val().replace(',','');     
      var otrasreten = $( "#otras_retenciones" + id).val().replace(',','');     
      var totalreten = $( "#retencion_gan" + id).val().replace(',','');     
      var neto = $( "#importe_neto" + id).val().replace(',','');     
      var total = $( "#total" + id).val().replace(',','');     
      var op = $( "#operacion" + id).val();     
      var importe_iva = $( "#importe_iva" + id).val().replace(',','');      
      var importe_neto = $( "#importe_neto" + id).val().replace(',',''); 
      var total = $( "#total" + id).val().replace(',','');      

      if( mode == "update" )
      $.ajax({
          type: "POST",
          url: "contableUpdateComprobante.php",
          data: { 'mode': mode, 'id': id, 'fecha': fecha, 'op': op, 'numero': numero, 'customer': code_empresa, 'empresa': empresa, 'iva105': iva105, 'iva21': iva21, 'iva27': iva27, 'ivamt': ivamt,
                  'importe_iva': importe_iva, 'retenciones': retenib, 'retenciones_iva': reteniva, 'otras_retenciones': otrasreten, 'total': total, 'gan': totalreten },
              success: function(data){
                              var msg = JSON.parse(data);
//                              if( msg.length >= 0 ) {
                                 console.log( msg.status );

                                 $( "#fechac" + id).val(fecha); 
                                 $( "#numero" + id).val(numero);  
                                 $( "#empresa_" + id).val(empresa);   
                                 $( "#iva105" + id).val(iva105);   
                                 $( "#iva21" + id).val(iva21);   
                                 $( "#iva27" + id).val(iva27);   
                                 $( "#ivamt" + id).val(ivamt);   

                                 $( "#retenciones" + id).val(retenib);    
                                 $( "#retenciones_iva" + id).val(reteniva);    
                                 $( "#otras_retenciones" + id).val(otrasreten);    
                                 $( "#retencion_gan" + id).val(totalreten);    
                                 $( "#importe_neto" + id).val(neto);
                                 $( "#total" + id).val(total);
                                 $( "#operacion" + id).val(operacion);
                                 $( "#code_empresa" + id).val(code_empresa);   
                                 post("contableComprobantes.php", "");
//                               post("detalle.php", {dia: e.currentTarget.cells[0].innerHTML }); 


//                              }    
                       }
      });
   }

   function captureEmpresa(el) {
      var mode = "";
      var inputname = "";

      console.log( "onOpenStart" );
    if( $( "#dropdownMenu" ).hasClass( "active" ) ) {
         $( "#dropdownMenu" ).removeClass( "active" );
         $( "#dropdownMenu" ).css( "opacity", 0 );
         $( "#dropdownMenu" ).css( 'display', 'none' );
    }
  
      console.dir( el);
//    var id = el.attr('id');
      var id = el.id;
      console.dir(id);

      inputname = "#empresa_" + id;
      $('#id').val(id);
      console.log( inputname );
      mode = "update";
      
      $("#numero" + id).mask("9999-99999999",{placeholder:" ", autoclear: false});
      $( "#updateBtn_" + id ).click(function() {       

         $( "#updateBtn_" + id ).addClass( "hide" )
         $( "#updateBtn_" + id ).addClass( "disabled" )

         Invoice( mode );
      });

      saveRecord();

      console.log(inputname);

       $(inputname).on('keyup', function() {

            var cliente  = this.value;
            if( keyTimeout != undefined ) clearInterval(keyTimeout); 
            keyTimeout = setTimeout(function() {
               clearInterval(keyTimeout); 
               if( cliente.length >= 0 ) {
                  if( empresa != $("#empresa_" + id).val() ) {
                     populateEmpresas(cliente,id);
                  }
               }
            },2000);
       });   
   }


   function enableBtn(id) {

      $( "#updateBtn_" + id ).removeClass( "hide" )
      $( "#updateBtn_" + id ).removeClass( "disabled" )
   }

   function calculateTotals(id) {
      var id = $('#id').val();

      var fecha = $( "#fechac" + id).val(); 
      var numero = $( "#numero" + id).val();  
      var empresa = $( "#empresa_" + id).val();   
      var iva105 = $( "#iva105" + id).val().replace(',','');   
      var iva21 = $( "#iva21" + id).val().replace(',','');    
      var iva27 = $( "#iva27" + id).val().replace(',','');    
      var ivamt = $( "#ivamt" + id).val().replace(',','');    
      var retenib = $( "#retenciones" + id).val().replace(',','');    
      var reteniva = $( "#retenciones_iva" + id).val().replace(',','');     
      var otrasreten = $( "#otras_retenciones" + id).val().replace(',','');     
      var totalreten = $( "#retencion_gan" + id).val().replace(',','');     
      var neto = $( "#importe_neto" + id).val().replace(',','');     
      var total = $( "#total" + id).val().replace(',','');     
      var operacion = $( "#operacion" + id).val();     

      var total_siniva = parseFloat(iva105) + parseFloat(iva21) + parseFloat(iva27) + parseFloat(ivamt);
      var total_iva = parseFloat(iva105) * 10.5 / 100 + parseFloat(iva21) * 21 / 100 + parseFloat(iva27) * 27 / 100;
      var total_ret = parseFloat(retenib) + parseFloat(reteniva) + parseFloat(otrasreten) + parseFloat(totalreten);
      var total = total_siniva + total_iva + total_ret;

      if( operacion == "8" || operacion == "9" ) {
         total_siniva = parseFloat(iva105);
         total_iva = 0;
         total_ret = parseFloat(retenib) + parseFloat(reteniva) + parseFloat(otrasreten) + parseFloat(totalreten);
         total = total_siniva + total_iva + total_ret;
      }

      $("#importe_iva" + id).val(total_iva);
      $("#retencion_gan" + id).val(totalreten);
      $("#importe_neto" + id).val(total_siniva);
      $("#total" + id).val(total);

      $("#iva105" + id).val(numeral($("#iva105" + id).val()).format('0,0.00' ));
      $("#iva21" + id).val(numeral($("#iva21" + id).val()).format('0,0.00' ));
      $("#iva27" + id).val(numeral($("#iva27" + id).val()).format('0,0.00' ));
      $("#ivamt" + id).val(numeral($("#ivamt" + id).val()).format('0,0.00' ));
      $("#importe_iva" + id).val(numeral($("#importe_iva" + id).val()).format('0,0.00' ));
      $("#retencion_gan" + id).val(numeral($("#retencion_gan" + id).val()).format('0,0.00' ));
      $("#importe_neto" + id).val(numeral($("#importe_neto" + id).val()).format('0,0.00' ));
      $("#total" + id).val(numeral($("#total" + id).val()).format('0,0.00' ));
   }
 
   function saveRecord() {
      
      var id = $('#id').val();

      fecha = $( "#fechac" + id).val(); 
      numero = $( "#numero" + id).val();  
      empresa = $( "#empresa_" + id).val();   
      iva105 = $( "#iva105" + id).val().replace(',','');   
      iva21 = $( "#iva21" + id).val().replace(',','');    
      iva27 = $( "#iva27" + id).val().replace(',','');    
      ivamt = $( "#ivamt" + id).val().replace(',','');    
      retenib = $( "#retenciones" + id).val().replace(',','');    
      reteniva = $( "#retenciones_iva" + id).val().replace(',','');
      otrasreten = $( "#otras_retenciones" + id).val().replace(',','');     
      totalreten = $( "#retencion_gan" + id).val().replace(',','');     
      neto = $( "#importe_neto" + id).val().replace(',','');     
      total = $( "#total" + id).val().replace(',','');     
      operacion = $( "#operacion" + id).val();     

      if( operacion == 8 || operacion == 9 ) {
         $( "#iva21" + id ).addClass( 'hide disabled' );
         $( "#iva27" + id ).addClass( 'hide disabled' );
         $( "#ivamt" + id ).addClass( 'hide disabled' );
         $( "#importe_neto" + id ).addClass( 'hide disabled' );
         $( "#importe_iva" + id ).addClass( 'hide disabled' );
         $( ".recibo" ).addClass( 'hide disabled' );
      } 
      else {
         $( "#iva21" + id ).removeClass( 'hide disabled' );
         $( "#iva27" + id ).removeClass( 'hide disabled' );
         $( "#ivamt" + id ).removeClass( 'hide disabled' );
         $( "#importe_neto" + id ).removeClass( 'hide disabled' );
         $( "#importe_iva" + id ).removeClass( 'hide disabled' );
         $( ".recibo" ).removeClass( 'hide disabled' );
      }                 

      $( "#fechac" + id ).change(function() {
         if( recordChange() == true ) enableBtn(id);
      });

      $( "#numero" + id ).change(function() {
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      $( "#empresa_" + id ).change(function() {
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });


      $( "#iva105" + id ).change(function() {
         $("#iva105" + id).val(numeral($("#iva105" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      $( "#iva21" + id ).change(function() {
         $("#iva21" + id).val(numeral($("#iva21" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      $( "#iva27" + id ).change(function() {
         $("#iva27" + id).val(numeral($("#iva27" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      $( "#ivamt" + id ).change(function() {
         $("#ivamt" + id).val(numeral($("#ivamt" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      $( "#retenciones" + id ).change(function() {
         $("#retenciones" + id).val(numeral($("#retenciones" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      $( "#retencion_gan" + id ).change(function() {
         $("#retencion_gan" + id).val(numeral($("#retencion_gan" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      $( "#retenciones_iva" + id ).change(function() {
         $("#retenciones_iva" + id).val(numeral($("#retenciones_iva" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });


      $( "#otras_retenciones" + id ).change(function() {
         $("#otras_retenciones" + id).val(numeral($("#otras_retenciones" + id).val()).format('0,0.00' ));
         if( recordChange() == true ) {
            enableBtn(id);
            calculateTotals(id);
         }
      });

      var total_siniva = parseFloat(iva105) + parseFloat(iva21) + parseFloat(iva27) + parseFloat(ivamt);
      var total_iva = parseFloat(iva105) * 10.5 / 100 + parseFloat(iva21) * 21 / 100 + parseFloat(iva27) * 27 / 100;
      var total_ret = parseFloat(retenib) + parseFloat(reteniva) + parseFloat(otrasreten) + parseFloat(totalreten);
      var total = total_siniva + total_iva + total_ret;

      if( operacion == 8 || operacion == 9 ) {
         total_siniva = parseFloat(iva105);
         total_iva = 0;
         total_ret = parseFloat(retenib) + parseFloat(reteniva) + parseFloat(otrasreten) + parseFloat(totalreten);
         total = total_siniva + total_iva + total_ret;
      }

      $("#importe_iva" + id).val(total_iva);
      $("#retencion_gan" + id).val(totalreten);
      $("#importe_neto" + id).val(total_siniva);
      $("#total" + id).val(total);

      $("#importe_iva" + id).val(numeral($("#importe_iva" + id).val()).format('0,0.00' ));
      $("#retencion_gan" + id).val(numeral($("#retencion_gan" + id).val()).format('0,0.00' ));
      $("#importe_neto" + id).val(numeral($("#importe_neto" + id).val()).format('0,0.00' ));
      $("#total" + id).val(numeral($("#total" + id).val()).format('0,0.00' ));

   }

   function recordChange() {
      var id = $('#id').val();
      var f = false;

      if( fecha != $("#fechac" + id).val() ) f = true; 
      if( numero != $("#numero" + id).val() ) f = true;  
      if( empresa != $("#empresa_" + id).val() ) f = true;   
      if( iva105 != $("#iva105" + id).val() ) f = true;   
      if( iva21 != $("#iva21" + id).val() ) f = true;    
      if( iva27 != $("#iva27" + id).val() ) f = true;    
      if( ivamt != $("#ivamt" + id).val() ) f = true;    
      if( retenib != $("#retenciones" + id).val() ) f = true;    
      if( reteniva != $("#retenciones_iva" + id).val() ) f = true;     
      if( otrasreten != $("#otras_retenciones" + id).val() ) f = true;     
      if( totalreten != $("#retencion_gan" + id).val() ) f = true;     
      if( neto != $("#importe_neto" + id).val() ) f = true;     
      if( total != $("#total" + id).val() ) f = true;     
      if( operacion != $("#operacion" + id).val() ) f = true;     
      return f;
   }   

   function showEmpresas(id) {
      $( "#dropdownEmpresa" ).addClass( "active" );
      $( "#dropdownEmpresa" ).css( "opacity", 1 );
      $( "#dropdownEmpresa" ).css( 'display', 'inline-block' );
      $( "#dropdownEmpresa" ).css( "width", "35%" );
      $( "#dropdownEmpresa" ).css( "height", "15%" );
      $( "#dropdownEmpresa" ).css( "height", window.innerHeight - 50 );
      $( "#dropdownEmpresa" ).css( "color", "#009688" );
      $( "#dropdownEmpresa" ).css( "position", "absolute" );
      $( "#dropdownEmpresa" ).css( "vertical-align", "top" );

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

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

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

            if( id == "-1" ) {
               fieldname = '#iempresa';
            }
            else {
               
               fieldname = '#empresa_' + $('#id').val();
               var btnname = '#updateBtn_' + $('#id').val();
            }
            var name = $(this).html(); 
            $( fieldname ).val(name); 

            $.ajax({
                type: "POST",
                url: "getEmpresa.php",
                data: { 'key': key  },
                    success: function(data){

                       console.log( data ); 
                       var msg = JSON.parse(data);
                       
                       $('#code_empresa' + $('#id').val()).val(msg.id); 
                       $('#empresa_' + $('#id').val() ).val(msg.nombre); 

                       found = true;
                       if( recordChange() == true ) {
                          $( "#updateBtn_" + $('#id').val() ).removeClass( "hide" )
                          $( "#updateBtn_" + $('#id').val() ).removeClass( "disabled" )
                       }
                       $('#cancel').css("display", "" );
                     }
           });
           hideEmpresas();
      });   
   }

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

   function populateEmpresas(key,id) {
      $('#dropdownEmpresa').empty();
      $.ajax({
          type: "POST",
          url: "listEmpresas.php",
          data: { 'key': key  },
              success: function(data){
                  var msg = JSON.parse(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#dropdownEmpresa").append($("<li></li>").val(msg[i].option).html(msg[i].name));
                  }

                  if( msg.length > 0 ) {
                     showEmpresas(id);
                     $( "#dropdownEmpresa" ).focus();
                     searchflag = 2;
                  }
                  else {
                     M.toast({html: 'No hay empresas que comiencen con ese nombre',displayLength:3000, classes: 'rounded'}) 
                     hideEmpresas();
                     $( "#empresa_" + id ).focus();
                  }
              }
      });
   }

   function newInvoice() {
      $('#addInvoice').modal('open');
   }


   function onChange(element) {
      switch( element.id ) {
         case "ifecha":
            lastDate = $("#ifecha").val();
            break;

         case "iva105":
         case "iva21":
         case "iva27":
         case "ivamt":
         case "retenciones":
         case "retenciones_iva":
         case "otras_retenciones":
            break;

         case "operacion":
            var  iop = $("#operacion").val();

            console.log( "!!!" + iop );
            if( iop == 8 || iop == 9 ) {
               $( "#iva21" ).addClass( 'hide disabled' );
               $( "#iva27" ).addClass( 'hide disabled' );
               $( "#ivamt" ).addClass( 'hide disabled' );
               $( "#importe_neto" ).addClass( 'hide disabled' );
               $( "#importe_iva" ).addClass( 'hide disabled' );
               $( ".recibo" ).addClass( 'hide disabled' );
               $( "#label105" ).html( 'Importe Abonado' );

            } 
            else {
               $( "#label105" ).html( 'IVA 10.5%' );
               $( "#iva21" ).removeClass( 'hide disabled' );
               $( "#iva27" ).removeClass( 'hide disabled' );
               $( "#ivamt" ).removeClass( 'hide disabled' );
               $( "#importe_neto" ).removeClass( 'hide disabled' );
               $( "#importe_iva" ).removeClass( 'hide disabled' );
               $( ".recibo" ).removeClass( 'hide disabled' );
            }                 
            return;
            break;

         default:
            break;
      }

      var fecha = $( "#ifecha").val(); 
      var numero = $( "#inumero").val();  
      var empresa = $( "#iempresa").val();   
      var operacion = $( "#operacion").val();   

      var iva105 = $( "#iva105").val().replace(',','');   
      var iva21 = $( "#iva21").val().replace(',','');    
      var iva27 = $( "#iva27").val().replace(',','');    
      var ivamt = $( "#ivamt").val().replace(',','');    
      var retenib = $( "#retenciones").val().replace(',','');    
      var reteniva = $( "#retenciones_iva").val().replace(',','');     
      var retengan= $( "#retencion_gan").val().replace(',','');     
      var otrasreten = $( "#otras_retenciones").val().replace(',','');     

      console.log( "HOLA!" );
      console.log( parseFloat(ivamt) );
      var total_siniva = parseFloat(iva105) + parseFloat(iva21) + parseFloat(iva27) + parseFloat(ivamt);
      var total_iva = parseFloat(iva105) * 10.5 / 100 + parseFloat(iva21) * 21 / 100 + parseFloat(iva27) * 27 / 100;
      var total_ret = parseFloat(retenib) + parseFloat(reteniva) + parseFloat(otrasreten) + parseFloat(retengan);
      var total = total_siniva + total_iva + total_ret;

      console.log( parseFloat(total_siniva) );
      console.log( parseFloat(total) );

      if( operacion == "8" || operacion == "9" ) {
         total_siniva = parseFloat(iva105);
         total_iva = 0;
         total_ret = parseFloat(retenib) + parseFloat(reteniva) + parseFloat(otrasreten) + parseFloat(retengan);
         total = total_siniva + total_iva + total_ret;
      }

      $("#importe_iva").val(total_iva);
      $("#retencion_gan").val(retengan);
      $("#importe_neto").val(total_siniva);
      $("#total").val(total);

      $("#iva105").val(numeral($("#iva105").val()).format('0,0.00' ));
      $("#iva21").val(numeral($("#iva21").val()).format('0,0.00' ));
      $("#iva27").val(numeral($("#iva27").val()).format('0,0.00' ));
      $("#ivamt").val(numeral($("#ivamt").val()).format('0,0.00' ));

      $("#retenciones").val(numeral($("#retenciones").val()).format('0,0.00' ));
      $("#retenciones_iva").val(numeral($("#retenciones_iva").val()).format('0,0.00' ));
      $("#retencion_gan").val(numeral($("#retencion_gan").val()).format('0,0.00' ));
      $("#otras_retenciones").val(numeral($("#otras_retenciones").val()).format('0,0.00' ));
      $("#retencion_gan").val(numeral($("#retencion_gan").val()).format('0,0.00' ));

      $("#importe_iva").val(numeral($("#importe_iva").val()).format('0,0.00' ));
      $("#importe_neto").val(numeral($("#importe_neto").val()).format('0,0.00' ));
      $("#total").val(numeral($("#total").val()).format('0,0.00' ));
   }

   function ipopulateEmpresas(key) {
      $('#idropdownEmpresa').empty();
      $.ajax({
          type: "POST",
          url: "listEmpresas.php",
          data: { 'key': key  },
              success: function(data){
                  var msg = JSON.parse(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#idropdownEmpresa").append($("<li></li>").val(msg[i].option).html(msg[i].name));
                  }
                  if( msg.length > 0 ) {
                     ishowEmpresas();
                     $( "#idropdownEmpresa" ).focus();
                     searchflag = 2;
                  }
                  else {
                     M.toast({html: 'No hay empresas que comiencen con ese nombre',displayLength:3000, classes: 'rounded'}) 
                     ihideEmpresas();
                     $( "#iempresa" ).focus(); 
                  }
              }
      });
   }


   function mpopulateEmpresas(key) {
      $('#mdropdownEmpresa').empty();
      $.ajax({
          type: "POST",
          url: "listEmpresas.php",
          data: { 'key': key  },
              success: function(data){
                  var msg = JSON.parse(data);
                  for( i = 0; i < msg.length; i++ ) {
                      $("#mdropdownEmpresa").append($("<li></li>").val(msg[i].option).html(msg[i].name));
                  }
                  if( msg.length > 0 ) {
                     mshowEmpresas();
                     $( "#mdropdownEmpresa" ).focus();
                     searchflag = 2;
                  }
                  else {
                     M.toast({html: 'No hay empresas que comiencen con ese nombre',displayLength:3000, classes: 'rounded'}) 
                     mhideEmpresas();
                     $( "#iempresa" ).focus(); 
                  }
              }
      });
   }

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

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

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

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

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

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

            $.ajax({
                type: "POST",
                url: "getEmpresa.php",
                data: { 'key': key  },
                    success: function(data){
                       var msg = JSON.parse(data);
                       
                       $('#icode_empresa').val(msg.id); 
                       $('#iempresa').val(msg.nombre); 
                       found = true;
                     }
           });
           mhideEmpresas();
      });   
   }

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

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

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

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

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

            $.ajax({
                type: "POST",
                url: "getEmpresa.php",
                data: { 'key': key  },
                    success: function(data){
                       var msg = JSON.parse(data);
                       
                       $('#icode_empresa').val(msg.id); 
                       $('#iempresa').val(msg.nombre); 
                       found = true;
                     }
           });
           ihideEmpresas();
      });   
   }

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

   function modalOpen(e) {
   
       $("#ifecha") .val( lastDate );
       console.log( lastDate );

       $("#iempresa").on('keyup', function() {
            var cliente  = this.value;

            console.log( cliente );
            if( keyTimeout != undefined ) clearInterval(keyTimeout); 
            keyTimeout = setTimeout(function() {
               clearInterval(keyTimeout); 

               if( cliente.length > 0 ) {
                  console.log( "popu: " + cliente );
                  mpopulateEmpresas(cliente,"-1");
               }
            },2000);
       });   
   }

   function Accept() {

      console.log( "1.1" );
      if( $("#inumero").val().length < 13 ) {
         M.toast({html: 'Debe ingresar un numero de comprobante',displayLength:3000, classes: 'rounded'}) 
         return false;
      }

      if( parseFloat($("#total").val()) == 0 ) {
         M.toast({html: 'No hay importes ingresados en el comprobante',displayLength:3000, classes: 'rounded'}) 
         return false;
      }

      console.log( "1.2" );

      var fecha = $( "#ifecha").val(); 
      var numero = $( "#inumero").val();  
      var empresa = $( "#iempresa").val();   
      var code_empresa = $( "#icode_empresa").val();   
      var iva105 = $( "#iva105").val().replace(',','');   
      var iva21 = $( "#iva21").val().replace(',','');    
      var iva27 = $( "#iva27").val().replace(',','');    
      var ivamt = $( "#ivamt").val().replace(',','');    
      var retenib = $( "#retenciones").val().replace(',','');    
      var reteniva = $( "#retenciones_iva").val().replace(',','');     
      var otrasreten = $( "#otras_retenciones").val().replace(',','');     
      var totalreten = $( "#retencion_gan").val().replace(',','');     
      var neto = $( "#importe_neto").val().replace(',','');     
      var total = $( "#total").val().replace(',','');     
      var op = $( "#operacion").val();     
      var importe_iva = $( "#importe_iva").val().replace(',','');
      var importe_neto = $( "#importe_neto").val().replace(',','');
      var etiquetas = $( "#observaciones").val();
      
      var year = fecha.substr(6,4);
      var month = fecha.substr(3,2);

      console.log( fecha  );

      $.ajax({
          type: "POST",
          url: "contableUpdateComprobante.php",
          data: { 'mode': 'append', 'fecha': fecha, 'op': op, 'numero': numero, 'customer': code_empresa, 'empresa': empresa, 'iva105': iva105, 'iva21': iva21, 'iva27': iva27, 'ivamt': ivamt,
                  'importe_iva': importe_iva, 'retenciones': retenib, 'retenciones_iva': reteniva, 'otras_retenciones': otrasreten, 'total': total, 'gan': totalreten, 'etiquetas': etiquetas },
              success: function(data){
                              var msg = JSON.parse(data);
                              if( msg != undefined ) {
                                 console.log( msg.status );
                                 console.log( "ACCEPT!" );
                                 post("contableComprobantes.php", { 'year': year, 'month': month } );
                              }    
                       }
      });
//      console.log("{ 'mode': 'append', 'fecha': " + fecha + ", 'op': " + op + ", 'numero': " + numero + ", 'customer': " + code_empresa + ", 'empresa': " + empresa + ", 'iva105': " + iva105 + ", 'iva21':  " +iva21 + ", 'iva27': " + iva27 + ", 'ivamt': " + ivamt + ", 'importe_iva': " + importe_iva + ", 'retenciones': " + retenib + ", 'retenciones_iva': " + reteniva + ", 'otras_retenciones': " + otrasreten + ", 'total': " + total + ", 'gan': " + totalreten + "}" );
//      post("contableUpdateComprobante.php.php", { 'mode': 'append', 'fecha': fecha, 'op': op, 'numero': numero, 'customer': code_empresa, 'empresa': empresa, 'iva105': iva105, 'iva21': iva21, 'iva27': iva27, 'ivamt': ivamt, 'importe_iva': importe_iva, 'retenciones': retenib, 'retenciones_iva': reteniva, 'otras_retenciones': otrasreten, 'total': total, 'gan': totalreten } );

      $('#addInvoice').modal('close');
//      post("contableComprobantes.php", { 'year': year, 'month': month }  );
   }

   function Cancel() {
      console.log( "CANCEL!" );
   }

   function listClick(el) {
//      console.dir( el );

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

      var li = $( "#dropdownMenu" ).attr( "option" );
//      console.log( "option: " + li );

      switch( el.id ) {
         // Delete
         case "l1":
            $.ajax({
            type: "POST",
                url: "contableUpdateComprobante.php.php",
                data: { 'mode': 'delete', 'id': li }, success: function(data){ 
                                        var msg = JSON.parse(data);
                                        if( msg != undefined ) {
                                           console.log( msg.status );
                                           console.log( "DELETE!" );
                                           post("contableComprobantes.php", "");
                                        }    
                                    }
            });
            break;

         // Edit
         case "l2":
            $( li ).trigger( 'click' );
            break;

         // New
         case "l3":
            newInvoice();
            break;
      }
   }   
   
   
   function onChangeOperacion( el ) {

      console.log( el.id );
      console.log( el.value );
      switch( el.value ) {
         case "5":
            console.log( "RetencionIVA>>" );
            $("#labelPercepcionVA").html("Retencion IVA");
            $("#labelPercepcionIVA2").html("Retencion IVA");
            break;

         default: 
            $("#labelPercepcionVA").html("Percepcion IVA");
            $("#labelPercepcionIVA2").html("Percepcion IVA");
            break;
      }
   }
      
</script>
</body>
</html>

