/**
* jMemoGame
*
* @author Yann Michalski <yann.michalski@gmail.com>
* @version 1.0
* 
*/

var jMemoGame = {
	
	// index of the current level
	indexLevel : 0,
	
	// global score
	score: 0,
	
	// number of found cards
	nbFound: 0,
	
	// time left before loosing level
	timeLeft: 0,
	
	// TimeOut object used for managing the mask
	objToMask: 0,
	
	// TimeOut object used for managing the level countdown
	objToCountdown: 0,
	
	loseText: "",
	
	lang: "d" ,
	
	// Description of cards
	cards : [
		
	],
	
	// Description of levels
	levels: [
		
		/*{level: 2, x_max: 4, y_max: 4, time: 60, msgWin: 'Good!'},
		{level: 3, x_max: 5, y_max: 4, time: 50, msgWin: 'Superb!'},
		{level: 4, x_max: 6, y_max: 5, time: 45, msgWin: 'Marvelous!'},
		{level: 5, x_max: 6, y_max: 6, time: 45, msgWin: 'Outstanding! Be ready for the last level!'},
		{level: 6, x_max: 6, y_max: 7, time: 40, msgWin: 'Yipee! You completed all levels =)'}*/
	],
	
	/**
	* Launch game
	**/
	Play : function(){
		var objJMG = this;
		$().playground("#playground",{refreshRate: 30, width: 820, height: 415, position: 'relative'});
		$('#start').show();
		$().playground().startGame(); 
		$('#bt-start').hover(
	      function () {
	        $(this).css({'background-color': '#000000', 'color':'#ffffff'});
	      }, 
	      function () {
	        $(this).css({'background-color': '#ffffff', 'color':'#000000'});
	      }
	    ).click(function(){
			pageTracker._trackEvent('Memory Page', 'Start Game', 'lang:'+this.lang);
			objJMG.Init();
		});
	},
	
	/**
	* Build and start the current level
	**/
	Init : function(){
		var CarteDos = new Animation({ imageURL: 'bilder/card-back_'+this.lang+'.gif', numberOfFrame: 1, delta: 125, rate: 30, type: Animation.HORIZONTAL | Animation.ONCE}); 
		var tabcards = new Array();
		$('.card').each(function(){
			$(this).removeSprite();
		});
		if(this.indexLevel == 0){
			this.score = 0;
		}
		$('#time').html(this.levels[this.indexLevel].time);
		$('#num-level').html(this.levels[this.indexLevel].level);
		$('#score').html(String(this.score));
		this.timeLeft = this.levels[this.indexLevel].time;
		this.CountDown();
		this.nbFound = 0;
		for (var i = 0; i < this.levels[this.indexLevel].x_max * this.levels[this.indexLevel].y_max; i+=1){
			tabcards[i] = Math.floor(i/2);
		}
		for(var j, x, i = tabcards.length; i; j = parseInt(Math.random() * i), x = tabcards[--i], tabcards[i] = tabcards[j], tabcards[j] = x);
		for (var i = 0; i < tabcards.length; i+=1){
			Coord_x = Math.floor(i/this.levels[this.indexLevel].y_max)*135 + 10
			Coord_y = Math.floor(i%this.levels[this.indexLevel].y_max)*135 + 10
			$().playground().addSprite('sprite' + i.toString(),{height: 125, width: 125, posx: Coord_x, posy: Coord_y, animation: CarteDos}); 
			$('#sprite' + i.toString()).addClass('card');	
			$('#sprite' + i.toString()).addClass(this.cards[tabcards[i]].name);
			this.SetAnimShow('#sprite' + i.toString(), tabcards[i]);
		}
		$('#start').css('display', 'none').css('opacity', 0);
		$("#mask").css("display", "none");
	},
	
	
	/**
	* Apply the hiding animation when clicking the card
	**/
	SetAnimShow : function(Sprite, IndexCard){
		var objJMG = this;
		
		$(Sprite).bind( 'click', function(){
			$(Sprite).addClass('shown');
			$(Sprite).addClass('found');
			objJMG.DisplayMask(100);
			var Anim1 = new Animation({ imageURL: 'bilder/card-back-show_'+this.lang+'.gif', numberOfFrame: 6, delta: 125, rate: 30, type: Animation.HORIZONTAL | Animation.ONCE | Animation.CALLBACK });
			var Anim2 = new Animation({ imageURL: 'bilder/' + objJMG.cards[IndexCard].imgShow, numberOfFrame: 1, delta: 125, rate: 30, type: Animation.HORIZONTAL | Animation.ONCE }); 
			$(Sprite).setAnimation(Anim1, function(){
				$(Sprite).setAnimation(Anim2);
			});
			objJMG.IsFound(Sprite, IndexCard);
		});
	},
	
	/**
	* Launch the hiding animation after 1.5 second
	**/
	ProgAnimHide : function(Sprite, IndexCard){
		var objJMG = this;
		window.setTimeout( function(){objJMG.SetAnimHide(Sprite, IndexCard);}, 800); 
		window.setTimeout( function(){objJMG.SetAnimShow(Sprite, IndexCard);}, 1000); 
		this.DisplayMask(1000);
	},
	
	/**
	* Hide the card
	**/
	SetAnimHide : function(Sprite, IndexCard){
		$(Sprite).removeClass('shown');
		var Anim1 = new Animation({ imageURL: 'bilder/' + this.cards[IndexCard].imgHide, numberOfFrame: 2, delta: 125, rate: 30, type: Animation.HORIZONTAL | Animation.ONCE | Animation.CALLBACK }); 
		var Anim2 = new Animation({ imageURL: 'bilder/card-back-hide_'+this.lang+'.gif', numberOfFrame: 6, delta: 125, rate: 30, type: Animation.HORIZONTAL | Animation.ONCE });
		$(Sprite).setAnimation(Anim1, function(){
			$(Sprite).setAnimation(Anim2);
		});
	},
	
	/**
	* Display the transparent mask to block clicking
	**/
	DisplayMask : function(time){
			$('#mask').css('display', 'block');
			clearTimeout(this.objToMask);
			this.objToMask = window.setTimeout (function(){$("#mask").css("display", "none");}, time); 
	},

	/**
	* Check if the shown cards are a couple
	**/
	IsFound : function(Sprite, IndexCard){
		var objJMG = this;
		var coupleIsFound = true;
		$(Sprite).unbind('click');
		var CardName = this.cards[IndexCard].name;
		$('.shown').each(function(){
			if(!$(this).hasClass(CardName)){
				coupleIsFound = false;
				$('.shown').each(function(){
					for (var i = 0; i < objJMG.cards.length; i+=1){
						if($(this).hasClass(objJMG.cards[i].name)){
							objJMG.ProgAnimHide('#' + $(this).attr('id'), i);
							break;
						}
					}
					$(this).removeClass('found');
				});
			}
		});
		if($('.shown').length == 2){
			$('.shown').each(function(){
				$(this).removeClass('shown');
			});
		}else{
			coupleIsFound = false;
		}
		if (coupleIsFound){
			this.SetScore();
		}
	},
	
	/**
	* Set the global score
	**/
	SetScore : function(){
		this.nbFound++;
		this.score += $('#time').html().replace('s', '') * this.levels[this.indexLevel].time * this.levels[this.indexLevel].level
		$('#score').html(this.score).css('color', '#FF0000').animate({ color: '#000000'}, 1000 );
		if(this.nbFound == this.levels[this.indexLevel].x_max * this.levels[this.indexLevel].y_max/2){
			this.FinishGame('win');
			
		}
	},
	
	/**
	* Finish the current level
	**/
	FinishGame : function(state){
		$('#start').css('display', 'block').animate({opacity: 0.9}, 500 );
		if(state == 'win'){
			this.StopCountDown();
			$('#msg-endgame').css('color', '#000');
			$('#msg-endgame').html(this.levels[this.indexLevel].msgWin);
			this.indexLevel++;	
			if(this.indexLevel == this.levels.length){
				$('#bt-start').css('display', 'block');
				$('#continue').css('display', 'block');
			}
			this.indexLevel = 0;
			pageTracker._trackEvent('Memory Page', 'Win Game', 'lang:'+this.lang);
			memoryWinProcess();
		}else{
			$('#msg-endgame').html(this.loseText);
			pageTracker._trackEvent('Memory Page', 'Lose Game', 'lang:'+this.lang);
			this.indexLevel = 0;
		}
	},
	
	/**
	* Decrements the level countdown
	**/
	CountDown : function(){
		var objJMG = this;
		if(this.timeLeft < 0){
			this.FinishGame('lose');
		}else{
			this.objToCountdown = window.setTimeout(
				function() {
					$('#time').html(String(objJMG.timeLeft));
					--objJMG.timeLeft;
					objJMG.CountDown();
				}
				, 1000
			);
		}
	},
	
	/**
	* Stop the level countdown
	**/
	StopCountDown : function(){
		window.clearTimeout(this.objToCountdown);
	}
};



