$(function(){

	var ie6 = $.browser.msie && $.browser.version=='6.0';
	var oldIE = $.browser.msie && $.browser.version < 9;
	var iMachine = navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod';

	////////////////////////////////////////////////////////////////////////////
	// Bookmarks
	
	var activeclass = 'active';
	var hidingclass = 'hidden';
	
	var $bookmarks = $('.bookmarks:not(.disable)');
	
	$.each($bookmarks, function() {
	
		var $parent = $(this);
		var $links = $parent.find('li a');
		
		if($parent.hasClass('hover'))
			eventtype = 'mouseenter mouseleave';
		else
			eventtype = 'click';
		
		$.each($links, function() {
		
			var $link = $(this);
			
			try {
				// IE strange error handling
				if($link.attr('href') == '#')
					var $target = $();
				else
					var $target = $($link.attr('href'));
			} catch(e) {
				var $target = $();
			}
			
			// If the target exists
			if($target.length) {
							
				// Hide all bookmarks except first				
				if(!$link.closest('li').is(':first-child'))
					$target.addClass(hidingclass);
				else
					$link.addClass(activeclass);
				
				// Binding with click event
				$link.bind(eventtype, function() {
				
					$link = $(this);
					
					$sibling = $link.closest('ul').find('.' + activeclass);
					
					// Hide bookmark from active sibling and remove active class
					$($sibling.attr('href')).addClass(hidingclass);
					$sibling.removeClass(activeclass);
					
					// Display target bookmark and add active class
					$($(this).attr('href')).removeClass(hidingclass);
					$link.addClass(activeclass);
				
					return false;
				});
			
			} else { // The target doesn't exist
			
				$link.bind(eventtype, function() { return false; });
			
			}
		
		});
	
	});

	// /Bookmarks
	////////////////////////////////////////////////////////////////////////////
	// Anchors

	var anchorSelector = 'a';
	var externalTitle = 'Odkaz vede do nového okna';

	/* PROJDE: za čárkami mohou a nemusí být mezery, volitelný je poslední parametr - čárka, za ním možný bílý znak a jakýkoli znak ([a-zA-Z0-9_]) -> zapne scrollbary
	* external
	* external,foto,600,500
	* external, foto, 600, 500
	* external,foto,600,500,yes
	*/
	
	function external() {
		
		var anchors = $(anchorSelector);
		var reg_ext = /^external(?:,\s*(\w+),\s*(\d+),\s*(\d+)(?:,\s*(\w+))?)?$/;
		
		$.each(anchors, function() {
			$link = $(this);
			
			if(reg_result = $link.attr('rel').match(reg_ext)) {
				
				// Creates closure
				$link.click(
					(function(reg_result,$link){
						return function() {
							if(reg_result[1]) {
								window.open($link.attr('href'), reg_result[1], 'width=' + reg_result[2] + ',height=' + reg_result[3] + ',menubar=no,resizable=yes' + (reg_result[4] ? ',scrollbars=yes' : ''));
							} else
								window.open($link.attr('href'));
							return false;
						}
					})(reg_result,$link)
				);
				
				if($link.attr('title') == '')
					$link.attr('title', externalTitle);
				else
					$link.attr('title', $link.attr('title') + ' | ' + externalTitle);
				
			}
				
		});
		
	}
	external();

	// /Anchors
	////////////////////////////////////////////////////////////////////////////
	// Other scripts

	var cache = [];

	$('.hover a').each(function(){
		var $img = $(this).find('img');
		if($img.size()) {
			var src1 = $img.attr('src'); // initial src
			var newSrc = src1.substring(0, src1.lastIndexOf('.')); // let's get file name without extension
			
			$(this).bind('mouseover focus', function(){
				$img.attr('src', newSrc + '-hover.' + /[^.]+$/.exec(src1)); // last part is for extension   
			}).bind('mouseout blur', function(){
				$img.attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); // removing '-over' from the name
			});

			var tmp = new Image();
			tmp.src = newSrc + '-hover.' + /[^.]+$/.exec(src1);
			cache.push(tmp);

			// Unclickable img - impossible to solve this f*cking problem via CSS
			$img.click(function(){
				if($.browser.msie && $.browser.version <= 7) {
					location.hash = $(this).closest('a').attr('href');
				}
			});

		}

	});
	
	if(ie6) {
		/*$().hover(function(){
			$(this).addClass('hover');
			
		}, function(){
			$(this).removeClass('hover');

		});*/

		if(DD_belatedPNG)
			DD_belatedPNG.fix('#logo img, #city img, #city span, #footer span, #topnav, #mininav img, .madeo img, #imgnav img, .moreinfo img');

	}

	/*if(!window.console) {

		window.console = {};
		var logs = ['log', 'debug', 'info', 'warn', 'error', 'time', 'timeEnd', 'profile', 'profileEnd', 'group', 'groupEnd'];
		for(i in logs)
			window.console[i] = function(){};

	}*/

	////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	//$.fx.interval = 13;

	$.getDimensions = function(el){
		var $el = el? $(el) : $(window);
		return { width: $el.width(), height: $el.height() };
	};

	/*var queue = function(pause, debug) {
		//console.log('delka fronty: ' + $page.queue('main').length);
		if(pause) {
			console.debug($page.queue('main'))
			if(debug != false)
				debugger;

		}

	};*/

	var supportsVideo = function() {
		return !!document.createElement('video').canPlayType; 
	}

	var getHash = function() {
		return location.hash.replace('#', '');
	}

	// Handling queues
	var $page = $({});

	$page.state = function(){

		$('#headline').fadeToggle('normal');
		$('#city, #imgnav').trigger('toggle');

		$page.state.togglePresentState();
		
	};
	$page.state.present = 0;
	$page.state.future = 0;

	$page.state.togglePresentState = function(state){
		return ($page.state.present = ++$page.state.present % 2);

	};

	$page.state.toggleFutureState = function(){
		return ($page.state.future = ++$page.state.future % 2);

	}

	$page.state.isHomePresent = function(){
		return $page.state.present == 0;

	};

	$page.state.isHomeFuture = function(){
		return $page.state.future == 0;

	}

	$page.state.shouldChange = function(url){
		return (!url && !$page.state.isHomeFuture()) || (url && $page.state.isHomeFuture());

	};

	$page.state.lock = {
		max: 2,
		actual: 2,

		isOpen: function(){
			return this.actual == this.max;
		},

		minus: function(){
			return --this.actual;
		},

		plus: function(){
			if(++this.actual == this.max) {
				$page.dequeue('main');
			}

			return this.actual;
		}

	};

	$page.sub = {

		open: function(url){

			$page.sub.close();

			$page.queue('main', function(){

				var $active = $('#imgnav a[href="#' + url + '"]');
				var $content = $('#' + url);

				if($content.size()) {
					$content
						.hide()
						.removeClass('hidden')
						.queue(function(next){

							// Performace tunning in IE
							if(oldIE)
								$content.show();
							else
								$content.fadeIn('fast');

							next();
						});

				}

				if($active.size()) {
					$active.stop(true, true).animate({
						left: '30',
						top: '-20'
					}, 300).addClass('active');

				}

				$page.dequeue('main');

			});


		},

		close: function(){
			$page.queue('main', function(){

				var $active = $('#imgnav .active');

				if($active.size()) {

					var $content = $($active.attr('href'));

					$active.stop(true, true).animate({
						left: '0',
						top: '0'
					}, 300).removeClass('active');

				} else {
					var $content = $('.text').not('.hidden');
				}

				if($content.size()) {

					// Performace tunning in IE
					if(oldIE) {
						$content.hide();
						$(this).addClass('hidden');

					} else {
						$content
							.fadeOut('fast', function(){
								$(this).addClass('hidden');
							});
						
					}

				}
				
				$page.dequeue('main');

			});

		}

	}

	$('#city').bind('toggle', function(){

		$page.state.lock.minus();
		
		var $this = $(this),
			hidden = $this.data('outside'),
			win = $.getDimensions('#main'),
			position = $this.offset(),
			move,
			settings,
			speed = { x: 2, y: 1 };

		move = {
			x: ((win.width  - $this.width())  / 2 + $this.width())  / speed.x,
			y: ((win.height - $this.height()) / 2 + $this.height()) / speed.y
		}

		if(hidden) {

			if(move.x < move.y) {
				settings = {
					marginLeft: move.x * speed.x,
					marginTop:  move.x * speed.y
				}
			} else {
				settings = {
					marginLeft: move.y * speed.x,
					marginTop:  move.y * speed.y
				}
			}

			$this.css(settings).show().animate({ marginLeft: -.5 * $this.width(), marginTop: 0 }, 800, function(){
				$this.data('outside', false);
				$page.state.lock.plus();
			});
			
		} else {

			if(move.x < move.y) {
				settings = {
					marginLeft: '+=' + move.x * speed.x,
					marginTop:  '+=' + move.x
				}
			} else {
				settings = {
					marginLeft: '+=' + move.y * speed.x,
					marginTop:  '+=' + move.y
				}
			}

			$this.animate(settings, 400, function(){
				$this.hide().data('outside', true);
				$page.state.lock.plus();
			});

		}

		$('#mininav li:visible').fadeOut('fast', function(){
			$(this).siblings('li').fadeIn('fast');
		});

	});

	$('#imgnav').bind('toggle', function(event){

		$page.state.lock.minus();
		
		var $nav = $(this),
			$children = $nav.children(),
			$ico = $nav.find(':last-child img'),
			visible = $nav.data('inside'),
			delayPerItem = 50,
			itemOffset = { x: 120, y: 60 },
			speed = { x: 2, y: 1 },
			offset,
			beginOffset,
			time,
			maxHeight = 0;

		$ico.each(function(ico, el){
			var $el = $(el);
			maxHeight = $el.height() > maxHeight ? $el.height() : maxHeight;
		});

		offset = $nav.offset();
		offset = {
			left: offset.left + $ico.width(),
			top:  offset.top + maxHeight
		};

		// Moving in X direction?
		if(offset.left / speed.x < offset.top / speed.y) {
			beginOffset = {
				marginLeft: - offset.left,
				marginTop:  - offset.left / speed.x
			};

		} else {
			beginOffset = {
				marginLeft: - offset.top * speed.x,
				marginTop:  - offset.top
			};

		}

		$children.each(function(index, child){

			var $child = $(child),
				animationSettings,
				delay;

			if(visible) {
				animationSettings = beginOffset;

				delay = 100 + (index * delayPerItem);

			} else {
				animationSettings = {
					marginLeft: itemOffset.x * index,
					marginTop:  itemOffset.y * index
				}

				delay = $children.size() * delayPerItem - (index * delayPerItem);

				$child.css(beginOffset);

			}

			$child.show().delay(delay).animate(animationSettings, time, function(){
				var $child = $(this); // simulate closure

				if(visible)
					$child.hide();

				if((visible && $child.is(':last-child')) || (!visible && $child.is(':first-child'))) {

					if(visible) {
						$nav.data('inside', false);
					} else {
						$nav.data('inside', true);
					}

					$page.state.lock.plus();
				}

			});

		});

	});

	// Init
	$('#imgnav').removeClass('n').data('inside', false).find('li').hide().find('a').tipsy({ gravity: 'w', opacity: 0.75 });

	$('#mininav').find('li:last-child').hide().end().removeClass('n');

	$('.text .button')
		.find('em').parent().tipsy({ gravity: 'n', opacity: 0.9, holdMouse: false });

	// Setup video
	$page.video = $();

	// Chrome 10 has "bug" with strange color profiles (in opposite of version 9), this is temporary solution
	// If you know the solution (how to export video files with propper color profiles), contact me at zdenek@madeo.cz, thanks :)
	if(false && supportsVideo()) {

		$page.video = $('#video')
			.bind('replace', function(){
				this.pause();

				$page.video.replaceWith($page.video.find('img'));
				$('#nav, .fcb span')
					.hide()
					.fadeIn('slow')
					.removeClass('hidden');

			}).bind('click ended abort error emptied stalled', function(){
				$page.video.trigger('replace');
			}).bind('canplay canplaythrough loadeddata', function(){
				this.volume = 0;
				this.play();
			});

			// Waiting long?
			window.setTimeout(function(){ $page.video.trigger('replace'); }, 7000);

		var preload = new Image();
		preload.src = $page.video.find('img').attr('src');

		if(($.browser.safari && $.client.os == 'Mac') || iMachine || ($.client.browser == "Chrome" && $.browser.version > 534))
			$page.video.trigger('replace');

	} else {
		var $collection = $('#nav, .fcb span, #videoposter');

		if($.browser.msie && $.browser.version < 8) {
			$collection.removeClass('hidden');
			slideCity();
		} else {
			$(window).load(function(){
				$collection.hide().removeClass('hidden').fadeIn('slow');
				slideCity();
			});
		}

	}

	function slideCity() {
		var $city = $('#city');
		$city.css('top',(parseInt($city.css('top')) + 25) + 'px').animate({ top: '-=25px' }, 'fast');		
	}

	$(window).bind('hashchange', function(e) {

		var url = getHash();
		var queueWasEmpty = !$page.queue('main').length;

		if(url)
			$page.video.trigger('replace');

		$('#topnav')
			.find('.active').removeClass('active').end()
			.find('[href=#' + url + ']').addClass('active');

		if($page.state.shouldChange(url)) {

			if(!$page.state.isHomeFuture()) {
				$page.sub.close();
			}

			$page.queue('main', $page.state);

			if($page.state.isHomeFuture()) {
				$page.sub.open(url);
			}

			// Binded changing state -> we should know in which state we will be
			$page.state.toggleFutureState();

		} else if(url) {
			$page.sub.open(url);

		}

		// Queue was empty? Start it
		if(queueWasEmpty && $page.state.lock.isOpen())
			$page.dequeue('main');

	});

	// Since the event is only triggered when the hash changes, we need to trigger
	// the event now, to handle the hash the page may have loaded with.
	$(window).trigger('hashchange');

});

