var HollandCom = HollandCom || {};
var rootfolder = rootfolder || '';
var imagerootfolder = imagerootfolder || '';


HollandCom.POIMap = function(obj, maps){	
	this.obj = obj;
	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.init();
};

HollandCom.POIMap.prototype = {
	init: function() {
		if (typeof(googlemapsdata) !== 'undefined' && google && google.maps && GBrowserIsCompatible()) {
			var _this = this;
			
			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.onGDirectionsAddOverlay()});
			
			$("#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();
		}
	},
	addHtml: function() {
		
	},
	addMap: function() {
		this.map = new google.maps.Map2(this.obj);			
		this.map.setMapType(G_PHYSICAL_MAP);
		this.map.setUIToDefault();
		
		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' ) {	
						
			var fileName = this.data.categories[catIndex].title;

			var icon = new GIcon();			
			icon.image = imagerootfolder+'static/gfx/poi-icons/'+fileName+'.png';		
			icon.shadow = imagerootfolder+'static/gfx/poi-icons/shadow.png';
			icon.iconSize = new GSize(20.0, 20.0);
		    icon.shadowSize = new GSize(31.0, 20.0);
		    icon.iconAnchor = new GPoint(10.0, 10.0);
		    icon.infoWindowAnchor = new GPoint(10.0, 10.0);
			                
			//Options
			markerOptions = { 
				title: poi.title,
				icon: icon 
			}
								
			var position = new GLatLng(poi.point.lat, poi.point.long);
			var marker = new GMarker(position, markerOptions);
			this.map.addOverlay(marker);
			
			poi.showOnLoad = poi.showOnLoad || 'false';
			
			//Hide on load		
			if (poi.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);
				}				
			});
			
			//Add marker to markers array;
			this.gMarkers[catIndex].push(marker);
		}	
	},
	toggleMarkers: function(catIndex, toggle) {
		if (this.currentObject) {catIndex += 1}
		
		var _this = this;
		
		//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 {
					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();
		$("#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();
		$("#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);
		this.activateTab(e.data.tab);
		$("#mapWrap").hide();
		$("#routeControls").hide();
		$("#directions").hide();
		$("#mapDetailWrap").hide();
		$("#streetviewWrap").show();
		return false;
	},
	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);
			//this.openMapLightbox(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.map.setMapType(G_NORMAL_MAP);
		/* var summary = "";
		//var summary = '<span class="summaryLabel">' + SUMMARY_LABEL + ' </span>';
		summary += this.gdir.getSummaryHtml();
		$("#routeSummary").show();
		$("#routeSummary").html(summary); */
		$("#routeControls form").removeClass("spinnerOn");
					
		this.openMapLightbox();
	},
	onGDirectionsAddOverlay: function(){	
		if ($("#mapairports")[0].selectedIndex == 0){
			var fromAddress = "";
			if ($("#map_address").val() != "")  fromAddress = $("#map_address").val() + " - ";
			if ($("#map_city").val() != "")  fromAddress += $("#map_city").val() + " - ";
			fromAddress += $("#map_country option:selected").text();
			$("#directions td[jscontent='address']:first").text(fromAddress);
		}
				
		//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;
		
		//Add overlay		
		if ( $('#routeMap-overlay').length == 0) {		
			var $overlay = $('<div class="jqmWindow" id="routeMap-overlay"></div>');
			var $close = $('<a href="#" id="jqmClose" class="close">X</a>');
			var $print = $('<a href="#" id="mapPrint" class="print">Print</a>');
			$('body').append($overlay.append($close, $print));
		} else {
			$overlay = $('#routeMap-overlay');
		}
		
		$('#mapPrint').bind('click', function(e){
			window.print();			
			return false;
		});
		
		//Onload: Append Map div to overlay div				
		var loadMapWindow = function(hash){
		    var $trigger = $(hash.t);
		    var $modal = $(hash.w);	
			$("#directions").show();				
			$('#mapWrap').removeClass('hidden').appendTo($modal).show();		    
		    $modal.show();
			
			//Scroll to top for IE6
			if ($.browser.msie && parseInt($.browser.version) == 6) {
				$('html, body').animate({scrollTop: 0}, 'slow');
			}
		};
		
		//onHide: Append Map div back to wrapper div
		var closeMapWindow = function(hash){			
		    var $trigger = $(hash.t);
		    var $modal = $(hash.w);
			var $overlay = $(hash.o);					
			$('#mapWrap').appendTo('#mapWrapOuter').hide();		    
		    $modal.hide();
			$overlay.hide();
		};
		
		// Initialise jqModal
		$($overlay).jqm({
			closeClass: 'close',			
			onShow:  loadMapWindow,
			onHide : closeMapWindow
		});	
		
		//Show overlay
		$($overlay).jqmShow();				
	}
};


HollandCom.FauxDropdown = (function() {
	
	var setUp = function() {		
		$('.faux-dropdown').each(function(){
			
			// attach events
			attachDefaultEvents(this);
						
			//Category selector
			if ( $(this).is('#category-selector') ){
				//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 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];
			
			$(toggle).find('.header a').append('<span class="icon">open</span>');
			
			//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.cityMap = false;
	this.zoom = 8;
	this.gMarkers = [];
	this.init();
};

HollandCom.DestinationMap.prototype = {
	init: function(){
		if (google && google.maps && typeof(googlemapsdata) !== 'undefined') {
			this.data = googlemapsdata;
			
			if (this.data.categories.length == 1) {
				this.cityPage = 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(250, 10)));
			this.map.enableScrollWheelZoom();


			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			
		$(this.obj).after('<div id="map-menu"></div>');
		
		$.each(this.data.categories, function(i, category){
			if (category && category.items.length > 0) {
			
				//Add array for category markers
				_this.gMarkers[i] = [];
				
				//Add category
				$('#map-menu').append('<h2><a href="#' + category.title + '">' + category.title + '</a></h2><ul style="display: none;"></ul>');
				
				//Add category markers
				$.each(category.items, function(j, poi){
					if (poi && typeof(poi.point) !== 'undefined' ) {
						$('#map-menu ul:last').append('<li><a href="#' + poi.title + '">' + poi.title + '</a></li>');
						_this.addMarker(poi, 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('ul').find('li').each(function(j){
				$(this).click(function(){					
					$(this).addClass('active');
					$('#map-menu > ul > li.active').removeClass('active');
					if (typeof _this.gMarkers[i] != 'undefined') { 
						GEvent.trigger(_this.gMarkers[i][j], 'click');
					}					
					return false;
				});
			});
		});
		
	},
	addMarker: function(poi, catIndex){
		if (  typeof(poi.point) !== 'undefined' ) {
			var _this = this;
			var position = new google.maps.LatLng(poi.point.lat, poi.point.long);						
			var marker = new GMarker(position);
			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>';
				
				//var html = '<div id="infowindow"><h2>'+poi.title+'</h2><div class="description"><div class="figure"><img src="'+poi.image+'" alt="" /></div>'+poi.description+'</div><a class="btn" href="'+poi.link+'"><span>'+poi.linktext +'</span></a></div>';			    
			   _this.map.openInfoWindowHtml(position, html, { maxWidth: 400 });		   
			});				
							
			this.gMarkers[catIndex].push(marker);
			}				
	},
	toggleMarkers: function(catIndex) {
		var _this = this;	
		var infoWindow = this.map.getInfoWindow();
		infoWindow.hide();
		
		var ul = $('#map-menu > ul').eq(catIndex);
		var h2 = $('#map-menu > h2').eq(catIndex);
		$('#map-menu > h2.active').removeClass('active');
		h2.addClass('active');
		
		ul.slideDown('fast').siblings('ul:visible').slideUp('fast');	
		
		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.panTo(this.bounds.getCenter(), this.map.getBoundsZoomLevel(this.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;
		}
	}
}

$(document).ready(function(){	
	
	// Toon alleen eerste 'more-objecttype' link
	$('span.more-appartement:first').css('display','inline');
	$('span.more-attractie:first').css('display','inline');
	$('span.more-pension:first').css('display','inline');
	$('span.more-bungalowpark:first').css('display','inline');
	$('span.more-camping:first').css('display','inline');
	$('span.more-congresaccommodatie:first').css('display','inline');
	$('span.more-evenement:first').css('display','inline');
	$('span.more-golfterrein:first').css('display','inline');
	$('span.more-groepsaccommodatie:first').css('display','inline');
	$('span.more-hostel:first').css('display','inline');
	$('span.more-hotel:first').css('display','inline');
	$('span.more-museum:first').css('display','inline');
	$('span.more-restaurant:first').css('display','inline');
	$('span.more-uitgaansgelegenheid:first').css('display','inline');
	$('span.more-vakantiewoning:first').css('display','inline');
	
	//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	
	$('.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(jQuery().jqm && $('.brochure .figure a').length) {					
		var $overlay = $('<div class="jqmWindow" id="brochure-overlay"></div>');
		var $close = $('<a href="#" id="jqmClose" class="close">X</a>');
		var $iframe = $('<iframe id="jqmContent" frameborder="0"></iframe');		
		$('body').append($overlay.append($close,$iframe));
		
		//Load in iFrame		
		var loadInIframeModal = function(hash){
		    var $trigger = $(hash.t);
		    var $modal = $(hash.w);
		    var myUrl = $trigger.attr('href');
		    var $modalContent = $iframe;
		    $modalContent.html('').attr('src', myUrl);
		    $modal.show();		
		};
		
		// Initialise jqModal
		$($overlay).jqm({
			closeClass: 'close',
			trigger: '.brochure .figure a',
			onShow:  loadInIframeModal
		});		
	};
	
	//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();
	};
			
	//Tabs
	if ( $('.tabs').length ) {
		$('.tabs .tab-panel').each(function(){
			$(this).find('.line').not(':first').hide();
			$(this).find('.show-all').show();
		});
						
		$('.tabs .show-all').click(function() {
			$(this).hide().siblings('.line').show();			
			return false;
		});
		
		$('.tabs').bind('tabsselect', function(event, ui) {					
			$(ui.panel).find('.line').not(':first').hide();
			$(ui.panel).find('.show-all').show();				
		});		
	};
	
	//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'));
		}
	}); 
	
	//Search map
	if ( $('#show-map').length && typeof(googlemapsdata) !== 'undefined' ) {	
		if (google && google.maps && GBrowserIsCompatible()) {					
			
			//Create map containers	
			var $map = $('<div id="search-map"></div>');
			var $categories = $('<div id="map-categories" class="options"></div>');
															
			//Create overlay
			var $overlay = $('<div class="jqmWindow" id="map-overlay"></div>');
			var $close = $('<a href="#" id="jqmClose" class="close">X</a>');
					
			$('body').append($map, $categories);	
			
			//Add POI map
			var sMap = new HollandCom.POIMap(document.getElementById('search-map'));
			
			//Append the map to the overlay
			$overlay.append($close,$map,$categories);
			$('body').append($overlay);	
			
						
			//Resize map		
			var resizeMap = function(hash){	
				var $modal = $(hash.w);
			    $modal.show();
				//sMap.checkResize();				
			};		
													
			$($overlay).jqm({
				closeClass: 'close',		
				onShow: resizeMap
			});
			
			//Show button
			$('#show-map').show().click(function(e){
				e.preventDefault();				
				$($overlay).jqmShow();						
			});															
		}
	};
		
	//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").bind("click", function(e){
		$("#poipaging").attr("action", $(this).attr("href"));
		$("#poipaging").submit();
		return false;
	});	
	
});	

/*
 * Headers / content equal height based on the tallest item
 * Run function when the page is fully loaded including graphics.
 * 
 */
$(window).load(function () {  	
	$('.main-content > .line, .line > .article.size1of1, .tab-panel > .line').each(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: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: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) {
				$(this).children('.article').find('.content:first').height(contentTallest).addClass('fix-height');
			}
		}
	});	
});

//Unload Google Maps when loaded
$(window).unload( function () { 
	if (typeof google !== 'undefined' && typeof google.maps !== 'undefined') {
		GUnload();
	}
});