var cabinObject;
var deckObject;
var tabsInfoJsonParsed;
var divGlobal;
/**
 * Mehtod to obtain the XmlHttpReuqestObject.
 * @return, the XmlHttpReuqestObject.
 */
function getXmlHttpRequestObject() 
{
	var req = null;
	//Not IE
	if (window.XMLHttpRequest) 
	{
		req = new XMLHttpRequest(); 
	}
	//IE
	else if(window.ActiveXObject) 
	{
		req =  new ActiveXObject("Microsoft.XMLHTTP"); 
	}
	return req;
}
/**
 * Method called to make the request of the json tabs.
 * @param navyId Navy Id.
 * @param boatId Boat id.
 * @param cabinId Cabin id.
 * @return
 */
function showCabinDetails(navyId, boatId, cabinId, resultNumber, showDiv)
{
	navyIdGlobal = navyId;
	boatIdGlobal = boatId;
	cabinIdGlobal = cabinId;
	resultNumberGlobal = resultNumber;
	divGlobal = showDiv;

	if (tabsInfoJsonParsed == null)
	{
		if(xmlHttpRequest != null && xmlHttpRequest.readyState != 0 && xmlHttpRequest.readyState != 4)
		{
			xmlHttpRequest.abort();
		}
		xmlHttpRequest = getXmlHttpRequestObject();
		xmlHttpRequest.onreadystatechange = checkTabsResponse;
		xmlHttpRequest.open('GET','/js/cruises/tabs.json', true);
		xmlHttpRequest.send(null);
	}
	else
	{
		if(divGlobal == 'displayCabinDetail')
   		{
			drawCabinDetails(getCabinFromJson(tabsInfoJsonParsed));
   		}
		else if(divGlobal == 'displayDeckDetail')
		{
			deckObject = getDeckFromJson(tabsInfoJsonParsed);
			var listOfCategories = getCategoriesFromJsonByDeck(deckObject, tabsInfoJsonParsed);
	   		if(deckObject != null)
	   		{
	   			drawDeckDetails(deckObject, listOfCategories);
	   		}
		}
	}
}
/**
 * Method to check the response of the request.
 * @return
 */
function checkTabsResponse()
{
	if(xmlHttpRequest.readyState==4)
	{
       	if(xmlHttpRequest.status==200)
		{
       		var tabsInfoJson = xmlHttpRequest.responseText;
       		tabsInfoJsonParsed = eval('(' + tabsInfoJson + ')');
       		if(divGlobal == 'displayCabinDetail')
       		{
       			cabinObject = getCabinFromJson(tabsInfoJsonParsed);
       			if (cabinObject != null)
           		{
           			drawCabinDetails(cabinObject);
           		}
       		}
       		else if(divGlobal == 'displayDeckDetail')
       		{
       			deckObject = getDeckFromJson(tabsInfoJsonParsed);
       			var listOfCategories = getCategoriesFromJsonByDeck(deckObject, tabsInfoJsonParsed);
       			if(deckObject != null)
       			{
       				drawDeckDetails(deckObject, listOfCategories);
       			}
       		}	
		}
	}
}
/**
 * Method to get the cabin that we gona show.
 * @param tabJson the json.
 * @return the cabin.
 */
function getCabinFromJson(tabJson)
{
	if (tabJson != null)
	{
		for (var iNavy = 0; iNavy < tabJson.navies.length; iNavy++)
		{
			var navy = tabJson.navies[iNavy];
			if (navyIdGlobal == navy.id)
			{
				for (var iBoat = 0; iBoat < navy.ships.length; iBoat++)
				{
					var boat = navy.ships[iBoat];
					if(boat.cod == boatIdGlobal)
					{
						for (var iCabin = 0; iCabin < boat.categories.length; iCabin++)
						{
							var cabin = boat.categories[iCabin];
							if (cabinIdGlobal == cabin.cod)
							{
								return cabin;
							}
						}
					}
				}
			}
		}
	}
	return null;
}
/**
 * Method to draw the layer with the cabin information.
 * @param cabinInfo the cabin object.
 * @return
 */
function drawCabinDetails(cabinInfo)
{
	// Div en el cual se va a mostrar el div en al jsp.
	var divShowCabinDetails = document.getElementById('displayCabinDetail');
	// Cleaning the div.
	divShowCabinDetails.innerHTML="";
	divShowCabinDetails.setAttribute("id","displayCabinDetail");
	divShowCabinDetails.className="detalle-camarote";
	divShowCabinDetails.style.left="50px";
	
	var divShowCabinHeader = document.createElement('div');
	divShowCabinHeader.setAttribute("id","jsDivCabin");
	divShowCabinHeader.className="titulo";
	var spanShowCabinHeader = document.createElement('span');
	var aShowCabinHeader = document.createElement('a');
	aShowCabinHeader.setAttribute('href',"javascript:hiddenFloatingDiv('displayCabinDetail')");
	
	var imgShowCabinHeader = document.createElement('img');
	imgShowCabinHeader.setAttribute('border','0');
	imgShowCabinHeader.setAttribute('src','/pictures/button-close-info.png');
	imgShowCabinHeader.setAttribute('alt','cerrar');
	
	aShowCabinHeader.appendChild(imgShowCabinHeader);
	
	var textShowCabinHeader = document.createTextNode('Detalle del camarote');
	spanShowCabinHeader.appendChild(textShowCabinHeader);

	spanShowCabinHeader.appendChild(aShowCabinHeader);
	
	divShowCabinHeader.appendChild(spanShowCabinHeader);
	
	divShowCabinDetails.appendChild(divShowCabinHeader);
	
	var divInfoCabin = document.createElement('div');
//	divInfoCabin.className = "infoResponse";
	divInfoCabin.setAttribute('id','infoResponse');
	if (cabinInfo.photo != null)
	{
		var divCabinImage = document.createElement('div');
		divCabinImage.className="imagen-camarote";
	
		var imgCabinImage = document.createElement('img');
	// Quitar la extension del fichero de imagen para poder reemplazarla por _grande+extension.
		imgCabinImage.style.width='360px';
		imgCabinImage.style.height='250px';
		var cabinFoto = cabinInfo.photo.lastIndexOf('.');
		imgCabinImage.setAttribute('src','/images/cruises/'+cabinInfo.photo.substring(0,cabinFoto)+'.jpg');
	
		divCabinImage.appendChild(imgCabinImage);
	
		divInfoCabin.appendChild(divCabinImage);
	}
	var divCabinDescription = document.createElement('div');
	divCabinDescription.className="texto";
	
	
	var pCabinType = document.createElement('p');
	var pCabinCapacity = document.createElement('p');
	var pPosibleDecks = document.createElement('p');
	
	var pCabinTypeText = document.createTextNode('Categoria ' + cabinInfo.cod + ' - ' + cabinInfo.name);
	pCabinType.appendChild(pCabinTypeText);
	var pCabinCapacityText = document.createTextNode('Capacidad máxima - ' + cabinInfo.cap + ' pasajeros.');
	pCabinCapacity.appendChild(pCabinCapacityText);
	// Get all deck where the categeory can be.
	var listOfDecks = '';
	for (var iDeck = 0; iDeck < cabinInfo.covs.length; iDeck++)
	{
		if(iDeck != cabinInfo.covs.length -1)
		{
			listOfDecks += cabinInfo.covs[iDeck].name + ', ';
		}
		else
		{
			listOfDecks += cabinInfo.covs[iDeck].name;
		}
	}
	var pPosibleDecksText = document.createTextNode('Posibles Cubiertas: ' + listOfDecks);
	pPosibleDecks.appendChild(pPosibleDecksText);
	
	divCabinDescription.appendChild(pCabinType);
	divCabinDescription.appendChild(pCabinCapacity);
	divCabinDescription.appendChild(pPosibleDecks);
	
	divInfoCabin.appendChild(divCabinDescription);
	if(cabinInfo.phoLay != null)
	{
		var divCabinLayout = document.createElement('div');
		divCabinLayout.className="planta-camarote";
	
		divInfoCabin.appendChild(divCabinLayout);
	
		var imgCabinLayout = document.createElement('img');
		imgCabinLayout.setAttribute('src','/images/cruises/' + cabinInfo.phoLay);
	
		divInfoCabin.appendChild(imgCabinLayout);
	}
	divShowCabinDetails.appendChild(divInfoCabin);
	displayCabinDetails(resultNumberGlobal, 'displayCabinDetail');
	
}


function getDeckFromJson(tabJson)
{
	if(tabJson != null)
	{
		for (var iNavy = 0; iNavy < tabJson.navies.length; iNavy++)
		{
			var navy = tabJson.navies[iNavy];
			if(navyIdGlobal == navy.id)
			{
				for(var iBoat = 0; iBoat < navy.ships.length; iBoat++)
				{
					var boat = navy.ships[iBoat];
					if(boatIdGlobal == boat.cod)
					{
						for (var iDeck = 0; iDeck < boat.coverts.length; iDeck++)
						{
							var deck = boat.coverts[iDeck];
							// Utilizamos el codigo de la cabina para el codigo de la cubierta.
							if(cabinIdGlobal == deck.id)
							{
								return deck;
							}
						}
					}
				}
			}
		}
	}
}

function getCategoriesFromJsonByDeck(deckObject, tabJson)
{
	var listCategories = [];
	for(var iNavy = 0; iNavy < tabJson.navies.length; iNavy++)
	{
		var navy = tabJson.navies[iNavy];
		if(navyIdGlobal == navy.id)
		{
			for(var iBoat = 0; iBoat < navy.ships.length; iBoat++)
			{
				var boat = navy.ships[iBoat];
				if(boatIdGlobal == boat.cod)
				{
					for (var iCabin = 0; iCabin < boat.categories.length; iCabin++)
					{
						var cabin = boat.categories[iCabin];
						for (var iDeck = 0; iDeck < cabin.covs.length; iDeck++)
						{
							var deck = cabin.covs[iDeck];
							if (deckObject != undefined)
							{
								if(deck.id == deckObject.id)
								{
									listCategories.push(cabin);
								}
							}
						}
					}
				}
			}
		}
	}
	return listCategories;
}

function drawDeckDetails(deck, categories)
{
	var divDetailDeck = document.getElementById('displayDeckDetail');
	divDetailDeck.innerHTML="";
	divDetailDeck.className="detalle-cubierta";
	divDetailDeck.setAttribute("id","displayDeckDetail");
	
	var divShowDeckHeader = document.createElement('div');
	divShowDeckHeader.setAttribute("id","jsDivCabin");
	divShowDeckHeader.className="titulo";
	var spanShowDeckHeader = document.createElement('span');
	var aShowDeckHeader = document.createElement('a');
	aShowDeckHeader.setAttribute('href',"javascript:hiddenFloatingDiv('displayDeckDetail')");
	
	var imgShowDeckHeader = document.createElement('img');
	imgShowDeckHeader.setAttribute('border','0');
	imgShowDeckHeader.setAttribute('src','/pictures/button-close-info.png');
	imgShowDeckHeader.setAttribute('alt','cerrar');
	
	aShowDeckHeader.appendChild(imgShowDeckHeader);
	
	var textShowDeckHeader = document.createTextNode('Detalle de la cubierta');
	spanShowDeckHeader.appendChild(textShowDeckHeader);

	spanShowDeckHeader.appendChild(aShowDeckHeader);
	
	divShowDeckHeader.appendChild(spanShowDeckHeader);
	
	divDetailDeck.appendChild(divShowDeckHeader);
	
	var divInfoDeck = document.createElement('div');
	
	var detailDeckTable = document.createElement('table');
	detailDeckTable.className='detail-deck-table';
	detailDeckTable.width="100%";
	var detailDeckTBody = document.createElement('tbody');
	
	// Row with name of the boat and the deck name.
	var detailDeckTableTr = document.createElement('tr');
	var detailDeckTableTd = document.createElement('td');
	detailDeckTableTd.className='detail-deck-tablename';
	detailDeckTableTd.colSpan='2';
	
	var detailDeckTableTitleText = document.createTextNode('Cubierta ' + deck.name.toUpperCase());
	
	detailDeckTableTd.appendChild(detailDeckTableTitleText);
	detailDeckTableTr.appendChild(detailDeckTableTd);
	
	
	// Row with two columns, the left column to show the deck plan and right one to show the list of the cabins in that deck.
	var detailDeckInfoTr = document.createElement('tr');
	// Column for the deck plan.
	var detailDeckPlanTd = document.createElement('td');
	detailDeckPlanTd.width="35%";
	if(deck.photo != null)
	{
		// Image of the deck plan.
		var imgDeckPlan = document.createElement('img');
		imgDeckPlan.setAttribute('src','/images/cruises/' + deck.photo);
		
		detailDeckPlanTd.appendChild(imgDeckPlan);
	}
	detailDeckInfoTr.appendChild(detailDeckPlanTd);
	// Column that displays all cabins in that deck.
	var detailDeckCabinsTd = document.createElement('td');
	detailDeckCabinsTd.vAlign='top';
	detailDeckCabinsTd.width="65%";
	// the table that gonna show the information.
	var detailDeckShowListCabinsTable = document.createElement('table');
	detailDeckShowListCabinsTable.className='detail-deck-cabins-table';
	detailDeckShowListCabinsTable.width="100%";
	
	var detailDeckShowListCabinsTBody = document.createElement('tbody');
	// Row for the description of the table.
	var detailDeckShowListCabinsDescTr = document.createElement('tr');
	detailDeckShowListCabinsDescTr.style.textAlign='center';
	
	var detailDeckShowListCabinsDescTd = document.createElement('td');
	
	detailDeckShowListCabinsDescTd.height='10px';
	detailDeckShowListCabinsDescTd.colSpan='2';
	detailDeckShowListCabinsDescTd.style.paddingTop="10px";
	detailDeckShowListCabinsDescTd.style.paddingBottom="10px";
	
	var detailDeckShowListCabinsDescText = document.createTextNode('Categorías en esta cubierta');
	
	detailDeckShowListCabinsDescTd.appendChild(detailDeckShowListCabinsDescText);
	detailDeckShowListCabinsDescTr.appendChild(detailDeckShowListCabinsDescTd);
	detailDeckShowListCabinsTBody.appendChild(detailDeckShowListCabinsDescTr);

	
	// Rows for categories...
	for(var iCabins = 0; iCabins < categories.length; iCabins++)
	{
		var category = categories[iCabins];
		
		var categoryRow = document.createElement('tr');
		
		// Column of the cabin image.
		var categoryImageColumn = document.createElement('td');
		categoryImageColumn.height="80px";
		categoryImageColumn.style.paddingLeft="5px";
		categoryImageColumn.style.paddingRight="5px";
		categoryImageColumn.style.paddingTop="10px";
		categoryImageColumn.style.paddingBottom="10px";
		categoryImageColumn.style.backgroundColor="#eef1fa";
		
		var imgCategory = document.createElement('img');
		imgCategory.style.width='115px';
		imgCategory.style.height='80px';
		imgCategory.setAttribute('src','/images/cruises/' + category.photo);
		
		categoryImageColumn.appendChild(imgCategory);
		categoryRow.appendChild(categoryImageColumn);
		
		// Column with the category description.
		var categoryDescriptionColumn = document.createElement('td');
		categoryDescriptionColumn.style.backgroundColor="#eef1fa";
		categoryDescriptionColumn.style.paddingLeft="5px";
		categoryDescriptionColumn.style.paddingRight="5px";
		categoryDescriptionColumn.style.paddingTop="10px";
		categoryDescriptionColumn.style.paddingBottom="10px";
		// Category Name.
		var pcategoryDescriptionColumn = document.createElement('p');
		pcategoryDescriptionColumn.style.paddingRight="3px";
		var categoryDescriptionColumnCategoryName = document.createTextNode('Categoría ' + category.cod + ' - ' + category.name + '.');
		pcategoryDescriptionColumn.appendChild(categoryDescriptionColumnCategoryName);
		categoryDescriptionColumn.appendChild(pcategoryDescriptionColumn);
		// Category Capaxity.
		var pcategoryDescriptionColumnCap = document.createElement('p');
		pcategoryDescriptionColumnCap.style.paddingRight="3px";
		var categoryDescriptionColumnMaxCapacity = document.createTextNode('Capacidad máxima - ' + category.cap + ' pasajeros.');
		pcategoryDescriptionColumnCap.appendChild(categoryDescriptionColumnMaxCapacity);
		categoryDescriptionColumn.appendChild(pcategoryDescriptionColumnCap);
		
		//Category Description.
		var pcategoryDescriptionColumnDesc = document.createElement('p');
		pcategoryDescriptionColumnDesc.style.textAlign="justify";
		pcategoryDescriptionColumnDesc.style.paddingRight="3px";
		var categoryDescriptionColumnDescription = document.createTextNode(category.desc);
		pcategoryDescriptionColumnDesc.appendChild(categoryDescriptionColumnDescription);
		categoryDescriptionColumn.appendChild(pcategoryDescriptionColumnDesc);
		
		categoryRow.appendChild(categoryDescriptionColumn);
		
		
		detailDeckShowListCabinsTBody.appendChild(categoryRow);
	}
	
	detailDeckShowListCabinsTable.appendChild(detailDeckShowListCabinsTBody);
	
	detailDeckCabinsTd.appendChild(detailDeckShowListCabinsTable);
	detailDeckInfoTr.appendChild(detailDeckCabinsTd);
	detailDeckTBody.appendChild(detailDeckInfoTr);
	
	detailDeckTable.appendChild(detailDeckTBody);
	
	divInfoDeck.appendChild(detailDeckTable);
	
	divDetailDeck.appendChild(divInfoDeck);
	
	displayCabinDetails(resultNumberGlobal, 'displayDeckDetail');
}
//Ajax request to Detail Cabin - jmarevalo

var dataCabin = null;
var addxmlobj;
var dato;

function displayCabinDetails(numIti, divName)
{ 
	var w, h, l, t;
	if (divName == 'displayDeckDetail')
	{
		w = 575;
	}
	else if(divName == 'displayCabinDetail')
	{
		w = 370;
	}
	h = 190;
	l = 50;
	var niti = parseInt(numIti);
//	t = 270 * (niti+1);
	
	t = document.body.scrollTop ||  document.documentElement.scrollTop;
	t+=screen.availHeight/5;
    displayFloatingDiv(divName, w, h, l, t);
}

function displayMinPriceDetails(numIti, divName)
{
	var w, h, l, t;
	w = 370;
	h = 190;
	l = 570;
	var niti = parseInt(numIti);
//	t = 270 * (niti+1);
	
	t = document.body.scrollTop ||  document.documentElement.scrollTop;
	t+=screen.availHeight/5;
	displayFloatingDiv(divName, w, h, l, t);
}



//Get our browser specific XmlHttpRequest object.
var receiveReq = getXmlHttpRequestObject();
var n;

var numItiForPriceDetails;
var matrixType;

var priceDetailsReq = getXmlHttpRequestObject();
var numIti;


//Initiate the asyncronous request.
function sayHello(iti,tab,barco,cod,cabin,naviera,npix) {
	//If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call.
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
		//Setup the connection as a GET call to detailCabin Action
		//True explicity sets the request to asyncronous (default).
		receiveReq.open("GET", '/cruises/detailCabin.do?iti='
				+iti+'&tab='+tab+'&barco='+barco+'&cod='+cod+'&cabin='+cabin+'&naviera='+naviera, true);
		//Set the function that will be called when the XmlHttpRequest objects state changes.
		n = npix;
		receiveReq.onreadystatechange = handleSayHello; 
		//Make the actual request.
		receiveReq.send(null);
	}			
}



//Called every time our XmlHttpRequest objects state changes.
function handleSayHello() {
	//Check to see if the XmlHttpRequests state is finished.
	if (receiveReq.readyState == 4) {
		//Set the contents of our span element to the result of the asyncronous call.
		displayCabinDetails(n, 'verDetalleCamarote');
	
		document.getElementById('infoResponse').innerHTML = receiveReq.responseText;
		
	}
}

function getPriceDetails(ncrpreciosfecha,npix) {
	
	//If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call.
	if (priceDetailsReq.readyState == 4 || priceDetailsReq.readyState == 0) {
		//Setup the connection as a GET call to priceDetails Action
		//True explicity sets the request to asyncronous (default).
		priceDetailsReq.open("GET", '/cruises/priceDetails.do?ncrpreciosfecha=' +ncrpreciosfecha + '&itiInd=' + npix, true);
		//Set the function that will be called when the XmlHttpRequest objects state changes.
		numItiForPriceDetails = npix;
		priceDetailsReq.onreadystatechange = handlePriceDetails; 
		//Make the actual request.
		priceDetailsReq.send(null);
	}			
}


function handlePriceDetails()
{
	//Check to see if the XmlHttpRequests state is finished and its ok
	if (priceDetailsReq.readyState == 4 )
	{
		if( priceDetailsReq.status==200 ) 
		{
			//Set the contents of our span element to the result of the asyncronous call.
			document.getElementById('minPriceDetailsResponse').innerHTML = priceDetailsReq.responseText;
		}else
		{
			document.getElementById('minPriceDetailsResponse').innerHTML ='This function is not available temporarily. Sorry for the inconvenience.';
		}
		displayMinPriceDetails(numItiForPriceDetails, 'minPriceDetails');
		
	}
	
}



function hideGrantedCabinDescription()
{
	hiddenFloatingDivs();
}
function showGrantedCabinDescription()
{
	displayWindows();
}

function displayWindows()
{
	var w, h, l, t;
	w = 370;
	h = 190;
	l = 200;
	var niti = parseInt(20);
	t = 270 * (niti+1);
    displayFloatingDivs('capaGarantizada', w, h, l, t);
}

function displayFloatingDivs(capaGarantizada, width, height, left, top) {
	document.getElementById(capaGarantizada).style.top = top + "px";
	shiftOpacityShows(capaGarantizada);
}

function shiftOpacityShows(capaGarantizada) {
	var obj = document.getElementById(capaGarantizada);
	transicions.call(obj, 0, 1, 1, capaGarantizada,1);
}
var transicions = function(inicio, fin, segundos, capaGarantizada, show) {
	var _this = this;
	this.test = 0;
	if (_this.intervalo)
		clearInterval(_this.intervalo);
	if (this.val && Math.abs(fin - _this.val) < 0.01)
		return;
	this.val = !this.val ? inicio < 1 ? inicio + .0001 : inicio : this.val;
	set_opacitys(this, this.val);
	this.pasos = (fin - inicio) / 25;
	this.pausa = segundos * 10;
	this.intervalo = setInterval( function() {
		if (_this.test > 99 || Math.abs(fin - _this.val) < 0.01) {
			clearInterval(_this.intervalo);

}
_this.test++;
_this.val = _this.val + _this.pasos;
if (_this.val <= .01) {
	_this.style.display = 'none';
} else {
	_this.style.display = 'block';
	set_opacitys(_this, _this.val, capaGarantizada);
}
}, this.pausa);
}
function set_opacitys(div, value, capaGarantizada) {
	div.style.opacity = value;
	div.style.MozOpacity = value;
	div.style.KhtmlOpacity = value;
	div.style.filter = 'alpha(opacity=' + value * 100 + ')';
	div.style.zoom = 1;
}
function hiddenFloatingDivs() {
	shiftOpacityHides();
}
function shiftOpacityHides() {
	var obj = document.getElementById('capaGarantizada');
	transicions.call(obj, 1, 0, 1, "capaGarantizada",0);
}
