// Receive the scores from the flash game and send to the server
//
function flash_game_DoFSCommand(command, args) {
    switch (command) {
    case "score_event":
        var score = Number(args.split(",")[1]);
        currentGame.handleScore(score);
        break;
    }
}


// Handles all javascript functionality for each ZuiGame
//
function ZuiGame(gameId, swfUrl, authToken, inClient, kidzui_download_url) {

    var gameContainer = "flash_game";
    var scoreContainer = "scoreboard";
    
    var options = {
        defaultWidth: "550",
        defaultHeight: "400",
        defaultFlashVersion: "8.0.0",
        installSwfPath: "/swfs/expressInstall.swf",

        gameParams: {
            name: gameContainer,
            allowScriptAccess: 'always',
            bgcolor: 'FFFFFF'
        }
    };


    function initialize() {
        swfobject.embedSWF(
            swfUrl,
            gameContainer,
            options.defaultWidth,
            options.defaultHeight,
            options.defaultFlashVersion,
            options.installSwfPath,
            {},
            options.gameParams,
            { id: gameContainer }
        );

        if(inClient) { swffit.fit(gameContainer, options.defaultWidth, options.defaultHeight); }
    }

    function hideGame() {
        $(gameContainer).hide();
    }

    function hideScore() {
        if(inClient) { 
            $(scoreContainer).hide();
        };
    }
    
    function displayMembershipMessage() {
        var membershipMessageElt = $('membership_message');
        if(membershipMessageElt == null) {
            var elt = $$('#game_container h2')[0];
            var message = 'You must play on <a href="' + kidzui_download_url + '">KidZui</a> to have your score recorded. Get <a href="' + kidzui_download_url + '">KidZui</a> or <a href="http://www.kidzui.com/product">learn more</a>.';
            var membershipMessageElt = new Element('p', { 'id': 'membership_message'}).update(message);
            elt.insert({after: membershipMessageElt});
        }
    }

    function displayScore() {
    	hideGame();
		$(scoreContainer).show();
    }
    
    function saveScore(score) {
        new Ajax.Request('/games/'+gameId+'/scores', {
            asynchronous:true,
            evalScripts:true,
            method:'post',
            parameters:'authenticity_token=' + encodeURIComponent(authToken) + '&score=' + score
        });
    }

    this.handleScore = function(score) {
        if(inClient) {
            saveScore(score);
            displayScore();
        }
        else {
            displayMembershipMessage();
        };
    };
    
    this.restart = function() {
        hideScore();
        $(gameContainer).show();
    };

    initialize();
}


