///// <reference path="../_references.js" />

// AjaxNav Config
AjaxNav.preventScrollAnimation = true;


function content() {
    $('#video').bind('contextmenu', function () { return false; });

    content.responsiveTables();
    //content.modulesFixed();
    content.extendListItemClicks();
    content.addTopScroller();
    content.actionButton();
    content.mobilenav();
    //content.contentPosition();
    content.animateFormLabels();


    //// PARALLAX EFFEKT
    $('.parallax-window').parallax();
    content.updateActiveParallaxItem();
    content.parallaxNavigation();

    // Bei Klick auf active NavItem Navigation schließen
    var main = $("#mainnav");
    main.find("a.active").each(function () {
        $(this).click(function () {
            content.closeNavigation();
        });
    });

    // Toggle Class
    $("#header").unbind("hover").hover(function () {
        $(this).toggleClass("over");
    });

    //// init Masonry (Bildergalerie)
    //var grid = $('.list.images .items').masonry({
    //    columnWidth: '.grid-sizer',
    //    itemSelector: '.grid-item',
    //    percentPosition: true
    //});
    //// layout Isotope after each image loads
    //grid.imagesLoaded().progress(function () {
    //    grid.masonry('layout');
    //});

    // Tabs
    var tabs = $('ul.tab-menu li');
    tabs.click(function (event) {
        event.preventDefault();
        var tab_id = $(this).attr('data-tab');

        tabs.removeClass('current');
        $('.tab-content').removeClass('current');

        $(this).addClass('current');
        $("#" + tab_id).addClass('current');
    })

    // Parallax Hotfix IE / EDGE
    if (navigator.userAgent.match(/MSIE/i) || navigator.userAgent.match(/Trident\/7./) || navigator.userAgent.match(/Edge\/12./)) {
        $('body').on("mousewheel", function () {
            event.preventDefault ? event.preventDefault() : (event.returnValue = false); //IE kennt teilweise kein preventDefault()
            var wd = event.wheelDelta;
            var csp = window.pageYOffset;
            window.scrollTo(0, csp - wd);
        });
    }
}

content.contentPosition = function () {
    $("#content").css({ "margin-top": $("#teaser").height() })
}

// Effekte Formular-Labels
content.animateFormLabels = function () {

    // Form Absolut (Label-Positionierung innerhalb Input)
    $("input, textarea").focusout(function () {
        var label = $(this).parent().find("label").not("label.checkbox, .noAbs, .txt");
        if ($(this).val() === "") {
            label.animate({ "top": "13px", "font-size": "16px", "opacity": "1" }, 200);
        } else {
            label.css({ "top": "-1px", "font-size": "10px", "opacity": "0.5" }, 200);
        }
    });

    $("input, textarea").focus(function () {
        var hasValue = $(this).val() != "";
        var label = $(this).parent().find("label").not("label.checkbox, .noAbs, .txt");

        if (!hasValue) {
            label.animate({ "top": "-1px", "font-size": "10px", "opacity": "0.5" }, 200);
        }
    });


    var dpSelector = $("input[name=Date]");
    dpSelector.datepicker('option', {
        beforeShow: function () {
            dpSelector.expandLabel();
        },
        onClose: function () {
            dpSelector.reduceLabel();           
        }
    })
    
};
$.fn.expandLabel = function () {
    $(this).getFormLabel().animateIn();
}

$.fn.reduceLabel = function () {
    var hasValue = $(this).datepicker("getDate") != null;
    if (!hasValue) {
        $(this).getFormLabel().animateOut();
    }
}
$.fn.getFormLabel = function () {
    var formLabel = $(this).parents(".form-group").find("label").not("label.checkbox, .noAbs");
    return formLabel;
}

$.fn.animateIn = function () {
    $(this).animate({ "top": "-1px", "font-size": "10px", "opacity": "0.5" }, 200);
}
$.fn.animateOut = function () {
    $(this).animate({ "top": "13px", "font-size": "16px", "opacity": "1" }, 200);
}


// Ausklappnavigation
content.mobilenav = function () {
    var button = $("#mobilenavBtn");
    button.unbind("click").click(function () {
        content.toggleNavigation();
    });
}

content.toggleNavigation = function () {
    var mobilenav = $("#navigation");

    if (!mobilenav.hasClass("open")) {
        content.openNaviation();
    } else {
        content.closeNavigation();
    }
}

content.openNaviation = function () {
    var mobilenav = $("#navigation");
    var button = $("#mobilenavBtn");

    mobilenav.addClass("open");
    button.addClass("active")
    mobilenav.removeClass("close");
    $("#master").addClass("open");
}

content.closeNavigation = function () {
    var mobilenav = $("#navigation");
    var button = $("#mobilenavBtn");

    button.removeClass("active")
    mobilenav.addClass("close");
    mobilenav.removeClass("open");
    $("#master").removeClass("open");
}

content.parallaxNavigation = function () {
    $(document).on('click', '.page-menu a', function (event) {
        event.preventDefault();
        var page = $('html, body');

        if ($("body").hasClass("scrolling")) {
            // Stop Scrolling
            page.stop();
        }
        $("body").addClass("scrolling");

        var minOffset = 500;
        var offset = 50;
        var lnk = $('[name="' + $.attr(this, 'href').substr(1) + '"]');
        var wHeight = $(window).height();
        var cntEl = lnk.closest(".parallax-content.item");

        if (cntEl.length == 0) {
            cntEl = $("#content .section.top");
        }
        var cntHeight = cntEl.height();
        offset = wHeight - cntHeight;

        if (wHeight - cntHeight < minOffset) {
            offset = minOffset;
        }

        $('html, body').animate({
            scrollTop: cntEl.offset().top - offset,
        }, {
            duration: 500,
            complete: function () {
                page.removeClass("scrolling");
            }
        }
        );
    });
}
// Suche
content.optimizeSearch = function () {
    $("#txtSearch").siteSearch({
        layerTarget: "#search-field"
    });
    // SUCHE
    $("#search-field").on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (e) {
        $("#txtSearch").focus();
    });
    $("#check-search").click(function () {
        $("#txtSearch").focus();
    });
    // Check if Search Field is active, close on document click
    $(document).click(function (event) {
        if (!$(event.target).closest('#search-field').length) {
            if ($(event.target)[0].id != "check-search") {
                var chk = $("#check-search");
                chk.attr("checked", false);
                $("#header, .search-field").removeClass("open");
            }
        }
        if (!$(event.target).closest('#search').length) {
            if ($(event.target)[0].id != "header") {
                var header = $("#header");
                header.removeClass("open");
            }
        }
    })
}

// Tap Navigation 
content.tapNavigation = function () {
    // MOBILE TA
    $("a.lvl1").click(function () {
        var parent = $(this).parent();
        var navOpen = parent.hasClass("mobileOpen");
        if (isMobile() && !navOpen) {
            parent.addClass("mobileOpen");
            return false;
        }
        parent.removeClass("mobileOpen");
        return true;
    });
}

// Action Button
content.actionButton = function () {
    function leave(e, fromWrapper, fromIcons) {
        var iconContainer = $(".fab-icons");
        var icons = $(".buttons:not(.fab-main)");

        if (!fromWrapper && !$(e.toElement).hasClass("float-action-button")) {
            icons.removeClass("fab-visible");
        }
        else if (fromWrapper && !$(e.toElement).hasClass("fab-main-wrapper")) {
            if (icons.hasClass("fab-visible")) {
                icons.removeClass("fab-visible")
            }
        }
    }

    $(".fab-main").click(function () {
        var iconContainer = $(".fab-icons");
        iconContainer.css("opacity", "1");

        var icons = $(".buttons");
        icons.toggleClass("fab-visible");

    }).mouseleave(function (e) {
        leave(e);
    })

    $(".float-action-button .buttons:not(.fab-main)").mouseleave(function (e) {
        leave(e, false, true);
    });

    $(".fab-icons").mouseleave(function (e) {
        leave(e, true);
    })
}

// Elemente vollflächig anklickbar
content.extendListItemClicks = function () {
    // List Item Click
    var list = $(".list.box, .list.box2");
    list.find(".item").each(function () {
        var t = $(this);
        t.css("cursor", "pointer");
        t.click(function (e) {
            if (e.target.localName != "a" && t.find(".edit").length == 0) {
                //AjaxNav.go($(this).find("a:first").attr("href"));
                $(this).find("a:first").click();
            }
        });
    });
}

// Filter-Dropdowns
content.dropDowns = function () {

    if (content.dropDownsInitialised) {
        return false;
    } else {
        content.dropDownsInitialised = true;
    }

    var filterDropSelector = ".filter.values";

    $(document).on("click", filterDropSelector, function () {
        var drop = $(this);

        // Close other drops
        $(filterDropSelector).each(function () {
            if ($(this).attr("class") != drop.attr("class")) {
                $(this).removeClass("active");
            }
        });

        if (!drop.hasClass("active")) {
            drop.addClass("active");  // Open this drop
        } else {
            drop.removeClass("active"); // Close this drop
        }

        // Close all drops on body click
        if (!document.dropMoveOutInitialised) {
            document.dropMoveOutInitialised = true;

            $(document).on("click tap", function (e) {
                var target = $(e.target);

                // Checks that no drops in click path, then close all
                if (target.closest(filterDropSelector).length === 0) {
                    $(filterDropSelector).removeClass("active");
                }
            });
        }

    });
};

// Elemente fixieren
content.modulesFixed = function () {
    // Modules Fixed
    var headerHeight = 250;
    if ($("#teaser").length > 0) {
        headerHeight = $("#teaser").height() - 70;
    }
    var checkHeight = headerHeight;
    var footerTop = 10;

    if ($("#teaser").length > 0) {
        headerHeight = $("#teaser").height();
    } else {
        headerHeight = 250;
    }

    // Prüfung ob ScrollHöhe >= Bildhöhe (checkHeight)
    var screenWidthValid = ($(window).width() > 678);
    var fixedItem = $("#header");

    var scrollTop = $(document).scrollTop();

    if (scrollTop > checkHeight) {
        fixedItem.addClass("fixed");
        $("#master").addClass("fixed");
        $(".lnk-back").css("opacity", "1");
    } else {
        fixedItem.removeClass("fixed");
        $("#master").removeClass("fixed");
        $(".lnk-back").css("opacity", "0");
    }

    if (scrollTop > footerTop) {
        $("#footer").addClass("fixed");
    } else {
        $("#footer").removeClass("fixed");
    }
};


// Scroll to H1
content.addTopScroller = function () {
    // Teaser-Scroller scrollt zu H1
    $("#scroller").on("click", function () {
        var body = $('body,html');
        body.animate({ scrollTop: 400 }, 800);
    });

    var sLink = $(".lnk-back");
    var body = $("html, body");

    sLink.click(function () {
        body.animate({ scrollTop: 0 }, 800);
        //console.log("clicked")
        return false;
    });
}

// Responsive Tables
content.responsiveTables = function () {

    $("table").not(".responsive").each(function () {
        var table = $(this);
        table.addClass("responsive");

        var tableHead = table.find("thead");
        var tableBody = table.find("tbody");

        tableBody.find("tr").each(function () {
            var tr = $(this);

            tr.find("td").each(function (tdIdx) {
                var td = $(this);
                var th = tableHead.find("tr>:eq(" + tdIdx + ")");
                var tdLabel = td.find("label.title");

                if (tdLabel.length == 0) {
                    tdLabel = $("<label class='title' style='display:none;'>").html(th.html()).prependTo(td);
                }
            });

        });

    });

};

content.updateActiveParallaxItem = function () {
    var conenteElements = $(".parallax-content.item");
    var visibileContent = $("#content .section.top");
    var isTopSection = true;
    conenteElements.each(function () {
        var el = $(this);
        if (el.isOnScreen()) {
            visibileContent = el;
            isTopSection = false;
        }
    });

    // Navigation Item Active Class
    var activeNavItem = $("#page-menu li:first-child a");
    var lnk = $(visibileContent).find("a");
    if (!isTopSection && lnk.length > 0) {
        var lnkName = lnk.attr("name");
        // Navigation Item suchen
        activeNavItem = $("a[href=#" + lnkName + "]");
    }
    // Remove Active Class
    $("#page-menu li a").removeClass("active");
    activeNavItem.addClass("active");
}

// On Resize
$(window).resize(function (e) {
    if (!isMobile()) {
        content.responsiveTables();
        content.contentPosition();
        $('.parallax-window').parallax();
    }
});

// Check if is scrolled
function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = (docViewTop * 2 + $(window).height()) / 2;

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();
    return !(docViewBottom > elemBottom);
}

function elementIsHigher(el, offset) {
    var wHeight = $(window).height();
    var scrollPos = window.frames.scrollY;

    var offset = 70 * wHeight / 100;
    //console.log("70%: ", offset);
    //console.log("scrollPos", scrollPos);

    return scrollPos > offset;
}

// On Scolling
$(window).scroll(function (e) {
    //content.modulesFixed();

    //var video = $("#video")[0];
    //if (video) {
    //    if (elementIsHigher($(".section.top"), 250)) {
    //        video.pause();
    //    }
    //    else {
    //        video.play();
    //    }
    //}

    var scrollTop = $(this).scrollTop();
    var opacity = 1 - (Math.round((scrollTop / 3) * 100) / 10000).toFixed(2);;
    $("#teaser .h1").css({ "opacity": opacity, "margin-top": scrollTop / -2 });

    content.updateActiveParallaxItem();
});

$.fn.isOnScreen = function () {

    var win = $(window);

    var viewport = {
        top: win.scrollTop(),
        left: win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Site.Nav.bind("content", "live", content);
Site.Nav.bind("parallax", "afterPageChanged", function () {
    setTimeout(function () {
        jQuery(window).trigger('resize').trigger('scroll');
    }, 600);
});