(function($) {
$(document).ready(function() {

  var scJoueurId = scInput_JoueurId;
  var lastData;

  var dejaJoue = false;

  function refreshScreen(data) {
    if(data['statut'] == 0) {
      window.location.href = 'index.php?j=' + scJoueurId;
    }


    for(var j in data['joueur']) {


      /*
       * AFFICHAGE DES TEMPLES
       */
      for(var t = 0 ; t < data['joueur'][j]['temple'].length ; t++) {
        if( ( !lastData || data['joueur'][j]['temple'][t] != lastData['joueur'][j]['temple'][t] ) && data['joueur'][j]['temple'][t] > 0 ) {
          // Supprime l'ancien Temple
          $('#AffTemple_User' + j + '_Temple' + (t + 1)).remove();
          // Affiche le Temple a la nouvelle position
          mInfo = data['joueur'][j]['temple'][t];
          $('#PlateauCase_User' + j + '_Temple' + mInfo).append('<img src="src/temple' + (t + 1) + '.png" id="AffTemple_User' + j + '_Temple' + (t + 1) + '" />');
        }
      }


      /*
       * AFFICHAGE DES TUILES
       */
      for(var t = 0 ; t < data['joueur'][j]['plateau'].length ; t++) {
        if( ( !lastData || data['joueur'][j]['plateau'][t] != lastData['joueur'][j]['plateau'][t] ) && data['joueur'][j]['plateau'][t] != "" ) {
          var caseInfo = decomposerTuile( data['joueur'][j]['plateau'][t] );
          $('#PlateauCase_User' + j + '_Case' + (t + 1)).html('<img src="src/tuile_' + caseInfo[0] + '.png" />');
          if(caseInfo[1] != "")
            $('#PlateauCase_User' + j + '_Case' + (t + 1)).append('<img src="src/tuile_' + caseInfo[1] + '.png" />');
        }
      }


      /*
       * AFFICHAGE DES MEEPLES
       */
      for(var m = 0 ; m < data['joueur'][j]['meeple'].length ; m++) {
        if( ( !lastData || data['joueur'][j]['meeple'][m] != lastData['joueur'][j]['meeple'][m] ) && data['joueur'][j]['meeple'][m] > 0 ) {
          // Supprime l'ancien Meeple
          $('#AffMeeple_User' + j + '_Meeple' + (m + 1)).remove();
          // Affiche le Meeple a la nouvelle position
          mInfo = data['joueur'][j]['meeple'][m];
          if(mInfo >= 200)
            $('#PlateauCase_User' + j + '_Temple' + (mInfo - 200)).append('<img src="src/meeple' + (m + 1) + '.png" id="AffMeeple_User' + j + '_Meeple' + (m + 1) + '" />');
          else if(mInfo >= 100)
            $('#PlateauCase_User' + j + '_Meeple' + (mInfo - 100)).append('<img src="src/meeple' + (m + 1) + '.png" id="AffMeeple_User' + j + '_Meeple' + (m + 1) + '" />');
          else
            $('#PlateauCase_User' + j + '_Case' + mInfo).append('<img src="src/meeple' + (m + 1) + '.png" id="AffMeeple_User' + j + '_Meeple' + (m + 1) + '" />');
        }
      }


      /*
       * AFFICHAGE DES INFOS
       */
      var total = 0;

      for(var i = 0 ; i < data['joueur'][j]['tresor'].length ; i++) {
        $('#Plateau_User' + j + '_Temple' + (i + 1) + 'Nbr').html( data['joueur'][j]['tresor'][i] );
        total += parseInt( data['joueur'][j]['tresor'][i] );
      }

      $('#Plateau_User' + j + '_OrNbr').html( data['joueur'][j]['or'] );
      total += parseInt( data['joueur'][j]['or'] * 2 );

      $('#Plateau_User' + j + '_DiamantNbr').html( data['joueur'][j]['diamant'] );
      total += parseInt( data['joueur'][j]['diamant'] );

      $('#Plateau_User' + j + '_TotalNbr').html( total );

      if(j != scJoueurId) {
        if(data['joueur'][j]['dernier_coup'].length == 0) {
          $('#Plateau_User' + j + '_Joue').empty();
        }
        else {
          if( !lastData || lastData['joueur'][j]['dernier_coup'].length == 0 )
            $('#Plateau_User' + j + '_Joue').html('<img src="src/ok.png" />');
        }
      }


    } // FIN BOUCLE : REFRESH DES ECRANS DE CHAQUE JOUEUR


    // ETAPES INITIALES DE POSITIONNEMENT DES MEEPLES & TEMPLES
    if(data['statut'] > 0 && data['statut'] < 9 && (!lastData || data['statut'] != lastData['statut']) ) {
      if(data['statut'] % 2 == 0) {
        $('#zoneInfosTuile_tuile').html('<img src="src/temple' + (data['statut'] / 2) + '.png" />');
        for(var i = 1 ; i <= 11 ; i++) {
          $('#PlateauCase_User' + scJoueurId + '_Temple' + i).addClass('clickable');
          $('#PlateauCase_User' + scJoueurId + '_Meeple' + i).removeClass('clickable');
        }
      }
      else {
        $('#zoneInfosTuile_tuile').html('<img src="src/meeple' + (Math.floor(data['statut'] / 2) + 1) + '.png" />');
        for(var i = 1 ; i <= 11 ; i++) {
          $('#PlateauCase_User' + scJoueurId + '_Meeple' + i).addClass('clickable');
          $('#PlateauCase_User' + scJoueurId + '_Temple' + i).removeClass('clickable');
        }
      }
    }
    // PENDANT LA PARTIE
    else if(data['statut'] == 9) {
      for(var i = 1 ; i <= 11 ; i++) {
        $('#PlateauCase_User' + scJoueurId + '_Temple' + i).removeClass('clickable');
        $('#PlateauCase_User' + scJoueurId + '_Meeple' + i).removeClass('clickable');
      }
      for(var i = 1 ; i <= 30 ; i++)
        $('#PlateauCase_User' + scJoueurId + '_Case' + i).addClass('clickable');
      for(var i = 1 ; i <= 4 ; i++) {
        $('#AffMeeple_User' + scJoueurId + '_Meeple' + i).addClass('clickable');
        $('#AffTemple_User' + scJoueurId + '_Temple' + i).addClass('clickable');
      }



      // AFFICHAGE DES INFOS
      if(!dejaJoue && data['joueur'][scJoueurId]['dernier_coup'].length > 0) {
        $('#zoneInfosTuile_tuile').html('<img src="src/ok.png" />');
        dejaJoue = true;
      }

      if( ( !lastData || lastData['statut'] < 9 || dejaJoue ) && data['joueur'][scJoueurId]['dernier_coup'].length == 0 ) {
        dejaJoue = false;
        var pioche = decomposerTuile( data['pioche'] );
        $('#zoneInfosTuile_tuile').html('<img src="src/tuile_' + pioche[0] + '.png" />');
        if(pioche[1] != "")
          $('#zoneInfosTuile_tuile').append('<img src="src/tuile_' + pioche[1] + '.png" />');
      }

      $('#zoneInfosReste').html( 'Reste : ' + data['nbpioche'] );
      for(var t = 0 ; t < 4 ; t++)
        $('#zoneInfosTemple' + (t + 1)).html( data['tresor'][t] );


      // AFFICHAGE DU NBR DE TUILES RESTANTES
      if( !lastData || lastData['nbpioche'] != data['nbpioche'] || lastData['statut'] != data['statut'] ) {
        var listeTuilesRestantes = ['1', '1d', '1o', '2', '2d', '2o', '3', '4', '4d', '5', '6', '7', '8d', '9', '9d', '10', '10d', '11', '11d'];
        for(var t = 0 ; t < listeTuilesRestantes.length ; t++)
          $( '#TuileRestante_' + listeTuilesRestantes[t] ).html( ( data['tuilesrestantes'][ listeTuilesRestantes[t] ] ? data['tuilesrestantes'][ listeTuilesRestantes[t] ] : '0' ) + 'x' );
      }

      // SUPPRESION DES FANTOMES
      if( !lastData || lastData['nbpioche'] != data['nbpioche'] ) {
        $('.meepleFantome').remove();
      }
    }
    // FIN DE PARTIE : statut > 10
    else if(data['statut'] >= 10) {

      $('#finPartie').fadeIn();

    }

    lastData = data;
  }

  function refresh() {
    // S'il y a deja une ecriture en cours, attendre le prochain creneau pour le refresh d'affichage
    if(requestWriteInProgress) {
      refreshTimer = setTimeout(refresh, 1000);
      return;
    }

    requestReadInProgress = true;

    $.get('jeu.php?j=' + scJoueurId)
      .done(function(data, text, jqxhr) {
        try {
          var JsonResponse = JSON.parse(jqxhr.responseText);
          refreshScreen(  JsonResponse );
        }
        catch(error) {
//        alert(jqxhr.responseText);
          console.log("TRY JSON PARSE : --- " + jqxhr.responseText + " --- " + error);
        }
      })
      .fail(function(jqxhr){
          console.log("BACKEND REFRESH : " + jqxhr.responseText);
//        alert(jqxhr.responseText);
      })
      .always(function(){
        refreshTimer = setTimeout(refresh, 1000);
        requestReadInProgress = false;
      });
  }

  refresh();
  var refreshTimer;

  var requestWriteInProgress = false;
  var requestReadInProgress = false;




  /*
   * CLICKS
   */

  var meepleSelected = 0;

  $('.zone-moi-plateau table tr td').on('click', function(e) {
    if(dejaJoue) return;
    if(lastData['statut'] > 9) return;

    var ReadID = $(this).attr('id');
    if(!ReadID) return;
    ReadID = ReadID.substring('PlateauCase_User'.length);
    var UserID = ReadID.substring(0, ReadID.indexOf('_'));
    var InfoType = ReadID.substring(ReadID.indexOf('_') + 1);
    var InfoID = 0;
    if(InfoType.substring(0, 'Case'.length) == 'Case') { InfoID = InfoType.substring('Case'.length); InfoType = 'c'; }
    else if(InfoType.substring(0, 'Temple'.length) == 'Temple') { InfoID = InfoType.substring('Temple'.length); InfoType = 't'; }
    else if(InfoType.substring(0, 'Meeple'.length) == 'Meeple') { InfoID = InfoType.substring('Meeple'.length); InfoType = 'm'; }

    /*
     * DEBUT DE PARTIE : CHOIX DES POSITIONS DES TEMPLES ET MEEPLES
     */
    if(lastData['statut'] > 0 && lastData['statut'] < 9) {
      if(lastData['statut'] % 2 == 0) {
        if( InfoType == 't' && !caseHasTemple(InfoID) ) {
          requestWriteInProgress = true;

          $.get('jeu.php?j=' + scJoueurId + '&temple=' + InfoID)
            .done(function(data, text, jqxhr) {

            })
            .fail(function(jqxhr){
      //        alert(jqxhr.responseText);
              console.log("BACKEND TEMPLE : " + jqxhr.responseText);
              window.location.href = 'index.php?j=' + scJoueurId;
            })
            .always(function(){
              requestWriteInProgress = false;
            });
        }
      }
      else {
        if( InfoType == 'm' && !caseHasMeeple('m', InfoID) ) {
          requestWriteInProgress = true;

          $.get('jeu.php?j=' + scJoueurId + '&meeple=' + InfoID)
            .done(function(data, text, jqxhr) {

            })
            .fail(function(jqxhr){
              console.log("BACKEND MEEPLE : " + jqxhr.responseText);
      //        alert(jqxhr.responseText);
              window.location.href = 'index.php?j=' + scJoueurId;
            })
            .always(function(){
              requestWriteInProgress = false;
            });
        }
      }
    }
    /*
     * PENDANT LA PARTIE : JOUER UN COUP
     */
    else if(lastData['statut'] == 9) {

      meepleSelectId = caseHasMeeple(InfoType, InfoID);

      // => CASE VIDE : DEPOSER LA TUILER
      if(InfoType == 'c' && lastData['joueur'][scJoueurId]['plateau'][InfoID - 1].length == 0 && !meepleSelectId) {
        if(meepleSelected > 0) $('#SelectionMeeple' + meepleSelected).remove();
        meepleSelected = 0;

        requestWriteInProgress = true;

        var piocheAff = decomposerTuile( lastData['pioche'] );
        $('#zoneInfosTuile_tuile').html('<img src="src/ok.png" />');
        $('#PlateauCase_User' + scJoueurId + '_Case' + InfoID).append('<img src="src/tuile_' + piocheAff[0] + '.png" style="opacity: 0.5" />');
        if(piocheAff[1] != "")
          $('#PlateauCase_User' + scJoueurId + '_Case' + InfoID).append('<img src="src/tuile_' + piocheAff[1] + '.png" style="opacity: 0.5" />');
        dejaJoue = true;

        $.get('jeu.php?j=' + scJoueurId + '&dc=c' + InfoID)
          .done(function(data, text, jqxhr) {

          })
          .fail(function(jqxhr){
            console.log("BACKEND DC=C : " + jqxhr.responseText);
    //        alert(jqxhr.responseText);
            window.location.href = 'index.php?j=' + scJoueurId;
          })
          .always(function(){
            requestWriteInProgress = false;
          });
      }

      // => CASE AVEC MEEPLE : LE SELECTIONNER
      else if(meepleSelectId) {
        if(meepleSelected > 0) $('#SelectionMeeple' + meepleSelected).remove();
        $('#AffMeeple_User' + scJoueurId + '_Meeple' + meepleSelectId).parent().append('<img src="src/selection.png" id="SelectionMeeple' + meepleSelectId + '" />');
        meepleSelected = meepleSelectId;
      }

      // => MEEPLE SELECTED vers CASE VIDE OU TEMPLE : BOUGER LE MEEPLE
      else if(meepleSelected) {
        if(InfoType == 'c' && lastData['joueur'][scJoueurId]['plateau'][InfoID - 1].length > 0) {

          if(meepleSelected > 0) $('#SelectionMeeple' + meepleSelected).remove();
          tempMeepleSelected = meepleSelected;
          meepleSelected = 0;

          requestWriteInProgress = true;

          $('#zoneInfosTuile_tuile').html('<img src="src/ok.png" />');
          $('#PlateauCase_User' + scJoueurId + '_Case' + InfoID).append('<img src="src/meeple' + tempMeepleSelected + '_vide.png" class="meepleFantome" />');
          dejaJoue = true;

          $.get('jeu.php?j=' + scJoueurId + '&dc=m' + tempMeepleSelected + 'c' + InfoID)
            .done(function(data, text, jqxhr) {

            })
            .fail(function(jqxhr){
              console.log("BACKEND DC=C : " + jqxhr.responseText);
      //        alert(jqxhr.responseText);
              window.location.href = 'index.php?j=' + scJoueurId;
            })
            .always(function(){
              requestWriteInProgress = false;
            });

        }
        else if(InfoType == 't') {
          templeSelectId = caseHasTemple(InfoID);
          if(templeSelectId == meepleSelected) {

            if(meepleSelected > 0) $('#SelectionMeeple' + meepleSelected).remove();
            tempMeepleSelected = meepleSelected;
            meepleSelected = 0;

            requestWriteInProgress = true;

            $('#zoneInfosTuile_tuile').html('<img src="src/ok.png" />');
            $('#PlateauCase_User' + scJoueurId + '_Temple' + InfoID).append('<img src="src/meeple' + tempMeepleSelected + '_vide.png" class="meepleFantome" />');
            dejaJoue = true;

            $.get('jeu.php?j=' + scJoueurId + '&dc=m' + tempMeepleSelected + 't' + InfoID)
              .done(function(data, text, jqxhr) {

              })
              .fail(function(jqxhr){
                console.log("BACKEND DC=C : " + jqxhr.responseText);
        //        alert(jqxhr.responseText);
                window.location.href = 'index.php?j=' + scJoueurId;
              })
              .always(function(){
                requestWriteInProgress = false;
              });


          }
        }
      }

    }
  });

  function caseHasMeeple(type, id) {
    if(type == 't') return false;

    var position = parseInt(id);
    if(type == 'm') position += 100;

    for(var i = 0 ; i < lastData['joueur'][scJoueurId]['meeple'].length ; i++)
      if( lastData['joueur'][scJoueurId]['meeple'][i] == position ) return (i + 1);

    return false;
  }

  function caseHasTemple(id) {
    for(var i = 0 ; i < lastData['joueur'][scJoueurId]['temple'].length ; i++)
      if( lastData['joueur'][scJoueurId]['temple'][i] == id ) return (i + 1);

    return false;
  }




  var actionJeter = false;

  // Click sur la pioche : Action jeter
  $('#zoneInfosTuile').on('click', function(e) {
    if(dejaJoue) return;

    if(actionJeter) {
      actionJeter = false;
      $('#zoneInfosTuile_jeter').hide();
      if(meepleSelected > 0) $('#SelectionMeeple' + meepleSelected).remove();
      meepleSelected = 0;

      requestWriteInProgress = true;

      $('#zoneInfosTuile_tuile').html('<img src="src/ok.png" />');
      dejaJoue = true;

      $.get('jeu.php?j=' + scJoueurId + '&dc=p')
        .done(function(data, text, jqxhr) {

        })
        .fail(function(jqxhr){
          console.log("BACKEND DC=P : " + jqxhr.responseText);
  //        alert(jqxhr.responseText);
          window.location.href = 'index.php?j=' + scJoueurId;
        })
        .always(function(){
          requestWriteInProgress = false;
        });
    }
    else {
      $('#zoneInfosTuile_jeter').fadeIn();
      actionJeter = true;
    }
  });

  $('#zoneInfosTuile').on('mouseleave', function(e) {
      $('#zoneInfosTuile_jeter').fadeOut();
      actionJeter = false;
  });





  /*
   * BOUTON FIN DE PARTIE / NOUVELLE PARTIE
   */
  function nouvellePartie() {
    $.get('jeu.php?j=' + scJoueurId + '&new=1')
      .done(function(data, text, jqxhr) {

      })
      .fail(function(jqxhr){
        console.log("BACKEND NEW : " + jqxhr.responseText);
//        alert(jqxhr.responseText);
        window.location.href = 'index.php?j=' + scJoueurId;
      })
      .always(function(){

      });

  }

  $('#finPartieBtn').on('click', function(e) {
    nouvellePartie();
  });

  $('#basBoutonTerminer').on('click', function(e) {
    nouvellePartie();
  });




  /*
   * FONCTIONS ANNEXES
   */
  function decomposerTuile(id) {
    var newId = id;
    var pepite = newId[newId.length - 1];
    if(pepite == 'o' ||pepite == 'd')
      newId = newId.substring(0, newId.length - 1);
    else
      pepite = '';

    return [newId, pepite];
  }





});
})(jQuery);