var Kubik = function () {
	var options = {
		'scrollFirstStep': 0.2,
		'scrollCycle': 25,
		'scrollMaxSpeed': 15,
		'scrollInc': 0.3,
		'rotate': {
			'inc': 20,
			'cycle': 200,
			'value': 45
		},
		'bubbleTime': 200,
		'menuHideDuration': 600,
		'showSectionDuration': 600,
		'animations': {
			'duration': 1500,
			'balloon': {
				'duration': 2000
			},
			'shark': {
				'duration': 1000
			}
		},
		'newsRotate': 4000,
		'newsProduct': 5,
		'sections': {
			'balloon': {
				'name': 'about-kubik',
				'pagination': true,
				'background': 'background-uni'
			},
			'frog': {
				'name': 'for-parents',
				'pagination': true,
				'background': 'background-uni'
			},
			'mill': {
				'name': 'news-page',
				'background': 'novinkybg'
			},
			'news': {
				'name': 'news-page',
				'background': 'novinkybg'
			},
			'ladybird': {
				'name': 'products',
				'background': 'produktybg',
				'pagination': true
			},
			'owl': {
				'name': 'games',
				'background': 'hrybg',
				'pagination': true
			},
			'tower': {
				'name': 'games',
				'background': 'hrybg',
				'pagination': true
			},
			'club': {
				'name': 'club-page',
				'background': 'klubbg'
			},
			'post': {
				'name': 'post-page',
				'pagination': true,
				'background': 'background-uni'
			},
			'painter': {
				'name': 'games',
				'game': 'game6',
				'background': 'hrybg',
				'pagination': true
			}
		},
		'games': {
			'game1': {
				'flash': 'fotbalova_skola.swf'
			},
			'game2': {
				'flash': 'kubik_popelarem.swf'
			},
			'game3': {
				'flash': 'nejdelsi_strela.swf'
			},
			'game4': {
				'flash': 'skotaceni_na_vode.swf'
			},
			'game5': {
				'flash': 'strasidelna_jizda.swf'
			},
			'game6': {
				'flash': 'drawGame.swf'
			},
			'game7': {
				'flash': 'fruits.swf',
				'width': 640,
				'height': 480
			},
			'game8': {
				'flash': 'masters_season.swf',
				'width': 550,
				'height': 400
			},
			'game9': {
				'flash': 'microworld.swf',
				'width': 650,
				'height': 500
			},
			'game10': {
				'flash': 'snowboard_master.swf',
				'width': 600,
				'height': 420
			}
		},
		'zoom': {
			'scale': 1.5,
			'duration': 2000
		},
		'pulse': {
			'ratios': [70, 120, 80, 110, 100],
			'fadeOutSpeed': 1000
		},
		'hideMessageIn': 3000
	};
	var $landscape      = $('#landscape');
	var $arrows			= $('#arrow-left, #arrow-right');
	var landscapeWidth  = $landscape.width();
	var landscapeParts  = getLandscapeParts();
	var firstChild      = 0;
	var lastChild       = landscapeParts.length - 1;
	var leftTreshold    = -landscapeParts[firstChild].width;
	var rightTreshold   = -landscapeWidth + landscapeParts[lastChild].width;
	var $window			= $(window);
	var screenWidth     = $window.width();
	var screenLeftPos   = parseInt($landscape.css('left'), 10);
	var screenRightPos  = screenLeftPos - screenWidth;
	var keepScrolling   = false;
	var scrollDirection = null;
	var scrolling       = false;
	var bubbles         = getBubbles();
	var activeElements  = getActiveElements();
	var $section		= null;
	var sectionName		= null;
	var $menu			= $('#menu');
	var $menu2			= $('#menu2');
	var $billboardNews	= $('#news img');
	var billboardId		= null;
	var page			= {
		'current': 1,
		'max': 0
	};
	var $pages					= null;
	var productsSet				= false;
	var gamesSet				= false;
	var postSet					= false;
	var newsSet					= false;
	var clubSet					= false;
	var tmp						= {};
	var fromNews				= false;
	var send					= false;
	var ie7						= ($('html').hasClass('ie7') ? true : false);
	var $clubForm				= $('#club-form');	
	var directProduct			= false;
	var oldShowSectionDuration	= options.showSectionDuration;
	var oldZoomDuration			= options.zoom.duration;
	var newsCounter				= 0;
	
	/**
	 * Nastaví posluchače událostí pro skrolování.
	 * 
	 * @return void
	 */
	function initScrollHandlers() {
		$('#arrow-left, #arrow-right').hover(function (e) {
			scrollDirection = this.id;
			startScroll();
		}, function () {
			stopScroll();
		});
	}
	
	/**
	 * Nastaví posluchače událostí pro menu s ikonami.
	 *
	 * @return void
	 */
	function initMenuHandlers(selector) {
		$('#' + selector).children('a').click(function () {
			var $this = $(this);
			if ($this.attr('id') !== 'menu2-homepage') {
				sectionControll($this.attr('id').replace(selector + '-', '').split('-'));
			}
			return false;
		});
	}
	
	function sectionControll(name) {
		// zobrazení sekce
		if ($section === null) {
			$arrows.fadeOut();
			zoom(name);
		} else { // přepnutí sekce
			hideSection(true, name[0]);
		}
	}
	
	function showSection(switchSection) {
		if (!switchSection) {
			$menu2.fadeOut(options.menuHideDuration, function () {
				showCallback();
			});
		} else {
			showCallback();
		}
	}
	
	function showCallback() {
		$section = $('#' + options.sections[sectionName].name);
		
		if (options.sections[sectionName].name == 'news-page' && !newsSet) {
			newsSet = true;
			$('#video', $section).click(function () {
				$('#news-content').fadeOut();
				$('#news-video').fadeIn();
				
				return false;
			});
			$('.newsarrowleft, .newsarrowright', $section).click(function () {
				return false;
			});
		} else if (options.sections[sectionName].name == 'products') {
			if (!productsSet) {
				productsSet = true;
				
				$('#products-content a').click(function () {
					tmp.curClass = $(this).attr('class');
					tmp.productSection = $('#' + tmp.curClass);
					page.current = parseInt(tmp.curClass.substring(tmp.curClass.length - 1), 10);

					$('#products-content').fadeOut();

					$('#product-detail').fadeIn();

					tmp.productSection.fadeIn('slow', function () {
						tmp.productTexts = $('.textproduct', tmp.productSection);

						$('img.bottle-switcher').click(function (e) {
							e.stopImmediatePropagation();
							var $thisImg = $(this);
							var textClass = $thisImg.attr('class').replace('bottle-switcher ', '');

							var src = $thisImg.attr('src').replace('s', '');
							$('.mainproduct img', tmp.productSection).attr('src', src);

							$('.prichut', tmp.productSection).html(flavors[textClass]);
							return false;
						});
					});
					return false;
				});

				$('.productsarrowleft, .productsarrowright', $section).click(function () {
					if ($(this).hasClass('productsarrowright')) {
						changePage(true);
					} else {
						changePage();
					}

					return false;
				});
			}
			if (fromNews) {
				$('#products-content').hide();
				$('#products-content a').each(function (idx, elem) {
					if (idx == options.newsProduct) {
						$(elem).click();
					}
				});
			}
		} else if (options.sections[sectionName].name == 'games') {
			if (!gamesSet) {
				gamesSet = true;
				
				$('a.game-selector', $section).click(function () {
					var gameContent = $('#game-content').fadeIn();
					$('#games-content').fadeOut();
					$('#games-pager').fadeOut();
					var width = 700;
					var height = 500;
					var game = options.games[$(this).attr('id')];
					if (game.width) {
						width = game.width;
					}
					if (game.height) {
						height = game.height;
					}
					if (height < 500) {
						gameContent.css('padding-top', (500 - height) / 2);
					} else {
						gameContent.css('padding-top', 0);
					}
					var so = new SWFObject("swf/" + game.flash, "obsahflashbanner", width, height, "8", "#000");
					so.addParam("quality", "high");
					so.addParam("wmode", "transparent");
					so.write("flashcontent");
					return false;
				});
				
				var $children = $('#games-pager').children('a');
				$children.click(function () {
					var result = true;
					var pageNumber = parseInt($(this).attr('class').replace('act', '').replace('gamepage', ''), 10);
					if (pageNumber > page.current && pageNumber <= page.max) {
						result = changePage(true, pageNumber);
					} else if (pageNumber < page.current && pageNumber >= 1) {
						result = changePage(false, pageNumber);
					}

					if (!result) {
						return false;
					}

					refreshGamePaginator($children);
					return false;
				});

				$('.gamesarrowleft, .gamesarrowright', $section).click(function () {
					var result = true;
					if ($(this).hasClass('gamesarrowright')) {
						result = changePage(true);
					} else {
						result = changePage();
					}

					if (!result) {
						return false;
					}

					refreshGamePaginator($children);

					return false;
				});
			}
			
			if (options.sections[sectionName].game) {
				setTimeout(function() {
					$('#' + options.sections[sectionName].game).click();
					$('.gamesarrowright', $section).click();
				}, 10);
			}
		} else if (options.sections[sectionName].name == 'club-page') {
			if (!clubSet) {
				clubSet = true;
				initClub();
			}
			if ($window.height() < 655) {
				if ($('html').hasClass('ie7')) {
					$('html,body').css({
						'overflow-x': 'hidden',
						'overflow-y': 'auto'
					});
				} else {
					$('body').css('overflow', 'auto');
				}
			}
		}

		if (options.sections[sectionName].background) {
			$('#background').removeClass('hidden2').addClass(options.sections[sectionName].background, 1000);
		}
		
		if (options.sections[sectionName].pagination) {
			initPagination();
		}
		
		if (options.sections[sectionName].name === 'post-page') {
			$('#errormessage').hide();
			if (!postSet) {
				postSet = true;
				emailSend();
			}
		}

		if (directProduct) {
			$section.fadeIn(options.showSectionDuration, function () {
				directProduct = false;
				$('#products-content a.product1').first().click();
				setTimeout(function () {
					options.showSectionDuration = oldShowSectionDuration;
					options.zoom.duration = oldZoomDuration;
				}, 100);
			});
		} else {
			$section.fadeIn(options.showSectionDuration);
		}
		$menu.fadeIn(options.showSectionDuration);
	}
	
	function refreshGamePaginator(elems) {
		elems.each(function (idx, elem) {
			var elem = $(elem);
			if (elem.hasClass('gamepage' + page.current)) {
				elem.addClass('act');
			} else {
				elem.removeClass('act');
			}
		});
	}
	
	function formRemoveErrors() {
		$('input[name="subject"]', tmp.$form).removeClass('error');
		$('input[name="name"]', tmp.$form).removeClass('error');
		$('textarea', tmp.$form).removeClass('error');
		$('input[name="email"]', tmp.$form).removeClass('error');
	}
	
	function hideEmailMessageWindow(window) {
		if (send) {
			send = false;
			$('#email-form').children().each(function (idx, elem) {
				$(elem).val('');
			});
		}
		window.fadeOut('slow');
	}
	
	function emailSend() {
		$('#email-send').click(function (e) {
			e.stopImmediatePropagation();
			e.preventDefault();
			
			tmp.$form = $('#email-form');
			$.ajax({
				'url': 'index/mailsend',
				'data': tmp.$form.serializeArray(),
				'type': 'POST',
				'dataType': 'json',
				'error': function () {
					formRemoveErrors();
					var $message = $('#errormessage');
					$message.children('p').html(errorMessage);
					$message.fadeIn('slow', function () {
						setTimeout(function () {
							hideEmailMessageWindow($message);
						}, options.hideMessageIn)
					});
				},
				'success': function (data) {
					var $message = $('#errormessage');
					
					$message.children('p').html(data.message);
					$message.fadeIn('slow', function () {
						setTimeout(function () {
							hideEmailMessageWindow($message);
						}, 2000)
					});
					
					if (data.send) {
						send = true;
						formRemoveErrors();
					} else if (data.error) {
						if (data.errorSubject) {
							$('input[name="subject"]', tmp.$form).addClass('error');
						} else {
							$('input[name="subject"]', tmp.$form).removeClass('error');
						}
						if (data.errorName) {
							$('input[name="name"]', tmp.$form).addClass('error');
						} else {
							$('input[name="name"]', tmp.$form).removeClass('error');
						}
						if (data.errorMessage) {
							$('textarea', tmp.$form).addClass('error');
						} else {
							$('textarea', tmp.$form).removeClass('error');
						}
						if (data.errorMail) {
							$('input[name="email"]', tmp.$form).addClass('error');
						} else {
							$('input[name="email"]', tmp.$form).removeClass('error');
						}
					}
				}
			});
		});
	}
	
	function hideSection(switchSection, name) {
		if (!switchSection) {
			if (Modernizr.csstransforms) {
				$landscape.animate({'scale': 1.0}, {'duration': options.zoom.duration});
			}
		}
		
		$menu.fadeOut(options.showSectionDuration);
		$section.fadeOut(options.showSectionDuration, function () {
			if (!switchSection) {
				$menu2.fadeIn(options.menuHideDuration);
			}
			
			if (options.sections[sectionName].name === 'for-parents') {
				formRemoveErrors();
			}
			
			if (options.sections[sectionName].name === 'news-page') {
				$('#news-video').hide();
				$("#jquery_jplayer_1").jPlayer("pause");
				$('#news-content').show();
			}
			
			if (options.sections[sectionName].name === 'club-page') {
				clearClubForm();
				if ($('html').hasClass('ie7')) {
					$('html,body').css({
						'overflow-x': 'hidden',
						'overflow-y': 'hidden'
					});
				} else {
					$('body').css('overflow', 'hidden');
				}
			}
			
			if (options.sections[sectionName].pagination) {
				if (options.sections[sectionName].name === 'games') {
					$('#game-content').hide();
					$('#games-content').show();
					$('#games-pager').show();
					$('#flashcontent').html('');
					
					$('#games-pager').children('a').each(function (idx, elem) {
						if (idx === 0) {
							$(elem).addClass('act');
						} else {
							$(elem).removeClass('act');
						}
					});
				} else if (options.sections[sectionName].name === 'products') {
					fromNews = false;
					$('#product-detail').hide();
					$pages.each(function (idx, elem) {
						$(elem).hide();
					});
					$('#products-content').show();
				} else {
					$('.leftpagenummber', $section).html(1);
					$('.rightpagenummber', $section).html(2);
				}
				
				if (options.sections[sectionName].name !== 'products') {
					$pages.each(function (idx, elem) {
						if (idx === 0) {
							$(elem).removeClass('hidden2').show();
						} else {
							$(elem).addClass('hidden2').hide();
						}
					});
				} else {
					$('.leftpagenummber', $section).html(1);
					$('.rightpagenummber', $section).html(2);
				}
				
				$pages = null;
			}
			
			if (options.sections[sectionName].background) {
				$('#background').addClass('hidden2').removeClass(options.sections[sectionName].background);
			}
			if (switchSection) {
				sectionName = name;
				showSection(switchSection);
			}
		});
		
		tmp = {};
		
		if (!switchSection) {
			$section = null;
			$arrows.fadeIn();
		}
	}
	
	/**
	 * Nastaví posluchače událostí pro aktivní prky.
	 *
	 * @return void
	 */
	function initActiveElementsHandlers() {
		$.each(activeElements, function (idx, elem) {
			elem.click(function (e) {
				sectionControll([$(this).attr('id')]);
				return false;
			}).hover(function (e) {
				e.stopImmediatePropagation();
				
				var id = $(this).attr('id');
				if (bubbles[id]) {
					if (Modernizr.cssanimations) {
						bubbles[id].toggleClass('pulse-bubble');
					} else {
						if (ie7) {
							bubbles[id].show();
						} else {
							bubbles[id].stop().fadeIn();
						}
					}
				}
				return false;
			}, function (e) {
				e.stopImmediatePropagation();
				
				var id = $(this).attr('id');
				if (bubbles[id]) {
					if (Modernizr.cssanimations) {
						bubbles[id].toggleClass('pulse-bubble');
					} else {
						if (ie7) {
							bubbles[id].hide();
						} else {
							bubbles[id].fadeOut();
						}
					}
				}
				return false;
			});
		});
	}
	
	/**
	 * Provede zoom na daný prvek. Pokud je předáno více prvků, provede zoom, který je blíž.
	 *
	 * @return void
	 */
	function zoom(names) {
		if (Modernizr.csstransforms) {
			var originName = Modernizr.prefixed('transformOrigin')
							.replace(/([A-Z])/g, function (str,m1) {return '-' + m1.toLowerCase();})
							.replace(/^ms-/,'-ms-');
		}
		var curPos = Math.abs($landscape.position().left);
		var elem = null;
		var horizontalPos = null;
		var verticalPos = null;
		var prevPos = null;
		var right = true;
		
		if (names.length == 1) {
			elem = activeElements[names[0]];
			horizontalPos = getDistanceToElement(elem);
			sectionName = names[0];
		} else {
			var min = Number.MAX_VALUE;
			
			$.each(names, function (idx, el) {
				var tmpDistance = getDistanceToElement(activeElements[el]);
				var delta = Math.abs(curPos - tmpDistance);
				
				if (delta < min) {
					min = delta;
					elem = activeElements[el];
					sectionName = el;
					horizontalPos = tmpDistance;
				}
			});
		}
		
		horizontalPos += elem.width() / 2;
  		if (Modernizr.csstransforms) {
			var bodyHeight = $('body').height();
			var baseHeight = landscapeParts[0].elem.height();
			
			if (bodyHeight > baseHeight) {
				baseHeight = bodyHeight;
			}
			verticalPos = baseHeight - (elem.height() / 2 + parseInt(elem.css('bottom'), 10));
			$landscape.css(originName, horizontalPos + 'px ' + verticalPos + 'px');
		}
		horizontalPos -= screenWidth / 2;
		
		if (curPos > horizontalPos) {
			right = false;
		}
		
		var prop = {
			'left': -horizontalPos
		};
		
		if (Modernizr.csstransforms) {
			prop.scale = options.zoom.scale;
		}
		
		$landscape.animate(prop, {
			'duration': options.zoom.duration,
			'step': function (now, fx) {
				if (fx.prop === 'left') {
					if (!prevPos) {
						prevPos = now;
					} else {
						var distance = undefined;
						if (right) {
							distance = Math.abs(prevPos - now);
							scrollToDirection(distance, right);
						} else {
							distance = Math.abs(prevPos - now);
							scrollToDirection(distance, right);
						}

						prevPos = now;
					}
				}
			},
			'complete': function () {
				showSection();
			}
		});
	}
	
	function initSectionSwitcher() {
		$('a.section-switcher').click(function (e) {
			var className = $(this).attr('class').replace('section-switcher ', '');
			if (className === 'ladybird' && options.sections[sectionName].name !== 'for-parents') {
				fromNews = true;
			}
			
			hideSection(true, className);
			return false;
		});
	}

	function initCloseBtnHandlers () {
		$('.closebutton').click(function (e) {
			e.preventDefault();
			var $this = $(this);
			if ($this.hasClass('game-close')) {
				$('#game-content').fadeOut();
				$('#games-content').fadeIn();
				$('#games-pager').fadeIn();
				return false;
			} else if ($this.hasClass('closebutton-indetail')) {
				var $productDetail = $('#product-detail');
				$productDetail.fadeOut('slow', function () {
					$('.produkty-detail', $productDetail).each(function (idx, elem) {
						$(elem).hide();
					});
				});
				$('#products-content').fadeIn('slow');
				return false;
			} else if ($this.hasClass('closeemail')) {
				hideEmailMessageWindow($('#errormessage'));
				return false;
			} else if ($this.hasClass('vidkoclose')) {
				$('#news-video').fadeOut(400, function () {
					$("#jquery_jplayer_1").jPlayer("pause");
				});
				$('#news-content').fadeIn();
				return false;
			} else if ($this.hasClass('close-club')) {
				$this.parents('div').first().fadeOut();
				return false;
			}
			
			hideSection();
			return false;
		});
		$('.logo').click(function () {
			hideSection();
			return false;
		});
	}
	
	function initClub() {
		$('#club-message-show').click(function (e) {
			$('#club-message').fadeIn();
			e.preventDefault();
		});
		$('#send-club').click(function (e) {
			var $clubEmail = $('#club-email');
			if ($clubEmail.val() == '') {
				showAndHideMsg($('#club-message2'), 'email');
				$clubEmail.addClass('error');
			} else {
				$.ajax({
					'url': 'index/competition',
					'data': $clubForm.serializeArray(),
					'type': 'POST',
					'dataType': 'json',
					'error': function () {
						
					},
					'success': function (data) {
						if (data.success) {
							showAndHideMsg($('#club-message2'), 'success');
							clearClubForm();
						} else if (data.error) {
							showAndHideMsg($('#club-message2'), 'email');
							$clubEmail.addClass('error');
						} else if (data.duplicate) {
							showAndHideMsg($('#club-message2'), 'duplicate');
							$clubEmail.addClass('error');
						} else {
							showAndHideMsg($('#club-message2'), 'another');
						}
					}
				});
			}
			
			e.preventDefault();
		});
	}
	
	function clearClubForm() {
		$('#club-email').val('').removeClass('error');
		$('input[type="radio"]', $clubForm).each(function (idx, elem) {
			var $elem = $(elem);
			if (idx == 0) {
				$elem.attr('checked', 'checked');
			} else if ($elem.attr('checked') == 'checked') {
				$elem.removeAttr('checked');
			}
		});
	}
	
	function showAndHideMsg($msg, type) {
		$msg.children('p').first().text(clubMessages[type]);
		$msg.fadeIn();
		setTimeout(function () {
			$msg.fadeOut();
		}, options.hideMessageIn);
	}
	
	function initPageHandlers() {
		$('.nextpagearrow').click(function (e) {
			e.stopImmediatePropagation();
			changePage(true);
			return false;
		});
		$('.prevpagearrow').click(function (e) {
			e.stopImmediatePropagation();
			changePage(false);
			return false;
		});
	}
	
	function getFromJQueryByClass($elements, className) {
		var $elem = null;
		$elements.each(function (idx, elem) {
			$elem = $(elem);
			if ($elem.hasClass(className)) {
				return false;
			}
		});
		
		if ($elem === null) {
			return undefined;
		}
		
		return $elem;
	}
	
	function initPagination() {
		$pages = $('.whole-page', $section);
		page = {
			'current': 1,
			'max': $pages.size()
		};

		if (fromNews) {
			page.current = 3;
		}
	}
	
	function changePage(next, pageNumber) {
		if (next) {
			if (page.current == page.max) {
				if (options.sections[sectionName].name === 'products') {
					getFromJQueryByClass($pages, 'whole-page' + page.current).hide();
					page.current = 1;
					getFromJQueryByClass($pages, 'whole-page' + page.current).show();
					changeProductSection();
					return false;
				} else {
					return false;
				}
			}
			
			getFromJQueryByClass($pages, 'whole-page' + page.current).hide();
			if (pageNumber) {
				page.current = pageNumber;
			} else {
				page.current++;
			}
			getFromJQueryByClass($pages, 'whole-page' + page.current).show();
		} else {
			if (page.current == 1) {
				if (options.sections[sectionName].name === 'products') {
					getFromJQueryByClass($pages, 'whole-page' + page.current).hide();
					page.current = page.max;
					getFromJQueryByClass($pages, 'whole-page' + page.current).show();
					changeProductSection();
					return false;
				} else {
					return false;
				}
			}
			
			getFromJQueryByClass($pages, 'whole-page' + page.current).hide();
			if (pageNumber) {
				page.current = pageNumber;
			} else {
				page.current--;
			}
			getFromJQueryByClass($pages, 'whole-page' + page.current).show();
		}
		
		if (options.sections[sectionName].name !== 'games' && options.sections[sectionName].name !== 'products') {
			$('.leftpagenummber', $section).html(page.current * 2 - 1);
			$('.rightpagenummber', $section).html(page.current * 2);
		}
		if (options.sections[sectionName].name === 'products') {
			changeProductSection();
		}
		
		return true;
	}
	
	function changeProductSection() {
		tmp.productSection = $('#product' + page.current);
		tmp.productTexts = $('.textproduct', tmp.productSection);
	}
	
	/**
	 * Vrátí vzdálenost k elementu od okraje #landscape.
	 *
	 * @return int
	 */
	function getDistanceToElement(elem) {
		return elem.parents(':first').position().left + elem.position().left;
	}
	
	/**
	 * Vrátí jQuery objekty všech aktivních prvků.
	 *
	 * @return Object[]
	 */
	function getActiveElements() {
		var activeElements = {};
		$('.active-elem', $landscape).each(function (idx, elem) {
			var $elem = $(elem);
			activeElements[$elem.attr('id')] = $elem;
		});
		
		return activeElements;
	}
	
	/**
	 * Vrátí jQuery objekty všech informačních bublin.
	 *
	 * @return Object[]
	 */
	function getBubbles() {
		var bubbles = {};
		$('.bubble', $landscape).each(function (idx, elem) {
			var $elem = $(elem);
			bubbles[$elem.attr('id').replace('-bubble', '')] = $elem;
		});
		
		return bubbles;
	}
	
	/**
	 * Animuje pohyb elementu po trajektorii dané souřadnicemi ve tvaru:<br>
	 * <pre>
	 * [
	 *   [0, 0],		// první hodnota je left, druhá pak bottom
	 *   [100, 100]
	 * ]
	 * </pre>
	 *
	 * @return void
	 */
	function moveElement(elem, coords) {
		var opts = {
			'duration': (options.animations[elem]) ? options.animations[elem].duration : options.animations.duration,
			'easing': 'linear'
		};
		
		for (var i = 0; i < coords.length; i++) {
			if (i === coords.length - 1) {
				opts.complete = function () {
					moveElement(elem, coords);
				};
			}
			
			var tmpElem = activeElements[elem];
			if (!tmpElem) {
				tmpElem = $('#' + elem);
			}
			
			tmpElem.animate({
				'left': coords[i][0],
				'bottom': coords[i][1]
			}, opts);
		}
	}
	
	/**
	 * Inicializuje pohyb elementů po trajektorii.
	 *
	 * @return void
	 */
	function initAnimations() {
		moveElement('balloon', [[92, 400], [92, 440]]);
		moveElement('ladybird', [[550, 230], [520, 300], [494, 258]]);
		moveElement('owl', [[106, 200], [106, 220]]);
		moveElement('shark', [[50, 130], [50, 136]]);
	}
	
	/**
	 * Rotuje mlýnksým kolem.
	 * 
	 * @return void
	 */
	function rotateMill() {
		$('#mill-wheel').css('transform', 'rotate(' + options.rotate.value + 'deg)');
		options.rotate.value -= options.rotate.inc;
	}
	
	/**
	 * Spustí skrolování.
	 * 
	 * @return void
	 */
	function startScroll() {
		keepScrolling = true;
		if (!scrolling) {
			scrolling = true;
			scroll(options.scrollFirstStep);
		}
	}
	
	/**
	 * Zastaví skrolování.
	 * 
	 * @return void
	 */
	function stopScroll() {
		keepScrolling = false;
	}
	
	function scrollToDirection(distance, right) {
		var direction = right || false;
		
		if (direction) {
			screenLeftPos -= distance;
			screenRightPos -= distance;
			if (screenRightPos < rightTreshold) {
				moveRight();
			}
		} else {
			screenLeftPos += distance;
			screenRightPos += distance;
			if (screenLeftPos > leftTreshold) {
				moveLeft();
			}
		}
	}
	
	/**
	 * Animace skrolování.
	 *
	 * @return void
	 */
	function scroll(distance) {
		if (distance <= 0) {
			screenLeftPos = parseInt($landscape.css('left'), 10);
			screenRightPos = screenLeftPos - screenWidth;
			scrolling = false;
			return;
		}
		
		if (scrollDirection == 'arrow-right') {
			$landscape.css('left', '-=' + distance);
			scrollToDirection(distance, true);
		} else {
			$landscape.css('left', '+=' + distance);
			scrollToDirection(distance, false);
		}
		
		if (!keepScrolling) {
			distance -= options.scrollInc;
		}
		else if (keepScrolling && distance < options.scrollMaxSpeed) {
			distance += options.scrollInc;
		}
		
		setTimeout(function () {
			scroll(distance);
		}, options.scrollCycle);
	}
	
	/**
	 * Posune jednu část krajiny doprava.
	 *
	 * @return void
	 */
	function moveRight() {
		landscapeParts[firstChild].elem.css('left', '+=' + landscapeWidth);
		
		rightTreshold -= landscapeParts[lastChild].width;
		lastChild = firstChild;
		
		if (++firstChild == landscapeParts.length) {
			firstChild = 0;
		}
		
		leftTreshold -= landscapeParts[firstChild].width;
	}
	
	/**
	 * Posune jednu část krajiny doleva.
	 * 
	 * @return void
	 */
	function moveLeft() {
		landscapeParts[lastChild].elem.css('left', '-=' + landscapeWidth);

		leftTreshold += landscapeParts[firstChild].width;
		firstChild = lastChild;
		
		if (--lastChild < 0) {
			lastChild = landscapeParts.length - 1;
		}
		
		rightTreshold += landscapeParts[lastChild].width;
	}
	
	/**
	 * Vrátí části krajiny jako pole obsahující jejich jQuery objekty.
	 * 
	 * @return Object[]
	 */
	function getLandscapeParts() {
		var parts = [];
		
		$landscape.children('.landscape-part').each(function (idx, elem) {
			elem = $(elem);
			parts[idx] = {
				'elem': elem,
				'width': elem.width()
			};
		});
		
		return parts;
	}
	
	/**
	 * Schová všechny informační bubliny.
	 *
	 * @return void
	 */
	function hideBubbles() {
		$.each(bubbles, function (idx, elem) {
			elem.hide();
		});
	}
	
	function initHomepageHandlers() {
		$('#menu2-homepage').click(function () {
			var prevPos = null;
			var distance = null;
			var right = true;
			var partLeft = landscapeParts[3].elem.position().left;
			
			if (partLeft < Math.abs($landscape.position().left)) {
				right = false;
			}
			
			$landscape.animate({'left': -partLeft}, {
				'duration': 2000,
				'step': function (now) {
					if (!prevPos) {
						prevPos = now;
					} else {
						if (right) {
							distance = Math.abs(prevPos - now);
							scrollToDirection(distance, right);
						} else {
							distance = Math.abs(prevPos - now);
							scrollToDirection(distance, right);
						}

						prevPos = now;
					}
				}
			});
			
			return false;
		});
	}
	
	function initNewsBillboard() {
		$billboardNews.click(function (e) {
			e.stopImmediatePropagation();
			
			var $this = $(this);
			if ($this.attr('id') === 'billboard-products') {
				fromNews = true;
				sectionControll(['ladybird']);
			} else if ($this.attr('id') === 'billboard-games') {
				sectionControll(['owl', 'tower']);
			} else if ($this.attr('id') === 'billboard-club') {
				sectionControll(['club']);
			}
			
			return false;
		});
		$('#newsleft, #newsright').click(function (e) {
			e.stopImmediatePropagation();
			
			clearTimeout(billboardId);
			var prevCounter = null;
			if ($(this).attr('id') === 'newsleft') {
				newsCounter--;
				prevCounter = newsCounter + 1;
			} else {
				newsCounter++;
				prevCounter = newsCounter - 1;
			}
			if (newsCounter === -1) {
				newsCounter = $billboardNews.size() - 1;
				prevCounter = 0;
			} else if (newsCounter === $billboardNews.size()) {
				newsCounter = 0;
				prevCounter = $billboardNews.size() - 1;
			}
			
			$billboardNews.each(function (idx, elem) {
				var $elem = $(elem);
			
				if (idx === newsCounter) {
					$elem.fadeIn();
				} else if (idx === prevCounter) {
					$elem.fadeOut();
				}
			});
			billboardId = setTimeout(rotateNews, options.newsRotate);
			
			return false;
		});
	}
	
	function rotateNews() {
		newsCounter++;
		var prevCounter = newsCounter - 1;
		if (newsCounter == $billboardNews.size()) {
			newsCounter = 0;
			prevCounter = $billboardNews.size() - 1;
		}
		
		$billboardNews.each(function (idx, elem) {
			var $elem = $(elem);
			
			if (idx === newsCounter) {
				$elem.fadeIn();
			} else if (idx === prevCounter) {
				$elem.fadeOut();
			}
		});
		billboardId = setTimeout(rotateNews, options.newsRotate);
	}
	
	function watchResize() {
		var id = null;
		
		$window.resize(function (e) {
			e.preventDefault();
			screenWidth = $window.width();
			screenRightPos = screenLeftPos - screenWidth;
			menuPosition();
			
			// aby se fce updateScrollbarArrowsHeight zavolala pouze jednou v některých browserech se volá 2x (pro každou
			// osu zvlášť)
			clearTimeout(id);
			id = setTimeout(function () {updateScrollbarArrowsHeight();}, 300);
		});
	}
	
	function updateScrollbarArrowsHeight() {
		if ($window.width() <= 1024) {
			$arrows.css('height', $window.height() - $menu2.height());
		} else {
			$arrows.css('height', '100%');
		}
	}
	
	function menuPosition() {
		var left = 0;
		var $item = null;

		if (screenWidth < 1024) {
			$item = $('#menu2-homepage');
			left += $item.width() / 2; 
			$item.hide();
		} else {
			$item = $('#menu2-homepage');
			$item.show();
		}
		left += (screenWidth - $menu2.width() + 65) / 2;
		
		$menu2.css('left', left);
	}
	
	function redirection() {
		var pathName = window.location.pathname;
		
		if (pathName === '/waterrrsport') {
			oldShowSectionDuration = options.showSectionDuration;
			oldZoomDuration = options.zoom.duration;
			options.showSectionDuration = 1;
			options.zoom.duration = 1;
			
			setTimeout(function () {
				directProduct = true;
				$('#menu2-ladybird').click();
			}, 20);
		}
	}
	
	return {
		init: function () {
			menuPosition();
			updateScrollbarArrowsHeight();
			watchResize();
			
			rotateNews();
			
			initScrollHandlers();
			initMenuHandlers('menu');
			initMenuHandlers('menu2');
			initActiveElementsHandlers();
			initCloseBtnHandlers();
			initPageHandlers();
			initHomepageHandlers();
			initNewsBillboard();
			initAnimations();
			initSectionSwitcher();
			
			redirection();
			setInterval(rotateMill, options.rotate.cycle);
		}
	};
}();

jQuery(function ($) {
	Preloader.init();
	Kubik.init();
	
	$("#jquery_jplayer_1").jPlayer({
		ready: function () {
			$(this).jPlayer("setMedia", {
				m4v: "videos/kubikspot.mp4",
				ogv: "swf/kubikspot.ogv",
				poster: "img/kubikspot.png"
			});
		},
		size: {
			width: "640px",
			height: "360px"
		},
		swfPath: "js",
		supplied: "m4v, ogv"
	});
});

