/**
 *
 * KW43 jQuery-Library v0.42
 *
 * (c) wysiwyg.de (last change: 2012-01-11)
 *
 * @author Dirk Loose (loose@wysiwyg.de)
 *
 */


/*******************************************************************
 * init namespaces after dom is ready
 ******************************************************************/
jQuery(document).ready(function () {

	var runKW43 = true;     // run this Namespace
	if (runKW43) KW43.init();
});


/*******************************************************************
 * init functions after window is loaded
 ******************************************************************/
jQuery(window).load(function () {
	KW43.setDimensions();
});


var KW43 = {

	// --- configuration-settings ---
	fadeGalleryDuration:10000, // ms for fade-duration
	fadeGallerySpeed:1200, // ms for transition-time of fade-animation
	animateNavDuration:700, // ms for navigation-animation
	animateLayerWidth:1160, // from this window-size the layer-animation will start
	fadeHoverDuration:500, // ms to fade in/out the hover effect (e.g. magazine)

	// --- initialize ---
	init:function (event) {


		/**
		 * bind event to resize
		 */
		$(window).bind('resize', function () {
			KW43.setDimensions();
		});

		// --- setDimensions on domready (needed for internet-explorer)
		KW43.setDimensions();
		// end block


		/**
		 * init fade-gallery
		 *
		 * more option can be found here:
		 * http://malsup.com/jquery/cycle/options.html
		 */
		if ($('#holder.holder ul')[0]) {
			$('#holder.holder ul').cycle({
				fx:'fade',
				prev:'.prev',
				next:'.next',
				timeout:KW43.fadeGalleryDuration,
				speed:KW43.fadeGallerySpeed,
				sync:1,
				containerResize:0,
				fit:0,
				slideResize:0,
				onPrevNextEvent:function (isNext, zeroBasedSlideIndex, slideElement) {
				}
			});
		}


		/**
		 * open/close navigation
		 */
			// --- open navigation ---
		$('#navigation a.open').bind('click', function (elem) {

			var myObj = $('#navigation');
			myObj.attr({rel:'close'});
			myObj.animate(
				{
					left:0
				},
				{
					duration:KW43.animateNavDuration,
					easing:'swing',
					queue:true,
					complete:function () {
						// make aniamtion depended on window-size
						if ($(window).width() >= KW43.animateLayerWidth) {
							KW43.setDimensions();
						}
					}
				}
			);

			$('#navigation a.close').removeClass('fullhidden');
			$('#navigation a.open').addClass('fullhidden');
		});

		// --- close navigation ---
		$('#navigation a.close').bind('click', function () {
			var myObj = $('#navigation');
			myObj.attr({rel:'close'});
			myObj.animate(
				{
					left:-272
				},
				{
					duration:KW43.animateNavDuration,
					easing:'swing',
					queue:true,
					complete:function () {
						// make aniamtion depended on window-size
						if ($(window).width() >= KW43.animateLayerWidth) {
							KW43.setDimensions();
						}
					}
				}
			);

			$('#navigation a.close').addClass('fullhidden');
			$('#navigation a.open').removeClass('fullhidden');
		});


		/**
		 * init jquery masonry
		 *
		 */
		if ($('#grid:not(#grid.customerlist)')[0] != undefined) {
			var $container = $('#grid');
			$container.imagesLoaded(function () {
				$container.masonry({
					itemSelector:'.item',
					// columnWidth : 278,
					// gutterWidth: 4,
					isFitWidth:false,
					isResizable:true,
					isAnimated:!Modernizr.csstransitions,
					animationOptions:{
						duration:750,
						easing:'linear',
						queue:false
					}

				});
			});

			/* init infinite scrolling, if pagination found */
			if ($('#pagenav a')[0] != undefined) {
				$container.infinitescroll({
						navSelector:'#pagenav', // selector for the paged navigation
						nextSelector:'#pagenav a:first', // selector for the NEXT link (to page 2)
						itemSelector:'.item', // selector for all items you'll retrieve
						debug:false,
						animate:false,
						donetext:'No more content to load.',
						loadingText:"loading",
						loadingImg:'/-img/loader.gif',
						errorCallback:function () {
							// fade out the error message after 2 seconds
							$('#infscr-loading').animate({opacity:.8}, 2000).fadeOut('normal');
						}
					},
					// trigger Masonry as a callback
					function (newElements) {
						var $newElems = $(newElements);
						// ensure that images load before adding to masonry layout
						$newElems.imagesLoaded(function () {
							$container.masonry('appended', $newElems, true);
						});
					}
				);

				// @TODO
				// bei sichtbarer paginierung hier per click nachladen
				$('#appendItemsInfinite').bind('click', function (elem) {
					$(document).trigger('retrieve.infscr');
				});
			}

		}


		if ($('.infinite')[0] != undefined) {

			var $container = $('.infinite');

			/* init infinite scrolling, if pagination found */
			if ($('#pagenav a')[0] != undefined) {
				$container.infinitescroll({
						navSelector:'#pagenav', // selector for the paged navigation
						nextSelector:'#pagenav a:first', // selector for the NEXT link (to page 2)
						itemSelector:'.item', // selector for all items you'll retrieve
						debug:false,
						animate:false,
						donetext:'No more content to load.',
						loadingText:"loading",
						loadingImg:'/-img/loader.gif',
						errorCallback:function () {
							// fade out the error message after 2 seconds
							$('#infscr-loading').animate({opacity:.8}, 2000).fadeOut('normal');
						}
					}
					/*,
					 // trigger Masonry as a callback
					 function(newElements) {

					 var isMasonry = $.isFunction($.fn.masonry);
					 if (isMasonry) {
					 var $newElems = $(newElements);
					 // ensure that images load before adding to masonry layout
					 $newElems.imagesLoaded(function() {
					 $container.masonry('appended', $newElems, true);
					 });
					 }
					 }*/
				);

				// @TODO
				// bei sichtbarer paginierung hier per click nachladen
				$('#appendItemsInfinite').bind('click', function (elem) {
					$(document).trigger('retrieve.infscr');
				});
			}
		}

		/**
		 * item-hover and click
		 */
		$('#grid .item,#grid .customer-item, ul.award-logos li').live('mouseenter', function () {
			// $(this).find('div.highlight').switchClass('', 'active', KW43.fadeHoverDuration)
			$(this).find('div.highlight').toggleClass('active', KW43.fadeHoverDuration);
		});

		$('#grid .item,#grid .customer-item, ul.award-logos li').live('mouseleave', function () {
			// $(this).find('div.highlight').switchClass('active', '', KW43.fadeHoverDuration)
			$(this).find('div.highlight').toggleClass('active', KW43.fadeHoverDuration);
		});


		/**
		 * team-hover with fade
		 *
		 */
		var myFadeEasing = 'easeInOutQuart'; // swing, easeInOutElastic, easeInOutCubic, easeOutQuart
		$('#team .item div.teamImage').bind('mouseenter', function () {

			/*
			 $(this).find('img').fadeOut(500, myFadeEasing);
			 $(this).closest('img').fadeIn(500, myFadeEasing);
			 */

			$(this).find('img').animate(
				{
					opacity:0
				},
				{
					duration:500,
					easing:myFadeEasing,
					queue:false,
					complete:function () {
						// animation complete
					}

				});

			$(this).closest('img').animate(
				{
					opacity:1
				},
				{
					duration:500,
					easing:myFadeEasing,
					queue:false,
					complete:function () {
						// animation complete
					}
				});

		});

		$('#team .item div.teamImage').bind('mouseleave', function () {

			/*
			 $(this).closest('img').fadeOut(500, myFadeEasing);
			 $(this).find('img').fadeIn(500, myFadeEasing);
			 */

			$(this).closest('img').animate(
				{
					opacity:0
				},
				{
					duration:500,
					easing:myFadeEasing,
					queue:false,
					complete:function () {
						// animation complete
					}
				});

			$(this).find('img').animate(
				{
					'opacity':1,
					'background-color':'#f00'
				},
				{
					duration:500,
					easing:myFadeEasing,
					queue:false,
					complete:function () {
						// animation complete
					}
				});

		});


		/**
		 * fade navigation-links
		 *
		 */
		var myFadeDuration = 500;
		$('#navigation ul li:not(.actualPosition) a,#navigation div.footer p a:not(.active)').bind('mouseenter', function () {

			$(this).animate(
				{
					color:'#f21a00'
				},
				{
					duration:myFadeDuration,
					easing:'easeInOutQuart', // swing, easeInOutElastic, easeInOutCubic, easeOutQuart
					queue:false,
					complete:function () {
						// animation complete
					}
				});
		});
		$('#navigation ul li:not(.actualPosition) a,#navigation div.footer p a:not(.active)').bind('mouseleave', function () {

			$(this).animate(
				{
					color:'#c8c8c8'
				},
				{
					duration:myFadeDuration,
					easing:'easeInOutQuart', // swing, easeInOutElastic, easeInOutCubic, easeOutQuart
					queue:false,
					complete:function () {
						// animation complete
					}
				});
		});


		/**
		 * this is the short version for customer-item (kunden)
		 *
		 */
//         $('#grid .customer-item').hover( function() {
//             $(this).find('div.highlight').toggleClass('active', KW43.fadeHoverDuration);
//         });

		var myIsotopeSelector = '',
			myIsotopeItem = '',
			myIsotopeShuffle = false;
		if ($('#team')[0]) {
			myIsotopeSelector = '#team';
			myIsotopeItem = 'div.item';
			myIsotopeShuffle = true;
		}
		if ($('#grid.customerlist')[0]) {
			myIsotopeSelector = '#grid.customerlist';
			myIsotopeItem = 'div.customer-item';
			myIsotopeShuffle = true;
		}

		if (myIsotopeSelector != '') {
			KW43.initIsotope(myIsotopeSelector, myIsotopeItem, myIsotopeShuffle);
		}

	},


	/**
	 * init Isotope
	 *
	 */
	initIsotope:function (selector, item, doShuffle) {

		var container = $(selector);

		container.isotope({
			// options
			animationEngine:'best-available',
			transformsEnabled:true,
			hiddenStyle:{ opacity:0.0, scale:0.001 },
			visibleStyle:{ opacity:1, scale:1.0 },

			itemSelector:item,
			layoutMode:'masonry',

			resizesContainer:true,
			getSortData:{
				position:function ($elem) {
					return $elem.attr('data-position');
				},
				randomizer:function ($elem) {
					return $elem.attr('data-randomizer');
				},
				hasLink:function ($elem) {
					return $elem.attr('data-haslink');
				}
			}

		});


		// start-animation (sort random)
		setTimeout(function () {

			// --- shuffle
			if (doShuffle) {
				container.isotope('shuffle');
			}

			// --- sort
			if (selector === '#team') {
				// container.isotope({ sortBy : 'random'});
				container.isotope({ sortBy:'position' });
			}

			// --- sort filled by email
			if (selector === '#grid.customerlist') {
				container.isotope({ sortBy:'hasLink' });
			}

		}, 200);

	},


	/**
	 * set dimensions for navigation (adapted from mootools for testing in jQuery)
	 */
	setDimensions:function () {

		var holderOffset = 16;	        // top/bottom offset of calculated items
		// var layerOffset = 20;	        // left and right offset of layer
		// var layerPaddingX = 30;         // padding offset of the layer
		var layerBottom = 30;	        // bottom offset of the layer
		var layerHeightCorrection = 24; // correction for jquery offset for height

		// --- define needed objects
		var myBodyContent = $('#bodyContent');
		var myListItems = $('#holder ul li');

		// --- set height of slideshow-holder
		var myDocumentDimension = $(window).height();
		var myElementsHeight = 0;
		$('.calculateHeight').each(function () {
			myElementsHeight = myElementsHeight + $(this).height();
		});

		var myHolderHeight = myDocumentDimension - myElementsHeight - holderOffset;
		var myHolder = $('#holder');
		myHolder.css('height', myHolderHeight);


		var myLayers = myListItems.children('div.layer');  // --- TEST div.layer

		myLayers.each(function (index, domElement) {

			// var myHeight = $(domElement).height() + layerHeightCorrection;

			var myData = jQuery.parseJSON($(domElement).attr('data-styles'));
			var myHeight = Math.floor(myData.height) + layerHeightCorrection;

			var myTop = $(myHolder[0]).height();
			$(domElement).css({
				'height':myData.height,
				'opacity':myData.opacity,
				'width':myData.width,
				'background-color':myData.background_color,
				'top':myTop - myHeight - layerBottom
			});
		});

		// --- set size of navigation
		var myNavigationPadding = parseInt($('#navigation .menu').css('padding-top'));
		var myNavigation = $('#navigation .menu');
		myNavigation.css('height', myHolderHeight - myNavigationPadding);


		// --- set viewPort of images
		var myImages = $('#holder ul li img');
		var viewPort = 'landscape';
		myImages.each(function (index, domElement) {

			var theWindow = $('#holder'), // $(window) | $('#holder')
				myAspectRatio = 1400 / 900;
			// myAspectRatio = 1400 / 820;
			// myAspectRatio = 1400 / 990;

			viewPort = ( (theWindow.width() / theWindow.height()) < myAspectRatio ) ? 'portrait' : 'landscape';
			(viewPort == 'portrait') ? $(domElement).css('min-height', myHolderHeight) : $(domElement).css('min-height', '');

			$(domElement).removeClass().addClass(viewPort);
		});

	}

};


/**
 * output to console, if console.log exists
 *
 * usage: log(message);
 */
jQuery.fn.log = function (message) {
	if (typeof console.log != "undefined" || typeof jQuery.fn.console.log == 'function') {
		console.log(message);
	}
};


