window.addEvent(
    'domready', function() {
        var overlay   = new Element('div', {'id': 'overlay'});
        var shadow    = new Element('div', {'id': 'overlayShadow'});
        var container = new Element('div', {'id': 'videoPlayer'});
        var closeButton = new Element('div', {'id': 'closeButton'});
        closeButton.grab( new Element('a', {"html": "&nbsp;", "href": "#" }));

        $(document.body).adopt(
            overlay.adopt(
                shadow,
                closeButton,
                container
            ));

        if (!Browser.Engine.trident4){
            var resizeOverlay = function  () {
                var dimensions = $(document.body).getScrollSize();
                overlay.setStyles({
                    height: dimensions.y,
                    width: Math.max(
                        $(document.body).getSize().x,
                        $('mainContainer').getSize().x)
                });
            };
            window.addEvents({
                resize: resizeOverlay
            });
            resizeOverlay();
        }

        var hide = function(){
            overlay.setStyle('display', 'none');
            if($f()) $f().stop();
        };

        var show = function(){
            overlay.setStyle('display','block');
        };


        hide();
        closeButton.addEvent('click', hide);
        shadow
            .addEvent('click', hide)
            .setStyles({
                'background': 'black'
            });
        shadow.get('tween', {property: 'opacity'}).set(0.4);

        /* This code makes the overlay position "correctly" in ie6
         * stolen from Slimbox as allowed under the MIT License */
        var ie6 = Browser.Engine.trident4;
        var compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
        if (compatibleOverlay)  overlay.style.position = "absolute";

        function position() {
            var scroll = window.getScroll(), size = window.getSize();
            container.setStyle("left", scroll.x + (size.x / 2));
            if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
        }

        if (ie6) {
            window.addEvents({
                'scroll': position,
                'resize': position
            });
            position();
        }
        /* end stolen code */

        var player;
        var nextVideoIndex = -1;

        function play (index) {
            try {
		nextVideoIndex = -1;
		player.play(index);
	    } catch(err) {
                nextVideoIndex = index;
            }
            show();
	    return false;
        }

        function buildPlaylist () {
            function playlistData (element) {
                // This is going to run inside Array.collect
                // so it throws at the slightest provocation
                function videoData (element) {
                    // Extract playlist data from a video link
                    return {
                        url: element.get('href').match(/^#?(.*)$/)[1],
                        thumbnailUrl: element.getElement('img').get('src')
                    };
                }

                function imageData (element) {
                    // Extract playlist data from a staticImage link
                    var imageUrl = element.get('href');
                    return $defined(imageUrl) ? {
                        url: imageUrl,
                        thumbnailUrl: element.get('href')
                    } : $throw();
                }

                return element.hasClass('video')       ? videoData(element)
                    :  element.hasClass('staticImage') ? imageData(element)
                    :  $throw();
            }

            if($$('a[rel=media]')) {
                return $$('a[rel=media]').collect(
                    function(item, index) {
                        var data = playlistData(item);
                        item.addEvent('click', play.pass(index));
                        return data;
                    });
                }
        };

        flowPlayerConfig.playlist = buildPlaylist();
        flowPlayerConfig.onLoad = function()
        {
            if(nextVideoIndex >= 0)
            {
	        player.play(nextVideoIndex);
	        nextVideoIndex = -1;
            }
        };
	flowPlayerConfig.clip.onStart = onClipStart;
	flowPlayerConfig.clip.onBegin = onClipStart;
        player = flowplayer( container,  '/userfiles/flowplayer/flowplayer.commercial-3.1.0.swf', flowPlayerConfig);

	var imageUrlRegex = /\.(png|gif|jpg|jpeg)$/;
	player.getPlaylist().each(
            function(clip) {
		if(imageUrlRegex.test(clip.url))
		{
		    var img = new Element("img");
		    img.addEvent('load', onPlaylistImageLoaded.pass([ clip, img ]));
		    img.src = clip.url;
		}
	    });

	function onPlaylistImageLoaded(clip, img)
	{
	    clip.width = img.width;
	    clip.height = img.height;
	}

	function onClipStart(clip)
	{
	    var parent = this.getParent();
            var resize = function(width, height) {
                parent.setStyles({
                    'width': width,
		    'height': height
                });

                closeButton.setStyle('width', width + 128);
            };

	    if(clip.metaData && clip.metaData.width && clip.metaData.height)
	    {
                resize(clip.metaData.width, clip.metaData.height);
	    }
	    else if(clip.width && clip.height)
	    {
                resize(clip.width, clip.height);
	    }
	}
    });
