$(document).ready(function() {
	
	////////////////////////////////////////////////////////////////////////////
	// Cufon

	Cufon.replace('.page h2 a, .news table th em, .bookmarks li a', { fontFamily: 'primary', hover: true });
	Cufon.replace('.calendar strong', { fontFamily: 'secondary', hover: true });

	////////////////////////////////////////////////////////////////////////////	
	// Common settings for preloader & themes

	var themeImages = 2; 	// Number of main_images in theme
	var maxTime = 10000; 	// Max time showing preloader
	var supportsCanvas = !!(document.createElement('canvas').getContext);
	
	//------------------------------------------------------------------------//
	// Preloader

	var ie6 = $.browser.msie && $.browser.version=="6.0";
	var setThemes = new Array();
	
	// Set themes - without caching - Math.round(Math.random()*1000000)
	setThemes[0] = { bg: './main_images/body-green.jpg', illustration: './main_images/grass.png', buttonbg: '#7e964a' };
	setThemes[1] = { bg: './main_images/body-lightgreen.jpg', illustration: './main_images/corner-green.png', buttonbg: '#7e964a' };
	setThemes[2] = { bg: './main_images/body-brown.jpg', illustration: './main_images/corner-brown.png', buttonbg: '#413C29' };
	setThemes[3] = { bg: './main_images/body-blue.jpg', illustration: './main_images/corner-blue.png', buttonbg: '#000000' };
	setThemes[4] = { bg: './main_images/body-grey.jpg', illustration: './main_images/corner-blue.png', buttonbg: '#000000' };
	setThemes[5] = { bg: './main_images/body-greyblue.jpg', illustration: './main_images/corner-blue.png', buttonbg: '#000000' };
	
	var preloader = {
		
		totalImages: function() { return themeImages * setThemes.length },
		loadedImages: 0,		
		
		plus: function() {
			
			$('#preloader .bar').animate({ width: (++preloader.loadedImages/preloader.totalImages()*100)+'%' }, 100, function(){
				
				if(preloader.loadedImages == preloader.totalImages()) {
					$(this).hide();
					preloader.hide();
				}
					
			});
			
		},
		
		hide: function() {
			$('#preloader').fadeOut('slow');
			themes.computeHeight();
		}
		
	}
	
	setInterval(preloader.hide,maxTime);	
	
	//------------------------------------------------------------------------//
	// Settings for themes
		
	var themes = {
		
		themeImages: themeImages,
		theme: setThemes,	
		backgroundWidth: 1600,		// Theme background image width
		backgroundHeight: 900,		// Theme background image height
		startSliding: 1000,			// Minimal window width for topic
		topicIsShown: false,		// Is the last photo in topic section hidden because of small window width?
		minPadding: 150,			// This is sum of header and footer height + padding around the content
		actualTheme: 0,				// Which theme is actual? - in CSS is now set theme 0
	
	//------------------------------------------------------------------------//

		$main: $('#main'),
		
		windowWidth: function() { return themes.$main.width(); },
		windowHeight: function() { return themes.$main.height(); },

		aspectRatioW: function() { return themes.windowWidth() / themes.backgroundWidth; },
		aspectRatioH: function() { return themes.windowHeight() / themes.backgroundHeight; },
		
		// Count number of loaded main_images in each theme and set attribute to theme after theme onload
		themeonload: function() {
					
			this.current++;
	
			if(this.current == themes.themeImages)		
				this.loaded = true;
			
			preloader.plus();
						
		},
		
		// Set background main_images z-indexes after page onload and content change
		setImages: function(index) {
	
			themes.$main_images.css('z-index','1');
			themes.$main_images.filter(':nth-child('+(index+1)+')').css('z-index','2');
			
		},
		
		onload: function() {
			
			// Images preloading
			var backgroundImages = new Array();
			
			for(i in themes.theme) {
				
				themes.theme[i].load = new Array();
				themes.theme[i].current = 0;
				themes.theme[i].loaded = false;
				themes.theme[i].id = 'theme'+i;
				themes.theme[i].afterload = themes.themeonload;
		
				themes.theme[i].load[0] = new Image();
				themes.theme[i].load[0].cislo = i;
				
				
				themes.theme[i].load[1] = new Image();
				themes.theme[i].load[1].cislo = i;
		
				for(j in themes.theme[i].load) {	
				
					themes.theme[i].load[j].onload = function() { 
						
						themes.theme[this.cislo].afterload.call(themes.theme[this.cislo]);
					
						if(supportsCanvas && this.cislo == 0)
							themes.setCanvas(themes.theme[this.cislo].load[0]);
						
					};
				 
				}
				
				themes.theme[i].load[0].src = backgroundImages[i] = themes.theme[i].bg;
				themes.theme[i].load[1].src = themes.theme[i].illustration;
		
			};
		
			// Creating divs on background			
			var inserthtml = '';
			$.each(backgroundImages, function(index){
				inserthtml += '<img src="'+backgroundImages[index]+'" width="'+themes.backgroundWidth+'" height="'+themes.backgroundHeight+'" />';
			});

			$('#main').before('<div id="background"></div>').before('<div class="illustration"></div>');
			$('#background').html(inserthtml);

			themes.actualMinHeight = themes.defaultMinHeight = parseFloat($('#main').css('min-height'));
			
			themes.$wrappers = $('#main, #background, .illustration');			
			themes.$main_images = $('#background img');
			themes.$image = $('#background>img');
			
			// Image resizing in HTML makes problem in javascript animations
			if(supportsCanvas) {

				$('#background').html('<canvas id="background-canvas" width="3000" height="2000"></canvas>');
				
				themes.canvas = document.getElementById('background-canvas');
				ctx = themes.canvas.ctx = themes.canvas.getContext('2d');
								
				themes.setCanvas = function(image) {
					
					if(themes.theme[themes.actualTheme].loaded) {
						
						if(!image)
							var image = themes.theme[themes.actualTheme].load[0];
						
						if(themes.aspectRatioW() > themes.aspectRatioH())
							ctx.drawImage(image, 0, 0, themes.windowWidth(), themes.backgroundHeight*themes.aspectRatioW());
						else
							ctx.drawImage(image, 0, 0, themes.backgroundWidth*themes.aspectRatioH(), themes.windowHeight());
							
					}
					
				};
  
			};
			
			// If default theme isn't first theme in collection
			if(themes.actualTheme != 0)
				themes.themePick(themes.actualTheme)
			
			themes.setImages(themes.actualTheme);
			themes.sizing();
			
		},
		
		computeHeight: function() {
				
			// If AJAX is disabled or somebody is on our subpage
			if(typeof($wrapperAct) == 'undefined')
				$wrapperAct = $('#content>div:visible');
				
			// Compute new content height
			var newHeight = $wrapperAct.outerHeight() + themes.minPadding;
			//alert('Nová výška: '+newHeight+', základní výška: '+defaultMinHeight);

			// If computed height is higher then minimal height, set the computed
			if(newHeight > themes.defaultMinHeight) {
				
				themes.actualMinHeight = newHeight;
				
				if(ie6)
					themes.$wrappers.css('height','');
				else
					themes.$wrappers.css('min-height',newHeight);
					
			} else {
				
				themes.actualMinHeight = themes.defaultMinHeight;
				
				if(ie6)
					themes.$wrappers.css('height','');
				else
					themes.$wrappers.css('min-height','');
					
			}
			
		},
		
		// Change theme function based on theme index
		changeTheme: function(index,bookmarkindex) {
	
			//alert('měním na'+index);
			
			// Bind all what is neccesary
			onContentLoad(bookmarkindex);
	
			if(index > themes.theme.length - 1) index = themes.theme.length - 1;
			if(index < 0) index = 0;
	
			// Background color animations
			$('.button').animate({ backgroundColor: themes.theme[index].buttonbg }, 'fast');
			
			/*$('.illustration')
			.animate({ opacity: 0 })
			.queue(function(){
				$('.illustration').css('background-image','url(\''+themes.theme[index].illustration+'\')').dequeue();
			}).animate({ opacity: 1 });*/
			
			$('.illustration')
			.hide()
			.queue(function(){
				$('.illustration').css('background-image','url(\''+themes.theme[index].illustration+'\')').dequeue();
			}).show();
			
			themes.setImages(index);
			themes.computeHeight();
			themes.sizing();
			
		},
		
		sizing: function() {
			
			if(ie6) {
				if(themes.windowHeight() > themes.actualMinHeight) {
					themes.$wrappers.css('height',themes.windowHeight());
				} else {
					themes.$wrappers.css('height',themes.actualMinHeight);
					}
			}
			
			if(themes.setCanvas)
				themes.setCanvas();
			
			/*
			// Calculates background main_images resizing
			if(aspectRatioW > aspectRatioH) {
								
				$.each(themes.$image, function(){
					$(this).width(windowWidth).height(themes.backgroundHeight*aspectRatioW);
				});
				
			} else {
				
				$.each(themes.$main_images, function(){
					$(this).height(windowHeight).width(themes.backgroundWidth*aspectRatioH);
				});
				
			};*/
			
			// Calculate calendar position
			if(themes.windowHeight() > themes.defaultMinHeight) {
				$('#column').css('bottom', (themes.windowHeight() - themes.defaultMinHeight) / 2 )
			} else {
				$('#column').css('bottom','0');
			}

		},
		
		// Determine if target theme based on active item in navigation is loaded or not and pick loaded theme
		themePick: function(index,bookmarkindex) {
		
			if(arguments.length < 2)
				bookmarkindex = 1;
			
			var changeTo = 0;
			if(arguments.length > 0) changeTo = index;
			
			var whichTheme = (changeTo - 1) % themes.theme.length;

			// If actual theme isn't loaded, search another loaded theme
			do {
				if(themes.theme[whichTheme].loaded) {
					themes.actualTheme = whichTheme;
					themes.changeTheme(whichTheme,bookmarkindex);
					break;
				} else {
					(whichTheme++) % themes.theme.length;
					}

			} while(whichTheme != changeTo);
			
		}	
		
	}	
	
	themes.onload();
	
	$(window).resize(themes.sizing);

	////////////////////////////////////////////////////////////////////////////
	// AJAX navigation
	
	$('#navigation li a, #logo, .topics li a').click(function(e){

		e.preventDefault();

		var $link = $(this);		
		var bookmarkIndex = 1;
		
		if($link.is('.topics li a')) {
			
			var parentIndex = $('#bio').parent().index()+1;			
			bookmarkIndex = $link.closest('li').index()+1;
			
		} else
			var parentIndex = $link.parent().index()+1;
		
		//alert(parentIndex+' a záložka č. '+bookmarkIndex);
		
		var wrapperName = 'nav-'+parentIndex;
		$wrapperAct = $('#'+wrapperName);
				
		// Switching two divs
		var navSwitch = function() {

			Cufon.refresh();

			// Restore default color and change active class
			$('#navigation li a').attr('style','').removeClass("active");
			$('#navigation li a:eq('+ (parentIndex-1) +')').addClass("active");		
			
			/*
			// Hide visible div
			$('#content>div:visible').fadeOut('slow', function(){
			
				// The content is switching, we can switch also the theme
				//var parentIndex = $link.parent().index()+1;
				themes.themePick(parentIndex,bookmarkIndex);
							
				// Show actual content
				$wrapperAct.fadeIn('slow');
				
			});*/
			
			// Hide visible div
			$('#content>div:visible').hide();
			
			// The content is switching, we can switch also the theme
			themes.themePick(parentIndex,bookmarkIndex);
						
			// Show actual content
			$wrapperAct.fadeIn('slow');
			
		};
		
		// Is target content already loaded?
		if($wrapperAct.length) {
			
			// If the div is hidden (= isn't active)
			if ($wrapperAct.is(':hidden'))
				navSwitch();
				
		} else {
			
			if(wrapperName == 'nav-1')
				$wrapperActType = ' topics';
			else
				$wrapperActType = '';
			
			$wrapperAct = $('<div id="'+wrapperName+'" class="page'+$wrapperActType+'"></div>')
			.hide()
			.appendTo('#content')
			.load($link.attr('href')+'?ajax',navSwitch);
			
		};
		
				
	});

	

	
	
});