// JavaScript Document

$.fn.nextOrFirst = function (selector) {
    var next = this.next(selector);
    return (next.length) ? next : this.prevAll(selector).last();
};

var rotate = function() {
    $('#topNewsNav .active').nextOrFirst().trigger('click', ['auto']);
};


var setTopInfoWidth = function() {

    if ($(window).width() >= 1280) {
        viewportW = $(window).width() - 160;
        offsetX = (viewportW - 1080) / 2 + 690
    } else {
        offsetX = 710;
    }
    $('#topNews').width(offsetX);
    $('#topContent').css('marginLeft', offsetX);
};

var  positionNews = function() {
    var offsetL = 0;
    if ($(window).width() >= 1355)
        offsetL = $('#mainNav ul:first').offset().left;
    else
        offsetL = 38;

    $('#topNews a').css('left', offsetL - 38);
    $('#topNewsNav').css('left', offsetL + 10 - 38)
};

var initializeHomeOnReady = function () {

    // news auto rotation
    var newsRotationSpeed = 5000; // time in ms
    var newsRotation = true; // auto rotation

    if (newsRotation)
        var ID1 = setInterval(rotate, newsRotationSpeed);

    //topnews
    if ($('#topNews').length) {
        $('#topNews article').not('#topNews article:first').hide();

        $(document).on({
            mouseenter: function() {
                $('#topNewsNav .active').addClass('hover');
            },
            mouseleave: function() {
                $('#topNewsNav .active').removeClass('hover');
            }
        }, '#topNews a');

        $(document).on('click', '#topNewsNav li', function(e, p1) {
            $('#topNewsNav li').removeClass('active').removeClass('hover');
            $(this).addClass('active');
            $('#topNews article').fadeOut(200);
            $('#topNews article:eq(' + $(this).index() + ')').fadeIn(300);
            if (p1 != 'auto')
                clearInterval(ID1);
        });
    }

    //topnews add classes for color
    $('#topNews article:eq(0), #topNewsNav li:eq(0)').addClass('topNews1');
    $('#topNews article:eq(1), #topNewsNav li:eq(1)').addClass('topNews2');
    $('#topNews article:eq(2), #topNewsNav li:eq(2)').addClass('topNews3');


    setTopInfoWidth();
    positionNews();

    $(window).resize(function () {
        setTopInfoWidth();
        positionNews();
    });

    $.get('/typo3conf/ext/holzbauschweiz_template/Resources/Public/Images/Sections/sections.svg', function (data) {
        var svgContent = data;
        // render sections menu with svg
        var sectionsMenu;
        sectionsMenu = $('li.last .mainNavSubWrapper ul').detach();
        var sectionContainer = '<div class="section-map-container"><div class="map">' + svgContent + '</div><div class="section-menu"><ul>' + sectionsMenu.html() + '</ul></div></div> ';
        $('li.last .mainNavSubWrapper').prepend(sectionContainer);
    }, 'text');
};

var initializeHome = function() {
    $(document).ready(function () {
        initializeHomeOnReady();
    });
};

