ie = (navigator.userAgent.indexOf('msie')>-1);
win = (navigator.userAgent.indexOf('windows')>-1);

function prn() {
	document.write(' \| \074a href=\"javascript:goprn();\"\076vytisknout\074/a\076');
}
function goprn() {
	window.print();
}
function fav() {
	if ((ie) && (win)) {
	  document.write(' \| \074a href=\"javascript:gofav();\"\076přidat do záložek\074/a\076');
	}
}
function gofav() {
	window.external.addFavorite('http://www.nacesty.cz','NaCesty.cz: internetová cestovní agentura');
}

/**
 * Funkce zjisti, zda retezec zacina zadanym retezcem.
 * @param string
 * @param value
 * @return
 */
function startsWith(string, value) {
	var index = value.length;
	if (string.length >= index) {
		if (string.substring(0, index) == value) {
			return true;
		}
	}
	return false;
}

/**
 * Funkce oboustrane oseka retezec o bile znaky.
 * @param stringToTrim
 * @return
 */
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/**
 * ############ zapis, ziskanie a mazanie cookies #######################
 */

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
 
function translate(element) {
	var google = "http://translate.google.com/translate?hl=cs&sl=de&tl=cs&u=";
	if (element && element.href) {
	    var link = element.getAttribute('link');
		element.href = google + escape(link);
	}
} 

/**
 * ############ ovladani cervenych zalozek #######################
 */

function initLightbox() {
	$("a[rel^=lightbox]").lightBox();
}

/**
 * aktivuje ovladani zalozek
 */
function initZalozky() {
	if ($("#zalozky")) {
		/**
		 * obsluhuje udalosti prepinani zalozek 
		 */
		$("#zalozky ul:first a").click(function () {handleZalozku($(this).parent());});
	}
	var zalozkyObsah = $("#zalozky-obsah");
	
	var hash = window.location.hash;
	if (hash.length > 1) {
		var activeAnchorName;
		var activeZalozka;
		var activeAnchor;
		var activeAnchorIndex = hash.indexOf("-atlas-");
		if (activeAnchorIndex != -1) {
			activeAnchorName = hash.substring(activeAnchorIndex + 1, hash.length);			
		}
		if (hash.indexOf("textHodnoceni_") != -1) {
			activeZalozka = "hodnoceniHotelu";
		} else {
			activeZalozka = hash.substring(1, hash.indexOf("Tab"));
		}
		$("#zalozky li").each(function() {
			if (this.id != activeZalozka) {
				$(this).removeClass("active");
			} else {
				$(this).addClass("active");
			}
		});
		activeZalozka = activeZalozka + "Zalozka";
		$("#zalozky-obsah div.zalozka").each(function() {
			if (this.id != activeZalozka) {
				$(this).hide();
				$(this).removeClass("active");
			} else {
				$(this).addClass("active");	
				if (activeAnchorName != null) {
					activeAnchor = $(this).find("a[name='" + activeAnchorName + "']");
				}
			}
		});
	} else {
		if (zalozkyObsah) {		
			$("#zalozky-obsah div.zalozka:not(.active)").hide();
		}
	}
	
	// odscroluje na odstavec uvnitr zalozky
	scrollToAnchor(activeAnchor, true);
	
	$("#o-destinaciZalozka li a, #duleziteZalozka li a").live("click", function(event) {
		var href = $(this).attr("href");
		if(href.substring(0,1) != '#') {
			return;
		}
		event.preventDefault();
		href = href.substring(1, href.length);
		hash = window.location.hash;
		window.location.hash = hash.substring(0, hash.indexOf("Tab") + 3) + "-" + href;
		scrollToAnchor($(this).parent().parent().parent().find("a[name='" + href + "']"), false);
	});
	$("#o-destinaciZalozka h2 a[href='#atlas-top'], #duleziteZalozka h2 a[href='#atlas-top']").live("click", function(event) {
		event.preventDefault();
		hash = window.location.hash;
		if (hash.indexOf("-atlas-") != -1) {
			window.location.hash = hash.substring(0, hash.indexOf("-atlas-"));
		}
		scrollToAnchor($(this).parent().parent().find("a[name='atlas-top']"), false);
	});	
}

function handleZalozku(zalozka) {
	$("#zalozky ul:first li.active").removeClass("active");	
	zalozka.addClass("active");
	var zalozkaObsah = $("#" + zalozka.attr("id") + "Zalozka");
	if (zalozkaObsah) {
		$("div#zalozky-obsah div.zalozka").hide();
		zalozkaObsah.show();
	}
}

function scrollToAnchor(anchor, webKitShift) {
	if (anchor == null || !anchor.length) {	
		return;
	}
	var scrollOffset = anchor.offset().top;
	// prohlizece zalozene na WebKitu z nepochopitelnych duvodu vraci o 130px vyssi offset
	if (webKitShift && navigator.userAgent.indexOf("WebKit") != -1) {
		scrollOffset = scrollOffset - 128;
	}
	$("body,html").animate({scrollTop:scrollOffset}, 'fast');
}

$(document).ready(function() {
	initZalozky();
	initLightbox();
});

/**
 * SELECT / UNSELECT ALL
 */
function selectAll(className) {
	$('input.'+className).each(function() {
		this.checked = true;
	});
}

function unselectAll(className) {
	$('input.'+className).each(function() {
		this.checked = false;
	});
}


/** zobrazovani vyhledavaciho formulare */

function display (elementID) {
	if ($("#area" + elementID)) {
		$("#area" + elementID).show();
	}
}
function undisplay (elementID) {
	if ($("#area" + elementID)) {
		$("#area" + elementID).hide();
	}
}

/**
 * Seznam cilu
 */
 
var seznamCilu = new Array(  
				"CBYN,ERZ,ALL < vše >",
				"CBYN Bavorské Alpy",
				"CERZ Krkonoše",				
				"CALL Allgäu",
				"GG < vše >",
				"GACH Achental",
				"GARL Arlberg",
				"GAXA Axamer Lizum",
				"GBGZ Bregenzer Wald",
				"GDTR Dachstein-Tauern-Region",
				"GKAP Europa Sportregion",
				"GGTT Gasteiner Tal",
				"GGRG Grossglockner",
				"GISB Innsbruck a okolí",
				"GISG Ischgl/Samnaun",
				"GKSG Kaisergebirge",
				"GKNA Kaunertal",
				"GKIZ Kitzbühlské Alpy",
				"GMFN Montafon",
				"GOTZ Ötztal",
				"GPZN Paznauntal",
				"GPIZ Pitztal",
				"GAMA Radtstädter Tauern",
				"GRES Reschenpass/Nauders",
				"GSFL Sefaus/Fiss/Ladis",
				"GSAA Saalbach/Hinterglemm",
				"GASL Salzbursko",
				"GSEE Seefeld",
				"GSTB Stubaital",
				"GTXT Tuxertal",
				"GWLS Walsertal",
				"GWDK Wilder Kaiser/Walchsee",
				"GZIL Zillertal",
				"GZGS Zugspitzarena",
				"FF < vše >",
				"FSAF Saas Fee a okolí",
				"FZMT Zermatt a okolí",
				"FALS Aletschgebiet",
				"FEGL Engelberg, Andermatt",
				"FFLF Flims, Laax, Falera",
				"FADK Arosa, Davos, Klosters",
				"FSMO St. Moritz (Engadin)",
				"FCLK Crans Montana a okolí",
				"FGAS Gstaad, Adelboden a okolí",
				"FEMJ Eiger, Mönch, Jungfrau",
				"FVBR Verbier a okolí",
				"FSCH Zbytek Švýcarska",
				"MGAR,DOL < vše >",
				"MGAR Lago di Garda",
				"MDOL Jižní Tyrolsko, Dolomity",
				"KFAL Francouzské Alpy",
				"QTSC < vše >",
				"SSLO < vše >",
				"TSLJ Jurské Alpy"
			);

function handleCil(event, target) {
	var value = target.val();
	vyplnitDestinaceNaHorach(value);
} 

function vyplnitDestinaceNaHorach(value) {
	var cil = $('#zielDestinace');	
	if (!cil.length) {
		return;
	}
	
	//smaze veskere nastaveni selectboxu			
	cil.empty();
	
	//pokud jsme na velkem formulari, potom chceme aby se uchovavaly hodnoty, coz delame timto
	var predvypln = false;
	if (!(typeof aktualniCil == 'undefined') && aktualniCil.length > 0) {
		predvypln = true;
	}

	//naplni jej relevantnimi hodnotami podle vybraneho radia
	var idx = 0;	
	for (var i = 0; i < seznamCilu.length; i++) {
		var item = seznamCilu[i];		
		if (startsWith(item, value)) {			
			optionValue = item.substring(1,item.indexOf(' '));	
			var option = $("<option />").attr("value", trim(optionValue));
			option.html(item.substring(item.indexOf(' ') + 1));
			option.appendTo(cil);
			if (predvypln && option.val() == aktualniCil) {
				option[0].selected = true;
			}
		}
	}
	if (!predvypln) {
		cil[0].selectedIndex = 0;
	}
}

function nastavitAktualniHodnotyDestinaceNaHorach(aktualniCil) {
	var cil = $('#zielDestinace');	
	if (!cil.length) {
		return;
	}	

	//smaze veskere nastaveni selectboxu			
	while (cil[0].options[0].length > 0) {
 		cil[0].options[0] = null;
	}
	//najdeme zemi, jejichz destinace maji byt ve formulari
	var idx = 0;
	for (var i = 0; i < seznamCilu.length; i++) {
		if (seznamCilu[i].substring(1, seznamCilu[i].indexOf(' ')) == aktualniCil) {
			break;
		}else {
			idx++;
		}		
	}

	//pokud je kod vetsi, tudiz z travel it prisel region, ktery nemame v moznostech, predvyplnime na rakousko
	if (idx < 53) {
		//urci kod zeme
		var kod = trim(seznamCilu[idx].substring(0,1));
		//predvyplni zemi ve formulari zemi
		$("#cil option").each(function() {
			if (this.value == kod) {
				this.selected = true;
			}
		});
	} else {
		var kod = 'G';
	}
	
	//predvyplni destinace na zaklade kodu
	vyplnitDestinaceNaHorach(kod);
}


/**
* PrintF funkcionalita
*/
function sprintf() {
			if (!arguments || arguments.length < 1 || !RegExp) {
				return;
			}
			var str = arguments[0];
			var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
			var a = b = [], numSubstitutions = 0, numMatches = 0;
			while (a = re.exec(str))
			{
				var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
				var pPrecision = a[5], pType = a[6], rightPart = a[7];
				
				//alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

				numMatches++;
				if (pType == '%')
				{
					subst = '%';
				}
				else
				{
					numSubstitutions++;
					if (numSubstitutions >= arguments.length)
					{
						alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
					}
					var param = arguments[numSubstitutions];
					var pad = '';
					       if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
					  else if (pPad) pad = pPad;
					var justifyRight = true;
					       if (pJustify && pJustify === "-") justifyRight = false;
					var minLength = -1;
					       if (pMinLength) minLength = parseInt(pMinLength);
					var precision = -1;
					       if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
					var subst = param;
					       if (pType == 'b') subst = parseInt(param).toString(2);
					  else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
					  else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
					  else if (pType == 'u') subst = Math.abs(param);
					  else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
					  else if (pType == 'o') subst = parseInt(param).toString(8);
					  else if (pType == 's') subst = param;
					  else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
					  else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
				}
				str = leftpart + subst + rightPart;
			}
			return str;
		}

//nahradi vsetky vyskyty retazca strA retazcom strB v retazci text
function replaceAll(text, strA, strB)
{
    while ( text.indexOf(strA) != -1)
    {
        text = text.replace(strA,strB);
    }
    return text;
}


// number formatting function
// copyright Stephen Chapman 24th March 2006, 22nd August 2008
// permission to use this function is granted provided
// that this copyright notice is retained intact

function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {var x = Math.round(num * Math.pow(10,dec));if (x >= 0) n1=n2='';var y = (''+Math.abs(x)).split('');var z = y.length - dec; if (z<0) z--; for(var i = z; i < 0; i++) y.unshift('0'); if (z<0) z = 1; y.splice(z, 0, pnt); if(y[0] == pnt) y.unshift('0'); while (z > 3) {z-=3; y.splice(z,0,thou);}var r = curr1+n1+y.join('')+n2+curr2;return r;}

/**
 * Sestavi URL z pripravene URL vygenerovane servletem a Travel IT parametry.
 * Implementovalo se, aby se URL sestavila pomoci JS a nebyla tak prohledavana
 * vyhledavaci.
 */
function buildUrlWithTravelITParams(url, travelItParams) {
	var lastSlashIndex = url.lastIndexOf("/");
	if (lastSlashIndex != -1) {
		url = url.substring(0, lastSlashIndex) + travelItParams + url.substring(lastSlashIndex, url.length);			
	}
	return url;
}

