var BlackJackAdd = {};

var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, resId = 0, totalMarks = 100;
$(document).ready(function () {
    $(".se-pre-con").fadeOut("slow");
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
        Utils.mobileDeviceFlag = true;
    setTimeout(function () {
        BlackJackAdd.setImages();
        BlackJackAdd.AcknowledgementPage();
        BlackJackAdd.initializeVar();
    }, 200);
});

BlackJackAdd.setImages = function () {
    $('#home').prop('src', Utils.Path + 'images/Home.png');
    $('#logo').prop('src', Utils.Path + 'images/logo.png');
    $('#playImage').prop('src', Utils.Path + 'images/Play.png');
    $('#playGame').prop('src', Utils.Path + 'images/Play.png');
    $('#playAgain').prop('src', Utils.Path + 'images/playAgain.png');
    $('#nextQue').prop('src', Utils.Path + 'images/Next.png');
    $('#credit').prop('src', Utils.Path + 'images/credits.png');
    $('#checkAns').prop('src', Utils.Path + 'images/Done.png');
    $('#correctAns').prop('src','images/correct.png');
    $('.trailDiv').css('background-image', "url(" + Utils.Path + 'images/BOX.png' + ")");
    $('#cancelImg').prop('src', Utils.Path + 'images/Discard.png');
    $("body").css("background-image", "url(" + Utils.Path + 'images/background1.jpg' + ")");
}

BlackJackAdd.showInstruction = function () {
    $('#coverPage').hide();
    $('.instructionDiv').show();
    $('#homeDiv').css('visibility', 'visible');
    $("body").css("background-image", "url(" + Utils.Path + 'images/insideBg.jpg' + ")");
    $('#playInstruction').text(BlackJackAdd.instruction['playInstruction']);
    $('.rejectOptn').css('pointer-events', 'none');
    $('.unitDiv').css('pointer-events', 'none');
    document.getElementById('instruction').innerHTML = BlackJackAdd.instruction['instruction'];
}

function flipCard(id) {
    $('.flip-card').css('pointer-events', 'none');
    $('#' + id).next().css("margin-left", "-3vw");
    $('.unitDiv').css('pointer-events', 'auto');
    $('.rejectOptn').css('pointer-events', 'auto');
    BlackJackAdd.element = 0;
    BlackJackAdd.clickedCard = id;
    BlackJackAdd.generateRndmNo();
    var p = document.createElement('p');
    $(p).prop('class', 'num');
    $(p).text(BlackJackAdd.random);
    $('#'+id).css('transform' , 'rotateY(-180deg)');
    document.getElementById(id).style.zIndex = '1';
    BlackJackAdd.element = $('#' + id).children()[0];
    $(BlackJackAdd.element).append(p);
    $(BlackJackAdd.element).css('position', 'relative');
}

BlackJackAdd.initializeVar = function () {
    BlackJackAdd.questionArr = [];
    BlackJackAdd.questionCnt = 0;
    BlackJackAdd.count = 0;
    BlackJackAdd.noOfChances = 10;
    BlackJackAdd.nextQueTimer = 0;
    BlackJackAdd.gamePlayedFlag = false;
    BlackJackAdd.insideGame = false;
    BlackJackAdd.scorePageTimer = 0;
    $('.remainTxt').text(BlackJackAdd.instruction['chances']);
    BlackJackAdd.createCards(3, "QueCard", 'queCard', 'nopadding queDiv text-center col-xs-4 col-sm-4 col-lg-4 col-md-4', 'images/Card_01.png', 'queSpan');
    BlackJackAdd.createCards(3, "ansCard", 'ans', 'nopadding ansDiv text-center col-xs-4 col-sm-4 col-lg-4 col-md-4', 'images/Card_02.png', 'ansSpan');
    BlackJackAdd.createCards(3, "unitCards", 'unitCard', 'nopadding unitDiv text-center col-xs-4 col-sm-4 col-lg-4 col-md-4', 'images/Card_03.png', 'unitSpan');
    BlackJackAdd.addUnitTxt();
    BlackJackAdd.createPlacedCards();
    $('.checkAnsDiv').css('pointer-events', 'none');
}
BlackJackAdd.createCards = function (length, parentDiv, id, className, source, spanClass) {
    for (var i = 0; i < length; i++) {
        var div = document.createElement('div');
        $(div).prop('id', id + (i + 1));
        $(div).prop('class', className);
        $(div).css('background-image', "url(" + Utils.Path + source + ")")
        $('.' + parentDiv).append(div);

        var span = document.createElement('span');
        $(span).prop('id', id + 'span' + (i + 1));
        $(span).prop('class', spanClass);
        $(span).css({ 'position': 'relative' });
        $(div).append(span);
    }
}

BlackJackAdd.createPlacedCards = function () {
    $('.playing-card').empty();
    for (var i = 0; i < 10; i++) {
        var div, cardDiv, img;
        div = document.createElement('div');
        if (i == 0)
            $(div).prop('class', 'firstCard flip-card');
        else
            $(div).prop('class', 'flip-card');
        $(div).prop('id', 'div' + (i + 1));
        $('.playing-card').append(div);
        $(div).on('click', function () {
            flipCard(this.id);
        })
        for (var j = 0; j < 2; j++) {
            cardDiv = document.createElement('div');
            img = document.createElement('img');
            $(div).append(cardDiv);
            $(cardDiv).append(img);
            if (j == 0) {
                $(cardDiv).prop('class', 'card-front');
                $(img).prop('src', 'images/Card_01.png');
            }
            else {
                $(cardDiv).prop('class', 'card-back');
                $(img).prop('src', 'images/back.png');
            }
        }
    }
}

BlackJackAdd.addUnitTxt = function () {
    for (var i = 0; i < BlackJackAdd.unitArr.length; i++) {
        $('#unitCardspan' + (i + 1)).text(BlackJackAdd.unitArr[i].unit);
        $('#unitCardspan' + (i + 1)).data('value', BlackJackAdd.unitArr[i]['zeroes']);
        $('#unitCardspan' + (i + 1)).click(function () {
            BlackJackAdd.unitsClicked(this.id);
        });
    }
}
BlackJackAdd.playGame = function () {
    BlackJackAdd.insideGame = true;
    $('.instructionDiv').hide();
    $("body").css("background-image", "url(" + Utils.Path + 'images/background.jpg' + ")");
    $('#gamePage').show();
    $('#question').css('visibility', 'visible');
    //BlackJackAdd.createUnitDiv();
    BlackJackAdd.generateQuestion();
    BlackJackAdd.showQuestion();
}

BlackJackAdd.generateQuestion = function () {
    var number;
    for (var i = 0; i < 5; i++) {
        number = Math.floor(Math.random() * 1000) + 11;
        if (BlackJackAdd.questionArr.includes(number)) {
            i--;
            continue;
        }
        else
            BlackJackAdd.questionArr.push(number);
    }
}

BlackJackAdd.showQuestion = function () {
    var d;
    scoredMarks = 0;
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    BlackJackAdd.count = 0;
    BlackJackAdd.createPlacedCards();
    var que = BlackJackAdd.questionArr[BlackJackAdd.questionCnt].toString().split('');
   /*  for (var i = 0; i < que.length; i++)
        $('#queCardspan' + (i + 1)).text(que[i]); */
    
    for(var i = 0; i < que.length; i++)
    {
        if(que.length==1)
            $('#queCardspan'+(i+3)).text(que[i]);
        else if(que.length==2)
            $('#queCardspan'+(i+2)).text(que[i]);
        else
            $('#queCardspan'+(i+1)).text(que[i]);
    }
}

BlackJackAdd.generateRndmNo = function () {
    BlackJackAdd.random;
    //$('#number').addClass('bounceIn');
    if (BlackJackAdd.noOfChances > 0) {
        $('.chances').text(BlackJackAdd.noOfChances);
        BlackJackAdd.random = Math.floor(Math.random() * 9) + 1;
        // $('.num').text(random);
        //$('#number').removeClass('bounceIn');
    }
    else
        BlackJackAdd.checkAnswer();
}

BlackJackAdd.removeNumber = function () {
    BlackJackAdd.noOfChances--;
    //$(BlackJackAdd.element).parent().hide();
    $('.flip-card').css('pointer-events', 'auto');
    $('.rejectOptn').css('pointer-events', 'none');
    $('.unitDiv').css('pointer-events', 'none');
    $(BlackJackAdd.element).parent().next().css('margin-left', '3vw');
    BlackJackAdd.generateRndmNo();
    $(BlackJackAdd.element).parent().remove();
}

BlackJackAdd.unitsClicked = function (id) {
    $('#playSound').prop('src','sound/unitClick.mp3');
    document.getElementById('playSound').play();
    BlackJackAdd.noOfChances--;
    $(BlackJackAdd.element).parent().next().css('margin-left', '3vw');
    BlackJackAdd.gamePlayedFlag = true;
    $('.flip-card').css('pointer-events', 'auto');
    $('.rejectOptn').css('pointer-events', 'none');
    $('.unitDiv').css('pointer-events', 'none');
    $('.checkAnsDiv').css('pointer-events', 'auto');
    var data = $('#' + id).data('value');
    //$('.trailNo').append($('.num').text() + data + '+');
    BlackJackAdd.count = BlackJackAdd.count + parseInt($('.num').text() + data);
    $('.trailNo').text($('.num').text() + data);
    var ans = BlackJackAdd.count.toString().split('');
    for(var i=0;i<ans.length;i++)
    {
        if(ans.length==1)
            $('#ansspan'+(i+3)).text(ans[i]);
        else if(ans.length==2)
            $('#ansspan'+(i+2)).text(ans[i]);
        else
            $('#ansspan'+(i+1)).text(ans[i]);
    }
    var answer = 0;
    answer = parseInt(BlackJackAdd.count);
    if (answer < BlackJackAdd.questionArr[BlackJackAdd.questionCnt]) {
        var number = parseInt(BlackJackAdd.clickedCard.substr(3, 4));
        $('#div' + (number - 1)).css('pointer-events', 'auto');
        BlackJackAdd.generateRndmNo();
    }
    else
        BlackJackAdd.checkAnswer();

    $(BlackJackAdd.element).parent().remove();
}


BlackJackAdd.checkAnswer = function () {
    var answer = 0;
    $('.checkAnsDiv').css('pointer-events', 'none');
    $('.imgDiv').hide();
    $('#result').text('');
    answer = BlackJackAdd.count;
    if(BlackJackAdd.noOfChances<=0)
        $('#result').text(BlackJackAdd.instruction['chancesOver']);
    if (answer == BlackJackAdd.questionArr[BlackJackAdd.questionCnt]) {
        $('.imgDiv').show();
        $('#playSound').prop('src','sound/You_did_it.mp3');
        $('.flip-card').css('pointer-events', 'none');
        scoredMarks=100;
        BlackJackAdd.correctCnt++;
        clearInterval(BlackJackAdd.noResponseTimer);
        $('#result').text('');
        document.getElementById('playSound').pause();
    }
    else if (answer > BlackJackAdd.questionArr[BlackJackAdd.questionCnt]) {
        $('.flip-card').css('pointer-events', 'none');
        scoredMarks = 0;
        $('#result').text(BlackJackAdd.instruction['exceedAns']);
        $('#playSound').prop('src','sound/Try_again.mp3');
        clearInterval(BlackJackAdd.noResponseTimer);
        document.getElementById('playSound').pause();
    }
    else if ((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 1)) <= answer) && (answer >= BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 10))))
        scoredMarks = 90;
    else if ((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 10)) <= answer) && (answer >= BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 30))))
        scoredMarks = 70;
    else if ((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 30)) <= answer) && (answer >= BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 50))))
        scoredMarks = 50;
    else if ((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 50)) <= answer) && (answer >= BlackJackAdd.questionArr[BlackJackAdd.questionCnt] - Math.round((BlackJackAdd.questionArr[BlackJackAdd.questionCnt] / 100 * 100))))
        scoredMarks = 20;
    BlackJackAdd.scorePageTimer = setTimeout(function () {
        BlackJackAdd.showScorePage(scoredMarks);
    }, 4000);
    document.getElementById('playSound').play();
    //BlackJackAdd.showScorePage(scoredMarks);

}

BlackJackAdd.nextQue = function () {
    clearTimeout(BlackJackAdd.scorePageTimer);
    clearTimeout(BlackJackAdd.nextQueTimer);
    BlackJackAdd.addScore();
    BlackJackAdd.questionCnt++;
    if (BlackJackAdd.questionCnt > 4)
        BlackJackAdd.showLastPage();
    else {
        BlackJackAdd.resetVariables();
        BlackJackAdd.showQuestion();
    }
}

BlackJackAdd.addScore = function () {
    if (BlackJackAdd.gamePlayedFlag && Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, BlackJackAdd.questionArr[BlackJackAdd.questionCnt]);
    else if (BlackJackAdd.gamePlayedFlag == false && Utils.mobileDeviceFlag) {
        scoredMarks = -1;
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, BlackJackAdd.questionArr[BlackJackAdd.questionCnt]);
    }
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, BlackJackAdd.questionArr[BlackJackAdd.questionCnt]);
}

BlackJackAdd.resetVariables = function () {
    $('.trailNo').empty();
    $("body").css("background-image", "url(" + Utils.Path + 'images/background.jpg' + ")");
    $('.checkAnsDiv').css('pointer-events', 'none');
    $('.ansSpan').empty();
    $('.queSpan').empty();
    $('.flip-card').show();
    $('.flip-card').css('pointer-events', 'auto');
    $('.flip-card').css('transform', 'rotateY(0deg)');
    $('.card-front').css('position', 'absolute');
    BlackJackAdd.noOfChances = 10;
    BlackJackAdd.gamePlayedFlag = false;
    $('.scorePage').hide();
    $('#gamePage').show();
    $('#gamePage').css('opacity', '1');
    // $('#number').removeClass('bounceIn');
    //$('#answerDiv').text(0);
}
BlackJackAdd.showScorePage = function (marks) {
    $("body").css("background-image", "url(" + Utils.Path + 'images/insideBg.jpg' + ")");
    $('#gamePage').hide();
    $(".progress").each(function () {
        $('.scorePage').show();
        $('#score').text(marks);
        var value = marks;
        var left = $(this).find('.progress-left .progress-bar');
        var right = $(this).find('.progress-right .progress-bar');
        left.css('transform', 'rotate(0deg)');
        right.css('transform', 'rotate(0deg)');
        if (value > 0) {
            if (value <= 50) {
                left.css('transform', 'rotate(' + percentageToDegrees(-value) + 'deg)')
            } else {
                left.css('transform', 'rotate(180deg)')
                right.css('transform', 'rotate(' + percentageToDegrees(-value - 50) + 'deg)')//(-value)to move the progress bar anticlockwise 
            }
        }
    })

    function percentageToDegrees(percentage) {
        return percentage / 100 * 360
    }
    BlackJackAdd.nextQueTimer = setTimeout(function () {
        BlackJackAdd.nextQue();
    }, 2000);

}
BlackJackAdd.showLastPage = function () {
    $("body").css("background-image", "url(" + Utils.Path + 'images/background.jpg' + ")");
    BlackJackAdd.gamePlayedFlag = false;
    $('#gameOver').text(BlackJackAdd.hardCodedData['gameOver']);
    $('#gamePage').hide();
    $('.scorePage').hide();
    $('#endpage').show();
}

BlackJackAdd.AcknowledgementPage = function () {
    var i = 0, div;
    for (i = 0; i < Object.keys(BlackJackAdd.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.className = "ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(BlackJackAdd.AcknowledgementPageData)[i] + " : " + Object.values(BlackJackAdd.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.className = "ackFontClass text-center firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = BlackJackAdd.hardCodedData['createdOn'];
    acknowledgementDiv.appendChild(div);
}

BlackJackAdd.showCredits = function () {
    $("#acknowledgementDiv").css('visibility', 'visible');
}

BlackJackAdd.playAgain = function () {
    BlackJackAdd.questionArr = [];
    BlackJackAdd.questionCnt = 0;
    BlackJackAdd.count = 0;
    $('#question').css('visibility', 'visible');
    $('#gamePage').show();
    $("#acknowledgementDiv").css('visibility', 'hidden');
    $('#endpage').hide();
    BlackJackAdd.resetVariables();
    BlackJackAdd.generateQuestion();
    BlackJackAdd.showQuestion();
}

BlackJackAdd.backToHome = function () {
    clearTimeout(BlackJackAdd.nextQueTimer);
    clearTimeout(BlackJackAdd.scorePageTimer);
    if (BlackJackAdd.insideGame) {
        if (BlackJackAdd.gamePlayedFlag && Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, BlackJackAdd.questionArr[BlackJackAdd.questionCnt]);
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, BlackJackAdd.questionArr[BlackJackAdd.questionCnt]);
        BlackJackAdd.resetVariables();
        BlackJackAdd.questionArr = [];
        BlackJackAdd.questionCnt = 0;
        BlackJackAdd.count = 0;
        $('#gamePage').hide();
        $('.scorePage').hide();
        $('#endpage').hide();
        BlackJackAdd.insideGame=false;
        $("body").css("background-image", "url(" + Utils.Path + 'images/insideBg.jpg' + ")");
        $('.instructionDiv').show();
    }
    else
        location.reload(true);
}