/**
* 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,
	
	// plates animations
	platesFlipIn: 'question-card-left.png',
	platesFlipOut: 'question-card-left.png',
	
	// photos animations
	photosFlipIn: 'question-card.png',
	photosFlipOut: 'question-card.png',
	
	
	
	// Description of cards
	cards : [
		{name: 'chameau', plateShow: 'question-card-left-pope.png', plateHide: 'question-card-left-pope.png', photoShow: 'question-card-pope.png', photoHide: 'question-card-pope.png'},
		{name: 'chat', plateShow: 'question-card-left-queen.png', plateHide: 'question-card-left-queen.png', photoShow: 'question-card-queen.png', photoHide: 'question-card-queen.png'},
		{name: 'cheval', plateShow: 'question-card-left-einstein.png', plateHide: 'question-card-left-einstein.png', photoShow: 'question-card-einstein.png', photoHide: 'question-card-einstein.png'},
		{name: 'colibri', plateShow: 'question-card-left-armstrong.png', plateHide: 'question-card-left-armstrong.png', photoShow: 'question-card-armstrong.png', photoHide: 'question-card-armstrong.png'},
		{name: 'discus', plateShow: 'question-card-left-chaplin.png', plateHide: 'question-card-left-chaplin.png', photoShow: 'question-card-chaplin.png', photoHide: 'question-card-chaplin.png'},
		{name: 'ecureuil', plateShow: 'question-card-left-elvis.png', plateHide: 'question-card-left-elvis.png', photoShow: 'question-card-elvis.png', photoHide: 'question-card-elvis.png'}
	],
	
	// Description of levels
	levels: [
		{level: 1, x_max: 2, y_max: 3, time: 70, msgWin: 'Well done!'},
	],
	
	/**
	* Launch game
	**/
	Play : function(){
		var objJMG = this;
		$().playground("#playground",{refreshRate: 10, width: 900, height: 500, position: 'relative'});
		$().playground().startGame(); 
		$('#bt-start').click(function(){
			$("#panel4").fadeOut(250);
			objJMG.Init();
		}); 
		$('#btn-playagain').click(function(){
			$("#panel2").fadeOut(250);
			objJMG.Init();
		});
	},
	
	/**
	* Build and start the current level
	**/
	Init : function(){
		var CarteDos = new Animation({ imageURL: './images/'+this.platesFlipIn, numberOfFrame: 1, delta: 40, rate: 40, type: Animation.HORIZONTAL | Animation.ONCE}); 
		var CarteDos2 = new Animation({ imageURL: './images/'+this.photosFlipIn, numberOfFrame: 1, delta: 40, rate: 40, type: Animation.HORIZONTAL | Animation.ONCE}); 
		var tabcards = new Array();
		var tabcards2 = new Array();
		$('.card').each(function(){
			$(this).removeSprite();
		});
		if(this.indexLevel == 0){
			this.score = 0;
		}
		$('#time').html(this.levels[this.indexLevel].time + 's');
		$('#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 < 6; i+=1){
			tabcards[i] = i;
			tabcards2[i] = i;
		}
		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 j, x, i = tabcards2.length; i; j = parseInt(Math.random() * i), x = tabcards2[--i], tabcards2[i] = tabcards2[j], tabcards2[j] = x);
		
		for (var i = 0; i < tabcards.length; i+=1){
			Coord_x = Math.floor(i/this.levels[this.indexLevel].y_max)*148;
			Coord_y = Math.floor(i%this.levels[this.indexLevel].y_max)*112 + 2
			$().playground().addSprite('sprite' + i.toString(),{height: 112, width: 148, posx: Coord_x, posy: Coord_y, animation: CarteDos}); 
			$('#sprite' + i.toString()).addClass('card');
			$('#sprite' + i.toString()).addClass('plate');	
			$('#sprite' + i.toString()).addClass(this.cards[tabcards[i]].name);
			this.SetAnimShow('#sprite' + i.toString(), tabcards[i]);
		}
		
		for (var i = 0; i < tabcards2.length; i+=1){
			Coord_x = Math.floor(i/this.levels[this.indexLevel].x_max)*180+360;
			Coord_y = Math.floor(i%this.levels[this.indexLevel].x_max)*209 + 2
			$().playground().addSprite('sprite2' + i.toString(),{height: 209, width: 180, posx: Coord_x, posy: Coord_y, animation: CarteDos2}); 
			$('#sprite2' + i.toString()).addClass('card');
			$('#sprite2' + i.toString()).addClass('photo');	
			$('#sprite2' + i.toString()).addClass(this.cards[tabcards2[i]].name);
			this.SetAnimShow('#sprite2' + i.toString(), tabcards2[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(300);
			if($(this).hasClass('plate')) { 
				Anim1 = new Animation({ imageURL: './images/' + this.platesFlipIn, numberOfFrame: 10, delta: 40, rate: 10, type: Animation.HORIZONTAL | Animation.ONCE | Animation.CALLBACK});
				Anim2 = new Animation({ imageURL: './images/' + objJMG.cards[IndexCard].plateShow, numberOfFrame: 1, delta: 40, rate: 10, type: Animation.HORIZONTAL | Animation.ONCE }); 
			}
			else {
				Anim1 = new Animation({ imageURL: './images/' + this.photosFlipIn, numberOfFrame: 10, delta: 40, rate: 10, type: Animation.HORIZONTAL | Animation.ONCE | Animation.CALLBACK});
				Anim2 = new Animation({ imageURL: './images/' + objJMG.cards[IndexCard].photoShow, numberOfFrame: 1, delta: 40, rate: 10, 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);}, 1500); 
		window.setTimeout( function(){objJMG.SetAnimShow(Sprite, IndexCard);}, 1700); 
		this.DisplayMask(1600);
	},
	
	/**
	* Hide the card
	**/
	SetAnimHide : function(Sprite, IndexCard){
		$(Sprite).removeClass('shown');
		if($(Sprite).hasClass('plate')) { 
			var Anim1 = new Animation({ imageURL: './images/' + this.cards[IndexCard].plateHide, numberOfFrame: 10, delta: 40, rate: 10, type: Animation.HORIZONTAL | Animation.ONCE | Animation.CALLBACK}); 
			var Anim2 = new Animation({ imageURL: './images/' + this.platesFlipOut, numberOfFrame: 1, delta: 40, rate: 10, type: Animation.HORIZONTAL | Animation.ONCE});
		}
		else { 
			var Anim1 = new Animation({ imageURL: './images/' + this.cards[IndexCard].photoHide, numberOfFrame: 10, delta: 40, rate: 10, type: Animation.HORIZONTAL | Animation.ONCE | Animation.CALLBACK}); 
			var Anim2 = new Animation({ imageURL: './images/' + this.photosFlipOut, numberOfFrame: 1, delta: 40, rate: 10, 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', '#fbd800').animate({ color: '#ac672a'}, 1000 );
		if(this.nbFound == this.levels[this.indexLevel].x_max * this.levels[this.indexLevel].y_max){
			this.FinishGame('win');
		}
	},
	
	/**
	* Finish the current level
	**/
	FinishGame : function(state){
		$('#start').css('display', 'block').animate({opacity: 0.9}, 500 );
		if(state == 'win'){
			this.StopCountDown();
			$("#panel").fadeIn(250);
			this.indexLevel++;	
		}else{
			$("#panel2").fadeIn(250);
			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) + 's');
					--objJMG.timeLeft;
					objJMG.CountDown();
				}
				, 1000
			);
		}
	},
	
	/**
	* Stop the level countdown
	**/
	StopCountDown : function(){
		window.clearTimeout(this.objToCountdown);
	}
};


