// Brightcove V3 API wrapper. 

VideoPlayer = function (){
    var bcExp;
    var modVP;
    var modExp;
    var modContent;
    var modSocial;
    var startFlag = true;
    var customVideo = null;
    var loaded = false;
    var sortedList = null;

    return {
        onVideoLoad: function(evt){
            this.currentVideo = evt.video;
            VideoPlayer.modSocial.setLink(url_for_video(this.currentVideo.id));
            $(VideoPlayer).trigger('videoLoaded');
        },
        onVideoChange: function(evt){
            VideoPlayer.modSocial.setLink(url_for_video(VideoPlayer.getCurrentVideo().id));
            $(VideoPlayer).trigger('videoChanged');
        },
        playVideo: function(id){this.customVideo = id;this.modVP.loadVideo(id);},
        cueVideo: function(id){this.modVP.cueVideo(id)},
        cueFirstVideo: function(){
            var firstItem = VideoPlayer.sortedList[0];
            if (firstItem) this.cueVideo(VideoPlayer.sortedList[0].id);
        },
        scrollTo: function(newIndex){
            var list = this.modExp.getElementByID('videoList');
            list.scrollTo(newIndex);
        },
        getCurrentVideo: function(){return this.modVP.getCurrentVideo();},
        getCurrentList: function() {return this.modContent.getAllPlaylists()},
        tabVisibility: function(opt) {this.modExp.getElementByID('playlistTabs').setVisible(opt);},
        onContentLoad: function(){$(VideoPlayer).trigger('contentLoaded');},
        makeTime: function(ms){
            // Makes a nice readable time from the video length. 
            var sec = parseInt(ms/1000);
            var min = parseInt(sec/60);
            sec = sec - min *60;
            var secStr = sec<10? ('0'+sec): sec;
            return min+":"+secStr;
        },
        buildList: function(items,name,opts){
            // Constructs a HTML playlist for the given array of videos and the given title. 
            var defaults = {
                withSerial: true,
                withResultSet: true,
                withTitle: true,
                withTime: true,
                withDescription: false,
                withCombinedTime: false              
            };
            var opts = $.extend(defaults, opts);
            var clear = $('<div>').addClass('clearFloat');
            var list = $('<ul>');
            var serialNum = '';
            $(items).each(function(index, video) {
                var item = $('<li>');
                item.append($('<div>').addClass('thumbnail').append($('<img>').attr('src',video.thumbnailURL)));
                if (opts.withSerial) serialNum = (index+1)+'. ';
                if (opts.withTitle) item.append($('<div>').addClass('desc').text(serialNum+video.name));
                var time = VideoPlayer.makeTime(video.length);
                if (opts.withDescription) item.append($('<div>').addClass('shortDesc').text(video.shortDescription.slice(0,60) + ((opts.withCombinedTime)? " ("+time+")":"")));
                if (opts.withTime) item.append($('<div>').addClass('time').text(time));
                item.append($('<div>').css({height: '0'}).addClass('id offscreenText').text(video.id));
                item.append(clear.clone());
                var id = video.id;
                item.click(function() {
                    VideoPlayer.playVideo(id);
                });
                list.append(item);      
            });
            var num = items.length;
            var heading = $('<div>').addClass('heading');
            heading.html('<h3>'+name+'</h3><span class="info">1 to '+num+' of '+num+'</span>');

            var divList = $('<div>').addClass('list').append(list);
            return $('<div>').addClass('set').append(heading).append(clear.clone()).append(divList).append(clear.clone());    
        },
        separateIntoTypesBasedOnDate: function(items){
            // Accepts the video list returned by BC and returns a hash of videos, audio and photos, sorted by publishing date.
            items = items.sort(function(a,b){
					aLastModifiedDate = parseInt(a.lastModifiedDate);
					bLastModifiedDate = parseInt(b.lastModifiedDate);
					if(aLastModifiedDate == bLastModifiedDate) return 0;
					else if (aLastModifiedDate < bLastModifiedDate) return 1;
					else return -1;
				});
            separatedVideos = VideoPlayer.separateIntoTypes(items);
            return separatedVideos;
        },
        separateIntoTypes: function(items){
            var videos = $.grep(items,function(video){if ($.inArray("video",video.tags) > -1) return true;});
            var audios = $.grep(items,function(video){if ($.inArray("audio",video.tags) > -1) return true;});
            var photos = $.grep(items,function(video){if ($.inArray("photos",video.tags) > -1) return true;});
            return {'videos': videos, 'audios': audios, 'photos':photos};                        
        },
		getCountrySpecificItems: function(items){
			if(typeof(country) != 'undefined'){
				return $.grep(items,function(item){if ($.inArray(country,item.tags) > -1) return true;});
			}else{
				return items;
			}
		},
        doSearch: function(text,id,command,callback)
        {   
            if (!text || (typeof text != "string") || text=="" ) return;
            var search_str = $.trim(text);
            this.executeJSONSearch(command, search_str, function(data){
                separatedVideos = VideoPlayer.separateIntoTypesBasedOnDate(VideoPlayer.getCountrySpecificItems(data.items));            
                VideoPlayer.sortedList = new Array();
                VideoPlayer.sortedList  = VideoPlayer.sortedList.concat(separatedVideos.videos, separatedVideos.audios, separatedVideos.photos);
                var clear = $('<div>').addClass('clearFloat');
                var videoList = separatedVideos.videos.length > 0 ? VideoPlayer.buildList(separatedVideos.videos,"Video"):null;
                var audioList = separatedVideos.audios.length > 0 ? VideoPlayer.buildList(separatedVideos.audios,"Audio"):null;
                var photoList = separatedVideos.photos.length > 0 ? VideoPlayer.buildList(separatedVideos.photos,"Photo"):null;
                var noResult = null;
                if (!videoList&&!audioList&&!photoList) noResult = $('<div class="set"><div class="heading"><h3>No results found.</h3><div class="clearFloat"></div></div></div>');
                $(id).append(clear.clone()).append(noResult).append(videoList).append(clear.clone()).append(audioList).append(clear.clone()).append(photoList).append(clear.clone());
                if (callback) callback(data.items);
            });
        },
        executeJSONSearch: function(command, keywords, action){
            // Calls action with the returned JSON.. use data.items to get the video list. 
            var param_key = ''
            if (command == 'find_videos_by_text') {param_key = 'text'} else {param_key = 'or_tags'}
            brightcove_url = "http://api.brightcove.com/services/library?token=" + token + "&command=" + command + "&" + param_key + "=" + keywords
            $.getJSON(brightcove_url + "&callback=?", action);
        },        
        initialize: function(pEvent){
            this.bcExp = brightcove.getExperience(pEvent);
            this.modVP = this.bcExp.getModule(APIModules.VIDEO_PLAYER);
            this.modExp = this.bcExp.getModule(APIModules.EXPERIENCE);
            this.modContent = this.bcExp.getModule(APIModules.CONTENT);
            this.modSocial = this.bcExp.getModule(APIModules.SOCIAL);
            this.modContent.addEventListener(BCContentEvent.VIDEO_LOAD, this.onVideoLoad);
            this.modVP.addEventListener(BCVideoEvent.VIDEO_CHANGE, this.onVideoChange);
            this.modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, this.onContentLoad); 
            this.loaded = true;
            $(VideoPlayer).trigger('playerLoaded');
            VideoPlayer.setupGetLinks('#video_links');
        },
        parseTagLinks: function(tag){
            // parses the tags to get the info needed to generate related links
            var key = null;
            var video = this.getCurrentVideo();
            if (!video) return null;
            $.each(video.tags,function(index) {
                var p1 = this.split("_")[0];
                if (p1.toLowerCase() == tag.toLowerCase()) key = this.split("_")[1];                
            });
            return key;
        },
        setupGetLinks: function(idstr){       
            // pushes the related links for the current video into the jquery identifier provided     
            $(VideoPlayer).bind('videoChanged', function(event) {
                var authkey = this.parseTagLinks("author");
                var bookkey = this.parseTagLinks("book");            
                var url = "/multimedia/links_for_video?";
                if (authkey) url+= 'authorkey='+authkey;
                if (bookkey) url+= '&isbn13='+bookkey;
                if (authkey || bookkey) $(idstr).load(url);
            });

        }
    };
}
();

function url_for_video(video_id){
    return(mulitmedia_homepage_url + "?video=" + video_id);
}

function onTemplateLoaded(pEvent) {VideoPlayer.initialize(pEvent);}

var coverPlayer = function(){
    $('#multimedia-player').css('width', '642px');
    VideoPlayer.tabVisibility(false);
}
var unCoverPlayer = function(){
    $('#multimedia-player').css('width', '973px');
    VideoPlayer.tabVisibility(true);
}
var showSearchResults = function(){
    coverPlayer();        
    $('div.search-results').css('left', '644px');    
    scrollToTypeInSearchResults();    
}
var hideSearchResults = function(){        
    unCoverPlayer();
    $('div.search-results').css('left', '5000px');        
}

var prepareResultBox = function(){
    $('.search-results .list-set > *').unbind();    
    $('.search-results .list-set').empty();
}

var searchAndPopulate = function(){                
    prepareResultBox();
    var text = $('.search-holder .bottom input').val(); 
    VideoPlayer.doSearch(text,'.search-results .list-set','find_videos_by_text',showSearchResults);
}

var scrollToTypeInSearchResults = function(){
    if ($.trim(type)!='') {
        $('.search-results .list-set').scrollTo('.heading h3:contains("'+ type +'")');
    }
}

$(document).ready(function() {     
    $('div.search-holder .go-button').click(searchAndPopulate);
    $('.search-holder .bottom input').keypress(function(event){
        if (event.keyCode==13) searchAndPopulate();
    });
    $('.search-results .list-set .close-button').click(hideSearchResults);
    VideoPlayer.setupGetLinks('#video_links');
    $('.search-results .close-button').click(hideSearchResults);
});

$(VideoPlayer).bind('contentLoaded', function(event) {
    $('.search-holder').fadeIn();
    if ($.trim(search)!='') { 
        VideoPlayer.doSearch(search,'.search-results .list-set','find_videos_by_text',showSearchResults);
    }
    if ($.trim(video)!='') VideoPlayer.playVideo(video);
});

/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Tested with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.2/5 and Safari 3. on Windows.
 *
 * @author Ariel Flesler
 * @version 1.4
 *
*/
;(function($){var $scrollTo=$.scrollTo=function(target,duration,settings){$(window).scrollTo(target,duration,settings);};$scrollTo.defaults={axis:"y",duration:1};$scrollTo.window=function(scope){return $(window).scrollable();};$.fn.scrollable=function(){return this.map(function(){var win=this.parentWindow||this.defaultView,elem=this.nodeName=="#document"?win.frameElement||win:this,doc=elem.contentDocument||(elem.contentWindow||elem).document,isWin=elem.setInterval;return elem.nodeName=="IFRAME"||isWin&&$.browser.safari?doc.body:isWin?doc.documentElement:this;});};$.fn.scrollTo=function(target,duration,settings){if(typeof duration=="object"){settings=duration;duration=0;}if(typeof settings=="function"){settings={onAfter:settings};}settings=$.extend({},$scrollTo.defaults,settings);duration=duration||settings.speed||settings.duration;settings.queue=settings.queue&&settings.axis.length>1;if(settings.queue){duration/=2;}settings.offset=both(settings.offset);settings.over=both(settings.over);return this.scrollable().each(function(){var elem=this,$elem=$(elem),targ=target,toff,attr={},win=$elem.is("html,body");switch(typeof targ){case"number":case"string":if(/^([+-]=)?\d+(px)?$/.test(targ)){targ=both(targ);break;}targ=$(targ,this);case"object":if(targ.is||targ.style){toff=(targ=$(targ)).offset();}}$.each(settings.axis.split(""),function(i,axis){var Pos=axis=="x"?"Left":"Top",pos=Pos.toLowerCase(),key="scroll"+Pos,old=elem[key],Dim=axis=="x"?"Width":"Height",dim=Dim.toLowerCase();if(toff){attr[key]=toff[pos]+(win?0:old-$elem.offset()[pos]);if(settings.margin){attr[key]-=parseInt(targ.css("margin"+Pos))||0;attr[key]-=parseInt(targ.css("border"+Pos+"Width"))||0;}attr[key]+=settings.offset[pos]||0;if(settings.over[pos]){attr[key]+=targ[dim]()*settings.over[pos];}}else{attr[key]=targ[pos];}if(/^\d+$/.test(attr[key])){attr[key]=attr[key]<=0?0:Math.min(attr[key],max(Dim));}if(!i&&settings.queue){if(old!=attr[key]){animate(settings.onAfterFirst);}delete attr[key];}});animate(settings.onAfter);function animate(callback){$elem.animate(attr,duration,settings.easing,callback&&function(){callback.call(this,target,settings);});}function max(Dim){var attr="scroll"+Dim,doc=elem.ownerDocument;return win?Math.max(doc.documentElement[attr],doc.body[attr]):elem[attr];}}).end();};function both(val){return typeof val=="object"?val:{top:val,left:val};}})(jQuery);