//-----------------------------------------------------------------------------------------
//-- déclaration des variables globales
//-----------------------------------------------------------------------------------------

var reglages = [false,false] // [isDécongel, isSearing]
var btnDivImg = document.getElementsByClassName('btnIHM')
var nomBouton = ["power","decongel","marquage","leftArrow","rightArrow","ok"]
var ecranDiv = document.getElementById('ecran')
var ecranOverlay = document.getElementById('ecranOverlay')
var gauche = document.getElementById('gauche')
var droite = document.getElementById('droite')
var menu = document.getElementById('menuSlide')
var items = document.getElementsByClassName('item')
var topLeft = document.getElementById("ecranTopLeft")
var topRight = document.getElementById("ecranTopRight")
var actualScreen = "off"
var slidePos = 0
var viande = document.getElementById("viande")
var btnViande = document.getElementById("btnViande")
var viandeSound = document.getElementById("viandeSound")
var isViande = false
var boutonMarquageNum = 1
var arrayOverlay = ["","","",""]; //gère les timeout
var styleBoutonMarquage
var manuFolder = 2


viandeSound.volume=0.05;

//affiche un cercle là où l'utilisateur appuie
function touchPosition(posX,posY,nature){
  document.getElementById("touchPosition").style.left = (posX-25)+"px"
  document.getElementById("touchPosition").style.top = (posY-25)+"px"
}

document.addEventListener("mousemove", function (e){
  var teY = e.clientY;
  var teX = e.clientX;
  document.getElementById("hand").style.left = (teX-66)+"px"
  document.getElementById("hand").style.top = (teY-53)+"px"
})

document.addEventListener("mousedown", function (e){
  document.getElementById("hand").style.backgroundSize = "620px 800px"
})

document.addEventListener("mouseup", function (e){
  document.getElementById("hand").style.backgroundSize = "auto"
})


//go fullscreen
function toggleFullScreen() {
  var doc = window.document;
  var docEl = doc.documentElement;

  var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;

  if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
    requestFullScreen.call(docEl);
  }
  else {
    cancelFullScreen.call(doc);
  }
}

//-----------------------------------------------------------------------------------------
//-- fonction qui s'execute lorsqu'on clicque sur la touche "bouton"
//-----------------------------------------------------------------------------------------

function clickBtn(bouton){
  if (document.getElementsByClassName("btnIHM")[nomBouton.indexOf(bouton)].getElementsByTagName('img')[0].getAttribute("src") === "./ihm/carre-off.png" && nomBouton.indexOf(bouton) !== 0) {
    if (actualScreen === "off") {
      return
    }
  }else if (
    bouton === "decongel" && actualScreen !== "choix"
    || bouton === "marquage" && actualScreen !== "choix"
    || actualScreen === "choix" && isViande && bouton !== "power" && bouton !== "manuel"
    || actualScreen === "prechauffeAuto" && isViande && bouton !== "power" && bouton !== "manuel"
    || bouton === "leftArrow" || bouton === "rightArrow"
  ) {
    return
  }else{
    playSound()
  }
  if (bouton === "power") {
    if (actualScreen === "off") {
      displayScreen("bonjour")
    }else {
      reglages = [false,false]
      displayScreen("aurevoir")
    }
  }else if (bouton === "decongel" && actualScreen === "choix") {
    changeMode("decongel")
  }else if (bouton === "marquage" && actualScreen === "choix") {
    changeMode("marquage")
  }else if (bouton === "ok") {
    if (actualScreen === "choix" && slidePos % 13 === 1) {
      if (ecranOverlay.style.backgroundImage === "") {
        displayScreen("prechauffeAuto")
      }else {
        ecranOverlay.style.backgroundImage = ""
      }
    }else if (actualScreen === "choix" && slidePos % 13 === 12) {
      reglages = [false,false]
      displayScreen("manuTemperature")
    } else if (actualScreen === "manuTemperature" && slidePos === 12) {
      displayScreen("manuChauffe")
    } else if (actualScreen === "manuChauffe" && ecranOverlay.getElementsByTagName('video')[0].currentTime > 29) {
      displayScreen("manuTemps")
    } else if (actualScreen === "manuMinuteur" && ecranOverlay.getElementsByTagName('video')[0].currentTime > 50) {
      displayScreen("manuTemps")
    } else if (actualScreen === "manuTemps" && slidePos === 10) {
      displayScreen("manuMinuteur")
    }
  }
}



//-----------------------------------------------------------------------------------------
//-- fonction qui affiche l'écran "nextScreen"
//-----------------------------------------------------------------------------------------

function displayScreen(nextScreen,videoPosition){
  console.log(nextScreen);
  if (nextScreen === "choix" && actualScreen === "bonappetit") {
    if (isViande) {
      ecranOverlay.innerHTML = "<video src=\"./ecrans/retirez2.mov\" loop></video>"
      ecranOverlay.getElementsByTagName('video')[0].play()
    }else {
      ecranOverlay.innerHTML = ""
    }
    topRight.style.backgroundImage = "url('./ecrans/icone-marquage.png')"
    topLeft.style.backgroundImage = "url('./ecrans/icone-decongel.png')"
    topRight.style.display = "block"
    topLeft.style.display = "block"
    ecranDiv.style.transition = "background-position .2s"
    ecranDiv.style.backgroundPosition = "28px"
  }else if (nextScreen === "choix") {
    if (isViande) {
      ecranOverlay.innerHTML = "<video src=\"./ecrans/retirez2.mov\" loop></video>"
      ecranOverlay.getElementsByTagName('video')[0].play()
    }else {
      ecranOverlay.innerHTML = ""
    }
    topRight.style.opacity = 0
    topLeft.style.opacity = 0
    topRight.style.backgroundImage = "url('./ecrans/icone-marquage.png')"
    topLeft.style.backgroundImage = "url('./ecrans/icone-decongel.png')"
    topRight.style.display = "block"
    topLeft.style.display = "block"
    ecranDiv.style.transition = "background-position .2s"
    ecranDiv.style.backgroundPosition = "28px"
  }else if (nextScreen === "prechauffeAuto") {
    ecranOverlay.innerHTML = ""
    ecranDiv.style.transition = ""
    //ecranDiv.style.backgroundImage = ""
    //ecranDiv.style.backgroundColor = "black"
    ecranOverlay.style.backgroundImage= ""
  }else if (nextScreen === "cuisson") {
    ecranOverlay.innerHTML = ""
    ecranDiv.style.transition = ""
    ecranOverlay.style.backgroundImage= ""
  }else  {
    topRight.style.display = "none"
    topLeft.style.display = "none"
    ecranOverlay.innerHTML = ""
    ecranDiv.style.transition = ""
    ecranOverlay.style.backgroundImage= ""
  }
  if (nextScreen === "manuTemperature") {
    gauche.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/gauche-moins.png')"
    droite.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/droite-plus.png')"
    gauche.style.marginLeft = "0px"
    droite.style.marginLeft = "0px"
    gauche.style.marginTop = "0px"
    droite.style.marginTop = "0px"
  }else if (nextScreen === "manuTemperature") {
    gauche.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/gauche-moins.png')"
    droite.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/droite-plus.png')"
    gauche.style.marginLeft = "0px"
    droite.style.marginLeft = "0px"
    gauche.style.marginTop = "0px"
    droite.style.marginTop = "0px"
  }else if (nextScreen === "manuChauffe" || nextScreen === "manuMinuteur") {
    gauche.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/gauche-moins.png')"
    droite.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/droite-plus.png')"
    gauche.style.marginLeft = "15px"
    droite.style.marginLeft = "-15px"
    gauche.style.marginTop = "-53px"
    droite.style.marginTop = "-53px"
  }else if (nextScreen === "manuTemps") {
    gauche.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/gauche-moins.png')"
    droite.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/droite-plus.png')"
    gauche.style.marginLeft = "0px"
    droite.style.marginLeft = "0px"
    gauche.style.marginTop = "37px"
    droite.style.marginTop = "37px"
  }else {
    gauche.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/gauche-moins.png')"
    droite.style.backgroundImage = "url('./ecrans/manuel"+manuFolder+"/droite-plus.png')"
    gauche.style.marginTop = "-35px"
    droite.style.marginTop = "-35px"
    gauche.style.marginLeft = "-45px"
    droite.style.marginLeft = "45px"
  }
  if (search(nextScreen).type === "video") {
    if (search(nextScreen).folder === "manu") {
      ecranOverlay.innerHTML = "<video src=\"./ecrans/manuel"+manuFolder+"/"+nextScreen+".mov\" width=\"146\" height=\"146\"></video>"
    }else {
      ecranOverlay.innerHTML = "<video src=\"./ecrans/"+nextScreen+".mov\" width=\"146\" height=\"146\"></video>"
    }
    if(videoPosition){
      ecranOverlay.getElementsByTagName('video')[0].currentTime = videoPosition;
    }

    ecranOverlay.getElementsByTagName('video')[0].play()
  }else {
    //ecranOverlay.innerHTML = ""
    if (search(nextScreen).folder === "manu") {
      ecranDiv.style.backgroundImage = "url(./ecrans/manuel"+manuFolder+"/"+nextScreen+".png)";
    }else {
      ecranDiv.style.backgroundImage = "url(./ecrans/"+nextScreen+".png)";
    }
    document.getElementById("ecranBottom").style.display = (nextScreen === 'choix' || nextScreen === 'manuTemperature') ? 'block' :'none';
    document.getElementById("ecranBottom").style.backgroundImage = (nextScreen === 'choix') ? "url('./ecrans/choix-noms.png')" :"none";
  }

  if (nextScreen === "off") {
    viande.className = "pos1"
    btnViande.className = "pos1"
    viandeSound.pause()
    isViande = false
  }else if (nextScreen === "aurevoir") {
    ecranOverlay.innerHTML = ""
  }
  displayIHM(search(nextScreen).btnIHM)

  //-- ecrans avec timing -----------------------------------------------------------------------
  var BDDscreen = search(nextScreen);
  if (BDDscreen.timing) {
    setTimeout(function(){ displayScreen(BDDscreen.timing[1]); }, BDDscreen.timing[0])
  }
  if (nextScreen === "manuTemperature") {
    actualScreen = nextScreen
    slide("goTo", 7)
  }else if (actualScreen === "bonappetit"){
    actualScreen = nextScreen
    slide("goTo", 651)
  }else if (nextScreen === "choix") {
    actualScreen = nextScreen
    slide("goTo", 650)
  }else {
    actualScreen = nextScreen
    if (actualScreen === "prechauffeAuto") {
      setTimeout(function(){
        slide("goTo", 0)
      },1000)
    }else {
      slide("goTo", 0)
    }
  }
}


//-----------------------------------------------------------------------------------------
//-- fonction qui affiche l'IHM correspondant à l'écran "nextScreen"
//-----------------------------------------------------------------------------------------

function displayIHM(arrayBtn,numBtn,posBtn){
  if (arrayBtn === "change") {
    if (posBtn === 1) {
      btnDivImg[numBtn].innerHTML = "<img class=\"carre\" src=\"./ihm/carre.gif\">";
    }else if (posBtn === 2) {
      btnDivImg[numBtn].innerHTML = "<img class=\"carre\" src=\"./ihm/carre.png\">";
    }else{
      btnDivImg[numBtn].innerHTML = "<img class=\"carre\" src=\"./ihm/carre-off.png\">";
    }
  }else {
    for (var i = 0; i < arrayBtn.length; i++) {
      if (i=== 1 && reglages[0]) {
        btnDivImg[i].innerHTML = "<img class=\"carre\" src=\"./ihm/carre.png\">";
      }else if (i=== 2 && reglages[1]) {
        btnDivImg[i].innerHTML = "<img class=\"carre\" src=\"./ihm/carre.png\">";
      }else if (arrayBtn[i] === 1) {
        btnDivImg[i].innerHTML = "<img class=\"carre\" src=\"./ihm/carre.gif\">";
      }else if (arrayBtn[i] === 2) {
        btnDivImg[i].innerHTML = "<img class=\"carre\" src=\"./ihm/carre.png\">";
      }else{
        btnDivImg[i].innerHTML = "<img class=\"carre\" src=\"./ihm/carre-off.png\">";
      }
    }
  }
}

//-----------------------------------------------------------------------------------------
//-- fonction qui slide dans le menu d'accueil
//-----------------------------------------------------------------------------------------


function slide(direction, frame){
  if (direction === "goTo") {
    slidePos = frame
    if (actualScreen === "choix") {
      ecranDiv.style.backgroundPosition = "-"+(slidePos*90-28)+"px"
      document.getElementById("ecranBottom").style.backgroundPosition = "-"+(slidePos*146)+"px"
    }else {
      ecranDiv.style.backgroundPosition = "-"+(slidePos*146)+"px"
    }
    return;
  }
  if (direction === "leftArrow" && slidePos > 0) {
    slidePos -= 1
  }else if (direction === "rightArrow") {
    if (actualScreen === "choix") {
      slidePos += 1
    }else if (slidePos < (search(actualScreen).nmbreSlides-1)) {
      slidePos += 1
    }
  }else {
    return;
  }
  if (actualScreen === "choix") {
    ecranDiv.style.backgroundPosition = "-"+(slidePos*90-28)+"px"
    document.getElementById("ecranBottom").style.backgroundPosition = "-"+(slidePos*146)+"px"
  }else {
    ecranDiv.style.backgroundPosition = "-"+(slidePos*146)+"px"
  }
}


//-----------------------------------------------------------------------------------------
//-- fonction qui cherche dans l'array ecran
//-----------------------------------------------------------------------------------------

function search(nomEcran){
    for (var i=0; i < ecran.length; i++) {
        if (ecran[i].nom === nomEcran) {
            return ecran[i];
        }
    }
    return -1
}


//-----------------------------------------------------------------------------------------
//-- fonction qui change l'IHM
//-----------------------------------------------------------------------------------------

var IHMType = 2
function changeIHM(){
  if (IHMType === 1) {
    document.getElementById("IHM").style.backgroundImage = "url('./ihm/ihm1.png')"
    IHMType = 2
  } else {
    document.getElementById("IHM").style.backgroundImage = "url('./ihm/ihm2.png')"
    IHMType = 1
  }
}

//-----------------------------------------------------------------------------------------
//-- fonction qui permet d'ouvrir et de fermer l'Optigrill
//-----------------------------------------------------------------------------------------


function action(typeAction){
  var videoEnCours = ecranOverlay.getElementsByTagName('video')[0]
  if (typeAction === "ouvrir") {
    document.getElementById("IHMecran").style.top = "-670px"
    if (actualScreen === "cuisson" || actualScreen === "prechauffeAuto") {
      clearTimeout(arrayOverlay[2])
      videoEnCours.pause()
    }
  }else {
    document.getElementById("IHMecran").style.top = "0px"
    if (actualScreen === "choix") {
      if (isViande) {
        ecranOverlay.innerHTML = "<video src=\"./ecrans/retirez2.mov\" loop></video>"
        ecranOverlay.getElementsByTagName('video')[0].play()
      }else {
        ecranOverlay.innerHTML = ""
      }
    }else if (actualScreen === "prechauffeAuto") {
      if (videoEnCours.currentTime < 30 && !isViande) {
        clearTimeout(arrayOverlay[2])
        ecranOverlay.getElementsByTagName('video')[0].style.display = "block"
        if (ecranOverlay.getElementsByTagName('video')[1]) {
          ecranOverlay.getElementsByTagName('video')[1].parentNode.removeChild(ecranOverlay.getElementsByTagName('video')[1]);
        }
        videoEnCours.play()
      }else if (videoEnCours.currentTime > 30 && isViande) {
        clearTimeout(arrayOverlay[2])
        displayScreen("cuisson")
      }else if (isViande) {
        videoEnCours.pause()
        ecranOverlay.innerHTML += "<video src=\"./ecrans/retirez1.mov\"></video>"
        arrayOverlay[2] = setTimeout(function(){displayScreen("manuChauffe")},12000)
        ecranOverlay.getElementsByTagName('video')[1].play()
        ecranOverlay.getElementsByTagName('video')[0].style.display = "none"
      }
    }else if (actualScreen === "cuisson") {
      if (!isViande) {
        displayScreen("bonappetit")
      }else {
        videoEnCours.play()
      }
    }
  }
}



//-----------------------------------------------------------------------------------------
//-- fonction qui change les modes (décongel et marquage)
//-----------------------------------------------------------------------------------------

function changeMode(type){
  if (type === "marquage") {
    reglages[1] = !reglages[1]
    if (reglages[1]) {
      displayIHM("change",2,2)
      ecranOverlay.style.backgroundImage = "url('./ecrans/marquage.png')"
      clearTimeout(arrayOverlay[0])
      clearTimeout(arrayOverlay[1])
      arrayOverlay[0] = setTimeout(function(){ecranOverlay.style.backgroundImage= ""},2000)
      topRight.style.opacity = 1;
    }else {
      displayIHM("change",2,1)
      clearTimeout(arrayOverlay[0])
      clearTimeout(arrayOverlay[1])
      ecranOverlay.style.backgroundImage = "url('./ecrans/marquage2.png')"
      arrayOverlay[0] = setTimeout(function(){ecranOverlay.style.backgroundImage= ""},2000)
      topRight.style.opacity = 0;
    }

  }else {
    reglages[0] = !reglages[0]
    if (reglages[0]) {
      displayIHM("change",1,2)
      ecranOverlay.style.backgroundImage = "url('./ecrans/decongel.png')"
      clearTimeout(arrayOverlay[0])
      clearTimeout(arrayOverlay[1])
      arrayOverlay[1] = setTimeout(function(){ecranOverlay.style.backgroundImage= ""},2000)
      topLeft.style.opacity = 1;
    }else {
      displayIHM("change",1,1)
      ecranOverlay.style.backgroundImage = "url('./ecrans/decongel2.png')"
      clearTimeout(arrayOverlay[0])
      clearTimeout(arrayOverlay[1])
      arrayOverlay[1] = setTimeout(function(){ecranOverlay.style.backgroundImage= ""},2000)
      topLeft.style.opacity = 0;
    }
  }
}

//-----------------------------------------------------------------------------------------
//-- fonction qui place ou retire la viande des plaques
//-----------------------------------------------------------------------------------------

function toggleViande(value){
  var videoEnCours = ecranOverlay.getElementsByTagName('video')[0]
  if (value === true || value === false) {
    if (value) {
      viandeSound.play();
      viande.className = "pos2"
      btnViande.className = "pos2"
    }else {
      viandeSound.pause();
      ecranOverlay.style.backgroundImage = ""
      viande.className = "pos1"
      btnViande.className = "pos1"
    }
    isViande = value
    return
  }
  if (isViande) {
    viandeSound.pause();
    viande.className = "pos1"
    btnViande.className = "pos1"
  }else {
    if (["cuisson","manuTemps","manuMinuteur"].includes(actualScreen) || (actualScreen === "manuChauffe" && videoEnCours.currentTime > 29) || (actualScreen === "prechauffeAuto" && videoEnCours.currentTime > 31)) {
      viandeSound.play();
    }
    viande.className = "pos2"
    btnViande.className = "pos2"
  }
  isViande = !isViande
}

//-----------------------------------------------------------------------------------------
//-- fonction qui joue les sons de l'interface
//-----------------------------------------------------------------------------------------

function playSound(){
  var bipBtn = new Audio('./bip-optigrill.mp3');
  bipBtn.volume = 0.2
  bipBtn.play();
}

//-----------------------------------------------------------------------------------------
//-- fonction qui affiche le menu latéral
//-----------------------------------------------------------------------------------------

function toggleMenu(){
  if (menu.style.marginLeft === "400px") {
    menu.style.marginLeft = "0px";
  }else {
    menu.style.marginLeft = "400px";
  }
}

//-----------------------------------------------------------------------------------------
//-- fonction qui affiche le menu de droite
//-----------------------------------------------------------------------------------------

function toggleMenuBoutons(){
  if (items[0].style.marginLeft === "-70px") {
    for (var i = 0; i < items.length; i++) {
      items[i].style.marginLeft = "20px"
    }
  }else {
    for (var i = 0; i < items.length; i++) {
      items[i].style.marginLeft = "-70px"
    }
  }
}

//-----------------------------------------------------------------------------------------
//-- fonction qui initialise les boutons de l'IHM
//-----------------------------------------------------------------------------------------

function initiateBtnIHM(){
  var btnContainer = document.getElementById("btnContainer")
  btnContainer.innerHTML = ""
  for (var i = 0; i < nomBouton.length; i++) {
    if (i === 2){
      btnContainer.innerHTML += "<div id=\""+nomBouton[i]+"\" class=\"btnIHM\" style=\"background-image:url(./ihm/boutonsIHM-03-V"+boutonMarquageNum+".png)\" onmousedown=\"clickBtn('"+nomBouton[i]+"')\"></div>"
    } else {
      btnContainer.innerHTML += "<div id=\""+nomBouton[i]+"\" class=\"btnIHM\" style=\"background-image:url(./ihm/boutonsIHM-0"+(i+1)+".png)\" onmousedown=\"clickBtn('"+nomBouton[i]+"')\"></div>"
    }
  }
}


initiateBtnIHM()
displayScreen(actualScreen)


//-----------------------------------------------------------------------------------------
//-- fonction qui change l'élément sélectionné dans le menu de droite
//-----------------------------------------------------------------------------------------

function changeTo(e,num){
  manuFolder = num
  displayScreen(actualScreen)
  if (manuFolder === 1) {

  }
  for (var i = 0; i < items.length; i++) {
    items[i].className = "item"
  }
  e.className = "item select"
}


//-----------------------------------------------------------------------------------------
//-- Event listener qui gère l'appui long sur une des flèches (en JQuery)
//-----------------------------------------------------------------------------------------

$("#rightArrow").bind('mousedown', function(e){
  if (ecranOverlay.style.backgroundImage === "") {
    slide("rightArrow")
  }else {
    ecranOverlay.style.backgroundImage = ""
  }
  playSound()
})


$("#leftArrow").bind('mousedown', function(e){
  if (ecranOverlay.style.backgroundImage === "") {
    slide("leftArrow")
  }else {
    ecranOverlay.style.backgroundImage = ""
  }
  playSound()
})
