/*
 * Gisle Nes 2010
 * gisle@gisle.net
 */

/* Global config-variables */
var thumbHeight = 100;
var pixelsPerSec = 500;
var refreshRate = 5; 
var fadeDuration = 250;

var swipeSupport = ('ontouchstart' in document.documentElement);

kk.Ui.fullView('.fullViewImg:not(.noCrop,.auto)', 'body', { wrap: true, fadeFirst: 500 });
kk.Ui.fullView('.fullViewImg.noCrop', 'body', { wrap: true, noCrop: true, fadeFirst: 500 });
kk.Ui.fullView('.fullViewImg.auto', 'body', { wrap: true, mode: 'auto', fadeFirst: 500 });
kk.interactor('.nextInteractor', function() { kk('p').next(); });
kk.interactor('.prevInteractor', function() { kk('p').previous(); });
kk.interactor('a:not(.custom)', { fadeToNothing: true, fadeNothing: true, popupRemote: true });

if (Kveik.touchSupport) {
	kk.loader({ url: '/graphics/twirlYellow16.png', frames: 10, backwards: true, position: 'center' });
} else {
	kk.interactor('.galleryInteractor', { noHash: true, elements: 'p' });
	kk.loader({ url: '/graphics/twirlYellow16.png', frames: 10, backwards: true });
}

// Google analytics
kk.ga('UA-19988770-1');

var clickEvent = (Kveik.touchSupport) ? 'touchstart' : 'click';

$(document).ready(function() {
	// Arrow-keys
	$(document).keydown(function(e) {
		if ( e.keyCode == 37 ) kk('p').previous();
		else if ( e.keyCode == 39 ) kk('p').next();
	});
});

// Remove "old" states to free up memory for tablets (6MB(!) limit on iPad 2)
if (Kveik.touchSupport && false) {
	kk._stateCache = [], kk._stateVersion = 0, kk._cacheSize = 3;
	Kveik.bind('preparedState', function(state) {
		// Keep a link back to _stateCache index
		state._index = kk._stateCache.length;
		kk._stateCache.push({ state: state, version: kk._stateVersion, index: state._index });
	});

	Kveik.bind('postShowStates', function() {
		var activeIndexes = {};

		// Iterate through all elements to update their state
		var states = [];
		states.push(kk.root.get().currentState);
		while(states.length > 0) {
			var state = states.pop();

			// Mark as active
			activeIndexes[state._index] = true;

			// Update version 
			kk._stateCache[state._index].version = kk._stateVersion;

			var elements = state.children;
			for (var i in elements) states.push(elements[i].currentState);
		};

		// Only keep *cacheSize* number of inactive states
		var clone = $.extend([], kk._stateCache);
		clone.sort(function(a,b) {
			if (a.version > b.version) return 1;
			return -1;
		});
		var kept = 0;
		for (var i=0; i<clone.length; i++) {
			if (!clone[i] || activeIndexes[clone[i].index] || kept++ < kk._cacheSize) continue;
			clone[i].state.remove();
			kk._stateCache[clone[i].index] = false;
		}

		// Increase stateCounter
		kk._stateVersion++;
	});
}


kk.bind('loaded', function() {
	$('.nextInteractor:not(.bound),.prevInteractor:not(.bound),.galleryInteractor:not(.bound)').each(function() {
		/* Remove link-href, to avoid chrome-statusbar popping up */
		$(this).data('href', $(this).attr('href'));					
		$(this).removeAttr('href').css('cursor', 'pointer');
	}).addClass('bound');

	/* Header-hover */
	if (!Kveik.touchSupport) {
		$('.header.hover:not(.bound)').hover(function() {
			$(this).stop().fadeTo(fadeDuration, 1.0);
		}, function() {
			$(this).stop().fadeTo(fadeDuration, 0.0);
		}).addClass('bound');
	}

	/* Credits-link */
	$('.credits .open:not(.bound)').bind(clickEvent, function(e) {
		var $pop = $(this).closest('.credits').find('.popup');
		if ($pop.is(':hidden')) {
	 		$pop.fadeTo(150, 1.0);
			$(this).fadeTo(150, 1.0);
			var that = this;
			$('body').one(clickEvent, function() {
				if (!$pop.is(':hidden')) {
					$pop.stop().fadeOut(150);
					$(that).fadeTo(150, 0.4, resetOpacity);
				}
			});
		}
		else {
			$pop.stop().fadeOut(150);
			$(this).fadeTo(150, 0.4, resetOpacity);
		}
		e.stopPropagation();
	}).addClass('bound');

	/* Open thumbnails */
	var openThumbs = function() {
		var that = this;
		var $slider = $(this).find('.slider');
		$slider.stop().animate({ height: thumbHeight }, 200, function() {
			$(that).data('open', true);				
		});
		cancelHideThumbs.apply(this);
	};
	// Close thumbnails
	var closeThumbs = function() {
		var that = this;
		$(this).find('.slider').stop().animate({ height: 0}, 200, function() {
			$(that).data('open', false);						
		});
	};
	// Cancel hide timer
	var cancelHideThumbs = function(scope) {
		var $slider = $(scope || this).find('.slider');
		var hideTimer = $slider.data('hideTimer');
		if (hideTimer) {
			clearTimeout(hideTimer);
			$slider.data('hideTimer', false);
		}
	};
	var toggleThumbs = function () {
		var $thumbs = $(this).closest('.thumbnails');
		if ($thumbs.data('open') === true) closeThumbs.apply($thumbs[0]);
		else openThumbs.apply($thumbs[0]);
	};
	var noScroll = function() {
		return false;
	};
	// Bind events
	$('.thumbnails:not(.initiated)')
	 .bind('mouseenter', openThumbs)
	 .bind('mouseleave', closeThumbs)
	 .bind('touchstart', cancelHideThumbs)
	 .addClass('initiated');
	$('.thumbnails .clickArea:not(.initiated)')
	 .bind('touchstart', toggleThumbs)
	 .bind('touchmove', noScroll)
	 .addClass('initiated');
	$('.header:not(.initiated)')
	 .bind('touchmove', noScroll)
	 .addClass('initiated');
	

	/* Scroll-animation for thumbnails */
	$('.thumbnails .images:not(.initiated)').mousemove(function(e) {
		if (swipeSupport) return;

		var left = e.pageX - $(this).parent().offset().left;
		var perc = left / $(this).parent().width();

		var $images = $(this);
		var animation = $images.data('animation');
		if (!animation) return;

		if (perc >= 0.6 || perc <= 0.4) {
			if (perc >= 0.6) animation.relPerc = -(perc-0.6)/0.4;
			else animation.relPerc = (0.4-perc)/0.4;

			if (!animation.animation) {
				var loop = function() {
					var time, diff, speed;
					time = (new Date).getTime();
					diff	= (animation.time) ? time-animation.time : refreshRate;
					animation.time = time;
					speed = pixelsPerSec*diff/1000 * animation.relPerc * Math.abs(animation.relPerc);

					animation.currentPos = animation.currentPos + speed;
					if (animation.currentPos > 0) {
					 	animation.currentPos = 0;
						$images.css({'left': animation.currentPos});
						return;
					}
					else if (animation.currentPos < animation.end && speed < 0) {
						animation.currentPos = animation.end;
						$images.css({'left': animation.currentPos});
						return;
					}
					$images.css({'left': animation.currentPos});
					animation.animation = setTimeout(loop, refreshRate);
				};
				loop();
			}
		} else {
			if (animation.animation) clearTimeout( animation.animation );
			delete(animation.animation);
			delete(animation.time);
		}
	}).hover(function(e) {
		if (swipeSupport) return;

		var $images = $(this);
		var animation = $images.data('animation') || {};	
		// Update animation-properties
		animation.$lastImg = $images.find('.' + kk.stateClass + ':not(:hidden)').find('img:last');
	 	animation.start = animation.start || $images.offset().left;
		animation.end = -(animation.$lastImg.offset().left + animation.$lastImg.width()) + $images.parent().width() + (parseInt($images.css('left')) || 0);
		if (animation.end > 0) animation.end = 0;
		animation.currentPos = animation.currentPos;
		if (typeof(animation.currentPos) === 'undefined') animation.currentPos = $(this).offset().left;
		$images.data('animation', animation);
	}, function() {
		var animation = $(this).data('animation') || {};
		if (animation.animation) clearTimeout( animation.animation );
		delete(animation.time);
		delete(animation.animation);
	})
	// iPhone swipe
	.bind('touchstart', function(ev) {	
		$(this).data('targetLink', $(this).find('a:hover'));
	})
	.bind('touchmove', function(ev) {
		var e = ev.originalEvent;
		var animation = $(this).data('animation') || {};
		var prevX = $(this).data('prevX');

		// Initialize
		if (!prevX) {
			cancelHideThumbs.apply($(this).closest('.thumbnails')[0]);
			$(this).data('prevX', e.targetTouches[0].clientX);
			startX = $(this).data('prevX'); 
			return;
		}

		var delta = (prevX - e.targetTouches[0].clientX);
		$(this).data('prevX', e.targetTouches[0].clientX);
		var newLeft = (parseInt($(this).css('left')) || 0) - delta;
		var $lastImg = $(this).find('img:last');

		// Make sure swipe is not out of bounds
		var end = -($lastImg.offset().left+$lastImg.outerWidth())+$(this).parent().outerWidth()+parseInt($(this).css('left') || 0);
		if (newLeft > 0) newLeft = 0;
		if (newLeft < end) newLeft = end;
		$(this).css('left', newLeft); 
		ev.preventDefault();
		return false;
	}).bind('touchend', function(ev) {
		if (!$(this).data('prevX')) {
			var $link = $(this).data('targetLink');
			if ($link.length < 0) return;
			var url = $link.data('href');
			if (url) Kveik.goTo(url, {elements: 'p'});
		}
		$(this).data('startX', '').data('prevX', '');
		ev.preventDefault();	
		return false;
	}).each(function() {
		
	}).addClass('initiated');

	/* Dynamic color images */
	$('.dynamicColor.image:not(.init)').each(function() {
		var $inner = $('<span class="inner">');
		$inner.backgroundPositionY('-100%').css({opacity: 0, width: '100%', height: '100%', display: 'block' });
		$inner.css('backgroundImage', $(this).css('backgroundImage'));
		$(this).wrapInner($inner);
	}).addClass('init');

	$('.gallery.overlay:not(.bound)').bind('touchmove', function(ev) {
		ev.preventDefault();
	}).addClass('bound');

	/* Image-hover */
	if (!Kveik.touchSupport) $('.dynamicColor.dynamicHover.image:not(.bound)').hover(function() {
		var opacity = $(this).find('.inner').data('_opacity');
		if (opacity > 0.5) opacity -= 0.2; 
		else opacity += 0.2;
		$(this).find('.inner').stop().animate({ opacity: opacity }, 150);
	}, function() {
		var opacity = $(this).find('.inner').data('_opacity');
		$(this).find('.inner').stop().animate({ opacity: opacity }, 150);
	});

});

kk.updateColors = function(e, s) {
	if (!s) s = { property: function() {} };

	var bgColor = s.property('bg') || '#000000';
	var hdColor = s.property('hd') || 100;
	var duration = 150;

	if (bgColor) $('body,html').stop().animate({ backgroundColor: bgColor }, duration);

	var opacity = hdColor / 100;
	opacity = (opacity > 1) ? 1 : opacity;
	opacity = (opacity < 0) ? 0 : opacity;
	var color = 'rgb(' + parseInt(opacity*255) + ',' + parseInt(opacity*255) + ',' + parseInt(opacity*255) + ')';
	// Check if IE
	//
	$('.dynamicColor:not(.dynamicBorder)').stop().animate({ color: color }, duration);
	$('.dynamicBorder:not(.dynamicColor)').stop().animate({ borderTopColor: color, borderRightColor: color, borderBottomColor: color, borderLeftColor: color }, duration);
	$('.dynamicBorder.dynamicColor').stop().animate({ color: color, borderTopColor: color, borderRightColor: color, borderBottomColor: color, borderLeftColor: color }, duration);
	$('.dynamicColor.image .inner').stop().animate({ opacity: 1-opacity }, duration);

	// Helper for hover-functions
	$('.dynamicColor.text').data('_color', color);
	$('.dynamicColor.image .inner').data('_opacity', 1-opacity);
};

var resetOpacity = function() { $(this).stop().css('opacity', ''); };

var showThumbs = function(e, s) {
  if (!s.$state) return;

	if (s.$state.find('a').length <= 0 || s.$state.find('.noCat').length > 0) {
		s.$state.closest('.thumbnails').stop().fadeOut();
		return;
	} else {
		s.$state.closest('.thumbnails').stop().css('display', 'block').fadeTo(100, 1.0);
	}

	var $slider = s.$state.closest('.slider');
	if ($slider.data('sliding')) return;
	$slider.data('sliding', true);

	var loop = function() {
		var wait = 0;
		var $img = s.$state.find('img');
		$img.each(function() {
			var opacity = $(this).css('opacity');
			if (opacity >= 0.9) return;

			var that = this;
			setTimeout(function() {
				$(that).stop()
				 .animate({ opacity: 1.0 }, 210)
				 .animate({ opacity: opacity }, 210, function() {
					setTimeout(function() {
						$(that).stop().css('opacity', '');
					}, 300);
				});
			}, wait);
			wait += 80;
		});
		$slider.data('sliding', false);
	};

	var hideTimer = $slider.data('hideTimer');

	if (hideTimer) { // Already open
		clearTimeout(hideTimer);
		loop();
	} else {
	  $slider.stop().animate({ height: thumbHeight }, 200, loop); 
	}

	hideTimer = setTimeout(function() {
		$slider.stop().animate({ height: 0 }, 1500); //, 'easeOutQuad');	
		$slider.data('hideTimer', '');
	}, 5000);
	$slider.data('hideTimer', hideTimer);
};

kk('main').catchArg('portfolio').property('duration', 1000);
kk('subMenu').catchArg('portfolio').property('duration', 1000).property('crossFade', false);
kk('subMenuH').catchArg('portfolio').property('duration', 1000).property('crossFade', false);


