
$(function() {

    function formatCaption(title, currentArray, currentIndex, currentOpts) {
        var captionElement = document.getElementById(title);
        return captionElement.innerHTML;
    }

    function scale(w, h, max) {
        if (w > h) {
            return { w : Math.floor(max), h: Math.floor((max * h + max / 2) / w) };
        } else {
            return { w: Math.floor((max * w + max / 2) / h), h: Math.floor(max) };
        }
    }


    function encUri(str) {
       return encodeURI(str)
                 .replace(/%5B/g, "[")
                 .replace(/%5D/g, "]")
                 .replace(/[!'()*?&#]/g, function (c) {
                    return "%" + c.charCodeAt(0).toString(16).toUpperCase();
                 });
    }

    function renderGrid(data, textStatus) {

        var container = $("#container");
        container.empty();
        $("#name").text(data.name);
        document.title = data.name;

        var thmb = 250;
        var picSize = 800;
        var movieSize = 640;
        var prevName = null, thisName;

        function updateButton(selector, direction, destination) {
            var imgName = destination ? direction : direction + "-inactive",
                imgUrl = "/photo/assets/" + imgName + ".png",
                imgElement = $(selector),
                isWrapped = imgElement.parent().get()[0].tagName == "A",
                anchor = isWrapped ? imgElement.parent() : $("<a></a>");
            if (destination) {
                anchor.attr("href", encUri("/photo/album" + destination + ".album") + location.search);
                if (!isWrapped) {
                    imgElement.wrap(anchor);
                }
            } else {
                if (isWrapped) {
                    imgElement.unwrap();
                }
            }
            imgElement.attr("src", imgUrl);
        }

        $("#entryName").text(data.name);
        $("#arrowLeft").attr(data.name);
        updateButton("#arrowLeft", "left", data.prev);
        updateButton("#arrowUp", "up", data.parent);
        updateButton("#arrowRight", "right", data.next);
        if (location.search) {
            let params = new URL(location.href).searchParams;
            if (params.has("q")) {
                $("#searchBox").val(params.get("q"));
            }
        }


        $.each(data.contents, function(idx, entry) {

            if (data.groupPrefix && entry.type == "dir") {
                thisName = entry.earliest;
                if (prevName != null && prevName != thisName) {
                    $("<hr/>").appendTo(container);
                    prevName = null;
                }
                if (prevName == null) {
                    $("<h2></h2>").text(thisName).appendTo(container);
                    prevName = thisName;
                }
            }

            var dim = scale(entry.width, entry.height, thmb);
            var href, poster;
            if (entry.thumbtype == "movie") {
                href = "/photo/album" + encUri(entry.path) + ".movie";
                poster = "/photo/album" + encUri(entry.path) + ".frame";
            } else {
                href = "/photo/album" + encUri(entry.path) + "?size=" + picSize;
                poster = "/photo/album" + encUri(entry.path);
            }
            var imgTag = $("<img/>");
            imgTag.addClass(entry.type + "pic")
            .attr("src", poster + "?size=" + thmb)
            .attr("width", dim.w)
            .attr("height", dim.h)
            .attr("border", "0");
            var anchor = $("<a/>");
            anchor.addClass("ss")
            .attr("id", "ent" + idx)
            .attr("href", href)
            .attr("title", entry.name)
             anchor.append(imgTag);


            var gridDiv = $("<div></div>").addClass("grid");

            gridDiv.append($("<span></span>").addClass("name").text(entry.name), "<br>\n", $("<div class=\"imgborder\"></div>").append(anchor))

            var captionP = $("<p></p>").addClass("caption");
            captionP.attr("id", entry.name);
            if (entry.caption) {
                captionP.text(entry.caption);
            }
            captionP.appendTo(gridDiv);

            gridDiv.appendTo(container);

            switch (entry.type) {
            case "movie":
            case "image":
                var largeDim = scale(entry.width, entry.height, picSize);
                var options = {
                    'titlePosition' : 'inside',
                    'transitionIn'  : 'elastic',
                    'transitionOut' : 'elastic',
                    'easingIn'      : 'easeInQuad',
                    'easingOut'     : 'easeOutQuad',
                    'titleFormat'   : formatCaption,
                    'width'         : largeDim.w,
                    'height'        : largeDim.h,
                    'type'          : entry.type,
                    'href'          : href
                };
                if (entry.thumbtype == "movie") {
                    options['poster'] = poster + "?size=" + largeDim.w + "w";
                }
                $("#ent" + idx).attr("rel",  "album").fancybox(options);
                break;
            case "dir":
                $("#ent" + idx).attr("href", location.pathname.replace(/\.album?($|\?)/, "/" + entry.name + ".album"));
                break;
            }


	    });


        var selectedImg = window.location.search;
        var selectedPos = undefined;
        if (/^\?focus=/.test(selectedImg)) {
            selectedImg = selectedImg.substring('?focus='.length);
            $("a.ss").each(function(index) {
                if (selectedImg == $(this).attr("title")) {
                    selectedPos = index;
                }
            });
        }

        if (selectedPos !== undefined) {
            $("#ent" + selectedPos).trigger('click');
        }
    }


    $("#search").on("submit", function () {
        var searchStr = "?q=" + encUri($("#searchBox").val());
        history.pushState({ }, null, searchStr);
        $.getJSON(location.pathname.replace(/\.album(\?|$)/, '.json') + searchStr, renderGrid);
        return false;
    });

    function resetSearch() {
        $("#searchBox").val("");
        history.pushState({ }, null, location.pathname);
        $.getJSON(location.pathname.replace(/\.album(\?|$)/, '.json'), renderGrid);
        return false;
    }
    $("#search").on("reset", resetSearch);
    $("#searchBox").keyup(function (e) {
        if (e.key === "Escape") {
            resetSearch();
        }
    });


    $.getJSON(location.pathname.replace(/\.album(\?|$)/, '.json') + location.search, renderGrid);



});
