/*
 * alerts.js 
 * 
 * Copyright 2006 ESPN.com
 * Author: Sujal Shah
 * 
 * This file creates the alerts on the site.
 *
 * 
 */

var ESPNAlertSportChoice="";

if (typeof bytefx == 'undefined')
{
    var bTag = document.createElement('script');
    bTag.src = 'http://scache.espn.go.com/ESPNAlerts/bytefx.js';
    bTag.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(bTag);
}

if (typeof SWFObject == 'undefined')
{
    var cTag = document.createElement('script');
    cTag.src = 'http://scache.espn.go.com/ESPNAlerts/swfobject.js';
    cTag.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(cTag);

}

// Inspired by Scriptaculous's dependency checking

function initESPNAlerts() {
    var scriptNode = document.getElementById("ESPNAlertsScriptTag");
    //alert(scriptNode);
    //alert(scriptNode.src);
    var path = "";
    if (scriptNode.src.match(/ESPNAlerts\.js/))
    {
        var src=scriptNode.src;
        path = src.replace(/ESPNAlerts\.js(\?.*)?$/,'');
        matches = src.match(/[\?&]sport=([\w,]+)\&?/); // supports one sport, for now
        if (matches)
        {
            var sports = matches[1].split(',');
            for (var j=0; j<sports.length; j++)
            {
                var myTag = document.createElement('script');
                myTag.src = path + 'ESPNAlerts-' + sports[j].toUpperCase() + '.js';
                myTag.type = 'text/javascript';
                myTag.id = 'ESPNAlertsSport' + sports[j].toUpperCase();
                document.getElementsByTagName("head")[0].appendChild(myTag);
            }
        }
    }
    
    globalESPNAlerts.initializeAlerts();
}

// This is FIREBUG Lite code from http://www.getfirebug.com/lite.html
if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}
// End Firebug Lite code

if ((typeof Prototype=='undefined') || 
        parseFloat(Prototype.Version.split(".")[0] + "." +
           Prototype.Version.split(".")[1]) < 1.5)
{
    var Class = {
      create: function() {
        return function() {
          this.initialize.apply(this, arguments);
        }
      }
    }
}

var EspnAlerts = Class.create();

EspnAlerts.prototype = {
    initialize: function (){
        /*@cc_on @*/

        /*@if (@_jscript_version >= 5.7)
            this.isIE7 = true
        @elif (@_jscript_version >= 4)
            this.isIEx = true;

        @else @*/

            this.isOther = true;

        /*@end @*/

    },
    "mCookieName": "ESPN_AlertsSlider",
    "isIE7": false,
    "isIEx": false,
    "isOther": false,
    "currentAnimationId": null,
    "mGapLimit": 900, // in seconds
    "mSoundSwf": "http://scache.espn.go.com/ESPNAlerts/MobileESPNSound.swf",
    "mGameData": {
    },
    "mLastEventTime": 0,
    checkIfUserHasAccess: function () {
        var cookie = this.Get_Cookie("alerts_testing");
        return true;
        if (cookie != null)
        {
            return true;
        } else {
            return false;
        }
    },
    getAlertToShow: function() {
        var cookieVal = this.Get_Cookie(this.mCookieName);
        if(this.mGameData == null || this.mGameData.length <= 0)
        {
            return null;
        }
    
        unsortedGames = this.mGameData;

        if (cookieVal != null)
        {
            // select a game to pop off
            // eventually want to queue them up and play out over
            // time
        
            var cookiePieces = cookieVal.split(":");
            if (cookiePieces != null && cookiePieces.length == 2)
            {
                var lastSeenEventTime = Number(cookiePieces[0]);
                if (lastSeenEventTime < this.mLastEventTime)
                {
                    console.info(lastSeenEventTime);
                    var stateHash = new Array();
            
                    var cookieStates = cookiePieces[1].split(",");
                    var prefix = this.generateGameIdPrefix();
            
                    for (var state in cookieStates)
                    {
                        if(cookieStates.hasOwnProperty(state))
                        {
                            var cookieState = new String(cookieStates[state]);
                            var theSportGameId = prefix + cookieState.substring(0,6);
                            var theState = cookieState.substring(6);
                            stateHash[theSportGameId] = theState;
                        }
                    }

                    for (var gameId in unsortedGames)
                    {
                        if (unsortedGames.hasOwnProperty(gameId))
                        {
                            console.info(gameId);
                            console.info("this.mGameData[gameId].eventTime: " + this.mGameData[gameId].eventTime );//+ "\nlastSeenEventTime: " + lastSeenEventTime + "\n" + this.mGameData[gameId].eventCode + ":" + stateHash[gameId]);
                            if (this.mGameData[gameId].eventTime > lastSeenEventTime &&
                                this.mGameData[gameId].eventCode != stateHash[gameId])
                            {
                                console.info("found a game: " + gameId);
                                this.saveNewCookie();
                                return gameId;
                            }
                        }
                    }
                
                    this.saveNewCookie();

                    //alert("no games to show!");
                
                }
            }
        
        } else {
        
            // do the default behavior
            var tempDate = new Date();
            var correction = (8*60)-tempDate.getTimezoneOffset();
            var gameDate = new Date(this.mLastEventTime-(correction*60000));
        
            if (gameDate.getTime()-this.mLastEventTime > (this.mGapLimit*1000))
            {
                for (gameId in unsortedGames)
                {
                    if (unsortedGames.hasOwnProperty(gameId))
                    {
                        if (unsortedGames[gameId].eventTime == this.mLastEventTime)
                            return gameId;
                    }
                }
            } else {
                //alert("no games to show!");
            }

            this.saveNewCookie();
        
        }

        return null;
    }, 
    generateGameIdPrefix: function()
    {
        var tempDate = new Date();
        var correction = (8*60)-tempDate.getTimezoneOffset() + 180; // correct until 3AM PT

        var gameDate = new Date(this.mLastEventTime-(correction*60000));

        var gameIdPrefix = "" + (gameDate.getFullYear() - 1980) + 
                ((gameDate.getMonth()+1) < 10 ? "0" + (gameDate.getMonth()+1) : (gameDate.getMonth()+1)) + 
                (gameDate.getDate() < 10 ? "0" + gameDate.getDate() : gameDate.getDate()); 
        return gameIdPrefix;
    },    
    popToast: function(gameId) {
    
        var gameObj = this.mGameData[gameId];
   
        if (gameObj != null)
        {
            var height = 0;
            var useFixed = true;
            if (typeof( window.innerHeight ) == 'number')
                height = window.innerHeight;
            else if (document.documentElement || document.documentElement.clientHeight) {
                height = document.documentElement.clientHeight;
            } else if (document.body.clientHeight)
                height = document.body.clientHeight;

            if (this.isIE7 || this.isOther)
            {
                // good browsers
                useFixed = true;
            } else {
                // bad browser
                useFixed = false;
                if( typeof( window.pageYOffset ) == 'number' ) {
                    //Netscape compliant
                    height += window.pageYOffset;
                } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
                    //DOM compliant
                    height += document.body.scrollTop;
                } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
                    //IE6 standards compliant mode
                    height += document.documentElement.scrollTop;
                }
            }
            var container = document.createElement("div");
            container.id = "ESPNAlerts" + this.mGameData[gameId].eventTime;
            container.style.height = "130px";
            container.style.width = "225px";
            container.style.background = "url(http://scache.espn.go.com/ESPNAlerts/ESPN_alert_bkg.png)";
            container.style.position = (useFixed == true ? "fixed" : "absolute");
            container.style.left = "-225px";
            container.style.top = (height-100-130) + "px";
            container.style.fontFamily = "Verdana, Helvetica, sans-serif";

            var awayTeamField = document.createElement("div");
            awayTeamField.style.position = "absolute";
            awayTeamField.style.color = "#FFFFFF";
            awayTeamField.style.top = "26px";
            awayTeamField.style.left = "15px";
            awayTeamField.style.fontSize = "13px";
            awayTeamField.style.height = "15px";
            awayTeamField.style.lineHeight = "15px";
            awayTeamField.style.width = "50px";
            awayTeamField.innerHTML = gameObj.awayTeam;

            var awayScoreField = document.createElement("div");
            awayScoreField.style.position = "absolute";
            awayScoreField.style.color = "#FFFFFF";
            awayScoreField.style.top = "26px";
            awayScoreField.style.left = "70px";
            awayScoreField.style.fontSize = "13px";
            awayScoreField.style.height = "15px";
            awayScoreField.style.lineHeight = "15px";
            awayScoreField.style.width = "25px";
            awayScoreField.innerHTML = gameObj.awayScore;

            var homeTeamField = document.createElement("div");
            homeTeamField.style.position = "absolute";
            homeTeamField.style.color = "#FFFFFF";
            homeTeamField.style.top = "46px";
            homeTeamField.style.left = "15px";
            homeTeamField.style.fontSize = "13px";
            homeTeamField.style.height = "15px";
            homeTeamField.style.lineHeight = "15px";
            homeTeamField.style.width = "50px";
            //homeTeamField.style.border = "1px solid #FFF";
            homeTeamField.innerHTML = gameObj.homeTeam;

            var homeScoreField = document.createElement("div");
            homeScoreField.style.position = "absolute";
            homeScoreField.style.color = "#FFFFFF";
            homeScoreField.style.top = "46px";
            homeScoreField.style.left = "70px";
            homeScoreField.style.fontSize = "13px";
            homeScoreField.style.height = "15px";
            homeScoreField.style.lineHeight = "15px";
            homeScoreField.style.width = "25px";
            homeScoreField.innerHTML = gameObj.homeScore;

            var linksField = document.createElement("div");
            linksField.style.position = "absolute";
            linksField.style.color = "#ffde00";
            linksField.style.top = "29px"; 
            linksField.style.left = "100px";
            linksField.style.fontSize = "10px";
            linksField.style.height = "15px";
            linksField.style.lineHeight = "12px";
            linksField.style.width = "110px";
            linksField.style.overflow = "hidden";
            linksField.innerHTML = '<a style="font-size: 10px; color: #ffde00;" href="http://scores.espn.go.com/' + gameId.substring(gameId.length-3).toLowerCase() + '/boxscore?gameId=' +
             gameObj.gameId + '">Boxscore</a> - <a style="font-size: 10px; color: #ffde00;" href="http://scores.espn.go.com/' + gameId.substring(gameId.length-3).toLowerCase() + '/scoreboard">Scores</a>';

            var gameStatusField = document.createElement("div");
            gameStatusField.style.position = "absolute";
            gameStatusField.style.color = "#FFFFFF";
            gameStatusField.style.top = "49px"; 
            gameStatusField.style.left = "100px";
            gameStatusField.style.fontSize = "10px";
            gameStatusField.style.height = "15px";
            gameStatusField.style.lineHeight = "12px";
            gameStatusField.style.width = "110px";
            gameStatusField.style.overflow = "hidden";
            gameStatusField.innerHTML = gameObj.gameStatus;

            var lastPlayField = document.createElement("div");
            lastPlayField.style.position = "absolute";
            lastPlayField.style.color = "#FFFFFF";
            lastPlayField.style.top = "66px";
            lastPlayField.style.left = "15px";
            lastPlayField.style.fontSize = "9px";
            lastPlayField.style.height = "60px";
            lastPlayField.style.lineHeight = "15px";
            lastPlayField.style.overflow = "hidden";
            lastPlayField.style.width = "90%";
            if (gameObj.lastPlayText == null || gameObj.lastPlayText.length == 0)
            {
                lastPlayField.innerHTML = "";
            } else {
                lastPlayField.innerHTML = "<b>Last Score</b>: " + gameObj.lastPlayText + '<br/>';
            }


            var soundField = document.createElement("div");
            soundField.id = container.id + "soundBox";
            soundField.style.visibility = "hidden";
            soundField.style.position = "absolute";
            soundField.style.color = "#FFFFFF";
            soundField.style.top = "30px";
            soundField.style.left = "125px";
       
            var AlertsSOB = new SWFObject(this.mSoundSwf, container.id + "soundSwf", 1, 1, 8, "transparent");
            soundField.innerHTML = AlertsSOB.getSWFHTML();
        
            container.appendChild(awayTeamField);
            container.appendChild(awayScoreField);
            container.appendChild(homeTeamField);
            container.appendChild(homeScoreField);
            container.appendChild(linksField);
            container.appendChild(gameStatusField);
            container.appendChild(lastPlayField);
            container.appendChild(soundField);

            document.body.appendChild(container);
       
            bytefx.move(container, {x:0, y:(height-100-130)}, 10, function(){ 
                setTimeout('bytefx.move(document.getElementById("' + container.id + '"), {x:-225, y:'+(height-100-130)+'}, 10,function () { document.body.removeChild(document.getElementById("' + container.id + '"));});', 5000); 
                });
        }
    },
    Get_Cookie: function(name) { 
       var start = document.cookie.indexOf(name+"="); 
       var len = start+name.length+1; 
       if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
       if (start == -1) return null; 
       var end = document.cookie.indexOf(";",len); 
       if (end == -1) end = document.cookie.length; 
       return unescape(document.cookie.substring(len,end)); 
    },
    Set_Cookie: function(name, value, expires, path, domain, secure) {
       document.cookie= name + "=" + escape(value) +
           ((expires) ? "; expires=" + expires.toGMTString() : "") +
           ((path) ? "; path=" + path : "") +
           ((domain) ? "; domain=" + domain : "") +
           ((secure) ? "; secure" : "");
    },
    showPendingAlerts: function ()
    {
        if (this.checkIfUserHasAccess())
        {
            var alertGameId = this.getAlertToShow();
            if (alertGameId != null)
            {
                this.popToast(alertGameId);
            }
        }
    },
    saveNewCookie: function()
    {   
        //alert("saving cookie");
        var newCookieValue = this.mLastEventTime + ":";
        for (var i in this.mGameData)
        {
            onegame = String(i);
            newCookieValue += (onegame.substring(onegame.length-6) + this.mGameData[i].eventCode + ",");
        }

        newCookieValue = newCookieValue.substring(0, newCookieValue.length-1);
        this.Set_Cookie(this.mCookieName, newCookieValue, null, "/"); //, null, "/ESPNAlerts", "scache.espn.go.com");

    },
    initializeAlerts: function()
    {
        var timeoutToPop = Math.round(Math.random()*3000)+2000;
    
        setTimeout("globalESPNAlerts.showPendingAlerts();", timeoutToPop);
    }
}

var globalESPNAlerts = new EspnAlerts();
//Event.observe(window, 'load', globalESPNAlerts.initializeAlerts.bindAsEventListener(globalESPNAlerts), false);

if (window.addEventListener) {
    window.addEventListener('load', initESPNAlerts, false);
} else {
    window.attachEvent('onload', initESPNAlerts, false);
}

