var addedQuestions = [];
var addedNewQuestions = [];
var markHidden = false;
var answerHidden = false;
var noImgUrl = "images/no-image.png";
var result;
var ALL_SUB = [];
const NEW_QUES_TITLE = "Question Added By Teacher";
// console.log(online_offline, "online_offline");

function setAddToDetail(questionID, preview = false) {
  $(".iPage").hide();
  //$('#tree').hide();
  //$('.rtContainer').hide();
  $(".addToTestContainer").show();

  if ($(".addToTestContainer #addtestHeader").children().length > 0)
    $(".addToTestContainer #addtestHeader").empty();
  setHeaderDetails();

  //----------------------SAVE QUESTION----------------------------
  if (tg_MODE == "manual" && !preview) {
    $("#questBase")
      .children(".option-quest")
      .each(function () {
        if ($(this).find(".checkBoxes").prop("checked")) {
          var index = $(this)
            .find(".checkBoxes")
            .attr("id")
            .split("checkBoxes")[1];
          saveQuestion(questionID, index);
        }
      });
  }
  loadAnsImages();
  //----------------------------------------------------------------
  //setSelectedQuestDetail();
  //----------------------------------------------------------------
  $(".selected-full-quest .selected-mark").each(function () {
    $(this).find("span").hide();
    $(this).find("input").css("visibility", "hidden");
  });
  $(".selected-full-quest .selected-quest").each(function () {
    $(this).find("#answer-txt").hide();
  });
}
var ansAInd = -1;

// function loadAnsImages() {
//   ansAInd += 1;
//   if (ansAInd < addedQuestions.length) {
//     var imgStr = addedQuestions[ansAInd].questAns;
//     console.log(addedQuestions, "ind 123");
//     console.log(imgStr + "loadAnsImages-0-------" + checkImage(imgStr));
//     if (checkImage(imgStr) && addedQuestions[ansAInd].questAnsImg == "") {
//       var script = document.createElement("script");
//       console.log(script, "ind 444");

//       /* script.src = (""+addedQuestions[ansAInd].questAns).split(".")[0]+".js";
//             urlTemp.push((""+addedQuestions[ansAInd].questAns).split(".")[0]+".js"); */

//       script.src = createJsFileName(addedQuestions[ansAInd].questAns);
//       urlTemp.push(createJsFileName(addedQuestions[ansAInd].questAns));
//       //            const temprajji= urlTemp.filter((item)=>{
//       //  return item.includes("https")
//       //             });
//       //            urlTemp=temprajji

//       //console.log("loadAnsImages-1-------" + createJsFileName(addedQuestions[ansAInd].questAns), addedQuestions[ansAInd].questAns)
//       var ansAIndTemp = ansAInd;
//       script.onload = function () {
//         //console.log(g("=====loadAnsImages(3.0)=====" + ansAInd);
//         //console.log("=====loadAnsImages(3.1)=====" + addedQuestions[ansAInd].questAnsImg);

//         //var quest = questions[index].question;
//         //console.log(quest);
//         addedQuestions[ansAIndTemp].questAnsImg = img;

//         //console.log("=====loadAnsImages(4)=====");
//         loadAnsImages();
//       };
//       // console.log(document.head);

//       document.head.appendChild(script);
//     } else {
//       //addedQuestions[ansAInd].questAnsImg = "";
//       loadAnsImages();
//     }
//   } else {
//     $("script").each(function (i) {
//       if (urlTemp.indexOf($(this).attr("src")) > -1) $(this).remove();
//     });
//     ansAInd = -1;
//     urlTemp.length = 0;
//     setSelectedQuestDetail();
//   }
// }
function loadAnsImages() {
  ansAInd += 1;

  if (ansAInd < addedQuestions.length) {
    var imgStr = addedQuestions[ansAInd].questAns;
    console.log(addedQuestions, "ind 123");
    console.log(imgStr + "loadAnsImages-0-------" + checkImage(imgStr));

    if (checkImage(imgStr) && addedQuestions[ansAInd].questAnsImg === "") {
      var script = document.createElement("script");
      var scriptSrc = createJsFileName(addedQuestions[ansAInd].questAns);

      script.src = scriptSrc;
      urlTemp.push(scriptSrc);

      const ansAIndTemp = ansAInd; // closure-safe index

      script.onload = function () {
        try {
          if (typeof img === 'undefined' || img === null || img.length < 50) {
            console.warn("Missing or invalid image data in script:", script.src);
            loadAnsImages();
            return;
          }

          // Prepend base64 prefix if it's missing
          if (!img.startsWith("data:image/")) {
            img = "data:image/jpeg;base64," + img;
          }

          addedQuestions[ansAIndTemp].questAnsImg = img;
        } catch (e) {
          console.error("Error while processing loaded image:", e);
        }

        loadAnsImages(); // Continue to next
      };

      script.onerror = function () {
        console.error("Failed to load JS file:", script.src);
        loadAnsImages();
      };

      document.head.appendChild(script);
    } else {
      loadAnsImages(); // Skip this one
    }

  } else {
    // Cleanup
    $("script").each(function (i) {
      if (urlTemp.indexOf($(this).attr("src")) > -1) {
        $(this).remove();
      }
    });
    ansAInd = -1;
    urlTemp.length = 0;
    setSelectedQuestDetail();
  }
}

function setHeaderDetails() {
  var img = $('<img id="headLogo">');
  img.attr("src", "images/RS-Icon.png");
  $(".addToTestContainer #addtestHeader").append(
    "<div class='logoSection'></div>"
  );
  $(".addToTestContainer #addtestHeader .logoSection").append(img);
  //$(".addToTestContainer #addtestHeader .logoSection").append("<p>Ratna Sagar</p>");

  var allStr =
    '<div id="wrapper-button" class="wrapper-button-extra-margin"> <button class=btn-prop onclick="window.location.reload()">Home</button> <button id="add-more-quest" class=btn-prop>Add More Questions </button> <button id="add-your-quest" class=btn-prop>Add Your Questions</button><button id="shuffle-quest" class=btn-prop>Shuffle</button><button id="saveTest-quest" class=btn-prop>Save Test</button> <button id="finalize-test" class=btn-prop>Finalize Test</button> <div class="col2_allStr"><div class="column"><input type="checkbox" class="includeAns-check check-prop" id="v1"> <label for="v1"></label> <label>Include answers</label></div> <div class="column"><input type="checkbox" class="mark-check check-prop" id="v2"> <label for="v2"></label> <label>Include Marks</label></div></div></div>';

  //$('#addToTestContainer').hide();
  $(".addToTestContainer #addtestHeader").append(allStr);
  //*******************************************************************************//
  answerHidden = false;
  $("#addtestHeader .includeAns-check").on("click", function () {
    $(".selected-full-quest .selected-quest").each(function () {
      $(this).find("#answer-txt").toggle();
    });
    answerHidden = !answerHidden;
    //console.log(answerHidden)
  });
  //*******************************************************************************//
  markHidden = false;
  $("#addtestHeader .mark-check").on("click", function () {
    $(".selected-full-quest .selected-mark").each(function () {
      $(this).find("span").toggle();
      if ($(this).find("input").css("visibility") == "hidden")
        $(this).find("input").css("visibility", "visible");
      else $(this).find("input").css("visibility", "hidden");
    });
    markHidden = !markHidden;
    //console.log(markHidden);
  });
  //*******************************************************************************//
  $("#addtestHeader #add-more-quest").on("click", function () {
    //console.log("add-more-quest", addedQuestions.length)
    $(".iPage").show();
    $(".addToTestContainer").hide();

    if (tg_MODE == "manual" && addedQuestions.length > 0)
      setBreadCrum(addedQuestions[addedQuestions.length - 1].id); //this function is in main.js
    setHeaderText(); //this function is in main.js
  });
  //*******************************************************************************//
  $("#addtestHeader #add-your-quest").on("click", function () {
    addNewQuestion();
  });
  //*******************************************************************************//
  $("#addtestHeader #shuffle-quest").on("click", function () {
    setSelectedQuestDetail(true);
  });
  //*******************************************************************************//
  $("#addtestHeader #saveTest-quest").on("click", function () {
    saveTest();
  });
  //*******************************************************************************//
  $("#addtestHeader #finalize-test").on("click", function () {
    setPrintPage(); //printPreview.js
  });
}
var questTitleArr = [];
var selectSubject = "English";
function getTitleArr() {
  if (questTitleArr.length == 0) {
    for (var i = 0; i < questions.length; i++) {
      if (questTitleArr.indexOf(questions[i].question.title) == -1) {
        questTitleArr.push(questions[i].question.title);
      }
    }
  }
  return questTitleArr;
}

function addNewQuestion() {
  //console.log('addNewQuestion' + additionalBox);
  var additionalBox = $(".addBox");
  $(".addBox").remove();
  $("body").append(additionalBox);
  $(".addBox").show();
  console.log(online_offline, "online_offline");
  if (online_offline) {
    var checkboxQue = document.getElementById("myCheckbox");
    //console.log(g(checkboxQue.checked);
    checkboxQue.style.display = "block";
    checkboxQue.addEventListener("change", function () {
      //console.log(checkboxQue.checked);
    });
  }

  var uniqueValuesTg = [...new Set(allSubs)];

  uniqueValuesTg = uniqueValuesTg.length ? uniqueValuesTg : ALL_SUB;
  console.log(
    "*******",
    "allSubs: ",
    allSubs,
    "  uniqueValuesTg: ",
    uniqueValuesTg
  );
  console.log(online_offline, "online_offline");

//   if (online_offline) {
//     let subjectDropdown = document.getElementById("subjectDropdown");
//     // subjectDropdown.style.display = "block";
//     uniqueValuesTg.forEach(function (subject) {
//       //console.log(g(subject);
//       let options = document.createElement("option");
//       options.value = subject;
//       options.text = subject || "No Subject";
//       subjectDropdown.add(options);
//     });
//   }
  //console.log("MODE: ", tg_MODE);

//   subjectDropdown.addEventListener("change", (e) => {
//     selectSubject = e.target.value;
//     //console.log("SUBJECT: ", selectSubject);
//   });
  //console.log(g(selectSubject);

  //$('.question-img').hide();
  //$('.question-txt input').show();

  $(".answer-img").hide();
  $(".answer-txt input").show();

  var titleArr = getTitleArr();
  var s = "";
  for (var i = 0; i < titleArr.length; i++) {
    s += '<option value="' + titleArr[i] + '">' + titleArr[i] + "</option>";
  }
  $(".title-txt").append(s);
  $(".addBox .save-btn").on("click", function () {
    console.log("check1");
    
    // insertQuestion();
     console.log("check1");
    // var titleTxt = $('.addBox .title-txt >input').val().replace(/\s\s+/g, '');
    var titleTxt = $(".addBox .title-txt").val().replace(/\s\s+/g, "");
    var questionTxt = $(".addBox .question-txt >input")
      .val()
      .replace(/\s\s+/g, "");
    var answerTxt = $(".addBox .answer-txt >input").val().replace(/\s\s+/g, "");

    $(".addBox .title-txt >input").css("border", "solid 1px black");
    $(".addBox .question-txt >input").css("border", "solid 1px black");
    $(".addBox .answer-txt >input").css("border", "solid 1px black");
    $(".addBox .answer-img > div > img").css("border", "none");

    /* if(questNum == 2){//question is based on image
            srcStr = $('.addBox .question-img > div > img').attr('src');
            questionTxt = '';
        }else{
            srcStr = '';
        } */
    srcStr = $(".addBox .question-img > div > img").attr("src");
    if (srcStr == noImgUrl) {
      srcStr = "";
    }

    ansSrcStr = $(".addBox .answer-img > div > img").attr("src");
    if (ansSrcStr == noImgUrl) {
      ansSrcStr = "";
    }

    if (ansSrcStr.length > 0) {
      //answer is based on image
      answerTxt = "";
    }

    if (titleTxt.length == 0) {
      $(".addBox .title-txt >input").css("border", "solid 1px red");
    } else if (srcStr.length == 0 && questionTxt.length == 0) {
      $(".addBox .question-txt >input").css("border", "solid 1px red");
    } else if (ansSrcStr.length == 0 && answerTxt.length == 0) {
      $(".addBox .answer-txt >input").css("border", "solid 1px red");
      $(".addBox .answer-img > div > img").css("border", "solid 1px red");
    } else {
      saveAdditionalQuestion(
        titleTxt,
        questionTxt,
        srcStr,
        answerTxt,
        ansSrcStr,
        "0"
      );
      //console.log(answerTxt, 'addNewQuestion2=', ansSrcStr.length);
      $(".addBox").hide();

      if (online_offline) {
        console.log(online_offline,"check");
        
        if (checkboxQue.checked) {
          console.log("entered.... chked");
          insertQuestion(titleTxt, questionTxt, answerTxt, srcStr, ansSrcStr);
        }
      }

      // insertQuestion(titleTxt,questionTxt,answerTxt,srcStr,ansSrcStr);
      setSelectedQuestDetail();

      $("input[type=file]").val("");
      $(".addBox .answer-img > div > img").attr("src", noImgUrl);
    }
  });
  $(".addBox .cancel-btn").on("click", function () {
    $("input[type=file]").val("");
    $(".addBox .answer-img > div > img").attr("src", noImgUrl);

    $(".addBox .question-img > div > img").attr("src", noImgUrl);
    $(".addBox").hide();
  });
  $(".addBox .question-img > input").on("change", function () {
    console.log("LOAD QUESTION IMAGE")

    if (
      !convertImagesToBase64(
        document.getElementById("fileinput"),
        $(".addBox .question-img > div > img"),
        "80px",
        "80px"
      )
    ) {
      $(".addBox .question-img > div > img").attr("src", srcStr);
    }
  });
  $(".addBox .answer-img > input").on("change", function () {
    //console.log("LOAD ANSWER IMAGE")
    if (
      !convertImagesToBase64(
        document.getElementById("fileinput1"),
        $(".addBox .answer-img > div > img"),
        "80px",
        "80px"
      )
    ) {
      $(".addBox .answer-img > div > img").attr("src", noImgUrl);
    }
  });

  var questNum = 1;

  $(".addBox .add-lable-txt #ans-img-radio").on("click", function () {
    ansNum = 2;
    $(".answer-img").show();
    $(".answer-txt input").hide();
  });
  $(".addBox .add-lable-txt #ans-radio").on("click", function () {
    ansNum = 1;
    $(".answer-img").hide();
    $(".answer-txt input").show();
  });
  var ansNum = 1;

  $(".addBox .add-lable-txt #image-radio").prop("checked", false);
  $(".addBox .add-lable-txt #quest-radio").prop("checked", true);
  $(".addBox .add-lable-txt #ans-radio").prop("checked", true);
  $(".addBox .add-lable-txt #ans-img-radio").prop("checked", false);

  var srcStr = noImgUrl;
  var ansSrcStr = noImgUrl;
  $(".addBox .question-img > div > img").attr("src", noImgUrl);
  $(".addBox .answer-img > div > img").attr("src", noImgUrl);

  $(".addBox .title-txt >input:text").val("");
  $(".addBox .question-txt >input:text").val("");
  $(".addBox .answer-txt >input:text").val("");
}
var titleId = -1;
var titleIdArr = [];

function setSelectedQuestDetail(shuffle = false) {
  let titleIdArr = [];
  //console.log("5555555555555");
  //console.log("setSelectedQuestDetail=1=="+addedQuestions.length)
  if ($(".addToTestContainer #addtestBase").length > 0) {
    $(".addToTestContainer #addtestBase").empty();
    titleId = -1;
    titleIdArr.length = 0;
  }

  var shufflesArr = getShuffledQuestionArr(shuffle);
  //console.log("setSelectedQuestDetail=2==" + shufflesArr.length)
  var quesTitle = "";
  for (var i = 0; i < shufflesArr.length; i++) {
    var index = shufflesArr[i].num;
    //var quesDetail = questions[index].question;

    var strtitle = "";
    if (quesTitle != shufflesArr[i].title || i == 0) {
      titleId += 1;
      //strtitle =  '<div class="title-quest">'+quesDetail.title+'</div>';
      strtitle =
        '<div class="col5 title-id' +
        titleId +
        ' title-id-prop"><div class="column"><div class="title-quest">' +
        shufflesArr[i].title +
        '</div></div><div class="column img1"><div class="select-tot-mark"><span>Marks</span><input type="number" min="0" max="10" maxlength="2"></input></div></div><div class="column"><div class="selected-btn"></div></div><div class="column"><div class="selected-btn"></div></div><div class="column"><div class="selected-btn"></div></div></div>';
      titleIdArr.push("title-id" + titleId);
    }

    var str = "";
    var strAns = "";

    //console.log(shufflesArr[i].questImg);

    //console.log("setSelectedQuestDetail=3==(" + (shufflesArr[i].questAnsImg).length + ")===" + checkImage(shufflesArr[i].questAnsImg))
    //console.log("setSelectedQuestDetail=3==1(" + shufflesArr[i].questAns + ")===" + checkImage(shufflesArr[i].questAns))
    //if(shufflesArr[i].questAns.length>0)
    if (shufflesArr[i].questAnsImg.length == 0)
      strAns =
        '<div id="answer-txt"><ul><li><span>Answer:</span></li><li class="ansTxt"><span>' +
        shufflesArr[i].questAns +
        "</span></li></div>";
    else
      strAns =
        '<div id="answer-txt"><ul><li><span>Answer:</span></li><li class="ansTxt"><img src=' +
        shufflesArr[i].questAnsImg +
        "></li></div>";

    //if(shufflesArr[i].questTxt.length>0){
    str =
      '<span class="hang">' +
      (i + 1) +
      '. </span><span class="quest-text">' +
      shufflesArr[i].questTxt +
      "</span>";
    /* }else{ */
    //str = '<span class="hang">'+(i+1)+'. </span> <img class="quest-text" src=' +shufflesArr[i].questImg+ '>';
    if (shufflesArr[i].questImg.length > 0)
      str +=
        '<img class="quest-img" data-fileNameNNO="' +
        shufflesArr[i].questImgName +
        '" src="' +
        shufflesArr[i].questImg +
        '" style="margin-top: 10px;display:block">';
    else
      str +=
        '<img class="quest-img" src="' +
        shufflesArr[i].questImg +
        '" style="margin-top: 10px;display:none">';
    //}
    str = str + strAns;
    var allStr =
      '<div class="col5"><div class="column"><div class="selected-quest">' +
      str +
      '</div></div><div class="column"><div class="selected-mark"><span>Marks</span><input type="number"></input></div></div><div class="alterButtonsWrap"><div class="column"><div class="selected-btn"><button class="replace-btn select-btn-prop select-btn-prop-gray"><span>Replace</span></button></div></div><div class="column"><div class="selected-btn"><button class="remove-btn select-btn-prop select-btn-prop-gray"><span>Remove</span></button></div></div><div class="column"><div class="selected-btn"><button class="edit-btn select-btn-prop select-btn-prop-gray"><span>Edit</span></button></div></div></div></div>';

    quesTitle = shufflesArr[i].title;

    if (!shufflesArr[i].addedQuest) {
      $(".addToTestContainer #addtestBase").append(
        strtitle +
          '<div class="selected-full-quest title-id' +
          titleId +
          '" id=selectedQuest' +
          index +
          ">" +
          allStr +
          "</div>"
      );

      $("#addtestBase #selectedQuest" + index)
        .find(".selected-mark input")
        .val(shufflesArr[i].questMark);

      $("#selectedQuest" + index)
        .find(".remove-btn")
        .on("click", removeQuestionAlert);
      $("#selectedQuest" + index)
        .find(".replace-btn")
        .on("click", replaceQuestionAlert);
      $("#selectedQuest" + index)
        .find(".edit-btn")
        .on("click", editQuestionCont);
      /* $('#selectedQuest'+index).find('.selected-mark input').on('focusout',focusoutQuestMark);
            $('#selectedQuest'+index).find('.selected-mark input').on('focusin', focusinQuestMark); */
      $("#selectedQuest" + index)
        .find(".selected-mark input")
        .focusout(focusoutQuestMark);
      $("#selectedQuest" + index)
        .find(".selected-mark input")
        .focusin(focusinQuestMark);
    } else {
      //for additional question
      $(".addToTestContainer #addtestBase").append(
        strtitle +
          '<div class="selected-full-quest title-id' +
          titleId +
          '" id=selectedAddedQuest' +
          index +
          ">" +
          allStr +
          "</div>"
      );

      $("#addtestBase #selectedAddedQuest" + index)
        .find(".selected-mark input")
        .val(shufflesArr[i].questMark);

      $("#selectedAddedQuest" + index)
        .find(".remove-btn")
        .on("click", removeAddedQuestAlert);
      //$('#selectedAddedQuest'+index).find('.replace-btn').on('click',replaceQuestionAlert);
      $("#selectedAddedQuest" + index)
        .find(".edit-btn")
        .on("click", editQuestionCont);
      /* $('#selectedAddedQuest'+index).find('.selected-mark input').on('focusout',focusoutQuestMark);
            $('#selectedAddedQuest'+index).find('.selected-mark input').on('focusin',focusinQuestMark); */
      $("#selectedAddedQuest" + index)
        .find(".selected-mark input")
        .focusout(focusoutQuestMark);
      $("#selectedAddedQuest" + index)
        .find(".selected-mark input")
        .focusin(focusinQuestMark);
      $("#selectedAddedQuest" + index)
        .find(".replace-btn")
        .prop("disabled", true)
        .css("cursor", "default")
        .fadeTo(500, 0.6);
    }
    /* $('#addtestBase').find('.select-tot-mark input').on('focusout',focusoutTitleMark);
        $('#addtestBase').find('.select-tot-mark input').on('focusin', focusinTitleMark); */
  }

  //setAdditionalQuestDetail();

  //---------------set title marks---------------//
  for (var i = 0; i < titleIdArr.length; i++) {
    var t = calcTitleMark(titleIdArr[i]);
    $("." + titleIdArr[i])
      .find(".select-tot-mark input")
      .val(t);
    /* $('.'+titleIdArr[i]).find('.select-tot-mark input').on('focusout',focusoutTitleMark);
        $('.'+titleIdArr[i]).find('.select-tot-mark input').on('focusin',focusinTitleMark); */
    $("." + titleIdArr[i])
      .find(".select-tot-mark input")
      .focusout(focusoutTitleMark);
    $("." + titleIdArr[i])
      .find(".select-tot-mark input")
      .focusin(focusinTitleMark);
  }
  //---------------------------------------------//

  //-----------set size of all images------------//
  /* $('.selected-full-quest').each(function(){
        var tag = $(this).find('.selected-quest .quest-text');
        if(tag[0].tagName == 'IMG')
        {
            //console.log("HEIGHT::::", tag.css('height'))
            calculateAspectRatioFit(tag, maxWidth, maxHeight);
        }
        tag = $(this).find('.selected-quest #answer-txt .ansTxt img');
        if(tag.length > 0)
        {
            calculateAspectRatioFit(tag, maxWidth, maxHeight);
        }
    }); */
  //console.log('shufflesArr length===', shufflesArr.length)
  setAllQuestImageSize(shufflesArr);
  //---------------------------------------------//
  //console.log("setSelectedQuestDetail=3=="+$('#addtestHeader .includeAns-check').prop("checked"))
  if (!$("#addtestHeader .includeAns-check").prop("checked"))
    $("#addtestBase #answer-txt").hide();

  if (!$("#addtestHeader .mark-check").prop("checked")) {
    $("#addtestBase .selected-mark").find("span").hide();
    $("#addtestBase .selected-mark").find("input").css("visibility", "hidden");
  }
  //checkAndLoadAnswerImg();
}
function insertQuestion(titleTxt, questionTxt, answerTxt, srcStr, ansSrcStr) {
   console.log("check done");
  const insertUrl = `${url}/customwebservice/tg/tgcrud.php?wsfunction=questioninsert&wstoken=${token}`;
  console.log(selectSubject, "insert");

  const postinsertUrlData = {
    referenceid: refernce_ID,
    added_by: 1,
    question_data: {
      bookName: tgTitle.charAt(0).toUpperCase() + tgTitle.slice(1),
      semester: 0,
      class: stdClassInfo,
      // schoolcode: "1",
      subject: subject,
      chapter: NEW_QUES_TITLE,
      neworbook: "Teacher",
      topic: "topic",
      type: "type1",
      question: {
        title: titleTxt,
        option: [questionTxt],
        image: srcStr,
      },
      answer: [answerTxt || ansSrcStr],
      mark: "0",
    },
  };
  //console.log("DATA POST: ", postinsertUrlData);
  axios
    .post(insertUrl, JSON.stringify(postinsertUrlData))
    .then((response) => {
      console.log("Response:", response.data);
    })
    .catch((error) => {
      console.error("Error:", error);
    });
}

var shufQuestIndx = 0;

function setAllQuestImageSize(shufflesArr) {
  if (shufQuestIndx < shufflesArr.length) {
    //console.log('setAllQuestImageSize=1=', shufQuestIndx, shufflesArr.length, shufflesArr[shufQuestIndx].questImg.length)
    if (shufflesArr[shufQuestIndx].questImg.length > 0) {
      //console.log('setAllQuestImageSize=2=', shufQuestIndx, shufflesArr)
      var tempNum = shufflesArr[shufQuestIndx].num;
      var img = shufflesArr[shufQuestIndx].questImg;
      var imgTemp = new Image();
      imgTemp.src = img;
      imgTemp.onload = function () {
        //console.log('setAllQuestImageSize=4=', shufQuestIndx, shufflesArr)
        var h = imgTemp.height + "px";
        var w = imgTemp.width + "px";
        //var len = $('.quest-text').length;
        var imageObj = $("#selectedQuest" + tempNum + " .quest-img");
        //console.log('setAllQuestImageSize=4.1=', imageObj.width() + "===== " + "#selectedQuest" + tempNum + " .quest-img")
        if (imageObj.width() + "" == "undefined")
          imageObj = $("#selectedAddedQuest" + tempNum + " .quest-img");
        //
        imageObj.attr({ src: img });
        imageObj.css({ width: w, height: h });
        calculateAspectRatioFit(imageObj, maxWidth, maxHeight);
        shufQuestIndx += 1;
        setAllQuestImageSize(shufflesArr);
      };
    } else {
      shufQuestIndx += 1;
      setAllQuestImageSize(shufflesArr);
    }
  } else {
    //console.log('setAllQuestImageSize=5=', shufQuestIndx, shufflesArr.length)
    shufQuestIndx = 0;
    setAllAnsImageSize(shufflesArr);
  }
}
var shufAnsIndx = 0;

function setAllAnsImageSize(shufflesArr) {
  if (shufAnsIndx < shufflesArr.length) {
    //console.log('setAllAnsImageSize=1=', shufAnsIndx, shufflesArr.length)
    if (shufflesArr[shufAnsIndx].questAnsImg.length > 0) {
      //console.log('setAllAnsImageSize=2=', shufAnsIndx, shufflesArr.length)
      var tempNum = shufflesArr[shufAnsIndx].num;
      var img = shufflesArr[shufAnsIndx].questAnsImg;
      var imgTemp = new Image();
      imgTemp.src = img;
      imgTemp.onload = function () {
        var h = imgTemp.height + "px";
        var w = imgTemp.width + "px";
        //console.log('setAllAnsImageSize=4=', h, w);
        //var len = $('.quest-text').length;
        var imageObj = $(
          "#selectedQuest" + tempNum + " #answer-txt .ansTxt img"
        );
        //console.log('setAllAnsImageSize=4.1=', $("#selectedQuest" + tempNum + " #answer-txt .ansTxt").attr('class'));

        if (imageObj.width() + "" == "undefined")
          imageObj = $(
            "#selectedAddedQuest" + tempNum + " #answer-txt .ansTxt img"
          );

        imageObj.attr({ src: img });
        imageObj.css({ width: w, height: h });
        calculateAspectRatioFit(imageObj, maxWidth, maxHeight);
        shufAnsIndx += 1;
        setAllAnsImageSize(shufflesArr);
      };
    } else {
      shufAnsIndx += 1;
      setAllAnsImageSize(shufflesArr);
    }
  } else {
    //console.log('setAllAnsImageSize=5=', shufAnsIndx, shufflesArr.length)
    shufAnsIndx = 0;
    hideLoader();
  }
}

function calcTitleMark(titleId) {
  var tot = 0;

  $("#addtestBase")
    .children()
    .each(function () {
      if ($(this).attr("class") == "selected-full-quest " + titleId)
        tot += parseFloat($(this).find(".selected-mark input").val());
      //console.log($(this).attr('class') + '=calcTitleMark2=' + $(this).find('.selected-mark input').val())
    });
  return round(tot, 1);
}

function calcEachQuestMark(titleId) {
  var tot = 0;
  $("#addtestBase")
    .children()
    .each(function () {
      if ($(this).attr("class") == "selected-full-quest " + titleId) tot += 1;
    });

  var titleMark = $("." + titleId)
    .find(".select-tot-mark input")
    .val();
  //console.log('calcEachQuestMark1=', titleMark)
  var eachMark = titleMark / tot;
  //console.log(tot, 'calcEachQuestMark2=', eachMark)

  //$('.selected-full-quest .'+titleId).each(function(){
  $("#addtestBase")
    .children()
    .each(function () {
      if ($(this).attr("class") == "selected-full-quest " + titleId)
        $(this).find(".selected-mark input").val(round(eachMark, 1));
    });
}

function checkImage(imgStr) {
  var regularExp = [">", "<", ";", "!", "&"];
  var imgType = ["jpg", "png", "jpeg"];
  var imgArr = ("" + imgStr).split(".");
  if (imgType.indexOf(imgArr[imgArr.length - 1]) > -1) return true;
  else return false;

  /* var regularExp = ['>','<',';','!','&'];
    var imgType = ['jpg','png','jpeg'];
    var imgArr = (""+imgStr).split('.')
    if(imgType.indexOf(imgArr[imgArr.length-1]) > -1)
        return true;
    else
    {
        var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$");
        if (base64Matcher.test(imgStr)) {
            return true;
        } else {
            return false;
        }
    } */
}

function createJsFileName(str) {
  var imgType = ["jpg", "png", "jpeg"];
  var strArr;
  if (typeof str === "string") strArr = str.split(".");
  else strArr = str[0].split(".");

  var s = "";
  if (imgType.indexOf(strArr[strArr.length - 1]) > -1) {
    for (var i = 0; i < strArr.length - 1; i++) s += strArr[i] + ".";
  }
  return s + "js";
}
var ind = -1;
var imageArr = [];
var urlTemp = [];

function loadAllReplaceBoxImg() {
  ind += 1;
  //console.log("loadAllReplaceBoxImg(1)=====" + imageArr.length);
  if (ind < imageArr.length) {
    //console.log("loadAllReplaceBoxImg(2)=====" + imageArr[ind].id);
    var script = document.createElement("script");
    /* script.src = ""+imageArr[ind].path.split(".")[0]+".js";
        urlTemp.push(""+imageArr[ind].path.split(".")[0]+".js"); */
    script.src = createJsFileName(imageArr[ind].path);
    urlTemp.push(createJsFileName(imageArr[ind].path));
    script.onload = function () {
      //console.log(imageArr[ind].id + "=====loadAllReplaceBoxImg(3)=====" + imageArr[ind].path);
      $(".replaceBox #" + imageArr[ind].id + " img").attr("src", img);
      //console.log("loadAllReplaceBoxImg(4)=====");
      loadAllReplaceBoxImg();
    };
    document.head.appendChild(script);
  } else {
    $("script").each(function (i) {
      if (urlTemp.indexOf($(this).attr("src")) > -1) $(this).remove();
    });
    ind = -1;
    imageArr.length = 0;

    //-------------------------------------------
    $(".replaceBox.replaceBox-inner.replace-txt").each(function () {
      var tag = $(this).find(".replace-quest-txt img");
      if (tag.length > 0) calculateAspectRatioFit(tag, maxWidth, maxHeight);
    });
    //-------------------------------------------
  }
}

function removeAddedQuestAlert() {
  //console.log('removeAddedQuestAlert')
  var del = $(".deleteBox.alertBox");
  $(".deleteBox.alertBox").remove();
  $("body").append(del);
  $(".deleteBox.alertBox").show();
  var index = $(this)
    .closest(".selected-full-quest")
    .attr("id")
    .split("selectedAddedQuest")[1];

  //console.log("removeAddedQuestAlert===", index)
  $(".alertBox .alertBox-inner .cancel-btn").on("click", function () {
    $(".deleteBox.alertBox").hide();
  });
  $(".alertBox .alertBox-inner .confirm-btn").on("click", function () {
    $(".deleteBox.alertBox").hide();
    removeAddedQuestion(index);
    setSelectedQuestDetail();
  });
}

function focusinQuestMark() {
  //console.log("FOCUS INNNNNN");
  var txt = $(this);

  if (txt.val() == 0) txt.val("");

  $(document).keyup(function (e) {
    if (e.which >= 48 && e.which <= 57) {
      //console.log('==You pressed enter!===' + e.which);
      var str = txt.val();
      if (str.length > 1) txt.val(str[0] + str[1]);
    }
  });
}

function focusoutQuestMark() {
  var txt = $(this);
  //var str = Math.round(parseInt(txt.val()) * 10) / 10;
  var str = round(txt.val(), 1);

  //console.log("focusoutMark=1=" + $(this).closest('.selected-full-quest').attr('id'), str, str.length);

  if (str > -1 && str < 100) txt.val(str);
  else txt.val(0);
  /* if(txt.val()=='' || parseInt(txt.val())<0)
        txt.val(0) */

  var index;
  index = $(this)
    .closest(".selected-full-quest")
    .attr("id")
    .split("selectedQuest")[1];
  if (index == undefined) {
    index = $(this)
      .closest(".selected-full-quest")
      .attr("id")
      .split("selectedAddedQuest")[1];
    editAddedQuestion(index);
  } else {
    editQuestion(index);
  }

  //-----UPDATE TITLE MARKS---/
  var titleName = $(this)
    .closest(".selected-full-quest")
    .attr("class")
    .split("selected-full-quest ");
  $("." + titleName[1])
    .find(".select-tot-mark input")
    .val(calcTitleMark(titleName[1]));

  getShuffledQuestionArr();
}

function round(value, precision) {
  var multiplier = Math.pow(10, precision || 0);
  return Math.round(value * multiplier) / multiplier;
}
var prevTitleMark = 0;

function focusinTitleMark() {
  //console.log('focusinTitleMark', $(this).val())
  prevTitleMark = $(this).val();
}

function focusoutTitleMark() {
  var str = round($(this).val(), 1);
  if (str > -1 && str < 100) $(this).val(str);
  else $(this).val(0);

  //console.log('select-tot-mark', $(this).val(), prevTitleMark);

  if ($(this).val() != prevTitleMark) {
    prevTitleMark = $(this).val();
    //col5 title-id0 title-id-prop
    var t = $(this).closest(".col5").attr("class").split(" ");
    //console.log('focusinTitleMark2', $(this).closest('.col5').attr('class').split(' ')[1]);
    var titleName = $(this).closest(".col5").attr("class").split(" ");
    calcEachQuestMark(titleName[1]);

    $("#addtestBase")
      .children()
      .each(function () {
        if ($(this).attr("class") == "selected-full-quest " + titleName[1]) {
          var index = $(this).attr("id").split("selectedQuest")[1];
          if (index == undefined) {
            index = $(this)
              .closest(".selected-full-quest")
              .attr("id")
              .split("selectedAddedQuest")[1];
            editAddedQuestion(index);
          } else {
            editQuestion(index);
          }
        }
      });
    getShuffledQuestionArr();
  }
}
var editPrevIndex = "";
var editBool = false;

function editQuestionCont() {
  var index = $(this)
    .closest(".selected-full-quest")
    .attr("id")
    .split("selectedQuest")[1];
  if (index == undefined)
    var index = $(this)
      .closest(".selected-full-quest")
      .attr("id")
      .split("selectedAddedQuest")[1];

  if (editPrevIndex != "" && editBool) {
    //SAVE data
    editQuestion(editPrevIndex);
    var questTxt = $("#addtestBase #selectedQuest" + editPrevIndex).find(
      ".selected-quest .quest-text"
    );
    var andTxt = $("#addtestBase #selectedQuest" + editPrevIndex).find(
      ".selected-quest #answer-txt .ansTxt span"
    );
    questTxt.attr("contenteditable", "false");
    questTxt.css("border", "");
    questTxt.css("backgroundColor", "");
    questTxt.css("outline-color", "");

    var imgStr = $("#addtestBase #selectedQuest" + editPrevIndex)
      .find(".selected-quest .quest-img")
      .attr("src");
    if (imgStr == undefined || imgStr.length == 0)
      $("#addtestBase #selectedQuest" + editPrevIndex)
        .find(".selected-quest .quest-img")
        .hide();

    andTxt.attr("contenteditable", "false");
    andTxt.css("border", "");
    andTxt.css("backgroundColor", "");
    andTxt.css("outline-color", "");

    $("#addtestBase #selectedQuest" + editPrevIndex)
      .find(".selected-btn .edit-btn > span")
      .text("Edit");
    $("#addtestBase #selectedQuest" + editPrevIndex)
      .find(".selected-quest #fileinput")
      .remove();
    $("#addtestBase #selectedQuest" + editPrevIndex)
      .find(".selected-quest #fileinput1")
      .remove();

    //----------------------------------------------------------------
    editAddedQuestion(editPrevIndex);
    //console.log('EDIT+++++' + editPrevIndex)
    var questTxt = $("#addtestBase #selectedAddedQuest" + editPrevIndex).find(
      ".selected-quest .quest-text"
    );
    var andTxt = $("#addtestBase #selectedAddedQuest" + editPrevIndex).find(
      ".selected-quest #answer-txt .ansTxt span"
    );

    var imgStr = $("#addtestBase #selectedAddedQuest" + editPrevIndex)
      .find(".selected-quest .quest-img")
      .attr("src");
    if (imgStr == undefined || imgStr.length == 0)
      $("#addtestBase #selectedAddedQuest" + editPrevIndex)
        .find(".selected-quest .quest-img")
        .hide();

    questTxt.attr("contenteditable", "false");
    questTxt.css("border", "");
    questTxt.css("backgroundColor", "");
    questTxt.css("outline-color", "");

    andTxt.attr("contenteditable", "false");
    andTxt.css("border", "");
    andTxt.css("backgroundColor", "");
    andTxt.css("outline-color", "");

    $("#addtestBase #selectedAddedQuest" + editPrevIndex)
      .find(".selected-btn .edit-btn > span")
      .text("Edit");
    $("#addtestBase #selectedAddedQuest" + editPrevIndex)
      .find(".selected-quest #fileinput")
      .remove();
    $("#addtestBase #selectedAddedQuest" + editPrevIndex)
      .find(".selected-quest #fileinput1")
      .remove();
    //----------------------------------------------------------------
    getShuffledQuestionArr(false);
  }

  if (editPrevIndex != index) editBool = false;

  if (!editBool) {
    editBool = true;
    var questTxt = $(this)
      .closest(".selected-full-quest")
      .find(".selected-quest .quest-text");
    var andTxt = $(this)
      .closest(".selected-full-quest")
      .find(".selected-quest #answer-txt .ansTxt span");

    /* var hangTxt = $(this).closest('.selected-full-quest').find('.selected-quest > span .hang').text();
            questTxt = questTxt.slice(hangTxt.length, questTxt.length-1); */

    //console.log('LENGTH===' + $(this).closest('.selected-full-quest').find('.selected-quest .quest-text').tagName)

    //TO EDIT QUESTIONs IMAGE
    //if($(this).closest('.selected-full-quest').find('.selected-quest .quest-text').tagName == 'IMG'){
    $(this)
      .closest(".selected-full-quest")
      .find(".selected-quest #answer-txt")
      .before($('<input type="file" id="fileinput1" />'));
    $(this)
      .closest(".selected-full-quest")
      .find(".selected-quest #fileinput1")
      .on("change", function () {
        //$('#selectedQuest'+index).find('.selected-quest .quest-img').show();
        $(this).closest(".selected-full-quest").find(".quest-img").show();
        //convertImagesToBase64(document.getElementById("fileinput1"), $('#selectedQuest'+index).find('.selected-quest .quest-img'))
        convertImagesToBase64(
          document.getElementById("fileinput1"),
          $(this).closest(".selected-full-quest").find(".quest-img")
        );
      });
    //}/* else */
    {
      questTxt.attr("contenteditable", "true");
      questTxt.css({
        display: "block",
        "background-color": "#fff",
        border: "2px #b3b5b8 solid",
        outline: "none",
        padding: "5px",
        resize: "vertical",
        "margin-left": "10px",
      });
    }

    //TO EDIT ANSWERS IMAGE
    //if($(this).closest('.selected-full-quest').find('.selected-quest .quest-text img').length > 0){
    if (
      $(this)
        .closest(".selected-full-quest")
        .find(".selected-quest .ansTxt img").length > 0
    ) {
      $(this)
        .closest(".selected-full-quest")
        .find(".selected-quest .ansTxt")
        .append($('<input type="file" id="fileinput" />'));
      $(this)
        .closest(".selected-full-quest")
        .find(".selected-quest .ansTxt #fileinput")
        .on("change", function () {
          convertImagesToBase64(
            document.getElementById("fileinput"),
            $(this)
              .closest(".selected-full-quest")
              .find(".selected-quest .ansTxt > img")
          );
        });
    }

    andTxt.attr("contenteditable", "true");
    andTxt.css({
      display: "block",
      "background-color": "#fff",
      border: "2px #b3b5b8 solid",
      outline: "none",
      padding: "5px",
      resize: "vertical",
    });

    $(this).children("span").text("Save");
  } else {
    editBool = false;
  }
  editPrevIndex = index;
}

function replaceQuestionAlert() {
  $(".replaceBox.alertBox.replace-txt").remove();
  $(".replaceBox.alertBox").show();

  $(".replaceBox.alertBox .replace-txt").remove();
  $(".replaceBox.alertBox .replace-scroll").remove();
  $(".replaceBox.alertBox .closeBtn-wrap").remove();

  var index = $(this)
    .closest(".selected-full-quest")
    .attr("id")
    .split("selectedQuest")[1];
  /* var selectedQuest = [];
    for(var k=0; k<treeStructure.length; k++){
        selectedQuest.push(questions[index][treeStructure[k]]);
    }	
    //console.log('REPLACE==========', questions[index][treeStructure[2]]) */

  var remainQuestIndexArr = [];
  for (var i = 0; i < questions.length; i++) {
    var bool = true;
    //for(var j=0; j<treeStructure.length; j++)
    //{
    //if(selectedQuest.indexOf(questions[i][treeStructure[2]].question) == -1)

    if (questions[index].question.title != questions[i].question.title) {
      bool = false;
      //break;
    }
    //}

    if (bool && findQuestion(i) < 0) {
      //console.log('REPLACE=======1===', questions[index].question.title, questions[i].question.title)
      remainQuestIndexArr.push(i);
    }
  }

  //console.log("remainQuestIndexArr=0=" + remainQuestIndexArr.length)
  var str = "";

  if (remainQuestIndexArr.length == 0) {
    str =
      '<div class="replace-txt"><span>There is no question available.</span></div><div class="closeBtn-wrap"><button type="button" class="close-btn select-btn-prop">Close</button></div>';
  } else {
    for (var l = 0; l < remainQuestIndexArr.length; l++) {
      var s = "";
      if (questions[remainQuestIndexArr[l]].question.option.length > 0) {
        s =
          "<span>" +
          questions[remainQuestIndexArr[l]].question.option +
          "</span>";
      }
      /* else */
      if (questions[remainQuestIndexArr[l]].question.image.length > 0) {
        s +=
          "<img src=" + questions[remainQuestIndexArr[l]].question.image + ">";
        imageArr.push({
          id: "replace-quest-txt" + remainQuestIndexArr[l],
          path: questions[remainQuestIndexArr[l]].question.image,
          codeStr: "",
        });
      }

      str +=
        '<div class="replace-txt"><div class="replace-quest-txt" id="replace-quest-txt' +
        remainQuestIndexArr[l] +
        '">' +
        s +
        '</div><div class="replace-checkbox"><input type="checkbox" class="checkBoxes" id="checkBoxes' +
        remainQuestIndexArr[l] +
        '"/><label class="fright" for="checkBoxes' +
        remainQuestIndexArr[l] +
        '"' +
        "></label></div></div>";
    }

    str =
      '<div class="replace-scroll">' +
      str +
      '</div><div class="closeBtn-wrap"><button type="button" class="close-btn select-btn-prop">Close</button></div>';
  }

  $(".replaceBox >.replaceBox-inner").append(str);

  //console.log(g(checkboxQue);

  $(".replaceBox .replaceBox-inner")
    .find(".replace-checkbox")
    .on("click", function (e) {
      //console.log("remainQuestIndexArr=2===" + $(this).find('.checkBoxes').attr('id'));
      var newIndex = $(this)
        .find(".checkBoxes")
        .attr("id")
        .split("checkBoxes")[1];
      replaceQuestion(index, newIndex);
      $(".replaceBox.alertBox").hide();
      //setSelectedQuestDetail();
    });

  $(".closeBtn-wrap")
    .find(".close-btn")
    .on("click", function () {
      $(".replaceBox.alertBox").hide();
    });

  loadAllReplaceBoxImg();
}

function removeQuestionAlert() {
  var del = $(".deleteBox.alertBox");
  $(".deleteBox.alertBox").remove();
  $("body").append(del);
  $(".deleteBox.alertBox").show();
  var index = $(this)
    .closest(".selected-full-quest")
    .attr("id")
    .split("selectedQuest")[1];
  //console.log("removeQuestionAlert", index);

  $(".alertBox .alertBox-inner .cancel-btn").on("click", function () {
    $(".deleteBox.alertBox").hide();
  });
  $(".alertBox .alertBox-inner .confirm-btn").on("click", function () {
    $(".deleteBox.alertBox").hide();
    console.log(questionID, index, addedQuestions, "rajji");

    removeQuestion(questionID, index, addedQuestions);

    setSelectedQuestDetail();
  });
}
//-----------------------------------------------------------------------
//------------------------SAVE AUTO MODE QUESTION-----------------------------------
//##questionID = it is id generated to create jstree
//##index = it is the index of question in config.js
//##imgBase = it is base64 code of image question in config.js
function saveQuestAutoMode(questionID, index, imgBase = "") {
  //if(addedQuestions.indexOf(index) == -1)
  var bool = false;
  for (var i = 0; i < addedQuestions.length; i++) {
    if (addedQuestions[i].num == index) {
      bool = true;
      break;
    }
  }
  //console.log(bool + "=saveQuestAutoMode=" + i)
  if (!bool) {
    var questT = questions[index].question.option;
    var questI = imgBase; //questions[index].question.image;
    // NNO Changes
    var quesFileName = questions[index].question.image;
    var questA = questions[index].answer;
    var questM = questions[index].mark;
    var questTitle = questions[index].question.title;
    var tg_question = questions[index].tg_question;

    addedQuestions.push({
      num: index,
      id: questionID,
      questTxt: questT,
      questImg: questI,
      questImgName: quesFileName,
      questAns: questA,
      questAnsImg: "",
      questMark: questM,
      title: questTitle,
      tg_question: tg_question,
    });
  }
  //**********************************SORT****************************//
  var tempNewArr = [];
  var count = 0;
  while (addedQuestions.length > 0) {
    tempNewArr.push(addedQuestions[0]);
    addedQuestions.splice(0, 1);
    count = 0;
    while (count < addedQuestions.length) {
      if (
        addedQuestions[count].title == tempNewArr[tempNewArr.length - 1].title
      ) {
        tempNewArr.push(addedQuestions[count]);
        addedQuestions.splice(count, 1);
      } else count++;
    }
  }
  addedQuestions = tempNewArr.concat();
  //******************************************************************//
}
//------------------------SAVE QUESTION-----------------------------------
//##questionID = it is id generated to create jstree
//##index = it is the index of question in config.js
function saveQuestion(questionID, index) {
  //if(addedQuestions.indexOf(index) == -1)
  var bool = false;
  for (var i = 0; i < addedQuestions.length; i++) {
    if (addedQuestions[i].num == index) {
      bool = true;
      break;
    }
  }
  //console.log(bool + "=saveQuestion=" + i)
  if (!bool) {
    var questT = questions[index].question.option;
    var questI = ""; //questions[index].question.image;
    var questA = questions[index].answer;
    var questAImg = "";
    var questM = questions[index].mark;
    var questTitle = questions[index].question.title;
    var tg_question = questions[index].tg_question;

    var que = $(".iPage .rtContainer #questBase #option-quest" + index); //.find('.selected-quest > span');
    //if(que.find('.selected-quest img').length > 0)
    if (que.find("img").length > 0) {
      //questT="";
      questI = que.find("img").attr("src");
    }
    /* else
            questI=""; */

    addedQuestions.push({
      num: index,
      id: questionID,
      questTxt: questT,
      questImg: questI,
      questAns: questA,
      questAnsImg: questAImg,
      questMark: questM,
      title: questTitle,
      tg_question: tg_question,
    });
    console.log(addedQuestions);

    //**********************************SORT****************************//
    var tempNewArr = [];
    var count = 0;
    while (addedQuestions.length > 0) {
      tempNewArr.push(addedQuestions[0]);
      addedQuestions.splice(0, 1);
      count = 0;
      while (count < addedQuestions.length) {
        if (
          addedQuestions[count].title == tempNewArr[tempNewArr.length - 1].title
        ) {
          tempNewArr.push(addedQuestions[count]);
          addedQuestions.splice(count, 1);
        } else count++;
      }
    }
    addedQuestions = tempNewArr.concat();
    //console.log();

    //******************************************************************//
    /* for(var i=0; i<addedQuestions.length; i++)	
        //console.log(addedQuestions[i].title+"==saveQuestion==2="+i+"=="+addedQuestions[i].questAnsImg) */
  }
}
//------------------------REPLACE QUESTION-----------------------------
function replaceQuestion(oldIndex, newIndex) {
  //console.log(oldIndex + "++replaceQuestion++" + newIndex)
  /* for(var i=0; i<addedQuestions.length; i++)	
        //console.log("replace==0="+i+"=="+addedQuestions[i].num) */

  for (var i = 0; i < addedQuestions.length; i++) {
    if (addedQuestions[i].num == oldIndex) {
      var questT = questions[newIndex].question.option;
      var questI = ""; //$(".replaceBox #replace-quest-txt"+newIndex+" img").attr('src');//questions[newIndex].question.image;
      var questA = questions[newIndex].answer;
      var questAImg = "";
      //var questM = questions[newIndex].mark;
      var questTitle = questions[newIndex].question.title;

      if ($(".replaceBox #replace-quest-txt" + newIndex + " img").length > 0) {
        questI = $(".replaceBox #replace-quest-txt" + newIndex + " img").attr(
          "src"
        );
        //questT = "";
      }
      /*else{
                            questI = "";
                        } */

      addedQuestions[i].num = newIndex;
      //addedQuestions[i].id = newIndex;
      addedQuestions[i].questTxt = questT;
      addedQuestions[i].questImg = questI;
      addedQuestions[i].questAns = questA;
      addedQuestions[i].questAnsImg = "";
      //addedQuestions[i].questMark = questM;
      addedQuestions[i].title = questTitle;
      break;
    }
  }
  /* for(var i=0; i<addedQuestions.length; i++)	
        //console.log(addedQuestions[i].questAns+"==replace==2="+i+"=="+addedQuestions[i].questAnsImg) */
  loadAnsImages();
}
//------------------------EDIT QUESTION-----------------------------
function editQuestion(index) {
  for (var i = 0; i < addedQuestions.length; i++) {
    if (addedQuestions[i].num == index) {
      var que = $("#addtestBase #selectedQuest" + index); //.find('.selected-quest > span');
      var questT = que.find(".selected-quest .quest-text").html();
      var questI = que.find(".selected-quest img").attr("src");
      var questA = ""; //que.find('.selected-quest #answer-txt .ansTxt span').text();
      var questAImg = "";
      var questM = que.find(".selected-mark input").val();
      var questTitle = questions[index].question.title;

      //check question is image or text form
      //if(que.find('.selected-quest .quest-text')[0].tagName == 'IMG')
      //questT="";
      //else{
      //questI="";
      var str = que.find(".selected-quest .quest-text").html();
      if (str.replace(/\s/g, "").length > 0)
        questT = que.find(".selected-quest .quest-text").html();
      else {
        que
          .find(".selected-quest .quest-text")
          .text(addedQuestions[i].questTxt);
        questT = addedQuestions[i].questTxt;
      }
      //}

      if (questM == "") questM = "0";

      //check Answer is image or text form
      if (que.find(".selected-quest #answer-txt .ansTxt img").length > 0) {
        questAImg = que
          .find(".selected-quest #answer-txt .ansTxt img")
          .attr("src");
        questA = addedQuestions[i].questAns;
      } else {
        questAImg = "";
        var str = que.find(".selected-quest #answer-txt .ansTxt span").html();
        //console.log("str===", str)
        if (str.replace(/\s/g, "").length > 0)
          questA = que.find(".selected-quest #answer-txt .ansTxt span").html();
        else {
          que
            .find(".selected-quest #answer-txt .ansTxt span")
            .text(addedQuestions[i].questAns);
          questA = addedQuestions[i].questAns;
        }
      }
      addedQuestions[i].num = index;
      //addedQuestions[i].id = newIndex;
      addedQuestions[i].questTxt = questT;
      addedQuestions[i].questImg = questI;
      addedQuestions[i].questAns = questA;
      addedQuestions[i].questAnsImg = questAImg;
      addedQuestions[i].questMark = questM;
      addedQuestions[i].title = questTitle;
      break;
    }
  }
  /* for(var i=0; i<addedQuestions.length; i++)   
        //console.log("edit==1="+i+"=="+addedQuestions[i].num) */
}
//------------------------REMOVE QUESTION-----------------------------
function removeQuestion(questionID, index, addedQuestions) {
  console.log(index, addedQuestions);

  //if(addedQuestions.indexOf(index) > -1)
  var bool = false;
  var i = 0;
  for (; i < addedQuestions.length; i++) {
    if (addedQuestions[i].num == index) {
      bool = true;
      break;
    }
  }
  if (bool) addedQuestions.splice(i, 1);
}
//------------------------FIND QUESTION-----------------------------
function findQuestion(index) {
  var bool = false;
  var i = 0;
  for (; i < addedQuestions.length; i++) {
    if (addedQuestions[i].num == index) {
      bool = true;
      break;
    }
  }
  if (bool) return i;
  else return -1;
}
//------------------------SAVE Additional QUESTION-----------------------------------
function saveAdditionalQuestion(titleTxt, questT, questI, AnsT, AnsI, questM) {
  console.log(titleTxt, questT, questI, AnsT, AnsI, questM, "rajji");

  var index = "index" + addedNewQuestions.length;
  var questionID = "questionID" + addedNewQuestions.length;

  //console.log("saveAdditionalQuestion:" + questT.length, AnsT.length)

  addedNewQuestions.push({
    num: index,
    id: questionID,
    questTxt: questT,
    questImg: questI,
    questAns: AnsT,
    questAnsImg: AnsI,
    questMark: questM,
    title: titleTxt,
  });

  //for(i=0;i<addedNewQuestions.length;i++)
  //	//console.log('1num:'+addedNewQuestions[i].num+' id:'+addedNewQuestions[i].id+' questTxt:'+addedNewQuestions[i].questTxt+' questImg:'+addedNewQuestions[i].questImg+' questAns:'+addedNewQuestions[i].questAns+' questMark:'+addedNewQuestions[i].questMark)

  //**************************sort according to title**********************//
  var tempNewArr = [];
  var count = 0;
  while (addedNewQuestions.length > 0) {
    tempNewArr.push(addedNewQuestions[0]);
    addedNewQuestions.splice(0, 1);

    count = 0;
    while (count < addedNewQuestions.length) {
      if (
        addedNewQuestions[count].title ==
        tempNewArr[tempNewArr.length - 1].title
      ) {
        tempNewArr.push(addedNewQuestions[count]);
        addedNewQuestions.splice(count, 1);
      } else count++;
    }
  }
  addedNewQuestions = tempNewArr.concat();
  console.log(addedNewQuestions, "rajji");

  //**************************************************************************//
  /* for(i=0;i<addedNewQuestions.length;i++)
        //console.log('num:'+addedNewQuestions[i].num+' id:'+addedNewQuestions[i].id+' questTxt:'+addedNewQuestions[i].questTxt+' questImg:'+addedNewQuestions[i].questImg+' questAns:'+addedNewQuestions[i].questAns+' questMark:'+addedNewQuestions[i].questMark) */
}
//------------------------------------------------------------------
//------------------------REMOVE Additional QUESTION-----------------------------
function removeAddedQuestion(index) {
  console.log(addedNewQuestions, "rajji");

  var bool = false;
  var i = 0;
  for (; i < addedNewQuestions.length; i++) {
    if (addedNewQuestions[i].num == index) {
      bool = true;
      break;
    }
  }
  if (bool) addedNewQuestions.splice(i, 1);
}
//-------------------------------------------------------------------------------
//------------------------EDIT Additional QUESTION-----------------------------
function editAddedQuestion(index) {
  //console.log("+editAddedQuestion+++" + index)
  for (var i = 0; i < addedNewQuestions.length; i++)
    //console.log("edit==0=" + i + "==" + addedNewQuestions[i].num + "==" + index)

    for (var i = 0; i < addedNewQuestions.length; i++) {
      if (addedNewQuestions[i].num == index) {
        var que = $("#addtestBase #selectedAddedQuest" + index); //.find('.selected-quest > span');
        var questT = que.find(".selected-quest .quest-text").text();
        var questI = que.find(".selected-quest img").attr("src") || "";
        var ansT = que.find(".selected-quest #answer-txt .ansTxt span").text();
        var ansI = que.find(".selected-quest #answer-txt .ansTxt span").text();
        var questM = que.find(".selected-mark input").val();

        //check question is image or text form
        //if(que.find('.selected-quest img').length > 0)
        /* if(que.find('.selected-quest .quest-text')[0].tagName == 'IMG')
            questT="";
            else{ */
        var str = que.find(".selected-quest .quest-text").text();
        if (str.replace(/\s/g, "").length > 0)
          questT = que.find(".selected-quest .quest-text").text();
        else {
          que
            .find(".selected-quest .quest-text")
            .text(addedNewQuestions[i].questTxt);
          questT = addedNewQuestions[i].questTxt;
        }
        /* questI="";
            } */
        //check Answer is image or text form
        if (que.find(".selected-quest #answer-txt .ansTxt img").length > 0) {
          ansI = que
            .find(".selected-quest #answer-txt .ansTxt img")
            .attr("src");
          ansT = "";
        } else {
          ansI = "";
          var str = que.find(".selected-quest #answer-txt .ansTxt span").text();
          if (str.replace(/\s/g, "").length > 0)
            ansT = que.find(".selected-quest #answer-txt .ansTxt span").text();
          else {
            que
              .find(".selected-quest #answer-txt .ansTxt span")
              .text(addedNewQuestions[i].questAns);
            ansT = addedNewQuestions[i].questAns;
          }
        }

        if (questM == "") questM = "0";

        addedNewQuestions[i].num = index;
        //addedNewQuestions[i].id = newIndex;
        addedNewQuestions[i].questTxt = questT;
        addedNewQuestions[i].questImg = questI;
        addedNewQuestions[i].questAns = ansT;
        addedNewQuestions[i].questAnsImg = ansI;
        addedNewQuestions[i].questMark = questM;
        break;
      }
    }
  /* for (var i = 0; i < addedNewQuestions.length; i++){
        //console.log("edit==1=" + i + "==" + addedNewQuestions[i].num)
    } */
}
