// --------------------------------- //
// functions from main-old.js adjusted and
// commented out in main-old.js
//

/**
 * Get ideal Image for this size
 *
 * return new image
 */
function chooseImage(image, width) {

    /**
     * added "data-" in new Version
     * so check which to use
     */
     var smallAttrName  = ($(image)[0].hasAttribute('data-src-small'))  ? 'data-src-small'  : 'src-small';
     var mediumAttrName = ($(image)[0].hasAttribute('data-src-medium')) ? 'data-src-medium' : 'src-medium';
     var largeAttrName  = ($(image)[0].hasAttribute('data-src-large'))  ? 'data-src-large'  : 'src-large';
     var fullAttrName   = ($(image)[0].hasAttribute('data-src-full'))   ? 'data-src-full'   : 'src-full';

    /**
     * get ideal size
     */
    var srcSize = '';

    if(width <= window.small) {
        srcSize = smallAttrName;
    }
    else if (width <= window.medium) {
        srcSize = mediumAttrName;
    }
    else if (width <= window.large) {
        srcSize = largeAttrName;
    }
    else {
        srcSize = fullAttrName;
    }


    /**
     * check if ideal size exists (via data-attribute)
     * added "data-"
     */
    var notDefined = false;

    if( srcSize == smallAttrName) {

        if( $(image).attr(srcSize) === undefined) {
            notDefined = true;
        }
    }
    if( srcSize == mediumAttrName || notDefined == true) {

        notDefined = ( $(image).attr(mediumAttrName) === undefined) ? true : false;
        srcSize = mediumAttrName;

    }
    if( srcSize == largeAttrName || notDefined == true) {

        notDefined = ( $(image).attr(largeAttrName) === undefined) ? true : false;
        srcSize = largeAttrName;
    }
    if( srcSize == fullAttrName || notDefined == true) {

        notDefined = ( $(image).attr(fullAttrName) === undefined) ? true : false;
        srcSize = fullAttrName;
    }
    /**
     * if no data attribute found use src string
     */
    if (notDefined == true) {

        srcSize = 'src';
    }

    var imageIdeal = $(image).attr(srcSize);

    /**
     * get image name @2x for retina
     */
    if(window.isRetina) {

        imageIdeal = getImageRetina(imageIdeal);
    }

    /**
     * if ideal image differs from current one => change it
     */
    if($(image).attr('src') != imageIdeal) {

        /**
         * change image to ideal image
         */
        $(image).attr('src', imageIdeal);
    }

    /**
     * If image of Header Slider:
     * set as background image
     * (not for mobile)
     */
    if( window.hasHeaderSlider ) {

        if($(image).closest('#carousel-header').length) {

            setImageAsBackgroundOfParent(image);
        }
    }

    return image;
}

function setImageAsBackgroundOfParent(image) {

    var imgTextOnTop = $(image).closest('.text-on-top');

    /**
     * if text on top element
     */
    if( $(imgTextOnTop).length > 0 ) {

        $(imgTextOnTop).find('.container').css( {
            'background-image': 'url(' +  $(image).attr('src') + ')',
            'background-size': 'cover',
            'background-position': 'center center'
        } );
    }
    else {
        $(image).parent().css( {
            'background-image': 'url(' +  $(image).attr('src') + ')',
            'background-size': 'cover',
            'background-position': 'center center'
        } );
    }
}

/**
 * If submenu has another submenu put it in a
 * div with id nav-nth-level
 *
 * Places nth submenu on page
 * only implemented for 3rd level right now
 */
function writeNavNthLevel(nthLevel) {

    /**
     * if has megamenu not necessary
     */
    if($('.submenu-full-width').length > 0) {
        return;
    }

    /**
     * set default to 3rd
     */
    var nthLevel = nthLevel || 3;
    
    /**
     * Check if there are nth - 1 li.dropdown active
     * => there is a nth navigation level
     */
    var activeDropdown = $('#main-menu').find('li.dropdown.active');
    if( $(activeDropdown).length == nthLevel - 1) {

        var activeDropdownClone = $(activeDropdown).clone();
        /**
         * show nth-Navigation
         * new: changed from block to display flex
         */
        $('#header-nav-'+nthLevel).css( {'display' : 'flex' } );

        /**
         * Get Name of active page (nth - 1 level)
         */
        $( '#head-nav-'+nthLevel ).text( $(activeDropdownClone).last().children('a').text() );

        /**
         * get menu nth-Level
         * remove class dropdown-menu because this is set to display none
         * and because it's shown on the page it is no longer a dropdown
         */
        $('#nav-level-'+nthLevel ).html( $(activeDropdownClone).last().children('ul').removeClass('dropdown-menu'));
    }
}

/**
 * Check if image needs to be resized  (added "data-")
 *
 * image: the image element
 * width: the width of enclosing parent element
 *
 * return image (either changed or old one)
 */
function checkImageForResize (image, width) {

    var fullAttrName   = ($(image)[0].hasAttribute('data-src-full'))   ? 'data-src-full'   : 'src-full';

    var imageSrc            = (window.isRetina) ? $(image).attr('src').replace("@2x.",".") : $(image).attr('src');

    var imageNaturalWidth   = (window.isRetina && ( imageSrc != $(image).attr(fullAttrName) )) ? parseInt(image.naturalWidth / 2) : image.naturalWidth;

    var imageParentWidth    = parseInt(width);

    /**
     * check if resizing is necassary
     *
     * only if new container width is larger than real image width => load new image
     */

    if (imageNaturalWidth < imageParentWidth) {

        image = chooseImage(image, imageParentWidth);
    }

    return image;
}

/****
 * Set image size for all images in content on first load
 * (added "data-" )
 *
 * depending on parent div width
 */
function setImageSizeOnInit() {

    var width = 0;

    $('#content img').each(function() {

        /**
         * for content slider use same width for hidden slides
         * => do nothing
         */
        if( $(this).is(':visible') ) {

            width = $(this).parent().width();
        }
        /**
         * if hidden but header slide text-on-top
         * set width to browser width (full-width image)
         */
        else if( $(this).closest('.text-on-top').length > 0 ) {

            width = window.browserWidth;
            $(this).attr('data-width', window.browserWidth);
        }
        /**
         * if data-width is set use this value for hidden elements
         */
        else if( $(this).attr('data-width') !== undefined ) {

            width = $(this).attr('data-width');
        }

        /**
         * Exception for gif files because animation will be lost in resized images
         * Exception for svg files
         */
        var extension = this.src.split('.').pop();

        if(extension.toLowerCase() == "gif" || extension.toLowerCase() == "svg" || extension.toLowerCase() == "svgz") {

            var fullAttrName   = ($(this)[0].hasAttribute('data-src-full'))   ? 'data-src-full'   : 'src-full';
   
            if( $(this).attr(fullAttrName) !== undefined ) {
                $(this).attr('src', $(this).attr(fullAttrName));
            }
        }
        /**
         * no gif or svg file
         */
        else {

            /**
             * change image to ideal one
             */
            var idealImage = chooseImage(this, width);

            /**
             * store changed image in global array
             * to check on resize
             */
            window.arrImages.push(idealImage);
        }
    });
}

function initSectionCollapse() {

    var countSection = 0;
    var allSections = $('section[id]');

    /**
     * get all <section> with id
     */
    $(allSections).each( function(index, section) {

        /**
         * first section is the introduction of the page => skip collapse
         */
        if( countSection > 0) {

            var idSection = $(section).attr('id');

            /**
             * check if there are link <a> to the <section> id
             * if there are it is assumed that it is a page with a lot of content
             * which should collapse on mobile
             */
            var linkToSection = $(`a[href="#${idSection}"]`);

            if( $(linkToSection).length > 0) {

                var sectionName = $(linkToSection).html();
                /**
                 * add html teaser before section
                 */
                $(section).before(` 
                    
                    <div class="section-teaser clearfix v-center" data-id-section="${idSection}">
                        <h2 class="h3"><a>${sectionName} <span class="glyphicon glyphicon-einfacher-pfeil-runter right" aria-hidden="true"></span></a></h2>
                    </div>                   
               `);

                /**
                 * hide section on init
                 */
                $(section).addClass('hide');

                /**
                 * if last section add line after section
                 */
                if(countSection == $(allSections).length - 1) {

                    $(section).after('<div class="section-teaser last"></div>');
                }
            }
        }
        countSection ++;
    });

    /**
     * arrow element vertical align
     */
    sectionTeaserAdjust();

    /**
     * event Listener on new section teaser elements
     */
    $('.section-teaser').click( function() {
        showHideSection( $(this).attr('data-id-section') );
    });
}

/**
 * Set divs in slider to height
 *
 * all slides should have the same height
 *
 * For header slider mobile
 *
 * different handling:
 * 1) elements are stacked on top of each other
 * 2) no background image
 */
function sliderHeaderXsSameHeight(height, init) {

    init = init || false;

    $('#carousel-header-xs .item .slider-text').css('height', height + 'px');

    /**
     * set control arrows of half of image (it is asumed that all images have the same height)
     */

    /**
     * if onload wait till images has loaded
     */
    if(init) {

        /**
         * ideal img is dynamically loaded
         * wait for load and then get height
         * get actual height because inactive elements are hidden
         */
        // @todo attention needed to change .load() to .on('load'..
        $("#carousel-header-xs img").on('load', function(){

            var heightImage = $(this).actual('height');

            $('#carousel-header-xs .carousel-control span').css('top',  parseInt(heightImage / 2) + 'px');

            /**
             * set control circles in deco item  (it is asumed that all images have the same height)
             */
            $('#carousel-header-xs .carousel-indicators').css({ 'bottom' : 'auto', 'top' : parseInt(heightImage + 3 ) + 'px' });
        });
    }
    else {

        var heightImage =  $("#carousel-header-xs img").actual('height');

        $('#carousel-header-xs .carousel-control span').css('top',  parseInt(heightImage / 2) + 'px');

        /**
         * set control circles in deco item  (it is asumed that all images have the same height)
         */
        $('#carousel-header-xs .carousel-indicators').css({ 'bottom' : 'auto', 'top' : parseInt(heightImage + 3 ) + 'px' });
    }

}