/**
 * /javascript/vandekolk.js
 *
 * @version 1.0
 * @package van de kolk
 * @author  R.H.A. Jesse
 * @description
 *
 * Copyright (c) BenedenBoven / Malibomba
 * IT IS NOT ALLOWED TO USE OR MODIFY ANYTHING OF
 * THIS CODE, WITHOUT THE PERMISION OF THE AUTHOR.
 */
//<![CDATA[
window.onerror = null;
$(document).ready(function() {
	/**
	 * @description: browser detection + add font declaration to any browser but ie6, ie7 and ie8:
	 ----------------------------------------------------------------------------------------------*/
	var msg = '';
	for( var i in $.browser ) {
		if( i != 'browser' && i != 'OS' &&
			i != 'version' && i != 'linux' && i != 'mac' && i != 'win' ) {
			if( $.browser[i]() == true ) {
				$('body').addClass(i);
				var $browser = i + 'v' + $.browser.version.number()
				$('body').addClass('v' + $.browser.version.number());
			}
		}
	}

	/**
	 * @description: Cycle spotlight images/text:
	 ----------------------------------------------------------------------------------------------*/
	if($('.itemContainer').length > 0) {
		$('.itemContainer').cycle( {
			fx:			'fade',
			speed:		'slow',
			timeout:	5000,
			pager:		'.slideNav',
			pause:		1
		} );
		//$('.itemContainer').cycle('pause');
	}

	/**
	 * @description: Cycle for hire/sale block:
	 ----------------------------------------------------------------------------------------------*/
	if($('.saleContainer').length > 0) {
		$('.saleContainer').cycle( {
			fx:			'fade',
			speed:		'slow',
			timeout:	5000,
			pager:		'.saleNav'
		} );
		$('.saleContainer').cycle('pause');
	}

	/**
	 * @description: Cycle the small spotlight block:
	 ----------------------------------------------------------------------------------------------*/
	if($('.spotlightContainer').length > 0) {
		$('.spotlightContainer').cycle( {
			fx:			'fade',
			speed:		'slow',
			timeout:	5000,
			pager:		'.spotlightNav'
		} );
		$('.spotlightContainer').cycle('pause');
	}

	/**
	 * @description: Cycle projects on hover:
	 ----------------------------------------------------------------------------------------------*/
	if($('.projects .project').length > 0) {
		$('.projects .project a').cycle( {
			fx:			'fade',
			speed:		'slow',
			timeout:	3000,
			slideExpr:	'img.cycleThis'
		} );
		$('.projects .project a').cycle('pause');

		$('.projects .project').hover(function() {
			$('a', $(this)).cycle('resume');
		}, function() {
			$('a', $(this)).cycle('pause');
		} );
	}

	if($('a.submit').length > 0 ) {
		$('a.submit').click(function(e) {
			$(this).parents('form').submit();
		} );
	}

	/**
	 * @description: Small plugin that allows to add an overlay to the parent item containing
	 * the title of the given element.
	 ----------------------------------------------------------------------------------------------*/
	if($('.showOverlay').length > 0 ) {
		$('.showOverlay').each(function() {
			$(this).append('<div class="overlay">' + $(this).attr('title') + '</div>');
			height = $('.overlay', $(this)).outerHeight(true);
			$('.overlay', $(this)).css({'bottom': '-' + height + 'px', 'z-index':999});
		} );

		$('.showOverlay').hover(function() {
			$('.overlay', $(this)).stop().animate( {
				'bottom' : '0px'
			} );
		}, function() {
			$('.overlay', $(this)).stop().animate( {
				'bottom' : '-' + $('.overlay', this).outerHeight(true) + 'px'
			} );
		} );
	}

	/**
	 * @description: MUST be placed right below the 'show overlay' function. This is because
	 otherwise it will not work.
	 ----------------------------------------------------------------------------------------------*/
	if($('.detailHeader .right .img').length > 0) {
		$('.detailHeader .right .img').cycle( {
			fx:			'fade',
			speed:		'slow',
			timeout:	5000,
			pager:		'.rightNav',
			slideExpr:	'a',
			pause:		1
		} );
		//$('.itemContainer').cycle('pause');
	}

	if($('.greenOverlay').length > 0 ) {
		$('.greenOverlay').each(function() {
			$(this).append('<div class="overlay">' + $(this).attr('title') + '</div>');
			height = $('.overlay', $(this)).outerHeight();
			$('.overlay', $(this)).css({'bottom': '-' + height + 'px', 'z-index':999});
			$(this).hover(function() {
				height = $('.overlay', $(this)).outerHeight();
				$('.overlay', $(this)).stop().animate( {
					'bottom' : '0px'
				} );
			}, function() {
				height = $('.overlay', $(this)).outerHeight();
				$('.overlay', $(this)).stop().animate( {
					'bottom' : '-' + height + 'px'
				} );
			} );
		} )
	}

	/**
	 * @description: Add grayscale to images with the class 'grayscale': Disabled: 8-11-2011
	 ----------------------------------------------------------------------------------------------
	$('.grayscale .image').pixastic('desaturate');
	$('.grayscale').live( {
		mouseover: function() {
			Pixastic.revert($(this).find('.image').get(0));
		},
		mouseout: function() {
			if(!/activeImage/.test($(this).attr('class')) ) {
				$('.grayscale:not(.activeImage) .image').pixastic('desaturate');
			}
		}
	} );
	*/

	$('.overlay').click(function(e) {
		window.location = $(this).parent('a').attr('href').replace(/#/, '');
	} );

	var cache = {};
	$('.peopleDetail').click(function(e) {
		e.preventDefault();
		$('.peopleDetail').removeClass('activeImage');
		$(this).addClass('activeImage');
		var slug = $(this).attr('rel');
		if($('.profileInformation').length > 0) {
			if(!cache[slug]) {
				$.ajax( {
					'url': '/over-ons/onze-mensen/' + $(this).attr('rel') + '.html',
					'dataType':'json',
					'contentType':'application/jsonrequest',
					'success': function(json) {
						cache[json.slug] = [];
						var html = [
							'<h2>' + json.name + '</h2>',
							'<h3>' + json.functie + '</h3>',
							'<div class="p">',
								'<p>',
									json.description,
								'</p>',
							'<\/div>'
						].join("");
						$('.profileInformation').html(html);
						cache[json.slug].push(html);
						//Cufon.refresh();
						Cufon.set('fontFamily', 'Dax bold');
						Cufon.replace('.profileInformation h2');
						Cufon.replace('.profileInformation h3');
					}
				} );
			} else {
				$('.profileInformation').html(cache[slug][0]);
				Cufon.set('fontFamily', 'Dax bold');
				Cufon.replace('.profileInformation h2');
				Cufon.replace('.profileInformation h3');
			}
		}

	} );

	/**
	 * @description: Make sure fields are required when asking for company brochure:
	 ----------------------------------------------------------------------------------------------*/
	if($('#brochure').length > 0 ) {
		$('.response').change(function() {
			if($(this).val() == 'mij de bedrijfsbrochure toestuurt') {
				$('#address').attr('class', 'validate[required] textField');
				$('#zipcode').attr('class', 'validate[required] zipField textField');
				$('.address').html($('.address').html() + '*');
				$('.zipcode').html($('.zipcode').html() + '*');
			} else {
				$('.address').html($('.address').html().replace('\*', ''));
				$('.zipcode').html($('.zipcode').html().replace('\*', ''));
				$('#address').attr('class', 'textField');
				$('#zipcode').attr('class', 'zipField textField');
			}
		} );
	}

	/**
	 * @description: Make sure selectboxes are selected once clicked in the menu.
	 * Add functionality to the checkboxes.
	 ----------------------------------------------------------------------------------------------*/
	if($('.selectStatus').length > 0 ) {
		$('.selectBox').click(function(e) {
			e.preventDefault();
			if(($('.selectStatus').attr('disabled') !== true ) || ( $(this).find('input').hasClass('eigen-ontwikkeling') || $(this).find('input').hasClass('te-koop') || $(this).find('input').hasClass('te-huur') )) {
				var bool = ($('.selectStatus#' + $(this).attr('rel')).attr('checked') === true) ? false : true;
				$('.selectStatus').attr('disabled', true);
				$('.selectActivity').attr('disabled', true);
				$('.selectStatus.' + $(this).attr('rel')).attr('checked', bool);

				var href = $(this).attr('href');
				$.ajax( {
					type: 'POST',
					cache: false,
					data: 'ajax=true',
					url: href,
					success: function(data){
						if(data == 'true') {
							window.location = '/projecten.html';
						}
					}
				} );
			}
		} );
	}

	/**
	 * @description: Make sure checkboxes are selected once clicked (anywhere).
	 * Add functionality to the checkboxes.
	 ----------------------------------------------------------------------------------------------*/
	if($('.selectActivity').length > 0 ) {
		$('.selectActivityBox').click(function(e) {
			e.preventDefault();
			if($('.selectActivity').attr('disabled') !== true) {
				var bool = ($('.selectActivity#' + $(this).attr('rel')).attr('checked') === true) ? false : true;
				$('.selectActivity').attr('disabled', true);
				$('.selectStatus').attr('disabled', true);
				$('.selectActivity.' + $(this).attr('rel')).attr('checked', bool);

				var href = $(this).attr('href');
				$.ajax( {
					type: 'POST',
					cache: false,
					data: 'ajax=true',
					url: href,
					success: function(data){
						if(data == 'true') {
							window.location = '/projecten.html';
						}
					}
				} );
			}
		} );
	}

	/**
	 * @description: Delay the click event for iPad/iPhone/iPod users:
	 ----------------------------------------------------------------------------------------------*/
	$('.projectClick').click(function(e) {
		if( isiPhone() ) {
			var $this = $(this);
			e.preventDefault();
			setTimeout(function() {
				window.location = $this.attr('href');
			}, 3000 );
		}
	} );


	/**
	 * @description: Add change event to the selectbox on project pages to filter out different
	 * activites.
	 ----------------------------------------------------------------------------------------------*/
	if($('.selectCategory').length > 0 ) {
		$('.selectCategory').change(function() {
			if((/\/projecten/).test(window.location.href)) {
				if($(this).attr('value') != 'showAll') {
					var exceptions = [];
					$('.selectCategory option').each(function() {
						exceptions.push($(this).attr('value'));
					} );
					var uri = window.location.href.replace(/\.html.*$/, '');
					uri = uri.split('/');
					if(uri.length > 5) {
						var i = range(5, (uri.length));
						uri.splice(parseInt(i.join(',')));
					}
					for(var i = 0; i < uri.length; i++) {
						if(in_array(uri[i], exceptions) ) {
							uri.splice(i);
						}
					}
					uri = uri.join('/');
					window.location = uri + '/' + $(this).attr('value') + '.html';
				} else {
					window.location = '/projecten.html';
				}
			}
		} );

		var uri = window.location.href;
		uri     = uri.split('/');
		if(uri.length > 4) {
			var slug = uri[uri.length -1].replace(/\.html/, '');
			$('.selectCategory option').each(function() {
				if($(this).attr('value') == slug) {
					$(this).attr('selected', true);
				}
			} );
		}
	}

	/**
	 * @description: Pretty select box:
	 ----------------------------------------------------------------------------------------------*/
	$("select.selectCategory").selectBox();

	/**
	 * @description: Initialize lightbox and add event to where rel == lightbox.
	 ----------------------------------------------------------------------------------------------*/
	$("a[rel^='lightbox']").prettyPhoto( {animationSpeed:'slow', theme:'facebook', slideshow:6000, autoplay_slideshow: false, deeplinking: false, show_description:false} );

	/**
	 * @description: Initialize validation engine:
	 ----------------------------------------------------------------------------------------------*/
	$(".contactForm").validationEngine( {
		inlineValidation:false,
		ajaxSubmit: true,
		ajaxSubmitFile: "/contact.html",
		ajaxSubmitMessage: 'Bedankt voor uw bericht. Wij nemen zo snel mogelijk contact met u op.',
		success :  function() {},
		failure : function() {}
	} );

	$(".quickSend").validationEngine( {
		inlineValidation:true,
		ajaxSubmit: true,
		ajaxSubmitFile: "/contact.html",
		ajaxSubmitMessage: 'Bedankt voor uw bericht. Wij nemen zo snel mogelijk contact met u op.',
		success :  function() {},
		failure : function() {}
	} );

	$(".tellafriend").validationEngine( {
		inlineValidation:true,
		ajaxSubmit: true,
		ajaxSubmitFile: "/tellafriend.html",
		ajaxSubmitMessage: 'U heeft deze pagina succesvol gedeeld. Klik rechtsboven op het kruisje om deze pop-up te sluiten.',
		success :  function() {},
		failure : function() {}
	} );

	$(".requestKolkreport").validationEngine( {
		inlineValidation:true,
		ajaxSubmit: true,
		ajaxSubmitFile: "/kolk-report-aanvragen.html",
		ajaxSubmitMessage: 'Uw aanvraag is verzonden. U kunt dit venster sluiten door rechtsbovenin op het kruisje te klikken.',
		success :  function() {},
		failure : function() {}
	} );

	$(".search").validationEngine( {
		inlineValidation:true,
		ajaxSubmit: false,
		promptPosition:'bottomLeft',
		success :  function() {},
		failure : function() {}
	} );

	/**
	 * @description: Sub menus for iPad and iPhone:
	 ----------------------------------------------------------------------------------------------*/
	if($('#lc-navigation #menu a').length > 0) {
		$('#lc-navigation #menu a').click(function() {
			if(/#/.test($(this).attr('href'))) {
				return false;
			}
		} );
	}

	/**
	 * @description: Blank textfield on focus, restore it to the default value on blur:
	 ----------------------------------------------------------------------------------------------*/
	 if($('.sField').length > 0 ) {
		$('.sField').focus(function() {
			$(this).addClass("focusField");
			if (this.value == this.defaultValue){
				this.value = '';
			}
			if(this.value != this.defaultValue){
				this.select();
			}
		} );
		$('.sField').blur(function() {
			$(this).removeClass("focusField");
			if(this.value == '' ) {
				setTimeout(function() {
					$.validationEngine.closePrompt('.formError', true);
				}, 1500);
				this.value = (this.defaultValue ? this.defaultValue : '');
			}
		} );
	}

} );

/**
 * @description: Helper functions:
 --------------------------------------------------------------------------------------------------*/
function range (low, high, step) {
	// Create an array containing the range of integers or characters from low to high (inclusive)
	//
	// version: 1103.1210
	// discuss at: http://phpjs.org/functions/range    // +   original by: Waldo Malqui Silva
	var matrix = [];    var inival, endval, plus;
	var walker = step || 1;
	var chars = false;

	if (!isNaN(low) && !isNaN(high)) {        inival = low;
		endval = high;
	} else if (isNaN(low) && isNaN(high)) {
		chars = true;
		inival = low.charCodeAt(0);        endval = high.charCodeAt(0);
	} else {
		inival = (isNaN(low) ? 0 : low);
		endval = (isNaN(high) ? 0 : high);
	}
	plus = ((inival > endval) ? false : true);
	if (plus) {
		while (inival <= endval) {
			matrix.push(((chars) ? String.fromCharCode(inival) : inival));            inival += walker;
		}
	} else {
		while (inival >= endval) {
			matrix.push(((chars) ? String.fromCharCode(inival) : inival));            inival -= walker;
		}
	}
	return matrix;
}

function in_array( needle, haystack){
	var r = false;
	for(var i = 0; i < haystack.length; i++){
		if ( needle == haystack[i] ) {
			r = true;
			break;
		}
	}
	return r;
}

function isiPhone(){
	return (
		(navigator.platform.indexOf("iPhone") != -1) ||
		(navigator.platform.indexOf("iPad") != -1) ||
		(navigator.platform.indexOf("iPod") != -1)
	);
}


function initialize() {
	$(".contactForm").validationEngine( {
		inlineValidation:true,
		ajaxSubmit: true,
		ajaxSubmitFile: "/contact.html",
		ajaxSubmitMessage: 'Bedankt voor uw bericht. Wij nemen zo snel mogelijk contact met u op.',
		success :  function() {},
		failure : function() {}
	} );
}
//]]>
