function divaCaptions (txt)
{
    var captionArea = $('#caption-area');
    
    if (captionArea)
    {
        // If there's a current caption, remove its current class:
        $('.current', captionArea).removeClass('current');
        
        // Sentinel for marking <BR>, which we want to let through unescaped.
        txt = txt.replace(/<br[^>]*>/ig, "@@@@HACK@@@@");
        
        // Create a tag with the escaped HTML in it.
        var p = $('<div class="current"></div>');
        txt = p.text(txt).html();
        
        // Change our sentinels back into <BR> tags.
        txt = txt.replace(/@@@@HACK@@@@/g, '<br>');
        
        // Throw it into the captionArea.
        captionArea.html(p.html(txt));
    }
}

jQuery(document).ready(function ($) {
    var baseUrl = $('base')[0].href;
    
    $.fn.embedLabel = function (opts) {
        this.each(function () {
            var label = $(this);
            var id = label.attr('for');
            var field = document.getElementById(id);
            
            if (field)
            {
                opts = $.extend({}, $.fn.embedLabel.defaults, opts);
                
                var hideLabel = function () { label.addClass(opts.labelClass); }
                var showLabel = function () { this.value || label.removeClass(opts.labelClass); }
                
                $(field)
                    .parent().addClass(opts.wrapperClass).end()
                    .focus(hideLabel).blur(showLabel).focus().blur();
            }
        });
        
        return this;
    };
    
    $.fn.embedLabel.defaults = {
        labelClass: 'field-embed-hidden',
        wrapperClass: 'field-embed-wrapper'
    };
    
    $('.field-embed').embedLabel();
    
    $('.wysiwyg').wysiwyg({ base: baseUrl });
    $('.simple-wysiwyg').wysiwyg({ base: baseUrl, toolbar: ['bold', 'italic', 'underline', 'sep', 'ul', 'ol', 'sep', 'link' ] });
    $('.very-simple-wysiwyg').wysiwyg({ base: baseUrl, toolbar: ['bold', 'italic', 'underline', 'sep', 'link' ] });
    
    $('.select-all').change(function (evt) {
        var sel = this.checked;
        $(this).parents('.selectable-container').find('input.selectable').each(function () {
            this.checked = sel;
        });
    });
    
    $('#user-message')
        .css({ position: 'absolute', opacity: 0.8, top: '1em', left: '20%' })
        .length &&
            setTimeout(function () {
                $(document).mousemove(function () { $('#user-message').fadeOut(4000); });
            }, 1500);
    
    var navOffsets = $('#main-nav-wrap').offset();
    var moreOffsets = $('#more-option').offset();
    
    if (moreOffsets)
    {
        $('#more').
            css({ display: 'none', position: 'absolute', left: moreOffsets.left - navOffsets.left, textIndent: 0 })
            .addClass('enhanced')
            .attr('tabindex', -1);
        
        $('#more-option').click(function (evt) {
            var $this = $(this);
            var showing = $this.data('showing');
            
            var hideMore = function (option)
            {
                option.removeClass('active').data('showing', false);
                $('#more').hide();
                $('body').unbind('click.moremenu');
            };
            
            var showMore = function (option)
            {
                option.addClass('active').data('showing', true);
                $('#more').show().focus().bind('keydown', function (evt) {
                    if (evt.which == 27)
                    {
                        hideMore($("#more-option"));
                        $("#more-option a").focus();
                    }
                });
                
                $('body').bind('click.moremenu', function (evt) {
                    if (evt.target.id != 'more' && $(evt.target).parents('#more').length == 0)
                    {
                        hideMore($('#more-option'));
                    }
                });
            };
            
            if ($this.data('showing'))
            {
                hideMore($this);
            }
            else
            {
                showMore($this);
            }
            
            evt.preventDefault();
            evt.stopPropagation();
        }).data('showing', false);
    }
    
    //$('.add-from-diva').click(function (evt) {
    //});

	$('.full-view').click(function (evt) {
		var imageHref = this.href;
		var overlay = new BssImageOverlay(imageHref);
		overlay.show();
		evt.preventDefault();
		evt.stopPropagation();
	});


	// Last thing: Make sure we scroll to the fragment, since browsers get confused when the body changes.
	if (window.location.hash.length > 1)
	{
		var offset = $(window.location.hash).offset();
		if (offset && window.scrollTo)
		{
			window.scrollTo(offset.left, offset.top);
		}
	}
	
	var BrowseOverlay = function (settings)
	{
		BssOverlay.call(this, settings);
		this.setTitle('Browse DIVA');
		return this;
	}
	
	BrowseOverlay.prototype = new BssOverlay();
	
	var openDivaBrowser = function ()
	{
		var browser = new BrowseOverlay();
		browser.show();
	}
	
	var tabPanelId = 0;
	
	$('.dynamic-tab-container').each(function () {
		var tabs = $('<ul class="tabs"></ul>');
		var $this = $(this);
		var container = $this;
		var tabId = 0;
		
		$this.addClass('tab-panel')
			.children('.top').append(tabs).end()
			.find('.dynamic-tab-panel').each(function () {
				var panelId = this.id = this.id || ('-x-tabPanel-' + tabPanelId + '-' + tabId);
				var li = $('<li id="-x-tab-' + this.id + '"><a href="javascript:void(null);">' + (this.title || 'Tab ' + tabId+1) + '</a></li>')
					.appendTo(tabs)
					.click(function () {
						var $tab = $(this);
						
						// Only if we're not already active...
						if (!$tab.hasClass('active'))
						{
							// Remove 'active' class from all active tabs, hide all panels.
							tabs.find('li.active').removeClass('active');
							container.find('.dynamic-tab-panel').hide();
							
							// Show our panel, and set our tab to active.
							$tab.addClass('active');
							$('#' + panelId).show();
						}
					})
				;
				
				if (window.location.hash)
				{
					if ('#' + this.id == window.location.hash)
					{
						li.addClass('active');
					}
					else
					{
						$(this).hide();
					}
				}
				else if (tabId == 0)
				{
					li.addClass('active');
				}
				else
				{
					$(this).hide();
				}
				
				tabId++;
			})
		;
		
		tabPanelId++;
	});
	
	AudioPlayer.setup(baseUrl + 'audio.swf', { width: 290, initialvolume: 70 });
	$('.audio-embed').each(function () {
		AudioPlayer.embed(this.id, { soundFile: this.href });
	});
    
    // FIXME: Do a feature detection here instead of a browser detect.
    var selector = ($.browser.msie
        ? '.media-player.has-captions.ie'
        : '.media-player.has-captions.standard'
    );
    
    $(selector).each(function () {
        var controlId = 'player-controls-' + this.id;
        var div = $('<div id="' + controlId + '"></div>');
        var toggleCaptions = $('<a href="javascript:void(null);">Disable captions</a>');
        var showCaptions = $('<a href="javascript:void(null);">Show captions outside video</a>');
        var id = this.id;
        
        toggleCaptions.click(function (evt) {
            var $this = $(this);
            var captions = $this.data('captions');
            
            document.getElementById(id).hideCaptions(captions);
            
            if (captions)
            {
                $this.data('captions', false).html('Enable captions');
            }
            else
            {
                $this.data('captions', true).html('Disable captions');
            }
            
            evt.preventDefault();
            evt.stopPropagation();
        }).appendTo(div).data('captions', true);
        
        div.append(' ');
        
        showCaptions.click(function (evt) {
            var $this = $(this);
            var outside = $this.data('outside');
            var captions = toggleCaptions.data('captions');
            
            if (outside)
            {
                $('#caption-area').hide();
                $this.data('outside', false).html('Show captions outside video');
                toggleCaptions.show();
                
                if (!captions)
                {
                    toggleCaptions.click();
                }
            }
            else
            {
                // Turn off captions in the video itself.
                toggleCaptions.hide();
                
                if (captions)
                {
                    toggleCaptions.click();
                }
                
                // If the caption area doesn't exist, create it:
                if (!document.getElementById('caption-area'))
                {
                    $('<div id="caption-area"></div>').insertBefore('#' + controlId);
                }
                else
                {
                    $('#caption-area').show();
                }
                
                $this.data('outside', true).html('Show captions inside video');
            }
            
            evt.preventDefault();
            evt.stopPropagation();
        }).appendTo(div).data('outside', false);
        
        div.insertAfter($(this).parents('div')[0]);
    });
});
