 var ESPN = new function() {

    var current_timestamp = Math.round(new Date().getTime() / 1000);

    $(function() {
        $('#dropdown').parent().hover(
            function() {
                $(this).addClass('hover');
            },
            function() {
                $(this).removeClass('hover');
            }
        );
        
        carousel(
            $('div#summary-carousel'), 
            $('div#summary ul.pagination li.previous a'),
            $('div#summary ul.pagination li.next a'),
            null,
            8,
            true,
            120,
            2,
            true
        );
        
        $('div#summary-carousel ul.slide').css('left', '-960px');
        
        carousel(
            $('div#timeline-carousel'), 
            $('div#timeline ul.pagination li.previous a'),
            $('div#timeline ul.pagination li.next a'),
            null,
            8,
            true,
            120,
            0,
            true
        );

        carousel(
            $('li#video-carousel-viewport'), 
            $('ul#video-carousel li.previous a'),
            $('ul#video-carousel li.next a'),
            $('div#video-carousel-pagination ul'),
            4,
            false,
            140,
            0,
            function() {
                $('li', $(this).parent()).removeClass('summary-active');
                $(this).addClass('summary-active');
                embed_video($(this));
            }
        );    
        
        if ($('#video-player').size() > 0) {
            embed_video($('#video-player'));
        }
        
        if ($('#mp3-player').size() > 0) {
            embed_mp3($('#mp3-player'));
        }        
        
        time_capsules();
        highlight_schedule();
        embed_local_ads();
        
        //grab all external links and add link tracking
        $("a[href*='http://']:not([href*='"+location.hostname+"'])").each(function (i) {
        	if($(this).closest('div').attr('id') == 'nav') {
        		$(this).attr("name","&amp;lpos="+$(this).closest("div").attr("id")+"&amp;lid="+$(this).closest('li').attr('class'));
        	} else {
        		$(this).attr("name","&amp;lpos="+$(this).closest("div").attr("id")+"&amp;lid="+$(this).text().replace(/[\W]/g,"-"));
        	}
        });
        //grab all internal links and add link tracking
        $("a[href^='/']").each(function (i) {
        	if($(this).closest('ul').attr('id') == 'dropdown') {
        		$(this).attr('onclick',"anTrackLink(this, 'espn30for30', '"+$(this).closest("div").attr("id")+"', '"+$(this).text().replace(/[\W]/g,"-")+"')");
        	} else if($(this).closest('div').attr('id') == 'nav') {
        		$(this).attr('onclick',"anTrackLink(this, 'espn30for30', '"+$(this).closest("div").attr("id")+"', '"+$(this).closest('li').attr('class')+"')");
        	} else if($(this).closest('div').attr('id') == 'main-header-left') {
        		$(this).attr('onclick',"anTrackLink(this, 'espn30for30', '"+$(this).closest("div").attr("id")+"', 'home')");
        	} else {
        		$(this).attr('onclick',"anTrackLink(this, 'espn30for30', '"+$(this).closest("div").attr("id")+"', '"+$(this).text().replace(/[\W]/g,"-")+"')");
        	}
        });
        
    });

    // Private
    var time_capsules = function() {
        var capsule = $('#timeline-capsule');
        var open_capsule = function(el) {
            $('div.shade', capsule).css('height', $(document).height());
            capsule.css('height', $(document).height()).show();
            embed_video(el);
            embedded = false;
            return false;
        };
        
        $('#timeline-carousel div.capsule').filter(':not(div.capsule-coming-soon)').hover(
            function() {
                $(this).addClass('capsule-hover');
            },
            function() {
                $(this).removeClass('capsule-hover');
            }
        ).click(function() {
            open_capsule($(this));
            return false;
        });
        
        $('a.close', capsule).click(function() {
            capsule.hide();
            return false;
        });
    };
        
    var embed_mp3 = function(el) {
        var info = parse_info(el);
        var titleSong = info.title.replace(/-/g, " ");
        var attributes = {};
        var flashvars = {
            mp3: info.mp3,
            title: titleSong,
            showvolume: 1,
            loadingcolor: 'cccccc',
            slidercolor1: 'd7d7d7',
            slidercolor2: '999999',
            height: 40,
            width: 260,
            showlist: 1,
            showplaylistnumbers: 0,
            scrollbarcolor: '000000',
            scrollbarovercolor: '000000',
            currentmp3color: 'FFFFFF'       
        };
        var params = {
            wmode: 'transparent', 
            allowfullscreen: true, 
            allowscriptaccess: "always"
        };
        swfobject.embedSWF("/flash/player_mp3_multi.swf", "mp3Player", "260", "40", "9.0.98", "/flash/expressInstall.swf", flashvars, params, attributes);          
    };
    
    var embed_video = function(el) {
        var info = parse_info(el);

        switch (ESPN.EmbedVideoMethod) {
            case 'jw':
                embed_video_jw(info);
            break;
            
            case 'espn':
                embed_video_espn(info);
            break;
        }
        
        // Special case: Tracking for Honda ad video
        if (info.video_id == '4526685') {
            $('body').append('<img src="http://ad.doubleclick.net/ad/N2958.espn.comSD2489/B3941746;sz=1x1;ord='+current_timestamp+'?" style="border:0;width:1px;height:1px" alt="" />');
        }
    };
    
    var embedded = false;
    var embed_video_espn = function(info) {
        if (embedded) {
            com.espn.utils.PlayerCommands.mpfVideoSwitchMedia(info.video_id);
        }
        else {
            var flashvars = {};
            flashvars.autostart = "true"; 
            flashvars.id = info.video_id;
            flashvars.height = "334";
            flashvars.width = "560";
            flashvars.adminOver = "3805638";
            flashvars.cXml = "http://espn.go.com/videohub/mpf/config.prodXml";
            flashvars.player = "30for30_09";
            var params = {};
            params.wmode = "opaque";
            params.allowScriptAccess = "always";
            params.allowFullScreen = "true";
            params.quality = "high";
            params.bgcolor = "#000000";
            var attributes = {};
            swfobject.embedSWF("http://espn.go.com/videohub/mpf/players/design09/player.swf?player=30for30_09", "videoPlayer", "560", "334", "9.0.45", false, flashvars, params, attributes);

            embedded = true;
        }        
    };
    
    var embed_video_jw = function(info) {
        var attributes = {};
        var flashvars = {
            file: info.video, 
            image: info.image,
            bufferlength: 8,
            smoothing: true,
            //stretching: 'fill',
            backcolor: '000000',
            frontcolor: '6c6c6c',
            lightcolor: '6c6c6c',
            screencolor: '000000',
            autostart: true,
            height: 334,
            width: 560            
        };
        var params = {
            wmode: 'opaque', 
            allowfullscreen: true, 
            allowscriptaccess: "always"
        };
        swfobject.embedSWF("/flash/player.swf", "videoPlayer", "560", "334", "9.0.98", "/flash/expressInstall.swf", flashvars, params, attributes);         
    };

    var parse_info = function(el) {
        var classes = el.attr('class').split(' ');
        var info = {};
        
        for (var i=0, length=classes.length; i<length; i++) {
            var split = classes[i].split('=');
            if (split.length != 2) {                
                continue;
            }
            info[split[0]] = split[1];            
        }
        
        return info;
    };

    var carousel = function(container, previous, next, pagination, per_page, use_all_inactive, width, offset, toggle_callback) {
        var internal = $('ul.slide', container);
        var slide_by = per_page * width;
        var summaries = $('li.summary', internal);
        var infos = $('li.info', internal);
        var page = 0;
        var max_page = Math.ceil(summaries.size() / per_page) - 1;
        var slide_duration = 250;
        var toggle_duration = 250;
        var easing = 'swing';
        var current_open = null;
        var wait = false;
        
        var open = function(summary) {   
            if (wait) {
                return false;
            }            

            var func = function() {            
                summary.removeClass('summary-inactive');   
                summary.addClass('summary-active');                
                current_open = summary;
                
                var info = current_open.next();                
                if (!info.hasClass('info')) {
                    center();
                    return;
                }
                
                wait = true;
                info.addClass('info-active'); 
            
                center(function() {
                    info.animate({width: 360}, toggle_duration, easing, function() {
                        wait = false;
                    });                    
                });                
            };
         
            if (current_open) {
                close(func);
            }
            else {
                func();
            }
        };
        
        var close = function(callback) {
            if (wait || !current_open) {
                return false;
            }            

            var summary = current_open;
            summary.removeClass('summary-active');
            
            var info = current_open.next();                
            current_open = null;            
            if (!info.hasClass('info')) {            
                if (callback) {
                    callback();
                }
                return;
            }            
            
            wait = true;            
            info.removeClass('info-active');
            info.animate({width: 0}, toggle_duration, easing, function() {
                wait = false;                
                if (callback) {
                    callback();
                }    
                if (page == max_page) {
                    change_page();
                }  
            });                      
        };
        
        var all_inactive = function(state) {        
            if (state) {
                summaries.addClass('summary-inactive');
            }
            else {
                summaries.removeClass('summary-inactive');
            }
        };
        
        var change_page = function() {
            close();
            all_inactive(false);
            wait = true;
            
            if (offset > 0) {
                page = offset;
                offset = 0;
            }
            
            var slide_to = page * slide_by * -1;
            if (page == max_page && page != 0) {
                slide_to += width * ((max_page + 1) * per_page - summaries.length);
            }
            
            internal.animate({'left': slide_to}, slide_duration, easing, function() {
                wait = false;
            });            

            if (pagination) {
                $('li', pagination).removeClass('active');            
                $('a[href=page-'+(page+1)+']', pagination).parent().addClass('active');
            }
            
            if (page < max_page) {
                if (!next.hasClass('active')) {
                    next.addClass('active');
                }
            }
            else {
                next.removeClass('active');
            }

            if (page > 0) {
                if (!previous.hasClass('active')) {
                    previous.addClass('active');
                }
            }
            else {
                previous.removeClass('active');
            }
            
                     
        };
        
        var center = function(callback) {
            var index = current_open.attr('class').match(/index-(\d{1,2})/)[1];
            var left = (index - 1) * width * -1 + width * 2;
            
            if (index == 1 || index == 2) { 
                left = 0;
            }
            else if (index == summaries.length) {
                left = (summaries.length - per_page) * width * -1;
            }
            else if (index == summaries.length-1) {
                left += width * (summaries.length - index);
            }
            
            wait = true;
            internal.animate({'left': left}, slide_duration, easing, function() {
                wait = false;
                if (callback) {
                    callback();
                }
            });          
        };
        
        previous.click(function() {
            if (wait || page <= 0) {
                return false;
            }            

            page--;
            change_page();
            
            return false;
        });
        
        next.click(function() {
            if (wait || page >= max_page) {
                return false;
            }

            page++;
            change_page();
            
            return false;
        });
        
        summaries.click(function() {          
            if (typeof(toggle_callback) == 'function') {
                toggle_callback.apply(this);
                return true;
            }
            
            if ($(this).hasClass('summary-coming-soon')) {
                return false;
            }
            
            if (current_open && current_open[0] == this) {
                close();
                all_inactive(false);
            }
            else {
                all_inactive(true);
                open($(this));
            }
        });
        
        if (pagination) {
            $('a', pagination).click(function() {
                var selected_page = $(this).attr('href').split('-')[1] - 1;
                page = selected_page;
                change_page();                
                return false;
            });
        }
        
        summaries.filter(':not(li.summary-coming-soon)').hover(
            function() {
                $(this).addClass('summary-hover');
            }, 
            function() {
                $(this).removeClass('summary-hover');
            }
        );
        
        $('a.close', infos).click(function() {
            close();
            change_page();
            
            return false;
        });
        
        change_page();
    };

    
    var highlight_schedule = function() {
        $('#schedule div.showing').each( function(i) {
            var li = $('li.film', this);
            var start_time = li.attr('schedule_start_time');
            if (start_time) {
                if (start_time < current_timestamp) {
                    $(this).addClass('showing-past');
                }
                else if (start_time < current_timestamp + 604800) {
                    $(this).addClass('showing-upcoming');
                }
            }
        });
        
        // Home page; limit to 3
        var display_count = 0;
        $('#tune-in li').each( function(i) {
            var li = $(this);
            var start_time = li.attr('schedule_start_time');
            if (start_time) {
                if (start_time > current_timestamp) {
                    li.css('display', 'inline');
                    display_count++;
                    if (display_count == 3) {
                        return false;
                    }
                }
            }
        });
        
        
        // Remove past airings from film schedule
        var film_count = 0;
        $('.film-intro-schedule').each( function(i) {
            var film = $(this);
            var start_time = film.attr('schedule_start_time');
            if (start_time) {
                if (start_time < current_timestamp) {
                    film.css('display', 'none');
                }
                else {
                    film_count++;
                    if ($('#video-wrapper').is('.coming-soon') && film_count > 3) {
                        film.css('display', 'none');
                    }
                    else if (film_count > 2) {
                        film.css('display', 'none');
                    }
                }
            }
        });
    };
    
    var embed_local_ads = function() {
        $('.local-ad').each( function(i) {
            $(this).attr('id', $(this).parent().attr('id')+'-local-ad');
            var width = $(this).parent().width();
            var height = $(this).parent().height();
            var attributes = {};
            var flashvars = {};
            var params = {
                wmode: 'opaque', 
                quality: 'high'
            };
            swfobject.embedSWF("/flash/09080183IB1_3_EOE_"+width+"x"+height+".swf", $(this).attr('id'), width, height, "9.0.28", "/flash/expressInstall.swf", flashvars, params, attributes);
        });
    };
    
    // Public

    this.EmbedMethod = null;

    return this;
}();



//************************************
// MPF Player Observer
//************************************
// This code is used to listen for player
// events coming back into the page so that
// the page can handle appropriately.
//------------------------------------

var counter = 0;

function enableAutoStart(){
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". AutoStart Enabled";
}

function disableAutoStart(){
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". AutoStart Disabled";
}
function onVideoComplete(id)
{
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". This video is done: "+id;
}
function onVideoPlaylistEnded()
{
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". This video is done and any ads are complete.";
}

function onCommandsLoaded()
{
	document.getElementById("textChange").innerHTML += "<br />Registering event...";
	com.espn.utils.PlayerCommands.registerObserver("video_init_complete",com.espn.utils.PlayerCommands.INIT_COMPLETE,onPlayerInit);
	com.espn.utils.PlayerCommands.registerObserver("video_playlist_finished",com.espn.utils.PlayerCommands.VIDEO_PLAYLIST_ENDED,onVideoPlaylistEnded);
	com.espn.utils.PlayerCommands.registerObserver("video_player_ready",com.espn.utils.PlayerCommands.VIDEO_PLAYER_READY,onReady);
	com.espn.utils.PlayerCommands.registerObserver("video_complete",com.espn.utils.PlayerCommands.VIDEO_COMPLETE,onVideoComplete);
	com.espn.utils.PlayerCommands.registerObserver("video_ad_start",com.espn.utils.PlayerCommands.AD_START,onAdStart);
	com.espn.utils.PlayerCommands.registerObserver("video_ad_complete",com.espn.utils.PlayerCommands.AD_COMPLETE,onAdComplete);
	com.espn.utils.PlayerCommands.registerObserver("enable_autostart",com.espn.utils.PlayerCommands.ENABLE_AUTOSTART,onEnableAutoStart);
	com.espn.utils.PlayerCommands.registerObserver("disable_autostart",com.espn.utils.PlayerCommands.DISABLE_AUTOSTART,onDisableAutoStart);
	com.espn.utils.PlayerCommands.registerObserver("video_play",com.espn.utils.PlayerCommands.VIDEO_PLAY,onPlay);
	com.espn.utils.PlayerCommands.registerObserver("video_pause",com.espn.utils.PlayerCommands.VIDEO_PAUSE,onPause);
	com.espn.utils.PlayerCommands.registerObserver("video_stop",com.espn.utils.PlayerCommands.VIDEO_STOP,onStop);
	com.espn.utils.PlayerCommands.registerObserver("video_menu_on",com.espn.utils.PlayerCommands.WIDGET_ON,onMenuOn);
	com.espn.utils.PlayerCommands.registerObserver("video_menu_off",com.espn.utils.PlayerCommands.WIDGET_OFF,onMenuOff);
	document.getElementById("textChange").innerHTML += "<br />Event registered...";
}

function onPlayerInit(){
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". Player Initialized";
}

function onAdComplete()
{
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". Ad is complete";
}

function onAdStart(duration)
{
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". Ad started. Length: " + duration;
}
function onReady(){
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". Player Ready";
}
function onEnableAutoStart(){
	document.getElementById("autoStartState").innerHTML += "<br />" + ++counter + ". AutoStart Enabled";
}

function onDisableAutoStart(){
	document.getElementById("autoStartState").innerHTML += "<br />" + ++counter + ". AutoStart Disabled";
}

function onPlay(){
	document.getElementById("textCh").innerHTML += "<br />" + ++counter + ". PLAY";
}
function onPause(){
	document.getElementById("textCh").innerHTML += "<br />" + ++counter + ". PAUSE";
}
function onStop(){
	document.getElementById("textCh").innerHTML += "<br />" + ++counter + ". STOP";
}

function onMenuOn()
{
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". Menu On";
}
function onMenuOff()
{
	document.getElementById("textChange").innerHTML += "<br />" + ++counter + ". Menu Off";
}

//------------------------------------
// End Observer
//************************************

