$(document).ready( function() {
	$('#contactform .required').blur(function(){
		if($(this).val() !== ''){
			var inputVal = $(this).val();
			var inputId = $(this).attr('id');
			$(this).removeClass('correct').addClass('error');
			if(inputId==='email'){
				var regExMail = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
				if(!regExMail.test(inputVal)){ return false; }
			} else if(inputId==='phone' || inputId==='fax'){
				var regExPhone = /^((((0031)|(\+31))(\-)?6(\-)?[0-9]{8})|(06(\-)?[0-9]{8})|(((0031)|(\+31))(\-)?[1-9]{1}(([0-9](\-)?[0-9]{7})|([0-9]{2}(\-)?[0-9]{6})))|([0]{1}[1-9]{1}(([0-9](\-)?[0-9]{7})|([0-9]{2}(\-)?[0-9]{6}))))$/;
				if(!regExPhone.test(inputVal)){ return false; }
			} else if(inputId==='postcode'){
				var regExPostcode = /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/;
				if(!regExPostcode.test(inputVal)){ return false; }
			} else if(inputId==='huisnummer'){
				var regExHuisnummer = /^([0-9]){1,}([A-Z]){0,3}/;
				if(!regExHuisnummer.test(inputVal)){ return false; }
			} else {}
			$(this).removeClass('error').addClass('correct');
		} else {
			$(this).removeClass('correct').addClass('error');
		}
	});
	
// Contact submit
	$("#contactsubmit").click( function() {
		var allRequiredFilled = 'check';
		$('#contactform .required').each( function() {
			if($(this).val()==='') {
				$(this).removeClass('correct').addClass('error');
				allRequiredFilled = 'error';
			}
		});
		if($('#contactform .error').length > 0 || allRequiredFilled === 'error' || $('#contactform #checkbox.verplicht').length > 0 && $('#contactform #checkbox.verplicht').attr('checked')!=='checked') {
			if($('#contactform #checkbox.verplicht').length > 0 && $('#contactform #checkbox.verplicht').attr('checked')!=='checked'){
				$('label[for="checkbox"]').addClass('error');
				$('#contactform #checkbox.verplicht').click(function(){
					if ($(this).is(':checked')){
						$('label[for="checkbox"]').removeClass('error');
						$(this).removeClass('error').addClass('correct');
					}
				});
			} else {
				$('label[for="checkbox"]').removeClass('error');
			}
		} else {
			$('#contactform .loading').show();
			var values = $("#contactformulier").serialize();
			$.ajax({
				url: '/formprocess.php?submit=true',
				type: 'POST',
				data: values,

				success: function(result) {
					$('#contactform').append('<p id="response">' + result + '</p>');
					$('#response').hide();
					$('#contactformulier').fadeOut('normal', function() {
						$('#response').fadeIn('normal');
					});
				}
			});
		}
		return false;
	});
	
	$('.dienstImage img').click(function(){
		var elem = $('#overlayContainer img');
		var imgSrc = $(this).attr('src');
		var imgCat = $(this).closest('.dienstImages').attr('rel');
		var nrOfImagesInCat = $(this).closest('.dienstImages').find('img').length;
		var imgNr = $(this).attr('name');
		$('#overlay').fadeIn();
		$(elem).attr({'src':imgSrc,'name':imgNr});
		$('#overlayContainer').fadeIn('normal',function(){
			if(imgNr*1 != '1'){ $('#overlayContainer .arrowLeft:hidden').fadeIn();}
			if(imgNr*1 != nrOfImagesInCat){ $('#overlayContainer .arrowRight:hidden').fadeIn(); }
			$('#overlay, #overlayContainer img').click(function(){
				overlayClose();
			});
			
			$('#overlayContainer .arrowRight').click(function(){
				$('#overlayContainer .arrowLeft:hidden').fadeIn();
				var shownImgNr = $(elem).attr('name');
				$(elem).fadeOut('normal',function(){
					var imgSrc = $('.dienstImages[rel="' + imgCat + '"] img[name="' + (shownImgNr*1+1) + '"]').attr('src');
					$(elem).attr({'src':imgSrc,'name':(shownImgNr*1+1)}).fadeIn();
					if((shownImgNr*1+1) == nrOfImagesInCat){ $('#overlayContainer .arrowRight').fadeOut(); }
				});
			});
			
			$('#overlayContainer .arrowLeft').click(function(){
				$('#overlayContainer .arrowRight:hidden').fadeIn();
				var shownImgNr = $(elem).attr('name');
				$(elem).fadeOut('normal',function(){
					var imgSrc = $('.dienstImages[rel="' + imgCat + '"] img[name="' + (shownImgNr*1-1) + '"]').attr('src');
					$(elem).attr({'src':imgSrc,'name':(shownImgNr*1-1)}).fadeIn();
					if((shownImgNr*1-1) == '1'){ $('#overlayContainer .arrowLeft').fadeOut(); }
				});
			});
			
		});
	});
});

function popUp(url) {
	window.open(url,'','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=400,left=400,top=150');
}

function home(){
	$('.tweetContainer').tweet5('.tweetContainer', {
		username : 'p5design',
		numberOfTweets : 3, // 20=max
		showUsername : 'false',
		showUserAvatar : 'false',
		showTweetTime : 'true',
		showReplyButton : 'true',
		showRetweetButton : 'true',
		showLocation : 'false',
		altPath : '/'
	});
	
	$('.grayBar.twitter').hover(function(){
		$(this).addClass('over');
	},function(){
		$(this).removeClass('over');
	});
}

function about(){
	$(".slideable .imageContainer").mousemove(function(event) {
		var elem = $(this);
		var elemWidth = elem.width();
		var imgWidth = elem.find('img').width();
		var slideWidth = (imgWidth - elemWidth) / elemWidth;
		var offset = elem.offset();
		var position = event.pageX;
		var imgPosition = slideWidth * (position-offset.left);
		elem.find('img').css('left','-' + imgPosition + 'px');
	});
	$('a.mail').each(function() {
		e = this.rel.replace('#/#', '@');
		this.href = 'mailto:' + e;
	});
}

function portfolio(){
	$('#overlay').click(function(){
		overlayClose();
	});
	
	$('.portfolio .blok img').each(function() {
		var image = $(this);
		var filename = image.attr('rel');
		image.load(function() {
			image.fadeIn(600);
		}).attr('src', filename);
	});
}

function contact(){
	$('a.mail').each(function() {
		e = this.rel.replace('#/#', '@');
		this.href = 'mailto:' + e;
	});
	function initialize() {
		var mapDiv = document.getElementById('map-canvas');
		var map = new google.maps.Map(mapDiv, {
			center: new google.maps.LatLng(51.90904,4.501461),
			zoom: 15,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl: true,
			mapTypeControlOptions: {
				style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
			},
			navigationControl: true,
			navigationControlOptions: {
				style: google.maps.NavigationControlStyle.SMALL
			}
		});
		var marker = new google.maps.Marker({
			map: map,
			position: map.getCenter(),
			draggable: false
		});
	}
	google.maps.event.addDomListener(window,'load', initialize);
}

function portfolioItem(id){
	$('#overlay').fadeIn();
	$('#overlayContainer').load('/portfolioOverlay.php?id=' + id).fadeIn("normal",function(){
		$('#overlayShare').click(function(){
			$(this).slideUp('normal',function(){
				$('.socialBox .socials').fadeIn();
			});
		});
	});
}

function makeMeBig(elem){
	var targetImg = $('.blok.portfolioImg img');
	var imgSrc = $(elem).find('img').attr('src');
	$(targetImg).fadeOut('normal',function(){
		$(targetImg).attr('src',imgSrc).fadeIn();
	});
}

function overlayClose(){
	$('#overlay').fadeOut();
	$('#overlayContainer').fadeOut();
}

var tweet = 1;
function tweetSlider(val){
	$('ul.bullets li').removeClass('active');
	var slideDelay = 5000;
	var animationTime = 500;
	var elem = $('.tweetContainer');
	if($('.grayBar.twitter').hasClass('over')){
		setTimeout('tweetSlider()',slideDelay);
	} else {
		if(val == 'load'){
			var tweetid = $('.singleTweet:nth-child(' + tweet + ')').attr('rel');
			$('ul.bullets li:nth-child(' + tweet + ')').addClass('active');
			$('.tweetTime').text($('.singleTweet:nth-child(' + tweet + ')').attr('name'));
			$('a.replyButton').attr('onclick','popUp(\'http://twitter.com/intent/tweet?in_reply_to=' + tweetid + '\')');
			$('a.retweetButton').attr('onclick','popUp(\'http://twitter.com/intent/retweet?tweet_id=' + tweetid + '\')');
			setTimeout('tweetSlider()',slideDelay);
		} else {
			if(tweet == 3){
				elem.animate({'top':0},animationTime,function(){
					tweet = 1;
					$('ul.bullets li:nth-child(' + tweet + ')').addClass('active');
					var tweetid = $('.singleTweet:nth-child(' + tweet + ')').attr('rel');
					$('.tweetTime').text($('.singleTweet:nth-child(' + tweet + ')').attr('name'));
					$('a.replyButton').attr('onclick','popUp(\'http://twitter.com/intent/tweet?in_reply_to=' + tweetid + '\')');
					$('a.retweetButton').attr('onclick','popUp(\'http://twitter.com/intent/retweet?tweet_id=' + tweetid + '\')');
					setTimeout('tweetSlider()',slideDelay);
				});
			} else {
				elem.animate({'top':'-=34px'},animationTime,function(){
					tweet++;
					$('ul.bullets li:nth-child(' + tweet + ')').addClass('active');
					var tweetid = $('.singleTweet:nth-child(' + tweet + ')').attr('rel');
					$('.tweetTime').text($('.singleTweet:nth-child(' + tweet + ')').attr('name'));
					$('a.replyButton').attr('onclick','popUp(\'http://twitter.com/intent/tweet?in_reply_to=' + tweetid + '\')');
					$('a.retweetButton').attr('onclick','popUp(\'http://twitter.com/intent/retweet?tweet_id=' + tweetid + '\')');
					setTimeout('tweetSlider()',slideDelay);
				});
			}
		}
	}
	
}

function goBackContact(){
	$("#response").remove();
	$("#contactformulier").show();
}

// Placeholder-support
(function($) {
	// Return if native support is available.
	if ("placeholder" in document.createElement("input")) return;

	$(document).ready(function(){
		$(':input[placeholder]').not(':password').each(function() {
			setupPlaceholder($(this));
		});

		$(':password[placeholder]').each(function() {
			setupPasswords($(this));
		});

		$('form').submit(function(e) {
			clearPlaceholdersBeforeSubmit($(this));
		});
	});

	function setupPlaceholder(input) {

		var placeholderText = input.attr('placeholder');

		setPlaceholderOrFlagChanged(input, placeholderText);
		input.focus(function(e) {
			if (input.data('changed') === true) return;
			if (input.val() === placeholderText) input.val('');
		}).blur(function(e) {
			if (input.val() === '') input.val(placeholderText); 
		}).change(function(e) {
			input.data('changed', input.val() !== '');
		});
	}

	function setPlaceholderOrFlagChanged(input, text) {
		(input.val() === '') ? input.val(text) : input.data('changed', true);
	}

	function setupPasswords(input) {
		var passwordPlaceholder = createPasswordPlaceholder(input);
		input.after(passwordPlaceholder);

		(input.val() === '') ? input.hide() : passwordPlaceholder.hide();

		$(input).blur(function(e) {
			if (input.val() !== '') return;
			input.hide();
			passwordPlaceholder.show();
		});

		$(passwordPlaceholder).focus(function(e) {
			input.show().focus();
			passwordPlaceholder.hide();
		});
	}

	function createPasswordPlaceholder(input) {
		return $('<input>').attr({
			placeholder: input.attr('placeholder'),
			value: input.attr('placeholder'),
			id: input.attr('id'),
			readonly: true
		}).addClass(input.attr('class'));
	}

	function clearPlaceholdersBeforeSubmit(form) {
		form.find(':input[placeholder]').each(function() {
			if ($(this).data('changed') === true) return;
			if ($(this).val() === $(this).attr('placeholder')) $(this).val('');
		});
	}
})(jQuery);
