// 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 Ads = function() {
  var site_variable = '', receivedMessages = [], expectedMessages = [];
  return {
    display_ads: function() {
      if (showAds === true) {
					$("#ad_openx").remove();
					var ads_url = '/ads',
							request_url,
							openx_parameters = Ads.constructOpenxParameters(),
							main_content_height = $("#main_content").outerHeight(),
							sidebar_height = $("#sidebar").outerHeight() - $("#ad_openx").outerHeight(),
							ad_space_height = sidebar_height + 25;
					if (Ads.shouldDisplayAds(main_content_height, ad_space_height)) {
							Ads.createOpenxDiv();
							request_url = ads_url + "?main_content_height=" + main_content_height + "&sidebar_height=" + ad_space_height + "&openx_parameters=" + encodeURIComponent(this.site_variable) + encodeURIComponent(openx_parameters);
							$("#ad_openx").load(request_url, Ads.handleResponseForAds);
          }
      }
    },
    setSiteVariable: function(genres) {
				this.site_variable = "&exclusion=" + genres;
    },
    handleResponseForAds: function(response) {
      $("#ad_openx").remove();
      if (response !== "") {
        var main_content_height = $("#main_content").outerHeight(),
						sidebar_height = $("#sidebar").outerHeight() - $("#ad_openx").outerHeight(),
						div_height;
        if ((main_content_height - sidebar_height) > 110) {
						Ads.createOpenxDiv();
						div_height = main_content_height - sidebar_height - 54;
						$("#ad_openx").addClass("ad_openx lightGreyBg").css({ height:div_height + "px" });
						$("#ad_openx").html("<script type='text/javascript'>" + response + '</script>');
        }
      }
    },
    shouldDisplayAds: function(main_content_height, sidebar_height) {
				return $("#sidebar").length !== 0 && (sidebar_height < main_content_height);
    },
    constructOpenxParameters: function() {
				var openx_parameters = '';
				openx_parameters += "&amp;cb=" + Math.floor(Math.random() * 99999999999);
				openx_parameters += document.charset ? '&amp;charset=' + document.charset : (document.characterSet ? '&amp;charset=' + document.characterSet : '');
				openx_parameters += "&amp;loc=" + encodeURIComponent(window.location);
				if (document.referrer) openx_parameters += "&amp;referer=" + encodeURIComponent(document.referrer);
				if (document.context) openx_parameters += "&amp;context=" + encodeURIComponent(document.context);
				if (document.mmm_fo) openx_parameters += "&amp;mmm_fo=1";
				return openx_parameters;
    },
    createOpenxDiv: function() {
				var newDiv = document.createElement('div');
				newDiv.id = "ad_openx";
				$("#sidebar").append(newDiv);
    },
    display_page_specific_ads: function(domain, secure_domain, adserver_url, zone_id, adClassName) {
				var m3_u = (location.protocol == 'https:' ? secure_domain + adserver_url : domain + adserver_url),
						m3_r = Math.floor(Math.random() * 99999999999),
						adHolderEnd = (adClassName) ? '</div>' : '',
						adHolder = (adClassName) ? '<div class="' + adClassName + '">' : "";
				if (!document.MAX_used) document.MAX_used = ',';
				document.write(adHolder + "<script type='text/javascript' src='" + m3_u);
				document.write("?zoneid=" + zone_id);
				document.write('&amp;cb=' + m3_r);
				if (document.MAX_used != ',') document.write("&amp;exclude=" + document.MAX_used);
				document.write(document.charset ? '&amp;charset=' + document.charset : (document.characterSet ? '&amp;charset=' + document.characterSet : ''));
				document.write("&amp;loc=" + encodeURIComponent(window.location));
				if (document.referrer) document.write("&amp;referer=" + encodeURIComponent(document.referrer));
				if (document.context) document.write("&context=" + encodeURIComponent(document.context));
				if (document.mmm_fo) document.write("&amp;mmm_fo=1");
				document.write("'><\/script>" + adHolderEnd);
				if (adClassName) {
            $(document).ready(function() {
								$(".ad_holder").each(function() {
										var $this = $(this),
												AdContent = $("div[id~=beacon_]", $this).length;
										if (AdContent < 1) {
												$this.remove();
										} else {
												$("a[target=_blank]", this).each(function() {
														$(this).removeAttr("target");
												});
										}
								});
            });
				}
    },
    expectMessages: function(messageArray) {
				this.expectedMessages = messageArray;
				this.receivedMessages = [];
    },
    notify: function(message) {
				$.merge(Ads.receivedMessages, message);
				var receivedAll = true;
				$.each(Ads.expectedMessages, function() {
						if ($.inArray($.trim(this), Ads.receivedMessages) == -1) {
								receivedAll = false;
						}
        });
				if (receivedAll) Ads.display_ads();
		}
  };
}();

$(document).ready(function() {
	$(".ad_holder").each(function() {
		var $this = $(this),
				AdContent = $("div[id~=beacon_]", $this).length;
		if (AdContent < 1) {
				$(".flexi_ad", $this).remove();
		} else {
				$("a[target=_blank]", this).each(function() {
						$(this).removeAttr("target");
				});
		}
	});
});

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(6($){17.2m.27=6(b){4 c=b.2g||1j.22;5(!c&&b.J==Y)x F;j.A=$.2a({E:"E",1h:\'21\',1b:1T},b);5(b.C)j.C.1O(b.C);4 q=b.J!=Y?b.J.K().X(/[\\s,\\+\\.]+/):j.V(c,j.C);5(q&&q.1y("")){j.1v(q);x F.G(6(){4 a=F;5(a==1j)a=$("P")[0];j.1n(a,q)})}1l x F};4 j={A:{},m:[],C:[[/^9:\\/\\/(k\\.)?23\\./i,/q=([^&]+)/i],[/^9:\\/\\/(k\\.)?B\\.1X\\./i,/p=([^&]+)/i],[/^9:\\/\\/(k\\.)?B\\.1S\\./i,/q=([^&]+)/i],[/^9:\\/\\/(k\\.)?B\\.1R\\./i,/1Q=([^&]+)/i],[/^9:\\/\\/(k\\.)?B\\.1P\\./i,/1N=([^&]+)/i],[/^9:\\/\\/(k\\.)?1M\\.Z/i,/q=([^&]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){4 c=j.A,D,U;D=c.1d?$(c.1d):$("P");5(!D.z)D=$("P");U=c.1x?$(c.1x):$([]);D.G(6(){j.T(F,b,U)})},T:6(a,b,c){5(c.r(a)!=-1)x;4 d=j.A.E=="1k"?1:0;12(4 e=0,S=a.R.z;e<S;e++){4 f=a.R[e];5(f.O!=8){5(f.O==3){4 g=f.2j,1u=j.M(g);4 h="",v,r=0;j.m.11=0;2i(v=j.m.2h(1u)){h+=g.1p(r,v.r-r)+\'<I 2f="\'+j.N[v[d].K()]+\'">\'+g.1p(v.r,v[0].z)+"</I>";r=v.r+v[0].z}5(h){h+=g.2e(r);4 i=$.2d([],$("<I>"+h+"</I>")[0].R);S+=i.z-1;e+=i.z-1;$(f).2l(i).2b()}}1l{5(f.O==1&&f.2n.B(j.W)==-1)j.T(f,b,c)}}}}}})(17)',62,148,'||||var|if|function|ig||http|||||||||||www||regex|||||index||||match||return||length|options|search|engines|elHighlight|exact|this|each|regexAccent|span|keys|toLowerCase|matchAccent|replaceAccent|subs|nodeType|body|replace|childNodes|endIndex|hiliteTree|noHighlight|decodeURL|nosearch|split|undefined|com|escapeRegEx|lastIndex|for|u2019|u2018|x92|x91|jQuery|case|xFF|xDC|style_name_suffix|u0167|highlight|u015A|xD6|xD1|style_name|xCF|document|whole|else|u010D|hiliteElement|xC7|substr|xC5|xC0|u0100|xD8|textNoAcc|buildReplaceTools|test|nohighlight|join|break|null|textarea|cript|decodeURIComponent|gi|technorati|alltheweb|lycos|switch|push|feedster|altavista|ask|userQuery|unshift|aol|query|live|msn|true|xD9|new|RegExp|yahoo|u0162|tyle|u0161|hilite|referrer|google|xD2|xCC|xCB|SearchHighlight|xC8|u0106|extend|remove|u0105|merge|substring|class|debug_referrer|exec|while|data|false|before|fn|nodeName'.split('|'),0,{}))


function doVideoSearch(search_keyword){
  $('#videos, #audios, #photos').hide();
  VideoPlayer.executeJSONSearch('find_videos_by_text', search_keyword, function(data) {
    var separeatedVideos = VideoPlayer.separateIntoTypes(VideoPlayer.getCountrySpecificItems(data.items));
    var videoList = VideoPlayer.buildList(separeatedVideos.videos,"Video",{withSerial:false,withDescription:true, withCombinedTime: true, withTime:false});
    var audioList = VideoPlayer.buildList(separeatedVideos.audios,"Audio",{withSerial:false,withDescription:true, withCombinedTime: true, withTime:false});
    var photoList = VideoPlayer.buildList(separeatedVideos.photos,"Photos & Images",{withSerial:false,withTitle:false,withTime:false});

    $('ul',videoList).html($('li',videoList).slice(0,2));
    $('ul',audioList).html($('li',audioList).slice(0,2));
    $('ul',photoList).html($('li',photoList).slice(0,6));

    $('#videos .list').html(videoList);
    $('#audios .list').html(audioList);
    $('#photos .list').html(photoList);

    $(document).trigger("highlight");

    if ($('#videos ul li').length > 0) $('#videos').show();
    if ($('#audios ul li').length > 0) $('#audios').show();
    if ($('#photos ul li').length > 0) $('#photos').show();

    $('#video-results a').attr('href',$('#video-results a').attr('href') + '&search='+escape(search_keyword));

    $('#video-results').click(function(e) {
      parentLI = $(e.target).parents('li');
      if (parentLI.length>0) {
        var id = $('.id',parentLI).text();
        var type = $('.heading h3',parentLI.parents('.set')).text();
        window.location = '/multimedia?video='+id+'&search='+escape(search_keyword)+'&type='+escape(type);
      }
    });
  });
};

var handleNarrowResults = function(section, count) {
  var narrowResults = $("#narrow_search");
  var resultSection = $(section, narrowResults);
  var list_items = $("ol:eq(0) li", resultSection).length;
  if ( list_items > count ) {
    $("ol:eq(0)", resultSection).clone().appendTo(resultSection);
    $("ol:eq(0) li:gt( " + (count-1) + " )", resultSection).remove();
    $("ol:eq(1) li:lt( " + (count) + " )", resultSection).remove();
    $("ol:eq(1)", resultSection).addClass("more_list");
    $("ol.more_list", resultSection).hide();
    var title = $(".facet_group_title", resultSection).attr("title");
    $(resultSection).append("<div class='see_more'><a href='#' class='list_more'>See all " + title + "</a></div>");
    $("a.list_more", resultSection).toggle(
      function() { $("ol.more_list", resultSection).slideDown("300", function() {
        $("a.list_more", resultSection).text("See fewer " + title);
        if ( typeof(Ads) != "undefined" ) setTimeout("Ads.display_ads()", 300);} );
      },
      function() { $("ol.more_list", resultSection).slideUp("300", function(){
        $("a.list_more", resultSection).text("See all " + title);
        if ( typeof(Ads) != "undefined" ) setTimeout("Ads.display_ads()", 300);} );
    });
  }
};

$(document).ready(function() {    
  $("#sort").selectbox({setfirstval: false}).change(function() { window.location = $(this).val(); });
  var stop_words = ['a', 'about', 'above', 'an', 'and', 'any', 'are', 'can', 'do', 'find', 'for', 'from', 'have', 'how', 'i', 'is', 'me', 'not', 'or', 'the', 'under', 'what', 'when', 'where', 'with', 'your'];

  var keyword_array = $("#search_highlight_term").text().split(' ');

  // TODO: This is a temporary logic which will be removed once endeca search is implemented for videos.
  for( var i=0; i < keyword_array.length; i++ ) {
    for(var j=0; j < stop_words.length; j++) {
      if(keyword_array[i] == stop_words[j]) {
        keyword_array.splice(i, 1);
        i--;
        break;
      }
    }
  }
  var search_keyword = keyword_array.join(" ");

  if ( search_keyword != "" ) {
    doVideoSearch(search_keyword);

    var highlightKeyword = function() {
      var options = {
        exact: "exact",
        highlight: ".highlightable",
        nohighlight: ".nohighlight",
        style_name_suffix: false,
        keys: search_keyword
      };

      $(document).SearchHighlight(options);
    };

    $(document).bind("highlight", highlightKeyword);
  }
  
  handleNarrowResults("#search_categories",10);
  handleNarrowResults("#search_awards",5);
  handleNarrowResults("#search_formats",5);
  handleNarrowResults("#search_ages",5);
  handleNarrowResults("#search_grades",5);
  handleNarrowResults("#search_author",5);
  handleNarrowResults("#search_series",5);

  if(typeof(Ads) != "undefined") Ads.display_ads();
});
