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.createStars();
        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/Skip.png');
    $('#nextGame').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/background.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);
    document.getElementById(id).style.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.correctCnt=0;
    BlackJackAdd.gamePlayedFlag=false;
	BlackJackAdd.noResponseTimer=0
    BlackJackAdd.seconds=0;
    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;
    clearInterval(BlackJackAdd.noResponseTimer);
    document.getElementById('playSound').pause();
    BlackJackAdd.startTimer();
    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;
    $('.checkAnsDiv').css('pointer-events', 'none');
    $('.imgDiv').hide();
    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);
    }, 3000);
    document.getElementById('playSound').play();
}

/* 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.skippedQuestion=function()
{	
    clearTimeout(BlackJackAdd.scorePageTimer);
    clearTimeout(BlackJackAdd.nextQueTimer);
    clearInterval(BlackJackAdd.noResponseTimer);
    document.getElementById('playSound').pause();
	if(BlackJackAdd.gamePlayedFlag==false)
		BlackJackAdd.questionCnt++;
    else
    {
        BlackJackAdd.addScore();
        BlackJackAdd.questionArr.splice(BlackJackAdd.questionCnt,1);
    }
	if(BlackJackAdd.questionArr.length==0)
		BlackJackAdd.showLastPage();
	else if(BlackJackAdd.questionCnt>=BlackJackAdd.questionArr.length && BlackJackAdd.questionArr.length!=0)
		BlackJackAdd.showPopup();
	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])
    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();
    $('#result').text('');
    $('.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) {

    clearInterval(BlackJackAdd.noResponseTimer);
    document.getElementById('playSound').pause();
    $("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.skippedQuestion();
    }, 4000);
}

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.showSkippedQuestions=function()
{
	$('#responseBoxDiv').hide();
	BlackJackAdd.questionCnt=0;
	BlackJackAdd.resetVariables();
    BlackJackAdd.showQuestion();
}

BlackJackAdd.showPopup=function()
{
	document.getElementById('playSound').pause();
	clearTimeout(BlackJackAdd.AnsQuestionTimer);
	BlackJackAdd.AnsQuestionTimer=null;
	clearInterval(BlackJackAdd.noResponseTimer);
	clearTimeout(BlackJackAdd.timeOut);
	BlackJackAdd.timeOut=null;
	$('#responseBoxDiv').show();
	$('#questionMsg').text(BlackJackAdd.modalData.responseMsg);
	$('#Yes').text(BlackJackAdd.modalData.yes);
	$('#No').text(BlackJackAdd.modalData.no);
}

BlackJackAdd.showLastPage=function()
{
	$('#responseBoxDiv').hide();
	$("body").css("background-image", "url(" + Utils.Path + 'images/background.jpg' + ")");
	$('.scorePage').hide();
	BlackJackAdd.giveStars();
	document.getElementById('playSound').pause();
	gameOver.innerHTML=BlackJackAdd.hardCodedData.gameOver;
   // $('#question').css('visibility','hidden');
    $('#gamePage').hide();
	$('#endpage').show();
	clearTimeout(BlackJackAdd.AnsQuestionTimer);
	clearInterval(BlackJackAdd.noResponseTimer);
	clearTimeout(BlackJackAdd.timeOut);
	document.getElementById('nextDiv').classList.add('blink_me');
	if(BlackJackAdd.correctCnt>0)
	{
		document.getElementById('playSound').src="sound/instruction/star"+BlackJackAdd.correctCnt+".mp3";
		document.getElementById('playSound').play();
	}
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(BlackJackAdd.correctCnt,BlackJackAdd.totalQue,"6");
}

BlackJackAdd.createStars=function()
{
	var newImage,newDiv,i,numberOfStars=5;
	for(i=1;i<=Math.floor(numberOfStars);i++)
	{
		newDiv= document.createElement("div");
		newDiv.setAttribute("id","starDiv"+i); 
		newDiv.setAttribute("class","nopadding stars col-xs-2 col-md-2 col-lg-2 col-sm-2"); 

		newImage= document.createElement("img");
		newImage.setAttribute("id","starImg"+i); 
		newImage.setAttribute("class","img-responsive nopadding col-sm-12 col-lg-12 col-md-12 col-xs-12"); 
		newImage.setAttribute("src",Utils.Path+"images/star5.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
};

BlackJackAdd.giveStars=function()
{
	var fractionVar,i,numberOfStars=BlackJackAdd.correctCnt;
	fractionVar=numberOfStars-Math.floor(numberOfStars);
	for(i=1;i<=Math.floor(numberOfStars);i++)
		document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/star1.png");
	$("#starDiv").css("visibility","visible");
};

BlackJackAdd.goNext=function()
{
	clearInterval(BlackJackAdd.noResponseTimer);
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}

BlackJackAdd.startTimer=function()
{
	if(BlackJackAdd.noResponseTimer)
	{
        clearInterval(BlackJackAdd.noResponseTimer);
        BlackJackAdd.noResponseTimer=null;
        BlackJackAdd.seconds=0;
	}	
	BlackJackAdd.noResponseTimer=setInterval(function() 
	{
		BlackJackAdd.seconds++;
		if(BlackJackAdd.seconds>=5)
		{
			document.getElementById("playSound").src=Utils.Path+"sound/instruction/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(BlackJackAdd.noResponseTimer);
			BlackJackAdd.timeOut=setTimeout(function()
			{
				BlackJackAdd.seconds=0;
				BlackJackAdd.startTimer();
			},2000);
		}
	},1000);
}