﻿var StandardGameSchema = "http://www.SimpleConnexion.com/games/1.0";
var g_GameManagerID = null;


function gameManager() {
    this.objectId = g_GameManagerID = generateID("GameManager");
    window[this.objectId] = this;
    this.connection = null;
    this.gameSessionID = null;
    this.currentGame = null;
    this.displayPanel = null;
    this.gameRegistry = new Hashmap();
}

gameManager.prototype = {
    handleGameMsg: GM_handleGameMsg,
    handleConnected:GM_handleConnected,
    handleDiscussionChanged: GM_handleDiscussionChanged,
    startGame: GM_requestStartGame,
    openGame: GM_openGame,
    initGame: GM_initGame,
    register: GM_Register,
    init:function(_connection, msgDisplay) {
        this.connection = _connection;
        this.displayPanel = msgDisplay;
        this.connection.messageListeners.addListener(new MessageListener("msg2", "*", "*", StandardGameSchema, this.handleGameMsg, this));
        this.connection.connected.addListener(this.handleConnected, this);
        this.connection.discussionChanged.addListener(this.handleDiscussionChanged, this);
    }
}

var g_GameManager = new gameManager();

//function getGameBrowserHtml(objid){
//    var html = '<div id="divCardWard" >' //style="position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;" >'
//           + '<div><a onclick="noPrompt()" href="javascript:GM_openGame(\''+objid+'\', \'CardWar\')">Card war</a></div>'
//           + '<div><a onclick="noPrompt()" href="javascript:GM_openGame(\'' + objid + '\', \'TicTacToe\')">Tic Tac Toe</a></div>'
//           + '</div>';
//    return html;
// }

 function GM_handleGameMsg(sender, msg, targetObj) {
     if ( targetObj.gameSessionID == null) {
         if(msg.type == "notify" && typeof (msg.properties.gamesessionid) != "undefined"){
            targetObj.gameSessionID = msg.properties.gamesessionid;
         }else if(typeof (msg.gamesessionid) != "undefined"){
            targetObj.gameSessionID = msg.gamesessionid;
         }
     }

     if (targetObj.currentGame == null) {
         
         if (msg.type == "notify" && msg.command == "start") {
             if (typeof(msg.properties.requestApproval) != "undefined" && msg.properties.requestApproval == "1" ) {
                 targetObj.displayPanel.writeHtml("Stranger has invited you to play '" + msg.properties.gameName + "'. <a onclick='noPrompt()' class='DisplayMessageLine_GameNotifLink' href='javascript:GM_acceptRequest(\"" + targetObj.objectId + "\",\"" + msg.properties.game + "\")'>Accept</a> or <a onclick='noPrompt()' class='DisplayMessageLine_GameNotifLink' href='javascript:GM_rejectRequest(\"" + targetObj.objectId + "\",\"" + msg.properties.game + "\")'>Reject</a>", "DisplayMessageLine_GameNotif", false);
             }else if (typeof(msg.properties.accepted) != "undefined" && msg.properties.accepted == "auto") {
                targetObj.currentGame = targetObj.gameRegistry.getValueByKey(msg.properties.game)(targetObj, targetObj.connection, targetObj.displayPanel);
                targetObj.currentGame.initGame();
             }
         }
     }

     if (targetObj.currentGame != null) {
         var game = targetObj.currentGame;
         if (msg.type == "response" && msg.command == "start") {
             if(typeof(msg.properties.waitingApproval) != "undefined" && msg.properties.waitingApproval == "1"){
                 targetObj.displayPanel.writeHtml("Waiting for stranger to accept '" + msg.properties.gameName + "' invitation. <a onclick='noPrompt()' class='DisplayMessageLine_GameNotifLink' href='javascript:GM_cancelRequest(\"" + game.objectId + "\")'>Cancel invitation</a>", "DisplayMessageLine_GameNotif", false);
             }else
             if (typeof(msg.properties.accepted) != "undefined" ) {
                if(msg.properties.accepted == "1"){
                    targetObj.displayPanel.writeHtml("Stranger has accepted the '" + msg.properties.gameName + "' invitation.", "DisplayMessageLine_GameNotif");
                }
                 game.initGame();
             }
          }
          
         if (msg.type == "notify" && msg.command == "acceptstart") {
            if (typeof(msg.properties.accepted) != "undefined"){
                if(msg.properties.accepted == "1") {
                     targetObj.displayPanel.writeHtml("Stranger has accepted the '" + msg.properties.gameName + "' invitation.", "DisplayMessageLine_GameNotif");
                     game.initGame();
                 }else if(msg.properties.accepted == "0") {
                     targetObj.displayPanel.writeHtml("Stranger has rejected the '" + msg.properties.gameName + "'. invitation.", "DisplayMessageLine_GameNotif");
                     game.closeGame();
                     targetObj.currentGame = null;
                 }
            }
         }

         if (msg.type == "notify" && msg.command == "end") {
                 targetObj.displayPanel.writeHtml("Stranger has ended game '" + msg.properties.gameName + "'.", "DisplayMessageLine_GameNotif");
                 game.closeGame();
                 targetObj.currentGame = null;
         }
     }
 }
 
 function GM_handleConnected(){
 }

 function GM_handleDiscussionChanged() {
 }

 function GM_openGame(objid, gameType) {
     var gmObj = window[objid];
     if (gmObj != null) {
         var pnlGamePanel = $("divGamePanel");
         gmObj.currentGame = gmObj.gameRegistry[gameType](gmObj, gmObj.connection, gmObj.displayPanel);
         gmObj.currentGame.showGame(pnlGamePanel);
     }
 }

 function GM_initGame(objid) {
     var gmObj = this;
     if (typeof objid != "undefined") {
         gmObj = window[objid]; 
     }
      
     if (gmObj != null && gmObj.currentGame != null) {
         gmObj.currentGame.initGame();
     }
 }

 function GM_acceptRequest(gmid, gameSchema) {
     var gmObj = window[gmid];
     var sessionid = gmObj.gameSessionID;
     GM_openGame(gmid, gameSchema);
     GM_initGame(gmid);
    var m = createAcceptStartGameMessage(this.connection.nextMessageID(), gameSchema, sessionid, "1");
    gmObj.connection.postMessageObject(m);
    gmObj.currentGame.started = true;
 }

 function GM_rejectRequest(gmid, gameSchema) {
     var gmObj = window[gmid];
     var sessionid = gmObj.gameSessionID;
    var m = createAcceptStartGameMessage(this.connection.nextMessageID(), gameSchema, sessionid, "0");
    gmObj.connection.postMessageObject(m);
     gmObj.gameSessionID = null;
     if (gmObj.currentGame != null) {
         gmObj.currentGame.started = false;
         gmObj.currentGame = null;
     }
 }

 function GM_cancelRequest(id) {
     var obj = window[id];
     if (confirm("Are you sure you want to quit game?")) {
        var m = createEndGameMessage(this.connection.nextMessageID(), obj.currentGame.gameSchema, obj.gameSessionID);
        gmObj.connection.postMessageObject(m);
     }
 }

 function GM_requestStartGame(gameSchema) {
     if (this.connection.discussionStatus == 0) {
         alert("You are not connected to any person.\nPlease start a discussion in order to play.");
         return;
     }
     if (this.currentGame != null && this.currentGame.started) {
         alert("You are already playing. To start a new game you must end the current one first.");
         return;
     }
     
     if (this.currentGame == null) {
        this.currentGame = this.gameRegistry.getValueByKey(gameSchema)(this, this.connection, this.displayPanel);
        var m = createStartGameMessage(this.connection.nextMessageID(), gameSchema);
        this.connection.postMessageObject(m);
    }
}

function GM_Register(gameSchema, factoryFunc, obj) {
    this.gameRegistry.set(gameSchema, factoryFunc, obj);
}

function GM_Unregister(gameSchema) {
    this.gameRegistry.remove(gameSchema);
}


// this is the base of all games
// it should be inherited by calling __extendBaseGame(this) in the constructor of your game object
// ex:
// function YouGame(){
//    __extendBaseGame(this, optionalInitialPrototype);
//    ....
// }

function __extendBaseGame(childObject, _proto){
    var p = childObject;
    if(typeof(_proto) != "undefined"){
        p.prototype = _proto;
    }
    
    while(p.prototype != null){
        p = p.prototype;
    }
    p.prototype =  new baseGame();
}

function baseGame(){
}

baseGame.prototype = {
    __ID : "baseGame.prototype",
    initGame:function(){
    },
    openGame:function(){
    },
    closeGame:function(){
    },
    startGame:function(){
    }
}
