/**
* functions.js
*
* Contiene funciones de ajax con jquery para ejecutar procesos invisibles al usuario
*
* @author     Emilio De Agustin Cazorla <emilio.agustin@hotmail.com>
* @version    1.0
* @package    js
*/

var radio_id = '';
var radio_status = false;
var paso1 = false;
var paso2 = false;
var paso_final = false;
var protocolo = "http://";
/**
 * Metodo que elimina un tipo de oferta y las ofertas que contiene
 *
 * @param int id			Identificador de tipo de oferta
 */   
 
 
       
function borrar_tipo_oferta(id) {
	if (confirm("?Esta segur@ de que desea borrar el tipo de oferta y sus ofertas?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/borrar_tipo_oferta.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina una temporada
 *
 * @param int id			Identificador de temporada
 */   
function borrar_temporada(id) {
	if (confirm("?Esta segur@ de que desea borrar la temporada?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/borrar_temporada.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina un tipo de habitaci?n
 *
 * @param int id			Identificador de tipo de habitaci?n
 */   
function borrar_tipo_hab(id) {
	if (confirm("?Esta segur@ de que desea borrar el tipo de habitaci?n?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/borrar_tipo_hab.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina una habitaci?n
 *
 * @param int id			Identificador de habitaci?n
 */   
function borrar_habitacion(id) {
	if (confirm("?Esta segur@ de que desea borrar la habitaci?n?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/borrar_habitacion.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina una subcategoria
 *
 * @param int id			Identificador de subcategoria
 */  
function borrar_subcategoria(id) {
	if (confirm("?Esta segur@ de que desea borrar la subcategor?a y sus correspondientes fichas?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/siel/administrador/backend/borrar_subcat.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina un usuario
 *
 * @param int id			Identificador de usuario
 */  
function borrar_usuario(id) {
	if (confirm("?Esta segur@ de que desea borrar el usuario?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/siel/administrador/backend/borrar_usuario.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina un cliente
 *
 * @param int id			Identificador de cliente
 */  
function borrar_cliente(id) {
	if (confirm("?Esta segur@ de que desea borrar el cliente?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/siel/administrador/backend/borrar_cliente.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina un producto
 *
 * @param int id			Identificador de producto
 */  
function borrar_producto(id) {
	if (confirm("?Esta segur@ de que desea borrar el producto?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/siel/administrador/backend/borrar_producto.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina una oferta
 *
 * @param int id			Identificador de oferta
 */  
function borrar_oferta(id) {
	if (confirm("?Esta segur@ de que desea borrar la oferta?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/borrar_oferta.php";
		$.post(url, {
						'id': id
					}, function(html) {
						var num_records = $('tr[@class=records]');
						if (num_records.length > 1) {
							document.location.reload();
						} else {
							document.location = redirect_to_page(document.location.toString());
						}
					});	
		return;
	}
}

/**
 * Metodo que elimina una estancia m?nima
 *
 * @param int id			Identificador de estancia m?nima
 */  
function borrar_estancia_min(id) {
	if (confirm("?Esta segur@ de que desea borrar la estancia m?nima?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/borrar_estancia.php";
		$.post(url, {
						'id': id
					}, function(html) {
						document.location.reload();
					});	
		return;
	}
}

/**
 * Metodo que cambia las subcategorias al cambiar de categoria
 *
 * @param int id			Identificador de categoria
 * @param string event_hndl Manejador de eventos para el nuevo select
 */  
function change_subcat(select_cat) {
	var id = select_cat[select_cat.selectedIndex].value;
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/siel/administrador/backend/get_subcategorias.php";
	$.post(url, {
					'id': id
				}, function(html) {
					var options_html = html.split('<option');
					var select_subcats = $('#subcategoria')[0];
					var select_len = select_subcats.options.length;
					for (var i=0;i<select_len;i++) {
						select_subcats.options.length = 0;
					}
					if (options_html.length>1) {
						for(var i=1;i<options_html.length;i++) {
							var name = options_html[i].split('name')[1];
							name = name.split('=')[1];
							name = name.split('"')[1];
							var value = options_html[i].split('value')[1];
							value = value.split('=')[1];
							value = value.split('"')[1];
							select_subcats.options[i-1] = new Option(name, value);
						}
					} else {
						select_subcats.options[0] = new Option('No existe ninguna subcategor?a', '0');	
					}
					if ($('#producto')[0]) {
						change_products(select_subcats);
					}
				});	
	return;
}

/**
 * Metodo que cambia las subcategorias al cambiar de categoria
 *
 * @param int id			Identificador de categoria
 */  
function change_products(select_subcat) {
	var id = select_subcat.options[select_subcat.selectedIndex].value;
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/siel/administrador/backend/get_productos.php";
	$.post(url, {
					'id': id
				}, function(html) {
					var options_html = html.split('<option');
					var select_products = $('#producto')[0];
					var select_len = select_products.options.length;
					select_products.options.length = 0;
					if (options_html.length>1) {
						for(var i=1;i<options_html.length;i++) {
							var name = options_html[i].split('name')[1];
							name = name.split('=')[1];
							name = name.split('"')[1];
							var value = options_html[i].split('value')[1];
							value = value.split('=')[1];
							value = value.split('"')[1];
							select_products.options[i-1] = new Option(name, value);
						}
					} else {
						select_products.options.length = 0;	
					}
				});	
	return;
}

/**
 * Metodo que redirecciona a la pagina correspondiente despues 
 * de haber borrado un registro de una pagina de resultados
 *
 * @param string location			Url de la pagina
 */ 
function redirect_to_page(location) {
	var redir_page = '';
	var abs_url = location;
	var sub_url = abs_url.split('?');
	var var_page = sub_url[1];
	var url = sub_url[0];
	var params = var_page.split('&');
	if (params.length>1) {
		var page = parseInt(var_page.split('=')[1]);
		page = (page-1);
		var web_params = '';
		if (page>0) {
			if (params.length>1) {
				for (var i=0;i<params.length;i++) {
					web_params = '&' + params[i]; 		
				}
			}
			redir_page = url + '?pagina=' + page + web_params;
		} else {
			if (params.length>1) {
				var count = 0;
				for (var i=0;i<params.length;i++) {
					if (count==0) {
						web_params = '?' + params[i]; 		
					} else {
						web_params = '&' + params[i]; 		
					}
				}
			}
			redir_page = url + web_params;	
		}
	} else {
		var nombre_param = var_page.split('=');
		if (nombre_param[0]=='pagina') {
			var page = parseInt(var_page.split('=')[1]);
			page = (page-1);	
			redir_page = url + '?' + nombre_param[0] + '=' + page;
		} else {
			redir_page = url + '?' + nombre_param[0] + '=' + nombre_param[1];
		}
	}
	var url_fin = redir_page.substr(redir_page.length-1, redir_page.length);
	if (url_fin=='#') {
		redir_page = redir_page.substr(0, redir_page.length-1);		
	}
	return redir_page;
}

/**
 * Metodo que agrega los productos relacionados a un producto 
 *
 * @param string id_padre			Identificador del prodcuto padre
 * @param object formulario			Formulario donde se encuentra las opciones
 */
function insert_relations(id_padre, formulario) {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/siel/administrador/backend/add_relacion.php";
	var url2 = protocolo + host + ":" + port + "/siel/administrador/backend/borrar_relaciones.php";
	var products_sel = formulario.productos_sel;
	$.post(url2, {
					'id_padre': id_padre
				}, function(html) {
					for (var i=0;i<products_sel.options.length;i++) {
						$.post(url, {
										'id_padre': id_padre,
										'id_hijo': products_sel.options[i].value
									}, function(html) {
										return;
								});	
					}
			});
	alert('Se han guardado los cambios satisfactoriamente');
	return;		
}

/**
 * Metodo que agrega los productos asociados a un cliente
 *
 * @param string id_cliente			Identificador del cliente
 * @param object formulario			Formulario donde se encuentra las opciones
 */
function insert_asociados(id, formulario) {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/siel/administrador/backend/add_asociado.php";
	var url2 = protocolo + host + ":" + port + "/siel/administrador/backend/borrar_asociados.php";
	var products_sel = formulario.productos_sel;
	$.post(url2, {
					'id': id
				}, function(html) {
					for (var i=0;i<products_sel.options.length;i++) {
						$.post(url, {
										'id': id,
										'id_producto': products_sel.options[i].value
									}, function(html) {
										return;
								});	
					}
			});
	alert('Se han guardado los cambios satisfactoriamente');
	return;		
}

/**
 * Metodo que comprueba si existe una opcion en una lista
 *
 * @param string valor			Valor a comprobar
 * @param object lis_name_out	Lista donde se comprueba si existe el valor
 * @return boolean
 */
function existeOpt(valor, lis_name_out) {
	for (var i=0;i<lis_name_out.options.length;i++) {
		if (lis_name_out.options[i].value==valor) {
			return true;
		}
	}
	return false;
}

/**
 * Metodo que a?ade una opcion a una lista
 *
 * @param object lis_name	Lista donde se encuentra la opcion
 * @param object out_lis	Lista donde se inserta la opcion
 */
function addOpt(lis_name, out_lis) {
	if (lis_name.selectedIndex!=-1) {
		if (!existeOpt(lis_name.options[lis_name.selectedIndex].value, out_lis)) {
			var name = '';
			if (lis_name.options[lis_name.selectedIndex].name) {
				name = lis_name.options[lis_name.selectedIndex].name;
			} else {
				name = lis_name.innerHTML.split('>');	
				name = name[1].split('</');
				name = name[0];
			}
			out_lis.options[out_lis.options.length] = new Option(name, lis_name.options[lis_name.selectedIndex].value);
		}
	}	
}

/**
 * Metodo que borra una opcion de una lista
 *
 * @param object lis_name	Lista donde se encuentra la opcion
 */
function delOpt(lis_name) {
	if (lis_name.selectedIndex!=-1) {
		lis_name.options[lis_name.selectedIndex]=null;
	}	
}

function existeAnterior(formulario, nombre_campo) {
	for (var i=0;i<formulario.elements.length;i++) {
		if (formulario.elements[i].name.search(nombre_campo+'_ant')!=-1) {
			return true;
		}
	}
	return false;
}

/**
 * Metodo que comprueba si se checkea un paramaetro en funci?n del ?ndice y 
 * de un array de indices que no se checkean
 *
 * @param int indice	Indice a checkear
 * @param Array paramsNumNoCheck  Indices de los parametros que no se checkean
 * @return boolean
 */
function checkearParam(indice, paramsNumNoCheck) {
	for (var i=0;i<paramsNumNoCheck.length;i++) {
		if (paramsNumNoCheck[i]==indice) {
			return false;
		}	
	}	
	return true;
}

/**
 * Metodo que comprueba si se han rellenado correctamente los campos de un formulario
 *
 * @param object formulario	Formulario
 * @param string numParams	N?mero de par?metros
 * @param Array paramsNumNoCheck  Indices de los parametros que no se checkean
 */
function checkParams(formulario, numParams, paramsNumNoCheck, tinyMCECheck) {
var params = Array();
var esCorrecto = true;
var existePassAnt = false;
var existeUnaPass = false;
var pass1 = '';
var msg_error = '';
var pre_msg_error = 'Rellene el/los campo/s ';
var post_msg_error = 'correctamente';
var campos_error = '';
	for (var i=0;i<numParams;i++) {
		params[i] = formulario.elements[i];
		if (params[i].name.search('password_ant')!=-1) {
			existePassAnt = true;
		}
	}
	if (formulario.categoria) {
		var categoria = parseInt(formulario.categoria.options[formulario.categoria.selectedIndex].value);
		if (categoria<=0) {
			campos_error += 'categoria ';
			esCorrecto = false;
		}
	}
	if (formulario.subcategoria) {
		var subcategoria = parseInt(formulario.subcategoria.options[formulario.subcategoria.selectedIndex].value);
		if (subcategoria<=0) {
			campos_error += 'subcategoria ';
			esCorrecto = false;
		}
	}
	if (formulario.tipos_temporadas) {
		var tipo_temporada = parseInt(formulario.tipos_temporadas.options[formulario.tipos_temporadas.selectedIndex].value);
		if (tipo_temporada<=0) {
			campos_error += 'tipo de temporada ';
			esCorrecto = false;
		}
	}
	if (formulario.tipos_hab) {
		var tipo_hab = parseInt(formulario.tipos_hab.options[formulario.tipos_hab.selectedIndex].value);
		if (tipo_hab<=0) {
			campos_error += 'tipo de habitaci?n ';
			esCorrecto = false;
		}
	}
	for (var i=0;i<numParams;i++) {
		/*alert('name '+params[i].name);
		alert('value '+params[i].value);*/
		if (checkearParam(i, paramsNumNoCheck)) {
			if (params[i].name.search('password')==-1) {
				if (params[i].name.search('mce')==-1) {
					if (params[i].name.search('especificaciones')==-1) {
						if (params[i].name.search('caracteristicas')==-1) {
							if (params[i].name.search('tallaje')==-1) {
								if (params[i].value=="") {
									if (!existeAnterior(formulario, params[i].name)) {
										campos_error += params[i].name + ' ';
										esCorrecto = false;
									}
								} 
							}
						}
					}
				}
			} else {
				if (!existePassAnt) {
					if (params[i].value=="") {
						campos_error += params[i].name + ' ';
						esCorrecto = false;	
					} else {
						pass1 = params[i].value;	
					}
				} else {
					if ((params[i].value!="") && (params[i].value!="true")) {
						if (!existeUnaPass) {
							existeUnaPass = true;	
							pass1 = params[i].value;
						} else {
							existeUnaPass = false;
							if (pass1!=params[i].value) {
								esCorrecto = false;
								msg_error = 'Las passwords no coinciden';	
							}
						}
					}		
				}
			}
		}
	}
	if (tinyMCECheck) {
		alert(tinyMCE.idCounter);
		e
		if (tinyMCE.idCounter>0) {
			if (tinyMCE.getContent('mce_editor_0')=="") {
				campos_error += 'tallaje ';
				esCorrecto = false;
			}
			if (tinyMCE.idCounter>1) {
				if (tinyMCE.getContent('mce_editor_1')=="") {
					campos_error += 'caracteristicas ';
					esCorrecto = false;
				}
			}
			if (tinyMCE.idCounter>2) {
				if (tinyMCE.getContent('mce_editor_2')=="") {
					campos_error += 'especificaciones ';
					esCorrecto = false;
				}
			}
		}
	}
	if ((!esCorrecto) || (existeUnaPass)) {
		if (msg_error=='') {
			msg_error = pre_msg_error + campos_error + post_msg_error;
		}
		alert(msg_error);
		return false;
	} else {
		formulario.submit();
		return true;
	}
}

function insertarOferta() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/add_oferta.php";
	
	var id_tipo_oferta = $('#id_tipo_oferta').val();
	var titulo_oferta = $('#titulo_oferta').val();
    var descripcion_oferta = tinyMCE.activeEditor.getContent();
    var fecha_ini_oferta = $('#fecha_ini_oferta').val();
    var fecha_fin_oferta = $('#fecha_fin_oferta').val();
    var min_noches_oferta = $('#min_noches_oferta').val();
    var precio_doble_oferta = $('#precio_doble_oferta').val();
    var precio_doble_sup_oferta = $('#precio_doble_sup_oferta').val();
    var precio_suite_oferta = $('#precio_suite_oferta').val();
	var dias_oferta = "";
	var count = 0;
	for (var i=1;i<8;i++) {
		if ($('#dias_oferta_' + i)[0].checked) {
			if (count==0) {
				dias_oferta = dias_oferta + $('#dias_oferta_' + i).val();
			} else {
				dias_oferta = dias_oferta + "-" + $('#dias_oferta_' + i).val();		
			}
			count++;
		}
	}
	var tipos_hab_oferta = "";
	var count = 0;
	for (var i=1;i<4;i++) {
		if ($('#tipos_hab_oferta_' + i)[0].checked) {
			if (count==0) {
				tipos_hab_oferta = tipos_hab_oferta + $('#tipos_hab_oferta_' + i).val();
			} else {
				tipos_hab_oferta = tipos_hab_oferta + "-" + $('#tipos_hab_oferta_' + i).val();
			}
			count++;
		}
	}

    if (titulo_oferta == "") {
        alert("Introduzca el t?tulo de la oferta");
        return;
    }
	if (descripcion_oferta == "") {
        alert("Introduzca la descripci?n de la oferta");
        return;
    }
    if (fecha_ini_oferta == "") {
        alert("Introduzca la fecha de inicio de la oferta");
        return;
    }
    if (fecha_fin_oferta == "") {
        alert("Introduzca la fecha de fin de la oferta");
        return;
    }
    if ((min_noches_oferta == "") || (min_noches_oferta == "0")) {
        alert("Introduzca el m?nimo de noches de la oferta");
        return;
    }
    if (dias_oferta == "") {
        alert("Debe seleccionar alg?n d?a de la semana para aplicar la oferta");
        return;
    }
    if (tipos_hab_oferta == "") {
        alert("Seleccione un tipo de habitaci?n para aplicar la oferta");
        return;
    }
    
    $.post(url, {
        'id_tipo_oferta': id_tipo_oferta,
        'titulo_oferta': titulo_oferta,
        'descripcion_oferta': descripcion_oferta,
        'fecha_ini_oferta': fecha_ini_oferta,
        'fecha_fin_oferta': fecha_fin_oferta,
        'min_noches_oferta': min_noches_oferta,
		'precio_doble_oferta': precio_doble_oferta,
		'precio_doble_sup_oferta': precio_doble_sup_oferta,
		'precio_suite_oferta': precio_suite_oferta,
        'dias_oferta': dias_oferta,
        'tipos_hab_oferta': tipos_hab_oferta
    }, function(html) {
        alert(html);
        document.location = 'ofertas.php?id=' + id_tipo_oferta;
    });
    return;	
}

function modificarOferta() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/mod_oferta.php";
	
	var id_oferta = $('#id_oferta').val();
	var id_tipo_oferta = $('#id_tipo_oferta').val();
	var titulo_oferta = $('#titulo_oferta').val();
    var descripcion_oferta = tinyMCE.activeEditor.getContent();
    var fecha_ini_oferta = $('#fecha_ini_oferta').val();
    var fecha_fin_oferta = $('#fecha_fin_oferta').val();
    var min_noches_oferta = $('#min_noches_oferta').val();
    var precio_doble_oferta = $('#precio_doble_oferta').val();
    var precio_doble_sup_oferta = $('#precio_doble_sup_oferta').val();
    var precio_suite_oferta = $('#precio_suite_oferta').val();
	var dias_oferta = "";
	var count = 0;
	for (var i=1;i<8;i++) {
		if ($('#dias_oferta_' + i)[0].checked) {
			if (count==0) {
				dias_oferta = dias_oferta + $('#dias_oferta_' + i).val();
			} else {
				dias_oferta = dias_oferta + "-" + $('#dias_oferta_' + i).val();		
			}
			count++;
		}
	}
	var tipos_hab_oferta = "";
	var count = 0;
	for (var i=1;i<4;i++) {
		if ($('#tipos_hab_oferta_' + i)[0].checked) {
			if (count==0) {
				tipos_hab_oferta = tipos_hab_oferta + $('#tipos_hab_oferta_' + i).val();
			} else {
				tipos_hab_oferta = tipos_hab_oferta + "-" + $('#tipos_hab_oferta_' + i).val();
			}
			count++;
		}
	}

    if (titulo_oferta == "") {
        alert("Introduzca el t?tulo de la oferta");
        return;
    }
	if (descripcion_oferta == "") {
        alert("Introduzca la descripci?n de la oferta");
        return;
    }
    if (fecha_ini_oferta == "") {
        alert("Introduzca la fecha de inicio de la oferta");
        return;
    }
    if (fecha_fin_oferta == "") {
        alert("Introduzca la fecha de fin de la oferta");
        return;
    }
    if ((min_noches_oferta == "") || (min_noches_oferta == "0")) {
        alert("Introduzca el m?nimo de noches de la oferta");
        return;
    }
    if (dias_oferta == "") {
        alert("Debe seleccionar alg?n d?a de la semana para aplicar la oferta");
        return;
    }
    if (tipos_hab_oferta == "") {
        alert("Seleccione un tipo de habitaci?n para aplicar la oferta");
        return;
    }
    
    $.post(url, {
		'id_oferta': id_oferta,   
        'id_tipo_oferta': id_tipo_oferta,
        'titulo_oferta': titulo_oferta,
        'descripcion_oferta': descripcion_oferta,
        'fecha_ini_oferta': fecha_ini_oferta,
        'fecha_fin_oferta': fecha_fin_oferta,
        'min_noches_oferta': min_noches_oferta,
		'precio_doble_oferta': precio_doble_oferta,
		'precio_doble_sup_oferta': precio_doble_sup_oferta,
		'precio_suite_oferta': precio_suite_oferta,
        'dias_oferta': dias_oferta,
        'tipos_hab_oferta': tipos_hab_oferta
    }, function(html) {
        alert(html);
        document.location = 'ofertas.php?id=' + id_tipo_oferta;
    });
    return;	
}

function guardarExtra() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/mod_extra.php";
	
	var id_extra = $('#id_extra').val();
	var precio_extra = $('#precio_extra').val();
	var descripcion_extra = tinyMCE.activeEditor.getContent();
	
	if (precio_extra == "") {
        alert("Introduzca el precio de la cama extra");
        return;
    }

	$.post(url, {
		'id_extra': id_extra,   
        'precio_extra': precio_extra,
        'descripcion_extra': descripcion_extra
    }, function(html) {
        alert(html);
    });
    return;
}

function guardarCorreo() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/mod_correo.php";
	
	var id_correo = $('#id_correo').val();
	var direccion_correo = $('#direccion_correo').val();
	var nombre_correo = $('#nombre_correo').val();
	
	if (direccion_correo == "") {
        alert("Introduzca la direcci?n de correo");
        return;
    }
	if (nombre_correo == "") {
        alert("Introduzca el nombre del remitente del correo");
        return;
    }

	$.post(url, {
		'id_correo': id_correo,   
        'direccion_correo': direccion_correo,
        'nombre_correo': nombre_correo
    }, function(html) {
        alert(html);
    });
    return;
}

function addEstancia() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/add_estancia_min.php";
	
	var habitaciones_sel = $('#habitacs_fin_list')[0];
	var fecha_inicio_estancia = $('#fecha_inicio_estancia').val();
	var fecha_fin_estancia = $('#fecha_fin_estancia').val();
	
	if (habitaciones_sel.length <= 0) {
        alert("Debe seleccionar al menos una habitaci?n para realizar la estancia m?nima");
        return;
    }
	if (fecha_inicio_estancia == "") {
        alert("Introduzca la fecha inicial de la estancia m?nima");
        return;
    }
	if (fecha_fin_estancia == "") {
        alert("Introduzca la fecha final de la estancia m?nima");
        return;
    }
	
	var habs = '';
	for(var i=0;i<habitaciones_sel.length;i++) {
		habs = habs + habitaciones_sel[i].value + '-';	
	}
	
	$.post(url, {
		'habitaciones_sel': habs,   
        'fecha_inicio_estancia': fecha_inicio_estancia,
        'fecha_fin_estancia': fecha_fin_estancia
    }, function(html) {
        alert(html);
		document.location = 'estancia_min.php';
    });
    return;	
}

function modEstancia() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/mod_estancia_min.php";
	
	var id_estancia = $('#id_estancia').val();
	var habitaciones_sel = $('#habitacs_fin_list')[0];
	var fecha_inicio_estancia = $('#fecha_inicio_estancia').val();
	var fecha_fin_estancia = $('#fecha_fin_estancia').val();
	
	if (habitaciones_sel.length <= 0) {
        alert("Debe seleccionar al menos una habitaci?n para realizar la estancia m?nima");
        return;
    }
	if (fecha_inicio_estancia == "") {
        alert("Introduzca la fecha inicial de la estancia m?nima");
        return;
    }
	if (fecha_fin_estancia == "") {
        alert("Introduzca la fecha final de la estancia m?nima");
        return;
    }
	
	var habs = '';
	for(var i=0;i<habitaciones_sel.length;i++) {
		habs = habs + habitaciones_sel[i].value + '-';	
	}
	
	$.post(url, {
		'id_estancia': id_estancia,
		'habitaciones_sel': habs,   
        'fecha_inicio_estancia': fecha_inicio_estancia,
        'fecha_fin_estancia': fecha_fin_estancia
    }, function(html) {
        alert(html);
		document.location = 'estancia_min.php';
    });
    return;	
}

function addReservaMan() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/add_reserva_man.php";
	
	var habitaciones_sel = $('#habitacs_fin_list')[0];
	var fecha_inicio_estancia = $('#fecha_inicio_estancia').val();
	var fecha_fin_estancia = $('#fecha_fin_estancia').val();
	
	if (habitaciones_sel.length <= 0) {
        alert("Debe seleccionar al menos una habitaci?n para realizar la estancia m?nima");
        return;
    }
	if (fecha_inicio_estancia == "") {
        alert("Introduzca la fecha inicial de la estancia m?nima");
        return;
    }
	if (fecha_fin_estancia == "") {
        alert("Introduzca la fecha final de la estancia m?nima");
        return;
    }
	
	var habs = '';
	for(var i=0;i<habitaciones_sel.length;i++) {
		habs = habs + habitaciones_sel[i].value + '-';	
	}
	cargando();
	$.post(url, {
		'habitaciones_sel': habs,   
        'fecha_inicio_estancia': fecha_inicio_estancia,
        'fecha_fin_estancia': fecha_fin_estancia
    }, function(html) {
		cerrar_cargando();
        alert(html);
		document.location = 'estancia_min.php';
    });
    return;	
}

function getNumFormat(numero) {
	var number = new Number(numero);
	return new Number(number.toFixed(2));
}

function calcPrecRes() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/calc_prec.php";
	
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);	
	var num_adultos = $('#num_adultos_reserva').val();
	
	if (habitacion <= 0) {
        return;
    }
	if (fecha_inicio_reserva == "") {
        return;
    }
	if (fecha_fin_reserva == "") {
        return;
    }
	$.post(url, {
		'habitacion': habitacion,   
        'fecha_inicio_reserva': fecha_inicio_reserva,
        'fecha_fin_reserva': fecha_fin_reserva,
		'cama_extra_reserva': cama_extra_reserva,
		'num_adultos': num_adultos
    }, function(html) {
		var resultado = getNumFormat(html);
		$('#base_precio_reserva')[0].innerText = resultado;
		var iva = getNumFormat(resultado*0.08);
		$('#impuestos_precio_reserva')[0].innerText = iva;
		var total = (resultado + iva);
		$('#precio_reserva')[0].innerText = getNumFormat(total);
    });
    return;
}

function calcPrecResPaq() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/calc_prec_paq.php";
	
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);	
	var num_adultos = $('#num_adultos_reserva').val();
	var tipos_oferta = $('#tipos_oferta')[0];
	var tipo_oferta = tipos_oferta.options[tipos_oferta.selectedIndex].value;
	var ofertas = $('#ofertas_reserva')[0];
	var oferta = ofertas.options[ofertas.selectedIndex].value;
	
	if (habitacion <= 0) {
        return;
    }
	if (tipo_oferta <= 0) {
        return;
    }
	if (oferta <= 0) {
        return;
    }
	if (fecha_inicio_reserva == "") {
        return;
    }
	if (fecha_fin_reserva == "") {
        return;
    }
	$.post(url, {
		'habitacion': habitacion,   
        'fecha_inicio_reserva': fecha_inicio_reserva,
        'fecha_fin_reserva': fecha_fin_reserva,
		'cama_extra_reserva': cama_extra_reserva,
		'num_adultos': num_adultos,
		'oferta': oferta
    }, function(html) {
		var resultado = getNumFormat(html);
		$('#base_precio_reserva')[0].innerText = resultado;
		var iva = getNumFormat(resultado*0.08);
		$('#impuestos_precio_reserva')[0].innerText = iva;
		var total = (resultado + iva);
		$('#precio_reserva')[0].innerText = getNumFormat(total);
    });
    return;
}

function checkDispMod() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/check_disp_mod.php";
	
	var id_reserva = $('#id_reserva').val();
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n en la que desea comprobar la disponibilidad");
        return;
    }
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	
	$.post(url, {
		'id_reserva': id_reserva,
		'habitacion': habitacion,   
        'fecha_inicio_reserva': fecha_inicio_reserva,
        'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios': num_ninios,
		'num_adultos': num_adultos,
		'cama_extra_reserva': cama_extra_reserva
    }, function(html) {
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
		}
    });
    return;		
}

function checkDisp() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/check_disp.php";
	
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n en la que desea comprobar la disponibilidad");
        return;
    }
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	
	$.post(url, {
		'habitacion': habitacion,   
        'fecha_inicio_reserva': fecha_inicio_reserva,
        'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios': num_ninios,
		'num_adultos': num_adultos,
		'cama_extra_reserva': cama_extra_reserva
    }, function(html) {
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
		}
    });
    return;		
}

function checkDispModPaq() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/check_disp_mod_paq.php";
	
	var id_reserva = $('#id_reserva').val();
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	var tipos_oferta = $('#tipos_oferta')[0];
	var tipo_oferta = tipos_oferta.options[tipos_oferta.selectedIndex].value;
	var ofertas = $('#ofertas_reserva')[0];
	var oferta = ofertas.options[ofertas.selectedIndex].value;
	
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n en la que desea comprobar la disponibilidad");
        return;
    }
	if (tipo_oferta <= 0) {
        alert("Debe seleccionar el tipo de oferta en la que desea comprobar la disponibilidad");
        return;
    }
	if (oferta <= 0) {
        alert("Debe seleccionar la oferta en la que desea comprobar la disponibilidad");
        return;
    }
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	
	$.post(url, {
		'id_reserva': id_reserva,
		'habitacion': habitacion,   
        'fecha_inicio_reserva': fecha_inicio_reserva,
        'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios': num_ninios,
		'num_adultos': num_adultos,
		'cama_extra_reserva': cama_extra_reserva,
		'oferta': oferta
    }, function(html) {
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
		}
    });
    return;		
}

function checkDispPaq() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/check_disp_paq.php";
	
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	var tipos_oferta = $('#tipos_oferta')[0];
	var tipo_oferta = tipos_oferta.options[tipos_oferta.selectedIndex].value;
	var ofertas = $('#ofertas_reserva')[0];
	var oferta = ofertas.options[ofertas.selectedIndex].value;
	
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n en la que desea comprobar la disponibilidad");
        return;
    }
	if (tipo_oferta <= 0) {
        alert("Debe seleccionar el tipo de oferta en la que desea comprobar la disponibilidad");
        return;
    }
	if (oferta <= 0) {
        alert("Debe seleccionar la oferta en la que desea comprobar la disponibilidad");
        return;
    }
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	
	$.post(url, {
		'habitacion': habitacion,   
        'fecha_inicio_reserva': fecha_inicio_reserva,
        'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios': num_ninios,
		'num_adultos': num_adultos,
		'cama_extra_reserva': cama_extra_reserva,
		'oferta': oferta
    }, function(html) {
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
		}
    });
    return;		
}

function insertarReservaMan() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/add_reserva_man.php";
	
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	var nombre_reserva = $('#nombre_reserva').val();
	var apellidos_reserva = $('#apellidos_reserva').val();
	var email_reserva = $('#email_reserva').val();
	var telefono_reserva = $('#telefono_reserva').val();
	var precio_reserva = $('#precio_reserva')[0].innerText;
	var hora_llegada = $('#hora_llegada').val();
	var minuto_llegada = $('#minuto_llegada').val();
	var empresa_reserva = $('#empresa_reserva').val();
	var titular_tarjeta_reserva = $('#titular_tarjeta_reserva').val();
	var tipos_tarjeta = $('#tipos_tarjeta')[0].options[$('#tipos_tarjeta')[0].selectedIndex].value;
	var num_tarjeta_reserva = $('#num_tarjeta_reserva').val();
	var mes_exp_tarjeta_reserva = $('#mes_exp_tarjeta_reserva')[0].options[$('#mes_exp_tarjeta_reserva')[0].selectedIndex].value;
	var anyo_exp_tarjeta_reserva = $('#anyo_exp_tarjeta_reserva')[0].options[$('#anyo_exp_tarjeta_reserva')[0].selectedIndex].value;
	var tipos_motivo = $('#tipos_motivo')[0].options[$('#tipos_motivo')[0].selectedIndex].value;
	var comentario_reserva = tinyMCE.activeEditor.getContent();

	if (nombre_reserva=="") {
		alert("Introduzca su nombre para realizar la reserva");
		return;
	}
	if (apellidos_reserva=="") {
		alert("Introduzca sus apellidos para realizar la reserva");
		return;
	}
	if (email_reserva=="") {
		alert("Introduzca su email para realizar la reserva");
		return;
	}
	if (telefono_reserva=="") {
		alert("Introduzca su tel?fono para realizar la reserva");
		return;
	}
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	if (hora_llegada=="") {
		alert("Introduzca la hora de llegada para realizar la reserva");	
		return;
	}
	if (minuto_llegada=="") {
		alert("Introduzca el minuto de llegada para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (tipos_tarjeta==0) {
		alert("Seleccione el tipo de tarjeta para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva=="") {
		alert("Introduzca el n?mero de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva.length<16) {
		alert("El n?mero de la tarjeta de cr?dito que ha introducido debe contener 16 caracteres");
		return;
	}
	if (tipos_motivo==0) {
		alert("Seleccione el motivo del viaje para realizar la reserva");
		return;
	}
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n que desea reservar");
        return;
    }
	window.scrollTo(0, 0);
	cargando();
	$.post(url, {
		'id_habitacion_reserva': habitacion,   
		'fecha_inicio_reserva': fecha_inicio_reserva,
		'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios_reserva': num_ninios,
		'num_adultos_reserva': num_adultos,
		'cama_extra_reserva': cama_extra_reserva,
		'nombre_reserva': nombre_reserva,
		'apellidos_reserva': apellidos_reserva,
		'email_reserva': email_reserva,
		'telefono_reserva': telefono_reserva,
		'precio_reserva': precio_reserva,
		'hora_llegada_reserva': hora_llegada + ':' + minuto_llegada,
		'empresa_reserva': empresa_reserva,
		'titular_tarjeta_reserva': titular_tarjeta_reserva,
		'id_tipo_tarjeta_reserva': tipos_tarjeta,
		'num_tarjeta_reserva': num_tarjeta_reserva,
		'mes_exp_tarjeta_reserva': mes_exp_tarjeta_reserva,
		'anyo_exp_tarjeta_reserva': anyo_exp_tarjeta_reserva,
		'id_motivo_reserva': tipos_motivo,
		'comentario_reserva': comentario_reserva,
		'precio_reserva': precio_reserva
	}, function(html) {
		cerrar_cargando();
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
			document.location = 'reservas.php';
		}
	});
	return;
}

function guardarReserva(redir_inicio) {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/mod_reserva_man.php";
	
	var id_reserva = $('#id_reserva').val();
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	var nombre_reserva = $('#nombre_reserva').val();
	var apellidos_reserva = $('#apellidos_reserva').val();
	var email_reserva = $('#email_reserva').val();
	var telefono_reserva = $('#telefono_reserva').val();
	var precio_reserva = $('#precio_reserva')[0].innerText;
	var hora_llegada = $('#hora_llegada').val();
	var minuto_llegada = $('#minuto_llegada').val();
	var empresa_reserva = $('#empresa_reserva').val();
	var titular_tarjeta_reserva = $('#titular_tarjeta_reserva').val();
	var tipos_tarjeta = $('#tipos_tarjeta')[0].options[$('#tipos_tarjeta')[0].selectedIndex].value;
	var num_tarjeta_reserva = $('#num_tarjeta_reserva').val();
	var mes_exp_tarjeta_reserva = $('#mes_exp_tarjeta_reserva')[0].options[$('#mes_exp_tarjeta_reserva')[0].selectedIndex].value;
	var anyo_exp_tarjeta_reserva = $('#anyo_exp_tarjeta_reserva')[0].options[$('#anyo_exp_tarjeta_reserva')[0].selectedIndex].value;
	var tipos_motivo = $('#tipos_motivo')[0].options[$('#tipos_motivo')[0].selectedIndex].value;
	var comentario_reserva = tinyMCE.activeEditor.getContent();

	if (nombre_reserva=="") {
		alert("Introduzca su nombre para realizar la reserva");
		return;
	}
	if (apellidos_reserva=="") {
		alert("Introduzca sus apellidos para realizar la reserva");
		return;
	}
	if (email_reserva=="") {
		alert("Introduzca su email para realizar la reserva");
		return;
	}
	if (telefono_reserva=="") {
		alert("Introduzca su tel?fono para realizar la reserva");
		return;
	}
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	if (hora_llegada=="") {
		alert("Introduzca la hora de llegada para realizar la reserva");	
		return;
	}
	if (minuto_llegada=="") {
		alert("Introduzca el minuto de llegada para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (tipos_tarjeta==0) {
		alert("Seleccione el tipo de tarjeta para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva=="") {
		alert("Introduzca el n?mero de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva.length<16) {
		alert("El n?mero de la tarjeta de cr?dito que ha introducido debe contener 16 caracteres");
		return;
	}
	if (tipos_motivo==0) {
		alert("Seleccione el motivo del viaje para realizar la reserva");
		return;
	}
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n que desea reservar");
        return;
    }
	
	window.scrollTo(0, 0);
	cargando();
	$.post(url, {
		'id_reserva': id_reserva,
		'id_habitacion_reserva': habitacion,   
		'fecha_inicio_reserva': fecha_inicio_reserva,
		'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios_reserva': num_ninios,
		'num_adultos_reserva': num_adultos,
		'cama_extra_reserva': cama_extra_reserva,
		'nombre_reserva': nombre_reserva,
		'apellidos_reserva': apellidos_reserva,
		'email_reserva': email_reserva,
		'telefono_reserva': telefono_reserva,
		'precio_reserva': precio_reserva,
		'hora_llegada_reserva': hora_llegada + ':' + minuto_llegada,
		'empresa_reserva': empresa_reserva,
		'titular_tarjeta_reserva': titular_tarjeta_reserva,
		'id_tipo_tarjeta_reserva': tipos_tarjeta,
		'num_tarjeta_reserva': num_tarjeta_reserva,
		'mes_exp_tarjeta_reserva': mes_exp_tarjeta_reserva,
		'anyo_exp_tarjeta_reserva': anyo_exp_tarjeta_reserva,
		'id_motivo_reserva': tipos_motivo,
		'comentario_reserva': comentario_reserva,
		'precio_reserva': precio_reserva
	}, function(html) {
		cerrar_cargando();
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
			if (redir_inicio==0) {
				document.location = 'reservas.php';
			} else {
				document.location = 'index.php';	
			}
		}
	});
	return;
}


function insertarReservaPaq() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/add_reserva_paq.php";
	
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var tipos_oferta = $('#tipos_oferta')[0];
	var tipo_oferta = tipos_oferta.options[tipos_oferta.selectedIndex].value;
	var ofertas = $('#ofertas_reserva')[0];
	var oferta = ofertas.options[ofertas.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	var nombre_reserva = $('#nombre_reserva').val();
	var apellidos_reserva = $('#apellidos_reserva').val();
	var email_reserva = $('#email_reserva').val();
	var telefono_reserva = $('#telefono_reserva').val();
	var precio_reserva = $('#precio_reserva')[0].innerText;
	var hora_llegada = $('#hora_llegada').val();
	var minuto_llegada = $('#minuto_llegada').val();
	var empresa_reserva = $('#empresa_reserva').val();
	var titular_tarjeta_reserva = $('#titular_tarjeta_reserva').val();
	var tipos_tarjeta = $('#tipos_tarjeta')[0].options[$('#tipos_tarjeta')[0].selectedIndex].value;
	var num_tarjeta_reserva = $('#num_tarjeta_reserva').val();
	var mes_exp_tarjeta_reserva = $('#mes_exp_tarjeta_reserva')[0].options[$('#mes_exp_tarjeta_reserva')[0].selectedIndex].value;
	var anyo_exp_tarjeta_reserva = $('#anyo_exp_tarjeta_reserva')[0].options[$('#anyo_exp_tarjeta_reserva')[0].selectedIndex].value;
	var tipos_motivo = $('#tipos_motivo')[0].options[$('#tipos_motivo')[0].selectedIndex].value;
	var comentario_reserva = tinyMCE.activeEditor.getContent();

	if (nombre_reserva=="") {
		alert("Introduzca su nombre para realizar la reserva");
		return;
	}
	if (apellidos_reserva=="") {
		alert("Introduzca sus apellidos para realizar la reserva");
		return;
	}
	if (email_reserva=="") {
		alert("Introduzca su email para realizar la reserva");
		return;
	}
	if (telefono_reserva=="") {
		alert("Introduzca su tel?fono para realizar la reserva");
		return;
	}
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	if (hora_llegada=="") {
		alert("Introduzca la hora de llegada para realizar la reserva");	
		return;
	}
	if (minuto_llegada=="") {
		alert("Introduzca el minuto de llegada para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (tipos_tarjeta==0) {
		alert("Seleccione el tipo de tarjeta para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva=="") {
		alert("Introduzca el n?mero de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva.length<16) {
		alert("El n?mero de la tarjeta de cr?dito que ha introducido debe contener 16 caracteres");
		return;
	}
	if (tipos_motivo==0) {
		alert("Seleccione el motivo del viaje para realizar la reserva");
		return;
	}
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n que desea reservar");
        return;
    }
	if (tipo_oferta <= 0) {
        alert("Debe seleccionar el tipo de oferta que desea reservar");
        return;
    }
	if (oferta <= 0) {
        alert("Debe seleccionar la oferta que desea reservar");
        return;
    }
	
	window.scrollTo(0, 0);
	cargando();
	$.post(url, {
		'id_habitacion_reserva': habitacion,   
		'fecha_inicio_reserva': fecha_inicio_reserva,
		'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios_reserva': num_ninios,
		'num_adultos_reserva': num_adultos,
		'cama_extra_reserva': cama_extra_reserva,
		'nombre_reserva': nombre_reserva,
		'apellidos_reserva': apellidos_reserva,
		'email_reserva': email_reserva,
		'telefono_reserva': telefono_reserva,
		'precio_reserva': precio_reserva,
		'hora_llegada_reserva': hora_llegada + ':' + minuto_llegada,
		'empresa_reserva': empresa_reserva,
		'titular_tarjeta_reserva': titular_tarjeta_reserva,
		'id_tipo_tarjeta_reserva': tipos_tarjeta,
		'num_tarjeta_reserva': num_tarjeta_reserva,
		'mes_exp_tarjeta_reserva': mes_exp_tarjeta_reserva,
		'anyo_exp_tarjeta_reserva': anyo_exp_tarjeta_reserva,
		'id_motivo_reserva': tipos_motivo,
		'comentario_reserva': comentario_reserva,
		'precio_reserva': precio_reserva,
		'oferta': oferta
	}, function(html) {
		cerrar_cargando();
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
			document.location = 'reservas.php';
		}
	});
	return;
}

function guardarReservaPaq(redir_inicio) {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/mod_reserva_paq.php";
	
	var id_reserva = $('#id_reserva').val();
	var habitaciones = $('#id_habitacion_reserva')[0];
	var habitacion = habitaciones.options[habitaciones.selectedIndex].value;
	var tipos_oferta = $('#tipos_oferta')[0];
	var tipo_oferta = tipos_oferta.options[tipos_oferta.selectedIndex].value;
	var ofertas = $('#ofertas_reserva')[0];
	var oferta = ofertas.options[ofertas.selectedIndex].value;
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].checked);
	var nombre_reserva = $('#nombre_reserva').val();
	var apellidos_reserva = $('#apellidos_reserva').val();
	var email_reserva = $('#email_reserva').val();
	var telefono_reserva = $('#telefono_reserva').val();
	var precio_reserva = $('#precio_reserva')[0].innerText;
	var hora_llegada = $('#hora_llegada').val();
	var minuto_llegada = $('#minuto_llegada').val();
	var empresa_reserva = $('#empresa_reserva').val();
	var titular_tarjeta_reserva = $('#titular_tarjeta_reserva').val();
	var tipos_tarjeta = $('#tipos_tarjeta')[0].options[$('#tipos_tarjeta')[0].selectedIndex].value;
	var num_tarjeta_reserva = $('#num_tarjeta_reserva').val();
	var mes_exp_tarjeta_reserva = $('#mes_exp_tarjeta_reserva')[0].options[$('#mes_exp_tarjeta_reserva')[0].selectedIndex].value;
	var anyo_exp_tarjeta_reserva = $('#anyo_exp_tarjeta_reserva')[0].options[$('#anyo_exp_tarjeta_reserva')[0].selectedIndex].value;
	var tipos_motivo = $('#tipos_motivo')[0].options[$('#tipos_motivo')[0].selectedIndex].value;
	var comentario_reserva = tinyMCE.activeEditor.getContent();

	if (nombre_reserva=="") {
		alert("Introduzca su nombre para realizar la reserva");
		return;
	}
	if (apellidos_reserva=="") {
		alert("Introduzca sus apellidos para realizar la reserva");
		return;
	}
	if (email_reserva=="") {
		alert("Introduzca su email para realizar la reserva");
		return;
	}
	if (telefono_reserva=="") {
		alert("Introduzca su tel?fono para realizar la reserva");
		return;
	}
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	if (hora_llegada=="") {
		alert("Introduzca la hora de llegada para realizar la reserva");	
		return;
	}
	if (minuto_llegada=="") {
		alert("Introduzca el minuto de llegada para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (tipos_tarjeta==0) {
		alert("Seleccione el tipo de tarjeta para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva=="") {
		alert("Introduzca el n?mero de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva.length<16) {
		alert("El n?mero de la tarjeta de cr?dito que ha introducido debe contener 16 caracteres");
		return;
	}
	if (tipos_motivo==0) {
		alert("Seleccione el motivo del viaje para realizar la reserva");
		return;
	}
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n que desea reservar");
        return;
    }
	if (tipo_oferta <= 0) {
        alert("Debe seleccionar el tipo de oferta que desea reservar");
        return;
    }
	if (oferta <= 0) {
        alert("Debe seleccionar la oferta que desea reservar");
        return;
    }
	
	window.scrollTo(0, 0);
	cargando();
	$.post(url, {
		'id_reserva': id_reserva,
		'id_habitacion_reserva': habitacion,   
		'fecha_inicio_reserva': fecha_inicio_reserva,
		'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios_reserva': num_ninios,
		'num_adultos_reserva': num_adultos,
		'cama_extra_reserva': cama_extra_reserva,
		'nombre_reserva': nombre_reserva,
		'apellidos_reserva': apellidos_reserva,
		'email_reserva': email_reserva,
		'telefono_reserva': telefono_reserva,
		'precio_reserva': precio_reserva,
		'hora_llegada_reserva': hora_llegada + ':' + minuto_llegada,
		'empresa_reserva': empresa_reserva,
		'titular_tarjeta_reserva': titular_tarjeta_reserva,
		'id_tipo_tarjeta_reserva': tipos_tarjeta,
		'num_tarjeta_reserva': num_tarjeta_reserva,
		'mes_exp_tarjeta_reserva': mes_exp_tarjeta_reserva,
		'anyo_exp_tarjeta_reserva': anyo_exp_tarjeta_reserva,
		'id_motivo_reserva': tipos_motivo,
		'comentario_reserva': comentario_reserva,
		'precio_reserva': precio_reserva,
		'oferta': oferta
	}, function(html) {
		cerrar_cargando();
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
			if (redir_inicio==0) {
				document.location = 'reservas.php';
			} else {
				document.location = 'index.php';	
			}
		}
	});
	return;
}

function activar_reserva(id) {
	if (confirm('?Desea activar la reserva?')) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/includes/estado_reserva.php";		
		
		$.post(url, {
			'id_reserva': id,   
			'estado_reserva': 'Activada'
		}, function(html) {
			if (/^ERROR:/.test(html)) {
				alert(html.substring(6, html.length));
			} else {
				document.location.reload();
			}
		});
		return;
	}
}

function cancelar_reserva(id) {
	if (confirm('?Desea cancelar la reserva?')) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/includes/estado_reserva.php";		
		
		$.post(url, {
			'id_reserva': id,   
			'estado_reserva': 'Cancelada'
		}, function(html) {
			if (/^ERROR:/.test(html)) {
				alert(html.substring(6, html.length));
			} else {
				document.location.reload();
			}
		});
		return;
	}
}

/**
 * Metodo que cambia las subcategorias al cambiar de categoria
 *
 * @param int id			Identificador de categoria
 */  
function cambiar_ofertas(select_tipo_ofer) {
	var id = select_tipo_ofer.options[select_tipo_ofer.selectedIndex].value;
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/backend/get_ofertas.php";
	$.post(url, {
					'id': id
				}, function(html) {
					var options_html = html.split('<option');
					var select_oferts = $('#ofertas_reserva')[0];
					var select_len = select_oferts.options.length;
					select_oferts.options.length = 0;
					if (options_html.length>1) {
						for(var i=1;i<options_html.length;i++) {
							var name = options_html[i].split('name')[1];
							name = name.split('=')[1];
							name = name.split('"')[1];
							var value = options_html[i].split('value')[1];
							value = value.split('=')[1];
							value = value.split('"')[1];
							select_oferts.options[i-1] = new Option(name, value);
						}
					} else {
						select_oferts.options.length = 0;	
						select_oferts.options[0] = new Option("Seleccione una oferta...", "0");
					}
				});	
	return;
}

function guardarBloqueo() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/add_bloqueo.php";
	
	var habitacion_sel = $('#id_habitacion_bloqueo')[0];
	var habitacion = habitacion_sel.options[habitacion_sel.selectedIndex].value;
	var fecha_inicio_bloqueo = $('#fecha_inicio_bloqueo').val();
	var fecha_fin_bloqueo = $('#fecha_fin_bloqueo').val();
	var mes_calendario = $('#mes_calendario').val();
	var anyo_calendario = $('#anyo_calendario').val();
	
	if (habitacion_sel.length <= 0) {
        alert("Debe existe ninguna habitaci?n para realizar el bloqueo");
        return;
    }
	if (habitacion == 0) {
        alert("Debe seleccionar una habitaci?n para realizar el bloqueo");
        return;
    }	
	if (fecha_inicio_bloqueo == "") {
        alert("Introduzca la fecha inicial del bloqueo");
        return;
    }
	if (fecha_fin_bloqueo == "") {
        alert("Introduzca la fecha final del bloqueo");
        return;
    }
	
	$.post(url, {
		'habitacion_sel': habitacion,   
        'fecha_inicio_bloqueo': fecha_inicio_bloqueo,
        'fecha_fin_bloqueo': fecha_fin_bloqueo
    }, function(html) {
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			alert(html);
			setPlan(mes_calendario, anyo_calendario, '=');
			habitacion_sel.selectedIndex = 0;
			$('#fecha_inicio_bloqueo').val('');
			$('#fecha_fin_bloqueo').val('');
		}
    });
    return;
}

function setPlan(id_cal, mes, anyo, operador) {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/get_calendario.php";
	
	cargando();
	if (operador != '=') {
		if (operador == '-') {
			if (mes==1) {
				mes = 12;
				anyo--;
			} else {
				mes--;	
			}	
		} else {
			if (mes == 12) {
				mes = 1;
				anyo++;
			} else {
				mes++;	
			}	
		}
	} else {
		mes = new Number(mes);
	}
	
	if (mes<10) {
		mes = '0' + mes;	
	}
	
	$.post(url, {
		'id_cal': id_cal,
		'mes': mes,   
        'anyo': anyo
    }, function(html) {
		$('#' + id_cal).html(html);
		cerrar_cargando();
    });
    return;
}

function cargando() {
	tb_show("", '#TB_inline?inlineId=hiddenModalContent3&modal=true&height=160&width=250', null);
}

function cerrar_cargando() {
    tb_remove();
}

/**
 * Metodo que elimina una reserva
 *
 * @param int id			Identificador de estancia m?nima
 */  
function eliminar_reserva(id) {
	if (confirm("?Esta segur@ de que desea borrar la reserva?")) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/borrar_reserva.php";
		$.post(url, {
						'id': id
					}, function(html) {
						document.location.reload();
					});	
		return;
	}
}

function enviarCorreo() {
	var num_mails = $('#num_mails').val();
	if (confirm('Se va/n a enviar ' + num_mails + ' correo/s ?Desea continuar?')) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/administrador/backend/send_mails.php";
		var asunto_correo = $('#asunto_correo').val();
		var texto_correo = tinyMCE.activeEditor.getContent();
		if (asunto_correo=="") {
			alert("Introduzca el asunto del email que desea enviar");
			return;
		}
		if (texto_correo=="") {
			alert("Introduzca el texto del email que desea enviar");
			return;
		}
		cargando();
		$.post(url, {
			   			'asunto_correo': asunto_correo,
						'texto_correo': texto_correo
					}, function(html) {
						cerrar_cargando();
						alert(html);
						document.location.reload();
					});	
		return;
	}
}

function checkTipoHab(id_oferta, num_check) {
	var txt_bus_check = '_tipos_hab_oferta_';
	
	for (var i=0;i<3;i++) {
		var check = $('#'+id_oferta+txt_bus_check+(i+1));
		if (check.length>0) {
			if ((i+1)!=num_check) {
				if (check[0].checked) {
					check[0].checked = false;		
				}
			}
		}
	}
}

function openNewWindowReserva() {
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].value);
	var num_ofers = $('#num_ofers').val();
	var txt_bus_check = '_tipos_hab_oferta_';
	var id_oferta = 0;
	var tipo_hab = '';
	var tipo_oferta = '';
    
	if (num_ofers>0) {
		for (var i=0;i<num_ofers;i++) {
			var oferta = $('#id_tipo_ofer_'+(i+1))[0];
			if (oferta.status) {
				var id_ofer = oferta.value;
				var num_checks = $('#num_checks_'+id_ofer).val();
				var no_checked = 0;
				for (var j=0;j<3;j++) {
					var check = $('#'+id_ofer+txt_bus_check+(j+1));
					if (check.length>0) {
						if (check[0].checked) {
							tipo_hab = check[0].value;
							break;		
						} else {
							no_checked++;
						}
					}
				}
				if (no_checked == num_checks) {
					alert('Debe seleccionar una habitaci?n de la oferta');
					return;
				} else {
					id_oferta = id_ofer;
					tipo_oferta = oferta.name;
					
				}
			}
		}	
	}
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha de entrada de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha de salida de la reserva");
        return;
    }
	
	/*var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/get_num_noches.php";
	$.post(url, {
					'fecha_inicio_reserva': fecha_inicio_reserva,
					'fecha_fin_reserva': fecha_fin_reserva
				}, function(html) {
					$('#num_noches_reserva_ofer').html(html);
				});	
	
	$('#fecha_inicio_reserva_ofer').html(fecha_inicio_reserva);
	$('#fecha_fin_reserva_ofer').html(fecha_fin_reserva);
	if (id_oferta>0) {
		$('#tipo_oferta_reserva_ofer').html(tipo_oferta);
		$('#tipo_habitacion_reserva_ofer').html(tipo_hab);
		$('#id_oferta').val(id_oferta);
	} else {
		$('#tipo_oferta_reserva_ofer').html('');
		$('#tipo_habitacion_reserva_ofer').html('');
		$('#id_oferta').val(0);
	}
	$('#num_adultos_reserva_ofer').html(num_adultos);
	$('#num_ninios_reserva_ofer').html(num_ninios);*/
	window.open('index_params.php?num_adultos=' + num_adultos + '&num_ninios=' + num_ninios + '&cama_extra_reserva=' + cama_extra_reserva + '&id_oferta=' + id_oferta + '&tipo_hab=' + tipo_hab + '&fecha_inicio_reserva=' + fecha_inicio_reserva + '&fecha_fin_reserva=' + fecha_fin_reserva, "Reservas");
	//Paso2(num_adultos, num_ninios, cama_extra_reserva, id_oferta, tipo_hab, fecha_inicio_reserva, fecha_fin_reserva);
}

function checkCamposReserva() {
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva').val();
	var num_adultos = $('#num_adultos_reserva').val();
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].value);
	var num_ofers = $('#num_ofers').val();
	var txt_bus_check = '_tipos_hab_oferta_';
	var id_oferta = 0;
	var tipo_hab = '';
	var tipo_oferta = '';
    
	if (num_ofers>0) {
		for (var i=0;i<num_ofers;i++) {
			var oferta = $('#id_tipo_ofer_'+(i+1))[0];
			if (oferta.status) {
				var id_ofer = oferta.value;
				var num_checks = $('#num_checks_'+id_ofer).val();
				var no_checked = 0;
				for (var j=0;j<3;j++) {
					var check = $('#'+id_ofer+txt_bus_check+(j+1));
					if (check.length>0) {
						if (check[0].checked) {
							tipo_hab = check[0].value;
							break;		
						} else {
							no_checked++;
						}
					}
				}
				if (no_checked == num_checks) {
					alert('Debe seleccionar una habitaci?n de la oferta');
					return;
				} else {
					id_oferta = id_ofer;
					tipo_oferta = oferta.name;
					
				}
			}
		}	
	}
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha de entrada de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha de salida de la reserva");
        return;
    }
	
	if (id_oferta>0) {
		$('#tipo_oferta_reserva_ofer').html(tipo_oferta);
		$('#tipo_habitacion_reserva_ofer').html(tipo_hab);
		$('#id_oferta').val(id_oferta);
	} else {
		//alert('Debe seleccionar una oferta.');
		//return;
		/*$('#tipo_oferta_reserva_ofer').html('');
		$('#tipo_habitacion_reserva_ofer').html('');
		$('#id_oferta').val(0);*/
	}
	
	var host = document.location.hostname;
	var port = document.location.port;
    
	var url = protocolo + host + ":" + port + "/includes/get_num_noches.php";
    
	$.post(url, {
					'fecha_inicio_reserva': fecha_inicio_reserva,
					'fecha_fin_reserva': fecha_fin_reserva
				}, function(html) {
					$('#num_noches_reserva_ofer').html(html);
				});	
	
	$('#fecha_inicio_reserva_ofer').html(fecha_inicio_reserva);
	$('#fecha_fin_reserva_ofer').html(fecha_fin_reserva);
	$('#num_adultos_reserva_ofer').html(num_adultos);
	$('#num_ninios_reserva_ofer').html(num_ninios);
	Paso2(num_adultos, num_ninios, cama_extra_reserva, id_oferta, tipo_hab, fecha_inicio_reserva, fecha_fin_reserva);
}

function Paso2(num_adultos, num_ninios, cama_extra, id_oferta, tipo_hab, fecha_inicio_reserva, fecha_fin_reserva){
	if (!paso_final) {
		var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/includes/comprueba_disponibilidad.php";
		window.scrollTo(0, 0);
		cargando();
		$.post(url, {
					'num_adultos': num_adultos,
					'num_ninios': num_ninios,
					'cama_extra': cama_extra,
					'id_oferta': id_oferta,
					'tipo_hab': tipo_hab,
					'fecha_inicio_reserva': fecha_inicio_reserva,
					'fecha_fin_reserva': fecha_fin_reserva
				}, function(html) {
					if (/^ERROR:/.test(html)) {
						cerrar_cargando();
						alert(html.substring(6, html.length));
						return;
					} else {
						paso2Correcto(num_adultos, num_ninios, cama_extra, id_oferta, tipo_hab, fecha_inicio_reserva, fecha_fin_reserva);	
					}
				});
			
	}
	return;
}

function paso2Correcto(num_adultos, num_ninios, cama_extra, id_oferta, tipo_hab, fecha_inicio_reserva, fecha_fin_reserva) {
	paso1 = true;
	initPrecio();
	initHabDesc();
	$('#paso1')[0].src = 'images/estilo2/paso_01a.jpg';
	$('#paso2')[0].src = 'images/estilo2/paso_02a.jpg';
	$('#paso3')[0].src = 'images/estilo2/paso_03.jpg';
	$('#tabla_paso_1').css('display', 'none');
	$('#tabla_paso_3_1').css('display', 'none');
	$('#ofertas_paso_1').css('display', 'none');
	$('#ofertas_paso_2').css('display', 'block');
	$('#calendario').css('display', 'none');
	$('#hab_desc').css('display', 'block');
	$('#tabla_paso_3_2').css('display', 'none');
	
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/get_tabla_habitaciones.php";
	$.post(url, {
					'num_adultos': num_adultos,
					'num_ninios': num_ninios,
					'cama_extra': cama_extra,
					'id_oferta': id_oferta,
					'tipo_hab': tipo_hab,
					'fecha_inicio_reserva': fecha_inicio_reserva,
					'fecha_fin_reserva': fecha_fin_reserva
				}, function(html) {
					$('#tabla_paso_2')[0].innerHTML = html;
					$('#tabla_paso_2').css('display', 'block');
					cerrar_cargando();
				});	
}

function Paso1() {
	if (!paso_final) {
		$('#paso1')[0].src = 'images/estilo2/paso_01.jpg';
		$('#paso2')[0].src = 'images/estilo2/paso_02.jpg';
		$('#paso3')[0].src = 'images/estilo2/paso_03.jpg';
		$('#tabla_paso_1').css('display', 'block');
		$('#tabla_paso_2').css('display', 'none');
		$('#tabla_paso_3_1').css('display', 'none');
		$('#ofertas_paso_1').css('display', 'block');
		$('#ofertas_paso_2').css('display', 'none');
		if (!$.browser.msie) {
			$('#calendario').css('margin-top', '-341px');
		}
		$('#calendario').css('display', 'block');
		$('#hab_desc').css('display', 'none');
		$('#tabla_paso_3_2').css('display', 'none');
	}
}

function Paso3() {
	if (!paso_final) {
		paso2 = true;
		/*initPrecio();
		initHabDesc();*/
		var id_habitacion_reserva = 0;
		var radios = document.getElementsByName('habitacion');
		var seleccionado = false;
		for (var i=0;i<radios.length;i++) {
			if (radios[i].checked) {
				seleccionado = true;
				id_habitacion_reserva = radios[i].value;
				break;
			} else {
				seleccionado = false;
			}
		}
		
		
		if (!seleccionado) {
			alert('Debe seleccionar una habitación para continuar con la reserva');
			return;
		}
		
		$('#id_habitacion_reserva').val(id_habitacion_reserva);
		$('#paso1')[0].src = '/images/estilo2/paso_01a.jpg';
		$('#paso2')[0].src = '/images/estilo2/paso_02.jpg';
		$('#paso3')[0].src = '/images/estilo2/paso_03a.jpg';
		$('#tabla_paso_1').css('display', 'none');
		$('#tabla_paso_2').css('display', 'none');
		$('#ofertas_paso_1').css('display', 'none');
		$('#ofertas_paso_2').css('display', 'block');
		$('#tabla_paso_3_1').css('display', 'block');
		$('#calendario').css('display', 'none');
		$('#hab_desc').css('display', 'none');
		$('#tabla_paso_3_2').css('display', 'block');
		
		/*var host = document.location.hostname;
		var port = document.location.port;
		var url = protocolo + host + ":" + port + "/includes/get_tabla_habitaciones.php";
		$.post(url, {
						'num_adultos': num_adultos,
						'id_oferta': id_oferta,
						'tipo_hab': tipo_hab,
						'fecha_inicio_reserva': fecha_inicio_reserva
					}, function(html) {
						$('#tabla_paso_2')[0].innerHTML = html;
						$('#tabla_paso_2').css('display', 'block');
					});	*/
	}
	return;
}


function initPrecio() {
	$('#precio_base_reserva_ofer').html('0');
	$('#precio_total_reserva_ofer').html('0');	
}

function updatePrecio(radio_hab) {
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].value);
	var id_oferta = 0;
	var txt_bus_check = '_tipos_hab_oferta_';
	var num_ofers = $('#num_ofers').val();
	if (num_ofers>0) {
		for (var i=0;i<num_ofers;i++) {
			var oferta = $('#id_tipo_ofer_'+(i+1))[0];
			if (oferta.status) {
				var id_ofer = oferta.value;
				var num_checks = $('#num_checks_'+id_ofer).val();
				var no_checked = 0;
				for (var j=0;j<num_checks;j++) {
					var check = $('#'+id_ofer+txt_bus_check+(j+1));
					if (check.length>0) {
						if (check[0].checked) {
							tipo_hab = check[0].value;
							break;		
						} else {
							no_checked++;
						}
					}
				}
				if (no_checked == num_checks) {
					alert('Debe seleccionar una habitaci?n de la oferta');
					return;
				} else {
					id_oferta = id_ofer;
					tipo_oferta = oferta.name;
					
				}
			}
		}	
	}
	var resultado = getNumFormat(radio_hab.id);
	var num_adultos = getNumFormat($('#num_adultos_reserva_ofer').html());
	var num_noches = getNumFormat($('#num_noches_reserva_ofer').html());
	var precio_extra = 0;
	if (cama_extra_reserva>0) {
		var precio_cama_extra = $('#precio_cama_extra').val();	
		var precio_extra = getNumFormat(precio_cama_extra * num_noches);
	}
	var precio_adults = getNumFormat(resultado);//num_adultos
	if (id_oferta>0) {
		var precio_total = getNumFormat(precio_adults*(num_adultos*num_noches));
	} else {
		var precio_total = getNumFormat(precio_adults*num_noches);	
	}
	precio_total = getNumFormat(precio_total + precio_extra);
	$('#precio_base_reserva_ofer').html(precio_total);
	var iva = getNumFormat(precio_total*0.08);
	//$('#impuestos_precio_reserva')[0].innerText = iva;
	var total = (precio_total + iva);
	$('#precio_total_reserva_ofer').html(getNumFormat(total));	
}

function initHabDesc() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/get_hab_desc.php";
	$.post(url, {
					'id_hab': 0
				}, function(html) {
					$('#hab_desc')[0].innerHTML = html;
					$('#hab_desc').css('display', 'block');
				});	
	return;
}

function getHabDesc(radio_hab, tipo_hab) {
	updatePrecio(radio_hab);
	$('#tipo_habitacion_reserva_ofer').html(tipo_hab);
	var id_hab = radio_hab.value;
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/get_hab_desc.php";
	$.post(url, {
					'id_hab': id_hab
				}, function(html) {
					$('#hab_desc')[0].innerHTML = html;
					$('#hab_desc').css('display', 'block');
				});	
	return;
}

function checkState(radio_but) {
	if (radio_but.id == radio_id) {
		if (!radio_status) {
			radio_status = true;	
		} else {
			radio_status = false;
			radio_but.checked = false;	
		}
	} else {
		if (radio_id!="") {
			if (radio_status) {
				var radio_tmp = document.getElementById(radio_id);
				radio_tmp.checked = false; 
			}
		}
		radio_id = radio_but.id;
		radio_status = radio_but.checked;
	}	
}

function insertarReserva() {
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/add_reserva.php";
	
	var habitacion = $('#id_habitacion_reserva').val();
	var id_oferta = $('#id_oferta').val();
	var fecha_inicio_reserva = $('#fecha_inicio_reserva').val();
	var fecha_fin_reserva = $('#fecha_fin_reserva').val();
	var num_ninios = $('#num_ninios_reserva')[0].value;
	var num_adultos = $('#num_adultos_reserva')[0].value;
	var cama_extra_reserva = Number($('#cama_extra_reserva')[0].value);
	var nombre_reserva = $('#nombre_reserva').val();
	var apellidos_reserva = $('#apellidos_reserva').val();
	var email_reserva = $('#email_reserva').val();
	var telefono_reserva = $('#telefono_reserva').val();
	var precio_reserva = $('#precio_total_reserva_ofer')[0].innerText;
	var hora_llegada = $('#hora_llegada').val();
	var minuto_llegada = $('#minuto_llegada').val();
	var empresa_reserva = $('#empresa_reserva').val();
	var titular_tarjeta_reserva = $('#titular_tarjeta_reserva').val();
	var tipos_tarjeta = $('#tipos_tarjeta')[0].options[$('#tipos_tarjeta')[0].selectedIndex].value;
	var num_tarjeta_reserva = $('#num_tarjeta_reserva').val();
	var mes_exp_tarjeta_reserva = $('#mes_exp_tarjeta_reserva')[0].options[$('#mes_exp_tarjeta_reserva')[0].selectedIndex].value;
	var anyo_exp_tarjeta_reserva = $('#anyo_exp_tarjeta_reserva')[0].options[$('#anyo_exp_tarjeta_reserva')[0].selectedIndex].value;
	var comentario_reserva = $('#comentario_reserva').val();
	var confirmar_datos_reserva = $('#confirmar_datos_reserva')[0].checked;
	var aceptacion_datos_reserva = $('#aceptacion_datos_reserva')[0].checked;

	if (nombre_reserva=="") {
		alert("Introduzca su nombre para realizar la reserva");
		return;
	}
	if (apellidos_reserva=="") {
		alert("Introduzca sus apellidos para realizar la reserva");
		return;
	}
	if (email_reserva=="") {
		alert("Introduzca su email para realizar la reserva");
		return;
	}
	if (telefono_reserva=="") {
		alert("Introduzca su tel?fono para realizar la reserva");
		return;
	}
	if (fecha_inicio_reserva == "") {
        alert("Introduzca la fecha inicial de la reserva");
        return;
    }
	if (fecha_fin_reserva == "") {
        alert("Introduzca la fecha final de la reserva");
        return;
    }
	if (hora_llegada=="") {
		alert("Introduzca la hora de llegada para realizar la reserva");	
		return;
	}
	if (minuto_llegada=="") {
		alert("Introduzca el minuto de llegada para realizar la reserva");
		return;
	}
	if (titular_tarjeta_reserva=="") {
		alert("Introduzca el titular de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	/*if (tipos_tarjeta==0) {
		alert("Seleccione el tipo de tarjeta para realizar la reserva");
		return;
	}*/
	if (num_tarjeta_reserva=="") {
		alert("Introduzca el n?mero de la tarjeta de cr?dito para realizar la reserva");
		return;
	}
	if (num_tarjeta_reserva.length<16) {
		alert("El n?mero de la tarjeta de cr?dito que ha introducido debe contener 16 caracteres");
		return;
	}
	if (!aceptacion_datos_reserva) {
		alert("Debe aceptar las condiciones para realizar su reserva");
		return;
	}
	if (habitacion <= 0) {
        alert("Debe seleccionar la habitaci?n que desea reservar");
        return;
    }
	window.scrollTo(0, 0);
	cargando();
	$.post(url, {
		'id_habitacion_reserva': habitacion,   
		'id_oferta': id_oferta,
		'fecha_inicio_reserva': fecha_inicio_reserva,
		'fecha_fin_reserva': fecha_fin_reserva,
		'num_ninios_reserva': num_ninios,
		'num_adultos_reserva': num_adultos,
		'cama_extra_reserva': cama_extra_reserva,
		'nombre_reserva': nombre_reserva,
		'apellidos_reserva': apellidos_reserva,
		'email_reserva': email_reserva,
		'telefono_reserva': telefono_reserva,
		'precio_reserva': precio_reserva,
		'hora_llegada_reserva': hora_llegada + ':' + minuto_llegada,
		'empresa_reserva': empresa_reserva,
		'titular_tarjeta_reserva': titular_tarjeta_reserva,
		'id_tipo_tarjeta_reserva': tipos_tarjeta,
		'num_tarjeta_reserva': num_tarjeta_reserva,
		'mes_exp_tarjeta_reserva': mes_exp_tarjeta_reserva,
		'anyo_exp_tarjeta_reserva': anyo_exp_tarjeta_reserva,
		'confirmar_datos_reserva': confirmar_datos_reserva,
		'aceptacion_datos_reserva': aceptacion_datos_reserva,
		'comentario_reserva': comentario_reserva,
		'precio_reserva': precio_reserva
	}, function(html) {
		cerrar_cargando();
		if (/^ERROR:/.test(html)) {
			alert(html.substring(6, html.length));
		} else {
			//alert(html);
			paso_final = true;
			PasoFinal();
			//document.location = 'reservas.php';
		}
	});
	return;
}

function PasoFinal() {
	//$('#paso3')[0].src = 'images/estilo2/paso_03a.jpg';
	$('#imprimir_but').css('display', 'block');
	$('#paso_final').css('display', 'block');
	$('#tabla_paso_3_1').css('display', 'none');
	$('#hab_desc').css('display', 'block');
	$('#tabla_paso_3_2').css('display', 'none');
	
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/get_codigo_reserva.php";
	$.post(url, {
				}, function(html) {
					$('#cod_reserva')[0].innerHTML = html;
				});	
	return;
}

function imprimir_reserva() {
	var cod_reserva = $('#cod_reserva')[0].innerHTML;
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/imprimir_reserva.php";
	$.post(url, {
		   		'cod_reserva': cod_reserva
				}, function(html) {
					var ventimp = window.open(' ', 'popimpr');
					ventimp.document.write(html);
					ventimp.document.close();
					ventimp.print();
					ventimp.close();
				});	
	return;
}

function validarReserva() {
	var codigo_reserva = $('#codigo_reserva').val();
	
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/get_reserva_by_cod.php";
	$.post(url, {
					'codigo_reserva': codigo_reserva
				}, function(html) {
					if (/^ERROR:/.test(html)) {
						alert(html.substring(6, html.length));
					} else {
						$('#text_area_reserva').css('display', 'block');
					}
				});	
	return;
}

function enviarModificacionReserva() {
	var codigo_reserva = $('#codigo_reserva').val();
	var comentario_reserva = $('#comentario_reserva').val();
	
	if (comentario_reserva=="") {
		alert('Introduzca el comentario que desea enviar');
		return;
	}
	
	window.scrollTo(0, 0);
	cargando();
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/includes/envia_mod_reserva.php";
	$.post(url, {
					'codigo_reserva': codigo_reserva,
					'comentario_reserva': comentario_reserva
				}, function(html) {
					cerrar_cargando();
					alert('Su comentario ha sido enviado satisfactoriamente');
					$('#text_area_reserva').css('display', 'none');
					$('#text_area_reserva').val('');
					$('#codigo_reserva').val('');
				});	
	return;
}

function ocultar_campo_comentario() {
	$('#text_area_reserva').css('display', 'none');	
}

function addCliente() {
	var email_cliente = $('#email_cliente').val();
	
	var host = document.location.hostname;
	var port = document.location.port;
	var url = protocolo + host + ":" + port + "/administrador/includes/add_cliente.php";
	$.post(url, {
					'email': email_cliente,
					'iframe': true
				}, function(html) {
					$('#email_cliente').val('');
					/*if (/^ERROR:/.test(html)) {
						alert(html.substring(6, html.length));
					} else {
						alert(html);
					}*/
				});	
	return;
}
