(function($){
	var URL_ROOT = $('script[url-root]').attr('url-root');
	$.CMS = {
		URL_ROOT : URL_ROOT,
		URL_DATA : URL_ROOT+'cms-data/'
	};
})(jQuery);


jQuery(function($){
	$('body').delegate('#menu>ul>li', 'mouseenter', function() {
		var that = $(this), ul = that.children('ul').css('display', 'block').width(function() {
				var w = 0;
				$(this).children().each(function() {
					w += $(this).width();
				});
				return w;
			}), pos = that.position().left, w = that.children('a').width(), w2 = ul.width();
		
		ul.css('left', Math.max(-pos, (w - w2) / 2) + 12);
		ul.stop().fadeTo(200, 1);
	}).delegate('#menu>ul>li', 'mouseleave', function() {
		$(this).children('ul').stop().fadeTo(200, 0, function() {
			$(this).hide();
		});
	});
	
	/* Enable content menu */
	var titles = $('#content h1.nav'), contentMenu = $('#content-menu');
	if(titles.length > 1) {
		var wind = $(window), delta = wind.height() * 3 / 5;
		titles.each(function() {
			var that = $(this);
			$('<a href="#"></a>').append($('<span/>').text(that.text())).appendTo(contentMenu).click(function() {
				$.scrollTo(that, 800, { offset : { top : -161 } });
				return false;
			}).data('top', that.offset().top);
		});
		var contentMenuItems = contentMenu.children();
		wind.scroll(function(e) {
			var scrollTop = wind.scrollTop(), prev;
			contentMenuItems.each(function() {
				var that = $(this);
				if(!prev) {
					prev = that;
				}
				if(!scrollTop || scrollTop < that.data('top') - delta) {
					return false;
				}
				prev = that;
			});
			prev.addClass('open').siblings().removeClass('open');
		}).scroll();
	}
	$(function() {
		if(location.hash && $(location.hash).length) {
			$.scrollTo($(location.hash), 0, { offset : { top : -161 } });
		}
	});
	$(window).bind('hashchange', function() {
		if(location.hash && $(location.hash).length) {
			$.scrollTo($(location.hash), 0, { offset : { top : -161 } });
		}
	});
	setTimeout(function() {
		$(window).trigger('hashchange');
	}, 0);
	$(document).delegate('#content-menu:not(.reference) a, #content-menu.reference a:not(.open)', 'mouseenter', function() {
		$('span', this).addClass('open').stop().fadeTo(0,0).fadeTo(200, 1);
	}).delegate('#content-menu:not(.reference) a, #content-menu.reference a:not(.open)', 'mouseleave', function() {
		$('span', this).stop().fadeTo(200, 0, function() {
			$(this).removeClass('open')
		});
	});
	
	/* Enable video controls */
	$('video').each(function() {
		var video = $(this).wrap('<div class="video-player"></div>'),
			player = video.parent(),
			controls = $('<div class="video-player-controls"></div>').appendTo(player),
			playButton = $('<div class="video-player-play-button"></div>').appendTo(controls),
			fullButton = $('<div class="video-player-full-button"></div>').appendTo(controls),
			volumeControl = $('<div class="video-player-volume"></div>').appendTo(controls),
			tracker = $('<div class="video-player-tracker"></div>').appendTo(controls),
			trackLoaded = $('<div class="video-player-loaded"></div>').appendTo(tracker),
			trackPlayed = $('<div class="video-player-played"></div>').appendTo(tracker),
			time = $('<div class="video-player-time"></div>').appendTo(trackPlayed),
			interval,
			seekStart = null,
			trackerWidth = tracker.width(),
			trackerLeft,
			seekWasPaused,
			volumeStart = null,
			volumeLeft,
			volumeWidth = volumeControl.width(),
			videoLoaded = false,
			buffered = 0;
		
		function togglePlay() {
			if(video.paused) {
				video.play();
				startInterval();
			} else {
				video.pause();
			}
		}
		function seekTo(e) {
			video.currentTime = Math.max(0, Math.min(buffered, (e.pageX - trackerLeft - 7) / trackerWidth * video.duration));
			updatePlayer();
		}
		function volumeTo(e) {
			video.volume = Math.max(0, Math.min(1, (e.pageX - volumeLeft - 3) / volumeWidth));
			volumeControl.css('background-position', (100 * Math.round((1 - Math.max(0, Math.min(1, (e.pageX - volumeLeft + 3) / volumeWidth))) * 7) / 7)+'% 0');
		}
		function bindDocument() {
			$(document).bind('mousemove.video-player', function(e) {
				if(seekStart !== null) {
					seekTo(e);
					return false;
				}
				if(volumeStart !== null) {
					volumeTo(e);
				}
			}).bind('mouseup.video-player', function() {
				if(seekStart !== null) {
					seekStart = null;
					if(!seekWasPaused) {
						video.play();
						if(!interval) {
							startInterval();
						}
					}
				}
				if(volumeStart !== null) {
					volumeStart = null;
				}
				unbindDocument();
			});
		}
		function unbindDocument() {
			$(document).unbind('mousemove.video-player mouseup.video-player');
		}
		function updatePlayer() {
			if(video.buffered && !video.buffered.length) {
				return;
			}
			
			var h, m, s;
				
			buffered = video.buffered ? video.buffered.end(0) : video.duration
			
			trackLoaded.width(Math.round(trackerWidth * buffered / video.duration));
			trackPlayed.width(Math.round(trackerWidth * video.currentTime / video.duration));
			
			if(video.currentTime == video.duration) {
				video.pause();
			}
			playButton.toggleClass('playing', !video.paused);
			
			s = Math.floor(video.currentTime);
			h = s > 3600 ? Math.floor(s / 3600)+':' : '';
			s = s % 3600;
			m = s > 60 ? (h != '' && s > 599 ? '0' : '')+Math.floor(s / 60)+':': '0:';
			s = s % 60;
			s = s > 9 ? s : '0'+s;
			time.text(h+m+s);
			
			if(video.controls) {
				video.controls = false;
			}
		}
		function startInterval() {
			interval = setInterval(function() {
				updatePlayer();
				if(buffered == video.duration && video.paused) {
					clearInterval(interval);
					interval = null;
				}
			}, 50);
		}
		function toggleFullscreen() {
			player.toggleClass('fullscreen');
			if(player.is('.fullscreen')) {
				wind.bind('keydown.video-fullscreen-esc', function(e) {
					if(e.which == 27) {
						toggleFullscreen();
						return false;
					}
				});
			} else {
				wind.unbind('keydown.video-fullscreen-esc');
			}
			trackerWidth = tracker.width();
			controls.hide();
			setTimeout(function() {
				controls.show();
				updatePlayer();
			});
		}
			
		video.click(togglePlay).dblclick(toggleFullscreen);
		playButton.click(togglePlay);
		
		video = video[0];
		startInterval();
		
		tracker.mousedown(function(e) {
			if(e.button !== 0) {
				return;
			}
			trackerLeft = tracker.offset().left;
			seekStart = e.pageX;
			seekWasPaused = video.paused;
			video.pause();
			seekTo(e);
			bindDocument();
			return false;
		});
		
		volumeControl.mousedown(function(e) {
			if(e.button !== 0) {
				return;
			}
			volumeLeft = volumeControl.offset().left;
			volumeStart = e.pageX;
			volumeTo(e);
			bindDocument();
			return false;
		});
		
		fullButton.click(toggleFullscreen);
	});
	
	/* Image zoom */
	$('.zoom-image').bind('mouseenter mouseleave', function(e) {
		var hover = e.type == 'mouseenter', pic = $('.pic', this), description = $('.description', this), img = $('.pic img', this)[0], canvas = pic.data('canvas'), ctx, zoom = pic.data('zoom'), w = pic.width(), h = pic.height();
		if(!canvas) {
			canvas = $('<canvas>').attr('width', pic.width()).attr('height', pic.height()).appendTo(pic)[0];
			pic.data('canvas', canvas);
		}
		if(!zoom) {
			pic.data('zoom', 1);
			zoom = 1;
		}
		
		ctx = canvas.getContext('2d');
		ctx.drawImage(img, (1 - zoom) * w / 2, (1 - zoom) * h / 2, w * zoom, h * zoom);
		
		if(pic.data('interval')) {
			clearInterval(pic.data('interval'));
		}
		pic.data('interval', setInterval(function() {
			if(hover) {
				zoom = Math.min(1.1, zoom + 0.015);
				if(zoom >= 1.1) {
					zoom = 1.1;
					if(pic.data('interval')) {
						clearInterval(pic.data('interval'));
					}
				}
				pic.data('zoom', zoom);
				ctx.drawImage(img, (1 - zoom) * w / 2, (1 - zoom) * h / 2, w * zoom, h * zoom);
			} else {
				zoom = Math.max(1, zoom - 0.015);
				if(zoom <= 1) {
					zoom = 1;
					if(pic.data('interval')) {
						clearInterval(pic.data('interval'));
					}
				}
				pic.data('zoom', zoom);
				ctx.drawImage(img, (1 - zoom) * w / 2, (1 - zoom) * h / 2, w * zoom, h * zoom);
			}
		}, 20));
		
		if(hover) {
			description.slideDown(200);
		} else {
			description.slideUp(200);
		}
	});
	
	function openSitemap() {
		var sitemap = $('#sitemap'), timeout = sitemap.data('timeout');
		if(timeout) {
			clearTimeout(timeout);
		}
		sitemap.slideDown(500, 'easeOutQuad');
		return false;
	}
	$('#sitemap-open').click(false)
	$('#sitemap-open,#sitemap').mouseenter(openSitemap).mouseleave(function() {
		var sitemap = $('#sitemap'), timeout = sitemap.data('timeout');
		if(timeout) {
			clearTimeout(timeout);
		}
		sitemap.data('timeout', setTimeout(function() {
			$('#sitemap').slideUp(600, 'easeInOutQuad');
		}, 200));
	});
});

