{maxHeight: 150}var LAB = (typeof($LAB) !== 'undefined') ? $LAB : null;		// avoid jQuery conflicts
var javascriptPath = (typeof(javascriptPath) !== 'undefined') ? javascriptPath : null;
var imagePath = (typeof(imagePath) !== 'undefined') ? imagePath : null;
var jQueryVersion = '1.6.1';
var jQueryUiVersion = '1.8.13';

var gOverride = {		// 960 grid
	urlBase: 'http://gridder.andreehansson.se/releases/latest/',
	gColor: '#ff0000',
	gColumns: 12,
	gOpacity: 0.25,
	gWidth: 10,
	pColor: '#C0C0C0',
	pHeight: 20,
	pOffset: 0,
	pOpacity: 0.50,
	center: true,
	gEnabled: true,
	pEnabled: true,
	setupEnabled: true,
	fixFlash: true,
	size: 960
};

/* -----ERROR HANDLING------ */
/* --- output obj to console if available --- */
function debug(obj) {
	if (window.console && window.console.log) {
		console.log(obj);
	}
}

/* --- try calling given function with error handling --- */
function callFunction(func) {
	if (typeof(func) === 'object' && func.length !== 'undefined') {
		$.each(func, function (i) {
			try {
				func[i].call();
			} catch (e) {
				debug('ERROR: function[type:' + typeof(func[i]) + '] ' /* + func[i].name */ + '() - ' + e);
			}
		});
	} else {
		debug('ERROR: wrong type of argument in callFunction()');
	}
}

/* -----GENERIC RESOURCE LOAD WITH LABJS------ */
/* --- load resources --- */
function loadResources(resources, func) {
	if (typeof(LAB) !== 'undefined') {
		if (typeof(resources) === 'object' && resources.length !== 'undefined' && resources.length > 0) {
			LAB
				.setOptions({AlwaysPreserveOrder: true})
				.script(resources)
				.wait(
					function () {
						debug('loaded: ' + resources);
						func.call();
					}
				);
		} else {
			debug('ERROR: incorrect input \'resources\' - ' + resources);
		}
	} else {
		debug('ERROR: variable LAB undefined');
	}
}
/* --- if elem gt 0, check eq true >> load resources >> apply given function --- */
function applyFunction(elem, check, resources, func) {
	if (parseInt(elem, 10) > 0) {
		if (!check.call()) {
			loadResources(resources, func);
		} else {
			func.call();
		}
	}
}

/* -----FANCYFORM------ */
/* --- apply $.fn.fancyform() --- */
function applyFancyForm() {
	var submitButton = $('input.button[type=submit]');
	var inputMergeLabel = $('input.merge_with_label, select.merge_with_label');

	applyFunction(
		submitButton.length + inputMergeLabel.length,
		function () {
			return $.fn.fancyform;
		},
		[javascriptPath + '/jquery.fancyform.js'],
		function () {
			submitButton.fancyform('createFancySubmit');
			inputMergeLabel.fancyform('mergeLabel');
		}
	);
}

/* --- apply filament group dropdown --- */
function applyCustomDropdown() {
	var selectElem = $('select');

	applyFunction(
		selectElem.length,
		function () {
			return $.selectmenu;
		},
		[javascriptPath + '/jquery-ui-' + jQueryUiVersion + '.custom.min.js', javascriptPath + '/jquery-ui.selectmenu.js'],
		function () {
			if (!navigator.userAgent.match(/Android/i) && !navigator.userAgent.match(/webOS/i) && !navigator.userAgent.match(/iPhone/i) && !navigator.userAgent.match(/iPod/i) && !navigator.userAgent.match(/iPad/i)) {
				selectElem.selectmenu(
					{
						style: 'dropdown',
						width: 218,
						maxHeight: 150
					}
				);
				
				$(window).resize(function () {
					selectElem.selectmenu('close');
				})			
			}
			$('#recentwork_filter').css('visibility', 'visible');
		}
	);

}

/* -----ALIGNMENT------ */
/* --- vertical align $('#footer') to bottom --- */
function bottomAlignFooter() {
	var unitInfo;
	var marginTop;
	var func;
	
	// wrap function in variable so we can call it on $(window).resize()
	func = function () {
		unitInfo = $('#unit_info');
		unitInfo.css('margin-top', 0); // reset
		marginTop = $(window).height() - $('#canvas').outerHeight() - unitInfo.outerHeight() - $('#footer').outerHeight(); // define offset
		if (marginTop > 0) {
			unitInfo.css('margin-top', marginTop); // apply
		}
	};
	// call function; also on $(window).resize()

	func.call();
	$(window).resize(function () {
		func.call();
	});
}
/* --- vertical align columns --- */
function verticalAlignColumn() {
	var colwrp = $('ol.equal_col_height, ul.equal_col_height');
	var colwrpLength = colwrp.length;
	var colwrpLi;
	var wrp;
	var liLength;
	var liHeight;
	var rows;
	var row;
	var cols;
	var col;
	var current;

	if (colwrpLength) {
		
		for (wrp = 0; wrp < colwrpLength; wrp++) {

			colwrpLi = colwrp.eq(wrp).find('> li');
			liLength = $(colwrpLi).length;
			cols = Math.floor($(colwrp).eq(wrp).outerWidth() / colwrpLi.outerWidth());
			rows = Math.ceil(liLength / cols);

			for (row = 0; row < rows; row++) {
				// define heighest <li> within current 'row'
				for (col = 0; col < cols; col++) {
					if (col === 0) {
						liHeight = 0;
					}
					current = row * cols + col;
					liHeight = ($(colwrpLi).eq(current).height() > liHeight) ? $(colwrpLi).eq(current).height() : liHeight;

					if (row !== 0) {
						$(colwrpLi).eq(current).addClass('margintop');
						// liHeight += 1;
					}
				}
				
				// set height of <li>
				for (col = 0; col < cols; col++) {
					current = row * cols + col;
					$(colwrpLi).eq(current).height(liHeight);
				}
			}

			colwrp.eq(wrp).addClass('jquery_ech');

		}
	}
}

/* -----BLOG----- */
/* --- get new blog items --- */

function getBlogFilterCategory() {
	var blogFilter = $('#blogfilterForm');
	var result = [];
	
	blogFilter.find('input[name=category]:checked').each(function () {
		result.push($(this).val());
	});
	
	return result;
}

function getBlogContent() {

	var blogList = $('ol.bloglist');
	var html = '';
	var pagenr = (typeof(blogList.attr('id')) == 'undefined') ? 2 : parseInt(blogList.attr('id').replace('bloglist_', ''), 10) + 1;

	blogList.attr('id', 'bloglist_' + pagenr);

	$.ajax({
		url: '/inc/cfc/blogs.cfc',
		data: {
			method: 'getBlogs',
			returnformat: 'json',
			page: pagenr,
			category: getBlogFilterCategory().join(','),
			keyword: $('#blogfilter_keyword').val()
		},
		async: false,
		dataType: 'json',
		success: function (json) {
			
			if (json.TOTAL === 0) {
				html += '<li>' +
					'	<h2>Helaas</h2>' +
					'	<p><em>We hebben geen blogitems gevonden die voldoen aan de door u opgegeven criteria. Verruim uw zoekopdracht.</em></p>'
					'</li>';
				$('#bloglist_readmore').hide();
			} else {
				$('#bloglist_readmore').show();
				
				
				$.each(json.BLOG, function(i) {
					html += '<li>' +
						'	<h2 class="upperCase">' + json.BLOG[i].TITLE + '</h2>' + 
						'	<div class="datetime">' + json.BLOG[i].DATE + '</div>';
					html += (json.BLOG[i].IMAGE != '') ? '	<a href="/nl/blog__/q/id/' + json.BLOG[i].ID + '"><img alt="" src="/inc/upload/blogs/' + json.BLOG[i].IMAGE + '"></a>' : '';
					html += '	<div class="description">' +
						json.BLOG[i].DESCRIPTION +
						'		<a href="/nl/blog/q/id/' + json.BLOG[i].ID + '" class="readmore">Lees&nbsp;verder</a>' +
						'	</div>' + 
						'</li>';
				});
				if (json.ENDOFLIST) {
					$('#bloglist_readmore').remove();
				}
			}
			
		}
	});

	return html;
}

/* --- load more blog items onclick --- */
function applyBlogReadmore() {

	var readMore = $('a#bloglist_readmore');
	var blogList = $('ol.bloglist');
	var blogFilterForm = $('#blogfilterForm');
	
	function getThisContent(blogList) {
		blogList.attr('id', 'bloglist_0'); // reset pagenr
		blogList.find('li').remove();
		blogList.append(getBlogContent());
	}
	
	if (readMore.length) {
		readMore.click(function() {
			blogList.append(getBlogContent());
			return false;
		});
	}
	
	if (blogFilterForm.length) {
		blogFilterForm.find('input[type=checkbox]').change(function () {
			getThisContent(blogList);
		});
		blogFilterForm.find('input[type=text]').bind('keyup blur', function (e) {
			if (e.type === 'blur' || (e.type === 'keyup' && (e.keyCode == 8 || e.keyCode == 46 || $(this).val().length >= 3))) {
				getThisContent(blogList);
			}
		});
	}
}

function fillProjectDetail(dataListItems, json, type) {

	var thisContent;

	if (dataListItems.find('ul').length) {
		thisContent = dataListItems.find('ul');
		thisContent.find('li').remove();
	} else {
		$.each(dataListItems, function() {
			if ($(this).get(0).tagName.toLowerCase() === 'dd') {
				thisContent = $(this);
			}
		});
		thisContent.empty();
	}
	
	if (typeof(json) !== 'undefined') {
		$.each(json, function (i) {
			
			switch(type) {
				case 'team':
				case 'unit':
					thisContent.append('<li><a href="' + json[i].URL + '">' + json[i].NAME + '</a></li>');
					break;
				case 'client':
					if (typeof(json.NAME) != 'undefined') {
						thisContent.html('<img src="/inc/upload/clients/logos/' + json.IMG + '" alt="' + json.NAME + '" />');
					} else {
						thisContent.text(json.NAME);
					}
					break;
				case 'resources':
					thisContent.append('<li>' + json[i].NAME + '</li>');
					break;
				case 'account':
					thisContent.html('<a href="' + json.URL + '">' + json.NAME + '</a>');

					break;
				default:
					thisContent.append(json[i]);
					break;
			}
		});
	}
}




/* -----CAROUSEL----- */

/* --- get recent work content --- */
function getProjectOverviewContent(carousel) {
	
	var navigation = carousel.find('.navigation');
	var result = {
			html: null,
			total: null
	};
	
	$.ajax({
		url: '/inc/cfc/projects.cfc',
		data: {
			method: 'getProjects',
			returnformat: 'json',
			page: parseInt(navigation.eq(0).find('.current').text(), 10),
			portfolio_category: $('#portfolio_category').val(),
			portfolio_client: $('#portfolio_client').val()
		},
		async: false,
		dataType: 'json',
		success: function (json) {
			
			var clone = carousel.find('.wrp').clone(false);			
			
			// fill list
			clone.find('li').remove();
			$.each(json.PROJECT, function (i) {
				var addClass = (i > 2) ? ' class="margintop"' : '';
				clone.find('ul').append('<li' + addClass + '>' +
					'	<a href="' + json.PROJECT[i].URL + '">' +
					'		<img src="' + json.PROJECT[i].IMAGE + '" alt="' + json.PROJECT[i].TITLE + '" />' +
					'		<span>' + json.PROJECT[i].TITLE + '</span>' +
					'	</a>' +
					'</li>');
			});
			
			// paging
			navigation.find('.current').text(json.PAGE);

			result.html = clone.html();
			result.total = parseInt(Math.ceil(json.TOTAL), 10)

			// hide navigation if total pagecount equals 1; otherwise show navigation
			if (json.TOTAL == 1) {
				$('ol.navigation')
					.css('display', '')
					.addClass('hidden');
			} else {
				$('ol.navigation')
					.css('display', '')
					.removeClass('hidden');
			}
			
		}
	});
	
	return result;
}

/* --- get carousel content --- */
function getCarouselContent(obj) {

	var hyperlink = obj;
	var carousel = obj.parents('.carousel');
	var html;
	
	switch(carousel.attr('id')) {
		case 'recentwork_overview':
		
			var navigation = carousel.find('.navigation');
			var current = parseInt(navigation.find('.current').text(current), 10);
			var navigationIndex = parseInt(navigation.find('.index').text(), 10);
			var nextUrl = (current == 1) ? navigationIndex : current - 1;
			var prevUrl = (current == navigationIndex) ? 1 : current + 1;
			
			var navigationNext = navigation.find('.prev a');
			var navigationPrev = navigation.find('.next a');
			
			var urlPrefix = navigationNext.attr('href').split('/page/')[0];
			
			navigationNext.attr('href', urlPrefix + '/page/' + nextUrl);
			navigationPrev.attr('href', urlPrefix + '/page/' + prevUrl);

			html = getProjectOverviewContent(carousel).html;

			break;
		
		case 'recentwork_detail':

			$.ajax({
				url: '/inc/cfc/projects.cfc',
				data: {
					method: 'getProject',
					returnformat: 'json',
					id: hyperlink.attr('href').split('/id/')[1]
				},
				dataType: 'json',
				async: false,
				success: function (json) {

					var clone = carousel.find('.wrp').clone(false);
					
					clone.find('dl.aside .hidden').removeClass('hidden');
		
					carousel.prev('h1').text(json.TITLE);
					$('title').text(json.PAGETITLE);
					
					// fill aside
					fillProjectDetail(clone.find('dl .resources'), json.RESOURCES, 'resources');
					fillProjectDetail(clone.find('dl .client'), json.CLIENT, 'client');
					fillProjectDetail(clone.find('dl .account'), json.ACCOUNT, 'account');
					fillProjectDetail(clone.find('dl .team'), json.TEAM, 'team');
					fillProjectDetail(clone.find('dl .unit'), json.UNITS, 'unit');
					
					if (json.RESOURCES == '') {
						clone.find('dl .resources').addClass('hidden');
					}
					if (json.CLIENT == '') {
						clone.find('dl .client').addClass('hidden');
					}
					if (json.ACCOUNT == '') {
						clone.find('dl .account').addClass('hidden');
					}
					if (json.TEAM == '') {
						clone.find('dl .team').addClass('hidden');
					}
					if (json.UNITS == '') {
						clone.find('dl .unit').addClass('hidden');
					}
					
					// fill main
					var main = clone.find('.large');
					
					if (json.VIDEO) {
						var videoSrc = encodeURIComponent('http://' + location.host + '/' + json.VIDEO);
						main.empty();
						main.append('<h2>' + json.TITLE + '</h2>' + json.DESCRIPTION);
						main.prepend('<object width="620" height="349">' +
								'<param name="movie" value="/inc/swf/StrobeMediaPlayback.swf"></param>' + 
								'<param name="wmode" value="opaque"></param>' + 
								'<param name="flashvars" value="scaleMode=stretch&src=' + videoSrc + '"></param>' + 
								'<param name="allowFullScreen" value="true"></param>' + 
								'<param name="allowscriptaccess" value="always"></param>' + 
								'<embed wmode="opaque" src="/inc/swf/StrobeMediaPlayback.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="620" height="349" flashvars="scaleMode=stretch&src=' + videoSrc + '"></embed>' + 
							'</object>');
					} else {
						main.empty();
						main.append('<h2>' + json.TITLE + '</h2>' + json.DESCRIPTION);
						main.prepend('<div id="gallery" class="ad-gallery">' +
							'	<div class="ad-image-wrapper"></div>' + 
							'	<div class="ad-controls"></div>' +
							'	<div class="ad-nav">' +
							'		<div class="ad-thumbs">' +
							'			<ul class="ad-thumb-list"></ul>' +
							'		</div>' +
							'	</div>' +
						'</div>');

						var carouselThumbList = main.find('.ad-gallery ul.ad-thumb-list');			
						$.each(json.IMAGES, function (i) {
							carouselThumbList.append('<li><a href="' + json.IMAGES[i].LARGE + '"><img src="' + json.IMAGES[i].THUMB +'" alt="" /></a></li>');
						});
					}

					// paging
					var navigation = carousel.find('.navigation');
					
					navigation.find('.prev a').attr('href', hyperlink.attr('href').split('/id/')[0] + '/id/' + json.PREVIOUS);
					navigation.find('.current:eq(0)').attr('id', 'projects_' + json.ID);
					navigation.find('.current').text(json.POSITION);
					navigation.find('.next a').attr('href', hyperlink.attr('href').split('/id/')[0] + '/id/' + json.NEXT);
					
					html = clone.html();

				}
			});

			break;

		default:
			html = $('.carousel .wrp').html();
			break;
	}
	
	return html;
}

/* -----HISTORY----- */
/* --- This function is called when: --- */
/*	1. after calling $.historyInit(); */
/*	2. after calling $.historyLoad(); */
/*	3. after pushing "Go Back" button of a browser */

function historyPageLoad(hash) {
	// hash doesn't contain the first # character.
	if (hash) {

		var pageId = window.location.href.split('/page/');
		var obj = $('#carouselActive');
		obj = (obj.length) ? obj : $('.carousel .navigation .prev a');
		var navigation = obj.parents('.navigation');

		if (pageId.length > 1) {
			pageId = pageId[1].split('#');
			pageId = pageId[0];
		} else {			
			pageId = 1;
			/*
			$.history.load(pageId);
			return;
			*/
		}
		
		if (hash != pageId) {
			navigation.find('.current').text(hash);
		}
		
		var navigationCurrent = parseInt(navigation.find('.current').text(), 10)
		var navigationIndex = parseInt(navigation.find('.index').text(), 10);
		var list = obj.parents('.carousel').find('.carousel_wrp')
		var listParent = list.parent();
		var listWidth = list.outerWidth();
		var animationSpeed = 1000;

		obj.removeAttr('id');

		html = getCarouselContent(obj);
		
		if (!listParent.is(':animated')) {
			if (obj.parent().hasClass('prev')) {
				listParent
					.prepend(html)
					.css('left', -1 * listWidth)
						.animate(
							{ left: 0 },
							animationSpeed,
							function () {
								listParent.find('> .list:last-child').remove();
								verticalAlignColumn();
								applyAdGallery();
							}
						);
			} else {
				listParent
					.append(html)
					.css('left', 0)
						.animate(
							{ left: -1 * listWidth },
							animationSpeed,
							function () {
								listParent.find('> .list:first-child').remove();
								listParent.css('left', 0);
								verticalAlignColumn();
								applyAdGallery();
							}
						);
			}
		}
	
	}	
}

function bindCarouselClick(obj) {

	var navigation = obj.parents('.navigation');
	var navigationCurrent = parseInt(navigation.find('.current').text(), 10)
	var navigationIndex = parseInt(navigation.find('.index').text(), 10);

	var current = (obj.parent().hasClass('prev')) ? navigationCurrent - 1 : navigationCurrent + 1;
	current = (current > navigationIndex) ? 1 : current;
	current = (current < 1) ? navigationIndex : current;

	navigation.find('.current').text(current);	
	obj.attr('id', 'carouselActive');

	// create history instance of current URL
	$.history.load(current);

}

/* --- apply $.fn.carousel() --- */
function applyCarousel() { /* --- list, html --- */

	var list = $('.carousel_wrp');
	var html;
	var listParent;
	var listWidth;
	var animationSpeed = 1000;

	listWidth = list.outerWidth();
	list
		.addClass('list')
		.wrap('<div class="overflowHidden" />')
		.wrap('<div class="wrp" />');
	list.find('.wrp').append('<div class="clearboth" />');

	listParent = list.parent();
	listParent.width(20 + 2 * listWidth);

	$('.carousel .navigation a').click(function () {
		var current = parseInt($(this).parents('.navigation').find('.current').text(), 10);
		current = ($(this).parent().hasClass('prev')) ? current - 1 : current + 1;
		current = (parseInt(current, 10) > parseInt($(this).parents('.navigation').find('.index').text(), 10)) ? 1 : current;
		current = (current < 1) ? parseInt($(this).parents('.navigation').find('.index').text(), 10) : current;		
		$(this).parents('.carousel').find('.navigation .current').text(current);

		html = getCarouselContent($(this));
		
		if (!listParent.is(':animated')) {
			if ($(this).parent().hasClass('prev')) {
				listParent
						.prepend(html)
						.css('left', -1 * listWidth)
						.animate(
							{ left: 0 },
							animationSpeed,
							function () {
								listParent.find('> .list:last-child').remove();
								applyAdGallery();
							}
						);
			} else {
				listParent
						.append(html)
						.css('left', 0)
						.animate(
							{ left: -1 * listWidth },
							animationSpeed,
							function () {
								listParent.find('> .list:first-child').remove();
								$(this).css('left', 0);
								applyAdGallery();
							}
						);
			}
		}

		return false;

	});

}

/* --- refresh list on <select> change event --- */
function addChangeListener() {
	$('#recentwork_filter select').live('change', function () {
		var overview = $('#recentwork_overview');
		var result = getProjectOverviewContent($('#recentwork_overview'));

		overview.find('.wrp').html(result.html);
		overview.find('.navigation .current').text('1');
		overview.find('.navigation .index').text(result.total);
	});
}


/* -----PNGFIX------ */
/* --- apply $.fn.pngfix() to all PNG images on MSIE6  --- */
function applyPngFix() {
	if ($.browser.msie && $.browser.version === "6.0") {
		var imgPng = $("img[src$='.png']");
		
		applyFunction(
			imgPng.length,
			function () {
				return $.fn.pngfix;
			},
			[javascriptPath + '/jquery.pngfix.js'],
			function () {
				imgPng.pngfix();
			}
		);
	}
}

/* --- create tab for each <h2> of div.section --- */
function applyContentTabs() {
	var contentarea = $('.create_content_tabs');
	var section;
	var tabs;

	if (contentarea.length) {
		$(contentarea).each(
			function (i) {

				section = contentarea.eq(i).find('.section');
				if (section.length) {
					contentarea.eq(i).prepend('<ul class="jquery_tabs" />');
					tabs = contentarea.eq(i).find('ul.jquery_tabs');
					$(section).each(
						function (j) {
							tabs.append('<li><a href="#' + $(this).attr('id') + '">' + $(this).find('h2:eq(0)').text() + '</a></li>');
							$(this).find('h2').addClass('hidden');
						}
					);
					section.eq(0).addClass('act');
					tabs.find('li:eq(0) a').addClass('act');

					tabs.find('a').click(
						function () {

							// remove current active state
							$(this).parents('.create_content_tabs').find('.section.act').removeClass('act');
							$(this).parents('.jquery_tabs').find('a.act').removeClass('act');

							// add active state to clicked section
							$(this).parents('.create_content_tabs').find('.section:eq(' + $(this).parents('li').index() + ')').addClass('act');
							$(this).addClass('act');

							return false;
						}
					);
				}
			}
		);
	}
}


/* -----FORM VALIDATION------ */
/* --- validate forms within site --- */
function applyValidation() {
	var elem = $('form#directionsForm, form#contactForm, form#newsletterFormAside, form#newsletterForm, form#newsletterFormSignoff, form#blogfilterForm, form#frmDirections'),
		invalidFields = [],
		checklist = [],
		notEmpty = [],
		validEmail = [],
		thisForm = null,
		postUrl;

	applyFunction(
		elem.length,
		function () {
			return $.fn.validation;
		},
		[javascriptPath + '/jquery.validation.js'],
		function () {
						
			elem.submit(
				function () {
					
					thisForm = $('form#' + $(this).attr('id'));
					invalidFields = [];
					
					switch ($(this).attr('id')) {
						case 'directionsForm':
							notEmpty = ['input#location'];

							break;
						case 'contactForm':
							notEmpty = ['textarea#message'];
							validEmail = ['input#email'];

							break;
						case 'newsletterForm':
							notEmpty = ['input#newsletter_name'];
							validEmail = ['input#newsletter_email'];

							break;
						case 'newsletterFormSignoff':
							validEmail = ['input#newsletterSignoff_email'];
							
							break;
						case 'newsletterFormAside':
							notEmpty = ['input#newsletter_aside_name'];
							validEmail = ['input#newsletter_aside_email'];

							break;
						case 'blogfilterForm':
							notEmpty = ['input#blogfilter_keyword'];
							
							break;
						case 'frmDirections':
							notEmpty = ['input#start_location'];

							break;
					}
					
					/* check if not empty */
					$.each(notEmpty, function (i) {
						if (thisForm.find(notEmpty[i]).length > 0) {
							if (thisForm.find(notEmpty[i]).val() === '' || thisForm.find(notEmpty[i]).val() === $('label[for=' + thisForm.find(notEmpty[i]).attr('id') + ']').text()) {
								invalidFields.unshift(notEmpty[i]);
							}
						}
					});

					/* check if valid e-mail */
					$.each(validEmail, function (i) {
						if (thisForm.find(validEmail[i]).length > 0) {
							if (!$.fn.validation.validEmail(thisForm.find(validEmail[i]).val())) {
								invalidFields.unshift(validEmail[i]);
							}
						}
					});

					invalidFields = $.fn.validation.returnUniqueArray(invalidFields, 0);
					
					/* mark invalid fields OR post form */
					if (invalidFields.length > 0) {
						$.fn.validation.markInvalidFields(thisForm, invalidFields);
						return false;
					} else {
						return true;
					}
					
					return false;

				}
			);
		}
	);
}

/* -----CLIENTLIST------ */
function applyClientList() {

	var clientlist = $('ul.clientlist_nonjs');
	var clientImage;
	var clientLink;
	var html;
	var index;
	var className;
	var leftOffset;
	var overlay;
	var currentItem;
	var currentItemHref;
	
	if (clientlist.length) {
		
		html = '<ul class="clientlist four_cols">';
		clientlist.find('> li').each(function () {
			html += '<li>' + $(this).find('.imgwrp').html() + '</li>';
		});		
		html += '</ul>';
		
		clientlist.hide().after(html);
		clientlist = clientlist.next();

		clientlist.find('> li').each(function () {			
			// vertical align image
			clientImage = $(this).find('img');						
			$(this).css('background', $(this).css('background-color') + ' url(' + clientImage.attr('src') + ') no-repeat center center');
			clientImage.hide();
			
			// create overlay onhover
			clientLink = $(this).find('a');
			
			clientLink.click(function() { return false; }); // prevent regular click
			/*
			$(this).hover(
				function () {
					
					overlay = $(this).find('.overlay');
					currentItem = clientlist.prev().find('li:eq(' + $(this).index() + ')');
					currentItemHref = (typeof($(this).find('a').attr('href')) !== 'undefined') ? $(this).find('a').attr('href') : '#';
					
					if (overlay.length) {
						overlay.show();
					} else {
						index = $(this).index() % 4;
						clientLink = $(this).find('a');
						
						if (index > 1) {
							className = 'overlay_right';
							leftOffset = -480;
						} else {
							className = 'overlay_left';
							leftOffset = 0;
						}
		
						html = '<div class="overlay ' + className + '" style="left: ' + leftOffset + 'px">' +
							'<h2 class="upperCase">' + currentItem.find('h2').text() + '</h2>' +
							'<div class="text">' + currentItem.find('.text p').text() + '</div>';
						html += (currentItemHref !== '#') ? '<a href="' + currentItemHref + '" class="button">Bekijk projecten <span></span></a>' : '';
						html += '<div class="line"></div>';
						html += (currentItemHref !== '#') ? '<a class="logo" href="' + currentItemHref + '" style="background: url(' + currentItem.find('.imgwrp img').attr('src') + ') no-repeat center center;"></a></div>' : '<a class="logo" style="background: url(' + currentItem.find('.imgwrp img').attr('src') + ') no-repeat center center;"></a></div>';
							
						$(this).append(html);
					}					
				},
				function () {
					$(this).find('.overlay').hide();
				}
			);
			*/
			
		});
	}
}

/* Create fancy on/off switch instead of checkboxes */
function createCheckbox() {
	var checkboxItems = $('input[type=checkbox]');
	var container;
	
	if (checkboxItems.length && (!$.browser.msie || $.browser.msie && parseInt($.browser.version, 10) > 8)) {
		checkboxItems.each(
			function(i) {
				
				$(this).after('<a href="#" class="checkbox_wrp" />').hide();
				var checkBoxWrp = $(this).next();
				
				if ($(this).is(':checked')) {
					checkBoxWrp.addClass('checkbox_on');
				} else {
					checkBoxWrp.addClass('checkbox_off');
				}
			}
		);
		
		$('a.checkbox_wrp').live('click', function() {
			
			var container = $(this);
			var checkbox = container.prev();

			/* setup active state */
			$(this).toggleClass('checkbox_on checkbox_off');
			
			if ($(this).hasClass('checkbox_on')) {
				checkbox.attr('checked', 'checked');
			} else {
				checkbox.removeAttr('checked');
			}
			
			checkbox.change();
			
			return false;
			
		});
	}
}

/* --- apply tooltip --- */
function applyTooltip() {

	var elem = $('#socials a');
	var currentElem;
	var elemWrp;
	var tooltip;
	
	elem.each(function () {
		currentElem = $(this);
		currentElem.wrap('<div class="tooltip_wrapper"></div>');
		
		elemWrp = currentElem.parents('.tooltip_wrapper');
		elemWrp.append("<div class=\"tooltip\"><div class=\"tooltip_text\"></div><div class=\"tooltip_footer\"></div></div>");

		tooltip = elemWrp.find('.tooltip');

		if ($(this).is('img')) {
			tooltip.find('.tooltip_text').text(currentElem.attr('alt'));
		} else {
			tooltip.find('.tooltip_text').text(currentElem.text());
		}
		
		tooltip.hide().css(
			{
				'left' : -18 + Math.round(elemWrp.width() / 2),
				'bottom' : -2 + elemWrp.height()
			}
		);
		
		elemWrp.hover(
			function () {
				$(this).find('.tooltip').show();
				/*
				$(this).bind('mousemove', function (e) {
					tooltip = $(this).find('.tooltip');
					tooltip
						.css('left', Math.floor(e.pageX - $(this).offset().left) - 20)
						.css('top', Math.floor(e.pageY - $(this).offset().top) - tooltip.outerHeight());
				});
				*/
			},
			function () {
				$(this).find('.tooltip').hide();
				$(this).unbind('mousemove');
			}			
		);
		
	});
}

/* --- --- */
function applyAdGallery() {
	var gallery = $('.ad-gallery');

	applyFunction(
		gallery.length,
		function () {
			return $.fn.adGallery;
		},
		[javascriptPath + '/jquery.ad-gallery.js'],
		function () {
			gallery.adGallery(
				{
					loader_image: imagePath + '/ad-gallery/loader.gif'
				});
		}
	);
}

/* --- update dropdown based on select values --- */
function updatePortfolioFilter() {
	
	var selectPortfolioCategory = $('select#portfolio_category');
	var selectPortfolioClient = $('select#portfolio_client');
	
	if ( selectPortfolioCategory.length && selectPortfolioClient.length ) {

		selectPortfolioCategory.change(function () {
			$.ajax({
				url: '/inc/cfc/projects.cfc',
				data: {
					method: 'getClientsfromUnit',
					returnformat: 'json',
					unit: $(this).val()
				},
				dataType: 'json',
				success: function (json) {
					
					var currentVal = selectPortfolioClient.val();
					var optionHtml;
					
					// remove options in select except label
					$(selectPortfolioClient).find('option:gt(0)').remove();
					$.each(json.CLIENT, function (i) {
						optionHtml = ( json.CLIENT[i].ID == currentVal ) ? '<option value="' + json.CLIENT[i].ID + '" selected="selected">' + json.CLIENT[i].NAME + '</option>' : '<option value="' + json.CLIENT[i].ID + '">' + json.CLIENT[i].NAME + '</option>';
						selectPortfolioClient.append(optionHtml);
					});
					selectPortfolioClient.selectmenu('destroy').selectmenu( { style: 'dropdown', width: 218, maxHeight: 150 } );
				}
			});			
		});
		
		selectPortfolioClient.change(function () {
			$.ajax({
				url: '/inc/cfc/projects.cfc',
				data: {
					method: 'getUnitsfromClient',
					returnformat: 'json',
					client: $(this).val()
				},
				dataType: 'json',
				success: function (json) {
					
					var currentVal = selectPortfolioCategory.val();
					var optionHtml;

					// remove options in select except label
					$(selectPortfolioCategory).find('option:gt(0)').remove();
					$.each(json.UNIT, function (i) {
						optionHtml = ( json.UNIT[i].SHORTNAME == currentVal ) ? '<option value="' + json.UNIT[i].SHORTNAME + '" selected="selected">' + json.UNIT[i].NAME + '</option>' : '<option value="' + json.UNIT[i].SHORTNAME + '">' + json.UNIT[i].NAME + '</option>';
						selectPortfolioCategory.append(optionHtml);
					});
					selectPortfolioCategory.selectmenu('destroy').selectmenu( { style: 'dropdown', width: 218, maxHeight: 150 } );

				}
			});			
		});
	
	}
	
}

function applyStrobeMediaPlayback() {
	var video = $("video");
	var ua = navigator.userAgent.toLowerCase();
	
	if (!ua.match(/android/i) && !ua.match(/webos/i) && !ua.match(/iphone/i) && !ua.match(/ipod/i) && !ua.match(/ipad/i)) {
		applyFunction(
			video.length,
			function () {
				return typeof(swfobject) !== 'undefined';
			},
			[javascriptPath + '/swfobject.js'],
			function () {
				
				var flashvars = { src: null, autoPlay: null, loop: null, controlBarMode: 'none', backgroundColor: 'FFFFFF', 'playButtonOverlay': false, autoRewind: false };
				var params = { allowfullscreen: "false", allowscriptaccess: "always", wmode: "transparent" };
				var attributes = { id: null, name: null };
	
				video.each(function (i) {
					
					flashvars.src = $(this).attr('src');
					flashvars.autoPlay = true;
					flashvars.loop = $(this).attr('doloop') === 'true';
					attributes.id = 'video_player_' + i;
					attributes.name = attributes.id;
	
					$(this).wrap('<div class="video_player" id="' + attributes.id + '" />');
									
					swfobject.embedSWF("/inc/swf/StrobeMediaPlayback.swf", attributes.id, $(this).attr('width'), $(this).attr('height'), "10.0.0", false, flashvars, params, attributes);
	
				});
			}
		)
	} else {
		video.show();
	}

}

/* --- initialize Google Maps --- */
function initGoogleMaps() {
	
	// Hidden input with map gm_id.
	var map_id = $('#gm_id');
	
	if (map_id.length) {
		// Load settings.
		$.ajax({
			url: '/inc/cfc/settings.cfc?method=getGoogleMaps&returnFormat=json',
			data: { gm_id: map_id.val() },
			success: function(data) {
				var settings = jQuery.parseJSON(data);
				createMap(settings);
			}
		});
	}
}

function createMap(settings) {
	var mapContainer = document.getElementById('map_canvas');
	
	// Create map.
	var map = new google.maps.Map(mapContainer, {
		zoom: settings.zoomlevel,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		center: new google.maps.LatLng(settings.latitude, settings.longitude)
	});
	
	// Create markers on the map.
	var markerEvenement = new google.maps.Marker({
		position: new google.maps.LatLng(settings.latitude, settings.longitude),
		map: map,
		title: "Aan Zee"
	});
	var windowEvenement = new google.maps.InfoWindow({
		content: 	'Erasmusweg 19 <br />'+
					'2200 CA Noordwijk Aan Zee</p>'
	});
	
	// Add directions
	createDirections(map);
}

function createDirections(map) {
	var form = $('form#frmDirections');
	var dirContainer = document.getElementById('map_directions');
	var directionDisplay = new google.maps.DirectionsRenderer();
	
	directionDisplay.setMap(map);
	directionDisplay.setPanel(dirContainer);
	
	if (form.length) {
		// Submit form
		form.submit(function() {

			var request = {
					origin: form.find('input#start_location').val(),
					destination: 'Erasmusweg 19, Noordwijk Aan Zee',
					travelMode: google.maps.DirectionsTravelMode.DRIVING
				},
				directionsService = new google.maps.DirectionsService();

			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionDisplay.setDirections(response);
				}
			});

			return false;
				
		});
	}
}

/* --- --- */
function applyNewsletterBar() {

	var newsletterBar = $('#newsletter_bar');

	newsletterBar.find('input[type=submit]').hide();
	newsletterBar.find('select').change(function () {
		if (parseInt($(this).val(), 10) !== 0) {
			window.location.href = $(this).val();  /* stond nog iets voor: "/index.cfm?act=site.page&mn_id=" + */
		}
	});
}

/* -----BROWSER HACKS----- */
/* --- yes, it's ugly ... --- */
function applyBrowserHacks() {
	var subnavigation = $('#subnavigation');
	if (subnavigation.length) {
		if ($.browser.webkit) {
			subnavigation.find('a').css('line-height', '32px');
		}
	}
}

/* --- create fullwidth banners --- */
function applyFullWidthBanner (bind) {
	var banner = $('#banner');
	var bannerBackground = banner.find('.background img');
	var bannerOriginalWidth = 2000;
	var bannerOriginalHeight = ( banner.hasClass('banner_small') ) ? 130 : 276;;
	
	if ( banner.length && bannerBackground.length ) {
		
		// reset
		$(bannerBackground).css({
			'width': bannerOriginalWidth,
			'margin-top': 0,
			'margin-left': 0
		});
		
		// define and apply correct width and offset
		if ( $(window).width() > bannerOriginalWidth ) {
			$(bannerBackground).css({
				'width': $(window).width(),
				'margin-top': -1 * Math.round(((($(window).width() / bannerOriginalWidth) * bannerOriginalHeight) - bannerOriginalHeight) / 2)
			});
		} else {
			$(bannerBackground).css({
				'margin-left': Math.round(($(window).width() - bannerOriginalWidth) / 2)
			});
		}

		// bind window resize
		if (bind !== false) {
			$(window).bind('resize', function () {
				applyFullWidthBanner(false);
			});
		}
	}
}

/* --- vertical align employees names --- */
function verticalAlignEmployees () {
	var employees = $('#employees');
	var employeeItem;
	
	if ( employees.length ) {
		$(employees).find('span.name').each(function () {
			employeeItem = $(this).parent();
			$(this).css('margin-top', Math.round( ( $(employeeItem).eq(0).outerHeight() - $(this).outerHeight() ) / 2 ));
		});
	}
}

/* -----LOAD JQUERY WITH LABJS------ */
/* --- load jQuery from google CDN with local fallback --- */
if (typeof(LAB) !== 'undefined') {
	LAB
		.script({ src: 'http://ajax.googleapis.com/ajax/libs/jquery/' + jQueryVersion + '/jquery.min.js', alt: javascriptPath + 'jquery-' + jQueryVersion + '.min.js', test: 'jQuery' })
		.wait(
			function () {
				debug('loaded: jquery-' + jQueryVersion + '.min.js');
			}
		)
		.wait(
			function () {
				$(document).ready(
					function () {

						var documentBody = $('body');

						callFunction(
							[
								applyTooltip,
								applyCarousel,
								addChangeListener, // used for different carousel options
								applyBlogReadmore,
								applyFancyForm,
								applyCustomDropdown,
								verticalAlignColumn,
								applyClientList,
								applyContentTabs,								
								applyPngFix,
								createCheckbox,
								applyValidation,
								applyBrowserHacks,
								applyAdGallery,
								applyStrobeMediaPlayback,
								applyNewsletterBar,
								initGoogleMaps,
								updatePortfolioFilter,
								applyFullWidthBanner,
								verticalAlignEmployees
								
							]
						);
						
						documentBody.removeClass('document-loading').addClass('document-ready');
						
						if ($.browser.safari) {
							documentBody.addClass('safari');
						} else if ($.browser.msie) {
							documentBody.addClass('msie');
						}
					}
				);
			}
		);
/* --- LAB.js unavailable --- */
} else {
	debug('ERROR: LAB.js unavailable');
}

