/* Globalni promenne */
var imgWidth;
var imgHeight;

var tb_pathToImage = "design/images/thickbox/loadingAnimation.gif";
var imgLoaderText = "Načítám fotografii...";


//on page load call tb_init
$(document).ready(function() {
    tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
    imgLoader = new Image(); // preload image
    imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk) {
    $(domChunk).click(function() {
        var t = this.title || this.name || null;
        var a = this.href || this.alt;
        var g = this.rel || false;
        tb_show(t, a, g);
        this.blur();
        return false;
    });
};

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

    try {
        if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
            $("body", "html").css({ height: "100%", width: "100%" });
            $("html").css("overflow", "hidden");
            if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        } else {//all others
            if (document.getElementById("TB_overlay") === null) {
                $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div><div id='TB_window2'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        }

        
        
        $("body").append("<div id='TB_load'><div id='TB_load_text'>" + imgLoaderText + "</div><img src='" + imgLoader.src + "' /></div>"); //add loader to the page

        $("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity

        $('#TB_load').show(); //show loader
        
        
        if (caption === null) { caption = ""; }
        
        var baseURL;
        if (url.indexOf("?") !== -1) { //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
        } else {
            baseURL = url;
        }

        var queryString = url.replace(/^[^\?]+\??/, '');
        var params = tb_parseQuery(queryString);

        /* Prepocitani rozmeru fotky */
        var marginX = 100;
        var marginY = 150;
        var fullWidth = params['width'];
        var fullHeight = params['height'];
        var maxWidth = document.documentElement.clientWidth - marginX;
        var maxHeight = document.documentElement.clientHeight - marginY;
        var koefWidth = fullWidth / maxWidth;
        var koefHeight = fullHeight / maxHeight;

        var koef = Math.max(koefWidth, koefHeight);

        if (koef > 1) {
            imgWidth = Math.floor(fullWidth / koef);
            imgHeight = Math.floor(fullHeight / koef);

            if (params['navrhy']) {
                imgWidth = fullWidth;
                imgHeight = fullHeight;
            }
        }
        else {
            imgWidth = fullWidth;
            imgHeight = fullHeight;
        }


        TB_WIDTH = imgWidth;
        TB_HEIGHT = imgHeight;

        if (params['navrhy'] && koef > 1) {
            if (imgWidth < maxWidth) {
                TB_WIDTH = parseInt(imgWidth,10) + 17;
            }
            else {
                TB_WIDTH = maxWidth;
            }

            if (imgHeight < maxHeight) {
                TB_HEIGHT = parseInt(imgHeight, 10) + 17;
            }
            else {
                TB_HEIGHT = maxHeight;
            }
        }


        urlNoQuery = url.split('TB_');
        //$("#TB_iframe").remove();


        // Pocet nahledu
        var lastImgUrl = $("a.thickbox:last").attr("href");
        var lastParams = tb_parseQuery(lastImgUrl.replace(/^[^\?]+\??/, ''));
        var lastPos = lastParams["pos"];

        // Aktualni fotka
        var actualPos = parseInt(params["pos"], 10);

        
        // Nacteni odkazu a popisku predchoziho a dalsiho nahledu
        var prevPos = actualPos - 2;
        if (prevPos >= 0) {
            prevHref = $("a.thickbox:eq(" + prevPos + ")").attr("href");
            prevCaption = $("a.thickbox img:eq(" + prevPos + ")").attr("alt");
        }
        else {
            prevHref = "";
            prevCaption = "";
        }

        var nextPos = actualPos;
        if (nextPos < lastPos) {
            nextHref = $("a.thickbox:eq(" + nextPos + ")").attr("href");
            nextCaption = $("a.thickbox img:eq(" + nextPos + ")").attr("alt");
        }
        else {
            nextHref = "";
            nextCaption = "";
        }
    

        var iframeScroll = "no";
        if (params['navrhy'] && koef > 1) { iframeScroll = "auto"; }

                        
        $("#TB_window").replaceWith("<div id='TB_window'><div id='TB_title'><div id='TB_windowTop'><div></div></div><div id='TB_close' title='Zavřít'>&nbsp;</div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframe' name='TB_iframe" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (TB_WIDTH) + "px;height:" + (TB_HEIGHT) + "px;' scrolling='" + iframeScroll + "'> </iframe></div>");


        // Zobrazeni odkazu na predchozi snimek
        if (prevPos >= 0) {
            $("#TB_windowTop div").append("<a onclick=\"tb_show('" + prevCaption + "',this.href, false);return false;\" href='" + prevHref + "' class='prevImg' title='Předchozí fotografie'>&#160;</a>");
        }
        // Oddelovac
        if (prevPos >= 0 && nextPos < lastPos) {
            $("#TB_windowTop div").append("<span>&#160;&#124;&#160;</span>");
        }
        // Zobrazeni odkazu na dalsi snimek
        if (nextPos < lastPos) {
            $("#TB_windowTop div").append("<a onclick=\"tb_show('" + nextCaption + "',this.href, false);return false;\" href='" + nextHref + "' class='nextImg' title='Další fotografie'>&#160;</a>");
        }
        
        // Pridani popisku fotky, pokud je uveden
        if (caption != "") {// pokud je uveden popisek
            $("#TB_window").append("<div id='TB_windowBottom'>" + caption + "</div>");
        }
        
        $("#TB_close").click(tb_remove);

        // Umisteni fotky na strance
        tb_position();

        // Zavreni obrazku po stisknuti klavesy ESC
        document.onkeyup = function(e) {
            if (e == null) { // ie
                keycode = event.keyCode;
            } else { // mozilla
                keycode = e.which;
            }
            if (keycode == 27) { // close
                tb_remove();
            }
        };

    } catch (e) {
        //nothing here
    }
};


// Zobrazeni fotky
function tb_showIframe() {
    $("#TB_load").remove();
    $("#TB_window").fadeIn(200);
    $("#TB_window").css({ display: "block" });
    $("#TB_iframe").css({ position: "relative", left: "0", top: "0" });
};



// Zavreni fotky
function tb_remove() {
    $("#TB_closeWindowButton").unbind("click");
    $("#TB_window").fadeOut(100, function() { $('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove(); });
    $("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body", "html").css({ height: "auto", width: "auto" });
        $("html").css("overflow", "");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
};

// Umisteni fotky na stred obrazovky
function tb_position() {
    $("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
    if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        $("#TB_window").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
    }
};

// Parsovani retezce v url a ziskani hodnot jednotlivych parametru
function tb_parseQuery(query) {
    var Params = {};
    if (!query) { return Params; } // return empty object
    var Pairs = query.split(/[;&]/);
    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split('=');
        if (!KeyVal || KeyVal.length != 2) { continue; }
        var key = unescape(KeyVal[0]);
        var val = unescape(KeyVal[1]);
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
};
