/*
 * Special event for image load events
 * Needed because some browsers does not trigger the event on cached images.
 * MIT License
 * Paul Irish     | @paul_irish | www.paulirish.com
 * Andree Hansson | @peolanha   | www.andreehansson.se
 * 2010.
 * Usage:
 * $(images).bind('load', function (e) {
 *   // Do stuff on load
 * });
 */
 /*
(function ($) {
	$.event.special.load = {
		add: function (hollaback) {
			if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
				// Image is already complete, fire the hollaback (fixes browser issues were cached
				// images isn't triggering the load event)
				if ( this.complete || this.readyState === 4 ) {
					hollaback.handler.apply(this);
				}				
				else {
					$(this).bind('load', hollaback.handler);
				}
			}
		}
	};
}(jQuery));
*/

var inScroll = false;

jQuery(document).ready(function() {
	
	
	// SET ACTIVE NAVI LINK
	$('.navi a, .homeLink').click(function() {
		$('.navi a, .homeLink').removeClass('active');
		$(this).addClass('active');
	});

    var sections = $('.section');
    $(window).scroll(function(event) {
        // only perform for manual scrolling, not during animation
        if (! inScroll) {
            var top = $(window).scrollTop();
            $('.navi a, .homeLink').removeClass('active');
            sections.each(function(i, el){
                var $el = $(el);
                if ( top > $el.offset().top - 400 && top < $el.offset().top + $el.outerHeight() - 100) {
		            $('.navi a[href=#' + el.id + ']').addClass('active');                
                }
            });
        }
        
    });
	

	// jQuery SmoothScroll | Version 10-04-30
	$('a[href*=#]').click(function() {
	
	   // duration in ms
	   var duration=600;
	
	   // easing values: swing | linear
	   var easing='swing';
	
	   // get / set parameters
	   var newHash=this.hash;
	   var target=$(this.hash).offset().top;
	   var oldLocation=window.location.href.replace(window.location.hash, '');
	   var newLocation=this;
	
	   // make sure it's the same location      
	   //if(oldLocation+newHash==newLocation) { /* ann. johannes: does not work with local urls in safari */
       if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
		  // animate to target and set the hash to the window.location after the animation
          inScroll = true;
          $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
	
			 // add new hash to the browser location
			 window.location.href=newLocation;
             inScroll = false;
		  });
	
		  // cancel default click action
		  return false;
	   }
	});
		
	// ADD DEFAULT GALLERY OVERLAYS
	
	$('<div class="overlay"></div>').insertAfter('.preview img, .fullSize img'); // 
	
	// HOVERS FOR GALLERY & SLIDESHOW ITEMS
	
	$('.chapter').hover(
		function() {$(this).find('.overlay').stop().animate({"opacity": "0"}, "fast");},
		function() {$(this).find('.overlay').stop().animate({"opacity": "0.9"}, "slow");}
	);
/*	
	$('.preview, .fullSize').hover(
		function() {$(this).find('.overlay').stop().animate({"opacity": "0.9"}, "fast");},
		function() {$(this).find('.overlay').stop().animate({"opacity": "0"}, "slow");
	});	
	*/
	
	// TOGGLE FOR ABOUT TEXTS
	
	//$('.textToggle').click(function() {$('#about').toggleClass("toggle")});
	
	
	// TOGGLE FOR ARCHIVE
	
	$('.archiveToggle').click(function() {
		$('.archiveToggle span').toggleClass("hidden");
		var $imgs = $('.archive .preview');
		var visible = ! $imgs.eq(0).hasClass("hidden");
		var size = $imgs.size() - 1;
		var duration = 50;
		$imgs.each(function(i, el) {
		    window.setTimeout(function(){$(el).toggleClass("hidden")}, visible ? duration * (size - i) : duration * i)
		    //alert(i);
		});
		//$('.archive .preview, .archiveToggle span').toggleClass("hidden");
	});
	
	
	// SLIDETOGGLE FOR LINKLIST
	
	/*$('#media h1').click(function() {
		$(this).next().slideToggle('fast', function() {
    	// Animation complete.
		});
	});*/


	// SLIDESHOW
	
	// activate slideshow mode
	$('.gallery li').click(function() {
	    startSlideshow($(this));
	});

	$('.slideshow li').click(function(event){
		event.stopPropagation();
		gotoSlide(this);
	});
	
	// deactivate slideshow mode
	$('.slideshow').click(function(){
		$(this).fadeOut("slow");
	});
	
	// eventuell re-center on resize?
	$(window).bind('resize', function(){
	   // duration in ms
	   var duration=500;
	
	   // easing values: swing | linear
	   var easing='swing';
        
		window.setTimeout(function(){
		    var target=$(window.location.hash).offset().top;
		    $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing);
		}, 5000);
    });
});

$(window).load(function () {
	// INTRO SLIDESHOW
	
	$('#intro').cycle({ 
        timeout:  5000, 
        speed:  700//'slow'
	}); 
	
});

var SLIDESHOW_LEFT_OFFSET = 40;

var focusItem = null;

function startSlideshow(thumbEl) {
	
	var sectionID = thumbEl.parents('.section').attr('id'); // what's my section's id?
	var slideshowID = "#" + sectionID + "Slideshow"; // assemble the name of the requested slideshow
	var slideshow = $(slideshowID); // cache the object in a reusable variable
	
	// we need to display the slideshow to have layout
	slideshow.css({display: 'block', opacity: 0});
	
	var img = $(thumbEl).find('img').last();
	var src = img.attr('src').replace('Preview','');

	focusItem = slideshow.find('li img[alt=' + src + ']').parent();
	if (focusItem.size() == 0) focusItem = $('.slideshow li img[src$=' + src + ']').parent();
	if (focusItem && focusItem.size() > 0) {
	    setTimeout(function(){gotoSlide(focusItem, true)}, 10);
	}
	else {
	    slideshow.find('.slideshowWrapper ul').css({left: SLIDESHOW_LEFT_OFFSET});
	}
	
	loadSlide(focusItem);	
	
	$('.slideshow').animate({opacity: 1.0}, 'slow');
	//$('.slideshow').fadeIn('slow');
}

function loadSlide(item) {
    var $item = $(item);
    var imgs = $item.find('img');
    if (imgs.size() > 0) {
        imgs.each(function(i, img) {
            if (img.src.indexOf('white.gif') > -1) {
                img.src = img.alt;
                img.alt = '';
            }
        });
        imgs.bind('load', function() {
            var $slide = $(this).parent();
            if (!$slide.data('loaded')) {
                $slide.data('loaded', true);
                if ($slide.get(0) == focusItem.get(0)) {
                	// load previous immediately for going back
                    var prev = $slide.prev();
                    if (prev.size() > 0) {
    	                loadSlide(prev);
    	            }
    	        }
                var next = $slide.next();
                if (next.size() == 0) {
                    next = $slide.parent().first();
                }
                if (!next.data('loaded')) {
                    loadSlide(next);
                }
            }
        });
    }
    else {
        $item.data('loaded', true);
        var next = $item.next();
        if (!next.data('loaded')) {
            loadSlide(next);
        }
    }
        
}

function gotoSlideNum(num, noAnim) {
	var items = $('.slideshow ul li');
    slide = items[num];
    gotoSlide(slide, noAnim);
}

function gotoSlide(slide, noAnim) {
    offset = -$(slide).position().left;
    if (offset < 0) {
        offset += SLIDESHOW_LEFT_OFFSET;
    }
    if (noAnim) {
        $('.slideshowWrapper ul').css({left:offset});
    }
    else {
        $('.slideshowWrapper ul').animate({left:offset});
    }   
}

