var webLang = "";
var spacerSrc = "/img/u/spacer.gif";

if ($.browser.msie && ($.browser.version.substr(0,3)=="6.0" || $.browser.version.substr(0,2)=="5.")) {
	DD_belatedPNG.fix('.png-fix, .hp #p-top .logo img, .map-box');
}

/**
 * ie bg blink - prevent
 */
if(($.browser.msie && $.browser.version < 7)) {
	eval("try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}");
}

/**
 * objekt pro lepsi spravu stringu
 */
function StringBuffer() {
	this.buffer = "";
	this.append = function(str) { this.buffer += str; return this; };
	this.getString = function() { return this.buffer; };
	this.reset = function() { this.buffer=""; };
}

/**
 * tab system
 * @param activeTab
 */
$.prototype.makeTabs = function(activeTab) {
	var tabs = $("#" + this.attr("id") + " li a");
	if(tabs.length == 0) return;
	for (var ti=0; ti < tabs.length; ti++)
	{
		$("*[class*='tabs-" + $(tabs[ti]).attr("href").substring(1) + "']").hide();
		$(tabs[ti]).bind("click", function() {
			for (var tiin=0; tiin < tabs.length; tiin++)
			{
				$(tabs[tiin]).parents('li').removeClass("active");
				$("*[class*='tabs-" + $(tabs[tiin]).attr("href").substring(1) + "']").hide();
			}
			$(this).parents('li').addClass("active");
			$("*[class*='tabs-" + $(this).attr("href").substring(1) + "']").show();
			return false;
		});
	}
	if (typeof(activeTab) == "undefined" || isNaN(activeTab) || activeTab < 1 || activeTab > tabs.length) {
		activeTab = 0;
	} else {
		activeTab--;
	}
	$("#" + this.attr("id") + " li:eq("+activeTab+")").addClass("active");
	$("*[class*='tabs-" + $(tabs[activeTab]).attr("href").substring(1) + "']").show();
};


/**
 * Bottom buttons specific
 * ze zadaného seznamu buttonů vybere ten, který obsahuje aktuální url. Vrací index daného buttonu (0 - (n-1))
 * @param id - id daného seznamu buttonů
 */
function getButtonByLocation(id) {
	var localUrl = window.location.href;
	var retValue = -1;

	$("#"+id+" li a").each(function() {
		if (localUrl.indexOf($(this).attr("href")) > -1) {
			retValue = $("#"+id+" li a").index(this);
		}
	});
	return retValue;
}

/**
 * fade toggle - prepinani fade
 * @param speed
 * @param easing
 * @param callback
 */
jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback);
};

/**
 * aktivace dhtml selectu - skryvani a odkryvani seznamu polozek na klik, skryvani ostatnich selectu
 */
function initDhtmlSelects() {
	$("select.dhtml").each(function() {

		var optCount = 0;
		var selectValues = new Array();
		var selectTitles = new Array();

		// vygenerovani name a id selectu (pokud nejsou zadany)
		var selectIndex = $("select.dhtml").index(this);
		var selectId = $(this).attr("id") || "fg-dhtml-select-"+selectIndex;
		var selectName = $(this).attr("name") || "fg-dhtml-select-"+selectIndex;

		// temp prejmenovani a preideckovani selectu, kvuli input hidden nize
		$(this).attr("id", "sourceselect-"+selectIndex+"-" +  $(this).attr("id"));
		$(this).attr("name", "sourceselect-"+selectIndex+"-" +  $(this).attr("name"));

		// nacteni dat z options
		$("option", this).each(function() {
			selectValues[optCount] = $(this).attr("value");
			selectTitles[optCount] = $(this).text();
			optCount++;
		});

		// ulozeni options dat do objektu selectu
		$(this).data("values", selectValues);
		$(this).data("titles", selectTitles);

		// vytvoreni hidden inputu misto selectu
		$(this).after('<input type="hidden" name="'+selectName+'" id="'+selectId+'" value="" />');

		// vypsani noveho dhtml selectu
		var newDhtmlSelectDivTempId = "temp-"+selectId;
		var dhtmlSelectString = new StringBuffer();
		dhtmlSelectString.append('<div class="dhtml-select" id="'+newDhtmlSelectDivTempId+'">');
		dhtmlSelectString.append('	<a rel="'+selectId+'" href="#">'+selectTitles[0]+'</a>');
		if (selectValues.length > 0) {
			dhtmlSelectString.append('<ul>');
		}

		//onclickevent-gmapsSetSortimentId
		var selectClass = $(this).attr("class");
		var itemOnclickEvent = "";
		if (selectClass.indexOf("onclickevent-") > 0) {
			itemOnclickEvent = selectClass.substring(selectClass.indexOf("onclickevent-")+13);
		}

		for(i=0;i<selectValues.length; i++) {
			dhtmlSelectString.append('<li class="value'+selectValues[i]+'"><a rel="'+selectId+'" href="#" onclick="dhtmlSelectSetValue(\''+selectValues[i]+'\', this, \''+itemOnclickEvent+'\'); return false">'+selectTitles[i]+'</a></li>');
		}
		if (selectValues.length > 0) {
			dhtmlSelectString.append('</ul>');
		}
		dhtmlSelectString.append('</div>');

		$(this).after(dhtmlSelectString.getString());

		// schovani ul
		$("#"+newDhtmlSelectDivTempId+">ul").hide();
		
		//bind prvniho odkazu noveho dhtml selectu
		$("#"+newDhtmlSelectDivTempId+">a:first").bind("click", function(event) {
			$("#"+newDhtmlSelectDivTempId+">ul").toggle();
			event.preventDefault();
		});
	}).remove();
}

function dhtmlSelectSetValue(value, sender, optionsEvent) {

	// replace prvniho prvku (spoustece combo boxu) za aktualne kliknuty prvek
	$(">a:first", $(sender).parents("div:first")).replaceWith($(sender).parents("li").html());
	//spusteni custom funkce
	if (optionsEvent && optionsEvent != "") {
		if (optionsEvent == 'gmapsSetSortimentId') {
			BERNARD_select_sortiment(value, gm);
		}
	}

	// odstraneni default akce vybraneho prvku... a nahradi se za akci, ktera spusti combo box
	$(">a:first", $(sender).parents("div:first")).attr("onclick","").unbind("click").bind("click", function(event) {
		$("ul", $(sender).parents("div:first")).toggle();
		event.preventDefault();
	});

	// schovani rozbaleneho combo boxu
	$(">ul:first", $(sender).parents("div:first")).hide();

	// replace hodnoty v hidden inputu, ktery nahazuje select box
	var targetInput = $(sender).attr("rel");
	$("#"+targetInput).val(value);
}

/**
 * vypsani pageflipperu + odkazu PDF ke stazeni
 */
function writePagefliperMagazine(obj) {
	var $c = $("#container-magazine");
	var $l = $(obj);

	var sb = new StringBuffer();
	sb.append('<div class="clr">');
	sb.append('	<h2 class="fl">'+$l.text()+'</h2>');
			/*sb.append('	<ul class="file-list fr"');
			sb.append('		<li class="pdf"><a href="'+$l.attr("href")+'" target="_blank">'+locale["download"]+'<em>'+$l.attr("title")+'</em></a></li>');
			sb.append('	</ul');*/
	sb.append('</div>');
	sb.append('<div id="cPageFliper"></div>');
	$c.html(sb.getString());
	var settingsUrl = $l.attr("rel");

	swfobject.embedSWF("/swf/u/pagefliper/pagefliper.swf?v01", "cPageFliper", "936", "622", "10.0.12.0", null, { settingsPath: settingsUrl, preloaderBackgroundColor: "0x2f241b"}, { wmode: "opaque", allowScriptAccess: "sameDomain", allowfullscreen: "true", base: "/swf/u/pagefliper/", align: "middle", salign: "lt", bgcolor: "#FFFFFF", menu: "false", loop: "false", type: "application/x-shockwave-flash" });
}

/**
 * změna velikosti iframe
 * @param h - výška
 * @param f - id iframe
 */
function setIframeHeight(h,f) {
    $("#"+f).attr({
           height: h
     });
}

/**
 * funkce pro načítání parametru z url (parse querystring)
 */

function getParameter(name) {
	if(typeof document.parameters == "undefined") {
		setupParameters();
	}
	return document.parameters[name];
}
function setupParameters() {
	var parameters = new Object();
	if(window.location.search) {
		var paramArray = window.location.search.substr(1).split('&');
		var length = paramArray.length;
		for (var index = 0;index <length; index++ ) {
			var param = paramArray[index].split('=');
			var name = param[0];
			var value =
			typeof param[1] == "string"
				? decodeURIComponent(param[1].replace(/\+/g, ' '))
				: null;
			parameters[name] = value;
		}
	}
	document.parameters = parameters;
}


/**
 *  EPOHLEDNICE
 */
var activeCard = "card-back";
var hiddenCard = "card-front";
var cardProperties = new Array();
cardProperties['card-back-width'] = '516px';
cardProperties['card-front-width'] = '548px';
var ecardTurnClicked = false;

function turnEcard() {
	if (ecardTurnClicked) return;
	ecardTurnClicked = true;
	$(".cards .card *").hide();
	$("."+hiddenCard).css({"width" : "0px", "margin-left": "258px" });
	$("."+activeCard).animate({
		width: '0px',
		marginLeft: '+=258',
		opacity: 0
	}, 300, function() {
		$("."+activeCard).hide();
		$("."+hiddenCard).animate({
			width: cardProperties[hiddenCard+"-width"],
			marginLeft: '0',
			opacity: 1
		}, 500, function() {
			$("."+hiddenCard+" *").show();
			var tmp = activeCard;
			activeCard = hiddenCard;
			hiddenCard = tmp;
			ecardTurnClicked = false;
		});

	});
}

/**
 *  oceneni - zkraceni seznamu
 */
function shortenList(id) {
	$t = $("#"+id);
	if ($("li", $t).size() < 4) return false;
	$t.after('<p class="shortened-list-bottom"><a href="#" class="btn-show-awards" onclick="toggleShortenedListItems(\''+id+'\', this); return false">toggle</a></p>');
	$("li:gt(2)", $t).hide();
}

function toggleShortenedListItems(id, sender) {
	$("#"+id+" li:gt(2)").toggle();
	$(sender).toggleClass("btn-hide-awards");
}

$.fn.setLiRowHeight = function(columnCount) {
	var actHeight = 0;
	var liCount = $(">li", $(this)).size();
	var linesCount = Math.floor(liCount/columnCount);

	for (i=0; i < linesCount; i++) {
		actHeight = 0;

		for (j = i*columnCount; j < i*columnCount+columnCount; j++) {
			actHeight = ($(">li:eq("+j+")", $(this)).height() > actHeight) ? $(">li:eq("+j+")",  $(this)).height() : actHeight;
		}
		$(">li", $(this)).filter(function(index){
			return index >= i*columnCount && index < i*columnCount+columnCount; 
		}).css("height",actHeight);
	}
};

/**
 * * vypsani FLV playeru
 * @param videoContainer 	- div do kterého vložíme player
 * @param videoFile 		- video flv
 * @param imageFile			- img thumb
 * @param w					- šířka videa
 * @param h					- výška videa
 */

function writeFlashPlayer(videoContainer, videoFile, imageFile, w, h, autoplay) {
	var autostart = autoplay | false;
	var flashvars = {
		file: videoFile,
		image: imageFile,
		backcolor: "3c322a",
		frontcolor: "e9bf57",
		lightcolor: "e9bf57",
		screencolor: "000000",
		icons: "false",
		autostart: autostart
	};
	var params = {
		wmode: "transparent",
		allowscriptaccess: "always",
		allowfullscreen: "true"
	};
	var attributes = {
	};

	swfobject.embedSWF("/swf/u/jw-player-v53.swf", videoContainer, w, h, "8.0.34", null, flashvars, params, attributes);
}

function jwPlayerEvents(e) {
    jwplayer(e.ref).onComplete(function() { alert("That's all, folks"); });
}

function writeFlashPlayerMP3(playerContainer, audioFile,  w, h, autostart) {
	var flashvars = {
		file: audioFile,
		backcolor: "3c322a",
		frontcolor: "e9bf57",
		lightcolor: "e9bf57",
		screencolor: "000000",
		icons: "false",
		autostart: "true"
	};
	var params = {
		allowscriptaccess: "always"
	};
	var attributes = {
	};

	swfobject.embedSWF("/swf/u/jw-player-v53.swf", playerContainer, w, h, "8.0.34", null, flashvars, params, attributes);
}

function activateMP3Player(sndfile, sender) {
	$("#invisibleAudioPlayer").remove();
	$(".btn-play").removeClass("btn-stop");
	var state = $(sender).data("state");
	if (state == null) {
		state = true;
	}
	if (state) {
		$("body").append('<div id="invisibleAudioPlayer"></div>');
		writeFlashPlayerMP3("invisibleAudioPlayer", sndfile, 1, 1, true);
		$(sender).addClass("btn-stop");
	}
	$(sender).data("state", !state);
}


/**
 *
 * @param id
 * @param mapWidth
 * @param mapHeight
 * @param bgrImg - pozadi velkeho obrazku over verze mapy
 */

/*
* update 27.5.2011
*
//        .==.        .==.
//       //`^\\      //^`\\
//      // ^ ^\(\__/)/^ ^^\\
//     //^ ^^ ^/6  6\ ^^ ^ \\
//    //^ ^^ ^/( .. )\^ ^ ^ \\
//   // ^^ ^/\| v""v |/\^ ^ ^\\     
//  // ^^/\/ /  `~~`  \ \/\^ ^\\
//  -----------------------------
/// HERE BE DRAGONS >> FHL for more info
*/

function ImageMap(id, mapWidth, mapHeight, bgrImg, action) {
	this.id = id;
	this.map = $("img[usemap$='"+id+"']");
	this.mapH = mapHeight;
	this.mapW = mapWidth;
	this.action = action;

	this.overId = "IM-"+id;
	this.mapOver = null;
	this.activeArea = 0;
	this.activeAreaByBubble = 0;

	// bubbles
	this.bubbles = false;
	this.bubblesType = "";
	this.bubblesData = new Array();
	this.bubblesLayer = '<div class="map-bubble clr"></div>';
	this.actualBubbleOpened = "";
	this.bubbleTimeout = null;

	this.init = function() {
		this.map.after('<img src="' + spacerSrc + '" class="map-over" id="'+this.overId+'" style="width: '+this.mapW+'px; height: '+this.mapH+'px" alt="" usemap="#'+this.id+'" />');
		this.mapOver = $("#"+this.overId);
		this.mapOver.css("background-image", "url('"+bgrImg+"')");
		var mapAreas = $("map[name='"+this.id+"'] area");

		$t = this;

		for (var i=0; i< mapAreas.length; i++) {
			$(mapAreas[i]).attr("rel", "area"+(i+1));
			/***/
			$(mapAreas[i]).data("title", $(mapAreas[i]).attr("title"));
			$(mapAreas[i]).data("alt", $(mapAreas[i]).attr("alt"));
			/***/
			$(mapAreas[i]).attr("title", "");
			mapAreas[i].onmouseover = function(e) {
				var areaCnt = $(this).attr("rel").substring(4);
				$t.toggleArea(areaCnt);

			};
			mapAreas[i].onmouseout = function() {
				$t.toggleArea($t.getActiveArea());
			};

			if (typeof(this.action) != "undefined") {
				$(mapAreas[i]).bind("click", function(event) {
					$t.toggleBlock(this, this);
					event.preventDefault();
				});
			}
		}
		if(($.browser.msie && $.browser.version >= 7) || !($.browser.msie)) {
			this.checkBubbles();
			if (this.bubbles) {
				this.bindBubbles();
			}
		}

	};

	this.toggleBlock = function(o, activeArea) {
		if (this.action.indexOf("toggleBlockById") > -1) {
			var blockType = this.action.substr(action.lastIndexOf(" ")+1);
			var areaId = $(o).attr("href");
			areaId = areaId.substring(areaId.indexOf("#"), areaId.length);
			$("."+blockType).hide();
			$(areaId+" tr").removeClass("active");
			this.activeArea = String($(activeArea).attr("rel")).substring(4);
			this.toggleArea(this.getActiveArea());
			$(areaId).show();
		}
	};

	this.toggleArea = function(area) {
		var posY = -1*(parseInt(area)*this.mapH);
		this.mapOver.css("background-position", "0px "+posY+"px");
	};

	this.checkBubbles = function() {
		$t = this;
		this.bubbles = $("map[name='"+this.id+"']").hasClass("map-with-bubbles");
		var bsTypeClass = String($("map[name='"+this.id+"']").attr("class"));
		if (this.bubbles && bsTypeClass.indexOf("map-with-bubbles-") > 0) {
			this.bubblesType = bsTypeClass.substring(bsTypeClass.indexOf("map-with-bubbles-"), bsTypeClass.length).replace("map-with-bubbles-","");
			this.map.before(this.bubblesLayer);
		}

		$(".map-bubble .close").live("click", function() {
			$(this).parent().hide();
		});

		$(".map-bubble li a").live("click", function(e) {
			$t.toggleBlock(this, $("#"+$t.id+" area[href='"+$(this).attr("href")+"']"));
			$("#"+$(this).attr("rel")+" tr").removeClass("active");
			$("#"+$(this).attr("rel")+" tr[data-"+$t.bubblesType+"='"+$(this).text()+"']").addClass("active");
			e.preventDefault();
		});
		$(".map-box").hover(function() {

			},
			function() {
				$t.bubbleTimeout = setTimeout(function() {
					$(".map-bubble").hide();
					$t.actualBubbleOpened = "";
					$t.activeAreaByBubble = 0;
					$t.toggleArea($t.getActiveArea());
				}, 1000);
			}
		);
	};

	this.bindBubbles = function() {
		$t = this;
		var mapAreas = $("map[name='"+this.id+"'] area");
		// projit arey
		for (var i=0; i< mapAreas.length; i++) {
			// bind overu na arey
			$(mapAreas[i]).bind("mouseover", function(e) {
				var bubbleHref = $(this).attr("href");
				if ($t.actualBubbleOpened == bubbleHref) return false;
				var bubbleTitle = $(this).attr("alt");
				var sb = new StringBuffer();
				var items = new Array();
				// zapamatovat radky a jejich hodnoty
				$("tr[data-"+$t.bubblesType+"]", $(bubbleHref)).each(function() {
					items.push($(this).attr("data-"+$t.bubblesType));
				});

				// vypsat
				sb.append('<h3>').append(bubbleTitle).append('</h3>');
				//sb.append('<div class="close"></div>');
				var colDelimiter = 1;
				var secondColDelimiter = 1;
				if (items.length) {
					sb.append('<ul>');
					colDelimiter = Math.ceil(items.length / 3);
					secondColDelimiter = 2*colDelimiter;
					if (items.length%3 == 1) {
						secondColDelimiter--;
					}
				}
				//alert(colDelimiter+"\n"+secondColDelimiter);

				for (i=0; i<items.length; i++) {
					if (i == (colDelimiter) || i == (secondColDelimiter)) {
						sb.append('</ul><ul>');
					}
					sb.append('<li><a href="').append(bubbleHref).append('" rel="').append(bubbleHref.substring(1)).append('">').append(items[i]).append('</a></li>');
				}

				if (items.length) {
					sb.append('</ul>');
				}

				var bubbleTop, bubbleLeft;
				/* ***** */
				var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
				/* ***** */

				if(($.browser.msie && $.browser.version >= 7) && window.event) {
					bubbleTop = parseInt(window.event.clientY+iebody.scrollTop) - parseInt($(".map-box").offset().top) -15;
					bubbleLeft = parseInt(window.event.clientX+iebody.scrollLeft) - parseInt($(".map-box").offset().left) -15;
				} else {
					bubbleTop = parseInt(e.pageY) - parseInt($(".map-box").offset().top) -15;
					bubbleLeft = parseInt(e.pageX) - parseInt($(".map-box").offset().left) -15;
				}
				$t.activeAreaByBubble = String($("#"+$t.id+" area[href='"+bubbleHref+"']").attr("rel")).substring(4);
				$(".map-bubble").empty().append(sb.getString()).css({"top": bubbleTop+"px", "left" : bubbleLeft+"px"}).show();
				$t.actualBubbleOpened = bubbleHref; 
			});
		};
	};

	this.getActiveArea = function() {
		return this.activeAreaByBubble == 0 ? this.activeArea : this.activeAreaByBubble;
	};

	this.init();
}

/**
 * vertikalni slider oceneni
 * @param cl - trida
 */
function toggleAwards(cl) {
	$(cl+"-container:gt(0)").hide();
	$(cl+":first").addClass("toggle-active");

	$(cl).each(function() {
		$("h3", $(this)).append('<span class="toggle-awards-total-count">'+locale["awards-count"] + ':&nbsp;'+$("table tbody tr", $(this)).size()+'</span>');

		$("h3", $(this)).bind("click", function() {
			if ($(this).parents("div.toggle:first").hasClass("toggle-active")) { return false; }

			$(".toggle").removeClass("toggle-active");
			$(this).parents("div.toggle:first").addClass("toggle-active");
			var $tCont = $(".toggle-container", $(this).parents("div.toggle:first"));
			if ($.browser.msie) {
				$(".toggle-container").hide();
				$tCont.show();
			} else {
				$(".toggle-container").slideUp();
				$tCont.slideDown();
			}
			$tCont.slideDown();
		}).append('<span></span>').hover(function() {
			$(this).parents("div.toggle:first").addClass("toggle-active-hover");
		}, function() {
			$(this).parents("div.toggle:first").removeClass("toggle-active-hover");
		});
	});
};

function setSliderSortimentActive(id) {
	$(".slider-sortiment li a[href*='/"+id+".shtml']").parents("li:first").addClass("active");
}

function fixTable() {
	$("table td").each(function() {
		if ($.trim($(this).html()) == "") {
			$(this).html("&nbsp;");
		}
	});
}
function fixTableAwards() {
	var zIndex = 50 + $(".table-oceneni table td div p").size(); 
	$(".table-oceneni table td div p").each(function() {
		$(this).parents("div:first").css("z-index", zIndex);
		zIndex--;
	});
};

/**
 *
 *
 *
 *  DOCUMENT READY !!!
 *
 *
 *
 */

$(document).ready(function() {
	// navigation settings
	$("ul#p-navi>li").mouseover(function(){
		$(this).addClass("hover");
	}).mouseout(function(){
		$(this).removeClass("hover");
	});

	// dhtml selects
	initDhtmlSelects();

	// sortiment - animace overu
	if ($.browser.msie && ($.browser.version.substr(0,3)=="6.0" || $.browser.version.substr(0,2)=="5.")) {
		// alert("get yourself a better browser");
	} else {
		$(".slider-sortiment a").hover(function(){
			$("img", this).animate({
				height: '-=10',
				width: '-=6',
				top: '+=5',
				left: '+=3'
			}, 50);
		}, function(){
			$("img", this).animate({
				height: '+=10',
				width: '+=6',
				top: '-=5',
				left: '-=3'
			}, 50);
		});
	}

	// rozeskoky, automaticke spocitani sirky
	$("div.p-index ul").each(function() {
		var $t = $(this);
		var totalWidth = 0;
		$("li", $t).each(function() {
			totalWidth += $(this).width();
		});
		$t.css("width", totalWidth+"px");
	});

	// overflow hidden na body, pokud je sirka obrazovky vyssi nez 1024
	if($(window).width() >= 966) {
		$("body").addClass("oxh");
	}
	$(window).bind("resize", function() {
		if ($(this).width() >= 966) {
			$("body").addClass("oxh");
		} else {
			$("body").removeClass("oxh");
		}
	});

	// highslide zoom button
	$(".gallery a.highslide").append('<span class="zoom"></span>');

	// ie 7 a 6 fix
	if ($.browser.msie && ($.browser.version.substr(0,2)=="7." || $.browser.version.substr(0,2)=="6." || $.browser.version.substr(0,2)=="5.")) {
		fixTableAwards();
		fixTable();
	}
});

/* intro liveconnect */
function doPassVar(args){ window.document.introFlash.SetVariable("start_obj.co", args); }
function doSkipVar(args){ window.document.introFlash.SetVariable("start_obj.skp", args); }

function startIntro() {
	$(".logo, .step-1").hide();
	$("#btn-skip-intro").show();
	doPassVar('true');
}
function skipIntro() {
	$("#btn-skip-intro").hide();
	doSkipVar('true');
}

function goHomePage() {
	window.location.href = hp;
}
