(function($) {

function smoothAnchors(offset, beforeScroll, afterScroll) {
	var offset = offset || 0;
	var beforeScroll = beforeScroll || function() { void(0) }
	var afterScroll = afterScroll || function() { void(0) }
	var speed = 400;
	$('a[href*=#]').bind('click', function(event) {
		event.preventDefault();
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var h = this.hash;
			var $target = $(this.hash);
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
				//beforeScroll();
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset - offset}, speed, function(){
					if (history && history.pushState) {
						history.pushState(null, null, h);
					} else {
						location.hash = h;
					}
					//afterScroll();
				});
			}
		}
	});
}



function formValidation() {

	var $the_form = $('#contact form');
	var textarea = $the_form.find('textarea').eq(0);
	$('#formajax').attr('value', '1');

	$the_form.submit(function(e){
		e.preventDefault();
		var url = this.action;
		// create message container
		if ($('#message').length < 1) {
			$the_form.find('fieldset').append(
				$('<p/>').attr('id', 'message').hide()
			);
		}
		// do the post request
		$.ajax({
			url: url,
			type: 'POST',
			data: "formcontact=" + textarea.attr('value') + "&formajax=" + $('#formajax').attr('value') + "&formcheck=" + $('#formcheck').attr('value'),
			error: function(data, txt) {
				error(data.status + ' ' + txt);
			},
			success: function(data) {
				var $data = $(data);
				var err = $data.find('error').text();
				var message = $data.find('message').text();
				if (err == '0') {
					$('#message').attr('class', 'success').html(message).fadeIn(250);
					textarea.attr('value', '');
				} else {
					error(message);
				}
			}
		});
	});

	// handle errors
	var error = function(text) {
		var $el = $the_form.find('fieldset');
		$el.animate({
			opacity: 0
		}, 100,	function() {
			$el.animate({
				opacity: 1
			}, 100);
			$('#message').attr('class', 'error').html(text).fadeIn(250);
			textarea.focus();
		});		
	}

}



function showcase() {
	$('#showcase ul').after('<p id="showcase-nav">').cycle({
		fx: 'scrollHorz', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		speed: 500, 
		timeout: 0,
		pager:  '#showcase-nav',
		pagerAnchorBuilder: function(idx, slide) {
			return '<a href="#" title="' + $(slide).find('h3').eq(0).text() + '">' + (idx+1) + '</a>';
		}
	});
	$('#showcase-nav').append(
		$('<a/>').html('&larr;').attr({
			id: 'showcase-prev',
			title: 'Vorige',
			href: '#'
		}).bind('click', function(e){
			e.preventDefault();
			$('#showcase ul').cycle('prev');
		})
	).append(
		$('<a/>').html('&rarr;').attr({
			id: 'showcase-next',
			title: 'Volgende',
			href: '#'
		}).bind('click', function(e){
			e.preventDefault();
			$('#showcase ul').cycle('next');
		})
	);
	$('#showcase ul').swipe({
		swipeLeft: function() { $('#showcase ul').cycle('next') },
		swipeRight: function() { $('#showcase ul').cycle('prev') }
	});
	catchKeys($('#showcase'), Array(
		Array(37, function(){ $('#showcase ul').cycle('prev') }), // left: previous
		Array(39, function(){ $('#showcase ul').cycle('next') }) // right: next
	));
	setTimeout(function(){
		$('#showcase li').each(function(){
			if ($(this).height() > $('#showcase ul').height() - 16)
				$('#showcase ul').height($(this).height() + 16);
		});
	}, 100); // for Webkit: resize after Google WebFont has rendered
}



$.fn.cinbox=function(options){

	var defaults = {
		container: $('body'),
		speed: 250
	}
	var settings = $.extend(defaults, options);

	var cinboxElements = this;
	var currentElement = null;
	var borderWidth = 0;

	$(this).bind('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		currentElement = cinboxElements.index(this);
		this.blur();
		cinboxOpen(this.href, this.title, $(this.parentNode).find('p').html());
	});

	var cinboxOpen = function(href, title, text) {
		settings.container.append(
			$('<div id="cinbox"/>').css({
				position: 'absolute',
				overflow: 'hidden',
				zIndex: 999999
			}).append(
				$('<div id="cinboxTitle"/>').text(title).css({
					paddingRight: '16em'
				})
			).append(
				$('<a id="cinboxClose"/>').css({
					position: 'absolute',
					right: 0,
					top: 0,
					cursor: 'pointer'
				}).text('X').bind('click', function(){
					cinboxClose();
				})
			).append(
				$('<div id="cinboxNav"/>').css({
					position: 'absolute',
					right: '2em',
					top: 0
				}).append(
					$('<span id="cinboxNav_counter"/>').html('(<span id="cinboxNav_counter_current">' + (currentElement+1) + '</span>/' + cinboxElements.length + ')').css({
						marginRight: '1em'
					})
				).append(
					$('<a id="cinboxNav_prev"/>').text('< vorige').css({ cursor: 'pointer' }).bind('click', function(event){
						event.preventDefault();
						event.stopPropagation();
						gotoSlide(currentElement - 1, 1);
					})
				).append(
					$('<a id="cinboxNav_next"/>').text('volgende >').css({ cursor: 'pointer' }).bind('click', function(event){
						event.preventDefault();
						event.stopPropagation();
						gotoSlide(currentElement + 1, -1);
					})
				)
			).append(
				$('<div id="cinboxContent"/>').css({
					position: 'relative'
				}).append(
					$('<div id="cinboxText"/>').css({
						position: 'absolute',
						left: '-320px',
						width: '240px'
					})
				)
			)
		);
		borderWidth = $('#cinbox').css('borderLeftWidth').replace('px', '') * 1 + $('#cinboxContent').css('borderLeftWidth').replace('px', '') * 1;
		$('#cinbox').css({
			left: $(window).width() / 2 - ($('#cinbox').width() + borderWidth*2) / 2,
			top: $(window).scrollTop() + $(window).height() / 2 - ($('#cinbox').height() + borderWidth*2) / 2
		});
		catchKeys(document, Array(
			Array(37, function(){ gotoSlide(currentElement - 1, 1) }), // left: previous
			Array(39, function(){ gotoSlide(currentElement + 1, -1) }), // right: next
			Array(27, function(){ cinboxClose() }) // escape: close
		));
		$("#cinbox").swipe({
		     swipeLeft: function() { gotoSlide(currentElement + 1, -1) },
		     swipeRight: function() { gotoSlide(currentElement - 1, 1) }
		}).hover(function(){
			$('#cinboxText').animate({ left: 0 }, 250)
		}, function(){
			$('#cinboxText').animate({ left: '-320px' }, 250)
		});
		loadContent(href, title, null, text);
		$('body, nav a, #nav a').bind('click', function(){
			cinboxClose();
		});
	}

	var gotoSlide = function(slide, direction) {
		//alert(slide);
		//alert(direction);
		var direction = direction || -1;
		if (slide >= cinboxElements.length) {
			slide = 0;
		} else if (slide < 0) {
			slide = cinboxElements.length - 1;
		}
		currentElement = slide;
		loadContent(cinboxElements[slide].href, cinboxElements[slide].title, direction, $(cinboxElements[slide].parentNode).find('p').html());
	}

	var cinboxClose = function() {
		$('body, nav a, #nav a').unbind('click', cinboxClose);
		$('#cinbox').remove();
	}

	var loadContent = function(href, title, direction, text) {
		$('#cinboxText').css('visibility', 'hidden');
		var loadNew = function() {
			var throb = new throbber(document.getElementById('cinboxContent'));
			throb.on();
			var img = new Image();
			var max_width = $(window).width() - borderWidth*2 - 40;
			var max_height = $(window).height() - borderWidth*2 - 120;
			img.onload = function () {
				$(img).css({
					display: 'none',
					position: 'absolute'
				}).addClass('cinboxImage');
				setResize = function () {
					img.height -= img.height * percent;
					img.width -= img.width * percent;	
				};
				if (img.width > max_width) {
					percent = (img.width - max_width) / img.width;
					setResize();
				}
				if (img.height > max_height) {
					percent = (img.height - max_height) / img.height;
					setResize();
				}
				$('#cinboxContent').append($(img));
				$('#cinbox').animate({
					left: $(window).width() / 2 - ($(img).width() + borderWidth*2) / 2,
					top: $(window).scrollTop() + $(window).height() / 2 - ($(img).height() + borderWidth*2) / 2
				}, settings.speed, function(){
					$('#cinboxContent').animate({
						width: $(img).width(),
						height: $(img).height()
					}, settings.speed, function() {
						throb.off();
						$('#cinboxTitle').text(title);
						$('#cinboxText').css({
							visibility: 'visible',
							height: $('#cinbox').height() - 81
						}).html(text);
						$('#cinboxNav_counter_current').text(currentElement+1);
						$(img).css({
							display: 'block',
							opacity: 0
						}).animate({
							opacity: 1
						}, settings.speed*2);
					});
				});
			}
			setTimeout(function(){
				img.src = href;
			}, 1);
		}
		var images = $('#cinboxContent img');
		if (images.length > 0) {
			images.animate({
				left: ($('#cinbox').width()) * direction
			}, settings.speed*1.5, 'linear', function(){
				$(this).remove();
				loadNew();
			});
		} else {
			loadNew();
		}
	}

}



var throbber = function(el) {

	this.state = false;
	this.overlay = null;

	this.on = function() {
		this.state = true;
		this.overlay = $('<div/>').css({
			position: 'absolute',
			left: '0',
			top: '0',
			width: '100%',
			height: '100%',
			background: 'transparent url(/img/throbber.gif) center center no-repeat',
			opacity: '0.75'
		});
		$(el).append(this.overlay);
	}

	this.off = function() {
		this.state = false;
		this.overlay.remove()
	}
	
}



$.fn.cinAccordion = function(options){

	// default variables
	var $accordions = $(this);
	var defaults = {
		tabs: 'h3',
		tabWidth: 20,
		activeTab: 0,
		speed: 250,
		offset: 15
	}
	var settings = $.extend(defaults, options);
	var oldHTML = Array();

	$accordions.each(function(){

		oldHTML[oldHTML.length] = $(this).html();

		var $slides = $(this).children();
		var activeTab = defaults.activeTab;
		var slideWidth = $(this).width() - ($slides.length-1) * settings.tabWidth - $slides.css('border-left-width').replace('px', '') - $slides.css('border-right-width').replace('px', '');

		// initialize accordion
		var h = 0;
		$slides.eq(activeTab).addClass('active');
		$slides.find(defaults.tabs).each(function(i){
			$(this).css({
				position: 'absolute'
			}).text((i+1) + '. ' + $(this).text());
			if ($(this).width() > h)
				h = $(this).width();
		});
		h += 20; // for padding
		var accesskeys = Array();
		$slides.each(function(i){
			accesskeys[i] = Array((49+i), function(){ loadSlide(i) });
			$(this).html('<div class="accordion-content">' + $(this).html() + '</div>');
			$(this).css({
				position: 'absolute',
				left: $slides.index(this) * defaults.tabWidth + slideWidth - defaults.tabWidth,
				width: slideWidth - defaults.tabWidth,
				paddingLeft: +(defaults.tabWidth),
				paddingRight: 0,
				paddingTop: 0,
				paddingBottom: 0,
				overflow: 'hidden',
				listStyleType: 'none'
			});
			if ($slides.index(this) <= activeTab) {
				$(this).css({
					left: $slides.index(this) * defaults.tabWidth
				});
			}
			if ($(this).height() > h)
				h = $(this).height();
		});
		h += defaults.offset;

		// keyboard & swiping navigation
		catchKeys(document, accesskeys);
		catchKeys($(this), Array(
			Array(37, function() { if (activeTab > 0) loadSlide(activeTab - 1) }), // left: previous
			Array(39, function() { if (activeTab < $slides.length-1) loadSlide(activeTab + 1) }) // right: next
		));
		$(this).swipe({
			swipeLeft: function() { if (activeTab < $slides.length-1) loadSlide(activeTab + 1) },
			swipeRight: function() { if (activeTab > 0) loadSlide(activeTab - 1) }
		});

		// load Nth slide
		var loadSlide = function(n) {
			$slides.eq(activeTab).removeClass('active');
			activeTab = n;
			$slides.eq(n).addClass('active');
			$slides.each(function(){
				if ($slides.index(this) <= activeTab) {
					$(this).animate({
						left: $slides.index(this) * defaults.tabWidth
					}, defaults.speed);
				} else {
					$(this).animate({
						left: $slides.index(this) * defaults.tabWidth + slideWidth - defaults.tabWidth
					}, defaults.speed);
				}
			});
		}

		// tabs
		$slides.each(function(){
			var $slide = $(this);
			$slide.find(defaults.tabs).each(function(){
				if (document.all) { // IE
					$(this).css({
						left: 0,
						top: 0,
						filter: 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)'
					});
				} else { // other browsers
					$(this).css({
						left: -h/2 + defaults.tabWidth/2,
						top: h/2 - defaults.tabWidth/2,
						transform: 'rotate(90deg)',
						WebkitTransform: 'rotate(90deg)',
						OTransform: 'rotate(90deg)',
						MozTransform: 'rotate(90deg)'
					});
				}
				$(this).css({
					width: h,
					height: defaults.tabWidth,
					cursor: 'pointer'
				});
				var html = $(this).html();
				$(this).html('').append(
					$('<a href="#" class="accordion-tab" />').html(html).bind('click', function(e){
						e.preventDefault();
						loadSlide($slides.index($slide));
					})
				);
			});
		});

		$(this).css({
			position: 'relative',
			overflow: 'hidden',
			height: h + $slides.css('border-top-width').replace('px', '')*1 + $slides.css('border-bottom-width').replace('px', '')*1
		});
		$slides.css({
			height: h
		});

		// open slide when clicking on anchor link
		$('a[href*=#]').bind('click', function() {
			if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
				var index = $slides.index($(this.hash));
				if (index > -1) {
					loadSlide(index);
				}
			}
		});

	});

	$(window).bind('orientationchange', function(){
		$accordions.each(function(i){
			$(this).html(oldHTML[i]).cinAccordion(options);
		});
	});

	return oldHTML;

}



var tweets = function() {
	var fade_speed = 2000;
	var speed = 6000;
	$('#tweets').hide();
	setTimeout(function(){
		$('#tweets').fadeIn(fade_speed).cycle({ 
			fx: 'fade',
			speed: fade_speed,
			timeout: speed,
			random: 1,
			pause: 1
		});
	}, speed);
}



var scrollFX = function() {

	var viewportHeight = $(window).height();
	var $intro    = $('#intro div.inner');
	var $websites = $('#werk div.inner');
	var $proces   = $('#proces div.inner');
	var $wie      = $('#wie div.inner');
	var $footer   = $('footer div.inner');
	var $sections = $intro.add($websites).add($proces).add($wie).add($footer);
	if ($sections.length < 5) return false;
	var introTop    = $intro.offset().top;
	var websitesTop = $websites.offset().top;
	var procesTop   = $proces.offset().top;
	var wieTop      = $wie.offset().top;
	var footerTop   = $footer.offset().top;
	var introHeight    = $intro.height() + parseInt($intro.css('paddingTop')) + parseInt($intro.css('paddingBottom'));
	var websitesHeight = $websites.height() + parseInt($websites.css('paddingTop')) + parseInt($websites.css('paddingBottom'));
	var procesHeight   = $proces.height() + parseInt($proces.css('paddingTop')) + parseInt($proces.css('paddingBottom'));
	var wieHeight      = $wie.height() + parseInt($wie.css('paddingTop')) + parseInt($wie.css('paddingBottom'));
	var footerHeight   = $footer.height() + parseInt($footer.css('paddingTop')) + parseInt($footer.css('paddingBottom'));
	$sections.css('backgroundAttachment', 'fixed');

	$.fn.scrollBG = function(fixedY, offsetY, ratio, x) {
		// y-position will be fixedY when scrollPos == offset
		var offsetY = offsetY || 0;
		var ratio = ratio || 0.15;
		$(this).css({
			'backgroundPosition': x + ' ' + (fixedY-($(window).scrollTop()-offsetY)*ratio) + 'px'
		})
	}

	var setBGposition = function() {
		var viewYmin = $(window).scrollTop();
		var viewYmax = viewYmin + viewportHeight;
		if (introTop <= viewYmax && introTop+introHeight >= viewYmin)
			$intro.scrollBG(introHeight-384, 0, 0.2, 'center');
		if (websitesTop <= viewYmax && websitesTop+websitesHeight >= viewYmin)
			$websites.scrollBG(viewportHeight-280, websitesTop - (viewportHeight - websitesHeight), 0.2, 'left');
		if (procesTop <= viewYmax && procesTop+procesHeight >= viewYmin)
			$proces.scrollBG(viewportHeight-328, procesTop - (viewportHeight - procesHeight), 0.2, 'right');
		if (wieTop <= viewYmax && wieTop+wieHeight >= viewYmin)
			$wie.scrollBG(viewportHeight-331, wieTop - (viewportHeight - wieHeight), 0.2, 'right');
		if (footerTop <= viewYmax && footerTop+footerHeight >= viewYmin)
			$footer.scrollBG(viewportHeight-304, footerTop - (viewportHeight - footerHeight), 0.2, 'center');
	}
	setBGposition();

	var stopY = 156;
	var lineHeight = 40;
	$(window).bind('scroll', function(e){

		var scrollTop = $(window).scrollTop();
		// hide h2's when they scroll under logo
		$('article hgroup, #tweets').each(function(){
			var parentOffset = $(this.parentNode).offset().top;
			var parentHeight = $(this.parentNode).height();
			var off = 0;
			if ($(this).attr('id') == 'tweets') {
				off = 78;
			}
			if (scrollTop > parentOffset - stopY) {
				if (scrollTop < parentOffset + parentHeight - stopY - lineHeight) {
					$(this).css({
						position: 'fixed',
						top: off + stopY + 'px',
						opacity: 1,
						filter: 'none'
					});
				} else {
					if ($(this).attr('id') == 'tweets') {
						$(this).css({
							position: 'absolute',
							top: off + 'px',
							opacity: 0.1
						});
					} else {
						$(this).css({
							position: 'relative',
							top: parentHeight - lineHeight,
							opacity: 0.1
						});
					}
				}
			} else {
				if ($(this).attr('id') == 'tweets') {
					$(this).css({
						position: 'absolute',
						top: off + 'px'
					});
				} else {
					$(this).css({
						position: 'static'
					});
				}
			}
		});

		// scroll backgrounds
		setBGposition();

	})
}



// onkeydown in element el -> do act
function catchKeys(el, code_action) {
	$(el).bind('keydown', function catchKey(e) {
		if (typeof(e) == "undefined") { e = event; }
		for (var i=0; i<code_action.length; i++) {
			if (e.keyCode == code_action[i][0]) {
				newAction =  code_action[i][1]();
			}
		}
	});
}



var posFixed = function($el) {
	$el.css({
		visibility: 'visible',
		top: $(window).scrollTop() + "px"
	});
}



function iOS() {
    return (
        (/iphone|ipod|ipad/gi).test(navigator.appVersion)
    );
}
function iPad() {
    return (
        (/ipad/gi).test(navigator.appVersion)
    );
}
function android() {
    return (
        (/android/gi).test(navigator.appVersion)
    );
}



$(document).ready(function(){

	$('body').addClass('js');

	smoothAnchors(30);
	showcase();
	tweets();
	formValidation();

	if ($(window).width() > 479) { // accordion only w > 479
		var initAccordion = function() {
			oldHTML = $('ol.accordion').cinAccordion({
				tabs: 'h3',
				tabWidth: 21
			});
		}
		initAccordion();
		if ($(window).width() > 639) { // lightbox only w > 639
			$('a.lightbox').cinbox();
		}
	}
	if ($(window).width() > 959 && !iOS() && window.XMLHttpRequest) { // scrollFX: w > 959, no iOS (except iPad), no IE6
		scrollFX();
	} else { // no scrollFX > extra padding
		$('#proces .inner, #wie .inner').css({
			paddingBottom: '257px'
		});
	}

	if (iOS()) {
		$('input, select, textarea').bind('focus blur', function(event) {
			$('meta[name="viewport"]').attr('content', 'width=device-width,initial-scale=1,maximum-scale=' + (event.type == 'blur' ? 2 : 1));
		});
		//$(window).bind('scroll', function() {
		//	posFixed($('nav'));
		//});
		//$('#main').bind('touchstart', function() {
		//	$('nav').css('visibility', 'hidden');
		//});
		addEventListener("load", function() {
			setTimeout(function(){
				window.scrollTo(0,1);
			}, 0);
		}, false);
	}

	if (android()) {
		$('meta[name="viewport"]').attr('content', 'width=device-width,user-scalable=no');
	}

});



})(jQuery);

