var HollandCom = HollandCom || {};
var rootfolder = rootfolder || '';
var imagerootfolder = imagerootfolder || '';


HollandCom.POIMap = function(obj, width, height){	
	this.obj = obj;
	this.width = width || 510;
	this.height = height || 400;
	this.map = null;
	this.bounds = null;
	this.zoom = 8;
	this.gMarkers = [];	
	this.photos = null;
	this.centreHolland = new GLatLng(52.2, 5);
	this.currentObject = null;
	this.currentObjectMarker = null;
	this.toolTips = false;
	this.init();
};

HollandCom.POIMap.prototype = {
	init: function() {
		if (typeof googlemapsdata  !== 'undefined' && google && google.maps && GBrowserIsCompatible()) {
			var _this = this;
			
			if (typeof Tooltip === 'function') {
				this.toolTips = true;
			}
			
			this.data = googlemapsdata;
											
			//Add map
			this.addMap();
							
			$.each(this.data.categories, function(i, category){
				
				if (category.items.length > 0) {				
					//Add array for category markers
					_this.gMarkers[i] = [];
					
					var currentObject = category.currentObject;
					
					if (!currentObject) {
						var input = $('<input type="checkbox" name="cat-' + category.title + '" id="cat-' + category.title + '" />');
						var label = $('<label for="cat-' + category.title + '" style="background-image: url('+imagerootfolder+'static/gfx/poi-icons/' + category.title + '.png);" >' + category.displaytitle + '</label>');
						var div = $('<div class="form-item"></div>');
						$('#map-categories').append(div.append(input, label));
					}
															
					$.each(category.items, function(j, poi){
						_this.addMarker(poi, i, currentObject);
						if (currentObject) {
							_this.currentObject = poi;
							_this.initStreetview(new GLatLng(poi.point.lat, poi.point.long));
						}
					});
				}
			});
			
			this.mapZoomCenter();
			
			this.addEventHandlers();
			
			var showDetailTab = $("#showDetail").get(0);
			if(showDetailTab){
				$(showDetailTab).bind("click", {tab: showDetailTab}, function(e){
					_this.showDetail(e);
				});
			}
			var showOverviewTab = $("#showOverview").get(0);
			if(showOverviewTab){
				$(showOverviewTab).bind("click", {tab: showOverviewTab}, function(e){
					_this.showOverview(e);
				});
			}
			var showRouteTab = $("#showRoute").get(0);
			if(showRouteTab){
				$(showRouteTab).bind("click", {tab: showRouteTab}, function(e){
					_this.showRoute(e);
				});
			}
			var showStreetviewTab = $("#showStreetview").get(0);
			if(showStreetviewTab){
				$(showStreetviewTab).bind("click", {tab: showStreetviewTab}, function(e){
					_this.showStreetview(e);
				});
			}
			var routeStart = $("form#routeStart").get(0);		
			var routeStartPoint = $("form#routeStartPoint").get(0);			
			$("#mapRouteSubmit").bind("click", {form: routeStart}, function(e){_this.showDirections(e)});
			$("#mapRouteSubmitPoint").bind("click", {form: routeStartPoint}, function(e){_this.showDirections(e)});

			this.gdir = new GDirections(this.map, document.getElementById("directions"));
			GEvent.addListener(this.gdir, 'load', function(){
				_this.onGDirectionsLoad();
			});
			GEvent.addListener(this.gdir, 'error', function(){
				_this.handleErrors();
			});			
			/*GEvent.addListener(this.gdir, 'addoverlay', function(){
				_this.onGDirectionsLoad();
			});*/
			
			$("#mapPrint").bind("click", function(e){
				window.print();
				return false;
			});
						
			//Activate default map			
			if (this.data.language !== 'undefined' && this.data.language == 'NL') {
				//Detail map only for dutch visitors				
				$(showDetailTab).trigger('click');				
			} else {				
				$(showOverviewTab).trigger('click');
			}

		} else {
			$(this.obj).hide();
		}
	},
	mapResize: function() {
		this.map.checkResize();
	},
	addMap: function() {					
		var options = {
			size: new GSize(this.width, this.height)
		}		
		this.map = new google.maps.Map2(this.obj, options);			
		this.map.setMapType(G_PHYSICAL_MAP);
		this.map.setUIToDefault();
		this.map.disableScrollWheelZoom();
		
		var center = new google.maps.LatLng(52.2, 5); //NL
		this.map.setCenter(center, this.zoom);			
	},
	addMarker: function(poi, catIndex, currentObject){
		var _this = this;
			
		if (poi && typeof(poi.point) !== 'undefined' ) {
			
			if (currentObject == 'true') {
				poi.showOnLoad = currentObject;
			}	
														
			var fileName = this.data.categories[catIndex].title;
			var showOnLoad = poi.showOnLoad || 'false';
															
			var icon = new GIcon();
			
			if (showOnLoad == 'true'){
				icon.image = imagerootfolder+'static/gfx/markers/poi/blue/'+fileName+'.png';
			} else {
				icon.image = imagerootfolder+'static/gfx/markers/poi/orange/'+fileName+'.png';
			}
			
			icon.shadow = imagerootfolder+'static/gfx/markers/poi/shadow.png';
			icon.iconSize = new GSize(32.0, 37.0);
		    icon.shadowSize = new GSize(51.0, 37.0);
		    icon.iconAnchor = new GPoint(16.0, 37.0);
		    icon.infoWindowAnchor = new GPoint(16.0, 18.0);
			
			var position = new GLatLng(poi.point.lat, poi.point.long);
			var marker = new GMarker(position, icon);
				marker.hoverImage =	new Image();
				if (showOnLoad == 'true') {
					marker.hoverImage.src = imagerootfolder+'static/gfx/markers/poi/orange/'+fileName+'.png';
				} else {
					marker.hoverImage.src = imagerootfolder+'static/gfx/markers/poi/blue/'+fileName+'.png';
				}				
				marker.showOnLoad = showOnLoad;							
				
			this.map.addOverlay(marker);
						
			if (marker.showOnLoad == 'false' && !currentObject) {
				marker.hide();
			}			
			
			if (currentObject) {
				this.currentObjectMarker = marker;
			}
			
			GEvent.addListener(marker, 'click', function(){								
				
				var html = '<div id="infowindow"><h2>'+poi.title+'</h2>';						
				if (poi.description != '' && poi.image != '') {
					html += '<div class="description"><div class="figure shadow"><img src="'+poi.image+'" style="width: 100px; height: 70px;" alt="" /></div>'+poi.description+'</div>';
				}else if (poi.description != '') {
					html += '<div class="description">'+poi.description+'</div';
				} else if (poi.image != '') {
					html += '<div class="figure shadow"><img src="'+poi.image+'" style="width: 175px; height: 110px;" alt="" /></div>';
				}								
				if (poi.link != '') {
					html += '<a class="btn" href="'+poi.link+'"><span>'+poi.linktext +'</span></a>';
				}				
				html += '</div>';
												
				_this.map.openInfoWindowHtml(position, html, {
					maxWidth: 300
				});
				
				// Track landmark click				
				if (typeof pageTracker !== 'undefined') {
					pageTracker._trackPageview(root + "/functions/maps/landmark" + poi.id);
				}
			});
			
			//Tooltip
			if (this.toolTips) {			
				var tooltip = new Tooltip(marker, poi.title, 1);
				marker.tooltip = tooltip;
				this.map.addOverlay(tooltip);
										
				GEvent.addListener(marker, 'mouseover', function() {
		            this.setImage(this.hoverImage.src);
					this.tooltip.show();							
		        });
					
		        GEvent.addListener(marker, 'mouseout', function() {
		            this.setImage(icon.image);
					this.tooltip.hide();				
		        });
			} else {
				GEvent.addListener(marker, 'mouseover', function() {
		            this.setImage(this.hoverImage.src);								
		        });
					
		        GEvent.addListener(marker, 'mouseout', function() {
		            this.setImage(icon.image);				
		        });			
			}
			
			//Add marker to markers array;
			this.gMarkers[catIndex].push(marker);
		}	
	},
	toggleMarkers: function(catIndex, toggle) {			
		var _this = this;
		
		if (this.currentObject) {
			catIndex += 1;
		}
		
		//Hide infoWindow			
		this.map.getInfoWindow().hide();
		
		//Toggle markers		
		var markers = this.gMarkers[catIndex];					
		$.each(markers, function(i, marker){			
			if (typeof marker !== 'undefined') {
				if (toggle === true) {					
					_this.bounds.extend(marker.getPoint());
					marker.show();
				} else if (marker.showOnLoad == 'false') {										
					marker.hide();					
				}
			}
		});
		
		// Pan and zoom to markers bounds 
		this.mapZoomCenter();
	},	
	mapZoomCenter: function() {
		var _this = this;
		
		this.bounds = new GLatLngBounds();
		
		//Get markers from overlay?			
		$.each(this.gMarkers, function(i, category){
			if (typeof category !== 'undefined') {
				$.each(category, function(j, marker){
					if (typeof marker !== 'undefined') {
						if (marker.isHidden() === false) {					
							_this.bounds.extend(marker.getPoint());
							//marker.show();
						}
					}
				});
			}
		});
		//Center and zoom to markers bounds 		
		this.map.setCenter(this.bounds.getCenter(), this.map.getBoundsZoomLevel(this.bounds));
	},
	addEventHandlers: function() {		
		var _this = this;				
		
		$('#show-photos').click(function() {
			_this.togglePhotos($(this).attr('checked'));
		});	
		
		$('#map-categories input').each(function(i){
			$(this).click(function(){				
				_this.toggleMarkers(i, $(this).attr('checked'));						
			});
		});
	},	
	togglePhotos: function(toggle) {
		//Photos defined?			
		if (toggle === true && this.photos === null) {		
			this.photos = new GLayer("com.panoramio.all");
			this.map.addOverlay(this.photos);
		} else if (toggle === true) {
			this.photos.show();
		} else if (this.photos !== null) {
			this.photos.hide();
		}				
	},
	showDetail: function(e) {
		if (this.currentObjectMarker) {this.currentObjectMarker.show()};
		HollandCom.preventDefault(e);
		this.map.setMapType(G_NORMAL_MAP);
		//$("#mapWrap").show();
		$('#mapWrap').removeClass('hidden');
		$("#routeControls").hide();
		$("#directions").hide();
		$("#mapDetailWrap").show();
		$("#streetviewWrap").hide();
		this.activateTab(e.data.tab);
		this.mapZoomCenter();
		this.resetPhotosAndPOIs();
		return false;
	},
	showOverview: function(e) {
		HollandCom.preventDefault(e);
		this.map.setMapType(G_PHYSICAL_MAP)
		if (this.currentObjectMarker) {this.currentObjectMarker.show()};
		this.resetPhotosAndPOIs();
		//$("#mapWrap").show();
		$('#mapWrap').removeClass('hidden')
		$("#routeControls").hide();
		$("#directions").hide();
		$("#mapDetailWrap").show();
		$("#streetviewWrap").hide();
		this.activateTab(e.data.tab);
		var zoomLevel = 7;
		var centreMap = this.centreHolland;
		this.map.setCenter(centreMap, zoomLevel);
		return false;
	},
	showRoute: function(e, hideMap) {
		HollandCom.preventDefault(e);
		if(this.currentObject) {							
			$("#mapWrap").addClass('hidden');
			$("#routeControls").show();
			$("#directions").show();
			$("#mapDetailWrap").hide();
			$("#streetviewWrap").hide();
			this.activateTab(e.data.tab);
		}
		return false;
	},
	showStreetview: function(e) {
		HollandCom.preventDefault(e);
		if(this.currentObject) {							
			$("#mapWrap").addClass('hidden');
			$("#routeControls").hide();
			$("#directions").hide();
			$("#mapDetailWrap").hide();
			$("#streetviewWrap").show();
			this.activateTab(e.data.tab);
		}
	},
	resetPhotosAndPOIs: function(e) {
		this.togglePhotos($('#show-photos').attr('checked'));
		var _this = this;
		$('#map-categories input').each(function(i){
			_this.toggleMarkers(i, $(this).attr('checked'));
		});
	},
	activateTab: function(tab) {
		var ul = $(tab).parents("ul").get(0);
		if (ul) {
			$("a.active", ul).removeClass("active");
		}
		$(tab).addClass("active");
		if (this.gdir !== 'undefined') {
			this.gdir.clear();
			$("#directions").hide();
			$("#routeSummary").html("");
			$("#routeSummary").hide();
			$("#routeError").html("");
			$("#routeError").hide();
		}
	},
	setDirections: function(fromAddress, toAddress) {		
		this.gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": this.data.directionLocale });
	},
	showDirections: function(e){
		HollandCom.preventDefault(e);
		var form = e.data.form;
		var fromAddress = "";
		$("#routeError").html("");
		$("#routeError").hide();
		var toAddress = this.currentObject.point.lat + "," + this.currentObject.point.long;
		toAddress = $("#poiName").text() + " - " + $("#poiAddress").text() + " - " + $("#poiCity").text() + "@" + toAddress;
		if (form.id == "routeStart") {
			var country =  form.country.options[form.country.selectedIndex].value;
			if (country == "" ) country = form.country.options[form.country.selectedIndex].text;
			if (form.address.value != "")  fromAddress = form.address.value + ", ";
			if (form.city.value != "")  fromAddress += form.city.value + ", ";
			fromAddress += country;
			$("#mapairports").val(""); //reset aiports select to first option
		}
		else { // only point
			if(form.airports.selectedIndex != 0){
				fromAddress = form.airports.options[form.airports.selectedIndex].text + "@" + form.airports.value;
			}
		}
		if (fromAddress != "") {
			$(form).addClass("spinnerOn");			
			this.setDirections(fromAddress, toAddress);			
		}
		return false;
	},
	handleErrors: function(){
		var errorMessage = "";
		switch(this.gdir.getStatus().code){
			case G_GEO_BAD_REQUEST:
				errorMessage = MAP_TECHNICAL_ERROR;
				break;
			case G_GEO_SERVER_ERROR:
				errorMessage = MAP_TECHNICAL_ERROR;
				break;
			case G_GEO_MISSING_QUERY:
				errorMessage = MAP_TECHNICAL_ERROR;
				break;
			case G_GEO_UNKNOWN_ADDRESS:
				errorMessage = MAP_UNKNOWN_ADDRESS;
				break;
			case G_GEO_UNAVAILABLE_ADDRESS:
				errorMessage = MAP_UNAVAILABLE_ADDRESS;
				break;
			case G_GEO_UNKNOWN_DIRECTIONS:
				errorMessage = MAP_UNKNOWN_DIRECTIONS;
				break;
			case G_GEO_BAD_KEY:
				errorMessage = MAP_TECHNICAL_ERROR;
				break;			
			case G_GEO_BAD_KEY:
				errorMessage = MAP_TECHNICAL_ERROR;
				break;
			default:
				errorMessage = MAP_TECHNICAL_ERROR;
		}
		
		errorMessage += "<!-- ERRORCODE: " + this.gdir.getStatus().code + "-->";
		$("#routeError").show();
		//$("#routeSummary").hide();
		$("#routeError").html(errorMessage);
		$("#routeControls form").removeClass("spinnerOn");
	},
	onGDirectionsLoad: function(){
		//this.currentObjectMarker.hide();
	
		if(this.photos){this.photos.hide()};
		$.each(this.gMarkers, function(i, category){
			if (typeof category !== 'undefined') {
				$.each(category, function(j, marker){
					if (typeof marker !== 'undefined') {
						marker.hide();
					}
				});
			}
		});
							
		this.openMapLightbox();
	},
	initStreetview: function(latLng) {
		var panoramaOptions = { latlng:latLng };
		var streetView = new GStreetviewPanorama(document.getElementById("streetview"), panoramaOptions);
		var _this = this;
		$("#streetviewWrap").hide();
		GEvent.addListener(streetView, "error", _this.handleStreetView);
	},
	handleStreetView: function(errorCode) {
		var SUCCESS = 200;
		if (errorCode != SUCCESS) {
			$("#streetview").remove();
			$("#showStreetview").parent().remove();
		}
		return;
	},
	openMapLightbox: function() {		
		var _this = this;
		
		//Create overlay
		var $overlay = $('<div class="overlay" id="route-overlay">');
		var $print = $('<a href="#" id="mapPrint" class="print">Print</a>');
		
		$print.bind('click', function(){
			window.print();			
			return false;
		});
			
		//Append to the overlay
		$overlay.append($print);
		$('body').append($overlay);	
							
		var sMap = null;			
		
		var overlay = $overlay.overlay({		    		
		    expose: {
		        color: '#333', 			 
		        loadSpeed: 200,
		        opacity: 0.5 
		    },
		    closeOnClick: true, 
		    api: true,
			onLoad: function(e){				
				$("#directions").show();
				$('#poi-map').height(550);		
				$('#mapWrap').removeClass('hidden').appendTo($overlay);				
				_this.mapResize();
			},
			onClose: function() {						       
				$('#mapWrap').appendTo('#mapWrapOuter').addClass('hidden');
				$('#poi-map').height(400);				 
		    }
		});
				
		overlay.load();			
	}
};


HollandCom.FauxDropdown = (function() {
	
	var setUp = function() {		
		$('.faux-dropdown').each(function(){
			
			
			// attach events
			attachDefaultEvents(this);
						
			//Category selector
			if ( $(this).is('#category-selector') ){
				reorderElements( this );
				//Hide original category selector				
				$('#category').hide();				
				attachSelectEvent(this);
			}
		});
							
		//Hide when user clicks elsewhere
		 $('body').click(function() {
			var mapOpacityLayer = $("#mapOpacityLayer").get(0);
			var safecollapse = true;
			if (mapOpacityLayer) {
				safecollapse = ($(mapOpacityLayer).css("display") == "none");
			}
			if(safecollapse) {
				$('.faux-dropdown').each(function() {
					collapse(this);
				});
			}
		});
	};
	
	var reorderElements = function( dropdown ) {
		var arr = new Array();
		var arr2 = new Array();

		$(dropdown).find('li').each(function() {
				arr.push( this );
		} );
		
		//first element ('Alles') excluded from loop because it shouldn't float
		arr[0].style.styleFloat = "none"; //IE
		arr[0].style.cssFloat = "none"; //All other browsers
		arr2.push(arr.shift());
		//reorden
		var len = Math.ceil(arr.length/2 );
		for( i=0; i < len;i++) {
			arr2.push(arr[i] );
			arr2.push(arr[i+ len]);
		}
		
		// get list 
		var ul = $('ul',dropdown); 
		// clear list
		ul.empty(); 
		// add new items 
		for (var i=0;arr2[i]!=undefined;i++) { 
			ul.append(arr2[i]); 
		}
	};
	
	var attachDefaultEvents = function(dropdown) {

		$(dropdown).find('.select').click(function() {	
			toggle(this);									
			return false;
		});
		
		$(dropdown).find('.options a').focus(function() {																		
			expand(this);
		});
		
		$(dropdown).find('li:last-child a').blur(function() {
			collapse(this);
		});
		
		$(".poi-search").bind("submit", function(e){
			// Aanname dat zoeken altijd op /<land>/zoeken/<pagina>.jsp zit		
			var categoryInput = $('#category')[0];
			var categorySelected = $(categoryInput).val();
			if ( typeof categorySelected !== 'undefined' && categorySelected != ''){
				$(this).attr("action", $(this).attr("action").replace(/^(.*)\/(.*)\/([^\/]+)$/, "$1/$2/" + categorySelected + ".jsp")); //set action to ct value
			}

			// Google Analytics: track category, keyword, region en city
			var keywordInput = $('#keyword')[0];
			var keywordSelected = $(keywordInput).val();
			
			var regionInput = $('#region')[0];
			var regionSelected = $(regionInput).val();
			
			var cityInput = $('#city')[0];
			var citySelected = $(cityInput).val();
			
			if (typeof(pageTracker) !== 'undefined') {
				pageTracker._trackPageview(root + "/functions/search_objects/" + categorySelected + ";" + keywordSelected + ";" + regionSelected + ";" + citySelected);
			}

		});
	};
	
	var attachSelectEvent = function(dropdown) {
		$(dropdown).show().find('.options a').click(function(e) {
			selectOption(this);
			$(dropdown).trigger('change');
			e.preventDefault();
			$('#refinesearch').hide();
			$('#inthisregion').hide();
			return false;
		});
	};
	
	var getParentList = function(elm) {		
		return $(elm).parents('.faux-dropdown').andSelf()[0];
	};
	
	var toggle = function(elm) {
		if ( $(getParentList(elm)).hasClass('expand') ) {
			collapse(elm);
		} else {
			expand(elm);
		}
	};
	
	var expand = function(elm) {
		$(getParentList(elm)).addClass('expand');
		
		if ($.browser.msie && $.browser.version <= 7.0) {
			$(elm).parents('form').find('select').css('visibility', 'hidden');
		}			
	};
	
	var collapse = function(elm) {
		$(getParentList(elm)).removeClass('expand');
		
		if ($.browser.msie && $.browser.version <= 7.0) {
			$(elm).parents('form').find('select').css('visibility', 'visible');
		}			
	};
	
	var selectOption = function(elm) {			
		
		var parentList = $(getParentList(elm));
		
		parentList.find('.selected').removeClass('selected');
		$(elm).addClass('selected');
		var elmVal = $.trim($(elm).attr('rel'));
		var elmText = $.trim($(elm).text());
		
		//Toggle event dates
		if (elmVal == 'evenement') {
			$('.eventdates').show();
		} else {
			$('.eventdates').hide();
			$('#startdate').val('');
			$('#enddate').val('');
		}		
			
		parentList.find('.select span').text(elmText).attr('title',elmText);
					
		if (parentList.is('#category-selector')) {
			$('#category').val(elmVal);
			$('#keyword').focus();
		}
		
		collapse(elm);
	};
	
	var generate = function(id,items) {
		
		if (typeof(items)!== 'undefined' && items.length > 0) {
			
			// define parts
			var container = $('<div class="faux-dropdown" id="' + id + '"></div>');
			var selected = $('<a href="#' + id + '-options" class="select"><span></span></a>');
			var options = $('<div class="options"><ul></ul></div>');
			var optionsList = $('ul',options);
			var item = null;
			
			// add items
			for (var i=0;items[i]!==undefined;i++) {
				optionsList.append($('<li><a href="#' + items[i].value + '">' + items[i].label + '</a></li>'));
			}
			
			// build select
			container.append(selected,options);
			
			// attach event handlers
			attachDefaultEvents(container);
			attachSelectEvent(container);
			
			// select first option
			selectOption($('a',optionsList).get(0));
			
			// return element
			return container;
		}
		
		// if no items in array of items is undefined
		//Gives error in IE
		//throw new Error('HollandCom.FauxDropdown.generate(id,items): Argument "items" is required and should contain atleast one item.');
	};
	
	var init = function() {
		$(document).ready(function(){		
			setUp();
		});
	};
	
	return {
		init: init,
		generate: generate
	};
			
})();

HollandCom.FauxDropdown.init();


HollandCom.Toggler = function(obj){	
	this.obj = obj;
	this.toggles = null;
	this.linkedToggle = null;
	this.init();
};

HollandCom.Toggler.prototype = {
	init: function() {
		var _this = this;
		this.toggles = $(this.obj).find('.toggle');
		
		if (window.location.hash) {	
			var elm = $(this.obj).find(window.location.hash)[0];			
			if (elm) {
				this.linkedToggle = elm;
			}
		}		
					
		$(this.toggles).each(function(i){
			var toggle = this;
			var panel = $(toggle).find('.panel')[0];
			
			//Show linked or first toggle panel								
			if (_this.linkedToggle == null && i == 0 || _this.linkedToggle !== null && panel.id == _this.linkedToggle.id) {
				$(toggle).addClass('open');
				$(panel).css({'position': 'relative', 'left': '0'});
			} else {
				$(toggle).addClass('closed');
				$(panel).css({'position': 'relative', 'left': '0'}).hide();
			}		
			
			$(this).click(function(e){
				_this.toggle(this, e);
			})						
		});			
	},	
	toggle: function(elm, e) {		
		if ( $(elm).hasClass('closed') ){
			var $active = $(elm).siblings('.open');
						
			$active.children('.panel:first').animate({ 'height': 'toggle'}, { queue: false, duration: 300, complete: function() {					
					$active.addClass('closed').removeClass('open');
				} 
			});
			
			$(elm).children('.panel:first').animate({ 'height': 'toggle'}, { queue: false, duration: 300, complete: function() {					
					$(elm).removeClass('closed').addClass('open');
				}
			});
						
			//Activate corresponding inpage-nav item						
			var id = $(elm).attr('id');						
			if (id != '') {
				$('.inpage-nav a[href$="'+id+'"]').triggerHandler('click');
			}
			e.preventDefault();
		}
	}
};


HollandCom.DestinationMap = function(obj){	
	this.obj = obj;
	this.map = null;
	this.data = null;
	this.bounds = null;
	this.cityPage = false;
	this.zoom = 8;
	this.gMarkers = [];
	this.toolTips = false;
	this.init();
};

HollandCom.DestinationMap.prototype = {
	init: function(){
		if (google && google.maps && typeof googlemapsdata !== 'undefined' && GBrowserIsCompatible()) {
			
			this.data = googlemapsdata;
			
			if (this.data.categories.length == 1) {
				this.cityPage = true;
			}
			
			if (typeof Tooltip === 'function') {
				this.toolTips = true;
			}
						
			this.map = new google.maps.Map2(this.obj);
			var center = new google.maps.LatLng(52.2, 5); /* NL view */
			this.map.setCenter(center, this.zoom);
			this.map.setMapType(G_PHYSICAL_MAP);
			this.map.addControl(new GLargeMapControl3D(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(230, 10)));
			//this.map.enableScrollWheelZoom();

			//Add markers & menu
			this.addMarkersMenu();
			
			if (this.cityPage === true && this.bounds !== 'null') {
				this.map.setCenter(this.bounds.getCenter(), this.map.getBoundsZoomLevel(this.bounds) - 1);
			}			
		} else {
			$(this.obj).hide();
		}
	},
	addMarkersMenu: function(){
		var _this = this;		
		//menu placeholder
		var $menu = $('<div id="map-menu"></div>');
		$(this.obj).after($menu); //$(this.obj).append($menu);
		
		$.each(this.data.categories, function(i, category){
			if (category && category.items.length > 0) {
			
				//Add array for category markers
				_this.gMarkers[i] = [];
				
				//Add category
				$menu.append('<h2><a href="#">' + category.title + '</a></h2><ol style="display: none;"></ol>');
				
				//Add category markers
				$.each(category.items, function(j, poi){
					if (poi && typeof poi.point !== 'undefined' ) {
						var num = j + 1;												
						$menu.find('ol:last').append('<li><a href="#"><span>' + num + '</span>' + poi.title + '</a></li>');
						_this.addMarker(poi, num, i);
					}
				});
			}
		});
		
		//Show first category only
		this.toggleMarkers(0);
		
		$('#map-menu h2').each(function(i){			
			$(this).children('a').click(function(){
				_this.toggleMarkers(i);
				return false;
			});
			
			$(this).next('ol').find('li').each(function(j){							
				if (typeof _this.gMarkers[i][j] !== 'undefined') {
					//MouseOver
					$(this).hover(function () {
						//Do not 'hover' when animating																	
						if ($(this).parent('ol').not(':animated').length == 1) {							
							GEvent.trigger(_this.gMarkers[i][j], 'mouseover');
						}						
					}, function () {
						GEvent.trigger(_this.gMarkers[i][j], 'mouseout');
					});
					//Click
					$(this).bind('click',function(){					
						$(this).addClass('active');
						$('#map-menu > ol > li.active').removeClass('active');						
						GEvent.trigger(_this.gMarkers[i][j], 'click');
						return false;
					});
				}				
			});
		});
		
	},
	addMarker: function(poi, poiIndex, catIndex){		
		var _this = this;
		
		//poiIndex = poiIndex.toString();	
				
		var icon = new GIcon();
		    icon.image = imagerootfolder+'static/gfx/markers/numbers/orange/orange'+poiIndex+'.png';			
		    icon.shadow = imagerootfolder+'static/gfx/markers/numbers/shadow.png';
		    icon.iconSize = new GSize(27.0, 27.0);
		    icon.shadowSize = new GSize(41.0, 27.0);
		    icon.iconAnchor = new GPoint(13.0, 27.0);
		    icon.infoWindowAnchor = new GPoint(13.0, 13.0);
		var position = new google.maps.LatLng(poi.point.lat, poi.point.long);			
		var marker = new GMarker(position, icon);			
			marker.hoverImage =	new Image();
			marker.hoverImage.src = imagerootfolder+'static/gfx/markers/numbers/blue/blue'+poiIndex+'.png';	
		
		this.map.addOverlay(marker);		
				
		GEvent.addListener(marker, 'click', function() {
			var html = '<div id="infowindow"><h2>'+poi.title+'</h2>';						
			if (poi.description != '' && poi.image != '') {
				html += '<div class="description"><div class="figure shadow"><img src="'+poi.image+'" style="width: 175px; height: 110px;" alt="" /></div>'+poi.description+'</div>';
			}else if (poi.description != '') {
				html += '<div class="description">'+poi.description+'</div';
			} else if (poi.image != '') {
				html += '<div class="figure shadow"><img src="'+poi.image+'" style="width: 175px; height: 110px;" alt="" /></div>';
			}								
			if (poi.link != '') {
				html += '<a class="btn" href="'+poi.link+'"><span>'+poi.linktext +'</span></a>';
			}				
			html += '</div>';
										   
		   _this.map.openInfoWindowHtml(position, html, { maxWidth: 400 });		   
		});	
				
		//Tooltip
		if (this.toolTips) {			
			var tooltip = new Tooltip(marker, poi.title, 1);
			marker.tooltip = tooltip;
			this.map.addOverlay(tooltip);						
			GEvent.addListener(marker, 'mouseover', function() {
	            this.setImage(this.hoverImage.src);
				this.tooltip.show();							
	        });	
	        GEvent.addListener(marker, 'mouseout', function() {
	            this.setImage(icon.image);
				this.tooltip.hide();				
	        });
		} else {
			GEvent.addListener(marker, 'mouseover', function() {
	            this.setImage(this.hoverImage.src);								
	        });	
	        GEvent.addListener(marker, 'mouseout', function() {
	            this.setImage(icon.image);				
	        });			
		}
						
		this.gMarkers[catIndex].push(marker);				
	},
	toggleMarkers: function(catIndex) {
		var _this = this,
			ul = $('#map-menu > ol').eq(catIndex),
			h2 = $('#map-menu > h2').eq(catIndex);
				
		$('#map-menu > h2.active').removeClass('active');
		h2.addClass('active');
		
		ul.slideDown('fast').siblings('ol:visible').slideUp('fast');
		
		this.map.getInfoWindow().hide();	
		
		this.bounds = new GLatLngBounds();
		
		$.each(this.gMarkers, function(i, category){
			if (typeof category !== 'undefined') {
				$.each(category, function(j, marker){
					if (typeof marker !== 'undefined') {
						if (i == catIndex) {					
							_this.bounds.extend(marker.getPoint());
							marker.show();
						} else {
							marker.hide();
						}
					}
				});
			}
		});

		// Pan and zoom to markers bounds		
		this.map.setCenter(this.bounds.getCenter(), this.map.getBoundsZoomLevel(this.bounds)-1);
	}	
};


HollandCom.ImageCycle = function(obj){	
	this.obj = obj;	
	this.images = null;
	this.total = null;
	this.next = null;
	this.prev = null;
	this.active = null;	
	this.init();
};
		
HollandCom.ImageCycle.prototype = {
	init: function(){	
		this.images = $(this.obj).find('img');
		this.total = this.images.length;
		
		if (this.total > 1) {
			this.active = 0;
			this.addImages();
			this.addButtons();
			this.updateCount();
		}	
	},
	addButtons: function() {
		var _this = this;	
		
		this.prev = $('<a class="prev"></a>'); 
		this.next = $('<a class="next"></a>');
		
		$(this.obj).children('.content:first').append(this.prev, this.next);
		
		$(this.prev).click(function(){
			_this.prevImage();
			return false;
		});			
						
		$(this.next).click(function(){
			_this.nextImage();
			return false;
		});		
	},
	addImages: function(){
		$(this.images).each(function(i){
			$(this).css('display', 'block');
			var height = $(this).height();					
			if ( height < 350 ) {				
				var margin = (350 - height) / 2;										
				$(this).css('margin-top', margin+'px');
			} 
			
			if ($(this).width() > 560)  {
				$(this).width(560);
			}
			
			if ( i > 0) {
				$(this).hide();
			}
		});						
	},
	nextImage: function() {
		next = this.active + 1;
		if (next >= this.total) {
			next = 0;
		}			
		this.toggleImages(next);					
	},
	prevImage: function() {
		prev = this.active - 1;
		if (prev < 0) {
			prev = this.total - 1;
		}		
		this.toggleImages(prev);
	},
	toggleImages: function(index){
		var active = this.images[this.active];
		$(active).hide();
		var next = this.images[index];
		$(next).show();
		
		this.active = index;
		this.updateCount();
	},
	updateCount: function() {
		active = this.active + 1;
		activeText = active;
		if (active < 11) {
			activeText = '0' + activeText;
		}

		total = this.total;
		totalText = total;
		if (total < 10) {
			totalText = '0' + totalText;
		}
		
		$(this.next).text(activeText + '/' + totalText);
	}			
};

HollandCom.preventDefault = function(e) {
	if(e.preventDefault){
		e.preventDefault();
	}
	else{
		e.cancelBubble = true;
	}
};


HollandCom.domainPage = function() {
	this.msie = $.browser.msie;
	this.version = parseInt($.browser.version);
	this.overlay = null;
	this.toggle = null;
	this.init();
};

HollandCom.domainPage.prototype = {
	init: function(){		
		this.toggle = $('.domain-nav .toggle-inner').hide().css({'position': 'relative', 'left': '0'});		
		
		//Add overlay
		this.addOverlay();	
			
		//Set heights
		this.setHeights();
		
		//Add eventhandlers
		this.addHandlers();
	},	
	addHandlers: function() {
		var _this = this;
		
		$(window).resize(function(){
			_this.setHeights();
		});
		
		$('.toggle-btn, #domain-overlay').click(function(){
			_this.toggleDiversity(this);
			return false;
		});	
	},	
	addOverlay: function() {		
		this.overlay = $('<div id="domain-overlay"></div>');		
		$('body').prepend(this.overlay);
		this.overlay.css('opacity', 0);
		
		if (!this.msie || (this.msie && this.version >= 8)) { //Fix overlay for IE6/7
			$(this.overlay).css('z-index', 1);
		}
	},
	setHeights: function() {		
		var $height = $(document).height();
		$('html, body').height($height);
		$(this.overlay).height($height - 140);			
	},	
	toggleDiversity: function(elm) {		
		this.setHeights();
								
		if ($(this.toggle).is(':hidden')) {
			$(this.overlay).show().fadeTo('slow', 0.5);
		} else {
			$(this.overlay).fadeTo('slow', 0, function(){
				$(this).hide();
			});
		}
									
		$(this.toggle).slideToggle('fast');
		
		if ($(elm).is('a')) {
			$(elm).toggleClass('active').blur();
		}		
	}	
	
};


HollandCom.preventDefault = function(e) {
	if(e.preventDefault){
		e.preventDefault();
	}
	else{
		e.cancelBubble = true;
	}
}

HollandCom.hideDropDowns = function(root, hide){
	if (root != null){
		var dropdowns = root.getElementsByTagName("select");
		var visibility = hide ? "hidden" : "visible";
		for (var i=0; i<dropdowns.length; i++){
			dropdowns[i].style.visibility = visibility;
		}
	}
}

var jq;
$(document).ready(function(){	

	/*
	$('#email').change(function(){
		$(jq).each(resetborder);
		jq = $('#email').val();
		//alert('setting border on ' + jq );
		$(jq).each(setborder);
	});
	*/			

	
	// Toon alleen eerste 'more-objecttype' link
	$('span.more-appartement:first').show();
	$('span.more-attractie:first').show();
	$('span.more-pension:first').show();
	$('span.more-bungalowpark:first').show();
	$('span.more-camping:first').show();
	$('span.more-congresaccommodatie:first').show();
	$('span.more-evenement:first').show();
	$('span.more-golfterrein:first').show();
	$('span.more-groepsaccommodatie:first').show();
	$('span.more-hostel:first').show();
	$('span.more-hotel:first').show();
	$('span.more-museum:first').show();
	$('span.more-restaurant:first').show();
	$('span.more-uitgaansgelegenheid:first').show();
	$('span.more-vakantiewoning:first').show();
	
	//Form Auto submit
	$('.autoSubmit').each(function(){
		var form = this;
		$(this).find('select').change(function() {
			$(form).submit();
		});
	});
	
	//Print
	$('#print').click(function(){
		if (typeof(pageTracker) != 'undefined') {
			pageTracker._trackPageview(root + '/print/' + document.title );
		}
		return false;
	});
	
	//Book now
	$('.book-now').each(function(){
		var parent = this;
		$(this).find('.btn').show().click(function(event){
			event.preventDefault();
			$(parent).toggleClass('open');
			$(this).next('.booking-panel').slideToggle('fast');
			
			// Google Analytics pagetracker
			if (typeof(pageTracker) !== 'undefined') {
				var bookId = this.href.split('#booknow')[1].split('-')[0];
				var pageId = this.href.split('#booknow')[1].split('-')[1];
				pageTracker._trackPageview(root + '/functions/book_now/' + bookId + '/' + document.title );
			}
				
			//return false;
		});			
	});	
	
	//Diversity tool 2.0	
	if (jQuery().jCarouselLite) {		
		$('.diversity .content').each(function() {			
			if ($(this).find('li').length > 3) {			
				var next = $('<a class="next" href="#">next</a>');
				var prev = $('<a class="prev" href="#">previous</a>');
				$(this).append(next, prev);
				
				if (typeof(pageTracker) !== 'undefined') {					
					next.bind('click', function() {						
						pageTracker._trackPageview(root + '/functions/dutch_diversity/right');
					});					
					prev.bind('click', function() {					
						pageTracker._trackPageview(root + '/functions/dutch_diversity/left');
					});
				}
				
				$(this).children('.carousel').jCarouselLite({
					btnNext: next,
					btnPrev: prev
				});
			}			
		});
	};
		
	//Form search refine toggle items	
	$('.refine-search .options').each(function() {		
		if ( $(this).children('.form-item').length > 5 ) {
			
			var lessText = 'Less';
			var moreText = 'More';
			
			if ($(this).attr("rel") != null) {			
				lessText = $(this).attr("rel").split("~")[0];
				moreText = $(this).attr("rel").split("~")[1];
			}
			
			$(this).append('<a class="more" href="#">' + lessText + '</a><a class="less" href="#" style="display:none;">' + moreText + '</a>');
			
			var hiddenFields = $(this).children('.form-item:gt(3)');
			
			if ( $(this).hasClass('.show-all') ) {
				$(this).children('.more, .less').toggle();				
			} else {
				$(hiddenFields).hide();
			}
											
			$(this).children('.more, .less').click(function(){				
				$(this).siblings('.more, .less').andSelf().toggle();
				$(hiddenFields).toggle();						
				return false;
			});				
		}					
	});
		
	// IE label img 	
	if ($.browser.msie) {	
		$('label img').click(function(){
			$(this).parent('label').click();
		});
	};
	
	//POIMap
	if (document.getElementById('poi-map')) {
		new HollandCom.POIMap(document.getElementById('poi-map'));
	};

	//Toggler			
	$('.toggler').each(function() {
		new HollandCom.Toggler(this);
	});	
	
	//Imageviewer			
	$('div.imageviewer').each(function() {
		new HollandCom.ImageCycle(this);
	});		
		
	//Destination maps
	if (document.getElementById('map-destinations')) {
		new HollandCom.DestinationMap(document.getElementById('map-destinations'));
	};
			
	//Top5 list: add rank number	
	$('.top5list li').each(function(i){
		var rank = i+1;
		$(this).prepend('<span class="rank">'+rank+'</span>');
	})
	
	//Domain page	
	if ($('body.domainpage').length) {
		var domainPage = new HollandCom.domainPage();
	}	
	
	/*
	 * Brochures - Disable empty submit
	 */
	$('.brochures').each(function(){
		// Enable submit function
		function enableSubmit(){
			$("form#brochuresForm button:submit").unbind('click');
		}
		// Disable submit function		
		function disableSubmit(){
			$("form#brochuresForm button:submit").click(
				function(){
					if(jQuery.trim($("form#brochuresForm span#MINIMUM_BROCHURES_REQUIRED").text()) != ""){
						alert($("form#brochuresForm span#MINIMUM_BROCHURES_REQUIRED").text());
					}
					return false;
				}
			);
		}
	
		// Disable submit on form init
		disableSubmit();
		// OnChange listener on checkboxes to enable/disable submit
		$("form#brochuresForm input[@name='brochureId']:checkbox").change(
			function(){
				if($("input[@name='brochureId']:checkbox:checked").length >= 1){
					enableSubmit();
				}else{
					disableSubmit();
				}
			}
		);
	});	
	
	//Brochures	
	$('.inpage-nav li a').each(function(i){
		if (i==0){
			$(this).addClass('active');
		}
		$(this).click(function(){					
			var id = $(this).attr('href');
			//Trigger click
			$(id).parent('.toggle').triggerHandler('click');
			
			//Set active
			$(this).addClass('active').parents('li').siblings().find('a').removeClass('active');
			return false;				
		});	
	});
		
	//Brochure overlay
	if($('.brochure .figure a').length) {		
		var $overlay = $('<div class="overlay" id="brochure-overlay">');			
		var $iframe = $('<iframe frameborder="0"></iframe>');																								
		
		//Append the overlay
		$overlay.append($iframe);
		$('body').append($overlay);
				
		$('.brochure .figure a').overlay({
			expose: {
		        color: '#333', 			 
		        loadSpeed: 200,
		        opacity: 0.5 
		    },
			left:"center",
		    closeOnClick: true, 
		    api: true,
			target: $overlay,
			onLoad: function(e){				
				var $target = this.getTrigger(); //$(e.target);
				var url = $target.attr('href');				
				$iframe.attr('src', url);				
			}
		});					
	};
	
	//Moodpage
	if ($('body.moodpage').length) {
		$('html').addClass('moodpage');	
	};
	
	//Autocomplete
	if (jQuery().autocomplete) {	
		var geoUrl = '/geo/plaats';
		
		if ($("#geoPathUrl").attr("value") != null) {
			geoUrl = $("#geoPathUrl").attr("value");
		}
		
		$("#city").autocomplete(geoUrl, {
			matchSubset: true,
			minChars: 1,
			highlight: function(value, term){
				return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "i"), "<strong>$1</strong>");
			}
		});
		
		$("#city").result(function(event, data, formatted){
			if (data) {
			
				$("#city_hidden").val(data[0]); /* set hidden input to value selected */
				if ($("body.poi_result").length) { //on poi result pages, track input 
					inputTrackUrl($(this));
					clearTimeout(cityTimer); //by default input is tracked onchange after few millisecond, cancel this
				}
			}
		});
		
		$("#city").setOptions({
			extraParams: {
				region: $("#region").val()
			}
		});
	};
	
	//Datepicker
	if (jQuery().datepicker){
	
		$("#startdate").datepicker({dateFormat: 'dd-mm-yy'});
		$("#enddate").datepicker({dateFormat: 'dd-mm-yy',defaultDate: '+1y'});
		
		$('.datepicker-btn').click(function(){
			$(this).prev('input').focus();
			return false;
		});
	};
	
	//Show dates on pageload
	if ($('#category').val() == 'evenement') {
		$('.eventdates').show();
	};
	
	//Headers / content equal height based on the tallest item
	var setheight = function(){
		if (!$(this).hasClass('ignoreheights') && $(this).children('.article').length > 1) {
			var skip = false;
			var headerTallest = 0;
			var contentTallest = 0;
			$(this).children('.article').each(function(){				
				//Has nested articles, so don't set the height
				if ( $(this).children('.line').length ) {
					skip = true;
				}
				//Don't fix the height of the togglers and videoplayer													
				if ( $(this).children('.toggler, .videoplayer').length ) {
					skip = true;
				}				
				
				var header = $(this).find('.header :header:first');				
				if (header.length) {
					var headerHeight =  $(header).height();
					if (headerHeight > headerTallest) { 
						headerTallest = headerHeight; 
					}
				}
				
				var content = $(this).find('.content:first');				
				if (content.length) {
					var contentHeight =  $(content).height();
					if (contentHeight > contentTallest) { 
						contentTallest = contentHeight; 
					}
				}
				
			});
											
			//Set all headers to equal (tallest) height
			if (headerTallest > 0) {
				$(this).children('.article').find('.header :header:first').height(headerTallest);
			}			
			//Set all content boxes to equal (tallest) height, but not when there are nested lines within a article!
			if (skip != true && contentTallest > 0) {
				//if there are 2 article but only 1 link in tha footer then dont resize the content div
				if($(this).children('.article').find('.footer a').length > 1){
					$(this).children('.article').find('.content:first').height(contentTallest).addClass('fix-height');
				}
			}
		}
	};
	

	//Tabs
	if ( $('.tabs').length ) {
		
		var tabContainers = $('.tabs > div');
	    
	    $('div.tabs ul.tab-nav a').click(function () {
	        tabContainers.hide().filter(this.hash).show();
	        
	        $('.tabs ul.tab-nav li a').removeClass('active');
	        $('.tabs .show-first a.first').click();
	        $(this).addClass('active');
	        
	        return false;
	    }).filter(':first').click();
	    
	    
		
		$('.tabs .tab-panel').each(function(){
			$(this).find('.line').not(':first').hide();
			$(this).find('.show-all').show();
		});
		
		var showMore = $('.tabs .show-all a.more')
		var showFirst = $('.tabs .show-first a.first')
		showMore.click(function() {
			$(this).parent('div').hide()
			showFirst.parent('div').show()
			$(this).parent('div').siblings('.line').show();			
			return false;
		});
		showFirst.click(function() {
			$(this).parent('div').hide()
			showMore.parent('div').show()
			$(this).parent('div').siblings('.line').not(':first').hide();
			return false;
		});
		$('.tabs').bind('tabsselect', function(event, ui) {					
			$(ui.panel).find('.line').not(':first').hide();
			$(ui.panel).find('.show-all').show();				
		});		
	};
	//end tabs
	//ff hierheen gezet om issue 779 dit hoort bij het het uitlijnen van titels en linkjes	
	$('.main-content > .line, .line > .article.size1of1, .tab-panel > .line').each( setheight );
  //articles on homepage
  $('.main-content > span .line').each( setheight );
	
	
	//Set search value	
	$("#q").val($('#q').attr('title')).focus(function() {
		if ($(this).val() == $(this).attr('title')) {
			$(this).val('');
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
	}); 
		
	//POI map overlay V2 (search/contentpage)
	if ( $('#show-map').length && typeof googlemapsdata !== 'undefined' ) {	
		if (google && google.maps && GBrowserIsCompatible()) {								
			//Create overlay
			var $overlay = $('<div class="overlay" id="map-overlay">');
			
			//Create map containers	
			var $map = $('<div id="poi-map"></div>');
			var $categories = $('<div id="map-categories" class="options"></div>');
			
			var str_showAlso = typeof MAP_SHOW_ALSO !== 'undefined' ? MAP_SHOW_ALSO : 'toon ook';
			var str_showPhoto = typeof MAP_SHOW_PHOTO !== 'undefined' ? MAP_SHOW_PHOTO : 'toon foto\'s';
															
			//Append to the overlay
			$overlay.append($map,$categories);
			$('body').append($overlay);
			
			//Append 'show photos'
			$map.after('<h3>'+str_showAlso+'</h3><div class="options"><div class="form-item"><input type="checkbox" name="show-photos" id="show-photos"/><label for="show-photos">'+str_showPhoto+'</label></div></div>');	
								
			var sMap = null;
			
			var overlay = $overlay.overlay({			    
			    expose: {
			        color: '#333', 			 
			        loadSpeed: 200,
			        opacity: 0.5 
			    },
			    closeOnClick: true, 
			    api: true
			});
			
			$('#show-map').show().click(function(e){
				e.preventDefault();					
				//Add POI map
				if (sMap == null) {
					sMap = new HollandCom.POIMap(document.getElementById('poi-map'), 860, 360);
				}										
				overlay.load();
				sMap.mapResize();							
			});																		
		}
	};
		
	//Send a friend	(uses 'jQuery live events' to bind events)	
	if (jQuery().cluetip) {
		$('#send-a-friend').cluetip({
			dropShadowSteps: 4,
			showTitle: true,
			titleAttribute: 'title',
			height: 215,
			width: 350,
			positionBy: 'mouse',
			sticky: true,
			closePosition: 'title',
			cursor: 'pointer',
			cluetipClass: 'cluetip-sendafriend',
			closeText: '<img src="' + imagerootfolder + 'static/gfx/maplarge_close.gif" alt="" />',
			onShow: function(ct, c){
							
				//Toggle email example		
				$('#showEmailExample').live('click', function(){
					$('#exampleMail').slideToggle('slow');
					return false;
				});		
								
				//Form ajax submit		
				$('#saf-submit').live('click', function(){
					var form = $('#saf-form'), 
						url = form.attr('action'), 
						data = form.serialize()
					
					$.ajax({
						type: 'POST',
						url: url,
						data: data,
						cache: false,
						dataType: 'html',
						success: function(html){
							c.html(html);
							//Send a friend Google Analytics tracking
							if (typeof(pageTracker) !== 'undefined') {
								pageTracker._trackPageview(root + '/functions/sendafriend/sent');
							}
						},
						error: function(){
						}
					});
					return false;
				});
			}
		});
	};
	
		
	/* Klikken op een search result moet een submit zijn van het poiForm met alle hidden fields */
	$(".search-results-global a").not('.book-now a').bind("click", function(e){
		$("#sorteerform").attr("action", $(this).attr("href"));
		$("#sorteerform").submit();
		return false;									   
	});
	
	
	/* paging links, next, previous and back */
	$(".page-nav a").not(".newsoverview a").bind("click", function(e){
		$("#poipaging").attr("action", $(this).attr("href"));
		$("#poipaging").submit();
		return false;
	});	
	
});	


$(document).ready(function(){	
//$(window).load(function () {

});

//Unload Google Maps when loaded
$(window).unload( function () { 
	if (typeof google !== 'undefined' && typeof google.maps !== 'undefined') {
		GUnload();
	}
});
$('.related #advanced-search-seo-moreless').click(function () {
	$('.related li.hidden').animate({
	  height: 'toggle', opacity: 'toggle'
	}, "fast");
	$(".related #advanced-search-seo-moreless").toggle();
	return false;
});