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

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", "bv_tab_show", "bazaar_voice"]);

function hideFormats() {
  $('#book-format-dropdown div.slider, #excerpt .selection-box ul').hide();
  $(document).unbind('click', hideFormats);
}

$(document).ready(function() {
  $('#book-format-dropdown .selected').click(function() {
    $(document).bind('click', hideFormats);
		$('#book-format-dropdown  div.slider').toggle();
		return false;
  });

  $('#excerpt .selection-box .selected ').click(function() {
    $(document).bind('click', hideFormats);
    $('#excerpt .selection-box ul').toggle();
    return false;
  });

  if ($('#book-format-dropdown ul.list li').length > 0)
      $('.retailer_cart_link a.add_to_cart_link').click(function(){ alert('Please select an eBook format.'); return false; })
	
  $('#book-format-dropdown ul.list li a').each(function() {
    $(this).parent().attr('href',$(this).attr('href'));
    $(this).attr('href','#');
  });

  $('#book-format-dropdown ul.list li').click(function() {
    $('#book-format-dropdown div.selected').html($(this).html());
    $('.retailer_cart_link a.add_to_cart_link').attr('href', $(this).attr('href')).unbind().click(function(){return true;});
    $('#book-format-dropdown div.slider').hide();
    return false;
  });

		var PopupActive = false;
		$("#about_lexile").click(function(){
				if(PopupActive) { return false; }
				var link = $(this),
						contentHolder = link.attr("href"),
						popupHolder = $('<div id="inlinePopupHolder"></div>'),
						popupClose = $('<div id="inlinePopupClose">close</div>'),
						linkOffset = link.offset(),
						popupTop = (linkOffset.top - 50) + "px",
						popupLeft = (link.outerWidth() + 80) + "px";

			PopupActive = true;

				popupClose.click(function(){
						$("#inlinePopupHolder").remove();
						PopupActive = false;
				});

				popupHolder.html($(contentHolder).html());
				popupHolder.css({ top: popupTop, left: popupLeft });
				popupHolder.prepend(popupClose);

				$("#wrapper > .wrap_content").css("position", "relative").append(popupHolder);
				return false;
		});
});

$(document).ready(function() {
  $('#truncated_awards_list li:not(:last)').each(function(index) {
    $(this).text($(this).text()+", ");
  });
  $('#see_all_awards_message').toggle(function() {
    $('#all_awards_list').show();
    $('#see_all_awards_message').removeClass('bg-right-arrow').addClass('bg-down-arrow').text('Minimize');
  }, function() {
    $('#all_awards_list').slideUp('fast');    
    $('#see_all_awards_message').removeClass('bg-down-arrow').addClass('bg-right-arrow').text('See all');
  });
});

$(document).ready(function(){
  var handlethickBoxForAuthorsAlert = function(){
    var parameters = $("#alert_signup_form").formSerialize();
    tb_show("", $("#alert_signup_form").attr("action") + "?height=350&width=520&" + parameters);
  };
  var initializeAuthorAlertSignup = function() {
				var emailField = $("#alert_signup_form #subscriber_email");
		    emailField.setHintText({ defaultText : "Email" });

			  var authorAlertSignupFormSubmission = function() {
					var hintTxt = $.trim(emailField.val()).toLowerCase();
					if ( hintTxt == "" || hintTxt == "email") {
						emailField.val("").focus().removeClass("setHint");
						return false;
					}

          if($("#alert_signup_form input:checked").length == 0){
            $("#alert_signup_form .inRed").show();
            return false;
          }
          $("#alert_signup_form").unbind('click');
          handlethickBoxForAuthorsAlert();
          return false;
		    };

	      $("#alert_signup_form #alert_subscriber_submit").click(authorAlertSignupFormSubmission);
	      $("#alert_signup_form").submit(authorAlertSignupFormSubmission);
  };

  initializeAuthorAlertSignup();
});


(function($){
  $.fn.carouselController = function(o) {
    return this.each(function() {
      var carouselControl = $(this);
      var carouselHolder = $(this).parent();
      var customSelect = $(".carousel_controller select", carouselHolder);
      var isbn10 = $('#hidden_isbn10').text();

      var setupCarousel = function(data) {
        var name = carouselHolder.find(".jquery-selectbox-currentItem").text();
        $('.book_carousel', carouselHolder).remove();
        //alert(data);
        carouselControl.after(data);
        $(".book_carousel", carouselHolder).jPerspectiveCarousel({
          nextBtnName: ".carousel_next_button",
          prevBtnName : ".carousel_prev_button",
          totalNumHolder : "span.total_books",
          currentPositionHolder : "span.current_book",
          mainCarouselDiv : ".carousel_main",
          secondaryCarouselDiv : ".carousel_secondary",
          noBackgroundClass: "no_background",
          currentLinkText: "See all "+ name+" books",

          onBuild :function(carousel) {
            $(".carousel_secondary ul .bookTitle", carousel).truncateText({length: '30'});
            $(".carousel_main ul li", carousel).each(function() {
              if ($(".bookTitle",this).text().length > 70 ) { $(".bookBlurb", this).hide(); }
            });
          }
        });
      }

      var updateCarousel = function(e) {
        setupCarousel(e);
      }

      var change = function(e) {
        var id = customSelect.val();
        var updateURL = $('input.url_path', carouselHolder).val();
        $('.book_carousel .book_carousel_content', carouselHolder).html("").addClass("loading");
        
        $.ajax({
          url: updateURL + "/" + id,
          type: "GET",
          dataType:"html",
          success: updateCarousel
        });
      };

      var init = function(e) {
        customSelect.selectbox({fixWidth:true});
        customSelect.bind('change',change)
      };

      init();
    });
  }
})(jQuery);

$(document).ready(function() {
  $('.carousel_controller').carouselController();
});


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