(function($){

	/* * * * * * * * * * * * * * *
	* @desc			Bind navigation interaction to logo animation and other fancy machinery
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	function _acadInitNav(){
		// Presets
		var nav = $('header#masthead nav');
		var nestedNav = nav.find('ul ul');
		var buttons = nav.find('ul li a');
		
		var glow = $('header#masthead .glow');
		
		var substrate = $('section#substrate');
		
		// "Got work, sire?"
		if(buttons.length > 0){
			// Reset glow
			glow.show().css({ opacity : 0 });
			//nestedNav.show().css({ opacity : 0 });
			
			buttons
			.bind('mouseenter', function(){
				_acadGlow(true);
				
				if($(this).parent().hasClass('dropdown')){
					var ul = $(this).parent().find('ul');
					clearTimeout(ul.data('closingIn'));
					
					// Visible at all?
					if(ul.css('display') != 'none'){
						ul
							.stop()
							.animate({ opacity : 1 }, 200);
					} // Invisible, be trickier
					else if(ul.length > 0){
						ul
							.stop()
							.show()
							.css({ opacity : 0 })
							.animate({ opacity : 1 }, 200);
					}
				}
			})
			.bind('mouseleave', function(){
				_acadGlow(false);
					
				if($(this).parent().hasClass('dropdown')){
					var ul = $(this).parent().find('ul');
					
					ul.data('closingIn', setTimeout(function(){
						if(!ul.hasClass('hovering')){
							ul
								.stop()
								.animate({ opacity : 0 }, 200, function(){
									$(this).hide();
								});
						}
					}, 200));
				}
			})
			.click(function(){
				if($(this).attr('href') != '#'){
				// Close Dropdown
					nestedNav
						.stop()
						.animate({ opacity : 0 }, 200);
					
					substrate.data('destination', $(this).attr('href'));
					
					if(!substrate.is(':animated')){
						// SERIOUS sliding. Close first:
						substrate
							.stop()
							.animate({ height : 68 }, 700, 'easeInOutExpo', function(){
								// The machine that goes "BING":
								_acadGlow(false, true);
							
								window.location.href = $(this).data('destination');
							
								// HEAVY closing:
								/*var that = $(this);
								setTimeout(function(){
									that.animate({ height : 566 }, 900, 'easeInOutExpo');
								}, 400);*/
						
							// Done, done and done.
							// @TODO fix this mess
							});
						}
					}
					//else{
						return false;
					//}
			});
			
			// When hovering nested nav (dropdown) register that
			nestedNav
				.bind('mouseenter', function(){
					$(this)
						.addClass('hovering')
						.stop()
						.animate({ opacity : 1 }, 200);
						
					clearTimeout(ul.data('closingIn'));
				})
				.bind('mouseleave', function(){
					$(this).removeClass('hovering');
					
					var that = $(this);
					
					$(this).data('closingIn', setTimeout(function(){
						that
							.stop()
							.animate({ opacity : 0 }, 200, function(){
								$(this).hide();
							});
					}, 200));
				});
		}
		
		return false;		 
	}
	
	/* * * * * * * * * * * * * * *
	* @desc			Init displays
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	function _acadGlow(inOut, cycle){
		// Presets
		var glow = $('header#masthead .glow');
		
		if(glow.length > 0 && $('#client-ie').length < 1){
			if(typeof inOut == 'undefined')
				inOut = true;
		
			if(typeof cycle == 'undefined'){	
				if(inOut == true){
					glow
						.stop()
						.animate({ opacity : 1 }, 300, function(){
							$(this).animate({ opacity : 0.7 }, 'easeOutQuint');
						});
				}
				else if(inOut == false){
					glow
						.stop()
						.animate({ opacity : 0 }, 1000, 'easeOutQuint');
				}
			}
			else if(cycle == true){
				glow
					.stop()
					.animate({ opacity : 1 }, 300, 'easeOutQuint', function(){
						$(this).animate({ opacity : 0.7 }, 'easeOutQuint', function(){
							$(this).animate({ opacity : 0 }, 1000, 'easeOutQuint');
						});
					});
			}
		}
		
		return false;
	}
	
	/* * * * * * * * * * * * * * *
	* @desc			Init displays
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	function _acadInit(){
		// Presets
		var fadeins = $('.fadein');
		var slidedowns = $('.slidedown');
		var content = $('#substrate>div.content>section');
		
		// "Got work, sire?"
		if(fadeins.length > 0){
			fadeins.each(function(){
				if($('#client-ie').length < 1){
					$(this)
						.show()
						.css({ opacity : 0 })
						.animate({ opacity : 1 }, 1400, 'easeOutQuint');				
				}
				else {
					$(this)
						.removeClass('fadein');
				}
			})
		}
		
		if(slidedowns.length > 0){
			slidedowns.each(function(){
				$(this)
					.animate({ marginTop : 0 }, 1100, 'easeOutQuint');				
			})
		}
		
		if(content.length > 0){
			content.wrapInner('<div class="content-middle"><div></div></div>');
			content.append('<div class="content-bottom"></div>');
			content.prepend('<div class="content-top"></div>');
		}
		
		// Simulate :last-child classes for important elements since it's not properly supported in ie
		$('.column:last-child, .half-column:last-child')
			.addClass('last');
			
		// Simulate :nth-child selector
		$('body.page-referenzen #content-frame nav ul li:nth-child(5n)')
			.addClass('nth-child');
		
		return false;		 
	}
	
	/* * * * * * * * * * * * * * *
	* @desc			Get all form elements and wrap/style them properly
	* @param		obj container for dynamic form injections
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	function _acadInitForms(container, removeThis, removeP){	 
		 /* 
			* Labels
			*/
			if(container)
        var labels = $(container).find('label');
      else
        var labels = $('label');
     
     // Loop
     labels.each(function(){ 
			var confinement = $(this).closest('form');
      var name = $(this).attr('for'); 
			var input = confinement.find('input[name="' + name + '"], textarea[name="' + name + '"]');
			
			if(removeThis)
				var placeholder = $(this).html();
			else
				var placeholder = $(this).attr('rel');
				
			if(typeof placeholder == 'undefined')
				var placeholder = '';

      input
				.val(placeholder)
				.data('label', placeholder)
				.focus(function(){
					if($(this).closest('div').hasClass('fresh')){
						$(this).val('').closest('div').removeClass('fresh');
					}
				})
				.blur(function(){
					if($(this).val() == ''){
						$(this).val($(this).data('label'))
						.closest('div')
						.addClass('fresh');
					}
				});

			if(!input.closest('div').hasClass('erroneous'))
				input.closest('div').addClass('fresh');

			if(removeThis)
      	$(this).remove();

			if(removeP)
				confinement.find('p>*').unwrap();
     });

		 /*
			* Buttons
			*/
			//@todo
			
			return false;		 
	}
	
	/* * * * * * * * * * * * * * *
	* @desc			Init slideshow
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	function _acadSlideshow(){	 
		var breakTime = 5000;
		var slideSpeed = 1200;
		var container = $('#slideshow');
		var train = $('#slideshow nav.slideshow ul');
		var indicator = container.find('nav.indicator ul');
		var frameWidth = $(window).width();
		//var controls = $('#slideshow .slide-control');
		
		var elements = null;
		var currentIndex = null;
		var frameMargin = null;
		/*
		 * If available, INITiative
		 */
		if(container.length){
			elements = train.find('li');
			var count = elements.length;
			
			if(count > 0){
				var itemWidth = elements.first().width();
				var itemMargin = parseInt(elements.first().css('margin-left'))  + parseInt(elements.first().css('margin-right'));
				
				// Re-calculate
				var itemWidth = itemWidth + itemMargin + 1
				
				//Final dimension
				var trainWidth = itemWidth * (count + 2);
				
				// Set
				train.css({ width : trainWidth });
				
				// Re-position entire frame based on window width
				//frameMargin = -1 * ((frameWidth / 2) - (itemWidth / 2)) - itemWidth + 20;
				frameMargin = -165 - itemWidth;
				train.css({ marginLeft : frameMargin });
				
				// Assign indexes to data
				elements.each(function(){
					$(this).data('index', $(this).index());
				});
				
				// Create and reset aside
				$('#substrate').append('<div id="asideish"></div>');
				var aside = $('#asideish');
				
				if(train.find('li').eq(1).find('.title').length < 1)
					aside.css({ marginBottom : -100 });
					
				// Create indicator
				for(var i=0; i<count; i++){
					indicator.append('<li></li>');
				}
				indicator.find(':first').addClass('current');
			}
			
			/*
			 * Operative
			 */
			container.data('automat', setInterval(function(){
				//controls.animate({ opacity: 0.4 }, 300).addClass('inactive');
				
				currentIndex = -1 * parseInt(parseInt(train.css('margin-left')) / itemWidth) + 1;
				
				if(train.find('li').eq(currentIndex).find('.title').length < 1)
					aside.animate({ marginBottom : -80 }, 1000);
				else
					aside.animate({ marginBottom : 0 }, 1000);
					
				// Nudge indicator
				indicator.find('li').removeClass('current').eq(train.find('li').eq(currentIndex-1).data('index')).addClass('current');

				train.animate({ marginLeft : "-=" + itemWidth }, slideSpeed, 'easeInOutExpo', function(){										
					if($(this).find('.remove').length > 0){
						$(this)
							.css('margin-left', function(){
								return parseInt($(this).css('margin-left')) + itemWidth;
							})
							.find('.remove')
							.remove();
					}
					
					$(this)
						.find('li:first-child')
						.addClass('remove')
						.clone(true)
						.appendTo($(this))
						.removeClass('remove');
					
						//controls.animate({ opacity: 1 }, 300).removeClass('inactive');
				});
			}, breakTime));
		}
	}
	
	/* * * * * * * * * * * * * * *
	* @desc			Decorate stuff
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	function _acadDecorate(){
	}
	
	/* * * * * * * * * * * * * * *
	* @desc			Init tabbed content navigation
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	function _acadInitTabbed(){
		var tabs = $('#content-frame>.content-middle>div>article');
		var tabNav = $('#tab-navigation ul');

		if(tabs.length > 1 && tabNav.length > 0){
			/*
			 * We have a situation
			 * Create nav by iterating through titles
			 */
			var titles = tabs.find('h2');
			
			tabs.hide().first().addClass('current').show();
			
			titles.each(function(){
				tabNav.append(
					$('<li></li>').append(
						$('<a href="#"></a>')
							.attr('title', $(this).html())
							.attr('href', '#/' + $(this).attr('rel'))
							.click(function(){
								if(!$(this).closest('li').hasClass('current')){
									$(this).closest('ul').find('li').removeClass('current');
									$(this).closest('li').addClass('current');
								
									var index = $(this).closest('li').index();
									tabs.filter('.current').fadeOut('fast', function(){
										$(this).removeClass('current');
										tabs.eq(index).fadeIn('fast').addClass('current');
									})
								}
								
								return false;
							})
							.append('<div class="prefix"></div>')
							.append($('<div class="label"></div>').append($(this).html()))
							.append('<div class="suffix"></div>')
					)
				);
			});
			
			tabNav
				.find('li:first')
				.addClass('current')
				.closest('nav')
				.removeClass('hidden');
		}
	}
	
	/* * * * * * * * * * * * * * *
	* @desc			Strap yee boots, pirates, arrrrrr
	* @return		void
	* @author		jannik.w@me.com
  * * * * * * * * * * * * * * */
	$().ready(function(){
		/*
		 * Behold...
		 */
		_acadInitNav();
		_acadInit();
		_acadInitForms(false, false, true);
		//_acadDecorate();
		_acadSlideshow();
		_acadInitTabbed();
		
		/* * * * * * * * * * * * * * *
		* @desc		Contact-Form-7 Scripts
		* @author for tweaked stuff: Jannik
		* * * * * * * * * * * * * * */
		try {
			if (typeof _wpcf7 == 'undefined' || _wpcf7 === null)
				_wpcf7 = {};

			_wpcf7 = $.extend({ cached: 0 }, _wpcf7);

			$('div.wpcf7 > form').ajaxForm({
				beforeSubmit: function(formData, jqForm, options) {
					jqForm.wpcf7ClearResponseOutput();
					jqForm.find('img.ajax-loader').css({ visibility: 'visible' });
					return true;
				},
				beforeSerialize: function(jqForm, options) {
					jqForm.find('.wpcf7-use-title-as-watermark.watermark').each(function(i, n) {
						$(n).val('');
					});
					return true;
				},
				data: { '_wpcf7_is_ajax_call': 1 },
				dataType: 'json',
				success: function(data) {
					var ro = $(data.into).find('div.wpcf7-response-output');
					$(data.into).wpcf7ClearResponseOutput();

					if (data.invalids) {
						$.each(data.invalids, function(i, n) {
							$(data.into).find(n.into).wpcf7NotValidTip(n.message);
						});
						ro.addClass('wpcf7-validation-errors');
					}

					if (data.captcha)
						$(data.into).wpcf7RefillCaptcha(data.captcha);

					if (data.quiz)
						$(data.into).wpcf7RefillQuiz(data.quiz);

					if (1 == data.spam)
						ro.addClass('wpcf7-spam-blocked');

					if (1 == data.mailSent) {
						$(data.into).find('form').resetForm().clearForm();
						ro.addClass('wpcf7-mail-sent-ok');

						if (data.onSentOk)
							$.each(data.onSentOk, function(i, n) { eval(n) });
					} else {
						ro.addClass('wpcf7-mail-sent-ng');
					}

					if (data.onSubmit)
						$.each(data.onSubmit, function(i, n) { eval(n) });

					$(data.into).find('.wpcf7-use-title-as-watermark.watermark').each(function(i, n) {
						$(n).val($(n).attr('title'));
					});

					ro.append(data.message).slideDown('fast');
				}
			});

			$('div.wpcf7 > form').each(function(i, n) {
				if (_wpcf7.cached)
					$(n).wpcf7OnloadRefill();

				$(n).wpcf7ToggleSubmit();

				$(n).find('.wpcf7-acceptance').click(function() {
					$(n).wpcf7ToggleSubmit();
				});

				$(n).find('.wpcf7-exclusive-checkbox').each(function(i, n) {
					$(n).find('input:checkbox').click(function() {
						$(n).find('input:checkbox').not(this).removeAttr('checked');
					});
				});

				$(n).find('.wpcf7-use-title-as-watermark').each(function(i, n) {
					var input = $(n);
					input.val(input.attr('title'));
					input.addClass('watermark');

					input.focus(function() {
						if ($(this).hasClass('watermark'))
							$(this).val('').removeClass('watermark');
					});

					input.blur(function() {
						if ('' == $(this).val())
							$(this).val($(this).attr('title')).addClass('watermark');
					});
				});
			});

		} catch (e) {
		}
	});
	
	$.fn.wpcf7ToggleSubmit = function() {
		return this.each(function() {
			var form = $(this);
			if (this.tagName.toLowerCase() != 'form')
				form = $(this).find('form').first();

			if (form.hasClass('wpcf7-acceptance-as-validation'))
				return;

			var submit = form.find('input:submit');
			if (! submit.length) return;

			var acceptances = form.find('input:checkbox.wpcf7-acceptance');
			if (! acceptances.length) return;

			submit.removeAttr('disabled');
			acceptances.each(function(i, n) {
				n = $(n);
				if (n.hasClass('wpcf7-invert') && n.is(':checked')
				|| ! n.hasClass('wpcf7-invert') && ! n.is(':checked'))
					submit.attr('disabled', 'disabled');
			});
		});
	};

	$.fn.wpcf7NotValidTip = function(message) {
		return this.each(function() {
			var into = $(this);
			into.append('<span class="wpcf7-not-valid-tip">' + message + '</span>');
			$('span.wpcf7-not-valid-tip').mouseover(function() {
				$(this).fadeOut('fast');
			});
			into.find(':input').mouseover(function() {
				into.find('.wpcf7-not-valid-tip').not(':hidden').fadeOut('fast');
			});
			into.find(':input').focus(function() {
				into.find('.wpcf7-not-valid-tip').not(':hidden').fadeOut('fast');
			});
		});
	};

	$.fn.wpcf7OnloadRefill = function() {
		return this.each(function() {
			var url = $(this).attr('action');
			if (0 < url.indexOf('#'))
				url = url.substr(0, url.indexOf('#'));

			var id = $(this).find('input[name="_wpcf7"]').val();
			var unitTag = $(this).find('input[name="_wpcf7_unit_tag"]').val();

			$.getJSON(url,
				{ _wpcf7_is_ajax_call: 1, _wpcf7: id },
				function(data) {
					if (data && data.captcha)
						$('#' + unitTag).wpcf7RefillCaptcha(data.captcha);

					if (data && data.quiz)
						$('#' + unitTag).wpcf7RefillQuiz(data.quiz);
				}
			);
		});
	};

	$.fn.wpcf7RefillCaptcha = function(captcha) {
		return this.each(function() {
			var form = $(this);

			$.each(captcha, function(i, n) {
				form.find(':input[name="' + i + '"]').clearFields();
				form.find('img.wpcf7-captcha-' + i).attr('src', n);
				var match = /([0-9]+)\.(png|gif|jpeg)$/.exec(n);
				form.find('input:hidden[name="_wpcf7_captcha_challenge_' + i + '"]').attr('value', match[1]);
			});
		});
	};

	$.fn.wpcf7RefillQuiz = function(quiz) {
		return this.each(function() {
			var form = $(this);

			$.each(quiz, function(i, n) {
				form.find(':input[name="' + i + '"]').clearFields();
				form.find(':input[name="' + i + '"]').siblings('span.wpcf7-quiz-label').text(n[0]);
				form.find('input:hidden[name="_wpcf7_quiz_answer_' + i + '"]').attr('value', n[1]);
			});
		});
	};

	$.fn.wpcf7ClearResponseOutput = function() {
		return this.each(function() {
			$(this).find('div.wpcf7-response-output').hide().empty().removeClass('wpcf7-mail-sent-ok wpcf7-mail-sent-ng wpcf7-validation-errors wpcf7-spam-blocked');
			$(this).find('span.wpcf7-not-valid-tip').remove();
			$(this).find('img.ajax-loader').css({ visibility: 'hidden' });
		});
	};
})(jQuery)
