/*!
 * fhac_design_2021 v1.0.0 (https://www.fh-aachen.de)
 * Copyright 2017-2021 Michael Lausberg
 * Licensed under the GPL-2.0-or-later license
 */
console.log("FHAC-DESIGN: Script start");

button = document.getElementById('sidenavButton');
if (button) {
    button.addEventListener('click', function () {
        if (document.getElementById('sidenavButton').classList.contains('collapsed')) {
            document.getElementById('sideMenuToggle').classList.remove('bi-x');
            document.getElementById('sideMenuToggle').classList.add('bi-list');
        } else {
            document.getElementById('sideMenuToggle').classList.remove('bi-list');
            document.getElementById('sideMenuToggle').classList.add('bi-x');
        }
    });
}

if (window.innerWidth <= 800) {
    setTimeout('', 1000);
    if (document.getElementById('sidenavButton')) {
        document.getElementById('sidenavButton').click();
    }
}

window.onscroll = function () {
    scrollFunction()
};
window.onresize = function () {
    scrollFunction()
};

function logKlick(pid,action) {
    var xhr  = new XMLHttpRequest();

/*
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
            if (xhr.status == 200) {
                document.getElementById("LOGGER").innerHTML = xhr.responseText;
            }
            else if (xhr.status == 400) {
                document.getElementById("LOGGER").innerHTML = 'There was an error 400';
            }
            else {
                document.getElementById("LOGGER").innerHTML = 'Status ['+xhr.status+'] was returned';
            }
        }
    };
*/
    if(pid==0 && pageUid>0)
        pid = pageUid;
    var postData = new Object();
    // var postData=[];
    postData.pid = pid + 0;
    postData.action = action+"";
    postData.browser = window.navigator.userAgent;
    postData.screenSize=""+window.screen.availWidth+" * "+window.screen.availHeight+"";
    console.log(postData);
    url = "/fileadmin/log.php";
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.send(JSON.stringify(postData));
}

function loadNav(URL="",back=false) {
    // console.log("Subnav für '"+URL+"' laden. back=" + back + "");
    if(typeof(BC) == 'undefined') {
        BC=[];
        for (i = 0; i < (document.getElementById('subnavBreadcrumb').children.length); i++) {
            BC[i]=document.getElementById('subnavBreadcrumb').children[i].attributes['pid'].nodeValue;
        }
    }
    const xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
        SMP=this.responseText;
        subnavContentBox  = document.getElementById('subnavContentBox');
        subnavContentNAV  = document.getElementById('subnavContentNAV');
        if(SMP.search("\"AjaxMain\"")>0/* && SMP.search("\"fhac_bc\"")>0*/) {
            if(URL=="" || subnavContentNAV.innerHTML.trim()=="") {
                subnavContentMAIN = document.getElementById('subnavContentMAIN');
                subnavContentNAV.innerHTML = SMP.trim();
                AjaxMain=document.getElementById('AjaxMain');
                subnavContentMAIN.innerHTML = AjaxMain.innerHTML;
                AjaxMain.remove();
                found=false;
                for(i=document.getElementById('fhac_bc').children.length-1;i >= 0; i--) {
                    if (!found && typeof (document.getElementById('fhac_bc').children[i].firstElementChild.attributes['pid']) != 'undefined') {
                        NAVI = document.getElementById('fhac_bc').children[i].firstElementChild.attributes['pid'].nodeValue;
                        for (j = 0; j < BC.length; j++) {
                            if (!found && BC[j] == NAVI) {
                                document.getElementById('fhac_bc').children[i].classList.add('active');
                                found = true;
                            }
                        }
                    }
                }
                // document.getElementById('overview').focus();
            } else if(subnavContentNAV.innerHTML.trim() != SMP.trim()) {
                subnavContentNEW = document.getElementById('subnavContentNEW');
                subnavContentMAIN = document.getElementById('subnavContentMAIN');
                if (subnavContentNEW == null) {
                    subnavContentNEW = document.createElement('div');
                    subnavContentNEW.id = 'subnavContentNEW';
                    subnavContentNEW.classList.add('col');
                }
                subnavContentNEW.innerHTML = SMP;
                if (subnavContentNEW.firstChild.id) {
                    if (back) {
                        subnavContentBox.classList.add('back');
                        subnavContentBox.insertBefore(subnavContentNEW, subnavContentNAV);
                    } else {
                        subnavContentBox.classList.add('forward');
                        subnavContentBox.insertBefore(subnavContentNEW, subnavContentNAV.nextSibling);
                    }
                    setTimeout(function () {
                        subnavContentBox.classList.add('move');
                    }, 1);
                    setTimeout(function () {
                        subnavContentNAV.classList.add('invisible');
                        subnavContentBox.classList.remove('forward');
                        subnavContentBox.classList.remove('back');
                        subnavContentBox.classList.remove('move');
                        subnavContentNAV.remove();
                        subnavContentNEW.id = 'subnavContentNAV';
                        subnavContentNAV = document.getElementById('subnavContentNAV');
                        AjaxMain = document.getElementById('AjaxMain');
                        subnavContentMAIN.innerHTML = AjaxMain.innerHTML;
                        AjaxMain.remove();
                        // document.getElementById('overview').focus();
                        found = false;
                        for (i = document.getElementById('fhac_bc').children.length - 1; i >= 0; i--) {
                            if (!found && typeof (document.getElementById('fhac_bc').children[i].firstElementChild.attributes['pid']) != 'undefined') {
                                NAVI = document.getElementById('fhac_bc').children[i].firstElementChild.attributes['pid'].nodeValue;
                                for (j = 0; j < BC.length; j++) {
                                    if (!found && BC[j] == NAVI) {
                                        document.getElementById('fhac_bc').children[i].classList.add('active');
                                        found = true;
                                    }
                                }
                            }
                        }
                        // if (!found) {
                        //     document.getElementById('fhac_bc').children[0].classList.add('active');
                        // }
                    }, 321);
                } else {
                    // console.log("Menü Laden fehlerhaft! Lade Menü der Startseite.");
                    loadNav();
                }
            }
        }
        else
        {
            subnavContentNAV.innerHTML = "Leider ist ein Fehler aufgetreten. Bitte erstellen Sie ein Ticket!";
        }
    }
    xhttp.open("GET", URL+"?type=4711", true);
    xhttp.send();
}
function scrollFunction() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        document.getElementById("toTopBtn").classList.add('visible');
    } else {
        document.getElementById("toTopBtn").classList.add('hide');
        document.getElementById("toTopBtn").classList.remove('visible');
        setTimeout(function(btn){
            btn.classList.remove('hide');
        }, 300,document.getElementById("toTopBtn"));
    }
    activeBlock(getScrollTargets(),2);

}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
    logKlick(0,'toTop');
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

function parentIsTarget(element) {
    if(element.tagName == "BODY")
        return true;
    if(element.tagName != "MAIN") {
        if(element.parentNode.classList.contains("fhScrollTarget")) {
            return true;
        } else {
            return parentIsTarget(element.parentNode);
        }
    } else {
        return false;
    }
}

function getScrollTargets() {
    var sTL=[];var j=0;
    // console.log(document.getElementById('fh_main').getElementsByClassName('fhScrollTarget').length);
    for(var i=0;i<document.getElementById('fh_main').getElementsByClassName('fhScrollTarget').length;i++) {
        if(!parentIsTarget(document.getElementById('fh_main').getElementsByClassName('fhScrollTarget')[i])) {
            sTL[j]=[];
            document.getElementById('fh_main').getElementsByClassName('fhScrollTarget')[i].setAttribute('fhScrollTarget',j);
            sTL[j]['dom'] = document.getElementById('fh_main').getElementsByClassName('fhScrollTarget')[i];
            sTL[j]['top']=sTL[j]['dom'].offsetTop;
            sTL[j]['bottom'] = sTL[j]['top'] + sTL[j]['dom'].offsetHeight;
            j++;
        }
    }
    return sTL;
}
function activeBlock(scrollTargetList) {
    var returnBlock = -1; //HEADER
    var scrollPosition = document.documentElement.scrollTop+document.body.scrollTop+document.getElementsByTagName('header')[0].offsetHeight;
    for(var i=0;i<scrollTargetList.length;i++) {
/*
        // Block-Bestimmung nach oberer Kante für 1. Version (Buttons in der Mitte)
        if (
            (scrollTargetList[i]['top'] <= scrollPosition) &&
            (scrollTargetList[i]['bottom'] > scrollPosition)
        ) {
            returnBlock = i;
        }
*/
        const part=0.4;
        if ((scrollPosition + window.innerHeight) > (scrollTargetList[i]['bottom'] - 100) &&
            (scrollPosition + window.innerHeight) < (scrollTargetList[i]['bottom'] + part * window.innerHeight) &&
            (i < (scrollTargetList.length - 1))) {
            var transparenz = Math.min(((((scrollTargetList[i]['bottom'] - scrollPosition)/window.innerHeight)-(1-part))/0.3),1);
            scrollTargetList[i]['dom'].lastChild.style.setProperty('--scroll',transparenz);
            scrollTargetList[i]['dom'].lastChild.classList.add('visible');
            returnBlock = i;
        } else {
            scrollTargetList[i]['dom'].lastChild.classList.remove('visible');
        }
    }
    if(returnBlock==-1 && (scrollTargetList[scrollTargetList.length - 1]['bottom'] > scrollPosition)) {
        returnBlock = "-2"; //FOOTER
    }
    return returnBlock;
}
function prevBlockFunction() {
    var scrollTargetList=getScrollTargets();
    var aBlock = activeBlock(scrollTargetList);
    logKlick(0,'prevBlock('+aBlock+')');
    if(aBlock==-1) aBlock=0;
    if(aBlock==-2) aBlock=scrollTargetList.length-1;
    var scrollPosition = document.documentElement.scrollTop + document.body.scrollTop + document.getElementsByTagName('header')[0].offsetHeight;
    var scrollTarget;
    if ((aBlock - 1) > 0) {
        scrollTarget = scrollTargetList[aBlock - 1]['top'] - document.getElementsByTagName('header')[0].offsetHeight;
    } else {
        scrollTarget = 0;
    }
    document.documentElement.scroll({
        top: scrollTarget,
        left: 0,
        behavior: "smooth",
    });
}
function nextBlockFunction() {
    var scrollTargetList=getScrollTargets();
    var aBlock = activeBlock(scrollTargetList);
    logKlick(0,'nextBlock('+aBlock+')');
    if(aBlock==-1) aBlock=0;
    if(aBlock==-2) aBlock=scrollTargetList.length-1;
    var scrollPosition = document.documentElement.scrollTop+document.body.scrollTop+document.getElementsByTagName('header')[0].offsetHeight;
    if(aBlock < (scrollTargetList.length)) {
        var scrollTarget = scrollTargetList[aBlock + 1]['top'] - document.getElementsByTagName('header')[0].offsetHeight;
        document.documentElement.scroll({
            top: scrollTarget,
            left: 0,
            behavior: "smooth",
        });
    }
}

scrollFunction();

function abstandBreadcrumb(X) {
    if (X.classList.contains('collapsed')) {
        document.getElementById('fh_breadcrumbRow').classList.remove('abstand');
    } else {
        document.getElementById('fh_breadcrumbRow').classList.add('abstand');
    }
}

function resizeTopMenuDropdown() {
    let h_menu = document.getElementById('fh_topNavRow').offsetHeight;
    let h_bc = document.getElementById('fh_breadcrumbRow').offsetHeight;
    maxHeight = "calc(100vh - " + (h_menu + h_bc + 32) + "px)";
//    console.log(maxHeight);
    document.getElementById('navbarDropdownContentBlock').style.maxHeight = maxHeight;
}

function closeTopMenuDropdownOthers(O) {
    let P = O.parentNode.parentNode.children;
    for (let i = 0; i < P.length; i++) {
        if (P[i].childNodes[1].attributes['aria-expanded'].value == "true") {
            P[i].childNodes[1].click();
        }
    }
}

// resizeTopMenuDropdown();

function galleryScroll(ID) {
    if (!document.getElementById('fh-gallery_' + ID).classList.contains('autoslide')) {
        width = document.getElementById('fh_gallery_item_' + ID + '_0').clientWidth;
        sp = document.getElementById('fh-gallery_' + ID).firstElementChild.scrollLeft;
        pn = Math.round(sp / width) + 1;
        po=1;ready=false;
        while(document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1)) && !ready) {
            if (document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1)).classList.contains('active')) {
                ready=true;
            }
            po++;
        }
        // if (pn != (po-1)) {
        //     console.log(ID, "swipe", pn );
            galleryMoveTo(ID, pn);
        // }
    }
}

function gallerySetThumbnails(ID) {
    anz=document.getElementById('fh-gallery_' + ID).firstElementChild.children.length-2;
    for (po=1;po<=anz;po++) {
        item = document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1));
        si = 0;
        while (si < 16 && item.tagName != "IMG") {
            item_next = item.firstElementChild;
            if(!item_next) {
                si = 20;
            } else {
                if(item_next.tagName == "HEADER") {
                    item_next = item_next.nextElementSibling;
                }
                item = item_next;
            }
            si++;
        }
        if (item.tagName == "IMG") {
            src = item.src;
            document.getElementById("fh-gallery-indicator_" + ID + "_" + (po - 1)).style.backgroundImage = "url("+src+")";
        }
    }
}

function galleryChange(ID, po) {
    if (document.getElementById('fh-gallery_' + ID).classList.contains('autoslide')) {
        po=1;ready=false;
        while(document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1)) && !ready) {
            if (document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1)).classList.contains('active')) {
                ready=true;po--;
            }
            po++;
        }
        if (po >= (document.getElementById('fh-gallery_' + ID).firstElementChild.children.length - 2)) {
            pn = 1;
        } else {
            pn = po + 1;
        }
        galleryMoveTo(ID, pn);
    }
}

function galleryMoveTo(ID, pn) {
    width = document.getElementById('fh_gallery_item_' + ID + '_0').clientWidth;
    po=1;ready=false;
    while(document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1)) && !ready) {
        if (document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1)).classList.contains('active')) {
            document.getElementById('fh_gallery_item_' + ID + '_' + (po - 1)).classList.remove('active');
            ready=true;
        }
        po++;
    }
    if (pn==999) pn = po;
    if (pn < 0) pn = po-2;
    po=1;ready=false;
    while(document.getElementById('fh-gallery-indicator_' + ID + '_' + (po - 1)) && !ready) {
        if (document.getElementById('fh-gallery-indicator_' + ID + '_' + (po - 1)).classList.contains('active')) {
            document.getElementById('fh-gallery-indicator_' + ID + '_' + (po - 1)).classList.remove('active');
            ready=true;
        }
        po++;
    }
    if (pn < 1) {
        pn = 1;
    }
    if (pn > (document.getElementById('fh-gallery_' + ID).firstElementChild.childElementCount - 2)) {
        pn = document.getElementById('fh-gallery_' + ID).firstElementChild.childElementCount - 2;
    }
    // console.log(ID, "auto", pn );
    document.getElementById('fh-gallery-indicator_' + ID + '_' + (pn - 1)).classList.add('active');
    document.getElementById('fh_gallery_item_' + ID + '_' + (pn - 1)).classList.add('active');
    document.getElementById('fh-gallery_' + ID).firstElementChild.scroll((pn - 1) * width, 0);
}

function fh_carouselSetThumbnails(ID) {
    anz=document.getElementById('fh_carousel_' + ID).firstElementChild.children.length-2;
    for (po=1;po<=anz;po++) {
        item = document.getElementById('fh_carousel_item_' + ID + '_' + (po - 1));
        si = 0;
        while (si < 16 && item.tagName != "IMG") {
            item_next = item.firstElementChild;
            if(!item_next) {
                si = 20;
            } else {
                if(item_next.tagName == "HEADER") {
                    item_next = item_next.nextElementSibling;
                }
                item = item_next;
            }
            si++;
        }
        if (item.tagName == "IMG") {
            src = item.src;
            document.getElementById("fh_carousel_indicator_" + ID + "_" + (po - 1)).style.backgroundImage = "url("+src+")";
        }
    }
}
function fh_carouselChange(ID, po) {
    if (document.getElementById('fh_carousel_' + ID).classList.contains('autoslide')) {
        po=1;ready=false;
        while(document.getElementById('fh_carousel_item_' + ID + '_' + (po - 1)) && !ready) {
            if (document.getElementById('fh_carousel_item_' + ID + '_' + (po - 1)).classList.contains('active')) {
                ready=true;po--;
            }
            po++;
        }
        if (po >= (document.getElementById('fh_carousel_' + ID).firstElementChild.children.length - 2)) {
            pn = 1;
        } else {
            pn = po + 1;
        }
        fh_carouselMoveTo(ID, pn);
    }
}
function fh_carouselMoveTo(ID, pn) {
    width = document.getElementById('fh_carousel_item_' + ID + '_0').clientWidth;
    po=1;ready=false;
    while(document.getElementById('fh_carousel_item_' + ID + '_' + (po - 1)) && !ready) {
        if (document.getElementById('fh_carousel_item_' + ID + '_' + (po - 1)).classList.contains('active')) {
            document.getElementById('fh_carousel_item_' + ID + '_' + (po - 1)).classList.remove('active');
            ready=true;
        }
        po++;
    }
    if (pn==999) pn = po;
    if (pn < 0) pn = po-2;
    po=1;ready=false;
    while(document.getElementById('fh_carousel_indicator_' + ID + '_' + (po - 1)) && !ready) {
        if (document.getElementById('fh_carousel_indicator_' + ID + '_' + (po - 1)).classList.contains('active')) {
            document.getElementById('fh_carousel_indicator_' + ID + '_' + (po - 1)).classList.remove('active');
            ready=true;
        }
        po++;
    }
    if (pn < 1) {
        // pn = 1;
        pn=document.getElementById('fh_carousel_' + ID).firstElementChild.childElementCount - 2;
        // console.log("UnterLauf");
    }
    if (pn > (document.getElementById('fh_carousel_' + ID).firstElementChild.childElementCount - 2)) {
        // pn = document.getElementById('fh_carousel_' + ID).firstElementChild.childElementCount - 2;
        pn=1;
        // console.log("ÜberLauf");
    }
    document.getElementById('fh_carousel_indicator_' + ID + '_' + (pn - 1)).classList.add('active');
    document.getElementById('fh_carousel_item_' + ID + '_' + (pn - 1)).classList.add('active');
    document.getElementById('fh_carousel_' + ID).firstElementChild.scroll((pn - 1) * width, 0);
}

function doSearch() {
    suchwort = document.getElementById('googlesuche-sword').value;
    if(suchwort > "") {
        suchfeld=document.getElementById('gsc-i-id1');
        suchfeld.style.backgroundImage = "";
        suchfeld.value = suchwort;
        document.getElementsByClassName('gsc-search-button-v2')[0].click();
    }
}

function evalKey() {
    var key = ('which' in event) ? event.which : event.keyCode;
    if ( key == "13" || key == "32") {
        // console.log("Taste "+key+" Aktion Klick");
        document.activeElement.click();
    } else if ( key == "40" || key == "38") {
        // console.log("Taste "+key+" Aktion Pfeiltasten");
        document.activeElement.click();
    } else {
        // console.log("Taste "+key+" keine Aktion");
    }
}

function zielgruppeAfterClick(ID, action) {
    if (action == 'spin') {
        document.querySelector('#fh_zielgruppen_spinner_'+ID).style.display = 'inline-block';
    } else if (action == 'main') {
        document.getElementById('DZGT_grpContent').setAttribute('data-zga', 0);
        document.getElementById('DZG_grpContent').setAttribute('data-zga', 0);
    } else if (action == 'select') {
        if(document.getElementById('DZGT_grpContent').getAttribute('data-zga')==ID) {
            if (!document.getElementById('DZGT_grpContent').classList.contains('show')) {
                document.getElementById('DZGT_grpButton').click();
            }
        } else {
            if (document.getElementById('DZGT_grpContent').classList.contains('show')) {
                document.getElementById('DZGT_grpButton').click();
                setTimeout(() => {
                    document.getElementById('DZGT_grpContent').setAttribute('data-zga', ID);
                    document.getElementById('DZG_grpContent').setAttribute('data-zga', ID);
                    document.getElementById('DZGT_grpButton').click();
                }, 500);
            } else {
                document.getElementById('DZGT_grpContent').setAttribute('data-zga', ID);
                document.getElementById('DZG_grpContent').setAttribute('data-zga', ID);
                document.getElementById('DZGT_grpButton').click();
            }
        }
        setTimeout(() => {
            document.getElementById('DZGT_grpContent').scrollIntoViewIfNeeded(true);
        }, 500);
    } else if (action == 'ext') {
        document.getElementById('DZG_grpButton').click();
    }
    return true;
}

while (window.find('[machine translated]')) {
    id = Math.floor(Math.random() * 1000000);
    document.body.innerHTML = document.body.innerHTML.replace("\"[machine translated]", "\"");
    document.body.innerHTML = document.body.innerHTML.replace('[machine translated]', '<i alt="This text has been machine-translated." title="This is a machine translation provided by DeepL.\r\nManual corrections may be made where appropriate." id="MT-' + id + '" class="bi bi-translate"></i>');
    MT = document.getElementById('MT-' + id + '');
    P = MT.parentNode;
    if (P.localName == "p") {
        PP = P.parentNode;
        PP.classList.add('machine-translated');
        PP.title="This is a machine translation provided by DeepL.\r\nManual corrections may be made where appropriate.";
        PP.appendChild(MT);
        if (P.textContent == "") {
            P.remove();
        }
        MT.previousElementSibling.style.display = 'inline';
    } else {
        MT.remove();
        P.classList.add('machine-translated');
        P.title="This is a machine translation provided by DeepL.\r\nManual corrections may be made where appropriate.";
    }
}


console.log("FHAC-DESIGN: Script ready!");
