const images = ["./html5.png", "./css3.png", "./js.png"];
var idle = "./web.png";
var randomarray = [];
var turned = [];

document.addEventListener("DOMContentLoaded", function (){
    var numbers = [[0,0], [1,0], [2,0]];
    while(true){
        var pos = Math.floor(Math.random() * 3);
        if(numbers[pos][1] < 2){
            randomarray.push(numbers[pos][0]);
            numbers[pos][1]++;
        }
        var occurences = [];
        for(var i = 0; i < 3; i++){
            occurences.push(numbers[i][1]);
        }
        if(!occurences.includes(0) && !occurences.includes(1))
            break;
    }

    var cards = document.getElementsByTagName("img");
    for(var i = 0; i < cards.length; i++){
        cards[i].addEventListener("click", function (){

        if(turned.length < 2){
            this.classList.add("turned");
            var index = Array.from(cards).indexOf(this);
            this.src = images[randomarray[index]];
            turned.push(index);
            if(turned.length == 2){
                setTimeout(function (){
                    if(Array.from(cards)[turned[0]].src != Array.from(cards)[turned[1]].src){
                        Array.from(cards)[turned[0]].src = idle;
                        Array.from(cards)[turned[0]].classList = "";
                        Array.from(cards)[turned[1]].src = idle;
                        Array.from(cards)[turned[1]].classList = "";
                        turned = [];
                    }else{
                        Array.from(cards)[turned[0]].classList = "found";
                        Array.from(cards)[turned[1]].classList = "found";
                        turned = [];
                        document.getElementById("info").innerText = "Megtalált egy kártyát!";
                    }
                    var ended = true
                    cards = Array.from(cards);
                    for(var j = 0; j < cards.length; j++){
                        if(!cards[j].classList.contains("found")){
                            ended = false;
                            break;
                        }
                    }
                    if(ended){
                        document.getElementById("info").innerText = "Megtalált minden kártyát!";
                    }
                }, 2000)
            }
        }

        });
    }
});