// 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);}

//gigya.services.socialize.verbose = true;

(function($) {
	$.fn.share_appearance = function(api_key, message) {
			
		return this.each(function() {
			
			var provider = $(this).attr('rel');
			
			var api = {
				APIKey:api_key,
				enabledProviders:provider
			};
			
			var context = { api:api, message:message, provider:provider, selector:this }
			
			alert_if_debugging('getUserInfo', api);
			gigya.services.socialize.getUserInfo(api, { context:context, callback:get_user_info_callback });
	
		});
	};
	
	function alert_if_debugging(method, api, message)
	{
		if(document.location.search.indexOf("gigya_debug=true") > 0)
		{
			if(message) alert('calling: ' + method + '\nenabledProviders: ' + api.enabledProviders + '\nmessage: ' + message)
			if(!message) alert('calling: ' + method + '\nenabledProviders: ' + api.enabledProviders)
		}
	}
	
	function set_box_text(heading, message)
	{
		$('div.share_appearance h2').text(heading);
		$('div.share_appearance p').text(message);
	}
	
	function invalid_response(response)
	{
		/* DEBUG *** for some reason these callbacks get called twice sometimes

		msg = 'status: ' + response.status;
		msg = msg + '\nstatusMessage: ' + response.statusMessage;
		msg = msg + '\noperation: ' + response.operation;
		msg = msg + '\ncontext: ' + response.context;
		if(response.user)
		{
			msg = msg + '\nuserName: ' + response.user.firstName;
			msg = msg + '\nUID: ' + response.user.UID;
		}
		alert(msg)
		
		*/
		
		if(response.status != 'OK')
		{
			set_box_text('Sorry, there was an error', response.statusMessage)
			return true;
		}
		
		return false;
	}
	
	function get_user_info_callback(response)
	{
		if(invalid_response(response)) return;
		
		$(response.context.selector).click(function(e) {
			
			/* DEBUG *** the click only occurs once
			
			alert('icon clicked')
			alert(api.enabledProviders)
			//gigya.services.socialize.disconnect(api);
			*/
			
			set_box_text('Please wait...', 'Posting your message.')
			if(response.user.identities[response.context.provider])
			{
				alert_if_debugging('setStatus', response.context.api, response.context.message);
				gigya.services.socialize.setStatus(response.context.api, {status:response.context.message, callback: set_status_callback });
			}
			else
			{
				var context = { api:response.context.api, message:response.context.message }

				alert_if_debugging('connect', response.context.api);
				gigya.services.socialize.connect(response.context.api, { provider: response.context.provider, callback: connect_callback, context: context })
			}
			
		});
	}
	
	function connect_callback(response)
	{
		if(invalid_response(response)) return;
		
		alert_if_debugging('setStatus', response.context.api, response.context.message);
		gigya.services.socialize.setStatus(response.context.api, {status:response.context.message, callback: set_status_callback });
	}
	
	function set_status_callback(response)
	{
		if(invalid_response(response)) return;
		set_box_text('The event has been posted', 'Click on another network below to post again or close the window')
	}

})(jQuery);

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");
				});
		}
	});
});

var closePlaylist = function() {
    $('#video_playlist').css('top','5000px');
    $('#bc_player').css('top','0px');
    $('#bc_nowplaying .see_all').show();
}
var showPlaylist = function(){
    $('#video_playlist').css('top','0px');
    $('#bc_player').css('top','5000px');
    $('#bc_nowplaying .see_all').hide();
}

$(document).ready(function() { 
    $('#video_playlist .close-button').click(closePlaylist);
    $('#bc_nowplaying .see_all').click(showPlaylist);
    $('#player_wrapper').show();
    
	$('.scroll_section_video').jScrollPane({showArrows:true, scrollbarWidth: 27});
    if (typeof handleShowVideo != 'undefined') handleShowVideo();
    
    $(VideoPlayer).bind('playerLoaded', function(){
		VideoPlayer.cueVideo($("#video_playlist .list-set .list .item:first").attr("rel"));
	});
    
	$('#video_playlist .scroll_section').jScrollPane({showArrows:true, scrollbarWidth: 27});
    $('#video_playlist .list-set .set .list ul li').click(function() {
        $('#video_playlist .close-button').click();
    });
    
	$("#video_playlist .list-set .list .item").click(function() {
		video_id = $(this).attr("rel");
		VideoPlayer.playVideo(video_id);
	});
});


$(VideoPlayer).bind('videoChanged', function()
{    
    var vid = VideoPlayer.getCurrentVideo();
    $('#bc_nowplaying').slideDown('fast');
    $('#bc_nowplaying .title').text(vid.displayName);
    $('#bc_nowplaying .desc').text(vid.shortDescription);    
});

Ads.expectMessages(["message_board", "aggregate_knowledge"])

$(document).ready(function() {
  $('#main_content .selection-box .selected ').click(function(evt) {
    $('#main_content .selection-box ul').toggle();
    evt.stopPropagation();
  });
  $(window).click(function(evt) {
    $('#main_content .selection-box ul').hide();
  });
});

var registerSubmitButtonClick = function() {
	$("#light_registration_form select[id$=_dob_1i] option:eq(0)").text("Year").attr({ value : "default" });
	$("#light_registration_form select[id$=_dob_2i] option:eq(0)").text("Month").attr({ value : "default" });
	$("#light_registration_form select[id$=_dob_3i] option:eq(0)").text("Day").attr({ value : "default" });
  $('#light_registration_form select').not($("#light_registration_form select#appearance_reminder_time_period")).selectbox({ fixHeight : true });
  $("#light_registration_form select#appearance_reminder_time_period").selectbox();
  $('#light_registration_form').submit(function(){
    $("#light_registration_submit").parent().animate({opacity: 0.5});
    $('#light_registration_form').ajaxSubmit({target: '#TB_ajaxContent'});
    return false;
  });
};

/* Copy plugin
 * Copyright (c) 2007 Yang Shuai (http://yangshuai.googlepages.com)
 * Dual licensed under the MIT and GPL licenses - http://www.opensource.org/licenses/mit-license.php, http://www.gnu.org/licenses/gpl.html */
jQuery.copy=function(t){if(typeof t=='undefined'){t=''}var d=document;if(window.clipboardData){window.clipboardData.setData('Text',t)}else{var f='flashcopier';if(!d.getElementById(f)){var dd=d.createElement('div');dd.id=f;d.body.appendChild(dd)}d.getElementById(f).innerHTML='';var i='<embed src="/flash/copy.swf" FlashVars="clipboard='+encodeURIComponent(t)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';d.getElementById(f).innerHTML=i}};

$(document).ready(function() {
    $("#title_content .share_links a.rss").click(function() {
        $("#title_content #rss_options").fadeIn();
        $("#title_content #sharethis_0 a").click(function(){$("#title_content #rss_options").fadeOut();});
        return false;
    });
    $("#title_content #rss_options a.close").click(function() {
        $("#title_content #rss_options").fadeOut();
        return false;
    });
    $("#title_content #rss_options #copy_author_rss_url").click(function() {
        var copy_text = $("#title_content #rss_options #author_rss_url").attr("value");
        $.copy(copy_text);
        return false;
    });
});


$(document).ready(function(){
  $.get("/message_board/latest_topics/"+	message_board_type+"?tag="+message_board_tag,function(data) {
   eval(data);   
   if (typeof Ads != "undefined") Ads.notify(['message_board']);
  });
});
