//navcode
 $(document).ready(function() {
    $('.navchild').hide();
    $('.navgrandchild').hide();
    $('#navroot > li > a, .navchild > li > a').click(function() {
        var visibility = $(this).next('ul').css("display");
        if( visibility == "none" )
        {
            $(this).next('ul').show("normal");
            $(this).parent().siblings().children('ul:visible').hide("normal");
            $('.navgrandchild').hide();
            $('#message').text($(this).text() + " Opened");
        }
        else { $(this).next('ul').hide("normal"); $('#message').text($(this).text() + " Closed");}
    });
});

var videosToLoad;
var responseDone;

// The web service call
var token = "Tmpg-v1ATUWOLBqqW7ZKsyO0-t7PWwRRYGW7gAvf9dI.";

function initCall(playlistId) {
    // Create a new request object
    trace("jsonFunction initiated");
    var req = "http://api.brightcove.com/services/library?";
    req += "command=find_playlist_by_id&token=" + encodeURIComponent(token);  // tokens need to be URL-encoded
    req += "&playlist_id=" + playlistId;
    req += "&fields=videoIds&callback=response";

    bObj = new JSONscriptRequest(req);
    // Build the dynamic script tag
    bObj.buildScriptTag();
    // Add the script tag to the page
    bObj.addScriptTag();
}

// Define the callback function
// writes out the HTML for each title item in the list
function response(jsonData) {
    videosToLoad = jsonData["videoIds"];
    trace("Adding Custom Playlist");

    content.addEventListener(BCContentEvent.PLAYLIST_LOAD, onPlaylistLoad);

    content.getMediaInGroupAsynch(videosToLoad);
    trace(videosToLoad);
}

//player
var player;
var video, content, exp, menu, ads, social;
var videoList, tabBar;

function onTemplateLoaded(pPlayer) {
    trace("templateLoaded");

    player = bcPlayer.getPlayer(pPlayer);
    video     = player.getModule(APIModules.VIDEO_PLAYER);
    content = player.getModule(APIModules.CONTENT);
    exp     = player.getModule(APIModules.EXPERIENCE);

    exp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);

    exp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);

    video.addEventListener("videoConnect", onVideoConnect);

}

function onTemplateReady(e) {
    trace(e.type);

    videoList = exp.getElementByID("videoList");
    tabBar = exp.getElementByID("playlistTabs");
}

function onPlaylistLoad(e) {
    trace(e.type);
    content.removeEventListener(BCContentEvent.PLAYLIST_LOAD, onPlaylistLoad);

    var customPlaylist = new Object();
    customPlaylist.displayName = "Video Lineup";
    customPlaylist.videoIds = videosToLoad;

    customPlaylist.videoDTOs = new Array();
    for(var i = 0; i < customPlaylist.videoIds.length; i++) {
        customPlaylist.videoDTOs.push(content.getVideo(customPlaylist.videoIds[i]));
    }

    tabBar.replaceTabAt(customPlaylist, 0);
    tabBar.setSelectedIndex(0);
    videoList.setSelectedIndex(0);

}

function onContentLoad(e) {
    var currentVideo = video.getCurrentVideo();
    var videoInformation = document.getElementById("videoDescription");
    var str = "";
    wwd.stats.trackAction('video', currentVideo.displayName);

    str += '<h5>Now Playing</h5>';
    str += '<h1>' + currentVideo.displayName + '</h1>';
    if (currentVideo.longDescription == null || currentVideo.longDescription == "null" || currentVideo.longDescription == "")
        {
            str += '<p></p>';
        }
    else
    {
        str += '<p>' + currentVideo.longDescription + '</p>';
    }
    videoInformation.innerHTML = str;
}

function onVideoConnect(e) {
    var currentVideo = video.getCurrentVideo();
    var videoInformation = document.getElementById("videoDescription");
    var str = "";
    wwd.stats.trackAction('video', currentVideo.displayName);
    str += '<h5>Now Playing</h5>';
    str += '<h1>' + currentVideo.displayName + '</h1>';
    if (currentVideo.longDescription == null || currentVideo.longDescription == "null" || currentVideo.longDescription == "") {
        str += '<p class="videoDescriptionP"></p>';
    } else {
        str += '<p class="videoDescriptionP">' + currentVideo.longDescription + '</p>';
    }
    videoInformation.innerHTML = str;

    $(function() {
        $(".videoDescriptionP").truncate( 500 );
    });
}


//featured video container
$(document).ready(function() {
    getTopVideos();
});

function addScriptTag(id, url, callback) {
    var scriptTag = document.createElement("script");

    // Add script object attributes
    scriptTag.setAttribute("type", "text/javascript");
    scriptTag.setAttribute("charset", "utf-8");
    scriptTag.setAttribute("src", url + "&callback=" + callback);
    scriptTag.setAttribute("id", id);

    var head = document.getElementsByTagName("head").item(0);
    head.appendChild(scriptTag);
}

function getTopVideos() {
    addScriptTag("featuredVideos", "http://api.brightcove.com/services/library?command=find_videos_by_tags&token=Tmpg-v1ATUWOLBqqW7ZKsyO0-t7PWwRRYGW7gAvf9dI.&and_tags=featured&fields=id,name,thumbnailURL,shortDescription&page_size=5", "response2");
}

function response2(jsonData) {
    var respFeat = document.getElementById("bottomFeaturedUL");
    for (var i=0; i<jsonData["items"].length; i++) {
        var title = jsonData["items"][i];
        var str = "";
        str += '<li class="bottomFeatLi" onClick="playTitle(' + title.id + ')">';
        str += '<img class="largeThumbnail" width="90" height="68" src="' + title.thumbnailURL + '"/>';
        str += '<h3 class="featuredBottomH3">' + title.name + '</h3>';
        str += '</li>';
        respFeat.innerHTML += str;
    }
}

function playTitle(videoId) {
    video.loadVideo(videoId);
}

function onStreamStart() {
   callFlash("getCurrentTitle");
   wwd.stats.trackAction('video', title_id.displayName);
}
