// 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() {
	var emailField = $("#alert_sign_up_form #subscriber_email_id")
	emailField.setHintText({ defaultText : "Email" });
        var authorAlertSignupFormSubmission = function(){
           var hintTxt = $.trim(emailField.val()).toLowerCase(),
           email_alert_link = $("a#get_email_alerts").attr("href"),
           email_address = $("#alert_sign_up_form #alert_subscriber_email_id #subscriber_email_id").attr("value");
           if ( hintTxt == "" || hintTxt == "email") {
             emailField.val("").focus().removeClass("setHint");
             return false;
           }
           tb_show("", email_alert_link + "&subscriber_email=" + email_address);
           return false;
	};

       $("#alert_sign_up_form #alert_subscriber_submit").click(authorAlertSignupFormSubmission);
       $("#alert_sign_up_form").submit(authorAlertSignupFormSubmission);

	$('#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();
	});
});


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


function customMarkerOption() {
  var customIcon = new GIcon(G_DEFAULT_ICON);
  customIcon.image = "/images/google_map_marker.png";
  imageWidth = 19;
  imageHeight = 22;
  customIcon.iconSize = new GSize(imageWidth, imageHeight);
  customIcon.iconAnchor = new GPoint(0, imageWidth);
  customIcon.shadow = null;
  return { icon:customIcon };
}

var markerOptions = customMarkerOption();

function build_map(map, elementId, centerLatitude, centerLongitude, zoomLevel) {
  if (!map){

    var map_div = document.getElementById(elementId);
    if (!map_div) return;
    map = new GMap2(map_div);

    mapTypes = map.getMapTypes();
    for (i in mapTypes)
    mapTypes[i].getMinimumResolution = function() {return 1;}
    map.setCenter(new GLatLng(centerLatitude, centerLongitude), zoomLevel);
    map.enableScrollWheelZoom();
	map.addControl(new GLargeMapControl());
  }
  return map;
}

function info(marker, appearance_id, author_id) {
	map.closeExtInfoWindow();
	$.get("/author_appearance_info",{"appearance_id" : appearance_id ,"author_id" : author_id},function(data){
		marker.openExtInfoWindow(map, "info_window", data, {beakOffset: 1});
 tb_init('.map_bubble.appearances a.thickbox');
 });
}


function addAuthorAppearancesMarker(author_appearances, author_id) {
  var markers = new Array();	
  for (j in author_appearances) {
    var point = new GLatLng(parseFloat(author_appearances[j][0]),
    parseFloat(author_appearances[j][1]));
    marker = new GMarker(point,markerOptions);
    map.addOverlay(marker);
    markers[author_appearances[j][2]] = marker;
    GEvent.addListener(marker, "click", GEvent.callbackArgs(window,info, marker, author_appearances[j][2], author_id));
  }

  return markers;
}






/* ExtInfoWindow Class, v1.0
   Copyright (c) 2007, Joe Monahan (http://www.seejoecode.com)
   Licensed under the Apache License, Version 2.0 */
function ExtInfoWindow(marker,windowId,html,opt_opts){this.html_=html;this.marker_=marker;this.infoWindowId_=windowId;this.options_=opt_opts==null?{}:opt_opts;this.ajaxUrl_=this.options_.ajaxUrl==null?null:this.options_.ajaxUrl;this.callback_=this.options_.ajaxCallback==null?null:this.options_.ajaxCallback;this.borderSize_=this.options_.beakOffset==null?0:this.options_.beakOffset;this.paddingX_=this.options_.paddingX==null?0+this.borderSize_:this.options_.paddingX+this.borderSize_;this.paddingY_=this.options_.paddingY==null?0+this.borderSize_:this.options_.paddingY+this.borderSize_;this.map_=null;this.container_=document.createElement("div");this.container_.style.position="relative";this.container_.style.display="none";this.contentDiv_=document.createElement("div");this.contentDiv_.id=this.infoWindowId_+"_contents";this.contentDiv_.innerHTML=this.html_;this.contentDiv_.style.display="block";this.contentDiv_.style.visibility="hidden";this.wrapperDiv_=document.createElement("div");}ExtInfoWindow.prototype=new GOverlay();ExtInfoWindow.prototype.initialize=function(map){this.map_=map;this.defaultStyles={containerWidth:this.map_.getSize().width/2,borderSize:1};this.wrapperParts={tl:{t:0,l:0,w:0,h:0,domElement:null},t:{t:0,l:0,w:0,h:0,domElement:null},tr:{t:0,l:0,w:0,h:0,domElement:null},l:{t:0,l:0,w:0,h:0,domElement:null},r:{t:0,l:0,w:0,h:0,domElement:null},bl:{t:0,l:0,w:0,h:0,domElement:null},b:{t:0,l:0,w:0,h:0,domElement:null},br:{t:0,l:0,w:0,h:0,domElement:null},beak:{t:0,l:0,w:0,h:0,domElement:null},close:{t:0,l:0,w:0,h:0,domElement:null}};for(var i in this.wrapperParts){var tempElement=document.createElement("div");tempElement.id=this.infoWindowId_+"_"+i;tempElement.style.visibility="hidden";document.body.appendChild(tempElement);tempElement=document.getElementById(this.infoWindowId_+"_"+i);var tempWrapperPart=eval("this.wrapperParts."+i);tempWrapperPart.w=parseInt(this.getStyle_(tempElement,"width"));tempWrapperPart.h=parseInt(this.getStyle_(tempElement,"height"));document.body.removeChild(tempElement);}for(var i in this.wrapperParts){if(i=="close"){this.wrapperDiv_.appendChild(this.contentDiv_);}var wrapperPartsDiv=null;if(this.wrapperParts[i].domElement==null){wrapperPartsDiv=document.createElement("div");this.wrapperDiv_.appendChild(wrapperPartsDiv);}else{wrapperPartsDiv=this.wrapperParts[i].domElement;}wrapperPartsDiv.id=this.infoWindowId_+"_"+i;wrapperPartsDiv.style.position="absolute";wrapperPartsDiv.style.width=this.wrapperParts[i].w+"px";wrapperPartsDiv.style.height=this.wrapperParts[i].h+"px";wrapperPartsDiv.style.top=this.wrapperParts[i].t+"px";wrapperPartsDiv.style.left=this.wrapperParts[i].l+"px";this.wrapperParts[i].domElement=wrapperPartsDiv;}this.map_.getPane(G_MAP_FLOAT_PANE).appendChild(this.container_);this.container_.id=this.infoWindowId_;var containerWidth=this.getStyle_(document.getElementById(this.infoWindowId_),"width");this.container_.style.width=(containerWidth==null?this.defaultStyles.containerWidth:containerWidth);this.map_.getContainer().appendChild(this.contentDiv_);this.contentWidth=this.getDimensions_(this.container_).width;this.contentDiv_.style.width=this.contentWidth+"px";this.contentDiv_.style.position="absolute";this.container_.appendChild(this.wrapperDiv_);GEvent.bindDom(this.container_,"mousedown",this,this.onClick_);GEvent.bindDom(this.container_,"dblclick",this,this.onClick_);GEvent.bindDom(this.container_,"DOMMouseScroll",this,this.onClick_);GEvent.trigger(this.map_,"extinfowindowopen");if(this.ajaxUrl_!=null){this.ajaxRequest_(this.ajaxUrl_);}};ExtInfoWindow.prototype.onClick_=function(e){if(navigator.userAgent.toLowerCase().indexOf("msie")!=-1&&document.all){window.event.cancelBubble=true;window.event.returnValue=false;}else{e.stopPropagation();}};ExtInfoWindow.prototype.remove=function(){if(this.map_.getExtInfoWindow()!=null){GEvent.trigger(this.map_,"extinfowindowbeforeclose");GEvent.clearInstanceListeners(this.container_);if(this.container_.outerHTML){this.container_.outerHTML="";}if(this.container_.parentNode){this.container_.parentNode.removeChild(this.container_);}this.container_=null;GEvent.trigger(this.map_,"extinfowindowclose");this.map_.setExtInfoWindow_(null);}};ExtInfoWindow.prototype.copy=function(){return new ExtInfoWindow(this.marker_,this.infoWindowId_,this.html_,this.options_);};ExtInfoWindow.prototype.redraw=function(force){if(!force||this.container_==null){return;}var contentHeight=this.contentDiv_.offsetHeight;this.contentDiv_.style.height=contentHeight+"px";this.contentDiv_.style.left=this.wrapperParts.l.w+"px";this.contentDiv_.style.top=this.wrapperParts.tl.h+"px";this.contentDiv_.style.visibility="visible";this.wrapperParts.tl.t=0;this.wrapperParts.tl.l=0;this.wrapperParts.t.l=this.wrapperParts.tl.w;this.wrapperParts.t.w=(this.wrapperParts.l.w+this.contentWidth+this.wrapperParts.r.w)-this.wrapperParts.tl.w-this.wrapperParts.tr.w;this.wrapperParts.t.h=this.wrapperParts.tl.h;this.wrapperParts.tr.l=this.wrapperParts.t.w+this.wrapperParts.tl.w;this.wrapperParts.l.t=this.wrapperParts.tl.h;this.wrapperParts.l.h=contentHeight;this.wrapperParts.r.l=this.contentWidth+this.wrapperParts.l.w;this.wrapperParts.r.t=this.wrapperParts.tr.h;this.wrapperParts.r.h=contentHeight;this.wrapperParts.bl.t=contentHeight+this.wrapperParts.tl.h;this.wrapperParts.b.l=this.wrapperParts.bl.w;this.wrapperParts.b.t=contentHeight+this.wrapperParts.tl.h;this.wrapperParts.b.w=(this.wrapperParts.l.w+this.contentWidth+this.wrapperParts.r.w)-this.wrapperParts.bl.w-this.wrapperParts.br.w;this.wrapperParts.b.h=this.wrapperParts.bl.h;this.wrapperParts.br.l=this.wrapperParts.b.w+this.wrapperParts.bl.w;this.wrapperParts.br.t=contentHeight+this.wrapperParts.tr.h;this.wrapperParts.close.l=this.wrapperParts.tr.l+this.wrapperParts.tr.w-this.wrapperParts.close.w-this.borderSize_;this.wrapperParts.close.t=this.borderSize_;this.wrapperParts.beak.t=this.wrapperParts.bl.t+this.wrapperParts.bl.h+this.borderSize_-12;for(var i in this.wrapperParts){if(i=="close"){this.wrapperDiv_.insertBefore(this.contentDiv_,this.wrapperParts[i].domElement);}var wrapperPartsDiv=null;if(this.wrapperParts[i].domElement==null){wrapperPartsDiv=document.createElement("div");this.wrapperDiv_.appendChild(wrapperPartsDiv);}else{wrapperPartsDiv=this.wrapperParts[i].domElement;}wrapperPartsDiv.id=this.infoWindowId_+"_"+i;wrapperPartsDiv.style.position="absolute";wrapperPartsDiv.style.width=this.wrapperParts[i].w+"px";wrapperPartsDiv.style.height=this.wrapperParts[i].h+"px";wrapperPartsDiv.style.top=this.wrapperParts[i].t+"px";wrapperPartsDiv.style.left=this.wrapperParts[i].l+"px";if(i=="beak"){wrapperPartsDiv.style.zIndex=3000;}this.wrapperParts[i].domElement=wrapperPartsDiv;}this.wrapperParts.beak.st;var currentMarker=this.marker_;var thisMap=this.map_;GEvent.addDomListener(this.wrapperParts.close.domElement,"click",function(){thisMap.closeExtInfoWindow();});var pixelLocation=this.map_.fromLatLngToDivPixel(this.marker_.getPoint());this.container_.style.position="absolute";var markerIcon=this.marker_.getIcon();this.container_.style.left=(pixelLocation.x-markerIcon.iconAnchor.x+markerIcon.infoWindowAnchor.x)+"px";this.container_.style.top=(pixelLocation.y-this.wrapperParts.bl.h-contentHeight-this.wrapperParts.tl.h-this.wrapperParts.beak.h-markerIcon.iconAnchor.y+markerIcon.infoWindowAnchor.y+this.borderSize_+15)+"px";this.container_.style.display="block";if(this.map_.getExtInfoWindow()!=null){this.repositionMap_();}};ExtInfoWindow.prototype.resize=function(){var tempElement=this.contentDiv_.cloneNode(true);tempElement.id=this.infoWindowId_+"_tempContents";tempElement.style.visibility="hidden";tempElement.style.height="auto";document.body.appendChild(tempElement);tempElement=document.getElementById(this.infoWindowId_+"_tempContents");var contentHeight=tempElement.offsetHeight;document.body.removeChild(tempElement);this.contentDiv_.style.height=contentHeight+"px";var contentWidth=this.contentDiv_.offsetWidth;var pixelLocation=this.map_.fromLatLngToDivPixel(this.marker_.getPoint());var oldWindowHeight=this.wrapperParts.t.domElement.offsetHeight+this.wrapperParts.l.domElement.offsetHeight+this.wrapperParts.b.domElement.offsetHeight;var oldWindowPosTop=this.wrapperParts.t.domElement.offsetTop;this.wrapperParts.l.domElement.style.height=contentHeight+"px";this.wrapperParts.r.domElement.style.height=contentHeight+"px";var newPosTop=this.wrapperParts.b.domElement.offsetTop-contentHeight;this.wrapperParts.l.domElement.style.top=newPosTop+"px";this.wrapperParts.r.domElement.style.top=newPosTop+"px";this.contentDiv_.style.top=newPosTop+"px";windowTHeight=parseInt(this.wrapperParts.t.domElement.style.height);newPosTop-=windowTHeight;this.wrapperParts.close.domElement.style.top=newPosTop+this.borderSize_+"px";this.wrapperParts.tl.domElement.style.top=newPosTop+"px";this.wrapperParts.t.domElement.style.top=newPosTop+"px";this.wrapperParts.tr.domElement.style.top=newPosTop+"px";this.repositionMap_();};ExtInfoWindow.prototype.repositionMap_=function(){var mapNE=this.map_.fromLatLngToDivPixel(this.map_.getBounds().getNorthEast());var mapSW=this.map_.fromLatLngToDivPixel(this.map_.getBounds().getSouthWest());var markerPosition=this.map_.fromLatLngToDivPixel(this.marker_.getPoint());var panX=0;var panY=0;var paddingX=this.paddingX_;var paddingY=this.paddingY_;var infoWindowAnchor=this.marker_.getIcon().infoWindowAnchor;var iconAnchor=this.marker_.getIcon().iconAnchor;var windowT=this.wrapperParts.t.domElement;var windowL=this.wrapperParts.l.domElement;var windowB=this.wrapperParts.b.domElement;var windowR=this.wrapperParts.r.domElement;var windowBeak=this.wrapperParts.beak.domElement;var offsetTop=markerPosition.y-(-infoWindowAnchor.y+iconAnchor.y+this.getDimensions_(windowBeak).height+this.getDimensions_(windowB).height+this.getDimensions_(windowL).height+this.getDimensions_(windowT).height+this.paddingY_);if(offsetTop<mapNE.y){panY=mapNE.y-offsetTop;}else{var bottom_padding=15;var offsetBottom=markerPosition.y+this.paddingY_+bottom_padding;if(offsetBottom>=mapSW.y){panY=-(offsetBottom-mapSW.y);}}var offsetAfterBorder=4;var offsetRight=Math.round(markerPosition.x+this.getDimensions_(this.container_).width+this.getDimensions_(windowR).width+this.paddingX_+infoWindowAnchor.x-iconAnchor.x+this.borderSize_+offsetAfterBorder);if(offsetRight>mapNE.x){panX=-(offsetRight-mapNE.x);}else{var left_padding=65;var offsetLeft=-(Math.round((0-this.marker_.getIcon().iconSize.width/2)+this.getDimensions_(windowL).width+this.borderSize_+this.paddingX_)-markerPosition.x-infoWindowAnchor.x+iconAnchor.x)-left_padding;if(offsetLeft<mapSW.x){panX=mapSW.x-offsetLeft;}}if(panX!=0||panY!=0&&this.map_.getExtInfoWindow()!=null){this.map_.panBy(new GSize(panX,panY));}};ExtInfoWindow.prototype.ajaxRequest_=function(url){var thisMap=this.map_;var thisCallback=this.callback_;GDownloadUrl(url,function(response,status){var infoWindow=document.getElementById(thisMap.getExtInfoWindow().infoWindowId_+"_contents");if(response==null||status==-1){infoWindow.innerHTML='<span class="error">ERROR: The Ajax request failed to get HTML content from "'+url+'"</span>';}else{infoWindow.innerHTML=response;}if(thisCallback!=null){thisCallback();}thisMap.getExtInfoWindow().resize();GEvent.trigger(thisMap,"extinfowindowupdate");});};ExtInfoWindow.prototype.getDimensions_=function(element){var display=this.getStyle_(element,"display");if(display!="none"&&display!=null){return{width:element.offsetWidth,height:element.offsetHeight};}var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility="hidden";els.position="absolute";els.display="block";var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};};ExtInfoWindow.prototype.getStyle_=function(element,style){var found=false;style=this.camelize_(style);var value=element.style[style];if(!value){if(document.defaultView&&document.defaultView.getComputedStyle){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;}else{if(element.currentStyle){value=element.currentStyle[style];}}}if((value=="auto")&&(style=="width"||style=="height")&&(this.getStyle_(element,"display")!="none")){if(style=="width"){value=element.offsetWidth;}else{value=element.offsetHeight;}}return(value=="auto")?null:value;};ExtInfoWindow.prototype.camelize_=function(element){var parts=element.split("-"),len=parts.length;if(len==1){return parts[0];}var camelized=element.charAt(0)=="-"?parts[0].charAt(0).toUpperCase()+parts[0].substring(1):parts[0];for(var i=1;i<len;i++){camelized+=parts[i].charAt(0).toUpperCase()+parts[i].substring(1);}return camelized;};GMap.prototype.ExtInfoWindowInstance_=null;GMap.prototype.ClickListener_=null;GMap.prototype.InfoWindowListener_=null;GMarker.prototype.openExtInfoWindow=function(map,cssId,html,opt_opts){if(map==null){throw"Error in GMarker.openExtInfoWindow: map cannot be null";return false;}if(cssId==null||cssId==""){throw"Error in GMarker.openExtInfoWindow: must specify a cssId";return false;}map.closeInfoWindow();if(map.getExtInfoWindow()!=null){map.closeExtInfoWindow();}if(map.getExtInfoWindow()==null){map.setExtInfoWindow_(new ExtInfoWindow(this,cssId,html,opt_opts));if(map.ClickListener_==null){map.ClickListener_=GEvent.addListener(map,"click",function(event){if(!event&&map.getExtInfoWindow()!=null){map.closeExtInfoWindow();}});}if(map.InfoWindowListener_==null){map.InfoWindowListener_=GEvent.addListener(map,"infowindowopen",function(event){if(map.getExtInfoWindow()!=null){map.closeExtInfoWindow();}});}map.addOverlay(map.getExtInfoWindow());}};GMarker.prototype.closeExtInfoWindow=function(map){if(map.getExtInfWindow()!=null){map.closeExtInfoWindow();}};GMap2.prototype.getExtInfoWindow=function(){return this.ExtInfoWindowInstance_;};GMap2.prototype.setExtInfoWindow_=function(extInfoWindow){this.ExtInfoWindowInstance_=extInfoWindow;};GMap2.prototype.closeExtInfoWindow=function(){if(this.getExtInfoWindow()!=null){this.ExtInfoWindowInstance_.remove();}};

var map, markers;

function initialize_map() {
	if (GBrowserIsCompatible()) {
		map = build_map(map, "local_appearances_map", pageMapsCenterLatitude, pageMapsCenterLongitude, pageMapsZoomLevel);
		markers = addAuthorAppearancesMarker(author_appearances, author_id);
	}
}

$(document).ready(function() {
	if (typeof(author_appearances) !== "undefined" && typeof(author_id) !== "undefined") {
		initialize_map();
	}
	$(".map_it").click(function() {
		var map_it_id = this.id,
			appearance_id = $("#" + map_it_id).attr("appearance_id"),
			author_id = $("#" + map_it_id).attr("author_id");
		info(markers[appearance_id], appearance_id, author_id);
	});
});

$(document).ready(function(){
    Ads.display_ads();
});