/*
 * concentration - jQuery plugin for concentration solitaire game
 *
 * Copyright (c) 2009 Marion Sturtevant
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0
 *
 */
(function ($) {
// private functions

/* Fisher-Yates in place shuffle */
function shuffle(myArray) {
  var i = myArray.length;
  var j, temp;
  if (i === 0) { return false; }
  while (--i) {
     j = Math.floor(Math.random() * (i + 1));
     temp = myArray[i];
     myArray[i] = myArray[j];
     myArray[j] = temp;
   }
}

/*
Grab the next event from the flip queue. if it is a flip,
flip the card. If it is a pause, just pause. Then call ourselves
recursively to do it again. Terminates when flip queue is empty.
*/
function doFlip($game) {
  var gameData = $game.data('data');
  var flip
  var $card, $up, $down;
  if (gameData.flips.length === 0) {
    gameData.isFlipHandlerRunning = false;
    return;
  }
  flip = gameData.flips.shift();
  switch (flip.action) {
  case 'flip':
    $card = flip.card;
    $up = $card.find('.jqConcentrationUp');
    $down = $card.find('img').not('.jqConcentrationUp');
    $up.addClass('jqConcentrationUp-last');
    $down.css({opacity: 0.0}).
      addClass('jqConcentrationUp').
      animate({opacity: 1.0}, flip.time, function () {
        $up.removeClass('jqConcentrationUp jqConcentrationUp-last');
        doFlip($game);
      });
    break;
  case 'pause':
    window.setTimeout(function () { doFlip($game); }, flip.time);
    break;
  default: doFlip($game); // better luck w/ next action
  }
}

/*
Set isFlipHandlerRunning, and start flipping. Does nothing
if isFlipHandlerRunning was already true.
*/
function flipHandler($game){
  var gameData = $game.data('data');
  if (gameData.isFlipHandlerRunning === true) { return; }
  gameData.isFlipHandlerRunning = true;
  doFlip($game);
}

var paerchen = 0; //zaehlt, wie viele paerchen bereits gefunden wurden
var level = 1; //zaehlt, wie viele kartensets bereits geloest wurden

/* boolean: do these 2 cards match? */
function isMatching($c1, $c2, $game) {
	  var gameData = $game.data('data');

	var names= new Array();
	
	
	names[11] = "Hans Rosenthal - Mesut &Ouml;zil";
	names[12] = "Der Blendi-Biber - Ren&eacute; Renno";
	names[13] = "Javier Bardem - Marcel Raducanu";
	names[14] = "Morten Harket - Jens Lehmann";
	names[15] = "Rolf Zuckowski - Lucien Favre";
	names[16] = "Apu - Robin Dutt";
	names[17] = "Berti Vogts - Poldi";
	names[18] = "Fantomas - Jürgen Seeberger";
	
	names[21] = "Casten Jancker - Das Ding aus dem Sumpf";
	names[22] = "Hannes Linssen - Krusty the Clown";
	names[23] = "Zinedine Zidane - Gabriele Krone-Schmalz";
	names[24] = "Oliver Neuville - Lassie";
	names[25] = "Reiner Calmund - Jabba, the Hutt";
	names[26] = "German Burgos - Ozzy Osbourne";
	names[27] = "Martin Kind - Montgomery Burns";
	names[28] = "Paul Freier - Alfred E. Neumann";

	names[64] = "Volker Finke - Der Schrei";
	names[73] = "Rudi Dutschke - Sebastian Deisler";	
	names[75] = "Thomas Schaaf – Frietjof Nansen (Seefahrer)";
	names[79] = "Monster »Pans Labyrinth« – Oliver Kahn";
    names[80] = "Odo – Miroslav Klose";
	names[81] = "Fatih Terim - Meister Yoda";
	names[82] = "Gaius Faulus – Jos Luhukay";

	names[83] = "Playmobil-Männchen – Joachim Löw";
	names[84] = "Owen Wilson – Rene Adler";
	names[85] = "Das Ding – Martin Jol";
	names[87] = "Rolf Töpperwien - Jack Nicholson";
	names[88] = "Francesco Soma – Dietmar Beiersdorfer";
	names[89] = "Maniche - Alvin Chipmunk";
	names[90] = "SM-Zwerg - Hugo Almeida";
	names[91] = "Keith Richards - Klaus Augenthaler";

	names[92] = "Professor Frink - Reinhold Beckmann";
	names[93] = "Jérôme Boateng - Steve Urkel";
	names[94] = "Célia Okoyno da Mbabi - Michael Ballack";	
	names[95] = "Christoph Daum - Carl Benz";
	names[96] = "Maria Furtwängler - Diego Forlán";
    names[97] = "Alte Frau - Friedhelm Funkel";
	names[98] = "Mario Gómez - Rick Astley";
	names[99] = "Jos Luhukay - Gaius Faulus";

	names[30] = "Waldemar Hartmann - Bertil Wewer";
	names[31] = "Moe Szyslak - Bernd Hoffmann";
	names[32] = "Oliver Kahn - Andrea Sch&ouml;pp";
	names[33] = "Jürgen Klinsmann - Phrasenschwein";
	names[35] = "Kevin McKenna - Der Schrei";
	names[36] = "Thomas M&uuml;ller - Gei&szlig;enpeter";
	names[37] = "Severus Snape - Hans-Wilhelm Müller-Wohlfahrt";

	names[38] = "Mario Gómez - Philippinenadler";
	names[39] = "Bibiana Steinhaus - Donald Duck";
	names[40] = "Louis van Gaal - Benni Beimer";
	names[41] = "Heiko Westermann - Alvin Chipmunk";
	names[34] = "Zé Roberto - Mettigel";	
	
	
	//document.getElementById("tries_display").innerHTML = tries;
	if ($c1.find('img:first').attr('src').substr(0,21)  ===
    $c2.find('img:first').attr('src').substr(0,21))	{
    	var imageId = $c1.find('img:first').attr('src').substr(0,21).split('/');
     	tb_show(names[imageId[3]],"/img/concentration/bdgg/" + imageId[3] + ".jpg");
		ReloadPixelImages('geburt', 'comment');
     	paerchen++;
     	if (paerchen == 8) {
     		showSuccess($game);
     	}
    	return true;
    } else {
		ReloadPixelImages('geburt', 'comment');
       	return false;
    }
	 
}

/*
Handle click events from the clicks queue.
First, ignore illegal clicks (click on matched card, click on
turned card). Then, flip the card. Then, if this is 2nd card,
and the two match, mark them matched. Otherwise, flip them both
back. If this is first card, just remember it is the flippedCard.
Cards are flipped by putting them on the flips queue.
After all clicks are handled, call the flipHandler.
*/
function clickHandler($game) {
  var gameData = $game.data('data');
  var $card; // card clicked on
  var $prevFlipped;
  if (gameData.isClickHandlerRunning === true) { return; }
  gameData.isClickHandlerRunning = true;
  while (gameData.clicks.length > 0) {
    $card = gameData.clicks.shift();
    if ($card.hasClass('jqConcentrationMatched')) { continue; }
    $prevFlipped = gameData.$flippedCard;
    // note: no easy way to compare 2 jQuery objects for equality.
    if ($prevFlipped && $card.data('data').index === $prevFlipped.data('data').index) { continue; }
    gameData.flips.push({
      action: 'flip',
      card: $card,
      time: gameData.faceUpTime
    });
    if ($prevFlipped !== null) { // 2nd one now
      if (isMatching($card, $prevFlipped, $game)) { // got a match, leave them face up
        $card.addClass('jqConcentrationMatched');
        $prevFlipped.addClass('jqConcentrationMatched');
      } else { // they didn't match
        // wait a bit, then turn cards back over
        gameData.flips.push({
          action: 'pause',
          time: gameData.pauseTime
        });
        gameData.flips.push({
          action: 'flip',
          card: $prevFlipped,
          time: gameData.faceDownTime
        });
        gameData.flips.push({
          action: 'flip',
          card: $card,
          time: gameData.faceDownTime
        });
      }
      gameData.$flippedCard = null;
    } else {
      gameData.$flippedCard = $card;
    }
  }
  gameData.isClickHandlerRunning = false;
  flipHandler($game);
}

//
// plugin definition
//
$.fn.concentration = function (options) {
  // 'this' is jq collection
  // options: {fronts: [img], back: img, pairs: num, columns: num}
  var opts = $.extend({}, $.fn.concentration.defaults, options);
  opts.pairs = Math.min(opts.fronts.length, opts.pairs);
  // iterate and reformat each matched element
  return this.each(function () {
    // 'this' is single dom element (div usually) where the game sits
    var $this = $(this);
    var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;
    var fronts; // array of img for card fronts. 2 of each, shuffled
    var $table = $('<table></table>'); // layout table in game div
    var $row; // current row of table
    // game data
    $this.data('data', {
      clicks: [], // queue of click events
      flips: [], // queue of cards to be flipped
      isClickHandlerRunning: false, // mutex for clickHandler
      isFlipHandlerRunning: false, // mutex for flipHandler
      $flippedCard: null, // face up card
      faceUpTime: o.faceUpTime, // delay for turning card up
      faceDownTime: o.faceDownTime, // delay when turning card down
      pauseTime: o.pauseTime
    });
    shuffle(o.fronts);
    // DOPPELT VERHINDERN DAHER AUSKOMMENTIEREN
   	//////////////////
    //fronts = $.merge(o.fronts.slice(0, o.pairs), o.fronts.slice(0, o.pairs));
    fronts = o.fronts.slice(0, o.pairs);

    shuffle(fronts);
    $this.empty().append($table);
    $.map(fronts, function (elem, index) { // foreach card
      var $back = $('<img src="' + o.back + '" class="jqConcentrationUp">');
      var $card = $('<div class="jqConcentrationCard"></div>');
      // card data
      $card.data('data', { index: index });
      $card.append($('<img src="' + elem + '"/>')).append($back);
      if (index % opts.columns === 0) { // start a new row
        $row = $('<tr></tr>');
        $table.append($row);
      }
      $row.append($('<td></td>').append($card));
    });
    // click handler for the game div. Just queue the click and return.
    $this.click(function (event) {
      var thisData = $this.data('data');
      var $card = $(event.target).parent();
      if ($card.hasClass('jqConcentrationCard')) { // if we clicked on card img
        thisData.clicks.push($card);
        clickHandler($this);
      }
    });
  });
};

function showSuccess($game){
	//siegerPose();
    var gameData = $game.data('data');
    level = gameData.level;
	DivEinblenden('Sieg'+level);
	//level++;
	document.getElementById('level_button'+level).className = 'freeButton';
}

	function DivEinblenden(divName){
	
		var element = document.getElementById(divName);
	
 		//Gibt es das Objekt mit dem Namen der in divName Ùbergeben wurde?
 		if(element){
   			element.style.display = "inline";
			element.style.zIndex = "10";
 		} else {
 			alert(divName + " gibt es gar nicht!");
 		}
	}
	
	function DivAusblenden(divName){
	
		var element = document.getElementById(divName);

 		//Gibt es das Objekt mit dem Namen der in divName uebergeben wurde?
 		if(element){
   			element.style.display = "none";
			element.style.zIndex = "1";
 		} else {
 			alert(divName + " gibt es gar nicht!");
 		}
	}
	
//
// predefined plugin options
//
$.fn.concentration.defaults = {
  // fronts: [img urls], - required array of front of card image urls, 100x100px
  // back: img url, - required url of back of card image. 100x100px
  pairs: 8, // number of pairs. 8 pairs means 16 cards to match
  columns: 4, // number of columns in layout table
  faceUpTime: 0, // time to turn face up
  faceDownTime: 500, // time to turn face down (miliseconds)
  pauseTime: 250, // pause before reverting mismatched cards
  level: 1
};

})(jQuery);

