var songList = [];
var score = 0;
function init() {
    if (location.protocol == 'https:')
    {
        $("body").html("Redirecting...");
        location.href = 'http:' + window.location.href.substring(window.location.protocol.length);
    }
    songList[0] = [-1009169830]
    songList[1] = [-484681682]
    songList[2] = [-1378765040, 207956753]
    songList[3] = [180022012, -1377878990, 166658638]
    songList[4] = [-906861987, 99794, -69782447, 1671227740, 1706497596, -1423583114, 838850881, 458281287, 612358689]
    songList[5] = [-1732262507, 675981032]
    songList[6] = [-2084646130, -934233253, -935186565, 1045048207, -130025982, 366743004, 1162583023, 1994383945, -2084646130, 297490804]
    songList[7] = [-1017764262, 833314096]
    songList[8] = [1411307003, -1129977149]
    songList[9] = [-583544118, 101498, 1890880935, -2080529108, -1141712506, 281076844, 3146536, 97541474]
    songList[10] = [2105963451]
    songList[11] = [821640828, 796705761]
    songList[12] = [-917452295, 32946026]
    songList[13] = [-1386464949]
    songList[14] = [-262531414, 248048931, -723597402]
    songList[15] = [1544589690]
    songList[16] = [80169656, 1171623735, -2082848912]
    songList[17] = [-1049115641, -1458723995, 457145172]
    songList[18] = [-1580411253]
    songList[19] = [1901311216, -1220896846, 484446924, 930901477, 1837689483]
    songList[20] = [-902184760]
    songList[21] = [550926881]
    songList[22] = [-205294050]
    songList[23] = [-348132344, -1837805572, -975171460, -1580937976]
    songList[24] = [-490625305, -2096018765, 1638321923, -224245572, 0]
    songList[25] = [373193180, 387045995]
    songList[26] = [857438445]
    songList[27] = [461857932, -956455090, -86423417]
    songList[28] = [1785927165]
    songList[29] = [-1381206087, 921249901]
    songList[30] = [617008820]
    songList[31] = [3343734, 1625158288, -1199880610]
    songList[32] = [-1052666831]
    songList[33] = [-1418074464, 52120001, 186509999, 1849609200, 1816004795, 2124241407]
    songList[34] = [529824201]
    songList[35] = [1574712300]
    songList[36] = [727666068, -1081719115, 80305061, -299087837]
    songList[37] = [2113945566, -347450205]
    songList[38] = [-439676749, 113633]
    songList[39] = [-676611124]
}

function addToGrid() {
    for (var i = 0; i < songList.length; i++) {
        $(".row").append(
            "<div class='col-lg-4 music-box' id='col" + songList[i][0].toString() + "'>" +
            "<audio controls id='aud" + songList[i][0].toString() + "' onended='chageIconToPlay(" + songList[i][0].toString() + ")'>" +
            "<source src='Assets/ogg/" + songList[i][0].toString() + ".ogg' type='audio/ogg'>" +
            "</audio>" +
            "<img src='Assets/png/play-button.png' class='play' id='img" + songList[i][0].toString() + "' onclick='playAndChangeImage(" + songList[i][0].toString() + ")'>" +
            "<br>" +
            "<input type='text' placeholder='What anime is the OP from?' id='" + songList[i][0].toString() + "' class='form-control'>" +
            "<button type='button' id='but" + songList[i][0].toString() + "' class='btn btn-success' onclick='checkName(" + songList[i][0] + ")' >Check</button>" +
            "<br>" +
            "<button type='button' id='ans" + songList[i][0].toString() + "' class='btn btn-success ans' onclick='showAnswer(" + songList[i][0] + ")' >Show Answer</button>" +
            "<br>" +
            "<img src='Assets/png/error.png' style='display: none' class='result' id='res" + songList[i][0].toString() + "'>" +
            "</div>"
        );
        //check textboxes values and give appropriate answer
        if(localStorage.getItem(songList[i][0]) && localStorage.getItem(songList[i][0]).includes('CHECKED FOR ANSWER')) {
            //set textboxes to saved values
            $('#' + songList[i][0]).val(localStorage.getItem(songList[i][0]).substring(0, localStorage.getItem(songList[i][0]).indexOf('CHECKED FOR ANSWER') - 1));
            $("#but" + songList[i][0]).prop('disabled', true);
            $("#ans" + songList[i][0]).prop('disabled', true);
            $("#" + songList[i][0]).prop('disabled', true);
            $('#col' + songList[i][0])[0].style.backgroundColor = 'rgba(194, 116, 36, 0.5)';
        } else {
            //set textboxes to saved values
            $('#' + songList[i][0]).val(localStorage.getItem(songList[i][0]));
            if(localStorage.getItem(songList[i][0]) !== null && localStorage.getItem(songList[i][0]) !== '') {
                $('#but' + songList[i][0])[0].click();
            }
        }
    }
}
// taken from stackOverflow
String.prototype.hashCode = function () {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
        chr = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

function reset() {
    if($('#resetText').text() === 'Reset') {
        $('#resetText').fadeOut(100, function() {
            $(this).text('Are You Sure?').fadeIn(100);
        });
        var interval = setInterval(function() {
            $('#resetText').fadeOut(100, function() {
                $(this).text('Reset').fadeIn(100);
            });
            clearInterval(interval);
        }, 5000)
    } else if($('#resetText').text() === 'Are You Sure?') {
        localStorage.clear();
        location.reload();
    }
}

function showAnswer(hash) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            $('#' + hash).val(this.responseText);
       }
    };
    xhttp.open("GET", `http://Animegame-env.5jpsrm2bpc.us-east-1.elasticbeanstalk.com/?hash=${hash}`, false);
    xhttp.send()
    $('#res' + hash).toggle('slow');
    $("#but" + hash).prop('disabled', true);
    $("#ans" + hash).prop('disabled', true);
    $("#" + hash).prop('disabled', true);
    $('#col' + hash)[0].style.backgroundColor = 'rgba(194, 116, 36, 0.5)';
    localStorage.setItem(hash, $('#' + hash).val() + ' CHECKED FOR ANSWER');
}

//hash is the hash of the first name given to the song that the music box correspond to
function checkName(hash) {
    let correct = false;
    songList.forEach((value) => {
        if (value[0] === hash) {
            value.forEach((hashValue) => {
                if (hashValue === $('#' + hash).val().toLowerCase().hashCode()) {
                    correct = true;
                }
            });
        }
    });
    if (correct) {
        if (($('#res' + hash)[0].src.includes('Assets/png/error.png') || $('#res' + hash)[0].style.display === 'none')) {
            score++;
        }
        showResult(hash, 'success');
        $("#ans" + hash).prop('disabled', true);
        $('#col' + hash)[0].style.backgroundColor = 'rgba(21, 223, 145, 0.5)';
    } else {
        $("#ans" + hash).prop('disabled', false);
        showResult(hash, 'fail');
        $('#col' + hash)[0].style.backgroundColor = 'rgba(155, 43, 43, 0.5)';
    }
    localStorage.setItem(hash, $('#' + hash).val());
    updateScore();
}

function playAndChangeImage(id) {
    $('#aud' + id)[0].currentTime = 0;
    if ($('#img' + id)[0].src.includes('Assets/png/play-button.png')) {
        $('#img' + id)[0].src = 'Assets/png/stop.png';
        $('#aud' + id)[0].play();
    } else {
        $('#img' + id)[0].src = 'Assets/png/play-button.png';
        $('#aud' + id)[0].pause();
    }
}

function chageIconToPlay(id) {
    $('#img' + id)[0].src = 'Assets/png/play-button.png';
}

function showResult(id, res) {
    if (res === 'success') {
        $('#res' + id)[0].src = 'Assets/png/success.png';
        if ($('#res' + id).is(":hidden") || $('#res' + id)[0].src === 'Assets/png/success.png') {
            $('#res' + id).toggle('slow');
        }
    } else {
        if ($('#res' + id)[0].src.includes('Assets/png/success.png')) {
            score--;
        }
        $('#res' + id)[0].src = 'Assets/png/error.png';
        if ($('#res' + id).is(":hidden") || $('#res' + id)[0].src === 'Assets/png/error.png') {
            $('#res' + id).toggle('slow');
        }
    }
}

function addHandlers() {
    document.addEventListener('keydown', function (e) {
        if (e.keyCode === 13) {
            if (document.activeElement.tagName === 'INPUT' && $('#but' + document.activeElement.id)[0]) {
                $('#but' + document.activeElement.id)[0].click();
            }
        }
    })
    document.addEventListener('play', function (e) {
        var audios = document.getElementsByTagName('audio');
        for (var i = 0, len = audios.length; i < len; i++) {
            if (audios[i] != e.target) {
                audios[i].pause();
                $('#img' + audios[i].id.slice(3))[0].src = 'Assets/png/play-button.png';
            }
        }
    }, true);
    $('.play').toArray().forEach((obj) => {
        obj.onwaiting = () => {
            obj.src = 'Assets/png/error.png';
        }
        obj.onplaying = () => {
            obj.src = 'Assets/png/stop.png';
        }
        obj.onplay = () => {
            obj.src = 'Assets/png/stop.png';
        }
        obj.onpause = () => {
            obj.src = 'Assets/png/play-button.png';
        }
        obj.oncanplay = () => {
            obj.src = 'Assets/png/play-button.png';
        }
    })
}

function updateScore() {
    $("#score").html("Score: " + score + "/" + songList.length);
}

init();
addToGrid();
addHandlers();
updateScore();

