
var data={};
var settings= {};
var init=true;
var resize, container;
var prevHeight=0;
var slctN, slctNum, slctID;
var audios;
var loadedData={
    css: false,
    js: false
};
(function () {

    VLE.get_attachment("stylesheet",function(response){
        document.getElementById("attachCSS").innerHTML=response;
        window.setTimeout(function(){
            console.log("w css")
            loadedData.css=true;
        },500);
    }, function(){
        if(VLE.serverversion) {
            console.log("no stylesheet attached");
            window.setTimeout(function(){
                loadedData.css=true;
            },500);
        } else {
            console.log("loading local version of stylesheet for testing purposes");
            var requestURL = 'custom/stylesheet.css';
            var request = new XMLHttpRequest();
            request.open('GET', requestURL);
            request.responseType = 'string';
            request.send();
            request.onload = function() {
                loadedData.css=true
                document.getElementById("attachCSS").innerHTML=request.response;
            };
        }
    });

    VLE.get_attachment("data",function(response){
        data= JSON.parse(response);
        settings.accordion = VLE.get_param('accordion') || undefined;
        if(settings.accordion==="true"){
            settings.accordion=true;
        }
        settings.starton = VLE.get_param('starton') || undefined;
        settings.applystyle = VLE.get_param('applystyle') || undefined;
        layoutPage();
    }, function(){
        if(VLE.serverversion) {
            console.log("issue loading data.json");
        } else {
            console.log("loading local version of json for testing purposes");
            var requestURL = 'custom/data.json';
            var request = new XMLHttpRequest();
            request.open('GET', requestURL);
            request.responseType = 'string';
            request.send();
            request.onload = function() {
                data = JSON.parse(request.response);
                layoutPage();
            };
        }
    });
})();
function stopAudio(playingAudio){
    for(var b=0; b<audios.length; b++){
        if(audios[b]!==playingAudio){
            if(!audios[b].paused){
                audios[b].pause();
                audios[b].currentTime =0;
            }
        }
    }
}
function layoutPage(){
    if(settings.applystyle===undefined || settings.applystyle===""){
        settings.applystyle = "";
    }
    if(typeof settings.applystyle !== null){
        if(settings.applystyle!=="") {
            document.getElementById("switchCSS").href = "css/"+settings.applystyle+".css";
        }
    }
    container=document.getElementById("container");
    createPlainViewBtn("prepend");
    if(typeof data.content==="undefined"){
        if(typeof data.html!== "undefined"){
            createEl(container,"div",null,["top-content"],null,null,data.html)
        }
        for(var i=0; i<data.sections.length; i++){
            createClickToReveal(data.sections[i].content,i);
        }
    } else {
        createClickToReveal(data.content,0);
    }
    audios = document.querySelectorAll("audio")
    for(var a=0; a<audios.length; a++){
        audios[a].addEventListener("play",function(){
            stopAudio(this)
        });
    }
    var transcripts = document.querySelectorAll(".audio-transcript")
    for(var t=0; t<transcripts.length; t++){
        transcripts[t].id="transcript-"+t
        var transcriptBtn=createEl(transcripts[t],"button","show transcript",null,{"data-for":"transcript-"+t})
        transcripts[t].parentNode.insertBefore(transcriptBtn, transcripts[t]);
        transcriptBtn.onclick=function(){
            var transcriptEL=document.getElementById(this.getAttribute("data-for"))
            toggleClass(transcriptEL,"hidden");
            if(hasClass(transcriptEL,"hidden")){
                this.innerText="show transcript"
                updateClass("remove",this.parentNode, "show-transcript")
            } else {
                this.innerText="hide transcript"
                updateClass("add",this.parentNode, "show-transcript")
            }
            resizeContainer();
        }
        updateClass("add",transcripts[t], "hidden")
        var transcriptContainer=createEl(transcripts[t].parentNode,"div", null,"transcript-container")
        if(transcripts[t].getAttribute("data-for")!==null){
            transcriptContainer.appendChild(document.getElementById(transcripts[t].getAttribute("data-for")))
        }
        transcriptContainer.appendChild(transcriptBtn)
        transcriptContainer.appendChild(transcripts[t])
    }
    createPlainViewBtn("append");
    if(typeof settings.accordion!=="undefined" && settings.accordion===true) {
        updateClass("add",container,"accordion");
    }
    if(typeof settings.applystyle !=="undefined"){
        updateClass("add",container,settings.applystyle);
    }
    var allCTR = document.querySelectorAll(".click-to-reveal")
    if(typeof settings.starton !=="undefined" && typeof settings.starton!==false){
        for(var j=0; j<allCTR.length;j++){
            if(document.getElementById(allCTR[j].id) !==null){
                if(allCTR[j].parentNode.id==="container"){
                    selectLabel(settings.starton,j, allCTR[j].id);
                }
            }
        }
    }


    if(VLE.serverversion) {
        VLE.get_folder("assets", function (response) {
            for (var l in response) {
                var isImg = false
                if (response[l].path.indexOf(".jpg") !== -1 || response[l].path.indexOf(".gif") !== -1 || response[l].path.indexOf(".png") !== -1 || response[l].path.indexOf(".svg") !== -1) {
                    isImg = true;
                }
                if (isImg) {
                    var img = document.querySelectorAll("img[src=\"custom/" + response[l].path + "\"]")
                    for (var im = 0; im < img.length; im++){
                        if (img[im] !== null) {
                            img[im].src = response[l].url;
                        }
                    }
                }
            }
        }, function () {
            console.log("no attachments")
        });
    }
    init=false;
    loadedData.js=true;
    window.onresize = function(){
        resizeContainer();
    };
    checkLoaded();
}
function checkLoaded(){
    var count=0;
    for(var i in loadedData){
        if (!loadedData[i]) {
            window.setTimeout(function(){
                checkLoaded()
            },100)
        } else {
            count++;
        }
    }
    if(count===2){
        resizeContainer();
    }
}
function createClickToReveal(content,num,parent){
    var clickToReveal = createEl(container, "div", null, "click-to-reveal", {id: "click-to-reveal-" + num});
    var labelContainer = createEl(clickToReveal,"div", null, ["label-container"]);
    var labelScroller = createEl(labelContainer,"div", null, ["label-scroller"]);
    var revealContainer = createEl(clickToReveal,"div", null, ["reveal-container"]);
    for(var i=0; i<content.length; i++){
        var btnTxt=createEl(revealContainer, "div",null,null,null,null,content[i].label)
        var lbl = createEl(labelScroller,"button", null, ["label"], {"id": "label-"+num+"-"+i, "tabindex":0, "aria-label":btnTxt.innerText, "onclick":"selectLabel("+i+","+num+",\"click-to-reveal-"+num+"\")"});
        if(typeof content[i].colour !=="undefined"){
            updateClass("add",lbl,"colour-"+content[i].colour);
        }
        if(typeof content[i].class !=="undefined"){
            for(var j=0; j<content[i].class.length; j++){
                updateClass("add",lbl,content[i].class[j]);
            }
        }
        createEl(lbl,"span", content[i].label);
        var reveal = createEl(revealContainer,"div", null, ["reveal"], {"id": "reveal-"+num+"-"+i});
        var revealLbl=  createEl(reveal,"button", content[i].label, "label accordion-label", {"id": "accordion-label-"+num+"-"+i, "tabindex":0, "role": "button", "aria-label":btnTxt.innerText, "onclick":"selectLabel("+i+","+num+",\"click-to-reveal-"+num+"\")"});
        if(typeof content[i].colour !=="undefined"){
            updateClass("add",reveal,"colour-"+content[i].colour);
            updateClass("add",revealLbl,"colour-"+content[i].colour);
            reveal.setAttribute("data-colour","colour-"+content[i].colour);
        }
        if(typeof content[i].class !=="undefined"){
            for(var j=0; j<content[i].class.length; j++){
                updateClass("add",revealLbl,content[i].class[j]);
            }
        }
        createEl(reveal,"h"+String(reveal.id.split("-").length-2), content[i].label, ["reveal-title"]);
        var revealDiv = createEl(reveal,"div", null, ["reveal-content"], {"aria-labelledby":"label-"+num+"-"+i, "aria-live":"polite"});
        if(typeof content[i].content!=="string"){
            if(typeof content[i].content.sections!=="undefined") {
                for (var l = 0; l < content[i].content.sections.length; l++) {
                    if (content[i].content.html) {
                        revealDiv.innerHTML = content[i].content.html
                    }
                    document.getElementById("reveal-" + num + "-" + i).querySelector(".reveal-content").appendChild(createClickToReveal(content[i].content.sections[l].content, i + "-" + l, "reveal-" + num + "-" + i))
                }
            }
        } else {
            revealDiv.innerHTML=content[i].content;
        }
        revealContainer.removeChild(btnTxt);
    }
    updateClass("add",clickToReveal,"item-count-"+content.length);
    if(parent) {
        return clickToReveal;
    }
}
function selectLabel(n,num,id,resized){
    stopAudio();
    slctN=n;
    slctNum=num;
    slctID=id;
    var pre=id.split("click-to-reveal-")[1];
    var dontShow=false;
    if(hasClass(container, "accordion") && hasClass(document.getElementById("reveal-"+pre+"-"+n),"selected")){
        dontShow=true;
    }
    for(var i=0; i<document.getElementById(id).childNodes[0].childNodes[0].childNodes.length; i++){
        var lbl=document.getElementById(id).childNodes[0].childNodes[0].childNodes[i].id.split("label-")[1];
        updateClass("remove",document.getElementById("label-"+lbl),"selected");
        updateClass("remove",document.getElementById("accordion-label-"+lbl),"selected");
        updateClass("remove",document.getElementById("reveal-"+lbl),"selected");
    }
    document.getElementById(id).removeAttribute("data-selected");
    var reveal=document.querySelector("#reveal-"+pre+"-"+n+" .reveal-content");
    revealInner=reveal.innerHTML;
    reveal.innerHTML="";
    if(!dontShow) {
        updateClass("add", document.getElementById("label-" + pre + "-" + n), "selected");
        updateClass("add", document.getElementById("accordion-label-" + pre + "-" + n), "selected");
        updateClass("add", document.getElementById("reveal-" + pre + "-" + n), "selected");
        document.getElementById(id).setAttribute("data-selected", n);
        if (document.getElementById("reveal-" + pre + "-" + n)) {
            if (document.getElementById("reveal-" + pre + "-" + n).getAttribute("data-colour")) {
                container.setAttribute("data-colour", document.getElementById("reveal-" + pre + "-" + n).getAttribute("data-colour"));
            }
        } else {
            container.removeAttribute("data-colour");
        }
    }
    window.setTimeout(function(){
        reveal.innerHTML=revealInner;
        if(!init && typeof resized==="undefined"){
            VLE.resize_iframe();
        }
    },100)
}
function resizeContainer() {
    clearTimeout(resize);
    resize = setTimeout(function(){
        var reveal=document.querySelectorAll(".reveal");
        if(container.offsetWidth<512) {
            updateClass("add",container,"accordion");
        } else {
            if(typeof settings.accordion==="undefined" || settings.accordion===false) {
                updateClass("remove", container, "accordion");
            }
        }
        for(var i=0;i<reveal.length; i++){
            if(hasClass(container,"plain-view")){
                reveal[i].setAttribute("tabindex",0);
            } else {
                reveal[i].removeAttribute("tabindex");
            }
        }
        if(prevHeight!==container.offsetHeight) {
            prevHeight=container.offsetHeight;
            VLE.resize_iframe();
        } else {
            clearTimeout(resize);
        }
    }, 250);
}

function createPlainViewBtn(loc){
    var btn = createEl(container,"button", "toggle plain view", ["plainViewBtn"], {"aria-pressed":"false", "tabindex":0}, loc);
    btn.onclick=function() {
        toggleClass(container, "plain-view");
        resizeContainer();
    };
    if(loc==="prepend"){
        //btn.focus();
    }
}

/* repeats */
function createEl(parent, type, txt, classes, attributes, where, html) {
    var el = document.createElement(type);

    if(!where || where && where==="append"){
        parent.appendChild(el);
    } else {
        parent.insertBefore(el, parent.firstChild);
    }
    if (txt) {
        el.innerHTML = txt;
    }
    if (classes) {
        el.className = classes;
    }
    if (attributes) {
        for (var attr in attributes) {
            el.setAttribute(attr, attributes[attr]);
        }
    }
    if(html){
        el.innerHTML=html;
    }
    return el;
}


function hasClass(el, className) {
    var doesHaveClass = false;
    if(el!== null) {
        var classList = el.className.split(" ");
        for (var i = 0; i < classList.length; i++) {
            if (className === classList[i]) {
                doesHaveClass = true;
            }
        }
    }
    return doesHaveClass;
};

function toggleClass(el, className) {
    if (el) {
        if (hasClass(el, className)) {
            updateClass("remove", el, className);
        } else {
            updateClass("add", el, className);
        }
    }
}
function updateClass(action, el, className) {
    if (el) {
        var classList = el.className.split(" ");
        switch (action) {
            case "add":
                if (!hasClass(el, className)) {
                    classList.push(className);
                }
                break;
            case "remove":
                if (hasClass(el, className)) {
                    var removeClassAt;
                    for (var i = 0; i < classList.length; i++) {
                        if (className === classList[i]) {
                            removeClassAt = i;
                        }
                    }
                    classList.splice(removeClassAt, 1);
                }
                break;
            default:
                return;
                break;
        }
        el.className = classList.join(" ");
    }
};