﻿

function createTicTacToeGame(gameManager, _connection, msgDisplay) {
    return new TicTacToeGame(gameManager, _connection, msgDisplay);
}

function TicTacToeGame(gameManager, _connection, msgDisplay) {
    this.objectId = generateID("TicTacToe");
    this.connection = _connection;
    this.displayPanel = msgDisplay;
    this.yourTurn = false;
    this.board = [0, 0, 0, 0, 0, 0, 0, 0 ,0];
    this.sessionId = "";
    this.started = false;
    this.name = "Tic Tac Toe";
    this.gameType = "TicTacToe";
    this.gameManager = gameManager;
    
    _connection.messageListeners.addListener(new MessageListener("game", this.gameType, this.handleMessages, this));
    _connection.connected.addListener(TTT_handleConnected, this);
    _connection.discussionChanged.addListener(TTT_handleDiscussionChanged, this);
    window[this.objectId] = this;
}


TicTacToeGame.prototype = {
    //start:TTT_start,
    handleMessages: TTT_handleMessages,
    handleConnected:TTT_handleConnected,
    handleDiscussionChanged: TTT_handleDiscussionChanged,
    showGame: TTT_showGame,
    initGame: TTT_initGame
}

//function TTT_start() {
//    if (!this.started) {
//        var str = "<game type='"+this.gameType+"' status='start'/>"
//        this.connection.postMessage(str);
//    }
//}

function TTT_handleMessages(sender, msg, targetObj) {
    if (typeof (msg.session) != "undefined") {
        targetObj.sessionId = msg.session;
    }

//    if (msg.status == "requesting" ) {
//        targetObj.displayPanel.writeHtml("Stranger has invited you to play TicTacToe. <a class='DisplayMessageLine_GameNotifLink' href='javascript:acceptRequest(\"" + targetObj.objectId + "\")'>Accept</a> or <a class='DisplayMessageLine_GameNotifLink' href='javascript:rejectRequest(\"" + targetObj.objectId + "\")'>Reject</a>", "DisplayMessageLine_GameNotif", false);
//    }

//    if (msg.status == "requesting-wait") {
//        targetObj.displayPanel.writeHtml("Waiting for stranger to accept TicaTacToe invitation. <a class='DisplayMessageLine_GameNotifLink' href='javascript:cancelRequest(\"" + targetObj.objectId + "\")'>Cancel invitation</a>", "DisplayMessageLine_GameNotif", false);
//    }

//    if (msg.status == "accepted") {
//        targetObj.displayPanel.writeHtml("Stranger has accepted the TicaTacToe invitation.", "DisplayMessageLine_GameNotif");
//        this.started = true;
//    }

//    if (msg.status == "rejected") {
//        targetObj.displayPanel.writeHtml("Stranger has rejected the TicaTacToe invitation.", "DisplayMessageLine_GameNotif");
//        this.started = false;
//    }

    if (msg.status == "running" || msg.status == "gameover") {
        if (msg.status == "gameover") {
            targetObj.displayPanel.writeHtml(msg.txt, "DisplayMessageLine_GameNotif");
        }
        
        if (typeof (msg.playerTurn) != "undefined") {
            if (msg.playerTurn == targetObj.connection.userId) {
                targetObj.displayPanel.writeHtml("Your turn!", "DisplayMessageLine_GameNotif");
                this.yourTurn = true;
            } else {
                targetObj.displayPanel.writeHtml("Stranger turn!", "DisplayMessageLine_GameNotif");
                this.yourTurn = false;
            }
        }

        if (typeof (msg.cell) != "undefined" && typeof (msg.mark) != "undefined") {
            var cellImg = $("ttt_cell_" + msg.cell);
            cellImg.src = "images/tictactoe/" + msg.mark + ".gif";
        }
        if (typeof (msg.winLine) != "undefined") {
            if (msg.winLine.match("^r[123]")) {
                drawWinLineRow(parseInt(msg.winLine.charAt(1)));
            } else if (msg.winLine.match("^c[123]")) {
            drawWinLineColumn(parseInt(msg.winLine.charAt(1)));
            } else if (msg.winLine.match("^d[12]")) {
            drawWinLineDiagonal(parseInt(msg.winLine.charAt(1)));
            }
        }
    }
}

function TTT_checkCell(gameid, cellIndex) {
    var _this = window[gameid];
    if (cellIndex >= 0 && cellIndex < 9) {
        if (_this.board[cellIndex] == 0) {
            // post message
            var strMsg = "<game type='" + _this.gameType + "' session = '" + _this.sessionId + "' cell='" + cellIndex + "' />";
            _this.connection.postMessage(strMsg);
        } else {
        alert("Cell already checked!");
        }
    } else {
        alert("Invalid cell!");
    }
}

function drawWinLineRow(rowIndex) {
    var rowLine = $("ttt_WinRowLine");
    var x = 60;
    var ys = [188, 120, 54];

    setPosTopLeft(rowLine, ys[rowIndex - 1], x);
    rowLine.style.display = "inline";
}

function drawWinLineColumn(colIndex) {
    var colLine = $("ttt_WinColLine");
    var y = 28;
    var xs = [90, 157, 224];

    setPosTopLeft(colLine, y, xs[colIndex - 1]);
    colLine.style.display = "inline";
}

function drawWinLineDiagonal(diagIndex) {
    if (diagIndex == 1) {
        var diag = $("ttt_WinDiagLine1");
        setPosTopLeft(diag, 30, 61);
        diag.style.display = "inline";
    }else
    if (diagIndex == 2) {
        var diag = $("ttt_WinDiagLine2");
        setPosTopLeft(diag, 30, 61);
        diag.style.display = "inline";
    }
}



function TTT_handleConnected() {
}

function TTT_handleDiscussionChanged() {
}

function TTT_initGame() {
    for (var i = 0; i < 9; i++) {
        var img = $("ttt_cell_" + i);
        img.src = "images/tictactoe/point.gif";
    }
    
    $("ttt_WinRowLine").style.display = "none";
    $("ttt_WinColLine").style.display = "none";
    $("ttt_WinDiagLine1").style.display = "none";
    $("ttt_WinDiagLine2").style.display = "none";
    
}

function TTT_showGame(pnlGamePanel) {
//    g_TicTacToe = new TicTacToeGame(con, g_dispMsg);
    var tttid = this.objectId;
    var gmid = this.gameManager.objectId;
//    var pnlGamePanel = $("divGamePanel");

    var html = '<div id="pnlTicTacToePanel" style="top:10px; left=0px;width:100%;height:100%; position: absolute; ">'
    + '<table style="width: 200px; height: 200px; empty-cells: show; margin-right: auto; margin-left: auto; margin-top: 30px; background-color:White;z-index:900;" cellpadding="0" cellspacing="0">'
    + '<tr>'
    + '<td align="center" valign="middle" style="border-right-style: solid; border-bottom-style: solid; border-right-width: 2px; border-bottom-width: 2px; border-color: #000000">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',6)"><img id="ttt_cell_6" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '<td align="center" style="border-right-style: solid; border-bottom-style: solid; border-right-width: 2px; border-bottom-width: 2px; border-color: #000000" valign="middle">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',7)"><img id="ttt_cell_7" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '<td align="center" valign="middle" style="border-bottom-style: solid; border-bottom-width: 2px; border-color: #000000">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',8)"><img id="ttt_cell_8" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '</tr>'
    + '<tr>'
    + '<td align="center" valign="middle" style="border-right-style: solid; border-bottom-style: solid; border-right-width: 2px; border-bottom-width: 2px; border-color: #000000">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',3)"><img id="ttt_cell_3" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '<td align="center" valign="middle" style="border-right-style: solid; border-bottom-style: solid; border-right-width: 2px; border-bottom-width: 2px; border-color: #000000">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',4)"><img id="ttt_cell_4" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '<td align="center" valign="middle" style="border-bottom-style: solid; border-bottom-width: 2px; border-color: #000000">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',5)"><img id="ttt_cell_5" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '</tr>'
    + '<tr>'
    + '<td align="center" valign="middle" style="border-right-style: solid; border-right-width: 2px; border-color: #000000">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',0)"><img id="ttt_cell_0" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '<td align="center" valign="middle" style="border-right-style: solid; border-right-width: 2px; border-color: #000000">'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',1)"><img id="ttt_cell_1" alt="" src="images/tictactoe/point.gif" border="0" />'
    + '</a>'
    + '</td>'
    + '<td align="center" valign="middle" >'

    + '<a onclick="noPrompt()" href="javascript:TTT_checkCell(\'' + tttid + '\',2)"><img id="ttt_cell_2" alt="" src="images/tictactoe/point.gif" border="0" /></a>'
    + '</td>'
    + '</tr>'
    + '</table>'
    + '<br /><br /><input id="btnStartTTT" type="button" value="Start TicTacToe" onclick="startTTT(\'' + gmid + '\')"/>'
    + '<img id="ttt_WinRowLine" style="top:50px; left=13px; position: absolute; display:none; z-index:999;" src= "images/tictactoe/ttt_hbar.gif" />'
    + '<img id="ttt_WinColLine" style="top:0px; left=0px; position: absolute; display:none; z-index:999;" src= "images/tictactoe/ttt_vbar.gif" />'
    + '<img id="ttt_WinDiagLine1" style="top:0px; left=0px; position: absolute; display:none; z-index:999;" src= "images/tictactoe/ttt_diagbar1.gif" />'
    + '<img id="ttt_WinDiagLine2" style="top:0px; left=0px; position: absolute; display:none; z-index:999;" src= "images/tictactoe/ttt_diagbar2.gif" />'

    + '</div>';

    pnlGamePanel.innerHTML = html;
}

function startTTT(gmid) {
    var gm = window[gmid];
    if (gm != null) {
        gm.requestStartGame("TicTacToe");
    } else {
        alert("error: Game Manager not found");
    }
}
