$(function() {
    
    var currentSlide = 0, jqwin = $(window), jqcaption = $(".caption"),
        margin = 50,
        jqimgcontainer = $(".image-container"),
        jqmainimg = $(".main-image"),
        jqbackdrop = $(".backdrop"),
        jqpath = $(".clip-path"),
        lastSlide = null;
    
    function showSlide() {
        var slide = slides[currentSlide];
        
        if (slide !== lastSlide) {
            jqcaption.find("h2").text(slide.title);
            jqcaption.find("h3").text(slide.author);
            var captiondiv = jqcaption.find(".caption-description");
            captiondiv.empty();
            slide.description.split(/\s*[\r\n]\s*/gm).forEach(function(p) {
                captiondiv.append($("<p>").text(p));
            });
            jqmainimg.attr("xlink:href", slide.image.src);
            jqbackdrop.attr("src", slide.image.src);
            jqpath.attr("d", slide.path);
        }
        
        lastSlide = slide;
        
        if (slide.image && slide.image.width) {
            var pathcoords = slide.path.match(/[\d\.]+/g),
                pathx = pathcoords.filter(function(p,i) {
                    return !(i%2);
                }),
                pathy = pathcoords.filter(function(p,i) {
                    return (i%2);
                }),
                minpx = Math.min.apply(Math,pathx),
                maxpx = Math.max.apply(Math,pathx),
                minpy = Math.min.apply(Math,pathy),
                maxpy = Math.max.apply(Math,pathy),
                ww = jqwin.width(),
                wh = jqwin.height(),
                cw = jqcaption.outerWidth(),
                ch = jqcaption.outerHeight(),
                wi = slide.image.width,
                hi = slide.image.height,
                wp = wi * (maxpx - minpx),
                hp = hi * (maxpy - minpy),
                w1 = ww - 2 * margin, w2 = w1 - cw
                h1 = wh - 2 * margin, h2 = h1 - ch,
                ra = Math.max(
                    Math.min((h1 / hp), (w2 / wp)),
                    Math.min((h2 / hp), (w1 / wp))
                ),
                wa = wp * ra, ha = hp * ra,
                rb = Math.max(ww / wi, wh / hi),
                wb = wi * rb, hb = hi * rb,
                xb = (ww - wb) / 2, yb = (wh - hb) / 2;
            jqimgcontainer.css({
                width: wa,
                height: ha
            });
            jqimgcontainer[0].setAttribute("viewBox", [minpx,minpy,(maxpx-minpx),(maxpy-minpy)].join(" "));
            jqbackdrop.css({
                width: wb,
                height: hb,
                left: xb,
                top: yb
            });
            
        }
    }
    
    var playInterval, playing = false;
    
    function toggleSlideShow() {
        clearInterval(playInterval);
        playing = !playing;
        var jqppbtn = $(".play-pause");
        if (playing) {
            jqppbtn.addClass("pause");
            playInterval = setInterval(nextSlide,4000,false);
        } else {
            jqppbtn.removeClass("pause");
        }
        return false;
    }
    
    function nextSlide(resetInterval) {
        if (!!resetInterval && playing) {
            playing = false;
            toggleSlideShow();
        }
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide();
        return false;
    }
    
    function prevSlide(resetInterval) {
        if (!!resetInterval && playing) {
            playing = false;
            toggleSlideShow();
        }
        currentSlide = (currentSlide > 0 ? currentSlide - 1 : slides.length - 1);
        showSlide();
        return false;
    }
    
    var hideTO, isInArrow = false, jqControls = $(".arrow-wrap,.top-controls");
    function resetTO() {
        clearTimeout(hideTO);
        if (!isInArrow) {
            hideTO = setTimeout(function() {
                jqControls.hide();
            }, 1000);
        }
    }
    $("body").mousemove(function() {
        jqControls.show();
        resetTO();
        return false;
    });
    jqControls.hover(function() {
        isInArrow = true;
        resetTO();
    }, function() {
        isInArrow = false;
        resetTO();
    });
    
    $(".left-arrow").click(prevSlide);
    $(".right-arrow").click(nextSlide);
    
    function fullScreen() {
        var isFull = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen || false;
        if (isFull) {
            (document.cancelFullScreen || document.mozCancelFullScreen || document.webkitCancelFullScreen || function(){}).call(document);
        } else {
            (document.body.requestFullScreen || document.body.mozRequestFullScreen || document.body.webkitRequestFullScreen || function(){}).call(document.body);
        }
        showSlide();
        return false;
    }
    
    $(".full-screen").click(fullScreen);
           
    if ( typeof document.fullScreen === "undefined"
        && typeof document.mozFullScreen === "undefined"
        && typeof document.webkitIsFullScreen === "undefined") {
        $(".full-screen").remove();
    }
        
    $(".play-pause").click(toggleSlideShow);
    
    slides.forEach(function(slide, k) {
        if (!slide.path) {
            slide.path = "M0 0L1 0L1 1L0 1Z"
        }
        slide.image = new Image();
        slide.image.onload = function() {
            if (k === currentSlide) {
                showSlide();
            }
        };
        slide.image.src = imgurlbase + slide.src;
    });
    
    showSlide();
    
    jqwin.resize(showSlide);
    
    $(document).keydown(function(e) {
        if (e.keyCode === 122) { // F11
            fullScreen();
            return false;
        }
        if (e.keyCode === 32) { // Space
            jqControls.show();
            resetTO();
            toggleSlideShow();
            return false;
        }
        if (e.keyCode === 37) { // Left-Arrow
            prevSlide(true);
            return false;
        }
        if (e.keyCode === 39) { // Right-Arrow
            nextSlide(true);
            return false;
        }
    });
    
});