var NumberOrdering = {};
var Utils = {};
Utils.Path = "";
Utils.mobileDeviceFlag = false;
NumberOrdering.noOfQuestions = 0;
NumberOrdering.showHomeBtnFlag = false;
NumberOrdering.scoreFlag = false;

var questionId = 0,
  startTime = 0,
  scoredMarks = 0,
  totalMarks = 10,
  label = "",
  level = 0,
  resId = 0;

$(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;

  /*  if (Utils.mobileDeviceFlag)
     Utils.Path = Android.getMediaPath("LineLagao");
   */
  setTimeout(function() {
    $(document).prop("title",NumberOrdering.AcknowledgementPageData.NameoftheGame);
    $("#gameOverText").text(NumberOrdering.hardCodedData.gameovertext);
    NumberOrdering.setAllImages();
    NumberOrdering.init();
  },200);
});

NumberOrdering.setAllImages = function() {
  $("#playGame").prop("src",Utils.Path + "IMAGES/Play.png");
  $("#FinalOk").prop("src",Utils.Path + "IMAGES/doll.gif");
  $("#Next").prop("src",Utils.Path + "IMAGES/Next.png");
  $("#level1").prop("src",Utils.Path + "IMAGES/green-Leaf-with-1.png");
  $("#level2").prop("src",Utils.Path + "IMAGES/green-Leaf-with-2.png");
  $("#Home,#HomeImg,#HomeBtn").prop("src",Utils.Path + "IMAGES/Home.png");
  $("#Sound").prop("src",Utils.Path + "IMAGES/Sound.png");
  $("#creditImg").prop("src",Utils.Path + "IMAGES/Credit.png");
  $("#replayImg").prop("src",Utils.Path + "IMAGES/Replay.png");
  $("#logo").prop("src",Utils.Path + "IMAGES/logo.png");
};

NumberOrdering.init = function() {
  $("#coverPage,#playGame,#playGameDiv").show();
  $("#gamePage,#levelDiv,#endPage").hide();
  $("#background").css({
    "background-image":
      "url(" +
      Utils.Path +
      "IMAGES/" +
      NumberOrdering.hardCodedData["coverPage"] +
      ")"
  });
  NumberOrdering.AcknowledgementPage();
  $("#level1").data('level',1);
  $("#level2").data('level',2);
  $(".levels").on("click",function() {
    console.log("level");
    NumberOrdering.startGame(this);
  });

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

  $("#replayImg").click(function() {
    $("#endPage").hide();
    $("#acknowledgementDiv").css("visibility","hidden");
    console.log("replay");
    NumberOrdering.startGame(NumberOrdering.level);
  });
};

NumberOrdering.startGame = function(element) {
  NumberOrdering.showHomeBtnFlag = false;
  var d = new Date();
  startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
  console.log("Start");
  NumberOrdering.level = 0;
  //questionId++;
  level = $(element).data('level');
  console.log(level);
  NumberOrdering.level = element;
  NumberOrdering.replay = false;
  $("#NumbersDiv,.spaces,.align6InLine").empty();
  $("#gamePage,#Next").show();
  $("#coverPage,#FinalOk").hide();
  (NumberOrdering.AllNumbers = []),(NumberOrdering.arrOfNumbers = []);
  (NumberOrdering.answerCounter = 0),(NumberOrdering.gameOpened = false);
  NumberOrdering.optionArray = ["ascending","descending"];
  (NumberOrdering.arrayOfTopPositions = []),
    (NumberOrdering.arrayOfLeftPositions = []);
  NumberOrdering.chooseNumbers();
  if(NumberOrdering.noOfQuestions == 0) {
    NumberOrdering.playInstruction();
  }
};
NumberOrdering.playInstruction = function() {
  document.getElementById('playSound').pause();
  document.getElementById('playSound').src = Utils.Path + "SOUND/" + NumberOrdering.hardCodedData.instruction;
  document.getElementById('playSound').play();
};
NumberOrdering.addLevels = function() {
  NumberOrdering.showHomeBtnFlag = true;
  document.getElementById("playSound").pause();
  $("#playGame,#playGameDiv,#gamePage").hide();
  $("#background").css({
    "background-image":
      "url(" + Utils.Path + "IMAGES/" + NumberOrdering.hardCodedData["BG"] + ")"
  });
  $("#levelDiv,#coverPage").show();
  $('#HomeBtn').css('visibility','visible');
};

NumberOrdering.createInstructionSpans = function(instructionText) {
  document.getElementById('Title').innerHTML = "";
  let wordsArr = instructionText.split(" ");
  for(let i = 0; i < wordsArr.length; i++) {
    let span = document.createElement('span');
    span.setAttribute('id','span' + i);
    span.innerHTML = " " + wordsArr[i];
    if(i == 2)
      span.style.color = "yellow";
    document.getElementById('Title').appendChild(span);
  }
};

NumberOrdering.chooseNumbers = function() {
  var randomNumber = 0;
  var numberWithComma = "";
  NumberOrdering.numbercount = 8;
  var tempArr = [];
  randomOption = Math.floor(Math.random() * NumberOrdering.optionArray.length);
  label = NumberOrdering.optionArray[randomOption];
  /*  $("#Title").text(
     NumberOrdering.hardCodedData["" + NumberOrdering.optionArray[randomOption]]
   ); */
  NumberOrdering.createInstructionSpans(NumberOrdering.hardCodedData["" + NumberOrdering.optionArray[randomOption]]);
  if(NumberOrdering.level == level1) {
    if(NumberOrdering.optionArray[randomOption] == "ascending")
      randomNumber = Math.floor(Math.random() * (100000 - 1000) + 1000);
    else randomNumber = Math.floor(Math.random() * (100000 - 1000) + 1000);

    for(var i = 0; i < NumberOrdering.numbercount; i++) {
      if(randomNumber.toString().length >= 4) {
        numberWithComma = NumberOrdering.convertNumberToStringWithComma(
          randomNumber
        );
        NumberOrdering.arrOfNumbers.push(numberWithComma);
      } else {
        NumberOrdering.arrOfNumbers.push(randomNumber);
      }
      if(NumberOrdering.optionArray[randomOption] == "ascending") randomNumber++;
      else randomNumber--;
    }
  }
  if(NumberOrdering.level == level2) {

    for(var i = 0; i < NumberOrdering.numbercount; i++) {
      //randomNumber = Math.floor((Math.random() * 50) + 1);
      randomNumber = Math.floor(Math.random() * (100000 - 1000) + 1000);
      while($.inArray(randomNumber,NumberOrdering.arrOfNumbers) >= 0) {
        //randomNumber = Math.floor((Math.random() * 50) + 1);
        randomNumber = Math.floor(Math.random() * (100000 - 1000) + 1000);
      }
      NumberOrdering.arrOfNumbers.push(randomNumber);
    }

    if(NumberOrdering.optionArray[randomOption] == "ascending") {
      NumberOrdering.arrOfNumbers.sort(function(a,b) {
        return a - b;
      });
    } else {
      NumberOrdering.arrOfNumbers.sort(function(a,b) {
        return b - a;
      });
    }

    tempArr = NumberOrdering.arrOfNumbers.slice(0);
    NumberOrdering.arrOfNumbers = [];
    for(let i = 0; i < tempArr.length; i++) {
      if(tempArr[i].toString().length >= 4) {
        numberWithComma = NumberOrdering.convertNumberToStringWithComma(
          tempArr[i]
        );
        NumberOrdering.arrOfNumbers.push(numberWithComma);
      } else {
        NumberOrdering.arrOfNumbers.push(tempArr[i]);
      }
    }
    console.log(NumberOrdering.arrOfNumbers);
  }
  NumberOrdering.addSpacesForBarakhadi();
};

NumberOrdering.convertNumberToStringWithComma = function(randomNumber) {
  var numberWithComma = 0;
  var nolen = randomNumber.toString().length;
  if(nolen == 5) {
    numberWithComma =
      randomNumber.toString().substring(0,nolen - 3) +
      "," +
      randomNumber.toString().substring(nolen - 3);
  }
  if(nolen == 4) {
    numberWithComma =
      randomNumber.toString().substring(0,nolen - 3) +
      "," +
      randomNumber.toString().substring(nolen - 3);
  }
  return numberWithComma;
};

NumberOrdering.searchWord = function(evt) {
  for(var i = 0; i < NumberOrdering.words.length; i++) {
    if(NumberOrdering.words[i]["suffix"] == $(evt).text()) {
      break;
    }
  }
  NumberOrdering.ltrForbarakhadi = NumberOrdering.words[i];
  console.log(NumberOrdering.ltrForbarakhadi);
};

NumberOrdering.allowDrop = function(event) {
  event.preventDefault();
};

NumberOrdering.shuffleNumbers = function(array) {
  var i = 0,
    j = 0,
    temp = 0;
  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;
  }
};

NumberOrdering.addSpacesForBarakhadi = function() {
  var div,
    spanElement,
    outerDiv,
    k = 0;
  var tempArray = [];
  tempArray = NumberOrdering.arrOfNumbers.slice();
  NumberOrdering.shuffleNumbers(tempArray);
  for(var i = 0; i < 2; i++) {
    outerDiv = $(
      '<div style="margin-top:1%;margin-bottom:3%" class=" col-lg-12 col-md-12 col-xs-12 col-sm-12"></div>'
    );
    for(var j = 0; j < 4; j++) {
      innerDiv = $(
        '<div id="innerDiv' +
        k +
        '" class="text-center noPadding col-lg-3 col-md-3 col-xs-3 col-sm-3"></div>'
      );
      $(innerDiv).data("Answer",NumberOrdering.arrOfNumbers[k]);
      div = $(
        '<div id="div' +
        k +
        '"class="align6InLine noPadding text-center col-lg-10 col-md-10 col-xs-10 col-sm-10 col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 left" >' +
        NumberOrdering.arrOfNumbers[k] +
        "</div>"
      );
      $(innerDiv).droppable({
        drop: NumberOrdering.Handledrop,
        dragover: NumberOrdering.allowDrop
      });
      $(div).data("Answer",NumberOrdering.arrOfNumbers[k]);
      if(k < NumberOrdering.numbercount) {
        spanElement = $(
          '<p id="space' +
          k +
          '" class="text-center noPadding spaces" >' +
          tempArray[k] +
          "</p>"
        );
        //$(spanElement).data('Answer', tempArray[k]);
        $(div).draggable({
          cursor: "move",
          snap: "#div" + k,
          revert: "invalid",
          zIndex: 1,
          containment: "#NumbersDiv",
          scroll: false,
          start: function(event,ui) {
            document.getElementById('playSound').pause();
          }
        });
        $(div).append(spanElement);
        k++;
      }
      $(innerDiv).append(div);
      $(outerDiv).append(innerDiv);
    }
    $("#NumbersDiv").append(outerDiv);
  }
  $(".align6InLine").css({
    color: "transparent",
    "background-image": "url(" + Utils.Path + "IMAGES/yellow-Leaf.png)",
    "background-repeat": "no-repeat",
    "background-size": "95% 100%"
  });
  NumberOrdering.checkData();
};


NumberOrdering.checkData = function() {
  for(var i = 0; i < NumberOrdering.arrOfNumbers.length; i++) {
    if(
      $("#innerDiv" + i).data("Answer") ==
      $("#innerDiv" + i)
        .children("div")
        .children("p")
        .text()
    ) {
      console.log("Match Found");
      NumberOrdering.answerCounter++;
      $("#space" + i)
        .parent()
        .css({
          "background-image": "url(" + Utils.Path + "IMAGES/green-Leaf.png)"
        });
    }
  }
};

NumberOrdering.playSoundForEachWord = function(element) {
  document.getElementById("playSound").src = $(element).data("sound");
  document.getElementById("playSound").play();
};


NumberOrdering.clearAllAndShowNext = function() {
  if(!NumberOrdering.scoreFlag) {
    scoredMarks = -1;
    console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
    if(Utils.mobileDeviceFlag)
      Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
  }
  NumberOrdering.noOfQuestions++;
  document.getElementById('playSound').pause();
  if(NumberOrdering.gameOpened == true) {
    console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
    if(Utils.mobileDeviceFlag)
      Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
  }
  if(NumberOrdering.noOfQuestions < 5) {
    $("#FinalOk").hide();
    $("#Next").removeClass("blink_me");
    NumberOrdering.scoreFlag = false;
    if(NumberOrdering.nextQuestionTimer) {
      NumberOrdering.nextQuestionTimer = null;
      clearTimeout(NumberOrdering.nextQuestionTimer);
    }
    $("#NumbersDiv,.spaces,.align6InLine").empty();
    $("#Next").hide();
    scoredMarks = 0;
    NumberOrdering.startGame(NumberOrdering.level);
  }
  else {
    NumberOrdering.showEndPage();
  }
};

NumberOrdering.Handledrop = function(event,ui) {
  var destiDiv,sourceDiv;
  NumberOrdering.gameOpened = true;
  NumberOrdering.scoreFlag = true;
  document.getElementById('playSound').pause();
  sourceChild = ui.draggable;
  sourceDiv = $(ui.draggable).parent();
  destiDiv = $(this);
  destChild = $(this).children();

  $(sourceChild).css({
    top: "0px",
    left: "0px"
  });
  document.getElementById('playSound').src = Utils.Path + "SOUND/ting.mp3";
  document.getElementById('playSound').play();

  $(sourceChild).appendTo(destiDiv);
  $(destChild).appendTo(sourceDiv);

  if(sourceDiv !== destiDiv) {
    var j = 0;
    for(var i = 0; i < NumberOrdering.arrOfNumbers.length; i++) {
      if(
        $("#innerDiv" + i).data("Answer") == $("#innerDiv" + i).children("div").children("p").text()) {
        j++;
        $("#innerDiv" + i).children("div").css({"background-image": "url(" + Utils.Path + "IMAGES/green-Leaf.png)"});
      } else {
        $("#innerDiv" + i).children("div").css({
          "background-image": "url(" + Utils.Path + "IMAGES/yellow-Leaf.png)"
        });
      }
    }
    NumberOrdering.answerCounter = j;
  }
  if(NumberOrdering.answerCounter == NumberOrdering.numbercount) {
    scoredMarks = 10;
    $(".align6InLine").css({"pointer-events": "none"});
    console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
    if(Utils.mobileDeviceFlag)
      Android.addScore(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
    NumberOrdering.gameOpened = false;
    scoredMarks = 0;
    document.getElementById("playSound").src =
      Utils.Path + "SOUND/welldone.mp3";
    document.getElementById("playSound").play();
    $("#FinalOk").show();
    if(NumberOrdering.noOfQuestions == 5) {
      setTimeout(function() {
        clearTimeout(NumberOrdering.nextQuestionTimer);
        NumberOrdering.showEndPage();
        $("#Next").css("visibilty","hidden");
      },1000);
    }
  }
};
NumberOrdering.AcknowledgementPage = function() {
  var i = 0,
    div;
  console.log(Object.keys(NumberOrdering.AcknowledgementPageData).length);
  for(
    i = 0;
    i < Object.keys(NumberOrdering.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(NumberOrdering.AcknowledgementPageData)[i] +
      " : " +
      Object.values(NumberOrdering.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 = NumberOrdering.hardCodedData["createdOn"];
  acknowledgementDiv.appendChild(div);
};

NumberOrdering.showEndPage = function() {
  NumberOrdering.showHomeBtnFlag = true;
  document.getElementById("playSound").pause();
  clearTimeout(NumberOrdering.nextQuestionTimer);
  console.log("Done");
  NumberOrdering.noOfQuestions = 0;
  NumberOrdering.replay = true;
  $("#gamePage").hide();
  $("#endPage").show();
};

NumberOrdering.callHome = function() {
  NumberOrdering.noOfQuestions=0;
  if(NumberOrdering.showHomeBtnFlag != true) {
    if(NumberOrdering.gameOpened == true) {
      console.log(resId,questionId,scoredMarks,totalMarks,level,startTime,label);
      if(Utils.mobileDeviceFlag)
        Android.addScore(
          resId,
          questionId,
          scoredMarks,
          totalMarks,
          level,
          startTime,
          label
        );
    }
    NumberOrdering.addLevels();
  } else {
    location.reload(true);
  }
};

NumberOrdering.allowDrop = function(event) {
  event.preventDefault();
};

NumberOrdering.addbackgroundColours = function() {
  $(".trans").removeClass("trans");
};
