var browser = "";
var imageBuffer = new Image();
var waitInfoShowed = true;    // zda je zobrazeno okno o nacitani
var actualImageIndex = -1;
var showFirst = false;
var photoIndex = -1;
var onLoadHistoryHash = '';     // -2 jeste nebyl vygenerovany index, -1 zobrazit album 0-x zobrazit fotku
var storedScrollTop = -1;
var dir_ajax = '/_www_root_/ajax/';
var disabledShowPhotoDetail = false; // jednorazove zamezi zobrazeni detailu fotky (vhodne, pokud kliknuti ma slouzit k necemu jinemu ... napr. drag&drop)
var photoCount;
var nameToIndex = new Array();
var viewedPhotos = new Object();
var startTime = new Date();
var detailWindowWidth;
var detailWindowHeight;

cookiesUtil = {
	trim : function (stringToTrim) {
		return stringToTrim.replace(/^\s+|\s+$/g, "");
	},
	set : function (key, val) {
        var d = new Date(2020, 01, 01);
		var cook = key + "=" + escape(val)
                          + ';domain=' + domain 
                          + ';path=/'
                          + ';expires=' + d.toUTCString();
        document.cookie = cook;		
	},
	get : function (key) {
		try {
	 	    cookies = document.cookie.split(";");
		    for (i = 0; i < cookies.length; i++) {
		        var c = cookies[i].split("=");
		        if (this.trim(c[0]) == key) return c[1];
		    }
			return "";
		}
        catch (err) {
			return "";
        }
   }
}

function soutez() {
	var cDate = new Date();
	var d = cDate.getDate() + ''; while (d.length < 2) d = '0' + d; 
	var m = (cDate.getMonth() + 1) + ''; while (m.length < 2) m = '0' + m; 
	var y = cDate.getFullYear() + ''; while (y.length < 4) y = '0' + y;
	var date = y + '-' + m + '-' + d;
	document.loadScript("http://data.idnes.cz/soutez/vanocni-soutez.js?rnd=" + date);
}

function photo_exists(index) {
	return typeof photos[index] != 'undefined' && typeof photos[index].fileName != 'undefined';
}

function PromptMe()
{
    this.savePhotoName = function(index)
    {
        if (index == null || !photo_exists(index)) {
            unFocus.History.addHistory('album');
        }
        else {
            unFocus.History.addHistory(unescape(photos[index].fileName));
        }
    };
    
    this.historyListener = function(historyHash)
    {
        if (onLoadHistoryHash == '') {
            onLoadHistoryHash = historyHash;
        }
        else {
            if (historyHash != null && nameToIndex[historyHash] != null && historyHash != 'album') {
                ShowPhotoDetail(nameToIndex[historyHash]);
            }
            else {
                ShowAlbumThumbs();
            }
        }
    };
    
    unFocus.History.addEventListener('historyChange', this.historyListener);
    this.historyListener(unFocus.History.getCurrent());
};



var historyApp;
unFocus.Utilities.QuickLoader.addListener(function() {
	historyApp = new PromptMe();
	
	if(showFirst==true){
    ShowPhotoDetail(0);
	}
});

function ShowAlbum()
{
    if (historyApp != null) {
        historyApp.savePhotoName(null);
    }
}


// zobrazi cela album, nahledy
function ShowAlbumThumbs()
{
    //link_set('up', 'http://' + albumUserName + '.' + domain + '/');
    if (actualImageIndex != -1) {
        HideWait();
        
        document.getElementById("thumbnailPart").style.display = "block";
        document.getElementById("detailPart").style.display = "none";
        
        $("body").removeClass("mikro");
        $("body").addClass("mini");
        
        if (storedScrollTop != -1) {
            setScrollY(storedScrollTop);
        }
        
        actualImageIndex = -1;
		
		//vraceni panelaku zpet do pozice po prizpusobovani pozice pri prohlizeni HR fotek
		$('#panelakInDetail').css('left', '850px');
    }
    else if (photoCount == 1 && showFirst == false) { // pokud album obsahuje pouze jednu fotku, tak se rovnou zobrazi
        showFirst = true;
    }

	if (typeof CommentManager != 'undefined') {
		$('#albumComments div.commentList').empty(); //nutno odebrat komentare k drive zobrazene
		CommentManager.Show(new CommentView(albumUserID, albumID, null,'album'));	
	}		
}

// pred zobrazenim fotky to uchova pozici scroll (a take, necekane, zobrazi fotku)
function StoreScroll(index)
{
    storedScrollTop = getScrollY();
    setScrollY(0);
    ShowPhoto(index);
}

function ShowPhotoNext(index)
{
	var nextid;
	try {
		nextid = $("#pid" + index).parent().next().children(":first-child").attr("id").substr(3);
	} catch (err) {
		if(index == -1){
			nextid = 0;
		}
		else{
			nextid = photoCount;	
		}
	}
	ShowPhoto(nextid);
}

function ShowPhotoPrevious(index)
{
	var nextid;
	try {
		nextid = $("#pid" + index).parent().prev().children(":first-child").attr("id").substr(3);
	} catch (err) {
		nextid = -1;
	}
	ShowPhoto(nextid);
}

// zapsani do historie
function ShowPhoto(index)
{
	if (typeof viewedPhotos[index] == 'undefined') {
		viewedPhotos[index] = 1;
	} else {
		viewedPhotos[index] += 1;
	}
    // kontrola, jesli sem uz neprejel
    if (index < 0) {
        photoIndex = -1;
        ShowAlbum();
    }
    else {
     // unsavedEscape();
        if (index >= photoCount) {
            photoIndex = -1;
            ShowAlbum();
        }
    }
    historyApp.savePhotoName(index);
}


// tisk fotky
function photoPrint(index)
{
    index = photoIndex;
    main_rel = $("DIV.cartList").attr('rel');
    if (!$('#photoPrint').is('.statusPhoto')) {
        $('#photoPrint').addClass('statusPhoto');
        var pid = $('#pi-' + (index + 1) + ' A.printPhoto').attr('id').substr(3);
        var is_add = cartItem_is(index + 1);
        if (is_add) {
            $('#pa-' + pid).removeClass('deletePhoto');
            $('#photoPrint').removeClass('deletePhoto');
			selectedPhotos -= 1; 
        }
        else {
            $('#pa-' + pid).removeClass('addPhoto');
            $('#photoPrint').removeClass('addPhoto');
			selectedPhotos += 1; 
        }
        $.getJSON(dir_ajax + 'cart.php?id=' + pid + '&action=' + (is_add ? 'delete' : 'add') + '&' + main_rel + '&fileName=' + photos[index].fileName, function(json)
        {
            $('#pa-' + json.id).removeClass('statusPhoto');
            if ((json.action == 'add' && json.result == 1) || (json.action == 'delete' && json.result == 0)) {
                $('#pa-' + json.id).addClass('deletePhoto');
            }
            else {
                $('#pa-' + json.id).addClass('addPhoto');
            }
            $('#photoPrint').removeClass('statusPhoto');
            if (cartItem_is(index + 1)) {
                $('#photoPrint').addClass('deletePhoto');
            }
            else {
                $('#photoPrint').addClass('addPhoto');
            }
        });
    }
    return false;
}

// zobrazeni detailu fotky
function ShowPhotoDetail(index)
{	    
	if (index >= 0 && actualImageIndex != index) {
		
		if (index == 4) {
			soutez();
		}	     

		var $detailImageFrame = $("#detailImageFrame"); // ram pro detail fotky
		var $detailVideoFrame = $("#detailVideoFrame"); // ram pro detail videa
		var $detailImage = $('#detailImage'); // <img> obrazek detailu fotky 
        
        photoIndex = index;
		actualImageIndex = index;
        
		document.getElementById("thumbnailPart").style.display = "none";
        document.getElementById("detailPart").style.display = "block";
        
        // prehazovani reklamy
        try {
            var reklama = document.getElementById("bannerPanelak").childNodes[0];
            document.getElementById("bannerPanelak2").appendChild(reklama);
        } 
        catch (err) {
        }
        
        $("body").removeClass("mini").addClass("mikro");
        
        if ($(".cartList").size() > 0) {
            if (cartItem_is(photoIndex + 1)) {
                $('#photoPrint').removeClass('addPhoto');
                $('#photoPrint').addClass('deletePhoto');
            }
            else {
                $('#photoPrint').removeClass('deletePhoto');
                $('#photoPrint').addClass('addPhoto');
            }
        }

		if (photos[index].width > 0 && photos[index].height > 0) {			
		
			if (!photos[photoIndex].isVideo) {
				var resizedPhotoSize = ResizeHRImage(index);
				applyNewPhotoDimentions(resizedPhotoSize, $detailImage, $detailImageFrame);			
			}
			else {
				var resizedVideoSize = { width: photos[index].width, height: photos[index].height + 45};//45px pro ovladaci prvky videoprehravace
				applyNewPhotoDimentions(resizedVideoSize, $detailImage, $detailVideoFrame);				
			}
			
		} else {
            $detailImage.hide();
        }

		//nastaveni jmena fotky	
        try {
            if (typeof editingName != 'undefined' && photos[index].name == '') {
                $("div#detailName").text(writeNamePrompt);
            }
            else {
                $("div#detailName").text(photos[index].name);
            }
        } 
        catch (err) {
        }	
        
        var descHtml = "";
        try {
            descHtml = photos[index].desc;
        } 
        catch (err) {
            descHtml = "";
        }
		
		try {
			if (typeof editingCaption != 'undefined' && photos[index].desc == '') {
				$("div#photoDescription").html(writeCaptionPrompt);
			}
			else {
				$("div#photoDescription").html(descHtml);	
			}	
		}
		catch(err) {			
		}
		
        $("div#photoExif").text(photos[index].info);
		
		if (typeof CommentManager != 'undefined') {
			$('#albumComments div.commentList').empty(); //po zobrazeni detailu tez nutno oddebrat kvuli zmensovani nahledu
			$('#photoComments div.commentList').empty(); //nutno odebrat komentare k predchozim fotkam
			var textareaImg = $('#photoTextareaWrapper .commentThumb a img');
			textareaImg.attr('src', storage + '/thumb/' + photos[index].fileName);
			textareaImg.css({width: 'auto', height: 'auto', marginTop: '0px', visibility: 'hidden'});
			resizeCommentThumbImage($('#photoTextareaWrapper'));
			CommentManager.Show(new CommentView(authUserID, albumID, photos[index].photoID, 'photo'));	
		}
	
        // nejdriv nahraju nahled aktualni fotky
        LoadBuffThumb();

        //zobrazeni videa
        if (!photos[photoIndex].isVideo) {
			$detailVideoFrame.find('embed').remove();
			$detailVideoFrame.hide();
            $detailImageFrame.show();
            LoadBuffThumb();
			//scrollDetailFrameIntoView($detailImageFrame);
        }
		//zobrazeni detailu fotky
        else {
            $detailImageFrame.hide();
			$detailVideoFrame.find('embed').remove();
			$detailVideoFrame.show();
			//scrollDetailFrameIntoView($detailVideoFrame);
						
			//kontrola zda video bylo zobrazeno po kliknuti na nahled nebo pri prohlizeni alba sipkami
			var thumbHTMLobject = $('#p_' + photos[index].photoID);
			var autoStartValue; 
			
			//pokud bylo kliknuto na nahled videa hodnota pro autostart bude nastavena na true
			if (thumbHTMLobject.data('thumbClicked') != 'undefined' && thumbHTMLobject.data('thumbClicked') == true) {
				autoStartValue = true;
				thumbHTMLobject.data('thumbClicked',false);
			}
			//video bylo zobrazeno bud prohlizenim v albu, autostart je false
			else {
				autoStartValue = false;
			}
            $detailVideoFrame.append(embedVideo.getVideoHTML(photos[index].photoID, photos[index].width, photos[index].height, autoStartValue));
        }
		updateTitlesInDetail(index);		
		//skryti sdileni a exifu pri prechodu na dalsi fotku
		displayPhotoInfo();	
    }
}

function displayPhotoInfo(){
	var exifVisible = parseInt(cookiesUtil.get('rajce.net-exif'));	
	$('#sharePhoto').hide();
	
	if (exifVisible) {		
		$('#photoExif').show();		
	}
	else {		
		$('#photoExif').hide();		
	}	
}

function updateTitlesInDetail(index){
	var pohotoPreviousTitle = (index == 0) ? 'zobrazit celé album' : 'klikni pro předchozí ' + (index) + '/' + photoCount;
	var pohotoNextTitle = (index == (photoCount-1)) ? 'zobrazit celé album' : 'klikni pro další ' + (index + 2) + '/' + photoCount;
		
	$('#detailImage').attr('title',pohotoNextTitle);
	$('#photoPrevious').attr('title',pohotoPreviousTitle);
	$('#photoNext').attr('title',pohotoNextTitle);	
}

// Spocte novou velikost obdelniku objectSize tak, aby se vesel do obdelniku
// boundingBoxSize pri zachovani pomeru stran (pouze zmensuje nebo zachova velikost).
function ZmensiDoObdelniku(boundingBoxSize, objectSize)
{
	var ratio;
	if (boundingBoxSize.width * objectSize.height > boundingBoxSize.height * objectSize.width)
		ratio = boundingBoxSize.height / objectSize.height; // limitujici je vyska bounding boxu
	else
		ratio = boundingBoxSize.width / objectSize.width; // limitujici je sirka bounding boxu
	if (ratio > 1) ratio = 1; // nezvetsujeme
	return {
		width: Math.floor(objectSize.width * ratio),
		height: Math.floor(objectSize.height * ratio) };
}

function ResizeHRImage(index) {
	var photoWidth = photos[index].width;
	var photoHeight = photos[index].height;
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	var navOffset = $('#photoNavigation').offset();
	var navHeight = $('#photoNavigation').height();
	var pageTop = $(window).scrollTop();
	var border = 40; // 40px border (20 + 20px)
	var bannerPanelakWidth = ($('#panelakInDetail').length > 0) ? $('#panelakInDetail').width() : 0;
	var availableWidth = windowWidth - (2 * bannerPanelakWidth + border);
	var availableHeight = (windowHeight + pageTop) - (navOffset.top + navHeight + border); 	
	
	// budeme slusni a nebude delit nulou...
    if (photoWidth == 0 || photoHeight == 0)
    	return { width: photoWidth, height: photoHeight}

	// spocte nejvetsi velikost fotky pri zachovani pomeru stran tak, aby se vesla do daneho obdelniku
	var newSize = ZmensiDoObdelniku(
		{ width: availableWidth, height: availableHeight },
		{ width: photoWidth, height: photoHeight });

	// pokud je nejdelsi strana mensi nez 700, zvetsi ji na 700.
	var maxSideLength = Math.max(newSize.width, newSize.height);
	var scaleTo = Math.min(Math.max(photoWidth, photoHeight), 700);
  	if (maxSideLength < scaleTo || ($.browser.msie && $.browser.version=="6.0")) {
		var ratio = scaleTo / maxSideLength;
		newSize = { width: Math.round(newSize.width * ratio), height: Math.round(newSize.height * ratio) };
	}
	return newSize;
}

function applyNewPhotoDimentions(imgSize, imgObject, imgContainer) {
	var border = 20;
	var cornerSize = 169; 
	var panelakWidth = ($('#panelakInDetail').length > 0) ? $('#panelakInDetail').width() : 0;
	imgObject.css({ width: imgSize.width, height: imgSize.height });
	imgContainer.css({ width: imgSize.width + (2 * border), height: imgSize.height + (2 * border) });
	imgContainer.find('.hside')
		.css('width', Math.max(0, imgSize.width + 2 * border - 2 * cornerSize))
		.css('height', imgContainer.css('height'))
		.css('display', imgSize.width + 2 * border - 2 * cornerSize > 0 ? 'block' : 'none');
	imgContainer.find('.vside')
		.css('height', Math.max(0, imgSize.height + 2 * border - 2 * cornerSize))
		.css('width', imgContainer.css('width'))
		.css('display', imgSize.height + 2 * border - 2 * cornerSize > 0 ? 'block' : 'none');
	imgContainer.find('.corner')
		.css('width', Math.min(cornerSize, imgSize.width / 2 + border))
        .css('height', Math.min(cornerSize, imgSize.height / 2 + border));

	var negativeMargin = (imgSize.width > 700) ? Math.round(($('#content').width() - imgSize.width) / 2) + 'px' : 'auto';
	imgContainer.css('margin','0px ' + negativeMargin);
	var contentLeft = $('#content').offset().left;
	var frameLeft = imgContainer.offset().left;
	var addedLeft = ((contentLeft + border + panelakWidth) > frameLeft) ? (contentLeft - frameLeft) + (border + panelakWidth) : 0;  
	$('#panelakInDetail').css('left', 850 + addedLeft + 'px');
}

// uprava pro operu, nejak nechce posialt eventy... (tohle ji pomuze)
function InitImageBuffer()
{
    if (getBrowser() == "o") {
        imageBuffer = new Image();
    }
}

// pokud je nahraty hlavni obrazek, jen pro kontlu
function AfterLoadPhoto()
{
}

// nahraje do bufferu nahled aktualni fotky, ktery se zobrazi pri prekliku na dalsi fotku (pokud neni nahrata dalsi fotka)
function LoadBuffThumb()
{
    slideshow.setNextPhotoLoaded(false);
    if (photo_exists(photoIndex)) {
        ShowWait();
        InitImageBuffer();
        imageBuffer.onload = AfterLoadBuffThumb;		
        imageBuffer.src = storage + 'thumb/' + photos[photoIndex].fileName;
    }
}

function AfterLoadBuffThumb()
{
    if (photo_exists(photoIndex)) {
		document.getElementById('detailImage').style.msInterpolationMode = 'nearest-neighbor';
        document.getElementById('detailImage').src = storage + 'thumb/' + photos[photoIndex].fileName;		
        LoadBuffPhoto();
    }
}

// nahraje do bufferu aktualni fotku, ktera se zobrazi po nahrati nehledu
function LoadBuffPhoto()
{
    if (photo_exists(photoIndex)) {
        InitImageBuffer();
        imageBuffer.onload = AfterLoadBuffPhoto;
        imageBuffer.src = storage + 'images/' + photos[photoIndex].fileName;
    }
}

function AfterLoadBuffPhoto()
{
    if (photo_exists(photoIndex)) {

		document.getElementById('detailImage').src = storage + 'images/' + photos[photoIndex].fileName;	
		document.getElementById('detailImage').style.msInterpolationMode = 'bicubic';

		if ($.browser.msie && $.browser.version=="6.0") {
			document.getElementById('detailImage').src = 'http://www.' + domain + '/img/blank.gif';
			document.getElementById('detailImage').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true src='" + storage + 'images/' + photos[photoIndex].fileName + "', sizingMethod='scale')";	
		}        
									
        HideWait();
        LoadBuffNextThumb();
    }
}

// nahraje do bufferu nahled dalsi fotky
function LoadBuffNextThumb()
{
    if ((photoIndex + 1) < photoCount) {
        InitImageBuffer();
        imageBuffer.onload = AfterLoadBuffNextThumb;
        imageBuffer.src = storage + "thumb/" + photos[photoIndex + 1]["fileName"];
    }
}

function AfterLoadBuffNextThumb()
{
    LoadBuffNextPhoto();
}

// zobrazi progressbar nacitani nasledujici fotky
function DisplayLoadProcess()
{
    if ($("#loadingNext").data("process") == true) {
        $("#loadingNext").css("visibility", "visible");
    }
}

// nahraje do bufferu dalsi fotku
function LoadBuffNextPhoto()
{
    if ((photoIndex + 1) < photoCount) {
        InitImageBuffer();
        setTimeout('DisplayLoadProcess();', 200);
        $("#loadingNext").data("process", true); // probiha nacitani fotky
        imageBuffer.onload = AfterLoadBuffNextPhoto;
        imageBuffer.src = storage + "images/" + photos[photoIndex + 1]["fileName"];
    }
}

function AfterLoadBuffNextPhoto()
{
    $("#loadingNext").data("process", false); // nacitani fotky dokonceno
    $("#loadingNext").css("visibility", "hidden"); // schovani progressbaru
    // tuhle bude zobrazeni dalsi fotky pri slideshow
    slideshow.setNextPhotoLoaded(true);
}

// nastavi obrazek pouze nahledum, ktere jsou videt
function ShowPictures()
{
    var thumbX = 120;
    var thumbY = 130;
    var tmp = GetPageSize();
    var scroll = getScrollY();
    var winW = tmp[0], winH = tmp[1];
    
    var inLine = 7;
    var inRows = winH / thumbY;
    inRows -= inRows % 1;
    inRows++;
    var from = (scroll / thumbY - scroll % 1 - 2) * inLine;
    from -= from % 1;
    var to = inLine * (inRows + 1) + (scroll / thumbY - scroll % 1) * inLine;
    
    if (from < 0) {
        from = 0;
    }
    if (to > photoCount) {
        to = photoCount;
    }
    
    for (var i = from; i < to; i++) {
        SetPicture(i);
    }
}

// zobrazi cekaci animaci, pokuj jiz neni zobrazena
function ShowWait()
{
    if (waitInfoShowed == false) {
        waitInfoShowed = true;
        setTimeout("ShowWaitAfterTimeout();", /* timeout, kdy se ma cekat na zobrazeni cekatka, pokud je schovane */
		200); /* jeste pred vyprsenim tohoto timeoutu, proste se nezobrazi */
    }
}

function ShowWaitAfterTimeout()
{
    if (waitInfoShowed == true) {
    }
}

// schova cekaci animaci, pokud se nic nenahrava
function HideWait()
{
    if (waitInfoShowed == true) {
        waitInfoShowed = false;
    }
}

// nastavi nahledu prislusny obrazek
function SetPicture(index)
{
    if (index >= 0) {
        var imgTmp = document.getElementById('pid' + index);
        if (imgTmp != null && imgTmp.style.backgroundImage == "") {
            imgTmp.style.backgroundImage = 'url("' + storage + 'thumb/' + photos[index].fileName + '")';
        }
    }
}

// vrati velikost vnitrniho okna (nepocita velikost i s posuvniky)
function GetPageSize()
{
    var myWidth = 0;
    var myHeight = 0;
    if (typeof(window.innerWidth) == 'number') { //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight)) { //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [myWidth, myHeight];
}

// vrati pozici vertikalniho posuvniku
function getScrollY()
{
    var scrOfY = 0;
    if (typeof(window.pageYOffset) == 'number') {
        // Netscape compliant
        scrOfY = window.pageYOffset;
    }
    else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        // DOM compliant
        scrOfY = document.body.scrollTop;
    }
    else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        // IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
    }
    else {
        // IE6 scrool fix
        var divScroll = document.getElementById("body2");
        if (divScroll != null) {
            scrOfY = divScroll.scrollTop;
        }
    }
    return scrOfY;
}

// nastavi pozici vertikalniho posuvniku
function setScrollY(scrOfY)
{
    if (getBrowser() == 'ff') {
        scrollTo(0, scrOfY);
    }
    else {
        if (getBrowser() == "ie") {
            var divScroll = document.getElementById("body2");
            if (divScroll != null) {
                divScroll.scrollTop = scrOfY;
            }
        }
        else if (getBrowser() == "ie7") {
            document.documentElement.scrollTop = scrOfY;
        }
        else {
            document.body.scrollTop = scrOfY;
        }
    }
}

function GenerateIndex()
{
    for (var i = 0; i < photoCount; i++) {
        var name = unescape(photos[i].fileName);
        nameToIndex[name] = i;
    }
}

function getBrowser()
{
    if (browser == "") {
        if (navigator.userAgent.indexOf("MSIE 7") != -1) {
            browser = "ie7";
        }
        else if (navigator.userAgent.indexOf("MSIE") != -1) {
            browser = "ie";
        }
        else if (navigator.userAgent.indexOf("Mozilla") != -1) {
            browser = "ff";
        }
        else if (navigator.userAgent.indexOf("Opera") != -1) {
            browser = "o";
        }
        else if (navigator.userAgent.indexOf("HotJava") != -1) {
            browser = "java";
        }
    }
    return browser;
}

// po nahrati stranky
function AfterLoad()
{		
	$("div#photoList > a > div").css("background-image", "");
    
    // priprava pole fotek
    photoCount = photos.length;
    
    // veve: pridani klaves // 2008-06-15 15:17:39
    link_set('up', 'javascript:slideshow.stop();ShowAlbum();');
    link_set('previous', 'javascript:slideshow.stop();ShowPhotoPrevious(photoIndex);');
    link_set('next', 'javascript:slideshow.stop();ShowPhotoNext(photoIndex);');
    
    // navazani udalosti na elementy
    $("a#photoPrevious").click(function()
    {
        slideshow.stop();
        ShowPhotoPrevious(photoIndex);
        return false;
    });
    $("a#photoShowAll").click(function()
    {
        slideshow.stop();
        ShowAlbum();
        return false;
    });
    $("a#photoNext").click(function()
    {
        slideshow.stop();
        ShowPhotoNext(photoIndex);
        return false;
    });
    $("img#detailImage").click(function()
    {
        slideshow.stop();
        ShowPhotoNext(photoIndex);
        return false;
    });
    $("img#detailImage").load(function()
    {
        AfterLoadPhoto();
    });
    $("#photoList a").click(function(event){
		if (typeof newAlbumCover != 'undefined' && newAlbumCover.settingAlbumCover) {
			return false;
		}
		if (!disabledShowPhotoDetail) {
			$(this).data('thumbClicked',true)
			var id = $(this).children().filter("div").get(0).id.substr(3); // extrahuje cislo fotky z IDcka formatu pid123
			//var id = $("#photoList a").index(this);
			StoreScroll(id);
		} else {
			disabledShowPhotoDetail = false;
		}
        return false;
    });
    
    $("#photoNext").after(" <img id='loadingNext' src='http://www." + domain + "/img/mikro/load.gif' alt='' />");
    $("#loadingNext").css("visibility", "hidden");
    
    // > veve: prohlizeni v kosiku -- asi bude lepsi nejak sjednotit..
    $("DIV.cartList DIV.cartItem A.printPhoto").click(function(event)
    {
        StoreScroll($(this).attr('id').substr(3)); // extrahuje cislo fotky z IDcka formatu pid123
        return false;
    });
    if ($("DIV.cartList").size() > 0) {
        // Kosik je aktivni
        $("#photoShowAll").after(' | <a id="photoPrint" href="#">tisk</a> ');
        $('#photoPrint').click(photoPrint);
    }
    
    // BEGIN slideshow init
    $("#photoShowAll").after(' | <a id="slideshow" href=""></a><span id="slideshowSpeedControl" />');
    slideshow.init($("#slideshow"));
    // END slideshow init
    
    GenerateIndex();
    ShowPictures();
    window.onscroll = ShowPictures;
    window.onresize = ShowPictures;
	
	//custom resize event kvuli IE, spousti se i pri zmene rozmeru body
	$(window).bind('resize', function(){ 
		if ($(window).height() != detailWindowHeight || $(window).width() != detailWindowWidth ) {
			(function(){detailWindowWidth = $(window).width();detailWindowHeight = $(window).height();})();
			
			if ($('body').is('.mikro') && photo_exists(actualImageIndex)) {
				var resizedPhotoSize = ResizeHRImage(actualImageIndex);
				applyNewPhotoDimentions(resizedPhotoSize, $('#detailImage'), $('#detailImageFrame'));
			}			
		}
    });
			
    if (onLoadHistoryHash != '') {
        if (onLoadHistoryHash != null && nameToIndex[onLoadHistoryHash] != null && onLoadHistoryHash != 'album') {
            ShowPhotoDetail(nameToIndex[onLoadHistoryHash]);
        }
        else {
            ShowAlbumThumbs();
        }
    }
    else {
        onLoadHistoryHash = ' ';
		//docasne reseni pro IE, nezobrazuje komentare z ShowAlbumThumbs po nacteni alba
		if (jQuery.browser.msie) {
			if (typeof CommentManager != 'undefined') {
				$('#albumComments div.commentList').empty(); //nutno odebrat komentare k drive zobrazene
				CommentManager.Show(new CommentView(albumUserID, albumID, null,'album'));		
			}		
		}	
    }
    
    $(window).unload(function() {
    	var viewCount = 0;
    	var viewedPhotoCount = 0;
    	for (i in viewedPhotos) {
    		if (i >= 0 && i < photoCount) {
  				viewCount += viewedPhotos[i];
  				viewedPhotoCount += 1;
  			}
   		}
   		var stopTime = new Date();
   		var sec = Math.round((stopTime.getTime() - startTime.getTime()) / 1000);
    	$.post("/_www_root_/ajax/stats.php", { action: "albumView", albumID: albumID, authUserID: authUserID, albumUserID: albumUserID, photoCount: photoCount, viewCount: viewCount, viewedPhotoCount: viewedPhotoCount, time: sec });
	}); 
	
	//zobrazeni stavoveho radku s patricnym uvodnim textem
	albumShowInfoMsg.init();
	//oznaceni uvodni fotky alba rameckem
	$('#photoList a#p_' + albumCoverId + ' div').css('border', '1px solid #ff531a');
	
}

slideshow = {
    activePlaying: false,
    interval: 3000,
    minInterval: 1000,
    maxInterval: 10000,
    speedChangeCoef: 1000,
    waitingForNextPhoto: false,
    nextPhotoLoaded: false,
    init: function(element) {
        var intervalFromCookie = parseInt(cookiesUtil.get('slideshow_time'));
        if (intervalFromCookie >= this.minInterval && intervalFromCookie <= this.maxInterval)
			this.interval = intervalFromCookie;
        element.click(function() { slideshow.toggle(); return false; });
        this.onChangeState(this.activePlaying);
    },
    toggle: function() {
        if (this.activePlaying) {
            this.stop();
        } else {
            this.start();
        }
    },
    start: function() {
        if (photoIndex == -1) {
            ShowPhotoNext(0);
        }
        this.activePlaying = true;
        this.timer = setInterval(function() {
        	if (slideshow.nextPhotoLoaded || photoIndex == photoCount - 1) {
            	ShowPhotoNext(photoIndex);
            } else {
            	slideshow.waitingForNextPhoto = true;
			}
			if (photoIndex == -1)
            	slideshow.stop();
        }, this.interval);
        this.onChangeState(true);
    },
    stop: function() {
        this.activePlaying = false;
        clearTimeout(this.timer);
        this.onChangeState(false);
    },
    changeTime: function(newInterval) {
        newInterval = Math.min(newInterval, this.maxInterval);
        newInterval = Math.max(newInterval, this.minInterval);
        this.interval = newInterval;
        cookiesUtil.set('slideshow_time', this.interval);
        if (this.activePlaying) {
            this.stop();
            this.start();
        }
    },
    speedUp: function() {
        this.changeTime(this.interval - this.speedChangeCoef);
        this.onChangeSpeed();
    },
    speedDown: function() {
        this.changeTime(this.interval + this.speedChangeCoef);
        this.onChangeSpeed();
    },
    setNextPhotoLoaded: function(value)
    {
    	if (value && slideshow.waitingForNextPhoto) {
    		slideshow.waitingForNextPhoto = false;
    		ShowPhotoNext(photoIndex);
    	} else {
			slideshow.nextPhotoLoaded = value;
		}
	},
    onChangeState: function(activePlaying) {
        if (activePlaying) {
            $("#slideshow").html('<img src="http://www.' + domain + '/img/mikro/ico-pause.png" style="vertical-align: -3px; border: none" />');
            $("#slideshow").attr("title", "zastavit");
            $("#slideshowSpeedControl").html(' [<a id="slideshowSpeedUp" href="" title="zrychli">&minus;</a>&nbsp;<span id="speed" />&nbsp;s&nbsp;<a id="slideshowSpeedDown" href="" title="zpomal">+</a>]');
            $("#slideshowSpeedDown").click(function() { slideshow.speedDown(); return false; });
            $("#slideshowSpeedUp").click(function() { slideshow.speedUp(); return false; });
            slideshow.onChangeSpeed();
        } else {
            $("#slideshow").html('<img src="http://www.' + domain + '/img/mikro/ico-play.png" style="vertical-align: -3px; border: none" />');
            $("#slideshow").attr("title", "spustit prezentaci");
            $("#slideshowSpeedControl").html("");
        }
    },
    onChangeSpeed: function() {
    	var time = (slideshow.interval / 1000).toString();
    	while (time.length < 2) time = '<span style="margin-left: 2px;">&nbsp;</span>' + time;
        $("#speed").html(time);
    }
}


//zobrazi stavovy radek s patricnym uvodnim textem
albumShowInfoMsg = {
	messageInner: '<div class="b1f"/><div class="b2f"/><div class="b3f"/><div class="b4f"/><div id="message">' +
				'<span></span><span id="undoLinks" style="display: none;"> | <a id="undoLink" href="#">zpět</a> | ' +
				'<a id="revertLink" href="#">původní pořadí</a></span>' +
				'<span id="errorMsg" style="display: none;">Nelze navázat spojení se serverem, navazuji nové spojení... | ' +
				'<a id="postCancelLink" href="#"> zrušit</a></span></div><div class="b4f"/><div class="b3f"/><div class="b2f"/><div class="b1f"/>',
	msgElement: '#message span:first', 
				
	init: function(){
		this.show();
	},
	show: function(){
		if(typeof albumThumbsOrder != 'undefined' || ($('div.cartList').length > 0)){
			$('div#messageOuter').html(albumShowInfoMsg.messageInner);
			this.setText();
		}	
	},
	setText: function(){
		if($("div.cartList").length > 0){
			 $(albumShowInfoMsg.msgElement).text('vyberte fotografie pro tisk a klikněte na Přidat do košíku | vybráno: ' + selectedPhotos);
		}
		else if(typeof albumThumbsOrder != 'undefined'){
			$(albumShowInfoMsg.msgElement).text('Pořadí fotek v albu lze změnit přetažením myší');
		}
	}
}

embedVideo = {
    getVideoHTML: function(photoID, width, height, autoStartValue) {
        return '<embed width="' + width + '" height="' + (height + 45) + '" type="application/x-shockwave-flash" src="http://www.' + domain + '/flash/rajce-player-test3.swf"' +
			   'flashvars="configURL=http%3A%2F%2Fwww.' + domain + '%2Fajax%2Fvideoxml.php?id=' + photoID + '&initVolume=0.7&rtmpt=true&autostart=' + autoStartValue + '" quality="high" allowfullscreen="true" allowscriptaccess="always"/>'
    }
}

//posunuti stranky pri
scrollDetailFrameIntoView = function(detailFrame) {
	var docTop = $(window).scrollTop();
	var docHeight = $(document).height();
    var docAt = docTop + $(window).height();
	var windowHeight = $(window).height();
	var photoFrameHeight = $('#detailImageFrame').height();
	var photoFrameOffset = $('#detailImageFrame').offset();
	
	var photoFrameEndToWindowEnd = (docTop + windowHeight) - (photoFrameOffset.top + photoFrameHeight);
	
	if ( photoFrameEndToWindowEnd < 0 ) {
		$(window).scrollTo( detailFrame , 1000, {offset:-50} );
	}
}

$(document).ready(AfterLoad);
