﻿// inCMS common js
// (c)2008 Spika David, Inexes

var inCMS = {};

// Fce vrátí html prvek
// parametry: ID nebo prvek
inCMS.getObj = function(x) {
	if (typeof x != 'string') return x;
	else if (Boolean(document.getElementById)) return document.getElementById(x);
	else return null;
}

// Fce vrátí pole všech html prvků v daném prvku, jejichž className obsahuje zadaný řetězec
// parametry: ID prvku ve kterém hledat, název prvku který hledat (možno použít *), podřetězec className
inCMS.getElementsByClass = function(p, t, c) {
	var o = inCMS.getObj(p);
	var tempField = new Array();
	var elements = o.getElementsByTagName(t);
	for (var i = 0; i < elements.length; i++) {
		if (elements[i].className.indexOf(c) != -1) {
			tempField[tempField.length] = elements[i];
		}
	}
	return tempField;
}

// Fce přidá skript (před nebo za stávající funkce) navázaný na definovanou událost html prvku
// použití: addEvent(window,'onload','alert(o.id);');
// parametry: ID nebo prvek, název události, skript navázaný na událost (pravidla pro skript: na daný prvek neodkazovat přes this, ale přes o), příznak jestli má být nový skript vložen před/za stávající
inCMS.addEvent = function(obj, e, s, before) {
	var o = inCMS.getObj(obj);
	eval('var oldEvent = o.' + e + ';');
	if (!before) eval('o.' + e + ' = function (' + (inCMS.browser.IE ? '' : 'event') + ') { ' + (oldEvent ? 'oldEvent(' + (inCMS.browser.IE ? '' : 'event') + ');' : '') + s + ' };');
	else eval('o.' + e + ' = function (' + (inCMS.browser.IE ? '' : 'event') + ') { ' + s + (oldEvent ? 'oldEvent(' + (inCMS.browser.IE ? '' : 'event') + ');' : '') + ' };');
}

// Fce přidá skript navázaný na definovanou událost všem html prvkům, jejichž className obsahuje zadaný řetězec
// parametry: ID prvku ve kterém hledat, název prvku (možno použít *), podřetězec className, název události, skript navázaný na událost, příznak jestli má být nový skript vložen před/za stávající
inCMS.addEventByClass = function(p, t, c, e, s, before) {
	var o = inCMS.getObj(p);
	var elements = o.getElementsByTagName(t);
	for (var i = 0; i < elements.length; i++) {
		if (elements[i].className.indexOf(c) != -1) {
			inCMS.addEvent(elements[i], e, s, before);
		}
	}
}

// Fce přidá skript navázaný na definovanou událost všem formulářovým prvkům, jejichž className obsahuje zadaný řetězec
// parametry: název prvku (možno použít *), podřetězec className, název události, skript navázaný na událost, příznak jestli má být nový skript vložen před/za stávající
inCMS.addEventToForm = function(t, c, e, s, before) {
	var elements = document.forms[0];
	for (var i = 0; i < elements.length; i++) {
		if (elements[i].nodeName.toLowerCase() == t && elements[i].className.indexOf(c) != -1) {
			inCMS.addEvent(elements[i], e, s, before);
		}
	}
}

// Fce nahradí chybějící podporu css pseudotřídy :hover pro IE6- všem html prvkům, jejichž className obsahuje zadaný řetězec
// parametry: ID prvku ve kterém hledat, název prvku (možno použít *), podřetězec className
inCMS.hoverByClass = function(p, t, c) {
	if (inCMS.browser.IE6) {
		var o = inCMS.getObj(p);
		var elements = o.getElementsByTagName(t);
		for (var i = 0; i < elements.length; i++) {
			if (elements[i].className.indexOf(c) != -1) {
				inCMS.addEvent(elements[i], 'onmouseover', 'o.className += \' hover\';');
				inCMS.addEvent(elements[i], 'onmouseout', 'o.className = o.className.replace(\' hover\',\'\');');
			}
		}
	}
}

// Fce nastaví html prvku css styl
// parametry: ID nebo prvek, 'vlastnost', 'hodnota'
inCMS.setObjStyle = function(obj, prop, val) {
	var o = inCMS.getObj(obj);
	if (o && o.style) {
		eval('o.style.' + prop + '="' + val + '"');
		return true;
	}
	else return false;
}

// Fce vrátí hodnotu css parametru u html prvku
// parametry: ID nebo prvek, 'vlastnost'
inCMS.getObjStyle = function(obj, prop) {
	var o = inCMS.getObj(obj);
	if (document.defaultView) var val = window.document.defaultView.getComputedStyle(o, null).getPropertyValue(prop); // Mozilla
	else if (o.currentStyle) var val = eval('o.currentStyle.' + prop); // IE
	return val;
}

// Fce nastaví css styl všem html prvkům, jejichž className obsahuje zadaný řetězec
// parametry: název prvku (možno použít *), podřetězec className, 'vlastnost', 'hodnota'
inCMS.setObjStyleByClass = function(p, t, c, prop, val) {
	var o = inCMS.getObj(p);
	var elements = o.getElementsByTagName(t);
	for (var i = 0; i < elements.length; i++) {
		if (elements[i].className.indexOf(c) != -1) {
			inCMS.setObjStyle(elements[i], prop, val);
		}
	}
}

// Fce na zobrazení/zneviditelnění html prvku
// parametry: ID nebo prvek, zobrazení - true/false
inCMS.showObj = function(obj, on) {
	return inCMS.setObjStyle(obj, 'visibility', (on) ? 'visible' : 'hidden');
}

// Fce na zobrazení/skrytí html prvku
// parametry: ID nebo prvek, zobrazení - true/false, hodnota css vlastnosti display (není povinná, pokud 2. parametr = false)
inCMS.displayObj = function(obj, on, type) {
	if (on && !type) {
		if (!inCMS.browser.IE && inCMS.getObj(obj) && inCMS.getObj(obj).nodeName.toLowerCase() == 'tr') type = 'table-row';
		else if (!inCMS.browser.IE && inCMS.getObj(obj) && inCMS.getObj(obj).nodeName.toLowerCase() == 'tbody') type = 'table-row-group';
		else type = 'block';
	}
	return inCMS.setObjStyle(obj, 'display', (on) ? type : 'none');
}

// Konstruktor na vytvoření kopie objektu (pro uživatelské objekty příjímané přes AJAX, jejichž struktura není známa)
// použití: novy_objekt = new cloneObj(stary_objekt)
// parametry: objekt
inCMS.cloneObj = function(obj) {
	for (var property in obj) {
		if (typeof obj[property] == 'object') {
			if (obj.length) this.length = obj.length;
			this[property] = new cloneObj(obj[property]);
		}
		else this[property] = obj[property];
	}
}

// Fce na porovnání 2 objektů (pro uživatelské objekty příjímané přes AJAX, jejichž struktura není známa)
// Pokud se liší, vrací true
// parametry: objekt1, objekt2
inCMS.compareObjs = function(obj1, obj2) {
	var isChange = false;
	var maxCount = (obj1.length >= obj2.length) ? obj1.length : obj2.length;
	for (var i = 0; i < maxCount; i++) {
		var item = obj1[i]; // 1
		if (!item) { isChange = true; break; }
		else for (var property in item) {
			item = obj1[i]; // 1
			var val1 = item[property]; // 1 - vlastnost
			item = obj2[i]; // 2
			if (!item) { isChange = true; break; }
			else {
				var val2 = item[property]; // 2 - vlastnost
				if (typeof val1 != 'object' && typeof val2 != 'object' && val1 != val2) { isChange = true; break; }
			}
		}
	}
	return isChange;
}

// Fce vrátí pole indexů, na kterých se v zadaném poli vyskytuje zadaná hodnota
// parametry: pole, hodnota, příznak podle kterého se testuje rovnost(substring=false) nebo jen obsah podřetězce(substring=true)
inCMS.findFieldIndexesByValue = function(field, value, substring) {
	var fieldIndexes = new Array();
	for (var i = 0; i < field.length; i++) {
		if (field[i] == value && !substring) {
			fieldIndexes.length++;
			fieldIndexes[fieldIndexes.length - 1] = i;
		}
		if (field[i].indexOf(value) != -1 && substring) {
			fieldIndexes.length++;
			fieldIndexes[fieldIndexes.length - 1] = i;
		}
	}
	return fieldIndexes;
}

// Fce odstraní zadanou hodnotu z pole
// parametry: pole; hodnota
inCMS.removeValueFromField = function(field, value) {
	var position = field.length + 1;
	for (var i = 0; i < field.length; i++) if (field[i] == value) position = i;
	for (var i = position; i < field.length - 1; i++) field[i] = field[i + 1];
	field.length--;
}

// Fce odstraní zadanou hodnotu z pole
// parametry: pole; hodnota
inCMS.addValueToField = function(field, value) {
	field.length++;
	field[field.length - 1] = value;
}

// Fce vrátí hodnotu zadaného parametru z url
// použití: hodnota = getParamsFromUrl()['parametr']
inCMS.getParamsFromUrl = function() {
	var field = window.location.search.substr(1).split('&');
	var params = new Array();
	for (var i = 0; i < field.length; i++) {
		params[field[i].split('=')[0]] = unescape(field[i].split('=')[1]);
	}
	return params;
}

// Objekt pro práci s popup okny
inCMS.popup = {
	// Odkaz na popup okno otevřené metodou open()
	win: null,
	// Metoda na otevření nového popup okna 
	// parametry: url, šířka okna, výška okna, posuvníky a proměnná velikost okna - true/false, název okna
	open: function(src, width, height, fixedSize) {
		if (fixedSize) var param = 'no';
		else var param = 'yes';
		var p = 'toolbar=no,menubar=no,location=no,directories=no,scrollbars=' + param + ',resizable= ' + param + ',status=no,width=' + width + ',height=' + height + ',left=' + (screen.availWidth / 2 - width / 2) + ',top=' + (screen.availHeight / 2 - height / 2);
		if (this.win) this.win.close();
		this.win = window.open(src, '', p);
		this.win.focus();
	},
	// Metoda vrátí odkaz na html prvek umístěný v rodičovském okně do popup okna
	// parametry: ID nebo prvek
	getObj: function(x) {
		return inCMS.getObj(x);
	}
};

// Detail obrázku v novém okně:
inCMS.imagePopupWindow = null;
inCMS.imagePopup = function(src, title, width, height) {
	if (inCMS.imagePopupWindow) inCMS.imagePopupWindow.close();
	var imageWidth = width;
	var imageHeight = height;
	if (width < 400) width = 400;
	if (height < 300) height = 300;
	if (width > 990 || height > 700) var s = 'scrollbars=yes';
	else var s = 'scrollbars=no';
	if (width > 990) width = 990;
	if (height > 700) height = 700;
	var p = 'toolbar=no,menubar=no,location=no,resizable=yes,directories=no,status=no,width=' + width + ',height=' + height + ',left=' + (screen.availWidth / 2 - width / 2) + ',top=' + (screen.availHeight / 2 - height / 2) + ',' + s;
	inCMS.imagePopupWindow = window.open(appWWWRoot + 'admin/PreviewImage.html?src=' + escape(src) + '&title=' + escape(title) + '&width=' + imageWidth + '&height=' + imageHeight, '', p);
	inCMS.imagePopupWindow.focus();
}

// Objekt na detekci prohlížeče
inCMS.browser = {
	IE: navigator.appName == 'Microsoft Internet Explorer',
	IE6: navigator.userAgent.indexOf('MSIE 6') != -1,
	IE7: navigator.userAgent.indexOf('MSIE 7') != -1,
	opera: navigator.userAgent.indexOf('Opera') != -1,
	gecko: navigator.userAgent.indexOf('Gecko') != -1,
	safari: navigator.userAgent.indexOf('Safari') != -1
}
// Opera se může tvářit i jako jiný prohlížeč, proto oprava:
if (inCMS.browser.opera) {
	for (var property in inCMS.browser) {
		if (property != 'opera') inCMS.browser[property] = false;
	}
}

// Fce vrátí souřadnice html prvku vůči stránce (každý prohlížeč může vracet jiné)
// parametry: ID nebo prvek
inCMS.getObjCoords = function(obj) {
	var element = inCMS.getObj(obj);
	var coords = { x: 0, y: 0 };
	while (element) {
		coords.x += element.offsetLeft;
		coords.y += element.offsetTop;
		element = element.offsetParent;
	}
	return coords;
}

// Fce vrátí souřadnice kurzoru vůči stránce (každý prohlížeč může vracet jiné)
// parametry: event
inCMS.getMouseCoords = function(e) {
	if (e.pageX || e.pageY) {
		return { x: e.pageX, y: e.pageY };
	}
	return {
		x: e.clientX + document.body.scrollLeft - document.body.clientLeft,
		y: e.clientY + document.body.scrollTop - document.body.clientTop
	};
}

// Fce vrátí aktuální velikost okna
inCMS.windowSize = function() {
	if (document.documentElement && document.documentElement.clientWidth) {
		var size = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
		return size;
	}
	else if (document.body && document.body.clientWidth) {
		var size = { width: document.body.clientWidth, height: document.body.clientHeight };
		return size;
	}
	else var size = { width: 0, height: 0 };
	return size;
}

// Fce vrátí aktuální pozici stránky
inCMS.pagePosition = function() {
	var left = (window.pageXOffset) ? window.pageXOffset
		: (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft
		: (document.body) ? document.body.scrollLeft
		: 0;
	var top = (window.pageYOffset) ? window.pageYOffset
		: (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop
		: (document.body) ? document.body.scrollTop
		: 0;
	var position = { x: left, y: top };
	return position;
}

// Fce vrátí aktuální velikost stránky
inCMS.pageSize = function() {
	var w = (window.innerWidth && window.scrollMaxX) ? window.innerWidth + window.scrollMaxX
		: (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth
		: document.body.offsetWidth;
	var h = (window.innerHeight && window.scrollMaxY) ? window.innerHeight + window.scrollMaxY
		: (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight
		: document.body.offsetHeight;
	if (w < inCMS.windowSize().width) w = inCMS.windowSize().width;
	if (h < inCMS.windowSize().height) h = inCMS.windowSize().height;
	var size = { width: w, height: h };
	return size;
}

// Metoda nastaví průhlednost html prvku
// parametry: html prvek (nebo jeho ID), hodnota průhlednosti 0-100
inCMS.setOpacity = function(obj, val) {
	var o = inCMS.getObj(obj);
	if (inCMS.browser.IE) o.style.filter = (val == 100) ? 'none' : 'alpha(opacity=' + val + ')';
	else {
		o.style.MozOpacity = val / 100;
		o.style.KHTMLOpacity = val / 100;
		o.style.opacity = val / 100;
	}
}

// Fce uloží do cookies zadanou hodnotu
inCMS.setCookie = function(name, value, path, domain, secure) {
	expires = new Date();
	expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000 * 31));
	document.cookie = escape(name) + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

// Fce vrátí z cookies hodnotu podle jména
inCMS.getCookie = function(name) {
	var cookieList = document.cookie.split("; ");
	for (var i = 0; i < cookieList.length; i++) {
		var cookie = cookieList[i].split("=");
		if (unescape(cookie[0]) == name) {
			return unescape(cookie[1]);
			break;
		}
	}
	return null;
}

// *********************************
// Kód pro jednotlivé moduly a menu:
// *********************************


// FilharmonieBrno js
// (c)2009 Spika David, Inexes

var fB = {};
fB.langCode = ['cs', 'en'];
fB.langResources = {};
fB.langResources.tab0 = ['Koncerty', 'Concerts'];
fB.langResources.tab2 = ['Košík | rezervace | platba kartou', 'Cart | reservation | card payment'];
fB.langResources.limitInfo = ['10 a více položek lze objednat pouze při platbě kartou.', 'More then 10 items can not be reserved.'];

if (location.href.indexOf('/catalog/') != -1 && location.hash == '') {
	location.href = location.href.replace('/catalog/', '/#' + langPrefix + 'catalog/');
}
else if (location.href.indexOf('/detail/') != -1 && location.hash == '') {
	location.href = location.href.replace('/detail/', '/#' + langPrefix + 'detail/');
}
else if (location.href.indexOf('/cart/') != -1 && location.hash == '') {
	location.href = location.href.replace('/cart/', '/#' + langPrefix + 'cart/');
}
else if (location.href.indexOf('/ordersummary/') != -1 && location.hash == '') {
	location.href = location.href.replace('/ordersummary/', '/#' + langPrefix + 'ordersummary/');
}
else if (location.href.indexOf('/orderpayment/') != -1 && location.hash == '') {
	location.href = location.href.replace('/orderpayment/', '/#' + langPrefix + 'orderpayment/');
}

fB.initHash = location.hash;
fB.actualHash = fB.initHash;
fB.leftContent = {
	loaded: false,
	actualHash: (fB.initHash.indexOf('catalog/') != -1 || fB.initHash.indexOf('detail/') != -1) ? fB.initHash : '#' + langPrefix + 'catalog/',
	catalogHash: fB.initHash.indexOf('catalog/') != -1 ? fB.initHash : '#' + langPrefix + 'catalog/'
};

$(function() {
	if ($('html').attr('lang') == 'cs') fB.langIndex = 0;
	else if ($('html').attr('lang') == 'en') fB.langIndex = 1;

	if (fB.initHash.indexOf('catalog/') != -1 || fB.initHash.indexOf('detail/') != -1) {
		fB.ajaxRequest(appWWWRoot + fB.initHash.replace('#', ''));
		fB.tabAnimate(0);
	}
	if (fB.initHash.indexOf('cart/') != -1 || fB.initHash.indexOf('ordersummary/') != -1 || fB.initHash.indexOf('orderpayment/') != -1) {
		fB.ajaxRequest(appWWWRoot + fB.initHash.replace('#', ''));
		fB.tabAnimate(2);
	}

	inCMS.preloadImages = [];
	$('a[rel=lightbox]').each(function(i) {
		if (this.className.indexOf('id:') != -1) {
			var id = this.className.split(':')[1];
			var name = $(this).attr('href').split('/')[$(this).attr('href').split('/').length - 1];
			inCMS.preloadImages[i] = new Image();
			inCMS.preloadImages[i].src = name + '?docid=' + id + '&width=800&height=600&rtypeid=4';
			inCMS.preloadImages[i].className = 'preloadImage';
			$('body').append(inCMS.preloadImages[i]);
			$(this).click(function() {
				inCMS.galleries.showSingleLightbox(i, name + '?docid=' + id + '&width=800&height=600&rtypeid=4', $(this).attr('title'));
				return false;
			});
		}
	});

	/* hash change event handler */
	$(window).history(function(e, ui) {
		var history = {};
		if (fB.actualHash.indexOf('catalog/') != -1) history.prevIsCatalog = true;
		if (fB.actualHash.indexOf('detail/') != -1) history.prevIsDetail = true;
		if (fB.actualHash.indexOf('cart/') != -1 || fB.actualHash.indexOf('ordersummary/') != -1) history.prevIsCart = true;
		if (fB.actualHash == '' || fB.actualHash == '#page/') history.prevIsPage = true;
		if (ui.value.indexOf('catalog/') != -1) history.nextIsCatalog = true;
		if (ui.value.indexOf('detail/') != -1) history.nextIsDetail = true;
		if (ui.value.indexOf('cart/') != -1 || ui.value.indexOf('ordersummary/') != -1) history.nextIsCart = true;
		if (ui.value == '' || ui.value == 'page/') history.nextIsPage = true;
		fB.actualHash = ui.value;
		/* Catalog, detail */
		if (history.nextIsCatalog || history.nextIsDetail) {
			fB.leftContent.actualHash = fB.actualHash;
			if (history.nextIsCatalog) fB.leftContent.catalogHash = fB.actualHash;
			if (!(history.prevIsCatalog || history.prevIsDetail)) {
				if (!fB.leftContent.loaded || history.nextIsDetail) {
					fB.ajaxRequest(appWWWRoot + ui.value);
				}
				fB.tabAnimate(0);
			}
			else {
				fB.ajaxRequest(appWWWRoot + ui.value);
			}
		}
		/* Cart */
		else if (history.nextIsCart) {
			fB.ajaxRequest(appWWWRoot + ui.value);
			if (!history.prevIsCart) {
				fB.tabAnimate(2);
			}
		}
		/* inCMS page */
		else if (history.nextIsPage) {
			if (history.prevIsCatalog || history.prevIsDetail) {
				fB.tabAnimate(0);
			}
			else if (history.prevIsCart) {
				fB.tabAnimate(2);
			}
		}
	});
});

$(window).resize(function() {
	fB.dimensionsInit();
	if ($('#flashContent')[0]) fB.embedStageFlash();
});

$(window).load(function() {
	$('#tabFlash-0, #tabFlash-2').css('top', ((fB.winHeight - 600) / 2) + 'px');
});

if (inCMS.browser.IE6) {
	$(window).scroll(function() {
		$('.tabControl').css('top', inCMS.pagePosition().y + 'px').find('object,div').css('top', ((fB.winHeight - 600) / 2) + 'px');
	});
}

/* Masterpage */
fB.dimensionsInit = function() {
	fB.winWidth = inCMS.windowSize().width;
	fB.winHeight = inCMS.windowSize().height;

	//	$('#viewport').width(fB.winWidth).height(fB.winHeight);
	var actualContent = 1;
	$('.tabContent').each(function(i) { $(this).width(fB.winWidth - 72); });
	$('.tabContent').each(function(i) {
		if ($(this).hasClass('tabContent-visible')) {
			var id = $(this).attr('id');
			if (id == "leftContent") actualContent = 0;
			else if (id == "page") actualContent = 1;
			else if (id == "rightContent") actualContent = 2;
			return false;
		}
	});
	/* Catalog, detail */
	if (actualContent == 0) {
		$('#leftTab').css({ 'left': (fB.winWidth - 71) + 'px' });
		$('#rightTab').css({ 'left': (fB.winWidth - 35) + 'px' });
	}
	/* InCMS page */
	if (actualContent == 1) {
		$('#leftTab').css({ 'left': (0) + 'px' });
		$('#rightTab').css({ 'left': (fB.winWidth - 35) + 'px' });
	}
	/* Cart */
	if (actualContent == 2) {
		$('#leftTab').css({ 'left': (0) + 'px' });
		$('#rightTab').css({ 'left': (36) + 'px' });
	}
	$('.tabControl').height(fB.winHeight);
	$('#tabFlash-0, #tabFlash-2').css('top', ((fB.winHeight - 600) / 2) + 'px');
}

fB.tabAnimate = function(n) {
	var animateFrom = 1;
	$('.tabContent').each(function(i) {
		if ($(this).hasClass('tabContent-visible')) {
			var id = $(this).attr('id');
			if (id == "leftContent") animateFrom = 0;
			else if (id == "page") animateFrom = 1;
			else if (id == "rightContent") animateFrom = 2;
			return false;
		}
	});
	var animateTo = n;
	if (animateFrom == n) animateTo = 1;
	/* Catalog, detail */
	if (animateTo == 0) {
		$('#leftTab').css({ 'left': (fB.winWidth - 71) + 'px' });
		$('#rightTab').css({ 'left': (fB.winWidth - 35) + 'px' });
	}
	/* InCMS page */
	if (animateTo == 1) {
		$('#leftTab').css({ 'left': (0) + 'px' });
		$('#rightTab').css({ 'left': (fB.winWidth - 35) + 'px' });
	}
	/* Cart */
	if (animateTo == 2) {
		$('#leftTab').css({ 'left': (0) + 'px' });
		$('#rightTab').css({ 'left': (36) + 'px' });
	}
	if (animateTo != 1) {
		if (Math.abs(animateTo - animateFrom) > 1)
			fB.setTabFlashContent(2 - n, 3 - n, eval('fB.langResources.tab' + (2 - n) + '[' + fB.langIndex + ']'));
		var text = $('h1').text();
		var m = 2;
	}
	else {
		var text = eval('fB.langResources.tab' + n + '[' + fB.langIndex + ']');
		var m = n + 1;
	}
	fB.setTabFlashContent(n, m, text);
	$('#cartInfo,#limitInfo').hide();
	$('.tabContent').eq(animateFrom).removeClass('tabContent-visible').end()
	.eq(animateTo).addClass('tabContent-visible');
	$('html,body').scrollTop(0);
}

fB.tabClick = function(n) {
	var animateFrom = 1;
	$('.tabContent').each(function(i) {
		if ($(this).hasClass('tabContent-visible')) {
			var id = $(this).attr('id');
			if (id == "leftContent") animateFrom = 0;
			else if (id == "page") animateFrom = 1;
			else if (id == "rightContent") animateFrom = 2;
			return false;
		}
	});
	var animateTo = n;
	if (animateFrom == n) animateTo = 1;
	/* Catalog, detail */
	if (animateTo == 0) {
		if (!fB.leftContent.loaded) {
			location.hash = fB.leftContent.catalogHash;
		}
		else location.hash = fB.leftContent.actualHash;
	}
	/* InCMS page */
	if (animateTo == 1) {
		location.hash = '#page/';
	}
	/* Cart */
	if (animateTo == 2) {
		location.hash = '#' + langPrefix + 'cart/';
	}
}

fB.setTabFlashContent = function(n, m, text) {
	swfobject.embedSWF('Design/VerticalText.swf', 'tabFlash-' + n, '35', '600', '9.0.0', false, { clickthru: 'javascript:fB.tabClick(' + n + ');', text: text, index: m }, { scale: 'noscale', menu: 'false', wmode: 'transparent' }, { id: "tabFlash-" + n, title: text });
	$('#tabFlash-' + n).css('top', ((fB.winHeight - 600) / 2) + 'px');
	$('div#tabFlash-' + n).attr('title', text);
}

fB.setHashByUrl = function(url) {
	location.hash = '#' + url.replace(appWWWRoot, '');
}

// AJAX Page Flipper
fB.ajaxRequest = function(url) {
	$.ajax({
		type: "POST",
		url: appWWWRoot + "AjaxPageFlipper.asmx/RenderCmsPage",
		data: "{'pageUrl': '" + url + "' }",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			for (var a in data.d) {
				$("#" + a).html(data.d[a]);
				$('html,body').scrollTop(0);
				if (a == 'catalog') {
					if ($.browser.mozilla) $('#catalogView').css('margin', '1px 0 0 1px'); // firefox table offset fix
					$('#detail').hide();
					$('#catalog').show();
					/* do image loading error fix */
					$('#panelResults img').each(function() {
						$(this).load(function() {
							$(this).hide();
							$(this).show();
						});
					});
					fB.leftContent.loaded = true;
				}
				else if (a == 'detail') {
					fB.eventId = $('#hfEventId').val();
					fB.templateId = $('#hfTemplateId').val();
					fB.eventName = $('#hfEventName').val();
					fB.eventDate = $('#hfEventDate').val();
					fB.eventTime = $('#hfEventTime').val();
					fB.eventVenue = $('#hfEventVenue').val();
					$('#catalog').hide();
					$('#detail').show();
					if (fB.templateId != null) {
						fB.discountSelect(fB.selectedDiscount);
						setTimeout('fB.getStageData();', 100);
					}
				}
				else if (a == 'cart') {
				}
				else if (a == 'orderSummary') {
				}
			}
		},
		error: function(req, textStatus, errorThrown) {
			alert(req.responseText);
		}
	});
}

fB.getStageData = function() {
	$.ajax({
		type: "POST",
		url: appWWWRoot + "TicketService.asmx/GetStageTemplate",
		data: "{'stageTemplateId':'" + fB.templateId + "', 'eventId':'" + fB.eventId + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			fB.flashAspect = data.d.Aspect;
			fB.stageXml = data.d.StageXml;
			setTimeout('fB.embedStageFlash();', 100);
		},
		error: function(a, b, c) {
			alert(a.responseText);
		}
	});
}

fB.embedStageFlash = function() {
	var w = fB.winWidth - 72;
	var h = fB.winHeight;
	var a = fB.flashAspect;
	var flashW = w;
	var flashH = h;
	if (a > 1.33) {
		if (w < 1174) flashW = 1174; // 1280
		else if (w > 1494) flashW = 1494; // 1600
		flashH = Math.round(flashW / a);
	}
	else {
		if (h < 880) flashH = 880;
		else if (h > 940) flashH = 940;
		flashW = Math.round(flashH * a);
	}
	if (!inCMS.browser.IE6) $("#flashLimiter").css({ 'left': ($('#detail').width() - w) / 2 }).width(w).height(flashH);
	$("#flashContent").width(flashW).height(flashH);
	swfobject.embedSWF(appWWWRoot + "Design/ClientStage.swf?a=13&EventId=" + fB.eventId, "flashContent", flashW, flashH, "9.0.0", appWWWRoot + "expressInstall.swf", {}, { 'menu': 'false', 'scale': 'noscale', 'wmode': 'transparent', 'bgcolor': 'white', 'allowscriptaccess': 'sameDomain' }, { 'id': 'flashContent' });
}

// Fce volané z flashe
addTicket = function(id, p, priceGroupId, seatTitle) {
	fB.addTicket({ seatId: id, count: 1, priceGroupId: priceGroupId, seatTitle: seatTitle });
}
removeTicket = function(seatId) {
	fB.removeTicket(seatId, null, false);
}
function loadStageDesigner() {
	if (!fB.stageXml) {
		fB.getStageData();
		return;
	}
	setTimeout("fB.doLoadStageDesigner()", 100);
}
fB.doLoadStageDesigner = function() {
	var flashContent = $('#flashContent')[0];
	flashContent.loadXml(fB.stageXml);
	flashContent.showPreviewMode();
	fB.stageXml = null;
}

fB.getPrice = function(id) {
	var priceLookup = $("#hfPriceLookup");
	if (priceLookup.length == 0) {
		return $("#hfPrice").val().replace(',', '.');
	}

	var index = priceLookup.val().toLowerCase().indexOf(id.toLowerCase());
	if (index == -1) return -1;
	return $("#hfPrice-" + index / 37).val().replace(',', '.');
}

// AJAX přidání vstupenky
fB.addTicket = function(item) {
	if (!item.discountId)
		item.discountId = fB.selectedDiscount;

	$.ajax({
		type: "POST",
		url: appWWWRoot + "TicketService.asmx/AddTicket",
		data: "{'eventId':'" + fB.eventId
		+ "', 'discountId':'" + item.discountId
		+ "', 'seatId':'" + item.seatId
		+ "', 'count':'" + '1'
		+ "', 'basePrice':'" + fB.getPrice(item.priceGroupId)
		+ "', 'seatTitle':'" + item.seatTitle
		+ "', 'eventName':'" + fB.eventName
		+ "', 'eventStart':'" + fB.eventDate + ' ' + fB.eventTime
		+ "', 'venueName':'" + fB.eventVenue
		+ "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			var flash = $('#flashContent')[0];

			for (var prop in data.d.AddedItems) {
				fB.addTicketCallback(data.d.AddedItems[prop], data.d.TotalPrice, flash);
			}

			if (data.d.TotalCount == 11)
				fB.showLimitInfo();

			if (flash) {
				for (var prop in data.d.FailedItems) {
					flash.confirmSeatReservation(data.d.FailedItems[prop], 2);
				}
			}
		},
		error: function(a) {
			alert(a.responseText);
		}
	});
}

// AJAX callback po přidání vstupenky nebo abonentky
fB.addTicketCallback = function(item, totalPrice, flash) {
	if (flash) {
		flash.confirmSeatReservation(item.SeatId, 1);
	}
	else {
		if (item.SeatTitle == '') {
			var counter = $('#ticketCount-' + item.FriendlyDiscountId);
			if (counter.length > 0)
				counter.html(parseInt(counter.html()) + 1);
		}
	}

	fB.showCartAddedInfo();
}

fB.removeCartItem = function(id) {
	$.ajax({
		type: "POST",
		url: appWWWRoot + "TicketService.asmx/RemoveCartItem",
		data: "{itemId:'" + id + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			var flash = $('#flashContent')[0];
			if (data.d) {
				var tbody = $("#cartItem-" + data.d.ItemId).parent();

				$("#cartItem-" + data.d.ItemId).remove();
				$("#cartPrice").html(data.d.TotalPrice);

				tbody.children().each(function(n) { if (n % 2 == 1) $(this).addClass("hl"); else $(this).removeClass("hl"); });

				if (data.d.EventId == fB.eventId)
					fB.removeTicketCallback({ SeatId: data.d.SeatId }, data.d.TotalPrice, flash);
			}
		},
		error: function(a, b, c) {
			alert(a.responseText);
		}
	});
}

fB.removeTicketSeatless = function(discountId) {
	$.ajax({
		type: "POST",
		url: appWWWRoot + "TicketService.asmx/RemoveTicketSeatless",
		data: "{discountId:'" + discountId + "',eventId:'" + fB.eventId + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			var flash = $('#flashContent')[0];
			if (data.d)
				fB.removeTicketCallback(data.d.AddedItems[0], data.d.TotalPrice, flash);
		},
		error: function(a) {
			alert(a.responseText);
		}
	});
}

// AJAX odebrání vstupenky nebo abonentky
fB.removeTicket = function(seatId, eventId, isSerial) {
	if (eventId == null)
		eventId = fB.eventId;
	var serialSuccesionString = (isSerial ? "True" : "False");
	$.ajax({
		type: "POST",
		url: appWWWRoot + "TicketService.asmx/RemoveTicket",
		data: "{seatId:'" + seatId + "',eventId:'" + eventId + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			var flash = $('#flashContent')[0];
			if (data.d)
				fB.removeTicketCallback(data.d.AddedItems[0], data.d.TotalPrice, flash);
		},
		error: function(a) {
			alert(a.responseText);
		}
	});
}

// AJAX callback po odebrání vstupenky nebo abonentky
fB.removeTicketCallback = function(item, totalPrice, flash) {
	if (flash && flash.confirmSeatReservation) {
		flash.confirmSeatReservation(item.SeatId, 3);
	}
	else {
		if (item.SeatTitle == '') {
			var counter = $('#ticketCount-' + item.FriendlyDiscountId);
			if (counter.length > 0)
				counter.html(parseInt(counter.html()) - 1);
		}
	}
}

/* Catalog */
fB.dropdownExpand = function(obj) {
	var o = $(obj).children('.packedItems');
	if (o.css('display') != 'none') {
		o.fadeOut(300, function() {
			$(obj).css('position', 'static');
			if (inCMS.browser.IE6 || inCMS.browser.IE7) {
				$('#panelResults').css('position', 'relative');
			}
		});
	}
	else {
		$(obj).css('position', 'relative');
		if (inCMS.browser.IE6 || inCMS.browser.IE7) {
			$('#panelResults').css('position', 'static');
		}
		o.fadeIn(300);
	}
}

fB.changeDiscount = function(itemId, discountId) {
	$.ajax({
		type: "POST",
		url: appWWWRoot + "TicketService.asmx/ChangeCartItemDiscount",
		data: "{itemId:'" + itemId + "', discountId:'" + discountId + "'}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			$("#cartItemDiscount-" + data.d.ItemId).html(data.d.DiscountName);
			$("#cartItemPrice-" + data.d.ItemId).html(data.d.Price);
			$("#cartPrice").html(data.d.TotalPrice);
		},
		error: function(a) {
			alert(a.responseText);
		}
	});
}

fB.eventOver = function(obj) {
	var o = $(obj);
	var index = $.inArray(obj, $('.event').get());
	o.data('mouseOver', true);
	setTimeout('fB.eventOverTimeout(' + index + ')', 150);
}
fB.eventOverTimeout = function(n) {
	var o = $('.event').eq(n);
	if (o.data('mouseOver')) {
		var info = o.find('.eventInfo');
		info.html('<p class="infoName">' + o.find('h3 a').html() + '</p><p class="infoVenue">' + o.find('.venue').html() + '</p><p class="infoStart">' + o.find('.time').html() + '</p><div class="infoDesc">' + o.find('.desc').html() + '</div><div class="top"></div><div class="bottom"></div>');
		if (inCMS.browser.IE6) DD_belatedPNG.fix('.eventInfo .top, .eventInfo .bottom');
		var top = o.position().top + 75;
		if (top + info.outerHeight() + 7 > o.offsetParent().outerHeight()) top = o.position().top - 7 - info.outerHeight();
		var left = o.position().left + 98;
		if (left + info.outerWidth() > o.offsetParent().outerWidth()) left = o.position().left - info.outerWidth() + o.outerWidth() - 98;
		info.css({ 'top': top + 'px', 'left': left + 'px' })
		.fadeIn(300);
	}
}
fB.eventOut = function(obj) {
	var o = $(obj);
	var index = $.inArray(obj, $('.event').get());
	o.data('mouseOver', false);
	setTimeout('fB.eventOutTimeout(' + index + ')', 150);
}
fB.eventOutTimeout = function(n) {
	var o = $('.event').eq(n);
	if (!o.data('mouseOver')) o.find('.eventInfo').fadeOut(300);
}

/* Detail */
fB.backFromDetail = function() {
	location.hash = fB.leftContent.catalogHash;
}

fB.selectedDiscount = 0;
fB.discountSelect = function(n) {
	$('#discountSelect .rB').removeClass('rB-selected').eq(n).addClass('rB-selected').find('input').click();
	$('#tblDiscountInfo tbody tr').removeClass('selected').eq(n).addClass('selected');
	fB.selectedDiscount = n;
}

fB.showLimitInfo = function() {
	$('#limitInfo').html(fB.langResources.limitInfo[fB.langIndex] + '<span class="borderTop"></span><span class="borderBottom"></span>')
.css({ 'top': (((fB.winHeight - 50) / 2) + (inCMS.browser.IE6 ? inCMS.pagePosition().y : 0)) + 'px', 'left': ((fB.winWidth - 309) / 2) + 'px' })
.fadeIn(750, function() { setTimeout('$("#limitInfo").fadeOut(750);', 5000); });
	if (inCMS.browser.IE6) DD_belatedPNG.fix('#limitInfo .borderTop, #limitInfo .borderBottom');
}

fB.showCartAddedInfo = function() {
	var box = $('#cartInfo');
	if (typeof box.html() == undefined || box.html() == '' || box.html() == null) {
		box.html('<img src="' + appWWWRoot + 'Design/Detail/CartInfoAdded_' + fB.langCode[fB.langIndex] + '.png" alt="" />')
	.click(function() { fB.tabClick(2); });
	}
	if (inCMS.browser.IE6) DD_belatedPNG.fix('#cartInfo img');
	box.css('top', (((fB.winHeight - 277) / 2) + (inCMS.browser.IE6 ? inCMS.pagePosition().y : 0)) + 'px')
	//	.data('started', true)
.fadeIn(750, function() { setTimeout('$("#cartInfo").fadeOut(750);', 3000); });
}

/* Cart */
fB.backFromCart = function() {
	$(window).history('back');
}

fB.validateRequiredInner = function(name, tbxName, thName, rvName) {
	if ($('#' + tbxName).val() == '') {
		$('#' + thName).addClass('error');
		$('#' + rvName).removeClass('error-hidden');
		return false;
	}
	else {
		$('#' + thName).removeClass('error');
		$('#' + rvName).addClass('error-hidden');
		setCookie('cart' + name, $('#' + tbxName).val());

		return true;
	}
}

fB.validateRequired = function(name) {
	return fB.validateRequiredInner(name, 'tbx' + name, 'th' + name, 'rv' + name);
}

fB.validateMail = function() {
	var m1 = $('#tbxPersonMail').val();
	var m2 = $('#tbxPersonMailConfirmation').val();

	$('#thPersonMail').removeClass('error');
	$('#mvPersonMail').addClass('error-collapse');
	$('#thPersonMailConfirmation').removeClass('error');
	$('#cvPersonMailConfirmation').addClass('error-collapse');

	if (!fB.validateRequired('PersonMail'))
		return false;

	var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!m1.match(emailRegEx)) {
		$('#thPersonMail').addClass('error');
		$('#mvPersonMail').removeClass('error-collapse');

		return false;
	}

	if (m1 == m2) {
		setCookie('cartMail', m1);

		return true;
	}
	else {
		$('#thPersonMail').addClass('error');
		$('#thPersonMailConfirmation').addClass('error');
		$('#cvPersonMailConfirmation').removeClass('error-collapse');

		return false;
	}
}

toJSON = function(a) {
	var ret = '{';
	for (var i in a) {
		ret += (ret.length > 1 ? ', ' : '') + "'" + i + "':'" + a[i] + "'";
	}
	return ret + '}';
}

var today = new Date();
var expiry = new Date(today.getTime() + 3600 * 1000);

function getCookie(name) {
	var re = new RegExp(name + "=([^;]+)");
	var value = re.exec(document.cookie);
	return (value != null) ? unescape(value[1]) : '';
}

function setCookie(name, value) {
	document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
}

fB.validateCartPerson = function() {
	var err = true;

	err &= fB.validateRequired('Name');
	err &= fB.validateRequired('Surname');
	err &= fB.validateRequired('PersonMail');
	err &= fB.validateRequiredInner('PersonCaptcha', 'recaptcha_response_field', 'thPersonCaptcha', 'rvPersonCaptcha');
	err &= fB.validateMail();

	return err;
}

fB.reserveTicketsCallback = function(data) {
	// redirect to reservation completed page
	location.hash = '#ordersummary/' + data.d.OrderId + '/';
}

fB.prepareTicketsCallback = function(data) {
	var form = document.createElement("form");
	form.action = data.d.PostUrl;
	form.method = "POST";
	document.body.appendChild(form);

	// add fields
	for (var item in data.d.FormValues) {
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = item;
		input.value = data.d.FormValues[item];

		form.appendChild(input);
	}

	form.submit();
}

fB.reserveTickets = function(cardPayment) {
	$('#btnReserveTickets').show();
	$('#reservationPending').hide();
	$('#reservationError').hide();
	$('#cvPersonCaptcha').addClass('error-collapse');

	if (!fB.validateCartPerson())
		return false;

	var input = new Object();

	input.name = $('#tbxName').val();
	input.surname = $('#tbxSurname').val();
	input.email = $('#tbxPersonMail').val();
	input.phone = $('#tbxPersonPhone').val();
	input.challenge = $('#recaptcha_challenge_field').val();
	input.validationCode = $('#recaptcha_response_field').val();

	$('#reservationPending').show();
	$('#btnReserveTickets').hide();
	$('#btnPrepareTickets').hide();

	$.ajax({
		type: "POST",
		url: appWWWRoot + (cardPayment ? "TicketService.asmx/PrepareTickets" : "TicketService.asmx/ReserveTickets"),
		data: toJSON(input),
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			if (data.d.Status == 0) {
				// reservation successful

				if (cardPayment)
					fB.prepareTicketsCallback(data);
				else
					fB.reserveTicketsCallback(data);
			}
			else if (data.d.Status == 2) {
				// no items
				$('#reservationPending').hide();
				$('#reservationError').show();
			}
			else if (data.d.Status == 3) {
				// failed captcha
				$('#thPersonCaptcha').addClass('error');
				$('#cvPersonCaptcha').removeClass('error-collapse');

				$('#reservationPending').hide();
				$('#btnReserveTickets').show();
				$('#btnPrepareTickets').show();

				Recaptcha.reload();
			}
			else {
				// failed to book some items
				for (var i in data.d.FailedItems) {
					$("#cartItemError-" + data.d.FailedItems[i].Id).show();
				}

				$('#reservationPending').hide();
				$('#reservationError').show();
				$('#btnReserveTickets').show();
				$('#btnPrepareTickets').show();
			}
		},
		error: function(a) {
			alert(a.responseText);
		}
	});
}