var bcExp;
var modVP;
var modExp;
var modCon;



/**
 * Event handler for when the player the player first loads.
 *
 */
function onTemplateLoaded(pEvent) {
	
    bcExp = brightcove.getExperience(pEvent); 
    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE); 
    modCon = bcExp.getModule(APIModules.CONTENT);
    
    modExp.addEventListener("templateReady", onTemplateReady);

    // DE-803: ACT/ASS video tracking not working
    if (pEvent == "myExperience")
    {
        addingEvents(modVP);
    }
    // ...DE-803: ACT/ASS video tracking not working
}




/**
 * Event handler for when the player is ready for interaction.
 *
 * @param  event  Event dispatched by player experience module.
 */
function onTemplateReady(event) {
    
    modExp.removeEventListener("templateReady", onTemplateReady);
    
    if (modVP) 
    {
    	modVP.setRenditionSelectionCallback(selectRendition);
    }
}





/**
 * This function add the event listeners PLAY and COMPLETE to the video player
 * @author aluna
 */
function addingEvents(modVP) {
    modVP.addEventListener(BCVideoEvent.VIDEO_START,    onVideoStart);
    modVP.addEventListener(BCVideoEvent.VIDEO_COMPLETE, onVideoComplete);

    // ijiron - US-547/TA-2548
    if(typeof window.playPlaylist == 'function') {
       modVP.addEventListener(BCVideoEvent.VIDEO_COMPLETE, playPlaylist);
    }

    if(typeof window.onVideoProgress == 'function') {
       modVP.addEventListener(BCVideoEvent.VIDEO_PROGRESS, onVideoProgress);
    }

    if(typeof window.onPlayerLoaded == 'function') {
       onPlayerLoaded();
    }

    // ...ijiron - US-547/TA-2548
}

function onVideoStart() {

    // var currentVideo = modVP.getCurrentVideo();
    // var duration = modVP.getVideoDuration(false);
    //window.setTimeout(function() {

        // $(self).show(n, o, 1000, function() { $(this).removeClass("current");
        var currentVideo = modVP.getCurrentVideo();
        if (typeof currentVideo != "undefined" )
        {
            var videoId = currentVideo.id;
            var userId = $j('#userId').val();
            var url = '/download/trackprogressvideo';

            //alert("VIDEO COMPLETED INFO: Currently Loaded videoID: " + currentVideo.id);
            //alert("VideoID:" + videoId);
            //alert("UserID:" + userId);
            //alert("Ajax call right now...");

            //if (modVP.isPlaying())
            //{
                // alert("the video is playing...");
                if (typeof videoId != "undefined" && typeof userId != "undefined" && userId != 0) {
                    //alert(modVP.getVideoDuration());
                    if ( modVP.getVideoDuration() != 60000 ) {
                        $j(document).ready(
                            function() {
                                $j.post(url,{video_id: videoId, user_id : userId, status : "start" },function(data)
                                                {
                                                    //$j("#"+"outputAjax").html(data);
                                                    // alert("Ajax response: " + data );

                                                    if (data == "IN-PROGRESS") {
                                                       $j('#video_image_' + videoId).attr('src', '/images/ap/icons/checkbox_inprogress.png');
                                                       $j('#div-' + videoId).removeClass('tryMe');
                                                       $j('#div-' + videoId).removeClass('notStarted');
                                                       $j('#div-' + videoId).addClass('inProgress');
                                                    }
                                                    else if (data == "FINISHED") {
                                                       $j('#video_image_' + videoId).attr('src', '/images/ap/icons/checkbox_checked.png');
                                                       $j('#div-' + videoId).removeClass('tryMe');
                                                       $j('#div-' + videoId).removeClass('notStarted');
                                                       $j('#div-' + videoId).removeClass('inProgress');
                                                       $j('#div-' + videoId).addClass('finished');
                                                    }
                                                    else {
                                                       $j('#video_image_' + videoId).attr('src', '');
                                                    }
                                                }
                                );

                                //$j('#image_' + bonusMaterialId ).attr('src', '/images/ap/icons/checkbox_checked.png');
                           }
                       );
                    }
                }
                if( typeof onVideoBegin == 'function' ) {
                    onVideoBegin();
                }
            //}
        }
  //  },20000);
}

function onVideoComplete() {

    var currentVideo = modVP.getCurrentVideo();

    var videoId = currentVideo.id;
    var userId = $j('#userId').val();
    var url = '/download/trackprogressvideo';

    if (typeof videoId != "undefined" && typeof userId != "undefined" && userId != 0) {
        if ( modVP.getVideoDuration() > 5)
        {
            $j(document).ready(
                function() {
                    $j.post(url,{video_id: videoId, user_id : userId, status : "finish"  },function(data)
                        {
                            //$j("#"+"outputAjax").html(data);
                               //alert("Ajax response: " + data );

                            if (data == "IN-PROGRESS") {
                               $j('#video_image_' + videoId).attr('src', '/images/ap/icons/checkbox_inprogress.png');
                               $j('#div-' + videoId).removeClass('notStarted');
                               $j('#div-' + videoId).addClass('inProgress');
                            }
                            else if (data == "FINISHED") {
                               $j('#video_image_' + videoId).attr('src', '/images/ap/icons/checkbox_checked.png');
                               $j('#div-' + videoId).removeClass('notStarted');
                               $j('#div-' + videoId).removeClass('inProgress');
                               $j('#div-' + videoId).addClass('finished');
                            }
                            else {
                               $j('#video_image_' + videoId).attr('src', '');
                            }
                            bunchballHandler.showNotifications();

                            // US-504: Episode Quizzes: Classroom Tab Functionality - TA-2361: Update focus on Classroom Tab at end of video
                            if(typeof window.onVideoCompleteShowEpisodeQuizTab == 'function') {
                               onVideoCompleteShowEpisodeQuizTab();
                            }
                            // ...US-504: Episode Quizzes: Classroom Tab Functionality - TA-2361: Update focus on Classroom Tab at end of video
                        }
                    );
                }
            );
        }
    }
}

/**
 * Gets the Brightcove player to play the video with the id = the parameter
 * @author Carlos Soto <csoto@avantica.net>
 * @param int id BC video's id
 */
function loadVideo(id){

    // alert('loadingVideo');
    if(typeof(modCon) != 'undefined' && typeof(modVP) != 'undefined'){
        modCon.getVideo(id);
        modVP.loadVideo(id);
    }
    else{
        setTimeout('loadVideo(\'' + id + '\');', 200);
    }
}

/**
 * Gets the time position of the currently playing video in seconds.
 * @author Carlos Soto <csoto@avantica.net>
 * @return float time position of the currently playing video in seconds.
 */
function getCurrentVideoTime(){
    return modVP.getVideoPosition();
}

/**
 * Sets the time position of the currently playing video in seconds.
 * @author Carlos Soto <csoto@avantica.net>
 * @param float time position of the currently playing video in seconds.
 */
function setCurrentVideoTime(time){
    modVP.seek(time -2);
}

/**
 * Stops the video
 * @author Carlos Soto <csoto@avantica.net>
 */
function stopVideo()
{
    if( modVP )
    {
        //alert('stopping video');
        modVP.stop();
    }
}

/**
 * Play the video
 * @author Ivhan Jiron
 */
function playVideo() {

    if( modVP )
    {
        //alert('play video');
        modVP.play();
    }
}


/**
 * Resume the video
 * @author Ivhan Jiron
 */
function resumeVideo() {

    if( modVP )
    {
        //alert('resume video');
        modVP.pause(false);
    }
}


/**
 * Pause the video
 * @author Ivhan Jiron
 */
function pauseVideo() {

   if ( modVP )
   {
        //alert('pause video');
        modVP.pause(true);
   }
}


/**
 * Enable/Disable the player
 * @author Ivhan Jiron
 */
function setEnabledVideo(boolFlag) {

   if ( modVP )
   {
        //alert('enable-disable the player: ' + boolFlag);
        modVP.setEnabled(boolFlag);
   }
}




// How far in percent a rendition can be above the video screen height.
var FRAME_HEIGHT_TOLERANCE = 1.2;


// The percent amount the detected bandwidth is reduced when checking against encoding.
// Generally, you want a rendition to be encoded less than the available bandwidth in order to 
// ensure smooth playback.
var ENCODING_RATE_TOLERANCE = 0.70;


var ENCODING_MAX_RATE = 1300000; //1300kbps

/**
* The callback invoked whenever the player reaches a point when a new selection can be selected. This will occur on initial playback
* as well, for streaming videos, when there are multiple buffering events or when the screen size changed, as when going full screen.
* This method must take an object as an argument and return an int value that represents the index of the rendition to play.
*
* @param  context  The context that the player uses to select a new rendition. This object includes the following properties:
*           video  The video currently playing to which the renditions belong.
*           currentRendition  The currently selected rendition for the video.
*           renditions  An Array of renditions for the video to choose from.
*           detectedBandwidth  The last detected bandwidth value.
*           screenWidth  The pixel width of the video screen in which the rendition will play.
*           screenHeight  The pixel height of the video screen in which the rendition will play.
*
* @returns  The index of the rendition in the renditions list for the video player to play.
*/
function selectRendition(context) {
    var renditions = context.renditions.slice();
    var heightMatch;
    var currentRendition;
    var selectedRendition;
    var bandwidth = context.detectedBandwidth;
    var height = context.screenHeight;
    
/* 
Pseudo-algorithm:
 
if (detected bandwidth is high enough) {
   if (highest rendition < 1300kbps)
      Play 2nd highest rendition;
}
else
   Play what brightcove decides;
*/    
    
    // bandwidth has been detected, so find the closest encoding
    if (bandwidth > -1 && renditions.length > 1) {

       // sort renditions first by encoding, then by height
       renditions = sortRenditions(renditions);

       currentRendition = renditions[1]; // choose 2nd highest quality rendition                

       if (!isNaN(currentRendition.encodingRate) && 
           currentRendition.encodingRate <= bandwidth*1000*ENCODING_RATE_TOLERANCE && 
           currentRendition.frameHeight  <= height*FRAME_HEIGHT_TOLERANCE && 
           !isNaN(renditions[0].encodingRate) && 
           renditions[0].encodingRate < ENCODING_MAX_RATE)
       {
          selectedRendition = currentRendition;
       }
       else 
       {
          selectedRendition = context.currentRendition;                	
       }

    } 
    else 
    {
       // just let brightcove choose it
       selectedRendition = context.currentRendition;
    }

    // find the index in the initial list
    var renditionIndex = -1;
    for (var i = 0; i < context.renditions.length; i++) {
        if (selectedRendition == context.renditions[i]) {
            renditionIndex = i;
            break;
        }
    }
    //describeRendition(context.renditions[renditionIndex]);
    return renditionIndex;
}




/**
* Sorts renditions first by bandwidth, then by frame height.
*
* @param  renditions  The list of renditions to sort.
*
* @returns  The sorted renditions in a new array.
*/
function sortRenditions(renditions) {
    // first, sort by encoding
    renditions.sort(sortByEncoding);
    // run through sorted list and place same encodings into their own arrays
    var encodingRenditions = {};
    for (var i = 0; i < renditions.length; i++) {
        if (encodingRenditions[renditions[i].encodingRate] == null) {
            encodingRenditions[renditions[i].encodingRate] = [];
        }
        encodingRenditions[renditions[i].encodingRate].push(renditions[i]);
    }
    // now sort all nested arrays and put them back into single array
    var sortedRenditions = [];
    for (var i in encodingRenditions) {
        encodingRenditions[i].sort(sortByFrameHeight);
        sortedRenditions = sortedRenditions.concat(encodingRenditions[i]);
    }
    return sortedRenditions;
}

/**
* Sorts two renditions by encoding rate value.
*/
function sortByEncoding(a, b) {
    var x = a.encodingRate;
    var y = b.encodingRate;
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

/**
* Sorts two renditions by frame height value.
*/
function sortByFrameHeight(a, b) {
    var x = a.frameHeight;
    var y = b.frameHeight;
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

/**
* Traces out the values of rendition for testing.
*
* @param  rendition  The rendition to traces values for.
* @param  index  The index in the renditions array where this rendition is found.
*/
function describeRendition(rendition) {
    var message = ("size: " + rendition.size);
    message += ("\nframeWidth: " + rendition.frameWidth);
    message += ("\nframeHeight: " + rendition.frameHeight);
    message += ("\nencodingRate: " + rendition.encodingRate);
    alert(message);
}


