var $chrome = {

    /******* private fields *********/
    
    _version: 1.41,
    _target: 'nbaChromeNav',
    _onBodyDoneTimerId: null,
    _images: {},
    _user: {},
    
    
    /******* private methods ********/
    
    _onBodyDone: function(){
        $chrome._init();
    },
    _init: function(){
        var chr;
        if (document.getElementById(this._target)) {
            chr = document.getElementById(this._target);
        }
        else {
            chr = document.createElement('div');
            var body = document.getElementsByTagName('body')[0];
            body.insertBefore(chr, body.childNodes[0]);
        }
        chr.innerHTML = this._getHTML();
        this._hookHovers();
        if (document.removeEventListener) {
            document.removeEventListener('DOMContentLoaded', this._onBodyDone, false);
        }
        if (this._onBodyDoneTimerId) {
            clearInterval(this._onBodyDoneTimerId);
        }
    },
    _hookHovers: function(){
        // Preload hovers
        this._images.global_off = new Image();
        this._images.global_off.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_global.gif';
        this._images.global_on = new Image();
        this._images.global_on.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_global_hover.gif';
        this._images.dleague_off = new Image();
        this._images.dleague_off.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_dleague.gif';
        this._images.dleague_on = new Image();
        this._images.dleague_on.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_dleague_hover.gif';
        this._images.wnba_off = new Image();
        this._images.wnba_off.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_wnba.gif';
        this._images.wnba_on = new Image();
        this._images.wnba_on.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_wnba_hover.gif';
        this._images.store_off = new Image();
        this._images.store_off.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_store.gif';
        this._images.store_on = new Image();
        this._images.store_on.src = this.getCDN() + '/.element/img/1.0/chrome/chrome_store_hover.gif';
        
        // Hook into the mouse evewnts
        document.$chrome_global.onmouseover = function(){
            document.$chrome_global.src = $chrome._images.global_on.src;
        };
        document.$chrome_global.onmouseout = function(){
            document.$chrome_global.src = $chrome._images.global_off.src;
        };
        document.$chrome_dleague.onmouseover = function(){
            document.$chrome_dleague.src = $chrome._images.dleague_on.src;
        };
        document.$chrome_dleague.onmouseout = function(){
            document.$chrome_dleague.src = $chrome._images.dleague_off.src;
        };
        document.$chrome_wnba.onmouseover = function(){
            document.$chrome_wnba.src = $chrome._images.wnba_on.src;
        };
        document.$chrome_wnba.onmouseout = function(){
            document.$chrome_wnba.src = $chrome._images.wnba_off.src;
        };
        document.$chrome_store.onmouseover = function(){
            document.$chrome_store.src = $chrome._images.store_on.src;
        };
        document.$chrome_store.onmouseout = function(){
            document.$chrome_store.src = $chrome._images.store_off.src;
        };
    },
    
    _getUrl: function(){
        var url = window.location.href.match(/\.element\/js\/global\/1\.0\/chrome\.html/) ? '' : '?url=' + encodeURIComponent(window.location);
        return url;
    },
    
    _getHTML: function(){
        var out = '';
        out += '<div class="ChromeNav">';
        out += '  <div class="ChromeLinks">';
        out += '    <a href="' + this.getNBABaseUrl() + '" target="_top" title="NBA.com Home" class="Logo">' + this.img('/.element/img/1.0/chrome/chrome_nba.gif', 'NBA.com Home', 'class="Logo"') + '</a>';
        out += '    <a href="' + this.getNBABaseUrl() + '/global" target="_top" title="NBA.com Global" class="Logo">' + this.img('/.element/img/1.0/chrome/chrome_global.gif', 'NBA.com Global', 'name="$chrome_global" class="Logo"') + '</a>';
        out += '    <div class="Divider"></div>';
        out += '    <a href="' + this.getNBABaseUrl() + '/dleague" target="_top" title="NBA D-League" class="Logo">' + this.img('/.element/img/1.0/chrome/chrome_dleague.gif', 'NBA D-League', 'name="$chrome_dleague" class="Logo"') + '</a>';
        out += '    <div class="Divider"></div>';
        out += '    <a href="' + this.getWNBABaseUrl() + '" target="_top" title="WNBA.com" class="Logo">' + this.img('/.element/img/1.0/chrome/chrome_wnba.gif', 'WNBA.com Home', 'name="$chrome_wnba" class="Logo"') + '</a>';
        out += '    <div class="Divider"></div>';
        out += '    <a href="' + (this.getSite() == 'nba.com' ? 'http://store.nba.com/home/index.jsp?league=nba' : 'http://store.nba.com/category/index.jsp?categoryId=1398478&league=wnba') + '" target="_top" title="NBA.com Store" class="Logo">' + this.img('/.element/img/1.0/chrome/chrome_store.gif', 'NBA.com Store', 'name="$chrome_store" class="Logo"') + '</a>';
        out += '    <div class="Divider"></div>';
        out += '    <div class="AllAccessBar">';
        out += '      <div class="Logo"><a href="' + (this.getSite() == 'nba.com' ? this.getNBABaseUrl() : this.getWNBABaseUrl()) + '/allaccess" target="_top">' + this.img('/.element/img/1.0/chrome/chrome_aah_logo.gif', 'All-Access') + '</a></div>';
        out += '      <div class="User">' + (this.isUserAuthenticated() ? ('Welcome ' + this.getUserDisplayName()) : ('<a href="' + this.getMSIB() + '/flow/login' + this._getUrl() + '" target="_top">Login</a>')) + '</div>';
        out += '      <div class="Divider"></div>';
        out += '      <div class="Action">' + (this.isUserAuthenticated() ? ('<a href="' + this.getMSIB() + '/flow/logout' + this._getUrl() + '" target="_top">Logout</a>') : ('<a href="' + (this.getSite() == 'nba.com' ? this.getNBABaseUrl() : this.getWNBABaseUrl()) + '/allaccess/about.html" target="_top">Learn More</a>')) + '</div>';
        out += '      <div class="Endcap"></div>';
        out += '    </div>';
        out += '    <div class="Search">';
        out += '      <form method="get" action="' + (this.getSite() == 'nba.com' ? this.getNBABaseUrl() : this.getWNBABaseUrl()) + '/search" target="_top">';
        out += '        <input type="text" name="text" class="Text" />';
        out += '        <input type="image" class="Button" alt="Search" title="Search" src="' + this.getCDN() + '/.element/img/1.0/chrome/chrome_search_btn.gif" />';
        out += '        <input type="hidden" name="hl" value="en" />';
        out += '      </form>';
        out += '    </div>';
        out += '  </div>';
        out += '</div>';
        return out;
    },
    
    
    /******** public fields *********/
    
    getCDN: function(){
        var server = window.location.hostname;
        var secure = window.location.protocol.match(/https/i);
        if (server.match(/webdev|payp1|sasd/i)) {
            return 'http://nbap1wbdprev1.turner.com:81';
        }
        else 
            if (server.match(/ref/i) && !secure) {
                return 'http://nbap1refprev1.turner.com:81';
            }
            else 
                if (secure) {
                    return 'https://s.cdn.turner.com/nba/nba';
                }
                else {
                    return 'http://i.cdn.turner.com/nba/nba';
                }
    },
    getSite: function(){
        var server = window.location.hostname;
        if (server.match(/\.wnba.com$/i)) {
            return 'wnba.com';
        }
        else {
            return 'nba.com';
        }
    },
    getMSIB: function(){
        var server = window.location.hostname;
        //Adding in option for WNBA vs. NBA
        if (server.match(/wnba\.com/i)) {
	        if (server.match(/webdev|payp1/i)) {
	            return 'http://payp1dev1.turner.com:1085/services/msib';
	        }
	        else 
	            if (server.match(/ref|ite/)) {
	                return 'https://aud-ite.wnba.com/services/msib';
	            }
	            else {
	                return 'https://audience.wnba.com/services/msib';
	            }
        } else {
	        if (server.match(/webdev|payp1/i)) {
	            return 'http://payp1dev1.turner.com:1085/services/msib';
	        }
	        else 
	            if (server.match(/ref|ite/)) {
	                return 'https://aud-ite.nba.com/services/msib';
	            }
	            else {
	                return 'https://audience.nba.com/services/msib';
	            }
        }
    },
    getNBABaseUrl: function(){
        var server = window.location.hostname;
        if (server.match(/webdev|payp1/i)) {
            return 'http://nba-webdev-preview.turner.com';
        }
        else 
            if (server.match(/ref|ite/)) {
                return 'http://nba-ref-preview.nba.com';
            }
            else 
                if (server.match(/beta/)) {
                    return 'http://beta.nba.com';
                }
                else {
                    return 'http://www.nba.com';
                }
    },
    getWNBABaseUrl: function(){
        var server = window.location.hostname;
        if (server.match(/webdev|payp1/i)) {
            return 'http://wnba-webdev-preview.turner.com';
        }
        else 
            if (server.match(/ref|ite/)) {
                return 'http://wnba-ref-preview.wnba.com';
            }
            else 
                if (server.match(/beta/)) {
                    return 'http://beta.wnba.com';
                }
                else {
                    return 'http://www.wnba.com';
                }
    },
	getCSS: function(){
        var server = window.location.hostname;
        var secure = window.location.protocol.match(/https/i);
        if (secure) {
            return '/.element/css/1.0/chrome/secure.chrome.css';
        }
        else {
            return '/.element/css/1.0/chrome/chrome.css';
        }
    },
    img: function(src, alt, attributes){
        alt = typeof(alt) != 'undefined' ? alt : '';
        attributes = typeof(attributes) != 'undefined' ? attributes : '';
        return '<img src="' + this.getCDN() + src + '" alt="' + alt + '" ' + attributes + '/>';
    },
    isUserAuthenticated: function(){
        return this._user.TSid && this._user.TSid.match(/^G[\da-f]+-\d+-\d+-\d+$/) && this._user.authid && this._user.displayName ? true : false;
    },
    isUserSecure: function(){
        return this.isUserAuthenticated() && this._user.authpass ? true : false;
    },
    getUserDisplayName: function(){
        return this.isUserAuthenticated() ? this._user.displayName : '';
    },
    /*
     * url = destination
     * n = window name
     * w = width
     * r = resizable
     * h = height
     * t = toolbars (includes address, location, etc.)
     * s = status
     * sc = scroll
     */
    popup: function(url, n, r, w, h, t, s, sc){
        var opts = "";
        opts = "width=" + w + ",height=" + h;
        opts += ",resizable=" + r;
        opts += ",location=" + t + ",toolbars=" + t + ",menubar=" + t + ",titlebar=" + t;
        opts += ",status=" + s;
        opts += ",scrollbars=" + sc;
        var popup = window.open(url, n, opts);
        popup.focus();
        return popup;
    },
    
    
    // initializer
    init: function(){
        if (document.createStyleSheet) {
            document.createStyleSheet(this.getCDN() + this.getCSS());
        }
        else {
            var ss = document.createElement('link');
            ss.rel = 'stylesheet';
            ss.href = this.getCDN() + this.getCSS();
            var head = document.getElementsByTagName('head')[0];
            head.insertBefore(ss, head.childNodes[0]);
        }
        
        var a, c;
        c = document.cookie || '';
        a = c.split('; ');
        for (var i = 0; i < a.length; i++) {
            var k, v;
            try {
                k = a[i].split('=')[0] || null;
                v = a[i].split('=')[1] || null;
                // Check for errantly encoded values in these cookies and decode them
                if (k && k == 'authid') {
                    if (v != decodeURI(v)) {
                        var cookie = k + '=' + decodeURI(v) + '; ' +
                        'expires=Tue, 20 Oct 2009 04:00:00 GMT; path=/; ' +
                        'domain=.' +
                        this.getSite();
                        document.cookie = cookie;
                    }
                }
                if (k && (k == 'TSid' || k == 'authid' || k == 'authpass')) {
                    this._user[k] = v;
                }
                if (k && k == 'AA-Member') {
                    var u = decodeURIComponent(v).split("|");
                    if (u.length >= 3) {
                        this._user.displayName = u[0];
                        this._user.gender = u[1];
                        this._user.age = u[2];
                        this._user.status = u[3];
                    }
                }
                if (k && k == 's_vi') {
                    var svi = encodeURIComponent(v);
                    if (svi && svi[1]) {
                        var exp = new Date();
                        exp.setTime(exp.getTime() + 3600000);
                        var cookie = 'iv_s=' + svi + '; ' +
                        'expires=' +
                        exp.toGMTString() +
                        '; path=/; ' +
                        'domain=.' +
                        this.getSite();
                        document.cookie = cookie;
                    }
                }
            } 
            catch (e) {
            }
        }
        
        if (document.addEventListener) {
            document.addEventListener('DOMContentLoaded', this._onBodyDone, false);
        }
        this._onBodyDoneTimerId = setInterval(function(){
            if (/loaded|complete/.test(document.readyState)) {
                $chrome._onBodyDone();
            }
        }, 50);
    }
};

$chrome.init();

