$(function() {
    
    var currentSlide = 0, jqwin = $(window), jqcaption = $(".caption"),
        margin = 50, jqmainimg = $(".main-image"), jqbackdrop = $(".backdrop"),
        lastSlide = null;
    
    function showSlide() {
        var slide = slides[currentSlide];
        
        if (slide !== lastSlide) {
            jqcaption.find("h2").text(slide.title);
            jqcaption.find("h3").text(slide.author);
            jqcaption.find("p").text(slide.description);
            jqmainimg.attr("src", slide.image.src);
            jqbackdrop.attr("src", slide.image.src);
        }
        
        lastSlide = slide;
        
        if (slide.image && slide.image.width) {
            var ww = jqwin.width(),
                wh = jqwin.height(),
                cw = jqcaption.outerWidth(),
                ch = jqcaption.outerHeight(),
                wi = slide.image.width,
                hi = slide.image.height,    
                w1 = ww - 2 * margin, w2 = w1 - cw
                h1 = wh - 2 * margin, h2 = h1 - ch,
                ra = Math.max(
                    Math.min((h1 / hi), (w2 / wi)),
                    Math.min((h2 / hi), (w1 / wi))
                ),
                wa = wi * ra, ha = hi * ra,
                rb = Math.max(ww / wi, wh / hi),
                wb = wi * rb, hb = hi * rb,
                xb = (ww - wb) / 2, yb = (wh - hb) / 2;
            jqmainimg.css({
                width: wa,
                height: ha
            });
            jqbackdrop.css({
                width: wb,
                height: hb,
                left: xb,
                top: yb
            });
            
        }
    }
    
    function nextSlide() {
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide();
        return false;
    }
    
    function prevSlide() {
        currentSlide = (currentSlide > 0 ? currentSlide - 1 : slides.length - 1);
        showSlide();
        return false;
    }
    
    var hideTO, isInArrow = false, jqArrows = $(".arrow-wrap");
    function resetTO() {
        clearTimeout(hideTO);
        if (!isInArrow) {
            hideTO = setTimeout(function() {
                jqArrows.hide();
            }, 1000);
        }
    }
    $("body").mousemove(function() {
        jqArrows.show();
        resetTO();
        return false;
    });
    jqArrows.hover(function() {
        isInArrow = true;
        resetTO();
    }, function() {
        isInArrow = false;
        resetTO();
    });
    
    $(".left-arrow").click(prevSlide);
    $(".right-arrow").click(nextSlide);
    
    slides.forEach(function(slide, k) {
        slide.image = new Image();
        slide.image.onload = function() {
            if (k === currentSlide) {
                showSlide();
            }
        };
        slide.image.src = imgurlbase + slide.url;
    });
    
    showSlide();
    
    jqwin.resize(showSlide);
    
});