// JavaScript Document
//Se pasa como parametro un objeto, y en la carga del formulario éste tomará el foco
function tomarfoco(objeto)
{
	objeto.focus();
}

//Al cargarse por primera vez el formulario de Alta de Clientes, se toma el foco del campo apellido y luego se llama a la función carga_localidades. De esta manera se produce, la carga en cadena de provincia, localidad y código postal.
function onload_clientes(objeto,selObj1,objeto2,indiceobjeto2, restore1,formulario, taglocalidades, tagcodpostales, codpostal)
{
	tomarfoco(objeto);
	carga_localidades(selObj1,objeto2,indiceobjeto2, restore1,formulario, taglocalidades, tagcodpostales, codpostal, 'cargarcodigospostales');
}
//--------------------------------------------------------------

var urlinsumos = "../reservas/generaddl.php?hotel=";

function handleHttpResponseinsumos(taginsumo)
{	
  if (http.readyState == 4) {
    results = http.responseText;
	resultado = results[0];
	if(resultado != '') {
		document.getElementById(taginsumo).innerHTML = http.responseText;

		if(resultado == 'no') {
			document.getElementById(taginsumo).style.color = '';
			
		} else {
			document.getElementById(taginsumo).style.color = '';
			
		}
		document.getElementById(taginsumo).style.background = '';
	}
  } 
	calcular_total();
}

function buscar_insumo(txtcodigo, restore1, formulario, taginsumo)
{

	obj = document.formAltaReserva.ddlhotel.options[document.formAltaReserva.ddlhotel.selectedIndex];
	id = document.formAltaReserva.ddlhotel.selectedIndex;
		
	obj.value = obj.value.toUpperCase();
  var VALOR =  eval("'"+obj.value+"'");
  if (restore1) obj.value = '';
  
	document.getElementById(taginsumo).style.background = '';
	document.getElementById(taginsumo).style.padding = '';
	try{
		var loginelegido = VALOR;

	 http.open("GET", urlinsumos + escape(loginelegido) + '&taginsumo=' + taginsumo, true);
	 setTimeout("handleHttpResponseinsumos('"+taginsumo+"')",400);
	 
	 http.send(null);
	} 
	

	catch (e) {
		//setTimeout("busca_insumo(txtcodigo,restore1,formulario,taginsumo)", 400);
	}
	
	setTimeout("buscar_regimen(this, 0, 'formAltaReserva', 'tdddlregimen')",400);
}


var urlregimen = "../reservas/generaregimen.php?hotel=";

function handleHttpResponseinsumosregimen(taginsumo2)
{	
  if (http.readyState == 4) {
    results = http.responseText;
	resultado = results[0];
	if(resultado != '') {
		

	document.getElementById(taginsumo2).innerHTML = http.responseText;
if(resultado == 'no') {
			document.getElementById(taginsumo2).style.color = '';
			
		} else {
			document.getElementById(taginsumo2).style.color = '';
			
		}
		document.getElementById(taginsumo2).style.background = '';
	}
  } 

setTimeout("rest()",400);
setTimeout("calcular_total()", 400);
}


function buscar_regimen(txtcodigo, restore2, formulario, taginsumo2)
{
	obj = document.formAltaReserva.ddlhotel.options[document.formAltaReserva.ddlhotel.selectedIndex];
	id = document.formAltaReserva.ddlhotel.selectedIndex;
		
	obj.value = obj.value.toUpperCase();
  var VALOR =  eval("'"+obj.value+"'");
  if (restore2) obj.value = '';
	document.getElementById(taginsumo2).style.background = '';
	document.getElementById(taginsumo2).style.padding = '';
	try{
		var loginelegido = VALOR;

	 http.open("GET", urlregimen + escape(loginelegido) + '&taginsumo2=' + taginsumo2, true);
	 setTimeout("handleHttpResponseinsumosregimen('"+taginsumo2+"')",400);
	 
	 http.send(null);
	} catch (e) {
		//setTimeout("carga_insumo(txtcodigo,restore1,formulario,taginsumo)", 400);
	}
	
}

//-----------------------------------------------------------------------------------------------------------------------------------//
//FUNCIONES PARA CODIGOS POSTALES
//Se genera la url del .php donde se encuentra la función de load y echo del select con las localidades para una determinada provincia.
//el id localidades, corresponde a una celda del .php principal identificada con ese nombre, sobre la cuál se insertará el DDL de localidades una vez creado.
var urllocalidades = "../clientes/cargar_localidades.php?codprovincia=";
function handleHttpResponselocalidades(taglocalidades)
{	
  if (http.readyState == 4) {
    results = http.responseText;
	resultado = results[0];
	if(resultado != '') {
		document.getElementById(taglocalidades).innerHTML = http.responseText;
		if(resultado == 'no') {
			document.getElementById(taglocalidades).style.color = '';
			
		} else {
			document.getElementById(taglocalidades).style.color = '';
			
		}
		document.getElementById(taglocalidades).style.background = '';
	}
  }
}

//Se genera la url del .php donde se encuentra la función de load y echo del select con los códigos postales para una determinada localidad.
//el id codpostales, corresponde a una celda del .php principal identificada con ese nombre, sobre la cuál se insertará el TextBox de código postal una vez creado.
var urlcodpostales = "../clientes/cargar_codpostales.php?id_codpostal=";
function handleHttpResponsecodpostales(tagcodpostales)
{
  if (http.readyState == 4) {
    results = http.responseText;
	resultado = results[0];
	if(resultado != '') {
		document.getElementById(tagcodpostales).innerHTML = http.responseText;
		if(resultado == 'no') {
			document.getElementById(tagcodpostales).style.color = '';
			
		} else {
			document.getElementById(tagcodpostales).style.color = '';
			
		}
		document.getElementById(tagcodpostales).style.background = '';
	}
  }
}

//Se toma el valor de codprovincia seleccionado en el DDL de provincias y el valor se envía por GET a cargar_localidades.php el cuál generará el DDL de localidades, con las loacalidades para esa provincia en particular. Los parámetros que se pasan corresponden a: el DDL de provincias, un valor en 0, nombre del formulario que contiene los controles, nombre de la etiqueta donde se insertará el DDL de localidades, nombre de la etiqueta donde se insertará el TextBox de código postal, y una cadena de activación para la función onload_clientes
function carga_localidades(selObj1,objeto2,indiceobjeto2, restore1,formulario, taglocalidades, tagcodpostales, codpostal, cadena)
{
	 var VALOR =  eval("'"+selObj1.options[selObj1.selectedIndex].value+"'");
  if (restore1) selObj1.selectedIndex=0;
	document.getElementById(taglocalidades).style.background = '';
	document.getElementById(taglocalidades).style.padding = '';
	try{
		var loginelegido = VALOR;
	// var loginelegido = document.getElementById("pais").value;
	 http.open("GET", urllocalidades + escape(loginelegido) + '&indice=' + indiceobjeto2 + '&tagcodpostales=' + tagcodpostales, true);
	 setTimeout("handleHttpResponselocalidades('"+taglocalidades+"')",400);	
	 
	 http.send(null);
	} catch (e) {
		setTimeout("carga_localidades(selObj1,restore1)", 400);
	}

	setTimeout("carga_codpostales(document."+ formulario +"."+ objeto2 +", 0, '"+ tagcodpostales +"', '"+codpostal+"')",500);
}

//Se toma el valor de id_codpostal seleccionado en el DDL de localidades y el valor se envía por GET a cargar_codpostales.php el cuál generará el TextBox de código postal, con el código postal para esa localidad en particular. Los parámetros que toma esta función son: el DDL de códigos postales, un valor en 0, nombre de la etiqueta sobre la cuál se insertará el TextBox de código postal.
function carga_codpostales(selObj2,restore2,tagcodpostales,codpostal)
{
	 var VALOR =  eval("'"+selObj2.options[selObj2.selectedIndex].value+"'");
  if (restore2) selObj2.selectedIndex=0;
	document.getElementById(tagcodpostales).style.background = '';
	document.getElementById(tagcodpostales).style.padding = '';
	try{
		var loginelegido = VALOR;
	// var loginelegido = document.getElementById("pais").value;
	 http.open("GET", urlcodpostales + escape(loginelegido) + '&codpostal=' + codpostal, true);	 
	 setTimeout("handleHttpResponsecodpostales('"+tagcodpostales+"')", 400);
	 http.send(null);
	} catch (e) {
		setTimeout("carga_codpostales(selObj2,restore2)", 400);
	}
}

//Función necesaria para ejecutar las funciones carga_localidades() y carga_codpostales
function getHTTPObject()
{
	var xmlhttp; 
	/*@cc_on 
	@if (@_jscript_version >= 5) try { 
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
	} catch (e) { 
		try { 
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
		} catch (E) { 
			xmlhttp = false; 
		} 
	} @else xmlhttp = false; 
	@end 
	@*/  
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest(); 
		} catch (e) { 
			xmlhttp = false; 
		} 
	} 
	return xmlhttp; 
} 
var http = getHTTPObject();
//-----------------------------------------------------------------------------------------------------------------------------------//
//Completa el TextBox buscarcomo, a medida que se ingresan datos en Apellido y Nombre
function completa_buscarcomo()
{
	with (document.frmAltaCliente)
	{
		txtbuscarcomo.value = '';
		
		if ((txtapellido.value != null) && (txtnombre.value != null))
		{
			txtbuscarcomo.value = txtapellido.value + ", " + txtnombre.value;
		}
		else if ((txtapellido.value != null) && (txtnombre.value == null))
		{
			txtbuscarcomo.value = txtapellido.value;
		}
		else if ((txtapellido.value == null) && (txtnombre.value != null))
		{
			txtbuscarcomo.value = txtnombre.value;
		}		
	}
}

//Cambia el color de una fila en una tabla, se pasa como parámetro el objeto y el color en hexadecimal
function fila_cambiar_color(objeto, colorfila, colortexto)
{
	objeto.style.background = colorfila;
	objeto.style.color = colortexto;
	
	if (objeto.style.fontWeight == '')
		objeto.style.fontWeight = '';
	else
		objeto.style.fontWeight = '';
}

//Habilita dos radiobuttons que se encuentran deshabilitados
function habilitar_radiobuttons()
{
	document.getElementById('radio').disabled = false;
	document.getElementById('radio2').disabled = false;
}

//Recarga la ventana Padre y cierra la hija
function ventana_recargarycerrar()
{
	opener.document.focus();
	opener.window.location.reload();
	window.close();
}

//Reemplaza comas por puntos para poder grabar en la base de datos correctamente el tipo de dato Float
function reemplazar_decimales(objeto)
{
	objeto.value = objeto.value.replace(',','.');
}

//Valida las campos de un formulario. Esta función es para validar formularioes que requieran una validación más compleja que la automática de DreamWeaver. Nota: EL código de esta función puede variar en los dbhandlers.php, dependiendo el entorno donde se quiera aplicar.
function validar_formulario()
{
	var errores = '';
	var i, argumentos = validar_formulario.arguments;
	
	alert (argumentos);
	
	for (i = 0; i < argumentos.length(); i++)
	{
		alert ('holaaaaaa');
		objeto = document.getElementById(argumentos[i]);
		
		if (!objeto)
			alert('holaaaa');
	}
	document.MM_returnValue = (errores == '');
}

//FUNCIONES DEFINIDAS POR EL USUARIO PARA COMPLEMENTAR EL FUNCIONAMIENTO DE CALENDARIO
//Funciones para W.A.I.M
//Crea un nuevo calendario, y lo inserta en el tag indicado.
function crear_calendario(destino)
{	
		calendario = new Epoch('calendario', 'popup', document.getElementById(destino), false);
}

//Función de DreamWeaver para validación de formularios
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.id; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' debe contener una dirección de e-mail válida.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' debe contener un número.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' debe contener un número entre '+min+' y '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es requerido.\n'; }
    } if (errors) alert('Se han encontrado los siguientes errores:\n'+errors);
    document.MM_returnValue = (errors == '');
} }

function cambiar_decimales(objeto)
{
	objeto.value = objeto.value.replace(',', '.');
	objeto.value = parseFloat(objeto.value).toFixed(2);
}

function confirmLink(cadena,url)
{
	if (confirm(cadena))
	{
		window.location = url;		
	}
}


function buscar_producto()
{
	var cant = this.frmVender.txtcant.value;
	window.open('buscarproducto_vta.php?cantidad='+cant,'_blank','height=400, width=850,status=no, location=no, scrollbar=yes');
	
}

function seleccionar_producto(idproducto,nombre,precio,stock)
{
	opener.frmVender.id_producto.value = idproducto;
	opener.frmVender.txtdetalle.value = nombre;
	opener.frmVender.txtprecio.value = precio;
	opener.frmVender.txtstock.value = (stock - opener.frmVender.txtcant.value);
	opener.frmVender.txtcant.focus();
	
	window.close();
	
	
}


function agregar_producto()
{
	if (document.frmVender.txtdetalle.value != '')
	{
		var html, cant;
		var unitario, importe;
		var dest = document.getElementById('productos');

		cant = document.frmVender.txtcant.value;
		stock_restante = document.frmVender.txtstock.value;
		idproducto = document.frmVender.id_producto.value;
		producto = document.frmVender.txtdetalle.value;
		unitario = document.frmVender.txtprecio.value;
		importe = Math.round(document.frmVender.txtprecio.value * cant * 100)/100;
		indice = document.frmVender.indice.value = parseInt(document.frmVender.indice.value) + parseInt (1);
		document.frmVender.totalindices.value = parseInt(document.frmVender.totalindices.value) + 1;

						html = '<table width="645" border="0" cellpadding="0" cellspacing="0" bordercolor="#FCFCFC" bgcolor="#FFFFFF" id="'+indice+'">';
                        html +='  <tr>';
						html +=' <input type="hidden" name="cantidad'+indice+'" value="'+stock_restante+'"/>';
						html +=' <input type="hidden" name="idproducto'+indice+'" value="'+idproducto+'"/>';
						html +='   <td width="35" align="left" bgcolor="#FFFFFF"><div align="center"><strong>'+cant+'</strong></div></td>';
                        html +='    <td width="435" align="left" bgcolor="#FFFFFF"><div align="center"><strong>'+producto+'</strong></div></td>';
                        html +='    <td width="65" align="left" bgcolor="#FFFFFF"><div align="center"><strong>'+unitario+'</strong></div></td>';
                        html +='    <td width="65" align="left" bgcolor="#FFFFFF"><div align="center"><strong>'+importe+'</strong></div></td>';
                        html +='    <td width="45" align="left" bgcolor="#FFFFFF"><div align="center">';
                        html +='      <label><img src="../imagenes/cruz.png" width="16" height="16" onclick="eliminar_producto('+indice+','+importe+')" style="cursor:hand"/></label>';
                        html +='    </div></td>';
                        html +='  </tr>';
                        html +='</table>';
							
		dest.innerHTML += html;
		document.frmVender.totalaux.value = Math.round ((parseFloat (document.frmVender.totalaux.value) + parseFloat (importe))*100)/100;
		aplicar_importe();
		document.frmVender.txtdetalle.value = '';
		document.frmVender.txtprecio.value = 0;
		document.frmVender.txtstock.value = 0;
		document.frmVender.txtcant.value = 1;
		document.frmVender.txtcant.focus;
	}
	else
		window.alert('Se requiere algun producto seleccionado');
}

function validar (valor)
{
	if (isNaN(parseInt(valor.value)))	
	 {
		document.frmVender.txtdetalle.value='';
		document.frmVender.txtprecio.value=parseInt(0);
		document.frmVender.txtcant.value=parseInt(1);
		document.frmVender.txtstock.value=parseInt(0);
		window.alert ("Se requiere un numero");
	 }
}

function numero(objeto)
{
	if (isNaN(objeto.value))
	{
		window.alert("Se requiere un numero");	
		objeto.value = 1;
	}
}


function aplicar_importe()
{
		document.frmVender.txttotal.value = Math.round(((parseFloat(document.frmVender.totalaux.value) + (Math.round(parseFloat (document.frmVender.txtimpmanual.value) *100)/100)) - ((parseFloat(document.frmVender.totalaux.value) + (Math.round(parseFloat (document.frmVender.txtimpmanual.value) *100)/100))	* 																																																																				(Math.round(parseFloat (document.frmVender.txtdescuento.value) *100)/100)/100))*100)/100;
	
}

function aplicar_descuento()
{
		document.frmVender.dtoenpesos.value = Math.round(((parseFloat(document.frmVender.totalaux.value) + parseFloat(document.frmVender.txtimpmanual.value)) * (parseFloat(document.frmVender.txtdescuento.value) / parseFloat(100)))*100)/100;


		document.frmVender.txttotal.value = Math.round(((parseFloat(document.frmVender.totalaux.value) + (Math.round(parseFloat (document.frmVender.txtimpmanual.value) *100)/100)) - ((parseFloat(document.frmVender.totalaux.value) + (Math.round(parseFloat (document.frmVender.txtimpmanual.value) *100)/100))	* 																																																																				(Math.round(parseFloat (document.frmVender.txtdescuento.value) *100)/100)/100))*100)/100;

}

function recalcular_total(importe)
{
	
	cantservicios = document.formAltaReserva.cantservicios.value;
	monto = 0;
	
	for (i = 0; i < cantservicios; i++)
	{
		if (document.formAltaReserva.servicio[i].checked == true)
		{
	
			monto += parseFloat(document.formAltaReserva.servicio[i].value);	
		}
	
	}
	
	document.formAltaReserva.montoservicios.value = monto;
}



function iniciar_valores()
{
	document.frmVender.totalindices.value = parseInt(0);
	document.frmVender.txtprecio.value=parseFloat(0);
	document.frmVender.dtoenpesos.value=parseFloat(0);
	document.frmVender.txtstock.value=parseFloat(0);
	document.frmVender.txttotal.value=parseFloat(0);
	document.frmVender.totalaux.value=parseFloat(0);
	document.frmVender.indice.value = 0;
	document.frmVender.txtcant.focus;
}

function eliminar_producto(indice,importe)
{
//window.alert(indice);
	if (confirm("¿Realmente desea quitar este producto?"))
	{
		recalcular_total(importe);
		//document.frmVender.totalaux.value = document.frmVender.totalaux.value - 
		var elemento = document.getElementById(indice);
		var padre = elemento.parentNode;
		padre.removeChild(elemento);
	}
	
}

function reemplazar_coma(valor)
{
	var t = valor.value;
	t = t.replace(",",".");	
	valor.value = t;
}

function entera (valor)
{
//window.alert(valor.value);
	valor.value = Math.round(parseInt(valor.value));	
}

function validar_numero(valor)
{
	if ((isNaN(valor.value)) || (valor.value <= 0))
	{	window.alert("El valor ingresado no es un numero.");	
		valor.value = '';
	}
}

function validar_numero_positivo(valor)
{
	if ((isNaN(valor.value)) || (parseFloat(valor.value) <= 0))
	{	window.alert("El valor ingresado no es un numero o es nulo.");	
		valor.value = 1;
	}
}

function validar_numero_nonegativo(valor)
{
	if ((isNaN(valor.value)) || (parseFloat(valor.value) < 0))
	{	window.alert("El valor ingresado no es un numero o es nulo.");	
		valor.value = 1;
	}
}


function logout()
{
	if (confirm("¿Realmente desea cerrar la sesion?"))	
		window.location = "..\logout.php";
}

function dias(fecha1,fecha2)
{
m_fecha1 = fecha1.split('/');
dia_fecha1 = m_fecha1[0];
mes_fecha1 = m_fecha1[1];
year_fecha1 = m_fecha1[2];

mes_fecha1 = mes_fecha1 - 1; // para js los meses del año son de 0 - 11, de ahi ese calculo.
dia_fecha1 = dia_fecha1 - 1;
var fecha1_js = new Date(year_fecha1, mes_fecha1, dia_fecha1)

m_fecha2 = fecha2.split('/');
dia_fecha2 = m_fecha2[0];
mes_fecha2 = m_fecha2[1];
year_fecha2 = m_fecha2[2];

mes_fecha2 = mes_fecha2 - 1; // para js los meses del año son de 0 - 11, de ahi ese calculo.

var fecha2_js = new Date(year_fecha2, mes_fecha2, dia_fecha2)

var un_dia=1000*60*60*24

document.formAltaReserva.cantnoches.value = Math.ceil((fecha1_js.getTime()- fecha2_js.getTime())/(un_dia)) * -1;
document.formAltaReserva.cantnoches.value = document.formAltaReserva.cantnoches.value -1; // porque el check out es a la mañana y no cubre la noche esa
}

function calcular_total()
{
	formAltaReserva.montototal.value = 0;
	document.formAltaReserva.tiporegimen.value = document.formAltaReserva.ddlregimen.options[document.formAltaReserva.ddlregimen.selectedIndex].text;	
	document.formAltaReserva.tipotarifa.value = document.formAltaReserva.tarifa.options[document.formAltaReserva.tarifa.selectedIndex].text;

	var tarifa = document.formAltaReserva.tarifa.options[formAltaReserva.tarifa.selectedIndex].value;
	var regimen = document.formAltaReserva.ddlregimen.options[formAltaReserva.ddlregimen.selectedIndex].value;
	var plazas = document.formAltaReserva.cantplazas.value;

	if (document.formAltaReserva.ddlregimen.options[formAltaReserva.ddlregimen.selectedIndex].text.substr(0,10) == "RESTAURANT")
	{
		if ((document.formAltaReserva.cantrest.value != '') && (document.formAltaReserva.cantrest.value > 0))
		{
			regimen = regimen * document.formAltaReserva.cantrest.value;
			var x = parseFloat(tarifa);		
			var total = parseFloat(plazas * x) + parseFloat(regimen);
		}
		else
			{
				window.alert ("La cantidad de comidas debe ser un numero positivo");	
				document.formAltaReserva.cantrest.value = 1;
				regimen = regimen * document.formAltaReserva.cantrest.value;
				var x = parseFloat(tarifa);		
				var total = parseFloat(plazas * x) + parseFloat(regimen);
			}
	}
	else
	{
		var x = parseFloat(tarifa) + parseFloat(regimen);
		var total = parseFloat(plazas * x);
	}

	formAltaReserva.montototal.value = total - parseFloat (document.formAltaReserva.descuento.value);
	
}

function calcular_plazas()
{
	formAltaReserva.cantplazas.value = formAltaReserva.cantnoches.value * formAltaReserva.cantpax.value;
}

function rest()
{
	
	document.formAltaReserva.tiporegimen.value = document.formAltaReserva.ddlregimen.options[document.formAltaReserva.ddlregimen.selectedIndex].text;	

//	if (document.formAltaReserva.ddlregimen.options[document.formAltaReserva.ddlregimen.selectedIndex].text == 'RESTAURANT')	
	if (document.formAltaReserva.ddlregimen.options[document.formAltaReserva.ddlregimen.selectedIndex].text.substr(0,10) == 'RESTAURANT')		
	{
		document.formAltaReserva.cantrest.disabled = false;		
		document.formAltaReserva.cantrest.value = 1;
	}
	else
	{		document.formAltaReserva.cantrest.disabled = true;		
			document.formAltaReserva.cantrest.value = '';
	}

}

function reserva_vacia(objform)
{
	if (objform.montototal.value > 0)	
		return true;
	else
		{
			window.alert("No se ha generado ningun consumo");	
			return false;
		}
	
	
}


function saldado() // Suma y actualiza el disponible visible
{

	function redondear(cantidad, decimales) {
		var cantidad = parseFloat(cantidad);
		var decimales = parseFloat(decimales);
		decimales = (!decimales ? 2 : decimales);
		return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
	}  // funcion para redondear los flotantes del disponible de la agencia

	var cantelements = document.formListarReserva.elements.length; // Cantidad de componentes instanciados en el formulario.
	var pagos = 0;

	for (i = 0; i < cantelements; i++)
	{
		if ((document.formListarReserva.elements[i].type == 'checkbox') && (document.formListarReserva.elements[i].checked == true) && (document.formListarReserva.elements[i].name != 'todos'))
			pagos = Number(pagos) + Number(document.formListarReserva.elements[i].value);
	}

	document.formListarReserva.disponible.value = Number(document.formListarReserva.montodisponible.value) - Number(pagos);
	document.formListarReserva.disponible.value = redondear (document.formListarReserva.disponible.value,2);
	document.formListarReserva.saldo_agencia.value = document.formListarReserva.disponible.value; 
}

function seleccionar_todos()
{
	var cantelements = document.formListarReserva.elements.length; // Cantidad de componentes instanciados en el formulario.

	for (i = 0; i < cantelements; i++)
	{
		if (document.formListarReserva.elements[i].type == 'checkbox')
			document.formListarReserva.elements[i].checked = document.formListarReserva.todos.checked;
	}
	
}

function validar_saldo(obj)
{
	if (document.formListarReserva.disponible.value < 0) // valida que no se hayan seleccionado mas reservas de lo que el disponible rinde
	{
		window.alert ('Se ha superado el monto disponible. Destilde alguna reserva.');
		if (obj.type == 'checkbox')
			obj.checked = false;
			saldado();
		return false;
	}
	else // valida que no se envie el form sin ninguna reserva seleccionada
	{   if (obj.name == 'formListarReserva')	
		{
			if (Number(document.formListarReserva.disponible.value) < Number(document.formListarReserva.montodisponible.value))
				return true;
			else
			{	window.alert('No ha seleccionado ninguna reserva');
				return false;
			}
		}
	}
}


function validar_saldo_parcial(obj_form)
{
	var cantelements = document.formListarReserva.elements.length; // Cantidad de componentes instanciados en el formulario.

	for (i = 0; i < cantelements; i++)
	{
		if ((document.formListarReserva.elements[i].type == 'radio') && (document.formListarReserva.elements[i].checked == true))
			indice = document.formListarReserva.elements[i].value;
	}

	indecito = 'saldo_reserva'+indice;
	montoreserva = document.getElementById(indecito).value;
	
	if ((Number(document.formListarReserva.montoasaldar.value) <= Number(montoreserva)) && (Number(document.formListarReserva.montoasaldar.value) <= Number(document.formListarReserva.disponible.value)) && (document.formListarReserva.montoasaldar.value != ''))	
		return true;
	else
		{
			window.alert("El monto a saldar no es correcto");
			document.formListarReserva.montoasaldar.value = 1;
			return false;	
		}

}