/**
* This file contains all functions used at the search section of the frontoffice
* and are not directly related to the map or the basket.
*
* @author Jens Kendl
* @package Imevia
* @subpackage Frontoffice
*/

var housesXML; //Not used yet
var attractionsXML; //Not used yet
/**
* Contains the xml document, which was last set by a request to find rooms.
* @global xml-document resultXML
*/
var resultXML;
/**
* Contains the xml document, which was last set by a request to find attractions.
* @global xml-document resultAttractionXML
*/
var resultAttractionXML;

/**
* Display the hotel results as a list.
* The global variable resultXML has to be filled before using that function!
* It generates the list out of the xml-document stored in resultXML.
* HTML elements with the following ids are needed:
* - resultListImevia: Here the list will written in.
* - resultListHotel: The comtainer of resultList.
*/
function showResultListHotels() {

	var string='<div class="result">'+
'		<div style="float:left;"><img src=""/></div>'+
'		<div style="float:left;">'+
'			Hotel Flicker<br/>'+
'			Rust<br/>'+
'			5.4.-10.4.06; DZ; Fr?h<br/>'+
'			<br/>'+
'			90%'+
'		</div>'+
'		<div style="float:right;">'+
'			ab 1000,00 ?<br/>'+
'			mittel<br/>'+
'			<input type="button" value="buchen">'+
'		</div>'+
'	</div>';
	
	var house = resultXML.documentElement.getElementsByTagName("house");
	var adress = resultXML.documentElement.getElementsByTagName("adress");
	var info = resultXML.documentElement.getElementsByTagName("info");
	var housepictures = resultXML.documentElement.getElementsByTagName("housepictures");
	var bestprices = resultXML.documentElement.getElementsByTagName("bestprice");
	var bestmatches = resultXML.documentElement.getElementsByTagName("bestmatch");
	var offers = resultXML.documentElement.getElementsByTagName("offers");
	var ratings = resultXML.documentElement.getElementsByTagName("rating");
	
	var timespanSearch = resultXML.documentElement.getAttribute('timespanSearch');
	var alternatives = resultXML.documentElement.getAttribute('alternativesPossible');
	
	thumbs = new Array();
	var resultList=""; 
	
	if (house.length>0) {
	
		//Anzahl Ergebnise eintragen
		document.getElementById('resultCounter').innerHTML = '('+house.length+')';
	
		for (var i=0; i<house.length; i++) {
			var houseid = house[i].getAttribute('houseid');
			
			resultList+= '<div class="result" id="house'+houseid+'" style="clear:both;">';
			
			//Now the picture
			var pics = housepictures[i].getElementsByTagName("picture");
			
			//Cache the thumbs
			for (var picI=0; picI<pics.length && picI<2; picI++) {
				var a = new Image();
				a.src = httpPathHousePics+'th-'+pics[picI].getAttribute('filename');
				thumbs[thumbs.length] = a;
			}
			
			if (pics.length>0) {
				var filename = 'th-'+pics[0].getAttribute('filename');
			} else {
				var filename = 'nopicture_thumb.jpg';
			}
			//resultList+= '	<div class="resultPic" style="float:left;">';
			resultList+= '		<img class="resultPic" src="'+httpPathHousePics+filename+'" onclick="popupHotelDetail('+house[i].getAttribute('houseid')+',\'pictures\',true'+(timespanSearch==1?','+timespanSearch:'')+')" />';
			//resultList+= '	</div>';
			
			//right side (price)
			var rating = ratings[i].getAttribute('overall');
			resultList+= '	<div style="float:right; text-align:right;">';
			resultList+= '		<a href="javascript:popupHotelDetail('+house[i].getAttribute('houseid')+',\'offers\',true'+(timespanSearch==1?','+timespanSearch:'')+');" title="'+texts['detailButton']+'" class="price">'+texts['startAt']+' ' + number_format( (bestprices[i].getAttribute('value')/100),2,',','.') + ' '+texts['euroSign']+'</a><br/>';
			switch(rating) {
				case 3:
					var eval = texts['positiveEval'];
					break;
				case 1:
					var eval = texts['negativeEval'];
					break;
				case 2:
				default:
					var eval = texts['neutralEval'];
			}
			for (var ri=0; ri<rating; ri++) {
				resultList+= '		<img src="'+httpPathIcons+'thumb_up.gif" class="icon" title="'+eval+'" onclick="popupHotelDetail('+house[i].getAttribute('houseid')+',\'evaluations\',true'+(timespanSearch==1?','+timespanSearch:'')+');" style="cursor:pointer;" />';
			}
			resultList+= '		<br/>';
			resultList+= '		<a href="javascript:popupHotelDetail('+house[i].getAttribute('houseid')+',\'offers\',true'+(timespanSearch==1?','+timespanSearch:'')+');" title="'+texts['wishMatch']+'" style="color:#000000"><img src="'+httpPathIcons+'wish_icon_big.gif" class="icon" title="'+texts['wishMatch']+'"/>';
			resultList+= '		'+bestmatches[i].getAttribute('value')+'%</a>';
			resultList+= '	</div>';
			resultList+= '	<div style="clear:right; float:right; text-align:right; margin-top:7px; margin-right:-2px;">';
			resultList+= '		<input type="button" value="'+texts['detailButton']+'" onclick="popupHotelDetail('+house[i].getAttribute('houseid')+',\'offers\',true'+(timespanSearch==1?','+timespanSearch:'')+');" class="button" />';
			resultList+= '	</div>';
			
			//Now the houseinformation
			var offer = offers[i].getElementsByTagName('offer')[0];
			var room = offer.getElementsByTagName('room')[0];
			//resultList+= '	<div style="float:left;">';
			resultList+= '		<a href="javascript:popupHotelDetail('+house[i].getAttribute('houseid')+',\'description\',true'+timespanSearch+')" class="title" title="'+texts['moreInformation']+'"><img src="'+httpPathIcons+'info_icon_big.gif" class="icon" title="'+texts['moreInformation']+'"/>';
			resultList+= '		'+house[i].getAttribute('name')+'</a><br/>';
			resultList+= '		'+cities[adress[i].getAttribute('cityid')]+'<br/>';
			resultList+= '		'+cutYear(offer.getAttribute('arrival'))+'-'+offer.getAttribute('departure')+'<br/>';
			resultList+= '		'+roomCategories[room.getAttribute('roomcat')]+'<br/>';
			if (map!=undefined) {
				resultList+= '		<a href="javascript:openHouseResultInfoWindow('+houseid+')" title="'+texts['showOnMap']+'"><img src="'+httpPathIcons+'eye.gif" title="'+texts['showOnMap']+'" style="vertical-align:-4px;"/> '+texts['showOnMap']+'</a>';
			}
			//resultList+= '	</div>';
			
			
			//End the result
			resultList+= '<div style="clear:both"></div>';
			resultList+= '</div>';
		}
	} else {
		resultList+= '<div style="text-align:center; margin-top: 10px;">';
		if ( '1'==alternatives ) {
			resultList+= texts['noHotelResultsFoundButAlternativesPossible'];
		} else {
			resultList+= texts['noHotelResultsFound'];
		}
		resultList+= '</div>';
	}
	
	if ( '1'==alternatives ) {
		//resultList+= '<div style="clear:both;">';
		resultList+= '	<form name="alternativeSearch" id="alternativeSearch">';
		resultList+= '		<input type="button" name="getAlternatives" value="'+texts['alternatives']+'" onclick="getResults(document.forms[\'alternativeSearch\']);" class="button" />';
		resultList+= '	</form>';
		//resultList+= '</div>';
	}
	if ( house.length==0 ) {
		resultList+= '	<form name="alternativesBookingCom" id="alternativesBookingCom">';
		resultList+= '		<input type="button" name="getAlternativesBookingCom" value="'+texts['alternativesBookingCom']+'" onclick="redirectToBookingCom();" class="button"  style="margin-top: 5px;"/>';
		resultList+= '	</form>';
	}
	
	resultList+= '	<form name="backToSearchForm" id="backToSearchForm">';
	resultList+= '		<input type="button" name="backToSearch" value="'+texts['backToSearch']+'" onclick="hideSearchOverviewHotel()" class="button" style="margin-top: 5px;"/>';
	resultList+= '	</form>';

	document.getElementById('resultListImevia').innerHTML = resultList;
	document.getElementById('resultListHotel').style.display = 'block';
	hotelBreadCrump.setActualSubmenu(texts['subheader_searchresults']);
	breadCrumpManager.updateActualBreadCrump();
}

function buildBookingComURLString() {
	var bookingForm = document.forms.bookings;
	
	var link = 'http://www.booking.com/searchresults.de.html?region=2267%3Baid=313481&label=imevia&';
	link+= 'checkin_monthday='+bookingForm.arrivalDay.value;
	link+= '&checkin_year_month='+bookingForm.arrivalYear.value+'-'+bookingForm.arrivalMonth.value;
	link+= '&checkout_monthday='+bookingForm.departureDay.value;
	link+= '&checkout_year_month='+bookingForm.departureYear.value+'-'+bookingForm.departureMonth.value;
	link+= '&do_availability_check=1&rows=30&order=price';
	return link;
}

function redirectToBookingCom() {
	window.open(buildBookingComURLString(), '_blank');
}

/**
* This function will generate and display an overview of the search parameters of a room search.
* Therefore the form "bookings" is "parsed".
* HTML elemenst with the following ids are required:
* - searchOverview: Contains the overview
* - searchOverviewHotel: Container of searchOverview
* - searchHotelForm: Container of the form
*/
function showSearchOverviewHotel() {
	var overview = "";
	
	var form = document.forms['bookings'];
	
	overview = '<table>';
	
	//The city
		overview+= '<tr><th>'+texts['city']+':</th><td>';
		if (0<form.city.selectedIndex) {
			overview+= cities[form.city[form.city.selectedIndex].value];
		} else {
			overview+= texts['doesntMatter'];
		}
		overview+= '</td></tr>';
	//Arrival and departure plus duration, if exists
		overview+= '<tr><th>'+texts['date']+':</th><td>';
		if ( document.bookings.searchType[1].checked ) {
			overview+= cutYear(form.soonestArrival.value)+'-'+form.latestDeparture.value;
			overview+="; " + form.days.value + ' ' + texts['days'];
		} else {
			overview+= cutYear(form.arrival.value)+'-'+form.departure.value;
		}
		overview+= '</td></tr>';
	//Persons and Nr of rooms
		overview+= '<tr><th>'+texts['persons']+':</th><td>';
		overview+= (form.persons.value-form.children.value) + ' ' + texts['adults'];
		if (form.children.value>0) {
			overview+= '; ' + form.children.value + ' ' + texts['children'];
		}
		overview+= '; ' + form.rooms.value + ' ' + texts['rooms/holidayFlat'];
		overview+= '</td></tr>';
	//the rest
	overview+= '<tr><th>'+texts['more']+':</th><td>';
		var restNr = 0;
		var rest = "";
		if (0<form.roomCategory.selectedIndex) {
			restNr++;
			rest+= roomCategories[form.roomCategory.selectedIndex];
		}
		if (0<form.maxPrice.selectedIndex) {
			restNr++;
			rest+= (rest.length>0?'; ':'')+texts['max']+' '+form.maxPrice[form.maxPrice.selectedIndex].value+' '+texts['euroSign'];
		}
		if (0<form.catering.selectedIndex) {
			restNr++;
			rest+= (rest.length>0?'; ':'')+texts['catering'][form.catering.selectedIndex];
		}
		var ppp = false;
		if (restNr < 3 && 0<form.houseCategory.selectedIndex) {
			rest+= (rest.length>0?'; ':'')+houseCategories[form.houseCategory.selectedIndex];
		} else if ( 0<form.houseCategory.selectedIndex ) {
			rest+= ' (...)';
			ppp = true;
		}
		var houseEnvCheckboxes = form.elements['houseEnvs[]'];
		for (var i=0; !ppp && i<houseEnvCheckboxes.length; i++) {
			if(houseEnvCheckboxes[i].checked==true) {
				rest+= ' (...)';
				ppp = true;
			}
		}
		var roomEnvCheckboxes = form.elements['roomEnvs[]'];
		for (var i=0; !ppp && i<roomEnvCheckboxes.length; i++) {
			if(roomEnvCheckboxes[i].checked==true) {
				rest+= ' (...)';
				ppp = true;
			}
		}
	
	overview+= rest;
	overview+= '</td></tr>';
	overview+= '</table>';
	
	
	/*if (form.days.value!="" && form.days.value!=0) {
		overview+=", " + form.days.value + ' ' + texts['days'];
	}*/
	/*if (form.persons.value!="" && form.persons.value!=0) {
		overview+= '; ' + form.persons.value + ' ' + texts['adults'];
	}
	if (form.children.value!="" && form.children.value!=0) {
		overview+= '; ' + form.children.value + ' ' + texts['children'];
	}
	if (0<form.houseCategory.selectedIndex) {
		overview+= '; '+houseCategories[form.houseCategory.selectedIndex];
	}
	if (0<form.roomCategory.selectedIndex) {
		rest+= '; '+((form.rooms.value!="" && form.rooms.value!=0)?form.rooms.value+' ':'')+roomCategories[form.roomCategory.selectedIndex];
	}
	if (form.rooms.value!="" && form.rooms.value!=0) {
		overview+= '; ' + form.rooms.value + ' ' + (form.rooms.value>1?texts['rooms']:texts['room']);
	}
	if (0<form.catering.selectedIndex) {
		overview+= '; '+texts['catering'][form.catering.selectedIndex];
	}*/
	//Now look for the environments. first houseEnvs, then roomEnvs
	/*
	Too much room needed! uncomment, if it should be shown.
	var printBreak = true;
	var houseEnvCheckboxes = form.elements['houseEnvs[]'];
	for (var i=0; i<houseEnvCheckboxes.length; i++) {
		if(houseEnvCheckboxes[i].checked==true) {
			if (true == printBreak) {
				overview+= '<br/>';
				printBreak = false;
			}
			overview+= ' '+houseEnvs[houseEnvCheckboxes[i].value];
		}
	}
	var roomEnvCheckboxes = form.elements['roomEnvs[]'];
	for (var i=0; i<roomEnvCheckboxes.length; i++) {
		if(roomEnvCheckboxes[i].checked==true) {
			if (true == printBreak) {
				overview+= '<br/>';
				printBreak = false;
			}
			overview+= ' '+roomEnvs[roomEnvCheckboxes[i].value];
		}
	}*/
	
	document.getElementById("searchOverview").innerHTML = overview;

	document.getElementById("searchHotelForm").style.display = "none";
	document.getElementById("searchOverviewHotel").style.display = "block";
}

/**
* This function will display the form for search rooms and hides the result list and the overview.
*/
function hideSearchOverviewHotel() {
	document.getElementById("searchHotelForm").style.display = "block";
	document.getElementById("searchHotelCaption").innerHTML = texts['header_search_hotel'];
	document.getElementById("searchOverviewHotel").style.display = "none";
	document.getElementById("resultListHotel").style.display = "none";
	hotelBreadCrump.setActualSubmenu(texts['subheader_search']);
	breadCrumpManager.updateActualBreadCrump();
}

/**
* Transmits the search request, displays a waiting message and show the search overview
*/
function getResults(form) {
	document.getElementById("searchHotelCaption").innerHTML = texts['subheader_searchresults']+' <span id="resultCounter"></span>';
	showSearchOverviewHotel();
	document.getElementById('waitMessage').style.display = 'block';
	document.getElementById('resultListHotel').style.display = 'none';
	submitFormGET(form, httpPath+'getResults.php', workResults);
}

/**
* This function manages the processing of the response from searching rooms.
* That means, parsing the xml document, hiding the waitmessage, showing the resultlist and, if possible, updating the map.
*
* @param string data The response body of the request
* @param int responseCode The response code of the request
*/
function workResults(data, responseCode) {

	//Debug
	document.getElementById('debug').value=data;

	//First remove all old results
	if (map != undefined) {
		removeResultsFromMap();
		refreshHouseMarkers();
	}
	
	//Parse the data to xml
	resultXML = GXml.parse(data);
	
	//Now show all
	if(map != undefined) {
		showResultsOnMap();
	}
	document.getElementById('waitMessage').style.display = 'none';
	showResultListHotels();
	workResultErrors();
}

/**
* Will submit a form by using method GET with help of the Google Maps function GDownloadUrl
*
* @param HTMLFormElement form
* @param string url
* @param function func (function has to have the 2 parameter for data and responsecode)
*/
function submitFormGET(form, url, func) {
	var getString = "";
	var i=0;
	//Get all form elements
	for(i=0; i<form.elements.length; i++  ) {
		if (getString.length > 0) {
			getString+= "&";
		}
		//Only checkboxes which are checked and all other form elements
		/*if (form.elements[i].type!='checkbox' && form.elements[i].type!='select-one') {
			alert(form.elements[i].name+":"+form.elements[i].type+":"+form.elements[i].checked);
		}*/
		if ( (form.elements[i].type!='checkbox' && form.elements[i].type!='radio') || form.elements[i].checked==true) {
			getString+= form.elements[i].name+"="+form.elements[i].value;
		}
	}
	//alert(url+"?"+getString);
	//TODO wieder rausnehmen!
	//infoPanel.setHeader('SuchURL');
	//infoPanel.setContent(url+"?"+getString);
	//infoPanel.show();
	GDownloadUrl(url+"?"+getString, func);
}

/**
* This function will cut away the year of a german date.
*
* @param date date A date in the format dd.mm.yyyy
* @return string 
*/
function cutYear(date) {
	var parts = date.split(".");
	return parts[0]+"."+parts[1]+".";
}

function doSomething() {
	alert("Did something!");
}

/**
* This function will switch the page from room search to attraction search
* by hiding the room search main container and showing the attraction search main container.
*/
function switchToAttractionsearch() {

	//Change the main menu
	document.getElementById("menuAttraction").className = 'active';
//	document.getElementById("menuAttractionRight").style.backgroundImage = 'URL('+picActiveRight+')';
//	document.getElementById("menuAttractionLeft").style.backgroundImage = 'URL('+picActiveLeft+')';
	document.getElementById("menuHotel").className = '';
//	document.getElementById("menuHotelRight").style.backgroundImage = 'URL('+picRight+')';
//	document.getElementById("menuHotelLeft").style.backgroundImage = 'URL('+picLeft+')';
	
	//Change the content
	document.getElementById("searchAttraction").style.display = 'block';
	document.getElementById("searchHotel").style.display = 'none';
	
	//Change the breadCrump trail
//	document.getElementById("breadCrumpMenu").innerHTML = breadCrumpMenuAttraction;
//	document.getElementById("breadCrumpSubmenu").innerHTML = '';
//	breadCrumpManager.setActualBreadCrump(attractionBreadCrump);
}

/**
* This function will switch the page from attraction search to room search
* by hiding the attraction search main container and showing the room search main container.
*/
function switchToHotelsearch() {

	document.getElementById("menuAttraction").className = '';
//	document.getElementById("menuAttractionRight").style.backgroundImage = 'URL('+picRight+')';
//	document.getElementById("menuAttractionLeft").style.backgroundImage = 'URL('+picLeft+')';
	document.getElementById("menuHotel").className = 'active';
//	document.getElementById("menuHotelRight").style.backgroundImage = 'URL('+picActiveRight+')';
//	document.getElementById("menuHotelLeft").style.backgroundImage = 'URL('+picActiveLeft+')';
	
	//Change the breadCrump trail
	//document.getElementById("breadCrumpMenu").innerHTML = breadCrumpMenuHotel;
	//document.getElementById("breadCrumpSubmenu").innerHTML = '';
	breadCrumpManager.setActualBreadCrump(hotelBreadCrump);
	
	document.getElementById("searchAttraction").style.display = 'none';
	document.getElementById("searchHotel").style.display = 'block';
}


//Attraction Search functions

/**
* This function handles the event, which is thrown when the attraction maincategory
* of the attraction search form is changed.
* The corresponding subcategories of the maincategory are shown.
*/
function attractionMaincategoryChanged() {
	var id = document.forms['attractionSearchForm'].attractionmaincategoryid.value;
	if (id!=0) {
		document.getElementById('attractionSubcategorys').style.display = 'block';
		for(var i=0; i<attractionMainCategorys.length; i++) {
			if (attractionMainCategorys[i]!=id) {
				document.getElementById('attractionCats'+attractionMainCategorys[i]).style.display = "none";
			} 
		}
		document.getElementById('attractionCats'+id).style.display = "block";
	} else {
		document.getElementById('attractionSubcategorys').style.display = 'none';
	}
}


/**
* Transmits the search request, displays a waiting message and show the search overview.
*
* @param HTMLFormElement form The form, which will be sent.
*/
function getAttractionResults(form) {
	//document.getElementById("searchHotelCaption").innerHTML = texts['subheader_searchresults'];
	showSearchOverviewAttractions();
	document.getElementById('waitMessageAttractions').style.display = 'block';
	document.getElementById('AttractionsResultList').style.display = 'none';
	submitFormGET(form, httpPath+'attractions.php', workAttractionResults);
}

/**
* This functions is the same as the workResult function, but it is for attraction search instead.
*
* @param string data The response body of the request
* @param int responseCode The response code of the request
*/
function workAttractionResults(data, responseCode) {
	
	//Debug
	document.getElementById('debug').value=data;
	
	//First remove all old results
	if (map != undefined) {
		removeResultsAttractionFromMap();
	}
	
	//Parse the data to xml
	resultAttractionXML = GXml.parse(data);
	
	//Now show all
	if(map != undefined) {
		showResultsAttractionOnMap();
	}
	document.getElementById('waitMessageAttractions').style.display = 'none';
	showResultListAttractions();
}

/**
* the same as showResultListHotels, but for attractions instead.
*/
function showResultListAttractions() {

	var attractions = resultAttractionXML.documentElement.getElementsByTagName('attraction');
	var resultList = "";
	
	if (attractions.length>0) {
		for (var i=0; i<attractions.length; i++) {
			var attraction = attractions[i];
			var name = attraction.getAttribute('name');
			var id = attraction.getAttribute('id');
			
			var info = attraction.getElementsByTagName('info')[0];
			var shortDesc = info.getAttribute('short');
			
			var adress = attraction.getElementsByTagName('adress')[0];
			var city = adress.getAttribute('city');
			
			//Now the picture
			var pics = attraction.getElementsByTagName("picture");
			
			//Cache the thumbs
			for (var picI=0; picI<pics.length && picI<2; picI++) {
				var a = new Image();
				a.src = httpPathAttractionPics+'th-'+pics[picI].getAttribute('filename');
				thumbs[thumbs.length] = a;
			}
			
			if (pics.length>0) {
				var filename = 'th-'+pics[0].getAttribute('filename');
			} else {
				var filename = 'nopicture_thumb.jpg';
			}
			
			resultList+= '<div class="result" id="attraction'+id+'" style="clear:both;">';
			resultList+= '		<img class="resultPic" src="'+httpPathAttractionPics+filename+'" onclick="popupAttraction('+id+')" />';
			
			resultList+= '		<img src="'+httpPathIcons+'info_icon.gif" onclick="popupAttraction('+id+')" title="'+texts['moreInformation']+'" style="cursor: pointer;"/>';
			resultList+= '		<b><a href="#" onclick="popupAttraction('+id+')">'+name+'</a></b><br/>';
			resultList+= '		'+city+'<br/>';
			resultList+= '		'+shortDesc+'<br/>';
			if (map!=undefined) {
				resultList+= '		<img src="'+httpPathIcons+'eye.gif" onclick="openAttractionResultInfoWindow('+id+')" title="'+texts['showOnMap']+'" style="vertical-align:-4px; cursor:pointer;" /> ';
				resultList+= '		<a href="#" onclick="openAttractionResultInfoWindow('+id+')">'+texts['showOnMap']+'</a>';
			}
			
			
			resultList+= '<div style="clear:both"></div>';
			resultList+= '</div>';
			
		}
	} else {
		resultList+= '<div style="text-align:center; margin-top: 10px;">';
		resultList+= texts['noAttractionResultsFound'];
		resultList+= '</div>';
	}
	
	document.getElementById('resultListAttraction').innerHTML = resultList;
	document.getElementById('AttractionsResultList').style.display = 'block';
	attractionBreadCrump.setActualSubmenu(texts['subheader_searchresults']);
	breadCrumpManager.updateActualBreadCrump();
}

/**
* This function will open a popup for attraction details.
*
* @param int attractionid The ID of the attraction to show. 
*/
function popupAttraction(attractionid) {
	popup = open('../fo/attractionDetails_popup.php?attractionid='+attractionid+'&page=description', 'attractionDetails', 'width=600,height=620,menubar=0,toolbar=0,status=0,scrollbars=1,resizable=0');
	popup.focus();
}

/**
* Same as showSearchOverviewHotel but for attractions.
*/
function showSearchOverviewAttractions() {
	
	var overview = '';
	
	overview+= texts['searchWord']+': '+document.forms['attractionSearchForm'].search_string.value+'<br/>';
	overview+= texts['chooseAttractionMainCategory']+': '+attractionMainCatNames[document.forms['attractionSearchForm'].attractionmaincategoryid.value];
	
	document.getElementById("searchOverviewAttraction").innerHTML = overview;
	
	document.getElementById("searchAttractionForm").style.display = "none";
	document.getElementById("AttractionsSearchOverview").style.display = "block";
}

/**
* Same as hideSearchOverviewHotel, but for attractions.
*/
function hideSearchOverviewAttractions() {
	document.getElementById("searchAttractionForm").style.display = "block";
	//document.getElementById("searchHotelCaption").innerHTML = texts['header_search_hotel'];
	document.getElementById("AttractionsSearchOverview").style.display = "none";
	document.getElementById("AttractionsResultList").style.display = "none";
	attractionBreadCrump.setActualSubmenu(texts['subheader_search']);
	breadCrumpManager.updateActualBreadCrump();
}

/**
* This function opens a popup for regional information.
*
* @param int regionid The ID of the regional information to show.
*/
function popupRegionalInformation( regionid ) {
	
	/*pageURL = '';
	if ( page != undefined ) {
		pageURL = '&page='+page;
	}
	if ( showOffers==true ) {
		pageURL+= '&oMA=1';
	}
	if (timespanSearch == 1) {
		pageURL += '&timespanSearch=' + timespanSearch;
	}*/
	popup = open('../fo/regionDetails_popup.php?regionid='+regionid, 'regionDetails', 'width=600,height=620,menubar=0,toolbar=0,status=0,scrollbars=1,resizable=0');
	popup.focus();
}

/**
* Brings errors of the search, if occured, into a nice readable form and shows them.
*/
function workResultErrors() {
	var errors = resultXML.documentElement.getElementsByTagName("error");
	var errorString = "";
	if ( 0<errors.length ) {
		if ( 1<errors.length ) {
			errorString = "<ul>";
			for (i=0; i<errors.length; i++) {
				//errorString+= "<li>"+errors[i].textContent+"</li>";
				errorString+= "<li>"+GXml.value(errors[i])+"</li>";
			}
			errorString+= "</ul>";
		} else {
			errorString+= GXml.value(errors[0]);
		}
		fillErrorPanel(errorString);
		infoPanel.setHeader(texts['systemMessage']);
		infoPanel.setContent(errorString);
		infoPanel.show();
	}
}

/**
* shows the error panel
*/
function showErrorPanel() {
	document.getElementById("infoPanel").style.display = "block";
	document.getElementById("infoPanelWindow").style.display = "block";
}

/**
* Puts HTML into the error panel?s content section
*/
function fillErrorPanel(text) {
	document.getElementById("infoPanelBody").innerHTML = text;
}

/**
* Clears the error panel?s content section.
*/
function clearErrorPanel() {
	document.getElementById("infoPanelBody").innerHTML = "";
}

/**
* Hides the error panel and clears its content.
*/
function hideErrorPanel() {
	document.getElementById("infoPanel").style.display = "none";
	document.getElementById("infoPanelWindow").style.display = "none";
	clearErrorPanel();
}

/**
* checks the arrival and departure dates of the room search form.
* @return bool 
*/
function checkFoDates() {

	//First look which field to use
	var arrivalField;
	var departureField;
	if ( document.bookings.searchType[1].checked ) {
		arrivalField = document.bookings.soonestArrival.value;
		departureField = document.bookings.latestDeparture.value;
	} else {
		arrivalField = document.bookings.arrival.value;
		departureField = document.bookings.departure.value;
	}
	
	//Validate dates
	var arr_datetime = arrivalField.split(' ');
	if (!cal_prs_time1(arr_datetime[1], cal_prs_date1(arr_datetime[0]))) return false ;
	arr_datetime = departureField.split(' ');
	if (!cal_prs_time1(arr_datetime[1], cal_prs_date1(arr_datetime[0]))) return false ;
	
	/*if (cal_prs_tsmp1(arrivalField) || cal_prs_tsmp1(departureField)) {
		return false;
	}*/
	
	
	var arrival = convertString2Date(arrivalField);
	var departure = convertString2Date(departureField);
	if (arrival==null) {
		alert(arrivalField+""+texts['invalidArrivaldate']);
		return false;
	}
	
	var today = new Date();
	//today.setDate(today.getDate()+1);
	//Check the arrival
	//Year too small, Month too small and year equal, day too small and year and month equal, then at the past
	if ( arrival.getFullYear()<today.getFullYear() || (arrival.getMonth()<today.getMonth() && arrival.getFullYear()==today.getFullYear()) 
		|| (arrival.getDate()<today.getDate() && arrival.getMonth()==today.getMonth() && arrival.getFullYear()==today.getFullYear())  ) {
		alert(texts['arrivalTooEarly']);
		return false;
	}
	//Check the departure. Has to be at least one day later
	if (departure!=null) {
		arrival.setDate(arrival.getDate()+1);
		if (departure.getFullYear()<arrival.getFullYear() || (departure.getMonth()<arrival.getMonth() && departure.getFullYear()==arrival.getFullYear()) 
			|| (departure.getDate()<arrival.getDate() && departure.getMonth()==arrival.getMonth() && departure.getFullYear()==arrival.getFullYear())) {
			alert(texts['departureTooEarly']);
			return false;
		}
	} else {
		if ( document.bookings.days.value<1 ) {
			alert(texts['overnightsNumberLowerOne']);
			return false;
		}
	}
	
	//Check if persons at least one
	if ( document.bookings.persons.value < 1 ) {
		alert(texts['personsNumberLowerOne']);
		return false;
	}
	
	if ( document.bookings.persons.value-document.bookings.children.value < 1 ) {
		alert(texts['personsNumberLowerChildren']);
		return false;
	}
	
	//Now everything should be ok
	return true;
}

function checkFoArrival() {

	//First look which field to use
	var arrivalField;
	var departureField;
	if ( document.bookings.searchType[1].checked ) {
		arrivalField = document.bookings.soonestArrival.value;
		departureField = document.bookings.latestDeparture.value;
	} else {
		arrivalField = document.bookings.arrival.value;
		departureField = document.bookings.departure.value;
	}
	
	var arrival = convertString2Date(arrivalField);
	if (arrival==null) {
		alert(arrivalField+""+texts['invalidArrivaldate']);
		return false;
	}
	var today = new Date();
	//today.setDate(today.getDate()+1);
	//Check the arrival
	//Year too small, Month too small and year equal, day too small and year and month equal, then at the past
	if ( arrival.getFullYear()<today.getFullYear() || (arrival.getMonth()<today.getMonth() && arrival.getFullYear()==today.getFullYear()) 
		|| (arrival.getDate()<today.getDate() && arrival.getMonth()==today.getMonth() && arrival.getFullYear()==today.getFullYear())  ) {
		alert(texts['arrivalTooEarly']);
		return false;
	}
	var departure = convertString2Date(departureField);
	if (departure!=null) {
		arrival.setDate(arrival.getDate()+1);
		//Check departure
		if (departure.getFullYear()<arrival.getFullYear() || (departure.getMonth()<arrival.getMonth() && departure.getFullYear()==arrival.getFullYear()) 
			|| (departure.getDate()<arrival.getDate() && departure.getMonth()==arrival.getMonth() && departure.getFullYear()==arrival.getFullYear())) {
			alert(texts['departureTooEarly']);
			return false;
		}
	}
}

function checkFoDeparture() {

	//First look which field to use
	var arrivalField;
	var departureField;
	if ( document.bookings.searchType[1].checked ) {
		arrivalField = document.bookings.soonestArrival.value;
		departureField = document.bookings.latestDeparture.value;
	} else {
		arrivalField = document.bookings.arrival.value;
		departureField = document.bookings.departure.value;
	}

	var arrival = convertString2Date(arrivalField);
	var departure = convertString2Date(departureField);
	//Abort check
	if (departure==null) {
		alert(departureField+" "+texts['invalidDeparturedate']);
		return;
	}
	
	
	if (arrival==null) {
		arrival = new Date();
		arrival.setDate(arrival.getDate()+1);//Earliest departures is in 1 day. Cause one afte arrival and earliest arrival is today.
	} else {
		arrival.setDate(arrival.getDate()+1);//Else departure one day after arrival
	}
	//Check departure
	if (departure.getFullYear()<arrival.getFullYear() || (departure.getMonth()<arrival.getMonth() && departure.getFullYear()==arrival.getFullYear()) 
		|| (departure.getDate()<arrival.getDate() && departure.getMonth()==arrival.getMonth() && departure.getFullYear()==arrival.getFullYear())) {
		alert(texts['departureTooEarly']);
		return false;
	}
	//Check, if departure is at the past. (This may occure if arrival is at the past too)
	var today = new Date();
	today.setDate(today.getDate()+1);
	if (departure.getFullYear()<today.getFullYear() || (departure.getMonth()<today.getMonth() && departure.getFullYear()==today.getFullYear()) 
		|| (departure.getDate()<today.getDate() && departure.getMonth()==today.getMonth() && departure.getFullYear()==today.getFullYear())) {
		alert(texts['departureTooEarly']);
		return false;
	}
	
	//Now all should be fine
	return true;
}

//BreadCrump functions
var hotelBreadCrump;
var attractionBreadCrump;
var breadCrumpManager;

/**
* Initializes all breadcrumps and the manager.
* The switch defines which breadcrump should be the default.
* 1 - hotel
* 2 - attraction
* default - hotel
*/
function initializeBreadCrumps(ELEMm, ELEMsub, breadCrumpSwitch) {
	//init the objects
	breadCrumpManager = new BreadCrumpManager(ELEMm, ELEMsub);
	hotelBreadCrump = new BreadCrump(breadCrumpMenuHotel, texts['subheader_search']);
	attractionBreadCrump = new BreadCrump(breadCrumpMenuAttraction, texts['subheader_search']);
	
	//add the objects to the manager
	breadCrumpManager.addBreadCrump(hotelBreadCrump);
	breadCrumpManager.addBreadCrump(attractionBreadCrump);
	
	//set the hotelMenu to the actual
	switch(breadCrumpSwitch) {
		case 2:
			breadCrumpManager.setActualBreadCrump(attractionBreadCrump);
			break;
		case 1:
		default:
			breadCrumpManager.setActualBreadCrump(hotelBreadCrump);
			break;
	}
	
}



/**
* Switches the search form of hotels to standard search
*/
function switchTimesearch2Standard() {
	var form = document.forms['bookings'];
	
	//Enable Standardsearch
	form.arrivalDay.disabled = false;
	form.arrivalMonth.disabled = false;
	form.arrivalYear.disabled = false;
	document.getElementById('arrivalCal').href="javascript:cal1.popup();";
	document.getElementById('arrivalCal').style.cursor = "pointer";
	form.departureDay.disabled = false;
	form.departureMonth.disabled = false;
	form.departureYear.disabled = false;
	document.getElementById('departureCal').href="javascript:cal2.popup();";
	document.getElementById('departureCal').style.cursor = "pointer";
	
	document.getElementById('labelArrival').style.color ="#000000";
	document.getElementById('labelDeparture').style.color ="#000000";
	
	//Disable Timesearch
	form.soonestArrivalDay.disabled = true;
	form.soonestArrivalMonth.disabled = true;
	form.soonestArrivalYear.disabled = true;
	document.getElementById('soonestArrivalCal').href="javascript:return false";
	document.getElementById('soonestArrivalCal').style.cursor = "default";
	form.latestDepartureDay.disabled = true;
	form.latestDepartureMonth.disabled = true;
	form.latestDepartureYear.disabled = true;
	form.days.disabled = true;
	document.getElementById('latestDepartureCal').href="javascript:return false";
	document.getElementById('latestDepartureCal').style.cursor = "default";
	
	document.getElementById('labelSoonestArrival').style.color ="#808080";
	document.getElementById('labelLatestDeparture').style.color ="#808080";
	document.getElementById('labelDays').style.color ="#808080";
	document.getElementById('labelOvernights').style.color ="#808080";
}
/**
* Switches the search form of hotels to timespan search
*/
function switchStandard2Timesearch() {
	var form = document.forms['bookings'];
	
	//Disable Standardsearch
	form.arrivalDay.disabled = true;
	form.arrivalMonth.disabled = true;
	form.arrivalYear.disabled = true;
	document.getElementById('arrivalCal').href="javascript:return false";
	document.getElementById('arrivalCal').style.cursor = "default";
	form.departureDay.disabled = true;
	form.departureMonth.disabled = true;
	form.departureYear.disabled = true;
	document.getElementById('departureCal').href="javascript:return false";
	document.getElementById('departureCal').style.cursor = "default";
	
	document.getElementById('labelArrival').style.color ="#808080";
	document.getElementById('labelDeparture').style.color ="#808080";
	//DEBA94
	
	//Enable Timesearch
	form.soonestArrivalDay.disabled = false;
	form.soonestArrivalMonth.disabled = false;
	form.soonestArrivalYear.disabled = false;
	document.getElementById('soonestArrivalCal').href="javascript:cal3.popup();";
	document.getElementById('soonestArrivalCal').style.cursor = "pointer";
	form.latestDepartureDay.disabled = false;
	form.latestDepartureMonth.disabled = false;
	form.latestDepartureYear.disabled = false;
	form.days.disabled = false;
	document.getElementById('latestDepartureCal').href="javascript:cal4.popup();";
	document.getElementById('latestDepartureCal').style.cursor = "pointer";
	
	document.getElementById('labelSoonestArrival').style.color ="#000000";
	document.getElementById('labelLatestDeparture').style.color ="#000000";
	document.getElementById('labelDays').style.color ="#000000";
	document.getElementById('labelOvernights').style.color ="#000000";
}


function ResultEvent(type, result) {

	this.ADD = 1;
	this.REMOVE = 2;
	this.RESET = 3;

	var result = result;
	var type = type;
	
	this.getResult = function() {
		return result;
	}
	
	this.getType = function() {
		return type;
	}
}

/**
* Verwaltet ResultListener
*/
function ResultListenerManager() {
	var resultListener = new Array();
	
	/**
	* Fügt einen Listener hinzu. Listener benötigt die Methoden
	* resultAdded und resultRemoved
	*/
	this.addResultListener = function(listener) {
		for( i in resultListener ) {
			if ( resultListener[i] == listener ) {
				return;
			}
		}
		resultListener.push(listener);
	}
	
	/**
	* Entfernt den Listener
	*/
	this.removeResultListener = function(listener) {
		var i = 0;
		for( i in resultListener ) {
			if ( resultListener[i] == listener ) {
				resultListener.splice(i, resultListener.length-i, resultListener.slice(i+1));
				break;
			}
		}
	}
	
	/**
	* Entfernt alle Listener
	*/
	this.clearResultListener = function() {
		resultListener = new Array();
	}
	
	/**
	* Feuert ein ResultAdded Event
	*/
	this.fireResultAddedEvent = function(result) {
		var resultEvent = new ResultEvent(ResultEvent.ADD, result);
		for (i in resultListener) {
			resultListener.resultAdded(resultEvent);
		}
	}
	
	/**
	* Feuert ein ResultRemoved Event
	*/
	this.fireResultRemovedEvent = function(result) {
		var resultEvent = new ResultEvent(ResultEvent.REMOVE, result);
		for (i in resultListener) {
			resultListener.resultRemoved(resultEvent);
		}
	}
	
	/**
	 * Gibt an, dass die bisherige Ergebnismenge obsolet wurde.
	 */
	this.fireResultsReseted = function() {
		var resultEvent = new ResultEvent(ResultEvent.RESET, null);
		for (i in resultListener) {
			resultListener.resultReseted(resultEvent);
		}
	}
}