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

  var scJoueurId = scInput_JoueurId;
  var lastData;


  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 = data['joueur'][j]['plateau'][t];
          var pepite = caseInfo[caseInfo.length - 1];
          if(pepite == 'o' ||pepite == 'd')
            caseInfo = caseInfo.substring(0, caseInfo.length - 1);
          else
            pepite = '';
          $('#PlateauCase_User' + j + '_Case' + (t + 1)).html('<img src="src/tuile_' + caseInfo + '.png" />');
          if(pepite != "")
            $('#PlateauCase_User' + j + '_Case' + (t + 1)).append('<img src="src/tuile_' + pepite + '.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( !lastData || data['joueur'][j]['dernier_coup'] != lastData['joueur'][j]['dernier_coup'] ) {
          if(data['joueur'][j]['dernier_coup'].length > 0)
            $('#Plateau_User' + j + '_Joue').html('<img src="src/ok.png" />');
          else
            $('#Plateau_User' + j + '_Joue').empty;
        }
      }


    } // 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) {
      
    }
    // FIN DE PARTIE : statut > 10
    else {

    }




    if( !lastData || data['pioche'] != lastData['pioche'] ) {
      var pioche = data['pioche'];
      var pepite = pioche[pioche.length - 1];
      if(pepite == 'o' ||pepite == 'd')
        pioche = pioche.substring(0, pioche.length - 1);
      else
        pepite = '';
      $('#zoneInfosTuile_tuile').html('<img src="src/tuile_' + pioche + '.png" />');
      if(pepite != "")
        $('#zoneInfosTuile_tuile').append('<img src="src/tuile_' + pepite + '.png" />');
    }

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





    lastData = data;
  }

  function refresh() {
    $.get('backend/jeu.php?j=' + scJoueurId)
      .done(function(data, text, jqxhr) {
        refreshScreen(  JSON.parse(jqxhr.responseText) );
      })
      .fail(function(jqxhr){
//        alert(jqxhr.responseText);
      })
      .always(function(){
        refreshTimer = setTimeout(refresh, 1000);
      });
  }

  refresh();
  var refreshTimer;







  /*
   * CLICKS
   */

  $('.zone-moi-plateau table tr td').on('click', function(e) {
    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') {
          $.get('backend/jeu.php?j=' + scJoueurId + '&temple=' + InfoID)
            .done(function(data, text, jqxhr) {

            })
            .fail(function(jqxhr){
      //        alert(jqxhr.responseText);
            })
            .always(function(){

            });
        }
      }
      else {
        if(InfoType == 'm') {
          $.get('backend/jeu.php?j=' + scJoueurId + '&meeple=' + InfoID)
            .done(function(data, text, jqxhr) {

            })
            .fail(function(jqxhr){
      //        alert(jqxhr.responseText);
            })
            .always(function(){

            });
        }
      }
    }
    /*
     * PENDANT LA PARTIE : JOUER UN COUP
     */
    else if(lastData['statut'] == 9) {
    }


  });

});
})(jQuery);