/* ---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 rlmc_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 rlmc_selectClip(resourceId, element) {
    //first set all the popular clips to default class
//    var clipDivs = $A($(pageElements.get('rlmc_popClipResContainer')).childNodes);
  //  clipDivs.each(function(clipDiv) {
//        $(clipDiv).removeClassName("rl_clipON");
//    });

    //now do it again for the regular clips
    var clipDivs = $A($(pageElements.get('rlmc_clipResContainer')).childNodes);
    clipDivs.each(function(clipDiv) {
        $(clipDiv).removeClassName("rl_clipON");
    });

    if (element) $(element).addClassName("rl_clipON");
    rlmc_playEmbed(resourceId, PARTNER_GUID, rlmc_populateClipInfo);
}

/* ---Description---
* The populatePopularClips funtion is used to fill in the given element
* with the popular clips for the data provided. Popular clips is 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 rlmc_populatePopularClips(elementId, term, cat, limit) {
    api.Clip.getPopularClips(term, cat, POP_PARTNER_GUID, limit, function(data) {
        if (data != null
           && data.length > 0) {
            //The paginator is used to store all of the results from the clipSearch
            //and only display the amount of clips specified per page.
            rlmc_popPaginator = new RedLasso.Util.Paginator(data, api, rlmc_buildPopClips, limit);
            //Below is used to handle the display of the nav buttons for the paginator
            if (data.length <= RLMC_POP_CLIPS_PER_PAGE) {
                $(pageElements.get('rlmc_popPrevBttn')).fade();
                $(pageElements.get('rlmc_popNextBttn')).fade();
            }
            else {
                $(pageElements.get('rlmc_popPrevBttn')).fade();
                $(pageElements.get('rlmc_popNextBttn')).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) {
                rlmc_selectClip(data[0]);
            }
        }
        else {
            $(elementId).innerHTML = "<i>No results.</i>";
            $(pageElements.get('rlmc_popPrevBttn')).fade();
            $(pageElements.get('rlmc_popNextBttn')).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 rlmc_searchClips(elementId, term, cat, limit) {
    var channel = (rlmc_currentChan == "all") ? "" : rlmc_currentChan;
    api.Clip.searchClipsWithFilter(term, cat, PARTNER_GUID, RLMC_MAX_RESULTS, 'channel', channel, function(data) {
        if (data != null
           && data.length > 0) {
            //The paginator is used to store all of the results from the clipSearch
            //and only display the amount of clips specified per page.
            rlmc_paginator = new RedLasso.Util.Paginator(data, api, rlmc_buildClips, limit);

            //Below is used to handle the display of the nav buttons for the paginator
            if (data.length <= RLMC_CLIPS_PER_PAGE) {
                $(pageElements.get('rlmc_prevBttn')).fade();
                $(pageElements.get('rlmc_nextBttn')).fade();
            }
            else {
                $(pageElements.get('rlmc_prevBttn')).fade();
                $(pageElements.get('rlmc_nextBttn')).appear();
            }

            if (initialPlay) {
                rlmc_selectClip(data[0]);
            }
        }
        else {
            $(elementId).innerHTML = "<i>No results.</i>";
            $(pageElements.get('rlmc_prevBttn')).fade();
            $(pageElements.get('rlmc_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 rlmc_doSearch() {
    var term = $F(pageElements.get('rlmc_searchField'));
    var cat = "ALL"; //$F("clipCategory");
    rlmc_searchClips(pageElements.get('rlmc_clipResContainer'), term, cat, RLMC_CLIPS_PER_PAGE);
    Effect.Pulsate(pageElements.get('rlmc_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 rlmc_checkSearch(element, event) {   //If the enter key has been pressed, do the search
    if (event.keyCode == 13) rlmc_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 rlmc_buildClips(data, elementID, opt_fn) {
    if (!elementID) elementID = pageElements.get('rlmc_clipResContainer');

    var container = $(elementID);
    container.innerHTML = "";

    var idSuffix = '_rlmcdiv';

    for (var i = 0; i < data.length; i++) {
        //The following is used to limit the title length to fit in the DIV element
        var title = data[i].t;
        if (title.length > 50)
            title = title.substr(0, 50) + "...";
        //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 id = data[i].g + idSuffix;

	var newEl = new Element('div', {title: data[i].t, 'class': 'rl_clip', id: id });
	newEl.style.display = 'none';
	newEl.observe('click', function(){
	    
	    rlmc_selectClip(this.id.substring(0, this.id.lastIndexOf('_')), this);
	    Effect.Pulsate(this, {pulses:1,from:0.3,duration:1.0});
	});

	container.insert(newEl);

	var html = "<img id=\"" + data[i].g + "_img\" src=\"" + data[i].thumburl + "\"/><div class='title'>" + title + "<br/>Aired: " + airDate + "</div></div>";
	newEl.innerHTML = html;

	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 Pop 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 rlmc_buildPopClips(data) {
    rlmc_buildClips(data, pageElements.get('rlmc_popClipResContainer'));
}

/* ---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 rlmc_getNext() {
    $(pageElements.get('rlmc_clipResContainer')).innerHTML = "Loading...";
    if (rlmc_paginator.next()) {
        $(pageElements.get('rlmc_nextBttn')).observe('click', rlmc_getNext);
        $(pageElements.get('rlmc_nextBttn')).appear();
    }
    else {
        $(pageElements.get('rlmc_nextBttn')).stopObserving('click', rlmc_getNext);
        $(pageElements.get('rlmc_nextBttn')).fade();
    }
    $(pageElements.get('rlmc_prevBttn')).observe('click', rlmc_getPrev);
    $(pageElements.get('rlmc_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 rlmc_getPrev() {
    $(pageElements.get('rlmc_clipResContainer')).innerHTML = "Loading...";
    if (rlmc_paginator.prev()) {
        $(pageElements.get('rlmc_prevBttn')).observe('click', getPrev);
        $(pageElements.get('rlmc_prevBttn')).appear();
    }
    else {
        $(pageElements.get('rlmc_prevBttn')).stopObserving('click', getPrev);
        $(pageElements.get('rlmc_prevBttn')).fade();
    }
    $(pageElements.get('rlmc_nextBttn')).observe('click', getNext);
    $(pageElements.get('rlmc_nextBttn')).appear();
}

/* ---Description---
* This function is a helper function used to temporarily highlight a
* channel as the user roles over it
*/
function rlmc_highlightChannel(element) {
    if (rlmc_currentChan != element.id) {                                      
        element.style.backgroundColor = '#a6a6a6';
    }
}

function rlmc_unhighlightChannel(element){
    element.style.backgroundColor = '#01101b';
}

function rlmc_selectChannel(element) {
    if (!Object.isElement(element)) element = $(element);
    
    var channels = $('rl_mediaCenter_clip_channel_wrapper').childElements();
    channels.each(function(channel){
	channel.style.background = 'url("images/rl_mediaCenter/channel_star.png") no-repeat';
    });
    
    element.style.background = 'url("images/rl_mediaCenter/channel_star_selected.png") no-repeat';
    
    $('rl_mediaCenter_clipChannelTitle').innerHTML = element.innerHTML

    if (element.id.substring(0, 15) == 'rl_mediaCenter_'){
        rlmc_currentChan = element.id.substring(15);
    }
    else {
        rlmc_currentChan = element.id;
    }

    $("rl_mediaCenter_clip_search_field").value = "";
    rlmc_doSearch();
}

/* ---Description---
* The populateClipInfo function is an optional function used
* as the callback for the playEmbed function.
* It is simply used to add clip information to the info bar
* to the left of the player object.
* ---Parameters---
* info - the information about the current clip returned from
*     the API's getClipInfo function
*/
function rlmc_populateClipInfo(info) {
    //Clean up the duration...
    var dur = (info.d % 60).toString();
    if (dur.length != 2) dur = "0" + dur;
    dur = Math.floor(info.d / 60) + ":" + dur;

    $("rl_mediaCenter_np_title").innerHTML = info.t;
    $("rl_mediaCenter_np_details").innerHTML = "Aired: " + info.aired + "<br/>Duration: " + dur + " | Views: " + info.views;
    $("rl_mediaCenter_np_desc").innerHTML = unescape(info.dtl);

    //$("clipAuthor").innerHTML = info.author;
    //$("clipLink").href = info.stationurl;
    //$("clipSLogo").src = info.logo;    
}

function rlmc_channelActive(){
    $('rl_mediaCenter_clip_search_wrapper').hide();
    $('rl_mediaCenter_clip_channel_wrapper').show(); 
    $('rl_mediaCenter_clip_nav_channel').style.color = '#961c17';
    $('rl_mediaCenter_clip_nav_search').style.color = '#a6a6a6';
}

function rlmc_searchActive(){
    $('rl_mediaCenter_clip_search_wrapper').show();
    $('rl_mediaCenter_clip_channel_wrapper').hide();
    $('rl_mediaCenter_clip_nav_search').style.color = '#961c17';
    $('rl_mediaCenter_clip_nav_channel').style.color = '#a6a6a6';
}

/********************
*** Global Vars  ***
*******************/
//The maximum amount of results to return to the paginator for searchClips
var RLMC_MAX_RESULTS = 50;
//The amount of popular clips per page the paginator should show
var RLMC_POP_CLIPS_PER_PAGE = 4;
//The amount of clips per page the paginator should show
var RLMC_CLIPS_PER_PAGE = 9;
//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 rlmc_currentChan = "";

//Declaration of the var used for the JS-API Paginator
var rlmc_pageinator;
var rlmc_popPaginator;

pageElements.set('playerObj', 'rl_mediaCenter_FPlayer_obj');
pageElements.set('playerWidth', '392');
pageElements.set('playerHeight', '320');
pageElements.set('rlmc_searchButton', 'rl_mediaCenter_clip_search_button');
pageElements.set('rlmc_searchField', 'rl_mediaCenter_clip_search_field');
pageElements.set('rlmc_popPrevBttn', 'rl_mediaCenter_featured_prev_button');
pageElements.set('rlmc_popNextBttn', 'rl_mediaCenter_featured_next_button');
pageElements.set('rlmc_clipResContainer', 'rl_mediaCenter_clip_results');
pageElements.set('rlmc_popClipResContainer', 'rl_mediaCenter_featured_results');
pageElements.set('rlmc_prevBttn', 'rl_mediaCenter_clip_prev_button');
pageElements.set('rlmc_nextBttn', 'rl_mediaCenter_clip_next_button');

