var page = currentPage = 1;
var resultsPerPage = 6;
var adjacentPages = 2;
var documentLocation = document.location.href.split('pagina.php');
var currentPageNumberTop;
var currentPageNumberLeft;
var foundCheckedItems = false;

$(document).ready(function() {

	if ($.cookie('currentPage') != null) {
		currentPage = $.cookie('currentPage');
	}
	
	if ($("div.ratings").length > 0)	{
		$("div.ratings input.star").rating();
	}

	initReferenceHovers();

	$("ul#hoofdmenu > li > ul.submenu").css('display','none');
	$("ul#hoofdmenu > li").hover(
	    function(){
	        $("ul#hoofdmenu *:animated").stop(true,true).hide(); //stop the madness
	        $('ul',this).slideDown(500);
	    },
	    function(){
	    	$("ul#hoofdmenu *:animated").stop(true,true).hide(); //stop the madness
	        $('ul',this).slideUp(100);
	    }
	);

	setPageNumberPosition(true);

	if ($('.letter').length != 0) {
		$('.letter').hide();
		$('.abc').click(function() {
			var abcLetter = $(this).attr('id').split('_');
			if ($('#abcLetter_'+abcLetter[1]).css('display') == 'none') {
				$('#abcLetter_'+abcLetter[1]).slideDown();
			} else {
				$('#abcLetter_'+abcLetter[1]).slideUp();
			}
		});
	}

	if ($('.button').length != 0) {
		$('.button').mouseover(function() {
			$(this).children('.button_left').attr('src','/grafix/button_left_hover.gif');
			$(this).children('.button_right').attr('src','/grafix/button_right_hover.gif');
		}).mouseout(function() {
			$(this).children('.button_left').attr('src','/grafix/button_left.gif');
			$(this).children('.button_right').attr('src','/grafix/button_right.gif');
		});
	}

	if ($('.prev_button').length != 0) {
		$('.prev_button').mouseover(function() {
			$(this).children('.button_left_hover').attr('src','/grafix/button_left.gif');
			$(this).children('.button_right_hover').attr('src','/grafix/button_right.gif');
		}).mouseout(function() {
			$(this).children('.button_left_hover').attr('src','/grafix/button_left_hover.gif');
			$(this).children('.button_right_hover').attr('src','/grafix/button_right_hover.gif');
		});
	}

	if ($('#filter').length != 0 && projectPageID != undefined) {
		$.getScript('/json/handleFilterSession.php?action=loadSession', function() {

			$.getJSON('/json/projects_'+projectPageID+'.json', false, function(data, textStatus){

				var dienstenAdded = new Array();
				var typesAdded = new Array();
				var branchesAdded = new Array();
				var projectCount = 0;
				$.each(data.projects, function() {
					//voorkomende diensten toevoegen aan de diensten fieldset
					if (this.diensten != undefined) {
						$.each(this.diensten, function(i, val) {
							if (!in_array(i, dienstenAdded, false)) {
								dienstenAdded[dienstenAdded.length] = i;
							}
						});
					}

					//voorkomende types toevoegen aan de types fieldset
					if (this.types != undefined) {
						$.each(this.types, function(i, val) {
							if (!in_array(i, typesAdded, false)) {
								typesAdded[typesAdded.length] = i;
							}
						});
					}

					//voorkomende branches toevoegen aan de branches fieldset
					if (this.branches != undefined) {
						$.each(this.branches, function(i, val) {
							if (!in_array(i, branchesAdded, false)) {
								branchesAdded[branchesAdded.length] = i;
							}
						});
					}

					projectCount++;
				});
				$.each(data.diensten, function(i, val) {
					//dienst gevonden dus tonen
					if (in_array(i, dienstenAdded, false)) {
						$('#dienstenFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="diensten[]" id="diensten_' + i + '" value="' + i + '" onclick="handleSearch()"><label class="active" for="diensten_' + i + '">' + val.naam + '</label><br>');
						if (sessionDiensten != undefined && sessionDiensten != 'undefined') {
							if (in_array(i, sessionDiensten)) {
								$('#diensten_'+i).attr('checked', true);
								foundCheckedItems = true;
							}
						}
					}
				});

				$.each(data.types, function(i, val) {
					//dienst gevonden dus tonen
					if (in_array(i, typesAdded, false)) {
						$('#typesFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="types[]" id="types_' + i + '" value="' + i + '" onclick="handleSearch()"><label class="active" for="types_' + i + '">' + val.naam + '</label><br>');
						if (sessionTypes != undefined && sessionTypes != 'undefined') {
							if (in_array(i, sessionTypes)) {
								$('#types_'+i).attr('checked', true);
								foundCheckedItems = true;
							}
						}
					}
				});

				$.each(data.branches, function(i, val) {
					//dienst gevonden dus tonen
					if (in_array(i, branchesAdded, false)) {
						$('#branchesFieldset').append('<input class="checkbox floatLeft" type="checkbox" name="branches[]" id="branches_' + i + '" value="' + i + '" onclick="handleSearch()"><label class="active" for="branches_' + i + '">' + val.naam + '</label><br>');
						if (sessionBranches != undefined && sessionBranches != 'undefined') {
							if (in_array(i, sessionBranches)) {
								$('#branches_'+i).attr('checked', true);
								foundCheckedItems = true;
							}
						}
					}
				});
				if (currentPage == undefined) {
					currentPage = 1;
				}
				if (foundCheckedItems || currentPage > 1) {
					handleSearch(currentPage, true);
				}
	        });//end getJSON
		});//end getScript
	}

	startReferentieFader(true);

	addFormAction();


});


function initReferenceHovers()
{
	if ($('.referentie_link').length > 0) {
		$('.referentie_link').mouseenter(function() {
			//remove the old ones
			if ($("div.hoveringReference").length > 0)	{
				$('.hoveringReference').remove();
			}
			var curLink = $(this);
			var appendHtml = '<div class="hoveringReference"><img style="top:70px; display:none;" src="/grafix/referenceButton.gif"></div>';
			$(this).append(appendHtml);
			$('.hoveringReference').css('opacity', 0.65);
			//$('.hoveringReference img').animate({top: '70px'},500, function() {
				if (curLink.attr('rel') != undefined) {
					var thisRel = curLink.attr('rel');
					var splitted = curLink.attr('rel').split('_')
					if (splitted[2] != undefined && splitted[2].length > 0) {
						getReferentiesByID(splitted[1], splitted[2]);
					} else {
						getReferentiesByID(splitted[1]);
					}
				}
			//});
			$('.hoveringReference img').fadeIn();

			$('.hoveringReference').mouseleave(function() {
				//if (ajaxRequests != false) {
				if (typeof(ajaxRequests) != 'boolean') {
					ajaxRequests.abort();
				}
				ajaxRequests = false;
				$('.hoveringReference').remove();
			});

		});

	}
}

var currentIndex = 1;
var currentTimeOut;
var pauseSlide = false;
var faderTime = 10000;
function startReferentieFader(firstTime)
{
	//only start fading when needed
	if ($('#referentie_image_geheel').length > 0) {
		$('.pauseKnop').unbind('click').click(function() {
			if (!pauseSlide) {
				pauseSlide = true;
				$('.pauseKnop').addClass('iconsRef_play');
				$('.pauseKnop').removeClass('iconsRef_pause');
				clearTimeout(currentTimeOut);
			} else {
				$('.pauseKnop').removeClass('iconsRef_play');
				$('.pauseKnop').addClass('iconsRef_pause');
				pauseSlide = false;
				currentTimeOut = setTimeout('startReferentieFader()',faderTime);
			}
		});

		$('.iconsRef_left').click(function() {
			var childs = $('#referentie_image_geheel').children('.referentie_img_wrap');
			var show;
			var hide;
			if (currentIndex-1 < 0) {
				hide = childs.length-1;
			} else {
				hide = currentIndex-1;
			}
			if (currentIndex-2 == -1) {
				show = childs.length-1;
			} else if (currentIndex-2 == -2) {
				show = childs.length-2;
			} else {
				show = currentIndex-2;
			}
			clearTimeout(currentTimeOut);

			//show clicked
			$('#'+childs[show].id).fadeIn(1000);
			$('.button_readMore').attr('href',$('#'+childs[show].id).children('.tekst').children('.currentLink').attr('href'));

			if (currentIndex-1 < 0) {
				currentIndex = childs.length-1;
			} else {
				currentIndex = currentIndex-1;
			}

			//hide old
			$('#'+childs[hide].id).fadeOut(1000);

			if (!pauseSlide) {
				currentTimeOut = setTimeout('startReferentieFader()',faderTime)
			}
			return false;
		});

		$('.iconsRef_right').click(function() {
			var childs = $('#referentie_image_geheel').children('.referentie_img_wrap');
			var show;
			var hide;
			if (currentIndex-1 < 0) {
				hide = childs.length-1;
			} else {
				hide = currentIndex-1;
			}
			show = currentIndex;
			clearTimeout(currentTimeOut);

			//show clicked
			$('#'+childs[show].id).fadeIn(1000);
			$('.button_readMore').attr('href',$('#'+childs[show].id).children('.tekst').children('.currentLink').attr('href'));

			if (currentIndex+1 > childs.length-1) {
				currentIndex = 0;
			} else {
				currentIndex++;
			}

			//hide old
			$('#'+childs[hide].id).fadeOut(1000);

			if (!pauseSlide) {
				currentTimeOut = setTimeout('startReferentieFader()',faderTime)
			}
			return false;
		});


		var childs = $('#referentie_image_geheel').children('.referentie_img_wrap');
		if (firstTime == undefined && childs.length > 1 && currentIndex != undefined) {
			//fadein current
			if (childs[currentIndex] != undefined) {
				$('#'+childs[currentIndex].id).fadeIn(1000);
				$('.button_readMore').attr('href',$('#'+childs[currentIndex].id).children('.tekst').children('.currentLink').attr('href'));
			}
			//fadeout previous
			if (currentIndex - 1 >= 0) {
				$('#'+childs[currentIndex - 1].id).fadeOut(1000);
			} else {
				$('#'+childs[childs.length - 1].id).fadeOut(1000);
			}
			//change to next index
			currentIndex++;
			if (currentIndex == childs.length) {
				currentIndex = 0;
			}
			//start timer
			clearTimeout(currentTimeOut);
			currentTimeOut = setTimeout('startReferentieFader()',faderTime)
		} else if(childs.length > 0) {
			//start first timer
			clearTimeout(currentTimeOut);
			currentTimeOut = setTimeout('startReferentieFader()',faderTime)
		}
	}
}

var ajaxRequests = false;
function getReferentiesByID(referentieID,strid)
{
	//process ajaxrequest
	$('#referentie_image_geheel').css('opacity','0.6');
	//$('#referentie_image_geheel').fadeTo(400,0.6);
	if (documentLocation.length == 1) {
		currentLink = '&dynamic=false';
	} else {
		currentLink = '&dynamic=true';
	}
	if (strid != undefined)	{
		currentLink = currentLink+'&structuurid='+strid;
	}
	//alert(typeof(ajaxRequests));
	if (typeof(ajaxRequests) != 'boolean') {
		ajaxRequests.abort();
	}

	ajaxRequests = false;
	ajaxRequests = $.ajax({
		url: "/json/getProject.php",
		type: "POST",
		data: 'projectID=' + referentieID+currentLink,
		dataType: "html",
		async: false,
		cache: true,
		complete: function(XMLHttpRequest, textStatus) {
			responseHtml = XMLHttpRequest.responseText;

			$('#referentie_image_geheel').hide();
			$('#referentie_image_geheel').html(responseHtml);
			//$('#referentie_image_geheel').fadeTo(400,1.0);
			//starten van fader
			$('#referentie_image_geheel').css('opacity','1.0');
			$('#referentie_image_geheel').fadeIn(800, function()	{
				$(this).css('filter','');
			});
		}
	});
}

function referentieMore(myBoxID)
{
	$('#small' + myBoxID).hide();
	$('#large' + myBoxID).slideDown();
}

function referentieLess(myBoxID)
{
	$('#large' + myBoxID).hide();
	$('#small' + myBoxID).slideDown();
}

function submenu(id)
{
	$('.submenu').not('#submenu_' + id).slideUp();
	if ($('#submenu_' + id).css('display') == 'none') {
		$('#submenu_' + id).slideDown();
		$("a[id*=level]").removeClass("activeDropdown");
		$("a#level"+id).addClass("activeDropdown");
	} else {
		$('#submenu_' + id).slideUp();
		$("a#level"+id).removeClass("activeDropdown");
	}
	return false;
}

function preloadModule()
{
	var docLoc = document.location.href;
	var exploded = docLoc.split('_');
	if (exploded.length > 1) {
		var moduleID = exploded[exploded.length-1];
	}else {
		var moduleID = firstModule;
	}
	handleOpsomming(moduleID);

}

function toggleNews(id)
{
	$('.box_nieuws_contact').not('#newsHomeBox_' + id).slideUp();
	$('.box_nieuws').not('#newsHomeBox_' + id).slideUp();
	$('.head_nieuws_contact').not('#newsLinks_' + id).removeClass('activeDropdown');
	$('.head_nieuws_home').not('#newsLinks_' + id).removeClass('activeDropdown');
	if ($('#newsHomeBox_' + id).css('display') == 'none') {
		$('#newsHomeBox_' + id).slideDown();
		$('#newsLinks_' + id).addClass('activeDropdown');
	} else {
		$('#newsHomeBox_' + id).slideUp();
		$('#newsLinks_' + id).removeClass('activeDropdown');

	}
	return false;
}

function handleOpsomming(id)
{
	//fix jumpy animation of divs without a height
	var height = $('#moduleOpsomming_' + id).data("originalHeight");
	var visible = $('#moduleOpsomming_' + id).is(":visible");
	if(!height ){
	    // get original height
	    height = $('#moduleOpsomming_' + id).show().height();
	    // update the height
	    $('#moduleOpsomming_' + id).data("originalHeight", height);
	    // if the element was hidden, hide it again
	    if( !visible ) $('#moduleOpsomming_' + id).hide();
	}

	$('.inhoud_opsomming').not('#moduleOpsomming_' + id).slideUp();
	$('.head2').not('#moduleOpsommingHref_' + id).removeClass('head2_active');
	if ($('#moduleOpsomming_' + id).css('display') == 'none') {
		$('#moduleOpsomming_' + id).css('height',0).animate({height: $('#moduleOpsomming_' + id).data('originalHeight')}, {duration: 500});
		$('#moduleOpsommingHref_' + id).addClass('head2_active');
	} else {
		$('#moduleOpsomming_' + id).animate({height: 0}, {duration: 500, complete: function(){$('#moduleOpsomming_' + id).hide()}});
		$('#moduleOpsommingHref_' + id).removeClass('head2_active');
	}

}


$.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
	$("<img>").attr("src", arguments[i]);
  }
}

function showResultsPerPage(results)
{
	$('#productsPerpage').val(results);
	$('#theFilterForm').submit();
}

function submitFilterForm()
{
	$('#page').val('1');
	$('#theFilterForm').submit();
}

//add action to filterform
/*function addFormAction()
{
	$('#theFilterForm').submit(function() {
		//display loadingdiv
		$("#loadingFilter").css('opacity', '0.5');
		$("#loadingFilter").css('display','block');
		$("#loadingProducts").css('opacity', '0.5');
		$("#loadingProducts").css('display','block');
		var inputs = $("#theFilterForm :input");
		var filterUrl = '';
		//create filterAjaxurl
		inputs.each(function(i){
			if ($(this).attr('type') == 'checkbox' && $(this).attr('checked') == true) {
				if (filterUrl == '') {
					filterUrl =  $(this).attr('name') + '=' + $(this).val()
				} else {
					filterUrl =  filterUrl + '&' + $(this).attr('name') + '=' + $(this).val()
				}
			} else if ($(this).attr('type') == 'text' || $(this).attr('type') == 'hidden') {
				if (filterUrl == '') {
					filterUrl =  $(this).attr('name') + '=' + $(this).val()
				} else {
					filterUrl =  filterUrl + '&' + $(this).attr('name') + '=' + $(this).val()
				}
			}
 		});

 		//process ajaxrequest
		$.ajax({
			url: "/filterProducts.php",
			type: "POST",
			data: filterUrl,
			dataType: "html",
			//cache: false,
			success: function(responseHtml) {
				var $holder = $('<div/>').html(responseHtml);
				//update filterDiv
				$('#productFilter').html($('#productFilter', $holder).html());
				//update productresultdiv
				$('.content_bb').html($('#productsFound', $holder).html());

				$("#loadingFilter").css('display','none');
				$("#loadingProducts").css('display','none');
				addFormAction();
			}
		});
		return false;
	});
}*/

function showLoginError(elementName){

	var element = document.getElementById(elementName);

	$.modal($(element),{

    	minHeight:17,
		containerCss:{backgroundColor:"#fff",height:130,padding:0,width:322},

		onOpen: function(dialog)
		{
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.slideDown('normal', function () {
					dialog.data.fadeIn('normal');

					element.style.visibility = 'visible';


				});
			});
		},
		onClose: function(dialog)
		{
			dialog.overlay.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.data.fadeOut('fast', function () {

						$.modal.close(); // must call this!
						$("#klantLoginFoutMeldingen").remove(); // and this too!

					});
				});
			});
		}

	});
}

function showResultPage(number)
{
	$('#page').val(number);
	$('#theFilterForm').submit();
}

function uncheckFilter(id)
{
	$('#' + id + 'Fieldset > input').attr('checked', false);
	$('#theFilterForm').submit();
}



//add action to filterform
function addFormAction()
{
	$('#theFilterForm').submit(function() {
		//display loadingdiv
		$("#loadingFilter").css('opacity', '0.5');
		$("#loadingFilter").css('display','block');
		$("#loadingProducts").css('opacity', '0.5');
		$("#loadingProducts").css('display','block');
		var inputs = $("#theFilterForm :input");
		var filterUrl = '';
		//create filterAjaxurl
		inputs.each(function(i){
			if ($(this).attr('type') == 'checkbox' && $(this).attr('checked') == true) {
				if (filterUrl == '') {
					filterUrl =  $(this).attr('name') + '=' + $(this).val()
				} else {
					filterUrl =  filterUrl + '&' + $(this).attr('name') + '=' + $(this).val()
				}
			} else if ($(this).attr('type') == 'text' || $(this).attr('type') == 'hidden') {
				if (filterUrl == '') {
					filterUrl =  $(this).attr('name') + '=' + $(this).val()
				} else {
					filterUrl =  filterUrl + '&' + $(this).attr('name') + '=' + $(this).val()
				}
			}
 		});

 		//alert(filterUrl);

 		//process ajaxrequest
		$.ajax({
			url: "/filterProducts.php",
			type: "POST",
			data: filterUrl,
			dataType: "html",
			//cache: false,
			success: function(responseHtml) {
				var $holder = $('<div/>').html(responseHtml);
				//update filterDiv
				$('#productFilter').html($('#productFilter', $holder).html());
				//update productresultdiv
				$('.content_bb').html($('#productsFound', $holder).html());

				$("#loadingFilter").css('display','none');
				$("#loadingProducts").css('display','none');
				$("div.inhoud").ccs("marginLeft","10px");
				addFormAction();
			}
		});
		return false;
	});
}

function setPageNumberPosition(firstCall) {
	if ($('.pageNr').length != 0) {
		if (firstCall != undefined) {
			currentPageNumberTop = $('.pageNr').position().top;
			currentPageNumberLeft = $('.pageNr').position().left;
		}

		$('.pageNr').css('position', 'absolute');
		$('.pageNr').css('top', currentPageNumberTop + 'px');
		$('.pageNr').css('left', currentPageNumberLeft + 'px');
	}
}

function handleSearch(currentPage, isFirst)
{
	if (isFirst == undefined) {
		$('#loadingFilter').css('opacity', '0.6');
		$('#loadingFilter').fadeIn(100);
		$('#loadingProducts').css('opacity', '0.6');
		$('#loadingProducts').fadeIn(100);
	}
	if (currentPage == undefined) {
		page = 1;
	} else {
		page = currentPage;
	}

	var checkedBoxes = '';
	var checkedDiensten = $('#dienstenFieldset > input:checked');
	checkedDienstenIDs = new Array();
	$.each(checkedDiensten, function (i, val) {
		checkedDienstenIDs[checkedDienstenIDs.length] = val.value;
		checkedBoxes += '&diensten[]=' + val.value;
	});
	var checkedTypes = $('#typesFieldset > input:checked');
	checkedTypesIDs = new Array();
	$.each(checkedTypes, function (i, val) {
		checkedTypesIDs[checkedTypesIDs.length] = val.value;
		checkedBoxes += '&types[]=' + val.value;
	});
	var checkedBranches = $('#branchesFieldset > input:checked');
	checkedBranchesIDs = new Array();
	$.each(checkedBranches, function (i, val) {
		checkedBranchesIDs[checkedBranchesIDs.length] = val.value;
		checkedBoxes += '&branches[]=' + val.value;
	});

	//save checked items to session through ajax
	$.ajax({
		url: "/json/handleFilterSession.php",
		type: "POST",
		data: 'action=saveSession&currentPage=' + page + checkedBoxes,
		dataType: "html",
		cache: false
	});


	//load products in this productgroup

	$.getJSON('/json/projects_'+projectPageID+'.json', false, function(data, textStatus){
		var projectHTML = headerHTML = '';
		var projectCountTotal = projectCountFound = projectsDrawn = 0 ;
		var teller = 1;
		var dienstenFound = 0;
		var typesFound = 0;
		var branchesFound = 0;

		$.each(data.projects, function() {
			//project doorzoeken op diensten tags
			dienstenFound = 0;
			if (checkedDienstenIDs.length > 0) {
				if (this.diensten != undefined) {
					$.each(this.diensten, function (i, val) {
						if (in_array(i, checkedDienstenIDs)) {
							dienstenFound++;
						}
					});
				}
			}

			//diensten gevonden in aangevinkte diensten
			typesFound = 0;
			if (checkedDienstenIDs.length == 0 || dienstenFound == checkedDienstenIDs.length) {
				//doorzoeken van projecten op types
				if (checkedTypesIDs.length > 0) {
					if (this.types != undefined) {
						$.each(this.types, function (i, val) {
							if (in_array(i, checkedTypesIDs)) {
								typesFound++;
							}
						});
					}
				}

				//type gevonden in aangevinkte types
				branchesFound = 0;
				if (checkedTypesIDs.length == 0 || typesFound == checkedTypesIDs.length) {
					//doorzoeken van projecten op branches
					if (checkedBranchesIDs.length > 0) {
						if (this.branches != undefined) {
							$.each(this.branches, function (i, val) {
								if (in_array(i, checkedBranchesIDs)) {
									branchesFound++;
								}
							});
						}
					}

					if (checkedBranchesIDs.length == 0 || branchesFound == checkedBranchesIDs.length) {
						//if (projectCountTotal == 0) {
							if ( (projectCountFound >= ( (page-1) * resultsPerPage) )
								&& (projectCountFound < (page * resultsPerPage) )
							)
							{
								if (documentLocation.length == 1) {
									currentLink = this.info.link_static;
								} else {
									currentLink = this.info.link_dynamic;
								}
								if (isFirst == undefined) {
									className = ' special_link';
								} else {
									className = '';
								}
								var stridSp = getGETVar('id');
								if (stridSp != '')	{
									var onOverLink = 'getReferentiesByID(' + this.info.structuurID + ','+stridSp+')';
									var overID = this.info.structuurID + '_'+stridSp;
								}else{
									var onOverLink = 'getReferentiesByID(' + this.info.structuurID + ')';
									var overID = this.info.structuurID;
								}
								var onOverLink = '';

								//project toevoegen aan het overzicht als > start < start+8
								projectHTML += '<a id="absolute_' + (projectsDrawn+1) + '" class="referentie_link floatLeft' + className + '" href="' + currentLink + '" onmouseover="'+onOverLink+'" title="' + this.info.projectnaam + '" rel="str_' + overID + '">';
								projectHTML += '<img class="referentie_logo" src="/media/168x97/' + this.info.hoofdafbeelding + '" alt="' + this.info.projectnaam + '">';
								projectHTML += '</a>';
								teller++;
								projectsDrawn++;
							}
						//}
						projectCountFound++;
					}
				}
			}
			projectCountTotal++;
		});

		pagingHTML = $.getPaging(page, projectCountFound, resultsPerPage);
		$('.pageNr').html(pagingHTML);


		if (isFirst == undefined) {
			$('.referentie_link').each(function() {
				$(this).css('position', 'absolute');
				$(this).css('overflow', 'hidden');
				$(this).css('left', $(this).position().left + 'px');
				$(this).css('top', $(this).position().top + 'px');
				$(this).animate( { left: '600', top: '360', height: '1px', width: '1px' }, {duration: 350, complete: function() {
					$(this).hide();
					$('.referentieoverzicht').html('<h1>' + data.pageTitle + ' (' + projectCountFound + ' resultaten)</h1>' + projectHTML + '<div class="clear"></div><div class="pageNr">'  + pagingHTML + '</div>');
					//$.getScript('javascript/sifr-config.js');
					initCufon();
					//$('#loadingProducts').fadeOut(200);
					setPageNumberPosition();
					$('.referentie_link').each(function() {
						$(this).show();
						$(this).animate( { height: '97px', width: '166px' }, {duration: 250, complete: function() { $('#loadingFilter').fadeOut(200); }});
					});
					initReferenceHovers();
				}});
			});
			//bij geen resultaten wel weer de checkboxen beschikbaar maken
			if (projectHTML == '') {
				$('#loadingFilter').fadeOut(200);
			//na geen resultaten wel zorgen dat de nu gevonden weergegeven worden
			} else if($('.referentie_link').length == 0) {
				$('.referentieoverzicht').html('<h1>' + data.pageTitle + ' (' + projectCountFound + ' resultaten)</h1><p style="margin:0px; padding:0px; line-height:0px;">&nbsp;</p>' + projectHTML + '<div class="clear"></div><div class="pageNr">'  + pagingHTML + '</div>');
				//$.getScript('javascript/sifr-config.js');
				initCufon();
				initReferenceHovers();
				//$('#loadingProducts').fadeOut(200);
				setPageNumberPosition();
				$('.referentie_link').each(function() {
					$(this).show();
					$(this).animate( { height: '97px', width: '166px' }, {duration: 250, complete: function() { $('#loadingFilter').fadeOut(200); }});
				});
				initReferenceHovers();
			}
		} else {
			$('.referentieoverzicht').html('<h1>' + data.pageTitle + ' (' + projectCountFound + ' resultaten)</h1><p style="margin:0px; padding:0px; line-height:0px;">&nbsp;</p>' + projectHTML + '<div class="clear"></div><div class="pageNr">'  + pagingHTML + '</div>');
			//$.getScript('javascript/sifr-config.js');
			initCufon();
			initReferenceHovers();
			$('#loadingFilter').fadeOut(200);
			//$('#loadingProducts').fadeOut(200);
			setPageNumberPosition();
		}



	});


}


$.getPaging = function(page, productCountFound, resultsPerPage)
{
	page = parseInt(page);
	var prev = page - 1;                            					//previous page is page - 1
	var next= page + 1;                            						//next page is page + 1
	var lastpage = Math.ceil(productCountFound / resultsPerPage);       //lastpage is = total pages / items per page, rounded up.
	var lpm1 = lastpage - 1;                      						//last page minus 1

	var pagingHTML = '';
	if (lastpage > 1) {
		//previous button
		if (page > 1) {
			pagingHTML += '<a href="#" onclick="handleSearch(' + prev + ');" class="page_next">Vorige</a>';
		} else {
			pagingHTML += '<span class="disabled">Vorige</span>';
		}

		//don't break up
		if (lastpage < 7 + (adjacentPages * 2)) {
			for (i = 1; i <= lastpage; i++) {
				if (i == page)	{
		            pagingHTML += '<span class="current">' + i + '</span>';
				} else {
		            pagingHTML += '<a href="#" onclick="handleSearch(' + i + ');">' + i + '</a>';
				}
			}
		} else if (lastpage > 5 + (adjacentPages * 2) ) {//enough pages to hide some
		    //close to beginning; only hide later pages
		    if(page < 1 + (adjacentPages * 2)) {
		        for (i = 1; i < 4 + (adjacentPages * 2); i++) {
		            if (i == page)	{
		                pagingHTML += '<span class="current">' + i + '</span>';
					}else	{
		                pagingHTML += '<a href="#" onclick="handleSearch(' + i + ');">' + i + '</a>';
					}
		        }
		        pagingHTML += '<strong>...</strong>';
		        pagingHTML += '<a href="#" onclick="handleSearch(' + lpm1 + ');">' + lpm1 + '</a>';
		        pagingHTML += '<a href="#" onclick="handleSearch(' + lastpage + ');">' + lastpage + '</a>';
		    } else if(lastpage - (adjacentPages * 2) > page && page > (adjacentPages * 2)) {

	    		//in middle; hide some front and some back
		        pagingHTML += '<a href="#" onclick="handleSearch(1)">1</a>';
		        pagingHTML += '<a href="#" onclick="handleSearch(2)">2</a>';
		        pagingHTML += '<strong>...</strong>';
		        for (i = page - adjacentPages; i <= page + adjacentPages; i++)
		        {
		            if (i == page)	{
		                pagingHTML += '<span class="current">' + i + '</span>';
					}else	{
		                pagingHTML += '<a href="#" onclick="handleSearch(' + i + ')">' + i + '</a>';
					}
		        }
		        pagingHTML += '<strong>...</strong>';
		        pagingHTML += '<a href="#" onclick="handleSearch(' +  lpm1 + ')">' + lpm1 + '</a>';
		        pagingHTML += '<a href="#" onclick="handleSearch(' + lastpage + ')">' + lastpage + '</a>';
		    } else {
	    		//close to end; only hide early pages
		        pagingHTML += '<a href="#" onclick="handleSearch(1)">1</a>';
		        pagingHTML += '<a href="#" onclick="handleSearch(2)">2</a>';
		        pagingHTML += '<strong>...</strong>';
		        for (i = lastpage - (2 + (adjacentPages * 2)); i <= lastpage; i++)
		        {
		            if (i == page)	{
		                pagingHTML += '<span class="current">' + i + '</span>';
					}else	{
		                pagingHTML += '<a href="#" onclick="handleSearch(' + i + ')">' + i + '</a>';
					}
		        }
		    }
		}

		//next button
		if ( parseInt(next) <= parseInt(lastpage)) {
			pagingHTML += '<a href="#" onclick="handleSearch(' + next + ');" class="page_next">Volgende</a>';
		} else {
			pagingHTML += '<span class="disabled">Volgende</span>';
		}
	}
	return pagingHTML;
}
