var imageWidth = 905;
var nativeHeight = 0;
var scrollers = {};

// Detect iPad
var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua);

$(document).ready(function() {

	// Set min height to screen, that iPad does not zoom
	if (isiPad) {
		$('body').css('min-height', ($(window).height() + 200) + 'px');
	}

	// Preview in menu
	if (!isiPad) {
		$('li.haspreview').hover(
			function(e) { showPreview(e.currentTarget); },
			function(e) { hidePreview(e.currentTarget); }
		);
	}

	// Control sidebar
	nativeHeight = $('#sidebar').height();
	$(window).resize(function(){
		resizeSidebar();
	});
	$(window).scroll(function() {
		positionSidebar();
	});
	resizeSidebar();

	// start slideshow
	$('div.slideshow').cycle({fx: 'fade', speed: 400});

	// activate goto top button
	$('.toplink').click(function(e) { e.preventDefault(); gotoTop(); });

	$('.horizontalscroller img').each(function(i, e) { initScroller(i, e); });
	$('.horizontalscroller .overview').each(function(i, e) { $(e).cycle({fx: 'fade', speed: 400, timeout: 0, next: e, allowPagerClickBubble: true}) });

	// mark anchor links active
	if ($('li.active a[href="/"]')) {
		$('.submenue a').click(function() { markAnchor(this) });
	}

});

function unmarkUnactiveSubmenu() {
	$($('.submenue').get(1)).find('li').removeClass('active');
}
function markAnchor(element) {
	unmarkUnactiveSubmenu();
	$(element).parent('li').addClass('active');
}
function initScroller(i, element) {
	scrollers[i] = {element: $(element)};
	$(element).click(function(e) { markThisMenuItem(e, i) });
}
function markThisMenuItem(e, i) {
	// Mark current menu item
	var id = scrollers[i]['element'].parents('div.horizontalscroller').prev().attr('name');
	markAnchor($('.submenue li a[href="/#' + id + '"]'));
}
function gotoTop() {
	$(window).scrollTop(0);
}
function showPreview(element) {
	$('#content').hide();
	$('div.hidden', element).children().clone().appendTo('#preview');
	$('#preview').show();
}
function hidePreview(element) {
	$('#preview').hide();
	$('#content').show();
	$('#preview').empty();
}
function positionSidebar() {
	var scrollTop = $(window).scrollTop();
	var screenHeight = $(window).height();
	if (scrollTop + screenHeight <= nativeHeight) {
		$('#sidebar').css('position', 'fixed')
			.css('top', -scrollTop + 'px');
	} else {
		var diff = screenHeight - nativeHeight;
		if (diff > 0) {
			diff = 0;
		}
		$('#sidebar').css('position', 'fixed')
			.css('top', diff + 'px');
	}
	
}
function resizeSidebar() {
	var screenHeight = $(window).height();
	if (nativeHeight > screenHeight) {
		$('#sidebar').css('height', nativeHeight + 'px');
	} else {
		$('#sidebar').css('height', screenHeight + 'px');
	}
	$('#text').css('position', 'absolute')
		.css('bottom', '0px')
		.css('left', '0px');
	positionSidebar();
}
