/// <reference path="../_references.js" />

function media() {

    // Teaser
    media.teaser();
    media.teaserVideo();
    media.wowAnimation();

    // Images Content
    $("img[class*='imgcnt'], .images img").each(function () {
        var img = $(this);

        if (img.hasClass("noGal")) {
            return true;
        }

        // Wraps images with img-wrapper container (Quelle + Caption)
        var imgUrl = img.attr("src");
        imgUrl = $.param.querystring(imgUrl, "mw=1500", 2);

        var imgClasses = img.attr("class");
        if (!imgClasses) {
            imgClasses = "imgcnt";
        }

        var imgWrapper = $("<div class='" + imgClasses + " img-wrapper'><a href='" + imgUrl + "' caption='" + (img.attr("title") ? img.attr("title") : "") + "' class='gal fancy' rel='group'></a></div>");
        var imgLnk = imgWrapper.find("a");

        // Vorhandens Bild clonen und .imgcnt klasse entfernen damit es nicht nochmal verarbeitet wird
        var newImg = img.clone();
        newImg.removeAttr("class").removeAttr("align");
        newImg.attr("src", $.param.querystring(imgUrl, "mw=1250", 2));
        newImg.removeClass("imtcnt");

        imgLnk.append(newImg);

        // Copyright
        if (newImg.attr("title")) {
            imgWrapper.append($("<div class='alt'>" + newImg.attr("title") + "</div>"));

            imgLnk.attr("title", newImg.attr("alt") + (newImg.attr("longdesc") ? " (" + newImg.attr("longdesc") + ")" : ""));
        }

        // Descritpion
        if (newImg.attr("longdesc")) {
            imgWrapper.append("<div class='longdesc'>" + newImg.attr("longdesc") + "</div>");
        }

        img.replaceWith(imgWrapper);

    });

    // Fancybox Images
    $(".fancy, a.gal").fancybox({
        autoPlay: false,
        mouseWheel: true,
        arrows: true,
        padding: 0,
        openEffect: 'elastic',
        closeEffect: 'elastic',
        helpers: {
            title: {
                type: "outside"
            },
            overlay: {
                css: {
                    'background': 'rgba(0, 0, 0, 0.8)'
                },
                locked: false
            },
            thumbs: {
                width: 50,
                height: 50
            }
        },
        beforeLoad: function () {
            this.title = $(this.element).attr('caption');
        }
    });

    // Fancybox Iframe in Pop-Up
    $(".fancyframe").fancybox({
        maxWidth: 800,
        maxHeight: 600,
        fitToView: false,
        width: '70%',
        height: '70%',
        autoSize: false,
        closeClick: false,
        href: $(".fancyframe").attr("action")
    });

}

media.wowAnimation = function () {
    var doInit = false;
    wow = new WOW({
                    boxClass: 'wow',
                    animateClass: 'animated', 
                    mobile: false,
                    live: true
                });

    // Bei Akkordeon Loading keine Animation des Master DIV //  
    var currentQueryParams = AjaxNav.getUrlVars();

    if (!currentQueryParams.item && !currentQueryParams.sq && !$("#master").hasClass("animated") && !isMobile()) {
        $("#teaser").addClass("wow fadeIn");
        $("#teaser").attr("data-wow-duration", "0.6s");
        doInit = true;
    }
    else {
        $("#teaser").removeClass("wow fadeIn");
    }


    $(".wow:not(.letter-animation)").each(function (idx, val) {
        var el = $(this);
        if (!el.attr("data-wow-duration")) {
            el.attr("data-wow-duration", "0.8s");
            doInit = true;
        }
        if (!el.attr("data-wow-offset")) {
            el.attr("data-wow-offset", "100");
            doInit = true;
        }
    });
    $(".delayed-wow").each(function (idx, val) {
        var el = $(this);
        var durationDelayOffset = 0.05;
        if (isMobile()) {
            durationDelayOffset = 0.0;
        }
        var delay = 0 + (idx * durationDelayOffset);
        var delaySec = delay + "s";
        var duration = "0.5s";
        if (isMobile()) {
            el.attr("data-wow-offset", "-40");
            //duration = "1.5s";
            //alert("d", duration);
        }
        else {
            el.attr("data-wow-offset", "10");
        }
        el.attr("data-wow-delay", delaySec);
        el.attr("data-wow-duration", duration);
        
    });

    // H1 Animation pro Wort
    if (!isMobile()) {
        $(".letter-animation").each(function (idx, val) {
            var el = $(this);
            var delay = 0.3 + (idx * 0.2);
            var delaySec = delay + "s";
            el.attr("data-wow-delay", delaySec);
            el.attr("data-wow-duration", "1.2s");
            el.addClass("wow fadeInUpSmall");

        });
    } else {
        // Mobile ist letter Animation buggy
        var title = $("#teaser .h1")[0];
        $(title).attr("data-wow-delay", 0.8);
        $(title).attr("data-wow-duration", "0.5s")
        $(title).addClass("wow");
        $(title).addClass("fadeInDown");

        $(".letter-animation").css("opacity", "1");
    }
    

    if (doInit) {
        wow.init();
    }
}

media.teaserVideo = function () {
    var overlayVideoCnt = $(".videowrapper");
    var overlayVideo = $(overlayVideoCnt).find("video")[0];
    var teaserVideo = $("#video")[0];
    overlayVideo = $("#ifrmVideo");

    // Wenn nach x-Sec Video nicht ready --> Backgroundimage setzten
    if (teaserVideo) {
        setTimeout(function () {
            var ready = teaserVideo.readyState == 4;
            if (!ready) {
                teaserVideo.pause();
                teaserVideo.poster = "";
                var srcEl = $("#video").find("source")[0];
                $(srcEl).attr("src", "");
            }
        }, 2000)
    }

    $(document).click(function (event) {
        if (!$(event.target).closest('.videoframe').length) {
            
            // Wenn Table & Imagevideo (iFrame) 
            if ($(event.target)[0].id != ".videoframe") {
                if (teaserVideo) {
                    teaserVideo.play();
                }
                overlayVideoCnt.hide(400);
                setTimeout(function () {
                    if (!media.inlineIframe) {
                        overlayVideo.attr("src", "");
                    }
                }, 800)
                $("body").css("overflow", "auto");
                $(".infos, #mobilenavBtn, #footer").css("z-index", "600");
                $("#logo, #content").css("z-index", "100");
                $(".logo").css("visibility", "visible");

                clearInterval(media.focusInterval);
            }
        }
        return true;
    })

    $(document).on("click", "#teaser", function (e) {
        var btn = $(".videoLnk")
        if (btn.length == 0) {
            return;
        }
        var btnWidth = btn.width();
        var btnHeight = btn.height();

        var btnTopLeft = btn.offset().left;
        var btnTopRight = btnTopLeft + btnWidth;
        var btnBottomLeft = btnTopLeft + btnHeight;
        var btnBottomRight = btnBottomRight + btnWidth;

        var clickX = e.offsetX;
        var clickY = e.offsetY;

        var verticalOk = (clickY > btn.offset().top && clickY < btn.offset().top + btnHeight);
        var horizontalOk = (clickX > btn.offset().left && clickX < btn.offset().left + btnWidth);
        
        if (verticalOk && horizontalOk) {
            $(".videoLnk").click();
        }
    });
 
    $(".videoLnk").click(function () {
        var videoUrl = "https://player.vimeo.com/video/192621944?autoplay=1";
        
        var imageVideo = $("#video2")[0];
        var teaserVideo = $("#video")[0];

        var teaserVideoSrcEl = $("#video source")
        var imageVideoSrcEl = $("#video2 source")


        overlayVideo.attr("src", videoUrl);
       
        if ((isMobile() && !isTablet()) || !isLandscapeOrientation()) { // oder Tablet hochformat
            $(".swiper-wrapper").html("");
            overlayVideo.prependTo(".swiper-wrapper");
            media.inlineIframe = true;
            $(".videoLnk").hide();
        }
        else {
            // Overlay Video anzeigen
            overlayVideoCnt.show(400);
            if (teaserVideo != null) {
                // Tablet hat kein default TeaserVideo
                teaserVideo.pause();
            }
            $("body").css("overflow", "hidden");
            $("#logo, .infos, #mobilenavBtn, #content, #footer").css("z-index", "-999");

            media.focusInterval = window.setInterval(media.changeFocus, 1000);
        }
    });

    $(".videowrapper .close").click(function (e) {
        $("#video")[0].play();
        overlayVideoCnt.hide(400);
        overlayVideo.attr("src", "");
        $("body").css("overflow", "auto");
        $(".infos, #mobilenavBtn, #footer").css("z-index", "600");
        $("#logo, #content").css("z-index", "100");
        $(".logo").css("visibility", "visible");

        clearInterval(media.focusInterval);
    });

    $(document).keyup(function (e) {
        var video = $("#video");
        if (e.keyCode === 27 && video.length > 0) {
            video[0].play();
            overlayVideoCnt.hide(400);
            overlayVideo.attr("src", "");
            $("body").css("overflow", "auto");
            $(".infos, #mobilenavBtn, #footer").css("z-index", "600");
            $("#logo, #content").css("z-index", "100");
            $(".logo").css("visibility", "visible");

            
            clearInterval(media.focusInterval);
        }
    });
}

media.changeFocus = function () {
    if (document.activeElement.id == "ifrmVideo") {
        document.activeElement.blur();
    }
}

media.teaser = function () {
    // Wenn Teaser bereits initiiert
    var cnt = $('.swiper-container');
    if (cnt.length && cnt[0].swiper != null) {
        return;
    };

    var sliderParams = {
        // Optional parameters
        direction: 'horizontal',
        loop: false,
        paginationClickable: true,
        //autoplayDisableOnInteraction: true,
        keyboardControl: true,
        effect: 'fade',
        fade: {
            crossFade: true
        },
        iOSEdgeSwipeDetection: true,
        // If we need pagination
        pagination: '.swiper-pagination',

        // Navigation arrows
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',

        // And if we need scrollbar
        //scrollbar: '.swiper-scrollbar',
    };

    // Wenn mehrere Titelbilder Loop aktivieren
    var slides = $(".swiper-slide");
    if (slides.length > 1) {
        sliderParams.loop = true;
        sliderParams.autoplay = 5000;
        sliderParams.speed =1000;
        sliderParams.shortSwipes = true;

        sliderParams.longSwipesRatio = 0.5;
        sliderParams.touchRatio = 0.8;
    }

    var wrapper = $(".swiper-wrapper")[0];
    if (!$(wrapper).hasClass("scale")) {
        $(wrapper).addClass("scale");
    }

    // // Initial Blur
    //$(wrapper).removeClass("blur")

    // Loop Scale Transition
    $(".swiper-wrapper").not(".hasvideo").on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (e) {
        var cssProperty = e.originalEvent.propertyName;

        if (cssProperty == "transform") {
            if ($(wrapper).hasClass("scale")) {
                $(wrapper).removeClass("scale");
            }
            else if (!$(wrapper).hasClass("scale")) {
                $(wrapper).addClass("scale");
            }
        }

    });


    var piSwiper = new Swiper('.swiper-container', sliderParams);
};

Site.Nav.bind("media", "live", media);