/**
 * Copyright (C) 2008 Brightcove, Inc.  All Rights Reserved.  No
 * use, copying or distribution of this work may be made except in
 * accordance with a valid license agreement from Brightcove, Inc.
 * This notice must be included on all copies, modifications and
 * derivatives of this work.
 *
 * Brightcove, Inc MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT
 * THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. BRIGHTCOVE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
 * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS
 * SOFTWARE OR ITS DERIVATIVES.
 *
 * "Brightcove" is a trademark of Brightcove, Inc.
 **/

// update with valid playlist ID
var PLAYLIST_ID = 53688086001;

// initializing variables;
var player = null;
var selectedItem = null;
var slider = null;
var contentHeight = 0;

// sets up scrollbar after page load
window.onload = function() {

}


/**
* Handler for when Brightcove player initially loads, allowing for API interaction.
*
* @param  pExperienceID  The ID of the HTML object element where the player is embedded.
*/
function onTemplateLoaded(pExperienceID) {
    // store reference to player
    player = brightcove.getExperience(pExperienceID);
    // set up listener for templateReady, where all API interaction is enabled
    // (generally, this handler should be used primarily to set up this listener)
    var experienceModule = player.getModule(APIModules.EXPERIENCE);
    experienceModule.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
}

/**
* Handler for when Brightcove player is fully loaded and all API is accessible.
*
* @param  pEvent  Event dispatched by experience module.
*/
function onTemplateReady(pEvent) {
    // clean up by removing listener
    var experienceModule = player.getModule(APIModules.EXPERIENCE);
    experienceModule.removeEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    // load a playlist into the player -- the PLAYER_ID is defined at top
    var contentModule = player.getModule(APIModules.CONTENT);
    contentModule.addEventListener(BCContentEvent.PLAYLIST_LOAD, onPlaylistLoad);
    contentModule.getPlaylistAsynch(PLAYLIST_ID);
}

/**
* Handler for when playlist loads into player memory after the getPlaylistAsynch() call.
*
* @param  pEvent  Event dispatched by content module.
*/
function onPlaylistLoad(pEvent) {
    // get reference to tileList dev in HTML
    var tileList = document.getElementById("tileList");
    var listWrap = createElement("div");
    listWrap.className="listWrap";
    tileList.appendChild(listWrap);

    var contentModule = player.getModule(APIModules.CONTENT);
    // this will return an array of videoIds, which will allow us to fetch the individual videos
    // from the playlist through the content module
    var videoIds = pEvent.playlist.videoIds;
    var numVideos = videoIds.length;
    var video;
    // run through each video in playlist and create element to append to tileList element
    for (var i = 0; i < numVideos; i++) {
        // returns video DTO
        var video = contentModule.getVideo(videoIds[i]);
        // creates the HTML display
        var tile = makeVideoTile(video);
        // adds new element to the document
        listWrap.appendChild(tile);

        // for first item, select it and cue up the video in the player
        if (i == 0) {
            selectItem(tile);
            cueVideo(video);
        }
    }

    $('.playBtn').hide();
    autoScroll();
    
    $('.videoTile').hover(function() {
        $(this).animate({ backgroundColor: "#DDD" }, 200);    
        $(this).find('.displayName').each(function() {
            $(this).animate({ color: "#6baab1" }, 200);
        });
        $(this).find('.playBtn').each(function() {
            $(this).show();
        });
    },function() {
        $(this).animate({ backgroundColor: "#FFF" }, 200);
        $(this).find('.displayName').each(function() {
            $(this).animate({ color: "#EB3027" }, 200);
        });
        $(this).find('.playBtn').each(function() {
            $(this).hide();
        });
    });
    
}

/**
* Creates an HTML element to display the thumbnail and display name of video.
*
* @param  pVideo  The video DTO to create view for.
*
* @returns  The created HTML element.
*/
function makeVideoTile(pVideo) {
  
    
    // div to hold everything
    var tile = createElement("div");
    tile.className = "videoTile";
    // create image container
    var thumb = createElement("img");
    thumb.setAttribute("src", pVideo.thumbnailURL);
    thumb.className = "thumb";
    tile.appendChild(thumb);

    var playBtn = createElement("img");
    playBtn.setAttribute("src", "images/playBtn.png");
    playBtn.className = "playBtn";
    tile.appendChild(playBtn);

    // create paragraph tag for title
    var title = createElement("p");
    title.className = "displayName";
    // create text node within paragraph
    var text = document.createTextNode(pVideo.displayName);
    title.appendChild(text);
    tile.appendChild(title);

    var description = createElement("p");
    description.className = "description";

    text = document.createTextNode(pVideo.shortDescription);
    description.appendChild(text);
    tile.appendChild(description);
    
    // when item is clicked, it should call playVideo function
    tile.onmousedown = function() { playVideo(this, pVideo); };
    return tile;
}

/**
* Cues up the video in the video player, which will display its still without playing it.
*
* @param  pVideo  The video DTO to cue up.
*/
function cueVideo(pVideo) {
    var videoPlayerModule = player.getModule(APIModules.VIDEO_PLAYER);
    videoPlayerModule.cueVideo(pVideo.id);
}

/**
* Plays back the video in the player. This will also visually select the item that was clicked.
*
* @param  pVideoTile  The list item that was clicked.
* @param  pVideo  The video DTO to play.
*/
function playVideo(pVideoTile, pVideo) {
    var videoPlayerModule = player.getModule(APIModules.VIDEO_PLAYER);
    // gets reference to current video
    var currentVideo = videoPlayerModule.getCurrentVideo();
    // only play item if it is not current video
    if (currentVideo == null || pVideo.id != currentVideo.id) {
        selectItem(pVideoTile);
        videoPlayerModule.loadVideo(pVideo.id);
    }
}

/**
* Visually selects the item by changing its background color.
*
* @param  pVideoTile  The list item to select.
*/
function selectItem(pVideoTile) {
    // deselects previous item
    if (selectedItem != null) {
        selectedItem.className = "videoTile";
        deselectItem(selectedItem);
    }
    pVideoTile.className = "videoTile active";
    selectedItem = pVideoTile;
}

/**
* Visually deselects the item by changing its background color.
*
* @param  pVideoTile  The list item to deselect.
*/
function deselectItem(pVideoTile) {
    pVideoTile.style.backgroundColor = "#FFFFFF";
}

/**
* Creates HTML element in way required by browser.
*
* @param  pTag  The tag of the element to create.
*
* @returns  The created HTML element.
*/
function createElement(pTag) {
    if (document.createElementNS) {
        return document.createElementNS('http://www.w3.org/1999/xhtml', pTag);
    }
    return document.createElement(pTag);
}

function autoScroll() {
    //Get our elements for faster access and set overlay width
    var div = $('#tileList'),
               item = $('.listWrap'),
    // unordered list's left margin
               itemPadding = 200;
    //Get menu width
    var divHeight = div.height();

    //Remove scrollbars
    //div.css('overflow', 'hidden');

    //Find last image container
    var lastItem = item.find('div:last-child');

    //When user move mouse over menu
    div.mousemove(function(e) {
        var itemHeight = lastItem[0].offsetTop + lastItem.outerHeight() + itemPadding;
        var top = (e.pageY - div.offset().top) * (itemHeight - divHeight) / divHeight-100;
        div.scrollTop(top);
    });
}