/*

    VANIXON TIC TAC TOE JS
    
    --> TICTACTOE - GAME <--
    

    Created by Vanixon GmbH, Pascal Stoop <http://www.vanixon.com>

*/
    var $jq = jQuery.noConflict();

    var refTictactoeGame = null;
    var refTictactoeQuestionThread = null;

    /***********************************************
    
        DATA CLASSES
    
    ************************************************/
    
    var PLAYER1 = 0;
    var PLAYER2 = 1;
    
    // if is set on true, no answer can be given
    var answer_given = false;
    
    function TictactoeGame() {
    
        /***********************************************
            METHODS
        ************************************************/

        this.resetGameToStart = function () {
            this.isInPlay = false;
            this.actualPlayer = PLAYER1;
            this.score = new Array(2);
            this.score[PLAYER1] = 0;
            this.score[PLAYER2] = 0;
            this.showInstructions[PLAYER1] = true;
            this.showInstructions[PLAYER2] = true;
            this.points_to_win = this.points_per_question;

            //init gamePanelDatas
            for (var boxnr1 = 0; boxnr1 < this.gamePanelDatas.length; boxnr1++) {
                for (var boxnr2 = 0; boxnr2 < this.gamePanelDatas[boxnr1].length; boxnr2++) {
                    this.gamePanelDatas[boxnr1][boxnr2] = -1;
                }
            }

            this.recalculateGraphicDatas();
        };
        
        this.closeGame = function() {
            
        };
        
        this.getWinner = function(){
          var winner_id = -2;
          
          if(refTictactoeGame.checkHasWinner(PLAYER1) > -1){
            winner_id = refTictactoeGame.checkHasWinner(PLAYER1);
          }
          if(refTictactoeGame.checkHasWinner(PLAYER2) > -1){
            winner_id = refTictactoeGame.checkHasWinner(PLAYER1);
          }
          
          return winner_id;
          
        };
        // Überprüft ob es schon einen gewinner gibt -> hor - ver - dia
        this.checkHasWinner = function(player_id){
          // schauen ob aktueller spieler gewonnen hat
          var actualP = player_id;
          
          // Check horizontal
          if(((this.gamePanelDatas[0][0] == actualP) && (this.gamePanelDatas[0][1] == actualP) && (this.gamePanelDatas[0][2] == actualP)) ||
             ((this.gamePanelDatas[1][0] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[1][2] == actualP)) ||
             ((this.gamePanelDatas[2][0] == actualP) && (this.gamePanelDatas[2][1] == actualP) && (this.gamePanelDatas[2][2] == actualP))) 
             {
                return actualP;
             }
             
             // Check vertical
          if(((this.gamePanelDatas[0][0] == actualP) && (this.gamePanelDatas[1][0] == actualP) && (this.gamePanelDatas[2][0] == actualP)) ||
             ((this.gamePanelDatas[0][1] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[2][1] == actualP)) ||
             ((this.gamePanelDatas[0][2] == actualP) && (this.gamePanelDatas[1][2] == actualP) && (this.gamePanelDatas[2][2] == actualP))) 
             {
                return actualP;
             }
           if(((this.gamePanelDatas[0][0] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[2][2] == actualP)) ||
             ((this.gamePanelDatas[0][2] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[2][0] == actualP)))
             {
                return actualP;
             }  
          return -2;
          
        };
        
        // Gibt für den Winner Screen die Winner Reihe zurück
        this.getWinnerRow = function(player_id){
          var actualP = player_id;
          
          var winner = new Array(3);
          winner[0] = new Array(2);
          winner[1] = new Array(2);
          winner[2] = new Array(2);
          
          /* Horizontal BEGIN */
          if((this.gamePanelDatas[0][0] == actualP) && (this.gamePanelDatas[0][1] == actualP) && (this.gamePanelDatas[0][2] == actualP)){
            winner[0][0] = 0;
            winner[0][1] = 0;
            
            winner[1][0] = 0;
            winner[1][1] = 1;
            
            winner[2][0] = 0;
            winner[2][1] = 2;
            
            return winner;              
          }
          if((this.gamePanelDatas[1][0] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[1][2] == actualP)){
            winner[0][0] = 1;
            winner[0][1] = 0;
            
            winner[1][0] = 1;
            winner[1][1] = 1;
            
            winner[2][0] = 1;
            winner[2][1] = 2;
            
            return winner;              
          }
          if((this.gamePanelDatas[2][0] == actualP) && (this.gamePanelDatas[2][1] == actualP) && (this.gamePanelDatas[2][2] == actualP)){
            winner[0][0] = 2;
            winner[0][1] = 0;
            
            winner[1][0] = 2;
            winner[1][1] = 1;
            
            winner[2][0] = 2;
            winner[2][1] = 2;
            
            return winner;              
          }                           
          /* Horizontal END */
          
          /* Vertical BEGIN */
          if((this.gamePanelDatas[0][0] == actualP) && (this.gamePanelDatas[1][0] == actualP) && (this.gamePanelDatas[2][0] == actualP)){
            winner[0][0] = 0;
            winner[0][1] = 0;
            
            winner[1][0] = 1;
            winner[1][1] = 0;
            
            winner[2][0] = 2;
            winner[2][1] = 0;
            
            return winner;              
          }
          if((this.gamePanelDatas[0][1] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[2][1] == actualP)){
            winner[0][0] = 0;
            winner[0][1] = 1;
            
            winner[1][0] = 1;
            winner[1][1] = 1;
            
            winner[2][0] = 2;
            winner[2][1] = 1;
            
            return winner;              
          }
          if((this.gamePanelDatas[0][2] == actualP) && (this.gamePanelDatas[1][2] == actualP) && (this.gamePanelDatas[2][2] == actualP)){
            winner[0][0] = 0;
            winner[0][1] = 2;
            
            winner[1][0] = 1;
            winner[1][1] = 2;
            
            winner[2][0] = 2;
            winner[2][1] = 2;
            
            return winner;              
          }                           
          /* Vertical END */
          
          /* Diagonal BEGIN */
          if((this.gamePanelDatas[0][0] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[2][2] == actualP)){
            winner[0][0] = 0;
            winner[0][1] = 0;
            
            winner[1][0] = 1;
            winner[1][1] = 1;
            
            winner[2][0] = 2;
            winner[2][1] = 2;
            
            return winner;              
          }
          if((this.gamePanelDatas[0][2] == actualP) && (this.gamePanelDatas[1][1] == actualP) && (this.gamePanelDatas[2][0] == actualP)){
            winner[0][0] = 0;
            winner[0][1] = 2;
            
            winner[1][0] = 1;
            winner[1][1] = 1;
            
            winner[2][0] = 2;
            winner[2][1] = 0;
            
            return winner;              
          }                          
          /* Diagonal END */
          
        };
        
        
        
        this.recalculateGraphicDatas = function() {
        
            var min_width = 0;
      
            if($jq(window).height() > $jq(window).width()){
                min_width = $jq(window).width();
            }
            else{
                min_width = $jq(window).height() - $jq('div#header').height();
            }

            /* Noch mindestens 10px abstand zum nächsten Screen Ende */
            min_width = min_width-40;

            var box_width = parseInt(min_width/3);

            if(box_width > 110){
                box_width = 110;
            }   

            for(var boxnr1 = 0; boxnr1 < this.gamePanelDatas.length; boxnr1++){
                for(var boxnr2 = 0; boxnr2 < this.gamePanelDatas[boxnr1].length; boxnr2++){
                    $jq('div#div_box_' + (boxnr1+1) + '_' + (boxnr2+1)).css({'height':box_width+'px'});
                    $jq('div#div_box_' + (boxnr1+1) + '_' + (boxnr2+1)).css({'width':box_width+'px'});
                    $jq('img#box_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('width',box_width);
                    $jq('img#box_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('height',box_width);
                    
                }
            }        
            
            //refresh
            this.refresh();
        };
        
        this.refresh = function() {
            // Hier werden nur die Box Bilder verändert
            for(var boxnr1 = 0; boxnr1 < this.gamePanelDatas.length; boxnr1++){
                for(var boxnr2 = 0; boxnr2 < this.gamePanelDatas[boxnr1].length; boxnr2++){
                  //alert(this.gamePanelDatas[boxnr1][boxnr2] + ' ' + boxnr1 + ' ' +boxnr2);
                    if (this.gamePanelDatas[boxnr1][boxnr2] == -1) {
                        $jq('img#box_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('src','images/box_open' + extTriviaImgSuffix[extTriviaType] + extPlayerImgNameSuffix[this.actualPlayer] +'.png');
                    }
                    else if (this.gamePanelDatas[boxnr1][boxnr2] == PLAYER1) {
                        $jq('img#box_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('src','images/box_player_0_marked.png');
                    }
                    else if (this.gamePanelDatas[boxnr1][boxnr2] == PLAYER2) {
                        $jq('img#box_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('src','images/box_player_1_marked.png');
                    }
                }
            }
        };

        this.countDownQuestion = function () {
            //alert(this.countdown_counter);
            if (this.countdown_counter > 0) {
                this.points_to_win = parseInt(this.points_to_win - (this.points_to_win / 4));

                // Counter runterzaehlen
                this.countdown_counter--;
                var count_time = '' + this.countdown_counter;
                if (this.countdown_counter < 10) {
                    count_time = '0' + count_time;
                }
                $jq('#time_counter').text('00:' + count_time);
                $jq('#points_to_win').text(this.points_to_win);
                $jq('#player_points').text(this.score[this.actualPlayer]);
            }
            else {
                refTictactoeQuestionThread.setShutdownState(true);
                this.checkAnswer(-1);
            }
        };
        
        this.removeClassesFromButton = function(){
          for(var btn_counter = 1 ; btn_counter <= 4; btn_counter++){
            $jq('#'+ btn_counter).removeClass('vnx_button_red');
            $jq('#'+ btn_counter).removeClass('vnx_button_green');
            $jq('#'+ btn_counter).removeClass('vnx_button_inactive');
            $jq('#'+ btn_counter).removeClass('vnx_button_blue');
            $jq('#'+ btn_counter).removeClass('vnx_button_orange');
          }
        };
        
        // Gets the Amount of Empty Boxes - used for calculating winning points
        this.getAmountOfEmptyBoxes = function(){
          var counter_boxes = 0;
          for(var boxnr1 = 0; boxnr1 < this.gamePanelDatas.length; boxnr1++){
            for(var boxnr2 = 0; boxnr2 < this.gamePanelDatas[boxnr1].length; boxnr2++){
              if(this.gamePanelDatas[boxnr1][boxnr2] == -1){
                counter_boxes++;
              }
            }
          }
          return counter_boxes;  
        };
        
        // Checks which Answer was pressed and if the Result is correct
        this.checkAnswer = function (answer_id) {
            var left_time = 0;
            // is player in time to give an answer 
            if (!answer_given) {
                answer_given = true;
                if ((this.countdown_counter > 0) && (answer_id > 0)) {
                    // Stop Countdown and reset Timer var
                    refTictactoeQuestionThread.setShutdownState(true);
                    left_time = this.countdown_counter;

                    this.countdown_counter = 10;

                    // Alle klassen auf Button entfernen
                    this.removeClassesFromButton();

                    if ($jq('#' + answer_id).attr('data-is-correct') == "true") {
                        $jq('#' + answer_id).addClass('vnx_button_green');

                        for (var btn_counter = 1; btn_counter <= 4; btn_counter++) {
                            if (btn_counter != parseInt(answer_id)) {
                                $jq('#' + btn_counter).addClass('vnx_button_inactive');
                            }
                        }

                        // Punkte bei Player 2 nur addieren wenn nicht Computer ist
                        if (this.actual_player == PLAYER1) {
                            this.score[PLAYER1] = this.score[PLAYER1] + parseInt(this.points_to_win * left_time);
                        }
                        if (this.actual_player == PLAYER2) {
                            if (extNrPlayer == 1) {
                                this.score[PLAYER2] = this.score[PLAYER2] + parseInt(this.points_to_win * left_time);
                            }
                            else {
                                this.score[PLAYER1] = this.score[PLAYER1] + parseInt(this.points_to_win * left_time);
                            }
                        }
                        // Game Update
                        this.updateGameStatus(true);
                    }
                    // Falsche Antwort
                    else {
                        $jq('#' + answer_id).addClass('vnx_button_red');

                        for (var btn_counter = 1; btn_counter <= 4; btn_counter++) {
                            if (btn_counter != parseInt(answer_id)) {
                                if ($jq('#' + btn_counter).attr('data-is-correct') == "true") {
                                    $jq('#' + btn_counter).addClass('vnx_button_green');
                                }
                                else {
                                    $jq('#' + btn_counter).addClass('vnx_button_inactive');
                                }
                            }
                        }

                        // Game Update
                        this.updateGameStatus(false);
                    }
                }
                // nicht geantwortet
                else {
                    this.removeClassesFromButton();
                    for (var btn_counter = 1; btn_counter <= 4; btn_counter++) {
                        $jq('#' + btn_counter).addClass('vnx_button_red');
                    }
                    // Game Update
                    this.updateGameStatus(false);
                }
            }
            if (this.isTie()) {
                window.setTimeout("transitionToTieScreen()", 1000);
            }
            if (this.getWinner() > -1) {
                window.setTimeout("transitionToTicTacToeWinner()", 1000);
            }
            else {
                this.changePlayer();
                this.refresh();
                this.points_to_win = this.points_per_question;
                if (refTictactoeGame.showInstructions[refTictactoeGame.actualPlayer]) {
                    // change page to instruction
                    window.setTimeout("transitionToInstructions()", 1000);

                }
                else {
                    //change page to question
                    window.setTimeout("transitionToTicTacToe()", 1000);
                }
            }

        }; 
        
        this.updateGameStatus = function(isAnswerCorrect){
          var tempPlayer = -1;
          
          if(isAnswerCorrect){
             if (extNrPlayer == 0) {
              //Spieler<->Computer
              if(this.actualPlayer == PLAYER1){
                tempPlayer = PLAYER1;
              }  
              if(this.actualPlayer == PLAYER2){
                tempPlayer = PLAYER1;
              }
            }
            else if (extNrPlayer == 1) { 
              //Spieler<->Spieler
              tempPlayer = this.actualPlayer; 
            }
          }
          else{
            if (extNrPlayer == 0) {
              //Spieler<->Computer
              if(this.actualPlayer == PLAYER1){
                tempPlayer = -1;
              }  
              else{
                tempPlayer = PLAYER2;
              }
            }
            else if (extNrPlayer == 1) { 
              //Spieler<->Spieler
              tempPlayer = -1; 
            } 
          }
          this.gamePanelDatas[this.activeFieldY][this.activeFieldX] = tempPlayer;
        };
        
        this.changePlayer = function(){
          this.actualPlayer = this.getOppositePlayer();  
        };
        
        this.getOppositePlayer = function() {
          if(this.actualPlayer == PLAYER1) {
            return PLAYER2;
          }
          else {
            return PLAYER1;
          }
        };       
        
        
        this.stopQuestionTimerThread = function(){
           if(this.countdown_counter > 0){
            // Stop Countdown and reset Timer var
            refTictactoeQuestionThread.setShutdownState(true);
            this.countdown_counter = 10;
          }
        };
        
        // Zeigt dem Spieler die richtige Antwort an wenn er falsch geantwortet hat
        this.showResult = function(answer_id){
          this.stopQuestionTimerThread();            
        };
        
        
        // Antwortfelder die Spielerfarbe zuweisen
        this.prepareQuestionForPlayer = function(){
          if(this.actualPlayer == PLAYER1){
            for(var btn_counter = 1 ; btn_counter <= 4; btn_counter++){
                  $jq('#'+ btn_counter).addClass('vnx_button_orange');
            }  
          }
          else{
            for(var btn_counter = 1 ; btn_counter <= 4; btn_counter++){
                  $jq('#'+ btn_counter).addClass('vnx_button_blue');
              }  
          }
        };
        
        this.showWinningPlayer = function(){
          var winning_player = this.getWinner();
          var winner_array = new Array(3);
          
          winner_array = this.getWinnerRow(winning_player);
          
          for(var boxnr1 = 0; boxnr1 < this.gamePanelDatas.length; boxnr1++){
                for(var boxnr2 = 0; boxnr2 < this.gamePanelDatas[boxnr1].length; boxnr2++){
                  //alert(this.gamePanelDatas[boxnr1][boxnr2] + ' ' + boxnr1 + ' ' +boxnr2);
                    
                    
                    if(((boxnr1 == winner_array[0][0]) && (boxnr2 == winner_array[0][1])) ||
                       ((boxnr1 == winner_array[1][0]) && (boxnr2 == winner_array[1][1])) ||
                       ((boxnr1 == winner_array[2][0]) && (boxnr2 == winner_array[2][1])) ){
                        $jq('img#box_w_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('src','images/box_player_'+ winning_player +'_marked_winner.png');                       
                    }
                    else if (this.gamePanelDatas[boxnr1][boxnr2] == -1) {
                        $jq('img#box_w_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('src','images/box_5000_points.png');
                    }
                    else if (this.gamePanelDatas[boxnr1][boxnr2] == PLAYER1) {
                        $jq('img#box_w_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('src','images/box_player_0_marked.png');
                    }
                    else if (this.gamePanelDatas[boxnr1][boxnr2] == PLAYER2) {
                        $jq('img#box_w_' + (boxnr1+1) + '_' + (boxnr2+1)).attr('src','images/box_player_1_marked.png');
                    }
                }
            }
          
          
        };
        
        this.isTie = function(){
          for(var boxnr1 = 0; boxnr1 < this.gamePanelDatas.length; boxnr1++){
            for(var boxnr2 = 0; boxnr2 < this.gamePanelDatas[boxnr1].length; boxnr2++){
              if(this.gamePanelDatas[boxnr1][boxnr2] == -1){
                return false;
              }
            }
          }
          return true;
        };
        
        /***********************************************
            CONSTRUCTOR
        ************************************************/

      this.countdown_counter = 10;

      this.points_to_win = 5000;
        
        //vars
        this.actualPlayer = PLAYER1;
        
        this.activeFieldX = 0;
        this.activeFieldY = 0;
        
        this.isInPlay = false;
        
        this.score = new Array(2);
        this.score[PLAYER1] = 0;
        this.score[PLAYER2] = 0;
        
        this.showInstructions = new Array(2);
        this.showInstructions[PLAYER1] = true;
        this.showInstructions[PLAYER2] = true;
        
        this.points_per_question = 5000;
        
        this.gamePanelDatas = new Array(3);
        for (var i = 0; i < this.gamePanelDatas.length; i++) {
            this.gamePanelDatas[i] = new Array(3);
        }
        
        //init events
        
        
        //init
        this.resetGameToStart();
    
    }
