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

kk.interactor('a:not(.custom)', { switcher: 'fade', duration: 150 });
kk.interactor('a.custom.noPushState', {pushState: false, switcher: 'fade', duration: 150 });
kk.interactor('a.custom.noWait', { waitForImages: false, switcher: 'fade', duration: 150 });
Kveik.Ui.fullView('.fullViewImg', 'body', { fadeFirst: 500 });

kk('mainContent')
  .catchArg()
	.bind('postShowState', function(e,s) { kk.updateColors(e,s); })
	.bind('postShowState', function(e,s) { kk.openSubmenu(s) });

if (Kveik.touchSupport) kk.loader({ position: 'center' });
else kk.loader();

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

kk.colors = {
	'_': {
		dark: '#202020',
		darkest: '#000000',
		bright: '#cacaca',
		gray: '#7a7a7a',
		darkgray: '#404040'
	},
	'inverse': {
		dark: '#cacaca',
		darkest: '#ffffff',
		bright: '#202020',
		gray: '#7a7a7a',
		darkgray: '#a0a0a0'
	}
};

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

var skip = function(offset, that) {
	var $el = kk('fg').get().$element;
	var $ac = $el.closest('.topLevel').find('a.category.open').closest('li');
	var $all = $ac.find('li a');
	var $active = $ac.find('._active');
	var index = $all.index($active);
	var all = $all.length;
	if (index+offset < 0 || index+offset >= all) { 
		$ac.find('a.category').click();
	}
	else {
		$($all.get( index+offset )).click();
	}
};	

/* Open submenu to correct entry */
kk.openSubmenu = function(s) {
	if (!s || !s.$state) return;
	var $el = s.$state.find('#_isElement_p');
	if ($el.length <= 0) return;

	var el = $el.data('object');

	var cat = el.currentState.param('cat');
	var arg = el.currentState.param('_kkArg'); 
	var $list;
	if (cat) $list = s.$state.find('.cli.cat_' + cat); 
	if (!$list && !arg) return;
	if ((!$list&&arg) || $list.length <= 0 && arg && arg[0]) 
		$list = s.$state.find('.cli.cat_' + arg[0]); 
	if (!$list || $list.length <= 0) 
		$list = s.$state.find('.cli:first');

	$list.find('.category').addClass('open');
	$list.find('ul').stop().slideDown('fast');
	$list.siblings().find('ul').stop().slideUp('fast');
};
kk.hideInfoTimer = function(e,s) {
	var $info = s.$state.find('.textContainer');
	var timer = $info.data('timer');
	if (timer) clearTimeout(timer);
	kk.hideInfo($info, true, 0);
	timer = setTimeout(function() {
		kk.hideInfo($info);
	}, 2000); 
	$info.data('timer', timer);
	$info.closest('.textContainer').one('mouseenter', function() {
		var timer = $(this).data('timer');
		$(this).data('timer', '');
		if (timer) clearTimeout(timer);
		if ($info.data('sliding')) kk.hideInfo($info);
	});
};
kk.hideInfo = function(c, show, duration) {
	var $c = $(c);
	var $div = $c.find('.dynamic');

	if (typeof(duration) === 'undefined') duration = 'fast';
	else duration = 0;

	$c.data('sliding', true);
	if (!$c.data('closed') && !show) {
		$c.find('.textIcon.close').fadeIn('fast');
		$c.find('.textIcon:not(.close)').fadeOut('fast');
		$div.slideUp(duration, function() {
			$c.data('closed', true);	
			$c.data('sliding', false);
		});
	} else {
		$c.find('.textIcon.close').fadeOut('fast');
		$c.find('.textIcon:not(.close)').fadeIn('fast');
		$div.slideDown(duration, function() {
			$c.data('closed', false);	
			$c.data('sliding', false);
		});
	}
};

kk.bind('load', function() {
	$('.previousFG.loop:not(.bound)').click(function() {
		kk('fg').previous();
		return false;
	}).addClass('bound');
	$('.previousFG:not(.bound)').click(function() {
		kk('fg').previous({ endBack: function() {
			skip(-1);
		} });
		return false;
	}).addClass('bound');

	$('.nextFG.loop:not(.bound)').click(function() {
		kk('fg').next();
		return false;
	}).addClass('bound');
	$('.nextFG:not(.bound)').click(function() {
		var $this = $(this);
		kk('fg').next({ endForward: function() { 
			if ($this.is('.loop')) return false;
			skip(1);
		} });
		return false;
	}).addClass('bound');

	$('.gallery.overlay .bottom:not(.bound)').click(function() {
		$(this).closest('.topLevel').find('a.category.open').click();
	}).addClass('bound');

	$('.galleryControl .link:not(.bound)').click(function() {
		var $el = $(this).closest('.image').find('._isElement');
		var el = $el.data('object');
		if (el && $(this).is('.prev')) el.previous();
		else el.next();
	}).addClass('bound');


	$('.menu .category:not(.bound)').click(function() {
		var $thisUl = $(this).parent().find('ul');
		var $allUl = $(this).closest('ul').find('.inner');
		$allUl.not($thisUl).slideUp();
		$thisUl.slideDown();
		$('.menu .category.open').removeClass('open');
		$(this).addClass('open');
	}).addClass('bound');

	$('.overlay .wrapper:not(.cBound)').each(function() {
		$('.cursor', this).followCursor({ container: '.link', xDiff: -20, yDiff: -20 });		
	}).mousedown(function() {
//		$('.cursor', this).backgroundPositionY(-26);
	}).mouseup(function() {
//		$('.cursor', this).backgroundPositionY(0);
	}).addClass('cBound');
	$('.overlay .left:not(.cBound), .overlay .right:not(.cBound), .overlay .bottom:not(.cBound)').hover(function() {
		$('.cursor', this).stop().fadeTo(200, 1.0);
	}, function() {
		$('.cursor', this).stop().fadeTo(200, 0);
	}).addClass('cBound');

	$('.galleryIndex li:not(.bound)').hover(function() {
		$(this).find('a').stop().animate({ height: 20 }, 100);
	}, function() {
		$(this).find('a').stop().animate({ height: 10 }, 100);
	}).each(function() {
		$(this).find('a').data('href', $(this).find('a').attr('href'));
		$(this).find('a').removeAttr('href');	
	}).addClass('bound');

	$('.textContainer .slideToggle:not(.bound)').click(function() {
		kk.hideInfo($(this).closest('.textContainer') );
	}).css('cursor', 'pointer').addClass('bound');

	/* Hover-zoom for thumbnails */
	kk.resizeThumbs( $('.work .index .wrapper:not(.bound)').addClass('bound') );

	/* Dynamic images */
	$('.dynamicBg:not(.dyn)').addClass('dyn').each(function() {
		var $t = $(this);
		var $under = $('<span class="graphic _inner _under"></span>');
		var $over = $('<span class="graphic _inner _over"></span>');
		var $inner = $under.add($over);
		$inner.css({ 
			width:  $t.width(), 
			height: $t.height(), 
			backgroundPosition: $t.css('backgroundPosition'),
			backgroundPositionX: $t.css('backgroundPositionX'),
			backgroundPositionY: $t.css('backgroundPositionY'),
			backgroundImage: $t.css('backgroundImage'),
			position: 'absolute',
			opacity: 1.0,
			top: 0,
			left: 0
		});

		$over.css('opacity', 0);
		$over.backgroundPositionY('-200%');
		$t.css('backgroundImage', 'none').data('_io', 0.0);
		$t.append($inner).hover(function() {
			$(this).dynamicColor(kk.ho || 0.5, 150);
		}, function() {
			$(this).dynamicColor($(this).data('_io'), 150);
		});
	});

	/* Hover-effect for dynamic colored elements */
	$('.dynamicColor:not(._dh)').addClass('_dh').hover(function() {
		var $this = $(this);
		var rbh = $this.data('rbh');
		var rfh = $this.data('rfh');
		if (rbh) $(this).css('background', rbh);
		if (rfh && !$(this).is('._active')) $(this).css('color', rfh);
	}, function() {
		var $this = $(this);
		var rbg = $this.data('rbg');
		var rfg = $this.data('rfg');
		$(this).css('background', rbg || '');
		$(this).css('color', rfg);
	});
});


kk.bind('postActivate', function() {
	if ($('.header ul a._active').length > 0) $('.logo.image').removeClass('_active');
});


kk.updateColors = function(e, s, recursive) {
	var d = 150;

	// Make sure updateColors is executed only once
	s = s || kk._updateColors;
	if (!recursive) {
		if (!kk._updateColors) {
			Kveik.one('postShowStates', function() {
				kk.updateColors(null, null, true);
				kk._updateColors = null;
			});
		}
		if (!kk._updateColors || s.property('invert')) kk._updateColors = s;
		return;
	}

	if (s && s.property('invert') === 'yes') {
		o = 1.0;
		kk.ao = 0.8;
		kk.ho = 0.7;
		$('body').addClass('_invert');
	} else {
		o = 0.0;
		kk.ao = 0.2;
		kk.ho = 0.3;
		$('body').removeClass('_invert');
	}

	$('.dynamicBg._active:not(.logo)').each(function() {
		$(this).dynamicColor(kk.ao, 150);
		$(this).data('_io', kk.ao);
	});

	$('.dynamicBg:not(._active),.dynamicBg.logo').each(function() {
		$(this).dynamicColor( o, 150);
		$(this).data('_io', o);
	});

	$('.dynamicColor').each(function() {
		var v = '_';
		var invert = $(this).is('._active.invertActive');
		if ((o >= 0.5 && !invert) || (o < 0.5 && invert)) v = 'inverse';

		if (!kk.colors[v]) return;
		
		var classStr = $(this).attr('class');
	
		var rbg = ((/([^ ]+)Background[ $]/).exec(classStr) || [])[1];
		var rfg = ((/([^ ]+)Foreground[ $]/).exec(classStr) || [])[1];
		var rb = ((/([^ ]+)Border[ $]/).exec(classStr) || [])[1];
		var rbh = ((/([^ ]+)BackgroundHover[ $]/).exec(classStr) || [])[1];
		var rfh = ((/([^ ]+)ForegroundHover[ $]/).exec(classStr) || [])[1];

		if (rbg && !kk.colors[v][rbg]) rbg = undefined;
		if (rfg && !kk.colors[v][rfg]) rfg = undefined;
		if (rb && !kk.colors[v][rb]) rb = undefined;
		if (rbh && !kk.colors[v][rbh]) rbh = undefined;
		if (rfh && !kk.colors[v][rfh]) rfh = undefined;

		var css = {};
		if (rbg) css.backgroundColor = kk.colors[v][rbg];
		if (rfg && kk.colors[v][rfg]) css.color = kk.colors[v][rfg];
		if (rb) {
			css.borderTopColor = css.borderRightColor = css.borderBottomColor = css.borderLeftColor = kk.colors[v][rb];
		}

		if (rbg || rfg || rb) $(this).animate(css, d);
		if (rfg) $(this).find('a').animate({ color: kk.colors[v][rfg] }, d);

		if (rbg) $(this).data('rbg', kk.colors[v][rbg]);
		if (rfg) $(this).data('rfg', kk.colors[v][rfg]);

		if (rbh) $(this).data('rbh', kk.colors[v][rbh]); 
		if (rfh) $(this).data('rfh', kk.colors[v][rfh]); 
	});
};

$.fn.dynamicColor = function(v,s) {
	$(this).each(function() {
		$(this).find('._over').stop().animate({ opacity: v || 0.0 }, s);
		if (v > 0.5) $(this).find('._under').stop().animate({ opacity: 1.0-v }, s);
		else $(this).find('._under').stop().animate({ opacity: 1.0 }, s);
	});
	return this;
};

kk.resizeThumbs = function(index) {
	var maxWidth = 300;
	var maxHeight = 186;
	var topOffset = 100;

	var $index = $( index || '.work .index .wrapper');
	if ($index.length <= 0) return;

	var height = $('body').height() - topOffset;

	$index.fakeDisplay();
	$index.each(function() {
		var $this = $(this);
		var $cases = $this.find('.case');	
		if ($cases.length <= 0) return;
	
		var width = $this.width();
		var cols = Math.ceil(width / maxWidth); 
		var rows = Math.ceil($cases.length / cols);
		var thumbRatio = maxWidth / maxHeight;

		var marginLeft = parseInt($cases.css('marginLeft').replace('[^\d]', ''));
		var marginRight = parseInt($cases.css('marginRight').replace('[^\d]',''));
		var marginTop = parseInt($cases.css('marginTop').replace('[^\d]', ''));
		var marginBot = parseInt($cases.css('marginBottom').replace('[^\d]', ''));

		var margin = (marginLeft+marginRight) * cols;
		width -= margin;
		var cWidth = Math.floor(width / cols);
		var cHeight = cWidth / thumbRatio;

		var sumHeight = rows*(cHeight+marginTop+marginBot);
		if (sumHeight > height) {
			width -= $.scrollbarWidth();
			cWidth = Math.floor(width / cols);
			cHeight = cWidth / thumbRatio;
		}	

		$cases.width(cWidth).data('_width', '').data('_height', '');
		$cases.height(cHeight);
	});
	$index.fakeDisplay(true);
};

kk.resizeIndex = function(element, state, recurse) {
	var $index = state.$state.find('.galleryIndex');
	if ($index.length <= 0) return;

	$index.fakeDisplay();

	var $elements = $index.find('li');
	var elementNumber = $elements.length || 1;
	var individualWidth = Math.ceil(($index.width() - 2*elementNumber) / elementNumber);

	$elements.width( individualWidth );
	var remains = $index.width() - individualWidth*elementNumber - 2*elementNumber;
	if (remains > 0) $elements.last().width( individualWidth + remains );

	$index.fakeDisplay(true);


	$elements.filter(':hidden').fadeTo(200, 1.0);
	if (!recurse) $(window).resize(function() {
		kk.resizeIndex(element, state, true);
	});

};

kk.bounceIndex = function(element, state) {
	var $index = state.$state.find('.galleryIndex');
	if ($index.length <= 0) return;
	var $elements = $index.find('li');
	if ($elements.length <= 1) return;

	// Bounce icons
	var interval = 150;
	for(var i=0; i<$elements.length; i++) {
		(function(i) {
			var $a = $($elements[i]).find('a');
			setTimeout(function() {
				$a.stop().animate({ height: 30}, 250).animate({ height: 10 }, 250);
			}, i*interval);
		})(i);
	}
};

$.scrollbarWidth = function() { 
	if ($._scrollbarWidth) return $._scrollbarWidth;

	var $div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-100px;left:-100px;"><div style="height:100px;"></div>'); 
	$('body').append($div); 
	var w1 = $div.find('div').innerWidth(); 
	$div.css('overflow-y', 'scroll'); 
	var w2 = $div.find('div').innerWidth(); 
	$div.remove(); 

	$._scrollbarWidth = w1-w2;
	return $._scrollbarWidth; 
}

$(window).resize( function() { 
	kk.resizeThumbs() 
});

//
//Add style JS-only style
$('head').append('<style>.galleryIndex li { display: none; }</style>');

