
/*
 * HeroSlideshow with Preloading
 *
 * copyright (c) 2010 Matthias H. Risse Interactive, 
 * all rights reserved.
 *
 * MODIFICATION AND USAGE WITHOUT AUTHORIZATION PROHIBITED BY 
 * NATIONAL AND INTERNATIONAL COPYRIGHT LAWS!  
 *
 * @version 1.5
 * @license risse.org
 * @copyright Matthias H. Risse (www.risse.org)
 */

/* config */
var slideWidth = 1100;
var topOffset = -10; // for all elements which are floating around
var mode = "slide"; // slide, fade, multi
var minWidth = 900;
var minHeight = 450;
var slideImageOffset = '-20px'; // Offset for images inside the slideshow (top of whitespace around image: 20px is normally allright)

var slideCount = 0;
var currentSlide = 0;
var currentSlideObj = null;
var currentPage;
var currentHash; // current # in url
var lock = 0;
var preLoadTotal = 0;
var preLoadCurrent = 0;
var agent=navigator.userAgent.toLowerCase();
	
var delme;
var delme2;

function enlargeWindowToMinimum() {
		self.moveTo(0,1);
		window.resizeTo(screen.availWidth,screen.availHeight);
		$('#page').stop().fadeIn(350);
		$('#enlargeWindow').stop().fadeOut(100);	
	}

/* Reposition Relative Elements */
function positionElements() {
	
	var is_iphone = (agent.indexOf('iphone')!=-1);
	if (!is_iphone) { 	
		if(window.innerHeight < minHeight || window.innerWidth < minWidth) {
			$('#page').fadeTo(100,0.2);
			$('#enlargeWindow').stop().fadeTo(100,1);
		} else {
			$('#page').stop().fadeTo(100,1);
			$('#enlargeWindow').stop().fadeTo(100,0);	
		}
	} else {
		// "resize" image for iphone (landscape format)
		$('')
	}
	
	
	// Get Current Window Infos
	winHeight = $(window).height()/2;
	winWidth = $(window).width()/2;
	
	
	
	// Reposition Sliders
	eleHeight = $('#heroSliderRight').height()/2;
	$('#heroSliderRight').css('top',winHeight-eleHeight+ topOffset);
	$('#heroSliderLeft').css('top',winHeight-eleHeight+ topOffset);
	
	// Reposition Main Navigation
	navMainWidth = $('#navMain').width();
	$('#navMain').css('position','absolute');
	$('#mavMain').css('top',0);
	$('#navMain').css('left',winWidth - navMainWidth/2)
	
	// Reposition SubNavigation (Level2)
	$('#navMain ul').css('position','absolute');
	$('#navMain ul').css('top',200);
	// $('#navMain ul').css('left',winWidth - navMainWidth/2)
	$('#navMain ul').css('left', $('#navMain ul').parent().css('left') );
	
	// Reposition heroSlider  (wrapper)
	heroWrapperWidth = $('#heroWrapper').width();
	heroWrapperHeight = $('#heroWrapper').height();
	$('#heroWrapper').css('position','absolute');
	$('#heroWrapper').css('top',winHeight - heroWrapperHeight/2 + topOffset);
	$('#heroWrapper').css('left',winWidth - heroWrapperWidth/2);
	
	// RepositionContent
	contentWidth = $('#content').width();
	contentHeight = $('#content').height();
	$('#content').css('position','absolute');
	$('#content').css('top',winHeight - contentHeight/2);
	$('#content').css('left',winWidth - contentWidth/2);
	
	// Addthis below pictures 
	syndicationOffset = 27;
	/* $('.addthis_toolbox').css('position','absolute');
	syndicationWidth = $('#syndication').width();
	$('#syndication').css('top',winHeight - heroWrapperHeight/2 + topOffset + heroWrapperHeight + topOffset + syndicationOffset);
	$('#syndication').css('left',winWidth - syndicationWidth/2 - 5);
	*/
	
	$('#heroWrapper').fadeIn('slow');
}

function initMousewheel() {
		$('#page').mousewheel(function(event, delta) {
			if (delta > 0.1) 
				left(1);
			else if (delta < -0.1)
				right(1);
			
			event.stopPropagation();
			event.preventDefault();
		});
	}

$(document).ready(function() {
	positionElements();
	initMousewheel();
	
	// position current meta below slide
	updateMeta();
	
	
	// Bind in the future to window-resize event
	$(window).resize(function(e){
		positionElements();
	}); // call it the first time below (FFbug?)
						
	
	// Analyze how mayn hero images we have in the dom
	slideCount = $('#stage').children().size() -1; // minus clearer
	
	// email defuscate
	$('.email').defuscate();	
	
	// Bind arrow keys 
	$(document).keydown(function(e){
								 
		if(slideCount>1) {
			if (e.keyCode == 37) { 
			   left(1);
			   return false;
			}
			
			 if (e.keyCode == 39) { 
			   right(1);
			   return false;
			}	
		}
		
		// up 38
		if (e.keyCode == 38) { 
			prevPage = ($('#navMain .current_page_item').prev().find('a').attr('href'));
			// console.log(prevPage);
			if(prevPage)
				document.location.href = prevPage;
				return false;
		}
		
		// down 40
		if (e.keyCode == 40) { 
			nextPage = ($('#navMain .current_page_item').next().find('a').attr('href'));
			// console.log(nextPage);
			if(nextPage)
				document.location.href = nextPage;
				return false;
		}
	});
	
	$('#hero').delay(800).fadeIn(
		
			{
				duration: 200,
				delay: 20
			}, 		
				{
					easing: 'easeOutCubic'
				} 
			)
	
	// Show thumbnails only if >1 image available
	// In case we have more than one image, launch navgation items
	if(slideCount>1) {
		$('#heroThumbs').delay(100).fadeIn(200);
		thumbActivate(0);	
		$('#heroSliderRight').delay(800).fadeIn(
		
			{
				duration: 200,
				delay: 20
			}, 		
				{
					easing: 'easeOutCubic'
				} 
			)
	
		$('#heroSliderLeft').click(function() {
			left(1);
			}
		);
		
		$('#heroSliderRight').click(function() {
			right(1);
			}
		);
	}

	// get current page for GA
	currentPage = ($('#navMain .current_page_item').find('a').attr('href'));
	
	// dispatch direct (hashed) link - for nav and GA
	currentHash = $(location).attr("hash").substr(1,20);
	// if(currentHash != "" || currentHash==" ") currentHash=0;
	goto(null,currentHash); // xe
	
	googleAnalyticsEvent();
	$('#navMain').fadeIn(350);
	$('#content').fadeIn(350);
	// heroPageTextCopy();
	
	// Unobstrusive Bindings
	// Menu
	$('#navMainWrapper').bind('mouseleave', function(e){
		$('#navMainWrapper').fadeTo("fast", 0.6);	
		return false;
		});
	
	$('#navMainWrapper').bind('mouseenter', function(e){
		$('#navMainWrapper').fadeTo("fast", 1);
		return false;
		});
	
	// fix png/shadow bug in all IEs (jq function deprecated, tho)
	if(!$.browser.msie)
	// Slider
	{
		$('#heroSliderLeft').bind('mouseleave', function(e){
			$('#heroSliderLeft').fadeTo("fast", 0.6);	
			return false;
			});
		
		$('#heroSliderLeft').bind('mouseenter', function(e){
			$('#heroSliderLeft').fadeTo("fast", 1);
			return false;
			});
		
		// Slider
		$('#heroSliderRight').bind('mouseleave', function(e){
			// if(!$('#heroSliderRight:animated'))
				$('#heroSliderRight').fadeTo("fast", 0.6);	
			return false;
			});
		
		$('#heroSliderRight').bind('mouseenter', function(e){
				// if(!$('#heroSliderRight:animated'))
				$('#heroSliderRight').fadeTo("fast", 1);
			return false;
			});	
	}
	
	// ThumbBar in/out
	$('#thumbWrapper').bind('mouseleave', function(e){
		$('#thumbWrapper').stop(true,false).animate({
				bottom: -44
			}, 		
				{
					duration: 600,
					easing: 'easeInOutCubic'
				} 
		);	
		return false;
		});
	
	$('#thumbWrapper').bind('mouseenter', function(e){
		$('#thumbWrapper').stop(true,false).animate({
				bottom: -20
			}, 		
				{
					duration: 300,
					easing: 'easeOutCubic'
				} 
		);	
		return false;
		});	
	
	$('#sidebar .widget').each(function(index) {
			// console.log($(this));
			
			// mouseenter
			$('#sidebar .widget').bind('mouseenter', function(e){
				$(this).stop().animate(
					{
						left: 0
					}, 		
					{
						duration: 750,
						easing: 'easeInOutCubic'
					} 
				);							
			});
			
			// mouseleave
			$('#sidebar .widget').bind('mouseleave', function(e){
				$(this).stop().animate(
					{
						left: -210
					}, 		
					{
						duration: 750,
						easing: 'easeInOutCubic'
					} 
				);							
			});
		
		// end inner
		}
   );
	
	
	// DEV
	 
	
	
	
	
    // Meta Information
	$('#hero .slideImage').each(function(index) {
			$(this).bind('mouseenter', function(e){
				$(this).parent().find('.slideMeta').stop(true,true).fadeIn(50);							
				$(this).css('cursor','pointer');
			});
			
			$(this).bind('mouseleave', function(e){
				$(this).parent().find('.slideMeta').stop(true,true).fadeOut(50);							
			});
			
		// end inner
		}
   );
	
	
	// SmartPhone Orientation Test

   // Set Inital orientation
    // get the initial orientation from window which
    // returns 0 for portrait and 1 for landscape
    if(window.orientation == 0){
        ori = "portrait";
    }else{
        ori = "landscape";
    }
    changeOrientation(ori);
 
    // Orientation Change
    // When orientation changes event is triggered
    // exposing an orientation property of either
    // landscape or portrait
    $('body').bind('orientationchange',function(event){
        changeOrientation(event.orientation)
    })
 
    // Change the style dependengt on orientation
    function changeOrientation(ori){
       
       // alert('iphone version is BETA, sorry. you changed orientation to ' + ori);
    }

	
	
	// mouseover on share/link
	$('#hero .navActionShare').each(function(index) {
			// mouseenter
			$(this).bind('mouseenter', function(e) {	
				syndicationsParent = $(this).parent().parent();
				syndications = $(syndicationsParent).find('.syndication');
				$(syndications).stop(true,false).fadeIn('fast');
			});
			
			// mouseleave
			$(this).bind('mouseleave', function(e) {
				syndicationsParent = $(this).parent().parent();
				syndications = $(syndicationsParent).find('.syndication');
				$(syndications).stop(true,false).fadeOut('fast');	
			});
		
		// end inner
		}
   );
	
	$('.swipe').swipe()
	
	// make pictures clickable (right)
	$('.slide').each(function(index) {
			$(this).click(function(e) {	
				right(1);
			});	
				
			// ipad/iphone
			
			$(this).swipe({
				swipeLeft: function() { right(1) },
				swipeRight: function() { left(1) },
			})
				
		// end inner
		}
   );
		
	// keep syndications from fading away
	$('#hero .syndication').each(function(index) {
				// mouseenter
				$(this).bind('mouseenter', function(e) {	
					$(this).stop(true,false).css('display','block');
					$(this).stop(true,false).css('opacity','1');
				});
				
				// mouseleave
				$(this).bind('mouseleave', function(e) {
					$(this).stop(true,false).fadeOut('fast');	
				});
			
			// end inner
			}
	   );
	
// *
});


function preLoadUpdate() {
		var l = 100/preLoadTotal*preLoadCurrent;
		$('#pageLoader p').text( Math.round(l) +'% LOADED');
		if(l==100) {
			// $('#pageLoader p').text('COMPLETE');
			$('#pageLoader').stop().fadeOut(500);
			}
	}; 

function left(steps) {
	if(currentSlide == 0) {
		return false;
		}
	
	var currentStagePos = -1*currentSlide * slideWidth;
	var scrollOffset = (currentStagePos + (steps * slideWidth));

	currentSlide = currentSlide - steps;
	
	if(currentSlide <= 0) {
		$('#heroSliderLeft').fadeOut('sow');
	} 
	
	if(currentSlide < slideCount)
		$('#heroSliderRight').fadeIn('fast');

	heroAnimate(scrollOffset);
	thumbActivate(currentSlide);
	}

function right(steps) {
	if(currentSlide + steps >= slideCount) {
		return false;
		}
	
	var currentStagePos = -1*currentSlide * slideWidth;
	var scrollOffset = (currentStagePos - (steps * slideWidth));
	
	currentSlide = currentSlide + steps;
	
	// center image again - in case something went wrong during the preloading process
	var currImgDiv = null;
	heroSlideWidth = $('#heroWrapper .slide:first').width();
	imageWidth = $(currImgDiv).width();
	$(currImgDiv).css('position','absolute');
	$(currImgDiv).css('top',slideImageOffset);
	$(currImgDiv).css('left',heroSlideWidth/2 - imageWidth/2)
	
	if(currentSlide > 0)
		$('#heroSliderLeft').fadeIn('slow');
	
	if(currentSlide+1 >= slideCount) {
		$('#heroSliderRight').fadeOut('slow');
	} 
	
	heroAnimate(scrollOffset);
	thumbActivate(currentSlide);
}

function updateMeta() {
	nowSlide = "#hero #slide-" + currentSlide;
	nowSlideImage = nowSlide + " .slideImage";
	nowSlidePreloader = nowSlide + " .slidePreloader";
	nowSlideMeta = nowSlide + " .slideMeta";
	nowSlideNavAction = nowSlide + " .NavAction";
	nowSlideImageWidth = $(nowSlideImage).width();
	$(nowSlideImage).stop(false,true).fadeIn('fast');
	// $(nowSlideMeta).stop(false,true).delay(200).fadeIn('fast');
	$(nowSlideNavAction).stop(false,true).delay(200).fadeIn('fast');
	$(nowSlidePreloader).stop(false,true).delay(200).fadeOut('fast');
	slideMeta = $('#hero .slideMeta').get(currentSlide);
	nowSlideMeta = "#hero #slide-" + currentSlide + " .slideMeta";
	// $(nowSlideMeta).stop().delay(650).fadeIn(500);
	$(slideMeta).css('position','absolute');
	nowMetaLeft =  ( $(nowSlide).width() / 2 ) - ( nowSlideImageWidth / 2 ) + 30;
	$(slideMeta).css('top','490px');
	$(slideMeta).css('left',nowMetaLeft); 
	
	}

function heroAnimate(scrollOffset) {
	// Copy Text for upcoming image, fadeout - change - fadein
	// heroPageTextCopy();
	
	// Update Hash
	$(location).attr('hash',currentSlide);
	googleAnalyticsEvent(null,null,currentSlide);
	

	updateMeta();
	// nowSlideImage.width()
	
	// nowSlideImageWidth
	
	/*
	navAction = $('#hero .navAction').get(currentSlide);
	$(navAction).stop().delay(650).fadeIn(500);
	$(navAction).css('position','absolute');
	$(navAction).css('top','466px'); 
	$(navAction).css('right',nowSlideImageWidth - 4 ); 
	$(navAction).delay(1200).fadeIn(500);
				
	syndication = $('#hero .syndication').get(currentSlide);
	// $(syndication).stop().delay(650).fadeIn(500);
	$(syndication).css('display','none');
	$(syndication).css('position','absolute');
	$(syndication).css('top','472px'); 
	$(syndication).css('right',nowSlideImageWidth -6); 
	*/
	/* end safari fixing */
	
	
	
	
	if(mode == 'slide') {
		
//		if(console) console.log(currentSlide + " // " + scrollOffset/slideWidth);
		
		duration = 1100;
		
		$('#stage').stop(false,false).animate(
			{
				left: scrollOffset
			}, 		
				{
					duration: duration,
					easing: 'easeInOutCubic'
				} 
			)
		return true;
	}

	if(mode == 'fade') {
		$('#stage').stop(false,true).fadeOut(200, function(event) {
			$(this).css('left',scrollOffset) ;
			$(this).stop(false,true).delay(200).fadeIn(200);										    
		});
		return true;
	}	
	
	/* @todo this mode is unfinished! */
	if(mode == 'multi') {
		
		var transitionTime = 2000;
		var halfScrollOffset = $('#stage').css('left').slice(-2) 
		halfScrollOffset = parseFloat(halfScrollOffset, 10) + scrollOffset/2;
		var halfTransitionTime = transitionTime/2;
		
		alert("current: " + $('#stage').css('left').slice(-2));
		
		
		// fadeout and scroll to half of the destination
		/*
		$('#stage').stop().animate(
			{
				left: halfScrollOffset,
				opacity:0,
			},
			halfTransitionTime,		
			function() {
				$('#stage').animate(
					{
					
					left: scrollOffset,
					opacity:1,
					},
					1000  
					)
			}
		)
		*/
	}	
	
}
	
function heroPageTextCopy () {
	/*
	srcObj = $('#heroWrapper .slide').get(currentSlide); // xe
	headline = $(srcObj).find('.slideHeadline').html();
	text = $(srcObj).find('.slideText').html();
	
	$('#pageText').stop(false,true).fadeOut(200, function() {
		$('#pageText .headline').html(headline);
		$('#pageText .subtext').html(text);
	});
	
	$('#pageText').delay(220).fadeIn();
	*/
	} 

// jump to a picture
function goto(obj,no) {
	// passed calling object has priority
	if(obj) {
		var step = obj.id.substring(9);	// id of caller must be "heroThumbINTEGER"	
		var stepOffset;
	} else {
		var step = no;
	}
	
	if(step == currentSlide) {	
		return;
		}
	
	if(step > currentSlide) {
		stepOffset =  step - currentSlide;
		right(stepOffset);
		}
	
	if(step < currentSlide) {
		// x nach links	
		stepOffset = currentSlide - step;
		left(stepOffset);
		}
}

function thumbActivate(no) {
	var target = '#heroThumb' + no;
	$('.heroThumb').stop(true,true).animate(
		{
			opacity: 0.5
		}, 		
		{
			duration: 20
		}
	)	
	
	$('.heroThumb').removeClass('active');
	
	$(target).stop(true,true).animate(
		{
			opacity:1
		}, 		
		{
			duration: 20
			
		}
	)	
	
	$(target).addClass('active');
}

// Google Analytics Event Triggering
function googleAnalyticsEvent(id,type,target) {	

  /*
	if(!id) id= currentPage;
	if(!type) type='view';
	if(!target) target = currentHash;
	// trigger google analytics event
	try {
		pageTracker._trackEvent(id, type, target);
	} catch(e) {
		console.log(e);
	}
	*/
	
}
