var init=true;
var data={
    //display: string | together/seperate
    display:"together",
    //initialshow: int/boolean | number/false
    initialshow:false,
    //plaintexttoggle: boolean | true/false
    plaintexttoggle:true,
    content: [
        {
            label:"<div class=\"shadow-r\"></div><div class=\"title\">Feeling helpless</div>",
            content:"<div class=\"box\"><p class=\"n-m-t n-m-b\">Being asked for pain relief or caring for a child in pain, and not be able to relieve that pain, could lead to issues negatively affecting their relationship with parents:</p><p class=\"n-m-t n-m-b\">‘Parents lose confidence if their child is left in pain.’</p></div>"
        },
        {
            label:"<div class=\"shadow-l\"></div><div class=\"shadow-r\"></div><div class=\"title\">Losing confidence</div>",
            content:"<div class=\"box\"><p class=\"n-m-t n-m-b\">Having a parent lose confidence in the nurse caring for their child was reported as stressful for nurses:</p><p class=\"n-m-t n-m-b\">‘Staff get stressed when they look powerless in front of patients and relatives.’</p></div>"
        },
        {
            label:"<div class=\"shadow-l\"></div><div class=\"shadow-r\"></div><div class=\"title\">Feeling frustrated</div>",
            content:"<div class=\"box\"><p class=\"n-m-t n-m-b\">Frustration was also expressed in stating that there was:</p><p class=\"n-m-t n-m-b\">‘No time to spend time with the child and families. No time to listen.’</p></div>"
        },
        {
            label:"<div class=\"shadow-l\"></div><div class=\"shadow-r\"></div><div class=\"title\">Proposing solutions</div>",
            content:"<div class=\"box\"><p class=\"n-m-t n-m-b\">On the other hand a potential solution was suggested as:</p><p class=\"n-m-t n-m-b\">‘Being there, being approachable.’</p><p class=\"n-m-t n-m-b\">This is an interesting finding which hints that practitioners are not always approachable, which would deter parents calling on them to help manage their child’s pain.</p></div>"
        },
        {
            label:"<div class=\"shadow-l\"></div><div class=\"title\">Being informed</div>",
            content:"<div class=\"box\"><p class=\"n-m-t n-m-b\">Most participants talked of the importance of keeping children and their families informed, as this could help mitigate stress for parents and children related to pain management:</p><p class=\"n-m-t n-m-b\">‘discussing with the families ahead of a painful episode and letting them know what to expect … people available … people assessing the pain management, and … make adjustments if required.’</p></div>"
        }
    ]
};

var labels, reveals, resize;
var prevHeight;
(function () {
    createContentView();
    setupResize();
    if(data.plaintexttoggle) {
        createPlainViewBtn("prepend");
        createPlainViewBtn("append");
    }
    labels=document.querySelectorAll(".label");
    reveals=document.querySelectorAll(".reveal");
    selectLabel(data.initialshow);
    addClickToContainer();
    hasMediaLoaded();
    prevHeight=document.getElementById("container").offsetHeight;
    resizeScreen();
})();
function setupResize() {
    window.onresize = function () {
        clearTimeout(resize);
        resize = setTimeout(function(){
            if(prevHeight!==document.getElementById("container").offsetHeight) {
                prevHeight=document.getElementById("container").offsetHeight;
                VLE.resize_iframe();
                scrollTop()

            } else {
                clearTimeout(resize);
            }
        }, 250);
    };
}

function addClickToContainer(){
    var containers = document.querySelectorAll(".seperate-container");
    for(var i=0; i< containers.length;i++){
        containers[i].onclick=function(){
            this.querySelector(".label-container .label").click();
        }
    }
}

function selectLabel(num){
    for(var i=0; i<data.content.length; i++){
        updateClass("remove",labels[i],"selected");
        updateClass("add",reveals[i],"hidden");
    }
    updateClass("add",labels[num],"selected");
    updateClass("remove",reveals[num],"hidden");
    stopMedia();
    resizeScreen();
}
function stopMedia(){
    /* pauses vids */
    var medias = document.querySelectorAll("video,audio");
    for(var j=0; j<medias.length; j++){
        if(medias[j]) {
            if (medias[j].parentNode) {
                if (medias[j].parentNode.nextElementSibling) {
                    if (medias[j].parentNode.nextElementSibling.querySelector(".omp-stop")) {
                        medias[j].parentNode.nextElementSibling.querySelector(".omp-stop").click();
                    }
                }
            }
        }
    }
}
function resizeScreen(){
    if(!init) {
        setTimeout(function(){VLE.resize_iframe();scrollTop()}, 1000);
    } else {
        if(document.getElementById("container").offsetWidth<512) {
            setTimeout(function () {
                VLE.resize_iframe();
                scrollTop()
            }, 1000);
        }
        init=false;
    }
}
function createContentView(){
    var labelContainer, revealContainer;
    var content = createEl(document.querySelector("#container"),"div", null, null, {"id":"content"});
    if(data.display==="together") {
        labelContainer = createEl(content, "div", null, null, {"class": "label-container"});
        revealContainer = createEl(content, "div", null, null, {"class": "reveal-container"});
    }
    for(var i=0; i<data.content.length; i++){
        if(data.display==="seperate") {
            var seperateContainer = createEl(content,"div", null, ["seperate-container"])
            labelContainer = createEl(seperateContainer, "div", null, null, {"class": "label-container"});
            revealContainer = createEl(seperateContainer, "div", null, null, {"class": "reveal-container","aria-live":"polite"});
        }
        var label = createEl(labelContainer,"div", data.content[i].label, null, {"class":"label", "id":"label-"+i, "tabindex":"0", "role": "button", "aria-label":"test"}, null, data.content[i].label);
        label.setAttribute("aria-label", document.querySelectorAll(".label")[i].innerText)
        label.onkeyup=function(e){
            if(e.keyCode===13 || e.keyCode===32) {
                this.click();
            }
        };
        label.onclick=function() {
            selectLabel(Number(this.getAttribute("id").split("label-")[1]));
        };
        data.content[i].content="<h1 class=\"reveal-heading\">"+data.content[i].label+"</h1>"+data.content[i].content;
        var reveal = createEl(revealContainer,"div", null, null, {"class":"reveal"}, null, data.content[i].content);
        if(data.display==="together") {
            reveal.setAttribute("tabindex","0");
        }
    }
    if(data.backgroundimage) {
        createEl(content,"div", null, null, {"class":"bkg-img"});
    }
    createEl(document.getElementById("container"), "script", null, null, {
        "data-main": "./oump/js/oump",
        "src": "./oump/js/loader.js"
    });
    var mediaContainer = document.querySelectorAll(".media-holder");
    for (var mc = 0; mc < mediaContainer.length; mc++) {
        mediaContainer[mc].addEventListener("click", showHideTranscripts);
    }

    updateClass("add", document.querySelector("#container"), "loaded")
}

function createPlainViewBtn(loc){
    var parent=document.querySelector("#container")
    var btn = createEl(parent,"button", "toggle plain view", ["plainViewBtn"], {"aria-pressed":"false", "tabindex":0}, loc);
    if(loc==="append"){
        updateClass("add", btn,"hidden");
    }
    btn.onclick=function() {
        var content=document.querySelector("#content");
        var plainViewBtns = document.querySelectorAll(".plainViewBtn");
        var seperateContainer= document.querySelectorAll(".seperate-container");
        if(this.getAttribute("aria-pressed")==="true") {
            for(var i=0; i< plainViewBtns.length; i++){
                plainViewBtns[i].setAttribute("aria-pressed",false);
            }
            if(data.display==="seperate") {
                for (var j = 0; j < seperateContainer.length; j++) {
                    seperateContainer[j].removeAttribute("tabindex");
                }
            }
            content.removeAttribute("tabindex");
            updateClass("remove",content,"plain-view");
            updateClass("add", plainViewBtns[plainViewBtns.length-1],"hidden");
            document.querySelector(".plainViewBtn").focus();
        } else {
            for(var k=0; k< plainViewBtns.length; k++){
                plainViewBtns[k].setAttribute("aria-pressed",true);
            }
            if(data.display==="seperate") {
                for (var l = 0; l < seperateContainer.length; l++) {
                    seperateContainer[l].setAttribute("tabindex", "0");
                }
            }
            content.setAttribute("tabindex", "0");
            updateClass("add",content,"plain-view");
            updateClass("remove", plainViewBtns[plainViewBtns.length-1],"hidden");
            content.focus();
        }
        stopMedia();
        VLE.resize_iframe();
        scrollTop()
    };
    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 classList = el.className.split(" ");
    var doesHaveClass = false;
    for (var i = 0; i < classList.length; i++) {
        if (className === classList[i]) {
            doesHaveClass = true;
        }
    }
    return doesHaveClass;
};

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(" ");
    }
}
function hasMediaLoaded() {
    var mediaContainer = document.querySelectorAll(".media-holder");
    var loaded = true;
    if(!hasClass(document.querySelector("#container"),"loaded")){
        loaded = false;
    }
    for (var mc = 0; mc < mediaContainer.length; mc++) {
        if (!mediaContainer[mc].querySelector(".omp-placeholder-image")) {
            loaded = false;
        }
    }
    if (loaded) {
        setTimeout(function(){VLE.resize_iframe();scrollTop()}, 500);
        document.addEventListener('fullscreenchange', exitHandler);
        document.addEventListener('webkitfullscreenchange', exitHandler);
        document.addEventListener('mozfullscreenchange', exitHandler);
        document.addEventListener('MSFullscreenChange', exitHandler);
    } else {
        setTimeout(function () {
            hasMediaLoaded();
        }, 500);
    }

}
function exitHandler() {
    if (!document.fullscreenElement && !document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
        setTimeout(function () {
            VLE.resize_iframe();
            scrollTop()
        }, 500);
    }
}
function showHideTranscripts(e) {
    var el = e.target;
    if (hasClass(el.parentNode, "omp-transcript-toggle-checkbox")) {
        setTimeout(function () {
            VLE.resize_iframe();
            scrollTop()
        }, 500);
    }
};
function scrollTop(){
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}