/* Copyright (c) 2011 Felix Laukel (http://laukel.com)
 * Version 1.0.8
 ************************************************************* */
 
// check if console available
if (!window.console) {
	window.console = {};
	window.console.log = function(){};
}
 
// can not calculate with strings, so get rid of the 'px'
String.prototype.nopx = function() {
	return Number(this.replace('px', ''));
}

// setup piwik goals for tracking
var goals = {};
goals.mailed = 1;
goals.mousewheel = 2;
goals.keyboard = 3;
goals.gplusone = 4;
goals.fbshare = 5;
goals.skills = 6;
goals.livechat = 7;
// tracking function wrapper
piwikGoal = function(gid) {
	try {
		piwikTracker.trackGoal(gid);
		console.log('Piwik goal: '+gid);
	} catch( err ) {}
}
piwikTrackID = function() {
	try {
		var url = document.domain+'/#'+currentID;
		var title = '#'+currentID; 
		piwikTracker.setDocumentTitle(title);
		piwikTracker.trackPageView();
		//piwikTracker.trackLink(url, 'link');
		console.log('Piwik track: ' + url);	
	} catch( err ) {}
}



var startID = window.location.href.split('#')[1] || 'home'; // starting container
var currentID = ''; // active container
var slideShowDelay = 4000;

// main horizontal scrolling function
scrollToID = function(id, time) {
	
	currentID = id;
	var offset = $('#'+id).offset().left - /*$('#content').css('left').nopx() +*/ $(window).width()*0.5 + $('#'+id).width()*0.5;
	
	checkScrollEnds();
	
	// on scroll complete
	var oc = function() {
		var url = window.location.href.split('#')[0];
		window.location.href = url+'#'+id;
		
		$('#navi a').removeClass('active');
		$('#navi a[href=#'+id+']').addClass('active').parents('li').children('a').addClass('active');
		
		// hide image-list controls and kill interval of none active containers
		$('.work .teaser .controls').fadeOut( 300 );
		$('.work .teaser .img-list').each(function(index, element) {
            clearInterval( this.imginterval );
        });
		
		// reset image-list controls and interval of current active container ID
		$('#'+id+'.work .teaser .controls').clearQueue().fadeTo( 300, 1 );
		$('#'+id+'.work .teaser .img-list').each(function(index, element) {
			if (!Modernizr.touch)  this.imginterval = setInterval(this.imgnext, slideShowDelay);
        });
		// shadow
		if (time > 0) adjustShadow();
		
	};
	
	if (time == undefined) time = 600;
	$('html, body').animate({scrollLeft:offset}, time, 'easeInOutQuad', oc);
	
	// track current id
 	piwikTrackID();
	
}
stopScrolling = function() {
	$('html, body').clearQueue();
}

// setup the connection of anchor IDs and index numbers in an array
var IDList = [];
var IDIndex = 0;

getIndexByID = function(id) {
	var i = -1;
	while (++i < IDList.length) {
		if (id == IDList[i]) return i;	
	}
	return -1;
}

initIDList = function() {
	IDList = [];
	$('#content .container:not(.skip)').each(function(index, element) {
        IDList.push( $(this).attr('id') );
    });	
}

// check if user scrolled to beginning or end of the content and hides the specific overlay control
checkScrollEnds = function() {
	var i = getIndexByID( currentID );
	if (i == 0) 	$('.overlay-control.left').hide();
	else $('.overlay-control.left').show();
	
	if (i == IDList.length-1) $('.overlay-control.right').hide();
	else $('.overlay-control.right').show();	
}

// scrolling by keyboard
initKeyControls = function() {
	
	$(document).keydown(function(e) {
		
		var dir = 0;
		
		if (!formFocus) {
			if (e.keyCode == '37') { // left
				e.preventDefault();
				dir = -1;
			} else if (e.keyCode == '39') { // right
				e.preventDefault();
				dir = 1;
			}
		}
		
		if (dir != 0) {
			IDIndex = getIndexByID(currentID);
			IDIndex = Math.min(IDList.length-1, Math.max(0, IDIndex+dir));
			
			stopScrolling();
		
			scrollToID( IDList[ IDIndex ] );
			piwikGoal(goals.keyboard);
		}
    });	
}

// scrolling by mousewheel
enableScrollWheel = function() {
	
	//initIDList();
	
	$('html').bind('mousewheel', function(event, delta) {
		//var cs = $('html, body').scrollLeft();
		//$('html, body').scrollLeft(cs+100*-delta);
		var d = delta/Math.abs(delta);
		IDIndex = getIndexByID(currentID);
		IDIndex = Math.min(IDList.length-1, Math.max(0, IDIndex-d));
		stopScrolling();
		scrollToID( IDList[ IDIndex ] );
		piwikGoal(goals.mousewheel);
		
	});
}
disableScrollWheel = function() {
	$('html').unbind('mousewheel');
}

// setup scrolling image-lists
initImageLists = function() {
	
	$('.teaser .img-list').each(function(index, element) {
        this.imgcount = $(this).children('img').length;
		this.imgw = $(this).parent().width();
		this.imgi = 0;
		//alert(this);
		var that = this;
		var fn = function() {
			if (!stopAnimations) {
				if (that.imgi+1 < that.imgcount) that.imgi++;
				else that.imgi = 0;
				
				$(that).animate({left:-that.imgw*that.imgi}, 1200, 'easeInOutExpo');
				
				$(that).nextAll('.controls').children('.btn').removeClass('active');
				$(that).nextAll('.controls').children('.btn[data='+that.imgi+']').addClass('active');
			}
		}
		this.imgnext = fn;
		//this.imginterval = setInterval(this.imgnext, 5000);
		
		var i = 0;
		var btns = '';
		while (i < this.imgcount) {
			var active = (i == 0) ? ' active' : '';
			btns += '<li data="'+i+'" class="btn'+active+'"></li>';
			i++;
		}
		
		$(this).after('<ul class="controls">'+btns+'</ul>');
		
    });
	
	$('.teaser .controls .btn').click(function(e) {
		
		var list = $(this).parent().prevAll('.img-list').get(0);
        list.imgi = Number($(this).attr('data')-1);
		clearInterval(list.imginterval);
		//list.imginterval = setInterval(list.imgnext, slideShowDelay);
		list.imgnext();
		
    });
	
}

// checks if window height is enough to enable horizontal scrolling by mousewheel
checkScreenSize = function() {
	disableScrollWheel();
	
	if ( $('#content').height()+150 < window.innerHeight ) {
		enableScrollWheel();
	}
}


// setup contact form behaviour
var formFocus = false; // flag if focus is set to a inputfield to prevent scrolling the site on pressing arrowkeys

initFormFocus = function() {
	$('form *[title]').each(function() {
		if($(this).val() == '') {
			$(this).val($(this).attr('title')); 
		}
		
		$(this).focus(function() {
			if($(this).val() == $(this).attr('title')) {
				$(this).val('').addClass('focused'); 
			}
		});
		
		$(this).blur(function() {
			if($(this).val() == '') {
				$(this).val($(this).attr('title')).removeClass('focused'); 
			}
		});
	});
	$('input, textarea').focus(function(e) {
        formFocus = true;
    }).blur(function(e) {
        formFocus = false;
    });
}
// show little icons next to the false form fields
showFormError = function(name) {
	$('#contact .error.'+name)
			.clearQueue()
			.css('display', 'inline-block')
			.fadeOut(0).fadeTo(300, 1.0)
			.delay(5000).fadeOut(600);	
}

// setup ajax formmailer
initFormMailer = function() {
	$('#contact input[type=submit]').click(function (e) {
		e.preventDefault();
		e.stopPropagation();
		
		//disable inputs
		$('#contact input, #contact textarea').attr('disabled','true');
		
		var data = {ajax:true};
		var error = false;
		
		$('#contact input, #contact textarea').each(function(index, element) {
			var name = $(this).attr('name');
            if ( $(this).val() != $(this).attr('title') ) {
				if ( $(this).val().length >= 3 ) {
					data[ name ] = $(this).val();
					return true;
				}
			}
			showFormError(name);
			error = true;
        });
		
		
		if (error) {
			$('#contact input, #contact textarea').removeAttr('disabled');
			showMessage('Ohoh! Something is missing.<br />Please check your inputs and try again.');
			return;
		}
		// submit request
		$.ajax({
			url: "./mail_request.php",
			type: "POST",
			data: data,
			
			success: function (reqCode) {
				if (reqCode == 'success') {
					$('#contact form').slideUp(600);
					
					showMessage('Thank you. Your request has been sent.');
					piwikGoal(goals.mailed);
			
				} else {
					$('#contact input, #contact textarea').removeAttr('disabled');
					showMessage('Ohoh! Server says \'no\'.<br />Please check your inputs and try again.');
					showFormError(reqCode);
				}
			}
		});
	
	});
	
}

// display system messages or other feedback to the visitor
showMessage = function(msg, time) {
	if (!time) time = 4000;
	var hide = function() { $('#system-msg').hide(0) };
	$('#system-msg')
				.clearQueue()
				.css('top', '-200px')
				.html(msg)
				.show(0)
				.animate({top:200}, 800, 'easeOutElastic')
				.delay(time)
				.animate({top:-200}, 600, 'easeInExpo', hide);
}


// overlay launcher setup to view works directly on site
var launcherOn = false; // flag if launcher currently running
var stopAnimations = false; // flag to stop global animation playback like image-lists and flipping quotes
// setup links to show content in launcher
initLauncher = function() {
	$('a.launch').click(function(e) {
        e.preventDefault();
		e.stopPropagation();
		var w = 800;
		var h = 560;
		
		try {
			var rel = $(this).attr('rel');
			var href = $(this).attr('href');
			
			rel = rel.split('x');
			if (rel.length == 2) {
				w = rel[0]; h = rel[1];
			}
			
			showLauncher(href, w, h);
			
		} catch (error) {
			showMessage('Ohoh! The launcher ran into a problem and says \'sorry\'.<br /> Please try again or open in new window.', 6000);
		}
    });
}
showLauncher = function(url, w, h) {
	launcherOn = stopAnimations = true;
	
	// try to check for iframe loading error --tricky
	// seems to work only properly on webkit
	var lLoaded = false;
	loadError = function() {
		if (lLoaded) return;
		showMessage('Ohoh! The launcher has currently a hard time loading the content.<br /> Please try again or open in a new window.', 6000);
		setTimeout(hideLauncher, 3000);
	}
	var setFrame = function() { 
		$('#launcher #frame iframe') // IE and ff error handling fix not working :/
									.load(function(e) { lLoaded = true;/*$(this).contents().find("html") != undefined;*/ })
									.error( loadError )
									.attr( 'src', url );
		setTimeout(loadError, 4000);
		
		$('#launcher #power').fadeIn(600).add('#launcher #bg').click(function(e) {
			hideLauncher();
		});	
	 };
	 
	 $('#launcher *').clearQueue();
	
	$('#launcher #power').css('display', 'none');	
	$('#launcher #bg').fadeOut(0).fadeTo( 300, 1.0 );
	$('#launcher #frame').css({width:'50px', height:'1px', marginLeft:'0', marginTop:'0'});
	
	$('#launcher #frame')
						.delay(320)
						.animate({width:w, marginLeft:-w*.5}, 300, 'easeOutExpo')
						.animate({height:h, marginTop:-h*.5}, 200, 'swing', setFrame);
						
	$('#launcher').show(0);
}
hideLauncher = function() {
	if (!launcherOn) return;
	
	var hide = function() { $('#launcher').hide(0); launcherOn = stopAnimations = false; };
	
	$('#launcher #frame iframe').attr( 'src', '' );
	
	$('#launcher #power').css('display', 'none');	
	$('#launcher #frame')
						.animate({height:1, marginTop:0}, 200, 'swing')
						.animate({width:0, marginLeft:0}, 300, 'swing');
						
	$('#launcher #bg').delay(500).fadeOut( 300, 'swing', hide );
}


// live chat initialization
showLiveChat = function() {
	var lcLoaded = false;
	loadError = function() {
		if (lcLoaded) return;
		setTimeout(hideLiveChat, 3000);
		showMessage('It seems the chat is not available or I am not logged in right now.<br />Sorry, please try again some other time.', 6000);
	}
	initChat = function() {
		var url = $('.live-chat-btn').attr('href');
		$('#live-chat iframe')
							.load(function(e) { lcLoaded = true;/*$(this).contents().find("html") != undefined;*/ })
							.error( loadError )
							.attr( 'src', url );
		setTimeout(loadError, 5000);
		
		piwikGoal(goals.livechat);
	}
	$('#live-chat').animate({top:40}, 1200, 'easeOutElastic', initChat);
}
hideLiveChat = function() {
	killChat = function() {
		$('#live-chat iframe').attr( 'src', '' );
	}
	$('#live-chat').animate({top:-400}, 600, 'easeInOutExpo', killChat);
}


// config for flipping quotes on startscreen
var quotesLength;
var quotesIndex = 0;
flipQuotes = function() {
	
	if (!stopAnimations) {
		$('#content .random-quote.active').removeClass('active');
		
		quotesLength = $('#content .random-quote').length;
		var q = $('#content .random-quote').get( quotesIndex++ % quotesLength );
		$( q ).addClass('active');
	}
	
	setTimeout(flipQuotes, 4000);
}
// adjust overlay shadow width according to screen width
var shadowFirstRun = true;
adjustShadow = function() {
	var w = $('#content #'+currentID).width()+20;
	w = Math.min(800, Math.max(200, w));
	w = (window.innerWidth-w)*0.5 |0
	//$('.overlay-shadow').css('width', w+'px');
	var t = shadowFirstRun ? 2000 : 600;
	var e = shadowFirstRun ? 'easeInOutQuad' : 'swing';
	$('.overlay-shadow').clearQueue().animate({width:w, opacity:0.5}, t, e);
	
	shadowFirstRun = false;
}

// setup for touch/mobile devices
if (Modernizr.touch)  {
	$(document).scroll(function(e) {
		$('#navi').css('left', $('body').scrollLeft()+'px');
		$('.overlay-control.left').css('left', (20+$('body').scrollLeft())+'px');
		$('.overlay-control.right').css('left', (window.innerWidth+$('body').scrollLeft()-20-60)+'px');
	});
}

// check and process changes if window gets resized
$(window).resize(function(e) {
	stopScrolling();
	scrollToID(currentID);
	checkScreenSize();
	adjustShadow();
});

// setup when DOM is ready
$(document).ready(function () {
	$('#preloader').show(0);
	
	checkScreenSize();
	
	initIDList();
	
	initKeyControls();
	
	initImageLists();
	
	initFormFocus();
	
	initFormMailer();
	
	scrollToID(startID, 0);
	
	// enable advanced features if no touch/mobile
	if (!Modernizr.touch)  {
		
		initLauncher();
		
		if (!$.browser.msie) {
			$('.overlay-control').hide(0);
			// additional setup excluded on touch/mobile
			$(document).mousemove(function(e) {
				var notHome = (currentID != 'home');
				var notNav = (e.clientY > 100);
				var r = 300;
				if (e.clientX < r && notHome && notNav) {
					$('.overlay-control.left')	.clearQueue().fadeTo(200, 1.0)
												.css('top', e.clientY-20+'px');
				} else {
					$('.overlay-control.left')	.clearQueue().fadeTo(100, 0.0)
				}
				
				if (e.clientX > window.innerWidth-r && notHome && notNav) {
					$('.overlay-control.right')	.clearQueue().fadeTo(200, 1.0)
												.css('top', e.clientY-20+'px');
				} else {
					$('.overlay-control.right')	.clearQueue().fadeTo(100, 0.0);
				}
				checkScrollEnds();
			});
		}
	} else {
		$('.overlay-shadow').hide(0);	
	}
	
	$('body').css('overflow-x', 'hidden');
	
	$('.js-only').css('display', 'inherit');
	
	$('.css-only').removeClass('css-only');
	
	$('iframe').attr('frameborder', '0').attr('scrolling', 'no');
	
	$('.work .controls').hide();
	
	// no extra loading on IE --buggy
	if (!$.browser.msie) {
		$('#content .work .teaser img').hide().load( function() {  $(this).fadeIn(1200)  });
	}

});

// setup when page fully loaded, finally --------->
$(window).load(function(){
	
	$('#preloader').fadeOut(100);
	
	setTimeout(flipQuotes, 1600);

	// add features and intro animations if no touch/mobile
	if (!Modernizr.touch)  {
		
		setTimeout(adjustShadow, 10);
		
		// setup this cute little cockroach crawling around
		var roach = new Roach( $('#roach').get(0) );
		setTimeout(roach.move, 2400);
		
	}
	
									 
	// setup overlay controls to scroll prev and next container
	$('.overlay-control.left').click(function(e) {
        var prev = $('#'+currentID).prevAll('.container:not(.skip):first').attr('id');
		if (prev) scrollToID(prev);
    });
	$('.overlay-control.right').click(function(e) {
        var next = $('#'+currentID).nextAll('.container:not(.skip):first').attr('id');
		if (next) scrollToID(next);
    });
	
	// enable horizontal scrolling on all .scroll elements
	$('.scroll').click(function(e){
		e.preventDefault();
		var id = this.href.split('#')[1];
		
		if ($(this).hasClass('next')) {
			id = $('#'+id).next('.container:not(.skip)').attr('id');
		}
		scrollToID(id);
		
	});
	
	// show container details on rollover
	$('#content .container').mouseenter(function(e) {
		//$(this).children('.info').addClass('hover');
        $(this).children('.info:not(.no-slide)').animate({height:'100%'}, 300);
    }).mouseleave(function(e) {
		//$(this).children('.info').removeClass('hover');
        $(this).children('.info:not(.no-slide)').animate({height:'18px'}, 300, 'easeOutExpo');
    });
	
	// move banners a little on rollover
	$('#content img.banner').mouseenter(function(e) {
        $(this)
			.animate({marginTop:'-80px'}, 300, 'easeOutExpo')
			.animate({marginTop:'-100px'}, 800, 'easeOutElastic');
    });
	
	// fade-in sub navi
	$('#navi ul li').mouseenter(function(e) {
        $(this).children('ul').clearQueue().hide().delay(500).fadeTo(600, 1.0);
    }).mouseleave(function(e) {
        $(this).children('ul').hide();
    });
	
	// animate graphbars on show
	$('#content .graphbar').hide();
	animateGraphbars = function() {
		$('#content .graphbar')
			.show()
			.each(function(index, element) {
				var w = $(this).css('width');
				$(this).css('width', '0');
				$(this).animate({width:w}, 1600, 'easeInOutQuad');
		});
	}
	
	// scroll within a container
	$('.v-scroll').click(function(e) {
		var container = $(this).parents().children('div.long');
		var yoff = 20;
		if (container.css('margin-top').nopx() > 0) {
			yoff = -$(this).prev('p').height()+yoff;//$(this).offset().top - 214;
			animateGraphbars();
		}
        container.animate({marginTop:yoff+'px'}, 400, 'easeOutQuad');
    });
	
	// enable live chat
	$('.live-chat-btn').click(function(e) {
		e.preventDefault();
		e.stopPropagation();
		if (currentID != 'contact') {
			scrollToID('contact');
			setTimeout(showLiveChat, 800);
		} else {
			showLiveChat();
		}
    });
	$('#live-chat .close').click(function(e) {
		e.preventDefault();
		e.stopPropagation();
        hideLiveChat();
    });
	
		
});


