var radValueSelect = null;

var jsonSearcherParsed;
var globalSearcher;

function disableElements()
{
	document.getElementById('loading').style.display = 'block';
	if(document.getElementById('selMesLat').disabled == false)
	{
		document.getElementById('selMesLat').disabled = true;
	}
	if(document.getElementById('selZonaLat').disabled == false)
	{
		document.getElementById('selZonaLat').disabled = true;
	}
	if(document.getElementById('selNavieraLat').disabled == false)
	{
		document.getElementById('selNavieraLat').disabled = true;
	}
	if(document.getElementById('selDuracion').disabled == false)
	{
		document.getElementById('selDuracion').disabled = true;
	}
	if(document.getElementById('selBoatLat').disabled == false)
	{
		document.getElementById('selBoatLat').disabled = true;
	}
	if(document.getElementById('selSailPort').disabled == false)
	{
		document.getElementById('selSailPort').disabled = true;
	}
	
}

function enableElements()
{
	document.getElementById('loading').style.display = 'none';
	if(document.getElementById('selMesLat').disabled == true)
	{
		document.getElementById('selMesLat').disabled = false;
	}
	if(document.getElementById('selZonaLat').disabled == true)
	{
		document.getElementById('selZonaLat').disabled = false;
	}
	if(document.getElementById('selNavieraLat').disabled == true)
	{
		document.getElementById('selNavieraLat').disabled = false;
	}
	if(document.getElementById('selDuracion').disabled == true)
	{
		document.getElementById('selDuracion').disabled = false;
	}
	if(document.getElementById('selBoatLat').disabled == true)
	{
		document.getElementById('selBoatLat').disabled = false;
	}
	if(document.getElementById('selSailPort').disabled == true)
	{
		document.getElementById('selSailPort').disabled = false;
	}
}

function disableRadioFilter()
{
	if(document.getElementById('radPrice').disabled == false)
	{
		document.getElementById('radPrice').disabled = true;
	}
	if(document.getElementById('radDuration').disabled == false)
	{
		document.getElementById('radDuration').disabled = true;
	}
	if(document.getElementById('radNavy').disabled == false)
	{
		document.getElementById('radNavy').disabled = true;
	}
}

function enableRadioFilter()
{
	if(document.getElementById('radPrice').disabled == true)
	{
		document.getElementById('radPrice').disabled = false;
	}
	if(document.getElementById('radDuration').disabled == true)
	{
		document.getElementById('radDuration').disabled = false;
	}
	if(document.getElementById('radNavy').disabled == true)
	{
		document.getElementById('radNavy').disabled = false;
	}
}


function loadSearcher(doc, searcher)
{
	globalSearcher = searcher
	if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4)
	{
       	xmlobj.abort();
	}
	if (window.ActiveXObject) {
		xmlobj = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		xmlobj = new XMLHttpRequest();
	}
	// assign state handler
	
	xmlobj.onreadystatechange=stateCheckerLoadSearcher;
	// open socket connection
	xmlobj.open('GET',doc,true);
	xmlobj.send(null);
	
}

//check request status
function stateCheckerLoadSearcher()
{
	if(xmlobj.readyState==4)
	{
       	if(xmlobj.status==200)
		{
			//recogemos el json como string.
			var searchBoxJson = xmlobj.responseText;
			//parseamos el json.
			jsonSearcherParsed = eval('(' + searchBoxJson + ')');
			
			var navys = jsonSearcherParsed.navys;
			loadNavyOptions(navys);
			loadShipOptions(navys);
			loadPortOptions(navys, jsonSearcherParsed.ports);
			
			var zones = jsonSearcherParsed.zones;
			displayOptionsZona(zones);
			
			displayMonthAndYear();
			var itineraries = jsonSearcherParsed.itineraries;
			if(globalSearcher == 'BuscadorDisponibilidad')
			{
				fillParameter();
			}
			else
			{
				displayDataCount(itineraries);
				enableElements();
			}
		}
	    else
		{
       		//alert('Fallo al recibir json recommended');
	    }
    }	
}
function reloadSearcher(searcher)
{
	globalSearcher = searcher;
	if(globalSearcher == 'BuscadorDisponibilidad')
	{
		navyGlobalSelected =document.getElementById('selNavieraLat').value;
		boatGlobalSelected =document.getElementById('selBoatLat').value;
		portGlobalSelected =document.getElementById('selSailPort').value;
		duraGlobalSelected =document.getElementById('selDuracion').value;
		zoneGlobalSelected =document.getElementById('selZonaLat').value;
		dateGlobalSelected =document.getElementById('selMesLat').value;
		
		navys = jsonSearcherParsed.navys;
		loadShipOptions(navys);
		loadPortOptions(navys, jsonSearcherParsed.ports);
		fillParameter();
	}
	else
	{
		disableElements();
		var navys = jsonSearcherParsed.navys;
		loadShipOptions(navys);
		loadPortOptions(navys, jsonSearcherParsed.ports);
		
		var itineraries = jsonSearcherParsed.itineraries;
		displayDataCount(itineraries);
		
		enableElements();
	}
	
}


function loadNavyOptions(navys){
    // reset data container
    selectorNavy = document.getElementById('selNavieraLat');
    // sort navys by priority
    navys.sort(function sortNavys(a,b){return b.priority - a.priority});
	if(selectorNavy != null){
		for(var i=0;i<navys.length;i++){
			// create option
			var option=document.createElement('option');
			// assign 'value' attribute
			
			option.setAttribute('value',navys[i].code);
			// add link labels
			option.appendChild(document.createTextNode(navys[i].nombre));
			selectorNavy.appendChild(option);
		}
	}
}


function sleep(naptime){
	         naptime = naptime * 1000;
	         var sleeping = true;
	         var now = new Date();
	         var alarm;
	         var startingMSeconds = now.getTime();
	         while(sleeping){
	             alarm = new Date();
	             alarmMSeconds = alarm.getTime();
	             if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
	         }        
}

function loadShipOptions(navys)
{
	var selectorNavy = document.getElementById('selNavieraLat');
	var selectorShip = document.getElementById('selBoatLat');
	
	selectedNavy = parseInt(selectorNavy.value);
	
	if(selectorShip != null){
		
		selectedShip=parseInt(selectorShip.value);

		while(selectorShip.lastChild.value != "-1")
		{
			selectorShip.removeChild(selectorShip.lastChild);
		}
		
		for(var i=0;i<navys.length;i++)
		{
			if((navys[i].code == selectedNavy) || (selectedNavy ==-1)  )
			{
				navyShips=navys[i].ships;
				for(j=0; j<navyShips.length; j++)
				{
					// create option
					var option=document.createElement('option');
					// assign 'value' attribute
					
					option.setAttribute('value',navyShips[j].id);
					// add link labels
					option.appendChild(document.createTextNode(navyShips[j].nombre));
					selectorShip.appendChild(option);
					
					if(navyShips[j].id == selectedShip)
					{
						option.selected=true;
					}
					
				}
			}
		}

	}
}


function displayOptionsZona(zonas){
    // reset data container
    selector = document.getElementById('selZonaLat');
	if(selector != null){
		for(var i=0;i<zonas.length;i++){
			// create option
			var option=document.createElement('option');
			// assign 'value' attribute
			option.setAttribute('value',zonas[i].code);
			// add optionText
			option.appendChild(document.createTextNode(zonas[i].nombre));
			selector.appendChild(option);
		}
	}
}
function loadPortOptions(navys, sailPorts)
{
	selectorNavy = document.getElementById('selNavieraLat');
	selectorShip = document.getElementById('selBoatLat');
	selectorPort = document.getElementById('selSailPort');
	
	
	selectedNavy = parseInt(selectorNavy.value);
	selectedBoat = parseInt(selectorShip.value);
	
	// There's no navy and boat selected.
	if ((selectedNavy == -1)&&(selectedBoat == -1))
	{
		//then put all port of all navies and all boats.
		displayOptionsSailPort(sailPorts);
	}
	// else if is a boat selected we only show the ports of this boat, the navy isn't matter.
	else if(selectedBoat != -1)
	{
		for (var navy = 0; navy <  navys.length; navy++)
		{
			listOfBoats = navys[navy].ships;
			for (var boat = 0; boat < listOfBoats.length; boat++)
			{
				if (selectedBoat == listOfBoats[boat].id) 
				{
					listOfPorts = listOfBoats[boat].ports;
					displayOptionsSailPort(listOfPorts);
				}
			}
		}
	}
	else if ((selectedNavy != -1)&&(selectedBoat == -1))
	{
		for (var navy = 0; navy < navys.length; navy++) 
		{
			if(selectedNavy == navys[navy].code)
			{
				listOfPorts = navys[navy].ports;
				displayOptionsSailPort(listOfPorts);
			}	
		}
	}
}
function displayOptionsSailPort(sailPorts)
{
	selectorPort = document.getElementById('selSailPort');
	if(selectorPort != null)
	{
		selectedPort = selectorPort.value;
		
		while(selectorPort.lastChild.value != "-1")
		{
			selectorPort.removeChild(selectorPort.lastChild);
		}
		
		var lastPortCountry='';
		
		var optgroup;
		for(var port = 0; port < sailPorts.length; port++)
		{
			if(sailPorts[port].type != lastPortCountry)
			{
				// se añade el anterior optgroup, salvo si es el primero.
				if(lastPortCountry!='')
				{
					selectorPort.appendChild(optgroup);
				}
				
				optgroup = document.createElement('optgroup');
				optgroup.setAttribute('label',sailPorts[port].type);
				lastPortCountry=sailPorts[port].type;
			}
			
			// create option
			var option=document.createElement('option');
			// assign 'value' attribute
			option.setAttribute('value',sailPorts[port].portId);
			// add optionText
			option.appendChild(document.createTextNode(sailPorts[port].portName));
			optgroup.appendChild(option);
			
			if(sailPorts[port].portId == selectedPort)
			{
				option.selected=true;
			}
		}
		
		//se añade el último optgroup.
		selectorPort.appendChild(optgroup);
	}
}

function displayDataCount(itineraries)
{
	
	selectedMonth=document.getElementById('selMesLat').value;
	selectedZone=parseInt(document.getElementById('selZonaLat').value);
	selectedPort = parseInt(document.getElementById('selSailPort').value);
	selectedDuration='';
	if(document.getElementById('selDuracion') != null)
	{
		selectedDuration=document.getElementById('selDuracion').value;
	}
	
	selectedNavy=parseInt(document.getElementById('selNavieraLat').value);
	
	selectedBoat=-1;
	if(document.getElementById('selBoatLat') != null)
	{
		selectedBoat=parseInt(document.getElementById('selBoatLat').value);
	}
	counter=0;
	for(var i=0; i<itineraries.length; i++)
	{
		iti=itineraries[i];
		checkBoat=false;
		if( (iti.ship ==selectedBoat) || (selectedBoat ==-1) )
		{
			checkBoat=true;
		}
		checkZone= (selectedZone == -1);
		if(checkZone ==false)
		{
			for(var j=0; j< iti.zonesList.length; j++)
			{
				if(iti.zonesList[j].id ==selectedZone)
				{
					checkZone=true;
				}
			}
		}
		checkNavy=false;
		if( (iti.navy ==selectedNavy) || (selectedNavy ==-1) )
		{
			checkNavy=true;
		}
		checkMonth=(selectedMonth=='');
		if(checkMonth ==false)
		{
			for(var j=0; j< iti.monthsList.length; j++)
			{
				if(iti.monthsList[j].id ==selectedMonth)
				{
					checkMonth=true;
				}
			}
		}
		checkDuration=false;
		if( (iti.dura ==selectedDuration) || (selectedDuration =='') )
		{
			checkDuration=true;
		}
		checkPort = false;
		if((iti.portId == selectedPort)|| selectedPort == -1)
		{
			checkPort = true;
		}
		if( checkBoat && checkZone && checkNavy && checkMonth  &&   checkDuration && checkPort)
		{
			counter++;
		}
	}
	
	var result = document.getElementById('numResult');
	
	result.innerHTML = '';
	result.appendChild(document.createTextNode(counter));
}

function sendRequestRecommendedFilter(jsonRecomended, filter)
{
	radValueSelect = filter;
	disableRadioFilter();
	if(httpRequest!=null && httpRequest.readyState !=0 && httpRequest.readyState !=4)
	{
       	httpRequest.abort();
	}
	if (window.ActiveXObject) 
	{
		httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	} 
	else if (window.XMLHttpRequest) 
	{
		httpRequest = new XMLHttpRequest();
	}
	httpRequest.onreadystatechange = stateCheckerRecommendedFilter;
	httpRequest.open('GET',jsonRecomended,true);
	httpRequest.send(null);
}
function stateCheckerRecommendedFilter()
{
	if(httpRequest.readyState == 4)
	{
       	if(httpRequest.status==200)
		{
			//recogemos el json como string.
			var recommendedJson = httpRequest.responseText;
			//parseamos el json.
			var recommendedJsonParsed = eval('(' + recommendedJson + ')');
			//cogemos el array de recomendados.
			var arrayOfRecommended = recommendedJsonParsed.oferta;
			if(radValueSelect == 'price')
			{
				//Sort by price low to high
				arrayOfRecommended.sort(sort_by('precio', false, parseInt));
				displayRecommended(arrayOfRecommended);
			}
			else if (radValueSelect == 'duration')
			{
				// sort by duration low to high
				arrayOfRecommended.sort(sort_by('duracion', false, parseInt));
				displayRecommended(arrayOfRecommended);
			}
			else if (radValueSelect == 'navy')
			{
				// Sort by city, case-insensitive, A-Z
				arrayOfRecommended.sort(sort_by('nombreNaviera', false, function(a){return a.toUpperCase()}));
				displayRecommended(arrayOfRecommended);
			}
			enableRadioFilter();
		}
	    else
		{
       		//alert('Fallo al recibir json recommended');
	    }
    }
}
// algoritmo de ordenacion de un array segun un criterio y un orden.
var sort_by = function(field, reverse, primer)
{
	   reverse = (reverse) ? -1 : 1;
	   return function(a,b)
	   {
	       a = a[field];
	       b = b[field];
	       if (typeof(primer) != 'undefined')
	       {
	           a = primer(a);
	           b = primer(b);
	       }
	       if (a<b)
	       {
	    	   return reverse * -1;
	       }
	       if (a>b)
	       { 
	    	   return reverse * 1;
	       }
	       return 0;
	   }
}
//muestra los recomendados.
function displayRecommended(recommendeds)
{
	var recomendedsDiv = document.getElementById('nuestras_ofertas');
	if (recomendedsDiv != null && recomendedsDiv != "") {
		recomendedsDiv.innerHTML = '';
				
		var tableofertas = document.createElement('table');
		var tbodyofertas = document.createElement('tbody');
		tableofertas.appendChild(tbodyofertas);
		recomendedsDiv.appendChild(tableofertas);
		
		var troferta;
		var tdimagen;
		var divimg;
		var aconimg;
		var aimg;
		var tdtexto;
		var h5;
		var divtit;
		var diviti;
		var divdur;
		var divsal;
		var divpre;
		var tdnaviera;
		var imgitinerario;
		var trsepara;
		var tdsepara;
		
		var tdOfertas;
		var trOfertas;
		var divResultado;
		var divImg;
		var imgBarco;
		var divInfo;
		var ulTexto;
		var liTitulo;
		var ulTitulo;
		var liItinerario;
		var divLiTitulo;
		var textTitulo;
		var divLiMarca;
		var imgLogo;
		var spanItinerario;
		var textItinerario;
		var divLiClearer;
		var aTitulo;
		var texItinerario;
		var liDuracion;
		var spanDuracion;
		var textDuracion;
		var texDuracion;
		var liSalidas;
		var spanSalidas;
		var textSalidas;
		var texSalidas;
		var liSailPorts;
		var spanSailPorts;
		var textSailPorts;
		var texSailPorts;
		var liVuelos ;
		var saltoLinea;
		var imgVuelo;
		var divMapa;
		var liPrecio;
		var aPrecio;
		var textPrecioDesde;
		var divBotonSeleccionar;
		var imgBotonSeleccionar;
		var textBoatName;
		var spanBoatName;
		var linkBoatName;
		var imgDescBarco;
		var liNomPre;
		var spanNombre;
		var spanPrecio;
		
		for (var i = 0; i < recommendeds.length; i++) {
			// Crear el TR para los recomendados.
			trOfertas = document.createElement('tr');
			// Crear el TD para los recomendados.
			tdOfertas = document.createElement('td');
			// Crear el DIV global
			divResultado = document.createElement('div');
			// A�adair la clase al DIV
			divResultado.setAttribute('class', 'resultado-crc');
			divResultado.className = 'resultado-crc';
			// Crear el DIV para la imagem
			divImg = document.createElement('div');
			// A�adir la clase al DIV de la imagem.
			divImg.setAttribute('class', 'img');
			divImg.className = 'img';
			
			divLiMarca = document.createElement('div');
			// A�adir la clase al DIV marca.
			divLiMarca.setAttribute('class', 'marca');
			divLiMarca.className = 'marca';
			// Crear el IMG para el logo.
			imgLogo = document.createElement('img');
			// A�adir el SRC a la imagem.
			imgLogo.setAttribute('src', '/pictures/logo_' + recommendeds[i].codigoNaviera + '.gif');
			// A�adir el DIV marca a la linea de la lista.
			divImg.appendChild(imgLogo);
			
			
			var divDescuentoImagen = document.createElement('div');
			divDescuentoImagen.setAttribute('id', 'imgDescu');
			divDescuentoImagen.idName = 'imgDescu';
			
			imgDescBarco = document.createElement('img');
			imgDescBarco.setAttribute('src', '/pictures/' + recommendeds[i].imagenDescuento);
			
			if(recommendeds[i].promoImage != null)
			{
				var divDreamPromo = document.createElement('div');
				divDreamPromo.setAttribute('id','dreamPromo');
				var imgDreamPromo = document.createElement('img');
				imgDreamPromo.setAttribute('src', '/pictures/' + recommendeds[i].promoImage);
				divDreamPromo.appendChild(imgDreamPromo);
				divImg.appendChild(divDreamPromo);
			}
			
			
			divDescuentoImagen.appendChild(imgDescBarco);
			divImg.appendChild(divDescuentoImagen);
			
			// Crear la IMG para a la imagem.
			imgBarco = document.createElement('img');
			// A�adir la referencia de la imagem.
			imgBarco.setAttribute('src', '/images/cruises/' + recommendeds[i].imagenBarco);
			// A�adir el alt a la imagem.
			imgBarco.setAttribute('alt', recommendeds[i].nombreBarco);
			// A�adir el Width a la imagem.
			imgBarco.setAttribute('width', '161');
			// A�adir el Height a la imagem.
			imgBarco.setAttribute('height', '106');
			// A�adir el border a la imagem.
			imgBarco.setAttribute('border', '0');
			// A�adir la imagem al DIV de la imagem.
			divImg.appendChild(imgBarco);
			//Crear span par ael texto del nombre del barco.
			spanBoatName = document.createElement('span');
			//A�adir los estilos.
			spanBoatName.setAttribute('style', 'float: left; padding-bottom: 3px; padding-top: 3px;');
			// Crear un texto con el nombre del barco.
			textBoatName = document.createTextNode(recommendeds[i].nombreBarco.toUpperCase());
			//Poner el texto como link.
			linkBoatName = document.createElement('a');
			//Poner la clase al link.
			linkBoatName.setAttribute('class', 'textos-enlaces-bold');
			//Poner los estilos.
			linkBoatName.setAttribute('style', 'white-space: nowrap');
			//A�adir el href al link.
			linkBoatName.setAttribute('href', '/cruises/showCruiseDetailMatriz.do?selectedCruise=' +
			recommendeds[i].codigoItinerario +
			'&selectedDate=' +
			recommendeds[i].fechaprecio +
			'&tab=ficha&ship=' +
			recommendeds[i].codigoBarco +
			'&cruise=' +
			recommendeds[i].codigoItinerario +
			'&navy=' +
			recommendeds[i].codigoNaviera +
			'&selectedNavyId=' +
			recommendeds[i].codigoNaviera +
			'');
			//A�adir el texto al link.
			linkBoatName.appendChild(textBoatName);
			//A�adir el link al span.
			spanBoatName.appendChild(linkBoatName);
			//A�adir el span con el nombre del barco al divImg.
			divImg.appendChild(spanBoatName);
			// A�adir el DIV de la imagem al DIV global
			divResultado.appendChild(divImg);
			
			// Crear el DIV de Info
			divInfo = document.createElement('div');
			// A�adir la clase al DIV info.
			divInfo.setAttribute('class', 'info');
			divInfo.className = 'info';
			// A�adir el DIV info al DIV global.
			divResultado.appendChild(divInfo);
			// Crear una lista no ordenada para mostar las caracteristicas de de la oferta.
			ulTexto = document.createElement('ul');
			// Crear la linea de la lista para el Titulo
			liTitulo = document.createElement('li');
			// Crear el DIV para la linea del titulo.
			divLiTitulo = document.createElement('div');
			// A�adir la clase al DIV del titulo.
			divLiTitulo.setAttribute('class', 'titulo');
			divLiTitulo.className = 'titulo';
			//ul para el titulo y el precio
			ulTitulo = document.createElement('ul');
			//li para el nombre del itinerario y el precio
			liNomPre = document.createElement('li');
			//span para el nombre del itinerario
			spanNombre = document.createElement('span');
			spanNombre.className = 'destino';
			// Crear el texto para el titulo.
			aTitulo = document.createElement('a');
			// href t�tulo.
			aTitulo.setAttribute('href', '/cruises/searchCruises.do?selectedDate=' + recommendeds[i].fechaprecio + '&selectedCruise=' + recommendeds[i].codigoItinerario + '&selectedNavyId=' + recommendeds[i].codigoNaviera);
			// Nombre del itinerario.
			textTitulo = document.createTextNode(recommendeds[i].nombreItinerario);
			// A�adir el nombre del itinerario al enlace.
			aTitulo.appendChild(textTitulo);
			// Añadir enlace al span
			spanNombre.appendChild(aTitulo);
			// span para el precio
			spanPrecio = document.createElement('span');
			spanPrecio.className = 'precio';
			//precio.
			textPrecioDesde = document.createTextNode('desde ' + recommendeds[i].precio + String.fromCharCode(8364));
			//link precio.
			aPrecio = document.createElement('a');
			//href precio.
			aPrecio.setAttribute('href', '/cruises/searchCruises.do?selectedDate=' + recommendeds[i].fechaprecio + '&selectedCruise=' + recommendeds[i].codigoItinerario + '&selectedNavyId=' + recommendeds[i].codigoNaviera);
			//A�adir precio al enlace.
			aPrecio.appendChild(textPrecioDesde);
			//A�adir enlace al span precio.
			spanPrecio.appendChild(aPrecio);
			//Añadir el span del precio al li
			liNomPre.appendChild(spanPrecio);
			//Añadir span del nombre al li
			liNomPre.appendChild(spanNombre);
			//Añadir li del precio y el nombre al ul
			ulTitulo.appendChild(liNomPre);
			// A�adir el textNode al DIV de Tiutlo.
			divLiTitulo.appendChild(ulTitulo);
			// A�adir el DIV al LI.
			liTitulo.appendChild(divLiTitulo);
			//Crear el DIV clearer.
			divLiClearer = document.createElement('div');
			//A�adir la clase al DIV clearer.
			divLiClearer.setAttribute('class', 'clearer');
			divLiClearer.className = 'clearer';
			
			// A�adir el DIV clearer a Li de la lista.
			liTitulo.appendChild(divLiClearer);
			// A�adir el LI al UL.
			ulTexto.appendChild(liTitulo);
			// Crear el LI de la linea con Itinerario,
			liItinerario = document.createElement('li');
			// Crear el SPAN para el Itinerario.
			spanItinerario = document.createElement('span');
			// Crear el texto de Itinerario.
			textItinerario = document.createTextNode('Itinerario:');
			// A�aadir el text al spanItinerario.
			spanItinerario.appendChild(textItinerario);
			// A�adir el SPAN itinerario al LI de la lista.
			liItinerario.appendChild(spanItinerario);
			//Crear el texto de itinerario.
			var str = recommendeds[i].nombreItinerario;
			if (str.length >= 30) {
				//Anadir el itinerario  al Li de la lista.
				texItinerario = document.createTextNode(str.substring(0, 30) + '...');
			}
			else {
			
				texItinerario = document.createTextNode(str);
			}
			//Anadir el itinerario  al Li de la lista.
			liItinerario.appendChild(texItinerario);
			// A�adir el LI de Itinerario a la lista.
			ulTexto.appendChild(liItinerario);
			// Crear el LI de la Duracion
			liDuracion = document.createElement('li');
			// Crear el SPAN de la duracion.
			spanDuracion = document.createElement('span');
			// Crear el texto de duracion.
			var duraccion = 'Duracion';
			textDuracion = document.createTextNode(duraccion+':');
			// A�adir el texto al SPAN
			spanDuracion.appendChild(textDuracion);
			// A�adir el SPAN duracion al LI de Duracion
			liDuracion.appendChild(spanDuracion);
			// Crear el texto de duracion;
			var days = ' dias';
			texDuracion = document.createTextNode(recommendeds[i].duracion + days);
			// A�adir el texto duracion al LI de lista.
			liDuracion.appendChild(texDuracion);
			//A�adir el LI de la duracion a la lista
			ulTexto.appendChild(liDuracion);
			// Crear el LI para las salidas.
			liSalidas = document.createElement('li');
			//crear el span de salidas.
			spanSalidas = document.createElement('span');
			//crear el texto de salidas.
			textSalidas = document.createTextNode('Salidas:');
			//A�adir el texto salidas al spanSalidas.
			spanSalidas.appendChild(textSalidas);
			//A�dair el spanSalidas al LI de salidas.
			liSalidas.appendChild(spanSalidas);
			//crear el texto para salidas.
			texSalidas = document.createTextNode(recommendeds[i].salidas);
			// A�adir el texto de salidas al Li de salidas.
			liSalidas.appendChild(texSalidas);
			// A�adir el LI de salidas al UL
			ulTexto.appendChild(liSalidas);
			// Puertos de embarque.
			// Crear el Li para los puertos de embarque.
			liSailPorts = document.createElement('li');
			// Crear el span para los puertos de embarque.
			spanSailPorts = document.createElement('span');
			// Crear el texto de puertos de embarque.
			textSailPorts = document.createTextNode('Puerto de embarque:');
			// añadir el texto de puertos al span.
			spanSailPorts.appendChild(textSailPorts);
			// añadir el span al Li de puertos de embarque.
			liSailPorts.appendChild(spanSailPorts);
			// Crear el texto con el numbre del puerto de embarque.
			texSailPorts = document.createTextNode(recommendeds[i].nombrePuerto);
			// añadir el nombre al texto.
			liSailPorts.appendChild(texSailPorts);
			// añadir el li al ul.
			ulTexto.appendChild(liSailPorts);
			// Tasas de embarque.
			// Crear el Li para las tasas de embarque.
			liPortCharges = document.createElement('li');
			// Crear el span para las tasas de embarque.
			spanPortCharges = document.createElement('span');
			// Crear el texto de las tasas de embarque.
			textPortCharges = document.createTextNode('Tasas de embarque:');
			// añadir el texto de tasas al span.
			spanPortCharges.appendChild(textPortCharges);
			// añadir el span al Li de las tasas de embarque.
			liPortCharges.appendChild(spanPortCharges);
			// Crear el texto con el valor de las tasas.
			texPortCharges = document.createTextNode(recommendeds[i].tasasEmbarque + ' ' + '€');
			// añadir el nombre al texto.
			liPortCharges.appendChild(texPortCharges);
			// añadir el li al ul.
			ulTexto.appendChild(liPortCharges);
			
			
			if( recommendeds[i].flightImg != '')
			{
				// Crear el LI imagen vuelo
				liVuelos = document.createElement('li');
				saltoLinea=document.createElement('br');
				liVuelos.appendChild(saltoLinea);
				imgVuelo = document.createElement('img');
				// A�adir el SRC a la imagem.
				imgVuelo.setAttribute('src', '/pictures/' + recommendeds[i].flightImg  + '.gif');
				liVuelos.appendChild(imgVuelo)
				// A�adir el LI de vuelo al UL
				ulTexto.appendChild(liVuelos);
			}
			
			// A�adir el Ul al DIV de info.
			divInfo.appendChild(ulTexto);
			//A�adir el DIV info al DIV resultado
			divResultado.appendChild(divInfo);
			//crear el DIV para el Mapa
			divMapa = document.createElement('div');
			//A�adir la class al DIV mapa.
			divMapa.setAttribute('class','mapa');
			divMapa.className='mapa';
			
			//Crear el img del mapa.
			var imgMap = document.createElement('img');
			// A�adir la imagem del mapa.
			imgMap.setAttribute('src', '/images/cruises/itineraries/maps/' + recommendeds[i].nombreMapa );
			//a�adir la imagem al divMapa
			divMapa.appendChild(imgMap);
			var divTextPort = document.createElement('div');
			var spanTextPort = document.createElement('span');
			var textPort = document.createTextNode('Puerto de embarque / desembarque');
			spanTextPort.appendChild(textPort);
			divTextPort.appendChild(spanTextPort);
			divMapa.appendChild(divTextPort);
			//A�adir el divMapa al div resultado.
			divResultado.appendChild(divMapa);
			//crear el div del boton seleccionar
			divBotonSeleccionar = document.createElement('div');
			//A�adir la class al div del boton seleccionar
			divBotonSeleccionar.setAttribute('class','boton-resultado');
			divBotonSeleccionar.className='boton-resultado';
			//crear la img dek boton seleccionar
			imgBotonSeleccionar = document.createElement('img');
			//A�adir el SRC de la imagem
			imgBotonSeleccionar.setAttribute('src','/pictures/boton_seleccionar.gif');
			//A�adir el alt a la imagem
			imgBotonSeleccionar.setAttribute('alt','seleccionar crucero');
			//A�adir el border al boton
			//A�adir el border al boton
			imgBotonSeleccionar.setAttribute('border','0');
			
			// Crear el href del boton seleccionar.
			var aBotonSelec = document.createElement('a');
			//a�adir el href al a.
			aBotonSelec.setAttribute('href', '/cruises/searchCruises.do?selectedDate=' + recommendeds[i].fechaprecio + '&selectedCruise=' + recommendeds[i].codigoItinerario + '&selectedNavyId=' + recommendeds[i].codigoNaviera);
			//A�adir el link al boton.
			aBotonSelec.appendChild(imgBotonSeleccionar);
			
			//A�adir al imagem del boton al divBotonSeleccionaar
			divBotonSeleccionar.appendChild(aBotonSelec);

			//A�adir el divBotonSelecionar al divResultado.
			divResultado.appendChild(divBotonSeleccionar);
			// A�adir el DIV al TD
			tdOfertas.appendChild(divResultado);
			// A�adir el TD al TR
			trOfertas.appendChild(tdOfertas);
			// A�adir el TR al TBODY
			tbodyofertas.appendChild(trOfertas);
		}
	}	
	document.getElementById('group-left').style.visibility = 'visible';
}



// create data container
function createDataContainer(){
    var div=document.getElementById('container');
    if(div){return};
    var div=document.createElement('div');
    div.setAttribute('id','container');
    document.getElementsByTagName('body')[0].appendChild(div);
}


function expandCollapseCheck(idPanel,checkBox)
{
 var panel = document.getElementById(idPanel);
 
 if(checkBox.checked==true)
 {
	 panel.style.display="block";
 }
 else
 {
	panel.style.display="none";
 }
}

function validateSelectForm(formBuscador)
{
    var selectMes = document.getElementById("selMesLat").value;
    var selectZone = document.getElementById("selZonaLat").value;
    var selectNavy = document.getElementById("selNavieraLat").value;
    var selectDura = document.getElementById("selDuracion").value;
    var selectBoat = document.getElementById("selBoatLat").value;
	var selectPort = document.getElementById("selSailPort").value;

    if (document.getElementById("numResult").innerHTML == '0') 
    {
    	alert("No hay cruceros disponibles para los criterios seleccionados.");
        return false;
    }
    else 
    {
    	return true;
    }
}


function displayMonthAndYear()

{
     var mapOfMonths =  new Array(12);
       mapOfMonths [1]='Enero';
       mapOfMonths [2]='Febrero';
       mapOfMonths [3]='Marzo';
      mapOfMonths [4]='Abril';
       mapOfMonths [5]='Mayo';
       mapOfMonths [6]='Junio';
       mapOfMonths [7]='Julio';
       mapOfMonths [8]='Agosto';
       mapOfMonths [9]='Septiembre';
       mapOfMonths [10]='Octubre';
      mapOfMonths [11]='Noviembre';
      mapOfMonths [12]='Diciembre';
       var numberOfMonths = 24;
       var todaysDate = new Date();
       var selectBox = document.getElementById('selMesLat');

	while( selectBox.lastChild.value != "")
		{
			selectBox.removeChild(selectBox.lastChild);
		}


       //for (var i = selectBox.options.length-1; i >= 1;i--)
       //{
    	//    selectBox.options[i] = null;
       //} 
       var year = todaysDate.getFullYear();
       for (var i = 1 ; i <= numberOfMonths; i++)
       {
              var option = document.createElement('option');
              var months = todaysDate.getMonth() + i;
              var num = (months) % 13;
              if (num != 0)
              {
                     if (num == 1 && i > 1)
                     {
                           year = year + 1;
                     }
                     if (num < 10)
                     {      
                           option.setAttribute('value', '0' + num + ' ' + year);
                     }
                     else
                     {
                           option.setAttribute('value', num + ' ' + year);
                     }
                     var textOption = document.createTextNode(mapOfMonths[num]+ ' ' + year);
                     option.appendChild(textOption);
                     selectBox.appendChild(option);    
              }
       }
}


function getItineraryByNa(navyCode)
{
	sendRequestGetNavyByCode('/cruises/searchCruises.do?selectedNavyId='+navyCode);
}

function sendRequestGetNavyByCode(urlAndParams)
{
	if(xmlobj != null && xmlobj.readyState !=0 && xmlobj.readyState != 4)
	{
		xmlobj.abort();
	}
	try
	{
		xmlobj=new XMLHttpRequest();
		xmlobj.overrideMimeType('application/xml');   
	}
	catch(e)
	{
		try
		{
			xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch(e)
		{
			xmlobj=null;
			return false;
		}
	}
        xmlobj.onreadystatechange;
	xmlobj.open('GET',urlAndParams,true);
        xmlobj.send(null);
}
function refillCombos()
{
	var selectNavyCombo = document.getElementById('selNavieraLat');
	var selectDuraCombo = document.getElementById('selDuracion');
	var selectDateCombo = document.getElementById('selMesLat');
	var selectZoneCombo = document.getElementById('selZonaLat');
	var selectSailCombo = document.getElementById('selSailPort');
	var selectBoatCombo = document.getElementById('selBoatLat');
	if(duraGlobalSelected == "")
	{
		selectDuraCombo.options[0].selected='selected';
	}
	else
	{
		for (iDura = 0; iDura < selectDuraCombo.options.length; iDura++)
		{
			if(selectDuraCombo.options[iDura].value == duraGlobalSelected)
			{
				selectDuraCombo.options[iDura].selected='selected';
			}
		}
	}
	if(dateGlobalSelected == "")
	{
		selectDateCombo.options[0].selected='selected';
	}
	else
	{
		for (iDate = 0; iDate < selectDateCombo.options.length; iDate++)
		{
			if (selectDateCombo.options[iDate].value == dateGlobalSelected)
			{
				selectDateCombo.options[iDate].selected='selected';
			}
		}
	}
	if(boatGlobalSelected == null)
	{
		selectBoatCombo.options[0].selected='selected';
	}
	else
	{
		for (iBoat = 0; iBoat < selectBoatCombo.options.length; iBoat++)
		{
			if(selectBoatCombo.options[iBoat].value == boatGlobalSelected)
			{
				selectBoatCombo.options[iBoat].selected='selected';
			}
		}
	}

	for (iNavy = 0; iNavy < selectNavyCombo.options.length; iNavy++)
	{
		if(selectNavyCombo.options[iNavy].value == navyGlobalSelected)
		{
			selectNavyCombo.options[iNavy].selected='selected';
		}
	}
	for (iZone = 0; iZone < selectZoneCombo.options.length; iZone++)
	{
		if(selectZoneCombo.options[iZone].value == zoneGlobalSelected)
		{
			selectZoneCombo.options[iZone].selected='selected';
		}
	}
	for (iPort = 0; iPort < selectSailCombo.options.length; iPort++)
	{
		if(selectSailCombo.options[iPort].value == portGlobalSelected)
		{
			selectSailCombo.options[iPort].selected='selected';
		}
	}
}
function fillParameter()
{
	refillCombos();
}

