<?php
  $Seccion      = 'Finanzas';
  $SeccionId    = '1';
  $SubSeccion   = 'Facturacion';
  $SubSeccionId = '2';
  $NameSec      = 'Datos de Facturación';
  $NameSin      = 'Datos de Facturación';
  $SecLine      = array('Facturación','Datos de Facturación');
  $Position   = '../../';
  require_once($Position.'config/config.php');
  require_once($Position.'config/conexion.php');
  require_once($Position.'config/user.php');
  require_once($Position.'funciones/acces.php');
  require_once($Position.'funciones/logout.php');
  require_once($Position.'funciones/funciones.php');

  //Guardar Registro
  if( $_POST['Save'] == 'Ok' ){
    //Datos a Guardar
    $TipoPersona 	      = addslashes(strip_tags($_POST['TipoPersona']));
    $Giro 		          = addslashes(strip_tags($_POST['Giro']));
    $NombreFiscal       = addslashes(strip_tags($_POST['NombreFiscal']));
    $NombreComercial	  = addslashes(strip_tags($_POST['NombreComercial']));
    $Rfc 		            = addslashes(strip_tags($_POST['Rfc']));
    $Regimen 		        = addslashes(strip_tags($_POST['Regimen']));
    $Email 		          = addslashes(strip_tags($_POST['Email']));
    $Telefono 		      = addslashes(strip_tags($_POST['Telefono']));
    $TamanoEmpresa 		  = addslashes(strip_tags($_POST['TamanoEmpresa']));

    //Datos Sucursal
    $Calle	        = addslashes(strip_tags($_POST['Calle']));
    $NoExt 		      = addslashes(strip_tags($_POST['NoExt']));
    $NoInt 		      = addslashes(strip_tags($_POST['NoInt']));
    $CodigoPostal   = addslashes(strip_tags($_POST['CodigoPostal']));
    $Colonia 		    = addslashes(strip_tags($_POST['Colonia']));
    $Pais 		      = addslashes(strip_tags($_POST['Pais']));
    $Estado 		    = addslashes(strip_tags($_POST['Estado']));
    $Municipio 	    = addslashes(strip_tags($_POST['Municipio']));

    //Datos de Series
    $SerieId        = $_POST['SerieId'];
    $Serie	        = $_POST['Serie'];
    //var_dump($Serie);

    //Verifica existencia de Datos de Perfil
    $Query = "
      SELECT
        per.Id
      FROM FacturasPerfiles per
      WHERE per.Fk_Cuenta = '$Cuenta[Id]'
    ";
    $Result = mysqli_query($mysqli, $Query);
    $Perfil    = mysqli_fetch_assoc($Result);

    //Edita Informacion de Perfil
    if( $Perfil[Id] ){

      //Edita Informacion
      $Giro = 0;
      $TamanoEmpresa = 0;
      $Query = "
        UPDATE FacturasPerfiles
        SET
          Fk_TipoPersona = '$TipoPersona', Fk_Giro = '$Giro',
          Fk_RegimenFiscal = '$Regimen', Fk_TamanoEmpresa = '$TamanoEmpresa',
          NombreComercial = '$NombreComercial', NombreFiscal = '$NombreFiscal',
          Rfc = '$Rfc', Email  = '$Email', Telefono = '$Telefono'
        WHERE Id = '$Perfil[Id]'
      ";
      $Result = mysqli_query($mysqli, $Query);
      //End Edita Informacion

    }else{

      //Insertar Informacion
      $Query = "
        INSERT INTO FacturasPerfiles
        (
          Fk_Cuenta,
          Fk_TipoPersona, Fk_Giro, Fk_RegimenFiscal, Fk_TamanoEmpresa,
          NombreComercial, NombreFiscal, Rfc, Email, Telefono
         )
      	VALUES
        (
          '$Cuenta[Id]',
          '$TipoPersona', '$Giro', '$Regimen', '$TamanoEmpresa',
          '$NombreComercial', '$NombreFiscal', '$Rfc', '$Email', '$Telefono'
        )
      ";
      $Result = mysqli_query($mysqli, $Query);
      $IdPerfil = mysqli_insert_id($mysqli);
      //End Insertar Informacion
    }
    //End Edita Informacion de Perfil

    //Verifica existencia de Datos de Sucursal Principal
    $Query = "
      SELECT
        suc.Id
      FROM Sucursales suc
      WHERE suc.Fk_Cuenta = '$Cuenta[Id]'
        AND suc.Principal = '1'
    ";
    $Result = mysqli_query($mysqli, $Query);
    $Sucursal    = mysqli_fetch_assoc($Result);

    //Edita Informacion de Sucursal
    if( $Sucursal[Id] ){

      //Edita Informacion
      $Query = "
        UPDATE Sucursales
        SET
          Calle = '$Calle', NoExterior = '$NoExt', NoInterior = '$NoInt', CodigoPostal = '$CodigoPostal',
          Colonia = '$Colonia', Localidad = '$Localidad',
          Fk_Municipio = '$Municipio', Fk_Estado = '$Estado', Fk_Pais = '$Pais'
        WHERE Id = '$Sucursal[Id]' AND Fk_Cuenta = '$Cuenta[Id]' AND Principal = '1'
      ";
      $Result = mysqli_query($mysqli, $Query);
      //End Edita Informacion

      //Edita Series de Sucursal

      $Query = "
        UPDATE Series
        SET
          Borrar = '1'
        WHERE Fk_Sucursal = '$Sucursal[Id]'
      ";
      $Result = mysqli_query($mysqli, $Query);

      foreach($SerieId AS $SerId) {
        $Action           = $Serie[$SerId][Action];
        $SerieId          = $Serie[$SerId][Id];
        $SerNombre        = $Serie[$SerId][Nombre];
        $SerFolio         = $Serie[$SerId][Folio];
        $SerDescripcion   = $Serie[$SerId][Descripcion];

        if( $Action == 'New' ){

          //Inserta Serie
          $Query = "
            INSERT INTO Series
            (
              Fk_Cuenta,
              Fk_Sucursal, Nombre,
              Folio, Descripcion,
              Borrar
             )
          	VALUES
            (
              '$Cuenta[Id]',
              '$Sucursal[Id]', '$SerNombre',
              '$SerFolio', '$SerDescripcion',
              '0'
            )
          ";
          $Result = mysqli_query($mysqli, $Query);
          //End Inserta Serie

        }elseif( $Action == 'Edit' ){

          //Actualiza Serie de Sucursal
          $Query = "
            UPDATE Series
            SET
              Nombre = '$SerNombre',
              Folio = '$SerFolio', Descripcion = '$SerDescripcion',
              Borrar = '0'
            WHERE Id = '$SerieId'
          ";
          $Result = mysqli_query($mysqli, $Query);
          //End Actualiza Serie de Sucursal

        }
      }
      //End Edita Series de Sucursal

      $Query = "
        DELETE FROM Series
        WHERE Fk_Sucursal = '$Sucursal[Id]'
        AND Borrar = '1'
      ";
      $Result = mysqli_query($mysqli, $Query);

    }else{

      //Insertar Informacion
      $Query = "
        INSERT INTO Sucursales
        (
          Fk_Cuenta,
          Principal, Nombre,
          Calle, NoExterior, NoInterior, CodigoPostal,
          Colonia, Localidad,
          Fk_Municipio, Fk_Estado, Fk_Pais
         )
      	VALUES
        (
          '$Cuenta[Id]',
          '1', 'Principal',
          '$Calle', '$NoExt', '$NoInt', '$CodigoPostal',
          '$Colonia', '$Localidad',
          '$Municipio', '$Estado', '$Pais'
        )
      ";
      $Result = mysqli_query($mysqli, $Query);
      $IdPerfil = mysqli_insert_id($mysqli);
      //End Insertar Informacion
    }
    //End Edita Informacion de Sucursal

  }
  //End Guardar Registro

  //Perfil
  $Query = "
    SELECT
      per.Id,
      per.Fk_TipoPersona, per.Fk_Giro, per.Fk_RegimenFiscal, per.Fk_TamanoEmpresa,
      per.NombreComercial, per.NombreFiscal, per.Rfc, per.Email, per.Telefono
    FROM FacturasPerfiles per
    WHERE per.Fk_Cuenta = '$Cuenta[Id]'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $Per    = mysqli_fetch_assoc($Result);

  //Sucursal Principal
  $Query = "
    SELECT
      suc.Id,
      suc.Calle, suc.NoExterior, suc.NoInterior, suc.CodigoPostal,
      suc.Colonia, suc.Localidad,
      suc.Fk_Municipio, suc.Fk_Estado, suc.Fk_Pais
    FROM Sucursales suc
    WHERE suc.Fk_Cuenta = '$Cuenta[Id]'
      AND suc.Principal = '1'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $Suc    = mysqli_fetch_assoc($Result);

  //Tipos de Personas
  $Query = "
    SELECT
      per.Id, per.Nombre
    FROM PersonasTipos per
    ORDER BY per.Nombre ASC
  ";
  $TiposPersona = $mysqli->query($Query);

  //Giros
  /*$Query = "
    SELECT
      gir.Id, gir.Nombre
    FROM Giros gir
    ORDER BY gir.Nombre ASC
  ";
  $Giros = $mysqli->query($Query);*/

  //Regimenes
  $Query = "
    SELECT
      reg.Id, reg.Nombre
    FROM RegimenesFiscales reg
    WHERE reg.Fk_Persona = '$Per[Fk_TipoPersona]'
    ORDER BY reg.Nombre ASC
  ";
  $Regimenes = $mysqli->query($Query);

  //Tamaños de Empresa
  $Query = "
    SELECT
      tam.Id, tam.Nombre, tam.Descripcion
    FROM TamanosEmpresa tam
    ORDER BY tam.Id ASC
  ";
  $Tamanos = $mysqli->query($Query);

  //Paises
  $Query = "
    SELECT
      pai.Id, pai.Nombre
    FROM Paises pai
    WHERE pai.Activo = '1'
    ORDER BY pai.Nombre ASC
  ";
  $Paises = $mysqli->query($Query);

  //Estados
  $Query = "
    SELECT
      est.Id, est.Nombre
    FROM Estados est
    WHERE est.Fk_Pais = '$Suc[Fk_Pais]'
    ORDER BY est.Nombre ASC
  ";
  $Estados = $mysqli->query($Query);

  //Municipios
  $Query = "
    SELECT
      mun.Id, mun.Nombre
    FROM Municipios mun
    WHERE mun.Fk_Estado = '$Suc[Fk_Estado]'
    ORDER BY mun.Nombre ASC
  ";
  $Municipios = $mysqli->query($Query);

  //$Series
  $Query = "
    SELECT
      ser.Id, ser.Nombre, ser.Folio, ser.Descripcion
    FROM Series ser
    WHERE ser.Fk_Cuenta = '$Cuenta[Id]'
      AND ser.Fk_Sucursal = '$Suc[Id]'
    ORDER BY ser.Nombre ASC
  ";
  $Series = $mysqli->query($Query);

  //Numero de Serie máximo
  $Query = "
    SELECT
      ser.Id
    FROM Series ser
    WHERE ser.Fk_Cuenta = '$Cuenta[Id]'
      AND ser.Fk_Sucursal = '$Suc[Id]'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $SerieMax = mysqli_fetch_assoc($Result);

?>

<!DOCTYPE html>
<html lang="en">

<?php require_once($Position.'head.php'); ?>

<body class="fix-sidebar fix-header card-no-border">
    <!-- ============================================================== -->
    <!-- Preloader - style you can find in spinners.css -->
    <!-- ============================================================== -->
    <div class="preloader">
        <svg class="circular" viewBox="25 25 50 50">
            <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" /> </svg>
    </div>
    <!-- ============================================================== -->
    <!-- Main wrapper - style you can find in pages.scss -->
    <!-- ============================================================== -->
    <div id="main-wrapper">
        <?php require_once($Position.'header.php'); ?>
        <?php require_once($Position.'menu.php'); ?>

        <!-- ============================================================== -->
        <!-- Page wrapper  -->
        <!-- ============================================================== -->
        <div class="page-wrapper">
            <!-- ============================================================== -->
            <!-- Container fluid  -->
            <!-- ============================================================== -->
            <div class="container-fluid">
              <form method="post" enctype="multipart/form-data" data-validate="parsley" role="form" id="FormPer">
                <!-- ============================================================== -->
                <!-- Bread crumb and right sidebar toggle -->
                <!-- ============================================================== -->
                <div class="row page-titles page-titles-fixed">

                    <?php require_once($Position.'title.php'); ?>

                    <!-- Botones -->
                    <div class="col-md-7 align-self-center text-right">
                      <div class="btn-group" role="group" aria-label="Basic example">
                        <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='index.php'">Regresar<i class="fa fa-arrow-left m-l-5"></i></button>
                        <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='edit.php'">Nuevo<i class="fa fa-plus m-l-5"></i></button>
                        <button type="submit" class="btn btn-sm btn-success">Guardar<i class="fa fa-check m-l-5"></i></button>
                        <input type="hidden" name="Save" value="Ok">
                        <?php if( !empty($Cli['Id']) ){ ?>
                          <input type="hidden" name="Id" value="<?php echo $Cli['Id']; ?>">
                        <?php }else{ ?>
                          <input type="hidden" name="New" value="Ok">
                        <?php } ?>
                      </div>
                    </div>
                    <!-- End Botones -->

                </div>
                <!-- ============================================================== -->
                <!-- End Bread crumb and right sidebar toggle -->
                <!-- ============================================================== -->
                <!-- ============================================================== -->
                <!-- Page Content -->
                <!-- ============================================================== -->
                <div class="row inner-fixed-content">

                  <div class="col-sm-12">

                    <?php /*if( $Save == 'Ok' || $_GET['New'] == Ok ){ ?>
                      <!-- Alerta Save -->
                      <div class="alert alert-success"> <i class="fa fa-check m-r-10"></i> Guardado !
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
                      </div>
                      <!-- End Alerta Save -->
                    <?php }*/ ?>

                    <!-- Card -->
                    <div class="card">
                      <div class="card-body">
                        <h4 class="card-title"><?php echo $NameSin; ?></h4>
                        <h6 class="card-subtitle"><?php echo $NameSec; ?></h6>

                        <div class="row">

                          <!-- Tipo de Persona -->
                          <div class="form-group col-sm-6">
                            <label>Tipo de Persona <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="TipoPersona" name="TipoPersona" class="form-control chosen-select">
                                <option></option>
                                <?php
                                  mysqli_data_seek($TiposPersona, 0);
                                  while($Tip = mysqli_fetch_array($TiposPersona)) {
                                ?>
                                  <option <?php if( $Tip['Id'] == $Per['Fk_TipoPersona'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Tip['Id']; ?>"><?php echo $Tip['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Tipo de Persona -->

                          <!-- Giro --
                          <div class="form-group col-sm-6">
                            <label>Giro <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Giro" name="Giro" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Giros, 0);
                                while($Gir = mysqli_fetch_array($Giros)) {
                                ?>
                                  <option <?php if( $Gir['Id'] == $Per['Fk_Giro'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Gir['Id']; ?>"><?php echo $Gir['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Giro -->

                          <!-- Nombre Fiscal -->
                          <div class="form-group col-sm-6">
                            <label>Nombre Fiscal / Razón Social <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="NombreFiscal" value="<?php echo $Per['NombreFiscal']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Nombre Fiscal -->

                          <!-- Nombre Comercial --
                          <div class="form-group col-sm-6">
                            <label>Nombre Comercial <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="NombreComercial" value="<?php echo $Per['NombreComercial']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Nombre Comercial -->

                          <!-- Rfc -->
                          <div class="form-group col-sm-6">
                            <label>Rfc <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="Rfc" value="<?php echo $Per['Rfc']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Rfc -->

                          <!-- Regimen -->
                          <div class="form-group col-sm-6">
                            <label>Régimen Fiscal <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Regimen" name="Regimen" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Regimenes, 0);
                                while($Reg = mysqli_fetch_array($Regimenes)) {
                                ?>
                                  <option <?php if( $Reg['Id'] == $Per['Fk_RegimenFiscal'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Reg['Id']; ?>"><?php echo $Reg['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Regimen -->

                          <!-- Email -->
                          <div class="form-group col-sm-6">
                            <label>Email <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" data-type="email" name="Email" value="<?php echo $Per['Email']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Email -->

                          <!-- Tamaño de la Empresa --
                          <div class="form-group col-sm-6">
                            <label>Tamaño de la Empresa <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="TamanoEmpresa" name="TamanoEmpresa" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Tamanos, 0);
                                while($Tam = mysqli_fetch_array($Tamanos)) {
                                ?>
                                  <option <?php if( $Tam['Id'] == $Per['Fk_TamanoEmpresa'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Tam['Id']; ?>"><?php echo $Tam['Nombre'].' '.$Uso['Descripcion']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Tamaño de la Empresa -->

                        </div>

                      </div>
                    </div>

                    <!-- Card -->
                    <div class="card">
                      <div class="card-body">
                        <h4 class="card-title">Dirección</h4>
                        <h6 class="card-subtitle"><?php echo $NameSec; ?></h6>

                        <div class="row">

                          <!-- Calle -->
                          <div class="form-group col-sm-12">
                            <label>Calle <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="Calle" value="<?php echo $Suc['Calle']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Calle -->

                          <!-- NoExt -->
                          <div class="form-group col-sm-4">
                            <label>Número Exterior <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="NoExt" value="<?php echo $Suc['NoExterior']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End NoExt -->

                          <!-- NoInt -->
                          <div class="form-group col-sm-4">
                            <label>Número Interior <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input name="NoInt" value="<?php echo $Suc['NoInterior']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End NoInt -->

                          <!-- Codigo Postal -->
                          <div class="form-group col-sm-4">
                            <label>Código Postal <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="CodigoPostal" value="<?php echo $Suc['CodigoPostal']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Codigo Postal -->

                          <!-- Colonia -->
                          <div class="form-group col-sm-6">
                            <label>Colonia <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="Colonia" value="<?php echo $Suc['Colonia']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Colonia -->

                          <!-- Localidad -->
                          <div class="form-group col-sm-6">
                            <label>Localidad </label>
                            <div class="controls">
                              <input name="Localidad" value="<?php echo $Suc['Localidad']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Localidad -->

                          <!-- Pais -->
                          <div class="form-group col-sm-4">
                            <label>País <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Pais" name="Pais" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Paises, 0);
                                while($Pai = mysqli_fetch_array($Paises)) {
                                ?>
                                  <option <?php if( $Pai['Id'] == $Suc['Fk_Pais'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Pai['Id']; ?>"><?php echo $Pai['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Pais -->

                          <!-- Estado -->
                          <div class="form-group col-sm-4">
                            <label>Estado <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Estado" name="Estado" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Estados, 0);
                                while($Est = mysqli_fetch_array($Estados)) {
                                ?>
                                  <option <?php if( $Est['Id'] == $Suc['Fk_Estado'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Est['Id']; ?>"><?php echo $Est['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Estado -->

                          <!-- Municipio -->
                          <div class="form-group col-sm-4">
                            <label>Municipio <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Municipio" name="Municipio" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Municipios, 0);
                                while($Mun = mysqli_fetch_array($Municipios)) {
                                ?>
                                  <option <?php if( $Mun['Id'] == $Suc['Fk_Municipio'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Mun['Id']; ?>"><?php echo $Mun['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Municipio -->

                        </div>

                      </div>
                    </div>
                    <!-- End Card -->

                    <!-- Card -->
                    <div class="card">
                      <div class="card-body">
                        <h4 class="card-title">Series de Sucursal</h4>
                        <h6 class="card-subtitle">Principal</h6>

                        <div class="row">
                          <div class="col-sm-12 table-responsive m-t-20">
                            <table class="display nowrap table table-hover table-striped table-bordered" cellspacing="0" width="100%">
                              <thead>
                                <tr>
                                  <th>Serie</th>
                                  <th>Folio</th>
                                  <th>Descripción</th>
                                  <th></th>
                                </tr>
                              </thead>
                              <tbody class="Series">
                                <?php
                                mysqli_data_seek($Series, 0);
                                while($Serie = mysqli_fetch_array($Series)) {
                                  $Action = 'Edit';
                                  $Consecutivo = $Serie['Id'];
                                ?>
                                  <?php require('serie.php');  ?>
                                <?php } ?>
                              </tbody>
                            </table>
                            <div>
                              <button type="button" class="btn btn-success btn-s BtnAddSerie"><i class="fa fa-plus m-r-10"></i>Agregar Serie</button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- End Card -->

                  </div>
                </div>
              </form>
              <!-- ============================================================== -->
              <!-- End Page Content -->
              <!-- ============================================================== -->
            </div>
            <!-- ============================================================== -->
            <!-- End Container fluid  -->
            <!-- ============================================================== -->

            <?php require_once($Position.'footer.php'); ?>

        </div>
        <!-- ============================================================== -->
        <!-- End Page wrapper  -->
        <!-- ============================================================== -->
    </div>
    <?php require_once($Position.'scripts.php'); ?>
    <script>

      $(".chosen-select").chosen();

      //Regimen
      $("#TipoPersona").change(function () {
        $("option:selected", this).each(function () {
          per = $(this).val();
          //Actualiza Estados
          $.post("regimenes.php", { per: per }, function(data){
            console.log(data);
            $('#Regimen').html(data);
            $('#Regimen').trigger("chosen:updated");
          });
        });
      });
      //End Regimen

      //Pais-Estados
      $("#Pais").change(function () {
        $("option:selected", this).each(function () {
          pai = $(this).val();
          //Actualiza Estados
          $.post("estados.php", { pai: pai }, function(data){
            $('#Estado').html(data);
            $('#Estado').trigger("chosen:updated");
          });
        });
      });
      //End Pais-Estados

      //Estado-Municipios
      $("#Estado").change(function () {
        $("option:selected", this).each(function () {
          est = $(this).val();
          //Actualiza Estados
          $.post("municipios.php", { est: est }, function(data){
            $('#Municipio').html(data);
            $('#Municipio').trigger("chosen:updated");
          });
        });
      });
      //End Estado-Municipios

      //Agregar Series
      var Con = <?php echo $SerieMax['Id'] + 1; ?>;
      $(".BtnAddSerie").click(function () {
        Action = 'New';
        Con = Con + 1;
        $.post("serie.php", { Action: Action, Con: Con }, function(data){
          $('.Series').append(data);
        });
      });
      //End Agregar Series

      //Elimina Series
      $(document.body).on('click', '.BtnDelSerie' ,function(){
        $(this).parents('.Serie').remove();
      });
      //End Elimina Series

      //Input sin espacios
      $(document.body).on('keyup change', '.InSinEspacios' ,function(){
        val = $(this).val();
        val = $.trim(val);
        //val = val.replace(/\s+/g, '');
        val= val.split(' ').join('');
        $(this).val(val);
      });
      //End Elimina Series

      <?php if( $Save == 'Ok' ){ ?>
      $( document ).ready(function() {
         swal({
          title: "Elemento Guardado!",
          text: "...",
          timer: 2000,
          showConfirmButton: false
        });
      });
      <?php } ?>

    </script>

</body>

</html>
