var FREEDL;
var TOCDL;
var MOSTHELPDL;
var TOC_LAST_SELECTED_ITEM;
var PLAYLIST_BASE_INDEX;

// this video id is used when a specific video is being played
// for example, from the free videos or from the most poupular
// video list
var CURRENT_VIDEO_ID;

function pageLoad(sender, e)
{
    // Change these names when changing the ID in the form or if 
    // the nesting of controls is changed 
    FREEDL = $find('freeDataList');
    TOCDL = $find('tocDataList');
    MOSTHELPDL = $find('mostHelpfulDataList');
    
    // no specific video is curretly being played
    CURRENT_VIDEO_ID = 0;
    
    // playlist base index will be zero except when the user clicks on the TOC item.
    PLAYLIST_BASE_INDEX = 0;
    
    loadFreeVideos();
    loadMostHelpfulVideos();
    
    //decide how the player will be created here
    var vidDiv = $get('vidDiv');
    var uidDiv = $get('uidDiv');
    var coursesDropDownList = $get('courseList_coursesDropDownList');
    
    var vid = +(vidDiv.innerHTML);
    var uid = escapeHTML(uidDiv.innerHTML);
    
    // if a direct video request is made
    if (vid > 0)
    {
        createPlayerForRequestedVideo(vid, uid);
    }
    else if (coursesDropDownList != undefined)
    {
        var courseId = coursesDropDownList.value;
        createPlayerForCourse(courseId);
    }
    else
    {
        createPlayerForCourse(0);
        onActiveTabChanged(null, null);
    }
}

function setCurrentCourseId(courseId)
{
    var cidDiv = $get('cidDiv');
    cidDiv.innerHTML = courseId;
}

function getCurrentCourseId()
{
    var cidDiv = $get('cidDiv');
    return +(cidDiv.innerHTML);
}

function createPlayerForRequestedVideo(vid, uid)
{
    // Note that you must urlencode the three glyphs ? = & inside flashvars, because of the way 
    // these flashvars are presented to the player. The urlencoded values for these symbols are 
    // listed here:
    //      ? → %3F 
    //      = → %3D 
    //      & → %26 
    createPlayer('playlist.aspx%3Fvid=' + vid + '%26uid=' + uid, 
                 vid, '', "true", "true");
    refreshVideoRating(vid);

    // update the video rating control with the first video in the course
    VideoService.GetCourseId(vid, onGetCourseIdSuccess);
}

function onGetCourseIdSuccess(result)
{
    // result contains a courseId
    updateRelatedContents(result);
    setCurrentCourseId(result.courseId);
    loadTocVideosWhenNeeded();
    VideoService.getExamNameNumber(result, onSuccessExamNameNumber);
}

function onSuccessExamNameNumber(result)
{
    var examNameNumberDIV = $get('ExamNameNumber')
    examNameNumberDIV.innerHTML = result;
}

/*************************************************************
Methods for the free video datalist
*************************************************************/

function switchToFree()
{
    $get('freeVideoContainer').style.display = "block";
    $get('tocVideoContainer').style.display = "none";
    document.tabImage.src = "/images/olv/free_video_tab_up.jpg";
}

function loadFreeVideos()
{
    $get('freeVideoLoadingMessage').style.display = 'none';
    VideoService.GetFreeVideosByRating(onFreeVideosLoadSuccess);
}

function onFreeVideosLoadSuccess(result)
{
    FREEDL.set_dataSource(result);
    FREEDL.dataBind();
    $get('freeVideoLoadingMessage').style.display = 'none';
}

function freeDataList_ItemDataBound(sender, e)
{
    var item = e.get_item();
    if (item.get_isDataItemType())
    {
        var video = item.get_dataItem();
        if (typeof video != 'undefined')
        {
            var imgButton = item.findControl('imgVideoButton');
            imgButton.src = video.VideoImage;
            imgButton.alt = video.Title;
           
            // Add video title and duration
            var freeVideoTitle = item.findControl('freeVideoTitle');
            freeVideoTitle.innerHTML = video.Title;
            
            /*
            DO NOT SHOW VIDEO LENGTH ON FREE VIDEOS
            var freeVideoLength = item.findControl('freeVideoLength');
            freeVideoLength.innerHTML = video.Length;*/
            
            var videoButton = item.findControl('videoButton');
            var context = { videoId : video.VideoId, courseId : video.CourseId};
            var clickCallback = Function.createCallback(onSpecificVideoClick, context);
            $addHandler(videoButton, 'click', clickCallback);
        }
    }
}

function onSpecificVideoClick(evt, context)
{
    //alert('video: ' + context.videoId + '\ncourse: ' + context.courseId);
    createPlayer('playlist.aspx%3Fvid=' + context.videoId, context.videoId, '', "true", "true"); 
    updateRelatedContents(context.courseId);
    refreshVideoRating(context.videoId);
    VideoService.getExamNameNumber(context.courseId, onSuccessExamNameNumber);
   
   // update the global course id
   setCurrentCourseId(context.courseId);
   if ($get('courseList_coursesDropDownList').value != context.courseId)
        $get('courseList_coursesDropDownList').value = 0;
   loadTocVideosWhenNeeded();
   // reset any previous selection 
   resetTocSelectionIndex();
}

/*************************************************************
Methods for the most helpful datalist
*************************************************************/
function loadMostHelpfulVideos()
{
    $get('mostHelpfulLoadingMessage').style.display = '';
    VideoService.GetMostHelpfulVideos(onMostHelpfulVideosLoadSuccess);
}

function onMostHelpfulVideosLoadSuccess(result)
{
    MOSTHELPDL.set_dataSource(result);
    MOSTHELPDL.dataBind();
    $get('mostHelpfulLoadingMessage').style.display = 'none';
}

function mostHelpfulDataList_ItemDataBound(sender, e)
{
    var item = e.get_item();
    if (item.get_isDataItemType())
    {
        var video = item.get_dataItem();
        if (video != null)
        {
            // Add the counter
            var mostHelpfulVideoCounter = item.findControl("mostHelpfulVideoCounter");
            mostHelpfulVideoCounter.innerHTML = item._itemIndex + 1 + ". ";
             
            // Add video title and duration
            var mostHelpfulVideoTitle = item.findControl("mostHelpfulVideoTitle");
            mostHelpfulVideoTitle.innerHTML = video.Title;
            
            var mostHelpfulVideoLength = item.findControl("mostHelpfulVideoLength");        
            if(video.Length > 0)
                mostHelpfulVideoLength.innerHTML = '(' + convertToHHMMSS(video.Length) + ')';

            //Attach the event handler
            var mostHelpfulVideoButton = item.findControl("mostHelpfulVideoButton");
            var context = { videoId : video.VideoId, courseId : video.CourseId};
            var clickCallback = Function.createCallback(onSpecificVideoClick, context);
            $addHandler(mostHelpfulVideoButton, 'click', clickCallback);            
        }
    }
}        
 
 //*********************************Functions for Most Helpful Videos**************************
 
 /*************************************************************
 *Converts Seconds to respective Hours:Minutes:Seconds Format
 **************************************************************/
 function convertToHHMMSS(intseconds)
 {
    if(intseconds >= 60)
    {
        var intminutes = Math.floor(intseconds/60);
        intseconds -= (intminutes * 60);
        
        if(intminutes >= 60)
        {
            var inthours = Math.floor(intminutes/60);
            intminutes -= (inthours * 60);
        }
        else
            return (addZero(intminutes) + ':' + addZero(intseconds));
    }
    else
        return('0:' + addZero(intseconds));
    return (addZero(inthours) + ':' + addZero(intminutes) + ':' + addZero(intseconds));
 }
 /*************************************************************
 *Add zero if value < 10
 **************************************************************/
 function addZero(inttime)
 {
    if(inttime < 10)
        return ('0' + inttime);
    else
        return inttime;
 }
 //********************************End Most Helpful Video Functions****************************
 
/*************************************************************
Methods for the toc datalist
*************************************************************/
function onActiveTabChanged(sender, args)
{
    document.getElementById('tocVideoContainer').style.display = "block";
    document.getElementById('freeVideoContainer').style.display = "none";
    document.tabImage.src = "/images/olv/video_index_tab_up.jpg";
    loadTocVideosWhenNeeded();
}

// stores the last course id assigned to the TOC
var TOCCID;
function loadTocVideosWhenNeeded()
{    
        var courseId = getCurrentCourseId()
        //load the TOC only when a different one is needed
        if (TOCCID == undefined || TOCCID != courseId)
        {
            TOCCID = courseId;
            loadTocVideos(courseId);
        }
}

function loadTocVideos(courseId)
{
    $get('tocLoadingMessage').style.display = '';
    VideoService.GetVideos(courseId, onLoadTocVideosSuccess);
}

function onLoadTocVideosSuccess(result)
{
    TOCDL.set_dataSource(result);
    TOCDL.dataBind();
    $get('tocLoadingMessage').style.display = 'none';
    
    // TOC just loaded, reset the base index
    PLAYLIST_BASE_INDEX = 0;
    // highlight the currently playing video
    selectSpecificTocItem();
}

function selectSpecificTocItem()
{
    if (CURRENT_VIDEO_ID == 0) 
        setTocSelectionIndex(0);
    else
        VideoService.GetVideoPlayListIndex(CURRENT_VIDEO_ID, onSelectSpecificTocItemSuccess);
}

function onSelectSpecificTocItemSuccess(result)
{
   setTocSelectionIndex(result);
}

var LASTCHAP;
function tocDataList_ItemDataBound(sender, e)
{
    var item = e.get_item();
    if (item.get_isDataItemType())
    {
        var video = item.get_dataItem();
        if (typeof video != 'undefined')
        {
            if (LASTCHAP == undefined || LASTCHAP != video.ChapterName)
            {
                LASTCHAP = video.ChapterName;
                var tocChapterName = item.findControl('tocChapterName');
                if (tocChapterName != undefined)
                {
                    tocChapterName.innerHTML = video.ChapterName;        
                }
            }
            
            // Add video title and duration
            var tocVideoTitle = item.findControl('tocVideoTitle');
            tocVideoTitle.innerHTML = video.Title; //original
            
            //----------------------------------------------
            //hide certain videos
            /*if (video.Title.indexOf('Certification') != -1)*/
                 //tocVideoTitle.innerHTML = '<!--' + video.Title + '-->';
            /*else
                tocVideoTitle.innerHTML = video.Title;*/
            //----------------------------------------------
            
            var tocVideoLength = item.findControl('tocVideoLength');
            if(video.Length > 0)
                tocVideoLength.innerHTML = '(' + convertToHHMMSS(video.Length) + ')'
            
            //Attach the event handler
            var context = { videoId : video.VideoId, courseId : video.CourseId, tocItem : item };
            var clickCallback = Function.createCallback(onTocItemClick, context);
            $addHandler(tocVideoTitle, 'click', clickCallback);            
        }
    }
}

function onTocItemClick(evt, context)
{
    // Note that you must urlencode the three glyphs ? = & inside flashvars, because of the way 
    // these flashvars are presented to the player. The urlencoded values for these symbols are 
    // listed here:
    //      ? → %3F 
    //      = → %3D 
    //      & → %26
    // The second parameter is videoId which doesn't apply in this case, so it is passed as zero. 
    createPlayer('playlist.aspx%3Fcid=' + context.courseId + '%26index=' + context.tocItem.get_itemIndex(), 
                0, '', "true", "true");
    PLAYLIST_BASE_INDEX = context.tocItem.get_itemIndex();
	
    setTocSelectionIndex(0);
    refreshVideoRating(context.videoId);
}

function setTocSelectionIndex(selectedItemIndex)
{
    var selectedItem;
    var actualIndex = PLAYLIST_BASE_INDEX + selectedItemIndex;
    
    if (TOCDL != undefined)
    {
        selectedItem = TOCDL.get_items()[actualIndex];
    
        if (TOC_LAST_SELECTED_ITEM != undefined)
        {
            if (TOC_LAST_SELECTED_ITEM._container != undefined)
            {
                TOC_LAST_SELECTED_ITEM._container.className = "tocRowStyleNormal";
            }
        }
        
        if (selectedItem != undefined)
        {
            if (selectedItem._container != undefined)
            {
                selectedItem._container.className = "tocRowStyleSelected";
                TOC_LAST_SELECTED_ITEM = selectedItem; 
            }
        }
    }
}

function resetTocSelectionIndex()
{
    if (TOC_LAST_SELECTED_ITEM != undefined)
    {
        if (TOC_LAST_SELECTED_ITEM._container != undefined)
        {
            TOC_LAST_SELECTED_ITEM._container.className = "tocRowStyleNormal";
            TOC_LAST_SELECTED_ITEM = undefined;
        }
    }
    
    // highlight the currently playing video
    selectSpecificTocItem();
}
        
function refreshVideoRating(videoId)
{
    // get video rating from service
    VideoService.GetVideoRating(videoId, onRatingSuccess);
    var ratingControl = $find("videoRatingControl");
    if (ratingControl != null)
    {
        ratingControl._tag = videoId;
    }
}

function onRatingSuccess(result)
{
    var videoRating = result;

    // find the rating control
    var ratingControl = $find("videoRatingControl");
    
    // set the rating
    if (ratingControl != null)
    {
        ratingControl.set_Rating(videoRating);
    }
}

//Update the user's rating to the server
function updateVideoRating()
{
    videoId = $find("videoRatingControl")._tag;
    newRating = $find("videoRatingControl")._currentRating;

    VideoService.UpdateUserVideoRating(videoId, newRating, onCallComplete, onCallError);
}

function updateRelatedContents(courseId) 
{ 
    var behavior = $find('dynamicRelatedContents1'); 
    if(behavior) 
    { 
        behavior.populate(courseId); 
    } 
}     
    
function courseChanged(courseList) 
{
   var courseId = courseList.value;
   createPlayerForCourse(courseId);
 
   // update the video rating control with the first video in the course
   VideoService.GetFirstVideoId(courseId, onGetFirstVideoIdSuccess);
   
   // make the video index as the active tab
   onActiveTabChanged(null, null);
}

function onGetFirstVideoIdSuccess(result)
{
    // update the video rating control
    refreshVideoRating(result);
}

function createPlayerForCourse(courseId)
{
   setCurrentCourseId(courseId);
   
   //courseId will be empty if User has no courses in Dropdown
   //if this is the case we will display Intro Video
   if(courseId == "")
        courseId = 0
        
    //The second parameter is videoId which doesn't apply in this case, so it is passed as zero. 
    createPlayer('playlist.aspx%3Fcid=' + courseId, 0, '', "true", "true");

   updateRelatedContents(courseId);
   VideoService.getExamNameNumber(courseId, onSuccessExamNameNumber);
}

function onCallComplete(result, userContext, methodName) 
{
    //    alert(result);
}

function onCallError(error, userContext, methodName) {
    if(error !== null) 
    {
//        alert(error.get_message());
    }
}

/*************************************************************
Utility Methods
*************************************************************/
function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
