var crssword = crssword || {};

crssword.clues = (function () {
    var currentLang=null;

  var setClueNumber = function () {
    var clueNumber = 0;
    for (var i = 0; i < puzzleData.grid.data.length; i++) {
      var sameStartAsPrevious = false;
      if (i > 0) {
        if (puzzleData.grid.data[i].startAt === puzzleData.grid.data[i - 1].startAt) {
          sameStartAsPrevious = true;
        }
      }
      if (!sameStartAsPrevious) {
        clueNumber++;
      }
      puzzleData.grid.data[i].clueNumber = clueNumber;
      _displayGridNumbers(puzzleData.grid.data[i]);
      crssword.setup.displayCellInputs(puzzleData.grid.data[i]);
    }
    _displayBlanks();
  };

  var _displayBlanks = function () {
    var allRows = document.querySelectorAll("#gridGfx .row");
    for (var row=0; row<allRows.length; row++){
      var rowCells = allRows[row].querySelectorAll(".cell");
      for (var cell=0; cell<rowCells.length; cell++){
        if(!crssword.repeats.hasClass(rowCells[cell], "cellInput")){
          var cellImg = crssword.repeats.newEls("img",rowCells[cell],{"src":"images/cellBkg.jpg"});
          crssword.repeats.updateClass("add", cellImg, "cellBkg")
        }
      }
    }

  };
  var displayClues = function (lang) {
    //, "lang":"en", "hreflang":"en"
    for (var i = 0; i < puzzleData.grid.data.length; i++) {
      var direction = puzzleData.grid.data[i].direction.charAt(0).toUpperCase() + puzzleData.grid.data[i].direction.slice(1);
      var cluesContainer = document.getElementById("clues" + direction + "Container");
      var clueDiv = crssword.repeats.newEls("div", cluesContainer, {});
      var numDirId= puzzleData.grid.data[i].clueNumber + "-" + puzzleData.grid.data[i].direction
      var clueDivA = crssword.repeats.newEls("div", clueDiv, {
        "id": "clue-" +numDirId
      });
      crssword.repeats.updateClass("add", clueDivA, "item");
      var clueDivANum = crssword.repeats.newEls("div", clueDivA, {"aria-hidden":"true"});
      crssword.repeats.updateClass("add", clueDivANum, "num");
      var clueDivATxt = crssword.repeats.newEls("div", clueDivA, {});
      crssword.repeats.updateClass("add", clueDivATxt, "txt");







      clueDivA.onclick = function () {
        var el = document.getElementById(this.id.split("clue-").join("clue-txt-"));
        el.focus();
        _highlightCurrentClue(el);
      };
      clueDivANum.appendChild(document.createTextNode(puzzleData.grid.data[i].clueNumber));
      var clueDivATxtInput = crssword.repeats.newEls("input", clueDivATxt, {"type": "text","id": "clue-txt-" + numDirId});
      _addClueTxt(clueDivATxtInput, puzzleData.grid.data[i], lang);
      clueDivATxtInput.onblur = function () {
        unhighlightClue();
        _unhighlightCells();
      };

      clueDivATxtInput.onfocus = function () {
          _timeOutCellHighlight(this);
      };clueDivATxtInput.onclick = function () {
            _timeOutCellHighlight(this);
      };
      clueDivATxtInput.onkeyup = function (e) {
          var allAnswerCells = document.querySelectorAll("." + this.id.split("clue-txt").join("answer") + "-input");
        if(e.keyCode === 37 || e.keyCode === 39 || e.keyCode === 8 || e.keyCode === 46) {
          _unhighlightCells();
          if(document.getElementById(this.id.split("clue-txt-")[1] + "-input-" + this.selectionStart) !==null) {
              _highlightCell(document.getElementById(this.id.split("clue-txt-")[1] + "-input-" + this.selectionStart).parentNode);
          }
          if(e.keyCode === 8 || e.keyCode === 46){
              updateText(this);
          }
        }
        if (e.keyCode !== 9 && e.keyCode !== 13 && e.keyCode !== 27 && e.keyCode !== 16 && e.keyCode !== 17 && e.keyCode !== 37 && e.keyCode !== 39 &&  e.keyCode !== 46 && e.keyCode !== 8) {
          if (!this.getAttribute("readonly")) {
            if (this.value.split(" ").join("").length < allAnswerCells.length) {
              updateText(this);
              //_unhighlightCells();
              if (allAnswerCells.length !== this.value.split(" ").join("").length) {
                  _unhighlightCells();
                  _highlightCell(document.getElementById(this.id.split("clue-txt-")[1] + "-input-"  + this.selectionStart).parentNode);
              }
            } else {
              this.value = this.value.slice(0, allAnswerCells.length + this.value.split(" ").length - 1);
              updateText(this);
              _unhighlightCells();
            }
          }
        }
      };
    }
  };
  var _timeOutCellHighlight= function(el){
      unhighlightClue();
      _highlightCurrentClue(el);
      setTimeout(function(){
          var el = document.querySelector(".item.highlight .txt input[type=\"text\"")
          _unhighlightCells();
          _highlightCell(document.getElementById(el.id.split("clue-txt-")[1] + "-input-" + el.selectionStart).parentNode);
      },100);
  }

  var _addClueTxt = function (el, gridData, lang) {
    console.log()
      el.parentNode.setAttribute("lang",puzzleData.options.languages.types[lang].code)
      el.setAttribute("lang",puzzleData.options.languages.types[lang].code)
      var strLength = gridData.answer.split(" ");
      for (var j = 0; j < strLength.length; j++) {
        strLength[j] = strLength[j].length;
      }
      if(document.getElementById("sr-clue-"+gridData.clueNumber+"-"+gridData.direction)) {
        document.getElementById("sr-clue-"+gridData.clueNumber+"-"+gridData.direction).parentNode.removeChild(document.getElementById("sr-clue-"+gridData.clueNumber+"-"+gridData.direction))
      }
      var inputContainer = crssword.repeats.newEls("div",el.parentNode,{"id":"sr-clue-"+gridData.clueNumber+"-"+gridData.direction, "lang": puzzleData.options.languages.types[lang].code })
      var srclue = crssword.repeats.newEls("label",inputContainer,{"id":"sr-clue-"+gridData.clueNumber+"-"+gridData.direction, "lang": puzzleData.options.languages.types[lang].code, "for":"clue-txt-" + gridData.clueNumber + "-" + gridData.direction})
      var srOnly1 = crssword.repeats.newEls("span",srclue);
      srOnly1.appendChild(document.createTextNode(gridData.clueNumber+ " "+puzzleData.options.axis[gridData.direction][lang]+": "))
      crssword.repeats.updateClass("add", srOnly1, "sr-only");
      var srTxt1 = crssword.repeats.newEls("span",srclue, {"lang":puzzleData.options.languages.types[lang].code});
      srTxt1.appendChild(document.createTextNode(gridData.clue[lang]))
      var srTxt2 = crssword.repeats.newEls("span",srclue, {"lang":puzzleData.options.languages.types[lang].code});
      srTxt2.appendChild(document.createTextNode(". "+puzzleData.options.languages.types[lang].length+": "))
      crssword.repeats.updateClass("add", srTxt2, "sr-only");
    var srTxt3 = crssword.repeats.newEls("span",srclue, {"lang":puzzleData.options.languages.types[lang].code});
    srTxt3.appendChild(document.createTextNode(" ("+strLength+")"));

      //el.setAttribute("aria-label","testing this label thing and how it works")
      el.parentNode.insertBefore(srclue, el);


    var span = crssword.repeats.newEls("span", srclue, {"id": "readChars-" + gridData.clueNumber + "-" + gridData.direction});
    crssword.repeats.updateClass("add", span, "sr-only");
    updateCharactersForClue(document.getElementById("clue-txt-" + gridData.clueNumber + "-" + gridData.direction), true, lang);

    var span = crssword.repeats.newEls("span", srclue, {"id": "answeredSrOnly-" + gridData.clueNumber + "-" + gridData.direction});
    crssword.repeats.updateClass("add", span, "sr-only");

    var isblank= true;
    if(document.getElementById("clue-txt-" + gridData.clueNumber + "-" + gridData.direction).value.length>0){
      isblank=false;
    }
    updateCharactersForClue(document.getElementById("clue-txt-" + gridData.clueNumber + "-" + gridData.direction), isblank, lang);

  };



    /*"incorrectAnswer":"Incorrect answer",
    "correctAnswer":"Correct answer"*/

  var updateCharactersForClue = function (el, blanks) {
    var cells = document.querySelectorAll(".answer" + el.id.split("clue-txt")[1] + "-input");
    var updateInputs =[el.id];
    if(blanks) {
      var blankStr=[];
      _addCharactersTxt(document.getElementById("readChars"+el.id.split("clue-txt")[1]),". "+puzzleData.options.languages.types[crssword.clues.currentLang].lettersFound+": "+puzzleData.options.languages.types[crssword.clues.currentLang].noLettersFound+".")
    } else {
      for (var j = 0; j < cells.length; j++) {
        var siblingCells = cells[j].parentNode;
        siblingCells = siblingCells.getElementsByTagName("input");
        for (var k = 0; k < siblingCells.length; k++) {
          if (cells[j] !== siblingCells[k]) {
            updateInputs.push("clue-txt-" + siblingCells[k].id.split("-input")[0])
          }
        }
      }
      for (var inputCurr = 0; inputCurr < updateInputs.length; inputCurr++) {

        var str=[];
        var updateCells = document.querySelectorAll(".answer" + updateInputs[inputCurr].split("clue-txt")[1] + "-input");
        for (var l = 0; l < updateCells.length; l++) {
          if (updateCells[l].value === "") {
            var valToPush="";

            var siblingCellsCurr = updateCells[l].parentNode;
            siblingCellsCurr = siblingCellsCurr.getElementsByTagName("input");
            for (var m = 0; m < siblingCellsCurr.length; m++) {
              if (updateCells[l] !== siblingCellsCurr[m] && siblingCellsCurr[m].value !== "") {
                valToPush=siblingCellsCurr[m].value;
                str.push(valToPush)
              }
            }
            if(valToPush==="") {
              //console.log(puzzleData.options.languages.types[lang].blank)
              str.push(puzzleData.options.languages.types[crssword.clues.currentLang].blank)
            }
          } else {
            str.push(updateCells[l].value);
          }
        }
        var allCharsBlank=true;
        for(var char=0; char<str.length; char++){
          if(str[char]!==puzzleData.options.languages.types[crssword.clues.currentLang].blank) {
            allCharsBlank=false;
          }
        }
        if(allCharsBlank) {
          str=puzzleData.options.languages.types[crssword.clues.currentLang].noLettersFound
        } else {
          str=str.join(", ");
        }
        _addCharactersTxt(document.getElementById("readChars"+updateInputs[inputCurr].split("clue-txt")[1]),". "+puzzleData.options.languages.types[crssword.clues.currentLang].lettersFound+": "+str+".")
      }
    }
  };
  var _addCharactersTxt = function(el, val){
    while (el.firstChild){
      el.removeChild(el.firstChild);
    }
    el.appendChild(document.createTextNode(val));
  };
  var addDirectionTitleTxt = function (lang, axisData) {
    var cluesAcrossH1 = crssword.repeats.newEls("h1", document.getElementById("cluesAcrossContainer"), {"aria-hidden":"true", "lang":puzzleData.options.languages.types[lang].code});
    cluesAcrossH1.appendChild(document.createTextNode(axisData.across[lang]));
    var cluesDownH1 = crssword.repeats.newEls("h1", document.getElementById("cluesDownContainer"), {"aria-hidden":"true", "lang":puzzleData.options.languages.types[lang].code});
    cluesDownH1.appendChild(document.createTextNode(axisData.down[lang]));
  };

  var updateClues = function (lang) {

      crssword.clues.currentLang=lang;
    crssword.lang.highlightLangBtn(lang);
    for (var i = 0; i < puzzleData.grid.data.length; i++) {
      console.log(puzzleData.grid.data[i])
      //remove clue
      var txt = document.querySelectorAll("#clue-txt-" + puzzleData.grid.data[i].clueNumber + "-" + puzzleData.grid.data[i].direction);
      while (txt[0].firstChild) {
        txt[0].removeChild(txt[0].firstChild);
      }
      //inc clue
      _addClueTxt(txt[0], puzzleData.grid.data[i], lang);
    }

    var cluesAcrossContainer = document.querySelectorAll("#cluesAcrossContainer h1")[0];
    cluesAcrossContainer.removeChild(cluesAcrossContainer.firstChild);
    cluesAcrossContainer.appendChild(document.createTextNode(puzzleData.options.axis.across[lang]));
    var cluesDownContainer = document.querySelectorAll("#cluesDownContainer h1")[0];
    cluesDownContainer.removeChild(cluesDownContainer.firstChild);
    cluesDownContainer.appendChild(document.createTextNode(puzzleData.options.axis.down[lang]));
    refreshlangtags(lang)
  };

  var refreshlangtags = function(lang){
    var langcode=puzzleData.options.languages.types[lang].code;
    var updatelang=document.querySelectorAll(".updatelang")
    console.log(updatelang)
    for(var i=0; i<updatelang.length; i++){
      console.log(updatelang[i])
      updatelang[i].setAttribute("lang", langcode)
    }
  }

  var updateText = function (el, reveal) {
    crssword.setup.clearAnswerClasses(el);
    var allAnswerCells = document.querySelectorAll("." + el.id.split("clue-txt").join("answer") + "-input");
    var elVal = el.value.split(" ").join("");
    var firstBlank = null;
    for (var cell = 0; cell < allAnswerCells.length; cell++) {
      if (elVal.charAt(cell)) {
        allAnswerCells[cell].value = elVal.charAt(cell);
      } else {
        if (!firstBlank) {
          firstBlank = allAnswerCells[cell];
        }
        allAnswerCells[cell].value = "";
      }
      if (!reveal) {
        var intersectingCell = undefined;
        var inputSibling = allAnswerCells[cell].parentNode.childNodes;
        if (allAnswerCells[cell].value !== "") {
          if (inputSibling.length > 1) {
            for (var sibling = 0; sibling < inputSibling.length; sibling++) {
              if (inputSibling[sibling].tagName === "INPUT" && inputSibling[sibling] !== allAnswerCells[cell]) {
                intersectingCell = inputSibling[sibling];
                var intersectingCellIdSplit = intersectingCell.id.split("-input-");
                var intersectingTxt = document.getElementById("clue-txt-" + intersectingCellIdSplit[0]);
                if (intersectingTxt.value.length >= Number(intersectingCellIdSplit[1])) {
                  intersectingCell.value = allAnswerCells[cell].value;
                  var siblingCells = document.querySelectorAll(".answer-" + intersectingCellIdSplit[0] + "-input");
                  var newSiblingInputTxt = "";
                  for (var i = 0; i < siblingCells.length; i++) {
                    newSiblingInputTxt = newSiblingInputTxt + siblingCells[i].value;
                  }
                  intersectingTxt.value = newSiblingInputTxt;
                  crssword.setup.clearAnswerClasses(intersectingTxt)
                }
              }
            }
          }
        }
      }
    }
    updateCharactersForClue(el, null);
  };

  var _displayGridNumbers = function (data) {
    var currentCell = document.getElementById("cell-" + data.x + "-" + data.y);
    var cellNumber = crssword.repeats.newEls("span", currentCell, {});
    crssword.repeats.updateClass("add", cellNumber, "num");
    cellNumber.appendChild(document.createTextNode(data.clueNumber));
  };

  var _highlightCurrentClue = function (el) {
    unhighlightClue();
    var numDir=el.id.split("clue-txt-").join("");
    while (document.getElementById("srInputDesc").hasChildNodes()){
      document.getElementById("srInputDesc").removeChild(document.getElementById("srInputDesc").firstChild)
    }
    var clone = document.getElementById("sr-clue-"+numDir).cloneNode(true);
    if(clone.getAttribute("id")){
      clone.removeAttribute("id")
    }
    for(var i=0; i<clone.childNodes.length; i++){
     if(clone.childNodes[i].getAttribute("id")){
       clone.childNodes[i].removeAttribute("id")
     }
    }
   document.getElementById("srInputDesc").appendChild(clone)
   /* document.getElementById("sr-clue-"+numDir).setAttribute("aria-live","assertive")
    document.getElementById("sr-clue-"+numDir).setAttribute("aria-atomic","true")*/
    //
    var selectedInputCells = document.querySelectorAll(".answer-" +numDir);
    for (var cell = 0; cell < selectedInputCells.length; cell++) {
      crssword.repeats.updateClass("add", selectedInputCells[cell], "highlight");
    }
    crssword.repeats.updateClass("add", el.parentNode.parentNode, "highlight");
    _unhighlightCells();
    if (selectedInputCells.length > el.value.split(" ").join("").length) {
      _highlightCell(document.getElementById(el.id.split("clue-txt-")[1] + "-input-" + el.value.split(" ").join("").length).parentNode);
    }
  };

  var _highlightCell = function (cell) {
    crssword.repeats.updateClass("add", cell, "currentHighlight");
  };

  var _unhighlightCells = function () {
    var cells = document.querySelectorAll(".cell.cellInput");
    for (var cell = 0; cell < cells.length; cell++) {
      crssword.repeats.updateClass("remove", cells[cell], "currentHighlight");
    }
  };

  var unhighlightClue = function () {
    var allInputCells = document.querySelectorAll(".cellInput.highlight");
    for (var cell = 0; cell < allInputCells.length; cell++) {
      crssword.repeats.updateClass("remove", allInputCells[cell], "highlight");
    }
    var allClues = document.querySelectorAll("#cluesContainer .item");

    for (var clue = 0; clue < allClues.length; clue++) {
      crssword.repeats.updateClass("remove", allClues[clue], "highlight");
    }
  };

  return {
    setClueNumber: setClueNumber,
    displayClues: displayClues,
    addDirectionTitleTxt: addDirectionTitleTxt,
    updateText: updateText,
    updateClues: updateClues,
    unhighlightClue: unhighlightClue,
    refreshlangtags:refreshlangtags,
    currentLang:currentLang
  };
})();

