function openModal(modalId) {
    var modal = document.getElementById(modalId);
    modal.style.display = "block";


}

function closeModal(modal) {
    var modal = document.getElementById(modal);
    modal.style.display = "none";
}

function showBarTimer(checkbox) {
    if (checkbox.checked == true) {
        document.getElementById("progress_bar").style.display = 'block';
    } else {
        document.getElementById("progress_bar").style.display = 'none';
    }
}

function darkMode() {
    var checkbox = document.getElementById("darkcheck");
    if (checkbox.checked == true) {
        setColor("black");
    } else {
        setColor("white");
    }
}

function symbole(checkbox) {
    if (checkbox.checked == true) {
        pathImg = "img/sym/";
    } else {
        pathImg = "img/txt_en/";
    }
    saveStage();
}

function dysFont() {
    var checkbox = document.getElementById("dyscheckbox");
    var textToChange = document.querySelectorAll(".dys");
    var font;
    if (checkbox.checked == true) {
        font = "dys";
    } else {
        font = "main";
    }
    textToChange.forEach(function (item) {
        item.style.fontFamily = font;
    })
    document.getElementById("jeu-select").style.fontFamily = font;
}

function setColor(color) {
    if (color == "black") {
        var backgroundToChange = document.querySelectorAll(".background");
        backgroundToChange.forEach(function (element) {
            element.style.backgroundColor = blackColor;
        });
        document.querySelectorAll(".backgroundInv").forEach(function (element) {
            element.style.backgroundColor = whiteColor;
        });
        document.body.style.color = whiteColor;
        document.getElementById("setting_int").style.color = whiteColor;
        var hr = document.querySelectorAll("#hr");
        hr.forEach(function (item) {
            item.setAttribute("style", "border : 3px solid " + whiteColor);
        });
        document.querySelectorAll(".border").forEach(function (element) {
            element.style.border = "5px solid" + whiteColor;
        });
        document.querySelectorAll(".color").forEach(function (element) {
            element.style.color = whiteColor;
        });


    } else {
        document.body.style.color = blackColor;
        var backgroundToChange = document.querySelectorAll(".background");
        backgroundToChange.forEach(function (element) {
            element.style.backgroundColor = whiteColor;
        });
        document.querySelectorAll(".backgroundInv").forEach(function (element) {
            element.style.backgroundColor = blackColor;
        });
        document.getElementById("setting_int").style.color = blackColor;
        var hr = document.querySelectorAll("#hr");
        hr.forEach(function (item) {
            item.setAttribute("style", "border : 3px solid " + blackColor);
        });
        document.querySelectorAll(".border").forEach(function (element) {
            element.style.border = "5px solid" + blackColor;
        });
        document.querySelectorAll(".color").forEach(function (element) {
            element.style.color = blackColor;
        });
    }
    //fun
    document.querySelector(".secret").style.color = "#fe8a71";
}

document.querySelectorAll(".listenerHover").forEach(function (element) {
    element.addEventListener("mouseover", function (event) {
        mouseOver(element);
    });
});
document.querySelectorAll(".listenerHover").forEach(function (element) {
    addEventListener("mouseout", function (event) {
        mouseOut(element);
    });
});

function mouseOver(button) {
    button.style.backgroundColor = document.querySelector(".modal-body").style.borderColor;
    button.style.color = document.querySelector(".modal-body").style.backgroundColor;
    button.childNodes[3].style.transform = "rotate(-15deg)";
}

function mouseOut(button) {
    button.style.backgroundColor = document.querySelector(".modal-body").style.backgroundColor;
    button.style.color = document.querySelector(".modal-body").style.borderColor;
    button.childNodes[3].style.transform = "rotate(0deg)";
}

function setLang(newLang) {
    var textToChange = document.querySelectorAll(".txt");
    if (newLang === "fr") {
        textToChange.forEach(function (item) {
            let currText = item.id;
            document.getElementById(currText).innerHTML = lang.fr[currText];
        });
        document.querySelector(".img_france").style.opacity = 1;
        document.querySelector(".img_usa").style.opacity = 0.2;
    } else {
        textToChange.forEach(function (item) {
            let currText = item.id;
            document.getElementById(currText).innerHTML = lang.en[currText];
        });
        document.querySelector(".img_france").style.opacity = 0.2;
        document.querySelector(".img_usa").style.opacity = 1;
    }
}

function calculNombreSwitch() {
    var entrelibre = 0;
    logiques.forEach(function (element) {

        if (element.id1 == null) {
            entrelibre++;
        }
        if (element.id2 == null && element.type != "inv") {
            entrelibre++;
        }
    });
    numberOfSwitch = entrelibre;
}

function whatIsElement(element) {
    if (findLogique(element.name) == null || findLogique(element.name) == undefined) {
        return "switch";
    } else {
        return "logique";
    }
}

function setLine(logiqueElement, lineId, lineName) {
    logiques.forEach(function (element, index) {
        if (element.name === logiqueElement.name) {
            Object.keys(element).map(function (objectKey, index) {
                if (objectKey == lineId) {
                    if (lineId === "id3") {
                        element[objectKey].push(lineName);
                    } else
                        element[objectKey] = lineName;
                }
            });
        }
    });
}

function changeSwitchColor(switchId) {
    let swi = stage.findOne("#" + switchId);
    var colorswi = swi.fill() == colorSwitchActiveBackground ? colorSwitchInnactiveBackground : colorSwitchActiveBackground;
    swi.fill(colorswi);
}

function changeLineColor(idLine) {
    let line = stage.findOne("#" + idLine);
    var colorline = line.stroke() == colorLineActive ? colorLineInnactive : colorLineActive;
    line.stroke(colorline);
}

function changeLineColorInput(idLine, color) {
    let line = stage.findOne("#" + idLine);
    line.stroke(color);
}

function changeLineColorBlack(idLine) {
    let line = stage.findOne("#" + idLine);
    line.stroke(colorLineInnactive);
}

function changeLineColorYellow(idLine) {
    let line = stage.findOne("#" + idLine);
    line.stroke(colorLineActive);
}

function checkAllSortieLogique() {
    switchsInfoCopy.forEach(function (element) {
        if (stage.findOne("#" + element.id).fill() === colorSwitchInnactiveBackground) {
            if (stage.findOne("#" + element.id3[0]).stroke() !== colorLineInnactive) {
                stage.findOne("#" + element.id).fill(colorSwitchActiveBackground);
            }
        } else {
            if (stage.findOne("#" + element.id3[0]).stroke() !== colorLineActive) {
                stage.findOne("#" + element.id).fill(colorSwitchInnactiveBackground);
            }
        }
    });
    logiques.forEach(function (element) {
        if (element.id3.length != 0)
            checkSortieLogique(element.name);
    });

}

function getSwitchById(switchId) {
    let switche;
    switchsInfoCopy.forEach(function (element) {
        if (element.id == switchId)
            switche = element;
    });
    return switche;
}

function checkEntreCroisement(logiqueId) {
    let croisement = false;
    let logique = findLogique(logiqueId);
    if (logique.id1 != null && logique.id2 != null) {
        if (stage.findOne("#" + logique.id1).points()[1] > stage.findOne("#" + logique.id2).points()[1]) {

            if (getSwitchFromLine(logique.id1) != null && getSwitchFromLine(logique.id2) != null) {
                let switch1 = getSwitchFromLine(logique.id1).id;
                let switch2 = getSwitchFromLine(logique.id2).id;
                removeLine(logique.id1);
                removeLine(logique.id2);
                logique.id1 = null;
                logique.id2 = null;
                createLink(stage.findOne("#" + switch1), logique);
                createLink(stage.findOne("#" + switch2), logique);
            } else if (getLogiqueFromLine(logique.id1) != null && getLogiqueFromLine(logique.id2) != null) {
                let logique1 = getLogiqueFromLine(logique.id1);
                let logique2 = getLogiqueFromLine(logique.id2);

                removeLine(logique.id1);
                removeLine(logique.id2);

                logique.id1 = null;
                logique.id2 = null;
                createLink(logique1, logique);
                createLink(logique2, logique);

            } else if (getSwitchFromLine(logique.id1) != null && getLogiqueFromLine(logique.id2) != null) {
                let logique1 = getLogiqueFromLine(logique.id2);
                let switch1 = getSwitchFromLine(logique.id1).id;
                removeLine(logique.id1);
                removeLine(logique.id2);
                logique.id1 = null;
                logique.id2 = null;
                createLink(logique1, logique);
                createLink(stage.findOne("#" + switch1), logique);
            } else if (getLogiqueFromLine(logique.id1) != null && getSwitchFromLine(logique.id2) != null) {
                let logique1 = getLogiqueFromLine(logique.id1);
                let switch1 = getSwitchFromLine(logique.id2).id;
                removeLine(logique.id1);
                removeLine(logique.id2);
                logique.id1 = null;
                logique.id2 = null;
                createLink(stage.findOne("#" + switch1), logique);
                createLink(logique1, logique);
            } else {
                croisement = true;
            }

        }
    }
    return croisement;
}

function getLogiqueFromLine(lineId) {
    var logique = null;
    logiques.forEach(function (element) {
        element.id3.forEach(function (line) {
            if (line == lineId) logique = element;
        })
    });
    return logique;
}

function getSwitchFromLine(lineId) {
    var switche = null;
    switchsInfoCopy.forEach(function (element) {
        element.id3.forEach(function (line) {
            if (line == lineId) switche = element;
        });
    });
    return switche;
}

function checkSortieLogique(logiqueId) {
    let logique = findLogique(logiqueId);
    logiques.forEach(function (element, index) {
        if (element.name === logique.name) {
            let line1State, line2State;
            let id1Color = stage.findOne("#" + element.id1).stroke();
            if (element.type !== "inv") {
                let id2Color = stage.findOne("#" + element.id2).stroke();
                if (id2Color == colorLineInnactive) {
                    line2State = false;
                } else {
                    line2State = true;
                }
            }

            if (id1Color == colorLineInnactive) {
                line1State = false;
            } else {
                line1State = true;
            }

            switch (logique.type) {
                case "et":
                    if (line1State == true && line2State == true) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                        });
                    }
                    break;
                case "inv":
                    if (line1State == false) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                        });
                    }
                    break;
                case "ou":
                    if (line1State == true || line2State == true) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                        });
                    }
                    break;
                case "nonou":
                    if (line1State == true || line2State == true) {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                        });
                    }
                    break;
                case "etnon":
                    if (line1State == false && line2State == false) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                        });
                    } else if (line1State == false && line2State == true) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                        });
                    } else if (line1State == true && line2State == false) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                        });
                    }
                    break;
            }
        }
    });
}

function isLineCollapsing() {
    var isCollapsing = false;
    if (stage.findOne("#s2") != undefined && stage.findOne("#s2") != null && stage.findOne("#s1") != undefined && stage.findOne("#s1") != null) {
        var distance = stage.findOne("#s2").getY() - stage.findOne("#s1").getY();
        switchsInfoCopy.forEach(function (element) {
            element.id3.forEach(function (line) {
                if (Math.abs(element.y - stage.findOne("#" + line).points()[7]) > distance) {
                    isCollapsing = true;
                }
            })
        });
    }
    return isCollapsing;
}

function getRandomArbitrary(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

function isElementExisting(elementId) {
    if (stage.findOne("#" + elementId) != null) {
        return true;
    }
    return false;
}

function checkLineSwitch(switchId) {
    if (stage.findOne("#" + switchId) != null) {
        return true;
    }
    return false;
}

function activeSwitch(idSwitch) {
    getSwitchById(idSwitch);
    var switche = getSwitchById(idSwitch);
    changeSwitchColor(switche.id);
    switche.id3.forEach(function (element) {
        changeLineColor(element);
    });

}

function checkIfEnd() {
    var ter = true;
    endLines.forEach(function (element) {
        if (stage.findOne("#line" + element).stroke() == colorLineInnactive) {
            ter = false;

        }
    });
    return ter;
}

function checkEnd(mode) {
    let ter = true;
    endLines.forEach(function (element) {
        if (stage.findOne("#line" + element).stroke() == colorLineInnactive) {
            ter = false;

        }
    });
    if (ter && !isTuto) {
        setTimeout(() => {
            success(mode);
        }, 100);
    }
}

function success(mode) {
    timeTot = timeTot + timer.getTimeValues().seconds;
    timer.stop();
    stage.findOne("#end").fill("yellow");
    layer.draw();
    if (successPanel) {
        openModal("success");
        document.querySelector("#click_number").innerHTML = click;
        document.querySelector("#next_level_button").onclick = function () {
            closeModal('success');
            nextLevel(mode);
        }
        var previewStage = new Konva.Stage({
            container: 'show_stage',
            width: window.innerWidth / 1.5,
            height: window.innerHeight / 2.5,
            scaleX: 1 / 1.5,
            scaleY: 1 / 1.5
        });
        let previewLayer = layer.clone({
            hitGraphEnabled: false
        });
        previewStage.add(previewLayer);
        previewLayer.batchDraw();
    } else {
        setTimeout(() => {
            nextLevel(mode);
        }, 1000);
    }
}

function successCheck() {
    if (document.querySelector("#success_check_input").checked === true) successPanel = true;
    else successPanel = false;
}

function nextLevel(mode) {
    niveauActuel++;
    if (mode != undefined && mode != null && mode === "tuto") {
        launchTuto();
    } else {
        launchGameOne();
    }
}

function calculNombreSwitch() {
    var entrelibre = 0;
    logiques.forEach(function (element) {

        if (element.id1 == null) {
            entrelibre++;
        }
        if (element.id2 == null && element.type != "inv") {
            entrelibre++;
        }
    });
    numberOfSwitch = entrelibre;
}



function resize() {
    stage.scale({
        x: 1,
        y: 1
    });
    stage.draw();
}

function activeSwitchInput(event) {
    changeAllSwitchColorActive(event.target.value);
}

function inactiveSwitchInput(event) {
    changeAllSwitchColorInActive(event.target.value);
}

function activeLineInput(event) {
    changeAllLineColorActive(event.target.value);
}

function inactiveLineInput(event) {
    changeAllLineColorInActive(event.target.value);
}

function inactiveEndInput(event) {
    changeEndColorInActive(event.target.value);
}

document.querySelector("#active_switch_picker").addEventListener("input", activeSwitchInput, false);
document.querySelector("#inactive_switch_picker").addEventListener("input", inactiveSwitchInput, false);
document.querySelector("#active_line_picker").addEventListener("input", activeLineInput, false);
document.querySelector("#inactive_line_picker").addEventListener("input", inactiveLineInput, false);
document.querySelector("#inactive_end_picker").addEventListener("input", inactiveEndInput, false);

function changeAllSwitchColorActive(color) {
    switchsInfoCopy.forEach(function (element) {
        var switche = stage.findOne("#" + element.id);
        if (switche.fill() == colorSwitchActiveBackground) {
            switche.fill(color);
        }
    });
    colorSwitchActiveBackground = color;
    layer.draw();
}

function changeEndColorInActive(color) {
    colorEnd = color;
    stage.findOne("#end").fill(color);
    layer.draw();
}

function changeAllSwitchColorInActive(color) {
    switchsInfoCopy.forEach(function (element) {
        var switche = stage.findOne("#" + element.id);
        if (switche.fill() == colorSwitchInnactiveBackground) {
            switche.fill(color);
        }
    });
    colorSwitchInnactiveBackground = color;
    layer.draw();
}

function changeAllLineColorActive(color) {
    var line1 = stage.findOne("#line2");
    var line2 = stage.findOne("#line3");
    var line3 = stage.findOne("#line4");
    if (line1.stroke() === colorLineActive) {
        line1.stroke(color);
    }
    if (line2.stroke() === colorLineActive) {
        line2.stroke(color);
    }
    if (line3.stroke() === colorLineActive) {
        line3.stroke(color);
    }
    colorLineActive = color;
    layer.draw();
}

function changeAllLineColorInActive(color) {
    var line1 = stage.findOne("#line2");
    var line2 = stage.findOne("#line3");
    var line3 = stage.findOne("#line4");
    if (line1.stroke() === colorLineInnactive) {
        line1.stroke(color);
    }
    if (line2.stroke() === colorLineInnactive) {
        line2.stroke(color);
    }
    if (line3.stroke() === colorLineInnactive) {
        line3.stroke(color);
    }
    colorLineInnactive = color;
    layer.draw();
}

function hideDiv(div) {
    div.style.display = 'none';
}

function showDiv(div) {
    if (div.id == "levelSelectionPage") {
        document.querySelectorAll("#right_select").forEach(function (element) {
            element.classList = "fa fa-arrow-right";
        });
    }
    div.style.display = 'block'
}

function play() {
    hideDiv(document.querySelector("#mainPage"));
    showDiv(document.querySelector("#levelSelectionPage"));
}

function modePerso() {
    document.querySelector("#generate_button_perso").childNodes[3].classList = "fa fa-arrow-right";
    hideDiv(document.querySelector("#levelSelectionPage"));
    showDiv(document.querySelector("#PersoSetupPage"));
}

function playNormal() {
    hideDiv(document.querySelector("#levelSelectionPage"));
    showDiv(document.querySelector("#playPage"));
    niveauActuel = 1;
    timeTot = 0;
    launchGameOne();
}

function modeTuto() {
    hideDiv(document.querySelector("#levelSelectionPage"));
    showDiv(document.querySelector("#playPage"));
    niveauActuel = 1;
    timeTot = 0;
    launchTuto();
}

function modeTest() {
    hideDiv(document.querySelector("#levelSelectionPage"));
    showDiv(document.querySelector("#playPage"));
    niveauActuel = 1;
    timeTot = 0;
    launchTest();
}

function wait(mode, btn) {
    var time = 300;
    spin(btn);
    switch (mode) {
        case "normal":
            setTimeout(playNormal, time);
            break;
        case "perso":
            setTimeout(modePerso, time);
            break;
        case "tuto":
            setTimeout(modeTuto, time);
            break;
        case "test":
            setTimeout(modeTest, time);
            break;
    }
}

function colonne_check_setup(value) {
    if (value != "" || value != null || value != undefined) {
        document.querySelectorAll(".colonne_selection").forEach(function (element) {
            element.remove();
        });
        for (let i = 0; i < value; i++) {
            var div = document.createElement("div");
            var input = document.createElement("input");
            var label = document.createElement("label");
            let colonne_number = i + 1;
            input.type = "number";
            input.oninput = refresh_input;
            input.id = i;
            input.classList = "input_refresh";
            div.classList.add("colonne_selection");
            label.innerHTML = " Nombre de fonctions dans la colonne " + colonne_number;
            div.appendChild(input);
            div.appendChild(label);
            div.appendChild(document.createElement("br"));
            document.querySelector('#colonne_number_ask').appendChild(div);
        }
    }
    refresh_input();
}

function refresh_input() {
    document.querySelector("#colonne_number_setup_global").value = "0";
    document.querySelectorAll(".input_refresh").forEach(function (element) {
        if (element.value == "" || element.value == null || element.value == undefined)
            element.value = '0';
        document.querySelector("#colonne_number_setup_global").value = parseInt(document.querySelector("#colonne_number_setup_global").value) + parseInt(element.value);
    });
}

function show_more_perso(div) {
    if (div.childNodes[3].className === "fa fa-arrow-down") {
        div.childNodes[3].className = "fa fa-arrow-up";
        document.querySelector("#colonne_number_ask").style.display = "block";
        document.querySelector("#colonne_number_setup_global").disabled = true;
        document.querySelector("#colonne_number_setup_global").value = 1;
    } else {
        div.childNodes[3].className = "fa fa-arrow-down";
        document.querySelector("#colonne_number_ask").style.display = "none";
        document.querySelector("#colonne_number_setup").value = "0";
        document.querySelectorAll(".colonne_selection").forEach(function (element) {
            element.remove();
        });
        document.querySelector("#colonne_number_setup_global").disabled = false;
    }
}

function launchGameOne() {
    document.querySelector(".niveau").innerHTML = niveauActuel;
    timer.stop();
    timer.reset();
    resetAllTabs(false);
    gameOne();
}

function launchTuto() {
    document.querySelector(".niveau").innerHTML = niveauActuel;
    timer.stop();
    timer.reset();
    resetAllTabs(false);
    tuto();
}

function launchTest() {
    document.querySelector(".niveau").innerHTML = niveauActuel;
    timer.stop();
    timer.reset();
    resetAllTabs(false);
    generate2();
}

function clearArray(arr) {
    while (arr.length > 0) {
        arr.pop();
    }
    return arr.splice(0, arr.length);
}

function closeGame() {
    timer.stop();
    showDiv(document.querySelector("#mainPage"));
    hideDiv(document.querySelector("#playPage"));
    resetAllTabs(false);
    tutoCreateLayer();
}

function closeSelection() {
    showDiv(document.querySelector("#mainPage"));
    hideDiv(document.querySelector("#levelSelectionPage"));
}

function closePerso() {
    showDiv(document.querySelector("#levelSelectionPage"));
    hideDiv(document.querySelector("#PersoSetupPage"));
}
var rotated = false;

function flip() {
    document.querySelectorAll(".fa").forEach(function (element) {
        deg = rotated ? 0 : 360;
        element.style.transform = 'rotate(' + deg + 'deg)';
    });
    rotated = !rotated;
}