/* These functions were mostly not built by me (I found this somewhere on the net),
   but modified to some extent. I can't really forbid you to reuse this script,
   so take it if you like it. But please use your own pictures and styles!
*/

  /* global variables */
  var memoryClickActive = new Array(36);
  var imgIsUsed = new Array(56);
  var memory = new Array(36);
  var imgs = new Array(18);
  var imgLoaded = 0;
  var imgNames = new Array(36);
  var memEnabled = 0;
  var first = -1;
  var moves = 0;
  var pairsFound = 0;
  var firstNumber = -1;
  var startTime = 0;
  var durationM = 0;
  var durationS = 0;
  
  /**
   * Define it empty in case it has not been defined outside the JavaScriopt file.
   */
  var basePath = (typeof(basePath) == "undefined") ? '' : basePath;
  
  
  /* set error handling function */
  window.onerror = handleError;


  /* error handling function, gives a message */
  function handleError(Nachricht) {
    alert("Es ist ein Fehler aufgetreten! Dieses Spiel setzt einen halbwegs aktuellen Browser und JavaScript voraus!");
    alert(Nachricht);
  }


  /* init variables */
  function doInit() {
    memEnabled = 0;
    for (i=0; i<36; i++) {
      memory[i] = -1;
      memoryClickActive[i] = 1;
    }
    for (i=0; i<18; i++) {
      /* save the picture names */
      imgNames[i] = "Pic" + (i);
      imgNames[i+18] = "Pic" + (i+18);
    }
    /* prepare position of the pictures */
    for (i=0; i<18; i++) {
      for (j=0; j<2; j++) {
        temp = 1;
        while (temp) {
          memPos = Math.floor(Math.random()*36);
          if ((memPos < 36) && (memory[memPos] == -1)) temp = 0;
        }
        memory[memPos] = i;
      }
    }
    /* detect and change same pictures lying next to each other */
    var changePos = 0;
    var tmp = 0;
    for (i=0; i<36; i++) {
      if ((i+1)%6 != 0) {
        if (memory[i] == memory[i+1]) {
          changePos = 35-i;
          tmp = memory[i];
          memory[i] = memory[changePos];
          memory[changePos] = tmp;
        }
      }
    }
  }


  /* starts the game */
  function startGameManually() {
    memEnabled = 1;
    $('#memoryLayerLoading').hide();
    $('#memoryImagesParent').show();
  }
    


  /* compares this image with the potentially previously clicked image */
  function compareImage(fieldPos) {
    if (!memoryClickActive[fieldPos] || !memEnabled) {
      /* do nothing if the clicked image was already clicked or if the game is not enabled */
      return;
    } else {
      /* save start time if first click */
      if (startTime == 0) {
        startTime = new Date().getTime();
      }
      /* disable this image for a second click */
      memoryClickActive[fieldPos] = 0;
      if (first == -1) {
        /* this is the first clicked image for this move */
        first = memory[fieldPos];
        firstNumber = fieldPos;
        document.getElementById("progress1").style.backgroundColor = "#FF9F00";
        displayImage(fieldPos);
      } else {
        /* this is the second clicked image for this move */
        memEnabled = 0;
        document.getElementById("progress2").style.backgroundColor = "#FF9F00";
        secondNumber = fieldPos;
        displayImage(fieldPos);
        moves++;
        if (first == memory[fieldPos]) {
          /* a pair is found */
          first = -1;
          pairsFound++;
          document.getElementById("progress1").style.backgroundColor = "#008030";
          document.getElementById("progress2").style.backgroundColor = "#008030";
          document.getElementById("progress3").firstChild.nodeValue = pairsFound + " / 18";
          setTimeout("checkFinished()", 500);
        } else {
          first = -1;
          setTimeout("nextMove(firstNumber, secondNumber)", 1000);
        }
      }
    }
  }


  /* loads a picture ('turns it around') */
  function displayImage(fieldPos) {
    document.getElementById(imgNames[fieldPos]).src = imgs[memory[fieldPos]].src;
  }


  /* sets the two clicked images back */
  function nextMove(fieldPos1, fieldPos2) {
    // set the playing field back
    memoryClickActive[fieldPos1] = 1;
    memoryClickActive[fieldPos2] = 1;
    document.getElementById(imgNames[fieldPos1]).src = basePath + "/pictures/fandom/funstuff/memor_0.jpg";
    document.getElementById(imgNames[fieldPos2]).src = basePath + "/pictures/fandom/funstuff/memor_0.jpg";
    memEnabled = 1;
    // update the stats panel
    document.getElementById("progress1").style.backgroundColor = "#FDFDF7";
    document.getElementById("progress2").style.backgroundColor = "#FDFDF7";
    updateDurationAndMoves();
  }


  /* checks after a pair was found if the game is over */
  function checkFinished() {
    for (i=0; i<36; i++) {
      if (memoryClickActive[i]) {
        memEnabled = 1;
        document.getElementById("progress1").style.backgroundColor = "#FDFDF7";
        document.getElementById("progress2").style.backgroundColor = "#FDFDF7";
        return;
      }
    }
    /* No active image found? So we're done! */
    updateDurationAndMoves();
    finished();
  }


  /* updates the duration variables and writes duration and moves to the stats panel */
  function updateDurationAndMoves() {
    document.getElementById("resultMoves").firstChild.nodeValue = moves;
    temp = new Date().getTime() - startTime;
    temp = Math.floor(temp / 1000); // change to seconds
    durationS = temp % 60; // get only the seconds
    durationM = Math.floor(temp / 60); // get only the minutes
    document.getElementById("resultTime").firstChild.nodeValue = durationM + " min " + durationS + " sek";
  }


  /* changes the content of the layer so that we see the result */
  function finished() {
    $('#memoryLayerFinished').show();
    checkHighscore();
  }


  /* checks with an AJAX call if the user is good enough to be entered into the highscore */
  function checkHighscore() {
    $.ajax({
      type: "POST",
      url: "highscore.php",
      data: {check: 'true',
             moves: String(moves),
             minutes: String(durationM),
             seconds: String(durationS)},
      async: false,
      timeout: 5000,
      dataType: 'text',
      success: function(response) {
        if (response == 'true') {
          $('#memoryLayerResultPositive').show();
        } else {
          $('#memoryLayerResultNegative').show();
        }
      },
      error: function(request, textStatus, errorThrown) {
        // don't allow the highscore, something went wrong
        $('#memoryLayerResultError').show();
      }
    });
  }


  /* retrieves the highscore from the server and shows it */
  function showHighscore() {
    // remove the memory images and show the highscore layer
    $('#memoryLayerLoading').hide();
    $('#memoryImagesParent').hide();
    $('#memoryHighscoreParent').show();
    // remove old highscore data
    $('#memoryHighscoreTable tbody tr').remove();
    // get the highscore data from the server and show them
    $.get('highscore.php', {get: 'true'},
      function(response) {
        $('#memoryHighscoreTable tbody').append(response);
      }, 'html'
    );
  }


  /* submits the form data to be written to the highscore on the server */
  function submitHighscore() {
    // check that a name was entered
    var playerName = $('#memoryPlayerName').val();
    if ((playerName == null) || (playerName == '')) {
      alert("Bitte gib einen Namen ein!");
      $('#memoryPlayerName')[0].focus();
      return;
    }
    // do the AJAX submit
    $.ajax({
      type: "POST",
      url: "highscore.php",
      data: {write: 'true',
             playerName: String(playerName),
             moves: String(moves),
             minutes: String(durationM),
             seconds: String(durationS)},
      async: false,
      timeout: 5000,
      dataType: 'text',
      success: function(response) {
        if (response == 'true') {
          $('#memoryLayerResultPositive').show();
        } else {
          $('#memoryLayerResultNegative').show();
        }
      },
      error: function(request, textStatus, errorThrown) {
        // don't allow the highscore, something went wrong
        $('#memoryLayerResultError').show();
      }
    });
    // show the updated highscore
    showHighscore();
  }


  /* call the init function when the page has loaded */
  jQuery(function($) {  
    // init variables
    doInit();
    // wait until all images for the memory have been loaded
    $("img.memoryPictureInvisible").load(function() {
      imgLoaded++;
      if (imgLoaded > 17) {
        startGameManually();
      }
    });
  });
