/*
 Copyright (c) 2008-2009, Red Universal de Marketing y Bookings Online, S.A. (Rumbo) All rights reserved.
 */
/**
 * 
 * Funcion que crea una linea vertical en una tabla
 * 
 */
function createVerticalLine()
{
    td = document.createElement("td");
    td.width = "1px";
    td.rowSpan = "1000";
    td.bgColor = "#cccccc";

    return td;
}

/**
 * 
 * Funcion que crea una tabla y le da un id que recibe por parametro
 * 
 */
function createTableWithId(tbody, id)
{
    var table = document.createElement("table");
    table.setAttribute("id", id);
    table.style.left = 0;
    table.style.top = 0;
    table.style.zIndex = 1;
    table.style.position = "relative";
    table.appendChild(tbody);

    return table;
}

/**
 * 
 * Funcion que crea una tabla y le da un id que recibe por parametro y el lugar
 * donde pintarla
 * 
 */
function createTableWithIdAndLocation(tbody, id, left)
{
    var table = document.createElement("table");
    table.setAttribute("id", id);
    table.style.left = left;
    table.style.top = 0;
    table.style.zIndex = 1;
    table.style.position = "relative";
    table.appendChild(tbody);

    return table;
}

/**
 * 
 * Funcion que crea un tr html
 * 
 */
function createTr()
{

    return document.createElement("tr");
}

/**
 * 
 * Funcion que crea una celda html recibe los parametros estilo, ancho, alto,
 * alineacion, colspan, rowspan y paddin
 * 
 */
function createTd(style, width, height, align, colSpan, rowSpan, padding)
{
    var td = document.createElement("td");

    if (style != "" && style != "undefined") {
        td.setAttribute("class", style);
        td.className = style;
    }

    if (width > 0) {
        td.width = width;
    }

    if (height > 0) {
        td.height = height;
    }

    if (align != null && align != "" && align != "undefined") {
        td.align = align;
    }

    if (colSpan > 1) {
        td.colSpan = colSpan;
    }

    if (rowSpan > 1) {
        td.rowSpan = rowSpan;
    }

    if (padding != "undefided" && padding != "" && padding != "0") {
        td.style.cssText = "padding-left:" + padding + "px;padding-right:" + padding + "px;";
        td.setAttribute("style", "padding-left:" + padding + "px;padding-right:" + padding + "px;");
    }

    return td;
}

/**
 * 
 * Funcion que crea una celda html que ocuparï¿½ una linea siempre el contenido
 * recibe los parametros estilo, ancho, alto, alineacion, colspan, rowspan y
 * paddin
 * 
 */
function createTdNoWrap(style, width, height, align, colSpan, rowSpan, padding)
{
    var td = document.createElement("td");

    if (style != "" && style != "undefined") {
        td.setAttribute("class", style);
        td.className = style;
    }

    if (width > 0) {
        td.width = width;
    }

    if (height > 0) {
        td.height = height;
    }

    if (align != null && align != "" && align != "undefined") {
        td.setAttribute("align", align);
        td.align = align;
    }

    if (colSpan > 1) {
        td.colSpan = colSpan;
    }

    if (rowSpan > 1) {
        td.rowSpan = rowSpan;
    }

    if (padding != "undefided" && padding != "" && padding != "0") {
        td.style.cssText = "padding-left:" + padding + "px;padding-right:" + padding + "px;";
        td.setAttribute("style", "padding-left:" + padding + "px;padding-right:" + padding + "px;");
    }
    // td.setAttribute("nowrap", "nowrap");
    td.noWrap = "true";

    return td;
}

/**
 * 
 * Funcion que crea una celda html que ocuparï¿½ una linea siempre el contenido
 * recibe los parametros estilo, alto, alineacion, colspan, rowspan y paddin,
 * sin ancho!
 * 
 */
function createTdNoWrapOutWidth(style, height, align, colSpan, rowSpan, padding)
{
    var td = document.createElement("td");

    if (style != "" && style != "undefined") {
        td.setAttribute("class", style);
        td.className = style;
    }

    if (height > 0) {
        td.height = height;
    }

    if (align != null && align != "" && align != "undefined") {
        td.setAttribute("align", align);
        td.align = align;
    }

    if (colSpan > 1) {
        td.colSpan = colSpan;
    }

    if (rowSpan > 1) {
        td.rowSpan = rowSpan;
    }

    if (padding != "undefided" && padding != "" && padding != "0") {
        td.style.cssText = "padding-left:" + padding + "px;padding-right:" + padding + "px;";
        td.setAttribute("style", "padding-left:" + padding + "px;padding-right:" + padding + "px;");
    }
    // td.setAttribute("nowrap", "nowrap");
    td.noWrap = "true";

    return td;
}

/**
 * 
 * Funcion que crea un nodo de texto en html
 * 
 */
function createText(text)
{
    var textNode = document.createTextNode(text);

    return textNode;
}

/**
 * 
 * Funcion que crea el cuerpo de una tabla
 * 
 */
function createTableBody()
{
    var tbody = document.createElement("tbody");

    return tbody;
}

/**
 * 
 * Funcion que crea un link html que recibe los parametros texto del enlace,
 * ruta y estilo
 * 
 */
function createLink(text, href, style)
{
    var link = document.createElement("a");
    link.setAttribute("class", style);
    link.className = style;
    link.setAttribute("href", href);
    var text = document.createTextNode(text);
    link.appendChild(text);

    return link;
}

/**
 * 
 * Funcion que crea un link html que recibe los parametros texto del enlace,
 * ruta y estilo
 * 
 */
function createLinkAlt(text, href, style, alt)
{
    var link = document.createElement("a");
    link.setAttribute("class", style);
    link.className = style;
    link.setAttribute("href", href);
    link.setAttribute("alt", alt);
    link.setAttribute("title", alt);
    var text = document.createTextNode(text);
    link.appendChild(text);

    return link;
}

/**
 * 
 * Funcion que crea un link html que recibe los parametros la imagen que enlaza,
 * y la ruta de destino
 * 
 */
function createLinkImg(domImg, href)
{
    var link = document.createElement("a");
    link.setAttribute("href", href);
    link.appendChild(domImg);

    return link;
}

/**
 * 
 * Funcion que crea una tabla y le enlaza el cuerpo que se le pase por parametro
 * 
 */
function createTable(tbody)
{
    var table = document.createElement("table");
    table.appendChild(tbody);

    return table;
}

/**
 * 
 * Funcion que enlaza codigo dom con una etiqueta cuyo div recibe por parametro
 * 
 */
function linkDomToHtml(id, dom)
{
    document.getElementById(id).appendChild(dom);
}

/**
 * 
 * Funcion que crea una etiqueta html de imagen que recibe la ruta de la imagen
 * y el title/alt
 */
function createImg(src, title)
{
    img = document.createElement("img");
    img.setAttribute("src", src);
    img.setAttribute("border", "0");

    if (title != "") {
        img.setAttribute("title", title);
        img.setAttribute("alt", title);
    }

    return img;
}

/**
 * 
 * Funcion que recibe una lista de celdas y devulve una linea con las celdas
 * dentro
 */
function putTdListInTr(tds)
{
    tr = createTr();
    for (i = 0; i < tds.length; i++) {
        tr.appendChild(tds[i]);
    }

    return tr;
}

/**
 * 
 * Funcion que crea una etiqueta html span que contiene el texto que se le pasa
 * por parametro y el estilo que tambien recibe por parametro
 * 
 */
function createSpan(text, style)
{
    var span = document.createElement("span");

    if (style != '' && style != undefined) {
        span.setAttribute("class", style);
        span.className = style;
    }

    if (text != '' && text != undefined) {
        var textNode = document.createTextNode(text);
        span.appendChild(textNode);
    }

    return span;
}

/**
 * 
 * Funcion que crea una etiqueta html span que contiene el texto que se le pasa
 * por parametro, el estilo que tambien recibe por parametro y un texto
 * alternativo o title
 * 
 */
function createSpan(text, style, alt)
{
    var span = document.createElement("span");

    if (style != '' && style != undefined) {
        span.setAttribute("class", style);
        span.className = style;
    }

    if (alt != '' && alt != undefined) {
        span.setAttribute("title", alt);
    }

    if (text != '' && text != undefined) {
        var textNode = document.createTextNode(text);
        span.appendChild(textNode);
    }

    return span;
}

/**
 * 
 * Funcion que elimina todos los hijos de una etiqueta html cuyo id recibe por
 * parametro
 * 
 */
function deleteDivChildren(id)
{
    var div = document.getElementById(id);
    while (div.hasChildNodes()) {
        div.removeChild(div.childNodes[0]);
    }
}

/**
 * 
 * Funcion que crea los links de precio de la matriz y las llamadas a sus
 * efectos
 * 
 */
function createLinkPrice(text, href, style, idhotel, idfecha)
{
    var link = document.createElement("a");
    link.setAttribute("class", style);
    link.className = style;
    link.onmouseover = function()
    {
        cambiaEstiloSeleccion(idhotel, idfecha);
    };
    link.onmouseout = function()
    {
        cambiaEstiloNoSeleccion(idhotel, idfecha);
    };
    link.setAttribute("href", href);
    var text = document.createTextNode(text);
    link.appendChild(text);

    return link;
}

function createblankSpace()
{

    return document.createTextNode(" ");
}

/**
 * funcion que dice si una variable esta definida
 */
function isDefined(variable)
{

    return (typeof (window[variable]) != "undefined");
}

//Versión del js 0.94.e

rmbui.i18n.requireLocalization('vacations');

var mostrarHoteles = 0; // muestra solo 8 hoteles
var numHotelesPorAgrupacion;
var nombreLinkMostrar = rmbui.i18n.label.linkMostrar;

// Array que contendrá los regímenes por los que hay que filtrar
var array = new Array();
// Primera vez que recorremos la matriz
var firstTime = true;
var selectedRegimen = 'todos';
// Variable para saber si ha presionado el enlace de ocultarHoteles
var pressLink = false;
var changedRegimen = false;
var searchHotel = false;
// Variables globales para poder aplicar el descuento
var cantidadDescuento = null;
var tipoDescuento = null;
var src = "/pictures/mostrar-hotel-vacacional.gif";
// Para saber si tenemos que mostrar el enlace de más hoteles o no
var moreHotels = false;

function creaMatriz() {
	// creamos por un lado la tabla con los hoteles
	// y por otro la matriz con las fechas y los precios
	// esto se hace para conseguir el efecto de deslizar
	numNigths = document.opcionesPaqueteForm.numNoches.value;
	// si hemos encontrado el numero de noches sigue normal

	if (creaTablaHotel(numNigths)) {
		creaTablaPrecios(numNigths);
		refreshButton();
		deleteDivChildren('imgCargando');

	}
	// si no hacemos una llamada ajax con el numero de noches que necesitamos
	// porque hay un bug en la carga y puede dar error
	else {
		getOrign();
	}
}

function creaTablaHotel(numNigths) {
	result = false;

	for ( var i = 0; i < json.lDuraciones.length; i++) {

		if (json.lDuraciones[i].numNoches == numNigths) {

			reparteHotelesAgrupacion(json.lDuraciones[i]);

			poneVisiblesHoteles(json.lDuraciones[i]);

			creaTablaHotelDom(json.lDuraciones[i]);

			result = true;

			break;

		}

	}
	return result;

}

function creaTablaPrecios(numNigths) {
	for ( var i = 0; i < json.lDuraciones.length; i++) {

		if (json.lDuraciones[i].numNoches == numNigths) {

			creaTablaPreciosDom(json.lDuraciones[i]);

			break;

		}

	}
}

function reparteHotelesAgrupacion(duracion) {

	// repartimos 8 hoteles entre el número de agrupaciones

	numHotelesPorAgrupacion = new Array(duracion.lAgrupaciones.length);

	// iniciamos el array todos a 0

	for ( var iNumHoteles = 0; iNumHoteles < numHotelesPorAgrupacion.length; iNumHoteles++) {

		numHotelesPorAgrupacion[iNumHoteles] = 0;

	}

	// vamos añadiendo 1 a cada agrupación hasta llegar a 8

	var nHoteles = devuelveTotalHoteles(duracion);

	while (nHoteles > 0) {

		var nAgrup = 0;

		while (nAgrup < numHotelesPorAgrupacion.length && nHoteles > 0) {

			var numeroListaHoteles = 0;

			// Contamos el número de Hoteles que se pueden visualizar

			for ( var i = 0; i < duracion.lAgrupaciones[nAgrup].lHoteles.length; i++) {

				if (duracion.lAgrupaciones[nAgrup].lHoteles[i].visible == 1) {

					numeroListaHoteles = numeroListaHoteles + 1;

				}

			}

			if (numHotelesPorAgrupacion[nAgrup] < numeroListaHoteles) {

				numHotelesPorAgrupacion[nAgrup]++;

				nHoteles--;

			}

			nAgrup++;

		}

	}

}

function devuelveTotalHoteles(duracion) {

	var totalHoteles = 0;
	for ( var nH = 0; nH < duracion.lAgrupaciones.length; nH++) {
		var numHotelsVisible = 0;
		// Contamos el número de Hoteles que se pueden visualizar
		for ( var i = 0; i < duracion.lAgrupaciones[nH].lHoteles.length; i++) {
			if (duracion.lAgrupaciones[nH].lHoteles[i].visible == 1) {

				numHotelsVisible = numHotelsVisible + 1;
			}
		}
		totalHoteles = totalHoteles + numHotelsVisible;
	}

	if (totalHoteles > parseInt(rmbui.i18n.label.numeroTotalHoteles)) {

		totalHoteles = parseInt(rmbui.i18n.label.numeroTotalHoteles);

		moreHotels = true;

	} else {

		moreHotels = false;

	}
	return totalHoteles;
}

function poneVisiblesHoteles(duracion) {

	if (mostrarHoteles == 0) {

		for ( var i = 0; i < duracion.lAgrupaciones.length; i++) {

			contVisibles = 0;

			for ( var j = 0; j < duracion.lAgrupaciones[i].lHoteles.length; j++) {

				if (contVisibles < numHotelesPorAgrupacion[i]
						&& duracion.lAgrupaciones[i].lHoteles[j].visible == 1) {
					duracion.lAgrupaciones[i].lHoteles[j].visible = 1;
					contVisibles++;
				} else {

					duracion.lAgrupaciones[i].lHoteles[j].visible = 0;

				}

			}

		}

	}

}

function creaTablaPreciosDom(duracion) {
	// creamos el cuerpo de la tabla de precios
	var tbodyFechasPrecios = createTableBody();

	// creamos la linea de cabecera con las fechas
	var trFechasPrecios = creaLineaCabeceraPrecios(duracion.lFechas);

	// ponemos el numero de dias totales que tiene el mes que estamos mostrando
	// porque la funcion de movimiento de la tabla necesita saberlos para saber
	// cuando parar
	document.opcionesPaqueteForm.numDiasTotales.value = duracion.lFechas.length;

	// se la aniadimos al cuerpo de la tabla
	tbodyFechasPrecios.appendChild(trFechasPrecios);

	// celdas donde meteremos los precios de cada hotel
	var tdsPrecios = new Array();

	// iteramos por cada lista de agrupaciones para crear sus celdas de precios
	var codigoHotel;
	var lineasPintadas = 0;

	for ( var i = 0; i < duracion.lAgrupaciones.length; i++) {

		if (duracion.lAgrupaciones[i].visible == 1) {

			// para ir cambiando alternativamente el color de las lineas
			style = devuelveEstiloLinea(lineasPintadas);
			lineasPintadas++;

			// Si tenemos que mostrar la agrupación la pintamos, sino pintamos
			// igualmente sus hoteles
			if (duracion.lAgrupaciones[i].mostrar == 1) {

				// devuelve las celdas de nombre y regimen
				tdsFechasPrecios = creaLineaAgrupacionPrecios(
						duracion.lAgrupaciones[i], i, style);

				// lo metemos dentro de su tr
				trFechasPrecios = putTdListInTr(tdsFechasPrecios);

				// lo enganchamos a la tabla
				tbodyFechasPrecios.appendChild(trFechasPrecios);
			}

			// si la agrupacion esta desplegada pintamos sus hoteles
			if (duracion.lAgrupaciones[i].desplegado == 1) {
				// recorremos los hoteles interiores
				for ( var j = 0; j < duracion.lAgrupaciones[i].lHoteles.length; j++) {
					// si el hotel es visible pintamos sus precios
					if (duracion.lAgrupaciones[i].lHoteles[j].visible == 1) {

						for ( var k = 0; k < duracion.lAgrupaciones[i].lHoteles[j].lRegimenes.length; k++) {
							// Si el régimen es visible pintamos sus precios
							if (duracion.lAgrupaciones[i].lHoteles[j].lRegimenes[k].visible == 1) {
								style = devuelveEstiloLineaInterior();
								codigoHotel = duracion.lAgrupaciones[i].lHoteles[j].codDestino
										+ duracion.lAgrupaciones[i].lHoteles[j].codZona
										+ duracion.lAgrupaciones[i].lHoteles[j].codHotel;
								tdsPrecios = creaCeldasPrecios(
										duracion.lAgrupaciones[i].lHoteles[j].lRegimenes[k],
										codigoHotel, i, j, k, style);
								trFechasPrecios = putTdListInTr(tdsPrecios);
								tbodyFechasPrecios.appendChild(trFechasPrecios);

							}

						}

					}

				}

			}

		}

	}

	var tableFechasPrecios;
	tableLocation = document.opcionesPaqueteForm.moveTo.value;
	if (lineasPintadas == 0) {
		tbodyMens = creaMensajeNoDisponible(duracion);
		tableFechasPrecios = createTableWithIdAndLocation(tbodyMens, 'tabla', 0);
		deleteDivChildren('hotel');
	} else {
		tableFechasPrecios = createTableWithIdAndLocation(tbodyFechasPrecios,
				'tabla', tableLocation);
	}
	// eliminamos la anterior tabla
	deleteDivChildren('matriz');

	// ponemos la nueva que acabamos de construir
	linkDomToHtml('matriz', tableFechasPrecios);

	// la movemos en caso de que no este en el primer trozo
}

function creaMensajeNoDisponible(duracion) {

	var aConTilde = String.fromCharCode(225);
	var eConTilde = String.fromCharCode(233);
	var iConTilde = String.fromCharCode(237);
	var oConTilde = String.fromCharCode(243);
	var uConTilde = String.fromCharCode(250);
	var enye = String.fromCharCode(241);
	tbodyMens = createTableBody();
	trMens = createTr();
	td = createTdNoWrap('titular-peke', 450, 50, 'center', 1, 1, 35);
	td.appendChild(createText(rmbui.i18n.label.diposnibilidadHabitaciones));
	trMens.appendChild(td);

	// trAcoList = createTr();
	var acomodaciones = listaAcamodacionesPermitidas(duracion);
	// td2 = createTdNoWrap('negro-normal', 226, 25, 'center', 1, 1, 5);
	var anterior = false;
	if (acomodaciones[0] == true) {
		td.appendChild(createText(rmbui.i18n.label.individuales));
		anterior = true;
	}
	if (anterior) {
		td.appendChild(createText(', '));
		anterior = false;
	}
	if (acomodaciones[1] == true) {
		td.appendChild(createText(rmbui.i18n.label.dobles));
		anterior = true;
	}
	if (anterior) {
		td.appendChild(createText(', '));
		anterior = false;
	}
	if (acomodaciones[2] == true) {
		td.appendChild(createText(rmbui.i18n.label.triples));
		anterior = true;
	}
	if (anterior) {
		td.appendChild(createText(', '));
		anterior = false;
	}
	if (acomodaciones[3] == true) {
		td.appendChild(createText(rmbui.i18n.label.cuadruples));
		anterior = true;
	}
	if (anterior) {
		td.appendChild(createText(', '));
		anterior = false;
	}
	if (acomodaciones[4] == true) {
		td.appendChild(createText(rmbui.i18n.label.quintuples));
		anterior = true;
	}
	if (anterior) {
		td.appendChild(createText(', '));
		anterior = false;
	}

	if (acomodaciones[5] == true) {
		td.appendChild(createText(rmbui.i18n.label.sextuples));
		anterior = true;
	}

	td.appendChild(createText('.'));

	// trAcoList.appendChild(td2);

	trMens.appendChild(td);

	tbodyMens.appendChild(trMens);

	// tbodyMens.appendChild(trAcoList);

	document.opcionesPaqueteForm.numDiasTotales.value = 0;

	document.opcionesPaqueteForm.fecha.value = '';

	return tbodyMens;

}

function listaAcamodacionesPermitidas(duracion) {

	var ind, dob, tpl, cuad, quin, sext = false;

	for ( var i = 0; i < duracion.lAgrupaciones.length; i++) {
		if (duracion.lAgrupaciones[i].acomodacion.toUpperCase().charAt(0) == 'S') {

			ind = true;
		}
		if (duracion.lAgrupaciones[i].acomodacion.toUpperCase().charAt(1) == 'S') {
			dob = true;
		}
		if (duracion.lAgrupaciones[i].acomodacion.toUpperCase().charAt(2) == 'S') {

			tpl = true;
		}

		if (duracion.lAgrupaciones[i].acomodacion.toUpperCase().charAt(3) == 'S') {
			cuad = true;

		}

		if (duracion.lAgrupaciones[i].acomodacion.toUpperCase().charAt(4) == 'S') {
			quin = true;

		}

		if (duracion.lAgrupaciones[i].acomodacion.toUpperCase().charAt(5) == 'S') {
			sext = true;
		}

	}

	var results = new Array();
	results[0] = ind;
	results[1] = dob;
	results[2] = tpl;
	results[3] = cuad;
	results[4] = quin;
	results[5] = sext;

	return results;

}

function devuelvePrecioAgrupacion(agrupacion) {

	var numhabitacionesInd = document.opcionesPaqueteForm.numhabitacionesInd.value;

	var numhabitacionesDoble = document.opcionesPaqueteForm.numhabitacionesDoble.value;

	var numhabitacionesTriple = document.opcionesPaqueteForm.numhabitacionesTriple.value;

	var numhabitacionesCuad = document.opcionesPaqueteForm.numhabitacionesCuad.value;

	var numhabitacionesQuin = document.opcionesPaqueteForm.numhabitacionesQuin.value;

	var numhabitacionesSext = document.opcionesPaqueteForm.numhabitacionesSext.value;

	var result = 9999999;

	if (numhabitacionesInd > 0) {

		result = agrupacion.lPrecios[0];

	}

	if (numhabitacionesDoble > 0 && agrupacion.lPrecios[1] < result) {

		result = agrupacion.lPrecios[1];

	}

	if (numhabitacionesTriple > 0 && agrupacion.lPrecios[2] < result) {

		result = agrupacion.lPrecios[2];

	}

	if (numhabitacionesCuad > 0 && agrupacion.lPrecios[3] < result) {

		result = agrupacion.lPrecios[3];

	}

	if (numhabitacionesQuin > 0 && agrupacion.lPrecios[4] < result) {

		result = agrupacion.lPrecios[4];

	}

	if (numhabitacionesSext > 0 && agrupacion.lPrecios[5] < result) {

		result = agrupacion.lPrecios[5];

	}

	return result;

}

function creaLineaAgrupacionPrecios(agrupacion, id, style) {

	var euro = String.fromCharCode(8364);

	var tds = new Array();

	var precio;

	for (i = 0; i < agrupacion.lFechasAgrupacion.length; i++) {

		td = createTd(style, 0, 25, 'center', 1, 1, 0);

		// Si el usuario ha filtrado por regímenes se modificará el precio de la

		// agrupación

		if (selectedRegimen == 'todos') {

			precio = devuelvePrecioAgrupacion(agrupacion.lFechasAgrupacion[i]);

		} else if (selectedRegimen == 'Sólo alojamiento') {

			precio = agrupacion.lFechasAgrupacion[i].precioSoloAlojamiento;

		} else if (selectedRegimen == 'Alojamiento y desayuno') {

			precio = agrupacion.lFechasAgrupacion[i].precioAlojamientoDesayuno;

		} else if (selectedRegimen == 'Media pensión') {

			precio = agrupacion.lFechasAgrupacion[i].precioMediaPension;

		} else if (selectedRegimen == 'Pensión completa') {

			precio = agrupacion.lFechasAgrupacion[i].precioPensionCompleta;

		} else if (selectedRegimen == 'Todo incluido') {

			precio = agrupacion.lFechasAgrupacion[i].precioTodoIncluido;

		}

		precio = String(precio);

		if (precio != '-1' && precio != '-1.0') {

			link = "javascript:despliegaAgrupacion('" + id + "')";

			td.appendChild(createLink(quitaDecimal(precio) + euro, link,
					'Negro-bold-enlaces'));

		}

		tds[i] = td;

	}

	return tds;

}

function quitaDecimal(precio) {

	result = precio;

	if (precio.indexOf('.') != -1) {

		result = precio.substring(0, precio.indexOf('.'));

	}

	return result;

}

function creaTablaHotelDom(duracion) {

	// creamos el cuerpo de la tabla de hoteles

	var tbodyHotel = createTableBody();

	// creamos la linea de cabecera con los titulos

	var trHotel = creaLineaCabeceraHotel();

	// se la aniadimos al cuerpo de la tabla

	tbodyHotel.appendChild(trHotel);

	// celdas donde meteremos los hoteles de cada agrupacion

	var tdsHotel = new Array();

	// iteramos por cada lista de agrupaciones para crear sus celdas de nombre

	var lineasPintadas = 0;

	for ( var i = 0; i < duracion.lAgrupaciones.length; i++) {

		if (duracion.lAgrupaciones[i].visible == 1) {

			// para ir cambiando alternativamente el color de las lines

			var style = devuelveEstiloLinea(lineasPintadas);

			lineasPintadas++;

			// Si tenemos que mostrar la agrupación la pintamos, sino pintamos

			// igualmente sus hoteles

			if (duracion.lAgrupaciones[i].mostrar == 1) {

				// devuelve las celdas de nombre y regimen

				tdsHotel = creaLineaAgrupacionHotel(duracion.lAgrupaciones[i],
						i, style);

				trHotel = putTdListInTr(tdsHotel);

				tbodyHotel.appendChild(trHotel);

			}

			// si la agrupacion esta desplegada pintamos sus hoteles

			if (duracion.lAgrupaciones[i].desplegado == 1) {

				// recorremos los hoteles interiores

				for ( var j = 0; j < duracion.lAgrupaciones[i].lHoteles.length; j++) {

					// Obtenemos el número de regímenes a pintar

					numberOfVisibleRegimen = numberOfRegimenHotels(duracion.lAgrupaciones[i].lHoteles[j]);

					var firstHotel = true;

					// si el hotel es visible lo pintamos

					if (duracion.lAgrupaciones[i].lHoteles[j].visible == 1) {

						for ( var k = 0; k < duracion.lAgrupaciones[i].lHoteles[j].lRegimenes.length; k++) {

							// Sólo muestra los regímenes seleccionados por el

							// usuario

							if (duracion.lAgrupaciones[i].lHoteles[j].lRegimenes[k].visible == 1) {

								style = devuelveEstiloLineaInterior();

								// si es el primer regimen del hotel tenemos que

								// pintar el nombre

								// del hotel

								// y darle rowspan del tamanio de los regimenes

								//                                              

								if (firstHotel) {

									tdsHotel = creaCeldasRegimenConHotel(
											duracion.lAgrupaciones[i].lHoteles[j],
											k, style, numberOfVisibleRegimen);

									firstHotel = false;

								}

								// si no solo pintamos el regimen ya que el

								// hotel ya

								// esta pintado

								else {

									tdsHotel = creaCeldasRegimen(
											duracion.lAgrupaciones[i].lHoteles[j].lRegimenes[k],
											style);

								}

								trHotel = putTdListInTr(tdsHotel);

								tbodyHotel.appendChild(trHotel);

							}

						}

					}

				}

			}

		}

	}

	var tablehotel = createTable(tbodyHotel);

	// eliminamos la anterior tabla

	deleteDivChildren('hotel');

	// ponemos la nueva que acabamos de construir

	linkDomToHtml('hotel', tablehotel);

	if (moreHotels == true) {

		image = createImg(src, nombreLinkMostrar);

		dLink = createLinkImg(image, "javascript:cambiaMostrar();initMatrix()");

		deleteDivChildren('linkMostrar');

		linkDomToHtml('linkMostrar', dLink);

	} 
	/*
	else {
		deleteDivChildren('linkMostrar');
	}
	*/

}

// Cuenta el número de regímenes que se van a visualizar por cada Hotel

// dependiendo de la elección del usuario

function numberOfRegimenHotels(lHoteles) {

	var numberOfVisibleRegimen = 0;

	for ( var k = 0; k < lHoteles.lRegimenes.length; k++) {

		if (lHoteles.lRegimenes[k].visible == 1) {

			numberOfVisibleRegimen = numberOfVisibleRegimen + 1;

		}

	}

	return numberOfVisibleRegimen;

}

function cambiaMostrar() {

	if (mostrarHoteles == 0) {

		mostrarHoteles = 1;

		nombreLinkMostrar = rmbui.i18n.label.linkOcultar;

		src = "/pictures/ocultar-hotel-vacacional.gif";

	} else {

		mostrarHoteles = 0;

		nombreLinkMostrar = rmbui.i18n.label.linkMostrar;

		src = "/pictures/mostrar-hotel-vacacional.gif";

	}

	pressLink = true;

}

// Función que cambia de valor la variable de control de regimenes

function modifySelect() {

	changedRegimen = true;

}

function creaLineaCabeceraHotel() {

	var eConTilde = String.fromCharCode(233);

	tr = createTr();

	td = createTdNoWrap('precios-seo', 220, 25, 'center', 1, 1, 5);

	td.appendChild(createSpan(rmbui.i18n.label.alojamiento, 'precios-seo'));

	tr.appendChild(td);

	tr.appendChild(createVerticalLine());

	td = createTd('precios-seo', 80, 25, 'center', 1, 1, 5);

	td.appendChild(createText(rmbui.i18n.label.regimen));

	tr.appendChild(td);

	tr.appendChild(createVerticalLine());

	return tr;

}

function creaLineaAgrupacionHotel(agrupacion, id, style) {

	var tds = new Array();

	tds[0] = creaCeldaDescripcionAgrupacion(agrupacion, id, style);

	tds[1] = creaCeldaDescripcionRegimenAgrupacion("", style);

	return tds;

}

function creaCeldaDescripcionAgrupacion(agrupacion, id, style) {

	td = createTdNoWrap(style, 0, 25, 'left', 1, 1, 5);

	link = "javascript:despliegaAgrupacion('" + id + "')";

	// si esta desplegado le ponemos una imagen de menos

	if (agrupacion.desplegado == 1) {

		domImg = createImg('/pictures/minimizar-info.gif',
				rmbui.i18n.label.ocultarHoteles);

	}

	// si no lo esta un mas

	else {

		domImg = createImg('/pictures/maximizar-info.gif',
				rmbui.i18n.label.mostrarHoteles);

	}

	domLink = createLink(agrupacion.nombre, link, 'negro-bold');

	domLinkImg = createLinkImg(domImg, link);

	td.appendChild(domLinkImg);

	td.appendChild(createblankSpace());

	td.appendChild(domLink);

	return td;

}

function creaCeldaDescripcionRegimenAgrupacion(regimen, style) {

	td = createTd(style, 10, 25, 'center', 1, 1, 0);

	return td;

}

/**
 * Funcion que devuleve un estilo u otro en funcion de si la linea es par o
 * impar, se usa para cambiar alternativamente los colores de las lineas
 */
function devuelveEstiloLinea(posicion) {

	var bgcolor = '';

	if ((posicion % 2) == 0) {

		bgcolor = 'color-ski';

	}

	return bgcolor;

}

function creaLineaCabeceraPrecios(l_fechas) {

	tr = createTr();

	for (i = 0; i < l_fechas.length; i++) {

		if (navigator.userAgent.indexOf("Firefox") != -1) {

			var temp = navigator.userAgent.indexOf("Firefox") + 8;

			var versao = navigator.userAgent.substring(temp, temp + 6);

			if (versao.indexOf("3") != -1) {

				td = createTdNoWrap('naranja-comentario-horario', 68, 25,
						'center', 1, 1, 5);

			} else {

				td = createTdNoWrap('naranja-comentario-horario', 78, 25,
						'center', 1, 1, 5);

			}

		} else {

			td = createTdNoWrap('naranja-comentario-horario', 78, 25, 'center',
					1, 1, 5);

		}

		var fechaCompleta = displayDayWeek(l_fechas[i]) + " " + l_fechas[i]; // title
		td.setAttribute("id", l_fechas[i]);

		td.appendChild(createSpan(tratarFecha(l_fechas[i]),
				'naranja-comentario-horario', fechaCompleta));

		tr.appendChild(td);

		tr.appendChild(createVerticalLine());

	}

	return tr;

}

function tratarFecha(fecha) {

	var subFecha = fecha;

	var day_w = displayDayWeek(fecha);

	if (fecha.substring(fecha.indexOf('/'), fecha.length).indexOf('/') != -1) {

		var fin = fecha.substring(fecha.indexOf('/') + 1, fecha.length)
				.indexOf('/')
				+ fecha.indexOf('/') + 1;

		subFecha = fecha.substring(0, fin);

	}

	subFecha = day_w.substring(0, 2) + " " + subFecha;

	return subFecha;

}

/*
 * Funcion que dado un string dia/mes/aÃ±o obtiene la fecha de la clase Date
 * correspondiente
 */
function getFecha(fecha) {

	var temp = new Array();

	temp = fecha.split('/');

	var date = new Date(parseInt(temp[2], 10), parseInt(temp[1], 10) - 1,
			parseInt(temp[0], 10));

	return date;

}

/*
 * FunciÃ³n que devuelve el dia de la semana pasandole un fecha(string
 * dia/mes/aÃ±o)
 */
function displayDayWeek(fecha) {

	var date = getFecha(fecha);

	var this_day_e = new makeArray(7);

	var day;

	this_day_e[0] = rmbui.i18n.label.domingo;

	this_day_e[1] = rmbui.i18n.label.lunes;

	this_day_e[2] = rmbui.i18n.label.martes;

	this_day_e[3] = rmbui.i18n.label.miercoles;

	this_day_e[4] = rmbui.i18n.label.jueves;

	this_day_e[5] = rmbui.i18n.label.viernes;

	this_day_e[6] = rmbui.i18n.label.sabado;

	day = date.getDay();

	return this_day_e[day];

}

function makeArray(n) {

	this.length = n;

	for (k = 1; k <= n; k++) {

		this[k] = 0;

	}

	return this;

}

function creaCeldasRegimenConHotel(hotel, posRegimen, style,
		numberOfVisibleRegimen) {

	var tds = new Array();

	tdHotel = creaCeldaDescripcionHotel(hotel, style, numberOfVisibleRegimen);

	tdRegimen = creaCeldaDescripcionRegimen(hotel.lRegimenes[posRegimen], style);

	tds[0] = tdHotel;

	tds[1] = tdRegimen;

	return tds;

}

function creaCeldaDescripcionHotel(hotel, style, numberOfVisibleRegimen) {

	var aConTilde = String.fromCharCode(225);

	var oConTilde = String.fromCharCode(243);

	td = createTdNoWrap(style, 0, 25, 'left', 1, numberOfVisibleRegimen, 5);

	var id = hotel.codDestino + hotel.codZona + hotel.codHotel;

	td.setAttribute("id", id.replace(/ /g, ''));

	var codHotelCompleto = hotel.codDestino + hotel.codZona + hotel.codHotel;

	var content = hotel.nombre;

	// no cabe

	if (hotel.nombre.length + hotel.categoria.length > 26) {

		content = content.substring(0, 26 - hotel.categoria.length) + '...';

		td.appendChild(createLinkAlt(content,
				"javascript:abrirVentanaHotelIberojet('" + codHotelCompleto
						+ "','" + json.dcp + "')", 'textos-enlaces-bold',
				hotel.nombre));

	} else {

		td.appendChild(createLink(content,
				"javascript:abrirVentanaHotelIberojet('" + codHotelCompleto
						+ "','" + json.dcp + "')", 'textos-enlaces-bold'));

	}

	td.appendChild(createSpan(" " + hotel.categoria + " ",
			'naranja-comentario-horario'));

	td.appendChild(createLinkImg(createImg('/pictures/informacion.gif', 'M'
			+ aConTilde + 's informaci' + oConTilde + 'n'),
			"javascript:abrirVentanaHotelIberojet('" + codHotelCompleto + "','"
					+ json.dcp + "')"));

	return td;

}

function creaCeldaDescripcionRegimen(regimen, style) {

	td = createTdNoWrap(style, 0, 25, 'center', 1, 1, 0);

	td.appendChild(createImg(regimen.rutaImagen, regimen.title));

	return td;

}

/**
 * Funcion que se encarga del despliegue y la ocultacion de los hoteles dentro
 * de una agrupacion que recibe por parametro
 */
function despliegaAgrupacion(posAgrupacion) {

	numNigths = document.opcionesPaqueteForm.numNoches.value;

	// cambiamos el atributo desplegado de la agrupacion pulsada

	for ( var i = 0; i < json.lDuraciones.length; i++) {

		if (json.lDuraciones[i].numNoches == numNigths) {

			// si esta desplegado lo oculto

			if (json.lDuraciones[i].lAgrupaciones[posAgrupacion].desplegado == 1) {

				json.lDuraciones[i].lAgrupaciones[posAgrupacion].desplegado = 0;

				break;

			}

			// si no esta desplegado lo pinto

			else {

				json.lDuraciones[i].lAgrupaciones[posAgrupacion].desplegado = 1;

				break;

			}

		}

	}

	saveMove();

	creaMatriz();

}

function devuelveEstiloLineaInterior() {

	var bgcolor = 'color-ski-interior';

	return bgcolor;

}

/**
 * Funcion que crea las celdas de un regimen
 */
function creaCeldasRegimen(regimen, style) {

	var tds = new Array();

	tdRegimen = creaCeldaDescripcionRegimen(regimen, style);

	tds[0] = td;

	return tds;

}

/**
 * Funcion que crea las celdas que contienen los precios de la matriz
 */
function creaCeldasPrecios(regimen, codHotel, posAgrupacion, posHotel,
		posRegimen, style) {

	var euro = String.fromCharCode(8364);

	var tds = new Array();

	for (i = 0; i < regimen.lFechas.length; i++) {

		// si el precio no esta vacio lo pintamos

		if (regimen.lFechas[i].precio != '-1'
				&& regimen.lFechas[i].precio != '-1.0') {

			// si no es el precio pulsado

			if (regimen.lFechas[i].estado == 0) {

				td = createTd(style, 0, 25, 'center', 1, 1, 0);

				td.appendChild(createLinkPrice(
						quitaDecimal(regimen.lFechas[i].precio) + euro,
						"javascript:seleccion('" + posAgrupacion + "','"
								+ posHotel + "','" + posRegimen + "','" + i
								+ "');", 'Negro-bold-enlaces', codHotel,
						regimen.lFechas[i].fecha));

			}

			// si es el precio pulsado tiene otro estilo

			else {

				td = createTd('blanco-mes-calendario', 0, 25, 'center', 1, 1, 0);

				td.appendChild(document
						.createTextNode(quitaDecimal(regimen.lFechas[i].precio)
								+ euro));

				// hay que ver en que posicion esta el precio o al repintar la

				// tabla puede que saquemos un trozo en el que no esta

				if (document.getElementById('tabla') != undefined) {

					saveMove();

				}

			}

		} else {

			td = createTd(style, 0, 25, 'center', 1, 1, 0);

		}

		tds[i] = td;

	}

	return tds;

}

function saveMove() {

	if (document.layers) {

		var page = document.tabla;

	} else {

		if (document.getElementById) {

			var page = document.getElementById('tabla').style;

		} else {

			if (document.all) {

				var page = document.all.tabla.style;

			}

		}

	}

	document.opcionesPaqueteForm.moveTo.value = page.left;

}

function moveTable() {

	if (document.layers) {

		var page = document.tabla;

	} else {

		if (document.getElementById) {

			var page = document.getElementById('tabla').style;

		} else {

			if (document.all) {

				var page = document.all.tabla.style;

			}

		}

	}

	page.left = document.opcionesPaqueteForm.moveTo.value;

}

function getNumMoves(day) {

	if (day > 24) {

		result = 5;

	} else if (day > 19) {

		result = 4;

	} else if (day > 14) {

		result = 3;

	} else if (day > 9) {

		result = 2;

	} else if (day > 4) {

		result = 1;

	} else {

		result = 0;

	}

	return result;

}

/**
 * 
 * Funcion que cambia los colores de la fecha y el hotel al que pertenece el
 * precio al que se le pasa por encima
 * 
 */
function cambiaEstiloSeleccion(idHotel, idFecha) {

	var tdHotel = document.getElementById(idHotel);

	var tdFecha = document.getElementById(idFecha);

	tdHotel.setAttribute('class', 'color-ski-seleccion');

	tdHotel.className = 'color-ski-seleccion';

	tdFecha.setAttribute('class', 'color-ski-seleccion');

	tdFecha.className = 'color-ski-seleccion';

}

/**
 * 
 * Funcion que cambia los colores de la fecha y el hotel al que pertenece el
 * precio al que se le pasa por encima
 * 
 */
function cambiaEstiloNoSeleccion(idHotel, idFecha) {

	var tdHotel = document.getElementById(idHotel);

	var tdFecha = document.getElementById(idFecha);

	tdHotel.setAttribute('class', 'color-ski-interior');

	tdHotel.className = 'color-ski-interior';

	tdFecha.setAttribute('class', 'naranja-comentario-horario');

	tdFecha.className = 'naranja-comentario-horario';

}

/**
 * Se le pasa por parametro las posiciones de la eleccion y la funcion pone los
 * parametros necesarios en los inputs del form
 * 
 */
function seleccion(posAgrupacion, posHotel, posRegimen, posFecha) {

	var codHotel = "";

	var fechaPrecio;

	document.opcionesPaqueteForm.dcp.value = json.dcp;

	for ( var i = 0; i < json.lDuraciones.length; i++) {

		if (json.lDuraciones[i].numNoches == document.opcionesPaqueteForm.numNoches.value) {

			// ponemos los valores en el form

			fechaPrecio = json.lDuraciones[i].lAgrupaciones[posAgrupacion].lHoteles[posHotel].lRegimenes[posRegimen].lFechas[posFecha];

			codHotel = json.lDuraciones[i].lAgrupaciones[posAgrupacion].lHoteles[posHotel].codDestino
					+ json.lDuraciones[i].lAgrupaciones[posAgrupacion].lHoteles[posHotel].codZona
					+ json.lDuraciones[i].lAgrupaciones[posAgrupacion].lHoteles[posHotel].codHotel;

			document.opcionesPaqueteForm.codigo_hotel.value = codHotel;

			document.opcionesPaqueteForm.acomodacion.value = json.lDuraciones[i].lAgrupaciones[posAgrupacion].lHoteles[posHotel].acomodacion;

			document.opcionesPaqueteForm.codigo_destino.value = json.lDuraciones[i].lAgrupaciones[posAgrupacion].lHoteles[posHotel].codDestino;

			document.opcionesPaqueteForm.recomendacion.value = json.lDuraciones[i].lAgrupaciones[posAgrupacion].lHoteles[posHotel].lRegimenes[posRegimen].nombre;

			document.opcionesPaqueteForm.fecha.value = fechaPrecio.fecha;

			document.opcionesPaqueteForm.id_folleto.value = fechaPrecio.fol;

			document.opcionesPaqueteForm.paq.value = fechaPrecio.paq;

			document.opcionesPaqueteForm.marca.value = fechaPrecio.marca;
			//Como cada precio puede pertenecer a un DCPO diferente tenemos que guardar el precio del DCP pulsado por el cliente (DCP normales y los dCP de Vivatours)
			document.opcionesPaqueteForm.dcpSelected.value = fechaPrecio.dcp;

			// marcamos la celda como seleccionada y ponemos las demï¿½s como no

			// seleccionada

			cambiaSeleccion(i, posAgrupacion, posHotel, posRegimen, posFecha);

			// llamamos al ajax que pide el presupuesto

			PeticionPresupuesto();

			// hay que poner oculto el proveedor elegido para que lo puedan

			// saber en el call

			ponerProveedor();

			break;

		}

	}

}

// primera opcion para el precio seleccionado

// otra opcion seria guardar el precio anterior para no tener que recorrer el

// array entero

function cambiaSeleccion(posDuracion, posAgrupacion, posHotel, posRegimen,
		posFecha) {

	var fechaPrecio;

	for ( var i = 0; i < json.lDuraciones.length; i++) {

		for ( var j = 0; j < json.lDuraciones[i].lAgrupaciones.length; j++) {

			for ( var k = 0; k < json.lDuraciones[i].lAgrupaciones[j].lHoteles.length; k++) {

				for ( var l = 0; l < json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes.length; l++) {

					for ( var m = 0; m < json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[l].lFechas.length; m++) {

						fechaPrecio = json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[l].lFechas[m];

						if (posDuracion == i && posAgrupacion == j
								&& posHotel == k && posRegimen == l
								&& posFecha == m) {

							json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[l].lFechas[m].estado = 1;

						} else {
							json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[l].lFechas[m].estado = 0;

						}

					}

				}

			}

		}

	}

	creaMatriz();

}

function hideAcomodation() {

	for ( var i = 0; i < json.lDuraciones.length; i++) {

		for ( var j = 0; j < json.lDuraciones[i].lAgrupaciones.length; j++) {

			if (permiteHabitaciones(json.lDuraciones[i].lAgrupaciones[j])) {

				json.lDuraciones[i].lAgrupaciones[j].visible = 1;

			} else {

				json.lDuraciones[i].lAgrupaciones[j].visible = 0;

			}

			for ( var k = 0; k < json.lDuraciones[i].lAgrupaciones[j].lHoteles.length; k++) {

				if (permiteHabitaciones(json.lDuraciones[i].lAgrupaciones[j].lHoteles[k])) {

					json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].visible = 1;

				} else {

					json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].visible = 0;

				}

			}

		}

	}

}

// Realiza un filtro de la matriz dependiendo del régimen que seleccione el
// usuario

function hideRegimenAvailable() {
	var select = document.getElementById("regimenes");
	var selected = select.selectedIndex;
	selectedRegimen = select.options[selected].value;
	// Variables para saber si hay que mostrar los hoteles y las acomodaciones
	var visbleHotels = false;
	var visbleAcomodation = false;
	var numTotalHotel = 0;

	for ( var i = 0; i < json.lDuraciones.length; i++) {
		for ( var j = 0; j < json.lDuraciones[i].lAgrupaciones.length; j++) {
			for ( var k = 0; k < json.lDuraciones[i].lAgrupaciones[j].lHoteles.length; k++) {
				for ( var h = 0; h < json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes.length; h++) {
					var regimen = json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[h];
					if (selectedRegimen == 'todos') {
						regimen.visible = 1;
						numTotalHotel = numTotalHotel + 1;
						// Si el hotel tiene dicho régimen hay que mostrarlo
						visbleHotels = true;

					} else if (regimen.title == selectedRegimen) {

						regimen.visible = 1;

						// Si el hotel tiene dicho régimen hay que mostrarlo

						visbleHotels = true;

					} else {

						regimen.visible = 0;

					}

				}

				// Si el hotel no tiene ningún régimen igual al solicitado en el

				// filtro de regímenes no puede aparecer en la matriz

				if (!visbleHotels) {

					json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].visible = 0;

				} else {

					// Si hay algún hotel que mostrar, también mostraremos las

					// acomodaciones

					visbleAcomodation = true;

				}

				// Inicializamos otra vez las variables

				visbleHotels = false;

			}

			// Si la acomodación no tiene ningún hotel que mostrar, tampoco

			// mostraremos la acomodación

			if (!visbleAcomodation) {

				json.lDuraciones[i].lAgrupaciones[j].visible = 0;

			}

			// Si el usuario filtra por todos los regímenes no tiene que salir

			// la agrupación

			// else if (selectedRegimen == 'todos') {

			// json.lDuraciones[i].lAgrupaciones[j].visible = 0;

			// }

			// Inicializamos otra vez las variables

			visbleAcomodation = false;

			// Cuando el usuario filtre por "todos" los regímenes tiene que

			// salir las agrupaciones desplegadas

			if (selectedRegimen == 'todos') {

				json.lDuraciones[i].lAgrupaciones[j].desplegado = 1;

				visbleHotels = true;

			}

			// Si mostramos todos los hoteles tenemos que mostrar la agrupación

			if (mostrarHoteles == 1) {

				json.lDuraciones[i].lAgrupaciones[j].mostrar = 1;

			} else {

				json.lDuraciones[i].lAgrupaciones[j].mostrar = 0;

			}

		}

	}

	if (numTotalHotel > parseInt(rmbui.i18n.label.numeroTotalHoteles)) {

		image = createImg(src, nombreLinkMostrar);

		var dlink = createLink(nombreLinkMostrar,
				"javascript:cambiaMostrar(); initMatrix();",
				'textos-enlaces-bold');

		deleteDivChildren('linkMostrar');

		linkDomToHtml('linkMostrar', dlink);

	} else {

		deleteDivChildren('linkMostrar');

	}

}

// Obtenemos todos los regímenes disponibles de todos los hoteles
function obtainRegimenAvailable(array) {

	// Inicilizamos el array para que cada vez que se cambie el mes y el origen

	// se vuelva a rellenar con los regímenes de ese mes y origen

	array = new Array();

	if (firstTime) {

		var found = false;

		for ( var i = 0; i < json.lDuraciones.length; i++) {

			for ( var j = 0; j < json.lDuraciones[i].lAgrupaciones.length; j++) {

				for ( var k = 0; k < json.lDuraciones[i].lAgrupaciones[j].lHoteles.length; k++) {

					for ( var h = 0; h < json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes.length; h++) {

						var regimen = json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[h].title;

						// Comprobamos que el régimen no esté ya en la lista.

						for ( var arr = 0; arr < array.length; arr++) {

							if (array[arr] == regimen) {

								found = true;

								break;

							}

						}

						// Si el régimen es nuevo lo añadimos

						if (!found) {

							array[array.length] = regimen;

						}

						found = false;

					}

				}

			}

		}

		// si sólo tiene un regímen el filtro no lo añadimos a la lista

		// desplegable

		if (array.length > 1) {

			fillRegimenCombo(array);

		}

		firstTime = false;

	}

}

function fillRegimenCombo(array) {

	var select = document.getElementById("regimenes");

	// Borramos el contenido del Select para luego posteriormente volver a

	// insertar el contenido del nuevo array.

	// Eliminaremos los options del combo cuando éste tenga más options que no

	// el de por defecto ("Todos")

	if (select.length > 1) {

		for ( var i = select.length - 1; i >= 1; i--) {

			select.options[i] = null;

		}

	}

	array = arrangeOptions(array);

	for ( var i = 0; i < array.length; i++) {

		select.options[select.length] = new Option(array[i], array[i]);

	}

}

function arrangeOptions(array) {

	var arrangedArray = new Array();

	searchByRegimen(arrangedArray, array, 'Sólo alojamiento');

	searchByRegimen(arrangedArray, array, 'Alojamiento y desayuno');

	searchByRegimen(arrangedArray, array, 'Media pensión');

	searchByRegimen(arrangedArray, array, 'Pensión completa');

	searchByRegimen(arrangedArray, array, 'Todo incluido');

	return arrangedArray;

}

function searchByRegimen(arrangedArray, array, regimen) {

	for ( var i = 0; i < array.length; i++) {

		if (array[i] == regimen) {

			arrangedArray[arrangedArray.length] = array[i];

			break;

		}

	}

}

function permiteHabitaciones(hotel) {

	var numhabitacionesInd = document.opcionesPaqueteForm.numhabitacionesInd.value;

	var numhabitacionesDoble = document.opcionesPaqueteForm.numhabitacionesDoble.value;

	var numhabitacionesTriple = document.opcionesPaqueteForm.numhabitacionesTriple.value;

	var numhabitacionesCuad = document.opcionesPaqueteForm.numhabitacionesCuad.value;

	var numhabitacionesQuin = document.opcionesPaqueteForm.numhabitacionesQuin.value;

	var numhabitacionesSext = document.opcionesPaqueteForm.numhabitacionesSext.value;

	var result = true;

	if (numhabitacionesInd != 0 && hotel.acomodacion.substring(0, 1) == 'N') {

		result = false;

	}

	if (numhabitacionesDoble != 0 && hotel.acomodacion.substring(1, 2) == 'N') {

		result = false;

	}

	if (numhabitacionesTriple != 0 && hotel.acomodacion.substring(2, 3) == 'N') {

		result = false;

	}

	if (numhabitacionesCuad != 0 && hotel.acomodacion.substring(3, 4) == 'N') {

		result = false;

	}

	if (numhabitacionesQuin != 0 && hotel.acomodacion.substring(4, 5) == 'N') {

		result = false;

	}

	if (numhabitacionesSext != 0 && hotel.acomodacion.substring(5) == 'N') {

		result = false;

	}

	return result;

}

function aplicarFiltros() {
	aplicarDescuento();

	hideAcomodation();

	// Filtro de regímenes

	hideRegimenAvailable();

}

function cambiaMes() {
	pax = 0;
	document.opcionesPaqueteForm.moveTo.value = 0;
	origen = document.opcionesPaqueteForm.origen.value;
	mes = document.opcionesPaqueteForm.meses.value;
	var provee = "IBS";

	// Si el paquete es de IberSky tenemos que calcular los pasajeros

	// y tenemos que lanzar una petición cada vez que se filtra por pasajeros

	if (document.opcionesPaqueteForm.provName.value == provee) {
		pax = numHabitacionesRequested();

	}

	asyncronus = false;

	if (isDefined("json_" + origen + '_' + mes)
			&& document.opcionesPaqueteForm.provName.value != provee) {

		if ("json_" + origen + '_' + mes != "") {

			eval("json = json_" + origen + '_' + mes);

			asyncronus = false;

		}

	} else
	// Si no se ha presionado el link, ni se ha filtrado por regimen ni por
	// hotel hacemos una nueva petición
	if (!pressLink && !changedRegimen && !searchHotel) {
		// no existia tenemos que hacer llamada asincrona para recuperarla

		getOrign();

		asyncronus = true;

	}

	// Reiniciamos el valor de la variable

	pressLink = false;

	changedRegimen = false;

	searchHotel = false;

	return asyncronus;

}

// Pasamos por todo el flujo las variables de cantidadDescuento, tipoDescuento

// para poder utilziarlas en la funciï¿½n de aplicarDescuento.

function initMatrix(discount, typeDiscount) {
	cantidadDescuento = discount;

	tipoDescuento = typeDiscount;

	// si la llamada ha sido asincrona no hay que aplicar filtros ni repintar ya

	// que todavÃ­a no tenemos los datos

	// se harÃ¡ al recibir la respuesta del ajax en la clase asyncronusJson

	// si la variable ya la tenÃ­amos aplicamos y repintamos directamente

	if (!cambiaMes()) {
		aplicarFiltros();
		creaMatriz();
	}

}

/*
 * Funcion que mira la url para ver si viene un parametros de mes que se quiera
 * mostrar y actualiza el combo de meses
 */
function getParam(name) {

	result = '';

	var regexS = "[\\?&]" + name + "=([^&#]*)";

	var regex = new RegExp(regexS);

	var url = window.location.href;

	var results = regex.exec(url);

	if (results != null) {

		result = results[1];

	}

	return result;

}

/*
 * Esconde o enseï¿½a los botones de moviemiento de la tabla
 */
function actualizaComboMes() {
	mes = getParam('mes');

	if (mes != '') {

		for (i = 0; i < document.opcionesPaqueteForm.meses.options.length; i++) {

			if (document.opcionesPaqueteForm.meses.options[i].value == mes) {

				document.opcionesPaqueteForm.meses.options.selectedIndex = i;

			}

		}

	}
}

/*
 * Esconde o enseï¿½a los botones de moviemiento de la tabla
 */
function refreshButton() {
	if (document.layers) {

		var page = document.tabla;

		anteriores = document.anteriores;

		siguientes = document.siguientes;

	} else {

		if (document.getElementById) {

			var page = document.getElementById('tabla').style;

			var anteriores = document.getElementById('anteriores').style;

			var siguientes = document.getElementById('siguientes').style;

		} else {

			if (document.all) {

				var page = document.all.tabla.style;

				var anteriores = document.all.anteriores.style;

				var siguientes = document.all.siguientes.style;

			}

		}

	}

	// tableLocation = page.left;

	numDays = document.opcionesPaqueteForm.numDiasTotales.value;

	// tableLocation = tableLocation.substring(0, tableLocation.indexOf('p'));

	tableLocation = parseInt(page.left);

	if (tableLocation == 0) {

		anteriores.display = "none";

	} else {

		anteriores.display = "";

	}

	siguientes.display = "";

	if (numDays <= 5 && tableLocation == 0) {

		siguientes.display = "none";

	} else if (numDays <= 9 && ((tableLocation < 0) && (tableLocation >= -336))) {

		siguientes.display = "none";

	} else if (numDays <= 13
			&& ((tableLocation < -336) && (tableLocation >= -672))) {

		siguientes.display = "none";

	} else if (numDays <= 17
			&& ((tableLocation < -672) && (tableLocation >= -1008))) {

		siguientes.display = "none";

	} else if (numDays <= 21
			&& ((tableLocation < -1008) && (tableLocation >= -1344))) {

		siguientes.display = "none";

	} else if (numDays <= 25
			&& ((tableLocation < -1344) && (tableLocation >= -1680))) {

		siguientes.display = "none";

	} else if (numDays <= 29
			&& ((tableLocation < -1680) && (tableLocation >= -2016))) {

		siguientes.display = "none";

	} else if (numDays <= 32
			&& ((tableLocation < -2016) && (tableLocation >= -2184))) {

		siguientes.display = "none";

	}
}

/*
 * funcion que pone el proveedor de manera oculta para que lo puedan ver en el
 * call
 */
function ponerProveedor() {

	proveedor = document.opcionesPaqueteForm.marca.value;

	deleteDivChildren('proveedorElegido');

	huecoProveedor = document.getElementById('proveedorElegido');

	huecoProveedor.appendChild(createSpan(proveedor, ''));

}

function aplicarDescuento() {

	for ( var i = 0; i < json.lDuraciones.length; i++) {

		for ( var j = 0; j < json.lDuraciones[i].lAgrupaciones.length; j++) {

			if (cantidadDescuento != 'null') {

				for ( var n = 0; n < json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion.length; n++) {

					// Variables que indican si los precios por

					// regimen/agrupación se han descontado

					var descuentoSoloAlojamiento = true;

					var descuentoAlojamientoDesayuno = true;

					var descuentoMediaPension = true;

					var descuentoPensionCompleta = true;

					var descuentoTodoIncluido = true;

					// Variables que contienen los precios por

					// regimen/agrupacion antes de ser descontados

					var precioSoloAlojamiento = json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioSoloAlojamiento;

					var precioAlojamientoDesayuno = json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioAlojamientoDesayuno;

					var precioMediaPension = json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioMediaPension;

					var precioPensionCompleta = json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioPensionCompleta;

					var precioTodoIncluido = json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioTodoIncluido;

					// Obtenemos el descuento para el precio de cada agrupación

					for ( var m = 0; m < json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].lPrecios.length; m++) {

						var precio = json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].lPrecios[m];

						var precioSinDescontar = json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].lPreciosSinDescontar[m];

						if (precio != -1) {

							if (precio == precioSinDescontar) {

								precio = calculateDiscountPrice(precio);

								// Se calcula el descuento por cada precio de

								// regimen/agrupacion

								if (precioSoloAlojamiento != -1
										&& descuentoSoloAlojamiento) {

									precioSoloAlojamiento = calculateDiscountPrice(precioSoloAlojamiento);

									descuentoSoloAlojamiento = false;

								}

								if (precioAlojamientoDesayuno != -1
										&& descuentoAlojamientoDesayuno) {

									precioAlojamientoDesayuno = calculateDiscountPrice(precioAlojamientoDesayuno);

									descuentoAlojamientoDesayuno = false;

								}

								if (precioMediaPension != -1
										&& descuentoMediaPension) {

									precioMediaPension = calculateDiscountPrice(precioMediaPension);

									descuentoMediaPension = false;

								}

								if (precioPensionCompleta != -1
										&& descuentoPensionCompleta) {

									precioPensionCompleta = calculateDiscountPrice(precioPensionCompleta);

									descuentoPensionCompleta = false;

								}

								if (precioTodoIncluido != -1
										&& descuentoTodoIncluido) {

									precioTodoIncluido = calculateDiscountPrice(precioTodoIncluido);

									descuentoTodoIncluido = false;

								}

								// Son los precios de las agrupaciones de los

								// hoteles

								json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].lPrecios[m] = String(precio);

							}

						}

					}

					// Introducimos los datos reales de cada agrupación

					json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioSoloAlojamiento = precioSoloAlojamiento;

					json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioAlojamientoDesayuno = precioAlojamientoDesayuno;

					json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioMediaPension = precioMediaPension;

					json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioPensionCompleta = precioPensionCompleta;

					json.lDuraciones[i].lAgrupaciones[j].lFechasAgrupacion[n].precioTodoIncluido = precioTodoIncluido;

				}

			}

			for ( var k = 0; k < json.lDuraciones[i].lAgrupaciones[j].lHoteles.length; k++) {

				for ( var z = 0; z < json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes.length; z++) {

					if (cantidadDescuento != 'null') {

						for ( var h = 0; h < json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[z].lFechas.length; h++) {

							var precio = json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[z].lFechas[h].precio;

							var precioSinDescontar = json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[z].lFechas[h].precioSinDescontar;

							if (precio != -1) {

								// Si lso precios de la matriz no han sido

								// descontados

								if (precio == precioSinDescontar) {

									precio = calculateDiscountPrice(precio);

									// Estos son los precios de cada casilla de

									// la matriz

									json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].lRegimenes[z].lFechas[h].precio = String(precio);

								}

							}

						}

					}

				}

			}

		}

	}

}

function calculateDiscountPrice(precio) {
	if (tipoDescuento == 0) {
		var descuento = cantidadDescuento / 100;
		var cantidadADescontar = precio * descuento;
		// Indicamos que como mï¿½ximo hay dos
		// decimales
		cantidadADescontar = cantidadADescontar.toFixed(0);
		precio = precio - cantidadADescontar;
	} else // Si el tipo de descuento es 1 es
	// una
	// cantidad exacta
	if (tipoDescuento == 1) {
		cantidadADescontar = cantidadDescuento;
		precio = precio - cantidadADescontar;
	}
	return precio;

}

// Función que muestra el cuadro para filtrar por hotel cuando pulsas la palabra
// aquí.
function mostrarHotel() {
	document.getElementById("hotelSearchBox").style.display = 'block';
}

// Función que hace que desaparezca el cuadro para filtrar por hotel cuando
// pulsas la palabra cerrar.
function cerrarHotel() {
	document.getElementById("hotelSearchBox").style.display = 'none';
}

// Función que muestra la nueva frase cuando se encuentra el hotel
function mostrarFraseTodosHoteles() {
	document.getElementById("fraseMostrarTodosHoteles").style.display = 'block';
}

// Función que oculta la segunda frase y muestra la primera
function ocultarFraseMostrarTodosHoteles() {
	document.getElementById("fraseMostrarTodosHoteles").style.display = 'none';
	document.getElementById("fraseOriginal").style.display = 'block';
}

// Función que oculta la frase original cuando aparece el hotel que busca el
// usuario.
function ocultarFraseOriginal() {
	document.getElementById("fraseOriginal").style.display = 'none';
}

// Función que compara una cadena con otra y pasa el contenido a mayúsculas
function nameContainsHotel(nameHotelUsuario, nameHotelAgrupacion) {

	nameHotelAgrupacion = ignoreAccent(nameHotelAgrupacion.toUpperCase());
	nameHotelUsuario = ignoreAccent(nameHotelUsuario.toUpperCase());
	if (nameHotelAgrupacion.toUpperCase().indexOf(
			nameHotelUsuario.toUpperCase()) != -1) {
		return true;
	} else {
		return false;

	}

}

function ignoreAccent(nombre) {
	var name = nombre.replace("Á", "A");
	name = name.replace("É", "E");
	name = name.replace("Í", "I");
	name = name.replace("Ó", "O");
	name = name.replace("Ú", "U");
	return name;

}

// Función que realiza un filtro de la matriz por nombre de hotel
function filtroporHotel() {

	searchHotel = true;

	var coincide = false;

	var numTotalHotel = 0;

	var nombre_hotel = document.opcionesPaqueteForm.cuadroNombreHotel.value;

	for ( var i = 0; i < json.lDuraciones.length; i++) {

		for ( var j = 0; j < json.lDuraciones[i].lAgrupaciones.length; j++) {

			json.lDuraciones[i].lAgrupaciones[j].mostrar = 0;

			for ( var k = 0; k < json.lDuraciones[i].lAgrupaciones[j].lHoteles.length; k++) {

				var hotelAgrupacion = json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].nombre;

				if (nameContainsHotel(nombre_hotel, hotelAgrupacion)) {

					json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].visible = 1;

					numTotalHotel = numTotalHotel + 1;

					coincide = true;

				} else {

					json.lDuraciones[i].lAgrupaciones[j].lHoteles[k].visible = 0;

				}

			}

		}

	}

	if (!coincide) {

		// Si no encuentra el hotel en cuestión construye la matriz otra vez
		initMatrix('null', 'null');
		// y añade nueva frase y hotel añadido por el usuario
		document.getElementById("noHotel").innerHTML = "'"
				+ document.opcionesPaqueteForm.cuadroNombreHotel.value + " '.";
		document.getElementById("frasaNoHayHotel").style.display = '';
		document.getElementById("fraseOriginal").style.display = '';
		cerrarHotel("botonBuscar");
	} else {

		// mostrar todos los hoteles que coincidan con el nombre buscado y
		// vuelve a salir la frase original
		creaMatriz();
		document.getElementById("frasaNoHayHotel").style.display = 'none';
		document.getElementById("noHotel").innerHTML = "";
		cerrarHotel("botonBuscar");
		ocultarFraseOriginal();
		mostrarFraseTodosHoteles();

	}
	deleteDivChildren('linkMostrar');
}

//Versi�n del js 0.94.e

/**
 * al cambiar el origen y comprobar que no tenemos su json hacemos una llamada
 * asincrona al servidor para que nos lo sirva
 */
function getOrign()
{
	
    putWaitImg();
    var codOrigen = document.opcionesPaqueteForm.origen.value;
    var mes = document.opcionesPaqueteForm.meses.value;
    var dcp = document.opcionesPaqueteForm.dcp.value;
    var numNoches = document.opcionesPaqueteForm.numNoches.value;
    var folletos = document.opcionesPaqueteForm.folletos.value;
    var codDestino = document.opcionesPaqueteForm.codDestino.value;
    /* nICircuit significa que no es un circuito.*/
    var circuit = "nICircuit";
    var asociatedDcp = document.opcionesPaqueteForm.asociatedDcp.value;
    
    dojo.xhrGet({
        content: {
            codOrigen: codOrigen,
            dcp: dcp,
            mes: mes,
            numNoches: numNoches,
            folletos: folletos,
            codDestino: codDestino,
            pax: pax,
            circuit:circuit,
            asociatedDcp:asociatedDcp
        },
        error: function()
        {
            putErrorMessage();
        },
        url: '/vacacional/servlet/MatrixJsonServlet.ajax',
        handleAs: 'json',
        load: function(responseObject, ioArgs)
        {
            // si hemos recibido la respuesta correctamente
            if (responseObject != null) {
                json = window["json_" + origen + '_' + mes] = responseObject;
				// Obtenemos los regímenes que se visualizarán en el filtro de regímenes
				firstTime=true;
				obtainRegimenAvailable(array);
				aplicarFiltros();
                creaMatriz();
            } else {
                putErrorMessage();
            }
        },
        preventCache:true
    });
}


/**
 * metodo que pone la img de cargando mientras se recibe la respuesta asincrona
 */
function putWaitImg()
{
    deleteDivChildren('imgCargando');
    // quitamos los botones
    var anteriores = document.getElementById('anteriores').style;
    var siguientes = document.getElementById('siguientes').style;
    anteriores.display = "none";
    siguientes.display = "none";
    // ponemos imagen de espera
    img = createImg("/pictures/animacion-espera-salida.gif", "Cargando precios");
    deleteDivChildren('CircuitTabla');
    deleteDivChildren('hotel');
    deleteDivChildren('matriz');
    linkDomToHtml('imgCargando', img);
    deleteDivChildren('linkMostrar');
}
/**
 * metodo que pone el mensaje de error si el json no viene
 */
function putErrorMessage()
{
    deleteDivChildren('imgCargando');
    // quitamos los botones
    var anteriores = document.getElementById('anteriores').style;
    var siguientes = document.getElementById('siguientes').style;
    anteriores.display = "none";
    siguientes.display = "none";
    // ponemos imagen de espera
    span = createSpan(rmbui.i18n.label.disponibilidad, "negro-bold");
    deleteDivChildren('hotel');
    deleteDivChildren('matriz');
    linkDomToHtml('imgCargando', span);
    deleteDivChildren('linkMostrar');
}
/**
 * Funcion que calcula el numero de habitaciones cuando Marca = Iberski.
 * @return las habitaciones a pedir cuando la marca es Iberski.
 */
function numHabitacionesRequested()
{
	var totalHabitaciones;
	if (sumaHabitciones() == 1)
	{
		if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value) != 0)
		{
			totalHabitaciones = 1;
		}
		if (parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value) != 0)
		{
			totalHabitaciones = 2;
		}
		if (parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) != 0)
		{
			totalHabitaciones = 3;
		}
		if (parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) != 0)
		{
			totalHabitaciones = 4;
		}
		if (parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value) != 0)
		{
			totalHabitaciones = 5;
		}
		if (parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value) != 0)
		{
			totalHabitaciones = 6;
		}
	}
	/**
	 * El numero de habitaciones es superior que una.
	 * 
	 */
	else
	{
		/**
		 * Ver que las habitaciones pedidas son todas del mismo tipo esto es o
		 * todas individuales, o dobles, triples, cuadruples . . .
		 */
		totalHabitaciones = checkAcomodationTypes();
	}
	return totalHabitaciones;
}
/**
 * Funcion que calcula el somatorio de las habitaciones.
 * @return Numero total de habitaciones.
 */
function sumaHabitciones()
{
	var total = parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)
	+ parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value)
	+ parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value)
	+ parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value)
	+ parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value)
	+ parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value);
	
	return total;
}
/**
 * Funcion para ver que tipos de habitaciones han sido seleccionadas.
 * @return el pax correspondiende al tipo de habitacion.
 */
function checkAcomodationTypes()
{
	var nPax = 0;
	if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)!= 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value) == 0)
	{
		nPax = 1;
	}
	else if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value) != 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value) == 0)
	{
		nPax = 2;
	}
	else if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) != 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value) == 0)
	{
		nPax = 3;
	}
	else if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) != 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value) == 0)
	{
		nPax = 4;
	}
	else if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value)!= 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value) == 0)
	{
		nPax = 5;
	}
	else if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesSext.value) != 0)
	{
		nPax = 6;
	}
	else if (parseInt(document.opcionesPaqueteForm.numhabitacionesInd.value)== 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesCuad.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesQuin.value) == 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesDoble.value)!= 0
			&& parseInt(document.opcionesPaqueteForm.numhabitacionesTriple.value) != 0) 
	{
		nPax = 2;
	}
	else
	{
		nPax = 0;
	}
	return nPax;
}

/*
 *
 *	Funciones para el efecto de movimiento de la matriz	
 *	recibe la direccion hacia la que tiene que mover la tabla
 *	el tamaï¿½o de la celda de precios, las celdas que se quieren mover
 *	y el numero de celdas total de la tabla
 *
 */
function verScrollStep(dir, prizeCeldTam, celdsMove) 
{
	/*var scrollStep = "";
	if (navigator.userAgent.indexOf("Firefox") != -1) 
	{
		var temp = navigator.userAgent.indexOf("Firefox") + 8;
		var versao = navigator.userAgent.substring(temp, temp + 6);
		if (versao.indexOf("3.") != -1) 
		{
			prizeCeldTam = "84";
		} 
		else 
		{
			prizeCeldTam = "86";
		}
	 }*/
	// valores por defecto
	numCelds = document.opcionesPaqueteForm.numDiasTotales.value;
	direction = "left";
	speed = 82;
	var spd = parseInt(prizeCeldTam) * parseInt(celdsMove);
	var tam = (parseInt(prizeCeldTam) * parseInt(numCelds) - parseInt(prizeCeldTam) * 5)* (-1);
	scrolltimer = null;
	if (document.layers) {
		var page = document.tabla;
	} else {
		if (document.getElementById) {
			var page = document.getElementById('tabla').style;
		} else {
			if (document.all) {
				var page = document.all.tabla.style;
			}
		}
	}

	direction = dir;
	speed = parseInt(spd);
	var x_pos = parseInt(page.left);
	var tablaWidth = parseInt(page.width);
	if (direction == "rigth" && x_pos > tam) {	
		//page.left = (x_pos - (speed));
		
		var attrpageleft = (x_pos - (speed));
		if (attrpageleft<=tam){
			page.left = tam;
			/*
             * var siguientes =
             * eval("document.getElementById('siguientes').style");
             * siguientes.display = "none";
             */
		}else{
			page.left = attrpageleft;
		}
		
	} else {
		if (direction == "left" && x_pos < 0) 
		{
			//page.left = (x_pos + (speed));
			var attrpageright = (x_pos + (speed));
			if (attrpageright > 0)
			{
				page.left = 0;
			}
			else
			{
				page.left = attrpageright;
			}
		} /*else {
			if (direction == "left") {
				page.left = 0;
			}
		}*/
	}
	
}

var mes_Ano;
var codOrig;
var allowDiscount = false;
var discount;
var typeDiscount;
/**
 *  Hacer la llamada para crear el json segun origen y mes
 * @return
 */
function CargaCirtuito(isCircuit,codOrigen,mes,dcp, discounts, typeDiscounts)
{
	var arrDeOrigenes = new Array(document.opcionesPaqueteForm.origen.length);
	var folletos = document.opcionesPaqueteForm.folletos.value;
	var nameHotel = document.opcionesPaqueteForm.nameHotel.value;
	for(var i = 0; i < document.opcionesPaqueteForm.origen.length; i++)
	{
		arrDeOrigenes[i] = document.opcionesPaqueteForm.origen.options[i].value;
	}
	putWaitImg();
	mes_Ano = mes;
	codOrig = codOrigen;
	discount = discounts;
	typeDiscount = typeDiscounts;
	var url = '/vacacional/servlet/MatrixJsonServlet.ajax?codOrigen='
			+ codOrigen + '&mes=' + mes + '&dcp=' + dcp + '&Origenes=' + arrDeOrigenes
			+ '&circuit=' + isCircuit + '&folletos=' + folletos + '&nameHotel=' + nameHotel;
	if (window.ActiveXObject) 
	{
		httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	} 
	else if (window.XMLHttpRequest) 
	{
		httpRequest = new XMLHttpRequest();
	}
	httpRequest.open("GET", url, true);
	httpRequest.onreadystatechange = function() 
	{
		processCircuitRequest();
	};
	httpRequest.send(null);
}
function processCircuitRequest() 
{
	if (httpRequest.readyState == 4) 
	{
		if (httpRequest.status == 200) 
		{
			var profileJson = httpRequest.responseText;
			/* Verficar que el descuento y el tipo de descuento contienen algo.*/
			if (discount != "undefined" && typeDiscount != "undefined")
			{
				/* Verificar que existe descuento aplicar.*/
				if (discount != "null")
				{
					/* Si allowDiscount == true, se tiene que aplicar descuento.*/
					allowDiscount = true;
				}
				else
				{
					/* Si allowDisocunt == false, no hay descuento para aplicar. */
					allowDiscount = false;
				}
				
			}
			else
			{
				/* Si el descuento y el tipo de descuento no contienen nada, no se aplica ningun descuento.*/
				allowDiscount = false;
			}
			showTable(profileJson,codOrig,mes_Ano,0,6);	
		}	
	}
}

var jsonGlobal;
// Simbolo del euro.
var euro = String.fromCharCode(8364);
var origFecha = null;
var origen = null;
var mesAno = null;
// Numero de colunas de la matriz sin incluir el nombre.
var salto = 6;
var tdSelect = 0;
var dif = 0;
var deplaza ;

/**
 * Cada linea de el json viene en el formato var ORI_mmaaaa = {. . .} en este
 * metodo escojemos la linea el json (profileJson) que correponde al origen
 * (orig) y la fecha (me_an, mes y año) seleccionada. Retorna el json de un
 * determinado origen y fecha.
 * 
 * @param profileJson es el json completo para un mes para todos los origenes.
 * @param orig es el origen deseado.
 * @param me_an el mes y año concatenados.
 * 
 * @return un json para el origen y fecha seleccionados.
 */
function watchOriDate(profileJson, orig, me_an) 
{
	var spl = "var ";
	var result;
	var found = false;
	profileJson = profileJson.split(spl);
	for ( var j = 0; j < profileJson.length; j++) 
	{
		/* Va percorriendo el json hasta encontar el que empieza por el origen+fecha.*/
		if (profileJson[j].startsWith(orig + me_an)) 
		{
			result = profileJson[j];
			found=true;
		}
	}
	if(!found)
	{
		putErrorMessage();
	}
	return result;
}

/**
 * Metodo para la paginacion de la matriz sea hace adelante o hace a tras.
 * @param side direccion de la paginacion right - hace adelante, left hace a tras.
 * @param step Numero de dias que salta por paginacion.
 * @return
 */
function moreDays(side, step) 
{
	tdSelect = 0;
	/* Mostrar seguientes.*/
	if (side == 'right') 
	{
		dif++;
		salto = salto + step;
		showTable(null, origen, mesAno, (salto - step), salto);
	}
	/* Mostrar anteriores. */
	else if (side == 'left') 
	{
		dif--;
		salto = salto - step;
		showTable(null, origen, mesAno, (parseInt(salto) - parseInt(step)),
				salto);
	}
}
function drawMatriz(jsonOrigeFecha, pointInf, pointSup, mar) 
{
	deplaza = mar;
	var linea = createHeaderTr();
	var tabela = document.createElement('table');
	var tbody = document.createElement('tbody');
	tabela.appendChild(tbody);

	for ( var i = pointInf; i < pointSup; i++) 
	{

		if (i % 6 == 0) 
		{
			var colun = createHeaderTD('precios-seo');

			linea.appendChild(colun);
			tbody.appendChild(linea);
		}
		var col = createVerticalLine();
		linea.appendChild(col);
		var dateComplete = displayDayWeekCirc(origFecha.allDates[i-mar].Fecha);
		
		var fechaFormateada = origFecha.allDates[i-mar].Fecha;
		fechaFormateada = fechaFormateada.substring(0, 5);
		var dateDayAndNumber = dateComplete.substring(0,2)+" "+fechaFormateada.substring(0, 5);
		var columnTitle = dateComplete + " " + origFecha.allDates[i-mar].Fecha;
		var colun = createTD('naranja-comentario-horario', dateDayAndNumber, columnTitle);
		linea.appendChild(colun);
	}
	var col = createVerticalLine();
	linea.appendChild(col);
	tbody.appendChild(linea);

	var linea = createHeaderTr();
	for ( var i = pointInf; i < pointSup; i++) 
	{
		if (i % 6 == 0) 
		{
			var linea = createHeaderTr();
			var colun = createTdFirstColumn('color-ski-interior',
					origFecha.allDates[i-deplaza].Name);
			linea.appendChild(colun);
			tbody.appendChild(linea);
		}
		/* Ver si el paquete permite hacer descuentos.*/
		if (allowDiscount)
		{
			/* Ver el tipo de descuento a aplicar, si el tipo es igual a 0 entonces descuento por % .*/
			if (typeDiscount == 0)
			{
				/* Calcular el descuento a aplicar y réstalo al precio.*/
				var price = origFecha.allDates[i-deplaza].Precio;
				var totalDiscount = price * (discount / 100);
				var priceWithDiscount = price - totalDiscount;
				/* Pintar en la matriz el precio con el descuento.*/
				var colun = createTdOtherColumn('color-ski-interior', priceWithDiscount.toFixed(0) , origFecha, i);
			}
			else
			{
				/* Si el descuento es de otro tipo diferente al de porcentaje.*/
				var colun = createTdOtherColumn('color-ski-interior', origFecha.allDates[i-deplaza].Precio, origFecha, i);
			}
		}
		else
		{
			/* Si no se aplica ningun tipo de descuento.*/
			var colun = createTdOtherColumn('color-ski-interior', origFecha.allDates[i-deplaza].Precio, origFecha, i);
		}
		linea.appendChild(colun);
	}
	tbody.appendChild(linea);
	document.getElementById("CircuitTabla").appendChild(tabela);
	deleteDivChildren('imgCargando');
}

function displayDayWeekCirc(fecha) 
{
	
	var date = getFecha(fecha);
	var this_day_e = new makeArray(7);
	var day;
	this_day_e[0]  = 'Domingo';
	this_day_e[1]  = 'Lunes';
	this_day_e[2]  = 'Martes';
	this_day_e[3]  = 'Miercoles';
	this_day_e[4]  = 'Jueves';
	this_day_e[5]  = 'Viernes';
	this_day_e[6]  = 'Sabado';
		
	day = date.getDay();
 
	return this_day_e[day];
}

/**
 * Crear la tabla con las fechas de un origen mostrando el precio mas barato
 * @param el json con el listado de todos los origenes y fechas de un determinado mes 
 * @return
 */
function showTable(jsonSelec, origenSelec, mesAnSelec, pointInf, pointSup) 
{
	tdSelect = 0;
	var json = null;
	if (jsonSelec == null) 
	{
		json = watchOriDate(jsonGlobal, origenSelec, mesAnSelec);
	} 
	else 
	{
		jsonGlobal = jsonSelec;
		origen = origenSelec;
		mesAno = mesAnSelec;
		json = watchOriDate(jsonSelec, origenSelec, mesAnSelec);
	}

	//Limpiar el div que va a mostrar la tabla
	document.getElementById("CircuitTabla").innerHTML = "";
	var x = json;
	try 
	{
		// Creando el Objecto JSON
		origFecha = eval(x);
	} 
	catch (failed) 
	{
		//Si no consigue crear el objecto
		putErrorMessage();
	}
	if (origFecha != null) 
	{
		if ((origFecha.allDates.length+(1*dif)) <= pointSup) {
			if (origFecha.allDates.length == pointSup) {
				document.getElementById("anteriores").style.display = 'none';
				document.getElementById("siguientes").style.display = 'none';
				drawMatriz(origFecha, pointInf, pointSup, 1*dif);
			} else {
				if (pointInf >= 6) {
					document.getElementById("siguientes").style.display = 'none';
					document.getElementById("anteriores").style.display = 'block';
					//drawMatriz(origFecha, pointInf, origFecha.allDates.length);
					drawMatriz(origFecha, pointInf, pointSup, pointSup-origFecha.allDates.length);
				} else {
					document.getElementById("siguientes").style.display = 'none';
					document.getElementById("anteriores").style.display = 'none';
					drawMatriz(origFecha, pointInf, origFecha.allDates.length, 0);
				}
			}
		} else {
			if (pointInf >= 6) {
				document.getElementById("anteriores").style.display = 'block';
				document.getElementById("siguientes").style.display = 'block';
				drawMatriz(origFecha, pointInf, pointSup, 1*dif);
			} else {
				document.getElementById("anteriores").style.display = 'none';
				document.getElementById("siguientes").style.display = 'block';
				drawMatriz(origFecha, pointInf, pointSup, 0);
			}
			
		}

	}

}
// Metodo para crear lineas en la tabla.
function createHeaderTr() 
{
	var tr = document.createElement('tr');
	return tr;
}
// Metodo para crear columnas del Header
function createHeaderTD(style) 
{
	var td = document.createElement("td");

	if (style != "" && style != "undefined") 
	{
		td.setAttribute("class", style);
		td.className = style;
	}
	td.width = 226;
	td.height = 25;
	td.align = 'center';
	td.colSpan = 1;
	td.rowSpan = 1;
	td.style.cssText = "padding-left:" + 5 + "px;padding-right:" + 5 + "px;";
	td.setAttribute("style", "padding-left:" + 5 + "px;padding-right:" + 5
			+ "px;");
	td.appendChild(createSpanCirc('', 'precios-seo'));

	return td;
}
// Metodo para crear las demas columnas del header
function createTD(style, text, alt) 
{
	var td = document.createElement('td');
	if (style != "" && style != "undefined") 
	{
		td.setAttribute("class", style);
		td.className = style;
	}
	td.setAttribute("nowrap", "nowrap");
	td.height = 25;
	td.width = 68;
	td.align = 'center';
	td.style.cssText = "padding-left:" + 5 + "px;padding-right:" + 5 + "px;";
	td.setAttribute("style", "padding-left:" + 5 + "px;padding-right:" + 5
			+ "px;");
	td.appendChild(createSpanAlt(text, 'naranja-comentario-horario', alt));
	return td;
}
// Metodo para la creacion de la primera columna de datos.

function createTdFirstColumn(style, text) 
{
	var td = document.createElement('td');
	if (style != "" && style != "undefined") 
	{
		td.setAttribute("class", style);
		td.className = style;
	}
	td.height = 25;
	td.setAttribute("nowrap", "nowrap");
	td.align = 'left';
	td.style.cssText = "padding-left:" + 5 + "px;padding-right:" + 5 + "px;";
	td.setAttribute("style", "padding-left:" + 5 + "px;padding-right:" + 5
			+ "px;");
	if (text.length > 30) 
	{
		text = text.substring(0, 30);
		text = text + "...";
		td.appendChild(createCircuitDetailLink(text, 'Negro-bold-enlaces', td));
	} 
	else 
	{
		td.appendChild(createCircuitDetailLink(text, 'Negro-bold-enlaces', td));
	}
	return td;
}
// Metodo para la creacion para las demas columnas de datos
function createTdOtherColumn(style, text, origFecha, i) 
{
	var td = document.createElement('td');
	if (style != "" && style != "undefined") 
	{
		td.setAttribute("class", style);
		td.className = style;
	}
	td.noWrap;
	td.height = 25;
	td.align = 'center';
	td.style.cssText = "padding-left:" + 5 + "px;padding-right:" + 5 + "px;";
	td.setAttribute("style", "padding-left:" + 5 + "px;padding-right:" + 5
			+ "px;");
	td.appendChild(createCircuitLinkPrice(text, 'Negro-bold-enlaces', td,
			origFecha, i));
	return td;
}
// Metodo para la creacion de campos text
function createText(text) 
{
	var textNode = document.createTextNode(text);

	return textNode;
}
//Metodo para la creacion de campos Span con alt
function createSpanAlt(text, style, alt) 
{
	var span = document.createElement("span");
	if (style != '' && style != undefined) 
	{
		span.setAttribute("class", style);
		span.className = style;
	}

    if (alt != '' && alt != undefined) {
        span.setAttribute("title", alt);
    }
	if (text != '' && text != undefined) 
	{
		var textNode = document.createTextNode(text);
		span.appendChild(textNode);
	}
	return span;
}
// Metodo para la creacion de campos Span
function createSpanCirc(text, style) 
{
	var span = document.createElement("span");
	if (style != '' && style != undefined) 
	{
		span.setAttribute("class", style);
		span.className = style;
	}
	if (text != '' && text != undefined) 
	{
		var textNode = document.createTextNode(text);
		span.appendChild(textNode);
	}
	return span;
}
// Metodo para crear los Link de los precios
function createCircuitLinkPrice(text, style, td, origFecha, i) 
{
	var textAux = document.createTextNode(text + euro);
	var link = document.createElement("a");
	link.setAttribute("class", style);
	link.className = style;
	var folleto = origFecha.allDates[i-deplaza].fol;
	var paquete = origFecha.allDates[i-deplaza].Paq;
	var fecha = origFecha.allDates[i-deplaza].Fecha;
	i++;
	link.setAttribute("href", "javascript:select('" + folleto + "','" + fecha
			+ "');peticionPresupuestoCircuito();changeStyle("+i+")");
	link.appendChild(textAux);
	return link;
}
function createCircuitDetailLink(text, style, td) 
{
	var serviceCountry = '<bean:write name="sessionBean" property="codeServicio"/>' + '<bean:write name="sessionBean" property="language"/>';
	var textAux = document.createTextNode(text);
	var link = document.createElement("a");
	link.setAttribute("class", style);
	link.className = style;
	link.setAttribute("href", "javascript:abrirVentanaCircuitIberojet('"
			+ serviceCountry + "','" + text + "');");
	link.appendChild(textAux);

	return link;
}

/**
 * Funcion para cambiar el estilo de la celda cuando se selecciona.
 * @param td La columna seleccionada.
 * @param i Numero de la columna.
 * @return la columna con los estilos aplicados.
 */
function changeStyle(i) 
{
	var numTd = i;
	numTd = numTd - (dif*6);
	paramAtiguo = tdSelect;
	if(paramAtiguo != numTd)
	{
		var stile = 'blanco-mes-calendario';
		td = document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[numTd];
		td.setAttribute("class", stile);
		td.className = stile;
		td.removeAttribute('bgColor');
		var precio = document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[numTd].firstChild.firstChild;		
		document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[numTd].removeChild(document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[numTd].childNodes[0]);
		var textAux = document.createTextNode(precio.nodeValue);
		document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[numTd].appendChild(textAux);

		if (paramAtiguo != 0)
		{
			var style = 'Negro-bold-enlaces';
			var link = document.createElement("a");
			link.setAttribute("class", style);
			link.className = style;
			var folleto = origFecha.allDates[paramAtiguo-1].fol;
			var paquete = origFecha.allDates[paramAtiguo-1].Paq;
			var fecha = origFecha.allDates[paramAtiguo-1].Fecha;
			
			link.setAttribute("href", "javascript:select('" + folleto + "','" + fecha
					+ "');peticionPresupuestoCircuito();changeStyle("+paramAtiguo+")");
			 
			var auxTest = document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[paramAtiguo].firstChild.nodeValue;
			var auxTextNode = document.createTextNode(document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[paramAtiguo].firstChild.nodeValue);
			link.appendChild(auxTextNode);
			document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[paramAtiguo].removeChild(document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[paramAtiguo].childNodes[0]);
			document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[paramAtiguo].appendChild(link);
			document.getElementById("CircuitTabla").firstChild.firstChild.lastChild.childNodes[paramAtiguo].setAttribute("class", 'color-ski-interior');
		}
		tdSelect = numTd;
	}
}
// Metodo para dibujar la linea vertical
function createVerticalLine() 
{
	td = document.createElement("td");
	td.width = "1px";
	td.rowSpan = "1000";
	td.bgColor = "#cccccc";

	return td;
}

function select(fol, fecha) 
{
	document.opcionesPaqueteForm.id_folleto.value = fol;
	var dcpValue = document.opcionesPaqueteForm.dcp.value;
	document.opcionesPaqueteForm.dcp.value = dcpValue;
	document.opcionesPaqueteForm.fecha.value = fecha;
	document.opcionesPaqueteForm.startCity.value = document.forms[0].origen.options[document.forms[0].origen.selectedIndex].value;
}

String.prototype.startsWith = function(s) 
{
	return this.indexOf(s) == 0;
}

/************************Seleccionar Grupo Excluyentes *******************************/
/**
 * Metodo que recoge los codigos servicios terrestres excluyentes seleccionados
 * en la jsp y los concatena enviandolos al action para la validacion.
 */
function verSelectedSt(index)
{
	var numOfGroups = parseInt(index)+parseInt(1);
	/* Count para verificar que se ha seleccionado un servicio por grupo. */
	var count = 0;
	var codsSts="";
	for ( var i = 0; i < numOfGroups; i++) 
	{
		eval("Grupo = document.forms[0].Grupo"+i );
		if(Grupo.length == undefined)
		{
			codsSts+=Grupo.value+"#";
			count++;
		}
		else
		{
			for(var j = 0; j <= Grupo.length; j++ )
			{
				if(Grupo[j].checked)
				{
					count++;
					codsSts+=Grupo[j].value+"#";
					break;
				}
			}
		}
	}
	if (count == numOfGroups)
	{
		document.getElementById("codigoServicioTerrestres").value=codsSts;
		document.forms[0].submit();
	}
	else
	{
		alert("Tiene que seleccionar un servicio por cada grupo.");
	}
}

