/* 
	Author: Daniel Kremin, Christian Hermann Quinders
*/

$(function(){
	
	if( !Modernizr.touch ) {
		$('.globalmenu').slideMenu();
	}
	
	$('.collapsible').collapsibleContent();
	
	$('video').mediaelementplayer({
		defaultVideoWidth: 928,
		defaultVideoHeight: 522
	});

	$('audio').mediaelementplayer({
		features: ['playpause','current','volume'],
		audioWidth: 88,
		audioHeight: 30
	});
	
	$('form.do-ajax').ajaxForm({track:(typeof window._gaq === 'object')});
	
	$('[data-ga]').trackEvent();
	
});

/* 
	Author: Christian Hermann Quinders
*/
//
// create closure
//
(function($) {
	//
	// plugin definition
	//
	$.fn.ajaxForm = function(options) {
		
		// build main options before element iteration
		var opts = $.extend({}, $.fn.ajaxForm.defaults, options);
		
		// iterate and reformat each matched element
		return this.live('submit', function(e) {
			
			var $form = $(this),
				form_id = $form.attr('id'),
				$msg = $form.parent().find('.form-message'),
				$submit = $form.find(':submit'),
				url = ( $form.data('ajax') ) ? $form.data('ajax') : opts.url ;

			//console.log(url);
			//console.log(opts.track);
			
			$.ajax({
				type: 'POST',
				url: url,
				data: $form.serialize(),
				beforeSend: function() {
					$msg.empty().removeClass('error-msg success-msg').addClass('processing');
					$submit.addClass('disabled').attr('disabled','disabled');
				},
				success: function(r) {
					//console.log(r);
					window.setTimeout(function(){
						$form.find('.error').removeClass('error');
						var msg_class;
						//console.log(r);
						// form has no errors
						if ( r.status ) {
							msg_class = 'success-msg';
							// reset form input
							$form.find(':input').not(':button, :submit, :reset, :hidden')
								.val('').removeAttr('checked').removeAttr('selected');
							if ( opts.track ) {
								_gaq.push(['_trackPageview', url]);
								//console.log(url);
							}
						// form has errors
						} else {
							msg_class = 'error-msg';
							//console.log(r.error.length);
							for( i=0; i <= r.error.length-1; i++ ) {
								$form.find( '#' + form_id + '-' + r.error[i] ).addClass('error').parent().parent().addClass('error');
							}
						}
						
						$submit.removeClass('disabled').removeAttr('disabled');
						$msg.removeClass('processing').addClass(msg_class).html( r.message );
						
						if ( opts.track ) {
							var event_message = $(r.message).text();
							//console.log(event_message);
							_gaq.push(['_trackEvent', opts.trackCategory, (r.status) ? 'Success' : 'Error' , event_message ]);
						}
						
						if ( r.restore ) {
							window.setTimeout(function(){
								$msg.removeClass('success-msg error-msg').html( r.restore );
							}, opts.restoreDelay );
						} else if ( r.dessert ) {
							$form.detach();
							$msg.parent().append( r.dessert );
						}
						
					}, opts.requestDelay);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					var error_message = 'An Error occured. Please try again later. (' + textStatus + ')';
					console.log(XMLHttpRequest.responseText);
					$msg.removeClass('processing').addClass('error-msg').html( '<p>' + error_message + '</p>' );
					$submit.removeClass('disabled').removeAttr('disabled');
					if ( opts.track ) _gaq.push(['_trackEvent', opts.trackCategory, 'Error' , error_message + ' ' + errorThrown ]);
				}
			});
			
			// prevent default submit
			return false;
		});
	};
	//
	// plugin defaults
	//
	$.fn.ajaxForm.defaults = {
		track: false,
		trackCategory: 'Kontakt',
		restoreDelay: 6000,
		requestDelay: 250,
		url: window.location.href
	};
//
// end of closure
//
})(jQuery);

/*
 *
 *	Author: Christian Hermann Quinders
 *
 */
//
// create closure
//
(function($) {
	//
	// plugin definition
	//
	$.fn.slideMenu = function(options) {
		
		// build main options before element iteration
		var opts = $.extend({}, $.fn.slideMenu.defaults, options);
		
		// iterate and reformat each matched element
		return this.each(function() {
			var $this = $(this),
				$items = $( opts.items, this ),
				$spacer = $( opts.spacer, this ),
				collapse = ( !$this.hasClass( opts.expandedClass ) ),
				isOverLink = false,
				$active = null;
			
			if( !collapse ) {
				$active = $items.filter( '.' + opts.activeClass ).find( opts.submenu );
			} 
			
			$items.hoverIntent({
				interval: opts.delay/2,
				timeout: opts.delay,
				over: function() {
					var $that = $(this),
						$submenu = $that.find( opts.submenu );
						is_active = ( collapse ) ? false : ( $that.hasClass( opts.activeClass ) );
					//console.log( is_active );
					if( !is_active ) {

						// submenu slide down and fade in
						showSub( $submenu, {
							duration: opts.duration,
							easing: opts.easing
						});
						
						// if no default submenu then reveal spacer
						if( collapse ) {
							animateDrawer( $spacer, { 
								height: $submenu.outerHeight(),
								duration: opts.duration,
								easing: opts.easing
							});
						} else {
							// hide active default menu
							if( $active ) {
								$active.clearQueue();
								hideSub( $active, {
									duration: opts.duration,
									easing: opts.easing
								});
							}
						}
						
						// slide up arrow of menu item
						animateBG( $that, {
							y: '-7px',
							duration: opts.duration,
							easing: opts.easing
						});
					}
				},
				out: function() {
					var $that = $(this),
						$submenu = $that.find( opts.submenu ),
						is_active = ( collapse ) ? false : ( $that.hasClass( opts.activeClass ) );
					
					if( !is_active ) {
						
						// submenu slide up and fade out
						hideSub( $submenu, {
							duration: opts.duration,
							easing: opts.easing
						});
						
						// if no default submenu then collapse spacer
						if( collapse && !isOverLink ) {
							animateDrawer( $spacer, { 
								height: 0,
								easing: opts.easing,
								duration: opts.duration
							});
						} else {
							// show active default menu
							if( $active ) {
								//console.log('show active');
								showSub( $active.delay(opts.duration/2), {
									duration: opts.duration,
									easing: opts.easing
								});
							}
						}
						
						// slide down arrow of menu item
						animateBG( $that, {
							y: '0px',
							duration: opts.duration,
							easing: opts.easing
						});
					}
					
				}
				
			}).bind('mouseenter', function() {
				isOverLink = true;
			}).bind('mouseleave', function() {
				isOverLink = false;
			});
			
			function init() {
				$items
					.not( '.' + opts.activeClass )
						.find( opts.submenu )
							.each(function(){
								$t = $(this);
								$t.css({
									marginTop: -$t.height() +'px',
									opacity: 0
								});
							})
								.parent()
									.css( 'visibility', 'visible' );
			}
			
			init();
			
		});
	};
	
	//
	// private functions
	//
	
	// animate background arrow
	function animateBG( $this, opts ) {
		$this.children().filter('a').stop().delay(opts.duration/2).animate({ backgroundPosition: '50% ' + opts.y }, { duration: opts.duration/2, easing: opts.easing } );
	}
	
	// animate drawer
	function animateDrawer( $drawer, opts ) {
		$drawer.stop().animate({ height: opts.height }, { duration: opts.duration, easing: opts.easing });
	}
	
	// show sub
	function showSub( $sub, opts ) {
		//console.log( $elem );
		$sub.show().css({ marginTop: -$sub.outerHeight(), opacity: 1 }).delay(opts.duration/2).animate({ marginTop: 0, opacity: 1 }, { duration: opts.duration/2, easing: opts.easing });
	}
	
	// hide sub
	function hideSub( $sub, opts ) {
		// animate background arrow in menu item
		//$sub.stop().css({ marginTop: -$sub.outerHeight(), opacity: 0 });
		$sub.stop().fadeTo( opts.duration/3, 0, function(){
			$sub.hide();
		});
	}
	
	//
	// plugin defaults
	//
	$.fn.slideMenu.defaults = {
		easing: 'swing',
		expandedClass: 'expanded',
		activeClass: 'active',
		items: '.slideout',
		submenu: '.submenu ul',
		spacer: '.spacer',
		delay: 400,
		duration: 400,
		ratio: 2.5
	};
//
// end of closure
//
})(jQuery);

/* 
 *	Author: Christian Hermann Quinders
 */
//
// create closure
//
(function($) {
	//
	// plugin definition
	//
	$.fn.collapsibleContent = function(options) {
		
		// build main options before element iteration
		var opts = $.extend({}, $.fn.collapsibleContent.defaults, options);
		
		// iterate and reformat each matched element
		return this.each(function() {
			var $this = $(this),
				$toggle = $( opts.toggle, this ),
				$content = $( opts.content, this );
			
			$content.hide();
			$toggle.click(function(e) {
				if( $content.is(':visible') ) {
					//console.log('visible');
					$content.slideUp( opts.duration, 'easeOutQuad', function(){
						$this.removeClass( opts.status );
					});
				} else {
					//console.log('hidden');
					$content.slideDown( opts.duration, 'easeOutQuad', function() {
						$this.addClass( opts.status );
					});
				}
				e.preventDefault();
			});
			
		});
	};
	//
	// plugin defaults
	//
	$.fn.collapsibleContent.defaults = {
		toggle: '.collapsible-toggle',
		content: '.collapsible-content',
		status: 'collapsible-expanded',
		duration: 250
	};
//
// end of closure
//
})(jQuery);

/* 
	Author: Christian Hermann Quinders
*/
//
// create closure
//
(function($) {
	//
	// plugin definition
	//
	$.fn.trackEvent = function(options) {
		// return early if google analytics is not avilible
		if ( !window._gaq ) {
			//console.log('analytics not availible');
			return this;
		}
		// build main options before element iteration
		var opts = $.extend({}, $.fn.trackEvent.defaults, options);
		// bind event handler to each element and trigger event tracking
		return this.each(function () {
			var that = $(this),
				data = that.data('ga');
			//console.log(data);
			that.bind(opts.onEvent, function () {
				_gaq.push(['_trackEvent', data.category, data.action, data.label]);
			});
		});
	};
	//
	// plugin defaults
	//
	$.fn.trackEvent.defaults = {
		onEvent: 'click'
	};
//
// end of closure
//
})(jQuery);

(function($) {
	$.extend( $.easing,
	{
		def: 'easeOutQuad',
		easeInQuad: function (x, t, b, c, d) {
			return c*(t/=d)*t + b;
		},
		easeOutQuad: function (x, t, b, c, d) {
			return -c *(t/=d)*(t-2) + b;
		}
	});
})(jQuery);

