var mrssData; //in order to use this js, the page need to provide var mrss
var fullDataPassed = false;
//var metric25Passed = false;
//var metric50Passed = false;
//var metric75Passed = false;
var metricCompletePassed = false;
var timeCounter = 0;
var longformDesignatorTime = 1200; //Defines whether a video is longform or not.  If a video is over this amount, then the video is LF, otherwise it's SF
var longformTimeCount = 180; //Defines the time interval to fire off to Omniture for LF-based content
var shortformTimeCount = 60; //Defines the time intervale to fire off to Omniture for SF-based content
var lastSystemTime = 0;
var currentSystemTime = 0;
var actualSeconds = 0;

var VideoPlayer = {
    playlistPosition: -1,
    playlist: new Array()
};

var videoh5player;

var playerName;

function init() {
    videoh5player = $('#vidplayer')[0];
    //addEventListeners(videoh5player);
    VideoPlayer.playlist = parseEncrypedMrss(mrssData);

    var href, media_type = $('#content > div.media-wrap').attr('id') == 'media-audio' ? 'audio' : 'video';
    var related_media_type = $('#content > div.media-wrap').attr('id') == 'media-audio' ? 'video' : 'audio';

    setControls();
    if (HISTORY.videoPlayer.isTdih === false) {
        playerName = '644x402';
        var thumbs = $('ul.media-thumbs li.' + media_type + ' a.thumb');
        //unbind any event handler first before bind to the video player function. hoverModals doesn't apply on ipad        
        thumbs.unbind();
        thumbs.removeClass("thumb").addClass("thumbVideoh5");
        thumbs.bind('click', function (e) {
            e.preventDefault();
            var split_char = (this.href.indexOf('#') != -1) ? '#' : '/';
            href = this.href.split(split_char);
            loadVideoBySlugName(href[href.length - 1]);
        });

        var related_thumbs = $('ul.media-thumbs li.' + related_media_type + ' a.thumb');
        related_thumbs.bind('click', function(e) {
            document.location = this.href;
        });

        if (document.location.toString().indexOf('#') != -1) {
            var splits = document.location.toString().split('#');
            loadVideoBySlugName(splits[1]);
        } else
           loadVideoByIndex(0);
        
    } else {
        playerName = '480x300';
        loadVideoByIndex(1);
    }

    $('#videowrapper').bind('aetn_lib_videoplayer_html5_ad_init', function(e, data) {
        adManager = data.adManager;
        $(videoh5player).unbind('ended');
        $(videoh5player).bind('play.preRollAd', function() {
            $(videoh5player).unbind('play.preRollAd');
            if (!adManager.isAdPlaying()) {
                adManager.requestAd('preroll');
            }

        });


        $('#videowrapper').bind('aetn_lib_videoplayer_html5_ad_complete', function() {

            if (HISTORY.videoPlayer.isTdih === false) {
                $('#ad-box').css("z-index", "-10");
            }
            $(videoh5player).bind('ended', function() {
                videoCompleted()
            });
        });

        videoh5player.controls = true;
        videoh5player.play();
    });

    $(videoh5player).bind('ended', function() {

        videoCompleted()
    });
}

function parseEncrypedMrss(encryptedData) {
    //populate the videoList array with data from mrss feed
    var mrss = urlDecode(decodeBase64(encryptedData));
    return parseMrss(mrss);
}

function parseMrss(clearText) {
    var item;
    var count = 0;
    var videoList = new Array();
    var xmlDoc;
    var parser;

    // Mozilla and Netscape browsers
    if (document.implementation.createDocument) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(clearText, "text/xml");
    }
    // MSIE
    else if (window.ActiveXObject) {
        parser = new ActiveXObject("Microsoft.XMLDOM");
        parser.async = "false";
        xmlDoc = parser.loadXML(clearText);
    }

    while (item = xmlDoc.getElementsByTagName("item")[count]) {
        var title = item.getElementsByTagName("title")[0].childNodes[0].nodeValue;
        var description;
        if (item.getElementsByTagName("description")[0].childNodes[0] !== undefined)
            description = item.getElementsByTagName("description")[0].childNodes[0].nodeValue;
        var category = item.getElementsByTagName("category")[0].childNodes[0].nodeValue;
        var guid = item.getElementsByTagName("guid")[0].childNodes[0].nodeValue;
        var slug = item.getElementsByTagName("category")[0].childNodes[0].nodeValue;
        var thumbnails = item.getElementsByTagName("thumbnail");
        var thumbnailSmall = thumbnails[0].attributes.getNamedItem("url").value;
        var thumbnailStill = thumbnails[1].attributes.getNamedItem("url").value;
        var duration = item.getElementsByTagName("content")[0].getAttribute("duration");
        var videoData = new Object;

        videoData.clipTitle = title;
        videoData.clipCategory = category;
        videoData.duration = duration;

        var mediaText = item.getElementsByTagName('text')[1].childNodes[0].nodeValue;
        var vData = mediaText.split("&");

        for (var i = 0; i < vData.length; i++) {

            var vItem = vData[i];
            var itemArray = vItem.split("=");
            var itemKey = itemArray[0];
            var itemValue = itemArray[1];

            switch (itemKey) {
                case "prop27" :
                    videoData.isShow = itemValue;
                    break;

                case "siteName":
                    videoData.siteName = itemValue;
                    break;

                case "zone1":
                    videoData.zone1 = itemValue;
                    break;

                case "zone2":
                    videoData.zone2 = itemValue;
            }
        }

        var m3uPath = item.getElementsByTagName('text')[7].childNodes[0].nodeValue;

        if (m3uPath.length > 0) {
            m3uPath = m3uPath.substring("m3uUrl=".length);
        }

        //for future use with freewheel
        var cuePoints = item.getElementsByTagName('text')[6].childNodes[0].nodeValue;
        if (cuePoints.length > 0)
            cuePoints = cuePoints.substring("cuePoints=".length);

        var platformId = item.getElementsByTagName('text')[8].childNodes[0].nodeValue;
        var adSiteName = item.getElementsByTagName('text')[1].childNodes[0].nodeValue;
        var freewheelServer = item.getElementsByTagName('text')[9].childNodes[0].nodeValue;
        var freewheelNetworkId = parseInt(item.getElementsByTagName('text')[10].childNodes[0].nodeValue);
        var freewheelProfileId = item.getElementsByTagName('text')[11].childNodes[0].nodeValue;
        var freewheelAdManager = item.getElementsByTagName('text')[12].childNodes[0].nodeValue;

        adSiteName = adSiteName.substring(adSiteName.indexOf("=") + 1, adSiteName.indexOf("&"));
        platformId = platformId.substring(platformId.indexOf("=") + 1);

        videoList[count] = {'title':title,'description':description,
            'slug':slug,
            'thumbnailpath': thumbnailStill,
            'thumbnailsmall': thumbnailSmall,
            'duration': secondsToMS(duration),
            'durationInSeconds': duration,
            'guid': guid,
            'm3uPath': m3uPath,
            'videoData': videoData,
            'cuepoints':'',
            'platformId': platformId,
            'adSiteName': adSiteName,
            'freewheelServer': freewheelServer,
            'freewheelNetworkId': freewheelNetworkId,
            'freewheelProfileId': freewheelProfileId,
            'freewheelAdManager': freewheelAdManager
        };

        count += 1;
    }

    return videoList;
}


function loadNextVideo() {
    loadVideoByIndex(VideoPlayer.playlistPosition + 1, false);
}

function loadVideoIncremental(change) {
    if (videoh5player.style.display == 'none')
        loadVideoByIndex(VideoPlayer.playlistPosition + change);
}

function loadVideoBySlugName(slug) {
    for (var i = 0; i < VideoPlayer.playlist.length; i++) {
        if (VideoPlayer.playlist[i].slug == slug) {
            loadVideoByIndex(i);
            break;
        }
    }
}

function loadVideoByIndex(index) {
    $('#replayornext').css('opacity', 0);
    if (videoh5player.style.display == "none")
        videoh5player.style.display = "block";
    VideoPlayer.playlistPosition = index;
    if (VideoPlayer.playlist[VideoPlayer.playlistPosition]) {
        var m3uPath = VideoPlayer.playlist[VideoPlayer.playlistPosition].m3uPath;
        // get signed url to access mpx
        var token = m3uPath.substring("http://link.theplatform.com/s/".length, m3uPath.indexOf("?"));
        $.get('/components/get-signed-signature?url=' + token, function(data) {
            m3uPath += "&sig=" + data;
            addEventListeners(videoh5player);            
            videoh5player.src = m3uPath;
            videoh5player.poster = VideoPlayer.playlist[index].thumbnailpath;

            //before load video,
            //diable control first
            videoh5player.controls = false;
            //initialize freewheel adManager
            aetn.lib.videoplayer.HTML5.advertising.init($('#videowrapper'),
            {assetId : VideoPlayer.playlist[VideoPlayer.playlistPosition].platformId,    //platformid
                duration : VideoPlayer.playlist[VideoPlayer.playlistPosition].durationInSeconds,  //duration in seconds
                midRoll : []
            }, {
                freewheel : { // Freewheel Settings
                    'jsUrl' : VideoPlayer.playlist[index].freewheelAdManager,
                    'serverUrl' : VideoPlayer.playlist[index].freewheelServer,
                    'networkId' : VideoPlayer.playlist[index].freewheelNetworkId,
                    'profileId' : VideoPlayer.playlist[index].freewheelProfileId,
                    'siteSectionId' : VideoPlayer.playlist[VideoPlayer.playlistPosition].adSiteName,  //to change to siteName
                    'adKeys' : []
                },
                'companionBanners' : {
                    '728x90' :  {
                        id: 'top-leaderboard',  // divID for the companion banner
                        settings : 'ptgt=s&envp=g_js&slau=728x90&w=728&h=90'},
                    '300x250' : { id: 'ad-box', settings : 'ptgt=s&envp=g_js&slau=300x250&w=300&h=250&cd=300,250|300,600'}
                }
            });


            videoh5player.load();


            if (HISTORY.videoPlayer.isTdih === false) {
                $('#ad-box').css("z-index", "10");
                updateContainer();
                updateThumb();
            }

        });

    }
}


/* control gui */
function setControls() {
    var pos = $("#vidplayer").position();

    $("#replayornext").css('top', pos.top);
    $("#replayornext").css('left', pos.left);
    $("#replayornext").css('min-width', $("#vidplayer").width());
    $("#replayornext").css('min-height', $("#vidplayer").height());
    $("#replayornext").css('opacity', 0);
}


function updateContainer() {
    $('div.controller > h4')[0].innerHTML = VideoPlayer.playlist[VideoPlayer.playlistPosition].title + '<span>(' + VideoPlayer.playlist[VideoPlayer.playlistPosition].duration + ')</span>';
    $('div.controller > div.copy').empty();
    $('div.controller > h4').after('<div class="copy"><p>' + VideoPlayer.playlist[VideoPlayer.playlistPosition].description + '</p></div>');
    if ($('#ad-box')[0] == undefined)
        $('div.controller > div.copy').after('<div id="ad-box"></div>');

}

function updateThumb() {
    var thumbs_lists = $('ul.media-thumbs');

    if (thumbs_lists.length > 0) {

        // Find the item that corresponds to the slug.
        var target = $('a.thumbVideoh5[href*="' + VideoPlayer.playlist[VideoPlayer.playlistPosition].slug + '"]', thumbs_lists).parent();
        // Remove the playing indicator from the old playing item.
        $('li.playing', thumbs_lists).removeClass('playing');

        // Indicate that the target is playing and if it's inside a collapsed box, show it.
        target.addClass('playing');

        if (target.hasClass('truncated-video')) {
            $('#truncated-video').show();
        }

        // Update the URL hash.
        window.location.hash = VideoPlayer.playlist[VideoPlayer.playlistPosition].slug;
    }
}

/* event listener on the player */
function addEventListeners(player) {
 
    player.addEventListener('timeupdate', function(e) {
        var passData = false; // Used to prevent double-fires
        var videoData = VideoPlayer.playlist[VideoPlayer.playlistPosition].videoData;

        //the omniture codes go here;
        var timePassed = parseInt(player.currentTime); // Gets the currentTime of the video for each update
        var percentDuration = parseInt(( (timePassed / player.duration) * 100 )); // What percent we're at in the video.

        // Check if we've hit the number of seconds to track, and if so, fire a beacon.
        timeCounter ++;
        var secondsPast = 0;

        secondsPast = CheckAgainstSystemTimer();
        actualSeconds = actualSeconds + secondsPast;

        // Start video event capture
        if (timePassed == 1 && !fullDataPassed) {
            // At 1 second, we're now going to do a fullDataPass to Omniture.  This includes both MRSS-based and Player-based information.
            // Set callType (identifies which data call. Not passed to Omniture.  Used for debug purposes only.)
            videoData.callType = "1 second Video Start Data";

            // Set player / page / call specific Omniture data
            videoData.playerName = player.width + "x" + player.height; //Player name is specified by "playerWidthXplayerHeight"
            videoData.chapterNumber = 0; //  Kept for reference only at the moment.  We're not doing LF at the moment with Cue points.
            videoData.playlistPosition = "1"; // Put in here where the video is in the playlist.
            videoData.autoStarted = "Non Auto-Start"; // Allowed values: "Auto-Start" or "Non Auto-Start"
            videoData.videoType = "HTML5";  // New variable capture just for HTML5 video
            videoData.deviceType = "iPad/iPhone"; //New variable capture just for HTML5 video.  Should we change player detection to include others, we should put that in here.
            videoData.events = "event33"; //Start event ,change from 31 to 33 on 2/16/11

            if (player.duration > longformDesignatorTime) {
                videoData.length = "Longform";
            }
            else {
                videoData.length = "Shortform";
            }

            //Prevents double fire.  Sometimes timePassed gives two '1' events.
            fullDataPassed = true;

            //Tells us that we're good to pass data.  Probably not really needed.
            passData = true;
        }


        if (percentDuration >= 98 && !metricCompletePassed) {
            videoData.callType = "Video Complete Data (98% mark)";
            videoData.events = "event37"; //Complete mark (98% = complete), changed to event37 based on new spec.

            //Prevents double fire.
            metricCompletePassed = true;
            passData = true;
        }

        if (videoData && passData) {
            linkCode(videoData);
            passData = false;
        }

    }, true);

    player.addEventListener('loadeddata', function(e) {
        player.play();
    });


}


//only display MM:SS if HH is 00
function secondsToMS(seconds) {
    var time = secondsToHMS(seconds);
    if (time.indexOf("00:") == 0)
        time = time.substr(3);
    return time;
}

function secondsToHMS(seconds) {
    var h = Math.floor(seconds / 3600);
    var m = Math.floor((seconds % 3600) / 60);
    var s = Math.floor(seconds % 60);
    if (s < 10) s = "0" + s;
    if (m < 10) m = "0" + m;
    if (h < 10) h = "0" + h;
    return h + ":" + m + ":" + s;
}

function replay() {
    loadVideoByIndex(VideoPlayer.playlistPosition);
}

function videoCompleted() {
    if (HISTORY.videoPlayer.isTdih === false) {
        $('#replaythumb')[0].src = VideoPlayer.playlist[VideoPlayer.playlistPosition].thumbnailsmall;
        $('#replaytitle')[0].innerHTML = VideoPlayer.playlist[VideoPlayer.playlistPosition].title;

        if (VideoPlayer.playlistPosition < VideoPlayer.playlist.length - 1) {
            showNext();
            $('#nextthumb')[0].src = VideoPlayer.playlist[VideoPlayer.playlistPosition + 1].thumbnailsmall;
            $('#nexttitle')[0].innerHTML = VideoPlayer.playlist[VideoPlayer.playlistPosition + 1].title;

            if (VideoPlayer.playlistPosition < VideoPlayer.playlist.length - 2) {
                showNext2();
                $('#nextthumb2')[0].src = VideoPlayer.playlist[VideoPlayer.playlistPosition + 2].thumbnailsmall;
                $('#nexttitle2')[0].innerHTML = VideoPlayer.playlist[VideoPlayer.playlistPosition + 2].title;
            }
            else {
                hideNext2();
            }
        }
        else {
            hideNext();
            hideNext2();
        }

    } else {
        $('#replaythumb')[0].src = VideoPlayer.playlist[VideoPlayer.playlistPosition - 1].thumbnailsmall;
        $('#replaytitle')[0].innerHTML = getFormattedDate(0);
        $('#nextthumb')[0].src = VideoPlayer.playlist[VideoPlayer.playlistPosition].thumbnailsmall;
        $('#nexttitle')[0].innerHTML = getFormattedDate(1);
        $('#nextthumb2')[0].src = VideoPlayer.playlist[VideoPlayer.playlistPosition + 1].thumbnailsmall;
        $('#nexttitle2')[0].innerHTML = getFormattedDate(2);
    }
    videoh5player.style.display = "none";
    $("#replayornext").css('opacity', 1);
}

function showNext() {
    $('#nexticon')[0].style.display = "block";
    $('#nextthumb')[0].style.display = "block";
    $('#nexttitle')[0].style.display = "block";
    $('#nextheader')[0].style.display = "block";

}

function hideNext() {
    $('#nexticon')[0].style.display = "none";
    $('#nextthumb')[0].style.display = "none";
    $('#nexttitle')[0].style.display = "none";
    $('#nextheader')[0].style.display = "none";
}

function showNext2() {
    $('#nexticon2')[0].style.display = "block";
    $('#nextthumb2')[0].style.display = "block";
    $('#nexttitle2')[0].style.display = "block";
}

function hideNext2() {
    $('#nexticon2')[0].style.display = "none";
    $('#nextthumb2')[0].style.display = "none";
    $('#nexttitle2')[0].style.display = "none";
}

function playIfVideoNotOn() {
    if (videoh5player.style.display == 'none')
        loadNextVideo();
}

//set up ominuture code
function ResetCounters() {
    // These are counters used to indicate whether or not a particular Omniture event has been fired or not
    // Not core to functionality.

    fullDataPassed = false;
    metric25Passed = false;
    metric50Passed = false;
    metric75Passed = false;
    metricCompletePassed = false;
}


function linkCode(videoData) {
    var s = s_gi(s_account); //Should be s_account as set in regular page Omniture code.

    s.linkTrackVars = 'events,eVar23,eVar24,eVar25,eVar26,eVar27,eVar28,eVar29,eVar30,eVar31,eVar33,eVar34,eVar34,eVar35,eVar37,eVar38,eVar39,eVar52';
    s.linkTrackEvents = videoData.events;
    s.events = videoData.events;
    s.eVar23 = 'HIS:' + videoData.clipCategory + ":" + videoData.clipTitle;
    s.eVar24 = 'HIS:' + videoData.clipCategory;
    s.eVar25 = videoData.length;
    s.eVar26 = (videoData.seasonNumber) ? videoData.seasonNumber : '';
    s.eVar27 = (videoData.isShow == 'show') ? 'TV' : 'Non-TV';
    s.eVar28 = '';
    s.eVar29 = (videoData.episodeNumber) ? videoData.episodeNumber : '';
    s.eVar30 = 'None';
    s.eVar31 = 'HIS:' + playerName;              //player name.
    s.eVar33 = VideoPlayer.playlistPosition;
    s.eVar34 = 'Non-autoplay';
    s.eVar35 = videoData.duration;        //duration in seconds.
    s.eVar37 = '';                  //AdvertiserName
    s.eVar38 = Math.round(videoData.duration / 5) * 5;  //duration rounded to nearest 5 seconds.
    s.eVar39 = '';                  //AdvertiserName:AdTitle?
    s.eVar52 = videoData.siteName + ":" + videoData.zone1 + (videoData.zone2 != '') ? ":" + videoData.zone2 : '';

    s.tl(this, 'o', ' '); //Makes the actual call to Omniture
}


function CheckAgainstSystemTimer() {
    var currentTime = new Date();
    if (lastSystemTime == 0) {
        lastSystemTime = ( currentTime.getTime() / 1000 );  // Current seconds
        return 0;
    }
    else {
        currentSystemTime = (currentTime.getTime() / 1000); // Current seconds
        if ((currentSystemTime - lastSystemTime) >= 1) {
            lastSystemTime = (currentTime.getTime() / 1000);
            return 1;
        }
        else {
            return 0;
        }
    }
}


jQuery(function($) {
    if (!isFlashable()) {
        if (useVideoH5()) {
            init();
        }
        else {
            $('#flash-player').empty();
            $('#flash-player')[0].innerHTML = '<p>It appears you do not have the latest version of the <a href="http://get.adobe.com/flashplayer/">Adobe Flash Player</a> or you may have JavaScript disabled.</p>';
        }
    }

});

/*only use videoH5 for ipah/iphone
 1st: check if flash if abled
 2nd: if not, check if it suppost mp4
 3rd: if not, check if user agent is iphone/ipad
 */
function useVideoH5() {

    //check if flash-installed
    if (isFlashable())
        return false;

    //if flash is not installed, check h246 support
    var mp4Capable = false;
    mp4Capable = supports_h264_baseline_video();
    if (!mp4Capable)
        return false;
    //check user agent
    return isIPadIPhone();
}

function isFlashable() {
    //check if flash-installed
    var versionReported = PluginDetect.isMinVersion('Flash', '0');
    return versionReported > 0 || versionReported < -1;
}

function isIPadIPhone() {
    return navigator.userAgent.indexOf("iPad") != -1 || navigator.userAgent.indexOf("iPhone") != -1;
}

function supports_h264_baseline_video() {
    var v = document.createElement("video");
    var mp4Supported = v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
    return mp4Supported.length > 0 ? true : false;
}

function getFormattedDate(position) {
    var array = VideoPlayer.playlist[position].guid.split("_");
    var month = array[1].substring(0,3);
    var day = array[1].substring(3);
    if (month == 'jan')
        month = "January";
    else if (month == 'feb')
        month = "Feburary";
    else if (month == 'mar')
        month = 'March';
    else if (month == 'apr')
        month = 'April';
    else if (month == 'may')
        month = 'May';
    else if (month == 'jun')
        month = 'June';
    else if (month == 'jul')
        month = 'July';
    else if (month == 'aug')
        month = 'August';
    else if (month == 'sep')
        month = 'September';
    else if (month == 'oct')
        month = 'October';
    else if (month == 'nov')
        month = 'November';
    else if (month == 'dec')
        month = 'December';

    day = parseInt(day);


    return month + ' ' + day;

}



