﻿String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); }

window.onload = function() {
}

function onTemplateLoaded(pExperienceID) {
    Brightcove.playerAPIInit(pExperienceID);
}

//function to dynamically change the player rendered
function viewAccessiblePlayer() {

    //gather params
    var params = {};
    params.playerID = $j("#accessiblePlayerId").html().trim();
    params.playerKey = $j("#accessiblePlayerKey").html().trim();
    params.videoId = $j("#active-video").html().trim();
    params.autoStart = "false";
    params.bgcolor = "#FFFFFF";
    params.width = "490";
    params.height = "470";
    params.isVid = "true";
    params.isUI = "true";
    params.publisherID = $j("#publisherId").html().trim();
    params.dynamicStreaming = "true";
    params.wmode = "transparent";

    //create html container
    var player = brightcove.createElement("object");
    player.id = params.playerID;
    var parameter;
    for (var i in params) {
        parameter = brightcove.createElement("param");
        parameter.name = i;
        parameter.value = params[i];
        player.appendChild(parameter);
    }

    //switch the player
    var playerContainer = document.getElementById("playerContainer");
    $j('#playerContainer').html('');
    $j('#viewAP').hide();
    $j('#viewRP').show().removeClass("hide");
    
    brightcove.createExperience(player, playerContainer, true);
}

//function to dynamically change the player rendered
function viewLivePlayer() {

    //gather params
    var params = {};
    params.playerID = $j("#playerId").html().trim();
    params.playerKey = $j("#playerKey").html().trim();
    params.videoId = $j("#active-video").html().trim();
    params.autoStart = "false";
    params.bgcolor = "#FFFFFF";
    params.width = "615";
    params.height = "400";
    params.isVid = "true";
    params.isUI = "true";
    params.publisherID = $j("#publisherId").html().trim();
    params.dynamicStreaming = "true";
    params.wmode = "transparent";

    //create html container
    var player = brightcove.createElement("object");
    player.id = params.playerID;
    var parameter;
    for (var i in params) {
        parameter = brightcove.createElement("param");
        parameter.name = i;
        parameter.value = params[i];
        player.appendChild(parameter);
    }

    //switch the player
    var playerContainer = document.getElementById("playerContainer");
    $j('#playerContainer').html('');
    $j('#viewRP').hide();
    $j('#viewAP').show();

    brightcove.createExperience(player, playerContainer, true);
}

$j(document).ready(function() {

    // preload some images    
    if (document.images) {
        preload_image_object = new Image();
        image_url = new Array();
        image_url[0] = baseUrl + 'content/img/play_overlay.png';
        image_url[1] = baseUrl + 'content/img/play_overlay-120.png';
        var i = 0;
        for (i = 0; i <= 1; i++)
            preload_image_object.src = image_url[i];
    }

    Brightcove.pagingStart = parseInt($j("#p-start").html());
    Brightcove.pagingEnd = parseInt($j("#p-end").html());
    Brightcove.pagingTotal = parseInt($j("#p-total").html());
    Brightcove.pageSize = parseInt($j("#pageSize").html().trim());
    Brightcove.currentPage = parseInt($j("#pageNum").html().trim());

    // handle user clicking on sub navigation
    $j('.subnav-item').live('click', function() {
        $j('#pageSearch').html($j(this).attr('tags'));
        $j('#pageSearchSeo').html($j(this).attr('seo'));
        $j('#columns').html('2');
        $j('#video-title h2').html($j(this).html());
        $j('#secTitle').html($j(this).attr('name'));
        $j('#subnav li').each(function(index) {
            $j(this).removeClass("active");
        });

        $j('.dropdown-trigger').html('<span></span>' + $j(this).html());

        $j(this).parent().addClass("active");
        Brightcove.currentCategory = $j(this).html();
        Brightcove.currentPage = 0;
        Brightcove.RefreshLibrary(Brightcove.currentPage);
    });

    // handle user clicking on sub navigation
    $j('.nav-item').live('click', function() {
        $j('#pageSearch').html($j(this).attr('tags'));
        $j('#pageSearchSeo').html($j(this).attr('seo'));
        $j('#columns').html('3');
        $j('#video-title h2').html($j(this).html());
        $j(this).addClass("active");
        Brightcove.currentCategory = $j(this).html();
        Brightcove.currentPage = 0;
        Brightcove.RefreshSubNavigation();
        Brightcove.RefreshLibrary(Brightcove.currentPage);
    });

    // handle ajax video playing
    $j('.play').live('click', function() {

        var id = $j(this).attr("vid");
        $j('.sub-grid li').removeClass('active');
        $j(this).parent().addClass('active');
        Brightcove.activeVideo = id;
        Brightcove.loadVideo(id);
        $j('#video-info').html($j('#v-details-' + id).html());

    });


    // handle click to visit other sites in footer
    $j('#sites-go').bind('click', function() {
        window.location = $j('#site-list').val();
    });

    //bind pagination click to page classes
    $j('.page').live('click', function() {

        // get data about click
        var data = $j(this).attr("id").split('-');
        var page = data[1];
        if (data.length == 3) page = data[2];

        var pagingTotal = parseInt($j('#pagingTotal').html());
        var pagingLimit = parseInt($j('#pagingLimit').html());

        // handle next and previous links
        var last = 0;
        $j('.page').each(function(index) {
            if ($j(this).attr("id") != "page-prev" && $j(this).attr("id") != "page-next") {
                var lastData = $j(this).attr("id").split('-');
                last = lastData[1];
            }
        });

        // if large paging, set last page as pagingTotal
        if (pagingTotal > last) last = pagingTotal - 1;

        // remove active indicator from current active page
        $j('#page-' + Brightcove.currentPage).removeClass('active');

        // handle display of next and previous buttons
        if (page == "next") page = (Brightcove.currentPage + 1);
        if (page == "prev") page = (Brightcove.currentPage - 1);
        if (page < 0) page = 0;

        // handle page walking
        if (pagingTotal > pagingLimit) {
            if (parseInt(page) > 2) {
                var startCnt = page - 2;
                $j('.page').each(function(index) {
                    if ($j(this).attr("id") != "page-prev" && $j(this).attr("id") != "page-next") {
                        if ((startCnt + 1) <= pagingTotal) {
                            $j(this).attr("title", "Page " + (startCnt + 1));
                            $j(this).attr("id", "page-" + startCnt);
                            $j(this).html(startCnt + 1);
                            $j(this).show();
                        } else {
                            $j(this).hide();
                        }
                        startCnt++;
                    }
                });
            } else if (Brightcove.currentPage > 2) {
                var startCnt = 0;
                $j('.page').each(function(index) {
                    if ($j(this).attr("id") != "page-prev" && $j(this).attr("id") != "page-next") {
                        $j(this).attr("title", "Page " + (startCnt + 1));
                        $j(this).attr("id", "page-" + startCnt);
                        $j(this).html(startCnt + 1);
                        $j(this).show();
                        startCnt++;
                    }
                });
            }
        }

        // handle display of next and previous buttons
        if (last == page) {
            $j('#page-next').hide();
        } else {
            $j('#page-next').show();
        }
        if (page == 0) {
            $j('#page-prev').hide();
        } else {
            $j('#page-prev').show();
        }

        // handle current page indication
        $j('#page-' + page).addClass('active');
        Brightcove.currentPage = page;
        // display loading icon
        $j('.liGrid').each(function(index) {
            $j(this).html('<img alt="loader" src="' + baseUrl + 'content/img/bc/ajax-loader.gif" id="loading" />');
        });
        // refresh videos
        Brightcove.RefreshLibrary(page);
        // set new current page
        Brightcove.currentPage = parseInt(page);
    });

    // bind sorting click to sorting classes
    $j('.sort-option').live('click', function() {
        var data = $j(this).attr("id").split('-');
        var height = $j('#data').height();
        // display loading icon
        $j('#video-library').html('<div id="loading"><img alt="loader" src="' + baseUrl + 'content/img/ajax-loader.gif" /></div>');
        // toggle sort icons
        $j('#sort-' + Brightcove.sortBy).removeClass('active');
        $j('#sort-' + data[1]).addClass('active');
        // set sort value
        Brightcove.sortBy = data[1];

        Brightcove.currentPage = 0;

        // reset active flags
        $j('.page').each(function(index) {
            if ($j(this).attr("id") != "page-previous" && $j(this).attr("id") != "page-next") {
                $j(this).removeClass('active');
            }
        });

        var pagingTotal = parseInt($j('#pagingTotal').html());
        if (pagingTotal > 1) $j('#page-next').show();

        $j('#page-previous').hide();
        $j('#page-' + Brightcove.currentPage).addClass('active');
        // refresh videos
        Brightcove.RefreshLibrary(Brightcove.currentPage);
    });

});

var Brightcove = {
    //related, newest, popular, alphabetical, featured, none
    baseUrl: '',
    sortBy: 'newest',
    // stores the active paging
    activeSubNav: '',
    currentPage: 0,
    pagingTotal: 0,
    pagingStart: 0,
    pagingEnd: 0,
    pageSize: 0,
    currentCategory: '',
    // load video in player
    loadVideo: function(pVideoID) {
        if (Brightcove.menuModule.isMenuPageShowing()) {
            Brightcove.menuModule.closeMenuPage();
        }
        this.videoPlayerModule.loadVideo(pVideoID);
    },
    // initialize experience
    playerAPIInit: function(pExperienceID) {
        this.bcPlayer;
        this.videoPlayerModule;
        this.bcPlayer = brightcove.getExperience(pExperienceID);
        this.videoPlayerModule = this.bcPlayer.getModule(APIModules.VIDEO_PLAYER);
        this.experienceModule = this.bcPlayer.getModule(APIModules.EXPERIENCE);
        this.menuModule = this.bcPlayer.getModule(APIModules.MENU);
    },
    // refresh video library
    RefreshLibrary: function(page) {
        var searchTerm = $j("#pageSearch").html().trim();
        var searchTermSeo = $j("#pageSearchSeo").html().trim();
        var columns = $j("#columns").html().trim();
        var videoId = $j("#active-video").html().trim();
        var country = $j("#country").html().trim();
        var language = $j("#language").html().trim();
        $j.ajax({
            url: baseUrl + "search/refreshLibrary/ajax/?country=" + country + "&language=" + language,
            data: ({ page: page, searchTerm: searchTerm, searchType: "category", renderLibrary: "grid", sortBy: this.sortBy, columns: columns, searchTermSeo: searchTermSeo, videoId: videoId, currentCategory: this.currentCategory }),
            success: function(data) {
                var content = data.trim();
                $j('#ajax-library').html(content);
            }
        });
    },
    // refresh subNavigation
    RefreshSubNavigation: function() {
        var searchTermSeo = $j("#pageSearchSeo").html().trim();
        $j.ajax({
            url: baseUrl + "search/refreshSubNavigation/ajax/",
            data: ({ seoUrl: searchTermSeo }),
            success: function(data) {
                var content = data.trim();
                $j('#ajax-subNavigation').html(content);
            }
        });
    },
    // refresh pagination
    RefreshPagination: function(page) {
        if ($j("#pageSearch").html()) 
        {
            var searchTerm = $j("#pageSearch").html().trim();
            var searchTermSeo = $j("#pageSearchSeo").html().trim();
            var total = parseInt($j("#pagingTotal").html().trim());
            var pageSize = parseInt($j("#pageSize").html().trim());
            $j.ajax({
                url: baseUrl + "search/refreshPagination/ajax/",
                data: ({ page: page, searchTerm: searchTerm, seoUrl: searchTermSeo, pageSize: pageSize, totalCount: total }),
                success: function(data) {
                    var content = data.trim();
                    $j('#ajax-pagination').html(content);
                }
            });
        }
    },
    // update pagination summary for videos
    UpdatePagingSummary: function() {
        var pageStart = 1;
        if (this.currentPage > 0) pageStart = (this.currentPage * this.pageSize) + 1;
        var pageEnd = this.pageSize;
        if (this.currentPage > 0) {
            if (((this.currentPage + 1) * this.pageSize) > this.pagingTotal)
                pageEnd = this.pagingTotal;
            else
                pageEnd = (this.currentPage + 1) * this.pageSize;
        } else {
            if (this.pagingTotal < this.pageSize)
                pageEnd = this.pagingTotal;
        }
        $j("#p-start").html(pageStart);
        $j("#p-end").html(pageEnd);
    },
    ValidateSearch: function() {
        var term = $j('#term').val();
        if (term == "Search Videos" || term.trim().length == 0) {
            alert("Please enter a search term");
            return false;
        } else {
            //term = term.replace(/>/g, term).replace(/</g, term);
            $j('#term').val(escape(term));
            return true;
        }
    }
};


