'use strict';

/**
@author Felipe Vargas RIC-SOUTH
A module representing the  GAME TICTACTOE the idea is in each attempt anwser some question 
@Module sgGameTicTacToe  
**/
define(['jquery','sgSound'], function($,sgSound) {

	var app = {};
	
	var players = ['X', 'O']; // this array represents what will be painted in the turn give
	var columns = 3; // how many squares will be organized in each row
	var rows = 3; // how many rows has the board 
	var currentSquare;// when the user pushes click in some square this var saves the square pressed
	var currentBtnPopUpItem; // when the user pushes click some square this var saves which one the popup lunched 
	var currentTicTacToe; // this var save the tic tac toe element 
	var ticTacToeGames;
	
	
	

	//var winner = "";// this var save who is the winner 
	//var turn = 0; // these are the turns , 0 is for X  and 1 for O

	app.init = function() {

		// init the vars depending of the DOM a jquery
		
		ticTacToeGames=$("[data-sg-id=game-tictactoe]");



		if (ticTacToeGames.length > 0) {
			$("head").append($("<link rel='stylesheet' href='../../common/css/modules/sgGameTictactoe.css' type='text/css' media='screen' />"));
		};

		ticTacToeGames.each(function(index,value){

			var ticTacToe= $(this);
			

			ticTacToe.data('turn',0);

			var boardTurn= $('<div>');
			var boardTurnX=$('<div>').addClass('board-turn-'+players[0]).addClass('active');
			var boardTurnO=$('<div>').addClass('board-turn-'+players[1]);
			


			boardTurn.addClass('board-turn');
			boardTurn.append(boardTurnX);
			boardTurn.append(boardTurnO);

			ticTacToe.append(boardTurn);


			var btnPopUp = ticTacToe.find('[data-sg-id="btn-popup"]');
			btnPopUp.hide();

			// check if the tic tac toe has enought questions
			if (btnPopUp.length != 9) {
				console.error('The number of squares should be 9');
				return;
			}

			// create the board for playing
			for (var j = 0; j < rows * columns; j++) {

				var rowTicTac;
				if (j % columns == 0) {
					rowTicTac = $('<div>');
					rowTicTac.addClass('row-squares');
					rowTicTac.css({
						display: 'table-row'
					});
					ticTacToe.append(rowTicTac);
				}

				var square = $('<div>'); //squares[j]);//.append('X');
				var spanNumber=$('<span>').css({'color':'#CC7733','font-size':'2em'});
				if (ticTacToe.attr('data-sg-rand')!= undefined) {
					spanNumber.text('?');
				}else{
					spanNumber.text(''+(j+1));
				}
				square.append(spanNumber);
				square.addClass('square');

				

				// square.css('background-img','../../img/modules/sgGameTictactoe/fondo-circulo.png');
				// square.css('background-size','100% 100%');

				var sgKeyPopUp = $(btnPopUp[j]).attr('data-sg-key');
				square.attr('data-sg-key', sgKeyPopUp); // this is used only when is different of rand
				square.attr('data-sg-index-tictactoe',""+index);

				var currentPopUp = $('[data-sg-id="item-popup"][data-sg-key="' + sgKeyPopUp + '"]');

				var correctButton = currentPopUp.find('[data-sg-id="btn-correct"]');
				var incorrectButton = currentPopUp.find('[data-sg-id="btn-incorrect"]');

				if (correctButton.length == 0 || incorrectButton.length == 0) {
					console.error(j + " Some popup doesn't have the buttons correct and incorrect ");
				}
				correctButton.click(correctClick);
				incorrectButton.click(incorrectClick);
				square.click(squareClick);
				rowTicTac.append(square);
			}

		 }
		);// end each
		

		
	}

	// this is triggered when the user press incorrect in the question
	function incorrectClick(e) {
		sgSound.sg_sound("error");
		closePopUp(this);
		var isOnce = currentTicTacToe.attr('data-sg-once');

		// once is used for definig if one question only could be showed once time
		// additionaly disable the square pushed
		if (isOnce != undefined) {
			// currentSquare.append('Corregido');
			currentSquare.addClass('corrected');
			currentSquare.find('span').remove();
			disableSquare();
			destroyPopUp();
		}

		hasEnabledSquares();
		changeTurn();
	}
	// this is triggered when the user press correct in the question
	function correctClick(e) {
		sgSound.sg_sound("success");
		var turn = currentTicTacToe.data('turn');
		currentSquare.append(players[turn]);
		currentSquare.find('span').remove();
		disableSquare();
		currentSquare.addClass('to' + players[turn]);// class for indentifing in CSS the squares marked for each player
		closePopUp(this);
		destroyPopUp();
		checkWinner();
		changeTurn();
	}


	// this is triggered when the user press click in some square enable
	function squareClick(e) {
		sgSound.sg_sound("success-low");
		var indexTic= $(this).attr('data-sg-index-tictactoe');
		currentTicTacToe=ticTacToeGames.eq(indexTic); 
		
		var isRand = currentTicTacToe.attr('data-sg-rand');

		var btnPopUp=currentTicTacToe.find('[data-sg-id="btn-popup"]');


		if (isRand != undefined) {
			var pos = Math.floor(Math.random() * btnPopUp.length);
			var btnPopUpItem = btnPopUp[pos];
			$(btnPopUpItem).click();
			currentBtnPopUpItem = $(btnPopUpItem);


		} else {
			var dataSgKey = $(this).attr('data-sg-key');
			var btnPopUpItem = btnPopUp.filter('[data-sg-key=' + dataSgKey + ']');
			btnPopUpItem.click();
			currentBtnPopUpItem = btnPopUpItem;
		}
		currentSquare = $(this);
	}

	//  a basic function for changing the current player 
	function changeTurn() {

		var turn = currentTicTacToe.data('turn');
		if (turn == 0) {
			turn = 1;
		} else {
			turn = 0;
		}
		currentTicTacToe.find(".active").removeClass('active');
		currentTicTacToe.find(".board-turn-"+players[turn]).addClass('active');

		currentTicTacToe.data('turn', turn);
	}

	//  when a user press click in incorrect or correct the pop up has to be closed
	function closePopUp(btnOnPopUp) {
		var closeButton = $(btnOnPopUp).parent().find('[data-sg-id=btn-popup-close]');
		closeButton.click();
	}

	//  when the anwser could'n appear again 
	function destroyPopUp() {
		var btnPopUp=currentTicTacToe.find('[data-sg-id="btn-popup"]');
		var dataSgKey = currentBtnPopUpItem.attr('data-sg-key');
		btnPopUp.filter('[data-sg-key=' + dataSgKey + ']').remove();

		btnPopUp = currentTicTacToe.find('[data-sg-id="btn-popup"]');
		$('[data-sg-id="btn-popup"][data-sg-key=' + dataSgKey + ']').remove();
	}
	//  disable the current square when is marked
	function disableSquare() {
		currentSquare.attr('disabled', 'true');
		currentSquare.css('cursor', 'default');
		currentSquare.unbind();
	}

	// disable all the squares when there is a winner 
	function disableAllSquares() {

		var allSquares = currentTicTacToe.find('.square');
		allSquares.attr('disabled', 'true');
		allSquares.css('cursor', 'default');
		allSquares.unbind();

	}

	//  look if there is some winner 
	function checkWinner() {

		var incrementColumn = [1, 0, 1, -1, 1, 1, 0, 0];
		var incrementRow =    [0, 1, 1, 1, 0, 0, 1, 1];

		var beginColumn =     [0, 0, 0, 2, 0, 0, 1, 2];
		var beginRow = 	      [0, 0, 0, 0, 1, 2, 0, 0];



		for (var j = 0; j < incrementColumn.length; j++) {
			var posRow = beginRow[j],
				posColumn = beginColumn[j];

			var player = getTextSquare(posRow, posColumn);
			
			var winner = player;

			if (player !== "") {
				for (var i = 1; i < columns; i++) {

					posRow = posRow + incrementRow[j];
					posColumn = posColumn + incrementColumn[j];

					var nextPlayer =getTextSquare(posRow, posColumn);
					

					if (player != nextPlayer) {
						winner = "";
						break;
					}

					


				}

				if (winner != "") {

					currentTicTacToe.find('.win').addClass('winner-square');

					var codeWinner = currentTicTacToe.attr('data-sg-winner-js');

					var fn=window[codeWinner];
					if(typeof fn=='function'){
						
						fn.apply(null, [winner]);
					}
					else {
						alert('El ganador es '+winner);
					}

					disableAllSquares();

					return winner;
				}

				currentTicTacToe.find('.win').removeClass('win');


			}


		}

		hasEnabledSquares();
		return "";
	}

	// get the text from the square
	function getTextSquare(rowSquare, columnSquare) {
		var rowsTicTac = currentTicTacToe.find('.row-squares');
		var curRow = $(rowsTicTac[rowSquare]);
		var curSquare = $(curRow.find('.square')[columnSquare]);
		curSquare.addClass('win');
		var text= curSquare.text();
		if(players.indexOf(text)<0){
			return "";
		}else {
			return curSquare.text();
		}


	}
	//  look is there is some square enable
	function hasEnabledSquares() {
		var allSquares = currentTicTacToe.find('.square');

		for (var i = 0; i < allSquares.length; i++) {
			var $curSquare = allSquares.eq(i);
			if (!$curSquare.attr('disabled')) return;
		}

		allSquares.css('opacity','0.7');

		
	}

	
	return app;
});