// IE - fix blikajicich backgroundu
if(($.browser.msie && $.browser.version < 7)) {
	eval("try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}");
}

var countPlayer = 5; //počet obrázků, které můžou být na pozadí
var player = 0; //náhodné číslo, číslo obrázku které se použije na pozadí
var contentWidth = 994; // šířka obsahu
var imageBgWidth = 373; // šírka obrázku
var skyscraperWidth = 160; // šírka obrázku
var visibleimageBgWidth = 150; // minimální přípustní viditelná šířka pozadí
var imageBgHeight = 775; // šírka obrázku
var userboxHeight = 33; // výška user-boxu
var leaderboardHeight = 0; // výška leaderboardu
var bgPositionX = 0; // X souřadnice obrázku na pozadí
var bgPositionY = 0; // Y souřadnice obrázku na pozadí
var browserWidth = 0; // šířka použitelné plochy prohlížeče
var browserHeight = 0; // výška použitelné plochy prohlížeče
var topHeight = 0; //velikost leaderboardu a user-boxu

$(document).ready(function() {
	leaderboardHeight = $("#banner-leaderboard").height()+30;
	topHeight = leaderboardHeight+userboxHeight;

	if(!($.browser.msie && $.browser.version < 7)) {
		if (!$("#banner-skyscraper").height()){
			player = Math.ceil(Math.random()*countPlayer);
			$("body:not('#external')").prepend('<div id="bg-player"></div>');
			//$("body").attr("onresize","playerBackground();");
			$(window).resize(function(){
				playerBackground();
				skyscraper();
			})
			playerBackground();
			skyscraper();
		}
	}

	if(!$("#banner-leaderboard").height()){
		$("body").css("background-position","50% -230px");
		//$("#p-bgr").css("background-position","50% -160px");
		$("#banner-leaderboard").css("margin","0").css("padding","0");
		$("#p-root").css("padding-top","222px");
		$("#p-top").css("height","222px");
		$("#banner-skyscraper").css("top","222px");
		$("#logo").css("top","54px");
	}
	if($("#banner-leaderboard").height()==200){
		$("body").css("background-position","50% 0");
		$("#p-root").css("padding-top","452px");
		$("#p-top").css("height","452px");
		$("#banner-skyscraper").css("top","452px");
		$("#logo").css("top","284px");
	}

	$(".newsFeed").css("width", function() {
		var ln = 0;
		$("li", $(this)).each(function() {
			ln += $(this).width();
			ln +=51;
		});
		return ln;
	});

	$("#newsFeed").marquee("newsFeedContainer").mouseover(function(){
		$(this).trigger('stop');
	}).mouseout(function(){
		$(this).trigger('start');
	}).mousemove(function(event){
		if ($(this).data('drag') == true) {
			this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
		}
	}).mousedown(function(event){
		$(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
	}).mouseup(function(){
		$(this).data('drag', false);
	});
	$("#news-slider").append('<div class="side-vanish-left"></div><div class="side-vanish-right"></div>');

	$('#p-top input.text').fitt({
		classBlur: 'text',
		classFocus: 'text'
	});

	if(!($.browser.msie && $.browser.version < 7)) {
		$("#p-mid .hs-expand:not('.no-zoom')").append('<span class="zoom"></span>');
	}

	$(".stripe li:odd").addClass('zebra');

	$("table:not('.no-stripe')").each(function(){
		$("tbody tr:odd",this).addClass("zebra");
	});

	// naplnění hodnot po najetí na novinku
	$("#hp .news li").bind("mouseover", function() {
		$("#hp .news li").removeClass("hover");
		var actualItem = $("#hp .news li").index(this)+1;
		$("#hp .news li:eq("+(actualItem-1)+")").addClass("hover");
		$("#hp .news .motive").attr("src", $("a", this).attr("rel"));
		$("#hp .news div.perex").html("<strong>"+$("a", this).attr("title")+"</strong><br />"+$(".perex", this).text());
	});

	/* poslední řádek seznamu partnerů */
	$(".partners.grid").each(function(){
		countGridItem = $("li",this).size();
		if(countGridItem%itemsInRow){
			lastRowCount = countGridItem-(countGridItem%itemsInRow)-1;
			if(lastRowCount >= 0){
				$("li:gt("+lastRowCount+")",this).addClass("last-row");
			} else {
				$("li",this).addClass("last-row");
			}
		} else {
			lastRowCount = countGridItem-itemsInRow-1;
			if(lastRowCount >= 0){
				$("li:gt("+lastRowCount+")",this).addClass("last-row");
			} else {
				$("li",this).addClass("last-row");
			}
		}
	});
	if(typeof(user_state) != "undefined"){
		if(user_state){
			$("#user-box").append("<p class=\"fl\"><span class=\"user\">"+locale["logged"]+": <strong>"+user_name+"</strong></span><a href=\"/srv/www/"+locale["lang"]+"/user/settings.do\">"+locale["account-edit"]+"</a><span class=\"sep\"> | </span><a href=\"/srv/www/"+locale["lang"]+"/user/logout.do\">"+locale["logout"]+"</a></p>");
			$(".register").hide();
			$("#commentary").append('<div id="add-commentary">'+locale["add-commentary"]+'</div>');
			$(".loggedContent").show();
		} else {
			$("#user-box form").show();
			$(".register").show();
			$("#commentary #add-commentary").remove();
			$(".loggedContent").hide();
		}
	}

	//inicializace přepínání kalendáře
	bindCalendarReload();

	//zobrazování komentářů
	//$("#commentary").append('<div id="add-commentary">'+locale["add-commentary"]+'</div>');
	$("#commentary-form").hide();
	$("#add-commentary").click(function () {
		$("#commentary-form").slideToggle("slow");
	});

/* schovávání obsahu pro IE6 */
	if($.browser.msie && $.browser.version < 7) {
		$('.no-ie6').hide();
	}

	/* přepínání v rámci boxu Naše výsledky na hp */
	$("ul#competitionTabs li a").click(function () {
		$("ul#competitionTabs li").removeClass("active");
		$(this).parent().addClass("active");
	});

	/* odkazy z obrázků na rozezkovových stránkách */
/*
	$(".index .box .in img").bind("click", function(){
		index = $("img").index(this)-1;
		if(typeof($(".index .box:eq("+index+") .header a").attr("onclick")) == "undefined"){
			window.location = $(".index .box:eq("+index+") .header a").attr("href");
		} else {
			$(".index .box:eq("+index+") .header a").click();
		}
	});
*/
	$("#no-bg-player #bg-player").hide();
});

/* přepínání tabů */
$.prototype.makeTabs = function(activeTab) {
	var tabs = $("#" + this.attr("id") + " a");
	if(tabs.length == 0) return;
	for (var ti=0; ti < tabs.length; ti++) {
		$("div[class*='tabs-" + $(tabs[ti]).attr("href").substring(1) + "']").hide();
		$(tabs[ti]).bind("click", function() {
			for (var tiin=0; tiin < tabs.length; tiin++) {
				$(tabs[tiin]).removeClass("active");
				$("div[class*='tabs-" + $(tabs[tiin]).attr("href").substring(1) + "']").hide();
			}
			$(this).addClass("active");
			$("div[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") + " a:eq("+activeTab+")").addClass("active");
	$("div[class*='tabs-" + $(tabs[activeTab]).attr("href").substring(1) + "']").show();
};

/* Nastavení výšky řádku floatovaného seznamu */
$.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);
	}
}

/* nastavování velikosti iframu */
function setIframeHeight(h,f) {
	$("#"+f).attr({
		height: h
	});
}

//přepínání stránek
function changeTable(season, competition, lang) {
	window.location.href = "/"+lang+"/"+locale["url-matches"]+"/"+competition+"/"+locale["url-table"]+"-"+season+".shtml";
}

function getCenterW(width) {
	return parseInt( eval( (screen.width-parseInt(width))/2 ) );
}

function getCenterH(height) {
	return parseInt( eval( (screen.height-parseInt(height))/2 ) );
}

function openPopUp( path, name, width, height, scrollB, center ) {
		path = getPathWithBaseHref(path);
		var scrollBar = (scrollB=='1') ? 'yes' : 'no';
		var screenX = ( center != false ? getCenterW(width) : 0 );
		var screenY = ( center != false ? getCenterH(height) : 0 );
		var win=window.open(path,name,'scrollbars=' +scrollBar+ ',resizable=no,resize=no,width='+width+',height='+height+',screenX=' + screenX + ',screenY=' + screenY +',top=' + screenY + ',left=' + screenX + ',locationbar=no,directories=no' );
		win.focus();
}

//function adds base href to path when base href is present
//should be called on every window.open and window.location
function getPathWithBaseHref(path) {
	if(path.indexOf('http://') == -1) {
		var bh = document.getElementsByTagName('base');
		if (bh && bh[0] && bh[0].href) {
		if (bh[0].href.substr(bh[0].href.length-1) == '/' && path.charAt(0) == '/')
		path = path.substr(1);
		path = bh[0].href + path;
		}
	}
	return path;
}

//uzavření vláken fóra
function closeTopicThreads() {
	$(".forum ul").each(function(){
		$(">li:last",this).addClass("close-level");
	});
}

/* Kalendář */
function bindCalendarReload() {
	$("#p-mid .calendar td .tooltip").hide();
	$(".calendar-block .calendar-select a").bind("click", calendarReload);
	//inicializace bublin kalendáře (pro všechny prohlížeče kromě IE6)

	if (!(($.browser.msie) && (parseInt($.browser.version) == 6))) {
		$(".calendar-block table td.action").bind("mouseover", calendarOver);
		$(".calendar-block table td.action").bind("mouseout", calendarOut);
	}
}

function calendarOver() {
	$(this).find(".tooltip").show();
	return false;
}

function calendarOut() {
	$(".calendar-block table td .tooltip").hide();
	return false;
}

function calendarReload() {
	var url = $(this).attr('href');
	$(".calendar-block").css({height: $(".calendar-block").get(0).offsetHeight});
	$(".calendar-block").fadeOut("normal", function() {
		$(".calendar-block").css({visibility: "hidden", display: "block"});
		$(this).load(url, null, function() {
			bindCalendarReload();
			$(".calendar-block").css({height: "auto"});
			$(".calendar-block").css({visibility: "visible"});
			$(".calendar-block").fadeIn("normal");
		})
	});
	return false;
}

function skyscraper() {
	if ($("#banner-skyscraper").height()){
		browserWidth = $(window).width();
		if (browserWidth > (contentWidth+skyscraperWidth)) {
			$("#p-root").css("margin","0px");
			if (browserWidth > (contentWidth+(2*skyscraperWidth))) {
				$("#p-root").css("margin","0px auto");
			}
		} else {
			$("#p-root").css("margin","0px");
		}
	}
}

/**
 * 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=""; };
}

var regDate=/^([0-9]{2})[.]\s([0-9]{2})[.]\s([0-9]{4})$/; /* regulární výraz definice datumu */
/* pole ketegorií automobilů */
var arrayCarCategory = new Array();
arrayCarCategory = [
	["A","A01","do 1000 ccm"],
	["A","A02","1001 -1350 ccm"],
	["A","A13","1351 - 1450 ccm"],
	["A","A03","1451 - 1850 ccm"],
	["A","A14","1851 - 2000 ccm"],
	["A","A04","2001 - 2500 ccm"],
	["A","A05","nad 2500 ccm"],
	["B","B06","do 50 ccm"],
	["B","B07","51 - 350 ccm"],
	["B","B08","351 - 500 ccm"],
	["B","B09","nad 500 ccm"],
	["C","C10","do 3500 kg"],
	["C","C11","3500 - 12000 kg"],
	["T","C14","traktory"],
	["F","F18","do 750 kg"],
	["F","F19","nad 750 kg"]
];
//alert(carCategory.length);


function carCategory() {
	//alert($("select[name='class-car']").val());
	$("#category-car").html('<option value="">'+locale["class-car"]+'&hellip;</option>\n');
	var sb = new StringBuffer();
	for (var i=0; i < arrayCarCategory.length; i++) {
		if(arrayCarCategory[i][0] == $("#class-car").val()) {
			sb.append('<option value="'+arrayCarCategory[i][1]+'">'+arrayCarCategory[i][2]+'</option>\n');
		}
	}
	$("#category-car").append(sb.getString()).removeAttr("disabled");
	$("#client, #birth, #product, #way-application").val("").attr("disabled", "disabled");
	$("#selectBirth").hide();
	if($("#class-car").val() == "T") {
		$("#tractor-info").show();
	}
	else {
		$("#tractor-info").hide();
	}
	campainCheck();
	countInsurance();
};
function typeClient() {
	$("#client").removeAttr("disabled");
	campainCheck();
	countInsurance();
	//$("#birth, #product, #way-application").val("").attr("disabled", "disabled");
	//$("#selectBirth").hide();
};
function typeClientResult() {
	campainCheck();
	if ($("#client").val() == "FO") {
		$("#birth").removeAttr("disabled");
		$("#selectBirth").show();
		campainCheck();
	}
	else {
		$("#selectBirth").hide();
		typeProduct();
	}
}
function typeProduct() {
	$("#product").html('<option value="">'+locale["select-variant"]+'&hellip;</option>\n');
	campainCheck();
	var sb = new StringBuffer();
	if (($("#client").val() != "PO") && ($("#class-car").val() == "A") && ($('input[name="residence"]:checked').val() == "pod")) {
		sb.append('<option value="zv">'+locale["basic-country"]+'<\/option>\n');
		sb.append('<option value="kv">'+locale["set-country"]+'<\/option>\n');
	}
	else {
		sb.append('<option value="zm">'+locale["basic-city"]+'<\/option>\n');
		sb.append('<option value="km">'+locale["set-city"]+'<\/option>\n');
	}
	$("#product").append(sb.getString()).removeAttr("disabled");
	countInsurance();
}
function wayApplication() {
	//$("#way-application").val("").attr("disabled", "disabled");
	$("#way-application").removeAttr("disabled");
	countInsurance();
}
function countInsurance() {
	//if ()
	if (($("#class-car").val() != "") && ($("#category-car").val() != "") && ($("#product").val() != "") && ($("#way-application").val() != "")) {
		$.get('/srv/www/qf/cs/ramjet/xss/calculatePojisteniNew?druhvoz='+$("#class-car").val()+'&katvoz='+$("#category-car").val()+'&produkt='+$("#product").val()+'&bonus=1', function(data) {
			if (data) {
				calcInsurance = parseInt(data, 10);
			}
			$.get('/srv/www/qf/cs/ramjet/xss/calculateBonus?rd='+$("#time-insurance").val()+'&pu='+$("#count-damage").val(), function(data) {
				if (data) {
					calcBonusPercent = parseInt(data, 10);
				}
				calcBonus = calcInsurance*calcBonusPercent/100;
				calcFinal = calcInsurance - calcBonus;
				if (calcBonusPercent >= 0) {
					$("#bonus").html(locale["bonus"]);
				}
				else {
					$("#bonus").html(locale["malus"]);
					calcBonus = calcBonus*(-1);
					calcBonusPercent = calcBonusPercent*(-1);
				}
				$("#calc-insurance").html(calcInsurance);
				$("#calc-bonus").html(calcBonus);
				$("#calc-bonus-percent").html(calcBonusPercent);
				$("#calc-final").html(calcFinal);
			});
		});
		//alert("ze getem");
	}
	else {
		calcInsurance = 0;
		calcBonus = 0;
		calcBonusPercent = 0;
		calcFinal = 0;
		$("#bonus").html(locale["bonus"]);
		$("#calc-insurance").html(calcInsurance);
		$("#calc-bonus").html(calcBonus);
		$("#calc-bonus-percent").html(calcBonusPercent);
		$("#calc-final").html(calcFinal);
	}
}
function campainCheck() {
	if ($("#class-car").val() == "A" && $("#category-car").val() != "" && $("#category-car").val() != "A01" && $("#category-car").val() != "A02") {
		if (($("#client").val() != "" && $("#client").val() != "FO") || ($("#client").val() == "FO" && $("#birth").val() < 1980 && $("#birth").val() > 1900)) {
			$("#offer-campain-check").show();
		}
		else {
			$("#offer-campain-check").hide();
		}
	}
	else {
		$("#offer-campain-check").hide();
	}
}

function addCampainCheck() {
	if ($('input[name="campain-check"]:checked').val() == "on") {
		$("#time-insurance").val("132");
		$("#time-insurance, #count-damage").attr("disabled", "disabled");
	}
	else {
		$("#time-insurance").val("");
		$("#time-insurance, #count-damage").removeAttr("disabled");
	}
	countInsurance();
}

function annual() {
	$("#stopInsurance").remove();
	$("#countChildren, #countSeniors").parent().hide();
	$("#countChildren, #countSeniors").val("");
	$("#region-1").attr("disabled", "disabled");
	$("label[for='stopInsurance']").after('<span id="stopInsurance" class="text-instead-input"></span>');
	fStopInsurance()
	countTravelInsurance();
}
function oneOff() {
	$("#stopInsurance").remove();
	$("#countChildren, #countSeniors").parent().show();
	$("#region-1").removeAttr("disabled");
	$("label[for='stopInsurance']").after('<input type="text" value="" name="stopInsurance" id="stopInsurance" class="datepicker" onchange="countDays()" />');
	countTravelInsurance();
}

function fStopInsurance() {
	var dateStopInsurance = $("#startInsurance").val();
	if (regDate.test(dateStopInsurance) && $('input[name="typeInsurance"]:checked').val() == "r") {
		dateStopInsurance = new Date(dateStopInsurance.replace(regDate,"$3/$2/$1"));
		dateStopInsurance.setFullYear(dateStopInsurance.getFullYear()+1);
		$("#stopInsurance").text(dateStopInsurance.getDate()+". "+ (dateStopInsurance.getMonth()+1)+". "+dateStopInsurance.getFullYear());
		$("#countDays").text("366");
	}
	countDays()
	countTravelInsurance();
}

function countDays() {
	var dateStartInsurance = $("#startInsurance").val();
	var dateStopInsurance = $("#stopInsurance").val();
	if (regDate.test(dateStartInsurance) && regDate.test(dateStopInsurance)) {
		dateStartInsurance = new Date(dateStartInsurance.replace(regDate,"$3/$2/$1"));
		dateStopInsurance = new Date(dateStopInsurance.replace(regDate,"$3/$2/$1"));
		diff = dateStopInsurance - dateStartInsurance;
		diff = Math.round(diff / (1000*60*60*24))+1; // převod zpět na dny
		$("#countDays").text(diff);
		countTravelInsurance();
	}
}

function countTravelInsurance() {
	var countDays = $("#countDays").text();
	if ( countDays != 0 && ($("#countChildren").val() > 0 || $("#countAdults").val() > 0 || $("#countSeniors").val() > 0) && typeof($('input[name="region"]:checked').val()) !="undefined") {
		if ($("#countChildren").val() > 0) { countChildren = $("#countChildren").val(); } else { countChildren = 0; }
		if ($("#countAdults").val() > 0) { countAdults = $("#countAdults").val(); } else { countAdults = 0; }
		if ($("#countSeniors").val() > 0) { countSeniors = $("#countSeniors").val(); } else { countSeniors = 0; }
		var priceTravelInsuranceUrl = "/srv/www/qf/cs/ramjet/insurance?dni="+countDays+"&pocet1="+countChildren+"&pocet2="+countAdults+"&pocet3="+countSeniors+"&region="+$('input[name="region"]:checked').val()+"&pojisteni="+$('input[name="typeInsurance"]:checked').val();
		$("#box-generali").hide();
		$.get(priceTravelInsuranceUrl, function(data) {
			$("#calc-final").text(locale["yet-from"]+data);
			$("#box-generali").hide();
		})
	}
	else {
		$("#box-generali").show();
		$("#calc-final").text("0");
	}
}

