﻿/**
 * @package Skoda
 * @copyright eFocus (http://www.efocus.nl)
 * @author Klaas Dieleman
 * @since december 2010
 *
 * @require jQuery 1.4.2 (http://www.jquery.com)
 * @require Shadowbox 3.0.3 (http://shadowbox-js.com)
 * @require SWFObject v2.2 (http://code.google.com/p/swfobject)
 * @require FlashDetect 1.0.4, <http://www.featureblend.com>
 * @require jQuery Cookie (http://plugins.jquery.com/project/Cookie)
 * @require /js/global/popuphandler.jquery.js
 * @require /js/global/popinhandler.jquery.js
 * @require /js/global/videoplayer.jquery.js
 * @require /js/global/flashembedder.jquery.js
 * @require /js/global/iframeembedder.jquery.js
 * @require /js/skoda/tabnavigation.class.js
 * @require /js/skoda/etip.class.js
 * @require /js/skoda/carrousel.class.js
 * @require /js/skoda/accordion.class.js
 * @require /js/skoda/googlemap.class.js
 */


jQuery.noConflict();

if(eFocusGlobalHtml.IsPreview == false && eFocusGlobalHtml.IsPageEditor == false && eFocusGlobalHtml.IsPageEditorEditing == false) {
	stripHostname();
}

var addthis_config = {
	ui_language	: "nl",
	ui_cobrand	: "&#352;koda"
};

// write campagneID-cookie if found in url querystring
if(window.location.search != '') {
	var startIndex = location.search.toLowerCase().indexOf('campagneid=');
	if(startIndex != -1) {
		var strCampagneID = location.search.substring(startIndex).split('&')[0].toLowerCase().replace('campagneid=', '');
		var strHostname = location.hostname.split('.')[location.hostname.split('.').length - 2];
		strHostname += '.';
		strHostname += location.hostname.split('.')[location.hostname.split('.').length - 1];
		jQuery.cookie('skoda-CampagneID', strCampagneID, {path: '/', domain: strHostname});
	}
}


/**
 * Executed when DOM structure is loaded
 */
jQuery(window).ready(function() {
	
	jQuery('div.carrousel').each(function(index, item) {
		new Carrousel(jQuery(item).find('ul.carrousel'), jQuery(item).find('a.nextbut'), jQuery(item).find('a.prevbut'), {
			onScroll	: function() {
				jQuery('body > .tempoverlay').remove();
			}
		});
	});

    if (isMobile()) {
        jQuery.each(jQuery("a[rel^='shadowbox']"), function () {
            this.rel = '';
            this.target = '_blank';
        });
    }

	Shadowbox.init({
		onOpen		: function() {
			jQuery('#sb-container').addClass('ims skoda');
			jQuery('#sb-wrapper-inner').css('display', 'none');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onClose		: function() {
			jQuery('#sb-container').removeClass('ims skoda');
			jQuery('#sb-wrapper-inner').css('height', 'auto');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onFinish	: function() {
			jQuery('#sb-wrapper-inner').css('height', 0);
			jQuery('#sb-wrapper-inner').css('display', 'block');
			setLightboxMaxHeight(window);
		},
		displayNav	: false,
		animate		: false,
		troubleElements	: [],
        handleOversize: 'none'
	});

	Shadowbox.setup('a.btn_information', {
		onOpen		: function() {
			jQuery('#sb-container').addClass('ims skoda uitvoering_popin');
			jQuery('#sb-wrapper-inner').css('display', 'none');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onClose		: function() {
			jQuery('#sb-container').removeClass('ims skoda uitvoering_popin');
			jQuery('#sb-wrapper-inner').css('height', 'auto');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onFinish	: function() {
			jQuery('#sb-wrapper-inner').css('height', 0);
			jQuery('#sb-wrapper-inner').css('display', 'block');
			setLightboxMaxHeight(window);
		},
		displayNav	: false,
		animate		: false,
		troubleElements	: []
	});

	setupFlashAlternative(jQuery('div.pushbox, div.teaser, div.dealer_banner'));

	PopinHandler.init();
	PopupHandler.init();
	
	jQuery.each(jQuery("a[rel^='flash']"), function(index, item) {
		new FlashEmbedder(jQuery(item), index);
	});

	jQuery.each(jQuery("a[rel^='videoplayer']"), function(index, item) {
		new VideoPlayer(jQuery(item), {
			playerurl: '/flash/global/player-licensed.swf',
			skinurl: '/flash/global/testsite/jwplayer_skin/dynamisch-skin.xml',
			controlbar		: 'over',
			posterframe		: jQuery(item).find('img').attr('src')
		}, index);
	});
	
	jQuery.each(jQuery("a[rel^='iframe']"), function(index, item) {
		new IframeEmbedder(jQuery(item));
	});
	
	styleFloatingList(jQuery('div.accessories.col3_wrapper ul.accessories li'), 3);
	styleFloatingList(jQuery('div.accessories.col2_wrapper ul.accessories li'), 4);

	makeEqualHeight(jQuery('div.col_footer h3'));
	makeEqualHeight(jQuery('div.nieuwslijst h2.head'));
	makeEqualHeight(jQuery('div.uitvoeringen div.body'));
	makeEqualHeight(jQuery('ul.overview_subpages li'), 3);
	makeEqualHeight(jQuery('div.dealer_actieteasers div.actieteaser'), 3);
	makeEqualHeight(jQuery('div.maintenance_benefits ul li'), 2);
	makeEqualHeight(jQuery('div.accessories.col3_wrapper ul.accessories li'), 3);
	makeEqualHeight(jQuery('div.accessories.col2_wrapper ul.accessories li'), 4);
	jQuery('div.col_right div.teaser div.teaserbg').each(function(index, item) {
		makeEqualHeight(jQuery(item).add(jQuery(item).parent()));
	});
	makeEqualHeight(jQuery('div.col3_wrapper + div.col_right').add(jQuery('div.col3_wrapper + div.col_right').prev()));

	new TabNavigation(jQuery('ul.photo_viewer_thumbnails li'), jQuery('ul.photo_viewer_main_photo li'), {
		onChange: function() {
			jQuery('ul.photo_viewer_thumbnails li a img').css('opacity', 0.6);
			jQuery('ul.photo_viewer_thumbnails li.active a img').css('opacity', 1);
			jQuery('ul.photo_viewer_thumbnails li.active a').blur();
		}
	});
	new TabNavigation(jQuery('div.brandbox_modeltype ul.modeltabs li'), jQuery('div.brandbox_modeltype div.carrousel'));
	new TabNavigation(jQuery('div.trim_options ul.tabswitch li'), jQuery('div.trim_options div.visualsection'), {
		onChange: function(intTab) {
			if(intTab == 2) {
				jQuery('div.trim_options h1').addClass('interior');
			} else {
				jQuery('div.trim_options h1').removeClass('interior');
			}
		}
	});
	new TabNavigation(jQuery('div.trim_options ul.trim_options_switch li'), jQuery('div.trim_options div.trim_options_list'));
	new TabNavigation(jQuery('div.route ul.tabswitch li'), jQuery('div.route ul.openingstijden'));
	jQuery('div.finddealer ul.tabswitch').each(function(index, item) {
		new TabNavigation(jQuery(item).children('li'), jQuery(item).siblings('ul.openingstijden'));
	});
	
	defaultInputText();
	
	initDownloadDropdown();
	
	initExternalLinks();
	
	jQuery('a.flash').each(function(index, item) {
		var strID = jQuery(item).attr('id');
		var strSWF = jQuery(item).attr('href');
		var objFlashvars = stringToObject(jQuery(item).attr('rel'));
		var intWidth = jQuery(item).find('img').width();
		var intHeight = jQuery(item).find('img').height();
		
		insertFlash(strID, strSWF, objFlashvars, intWidth, intHeight);
	});

	customToolTip = new eTip(jQuery('*[title!=""]'), {
		className		: 'tooltip tooltip_top',
		altClassName	: 'dropdown',
		delay			: 300,
		htmlStructure	: '<div><div class="corner_tl" /><div class="corner_tr" /><div class="corner_bl" /><div class="corner_br" /></div>'
	});

	modelAmountTip = new eTip(jQuery('div.uitvoeringen h2.head span.model_amount, div.preferences span.model_amount'), {
		className		: 'tooltip tooltip_top tooltip_preferences',
		altClassName	: 'dropdown',
		delay			: 300,
		customContent	: true,
		offset			: {x: 7, y: 2},
		htmlStructure	: '<div><div class="corner_tl" /><div class="corner_tr" /><div class="corner_bl" /><div class="corner_br" /></div>',
		onShow			: function(elAmount) {
			var strTooltipHtml = jQuery(elAmount).text() + jQuery(elAmount).next('span.preferences_tooltip').html();
			modelAmountTip.tip.find('p.tiptext').html(strTooltipHtml);
		},
		hideOnTipHover	: false
	});

	facetTip = new eTip(jQuery('fieldset.facetgroup label + div.tooltip').prev('label'), {
		className		: 'tooltip tooltip_top tooltip_facets',
		altClassName	: 'dropdown',
		delay			: 300,
		customContent	: true,
		htmlStructure	: '<div><div class="corner_tl" /><div class="corner_tr" /><div class="corner_bl" /><div class="corner_br" /></div>',
		onCreate		: function(objTip) {
			objTip.tip.find('p.tiptext').remove();
			objTip.tip.prepend('<div class="tipcontent" />');
		},
		onShow			: function(elFacetItem) {
			var strTooltipHtml = jQuery(elFacetItem).next('fieldset.facetgroup div.tooltip').html();
			facetTip.tip.find('div.tipcontent').html(strTooltipHtml);
		},
		hideOnTipHover	: false
	});

	motormerkTip = new eTip(jQuery('a.motormerk[href*="MotorMerkTooltip"]'), {
		className		: 'tooltip tooltip_top tooltip_motormerk',
		altClassName	: 'dropdown',
		delay			: 300,
		customContent	: true,
		htmlStructure	: '<div><div class="corner_tl" /><div class="corner_tr" /><div class="corner_bl" /><div class="corner_br" /></div>',
		onCreate		: function(objTip) {
			objTip.tip.find('p.tiptext').remove();
			objTip.tip.prepend('<div class="rte" />');
			objTip.elements.each(function(index, element) {
				jQuery.ajax({
					url			: jQuery(element).attr('href'),
					dataType	: 'html',
					success		: function(data) {
						jQuery(element).data('tipcontent', data);
					}
				});
				jQuery(element).removeAttr('href');
			});
		},
		onShow			: function(elLink) {
			motormerkTip.tip.find('div.rte').html(jQuery(elLink).data('tipcontent'));
		},
		hideOnTipHover	: false
	});
		
	jQuery('fieldset.facetgroup').each(function(index, item) {
		jQuery(item).find('p.hiddenfacets span').text(getChoicesAmount(jQuery(item), true));
		jQuery(item).find('li.more span.amount').text(getChoicesAmount(jQuery(item), false));
		if(getChoicesAmount(jQuery(item), false) < 1) {
			jQuery(item).find('li.more span.selected_text').hide();
		} else {
			jQuery(item).find('li.more span.selected_text').show();
		}
	});

	if(jQuery('#loading_overlay_dummylink').length != 0) {
		window.loadingOverlay = createCustomOverlay(jQuery('#loading_overlay_dummylink'), jQuery('#loading_overlay'), 'loading_overlay');
	}
	
	if(window.location.hash != '') {
	    jQuery('input.hashupdater').val(window.location.hash.substring(1));
		jQuery('input.hashupdater').trigger('change');
	}

	jQuery('a.scrolltoresults').click(function(){
		jQuery('body, html').animate({scrollTop: 0});
		jQuery('div.results_out_of_viewport').fadeOut();
	});

	divideTrimCategoriesList();
	
	new Accordion(jQuery('ul.sitemap_models h2'), jQuery('div.sub'), {
		alwaysHide		: true,
		onActive		: function(elToggler) {
			elToggler.addClass('active');
		},
		onBackground	: function(elToggler) {
			elToggler.removeClass('active');
		},
		show			: -1
	});

	new Accordion(jQuery('ul.faq > li > h3'), jQuery('ul.faq > li div.answer'), {
		alwaysHide		: true,
		onActive		: function(elToggler) {
			elToggler.parent('li').addClass('active');
		},
		onBackground	: function(elToggler) {
			elToggler.parent('li').removeClass('active');
		},
		show			: -1
	});

	if(jQuery('div.route div#map').length != 0) {
		var strAddress = jQuery('div.route span.street').text() + ', ' + jQuery('div.route span.city').text();
		window.map = new GoogleMap(jQuery('div.route div#map'), {
			zoomLevel		: 15,
			addressToShow	: strAddress,
			markerImg		: '/img/skoda/icon_mapmarker.png',
			markerCenter	: {x: 12, y: 24}
		});

		jQuery('div.map_panel a.button').click(function(event) {
			if(!jQuery('div.map_panel input.text').hasClass('default')) {
				map.showDirections(jQuery('#directions'), jQuery('div.map_panel input.text').val());	
			}
		});

		jQuery('div.map_panel input.text').keydown(function(event) {
			if(event.which == 13) {
				event.preventDefault();
				if(jQuery('div.map_panel input.text').val() != '') {
					map.showDirections(jQuery('#directions'), jQuery('div.map_panel input.text').val());
				}
			}
		});

	}

	initSearch(jQuery('div.header fieldset.search'));
    initSearch(jQuery('div.search fieldset.search'));

	// trigger .Net postback on dealersearch enter-key
	jQuery('div.finddealer div.col_left fieldset input.text').keydown(function(evt){
		if (evt.which || evt.keyCode) {
			if ((evt.which == 13) || (evt.keyCode == 13)) {
				__doPostBack('content_0$main_0$btnSubmit','');
				return false;
			}
			return true;
		}
	});

    jQuery('div.brandbox_modeltype ul.colors a, div.trim_options div.visualsection ul.colors a').click(
		function (event) { swapModelVisual(event) }
	);

});


/**
 * Executed when all resources have loaded and page is fully rendered
 */
jQuery(window).load(function() {
	
	// open popin on pageload from querystring parameter
	if(window.location.search != '') {
		var startIndex = location.search.indexOf('openpopin=');
		if(startIndex != -1) {
		    //var url = decodeURIComponent(location.search.substring(startIndex).split('&')[0].replace('openpopin=', ''));
		    var url = decodeURIComponent(location.search.substring(startIndex).replace('openpopin=', ''));
			setTimeout(function(){openPopin(url)}, 0);
		}
	}

    // open mopinion on pageload from querystring parameter
	if(window.location.search != '') {
		var startIndex = location.search.indexOf('mopinion=1');
		if(startIndex != -1) {
            // open mopinion pop-in
            setTimeout(function(){if(document.getElementById('mopinion')){Mgo.blockPop();Mgo.MreloadIframe('3f31fbd4bd2b64abc90341b95fc533bf','','http://www.skoda.nl/',0);Mgo.toggleMscreen(1);}}, 200);
		}
	}

	centerDropdown();
	
	jQuery('ul.photo_gallery').each(function(index, item) {
		createGallery(jQuery(item).find('a'), 'gallery' + String(index + 1));
	});
	
	jQuery('fieldset.facetgroup h2').each(function(index, item) {
		jQuery(item).click(function(event) {
			toggleFacetGroup(jQuery(item));
		});
		jQuery.cookie('facetgroup' + index, null);
	});

	jQuery('ul.facet_list li.more a').each(function(index, item) {
		jQuery(item).click(function() {
			toggleHiddenFacets(jQuery(item));
		});
		jQuery.cookie('facetgroup' + index + '_hiddenfacets', null);
	});

	if(window.blnNoResults) {
		setTimeout(function() {
			var noresult_overlay = createCustomOverlay(jQuery('#noresult_overlay_dummylink'), jQuery('#noresult_overlay'), 'noresult_overlay');
			if(jQuery('#noresult_overlay_dummylink').length != 0) Shadowbox.open(noresult_overlay)
		}, 0);
	}

	if (jQuery('div.tech_specs_holder').length != 0) initTechSpecsTable();

	initOverlays(jQuery('div.trim_options ul.hotspots li'), true);

	if (jQuery('.trim_options_list').length != 0) {
		var hiddenTabPanel;
		jQuery('.trim_options_list').each(function(intIndex, elDiv){
			if (jQuery(elDiv).css('display') == 'none') {
				hiddenTabPanel = elDiv;
				jQuery(hiddenTabPanel).css({
					'display'	: 'block',
					'visibility': 'hidden',
					'position'	: 'absolute'
				});
			}
		});

		initOverlays(jQuery('div.trim_options ul.items li.overlay'), true);

		jQuery(hiddenTabPanel).css({
			'display'	: 'none',
			'visibility': 'visible',
			'position'	: 'static'
		});
	}

	initLijstUitvoeringen();

	preparePrintTechSpecsTable();
});


/**
 * centers dropdown of the subnavigation underneath it's link
 *
 * @author Rou-hun Fan <lowen{AT}efocus.nl>
 * @since 1.0, 22 dec 2010
 */
function centerDropdown() {
	jQuery('ul.subnav div.dropdown').each(function(index, elDropdown) {
		jQuery(elDropdown).css('left', (jQuery(elDropdown).width() - jQuery(elDropdown).prev('a').width()) / -2)
	});
}


/**
 * equals the height of the elements in an array
 *
 * @author Rou-hun Fan <lowen{AT}efocus.nl>
 * @author Klaas Dieleman
 * @since 1.1, dec 2010
 * @param array - elements to equalize
 * @param integer - optional amount of columns per row
 */
function makeEqualHeight(arrElements, intColumns) {

	var intMaxheight = 0;
	var arrCurrentRow = [];

	jQuery(arrElements).each(function(index, item) {
		jQuery(item).css('height', 'auto');
		var intHeight = jQuery(item).outerHeight();
		if (intHeight > intMaxheight) {
			intMaxheight = jQuery(item).outerHeight();
		}
		arrCurrentRow.push(item);

		if((index+1)%intColumns == 0) {
			var intNewHeight = intMaxheight;
			intNewHeight -= parseInt(jQuery(item).css('padding-top'));
			intNewHeight -= parseInt(jQuery(item).css('padding-bottom'));

			jQuery(arrCurrentRow).css('min-height', intNewHeight);
			intMaxheight = 0;
			arrCurrentRow = [];
		}
	});
	
	jQuery(arrCurrentRow).each(function(index, item) {
		var intNewHeight = intMaxheight;
		intNewHeight -= parseInt(jQuery(item).css('padding-top'));
		intNewHeight -= parseInt(jQuery(item).css('padding-bottom'));

		jQuery(item).css('min-height', intNewHeight);
	});
	
}


/**
 * creates and shows notification about no Flash player installed
 *
 * @param jQuery object - flashcontainer(s)
 */
function setupFlashAlternative(arrContainers) {

	arrContainers.each(function(index, elContainer) {
		if (FlashDetect.major < 9) {
			if(jQuery(elContainer).find("a[rel^='videoplayer'], a[rel^='flash'], a[class^='flash']").length !=0) {
				if(jQuery.cookie('disableFlashAlert') != 'true') {
					var elFlashAlert = jQuery('<div class="flash_alert"></div>');
					elFlashAlert.append('<p>Om de &#352;koda website optimaal te kunnen bekijken is Adobe Flash Player nodig. <a href="http://get.adobe.com/flashplayer">Download</a></p>');	
					elFlashAlert.append('<a class="close_small" title="Deze melding niet meer tonen">Deze melding niet meer tonen</a>');
					elFlashAlert.appendTo(elContainer);
				}
				
				if(jQuery(elContainer).find('a.alt_link').length != 0) {
					var elAltLink = jQuery('<div class="alt_link"><span class="link" /></div>');
					elAltLink.find('span.link').append(jQuery(elContainer).find('a.alt_link'));
					elAltLink.find('span.link').append(jQuery('<span class="rightcap" />'));
					elAltLink.appendTo(elContainer);
				}
			}
		} else {
			jQuery(elContainer).find('a.alt_link').remove();
		}
	});
	
	jQuery('div.flash_alert a.close_small').click(function() {
	
		jQuery('div.flash_alert').remove();
		jQuery.cookie('disableFlashAlert', 'true');
		
	});
	
}


/**
 * toggles default text in text inputfields
 *
 * @param array - optional array om DOM elements to affect
 */
function defaultInputText(arrInputs) {
    var inputfields = arrInputs || jQuery('.defaultText');
	
	inputfields.each(function(index, item) {
		item.defaultText = jQuery(item).attr('value');
		jQuery(item).addClass('default');
		
		jQuery(item).bind({
			'focus': function() {
				if (jQuery(item).attr('value') == item.defaultText) jQuery(item).attr('value', '');
				jQuery(item).removeClass('default');
			},
			'blur': function() {
				if (jQuery(item).attr('value') == '') {
					jQuery(item).attr('value', item.defaultText);
					jQuery(item).addClass('default');
				}
			}
		});
	});
}


/**
 * sets domain to hostname only, for cross-frame communication
 */
function stripHostname() {
	var hostname = location.hostname.split('.')[location.hostname.split('.').length - 2];
	hostname += '.';
	hostname += location.hostname.split('.')[location.hostname.split('.').length - 1];

	document.domain = hostname;
}


/**
 * sets height of iframe
 *
 * @param integer target height in pixels
 */
function fitFrameHeight(height) {
	jQuery('#iframe').css('height', height);
}


/**
 * sets up lightbox gallery
 */
function createGallery(arrLinks, strGalleryName) {
	var strGalleryName = strGalleryName || 'gallery';
	
	arrLinks.each(function(index, item) {
		var strPlayer, strType;
		
		if(jQuery(item).hasClass('photo')) {
			strPlayer = 'img'
		} else if (jQuery(item).hasClass('video')) {
			strPlayer = 'flv';
			strType = 'video';
		} else if (jQuery(item).hasClass('youtube')) {
			strPlayer = 'flv';
			strType = 'youtube';
		} else {
			strPlayer = 'unknown'
		}
		
		if(strPlayer != 'unknown') {
			Shadowbox.setup(item, {
				gallery			: strGalleryName,
				autoplayMovies	: true,
				overlayOpacity	: 0.8,
				player			: strPlayer,
				handleOversize	: 'none',
				width			: 650,
				flashVars		: {
					'type'			: strType,
					'stretching'	: 'fill',
					'skin'			: encodeURIComponent('/flash/global/testsite/jwplayer_skin/dynamisch-skin.xml?fullscreenbutton=true&timesliderprogress=true&mutebutton=true'),
					'controlbar'	: 'over',
					'allowfullscreen'	: true
				},
				flashParams		: {
					'wmode'				: 'transparent',
					'allowfullscreen'	: true
				},
				onOpen			: function(item) {
					customToolTip.hideTip();
					setupShadowbox();
					checkNav();
					setItemContent(item);
				},
				onChange		: function(item) {
					checkNav();
					setItemContent(item);
					customToolTip.hideTip();
				},
				onClose			: function() {
					resetShadowbox();
					customToolTip.hideTip();
				},
				onFinish		: function(item) {
					customToolTip.hideTip();
					jQuery('#sb-caption').css('visibility', 'visible');
					jQuery('<div class="corner_lt" />').appendTo('#sb-body-inner');
					jQuery('<div class="corner_rt" />').appendTo('#sb-body-inner');
					jQuery('<div class="corner_lb" />').appendTo('#sb-body-inner');
					jQuery('<div class="corner_rb" />').appendTo('#sb-body-inner');
				}
			});
		}
	});
	
	/**
	 * set custom styles and elements on shadowbox
	 */
	var setupShadowbox = function() {
		jQuery('#sb-container').addClass('gallery_lightbox');
		
		jQuery('<a class="previous button"><span class="arrow arrow_left" />Vorige<span class="rightcap" /></a>').appendTo('#sb-wrapper-inner');
		jQuery('<a class="next button"><span class="arrow arrow_right" />Volgende<span class="rightcap" /></a>').appendTo('#sb-wrapper-inner');
		jQuery('<a class="close" title="Sluiten">Sluiten</a>').appendTo('#sb-wrapper');
		
		jQuery('#sb-wrapper a.close').click(Shadowbox.close);
		jQuery('#sb-wrapper a.previous').click(Shadowbox.previous);
		jQuery('#sb-wrapper a.next').click(Shadowbox.next);
		
		jQuery('<div id="sb-caption"></div>').appendTo('#sb-body');
		jQuery('<h1></h1>').appendTo('#sb-caption');
		jQuery('<div class="description"></div>').appendTo('#sb-caption');
		jQuery('a.proefrit_link').clone().appendTo('#sb-caption');
		jQuery('<a class="share_link button button_green">Link doorsturen<span class="rightcap" /></a>').appendTo('#sb-caption');

		// close current shadowbox and open new one from 'proefrit'-link
		jQuery('#sb-caption a.proefrit_link').click(function(event) {
			event.preventDefault();
			var intKey = jQuery('div.photo_gallery_holder a.proefrit_link')[0].shadowboxCacheKey;
			Shadowbox.close();
			setTimeout(
				function(){ Shadowbox.open(Shadowbox.cache[intKey]) },
				Shadowbox.options.fadeDuration * 1000 + 300
			);
		});
		
		// close current shadowbox and open e-mail-addthis-link
		jQuery('#sb-caption a.share_link').click(function(event) {
			event.preventDefault();
			window.email_lightbox_open = true;
			addthis.addEventListener('addthis.menu.close', function(event) {
				if(event.pane = 'email') {
					window.email_lightbox_open = false;
					location.hash = '';
				}
			});
			jQuery('div.footer a.addthis_button_email').trigger('click');
			Shadowbox.close();
		});
	};
	
	/**
	 * remove custom styles and elements from shadowbox
	 * to restore shadowbox in its original state
	 */
	var resetShadowbox = function() {
		if(!window.email_lightbox_open) location.hash = '';
		jQuery('#sb-caption').remove();
		jQuery('#sb-wrapper a.close').remove();
		jQuery('#sb-wrapper a.previous').remove();
		jQuery('#sb-wrapper a.next').remove();
		jQuery('#sb-container').removeClass('gallery_lightbox');
	};
	
	/**
	 * update caption of gallery item in shadowbox
	 */
	var setItemContent = function(item) {
		jQuery('#sb-caption').css('visibility', 'hidden');
		jQuery('#sb-caption h1').text(jQuery(item.link).data('title'));
		jQuery('#sb-caption div.description').html(jQuery(item.link).parents('li').find('.description').clone());
		
		location.hash = strGalleryName + '=' + String(Shadowbox.current + 1);
		
		customToolTip.updateElements(jQuery('a'));
	};
	
	/**
	 * enable/disable navigation buttons if necessary
	 */
	var checkNav = function() {
		if(Shadowbox.current <= 0) {
			jQuery('#sb-wrapper a.previous').hide();
		} else {
			jQuery('#sb-wrapper a.previous').show();
		}
		
		if(Shadowbox.current >= Shadowbox.gallery.length - 1) {
			jQuery('#sb-wrapper a.next').hide();
		} else {
			jQuery('#sb-wrapper a.next').show();
		}
	}
	
	// open Shadowbox if hash found in URL
	if(location.hash.indexOf(strGalleryName) != -1) {
		var intGalleryIndex = parseInt(location.hash.replace(strGalleryName, '').replace('#', '').replace('=', '')) - 1;
		if(!isNaN(intGalleryIndex)) {
			setTimeout(function(){Shadowbox.open(arrLinks[intGalleryIndex])}, 0);
		}
	}
}


/**
 * Sets up dropdown of maintenance prices with download buttons
 */
function initDownloadDropdown() {
	if(jQuery('div.maintenance_prices option').length != jQuery('div.maintenance_prices a.button').length) return false;
	
	var options = jQuery('div.maintenance_prices option');
	var buttons = jQuery('div.maintenance_prices a.button');
	
	buttons.not(buttons.first()).hide();
	
	jQuery('div.maintenance_prices select').change(function(){
		var index = options.index(jQuery(options + ':selected'));
		buttons.not(buttons[index]).hide();
		jQuery(buttons[index]).show();
	});
}


/**
 * Opens links with rel=external attribute in a new window/tab without the deprecated target attribute
 */
function initExternalLinks() {
	jQuery('a[rel~=external]').click(function(e) {
		e.preventDefault();
		window.open(jQuery(this).attr('href'));
	});
}


/**
 * Inserts swf object into DOM if flash player >= 9 is installed
 * 
 * @since 1.0, 23 apr 2010
 * @param string ID-attribute of HTML placeholder
 * @param string url of SWF file
 * @param object flashvars to pass to SWF file
 * @param integer width in pixels
 * @param integer height in pixels
 */
function insertFlash(strId, strSwf, objFlashvars, intWidth, intHeight) {
	
	if(FlashDetect.major >= 9) {
		var params = {
			'allowfullscreen'	: true,
			'allowscriptaccess'	: 'always',
			'wmode'				: 'transparent',
			'menu'				: false,
			'scale'				: 'ExactFit'
		};

		var attributes = {
			'id'	: strId,
			'name'  : strId
		};
		
		swfobject.embedSWF(strSwf, strId, intWidth, intHeight, '9.0.0', false, objFlashvars, params, attributes);
	
	} else {
		jQuery('#' + strId).children().first().unwrap();
	}
    
}


/**
 * parses a string with ; and = delimiters to an object
 *
 * @param string - string to parse
 */
function stringToObject(strString) {
	var objObject = {};
	
	var arrKeys = strString.split(';');
	jQuery(arrKeys).each(function(index, item) {
		var arrPair = item.split('=');
		objObject[arrPair[0]] = arrPair[1];
	});
	
	return objObject;
}


/**
 * adds 'right'- and 'bottom'-classes to right and bottom elements in a floating list
 *
 * @param array - floating listelements 
 * @param integer - amount of columns in the list
 */
function styleFloatingList(arrElements, intColumns) {
	var intLastRowCount = arrElements.length % intColumns;
	if(intLastRowCount == 0) intLastRowCount = intColumns;
	
	for(var n = arrElements.length - 1 ; n >= arrElements.length - intLastRowCount ; n --) {
		jQuery(arrElements[n]).addClass('bottom');
	}
	
	arrElements.filter(':nth-child(' + intColumns + 'n)').addClass('right');
}


/**
 * swaps large visual to match clicked color
 *
 * @param event - jQuery event which called this function 
 */
function swapModelVisual(event) {
	event.preventDefault();

	var elLink = jQuery(event.target);
	var elImage = elLink.parents('div.brandbox_modeltype, div.visualsection').find('img.visual');
	
	elLink.blur();
	elLink.parents('ul').children('li').removeClass('active');
	elLink.parent('li').addClass('active');
	elImage.attr('src', elLink.attr('href'));
}


/**
 * sets up Shadowbox for html overlay on Models-page
 *
 * @param element - link element to connect Shadowbox to
 * @param element - div element with contents for Shadowbox
 * @param string - classname for Shadowbox-container
 *
 * @return object - Shadowbox object
 */
function createCustomOverlay(elLink, elContents, strClassname) {
	var objShadowbox = Shadowbox.makeObject(jQuery(elLink)[0], {
		animate			: false,
		displayNav		: false,
		enableKeys		: false,
		modal			: true,
		fadeDuration	: 0,
		overlayColor	: '#fff',
		overlayOpacity	: 0.8,
		width			: jQuery(elContents).width(),
		height			: jQuery(elContents).height(),
		onOpen			: function() {
			jQuery('#sb-container').addClass(strClassname);
		},
		onClose			: function() {
			jQuery('#sb-container').removeClass(strClassname);
		},
		onFinish		: function() {}
	});

	objShadowbox.player = 'html';
	objShadowbox.content = jQuery(elContents).html();

	return objShadowbox;
}


/**
 * opens/closes Facet Group with slide animation
 *
 * @param element - h2 element which was clicked
 */
function toggleFacetGroup(elToggler) {
	elToggler.parent('fieldset.facetgroup').toggleClass('closedfacetgroup');

	var i = jQuery.inArray(elToggler[0], jQuery('fieldset.facetgroup h2'));
	if(elToggler.parent('fieldset.facetgroup').hasClass('closedfacetgroup')) {
		jQuery.cookie('facetgroup' + i, 'closed');
	} else {
		jQuery.cookie('facetgroup' + i, null);
	}
	
	if(getChoicesAmount(jQuery(elToggler.parent('fieldset.facetgroup')), true) < 1) {
		elToggler.siblings('p.hiddenfacets').addClass('hidden');
	} else {
		elToggler.siblings('p.hiddenfacets').removeClass('hidden');
	}

	elToggler.siblings('div.collapsible').slideToggle('fast');
	elToggler.siblings('p.hiddenfacets').slideToggle('fast');
}


/**
 * opens/closes hidden Facets within Facet Group with slide animation
 *
 * @param element - 'more'-link element which was clicked
 */
function toggleHiddenFacets(elToggler) {
	elToggler.toggleClass('less');

	var i = jQuery.inArray(elToggler[0], jQuery('fieldset.facetgroup li.more a'));
	if(elToggler.hasClass('less')) {
		elToggler.find('span.more_text').text('Minder');
		jQuery.cookie('facetgroup' + i + '_hiddenfacets', 'open');
	} else {
		elToggler.find('span.more_text').text('Meer');
		jQuery.cookie('facetgroup' + i + '_hiddenfacets', null);
	}
	
	elToggler.parent('li').siblings('li.standaardVerborgen').slideToggle('fast');
}


/**
 * gets amount of checked/selected inputs/dropdowns within Facet Group
 *
 * @param element - fieldset element which is the Facet Group
 * @param boolean - count all elements (true) or only the 'default-hidden' ones (false/default)
 *
 * @return integer - number of checked/selected inputs/dropdowns
 */
function getChoicesAmount(elFacetgroup, returnAll) {
	var intAmount = 0;

	elFacetgroup.find('ul.facet_list input[type=checkbox]').each(function(index, item) {
		if(jQuery(item).attr('checked') == true) {
			if(jQuery(item).parents('ul.facet_list li').hasClass('standaardVerborgen') || returnAll) intAmount ++;
		}
	});

	elFacetgroup.find('ul.facet_list select').each(function(index, item) {
		if(jQuery(item).val() != '') {
			if(jQuery(item).parents('ul.facet_list li').hasClass('standaardVerborgen') || returnAll) intAmount ++;
		}
	});

	return intAmount;
}


/**
 * fired when facet selection update via AJAX starts
 * shows overlay window
 */
function facetUpdateStart() {
	jQuery('div.results_out_of_viewport').hide()
	Shadowbox.close();
	facetTip.hideTip();
	customToolTip.hideTip();
	
	Shadowbox.open(window.loadingOverlay);
	jQuery('div.loading_overlay_inner span.amount').addClass('amount_anim');
}


/**
 * fired when facet selection update via AJAX finishes
 * re-inits state of facetgroups and hidden facets according to previous state,
 * updates result amount in overlay window and in header,
 * closes overlay with a delay and writes unique string in url-hash,
 * opens another overlay if zero results
 *
 * @param integer - amount of returned results
 * @param string - unique string to put in hash-portion of addressbar (for later retrieval of exact selection-state)
 */
function facetUpdateEnd(intResultAmount, strResultFilterHash) {
	jQuery('fieldset.facetgroup h2').each(function(index, item) {
		jQuery(item).click(function(event) {
			toggleFacetGroup(jQuery(item));
		});
		if(jQuery.cookie('facetgroup' + index) == 'closed') toggleFacetGroup(jQuery(item));
	});

	jQuery('ul.facet_list li.more a').each(function(index, item) {
		jQuery(item).click(function() {
			toggleHiddenFacets(jQuery(item));
		});
		if(jQuery.cookie('facetgroup' + index + '_hiddenfacets') == 'open') toggleHiddenFacets(jQuery(item));
	});
	
	jQuery('fieldset.facetgroup').each(function(index, item) {
		jQuery(item).find('p.hiddenfacets span').text(getChoicesAmount(jQuery(item), true));
		jQuery(item).find('li.more span.amount').text(getChoicesAmount(jQuery(item), false));
		if(getChoicesAmount(jQuery(item), false) < 1) {
			jQuery(item).find('li.more span.selected_text').hide();
		} else {
			jQuery(item).find('li.more span.selected_text').show();
		}
	});

	customToolTip.updateElements(jQuery('*[title!=""]'));

	jQuery('div.loading_overlay_inner span.amount').removeClass('amount_anim');
	jQuery('div.loading_overlay_inner span.amount').text(intResultAmount);
	
	jQuery('span.model_amount_total').text(intResultAmount);

	facetTip.updateElements(jQuery('fieldset.facetgroup label + div.tooltip').prev('label'));
	
	setTimeout(function () {
		window.location.hash = strResultFilterHash;

		Shadowbox.close();

	    if (intResultAmount == 0) {
	        var noresult_overlay = createCustomOverlay(jQuery('#noresult_overlay_dummylink'), jQuery('#noresult_overlay'), 'noresult_overlay');
			Shadowbox.open(noresult_overlay);
	    } else {
			if(isResultsVisible() == false) jQuery('div.results_out_of_viewport').show();
		}
	}, 1000);
}


/**
 * fired when 'uitvoeringen' retrieval via AJAX starts
 *
 * @param element - link element which initiated the AJAX-call
 */
function modeltypeUpdateStart(elLink) {
   jQuery(elLink).find('span.loader').show();
}


/**
 * fired when 'uitvoeringen' retrieval via AJAX finishes
 *
 * @param string - html id of link element which initiated the AJAX-call
 */
function modeltypeUpdateEnd(strLinkId) {
	
	customToolTip.updateElements(jQuery('*[title!=""]'));
	
	motormerkTip.updateElements(jQuery('a.motormerk[href*="MotorMerkTooltip"]'));
	jQuery('a.motormerk[href*="MotorMerkTooltip"]').each(function(index, element) {
		jQuery.ajax({
			url			: jQuery(element).attr('href'),
			dataType	: 'html',
			success		: function(data) {
				jQuery(element).data('tipcontent', data);
			}
		});
		jQuery(element).removeAttr('href');
	});
	
	Shadowbox.setup('a.btn_information', {
		onOpen		: function() {
			jQuery('#sb-container').addClass('ims skoda uitvoering_popin');
			jQuery('#sb-wrapper-inner').css('display', 'none');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onClose		: function() {
			jQuery('#sb-container').removeClass('ims skoda uitvoering_popin');
			jQuery('#sb-wrapper-inner').css('height', 'auto');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onFinish	: function() {
			jQuery('#sb-wrapper-inner').css('height', 0);
			jQuery('#sb-wrapper-inner').css('display', 'block');
			setLightboxMaxHeight(window);
		},
		displayNav	: false,
		animate		: false,
		troubleElements	: []
	});
	
	var elResultspanel = jQuery('#' + strLinkId).parents('div.model_type').find('div.model_versions');
	jQuery('#' + strLinkId).find('span.loader').hide();
	
	elResultspanel.hide();
	elResultspanel.slideDown(400, function(){
		jQuery('#' + strLinkId).parent('div.model_type_footer').addClass('open');
	});
}


/**
 * fired when 'uitvoeringen'-table sorting via AJAX finishes
 */
function modeltypeSortEnd() {
	customToolTip.updateElements(jQuery('*[title!=""]'));
	
	motormerkTip.updateElements(jQuery('a.motormerk[href*="MotorMerkTooltip"]'));
	jQuery('a.motormerk[href*="MotorMerkTooltip"]').each(function(index, element) {
		jQuery.ajax({
			url			: jQuery(element).attr('href'),
			dataType	: 'html',
			success		: function(data) {
				jQuery(element).data('tipcontent', data);
			}
		});
		jQuery(element).removeAttr('href');
	});

	Shadowbox.setup('a.btn_information', {
		onOpen		: function() {
			jQuery('#sb-container').addClass('ims skoda uitvoering_popin');
			jQuery('#sb-wrapper-inner').css('display', 'none');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onClose		: function() {
			jQuery('#sb-container').removeClass('ims skoda uitvoering_popin');
			jQuery('#sb-wrapper-inner').css('height', 'auto');
			customToolTip.hideTip();
			motormerkTip.hideTip();
			modelAmountTip.hideTip();
			facetTip.hideTip();
			jQuery('div.tempoverlay').remove();
		},
		onFinish	: function() {
			jQuery('#sb-wrapper-inner').css('height', 0);
			jQuery('#sb-wrapper-inner').css('display', 'block');
			setLightboxMaxHeight(window);
		},
		displayNav	: false,
		animate		: false,
		troubleElements	: []
	});
}


/**
 * Tweaks the table containing technical specifications
 *
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @since jan 2011
 */
function initTechSpecsTable() {

	if (jQuery('.print_pdf').length > 0) return;
	
	// Calculate table width based on the number of columns
	var intCellWidth = 210;
	jQuery('table.tech_specs_data').css('width', jQuery('table.tech_specs_data tr:first > th').length * intCellWidth);

	// Duplicate data table to be used as labels column
	jQuery('div.tech_specs_holder div.viewport_labels').append(jQuery('table.tech_specs_data').clone().removeClass('tech_specs_data').addClass('tech_specs_labels'));
	
	// Implement the carrousel interaction based on a class
	new Carrousel(
		jQuery('div.tech_specs_holder table.tech_specs_data'),
		jQuery('div.tech_specs_holder a.nextbut'),
		jQuery('div.tech_specs_holder a.prevbut'),
		{
			slides: jQuery('div.tech_specs_holder table.tech_specs_data tr:first > th')
		}
	);

	// Center the arrow in the buttons within the browserviewport:
	var intButtonHeight = jQuery('.nextbut').height();
	var intButtonOffset = Math.round(jQuery('.nextbut').offset().top);
	var intVisibleButtonHeight = 0;
	var intArrowPosLimitPercentage = 5;

	var calculateArrowPosition = function() {
		var intButtonPosition = jQuery(window).scrollTop() - intButtonOffset;

		if ((intButtonOffset + intButtonHeight) - jQuery(window).scrollTop() < jQuery(window).height()) {
			intVisibleButtonHeight = (intButtonOffset + intButtonHeight) - jQuery(window).scrollTop();
		} else if (intButtonPosition < 0) {
			intVisibleButtonHeight = jQuery(window).height() + intButtonPosition;
		} else {
			intVisibleButtonHeight = jQuery(window).height();
		}

		var intArrowTopPosition = (intButtonPosition > 0) ? intButtonPosition + (intVisibleButtonHeight / 2) : intVisibleButtonHeight / 2;
		var intArrowTopPercentage = (intArrowTopPosition / intButtonHeight) * 100;

		if (intArrowTopPercentage < intArrowPosLimitPercentage) {
			intArrowTopPercentage = intArrowPosLimitPercentage;
		} else if (intArrowTopPercentage > 100 - intArrowPosLimitPercentage) {
			intArrowTopPercentage = 100 - intArrowPosLimitPercentage;
		}

		jQuery('.prevbut .arrow, .nextbut .arrow').css('top', intArrowTopPercentage + '%');
	}
	calculateArrowPosition();
	
	jQuery(window).scroll(function(){
		calculateArrowPosition();
	});

	jQuery('table.tech_specs_data th, table.tech_specs_data td').not(':first-child').click(function(event){
		var index = jQuery(event.currentTarget).index() + 1;
		jQuery('table.tech_specs_data td').not('td:nth-child(' + index + ')').removeClass('highlight');
		jQuery('table.tech_specs_data td').filter('td:nth-child(' + index + ')').toggleClass('highlight');
	});
}

/**
 * Duplicates the table containing technical specifications in several tables to fit them on a portait A4-sheet for printing.
 *
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @since aug 2011
 */
function preparePrintTechSpecsTable() {
	var modelsPerTable = 3;
	var modelsTotal = jQuery('table.tech_specs_data').find('tr:first').children(':not(:first)').length;
	var tablesTotal = Math.ceil(modelsTotal / modelsPerTable);
	var modelsMissingInLastTable = modelsPerTable - modelsTotal % modelsPerTable;
	var emptyCell = '<td>&#160;</td>';

	// Hide the original table for print only when JavaScript is enabled:
	jQuery('table.tech_specs_data').addClass('noprint');

	// Clone the existing table and prepare it for the print version:
	var techSpecsTablePrint = jQuery(jQuery('table.tech_specs_data')[0]).clone().removeClass('noprint').addClass('print').removeAttr('style');

	// Add cells to the rows so the total number is exactly dividable trough the number of models per table:
	jQuery(techSpecsTablePrint).find('tr').each(function(indexRow, elRow){
		var arrTableCells = jQuery(this).children();
		jQuery(arrTableCells).each(function(index){
			if (jQuery(arrTableCells).length - 1 == index) {
				for (var m=0; m<modelsMissingInLastTable; m++) {
					jQuery(elRow).append(emptyCell);
				}
			}
		});
	});

	// Create the printtables with the first column of labels and several other columns:
	for (var t=0; t<tablesTotal; t++) {
		var modelPosition = t * modelsPerTable;
		var techSpecsTable = jQuery(techSpecsTablePrint).clone();
		
		// Loop through the printtables tot determine which cells to show:
		jQuery(techSpecsTable).find('tr').each(function(indexRow){
			var arrTableCells = jQuery(this).children();
			jQuery(arrTableCells).each(function(index){
				// Remove cells when not the first or models within the current range:
				if ( index != 0 && ((index <= modelPosition) || (index > (modelPosition + modelsPerTable))) ) {
					jQuery(this).remove();
				}
			});
		});

		jQuery('div.tech_specs_holder').append(techSpecsTable);
	}
}

/**
 * Divides the trim categories list in two seperate lists.
 *
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @since jan 2011
 */
function divideTrimCategoriesList() {
	var elCategories = jQuery('.trim_options_list:first ul.categories');
	var arrCats = jQuery(elCategories).children('li');
	var arrCatItems = jQuery('.trim_options_list:first ul.categories ul.items > li');
	var intCatItemsHalf = jQuery(arrCatItems[Math.ceil(jQuery(arrCatItems).length / 2)]);
	var intCatFirstColLastIndex = 0;
	
	jQuery(arrCats).each(function(intIndex, elCatListItem){
		if (jQuery(elCatListItem)[0] == jQuery(intCatItemsHalf).parents('li')[0]) intCatFirstColLastIndex = intIndex;
	});

	var elCategoriesSecond = jQuery(elCategories).clone();

	jQuery(elCategoriesSecond).children().each(function(intIndex, elCatListItem){
		if (intIndex <= intCatFirstColLastIndex) {
			jQuery(elCatListItem).remove();
		} else {
			jQuery(jQuery(arrCats)[intIndex]).remove();
		}
	});

	elCategories.after(elCategoriesSecond);
}


/**
 * enables visual toggling of overlay/tooltip divs,
 * optionally vertically centers overlay
 *
 * @param array - jQuery object of items containing an overlay div
 * @param boolean - centers overlay vertically if true
 */
function initOverlays(arrItems, blnCenter) {
	arrItems.each(function(index, item) {
		if(jQuery(item).find('div.overlay').length != 0) {
			
			var elOverlay = jQuery(item).find('div.overlay');
			
			if(blnCenter == true) elOverlay.css('margin-top', - elOverlay.height() / 2);

			elOverlay.find('a.close').click(function(event) {
				event.stopPropagation();
				jQuery('body > .tempoverlay').remove();
				customToolTip.hideTip();
			});

			jQuery(item).click(function() {
				customToolTip.hideTip();

				jQuery('body > .tempoverlay').remove();

				var tempOverlay = elOverlay.clone(true).addClass('tempoverlay');
				tempOverlay.appendTo('body');
				
				tempOverlay.css({
					'visibility': 'visible',
					'margin'	: 0,
					'position'	: 'absolute',
					'z-index'	: 999,
					'left'		: elOverlay.offset().left,
					'top'		: elOverlay.offset().top,
					'right'		: 'auto',
					'bottom'	: 'auto'
				});
			});

		}
	});

}


/**
 * checks whether the model results are visible within the browserwindow
 *
 * @return boolean
 */
function isResultsVisible() {
	var blnResultsVisible;

	if(jQuery(window).scrollTop() > jQuery('div.col_right_models').offset().top + jQuery('div.col_right_models').height()) {
		blnResultsVisible = false;
	} else {
		blnResultsVisible = true;
	}

	return blnResultsVisible;
}


/**
 * positions overlays of highlights and initializes slide transition when navigating to an uitvoering
 */
function initLijstUitvoeringen() {
	jQuery('div.uitvoeringen div.overlay_uitvoering').each(function(index, item) {
		jQuery(item).css('bottom', jQuery(item).parent('li').innerHeight() - 5);
	});

	jQuery('div.uitvoeringen h2.head a, div.uitvoeringen a.open_uitvoering').click(function(event) {
		if(jQuery(event.currentTarget).parents('ul.carrousel li').find('div.body').length != 0) {
			event.preventDefault();
			event.currentTarget.blur();

			jQuery(event.currentTarget).parents('ul.carrousel').find('div.body').slideUp(400, function() {
				window.location = jQuery(event.currentTarget).attr('href');
			});

		}
	});

	makeEqualHeight(jQuery('div.uitvoeringen div.body'));

	initOverlays(jQuery('div.uitvoeringen ul.highlightlist > li'));
}


/**
 * re-initializes uitvoeringen-list after asynchronous content-change
 */
function updateLijstUitvoeringen() {
	modelAmountTip.updateElements(jQuery('div.uitvoeringen h2.head span.model_amount'));

	new Carrousel(jQuery('div.uitvoeringen ul.carrousel'), jQuery('div.uitvoeringen a.nextbut'), jQuery('div.uitvoeringen a.prevbut'), {
		onScroll	: function() {
			jQuery('body > .tempoverlay').remove();
		}
	});

	initLijstUitvoeringen();
}


/**
 * setLightboxMaxHeight
 *
 * Animates the height of the lightbox depending on the available content or viewport size.
 *
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @author Klaas Dieleman
 * @since 1.2, jan, 2011
 * @return void
 */
function setLightboxMaxHeight(objParentWindow) {
	if (!objParentWindow) return false;
	
	var elParent = objParentWindow.document;
	var elLightboxWrapper = elParent.getElementById('sb-wrapper');
	if (!elLightboxWrapper) return false;
	
	var elLightboxTitle = elParent.getElementById('sb-title');
	var elLightboxWrapperInner = elParent.getElementById('sb-wrapper-inner');
	var elLightboxInfo = elParent.getElementById('sb-info');
	
	var intMinimalHeight = 500;
	var intContentHeight = jQuery('body').height();
	var intViewportHeight = jQuery(objParentWindow).height() - ( parseInt(jQuery(elLightboxWrapper).position().top) + parseInt(jQuery(elLightboxTitle).css('height')) + (parseInt(jQuery(elLightboxInfo).css('height')) - 22) );
	
	var intHeight = (intContentHeight < intMinimalHeight) ? intMinimalHeight : intContentHeight;
	intHeight = (intHeight > intViewportHeight) ? intViewportHeight : intHeight;
	intHeight += 1; // scrollbar fix
	
	jQuery(elLightboxWrapperInner).animate({'height': intHeight});
}


/**
 * opens Skoda-style popin
 * (when browsing on a mobile device opens the link in new window)
 *
 * @param string - url to open in popin
 */
function openPopin(strUrl) {
    var useragent = navigator.userAgent.toLowerCase();
    if (isMobile()) {
        // if browsing on a mobile device, open the url in a new window
        window.open(strUrl);
    } else {
        // otherwise open the url in the shadowbox popin
        var objTempLink = jQuery('<a href="' + strUrl + '" rel="shadowbox" style="display: none" />');
        objTempLink.appendTo('body');
        Shadowbox.open(objTempLink[0]);
        objTempLink.remove();
    }
}


/**
* checks whether browsing on a mobile device
*
* @return boolean
*/
function isMobile() {
    var mobile = false;
    var useragent = navigator.userAgent.toLowerCase();
    if (screen.width < 1000 ||
                useragent.indexOf('iphone') != -1 ||
                useragent.indexOf('ipad') != -1 ||
                useragent.indexOf('ipod') != -1 ||
                useragent.indexOf('android') != -1 ||
                useragent.indexOf('blackberry') != -1 ||
                useragent.indexOf('webos') != -1 ||
                useragent.indexOf('symbian') != -1) {
        mobile = true;
    }
    return mobile;
}


/**
 * Performs search functionality.
 * 
 * @author Dennis Velthuis <dennis.velthuis[AT]efocus.nl>
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @since 1.2, feb 2011
 */
function performSearch(elQuery) {
	var strUrl = jQuery('.search_url').val();
	var strQuery = jQuery(elQuery).val();
	window.location = strUrl + "?q=" + strQuery;
	return false;
}


/**
 * Triggers a search when pressing the Enter key or clicking the submitbutton.
 * 
 * @author Dennis Velthuis <dennis.velthuis[AT]efocus.nl>
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @since 1.2, mar 2011
 */
function initSearch(elFieldset) {
	var elQuery = jQuery(elFieldset).find('.text');
	
	jQuery(elQuery).keydown(function(evt){
		if (evt.which || evt.keyCode) {
			if ((evt.which == 13) || (evt.keyCode == 13)) {
				performSearch(elQuery);
				return false;
			}
			return true;
		}
	});
	
	jQuery(elFieldset).find('.submit').click(function(evt){
		evt.preventDefault();
		performSearch(elQuery);
	});
}
