/**
 * triplexPromoSlides
 * 
 * @author Robert Roemer, triplex neue medien GmbH
 * @version 1.0.0
 * @date 12.03.2011
 */

var promo_timer;

(function(jQuery){
	jQuery.fn.triplexPromoSlides = function(options) {
	
		var settings = {
			'slides': {
				'duration'		: 2000,
				'autoplay'		: true,
				'delay'			: 9000
			},
			'nav': {
				'duration'		: 1000
			},
			'customEvents': {
					'beforeInitNavigation': function(){},
					'afterInitNavigation': function(){},
					'onNavEntryMouseover': function(){},
					'onNavEntryMouseout': function(){},
					'beforeShowSlide': function(){},
					'afterShowSlide': function(){}
			}
		};
	
		function debug(variable) {
			if (window.console !== undefined) {
				console.log(variable);
			}
		}
	
		return this.each(function() {
			if (options) { 
				jQuery.extend(true, settings, options);
			}
			initSlides();
			initNavigation();

			var hash = window.location.hash;
			var index = 1;

			if ( hash.substring(0, 7) == '#promo_' )	{
				index = parseInt(hash.substr(7));
			}

			if ( (index >= 1) == false ) {
				index = 1;
			}
			
			getNavigation().find('a:eq('+(index-1)+')').trigger('click');
			
			var stage = getStage();
			var playstate = stage.find('.playstate');
			if ( playstate.length == 0 ) {
				stage.append('<a class="playstate" href="#">&nbsp;</a>');
				playstate = stage.find('.playstate');
			}

			playstate.unbind('click').bind('click', function() {
				togglePlay();
				return false;
			});

			// add event trigger to switch between the pages
			getStage().unbind('mouseenter').bind('mouseenter', function(){
				triggerCustomEvent('onStageMouseover', jQuery(this));
				pauseTimer();
			}).unbind('mouseleave').bind('mouseleave', function(){
				triggerCustomEvent('onStageMouseout', jQuery(this));
				startTimer();
			});
			
			window.onblur=function() {
				pauseTimer();
			}
			window.onfocus=function() {
				startTimer();
			}
			
			return true;
		});

		function triggerCustomEvent(name, params) {
			if ( settings.customEvents[name] !== undefined && typeof settings.customEvents[name] == 'function' ) {
				return settings.customEvents[name](params);
			}

			return null;
		}

		/*
		 * return the node of the stage as jQuery object
		 */
		function getStage() {
			var stage = jQuery('.promo .stage');

			if ( stage.length == 0 ) {
				jQuery('.promo').append('<div class="stage"></div>');
				stage = jQuery('.promo .stage');
			}

			return stage;
		}




/*
 *
 * Navigation related Methods
 *
 */
		/*
		 * return the node of the navigation as jQuery object
		 */
		function getNavigation() {
			var nav		= jQuery('.promo').children('.nav');
			return nav;
		}

		/*
		 * apply event triggers and functions to the navigation entries
		 */
		function initNavigation() {
			var nav		= getNavigation();
			var entries = nav.find('li');

			entries.find('.loading').css({'backgroundPosition': '-220px 15px'});
				
			if ( triggerCustomEvent('beforeInitNavigation', {'nav': nav, 'entries': entries}) == false ) {
				return false;
			}

			// add event trigger to switch between the pages
			entries.find('a').unbind('click').click(function(){
				var parent = jQuery(this).parent();
				var promo_id = parent.index();
				
				if ( triggerCustomEvent('beforeNavigationClick', jQuery(this)) !== false ) {
					showSlide(promo_id);
				}

				triggerCustomEvent('afterNavigationClick', {'promo_no': promo_id, 'entry': parent});
				return false;
			}).unbind('mouseenter').bind('mouseenter', function(){
				triggerCustomEvent('onNavEntryMouseover', jQuery(this));
				pauseTimer();
			}).unbind('mouseleave').bind('mouseleave', function(){
				triggerCustomEvent('onNavEntryMouseout', jQuery(this));
				startTimer();
			});

			triggerCustomEvent('afterInitNavigation', {'nav': nav, 'entries': entries});
		}

/*
 *
 * Slides related Methods
 *
 */
		function showSlide(index) {
			var stage			= getStage();

			if ( triggerCustomEvent('beforeShowSlide', settings.curPageObj) == false ) {
				return false;
			}

			if ( stage.hasClass('animating') == true ) {
				return false;
			}
				
			stage.addClass('animating');

			var st = jQuery('html').scrollTop();

			if ( (index === 0 || index >= 1) == false ) {
				index = 0;
			}

			var slides_wrapper	= stage.children('ul');
			var active			= slides_wrapper.children('li.active:eq(0)');
			var next			= slides_wrapper.children('li:eq('+index+')');
			
			if ( active.length > 0 && active.index() != index ) {
				switchSlides(active, next);
			} else {
				displaySlide(active);
				release();
			}

			triggerCustomEvent('afterShowSlide', settings.curPageObj);
		}

		function release() {
			getStage().removeClass('animating');
		}

		function initSlides() {
			getStage().find('li li').hide();
		}

		/*
		 * helper function to get the browser width
		 */
		function getBrowserWidth() {
			return jQuery('body').outerWidth(true);
		}

		
		/*
		 * activate a slide without animation
		 */
		function displaySlide(slide) {
			slide.css({'left': 0}).addClass('active').find('li').show(1).css({'left': 0});
			settings.curIndex	= slide.index();
			getNavLinkEl().find('.info').css({'marginTop': '20px'});
			getNavLinkEl(settings.curIndex).find('img').css({'backgroundPosition': '0 20px'});
			getNavLinkEl(settings.curIndex).find('.info').css({'marginTop': '0px'});
			startTimer();
		}

		
		/*
		 * hide the current slide and display a other
		 */
		function switchSlides(to_hide, to_show) {
			pauseTimer();

			var browser_width	= getBrowserWidth();
			var width			= to_hide.parent().outerWidth(true);
			var offset			= Math.round(browser_width / 2) + width;

			var duration		= settings.slides.duration;
			var n_duration		= settings.nav.duration;

			if (navigator && navigator.platform && navigator.platform.match(/^(iPad|iPod|iPhone)$/)) {
				duration = 0;
				n_duration = 0;
			}

			var h_layers		= to_hide.find('li');
			var h_average		= Math.floor(duration / h_layers.length);


			var inactive_links	= getNavLinkEl(to_hide.index()).removeClass('active');
			inactive_links.find('img').animate({'backgroundPosition': '0 110px'}, n_duration);
			inactive_links.find('.info').animate({'marginTop': '20px'}, n_duration, function(){
				inactive_links.removeClass('ready');
			});
			
			var hide_offset = offset;
			var show_offset = offset;
			
			if ( (to_hide.index() == 3 && to_show.index() == 0) || to_hide.index() < to_show.index() ) {
				hide_offset *= -1;
			} else {
				show_offset *= -1;
			}
			
			h_layers.each(function(index, item){
				if ( hide_offset < 0 ) {
					var h_duration	= h_average * (index + 1);
				}else {
					var h_duration	= h_average * (h_layers.length - index);
				}
				var h_duration	= h_average * (index + 1);

				jQuery(item).animate({'left': hide_offset+'px'}, h_duration, function() {
					to_hide.removeClass('active');
					to_show.addClass('active');
				});
			});

			to_hide.removeClass('active');
			to_show.addClass('active');
			settings.curIndex = to_show.index();
			//startTimer();

			var active_link = getNavLinkEl(to_show.index()).addClass('active');
			active_link.find('img').animate({'backgroundPosition': '0 20px'}, n_duration);
			active_link.find('.info').animate({'marginTop': '0px'}, n_duration, function(){
				active_link.addClass('ready');
			});
			
			var s_layers		= to_show.find('li');
			var s_average		= Math.floor(duration / s_layers.length);
			s_layers.css({'left': show_offset+'px'}).show(1).each(function(index, item){
				var s_duration	= show_offset < 0 ? s_average * (s_layers.length - index) : s_average * (index + 1);
				jQuery(item).animate({'left': 0}, s_duration, function() {
					if ( (show_offset > 0 && index >= s_layers.length-1) || (show_offset < 0 && index == 0)  ) {
						release();
						settings.curIndex = to_show.index();
						getStage().children('ul').find('li:eq('+settings.curIndex+')').addClass('active');
						startTimer();
					}
				});
			});
		}

		function getNavLinkEl(index) {
			var nav	= getNavigation();
			var t;

			if ( index !== null && index >= 0 ) {
				t = nav.find('li:eq('+index+') a');
			} else {
				t = nav.find('li a');
			}

			return t;
		}
		
		function deactivateNavigationEntry() {
			
		}

		function activateNavigationEntry() {
		}

		function startTimer() {
			var stage = getStage();
			if ( stage.hasClass('paused') || stage.hasClass('stopped') || settings.slides.autoplay == false ) {
				return false;
			}
			
			var loader = getNavLinkEl().find('.loading');
			var active = loader.eq(settings.curIndex);
			var not_active = loader.not('*:eq('+settings.curIndex+')').css({'backgroundPosition': '-220px 15px'});

			var t_pos = active[0].style.backgroundPosition.split(' ')[0];
			if ( t_pos == undefined ) {
				t_pos = '-220px';
			}

			var position = Math.abs( parseInt(t_pos) );

			var duration = Math.round( (settings.slides.delay / 220) * position ); 
			pauseTimer();
			promo_timer = setTimeout("jQuery('.promo .stage .right').trigger('click');", duration);
			active.animate({'backgroundPosition': '0 15px'}, duration, 'linear');
		}
		
		function pauseTimer() {
			clearTimeout(promo_timer);
			getNavLinkEl(settings.curIndex).find('.loading').stop();
		}
		
		function togglePlay() {
			var stage = getStage();
			
			if ( stage.hasClass('stopped') == false ) {
				stage.addClass('paused').addClass('stopped');
				pauseTimer();
			} else {
				stage.removeClass('paused').removeClass('stopped');
				startTimer();
			}
		}
	};
})(jQuery);

jQuery.fx.interval = 13;
