<?php require_once('Connections/conn.php'); ?>
<?php session_start();
if (!isset($_SESSION['MM_Username'])) {
      header ("Location: modulos/inicio/index.php");
	  }  
 $sede_usuario=$_SESSION['SEDE_USUARIO'];
 
  if (isset($_GET["order"])) $order = @$_GET["order"];
  if (isset($_GET["type"])) $ordtype = @$_GET["type"];

  if (isset($_POST["filter"])) $filter = @$_POST["filter"];
  if (isset($_POST["filter_field"])) $filterfield = @$_POST["filter_field"];
  $wholeonly = false;
  if (isset($_POST["wholeonly"])) $wholeonly = @$_POST["wholeonly"];

  if (!isset($order) && isset($_SESSION["order"])) $order = $_SESSION["order"];
  if (!isset($ordtype) && isset($_SESSION["type"])) $ordtype = $_SESSION["type"];
  if (!isset($filter) && isset($_SESSION["filter"])) $filter = $_SESSION["filter"];
  if (!isset($filterfield) && isset($_SESSION["filter_field"])) $filterfield = $_SESSION["filter_field"];

?>

<html>
<head>
<title>ceulac_sadce -- deudas</title>
<meta name="generator" http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
  body {
    background-color: #FFFFFF;
    color: #004080;
    font-family: Arial;
    font-size: 12px;
  }
  .bd {
    background-color: #FFFFFF;
    color: #000000;
    font-family: Arial;
    font-size: 12px;
  }
  .tbl {
    background-color: #FFFFFF;
  }
  a:link { 
    background-color: #FFFFFF01;
    color: #FF0000;
    font-family: Arial;
    font-size: 12px;
  }
  a:active { 
    background-color: #FFFFFF01;
    color: #0000FF;
    font-family: Arial;
    font-size: 12px;
  }
  a:visited { 
    background-color: #FFFFFF01;
    color: #800080;
    font-family: Arial;
    font-size: 12px;
  }
  .hr {
    background-color: #336699;
    color: #FFFFFF;
    font-family: Arial;
    font-size: 12px;
  }
  a.hr:link {
    color: #FFFFFF;
    font-family: Arial;
    font-size: 12px;
  }
  a.hr:active {
    color: #FFFFFF;
    font-family: Arial;
    font-size: 12px;
  }
  a.hr:visited {
    color: #FFFFFF;
    font-family: Arial;
    font-size: 12px;
  }
  .dr {
    background-color: #FFFFFF;
    color: #000000;
    font-family: Arial;
    font-size: 12px;
  }
  .sr {
    background-color: #FFFFCF;
    color: #000000;
    font-family: Arial;
    font-size: 12px;
  }
</style>
</head>

<script src="jquery.min.js" type="text/javascript"></script>
</head>


<script>
$(document).ready(function(){
	$("#id_alumno").change(function(){
		$.post("carga_carreras_alumno.php",{ id:$(this).val() },function(data){$("#id_carrera").html(data);})
	});
	$("#id_carrera").change(function(){
		$.post("carga_sedes_alumno.php",{ id:$(this).val(),c:$("#id_alumno").val() },function(data){$("#id_sede").html(data);})
	});
})
</script>

<body>
<table class="bd" width="100%"><tr><td class="hr"><h2>Gesti&oacute;n de Deudas</h2></td></tr></table>
<?php
  $conn = connect();
  $showrecs = 25;
  $pagerange = 25;

  $a = @$_GET["a"];
  $recid = @$_GET["recid"];
  $page = @$_GET["page"];
  if (!isset($page)) $page = 1;

  $sql = @$_POST["sql"];

  switch ($sql) {
    case "insert":
      sql_insert();
      break;
    case "update":
      sql_update();
      break;
  }

  switch ($a) {
    case "add":
      addrec();
      break;
    case "view":
      viewrec($recid);
      break;
    case "edit":
      editrec($recid);
      break;
    default:
      select();
      break;
  }

  if (isset($order)) $_SESSION["order"] = $order;
  if (isset($ordtype)) $_SESSION["type"] = $ordtype;
  if (isset($filter)) $_SESSION["filter"] = $filter;
  if (isset($filterfield)) $_SESSION["filter_field"] = $filterfield;
  if (isset($wholeonly)) $_SESSION["wholeonly"] = $wholeonly;

  mysql_close($conn);
?>
<table class="bd" width="100%"><tr><td class="hr"></td></tr></table>
</body>
</html>

<?php function select()
  {
  global $a;
  global $showrecs;
  global $page;
  global $filter;
  global $filterfield;
  global $wholeonly;
  global $order;
  global $ordtype;


  if ($a == "reset") {
    $filter = "";
    $filterfield = "";
    $wholeonly = "";
    $order = "";
    $ordtype = "";
  }

  $checkstr = "";
  if ($wholeonly) $checkstr = " checked";
  if ($ordtype == "asc") { $ordtypestr = "desc"; } else { $ordtypestr = "asc"; }
  $res = sql_select();
  $count = sql_getrecordcount();
  if ($count % $showrecs != 0) {
    $pagecount = intval($count / $showrecs) + 1;
  }
  else {
    $pagecount = intval($count / $showrecs);
  }
  $startrec = $showrecs * ($page - 1);
  if ($startrec < $count) {mysql_data_seek($res, $startrec);}
  $reccount = min($showrecs * $page, $count);
?>
<table class="bd" border="0" cellspacing="1" cellpadding="4">
<tr><td>N&uacute;mero de Registros <?php echo $startrec + 1 ?> - <?php echo $reccount ?> de <?php echo $count ?></td></tr>
</table>
<hr size="1" noshade>
<form action="deudas.php" method="post">
<table class="bd" border="0" cellspacing="1" cellpadding="4">
<tr>
<td><b>Filtrar por</b>&nbsp;</td>
<td><input type="text" name="filter" value="<?php echo $filter ?>"></td>
<td><select name="filter_field">
<option value="">Todos los Campos</option>
<option value="<?php echo "id_alumno" ?>"<?php if ($filterfield == "id_alumno") { echo "selected"; } ?>><?php echo htmlspecialchars("Matrícula") ?></option>
<option value="<?php echo "cedula" ?>"<?php if ($filterfield == "cedula") { echo "selected"; } ?>><?php echo htmlspecialchars("Cédula") ?></option>
<option value="<?php echo "participante" ?>"<?php if ($filterfield == "participante") { echo "selected"; } ?>><?php echo htmlspecialchars("Participante") ?></option>
</select></td>
<td><input type="checkbox" name="wholeonly"<?php echo $checkstr ?>>Palabra Completa</td>
</td></tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="action" value="Aplicar Filtro"></td>
<td><a href="deudas.php?a=reset">Quitar Filtro</a></td>
</tr>
</table>
</form>
<hr size="1" noshade>
<?php showpagenav($page, $pagecount); ?>
<br>
<table class="tbl" border="0" cellspacing="1" cellpadding="5"width="100%">
<tr>

<td class="hr">Editar</td>
<td class="hr"><a class="hr" href="deudas.php?order=<?php echo "id_alumno" ?>&type=<?php echo $ordtypestr ?>"><?php echo htmlspecialchars("Matrícula") ?></a></td>
<td class="hr"><a class="hr" href="deudas.php?order=<?php echo "cedula" ?>&type=<?php echo $ordtypestr ?>"><?php echo htmlspecialchars("Cédula") ?></a></td>
<td class="hr"><a class="hr" href="deudas.php?order=<?php echo "participante" ?>&type=<?php echo $ordtypestr ?>"><?php echo htmlspecialchars("Participante") ?></a></td>
<td class="hr"><a class="hr" href="deudas.php?order=<?php echo "id_carrera" ?>&type=<?php echo $ordtypestr ?>"><?php echo htmlspecialchars("Programa") ?></a></td>
<td class="hr" align="center"><a class="hr" href="deudas.php?order=<?php echo "deuda" ?>&type=<?php echo $ordtypestr ?>"><?php echo htmlspecialchars("Deuda (Bs.)") ?></a></td>
<td class="hr" align="center"><a class="hr" href="deudas.php?order=<?php echo "saldo_favor" ?>&type=<?php echo $ordtypestr ?>"><?php echo htmlspecialchars("Saldo a Favor (Bs.)") ?></a></td>
</tr>
<?php
  global $conn;
  $conn=connect();
 
  mysql_select_db($database_conn, $conn);
  mysql_query ("SET NAMES 'utf8'");
  
  for ($i = $startrec; $i < $reccount; $i++)
  {
    $row = mysql_fetch_assoc($res);
    $style = "dr";
    if ($i % 2 != 0) {
      $style = "sr";
    }
  
  $id_carrera=$row["id_carrera"];
  $query_rstCarreras = "SELECT id_carrera, nombre_carrera FROM carreras where id_carrera='$id_carrera'";
  $rstCarreras = mysql_query($query_rstCarreras, $conn) or die(mysql_error());
  $row_rstCarreras = mysql_fetch_assoc($rstCarreras);
  $totalRows_rstCarreras = mysql_num_rows($rstCarreras);
  $nom_carrera= $row_rstCarreras["nombre_carrera"];
  
  $deuda=$row['cuota1']+$row['cuota2']+$row['cuota3'];
  $deuda=number_format($deuda,2,",",".");
?>
<tr>
<td class="<?php echo $style ?>" align="center"><a href="deudas.php?a=edit&recid=<?php echo $i ?>"><img src="imagenes/edit.gif" border="0" ></a></td>
<td class="<?php echo $style ?>"><?php echo htmlspecialchars($row["id_alumno"]) ?></td>
<td class="<?php echo $style ?>"><?php echo htmlspecialchars($row["cedula"]) ?></td>
<td class="<?php echo $style ?>"><?php echo htmlspecialchars($row["participante"]) ?></td>
<td class="<?php echo $style ?>"><?php echo htmlspecialchars($nom_carrera) ?></td>
<td class="<?php echo $style ?>" align="right" ><?php echo htmlspecialchars($deuda) ?></td>
<td class="<?php echo $style ?>" align="right" ><?php echo htmlspecialchars($row["saldo_favor"]) ?></td>
</tr>
<?php
  }
  mysql_free_result($res);
?>
</table>
<br>
<?php } ?>

<?php function showrow($row, $recid)
  {
?>
<table class="tbl" border="0" cellspacing="1" cellpadding="5"width="50%">
<tr>
<td class="hr"><?php echo htmlspecialchars("Número de Matrícula")."&nbsp;" ?></td>
<td class="dr"><?php echo htmlspecialchars($row["id_alumno"]) ?></td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Cédula/Pasaporte")."&nbsp;" ?></td>
<td class="dr"><?php echo htmlspecialchars($row["cedula"]) ?></td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Apellidos y Nombres")."&nbsp;" ?></td>
<td class="dr"><?php echo htmlspecialchars($row["participante"]) ?></td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Monto de la Deuda")."&nbsp;" ?></td>
<td class="dr"><?php echo htmlspecialchars($row["cuota3"]) ?></td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Saldo a Favor")."&nbsp;" ?></td>
<td class="dr"><?php echo htmlspecialchars($row["saldo_favor"]) ?></td>
</tr>
</table>
<?php } ?>

<?php function showroweditor($row, $iseditmode)
  {
  global $conn;
  
  $conn=connect();
 
  mysql_select_db($database_conn, $conn);
  mysql_query ("SET NAMES 'utf8'");
  
  
  $cod_carrera=$row["id_carrera"];
  $sqlPrograma = "SELECT nombre_carrera,tipo,inversion,costo_inscripcion,costo_uc,costo_regular FROM carreras Where id_carrera='$cod_carrera'";
	$rstPrograma = mysql_query($sqlPrograma, $conn) or die(mysql_error());
	$rowPrograma = mysql_fetch_assoc($rstPrograma);
	$costo_uc=$rowPrograma["costo_uc"];
	$nombre_carrera=$rowPrograma["nombre_carrera"];
	$tipo_carrera=$rowPrograma["tipo"];
	
	 $id_sede=$row["id_sede"];
	$query_rstSede = "SELECT sedes.codigo, sedes.nombre_sede FROM sedes where codigo='$id_sede'";
	$rstSede = mysql_query($query_rstSede, $conn) or die(mysql_error());
	$row_rstSede = mysql_fetch_assoc($rstSede);
	$totalRows_rstSede = mysql_num_rows($rstSede);
	$nombre_sede=$row_rstSede['nombre_sede'];
	
	$total=$row['cuota1']+$row['cuota2']+$row['cuota3'];
	$total=number_format($total,2,",",".");
  
?>
<table class="tbl" border="0" cellspacing="1" cellpadding="3"width="100%">

<tr>
<td class="hr"><?php echo htmlspecialchars("Participante")."&nbsp;" ?></td>
<td class="dr"><input readonly="true" name="participante" type="text" value="<?php echo str_replace('"', '&quot;', trim($row["participante"])) ?>" size="70" maxlength="100"></td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Programa")."&nbsp;" ?></td>
<td class="dr"><input readonly="true" name="id_carrera" type="text" value="<?php echo str_replace('"', '&quot;', trim($nombre_carrera)) ?>" size="70" maxlength="5"></td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Sede")."&nbsp;" ?></td>
<td class="dr"><input readonly="true" type="text" name="id_sede" maxlength="2" value="<?php echo str_replace('"', '&quot;', trim($nombre_sede)) ?>"></td>
</tr>

<tr>
<td colspan="3" >Deuda Actual</td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Cuota 1 (*)")."&nbsp;" ?></td>
<td class="dr"><input name="cuota1" type="text" id="cuota1" onKeyPress="return NumCheck(event, this)"  value="<?php echo str_replace('"', '&quot;', trim($row["cuota1"])) ?>" size="6">
  &nbsp;&nbsp;(Para ingresar decimales utilice punto)</td>
</tr>

<tr>
<td class="hr"><?php echo htmlspecialchars("Cuota 2 (*)")."&nbsp;" ?></td>
<td class="dr"><input name="cuota2" type="text" id="cuota2" onKeyPress="return NumCheck(event, this)"  value="<?php echo str_replace('"', '&quot;', trim($row["cuota2"])) ?>" size="6">
  &nbsp;&nbsp;(Para ingresar decimales utilice punto)</td>
</tr>

<tr>
<td class="hr"><?php echo htmlspecialchars("Cuota 3 (*)")."&nbsp;" ?></td>
<td class="dr"><input name="cuota3" type="text" id="cuota3" onKeyPress="return NumCheck(event, this)"  value="<?php echo str_replace('"', '&quot;', trim($row["cuota3"])) ?>" size="6">
  &nbsp;&nbsp;(Para ingresar decimales utilice punto)</td>
</tr>

<tr>
<td class="hr"><?php echo htmlspecialchars("Total Deuda")."&nbsp;" ?></td>
<td class="dr"><input name="total" type="text" disabled="disabled" id="total"  value="<?php echo $total; ?>" size="6" >
  &nbsp;&nbsp;Bs.</td>
</tr>
<tr>
<td colspan="3" >Saldo a Favor</td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Saldo a Favor (*)")."&nbsp;" ?></td>
<td class="dr"><input name="saldo_favor" type="text" id="saldo_favor" onKeyPress="return NumCheck(event, this)"  value="<?php echo str_replace('"', '&quot;', trim($row["saldo_favor"])) ?>" size="6">
  &nbsp;&nbsp;(Para ingresar decimales utilice punto)</td>
</tr>

</table>
<?php } ?>

<?php function showrowadd($row, $iseditmode)
  {
  global $conn;
  
  mysql_select_db($database_conn, $conn);
mysql_query ("SET NAMES 'utf8'");
$query_rstAlumnos = "SELECT id_alumno,cedula,apellidos,nombres FROM alumnos ORDER BY apellidos,nombres";
$rstAlumnos = mysql_query($query_rstAlumnos, $conn) or die(mysql_error());
$totalRows_rstAlumnos = mysql_num_rows($rstAlumnos);

if($totalRows_rstAlumnos >0)
{
    $array_id = array();
	$array_alumno = array();
	$code=0;
	while($alumno = mysql_fetch_assoc($rstAlumnos))
		{
			$array_id[$code] = $alumno["id_alumno"];		
			$array_alumno[$code]=  $alumno["apellidos"].', '.$alumno["nombres"];	
			$code += 1;
		}
}
  
  
?>
<table class="tbl" border="0" cellspacing="1" cellpadding="3" width="100%">
<tr>
<td class="hr"><?php echo htmlspecialchars("Participante")."&nbsp;" ?></td>

      <td colspan="5">
        <select name="id_alumno" id="id_alumno" style="width:600px">
		<option value="0">Seleccione...</option>
         <?php
 			for($i=0;$i<count($array_alumno);$i++) {
  			echo "<option value=".$array_id[$i].">".$array_alumno[$i]."</option>" ;
			} 
		  ?> 
	    </select>
      </td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Programa")."&nbsp;" ?></td>
<td colspan="3"><select name="id_carrera" id="id_carrera" style="width:600px" onBlur="verificar_deuda(document.form1.id_alumno.value,this.value)"> 
        <option selected value="0">Seleccione...</option>
        <?php
			for($i=0;$i<count($array_areas);$i++) {
			  echo "<option value=".$array_carreras[$i].">".$array_carreras[$i].'-'.$array_areas[$i]."</option>" ;
			}
			?>
      </select><iframe name="frameDeuda" id="frameDeuda" with="0" height="0" frameborder="0" ></iframe></td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Sede")."&nbsp;" ?></td>
<td width="200"><select name="id_sede" id="id_sede" style="width:200px">
        <option value="0">Seleccione...</option>
      </select></td>
</tr>
<tr>
<td colspan="3" >Deuda Actual</td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Cuota 1")."&nbsp;" ?></td>
<td class="dr"><input name="cuota1" type="text" id="cuota1" onKeyPress="return NumCheck(event, this)"  value="<?php echo str_replace('"', '&quot;', trim($row["cuota1"])) ?>" size="6">
  &nbsp;&nbsp;(Para ingresar decimales utilice punto)</td>
</tr>

<tr>
<td class="hr"><?php echo htmlspecialchars("Cuota 2")."&nbsp;" ?></td>
<td class="dr"><input name="cuota2" type="text" id="cuota2" onKeyPress="return NumCheck(event, this)"  value="<?php echo str_replace('"', '&quot;', trim($row["cuota2"])) ?>" size="6">
  &nbsp;&nbsp;(Para ingresar decimales utilice punto)</td>
</tr>

<tr>
<td class="hr"><?php echo htmlspecialchars("Cuota 3")."&nbsp;" ?></td>
<td class="dr"><input name="cuota3" type="text" id="cuota3" onKeyPress="return NumCheck(event, this)"  value="<?php echo str_replace('"', '&quot;', trim($row["cuota3"])) ?>" size="6">
  &nbsp;&nbsp;(Para ingresar decimales utilice punto)</td>
</tr>
<tr>
<td colspan="3" >Saldo a Favor</td>
</tr>
<tr>
<td class="hr"><?php echo htmlspecialchars("Saldo a Favor")."&nbsp;" ?></td>
<td class="dr"><input type="text" name="saldo_favor" value="<?php echo str_replace('"', '&quot;', trim($row["saldo_favor"])) ?>"></td>
</tr>
</table>
<?php } ?>


<?php function showpagenav($page, $pagecount)
{
?>
<table class="bd" border="0" cellspacing="1" cellpadding="4">
<tr>
<td><a href="deudas.php?a=add">Agregar </a>&nbsp;</td>
<?php if ($page > 1) { ?>
<td><a href="deudas.php?page=<?php echo $page - 1 ?>">&lt;&lt;&nbsp;Anterior</a>&nbsp;</td>
<?php } ?>
<?php
  global $pagerange;

  if ($pagecount > 1) {

  if ($pagecount % $pagerange != 0) {
    $rangecount = intval($pagecount / $pagerange) + 1;
  }
  else {
    $rangecount = intval($pagecount / $pagerange);
  }
  for ($i = 1; $i < $rangecount + 1; $i++) {
    $startpage = (($i - 1) * $pagerange) + 1;
    $count = min($i * $pagerange, $pagecount);

    if ((($page >= $startpage) && ($page <= ($i * $pagerange)))) {
      for ($j = $startpage; $j < $count + 1; $j++) {
        if ($j == $page) {
?>
<td><b><?php echo $j ?></b></td>
<?php } else { ?>
<td><a href="deudas.php?page=<?php echo $j ?>"><?php echo $j ?></a></td>
<?php } } } else { ?>
<td><a href="deudas.php?page=<?php echo $startpage ?>"><?php echo $startpage ."..." .$count ?></a></td>
<?php } } } ?>
<?php if ($page < $pagecount) { ?>
<td>&nbsp;<a href="deudas.php?page=<?php echo $page + 1 ?>">Siguiente&nbsp;&gt;&gt;</a>&nbsp;</td>
<?php } ?>
</tr>
</table>
<?php } ?>

<?php function showrecnav($a, $recid, $count)
{
?>
<table class="bd" border="0" cellspacing="1" cellpadding="4">
<tr>
<td><a href="deudas.php">Regresar</a></td>
<?php if ($recid > 0) { ?>
<td><a href="deudas.php?a=<?php echo $a ?>&recid=<?php echo $recid - 1 ?>">Registro Anterior</a></td>
<?php } if ($recid < $count - 1) { ?>
<td><a href="deudas.php?a=<?php echo $a ?>&recid=<?php echo $recid + 1 ?>">Siguiente Registro</a></td>
<?php } ?>
</tr>
</table>
<hr size="1" noshade>
<?php } ?>

<?php function addrec()
{
?>
<table class="bd" border="0" cellspacing="1" cellpadding="4">
<tr>
<td><a href="deudas.php">Regresar</a></td>
</tr>
</table>
<hr size="1" noshade>

<form name="form1" id="form1" enctype="multipart/form-data" action="deudas.php" method="post" onSubmit="return validar_datos()">
<p><input type="hidden" name="sql" value="insert"></p>
<?php
$row = array(
  "id_alumno" => "",
  "cedula" => "",
  "participante" => "",
  "id_carrera" => "",
  "id_sede" => "",
  "cuota1" => "",
  "cuota2" => "",
  "cuota3" => "",
  "saldo_favor" => "",
  "situacion" => "");
showrowadd($row, false);
?>
<p><input type="submit" name="action" value="Guardar"></p>
</form>
<?php } ?>

<?php function viewrec($recid)
{
  $res = sql_select();
  $count = sql_getrecordcount();
  mysql_data_seek($res, $recid);
  $row = mysql_fetch_assoc($res);
  showrecnav("view", $recid, $count);
?>
<br>
<?php showrow($row, $recid) ?>
<br>
<hr size="1" noshade>
<table class="bd" border="0" cellspacing="1" cellpadding="4">
<tr>
<td><a href="deudas.php?a=edit&recid=<?php echo $recid ?>">Editar </a></td>
</tr>
</table>
<?php
  mysql_free_result($res);
} ?>

<?php function editrec($recid)
{
?>
<table class="bd" width="100%"><tr><td class="hr">Sólo puede modificar los campos marcados con (*)</td></tr></table>
<?php
  $res = sql_select();
  $count = sql_getrecordcount();
  mysql_data_seek($res, $recid);
  $row = mysql_fetch_assoc($res);
  showrecnav("edit", $recid, $count);
?>
<br>

<form name="form1" id="form1" enctype="multipart/form-data" action="deudas.php" method="post" onSubmit="return validar_datos()">
<input type="hidden" name="sql" value="update">
<input type="hidden" name="xid_alumno" value="<?php echo $row["id_alumno"] ?>">
<input type="hidden" name="xcedula" value="<?php echo $row["cedula"] ?>">
<input type="hidden" name="xid_carrera" value="<?php echo $row["id_carrera"] ?>">
<input type="hidden" name="xid_sede" value="<?php echo $row["id_sede"] ?>">
<input type="hidden" name="xcuota3" value="<?php echo $row["cuota3"] ?>">
<input type="hidden" name="xsaldo_favor" value="<?php echo $row["saldo_favor"] ?>">
<input type="hidden" name="xsituacion" value="<?php echo $row["situacion"] ?>">
<?php showroweditor($row, true); ?>
<p><input type="submit" name="action" value="Guardar"></p>
</form>
<?php
  mysql_free_result($res);
} ?>

<?php function connect()
{
  $conn = mysql_connect("localhost", "ceula_sadce_admi", "j7BnJdCGzyQBGcud");
  mysql_select_db("ceulac_sadce");
  return $conn;
}

function sqlvalue($val, $quote)
{
  if ($quote)
    $tmp = sqlstr($val);
  else
    $tmp = $val;
  if ($tmp == "")
    $tmp = "NULL";
  elseif ($quote)
    $tmp = "'".$tmp."'";
  return $tmp;
}

function sqlstr($val)
{
  return str_replace("'", "''", $val);
}

function sql_select()
{
  global $conn;
  global $order;
  global $ordtype;
  global $filter;
  global $filterfield;
  global $wholeonly;
  global $sede_usuario;

    
  mysql_select_db($database_conn, $conn);
  mysql_query ("SET NAMES 'utf8'");
  
  $filterstr = sqlstr($filter);
  if (!$wholeonly && isset($wholeonly) && $filterstr!='') $filterstr = "%" .$filterstr ."%";
  if($sede_usuario=='14'){ 
     $sql = "SELECT `id_alumno`, `cedula`, `participante`, `id_carrera`, `id_sede`, `cuota1`, `cuota2`, `cuota3`,  `saldo_favor`, `situacion` FROM `deudas` where id_sede>1";
  }
  else{ 
     $sql = "SELECT `id_alumno`, `cedula`, `participante`, `id_carrera`, `id_sede`, `cuota1`, `cuota2`, `cuota3`,  `saldo_favor`, `situacion` FROM `deudas` where id_sede='$sede_usuario'";
  }
  
  if (isset($filterstr) && $filterstr!='' && isset($filterfield) && $filterfield!='') {
    $sql .= " and " .sqlstr($filterfield) ." like '" .$filterstr ."'";
  } elseif (isset($filterstr) && $filterstr!='') {
    $sql .= " and (`id_alumno` like '" .$filterstr ."') or (`cedula` like '" .$filterstr ."') or (`participante` like '" .$filterstr ."') or (`cuota3` like '" .$filterstr ."')";
  }
   $sql .= " order by participante";
  if (isset($ordtype) && $ordtype!='') $sql .= " " .sqlstr($ordtype);
  
  $res = mysql_query($sql, $conn) or die(mysql_error());
  return $res;
}

function sql_getrecordcount()
{
  global $conn;   
  global $order;
  global $ordtype;
  global $filter;
  global $filterfield;
  global $wholeonly;
  global $sede_usuario;
  
    
  mysql_select_db($database_conn, $conn);
  mysql_query ("SET NAMES 'utf8'");
  $filterstr = sqlstr($filter);
  if (!$wholeonly && isset($wholeonly) && $filterstr!='') $filterstr = "%" .$filterstr ."%";
  if($sede_usuario=='14'){
     $sql = "SELECT COUNT(*) FROM `deudas` where id_sede>1";
  }
  else{
     $sql = "SELECT COUNT(*) FROM `deudas` where id_sede='$sede_usuario'";
	 }
  if (isset($filterstr) && $filterstr!='' && isset($filterfield) && $filterfield!='') {
    $sql .= " and " .sqlstr($filterfield) ." like '" .$filterstr ."'";
  } elseif (isset($filterstr) && $filterstr!='') {
    $sql .= " and (`id_alumno` like '" .$filterstr ."') or (`cedula` like '" .$filterstr ."') or (`participante` like '" .$filterstr ."') or (`deuda` like '" .$filterstr ."')";
  }
  $res = mysql_query($sql, $conn) or die(mysql_error());
  $row = mysql_fetch_assoc($res);
  reset($row);
  return current($row);
}

function sql_insert()
{
  global $conn;
  global $_POST;
  
  $id_alumno=$_POST["id_alumno"];
  $id_carrera=$_POST["id_carrera"];
  $fecha1 = explode("-",date("Y-m-d")); 
  $fecha2 = $fecha1[0].$fecha1[1].$fecha1[2]; 
  $fecha_hoy = cambioFecha($fecha2);   
  $fecha_registro=join ("-",(array_reverse(split("-",$fecha_hoy))));


   // Busco los datos del Participante.
  $sqlalumno = "select cedula,apellidos,nombres from alumnos where id_alumno='$id_alumno'";
  $rstalumno = mysql_query($sqlalumno, $conn) or die(mysql_error());
  $rowalumno=mysql_fetch_assoc($rstalumno);
   
   $cedula=$rowalumno['cedula']; 
   $participante=$rowalumno['apellidos'].','.$rowalumno['nombres'];
   
    $saldo_favor=@$_POST["saldo_favor"];
  if($monto_deuda>0){
     $saldo_favor=0;
  }
    
  if($saldo_favor>0){
	     $cuota1=0;
		 $cuota2=0;
		 $cuota3=0;
   }
   else{
		 $cuota1=$_POST["cuota1"];
		 $cuota2=$_POST["cuota2"];
		 $cuota3=$_POST["cuota3"];
	}
   
   
      
   $sql = "insert into `deudas` (`id_alumno`, `cedula`, `participante`, `id_carrera`, `id_sede`, `cuota1`, `cuota2`, `cuota3`, `saldo_favor`) values (" .sqlvalue(@$_POST["id_alumno"], false).", '$cedula', '$participante', " .sqlvalue(@$_POST["id_carrera"], true).", " .sqlvalue(@$_POST["id_sede"], true).", '$cuota1', '$cuota2', '$cuota3', '$saldo_favor')";
  mysql_query($sql, $conn) or die(mysql_error());
  
   // Incluye la deuda como como movimiento del alumno.
	  $tipo="DE";
	  $subtipo="05-01";
	  $referencia="S/R";
	  $id_sede=$_POST["id_sede"];
	  $monto=$_POST["cuota1"]+$_POST["cuota2"]+$_POST["cuota3"];
	  $concepto="Deuda al ".$fecha_hoy;
	    
      // Elimina las deudas anteriores que tenga el participante.
	  $sql = "delete from `movimientos` where id_alumno='$id_alumno' and id_carrera='$id_carrera' and tipo='$tipo'";
      mysql_query($sql, $conn) or die(mysql_error());
	  // Registro la nueva deuda como un movimiento
	  $sqlAddMov="INSERT INTO movimientos (tipo,subtipo,referencia,id_alumno, sede, id_carrera, concepto, monto, fecha) VALUES('$tipo','$subtipo','$referencia','$id_alumno','$id_sede','$id_carrera','$concepto','$monto','$fecha_registro')";
	  $rsAddMov = mysql_query($sqlAddMov, $conn) or die(mysql_error());
	  
}

function sql_update()
{
  global $conn;
  global $_POST;
  
  $id_alumno=$_POST["xid_alumno"];
  $id_carrera=$_POST["xid_carrera"];
  $id_sede=$_POST["xid_sede"];
  $fecha1 = explode("-",date("Y-m-d")); 
  $fecha2 = $fecha1[0].$fecha1[1].$fecha1[2]; 
  $fecha_hoy = cambioFecha($fecha2);   
 
  $fecha_registro=join ("-",(array_reverse(split("-",$fecha_hoy))));
  
  
  $saldo_favor=@$_POST["saldo_favor"];
  if($monto_deuda>0){
     $saldo_favor=0;
  }
    
  if($saldo_favor>0){
	     $cuota1=0;
		 $cuota2=0;
		 $cuota3=0;
   }
   else{
		 $cuota1=$_POST["cuota1"];
		 $cuota2=$_POST["cuota2"];
		 $cuota3=$_POST["cuota3"];
	}
  
  $sql = "update `deudas` set `cuota1`='$cuota1',`cuota2`='$cuota2',`cuota3`='$cuota3', `saldo_favor`='$saldo_favor', `situacion`=" .sqlvalue(@$_POST["situacion"], true) ." where id_alumno='$id_alumno' and id_carrera='$id_carrera'";
  mysql_query($sql, $conn) or die(mysql_error());
  
   
    // Modifica el Registro de Deuda como movimiento del alumno.
	  $tipo="DE";
	  $subtipo="05-01";
	  $referencia="S/R";
	  $id_sede=$_POST["id_sede"];
	  $concepto="Deuda al ".$fecha_hoy;
      $monto= $cuota1+$cuota2+$cuota3;
	  
	  // Actualiza el Movimienento de Deuda.
	  $sqlAddMov="update movimientos set concepto='$concepto',monto='$monto', fecha='$fecha_registro' where id_alumno='$id_alumno' and id_carrera='$id_carrera' and tipo='$tipo'";
	   mysql_query($sqlAddMov, $conn) or die(mysql_error());  
	  
	  
}
function primarykeycondition()
{
  global $_POST;
  $pk = "";
  $pk .= "(`id_alumno`";
  if (@$_POST["xid_alumno"] == "") {
    $pk .= " IS NULL";
  }else{
  $pk .= " = " .sqlvalue(@$_POST["xid_alumno"], false);
  };
  $pk .= ") and ";
  $pk .= "(`cedula`";
  if (@$_POST["xcedula"] == "") {
    $pk .= " IS NULL";
  }else{
  $pk .= " = " .sqlvalue(@$_POST["xcedula"], true);
  };
  $pk .= ") and ";
  $pk .= "(`id_carrera`";
  if (@$_POST["xid_carrera"] == "") {
    $pk .= " IS NULL";
  }else{
  $pk .= " = " .sqlvalue(@$_POST["xid_carrera"], true);
  };
  $pk .= ") and ";
  $pk .= "(`id_sede`";
  if (@$_POST["xid_sede"] == "") {
    $pk .= " IS NULL";
  }else{
  $pk .= " = " .sqlvalue(@$_POST["xid_sede"], true);
  };
  $pk .= ")";
  return $pk;
}


function cambioFecha($fecha){ //$fecha es de este formato --> ej: 20081229 
	$tieneCeroDiaMes = substr($fecha,6,1); 
	if ($tieneCeroDiaMes == 0) { 
		$diaMes = substr($fecha,7,1); 
	} else { 
		$diaMes = substr($fecha,6,2); 
	} 
	
	$Mes = substr($fecha,4,2); 
	
	
	$Anio = substr($fecha,0,4); 
	return $diaMes."-".$Mes."-".$Anio.""; 
	}     

 ?>
 
 <script type="text/javascript">
function NumCheck(e, field) {
  key = e.keyCode ? e.keyCode : e.which

  // backspace
  if (key == 8) return true
  
  // 0-9
  if (key >= 48 && key <= 57) {

    if (field.value == "") return true
    
    regexp = /...[0-9]{2}$/
    return !(regexp.test(field.value))
  }

  // ,
  if (key == 46) {
  
    if (field.value == "") return false
    
    regexp = /^[0-9]+$/
    return regexp.test(field.value)
  }
  
  // other key
  return false

}
</script>

<script type="text/javascript">
function verificar_deuda(id_alumno,id_carrera)
{
 	if (id_alumno!="0")
	 {
	 url="validar_deuda.php?id_alumno="+id_alumno+"&id_carrera="+id_carrera;
	 frameDeuda.location=url;
	 }
}

</script>


<script type="text/javascript">
	function validar_datos()
	{
	    if(document.form1.id_alumno.value==0){
			alert("El campo <<Participante>> es obligatorio");
			document.form1.id_carrera.focus();
			return false;
			}	
	 	if(document.form1.id_carrera.value==0){
			alert("El campo <<Programa>> es obligatorio");
			document.form1.id_carrera.focus();
			return false;
			}	
		if(document.form1.id_sede.value==0){
			alert("El campo <<Sede>> es obligatorio");
			document.form1.id_carrera.focus();
			return false;
			}		
			
			return true;
	}
</script>