/**
* This file contains all javascript needed for the map. 
*
* @author Jens Kendl
* @package Imevia
* @subpackage Frontoffice
*/

//global Vars
/**
* This array contains all Markers for houses showed on the map.
* The index of every field is the houseid
* @global array houseMarkers A assoziative array with GMarker objects. Format: [houseid][ 'marker' | 'infoTabs' ]
*/
var houseMarkers = new Array();
/**
* This array contains all Markers for attractions showed on the map.
* The index of every field is the attractionid
* @global array attractionMarkers A assoziative array with GMarker objects. Format: [houseid][ 'marker' | 'infoTabs' ]
*/
var attractionMarkers = new Array();
/**
* This array contains all Markers for results of houses showed on the map.
* The index of every field is the houseid
* @global array resultMarkers A assoziative array with GMarker objects. Format: [houseid][ 'marker' | 'infoTabs' ]
*/
var resultMarkers = new Array();
/**
* This array contains all Markers for results of attractions showed on the map.
* The index of every field is the attractionid
* @global array resultAttractionMarkers A assoziative array with GMarker objects. Format: [houseid][ 'marker' | 'infoTabs' ]
*/
var resultAttractionMarkers = new Array();
var basket; // Not used yet. Should be for the markers of the basket
/**
* This object manages all manual showed entries on the map.
* @global EntryManager
*/
var manualEntries;

//The map itself
/**
* The map itself
* @global GMap2 map
*/
var map;

var functionToExecuteAfterMapInit;

//Create the needed icons
	// Create our "house" marker icon
	/**
	* The icon for showing a house
	* @global GIcon houseIcon
	*/
	var houseIcon = new GIcon();
	houseIcon.image = httpPathIcons + "house.png";
	houseIcon.shadow = httpPathIcons + "house_shadow.png";
	houseIcon.iconSize = new GSize(25, 16);
	houseIcon.shadowSize = new GSize(25, 16);
	houseIcon.iconAnchor = new GPoint(6, 20);
	houseIcon.infoWindowAnchor = new GPoint(5, 1);
	// Create our "house_search" marker icon
	/**
	* The icon for showing a result of a house
	* @global GIcon houseSearchIcon
	*/
	var houseSearchIcon = new GIcon();
	houseSearchIcon.image = httpPathIcons + "houseSearch.png";
	houseSearchIcon.shadow = httpPathIcons + "house_shadow.png";
	houseSearchIcon.iconSize = new GSize(25, 16);
	houseSearchIcon.shadowSize = new GSize(25, 16);
	houseSearchIcon.iconAnchor = new GPoint(6, 20);
	houseSearchIcon.infoWindowAnchor = new GPoint(5, 1);
	// Create our "attraction" marker icon
	/**
	* The icon for showing a attraction
	* @global GIcon attIcon
	*/
	var attIcon = new GIcon();
	attIcon.image = httpPathIcons + "flag_red.png";
	attIcon.shadow = httpPathIcons + "flag_red_shadow.png";
	attIcon.iconSize = new GSize(25, 16);
	attIcon.shadowSize = new GSize(25, 16);
	attIcon.iconAnchor = new GPoint(6, 20);
	attIcon.infoWindowAnchor = new GPoint(5, 1);
	// Create our "attraction_search" marker icon
	/**
	* The icon for showing a result of a attraction
	* @global GIcon attSearchIcon
	*/
	var attSearchIcon = new GIcon();
	attSearchIcon.image = httpPathIcons + "flag_redSearch.png";
	attSearchIcon.shadow = httpPathIcons + "flag_red_shadow.png";
	attSearchIcon.iconSize = new GSize(25, 16);
	attSearchIcon.shadowSize = new GSize(25, 16);
	attSearchIcon.iconAnchor = new GPoint(6, 20);
	attSearchIcon.infoWindowAnchor = new GPoint(5, 1);

/**
* Stores, if the houses are shown on the map or not.
* 0 - no houses shown, 1 - houses shown
* @global int houseclick
*/
var houseclick=0;
/**
* Display or hide houses, build the map popups and add them to the map.
*/
function houseView() {
	if (houseclick==0){
		//alert("ich bin drin");
		
		GDownloadUrl(httpPath+"getHouses.php", function(data, responseCode) {
			
			document.getElementById('debug').value=data;
			
			var themarker;
			xmlDoc = GXml.parse(data);
			housesXML = xmlDoc;
			
			//Check if there are some resultMarkers on the map
			if (resultXML!=undefined) {
				var resultHouses=resultXML.documentElement.getElementsByTagName('house');
			}
			
			var houses = housesXML.documentElement.getElementsByTagName("house");
			
			
			houseMarkers = new Array();
			thumbs = new Array(); //For caching the pictures
			
			for (var i = 0; i < houses.length; i++) {
				var house = houses[i];
				
				//Create the point for the marker
				var markerXML = house.getElementsByTagName("marker");
				var point = new GLatLng(parseFloat(markerXML[0].getAttribute("lat")),
										parseFloat(markerXML[0].getAttribute("lng")) );
				
				var pics = house.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;
				}
				
				//Create the tab texts
				//var infotext = "<div class='mapPopup'>";
				//infotext += getHouseInfoTabText(house, pics);
				//infotext+= "<input type='button' class='button' value='"+texts['moreInfo']+"' onclick='popupHotelDetail("+house.getAttribute('houseid')+",\"description\");'/>";
				//infotext+= "</div>";
				
				var moreInfo = "<div class='mapPopup'>";
				moreInfo+= getHouseMoreInfoTabText(house, pics, false);
				moreInfo+= "</div>";
				
				var infoTabs = [
								new GInfoWindowTab(texts['tabAdditionalInfo'], moreInfo)
								];
				
				//Check if there is a resultMarker of the house on the map
				var printMarker = true;
				if (resultHouses!=undefined) {
					for(var i2=0; i2<resultHouses.length; i2++) {
						if (resultHouses[i2].getAttribute('houseid')==house.getAttribute('houseid')) {
							printMarker = false;
						}
					}
				}
				if (manualEntries instanceof EntryManager && manualEntries.containsHouse(house.getAttribute('houseid'))) {
					printMarker = false;
				}
				
				//Put the marker on the map, if no resultMarker is there
				themarker = createMarker(point, infoTabs, houseIcon);
				addMarkers(houseMarkers, i, themarker, infoTabs);
				/*houseMarkers[i] = new Array();
				houseMarkers[i]['marker'] = themarker;
				houseMarkers[i]['infoTabs'] = infoTabs;*/
				//houseMarkers[i] = themarker;
				if (true==printMarker) {
					map.addOverlay(themarker);
				}
			}
		});
		houseclick=1;
		//Change the legend of the map and tell the user that there are houses shown.
		var houseSearchButton = document.getElementById('houseSelectionButton');
		houseSearchButton.style.backgroundImage = 'url('+httpPathImages+'verlauf_orange_weiss.png)';
	} else {
		//Remove all houses
		removeMarkers(houseMarkers);
		houseMarkers = new Array();
		houseclick=0;
		//Change the legend of the map and tell the user that there are NO houses shown.
		var houseSearchButton = document.getElementById('houseSelectionButton');
		houseSearchButton.style.backgroundImage = 'url('+httpPathImages+'verlauf_grau_up.png)';
	}
}

/**
* Removes all markers of the array from the map.
* 
* @param array markerArray
*/
function removeMarkers(markerArray) {
	for (var i in markerArray) {
		map.removeOverlay(markerArray[i]['marker']);
	}
}

/**
* Adds a marker and its infoTabs into the array
*
* @param array markerArray The array to add to.
* @param int index The index where to add to.
* @param GMarker The marker itself.
* @param array infoTabs the content of the map popup. 
*/
function addMarkers(markerArray, index, marker, infoTabs) {
	markerArray[index] = new Array();
	markerArray[index]['marker'] = marker;
	markerArray[index]['infoTabs'] = infoTabs;
}

/**
* Refresh the house markers.
* This function will delete and then add all house markers to the map.
*/
function refreshHouseMarkers() {
	if ( houseclick==1 ) {
		removeMarkers(houseMarkers);
		for(var i in houseMarkers) {
			map.addOverlay(houseMarkers[i]['marker']);
		}
	}
}


/**
* Stores, if the attractions are shown on the map or not.
* 0 - no attractions shown, 1 - attractions shown
* @global int attclick
*/
var attclick=0;
/**
* Display or hide attractions, build the map popups and add them to the map.
*/
function attractionView() {
	if (attclick==0){
		
		//function checkOn(marker) {
		//}
			
			GDownloadUrl(httpPath+"getAttractions.php", function(data, responseCode) {
				
				document.getElementById('debug').value=data;
				
				var themarker;
				
				attractionsXML = GXml.parse(data);
				//alert(xml.firstChild);
				
				var attractions = attractionsXML.documentElement.getElementsByTagName("attraction");
				
				for (var i=0; i<attractions.length; i++) {
					
					attraction = attractions[i];
					var id = attraction.getAttribute("id");
					
					var marker = attraction.getElementsByTagName("marker")[0];
					var point = new GLatLng(parseFloat(marker.getAttribute("lat")), parseFloat(marker.getAttribute("lng")));
					
					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;
					}
					
					var infotext = "<div class='mapPopup'>";
					infotext+= getAttractionInfoTabText(attraction, pics);
					infotext+= "<br/><input type='button' class='button' value='"+texts['moreInfo']+"' onclick='popupAttraction("+id+");'/>";
					infotext+= "</div>";
					
					var moreInfo = "<div class='mapPopup'>";
					moreInfo+= getAttractionMoreInfoTabText(attraction, pics);
					moreInfo+= "</div>";
					
					//Make the infotabs
					var infoTabs = [
									new GInfoWindowTab(texts['tabInfo'], infotext),
									new GInfoWindowTab(texts['tabAdditionalInfo'], moreInfo)
									];
					
					//Create the marker and add it to the map
					themarker = createMarker(point, infoTabs, attIcon);
					map.addOverlay(themarker);
					
					addMarkers(attractionMarkers, i, themarker, infoTabs);
					
				}
			}
		);
		attclick=1;
		//Change the legend of the map and tell the user that there are houses shown.
		var houseSearchButton = document.getElementById('attractionSelectionButton');
		houseSearchButton.style.backgroundImage = 'url('+httpPathImages+'verlauf_orange_weiss.png)';
  	} else {
  		removeMarkers(attractionMarkers);
  		attractionMarkers = new Array();
  		attclick=0;
		//Change the legend of the map and tell the user that there are houses shown.
		var houseSearchButton = document.getElementById('attractionSelectionButton');
		houseSearchButton.style.backgroundImage = 'url('+httpPathImages+'verlauf_grau_up.png)';
	}
  
}

//Initialize the map.
/**
* Initialize the map.
* That means, add the controls and listeners
*/
function load() {
	//Check if the browser is able to 
	if (GBrowserIsCompatible()) {
	
		//create the map and add those needed controls
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		var overviewControl = new GOverviewMapControl();
		map.addControl(overviewControl);
		overviewControl.hide();
		//map.addControl(new HouseControl());
		//map.addControl(new AccControl());
		map.setCenter(new GLatLng(startLatitude, startLongitude), startZoomlevel);
		
		GEvent.addListener(map, "moveend", updateRegionalInfo);
		GEvent.addListener(map, "zoomend", zoomStopped);
		updateRegionalInfo();
		
		if ( typeof functionToExecuteAfterMapInit == "function" ) {
			functionToExecuteAfterMapInit();
		}
	}
}

// Creates a marker at the given point with the given number label
/**
* Creates a marker at the given point with the given number label
* and adds the listener for opening the map popup
*
* @param GLatLng point
* @param array infoTabs
* @param GIcon markerIcon
*/
function createMarker(point, infoTabs, markerIcon) {
	var marker = new GMarker(point, markerIcon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowTabsHtml(infoTabs,{maxWidth: 150});
	} );
	return marker;
}

/**
* This function opens the map popup of a given house
*
* @param int houseid
*/
function openHouseResultInfoWindow(houseid) {
	if (resultMarkers[houseid]!=undefined) {
		resultMarkers[houseid]['marker'].openInfoWindowTabsHtml(resultMarkers[houseid]['infoTabs'],{maxWidth: 150});
	}
}

/**
* This function will show the houses of a search for rooms on the map.
* It also adds to the standard output of the map popup the match and the price of the search.
* The global variable resultXML has to be filled before.
*/
function showResultsOnMap() {
	
	//Change the legend of the map and tell the user that there are search results
	var houseSearchButton = document.getElementById('houseSearchResultsButton');
	houseSearchButton.style.backgroundImage = 'url('+httpPathImages+'verlauf_orange_weiss.png)';
	
	//Get the relevant data
	var houses = resultXML.documentElement.getElementsByTagName("house");
	
	var timespanSearch = resultXML.documentElement.getAttribute('timespanSearch');
	
	//resultMarkers = new Array(houses.length);
	thumbs = new Array();//array for preloading the thumbs.

	for (var i=0; i<houses.length; i++) {
		house = houses[i];
		var houseid = house.getAttribute('houseid');
		//Create the point for the marker
		var markerXML = house.getElementsByTagName("marker");
		var point = new GLatLng(parseFloat(markerXML[0].getAttribute("lat")),
								parseFloat(markerXML[0].getAttribute("lng")) );
		
		var bestprice = house.getElementsByTagName("bestprice")[0].getAttribute("value");
		var bestmatch = house.getElementsByTagName("bestmatch")[0].getAttribute("value");
		
		//Now the picture
		var pics = house.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;
		}
		
		var infotext = "<div class='mapPopup'>";
		infotext += getHouseInfoTabText(house, pics);
		//infotext+= "<br/>"+texts['price']+": "+texts['startAt']+" "+number_format(bestprice/100, 2, ',', '.')+" "+texts['currency']+"<br/>"+texts['hitRate']+": "+bestmatch+"%<br/>";
		//infotext+= "<input type='button' class='button' value='"+texts['detailButton']+"' onclick='popupHotelDetail("+houseid+",\"offers\""+(timespanSearch==1?','+timespanSearch:'')+");'/>";
		infotext+= "</div>";
		
		var moreInfo = "<div class='mapPopup'>";
		moreInfo+= getHouseMoreInfoTabText(house, pics, true);
		moreInfo+= "</div>";
		
		//Make the infotabs
		var infoTabs = [
						new GInfoWindowTab(texts['tabInfo'], infotext),
						new GInfoWindowTab(texts['tabAdditionalInfo'], moreInfo)
						];
		
		//Create the marker and add it to the map
		themarker = createMarker(point, infoTabs, houseSearchIcon);
		map.addOverlay(themarker);
		
		//New for popups
		addMarkers(resultMarkers, houseid, themarker, infoTabs);
		
		addListenerForResultHighlight(themarker, houseid);
	}
}

/**
* Create the tab info text out of a xml-element.
* @param houseXML The house xml element
* @param pics The picture xml elem. (Could be extracted of the houseXML, but for performance issues, it is given by)
* return string
*/
function getHouseInfoTabText(houseXML, pics) {
	
	var rating = houseXML.getElementsByTagName("rating")[0].getAttribute("overall");
	var bestprice = houseXML.getElementsByTagName("bestprice")[0].getAttribute("value");
	var bestmatch = houseXML.getElementsByTagName("bestmatch")[0].getAttribute("value");
	
	var adress = houseXML.getElementsByTagName("adress")[0];
	var houseid = houseXML.getAttribute('houseid');
	var name = houseXML.getAttribute("name");
	var cityid = adress.getAttribute("cityid");
	
	var timespanSearch = resultXML.documentElement.getAttribute('timespanSearch');
	
	
	switch(rating) {
		case 3:
			var eval = texts['positiveEval'];
			break;
		case 1:
			var eval = texts['negativeEval'];
			break;
		case 2:
		default:
			var eval = texts['neutralEval'];
	}
	
	var infotext = '<a href="javascript:popupHotelDetail('+houseid+',\'description\',true'+(timespanSearch==1?','+timespanSearch:'')+')" class="title" title="'+texts['moreInformation']+'"><img src="'+httpPathIcons+'info_icon.gif" title="'+texts['moreInformation']+'"/> ';
	infotext+= name + "</a><br/>";
	infotext+= cities[cityid];// + "<br/>";
	if (pics.length>0) {
		infotext+= "<img class='rightThumb' src='"+httpPathHousePics+"th-"+pics[0].getAttribute("filename")+"'/>";
	}
	infotext+= '<h3>'+texts['wishMatch']+':</h3>';
	infotext+= '<img src="'+httpPathIcons+'wish_icon.gif" title="'+texts['wishMatch']+' style="vertical-align:-2px;"/>'+bestmatch+'%';
	
	infotext+= '<h3 style="margin-top:5px;">'+texts['Evaluation']+':</h3>';
	for (var ri=0; ri<rating; ri++) {
		infotext+= '		<img src="'+httpPathIcons+'thumb_up.gif" title="'+eval+'" onclick="popupHotelDetail('+houseid+',\'evaluations\',true'+(timespanSearch==1?','+timespanSearch:'')+');" style="cursor:pointer;" />';
	}
	
	infotext+= '<br/><br/><h3 class="price">'+texts['price']+':</h3>';
	infotext+= '<a class="price" href="javascript:popupHotelDetail('+houseid+',\'offers\',true'+(timespanSearch==1?','+timespanSearch:'')+');"/>'+texts['startAt']+' '+number_format(bestprice/100, 2, ',', '.')+' '+texts['euroSign']+'<br/>';
	infotext+= '<input type="button" class="button" value="'+texts['detailButton']+'" onclick="popupHotelDetail('+houseid+',\'offers\',true'+(timespanSearch==1?','+timespanSearch:'')+');"/>';
	
	return infotext;
}

/**
* Create the tab moreInfo text out of a xml-element.
* @param houseXML The house xml element
* @param pics The picture xml elem. (Could be extracted of the houseXML, but for performance issues, it is given by)
* return string
*/
function getHouseMoreInfoTabText(houseXML, pics, isSearchResult) {

	var timespanSearch = 0;
	var showOffers = false;
	if (isSearchResult) {
		showOffers = true;
		timespanSearch = resultXML.documentElement.getAttribute('timespanSearch');
	}
	
	//Prepare data
	if ( houseXML instanceof House ) {
		var houseid = houseXML.id;
		var rating = houseXML.rating;
		var name = houseXML.name;
		var cityid = houseXML.cityid;
		var shortDesc = houseXML.shortDesc;
		var picture = houseXML.picture;
		if (picture!='') {
			picture = "<img class='rightThumb' src='"+httpPathHousePics+"th-"+picture+"'/>";
		}
		var houseConfigs = houseXML.configs;
		var houseConfigText = '';
		for(ic in houseConfigs) {
			if (houseConfigText!='') {
				houseConfigText+= ", ";
			}
			houseConfigText+= houseConfigs[ic];
		}
	} else {
		var adress = houseXML.getElementsByTagName("adress")[0];
		var rating = houseXML.getElementsByTagName("rating")[0].getAttribute("overall");
		var houseid = houseXML.getAttribute('houseid');
		var name = houseXML.getAttribute("name");
		var cityid = adress.getAttribute("cityid");
		
		var info = houseXML.getElementsByTagName("info")[0];
		var houseconfigurations = houseXML.getElementsByTagName("houseconfigurations")[0];
		
		var shortDesc = info.getAttribute("short");
		var houseConfigs = houseconfigurations.getElementsByTagName("config");
		var houseConfigText = '';
		for(ic=0; ic<houseConfigs.length; ic++) {
			if (houseConfigText!='') {
				houseConfigText+= ", ";
			}
			houseConfigText+= houseConfigs[ic].getAttribute('name');
		}
		
		var picture = '';
		if (pics.length>1 && isSearchResult) {
			picture+="<img class='rightThumb' src='"+httpPathHousePics+"th-"+pics[1].getAttribute("filename")+"'/>";
		} else if (pics.length>0) {
			picture+="<img class='rightThumb' src='"+httpPathHousePics+"th-"+pics[0].getAttribute("filename")+"'/>";
		}
	}
	
	
	var moreInfo = '<a href="javascript:popupHotelDetail('+houseid+',\'description\','+showOffers+(timespanSearch==1?','+timespanSearch:'')+')" class="title" title="'+texts['moreInformation']+'"><img src="'+httpPathIcons+'info_icon.gif" title="'+texts['moreInformation']+'"/> ';
	moreInfo+= name + "</a><br/>";
	moreInfo+= cities[cityid];// + "<br/>";
	
	moreInfo+= picture;
	moreInfo+= '<br />';
	moreInfo+='<h3>'+texts['description']+'</h3>';
	moreInfo+= shortDesc;
	moreInfo+= "<br style='clear:both;' />";
	if (houseConfigs.length>0) {
		moreInfo+= "<h3>"+texts['configuration']+":</h3>";
		moreInfo+=houseConfigText;
	}
	
	if (isSearchResult) {
		moreInfo+= '<br/><input type="button" class="button" value="'+texts['detailButton']+'" onclick="popupHotelDetail('+houseid+',\'offers\',true'+(timespanSearch==1?','+timespanSearch:'')+');"/>';
	} else {
		switch(rating) {
			case 3:
				var eval = texts['positiveEval'];
				break;
			case 1:
				var eval = texts['negativeEval'];
				break;
			case 2:
			default:
				var eval = texts['neutralEval'];
		}
		moreInfo+= '<h3 style="margin-top:5px;">'+texts['Evaluation']+':</h3>';
		for (var ri=0; ri<rating; ri++) {
			moreInfo+= '		<img src="'+httpPathIcons+'thumb_up.gif" title="'+eval+'" onclick="popupHotelDetail('+houseid+',\'evaluations\');" style="cursor:pointer;" />';
		}
	}
	
	return moreInfo;
}

/**
* This function will remove all results of a search for rooms off the map.
*/
function removeResultsFromMap() {
	removeMarkers(resultMarkers);
	resultMarkers = new Array();
	var houseSearchButton = document.getElementById('houseSearchResultsButton');
	houseSearchButton.style.backgroundImage = 'url('+httpPathImages+'verlauf_grau_up.png)';
}

/**
* This function adds listeners to the map for highlighting house results on the result list.
*
* @param GMarker marker The marker of the result to hightlight
* @param int houseid
*/
function addListenerForResultHighlight(marker, houseid) {
	
	GEvent.addListener(marker, "mouseover", function() {
		//alert(document.getElementById('house'+houseid).style.backgroundColor);
		document.getElementById('house'+houseid).style.backgroundColor = "#EFEFEF";
	});
	GEvent.addListener(marker, "mouseout", function() {
		document.getElementById('house'+houseid).style.backgroundColor = "#FFFFFF";
	});
}

/**
* Opens the map popup of an attraction search marker
*
* @param int attractionid
*/
function openAttractionResultInfoWindow(attractionid) {
	if (resultAttractionMarkers[attractionid]!=undefined) {
		resultAttractionMarkers[attractionid]['marker'].openInfoWindowTabsHtml(resultAttractionMarkers[attractionid]['infoTabs'],{maxWidth: 150});
	}
}

/**
* This function will show the attractions of a attraction search on the map.
* The global variable resultAttractionXML has to be filled before.
*/
function showResultsAttractionOnMap() {
	
	//Get the relevant data
	var attractions = resultAttractionXML.documentElement.getElementsByTagName("attraction");
	var themarker = null;
	
	for (var i=0; i<attractions.length; i++) {
		attraction = attractions[i];
		var id = attraction.getAttribute("id");
		
		var marker = attraction.getElementsByTagName("marker")[0];
		var point = new GLatLng(parseFloat(marker.getAttribute("lat")), parseFloat(marker.getAttribute("lng")));
		
		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;
		}
		
		var infotext = "<div class='mapPopup'>";
		infotext+= getAttractionInfoTabText(attraction, pics);
		infotext+= "<br/><input type='button' class='button' value='"+texts['moreInfo']+"' onclick='popupAttraction("+id+");'/>";
		infotext+= "</div>";
		
		var moreInfo = "<div class='mapPopup'>";
		moreInfo+= getAttractionMoreInfoTabText(attraction, pics);
		moreInfo+= "</div>";
		
		//Make the infotabs
		var infoTabs = [
						new GInfoWindowTab(texts['tabInfo'], infotext),
						new GInfoWindowTab(texts['tabAdditionalInfo'], moreInfo)
						];
		
		//Create the marker and add it to the map
		themarker = createMarker(point, infoTabs, attSearchIcon);
		map.addOverlay(themarker);
		
		//New for popups
		addMarkers(resultAttractionMarkers, id, themarker, infoTabs);
		
		//Add Highlightlisteneres
		addListenerForAttractionResultHighlight(themarker, id);
	}
}


/**
* Create the tab info text out of a attraction xml-element.
* @param attractionXML The attraction xml element
* @param pics The picture xml elem. (Could be extracted of the attractionXML, but for performance issues, it is given by)
* return string
*/
function getAttractionInfoTabText(attractionXML, pics) {
	
	var picture = '';
	if (attractionXML instanceof Attraction) {
		var name = attractionXML.name;
		var street = attractionXML.street;
		var zip = attractionXML.zip;
		var city = attractionXML.city;
		var phone = attractionXML.phone;
		var fax = attractionXML.fax;
		var email = attractionXML.email;
		var url = attractionXML.url;
		
		var pictures = attractionXML.pictures;
		if (pictures.length>0) {
			picture = "<img class='rightThumb' src='"+httpPathAttractionPics+"th-"+pictures[0]+"'/>";
		}
		
	} else {
		var adress = attractionXML.getElementsByTagName("adress")[0];
		var info = attractionXML.getElementsByTagName("info")[0];
		
		var name = attractionXML.getAttribute("name");
		var street = adress.getAttribute("street");
		var zip = adress.getAttribute("zipcode");
		var city = adress.getAttribute("city");
		var phone = adress.getAttribute("phone");
		var fax = adress.getAttribute("fax");
		var email = adress.getAttribute("email");
		var url = info.getAttribute("url");
		
		if (pics.length>0) {
			picture = "<img class='rightThumb' src='"+httpPathAttractionPics+"th-"+pics[0].getAttribute("filename")+"'/>";
		}
	}
	
	
	var infotext = "<b>" + name + "</b><br/>";
	infotext+= picture;
	infotext+= "<br />";	
	infotext+= street + "<br/>" + zip + " " + city + "<br/>";
	infotext+= "<br style='clear:both;'/>";
	infotext+= texts['phone']+": "+phone+"<br/>";
	infotext+= texts['fax']+": "+fax+"<br/>";
	infotext+= texts['email']+": "+email+"<br/>";
	
	return infotext;
}

/**
* Create the tab moreInfo text out of a attraction xml-element.
* @param attractionXML The attraction xml element
* @param pics The picture xml elem. (Could be extracted of the attractionXML, but for performance issues, it is given by)
* return string
*/
function getAttractionMoreInfoTabText(attractionXML, pics) {

	var picture = '';
	if (attractionXML instanceof Attraction) {
		var name = attractionXML.name;
		
		var shortDesc = attractionXML.shortDesc;
//		var approach = attractionXML.approach;
//		var opening = attractionXML.opening;
		var id = attractionXML.id;
		
		var pictures = attractionXML.pictures;
		if (pictures.length>1) {
			picture ="<img class='rightThumb' src='"+httpPathAttractionPics+"th-"+pictures[1]+"'/>";
		} else if (pictures.length>0) {
			picture ="<img class='rightThumb' src='"+httpPathAttractionPics+"th-"+pictures[0]+"'/>";
		}
		
	} else {
		var name = attractionXML.getAttribute("name");
		var info = attractionXML.getElementsByTagName("info")[0];
		
		var shortDesc = info.getAttribute("short");
//		var approach = info.getElementsByTagName("approach")[0];
//		var opening = info.getElementsByTagName("opening")[0];
		var id = attraction.getAttribute("id");
		
		if (pics.length>1) {
			picture ="<img class='rightThumb' src='"+httpPathAttractionPics+"th-"+pics[1].getAttribute("filename")+"'/>";
		} else if (pics.length>0) {
			picture ="<img class='rightThumb' src='"+httpPathAttractionPics+"th-"+pics[0].getAttribute("filename")+"'/>";
		}
	}
	
	var moreInfo = "";
	moreInfo+= "<b>" + name + "</b><br/>";
	moreInfo+= picture;
	moreInfo+= "<br />";
	moreInfo+= shortDesc;
	moreInfo+= "<br />";
	moreInfo+= "<br/><input type='button' class='button' value='"+texts['moreInfo']+"' onclick='popupAttraction("+id+");'/>";
//	moreInfo+= "<h3>"+texts['openingTimes']+"</h3>";
//	moreInfo+= GXml.value(opening);
//	moreInfo+= "<h3>"+texts['approachInformation']+"</h3>";
//	moreInfo+= GXml.value(approach);
	
	return moreInfo;
}

/**
* Removes all markers of an attraction search off the map.
*/
function removeResultsAttractionFromMap() {
	removeMarkers(resultAttractionMarkers);
	resultAttractionMarkers = new Array();
}

/**
* Adds listener to the map for highlighting results of a attraction search.
*
* @param GMarker The attraction search marker
* @param int attractionid
*/
function addListenerForAttractionResultHighlight(marker, attractionid) {
	
	GEvent.addListener(marker, "mouseover", function() {
		//alert(document.getElementById('house'+houseid).style.backgroundColor);
		document.getElementById('attraction'+attractionid).style.backgroundColor = "#EFEFEF";
	});
	GEvent.addListener(marker, "mouseout", function() {
		document.getElementById('attraction'+attractionid).style.backgroundColor = "#FFFFFF";
	});
}

//Regionalinformation functions

/**
* This function will start the update for regional information.
* It is used as listener at the map.
*
* @param int oldLevel The zoomlevel from before the zoom.
* @param int newLevel The new zoomlevel.
*/
function zoomStopped(oldLevel, newLevel) {
	updateRegionalInfo();
}

/**
* This stores the id of the actual regional information
* @global int idOfActualRegionalInfo
*/
var idOfActualRegionalInfo = 0;
/**
* Gets regional information for the center and zoomlevel of the map
* and chances the displayed one, if required.
*/
function updateRegionalInfo() {
	var zoomlevel = map.getZoom();
	var latlng = map.getCenter();
	
	
	GDownloadUrl(httpPath+"getRegioInfo.php?x="+latlng.lat()+"&y="+latlng.lng()+"&zl="+zoomlevel, function(data, responseCode) {
		document.getElementById('debug').value=data;
		
		var regioXML = GXml.parse(data);
		
		var regionalInfos = regioXML.getElementsByTagName("regionalinformation");
		
		if ( regionalInfos.length>0 ) {
			var regionalInfo = regionalInfos[0];
			var id = regionalInfo.getAttribute("id");
			
			if ( id!=idOfActualRegionalInfo ) {
				var name = regionalInfo.getAttribute("name");
				//var info = regionalInfo.getElementsByTagName("infotexts")[0];
				//var shortInfo = info.getAttribute("short");
				
				idOfActualRegionalInfo=id;
				
				var maxLength = 36; //Number of characters allowed
				//maxLength-=(name.length+3);
				var text = "<b>"+name+"</b>";
				/*if (maxLength>0) {
					text+= " - ";
					text+= shortInfo.substring(0, maxLength);
					if (shortInfo.length>maxLength) {
						text+= "...";
					}
				}*/
				
								
				document.getElementById("regioInfoText").innerHTML = text;  
				document.getElementById("regionalLink").setAttribute('href', "javascript:location.href = '../"+id+"_region/region.html'");
			}
			
		} else {
			document.getElementById("regioInfoText").innerHTML = "";
			document.getElementById("regionalLink").setAttribute('href', "javascript: return false;");
		}
	});
}

function doNothing() {
	return false;
}


/**
* Manages Entries of Houses and attractions.
* Contains house and attraction objects
*/
function EntryManager() {
	/**
	* This array contains all manually setted houses
	*/
	this.houses = new Array();
	this.houseMarkers = new Array();
	/**
	* This array contains all manually setted attractions
	*/
	this.attractions = new Array();
	this.attractionMarkers = new Array();
	
	this.addHouse = function(house) {
		this.houses[house.id] = house;
	}
	
	this.containsHouse = function(houseid) {
		return this.houses[houseid] instanceof House;
	}
	
	this.getHouses = function() {
		return this.houses;
	}
	
	this.addAttraction = function(attraction) {
		this.attractions[attraction.id] = attraction;
	}
	
	this.containsAttraction = function(attractionid) {
		return this.attractions[attractionid] instanceof Attraction;
	}
	
	this.getAttractions = function() {
		return this.attractions;
	}
	
	this.createHouseMarkers = function() {
		
		//var houses = manualEntries.getHouses();
		
		thumbs = new Array(); //For caching the pictures
		
		var house;
		for (i in this.houses) {
			 house = this.houses[i];
			
			if (this.houseMarkers[house.id]==undefined || this.houseMarkers[house.id]==null ) {
				//Create the point for the marker
				var point = new GLatLng(parseFloat(house.x),
										parseFloat(house.y) );
				
				var pic = house.picture;
				
				//Cache the thumbs
				var a = new Image();
				a.src = httpPathHousePics+'th-'+pic;
				thumbs[thumbs.length] = a;
				
				//Create the tab texts
				var moreInfo = "<div class='mapPopup'>";
				moreInfo+= getHouseMoreInfoTabText(house, pic, false);
				moreInfo+= "</div>";
				
				var infoTabs = [
								new GInfoWindowTab(texts['tabAdditionalInfo'], moreInfo)
								];
				
				//Put the marker on the map
				themarker = createMarker(point, infoTabs, houseIcon);
				map.addOverlay(themarker);
				this.houseMarkers[house.id] = new Array();
				this.houseMarkers[house.id]['marker'] = themarker;
				this.houseMarkers[house.id]['infoTabs'] = infoTabs;
									
				addListenerForResultHighlight(themarker, house.id);
			}
		}
	}
	
	this.createAttractionMarkers = function() {
		
		//var houses = manualEntries.getHouses();
		
		thumbs = new Array(); //For caching the pictures
		
		var attraction;
		for (i in this.attractions) {
			 attraction = this.attractions[i];
			
			if (this.attractionMarkers[attraction.id]==undefined || this.attractionMarkers[attraction.id]==null ) {
				//Create the point for the marker
				var point = new GLatLng(parseFloat(attraction.x),
										parseFloat(attraction.y) );
				
				var pics = attraction.pictures;
				
				//Cache the thumbs
				var a = null;
				for(var i2=0; i2<pics.length; i2++) {
					a = new Image();
					a.src = httpPathAttractionPics+'th-'+pics[i2];
					thumbs[thumbs.length] = a;
				}
				
				//Create the tab texts
				var info = "<div class='mapPopup'>";
				info+= getAttractionInfoTabText(attraction);
				info+= "</div>";
				var moreInfo = "<div class='mapPopup'>";
				moreInfo+= getAttractionMoreInfoTabText(attraction);
				moreInfo+= "</div>";
				
				var infoTabs = [
								new GInfoWindowTab(texts['tabInfo'], info),
								new GInfoWindowTab(texts['tabAdditionalInfo'], moreInfo)
								];
				
				//Put the marker on the map
				themarker = createMarker(point, infoTabs, attIcon);
				map.addOverlay(themarker);
				this.attractionMarkers[attraction.id] = new Array();
				this.attractionMarkers[attraction.id]['marker'] = themarker;
				this.attractionMarkers[attraction.id]['infoTabs'] = infoTabs;
									
				addListenerForResultHighlight(themarker, attraction.id);
			}
		}
	}
	
	this.openHouseTab = function(houseid) {
		if (this.houseMarkers[houseid]!=undefined || this.houseMarkers[houseid]!=null) {
			this.houseMarkers[houseid]['marker'].openInfoWindowTabsHtml(this.houseMarkers[houseid]['infoTabs'],{maxWidth: 150});
		}
	}
	
	this.openAttractionTab = function(attractionid) {
		if (this.attractionMarkers[attractionid]!=undefined || this.attractionMarkers[attractionid]!=null) {
			this.attractionMarkers[attractionid]['marker'].openInfoWindowTabsHtml(this.attractionMarkers[attractionid]['infoTabs'],{maxWidth: 150});
		}
	}
}

function createManualMarkers() {
	if (manualEntries instanceof EntryManager){
		
		var houses = manualEntries.getHouses();
		
		thumbs = new Array(); //For caching the pictures
		
		var house;
		for (i in houses) {
			 house = houses[i];
			
			//Create the point for the marker
			var point = new GLatLng(parseFloat(house.x),
									parseFloat(house.y) );
			
			var pic = house.picture;
			
			//Cache the thumbs
			var a = new Image();
			a.src = httpPathHousePics+'th-'+pic;
			thumbs[thumbs.length] = a;
			
			//Create the tab texts
			var moreInfo = "<div class='mapPopup'>";
			moreInfo+= getHouseMoreInfoTabText(house, pic, false);
			moreInfo+= "</div>";
			
			var infoTabs = [
							new GInfoWindowTab(texts['tabAdditionalInfo'], moreInfo)
							];
			
			//Put the marker on the map
			themarker = createMarker(point, infoTabs, houseIcon);
			map.addOverlay(themarker);
				
			addListenerForResultHighlight(themarker, house.id);
		}
	}
}

function moveMap(x, y, zoomlevel){
	var x = x;
	var y = y;
	var zoomlevel = zoomlevel;
	map.panTo(new GLatLng(x, y));
	map.setZoom(zoomlevel);
	
}