var verb = {};
var Utils = {};
Utils.Path = "";
verb.tenseDemoCnt = 0;
Utils.mobileDeviceFlag = false;
verb.randomIndex = 0;
verb.dataLength = 6;
verb.gameStartFlag = false;
verb.scoreFlag = false;
verb.randomPositions = [];
verb.optionArray = [];
verb.toFillData = [];
verb.score = 0;
verb.attemptFlag = false;
verb.attemptCnt = 0;
verb.practice = false;
verb.correctCnt = 0;
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 3, resId = 0, level = 1, sentenceDroppedArr = [], label = "";
verb.subjectArray = ["We", "I", "They", "He", "She", "You", "It"];
verb.singularThirdPersonOption = ["He", "She", "It"];
//function for loader
$(document).ready(function () {
  $(".se-pre-con").fadeOut("fast");

  if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
    Utils.mobileDeviceFlag = true;

  setTimeout(function () {
    $("#coverpage").show();
    $("#gamePage,#home,#endPage").hide();
    verb.setImages();
    verb.setEventListeners();
    verb.setFont("fonts/hinted-CelloSans-Light.ttf");
    verb.copyJson = JSON.parse(JSON.stringify(verb.Data));
  }, 300);
});

verb.setFont = function (fontFilePath) {
  var newStyle =
    "<style>" +
    "@font-face {  " +
    "font-family: 'CustomFontFamily';" +
    "src: url('" +
    fontFilePath +
    "') format('truetype');" +
    "}  </style>";
  $("head").append(newStyle);
  $("#gamePage,#endPage").css("font-family", "CustomFontFamily");
};

//function to set images
verb.setImages = function () {
  document.body.style.backgroundImage =
    "url(" + Utils.Path + "images/coverpage.png)";
  $("#logo").prop("src", Utils.Path + "images/logo.png");
  $("#play").prop("src", Utils.Path + "images/Play.png");
  $("#home").prop("src", Utils.Path + "images/home.png");
  $("#check").prop("src", Utils.Path + "images/done.png");
  $("#skip").prop("src", Utils.Path + "images/Skip.png");
  $("#next").prop("src", Utils.Path + "images/Next.png");
  $("#sound").prop("src", Utils.Path + "images/sound.png");
  $("#replayImg").prop("src", Utils.Path + "images/replay.png");
  $("#creditImg").prop("src", Utils.Path + "images/credits.png");
  $(".icon").css("height", "15vh");
  $("#home").css("height", "16vh");
};
// Set Events
verb.setEventListeners = function () {
  $("#home").on("click", function () {
    verb.home();
  });

  $("#play").on("click", function () {
    $("#playGame,#coverPage").hide(); //,#checkDiv
    $("#home,#gamePage").show();
    $("#splitSentencesDiv,#sentenceDiv").show();
    verb.playGame();
  });

  $("#soundDiv").click(function () {
    document.getElementById("playSound").pause();
    verb.playSounds(verb.sounds.instruction);
  });

  $("#replayImg").click(function () {
    verb.attemptCnt = 0;
    verb.correctCnt = 0;
    $("#home").css("visibility", "visible");
    verb.playGame();
  });

  $("#nextDiv").click(function () {
    verb.nextQue();
  });

  $("#skipDiv").click(function () {
    $("#skipDiv").css("visibility", "hidden");
    $("#optionDisplayDiv").show();
    //$('#skipDiv').hide();
    verb.nowStartGame();
  });

  $("#credits").click(function () {
    //$("#acknowledgementDiv").empty();
    $("#acknowledgementDiv").css("visibility", "visible");
  });

  $("#checkDiv").click(function () {
    verb.validate();
  });
};

verb.nextQue = function () {
  document.getElementById("playSound").pause();
  verb.scoreFunction();
  if (verb.tenseDemoCnt == 2 && verb.gameStartFlag) {
    verb.showEndPage();
  } else {
    if (verb.tenseDemoCnt < 2) verb.changeTense();
    else {
      if (!verb.practice) {
        verb.tenseDemoCnt = 0;
        verb.nowStartGame();
        $("#optionDisplayDiv").show();
        $("#skipDiv").css("visibility", "hidden");
      }
    }
  }
};
//this function will execute on click of play button
verb.playGame = function () {
  document.body.style.backgroundImage = "url(" + Utils.Path + "images/Bg.png)";
  $("#acknowledgementDiv").empty();
  $("#endPage").hide();

     if (Utils.mobileDeviceFlag)
      verb.practice = Android.isPractice(); 

  if (verb.practice) {
    verb.gameStartFlag = true;
    $("#skipDiv").css("visibility", "hidden");
    $("#optionDisplayDiv").show();
  } else {
    verb.gameStartFlag = false;
    $("#skipDiv").css("visibility", "visible");
    $("#optionDisplayDiv").hide();
  }

  verb.cnt = 0;
  verb.tenseDemoCnt = 0;

  $("#nextDiv").removeClass("bounceCls");

  $("#home,#gamePage").show();
  verb.randomIndex = Math.floor(Math.random() * verb.Data.length);
  verb.getData();
  if (verb.practice)
    verb.playSounds(verb.sounds.instruction);

};

verb.playSounds = function (audio) {
  setTimeout(function () {
    document.getElementById("playSound").src =
      Utils.Path + "sounds/instruction/" + audio;
    document.getElementById("playSound").play();
  }, 100);
};

verb.generateOptions = function (tempArr) {
  var currentTense,
    tempText = [];
  for (let i = 0; i < 3; i++) {
    currentTense = verb.Data[verb.randomIndex].data[i].tenseData;
    for (let j = 0; j < 2; j++) {
      for (let k = 0; k < verb.dataLength / 2; k++) {
        if (j == 0) tempText = currentTense.Singular[k + 1 + "p"].split(" ");
        else tempText = currentTense.Plural[k + 1 + "p"].split(" ");

        let str = tempText[tempText.length - 1];
        str = str.slice(0, -1);

        if ($.inArray(str, tempArr) == -1) tempArr.push(str);
      }
    }
  }
  return tempArr;
};

//to get current verb all tense data
verb.getData = function () {
  var d = new Date();
  startTime =
    d.getDate() +
    "-" +
    (d.getMonth() + 1) +
    "-" +
    d.getFullYear() +
    " " +
    d.getHours() +
    ":" +
    d.getMinutes() +
    ":" +
    d.getSeconds();
  verb.attemptFlag = false;
  $("#optionDisplayDiv,#check").css("pointer-events", "auto");
  $("#nextDiv").css("pointer-events", "auto");
  $("#checkDiv").css("visibility", "hidden");
  verb.currentData = verb.Data[verb.randomIndex];
  verb.currentTenseData =
    verb.Data[verb.randomIndex].data[verb.tenseDemoCnt].tenseData;
  label = verb.Data[verb.randomIndex].data[verb.tenseDemoCnt].tenseType;
  questionId = verb.Data[verb.randomIndex].questionId;
  verb.setTenseData();
};

// Set or Change Tense Data on next Click
verb.setTenseData = function () {
  $("#CurrentTense").text(
    verb.Data[verb.randomIndex].data[verb.tenseDemoCnt].tenseType
  );
  let j = 0,
    span;
  var tempText = [];
  verb.toFillData = [];
  verb.optionArray = [];
  verb.scoreFlag = false;
  $(".optionSpan").remove();
  $(".textSpan").remove();
  populate(verb.dataLength / 2);
  for (var i = 0; i < verb.dataLength; i++) {
    if (i == verb.dataLength / 2) j = 0;

    if (i > 2) tempText = verb.currentTenseData.Plural[j + 1 + "p"].split(" ");
    else tempText = verb.currentTenseData.Singular[j + 1 + "p"].split(" ");

    str = tempText[tempText.length - 1];
    tempText[tempText.length - 1] = str.slice(0, -1);

    let randomIndex = Math.floor(Math.random() * tempText.length);
    while (i == 0 && randomIndex == 0)
      randomIndex = Math.floor(Math.random() * tempText.length);

    for (let k = 0; k < tempText.length + 1; k++) {
      if (k == tempText.length) {
        span = document.createElement("span");
        span.setAttribute("id", "div" + i + "span" + k);
        span.innerHTML = ".";
        span.setAttribute("class", "textSpan");
      } else {
        span = document.createElement("span");
        span.setAttribute("id", "div" + i + "span" + k);
        let tempId = "div" + i + "span" + k;
        span.innerHTML = tempText[k];
        span.setAttribute("class", "textSpan");

        if (
          (verb.gameStartFlag || verb.practice) &&
          $.inArray(i, verb.randomPositions) != -1
        ) {
          if (k == randomIndex) {
            if (tempText[k].length < 2) {
              $(span).css("padding", "2%");
            }
            span.setAttribute("class", "textSpan transperant dropClass");
            $(span).data("correctData", tempText[k]);
            $(span).data("sentenceSetFlag", 0);
            verb.toFillData.push(tempId);
            verb.optionArray.push(tempText[k]);
          }
        }
      }
      $("#dataEntry" + i).append(span);
    }
    j++;
  }
  if (verb.gameStartFlag || verb.practice) {
    $("#soundDiv").css("visibility", "visible");
    verb.setOptions();
  }
};
verb.setOptions = function () {
  var temp = [],
    options = [];
  temp = verb.optionArray.slice();
  verb.generateOptions(temp);

  for (let i = 0; i < temp.length; i++) {
    if ($.inArray(temp[i], options) == -1) {
      options.push(temp[i]);
    }
  }
  var optionArrayLength = options.length;
  for (let i = 0; i < 9 - optionArrayLength; i++) {
    let randomIndex = Math.floor(Math.random() * verb.subjectArray.length);
    while ($.inArray(verb.subjectArray[randomIndex], options) != -1)
      randomIndex = Math.floor(Math.random() * verb.subjectArray.length);
    options.push(verb.subjectArray[randomIndex]);
  }

  options = shuffleArray(options);
  for (let i = 0; i < options.length; i++) {
    span = document.createElement("span");
    span.setAttribute("id", "optionSpan" + i);
    span.innerHTML = options[i];
    span.setAttribute("class", "optionSpan");
    $("#optionDisplayDiv").append(span);
  }
  verb.addEvent();
};
// on Next Click Change Tense
verb.changeTense = function () {
  $("#nextDiv").removeClass("bounceCls");
  verb.correctCnt = 0;
  verb.attemptCnt = 0;
  sentenceDroppedArr = [];
  verb.sentenceFillCnt = 0;
  for (let i = 0; i < verb.dataLength; i++)
    $("#dataEntry" + i).data("sentenceSetFlag", 0);
  verb.tenseDemoCnt++;
  verb.getData();
};
// Start game after Demo or On Skip Button
verb.nowStartGame = function () {
  if (verb.gameStartFlag == false) {
    verb.tenseDemoCnt = 0;
    verb.gameStartFlag = true;
  }
  console.log("Game Start");
  verb.getData();
  populate(verb.dataLength / 2);
  verb.playSounds(verb.sounds.instruction);
};
function populate(length) {
  var randomIndex;
  verb.randomPositions = [];
  while (verb.randomPositions.length !== length) {
    randomIndex = Math.floor(Math.random() * verb.dataLength);
    if ($.inArray(randomIndex, verb.randomPositions) === -1)
      verb.randomPositions.push(randomIndex);
  }
}
//add drag drop event
verb.addEvent = function () {
  $(".dropClass").droppable({
    drop: verb.handleDrop
  });
  $(".optionSpan").draggable({
    cursor: "move",
    helper: "clone"
  });
};

// Handle Drop Event
verb.handleDrop = function (
  event,
  ui //drop Sentence
) {
  var src, dstDiv, dropId;
  verb.attemptFlag = true;
  dstDiv = $(this);
  verb.playSounds(verb.sounds.drop);
  dropId = dstDiv.attr("id");
  $("#" + dropId).data("dropped", 1);
  console.log(dropId);
  //$(dropId).removeClass("transperant");
  let idNum = dropId.substring(3, 4);
  $("#dataEntry" + idNum).data("sentenceSetFlag", 1);
  $("#" + dropId).removeClass("transperant");
  src = ui.draggable;
  var txt = $(src).text();
  $("#" + dropId).text(txt);
  $("#" + dropId).addClass("animated zoomIn");

  setTimeout(function () {
    $("#" + dropId).removeClass("animated zoomIn");
    dstDiv.css("border-bottom", "2px dashed #00ffff");
  }, 1000);
  verb.checkFillPosition();
};

//check the all sentences are filled or not
verb.checkFillPosition = function () {
  verb.sentenceFillCnt = 0;
  if (verb.checkAllFieldsFilled()) {
    $("#checkDiv").css("visibility", "visible");
  } else $("#checkDiv").css("visibility", "hidden");
};
verb.checkAllFieldsFilled = function () {
  var dataFillCount = 0;
  for (let i = 0; i < verb.toFillData.length; i++) {
    let data = $("#" + verb.toFillData[i]).data("dropped");
    if (data == 1) dataFillCount++;
  }
  if (dataFillCount == 3) return 1;
  else return 0;
};

verb.validate = function () {
  verb.attemptCnt++;
  console.log(verb.toFillData);
  clearTimeout(verb.manageClasses);
  for (i = 0; i < verb.dataLength / 2; i++) {
    if (verb.toFillData[i] == "div2span0") {
      if ($.inArray($("#" + verb.toFillData[i]).text(),verb.singularThirdPersonOption) != -1) {
        id = verb.toFillData[i];
        if ($.inArray(id, sentenceDroppedArr) == -1) {
          sentenceDroppedArr.push(id);
          verb.correctCnt++;
        }
        $("#" + verb.toFillData[i]).droppable("disable");
        $("#" + verb.toFillData[i]).addClass("rightClass");
      } else {
        $("#" + verb.toFillData[i]).addClass("wrongClass");
        $("#" + verb.toFillData[i]).data("dropped", 0);
        verb.attemptCounter++;
      }
    } else {
      if (
        $("#" + verb.toFillData[i]).text() !=
        $("#" + verb.toFillData[i]).data("correctData") ||
        $("#topSentence" + i).data("sentenceSetFlag") == 0
      ) {
        $("#" + verb.toFillData[i]).addClass("wrongClass");
        $("#" + verb.toFillData[i]).data("dropped", 0);
        verb.attemptCounter++;
      } else {
        id = verb.toFillData[i];
        if ($.inArray(id, sentenceDroppedArr) == -1) {
          sentenceDroppedArr.push(id);
          verb.correctCnt++;
        }
        $("#" + verb.toFillData[i]).droppable("disable");
        $("#" + verb.toFillData[i]).addClass("rightClass");
      }
    }
  }

  //execute if all are correct
  if (verb.correctCnt == verb.dataLength / 2) {
    verb.score += 10;
    scoredMarks = verb.correctCnt;
    verb.playSounds(verb.sounds.correct);

      if (Utils.mobileDeviceFlag)
        Android.addLearntData(label, verb.Data.length, "sentence");
      console.log(label, verb.Data.length, "sentence"); 
    if (Utils.mobileDeviceFlag)
      Android.addScore(
        resId,
        questionId,
        scoredMarks,
        totalMarks,
        level,
        startTime
      );
    console.log(questionId, scoredMarks, totalMarks, level, startTime);
    if (verb.manageClasses) {
      clearTimeout(verb.manageClasses);
      verb.manageClasses = null;
    }
    $("#optionDisplayDiv,#check").css("pointer-events", "none");
    verb.attemptFlag = false;
    verb.scoreFlag = true;
    $("#nextDiv").addClass("bounceCls");
  } else {
    if (verb.manageClasses) {
      clearTimeout(verb.manageClasses);
      verb.manageClasses = null;
    }
    if (verb.attemptCnt == 2) {
      verb.score += 10;
      scoredMarks = verb.correctCnt;
      if (Utils.mobileDeviceFlag)
        Android.addScore(
          resId,
          questionId,
          scoredMarks,
          totalMarks,
          level,
          startTime
        );
      console.log(questionId, scoredMarks, totalMarks, level, startTime);
      $("#optionDisplayDiv").css("pointer-events", "none");
      $("#nextDiv").addClass("bounceCls");
      verb.attemptFlag = false;
      verb.scoreFlag = true;
      verb.playSounds(verb.sounds.betterLuck);
    } else {
      verb.playSounds(verb.sounds.tryagain);
    }
    verb.manageClasses = setTimeout(function () {
      $("#checkDiv").css("visibility", "hidden");
      $(".wrongClass").addClass("transperant");
      $(".wrongClass").removeClass("wrongClass");
      $(".rightClass").removeClass("rightClass");
      $("#check").css("pointer-events", "none");
      console.log(verb.optionArray);
      for (var i = 0; i < verb.toFillData.length; i++) {
        $("#" + verb.toFillData[i]).text(verb.optionArray[i]);
        $("#" + verb.toFillData[i]).className = "transperant";
      }
    }, 1000);
  }
};
verb.scoreFunction = function () {
  if (verb.gameStartFlag && !verb.scoreFlag) {
    if (verb.attemptFlag) {
      scoredMarks = verb.correctCnt;
      if (Utils.mobileDeviceFlag)
        Android.addScore(
          resId,
          questionId,
          scoredMarks,
          totalMarks,
          level,
          startTime
        );
      console.log(questionId, scoredMarks, totalMarks, level, startTime);
    } else {
      scoredMarks = -1;
      if (Utils.mobileDeviceFlag)
        Android.addScore(
          resId,
          questionId,
          scoredMarks,
          totalMarks,
          level,
          startTime
        );
      console.log(questionId, scoredMarks, totalMarks, level, startTime);
    }
  }
};

verb.showEndPage = function () {
  verb.gameStartFlag = false;
  document.getElementById("playSound").pause();
  document.getElementById("gamePage").style.display = "none";
  document.getElementById("endPage").style.display = "block";
  $("#acknowledgementDiv").css("visibility", "hidden");
  $("#soundDiv").css("visibility", "hidden");
  $("#acknowledgementDiv").empty();
  verb.AcknowledgementPage();
  $("#gameOver").text(verb.hardCodedData.gameOver);
};

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

function shuffleArray(array) {
  var i, j, temp;
  for (i = array.length - 1; i > 0; i--) {
    j = Math.floor(Math.random() * (i + 1));
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

verb.home = function () {
  if (verb.gameStartFlag && verb.attemptCnt > 0) {
    scoredMarks = verb.correctCnt;
    if (Utils.mobileDeviceFlag)
      Android.addScore(
        resId,
        questionId,
        scoredMarks,
        totalMarks,
        level,
        startTime
      );
    console.log(questionId, scoredMarks, totalMarks, level, startTime);
  }
  location.reload(true);
};
