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 changeLineState(idLine) {
    let line = null;
    lines.forEach(function (element) {
        if (element.id === idLine) line = element;
    });
    var stateLine = line.state == true ? false : true;
    line.state = stateLine;
}

function setLineStateTrue(lineId) {
    lines.forEach(function (line) {
        if (line.id == lineId) line.state = true;
    });
}

function setLineStateFalse(lineId) {
    lines.forEach(function (line) {
        if (line.id == lineId) line.state = false;
    });
}

function getLineState(lineId) {
    var state = null;
    lines.forEach(function (line) {
        if (line.id == lineId) state = line.state;
    });
    return state;
}

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

function changeCircleBlack(logiqueId) {
    circles.forEach(function (cir) {
        if (cir[1] === logiqueId) {
            stage.findOne("#" + cir[0]).fill(colorLineInnactive);
        }
    });
}
function changeCircleYellow(logiqueId) {
    circles.forEach(function (cir) {
        if (cir[1] === logiqueId) {
            stage.findOne("#" + cir[0]).fill(colorLineActive);
        }
    });
}

function changeLineColorBlack(idLine) {
    setLineStateFalse(idLine);
    let line = stage.findOne("#" + idLine);
    line.stroke(colorLineInnactive);
    circles.forEach(function (circle) {
        if (circle === "circle" + idLine) {
            stage.findOne("#circle" + idLine).stroke(colorLineInnactive);
            stage.findOne("#circle" + idLine).fill(colorLineInnactive);
        }
    });
}

function changeLineColorYellow(idLine) {
    setLineStateTrue(idLine);
    circles.forEach(function (circle) {
        if (circle === "circle" + idLine) {
            stage.findOne("#circle" + idLine).stroke(colorLineActive);
            stage.findOne("#circle" + idLine).fill(colorLineActive);
        }
    });
    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 getLogiqueFromLineEnter(lineId) {
    var logique = null;
    logiques.forEach(function (element) {
        if (element.id1 === lineId || element.id2 === 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") {
                line2State = getLineState(element.id2);
                /*let id2Color = stage.findOne("#" + element.id2).stroke();
                if (id2Color == colorLineInnactive) {
                    line2State = false;
                } else {
                    line2State = true;
                }*/
            }
            line1State = getLineState(element.id1);
            /*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);
                            changeCircleYellow(logique.name);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                            changeCircleBlack(logique.name);
                        });
                    }
                    break;
                case "inv":
                    if (line1State == false) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                            changeCircleYellow(logique.name);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                            changeCircleBlack(logique.name);
                        });
                    }
                    break;
                case "ou":
                    if (line1State == true || line2State == true) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                            changeCircleYellow(logique.name);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                            changeCircleBlack(logique.name);
                        });
                    }
                    break;
                case "nonou":
                    if (line1State == true || line2State == true) {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                            changeCircleBlack(logique.name);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                            changeCircleYellow(logique.name);
                        });
                    }
                    break;
                case "etnon":
                    if (line1State == false && line2State == false) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                            changeCircleYellow(logique.name);
                        });
                    } else if (line1State == false && line2State == true) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                            changeCircleYellow(logique.name);
                        });
                    } else if (line1State == true && line2State == false) {
                        element.id3.forEach(function (line) {
                            changeLineColorYellow(line);
                            changeCircleYellow(logique.name);
                        });
                    } else {
                        element.id3.forEach(function (line) {
                            changeLineColorBlack(line);
                            changeCircleBlack(logique.name);
                        });
                    }
                    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 invertLine() {
    logiques.forEach(function (logique) {
        if (logique.type !== "inv") {
            var distance1;
            var distance2;
            if (getLogiqueFromLine(logique.id1) === null)
                distance1 = getSwitchFromLine(logique.id1).y;
            else distance1 = getLogiqueFromLine(logique.id1).y;
            if (getLogiqueFromLine(logique.id2) === null)
                distance2 = getSwitchFromLine(logique.id2).y;
            else distance2 = getLogiqueFromLine(logique.id2).y;
            if (distance2 < distance1) {
                if (getLogiqueFromLine(logique.id1) === null && getLogiqueFromLine(logique.id2) === null) {
                    let switch1Id = getSwitchFromLine(logique.id1).id;
                    let switch2Id = getSwitchFromLine(logique.id2).id;
                    removeLine(logique.id1);
                    removeLine(logique.id2);
                    logique.id1 = null;
                    logique.id2 = null;
                    createLink(stage.findOne("#" + switch2Id), logique);
                    createLink(stage.findOne("#" + switch1Id), logique);
                } else if (getLogiqueFromLine(logique.id1) === null && getLogiqueFromLine(logique.id2) !== null) {
                    let switch1Id = getSwitchFromLine(logique.id1).id;
                    let logique2 = getLogiqueFromLine(logique.id2);
                    removeLine(logique.id1);
                    removeLine(logique.id2);
                    logique.id1 = null;
                    logique.id2 = null;
                    createLink(stage.findOne("#" + switch1Id), logique);
                    createLink(logique2, logique);
                } else if (getLogiqueFromLine(logique.id1) !== null && getLogiqueFromLine(logique.id2) === null) {
                    let switch2Id = getSwitchFromLine(logique.id2).id;
                    let logique1 = getLogiqueFromLine(logique.id1);
                    removeLine(logique.id1);
                    removeLine(logique.id2);
                    logique.id1 = null;
                    logique.id2 = null;
                    createLink(logique1, logique);
                    createLink(stage.findOne("#" + switch2Id), 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);
                }
            }



        }
    });

}

function getLogiqueByLine(idLine) {
    var logique = null;
    logiques.forEach(function (element) {
        if (element.id1 === idLine || element.id2 === idLine) logique = element;
    });
    return logique;
}

function updateLines(logique) {
    if (logique !== null) {
        checkSortieLogique(logique.name);
        logique.id3.forEach(function (line) {
            updateLines(getLogiqueByLine(line));
        });
    }
}

function lineUpdate(swithId) {
    var lineId = getSwitchById(swithId).id3;
    var currLogique = getLogiqueByLine(lineId[0]);
    updateLines(currLogique);
    stage.draw();
}

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) {
    var switche = getSwitchById(idSwitch);
    changeSwitchColor(switche.id);
    switche.id3.forEach(function (element) {
        changeLineColor(element);
        changeLineState(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);
    }
    if (ter) {
        stage.findOne("#end").fill(colorSwitchActiveBackground);
    } else {
        stage.findOne("#end").fill(colorEnd);
    }
    stage.draw();
}

function success(mode) {
    console.log(mode)
    timeTot = timeTot + timer.getTimeValues().seconds;
    timer.stop();
    stage.findOne("#end").fill(colorSwitchActiveBackground);
    layer.draw();
    if (mode != undefined && mode != null && mode === "tuto") {
        document.querySelector(".retry_tuto").style.display = "flex";
        document.querySelector("#retry_tuto_button").onclick = function () {
            //closeModal('success');
            launchTuto();
        }
    } else {
        document.querySelector(".retry_tuto").style.display = "none";
    }
    if (successPanel) {
        document.querySelector("#win_pannel").style.display = "block";
        //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(mode);
    }
}



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("normal");
}

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

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

}

function ErrorMessage(message) {
    document.querySelector("#error_perso").innerHTML = message;
}

function WarningMessage(message) {
    if (message === "") {
        document.querySelector("#warning_perso_message").style.display = "none";
        document.querySelector(".fa-info-circle").style.display = "none";
    } else {
        document.querySelector("#warning_perso_message").innerHTML = message;
        document.querySelector("#warning_perso_message").style.display = "block";
        document.querySelector(".fa-info-circle").style.display = "block";
    }
}


function wait(mode, btn) {
    var time = 300;
    spin(btn);
    switch (mode) {
        case "normal":
            setTimeout(playNormal, time);
            setMode("Normal");
            break;
        case "vanilla":
            setTimeout(playVanilla, time);
            setMode("Vanilla")
            break;
        case "perso":
            setTimeout(modePerso, time);
            setMode("Perso")
            break;
        case "tuto":
            setTimeout(modeTuto, time);
            setMode("Tuto")
            break;
        case "test":
            setTimeout(modeTest, time);
            setMode("Perso");
            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(mode) {
    document.querySelector(".niveau").innerHTML = niveauActuel;
    document.querySelector("#win_pannel").style.display = "none";
    timer.stop();
    timer.reset();
    resetAllTabs(false);
    var col = [];
    var matchs = [];
    var porteLogique = [];
    var time = 20;
    switch (niveauActuel) {
        case 1:
            col = [2, 1];
            porteLogique = [[true, "et"], [true, "ou"]];
            break;
        case 2:
            col = [2, 2];
            porteLogique = [[true, "et"], [true, "ou"]];
            break;
        case 3:
            col = [3, 2];
            matchs = [[1, 2]];
            porteLogique = [[true, "et"], [true, "ou"]];
            break;
        case 4:
            col = [3, 2];
            porteLogique = [[true, "et"], [true, "inv"]];
            break;
        case 5:
            col = [3, 3];
            matchs = [[1, 2]];
            porteLogique = [[true, "et"], [true, "inv"]];
            break;
        case 7:
        case 6:
            col = [4, 3];
            matchs = [[1, 2]];
            porteLogique = [[true, "et"], [true, "inv"], [true, "ou"]];
            break;
        case 8:
        case 9:
        case 10:
        case 11:
            col = [5, 4, 3];
            matchs = [[1, 3], [2, 2]];
            porteLogique = [[true, "et"], [true, "ou"], [true, "inv"]];
            break;
        case 12:
        case 13:
        case 14:
        case 15:
        case 16:
            col = [5, 4, 4];
            matchs = [[1, 3], [2, 2]];
            porteLogique = [[true, "et"], [true, "nonou"], [true, "ou"], [true, "inv"]];
            break;

        default:
            col = [4, 3, 2];
            matchs = [[1, 2], [2, 2]];
            porteLogique = [[true, "et"], [true, "ou"]];
            break;
    }
    for (let i = 0; i < 200; i++) {
        tentative = i;
        if (generator(matchs, col, porteLogique, mode, time) === false)
            break;

    }
    if (mode === "normal") {
        switchsInfoCopy.forEach(function (sw) {
            if (getRandomArbitrary(0, 3) === 1) {
                activeSwitch(sw.id);
                checkAllSortieLogique();
            }
        });
    }
    while (checkIfEnd()) {
        for (let i = 0; i < 200; i++) {
            tentative = i;
            if (generator(matchs, col, porteLogique, mode, time) === false)
                break;
        }
        if (mode === "normal") {
            switchsInfoCopy.forEach(function (sw) {
                switchsInfoCopy.forEach(function (sw) {
                    if (getRandomArbitrary(0, 3) === 1) {
                        activeSwitch(sw.id);
                        checkAllSortieLogique();
                    }
                });
            });
        }
    }
}

function launchTuto() {
    document.querySelector("#win_pannel").style.display = "none";
    document.querySelector(".niveau").innerHTML = niveauActuel;
    timer.stop();
    timer.reset();
    if (niveauActuel < 6) {
        resetAllTabs(false);
        tuto();
        while (checkIfEnd()) {
            resetAllTabs(false);
            tuto();
            break;
        }
    } else {
        document.querySelector("#niveauSuivantText").innerHTML = "Niveau Suivant";
        document.querySelector(".niveauSuivantIcon").className = "fa fa fa-arrow-right niveauSuivantIcon";
        hideDiv(document.querySelector("#playPage"));
        showDiv(document.querySelector("#mainPage"));
    }
}

function setMode(mode) {
    document.querySelector("#modeDeJeu").innerHTML = mode;
}

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(div) {
    showDiv(document.querySelector("#levelSelectionPage"));
    hideDiv(div.parentElement.parentElement);
}
var rotated = false;

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


//https://gist.github.com/tkon99/4c98af713acc73bed74c
//Name Generator

function capFirst(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

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

function generateName() {
    var name1 = ["abandoned", "able", "absolute", "adorable", "adventurous", "academic", "acceptable", "acclaimed", "accomplished", "accurate", "aching", "acidic", "acrobatic", "active", "actual", "adept", "admirable", "admired", "adolescent", "adorable", "adored", "advanced", "afraid", "affectionate", "aged", "aggravating", "aggressive", "agile", "agitated", "agonizing", "agreeable", "ajar", "alarmed", "alarming", "alert", "alienated", "alive", "all", "altruistic", "amazing", "ambitious", "ample", "amused", "amusing", "anchored", "ancient", "angelic", "angry", "anguished", "animated", "annual", "another", "antique", "anxious", "any", "apprehensive", "appropriate", "apt", "arctic", "arid", "aromatic", "artistic", "ashamed", "assured", "astonishing", "athletic", "attached", "attentive", "attractive", "austere", "authentic", "authorized", "automatic", "avaricious", "average", "aware", "awesome", "awful", "awkward", "babyish", "bad", "back", "baggy", "bare", "barren", "basic", "beautiful", "belated", "beloved", "beneficial", "better", "best", "bewitched", "big", "big-hearted", "biodegradable", "bite-sized", "bitter", "black", "black-and-white", "bland", "blank", "blaring", "bleak", "blind", "blissful", "blond", "blue", "blushing", "bogus", "boiling", "bold", "bony", "boring", "bossy", "both", "bouncy", "bountiful", "bowed", "brave", "breakable", "brief", "bright", "brilliant", "brisk", "broken", "bronze", "brown", "bruised", "bubbly", "bulky", "bumpy", "buoyant", "burdensome", "burly", "bustling", "busy", "buttery", "buzzing", "calculating", "calm", "candid", "canine", "capital", "carefree", "careful", "careless", "caring", "cautious", "cavernous", "celebrated", "charming", "cheap", "cheerful", "cheery", "chief", "chilly", "chubby", "circular", "classic", "clean", "clear", "clear-cut", "clever", "close", "closed", "cloudy", "clueless", "clumsy", "cluttered", "coarse", "cold", "colorful", "colorless", "colossal", "comfortable", "common", "compassionate", "competent", "complete", "complex", "complicated", "composed", "concerned", "concrete", "confused", "conscious", "considerate", "constant", "content", "conventional", "cooked", "cool", "cooperative", "coordinated", "corny", "corrupt", "costly", "courageous", "courteous", "crafty", "crazy", "creamy", "creative", "creepy", "criminal", "crisp", "critical", "crooked", "crowded", "cruel", "crushing", "cuddly", "cultivated", "cultured", "cumbersome", "curly", "curvy", "cute", "cylindrical", "damaged", "damp", "dangerous", "dapper", "daring", "darling", "dark", "dazzling", "dead", "deadly", "deafening", "dear", "dearest", "decent", "decimal", "decisive", "deep", "defenseless", "defensive", "defiant", "deficient", "definite", "definitive", "delayed", "delectable", "delicious", "delightful", "delirious", "demanding", "dense", "dental", "dependable", "dependent", "descriptive", "deserted", "detailed", "determined", "devoted", "different", "difficult", "digital", "diligent", "dim", "dimpled", "dimwitted", "direct", "disastrous", "discrete", "disfigured", "disgusting", "disloyal", "dismal", "distant", "downright", "dreary", "dirty", "disguised", "dishonest", "dismal", "distant", "distinct", "distorted", "dizzy", "dopey", "doting", "double", "downright", "drab", "drafty", "dramatic", "dreary", "droopy", "dry", "dual", "dull", "dutiful", "each", "eager", "earnest", "early", "easy", "easy-going", "ecstatic", "edible", "educated", "elaborate", "elastic", "elated", "elderly", "electric", "elegant", "elementary", "elliptical", "embarrassed", "embellished", "eminent", "emotional", "empty", "enchanted", "enchanting", "energetic", "enlightened", "enormous", "enraged", "entire", "envious", "equal", "equatorial", "essential", "esteemed", "ethical", "euphoric", "even", "evergreen", "everlasting", "every", "evil", "exalted", "excellent", "exemplary", "exhausted", "excitable", "excited", "exciting", "exotic", "expensive", "experienced", "expert", "extraneous", "extroverted", "extra-large", "extra-small", "fabulous", "failing", "faint", "fair", "faithful", "fake", "false", "familiar", "famous", "fancy", "fantastic", "far", "faraway", "far-flung", "far-off", "fast", "fat", "fatal", "fatherly", "favorable", "favorite", "fearful", "fearless", "feisty", "feline", "female", "feminine", "few", "fickle", "filthy", "fine", "finished", "firm", "first", "firsthand", "fitting", "fixed", "flaky", "flamboyant", "flashy", "flat", "flawed", "flawless", "flickering", "flimsy", "flippant", "flowery", "fluffy", "fluid", "flustered", "focused", "fond", "foolhardy", "foolish", "forceful", "forked", "formal", "forsaken", "forthright", "fortunate", "fragrant", "frail", "frank", "frayed", "free", "French", "fresh", "frequent", "friendly", "frightened", "frightening", "frigid", "frilly", "frizzy", "frivolous", "front", "frosty", "frozen", "frugal", "fruitful", "full", "fumbling", "functional", "funny", "fussy", "fuzzy", "gargantuan", "gaseous", "general", "generous", "gentle", "genuine", "giant", "giddy", "gigantic", "gifted", "giving", "glamorous", "glaring", "glass", "gleaming", "gleeful", "glistening", "glittering", "gloomy", "glorious", "glossy", "glum", "golden", "good", "good-natured", "gorgeous", "graceful", "gracious", "grand", "grandiose", "granular", "grateful", "grave", "gray", "great", "greedy", "green", "gregarious", "grim", "grimy", "gripping", "grizzled", "gross", "grotesque", "grouchy", "grounded", "growing", "growling", "grown", "grubby", "gruesome", "grumpy", "guilty", "gullible", "gummy", "hairy", "half", "handmade", "handsome", "handy", "happy", "happy-go-lucky", "hard", "hard-to-find", "harmful", "harmless", "harmonious", "harsh", "hasty", "hateful", "haunting", "healthy", "heartfelt", "hearty", "heavenly", "heavy", "hefty", "helpful", "helpless", "hidden", "hideous", "high", "high-level", "hilarious", "hoarse", "hollow", "homely", "honest", "honorable", "honored", "hopeful", "horrible", "hospitable", "hot", "huge", "humble", "humiliating", "humming", "humongous", "hungry", "hurtful", "husky", "icky", "icy", "ideal", "idealistic", "identical", "idle", "idiotic", "idolized", "ignorant", "ill", "illegal", "ill-fated", "ill-informed", "illiterate", "illustrious", "imaginary", "imaginative", "immaculate", "immaterial", "immediate", "immense", "impassioned", "impeccable", "impartial", "imperfect", "imperturbable", "impish", "impolite", "important", "impossible", "impractical", "impressionable", "impressive", "improbable", "impure", "inborn", "incomparable", "incompatible", "incomplete", "inconsequential", "incredible", "indelible", "inexperienced", "indolent", "infamous", "infantile", "infatuated", "inferior", "infinite", "informal", "innocent", "insecure", "insidious", "insignificant", "insistent", "instructive", "insubstantial", "intelligent", "intent", "intentional", "interesting", "internal", "international", "intrepid", "ironclad", "irresponsible", "irritating", "itchy", "jaded", "jagged", "jam-packed", "jaunty", "jealous", "jittery", "joint", "jolly", "jovial", "joyful", "joyous", "jubilant", "judicious", "juicy", "jumbo", "junior", "jumpy", "juvenile", "kaleidoscopic", "keen", "key", "kind", "kindhearted", "kindly", "klutzy", "knobby", "knotty", "knowledgeable", "knowing", "known", "kooky", "kosher", "lame", "lanky", "large", "last", "lasting", "late", "lavish", "lawful", "lazy", "leading", "lean", "leafy", "left", "legal", "legitimate", "light", "lighthearted", "likable", "likely", "limited", "limp", "limping", "linear", "lined", "liquid", "little", "live", "lively", "livid", "loathsome", "lone", "lonely", "long", "long-term", "loose", "lopsided", "lost", "loud", "lovable", "lovely", "loving", "low", "loyal", "lucky", "lumbering", "luminous", "lumpy", "lustrous", "luxurious", "mad", "made-up", "magnificent", "majestic", "major", "male", "mammoth", "married", "marvelous", "masculine", "massive", "mature", "meager", "mealy", "mean", "measly", "meaty", "medical", "mediocre", "medium", "meek", "mellow", "melodic", "memorable", "menacing", "merry", "messy", "metallic", "mild", "milky", "mindless", "miniature", "minor", "minty", "miserable", "miserly", "misguided", "misty", "mixed", "modern", "modest", "moist", "monstrous", "monthly", "monumental", "moral", "mortified", "motherly", "motionless", "mountainous", "muddy", "muffled", "multicolored", "mundane", "murky", "mushy", "musty", "muted", "mysterious", "naive", "narrow", "nasty", "natural", "naughty", "nautical", "near", "neat", "necessary", "needy", "negative", "neglected", "negligible", "neighboring", "nervous", "new", "next", "nice", "nifty", "nimble", "nippy", "nocturnal", "noisy", "nonstop", "normal", "notable", "noted", "noteworthy", "novel", "noxious", "numb", "nutritious", "nutty", "obedient", "obese", "oblong", "oily", "oblong", "obvious", "occasional", "odd", "oddball", "offbeat", "offensive", "official", "old", "old-fashioned", "only", "open", "optimal", "optimistic", "opulent", "orange", "orderly", "organic", "ornate", "ornery", "ordinary", "original", "other", "our", "outlying", "outgoing", "outlandish", "outrageous", "outstanding", "oval", "overcooked", "overdue", "overjoyed", "overlooked", "palatable", "pale", "paltry", "parallel", "parched", "partial", "passionate", "past", "pastel", "peaceful", "peppery", "perfect", "perfumed", "periodic", "perky", "personal", "pertinent", "pesky", "pessimistic", "petty", "phony", "physical", "piercing", "pink", "pitiful", "plain", "plaintive", "plastic", "playful", "pleasant", "pleased", "pleasing", "plump", "plush", "polished", "polite", "political", "pointed", "pointless", "poised", "poor", "popular", "portly", "posh", "positive", "possible", "potable", "powerful", "powerless", "practical", "precious", "present", "prestigious", "pretty", "precious", "previous", "pricey", "prickly", "primary", "prime", "pristine", "private", "prize", "probable", "productive", "profitable", "profuse", "proper", "proud", "prudent", "punctual", "pungent", "puny", "pure", "purple", "pushy", "putrid", "puzzled", "puzzling", "quaint", "qualified", "quarrelsome", "quarterly", "queasy", "querulous", "questionable", "quick", "quick-witted", "quiet", "quintessential", "quirky", "quixotic", "quizzical", "radiant", "ragged", "rapid", "rare", "rash", "raw", "recent", "reckless", "rectangular", "ready", "real", "realistic", "reasonable", "red", "reflecting", "regal", "regular", "reliable", "relieved", "remarkable", "remorseful", "remote", "repentant", "required", "respectful", "responsible", "repulsive", "revolving", "rewarding", "rich", "rigid", "right", "ringed", "ripe", "roasted", "robust", "rosy", "rotating", "rotten", "rough", "round", "rowdy", "royal", "rubbery", "rundown", "ruddy", "rude", "runny", "rural", "rusty", "sad", "safe", "salty", "same", "sandy", "sane", "sarcastic", "sardonic", "satisfied", "scaly", "scarce", "scared", "scary", "scented", "scholarly", "scientific", "scornful", "scratchy", "scrawny", "second", "secondary", "second-hand", "secret", "self-assured", "self-reliant", "selfish", "sentimental", "separate", "serene", "serious", "serpentine", "several", "severe", "shabby", "shadowy", "shady", "shallow", "shameful", "shameless", "sharp", "shimmering", "shiny", "shocked", "shocking", "shoddy", "short", "short-term", "showy", "shrill", "shy", "sick", "silent", "silky", "silly", "silver", "similar", "simple", "simplistic", "sinful", "single", "sizzling", "skeletal", "skinny", "sleepy", "slight", "slim", "slimy", "slippery", "slow", "slushy", "small", "smart", "smoggy", "smooth", "smug", "snappy", "snarling", "sneaky", "sniveling", "snoopy", "sociable", "soft", "soggy", "solid", "somber", "some", "spherical", "sophisticated", "sore", "sorrowful", "soulful", "soupy", "sour", "Spanish", "sparkling", "sparse", "specific", "spectacular", "speedy", "spicy", "spiffy", "spirited", "spiteful", "splendid", "spotless", "spotted", "spry", "square", "squeaky", "squiggly", "stable", "staid", "stained", "stale", "standard", "starchy", "stark", "starry", "steep", "sticky", "stiff", "stimulating", "stingy", "stormy", "straight", "strange", "steel", "strict", "strident", "striking", "striped", "strong", "studious", "stunning", "stupendous", "stupid", "sturdy", "stylish", "subdued", "submissive", "substantial", "subtle", "suburban", "sudden", "sugary", "sunny", "super", "superb", "superficial", "superior", "supportive", "sure-footed", "surprised", "suspicious", "svelte", "sweaty", "sweet", "sweltering", "swift", "sympathetic", "tall", "talkative", "tame", "tan", "tangible", "tart", "tasty", "tattered", "taut", "tedious", "teeming", "tempting", "tender", "tense", "tepid", "terrible", "terrific", "testy", "thankful", "that", "these", "thick", "thin", "third", "thirsty", "this", "thorough", "thorny", "those", "thoughtful", "threadbare", "thrifty", "thunderous", "tidy", "tight", "timely", "tinted", "tiny", "tired", "torn", "total", "tough", "traumatic", "treasured", "tremendous", "tragic", "trained", "tremendous", "triangular", "tricky", "trifling", "trim", "trivial", "troubled", "true", "trusting", "trustworthy", "trusty", "truthful", "tubby", "turbulent", "twin", "ugly", "ultimate", "unacceptable", "unaware", "uncomfortable", "uncommon", "unconscious", "understated", "unequaled", "uneven", "unfinished", "unfit", "unfolded", "unfortunate", "unhappy", "unhealthy", "uniform", "unimportant", "unique", "united", "unkempt", "unknown", "unlawful", "unlined", "unlucky", "unnatural", "unpleasant", "unrealistic", "unripe", "unruly", "unselfish", "unsightly", "unsteady", "unsung", "untidy", "untimely", "untried", "untrue", "unused", "unusual", "unwelcome", "unwieldy", "unwilling", "unwitting", "unwritten", "upbeat", "upright", "upset", "urban", "usable", "used", "useful", "useless", "utilized", "utter", "vacant", "vague", "vain", "valid", "valuable", "vapid", "variable", "vast", "velvety", "venerated", "vengeful", "verifiable", "vibrant", "vicious", "victorious", "vigilant", "vigorous", "villainous", "violet", "violent", "virtual", "virtuous", "visible", "vital", "vivacious", "vivid", "voluminous", "wan", "warlike", "warm", "warmhearted", "warped", "wary", "wasteful", "watchful", "waterlogged", "watery", "wavy", "wealthy", "weak", "weary", "webbed", "wee", "weekly", "weepy", "weighty", "weird", "welcome", "well-documented", "well-groomed", "well-informed", "well-lit", "well-made", "well-off", "well-to-do", "well-worn", "wet", "which", "whimsical", "whirlwind", "whispered", "white", "whole", "whopping", "wicked", "wide", "wide-eyed", "wiggly", "wild", "willing", "wilted", "winding", "windy", "winged", "wiry", "wise", "witty", "wobbly", "woeful", "wonderful", "wooden", "woozy", "wordy", "worldly", "worn", "worried", "worrisome", "worse", "worst", "worthless", "worthwhile", "worthy", "wrathful", "wretched", "writhing", "wrong", "wry", "yawning", "yearly", "yellow", "yellowish", "young", "youthful", "yummy", "zany", "zealous", "zesty", "zigzag", "rocky"];

    var name2 = ["people", "history", "way", "art", "world", "information", "map", "family", "government", "health", "system", "computer", "meat", "year", "thanks", "music", "person", "reading", "method", "data", "food", "understanding", "theory", "law", "bird", "literature", "problem", "software", "control", "knowledge", "power", "ability", "economics", "love", "internet", "television", "science", "library", "nature", "fact", "product", "idea", "temperature", "investment", "area", "society", "activity", "story", "industry", "media", "thing", "oven", "community", "definition", "safety", "quality", "development", "language", "management", "player", "variety", "video", "week", "security", "country", "exam", "movie", "organization", "equipment", "physics", "analysis", "policy", "series", "thought", "basis", "boyfriend", "direction", "strategy", "technology", "army", "camera", "freedom", "paper", "environment", "child", "instance", "month", "truth", "marketing", "university", "writing", "article", "department", "difference", "goal", "news", "audience", "fishing", "growth", "income", "marriage", "user", "combination", "failure", "meaning", "medicine", "philosophy", "teacher", "communication", "night", "chemistry", "disease", "disk", "energy", "nation", "road", "role", "soup", "advertising", "location", "success", "addition", "apartment", "education", "math", "moment", "painting", "politics", "attention", "decision", "event", "property", "shopping", "student", "wood", "competition", "distribution", "entertainment", "office", "population", "president", "unit", "category", "cigarette", "context", "introduction", "opportunity", "performance", "driver", "flight", "length", "magazine", "newspaper", "relationship", "teaching", "cell", "dealer", "debate", "finding", "lake", "member", "message", "phone", "scene", "appearance", "association", "concept", "customer", "death", "discussion", "housing", "inflation", "insurance", "mood", "woman", "advice", "blood", "effort", "expression", "importance", "opinion", "payment", "reality", "responsibility", "situation", "skill", "statement", "wealth", "application", "city", "county", "depth", "estate", "foundation", "grandmother", "heart", "perspective", "photo", "recipe", "studio", "topic", "collection", "depression", "imagination", "passion", "percentage", "resource", "setting", "ad", "agency", "college", "connection", "criticism", "debt", "description", "memory", "patience", "secretary", "solution", "administration", "aspect", "attitude", "director", "personality", "psychology", "recommendation", "response", "selection", "storage", "version", "alcohol", "argument", "complaint", "contract", "emphasis", "highway", "loss", "membership", "possession", "preparation", "steak", "union", "agreement", "cancer", "currency", "employment", "engineering", "entry", "interaction", "limit", "mixture", "preference", "region", "republic", "seat", "tradition", "virus", "actor", "classroom", "delivery", "device", "difficulty", "drama", "election", "engine", "football", "guidance", "hotel", "match", "owner", "priority", "protection", "suggestion", "tension", "variation", "anxiety", "atmosphere", "awareness", "bread", "climate", "comparison", "confusion", "construction", "elevator", "emotion", "employee", "employer", "guest", "height", "leadership", "mall", "manager", "operation", "recording", "respect", "sample", "transportation", "boring", "charity", "cousin", "disaster", "editor", "efficiency", "excitement", "extent", "feedback", "guitar", "homework", "leader", "mom", "outcome", "permission", "presentation", "promotion", "reflection", "refrigerator", "resolution", "revenue", "session", "singer", "tennis", "basket", "bonus", "cabinet", "childhood", "church", "clothes", "coffee", "dinner", "drawing", "hair", "hearing", "initiative", "judgment", "lab", "measurement", "mode", "mud", "orange", "poetry", "police", "possibility", "procedure", "queen", "ratio", "relation", "restaurant", "satisfaction", "sector", "signature", "significance", "song", "tooth", "town", "vehicle", "volume", "wife", "accident", "airport", "appointment", "arrival", "assumption", "baseball", "chapter", "committee", "conversation", "database", "enthusiasm", "error", "explanation", "farmer", "gate", "girl", "hall", "historian", "hospital", "injury", "instruction", "maintenance", "manufacturer", "meal", "perception", "pie", "poem", "presence", "proposal", "reception", "replacement", "revolution", "river", "son", "speech", "tea", "village", "warning", "winner", "worker", "writer", "assistance", "breath", "buyer", "chest", "chocolate", "conclusion", "contribution", "cookie", "courage", "desk", "drawer", "establishment", "examination", "garbage", "grocery", "honey", "impression", "improvement", "independence", "insect", "inspection", "inspector", "king", "ladder", "menu", "penalty", "piano", "potato", "profession", "professor", "quantity", "reaction", "requirement", "salad", "sister", "supermarket", "tongue", "weakness", "wedding", "affair", "ambition", "analyst", "apple", "assignment", "assistant", "bathroom", "bedroom", "beer", "birthday", "celebration", "championship", "cheek", "client", "consequence", "departure", "diamond", "dirt", "ear", "fortune", "friendship", "funeral", "gene", "girlfriend", "hat", "indication", "intention", "lady", "midnight", "negotiation", "obligation", "passenger", "pizza", "platform", "poet", "pollution", "recognition", "reputation", "shirt", "speaker", "stranger", "surgery", "sympathy", "tale", "throat", "trainer", "uncle", "youth", "time", "work", "film", "water", "money", "example", "while", "business", "study", "game", "life", "form", "air", "day", "place", "number", "part", "field", "fish", "back", "process", "heat", "hand", "experience", "job", "book", "end", "point", "type", "home", "economy", "value", "body", "market", "guide", "interest", "state", "radio", "course", "company", "price", "size", "card", "list", "mind", "trade", "line", "care", "group", "risk", "word", "fat", "force", "key", "light", "training", "name", "school", "top", "amount", "level", "order", "practice", "research", "sense", "service", "piece", "web", "boss", "sport", "fun", "house", "page", "term", "test", "answer", "sound", "focus", "matter", "kind", "soil", "board", "oil", "picture", "access", "garden", "range", "rate", "reason", "future", "site", "demand", "exercise", "image", "case", "cause", "coast", "action", "age", "bad", "boat", "record", "result", "section", "building", "mouse", "cash", "class", "period", "plan", "store", "tax", "side", "subject", "space", "rule", "stock", "weather", "chance", "figure", "man", "model", "source", "beginning", "earth", "program", "chicken", "design", "feature", "head", "material", "purpose", "question", "rock", "salt", "act", "birth", "car", "dog", "object", "scale", "sun", "note", "profit", "rent", "speed", "style", "war", "bank", "craft", "half", "inside", "outside", "standard", "bus", "exchange", "eye", "fire", "position", "pressure", "stress", "advantage", "benefit", "box", "frame", "issue", "step", "cycle", "face", "item", "metal", "paint", "review", "room", "screen", "structure", "view", "account", "ball", "discipline", "medium", "share", "balance", "bit", "black", "bottom", "choice", "gift", "impact", "machine", "shape", "tool", "wind", "address", "average", "career", "culture", "morning", "pot", "sign", "table", "task", "condition", "contact", "credit", "egg", "hope", "ice", "network", "north", "square", "attempt", "date", "effect", "link", "post", "star", "voice", "capital", "challenge", "friend", "self", "shot", "brush", "couple", "exit", "front", "function", "lack", "living", "plant", "plastic", "spot", "summer", "taste", "theme", "track", "wing", "brain", "button", "click", "desire", "foot", "gas", "influence", "notice", "rain", "wall", "base", "damage", "distance", "feeling", "pair", "savings", "staff", "sugar", "target", "text", "animal", "author", "budget", "discount", "file", "ground", "lesson", "minute", "officer", "phase", "reference", "register", "sky", "stage", "stick", "title", "trouble", "bowl", "bridge", "campaign", "character", "club", "edge", "evidence", "fan", "letter", "lock", "maximum", "novel", "option", "pack", "park", "quarter", "skin", "sort", "weight", "baby", "background", "carry", "dish", "factor", "fruit", "glass", "joint", "master", "muscle", "red", "strength", "traffic", "trip", "vegetable", "appeal", "chart", "gear", "ideal", "kitchen", "land", "log", "mother", "net", "party", "principle", "relative", "sale", "season", "signal", "spirit", "street", "tree", "wave", "belt", "bench", "commission", "copy", "drop", "minimum", "path", "progress", "project", "sea", "south", "status", "stuff", "ticket", "tour", "angle", "blue", "breakfast", "confidence", "daughter", "degree", "doctor", "dot", "dream", "duty", "essay", "father", "fee", "finance", "hour", "juice", "luck", "milk", "mouth", "peace", "pipe", "stable", "storm", "substance", "team", "trick", "afternoon", "bat", "beach", "blank", "catch", "chain", "consideration", "cream", "crew", "detail", "gold", "interview", "kid", "mark", "mission", "pain", "pleasure", "score", "screw", "sex", "shop", "shower", "suit", "tone", "window", "agent", "band", "bath", "block", "bone", "calendar", "candidate", "cap", "coat", "contest", "corner", "court", "cup", "district", "door", "east", "finger", "garage", "guarantee", "hole", "hook", "implement", "layer", "lecture", "lie", "manner", "meeting", "nose", "parking", "partner", "profile", "rice", "routine", "schedule", "swimming", "telephone", "tip", "winter", "airline", "bag", "battle", "bed", "bill", "bother", "cake", "code", "curve", "designer", "dimension", "dress", "ease", "emergency", "evening", "extension", "farm", "fight", "gap", "grade", "holiday", "horror", "horse", "host", "husband", "loan", "mistake", "mountain", "nail", "noise", "occasion", "package", "patient", "pause", "phrase", "proof", "race", "relief", "sand", "sentence", "shoulder", "smoke", "stomach", "string", "tourist", "towel", "vacation", "west", "wheel", "wine", "arm", "aside", "associate", "bet", "blow", "border", "branch", "breast", "brother", "buddy", "bunch", "chip", "coach", "cross", "document", "draft", "dust", "expert", "floor", "god", "golf", "habit", "iron", "judge", "knife", "landscape", "league", "mail", "mess", "native", "opening", "parent", "pattern", "pin", "pool", "pound", "request", "salary", "shame", "shelter", "shoe", "silver", "tackle", "tank", "trust", "assist", "bake", "bar", "bell", "bike", "blame", "boy", "brick", "chair", "closet", "clue", "collar", "comment", "conference", "devil", "diet", "fear", "fuel", "glove", "jacket", "lunch", "monitor", "mortgage", "nurse", "pace", "panic", "peak", "plane", "reward", "row", "sandwich", "shock", "spite", "spray", "surprise", "till", "transition", "weekend", "welcome", "yard", "alarm", "bend", "bicycle", "bite", "blind", "bottle", "cable", "candle", "clerk", "cloud", "concert", "counter", "flower", "grandfather", "harm", "knee", "lawyer", "leather", "load", "mirror", "neck", "pension", "plate", "purple", "ruin", "ship", "skirt", "slice", "snow", "specialist", "stroke", "switch", "trash", "tune", "zone", "anger", "award", "bid", "bitter", "boot", "bug", "camp", "candy", "carpet", "cat", "champion", "channel", "clock", "comfort", "cow", "crack", "engineer", "entrance", "fault", "grass", "guy", "hell", "highlight", "incident", "island", "joke", "jury", "leg", "lip", "mate", "motor", "nerve", "passage", "pen", "pride", "priest", "prize", "promise", "resident", "resort", "ring", "roof", "rope", "sail", "scheme", "script", "sock", "station", "toe", "tower", "truck", "witness", "can", "will", "other", "use", "make", "good", "look", "help", "go", "great", "being", "still", "public", "read", "keep", "start", "give", "human", "local", "general", "specific", "long", "play", "feel", "high", "put", "common", "set", "change", "simple", "past", "big", "possible", "particular", "major", "personal", "current", "national", "cut", "natural", "physical", "show", "try", "check", "second", "call", "move", "pay", "let", "increase", "single", "individual", "turn", "ask", "buy", "guard", "hold", "main", "offer", "potential", "professional", "international", "travel", "cook", "alternative", "special", "working", "whole", "dance", "excuse", "cold", "commercial", "low", "purchase", "deal", "primary", "worth", "fall", "necessary", "positive", "produce", "search", "present", "spend", "talk", "creative", "tell", "cost", "drive", "green", "support", "glad", "remove", "return", "run", "complex", "due", "effective", "middle", "regular", "reserve", "independent", "leave", "original", "reach", "rest", "serve", "watch", "beautiful", "charge", "active", "break", "negative", "safe", "stay", "visit", "visual", "affect", "cover", "report", "rise", "walk", "white", "junior", "pick", "unique", "classic", "final", "lift", "mix", "private", "stop", "teach", "western", "concern", "familiar", "fly", "official", "broad", "comfortable", "gain", "rich", "save", "stand", "young", "heavy", "lead", "listen", "valuable", "worry", "handle", "leading", "meet", "release", "sell", "finish", "normal", "press", "ride", "secret", "spread", "spring", "tough", "wait", "brown", "deep", "display", "flow", "hit", "objective", "shoot", "touch", "cancel", "chemical", "cry", "dump", "extreme", "push", "conflict", "eat", "fill", "formal", "jump", "kick", "opposite", "pass", "pitch", "remote", "total", "treat", "vast", "abuse", "beat", "burn", "deposit", "print", "raise", "sleep", "somewhere", "advance", "consist", "dark", "double", "draw", "equal", "fix", "hire", "internal", "join", "kill", "sensitive", "tap", "win", "attack", "claim", "constant", "drag", "drink", "guess", "minor", "pull", "raw", "soft", "solid", "wear", "weird", "wonder", "annual", "count", "dead", "doubt", "feed", "forever", "impress", "repeat", "round", "sing", "slide", "strip", "wish", "combine", "command", "dig", "divide", "equivalent", "hang", "hunt", "initial", "march", "mention", "spiritual", "survey", "tie", "adult", "brief", "crazy", "escape", "gather", "hate", "prior", "repair", "rough", "sad", "scratch", "sick", "strike", "employ", "external", "hurt", "illegal", "laugh", "lay", "mobile", "nasty", "ordinary", "respond", "royal", "senior", "split", "strain", "struggle", "swim", "train", "upper", "wash", "yellow", "convert", "crash", "dependent", "fold", "funny", "grab", "hide", "miss", "permit", "quote", "recover", "resolve", "roll", "sink", "slip", "spare", "suspect", "sweet", "swing", "twist", "upstairs", "usual", "abroad", "brave", "calm", "concentrate", "estimate", "grand", "male", "mine", "prompt", "quiet", "refuse", "regret", "reveal", "rush", "shake", "shift", "shine", "steal", "suck", "surround", "bear", "brilliant", "dare", "dear", "delay", "drunk", "female", "hurry", "inevitable", "invite", "kiss", "neat", "pop", "punch", "quit", "reply", "representative", "resist", "rip", "rub", "silly", "smile", "spell", "stretch", "stupid", "tear", "temporary", "tomorrow", "wake", "wrap", "yesterday", "Thomas", "Tom", "Lieuwe"];

    var name = capFirst(name1[getRandomInt(0, name1.length + 1)]) + ' ' + capFirst(name2[getRandomInt(0, name2.length + 1)]);
    return name;

}