'use strict';

/**
@author Samuel Ramirez RIC-SOUTH
A module representing the GAME MATCH PAIR MEMORY the idea is find in a board, the cards with the same or equivalent information.
@Module sgGameMatchMemory  
**/
define(['jquery','sgSound'], function($,sgSound) {

	var app = {};
	
	//create all the variables
	var playGame;
	var score;
	var cardsmatched;
	var scoreTimeout;

	var ui;
	var uiIntro;
	var uiStats;
	var uiComplete;
	var uiScoreFinal;
	var uiCards;
	var uiPlay;
	var uiReset;
	var uiTimer;
	var uiScore;
	var uiReset2;

	var grade;
	var totalMatch;
	var num_cols;
	var rand;

	var marginLeft;
	var marginTop;
	var widthCard;
	var heightCard;

	var finalDuration;


	app.init = function() {

		 ui=			$("[data-sg-id=game-matchmemory]");
		 uiComplete = 	$("<div/>").attr("id", "gameComplete").prependTo(ui).html("<h2>BIEN HECHO!</h2><p>Te has demorado </p>");
		 uiIntro = 		$("<div/>").attr("id", "gameIntro").prependTo(ui);
		 uiStats = 		$("<div/>").attr("id", "gameStats").prependTo(ui);
		 uiPlay =		$("<button/>").appendTo(uiIntro).text("Jugar");
		 uiTimer =		$("<p/>").attr("id", "timer").text("Tiempo transcurrido: ").prependTo(uiStats);
		 uiScore = 		$("<span/>").attr("sg-timmer", "prueba").appendTo(uiTimer);
		 uiScoreFinal =	$("<span/>").appendTo(uiComplete.find("p"));
		 uiReset = 		$("<p/>").attr("id", "reset").text("Reiniciar").appendTo(uiStats);
		 uiReset2 = 	$("<button/>").text("Intentalo de Nuevo").appendTo(uiComplete);
		 uiCards= 		ui.find("#cards").css("z-index", "0");

		grade = 		uiCards.attr("data-sg-grade");
		totalMatch = 	uiCards.children().size()/grade;
		num_cols = 		uiCards.attr("data-sg-numcols");
		rand= 			uiCards.attr('data-sg-rand') != undefined ? 1 : 0;

		marginLeft =	uiCards.attr("data-sg-marginL") != undefined? parseInt(uiCards.attr("data-sg-marginL")): 20;
		marginTop = 	uiCards.attr("data-sg-marginT") != undefined? parseInt(uiCards.attr("data-sg-marginT")): 20;
		widthCard = 	uiCards.attr("data-sg-wCard") != undefined? parseInt(uiCards.attr("data-sg-wCard")): 0;
		heightCard = 	uiCards.attr("data-sg-hCard") != undefined? parseInt(uiCards.attr("data-sg-hCard")): 0;

		finalDuration = uiCards.attr("data-sg-finalTime") != undefined? parseInt(uiCards.attr("data-sg-finalTime")):0;

		uiComplete.hide();
		uiCards.hide();
		playGame = false;
		uiPlay.click(function(e) {
			e.preventDefault();
			uiIntro.hide();
			startGame();
		});

		uiReset.click(function(e) {
			e.preventDefault();
			uiComplete.hide();					
			reStartGame();
		});

		uiReset2.click(function(e) {
			e.preventDefault();
			uiComplete.hide();					
			reStartGame();
		});
	}


//start game and create cards from deck array
function startGame(){
	uiTimer.show();
	uiScore.html("0 segundos");
	uiStats.show();
	uiCards.fadeIn();
	score = 0;
	cardsmatched = 0;
   	if (playGame == false) {
   		playGame = true;

		var frontCard = $("<span/>").addClass("face front");
		var divCard = $("<div/>");
		// initialize each card's position
		if(rand){
			uiCards.shuffle();
		}
		uiCards.children().each(function(index) {
			var $this = $(this);
			var keymatch = $this.attr("data-sg-key");
			var divCardCopy = divCard.clone().attr( "data-sg-key", keymatch ).appendTo(uiCards);
			$this.addClass("face back").removeAttr("data-sg-key").appendTo(divCardCopy);
			frontCard.clone().appendTo(divCardCopy);

			// align the cards to be 3x6 ourselves.
			divCardCopy.css({
				"left" : ((widthCard==0?$this.parent().width():widthCard) + marginLeft) * (index % num_cols),
				"top" : ((heightCard==0?$this.parent().height():heightCard) + marginTop) * Math.floor(index / num_cols)
			}).click(selectCard);
		});
	   	timer();
	};
	app.extraStartGame();			   
}
app.extraStartGame = function(){
	
}

//timer for game
function timer() {
	//alert("timer set")
	if (playGame) {
		scoreTimeout = setTimeout(function() {
			uiScore.html(++score + " segundos");		
			timer();
		}, 1000);
	};
};

//shuffle cards
//http://jsfiddle.net/timur/bAynQ/
$.fn.shuffle = function() {
    return this.each(function(){
        var items = $(this).children().clone(true);
        return (items.length) ? $(this).html($.shuffle(items)) : this;
    });
}

$.shuffle = function(arr) {
    for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
}

app.extraActionFlippedCard = function(){

}

//onclick function add flip class and then check to see if cards are the same
function selectCard() {
	// we do nothing if there are already two cards flipped.
	if ($(".card-flipped").size() > (grade - 1)) {
		return;
	}
	$(this).addClass("card-flipped");
	app.extraActionFlippedCard($(this));

	// check the pattern of both flipped card 0.7s later.
	if ($(".card-flipped").size() == grade) {
		setTimeout(checkPattern,700);
	}
}
app.extraDontMatch = function(){

}

//if pattern is same remove cards otherwise flip back
function checkPattern() {
	if (isMatchPattern()) {
		sg.sound("success");
		$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
		if(document.webkitTransitionEnd){
			$(".card-removed").bind("webkitTransitionEnd",	removeTookCards);
		}else{
			removeTookCards();
		}
	} else {
		$(".card-flipped").removeClass("card-flipped");
		app.extraDontMatch();
	}
}

//put 2 flipped cards in an array then check the image to see if it's the same.
function isMatchPattern() {
	var cards = $(".card-flipped");
	var pattern_ini = $(cards[0]).attr("data-sg-key");
	var match = true;
	cards.each(function(index){
		var pattern_N = $(this).attr("data-sg-key");
		if (pattern_ini != pattern_N) {
			match = false;
			return match;
		};
	})
	return match;
}

app.afterCheck = function(){
		
	}

//check to see if all cardmatched variable is less than 8 if so remove card only otherwise remove card and end game 
function removeTookCards() {
	if (cardsmatched < (totalMatch-1)){
		cardsmatched++;
		$(".card-removed").fadeOut(50);
		app.afterCheck();
	}else{
		sg.sound("claps");
		app.afterCheck();
		$(".card-removed").fadeOut(10000);		
		uiCards.fadeOut(finalDuration, function(){
			uiComplete.fadeIn();
		});		
		uiScoreFinal.html( uiScore.html());
		clearTimeout(scoreTimeout);
	}	
}

app.extraRestartGame = function(){

}
//recreate the original card , stop the timer and re populate the array with class names
function reStartGame(){
	playGame = true;
	clearTimeout(scoreTimeout);
	uiTimer.show();
	uiScore.html("0 segundos");
	uiStats.show();
	uiCards.fadeIn();
	score = 0;
	cardsmatched = 0;
	if(rand){
		uiCards.shuffle();
	}
	uiCards.children().each(function(index) {
			var $this = $(this);
			$this.css({
				"left" : ((widthCard==0?$this.width():widthCard) + marginLeft) * (index % num_cols),
				"top" : ((heightCard==0?$this.height():heightCard) + marginTop) * Math.floor(index / num_cols)
			}).click(selectCard);
	});
	uiCards.children().fadeIn().removeClass("card-removed card-flipped");
	app.extraRestartGame();
	timer();
}


return app;

});
				