﻿var Arcade = {
    openGame: null,
    openGameScore: null,
    isLoggedIn: null,
    currentStartGame: null,
    currentGameId: null,
    currentGameActive: null,
    Swf: null,
    LinkHref: null,
    LinkText: null,
    PathsXml: null,
    LoadPath: null,

    init: function() {
        var hash = location.hash;
        hash = hash.replace(/#gameid=/, "");

        if ($.cookie("showgame") != undefined && $.cookie("showgame") != "") {
            hash = $.cookie("showgame");
            $.cookie("showgame", null, { path: '/' });
        }

        var gameid = Arcade.getGameId(hash);

        //$.cookie('islock', true);
        var showPostGame = $.cookie("showPostGame") != undefined && $.cookie("showPostGame") != "";
        // alert(gameid + " " + location.hash);       
        if (!showPostGame) {
            Arcade.show(Arcade.currentStartGame);
        }
        else {
            var temp = $.cookie("showPostGame").split("_");
            var id = escape(temp[0]);
            Arcade.openGameScore = escape(temp[1]);
            Arcade.openGame = Arcade.getGameName(id);

            Arcade.show(Arcade.openGame, true);
            $.cookie('showPostGame', null, { path: '/' });
        }
        //Arcade.initSlider();
        //$(document).bind('keydown', Arcade.captureKeys);
    },

    redirectDeepLink: function() {
        var hash = location.hash;
        var url = "";
        hash = hash.replace(/#gameid=/, "");
        if (hash != "") {

            var names = {
                "NumberMix": "number-mix",
                "Squirrel": "squirrel-spotter",
                "Astral": "astral-attack",
                "WarriorsMatch": "warriors-match",
                "WarriorsAnagram": "warriors-anagrams",
                "WarriorsConnection": "warriors-connection",
                "Anagram": "anagram-scramble",
                "MollyMoon": "molly-moon-morphing-mystery-match",
                "Cosmic": "cosmic-connect",
                "PowerMatch": "power-match"
            };

            for (var n in names) {
                if (n == hash) {
                    redirect = names[n];
                }
            }

            if (redirect != "") {
                //alert("/freegames/" + redirect);
                window.location = "/freegames/" + redirect;
            }
        }
    },

    captureKeys: function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code > 36 && code < 41) {
            e.preventDefault();
        }
    },

    isLocked: function(gameid) {
        $.cookie('showgame', null, { path: '/' });
        //for (var i in Arcade.locked) {
        //if (parseInt(Arcade.locked[i]) == gameid) {

        //}
        if (Arcade.currentGameActive != "1") {
            $.cookie("showgame", Arcade.getGameName(gameid));
            $.cookie('scoreToSave', null, { path: '/' });
            $.cookie('showPostGame', null, { path: '/' });
            return true;
        }
        return false;
    },

    show: function(id, isPostGame, clickedBack) {
        var gameid = Arcade.getGameId(id);

        var islock = Arcade.isLocked(gameid) && Arcade.isLoggedIn == 0;

        if (Arcade.openGame == id && isPostGame != true && clickedBack != true)
            return;
        if (islock == true) {
            isPostGame = true;
        }

        // alert("Show:" + id);
        $(".highscores .loading").show();
        $(".highscores iframe").attr("src", "/images/blank.gif");
        $(".highscores iframe").hide();

        Arcade.clearFlash();
        Arcade.openGame = id;

        //window.location = "#gameid=" + id;

        var container = ".gameBlock";

        $(".gameBlock").hide();
        $(".scoreBlock").hide();
        $(".howToBlock").hide();
        $(".swfBlock").hide();

        $(".lock").hide();

        if (isPostGame === true) {

            container = ".scoreBlock";
            $('.carousel_simple').attr('id', 'game' + id + "Score");
            $(container).attr('id', id + "Score");
            Arcade.loadRanking(gameid);
        }
        else {
            $('.carousel_simple').attr('id', 'game' + id);
            $(container).attr('id', id);
        }
        $(container).show();

        $(container + " .game_content").removeClass("logged_in");
        $(container + " .game_content").removeClass("logged_out");
        $(container + " .game_content").removeClass("lock_game");
        $(container + " .game_content").removeClass("unlock_game");

        if (Arcade.isLoggedIn == "1") {
            $(container + " .game_content").addClass("logged_in");
        }
        else {
            $(container + " .game_content").addClass("logged_out");
            if (isPostGame === true) {
                if (islock) {
                    $(container + " .game_content").addClass("lock_game");
                    $(".lock").show();
                    $(".book_link").hide();
                    $(".controls").hide();
                    $(".your_score").hide();
                }
                else {
                    $(container + " .game_content").addClass("unlock_game");
                    $(".your_score").show();
                    $(".book_link").show();
                    $(".controls").show();
                }


            } else {
                $(".book_link").show();
                $(".controls").show();
            }
        }

        // code added to handle additional site link
        if (id == "MollyMoon") {
            $(container + ' .site_link').attr('href', 'http://www.meetmollymoon.com').css('display', 'block');
        } else {
            $(container + ' .site_link').attr('href', '#').css('display', 'none');
        }


        var linkHref = Arcade.LinkHref;
        var linkText = Arcade.LinkText;

        $(container + ' .book_link').attr('href', linkHref);
        $(container + ' .book_link').html(linkText);

        $(container + ' .book_link').attr('href', linkHref);
        $(container + ' .book_link').html(linkText);
        $(container + ' .book_link').click(function(eventObject) {
            try {
                pageTracker._trackPageview('/game/' + Arcade.openGame + '/read_excerpt');
            } catch (err) { }
            window.location = $(this).attr("href");
            return false;
        });

        $(".controls .howto").unbind('click', Arcade.howto);
        $(".controls .howto").click(Arcade.howto);

        $(".controls .play").unbind('click', Arcade.launch);
        $(".controls .play").click(Arcade.launch);

        $(".controls .playAgain").unbind('click', Arcade.launchAgain);
        $(".controls .playAgain").click(Arcade.launchAgain);

        $(".controls .return").unbind('click', Arcade.backToArcade);
        $(".controls .return").click(Arcade.backToArcade);
        $(container + ' .highscores iframe').attr('src', "/scores.aspx?gameid=" + gameid);

    },
    /*show_lock: function(id, isPostGame, isLoggedIn) {
    Arcade.locked = [getGameId]
    Arcade.show(id);

    },*/
    onHighScoreLoad: function() {
        $(".highscores .loading").hide();
        $(".highscores iframe").fadeIn(100);
    },

    howto: function() {
        var id = Arcade.openGame;
        container = ".howToBlock";
        $('.carousel_simple').attr('id', 'game' + id + "Instructions");
        $(container).attr('id', id + "Instructions");
        Arcade.clearFlash();
        $(".gameBlock").attr('id', "");
        //$(".howToBlock").attr('id', Arcade.openGame);
        $(".gameBlock").hide();
        $(".howToBlock").show();


        $(".controls .play").unbind('click', Arcade.launch);
        $(".controls .play").click(Arcade.launch);
        $(".controls .back").unbind('click', Arcade.backToIntro);
        $(".controls .back").click(Arcade.backToIntro);
    },

    backToArcade: function() {
        //Arcade.show(Arcade.openGame, false, true);
        location.href = "/freegames.aspx";
    },

    backToIntro: function() {
        Arcade.show(Arcade.openGame, false, true);
    },

    launchAgain: function() {
        try { pageTracker._trackPageview('/game/' + Arcade.openGame + '/play_again'); } catch (err) { };
        Arcade.launch;
    },

    launch: function(e) {

        e.preventDefault();
        var id = Arcade.openGame;
        Arcade.openGameScore = 0;
        $('.carousel_simple').attr('id', 'game' + id + "Score");
        $(".gameBlock").hide();
        $(".scoreBlock").hide();
        $(".howToBlock").hide();

        //Arcade.clearFlash();

        var gameid = Arcade.getGameId(id);
        $(".swfBlock").show();


        var flashvars = {
            isBrowser: 'true',
            userId: Arcade.isLoggedIn,
            serviceUrl: '/flashgateway.aspx',
            gameId: gameid
        };
        var params = {
            scale: 'noScale',
            menu: 'false',
            allowFullScreen: 'true',
            allowScriptAccess: 'always'
        };

        if (Arcade.LoadPath != undefined && Arcade.LoadPath != "") {
            flashvars.loadPath = Arcade.LoadPath; //used by xml games
            params.base = Arcade.LoadPath;
            //alert("base" + params.base);
        }

        if (Arcade.PathsXml != undefined && Arcade.PathsXml != "") {
            flashvars.pathsXML = Arcade.PathsXml;
        }



        if ($.browser.msie === false) {
            params.wmode = 'transparent';
        }
        //wmode: 'transparent'
        var attributes = { id: 'flash', name: 'flash' };

        var swf = Arcade.Swf;

        Arcade.clearFlash();
        swfobject.embedSWF("/swf/" + swf, "flashGameContent", "760", "380", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);


    },
    clearFlash: function() {
        $(".swfBlock").html("<div id='flashGameContent'></div>");
    },
    initSlider: function() {
        //alert("Init Slider" + Arcade.openGame);
        var flashvars = {
            gameSelect: Arcade.openGame,
            xmlPath: '/data/games.aspx'
        };
        var params = {
            scale: 'noScale',
            menu: 'false',
            allowFullScreen: 'true',
            allowScriptAccess: 'sameDomain',
            wmode: 'transparent'
        };
        var attributes = { id: 'flashSliderObject', name: 'flashSliderObject' };
        swfobject.embedSWF("/swf/slider.swf?v=1.1", "flashSlider", "145", "370", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
    },
    getGameId: function(name) {
        //return Arcade.games[name];
        return Arcade.currentGameId;
    },
    getGameName: function(id) {
        /*var name = null;
        for (var n in Arcade.games) {
        if (Arcade.games[n] == id)
        name = n;
        }
        return name;*/
        return Arcade.currentStartGame;
    },
    loadRanking: function(gameid) {
        var url = "http://" + window.location.host + "/ranking.aspx?gameid=" + gameid + "&rand=" + Math.random() * 1000000000000000;
        //alert(url);
        $(".your_score").html(Arcade.openGameScore);
        if (Arcade.isLoggedIn) {
            //alert(url);
            $.getJSON(url,
            function(data) {
                //alert(data.ranking + " " + data.score);
                $(".your_ranking").html(data.ranking);
                //alert(data.points);
                $("#memberInfo strong").html(data.points);
            });
        }
    },

    updateBonusPoints: function(gameid, userid, sh) {
        var url = "http://" + window.location.host + "/flashgateway.aspx";
        var data = "action=addbonussweeppoint&gameid=" + gameid + "&userid=" + userid + "&sh=" + sh + "&rand=" + Math.random() * 1000000000000000;

        if (Arcade.isLoggedIn) {
            //alert(url);
            $.ajax({
                url: url,
                type: 'POST',
                url: url,
                data: data,
                dataType: 'xml',
                success: function(xml) {
                    //alert(xml);
                    Arcade.loadRanking(gameid);
                }
            });
        }
    },

    trackPageview: function(pageID) {
        try {
            pageTracker._trackPageview(pageID);
        } catch (err) { }
    }

};
