﻿/* ---Description---
* The playEmbed function is used to actually load the current clip
* into the player. The swfobject in the function can be edited, but
* is absolutely needed for functionality.
* ---Parameters---
* resourceId - The GUID of the clip you'd like to load into the player
* partner_guid - Your customer GUID assigned to you by RedLasso
* clipInfoCallback (optional) - specify a callback function to execute
*     after the player has finished loading. 
*/
function playEmbed(resourceId, partner_guid, clipInfoCallback) {
    swfobject.embedSWF(api.getPlayer(), pageElements.get('playerObj'), pageElements.get('playerWidth'), pageElements.get('playerHeight'), "8", "expressInstall.swf",
		       { embedId: resourceId, pid: partner_guid },
		       { allowScriptAccess: "always", allowFullScreen: "true" },
		       { xiRedirectUrl: location.href });

    //if there's a callback function, supply the clip info
    if (clipInfoCallback) {
        api.Clip.getClipInfo(new Array(resourceId), function(data)
			     { clipInfoCallback(data[0]); });
    }

    //If this is the first play, set initialPlay to false 
    //since the next time won't be the first play anymore
    if (initialPlay == true) initialPlay = false;
}

/* ---Description---
* The getParam function is used to collect parameters from the URL
* of the page. This is used in a case when a clip guid is specified
* in the URL, defaulting the player to that clip first.
* ---Parameters---
* name - The name of the parameter of which we want the value
*/
function getParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

/* ---Description---
* The selectClip function is used as the onclick function for
* the clips in this example. Each clip DIV on the right-hand side
* uses this function to call the playEmbed function as well as to
* highlight itself as the currently clicked clip. The additional
* clips are iterated through to set them back to the unselected state
* ---Parameters---
* resourceId - The GUID of the clip that is to be loaded into the player
* element - The HTML element that should be set to the active clip state.
*     In this example, each div passes itself(this) through to the function.
*/
function selectClip(resourceId, element) {
    //first set all the popular clips to default class
    var clipDivs = $A($(pageElements.get('ftClipResContainer')).childNodes);
    clipDivs.each(function(clipDiv) {
        $(clipDiv).removeClassName("rl_clipON");
    });

    //now do it again for the regular clips
    var clipDivs = $A($(pageElements.get('clipResContainer')).childNodes);
    clipDivs.each(function(clipDiv) {
        $(clipDiv).removeClassName("rl_clipON");
    });

    if (element) $(element).addClassName("rl_clipON");
    playEmbed(resourceId, PARTNER_GUID, populateClipInfo);
}

/* ---Description---
* The populateFeaturedClips funtion is used to fill in the given element
* with the popular clips for the data provided. Featured clips are useful
* so that a RedLasso customer can set clips they want always shown.
* ---Parameters---
* elementId - The ID of the HTML element that should contain the results
* term - An optional term that can be used to limit the results (similar to search)
* cat - An optional category can be used to limit the results to a specific category
* limit - The amount of results to show on the page.
*/
function populateFeaturedClips(elementId, term, cat, limit) {
    api.Clip.getPopularClips(term, cat, POP_PARTNER_GUID, limit, function(data) {
        if (data != null) {
            //The paginator is used to store all of the results from the clipSearch
            //and only display the amount of clips specified per page.
            ftPaginator = new RedLasso.Util.Paginator(data, api, buildFtClips, limit);
            //If we're going to paginate the featured results, set it up...
            if (FT_PAGINATION) {
                //Below is used to handle the display of the nav buttons for the paginator
                if (data.length <= FT_CLIPS_PER_PAGE) {
                    if ($(pageElements.get('ftPrevBttn')).style.display != "none") $(pageElements.get('ftPrevBttn')).fade();
                    if ($(pageElements.get('ftNextBttn')).style.display != "none") $(pageElements.get('ftNextBttn')).fade();
                }
                else {
                    if ($(pageElements.get('ftPrevBttn')).style.display != "none") $(pageElements.get('ftPrevBttn')).fade();
                    if ($(pageElements.get('ftNextBttn')).style.display == "none") $(pageElements.get('ftNextBttn')).appear();
                }
            }
            //For this site, we want the player to default load the first popular clip
            //but only if a clip has NOT yet been played in the player.
            if (initialPlay) {
                selectClip(data[0]);
            }
        }
        else {
            $(elementId).innerHTML = "<i>No results.</i>";
            //If we have pagination, hide the buttons...
            if (FT_PAGINATION) {
                if ($(pageElements.get('ftPrevBttn')).style.display != "none") $(pageElements.get('ftPrevBttn')).fade();
                if ($(pageElements.get('ftNextBttn')).style.display != "none") $(pageElements.get('ftNextBttn')).fade();
            }
        }
    });
}

/* ---Description---
* The searchClips function is used to limit the search results based 
* on a user's query. The results are then populated in the given element.
* Unlike populatePopularClips, the limit of searchClips is not how many elements
* are displayed on the page, but rather how many results are available to page through.
* ---Parameters---
* elementId - The ID of the HTML element that should contain the results
* term - An search term that is used to limit the results
* cat - A category can be used to limit the results to a specific category
* limit - The amount of results to show on each page of results.
*     **NOTE: the limit does NOT specify the number of results, rather it is the
*          amount of elements on each page of results. To limit the amount of 
*          results returned, the global variable MAX_RESULTS must be changed.
*/
function searchClips(elementId, term, cat, limit) {
    api.Clip.searchClipsWithFilter(term, cat, PARTNER_GUID, MAX_RESULTS, 'channel', currentChan, function(data) {
        if (data != null) {
            //The paginator is used to store all of the results from the clipSearch
            //and only display the amount of clips specified per page.
            paginator = new RedLasso.Util.Paginator(data, api, buildClips, limit);
            //Below is used to handle the display of the nav buttons for the paginator
            if (data.length <= CLIPS_PER_PAGE) {
                if ($(pageElements.get('prevBttn')).style.display != "none") $(pageElements.get('prevBttn')).fade();
                if ($(pageElements.get('nextBttn')).style.display != "none") $(pageElements.get('nextBttn')).fade();
            }
            else {
                if ($(pageElements.get('prevBttn')).style.display != "none") $(pageElements.get('prevBttn')).fade();
                if ($(pageElements.get('nextBttn')).style.display == "none") $(pageElements.get('nextBttn')).appear();
            }

            if (initialPlay) {
                selectClip(data[0]);
            }
        }
        else {
            $(elementId).innerHTML = "<i>No results.</i>";
            if ($(pageElements.get('prevBttn')).style.display != "none") $(pageElements.get('prevBttn')).fade();
            if ($(pageElements.get('nextBttn')).style.display != "none") $(pageElements.get('nextBttn')).fade();
        }
    });
}

/* ---Description---
* The doSearch function is a helper function for searchClips
* that grabs the user's selected category and search query
* from the HTML elements
*/
function doSearch() {
    var term = $F(pageElements.get('searchField'));
    var cat = "ALL"; //$F("clipCategory");
    searchClips(pageElements.get('clipResContainer'), term, cat, CLIPS_PER_PAGE);
    Effect.Pulsate(pageElements.get('searchButton'), { from: 0.4, pulses: 2 });
}

/* ---Description---
* checkSearch is a helper function for doSearch that checks
* to see if the Enter key has been pressed in a given element
* allowing the user to skip the step of clicking the Search button.
* In this example, the checkSearch function is applied to the onkeyup
* of the filterTerms input box.
* ---Parameters---
* element - The element to check to see if the key has been pressed in
* event - The event that has occured
*/
function checkSearch(element, event) {   //If the enter key has been pressed, do the search
    if (event.keyCode == 13) doSearch();
}

/* ---Description---
* The buildClips function is used to take the results of the searchClips
* function and construct a visible resultset inside the given HTML element. 
* In this example, an individually formatted div is created for each
* displayed clip, including a thumbnail, title, and airdate. In this example,
* the buildClips function is called by the JS-API's Paginator object.
* ---Parameters---
* data - The resultset of clips and clipinfo
* elementID - The ID of the element to build the results inside
* opt_fn (optional) - An optional callback function called after the build is complete.
*     In this example, the opt_fn is utilized after popularClips are finised building
*     to load the first clip into the player. 
*/
var test = new Array();
function buildClips(data, elementID, opt_fn) {
    if (!elementID) elementID = pageElements.get('clipResContainer');
    $(elementID).innerHTML = "";
    var idSuffix = (elementID == pageElements.get('ftClipResContainer')) ? '_ftdiv' : '_div';

    for (var i = 0; i < data.length; i++) {
        //The following is used to limit the title length to fit in the DIV element
	var clip = data[i];
        var title = clip.t;

	// duration:
	var durMin = Math.floor(clip.d / 60);
	var durSec = clip.d - (durMin * 60);
	var dur = durMin + ":" + durSec;

        var id = data[i].g + idSuffix

        if (title.length > 25)
            title = title.substr(0, 25) + "...";


        // using DOM methods for the outer div ensures we have a reference to the element
        // avoids a race condition that was throwing some errors when trying to fetch this
        
        var newEl = new Element('div', {title: data[i].t, 'class': 'rl_clip', id: id});
        newEl.setAttribute('class', 'rl_clip'); // needed for IE8, prototype does set class correctly
        newEl.style.display = 'none';
        newEl.observe('click', function(){
            selectClip(this.id.substring(0, this.id.lastIndexOf('_')), this);
            Effect.Pulsate(this, {pulses:1,from:0.3,duration:1.0});
        });


        //Formatting the airdate to make it look presentable
        var airDate = data[i].aired.substr(0, data[i].aired.indexOf(" "));

        //Below is where the clip's div is generated and attached to the containing element
        var html = "<img id=\"" + data[i].g + "_img\" src=\"" + data[i].thumburl + "\"/><div class='title'>" + title + "<div class='clipTime'>Duration: " + dur + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date: " + airDate + "</div></div>";
        newEl.innerHTML = html;

        $(elementID).insert(newEl);

        var timeout = 500 + (i * 100);
        Effect.Appear.delay(timeout / 1000, newEl, {duration: 1.0});

    }

    if (opt_fn) opt_fn();
}
//This is a helper function for dealing with featured clips and a paginator...
//I know there should be a better way by refactoring the paginator, but
//I don't have the time or willpower to do it!
function buildFtClips(data, elID) {
    if (!elementID) elementID = pageElements.get('ftClipResContainer');
    $(elementID).innerHTML = "";

    var idSuffix = '_ftdiv'; 

    for (var i = 0; i < data.length; i++) {
        //The following is used to limit the title length to fit in the DIV element
	clip = data[i];
        var title = clip.t;

        if (title.length > 23)
            title = title.substr(0, 23) + "...";

        //Formatting the airdate to make it look presentable
        var airDate = data[i].aired.substr(0, data[i].aired.indexOf(" "));

        //Below is where the clip's div is generated and attached to the containing element
        var html = "<div title='" + data[i].t + "' onclick=\"javascript:selectClip('" + data[i].g + "',this);Effect.Pulsate(this,{pulses:1,from:0.3,duration:1.0});\" class='rl_clip' id='" + data[i].g + idSuffix + "' style='display:none;'><img id=\"" + data[i].g + "_img\" src=\"" + data[i].thumburl + "\"/><div class='title'>" + title + "<div class='clipTime'>" + airDate + /*"<br />Views: " + clip.views +*/ "</div></div></div>";
        $(elementID).innerHTML = $(elementID).innerHTML + html;
    }

    //Now for some scriptaculous stuff....yay pretty...                                                                                                                      
    for (var i = 0; i < data.length; i++) {
        var elementID = data[i].g + idSuffix;
        test[i] = elementID;
        var timeout = 500 + (i * 100);
        setTimeout("Effect.Appear('" + elementID + "', { duration: 1.0 });", timeout);
    }

}

/* ---Description---
* This is a helper function for the paginator that is attached to the
* onclick of the next button. It handles getting the next set of results
* as well as making sure the nav buttons are enabled/disabled depending
* on the remaining results
*/
function getNext() {
    $(pageElements.get('clipResContainer')).innerHTML = "Loading...";
    if (paginator.next()) {
        $(pageElements.get('nextBttn')).observe('click', getNext);
        if ($(pageElements.get('nextBttn')).style.display == "none") $(pageElements.get('nextBttn')).appear();
    }
    else {
        $(pageElements.get('nextBttn')).stopObserving('click', getNext);
        if ($(pageElements.get('nextBttn')).style.display != "none") $(pageElements.get('nextBttn')).fade();
    }
    $(pageElements.get('prevBttn')).observe('click', getPrev);
    if ($(pageElements.get('prevBttn')).style.display == "none") $(pageElements.get('prevBttn')).appear();
}

/* ---Description---
* This is a helper function for the paginator that is attached to the
* onclick of the previous button. It handles getting the previous set of results
* as well as making sure the nav buttons are enabled/disabled depending
* on the remaining results
*/
function getPrev() {
    $(pageElements.get('clipResContainer')).innerHTML = "Loading...";
    if (paginator.prev()) {
        $(pageElements.get('prevBttn')).observe('click', getPrev);
        if ($(pageElements.get('prevBttn')).style.display == "none") $(pageElements.get('prevBttn')).appear();
    }
    else {
        $(pageElements.get('prevBttn')).stopObserving('click', getPrev);
        if ($(pageElements.get('prevBttn')).style.display != "none") $(pageElements.get('prevBttn')).fade();
    }
    $(pageElements.get('nextBttn')).observe('click', getNext);
    if ($(pageElements.get('nextBttn')).style.display == "none") $(pageElements.get('nextBttn')).appear();
}

/********************
*** Global Vars  ***
*******************/
//Used to limit the searchClips results to a specific customer's clips
var PARTNER_GUID = "5bcc2fd2-25e7-408b-acc3-a9b243e17524";
//Used to limit the populatePopularClips results to a specific customer's clips
var POP_PARTNER_GUID = "5bcc2fd2-25e7-408b-acc3-a9b243e17524";
//The maximum amount of results to return to the paginator for searchClips
var MAX_RESULTS = 50;
//The amount of clips per page the paginator should show
var CLIPS_PER_PAGE = 4;
//The amount of popular clips per page the paginator should show
var FT_CLIPS_PER_PAGE = 4;
//This var is used to determine if the Featured Clips should include pagination
var FT_PAGINATION = false;
//This var is a boolean used to determine if the clip being loaded is the first one to be played
var initialPlay = true;
//The current channel selected to be searched on
var currentChan = "";
//Instantiation of the RedLasso JS-API
var api = new RedLasso.Util.JSAPI();
//Declaration of the var used for the JS-API Paginator
var pageinator;
var ftPaginator;

var pageElements = new Hash();
pageElements.set('playerObj', 'rl_FPlayer_obj');
pageElements.set('playerWidth', '357');
pageElements.set('playerHeight', '290');
pageElements.set('searchButton', 'rl_search_button');
pageElements.set('searchField', 'rl_search_field');
pageElements.set('ftClipResContainer', 'rl_featured_results');
pageElements.set('clipResContainer', 'rl_clip_results');
pageElements.set('prevBttn', 'rl_prev_button');
pageElements.set('nextBttn', 'rl_next_button');