/*
* Custom jQuery functions
**/
var housingTotalPages = 0;
var housingCurrentPage = 0;
var gmapsCoords = new Array();
var currentViewType = 'LIST';
var gotoOverviewPage = '';

$(document).ready(function() {
	// tabs
	$('#tabs a').bind('click', function(e) {
	  //alert($(this).attr('id'));	
	  n = $(this).attr('id').substr(4);
	  changeTab(n);
	  e.preventDefault();
	});
	
	$('input[name=customerType]').bind('click', function(e) {
		toggleInputAnders();
	});
	
	$(".faqItem a").click(function(){
	    $(this).next("div").toggle();
	});
	
	$('select#numberOfChildren').live('change',function(){
		changeNumberOfChildrenBirthDays();
	});
	
	$('select#numberOfAdults').live('change',function(){
		changeNumberOfAdultBirthDays();
	});
});

function changeNumberOfChildrenBirthDays() {
	$('.numberOfChildrenBirthDates').addClass('hidden');
	for(var i=0;i<=$('#numberOfChildren').val();i++) {
		$('#numberOfChildrenBirthDates_'+i).removeClass('hidden');
	}
}

function changeNumberOfAdultBirthDays() {
	$('.numberOfAdultsBirthDates').addClass('hidden');
	for(var i=0;i<=$('#numberOfAdults').val();i++) {
		$('#numberOfAdultsBirthDates_'+i).removeClass('hidden');
	}
}

function toggleInputAnders(){
	if($("input[name=customerType]:checked").val() == 'Anders'){
		$('#inputAnders').attr("disabled", false); 
	}else{
		$('#inputAnders').val('');
		$('#inputAnders').attr("disabled", true);
	}
}

/* Sitemap */
function toggleSitemap(id, aId) {
	if($('#'+id).css('display') == 'none') {
		$('#'+id).css('display','block');
		$('a#'+aId+' img.toggleButton').attr('src',imgPath+'sitemap/min.png');
	}else{
		$('#'+id).css('display','none');
		$('a#'+aId+' img.toggleButton').attr('src',imgPath+'sitemap/plus.png');
	}
}


var stopAuto = false;

jQuery(document).ready(function() {	    
	$('.naildAdviceBtn').click(function() {
    	$('#nailAdviceForm').submit();
	});
	
	$('.submitBtn').click(function() {
    	$('#contactForm').submit();
	});
	
	/* Attach the fancybox for the Youtube lightbox */
	$("a.youtube").click(function() {
		$.fancybox({
			'autoScale'		 : false,
			'transitionIn'	 : 'none',
			'transitionOut'	 : 'none',
			'titlePosition'  : 'inside',
			'title'			 : $(this).find('img').attr('alt'),
			'width'			 : 680,
			'height'		 : 495,
			'overlayColor'	 : '#000',
			'overlayOpacity' : '0.8',
			'href'			 : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			 : 'swf',
			'swf'			 : {
			'wmode'			 : 'transparent',
			'allowfullscreen': 'true'
			}
		});

		return false;
	});
	
	// Bind headerLinks title
	$('a#icon_home').mouseenter(function(){$('#headerLinksTitle').text('home');}).mouseleave(function(){$('#headerLinksTitle').text('');});
	$('a#icon_contact').mouseenter(function(){$('#headerLinksTitle').text('contact');}).mouseleave(function(){$('#headerLinksTitle').text('');});
	$('a#icon_news').mouseenter(function(){$('#headerLinksTitle').text('nieuws');}).mouseleave(function(){$('#headerLinksTitle').text('');});
	$('a#icon_partners').mouseenter(function(){$('#headerLinksTitle').text('partners');}).mouseleave(function(){$('#headerLinksTitle').text('');});
	
	// Prepare printable stuff (housing detail, print detail)
		// Fill printMap
		try{
			var mapHTML = '<img src="http://maps.google.com/maps/api/staticmap?center='+detailLat+','+detailLon+'&zoom=14&size=400x400&sensor=false&markers=color:red%7Ccolor:red%7Clabel:%7C'+detailLat+','+detailLon+'"/>';
			$('#printMap').html(mapHTML);
		}catch(e){}
	
		// Copy main iamge to printPicture
		try{
			var imgHTML = $('#tabContent1 .tabContentRightColumn a.mainImage').html();
			$('#printPicture').html(imgHTML);
		}catch(e){}
		
	// Mouseover 'tooltips' for switch viewtype button
	$('img#viewTypeImage').mouseenter(function(){$('#viewTypeTooltip').text($('img#viewTypeImage').attr('alt'));}).mouseleave(function(){$('#viewTypeTooltip').text('');});
	
	// Mouseover for youtube links
	attachYoutubeMouseovers();
});


// stop the carousel
function stopCarousel(carousel){
	if(stopAuto){
		carousel.stopAuto();
	}
	
}

// update control
function updateControl(carousel, li, currentItem){
	//set active button	
	activeNumber = currentItem%5
	if(activeNumber%5 == 0){
		activeNumber = 5;
	}
	switchImage(activeNumber);
}

function mycarousel_initCallback(carousel) {
    jQuery('.jcarousel-control a').bind('click', function() {	
    	stopCarouselNow(carousel);
    	// scroll to item
    	carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
    	switchImage(jQuery(this).text());
    	//stopCarouselNow(carousel);
    	stopAuto = true;
    	return false;
    });   
    
    /*jQuery('.jcarousel-control a').bind('mouseup', function() {	
    	stopCarouselNow(carousel);
    });*/  


};

function stopCarouselNow(carousel){
	// stop carousel
	carousel.stopAuto();  
	//carousel.animation = 0;
	return false;	
}

function switchImage(activeNumber){
	//alert(activeNumber);		
	$('.jcarousel-control a').removeClass('active');
	$('#control'+activeNumber).addClass('active');
}

// active answer
var activeAnswer = '';
function changeAnswer(answerId){
	if(answerId != ''){
		// reset active label
		$('#contentStep label').removeClass('active');
		// set active label
		$('#answerLabel'+answerId).addClass('active');
		// hide main image
		$('#mainImage').hide();
		// if active answer is true, hide that block to
		if(activeAnswer != ''){
			$('#answerRightBlock' + activeAnswer).hide();
		}
		// show current answer block
		$('#answerRightBlock' + answerId).show();
		// set new active answer
		activeAnswer = answerId;
	}
}

function changeTab(tabNr){
	// toggle tabs
	$('#tabs').removeClass();
	$('#tabs').addClass('activeTab'+tabNr);
	// show content
	$('.tabContent').hide();
	$('#tabContent'+tabNr).show();
	
	if(tabNr == 3) {	// If third tab, init maps
		try{
			detailMap(detailLat,detailLon,'');
		}catch(e){}
	}
}

function goto(url){
	document.location.href = url;
}


/* Housing Overview functions */
	function initOverview() {
		/* Activate jquery slider */
			// Activate slider
			$("#sliderArea").slider({
				range: true,
				min: 50000,
				max: 350000,
				step: 25000,
				values: [50000, 350000],
				stop: function( event, ui ) {
					setSliderValuesIntoLabels();
					searchHousing();
				}
			});
			// Set values into labels
			setSliderValuesIntoLabels();
	
		/* Fill selectlists  */
			fillCitiesSelect();
			//fillNeighbourhoodsSelect();
			//fillHouseClassificationsSelect();
			fillHouseSubClassificationsSelect();
			
		/* Load earlier search filters from session */
			loadSearchFiltersFromSession();
			
		/* Connect 'do search' to all onblurs of selectlists and stuff */
			$('#cityId').change(function(){fillNeighbourhoodsSelect($('#cityId').val());searchHousing(true);});
			$('#neighbourhoodId').change(function(){searchHousing(true);});
			/*$('#houseClassificationId').change(function(){searchHousing(true);});*/
			$('#houseSubClassificationId').change(function(){searchHousing(true);});
			$('#existingBuild').change(function(){searchHousing(true);});
			$('#newBuild').change(function(){searchHousing(true);});
			$('#bothBuild').change(function(){searchHousing(true);});
			
		searchHousing();
	}
	
	function initRentalOverview() {
		/* Activate jquery slider */
			// Activate slider
			$("#sliderArea").slider({
				range: true,
				min: 600,
				max: 1250,
				step: 25,
				values: [600, 1250],
				stop: function( event, ui ) {
					setSliderValuesIntoLabels();
					searchHousingRental();
				}
			});
			// Set values into labels
			setSliderValuesIntoLabels();
	
		/* Fill selectlists  */
			fillCitiesSelect();
			//fillNeighbourhoodsSelect();
			//fillHouseClassificationsSelect();
			fillHouseSubClassificationsSelect();
			fillAgeTypeSelect();
			
		/* Load earlier search filters from session */
			loadSearchFiltersFromSessionRental();
			
		/* Connect 'do search' to all onblurs of selectlists and stuff */
			$('#cityId').change(function(){fillNeighbourhoodsSelect($('#cityId').val());searchHousingRental(true);});
			$('#neighbourhoodId').change(function(){searchHousingRental(true);});
			/*$('#houseClassificationId').change(function(){searchHousing(true);});*/
			$('#houseSubClassificationId').change(function(){searchHousingRental(true);});
			$('#ageTypeId').change(function(){searchHousingRental(true);});
			$('#existingBuild').change(function(){searchHousingRental(true);});
			$('#newBuild').change(function(){searchHousingRental(true);});
			$('#bothBuild').change(function(){searchHousingRental(true);});
			
		searchHousingRental();
	}
	
	function setSliderValuesIntoLabels() {
		var sliderValues = $("#sliderArea").slider("option","values");
		$('span#varMinPrice').html('&euro; '+formatThousands(sliderValues[0]));
		$('span#varMaxPrice').html('&euro; '+formatThousands(sliderValues[1]));
	}
	
	
	
	function fillCitiesSelect(selectedId) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getCities',
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#cityId').html('<option value="">Alle regio\'s</option>');
				fillValuesInSelectlist(evt,'select#cityId',selectedId);
			}
		});
	}
	
	function fillAgeTypeSelect(selectedId) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getAgeTypes',
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#ageTypeId').html('<option value="">Alle leeftijden</option>');
				fillValuesInSelectlist(evt,'select#ageTypeId',selectedId);
			}
		});
	}
	
	function fillProjectPlusCitiesSelect(selectedId) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getProjectPlusCities',
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#cityId').html('<option value="">Alle regio\'s</option>');
				fillValuesInSelectlist(evt,'select#cityId',selectedId);
			}
		});
	}
	
	function fillCommissionsCitySelect(selectedId) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getCommissionCities',
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#cityId').html('<option value="">Alle regio\'s</option>');
				fillValuesInSelectlist(evt,'select#cityId',selectedId);
			}
		});
	}
	
	function fillCityPartsSelect(cityId,selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getCityPartsForCity&cityId='+cityId,
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#cityPartId').html('<option value="">Alle stadsdelen</option>');
				fillValuesInSelectlist(evt,'select#cityPartId',selectValue);
			}
		});
	}
	
	
	function fillDistrictSelect(cityPartId,selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getDistrictsForCity&cityPartId='+cityPartId,
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#districtId').html('<option value="">Alle wijken</option>');
				fillValuesInSelectlist(evt,'select#districtId',selectValue);
			}
		});
	}
	
	
	function fillNeighborhoodsSelect(districtId,selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getNeighborhoodsForCity&districtId='+districtId,
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#neighborhoodId').html('<option value="">Alle buurten</option>');
				fillValuesInSelectlist(evt,'select#neighborhoodId',selectValue);
			}
		});
	}
	

	function fillObjectsSelect(neighborhoodId,selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getObjectsForCity&neighborhoodId='+neighborhoodId,
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#objectId').html('<option value="">Alle straten</option>');
				fillValuesInSelectlist(evt,'select#objectId',selectValue);
			}
		});
	}
	
	
	function fillNeighbourhoodsSelect(cityId,selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getNeighbourhoodsForCity&cityId='+cityId,
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#neighbourhoodId').html('<option value="">Alle wijken</option>');
				fillValuesInSelectlist(evt,'select#neighbourhoodId',selectValue);
			}
		});
	}
	
	function fillProjectPlusNeighbourhoodsSelect(cityId,selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getProjectPlusNeighbourhoodsForCity&cityId='+cityId,
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#neighbourhoodId').html('<option value="">Alle wijken</option>');
				fillValuesInSelectlist(evt,'select#neighbourhoodId',selectValue);
			}
		});
	}
	
	function fillCommissionsNeighbourhoodsSelect(cityId,selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getCommissionNeighbourhoodsForCity&cityId='+cityId,
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#neighbourhoodId').html('<option value="">Alle wijken</option>');
				fillValuesInSelectlist(evt,'select#neighbourhoodId',selectValue);
			}
		});
	}
	
	function fillHouseClassificationsSelect(selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getHouseClassifications',
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#houseClassificationId').html('<option value="">Alle woningtypen</option>');
				fillValuesInSelectlist(evt,'select#houseClassificationId',selectValue);
			}
		});
	}
	
	function fillHouseSubClassificationsSelect(selectValue) {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getHouseSubClassifications',
			dataType: 'json',
			async: false,
			success: function(evt){
				$('select#houseSubClassificationId').html('<option value="">Alle woningtypen</option>');
				fillValuesInSelectlist(evt,'select#houseSubClassificationId',selectValue);
			}
		});
	}
	
	function searchHousing(resetToPage1) {
		showHousingAjaxLoader();
		var sliderValues = $("#sliderArea").slider("option","values");
		var searchData = {action: 'searchHousing'}
		
		searchData.minPrice = sliderValues[0];
		searchData.maxPrice = sliderValues[1];
		searchData.cityId = $('select#cityId').val();
		searchData.neighbourhoodId = $('select#neighbourhoodId').val();
		//searchData.houseClassificationId = $('select#houseClassificationId').val();
		searchData.houseSubClassificationId = $('select#houseSubClassificationId').val();
		searchData.newBuild = $("input[@name='newBuild']:checked").val();
		searchData.sellType = $('input#sellType').val();
		searchData.viewType = $('input#viewType').val();
		searchData.orderPrice = $('input#orderPrice').val();
		
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php',
			dataType: 'json',
			data: searchData,
			success: function(evt){
				hideHousingAjaxLoader();
				
				if(evt.totalFound == 0) {
					$('div#resultHeader').html('');
					$('div#resultItems').html('Er zijn geen woningen gevonden die aan je criteria voldoen.');
				}else{			
					// Set correct class on Resultblock
					$('div#resultBlock').removeClass('resultBlockListview');
					$('div#resultBlock').removeClass('resultBlockGridview');
					if(searchData.viewType == 'LIST') {
						$('div#resultBlock').addClass('resultBlockListview');
						/*var resultHeaderHTML = '<span id="varTotalHouses">totaal ' + evt.totalFound + ' woningen</span><span>project wijk plaats</span><a href="#" id="listviewSort" class="';
						if($('input#orderPrice').val() == 'ASC') {
							resultHeaderHTML += 'orderUp';
						}else{
							resultHeaderHTML += 'orderDown';
						}
						resultHeaderHTML += '" onclick="switchOrderPrice();return false;">Prijs vanaf</a><div class="clear"></div>';*/
						var resultHeaderHTML = '<span id="varTotalHouses">totaal ' + evt.totalFound + ' woningen</span><div class="clear"></div>';
						$('div#resultHeader').html(resultHeaderHTML);
					}else{
						$('div#resultBlock').addClass('resultBlockGridview');
						// Update total found
						$('div#resultHeader').html('<span>totaal ' + evt.totalFound + ' woningen</span><div class="clear"></div>');
					}
					
					// Update HTML
					$('div#resultItems').html(evt.html);
					$('div#resultpage_1').show();
					if ($("select#cityId option:selected").text() == "Alle regio's") {
						$('span#varRegion').html("alle regio's");						
					} else {
						$('span#varRegion').html($("select#cityId option:selected").text());
					}
					
					// Update pagination
					$('div#pagination').html(evt.pagesHTML);
					housingTotalPages = evt.numberOfPages;
					if(housingTotalPages > 1) {
						$('a#moveHousingPageLinkNext').show();				
					}
					
					// Move to a page?
					if(gotoOverviewPage !== '') {
						moveHousingPage(gotoOverviewPage, 'housing');
					}else{
						moveHousingPage(1, 'housing');
					}
					if(resetToPage1) {
						moveHousingPage(1, 'housing');
					}
					
					// Set gmaps coords in var
					gmapsCoords = jQuery.parseJSON(evt.gmapsCoords);
					
					// Popup the first page's items on it and show on map
					try {
						MYMAP.placeMarkersArray(gmapsCoords[1]);
					}catch(e) {}
				}
			}
		});
	}
	
	function searchHousingRental(resetToPage1) {
		showHousingAjaxLoader();
		var sliderValues = $("#sliderArea").slider("option","values");
		var searchData = {action: 'searchHousingRental'}
		
		searchData.minPrice = sliderValues[0];
		searchData.maxPrice = sliderValues[1];
		searchData.cityId = $('select#cityId').val();
		searchData.neighbourhoodId = $('select#neighbourhoodId').val();
		//searchData.houseClassificationId = $('select#houseClassificationId').val();
		searchData.houseSubClassificationId = $('select#houseSubClassificationId').val();
		searchData.ageTypeId = $('select#ageTypeId').val();
		searchData.newBuild = $("input[@name='newBuild']:checked").val();
		searchData.sellType = $('input#sellType').val();
		searchData.viewType = $('input#viewType').val();
		searchData.orderPrice = $('input#orderPrice').val();
		
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php',
			dataType: 'json',
			data: searchData,
			success: function(evt){
				hideHousingAjaxLoader();
				//console.log(evt.html);
				if(evt.totalFound == 0) {
					$('div#resultHeader').html('');
					$('div#resultItems').html('Er zijn geen woningen gevonden die aan je criteria voldoen.');
				}else{			
					// Set correct class on Resultblock
					$('div#resultBlock').removeClass('resultBlockListview');
					$('div#resultBlock').removeClass('resultBlockGridview');
					if(searchData.viewType == 'LIST') {
						$('div#resultBlock').addClass('resultBlockListview');
						/*var resultHeaderHTML = '<span id="varTotalHouses">totaal ' + evt.totalFound + ' woningen</span><span>project wijk plaats</span><a href="#" id="listviewSort" class="';
						if($('input#orderPrice').val() == 'ASC') {
							resultHeaderHTML += 'orderUp';
						}else{
							resultHeaderHTML += 'orderDown';
						}
						resultHeaderHTML += '" onclick="switchOrderPrice();return false;">Prijs vanaf</a><div class="clear"></div>';*/
						var resultHeaderHTML = '<span id="varTotalHouses">totaal ' + evt.totalFound + ' woningen</span><div class="clear"></div>';
						$('div#resultHeader').html(resultHeaderHTML);
					}else{
						$('div#resultBlock').addClass('resultBlockGridview');
						// Update total found
						$('div#resultHeader').html('<span>totaal ' + evt.totalFound + ' woningen</span><div class="clear"></div>');
					}
					
					// Update HTML
					$('div#resultItems').html(evt.html);
					$('div#resultpage_1').show();
					
					if ($("select#cityId option:selected").text() == "Alle regio's") {
						$('span#varRegion').html("alle regio's");						
					} else {
						$('span#varRegion').html($("select#cityId option:selected").text());
					}
					
					// Update pagination
					$('div#pagination').html(evt.pagesHTML);
					housingTotalPages = evt.numberOfPages;
					if(housingTotalPages > 1) {
						$('a#moveHousingPageLinkNext').show();				
					}
					
					// Move to a page?
					if(gotoOverviewPage !== '') {
						moveHousingPage(gotoOverviewPage, 'housing');
					}else{
						moveHousingPage(1, 'housing');
					}
					if(resetToPage1) {
						moveHousingPage(1, 'housing');
					}
					
					// Set gmaps coords in var
					gmapsCoords = jQuery.parseJSON(evt.gmapsCoords);
					
					// Popup the first page's items on it and show on map
					try {
						MYMAP.placeMarkersArray(gmapsCoords[1]);
					}catch(e) {}
				}
			}
		});
	}
	
	function searchCommissions() {
		showCommissionsAjaxLoader();
		
		//alert(mapZoomLevel);
		
		var searchData = {action: 'searchCommissions'}
		searchData.cityId = $('select#cityId').val();
		searchData.cityPartId = $('select#cityPartId').val();
		searchData.districtId = $('select#districtId').val();
		searchData.neighborhoodId = $('select#neighborhoodId').val();
		searchData.objectId = $('select#objectId').val();
		
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php',
			dataType: 'json',
			data: searchData,
			success: function(evt){	

				if(evt.totalFound == 0) {
					
					// Reset the map
					try {
						MYMAP.placeMarkersArray();
					}catch(e) {}
					
					$('div#commissionOverview').html('Er zijn geen buurtcommissies gevonden die aan je criteria voldoen.');
				}else{			
					$('div#commissionOverview').html(evt.html);					
					
					// Set gmaps coords in var
					gmapsCoords = evt.gmapsCoords;
					//gmapsCoords = evt.gmapsCoords;
					//console.log(gmapsCoords);
					/*alert(gmapsCoords[1]);
					drawMyOverlayMarkers(gmapsCoords);
					*/
					
					//alert(OverlayMap);
					
					// Popup the first page's items on it and show on map
					try {
						//OverlayMap.draw(gmapsCoords[1]);
						MYMAP.placeMarkersArray(gmapsCoords[1]);
					}catch(e) {
					}
				
				}
			}
		});
		
		
	}
	
	function loadSearchFiltersFromSession() {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getSearchFiltersFromSession',
			dataType: 'json',
			async: false,
			success: function(evt) {
				if(evt != null) {
					if(!isNaN(evt.minPrice) && evt.minPrice != '') {
						$("#sliderArea").slider("values",0,evt.minPrice);
						setSliderValuesIntoLabels();
					}
					if(!isNaN(evt.maxPrice) && evt.maxPrice != '') {
						$("#sliderArea").slider("values",1,evt.maxPrice);
						setSliderValuesIntoLabels();
					}
					if(!isNaN(evt.cityId) && evt.cityId != '') {
						$("select#cityId").val(evt.cityId);
						
						// Load neighbourhoods
						if(!isNaN(evt.neighbourhoodId) && evt.neighbourhoodId != '') {
							fillNeighbourhoodsSelect(evt.cityId,evt.neighbourhoodId);
						}
					}
					if(!isNaN(evt.houseClassificationId) && evt.houseClassificationId != '') {
						$("select#houseClassificationId").val(evt.houseClassificationId);
					}
					if(!isNaN(evt.houseSubClassificationId) && evt.houseSubClassificationId != '') {
						$("select#houseSubClassificationId").val(evt.houseSubClassificationId);
					}
					if(evt.newBuild != '') {
						$("input#existingBuild").attr('checked',false);
						$("input#newBuild").attr('checked',false);
						$("input#bothBuild").attr('checked',false);
						
						switch(evt.newBuild) {
						case 'OLD':
							$("input#existingBuild").attr('checked',true);
							break;
						case 'NEW':
							$("input#newBuild").attr('checked',true);
							break;
						default:
						case 'BOTH':
							$("input#bothBuild").attr('checked',true);
							break;
						}
					}
					if(evt.viewType != '') {
						setViewType(evt.viewType);
					}
					if(evt.orderPrice != '') {
						setOrderPrice(evt.orderPrice);
					}
				}
			}
		});
	}
	
	function loadSearchFiltersFromSessionRental() {
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php?action=getSearchFiltersFromSessionRental',
			dataType: 'json',
			async: false,
			success: function(evt) {
				if(evt != null) {
					if(!isNaN(evt.minPrice) && evt.minPrice != '') {
						$("#sliderArea").slider("values",0,evt.minPrice);
						setSliderValuesIntoLabels();
					}
					if(!isNaN(evt.maxPrice) && evt.maxPrice != '') {
						$("#sliderArea").slider("values",1,evt.maxPrice);
						setSliderValuesIntoLabels();
					}
					if(!isNaN(evt.cityId) && evt.cityId != '') {
						$("select#cityId").val(evt.cityId);
						
						// Load neighbourhoods
						if(!isNaN(evt.neighbourhoodId) && evt.neighbourhoodId != '') {
							fillNeighbourhoodsSelect(evt.cityId,evt.neighbourhoodId);
						}
					}
					if(!isNaN(evt.houseClassificationId) && evt.houseClassificationId != '') {
						$("select#houseClassificationId").val(evt.houseClassificationId);
					}
					if(!isNaN(evt.houseSubClassificationId) && evt.houseSubClassificationId != '') {
						$("select#houseSubClassificationId").val(evt.houseSubClassificationId);
					}
					if(!isNaN(evt.ageTypeId) && evt.ageTypeId != '') {
						$("select#ageTypeId").val(evt.ageTypeId);
					}
					if(evt.newBuild != '') {
						$("input#existingBuild").attr('checked',false);
						$("input#newBuild").attr('checked',false);
						$("input#bothBuild").attr('checked',false);
						
						switch(evt.newBuild) {
						case 'OLD':
							$("input#existingBuild").attr('checked',true);
							break;
						case 'NEW':
							$("input#newBuild").attr('checked',true);
							break;
						default:
						case 'BOTH':
							$("input#bothBuild").attr('checked',true);
							break;
						}
					}
					if(evt.viewType != '') {
						setViewType(evt.viewType);
					}
					if(evt.orderPrice != '') {
						setOrderPrice(evt.orderPrice);
					}
				}
			}
		});
	}
	
	function resetHousingFilters() {
		var ajaxData = {action: 'resetHousingFilters'}
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php',
			data: ajaxData,
			async: false,
			success: function(evt){
				 moveHousingPage(1,'housing');
			}
		});
		location.reload();
	}
	
	function moveHousingPage(pageNumber,module) {
		// First deactivate all pages
		$('div.resultListPage').hide();
		$('div#pagination a').removeClass('active');
		
		// Activate correct page
		$('div#resultpage_'+pageNumber).show();
		$('div#pagination a#movePageLink_'+pageNumber).addClass('active');
		housingCurrentPage = pageNumber;
		
		// Set gotoPage-code so it'll come back to this page upon revisiting
		setGotoPageCode(module,pageNumber);
		
		// Update map
		try {
			MYMAP.placeMarkersArray(gmapsCoords[pageNumber]);
		}catch(e) {}
		
		// Update prev and next buttons
		updatePrevAndNextButton();
	}
	
	function moveHousingPagePrev() {
		housingCurrentPage--;
		moveHousingPage(housingCurrentPage);
		// Update prev and next buttons
		updatePrevAndNextButton();
	}
	
	function moveHousingPageNext() {
		housingCurrentPage++;
		moveHousingPage(housingCurrentPage);
		// Update prev and next buttons
		updatePrevAndNextButton();
	}
	
	function switchViewType() {	
		if($('input#viewType').val() == 'LIST') {
			setViewType('GRID');
		}else{
			setViewType('LIST');
		}
		// Reset gotoPageCode
		gotoOverviewPage = '1';
		searchHousing();
	}
	
	function switchViewTypeRental() {	
		if($('input#viewType').val() == 'LIST') {
			setViewType('GRID');
		}else{
			setViewType('LIST');
		}
		// Reset gotoPageCode
		gotoOverviewPage = '1';
		searchHousingRental();
	}
	
	/**
	 * Set viewtype
	 * @param ENUM GRID|LIST viewType
	 */
	function setViewType(viewType) {
		$('#viewTypeTooltip').text('');
		if(viewType == 'GRID') {
			$('img#viewTypeImage').attr('src',imgPath+'btn_listview.gif');
			$('img#viewTypeImage').attr('alt','Lijstweergave');
			$('input#viewType').val('GRID');
		}else{
			$('img#viewTypeImage').attr('src',imgPath+'btn_gridview.gif');
			$('img#viewTypeImage').attr('alt','Tegelweergave');
			$('input#viewType').val('LIST');
		}
	}
	
	function switchOrderPrice() {	
		if($('input#orderPrice').val() == 'ASC') {
			setOrderPrice('DESC');
		}else{
			setOrderPrice('ASC');
		}
		searchHousing();
	}
	
	/**
	 * Set the order price by asc or desc
	 * @param ENUM ASC|DESC orderPrice
	 */
	function setOrderPrice(orderPrice) {
		$('input#orderPrice').val(orderPrice);
		// Update class
		$('a#listviewSort').removeClass();
		if(orderPrice == 'ASC') {
			$('a#listviewSort').addClass('orderUp');
		}else{
			$('a#listviewSort').addClass('orderDown');
		}
	}
	
	function showHousingAjaxLoader() {
		$('div#resultItems').html('<div id="housingAjaxLoader"></div>');
		$('div#pagination').html('');
		$('div#resultHeader').hide();
	}
	
	function hideHousingAjaxLoader() {
		$('div#resultHeader').show();
	}
	
	function showCommissionsAjaxLoader() {
		$('div#commissionOverview').html('<div id="housingAjaxLoader"></div>');
	}
	
	function updatePrevAndNextButton() {
		// Check if prev and next button should be disabled/enabled
		$('a#moveHousingPageLinkNext').show();
		$('a#moveHousingPageLinkPrev').show();
		if(housingCurrentPage == 1) {
			$('a#moveHousingPageLinkPrev').hide();
		}
		if(housingCurrentPage == housingTotalPages) {
			$('a#moveHousingPageLinkNext').hide();
		}
	}

/* END Housing Overview functions */

/* START project overview functions */
	function searchProjects(resetToPage1) {
		showHousingAjaxLoader();

		var searchData = {action: 'searchProjects'}
		
		searchData.showBuyProjects = $('#showBuyProjects').attr('checked'); 
		searchData.showRentProjects = $('#showRentProjects').attr('checked');
		searchData.filterCity = $('#filterCity').val();
		searchData.filterHouseTypes = $('#filterHouseTypes').val();
		searchData.filterTargetgroups = $('#filterTargetgroups').val();
		searchData.filterStatus = $('#filterStatus').val();
		
		searchData.viewType = $('input#viewType').val();
		
		
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php',
			dataType: 'json',
			data: searchData,
			success: function(evt){
				hideHousingAjaxLoader();

				if(evt.totalFound == 0) {
					$('div#resultHeader').html('');
					$('div#resultItems').html('Er zijn geen projecten gevonden die aan je criteria voldoen.');
				}else{			
					/*
					// Set correct class on Resultblock
					//$('div#resultBlock').removeClass('resultBlockListview');
					//$('div#resultBlock').removeClass('resultBlockGridview');
					if(searchData.viewType == 'LIST') {
						
					}else{
						
					}
					*/
					
					// Update HTML
					$('div#resultItems').html(evt.html);
					$('div#resultpage_1').show();

					// Update pagination
					$('div#pagination').html(evt.pagesHTML);
					housingTotalPages = evt.numberOfPages;
					if(housingTotalPages > 1) {
						$('a#moveHousingPageLinkNext').show();				
					}
					
					// Move to a page?
					if(gotoOverviewPage !== '') {
						moveHousingPage(gotoOverviewPage, 'newbuildProjects');
					}else{
						moveHousingPage(1, 'newbuildProjects');
					}
					if(resetToPage1) {
						moveHousingPage(1, 'newbuildProjects');
					}
				}
			}
		});	
	}
	
	function switchProjectViewType() {	
		if($('input#viewType').val() == 'LIST') {
			setViewType('GRID');
		}else{
			setViewType('LIST');
		}
		// Reset gotoPageCode
		gotoOverviewPage = '1';
		searchProjects();
	}
/* END Project Overview functions */
	
/* START Woonincplus overview functions */
	function searchProjectsPlus(resetToPage1) {
		showHousingAjaxLoader();

		var searchData = {action: 'searchProjectsPlus'}
		
		searchData.showBuyProjects = $('#showBuyProjects').attr('checked'); 
		searchData.showRentProjects = $('#showRentProjects').attr('checked');
		searchData.cityId = $('#cityId').val();
		searchData.neighbourhoodId = $('#neighbourhoodId').val();
		
		searchData.viewType = $('input#viewType').val();
		
		
		$.ajax({
			url: rootPath+'pages/ajax_functions.inc.php',
			dataType: 'json',
			data: searchData,
			success: function(evt){
				hideHousingAjaxLoader();

				if(evt.totalFound == 0) {
					$('div#resultHeader').html('');
					$('div#resultItems').html('Er zijn geen projecten gevonden die aan je criteria voldoen.');
				}else{								
					// Update HTML
					$('div#resultItems').html(evt.html);
					$('div#resultpage_1').show();

					// Update pagination
					$('div#pagination').html(evt.pagesHTML);
					housingTotalPages = evt.numberOfPages;
					if(housingTotalPages > 1) {
						$('a#moveHousingPageLinkNext').show();				
					}
					
					// Move to a page?
					if(gotoOverviewPage !== '') {
						moveHousingPage(gotoOverviewPage, 'newbuildProjectsPlus');
					}else{
						moveHousingPage(1, 'newbuildProjectsPlus');
					}
					if(resetToPage1) {
						moveHousingPage(1, 'newbuildProjectsPlus');
					}
				}
			}
		});	
	}
	
	function switchProjectPlusViewType() {	
		if($('input#viewType').val() == 'LIST') {
			setViewType('GRID');
		}else{
			setViewType('LIST');
		}
		// Reset gotoPageCode
		gotoOverviewPage = '1';
		searchProjectsPlus();
	}
/* END Wooninc Plus overview functions */
	
/* START commercial project overview functions */
function searchCommercialProjects(resetToPage1) {
	showHousingAjaxLoader();

	var searchData = {action: 'searchCommercialProjects'}
	
	/*searchData.showBuyProjects = $('#showBuyProjects').attr('checked'); 
	searchData.showRentProjects = $('#showRentProjects').attr('checked');*/
	searchData.filterCity = $('#filterCity').val();
	searchData.filterHouseTypes = $('#filterHouseTypes').val();
	searchData.filterTargetgroups = $('#filterTargetgroups').val();
	searchData.filterStatus = $('#filterStatus').val();
	
	searchData.viewType = $('input#viewType').val();
	
	
	$.ajax({
		url: rootPath+'pages/ajax_functions.inc.php',
		dataType: 'json',
		data: searchData,
		success: function(evt){
			hideHousingAjaxLoader();

			if(evt.totalFound == 0) {
				$('div#resultHeader').html('');
				$('div#resultItems').html('Er zijn geen commerciële ruimtes gevonden die aan je criteria voldoen.');
			}else{			
				// Update HTML
				$('div#resultItems').html(evt.html);
				$('div#resultpage_1').show();

				// Update pagination
				$('div#pagination').html(evt.pagesHTML);
				housingTotalPages = evt.numberOfPages;
				if(housingTotalPages > 1) {
					$('a#moveHousingPageLinkNext').show();				
				}
				
				// Move to a page?
				if(gotoOverviewPage !== '') {
					moveHousingPage(gotoOverviewPage, 'newbuildCommercialProjects');
				}else{
					moveHousingPage(1, 'newbuildCommercialProjects');
				}
				if(resetToPage1) {
					moveHousingPage(1, 'newbuildCommercialProjects');
				}
			}
		}
	});	
}

function switchCommercialProjectViewType() {	
	if($('input#viewType').val() == 'LIST') {
		setViewType('GRID');
	}else{
		setViewType('LIST');
	}
	// Reset gotoPageCode
	gotoOverviewPage = '1';
	searchCommercialProjects();
}
/* END commercial Projects Overview functions */

/**
 * Fill values of a jsonString into a selectlist
 * 
 * @param valuesJson 	-> json array with values [value (id),text]
 * @param selector		-> selectlist to fill, ie 'select#myList'
 * @param valueToSelect -> Select this value in the selectlist
 */
function fillValuesInSelectlist(valuesJson,selector,valueToSelect) {
	var optionsHTML = '';
	for(var i in valuesJson) {
		optionsHTML += '<option value="'+valuesJson[i][0]+'">'+addSlashes(valuesJson[i][1])+'</option>';
	}
	$(selector).append(optionsHTML);
	if(valueToSelect != '') {
		$(selector).val(valueToSelect);
	}
}

/**
 * Select a value in a selectlist
 * @param selectlistId	->	ID of the selectlist
 * @param valueToSelect	->	The value to select
 */
function selectValueInSelectlist(selectlistId,valueToSelect) {
	$('select#'+selectlistId).val(valueToSelect);
}

/**
 * Escape quotes with leading slashes
 */
function addSlashes(input) {
	var output = input;
	output = output.replace("'","\'");
	output = output.replace('"','\"');
	return output;
}

function toggleMoreNews() {
	$('#moreNews').toggle();
	if($('#moreNews').css('display') == 'block') {
		$('#pagination a').html('minder nieuws &gt;');
	}else{
		$('#pagination a').html('meer nieuws &gt;');
	}
}

/**
 * Format thousands, add decimal to group thousands
 * @param inputValue	Value to format
 * @returns {String}
 */
function formatThousands(inputValue) {
	var inputString = inputValue.toString();
	var strLength = inputString.length-1;
	var output = '';
	// Loop backwards and after every 3rd number add decimal
	var q=0;
	for(var i=strLength;i>=0;i--) {
		decimalSymbol = '';
		if(q==3) {
			decimalSymbol = '.';
			q = 0;
		}
		output = inputString.charAt(i) + decimalSymbol + output;
		q++;
	}
	return output;
}

function toggleSubitem(aTag) {
	$(aTag).parent('li').find('ul.subitems').toggle();
	if($(aTag).parent('li').find('ul.subitems').css('display') == 'block') {
		$(aTag).css('background-image','url('+imgPath+'btn_min.gif');
	}else{
		$(aTag).css('background-image','url('+imgPath+'btn_plus.gif');
	}
}

function toggleSubSubitem(aTag) {
	$(aTag).parent('li').find('div.subsubitem').toggle();
	if($(aTag).parent('li').find('div.subsubitem').css('display') == 'block') {
		$(aTag).css('background-image','url('+imgPath+'btn_min.gif');
	}else{
		$(aTag).css('background-image','url('+imgPath+'btn_plus.gif');
	}
}

function setGotoPageCode(module,pageNumber) {
	$.ajax({
		url: rootPath+'pages/ajax_functions.inc.php?action=setGotoPageCode&module='+module+'&pagenumber='+pageNumber,
		success: function(evt){}
	});
}

function downloadBrochure(filename) {
	// Show download form
	$('div#downloadBrochureForm').show();
	// Fill filename
	$('div#downloadBrochureForm input#dl_downloadFilename').val(filename);
}

function closeDownloadBrochureForm() {
	$('div#downloadBrochureForm').hide();
}


function doDownloadBrochure() {
	var searchData = {action: 'doDownloadBrochure'}
	searchData.name = $('div#downloadBrochureForm input#dl_name').val();
	searchData.gender = $("input[name='dl_gender']:checked").val();
	searchData.city = $('div#downloadBrochureForm input#dl_city').val();
	searchData.birthdate = $('div#downloadBrochureForm input#dl_birthdate').val();
	searchData.phone = $('div#downloadBrochureForm input#dl_phone').val();
	searchData.email = $('div#downloadBrochureForm input#dl_email').val();
	searchData.downloadFilename = $('div#downloadBrochureForm input#dl_downloadFilename').val();
	searchData.projectId = $('div#downloadBrochureForm input#dl_projectId').val();
	
	$('div#downloadBrochureForm input').removeClass('errorfield');
			
	$.ajax({
		url: rootPath+'pages/ajax_functions.inc.php',
		dataType: 'json',
		data: searchData,
		success: function(evt){
			if(evt.msg == 0) {	// OK
				// open new screen for download
				var dlLink = rootPath+'pages/downloadprojectbrochure.php?id='+evt.downloadId+'&uniqueId='+evt.uniqueId;
				$('div#downloadBrochureFormContent').html('Bedankt voor het invoeren van uw gegevens.<br><a href="'+dlLink+'" target="_blank">Klik hier om uw brochure te downloaden</a>.');
			}else{
				for(var i in evt.errors) {
					alert('#dl_'+evt.errors[i]);
					$('#dl_'+evt.errors[i]).addClass('errorfield');
				}
			}
		}
	});
}

function doDownloadHouseBrochure() {
	var searchData = {action: 'doDownloadHouseBrochure'}
	searchData.name = $('div#downloadBrochureForm input#dl_name').val();
	searchData.gender = $("input:radio[name='dl_gender']:checked").val();
	searchData.city = $('div#downloadBrochureForm input#dl_city').val();
	searchData.birthdate = $('div#downloadBrochureForm input#dl_birthdate').val();
	searchData.phone = $('div#downloadBrochureForm input#dl_phone').val();
	searchData.email = $('div#downloadBrochureForm input#dl_email').val();
	searchData.downloadFilename = $('div#downloadBrochureForm input#dl_downloadFilename').val();
	searchData.houseId = $('div#downloadBrochureForm input#dl_projectId').val();
	
	$('div#downloadBrochureForm input').removeClass('errorfield');
			
	$.ajax({
		url: rootPath+'pages/ajax_functions.inc.php',
		dataType: 'json',
		data: searchData,
		success: function(evt){
			if(evt.msg == 0) {	// OK
				// open new screen for download
				var dlLink = rootPath+'pages/downloadhousebrochure.php?id='+evt.downloadId+'&uniqueId='+evt.uniqueId;
				$('div#downloadBrochureFormContent').html('Bedankt voor het invoeren van uw gegevens.<br><a href="'+dlLink+'" target="_blank">Klik hier om uw brochure te downloaden</a>.');
			}else{
				for(var i in evt.errors) {
					//alert(evt.errors[i]);
					$('#dl_'+evt.errors[i]).addClass('errorfield');
				}
			}
		}
	});
}


function attachYoutubeMouseovers() {
	$('a.youtube').mouseenter(function(){displayYoutubeMouseover(this);}).mouseout(function(){hideYoutubeMouseover(this);});
}

function displayYoutubeMouseover(aTagObject) {
	var overlayText = $(aTagObject).find('img').attr('alt');
	if(overlayText != '') {
		$(aTagObject).append('<div class="youtubeMouseover">'+overlayText+'</div>');
	}
}

function hideYoutubeMouseover(aTagObject) {
	 $(aTagObject).find('.youtubeMouseover').remove();
}

function toggleFaqCategory(clickedCategory, pagetrackerName) {
	if($(clickedCategory).parent('.faqCategory').hasClass('expanded')) {
		$(clickedCategory).parent('.faqCategory').removeClass('expanded');
		$(clickedCategory).parent('.faqCategory').addClass('collapsed');
	}else{
		$(clickedCategory).parent('.faqCategory').removeClass('collapsed');
		$(clickedCategory).parent('.faqCategory').addClass('expanded');
		if(pagetrackerName != ''){
			pageTracker._trackEvent('vragen', 'vraaggroep', pagetrackerName); 
		}
	}	
}

function toggleFaqQuestion(clickedQuestion, pagetrackerName) {
	if($(clickedQuestion).parent('.faqQuestion').hasClass('expanded')) {
		$(clickedQuestion).parent('.faqQuestion').removeClass('expanded');
		$(clickedQuestion).parent('.faqQuestion').addClass('collapsed');
	}else{
		$(clickedQuestion).parent('.faqQuestion').removeClass('collapsed');
		$(clickedQuestion).parent('.faqQuestion').addClass('expanded');
		if(pagetrackerName != ''){
			pageTracker._trackEvent('vragen', 'vraag', pagetrackerName); 
		}
	}
}

function expandAllFaqItems() {
	$('.faqCategory').removeClass('collapsed');
	$('.faqCategory').addClass('expanded');
	$('.faqQuestion').removeClass('collapsed');
	$('.faqQuestion').addClass('expanded');
}

function expandCompleteFaq() {
	$('.faqCategory').removeClass('collapsed');
	$('.faqQuestion').removeClass('collapsed');
	
	$('.faqCategory').addClass('expanded');
	$('.faqQuestion').addClass('expanded');
}

/* Footerbanner */
var totalFooterBanners = 0;
var currentFooterBanner = 0;
var footerBannerTimeout = '';

$(document).ready(function(){
	totalFooterBanners = $('.footerBanner').size();
	if(totalFooterBanners>1){
		footerBannerTimeout = setTimeout("switchFooterBanner();",5000);
	}
});

function switchFooterBanner() {
	var nextFooterBanner = currentFooterBanner+1;
	if(nextFooterBanner==totalFooterBanners){nextFooterBanner=0;}
	
	// Switch em
	$('#footerbanner_'+currentFooterBanner).removeClass('visible');
	$('#footerbanner_'+nextFooterBanner).addClass('visible');
	
	currentFooterBanner = nextFooterBanner;
	
	footerBannerTimeout = setTimeout("switchFooterBanner();",5000);
}
