/*!
	Slimbox v1.64 - The ultimate lightweight Lightbox clone
	(c) 2007-2008 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
	
	Modifications by Aaron B. Dixon <http://eVolve-web.com>
	Noted by mod[eVolve]
	* Modification to overlay requires cnet's IframeShim.js
	* Requires swfobject.js in many cases. Not using MooTools 1.2 Swiff object because of lack of express install feature.
*/

var Slimbox;

(function() {

    // Global variables, accessible to Slimbox only
    var state = 0, options, items, activeItem, prevItem, nextItem, top, fx, preloadPrev = new Image(), preloadNext = new Image(),
    // State values: 0 (closed or closing), 1 (open and ready), 2+ (open and busy with animation)

    // DOM elements
	overlay, center, item, content, prevLink, nextLink, bottomContainer, navigation, text, bottom, caption, number, shim;

    /*
    Initialization
    */

    window.addEvent("domready", function() {
        // Append the Slimbox HTML code at the bottom of the document
        $(document.body).adopt(
			$$([
				overlay = new Element("div", { id: "lbOverlay" }), //.addEvent("click", close), mod[eVolve]
				center = new Element("div", { id: "lbCenter" }),
				bottomContainer = new Element("div", { id: "lbBottomContainer" })
			]).setStyle("display", "none")
		);

        item = new Element("div", { id: "lbItem" }).injectInside(center);

        bottom = new Element("div", { id: "lbBottom" }).injectInside(bottomContainer).adopt(
		    navigation = new Element("div", { id: "lbNav" }),
		    text = new Element("div", { id: "lbText" })
		);

        navigation.adopt(
		    prevLink = new Element("a", { id: "lbPrevLink", href: "javascript:void(0);" }),
			nextLink = new Element("a", { id: "lbNextLink", href: "javascript:void(0);" }),
			closeLink = new Element("a", { id: "lbCloseLink", href: "javascript:void(0);" }).addEvent("click", close),
			new Element("div", { styles: { clear: "both"} })
		);

        text.adopt(
		    caption = new Element("div", { id: "lbCaption" }),
			number = new Element("div", { id: "lbNumber" }),
			new Element("div", { styles: { clear: "both"} })
		);

        fx = {
            overlay: new Fx.Tween(overlay, { property: "opacity", duration: 500 }).set(0),
            item: new Fx.Tween(item, { property: "opacity", duration: 500, onComplete: nextEffect }),
            bottom: new Fx.Tween(bottom, { property: "margin-top", duration: 400 })
        };
    });


    /*
    API
    */

    Slimbox = {
        open: function(_items, startItem, _options) {
            options = $extend({
                loop: false, 			// Allows to navigate between first and last images
                overlayOpacity: 0.8, 		// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
                resizeDuration: 400, 		// Duration of each of the box resize animations (in milliseconds)
                resizeTransition: false, 	// Default transition in mootools
                initialWidth: 250, 		// Initial width of the box (in pixels)
                initialHeight: 250, 		// Initial height of the box (in pixels) 
                animateCaption: true,
                showCounter: true, 		// If true, a counter will only be shown if there is more than 1 image to display
                counterText: 'Item {x} of {y}', 	// Translate or change as you wish
                theme: ''
            }, _options || {});

            // The function is called for a single image, with URL and Title as first two arguments
            if (typeof _items == 'string') {
                _items = [[_items, startItem]];
                startItem = 0;
            }

            items = _items;
            options.loop = options.loop && (items.length > 1);
            position();
            setup(true);
            top = window.getScrollTop() + (window.getHeight() / 15);
            fx.resize = new Fx.Morph(center, $extend({ duration: options.resizeDuration, onComplete: nextEffect }, options.resizeTransition ? { transition: options.resizeTransition} : {}));
            center.setStyles({ top: top, width: options.initialWidth, height: options.initialHeight, marginLeft: -(options.initialWidth / 2), display: '' });
            fx.overlay.start(options.overlayOpacity);
            state = 1;
            return changeItem(startItem);
        }
    };

    Element.implement({
        slimbox: function(_options, linkMapper) {
            // The processing of a single element is similar to the processing of a collection with a single element
            $$(this).slimbox(_options, linkMapper);

            return this;
        }
    });

    Elements.implement({
        /*
        options:	Optional options object, see Slimbox.open()
        linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
        the image URL and the image caption (may contain HTML)
        linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
        the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
        This function must always return true when the DOM element argument is "this".
        */
        slimbox: function(_options, linkMapper, linksFilter) {
            linkMapper = linkMapper || function(el) {
                return [el.href, el.title, getOptionHash(el.rel)];
            };

            linksFilter = linksFilter || function() {
                return true;
            };

            var links = this;

            links.removeEvents('click').addEvent('click', function() {
                // Build the list of images that will be displayed
                var filteredLinks = links.filter(linksFilter, this);
                return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
            });

            return links;
        }
    });

    /*
    Internal functions
    */

    function position() {
        overlay.setStyles({ top: window.getScrollTop(), height: window.getHeight() });
    }

    function setup(open) {
        // Use IframeShim instead of hiding IE Elements
        if (open) { shim = new IframeShim(overlay, { name: 'navshim', display: true }); }
        else { shim.hide(); }

        overlay.style.display = open ? '' : 'none';

        var fn = open ? 'addEvent' : 'removeEvent';
        window[fn]('scroll', position)[fn]('resize', position);
        document[fn]('keydown', keyDown);
    }

    function keyDown(event) {
        switch (event.code) {
            case 27: // Esc
            case 88: // 'x'
            case 67: // 'c'
                close();
                break;
            case 37: // Left arrow
            case 80: // 'p'
                previous();
                break;
            case 39: // Right arrow
            case 78: // 'n'
                next();
        }
        // Prevent default keyboard action (like navigating inside the page)
        return false;
    }

    function previous() {
        return changeItem(prevItem);
    }

    function next() {
        return changeItem(nextItem);
    }

    function changeItem(itemIndex) {
        if ((state == 1) && (itemIndex >= 0)) {
            state = 2;
            activeItem = itemIndex;
            prevItem = ((activeItem || !options.loop) ? activeItem : items.length) - 1;
            nextItem = activeItem + 1;
            if (nextItem == items.length) nextItem = options.loop ? 0 : -1;

            center.set('class', 'lbLoading');
            $$(item, bottomContainer).setStyle('display', 'none');
            fx.bottom.cancel().set(0);
            fx.item.set(0);

            setContent();    // handles what used to be handled by new Image() with onload = nextEffect / mod[eVolve]
        }

        return false;
    }

    // set content area  / mod[eVolve]
    function setContent() {
        var type, obj, videoId, link = items[activeItem][0], hash = items[activeItem][2], flashvars = {}, params = {}, loaded = true, flash;

        var coptions = $extend({
            modal: false,       // If false the overlay will close Slimbox / mod[eVolve]
            width: 400,
            height: 400,
            mediaPlayer: '/resources/flash/player.swf',       // location of media player for flv, mp3, mp4, h.264, aac flv7, flv8 formats
            expressInstall: '/resources/flash/expressinstall.swf',       // location of the expressinstall swf
            fullscreen: true,
            autoplay: false,
            controls: 'bottom',    // bottom | over | none
            bgcolor: '#000',
            wmode: 'opaque',
            version: 9.0,
            minor: 124.0
        });

        if (link.match(/dailymotion\.com/i)) { type = 'dailymotion'; }
        else if (link.match(/flickr\.com/i)) { type = 'flickr'; }
        else if (link.match(/google\.com\/videoplay/i)) { type = 'google'; videoId = link.split('='); videoId = videoId[1]; }
        else if (link.match(/metacafe\.com\/watch/i)) { type = 'metacafe'; videoId = link.split('/'); videoId = videoId[4] + '/' + videoId[5]; }
        else if (link.match(/metacafe\.com\/fplayer/i)) { type = 'metacafe'; videoId = link.split('/'); videoId = videoId[4] + '/' + videoId[5].replace('.swf', ''); }
        else if (link.match(/myspacetv\.com/i) || link.match(/vids.myspace\.com/i)) { type = 'myspacetv'; videoId = link.split('='); videoId = videoId[2]; }
        else if (link.match(/revver\.com/i)) { type = 'revver'; videoId = link.split('/'); videoId = videoId[4]; }
        else if (link.match(/youtube\.com\/v/i)) { type = 'youtube'; videoId = link.substr(link.lastIndexOf('/') + 1).toLowerCase(); }
        else if (link.match(/youtube\.com\/watch/i)) { type = 'youtube'; videoId = link.split('='); videoId = videoId[1]; }
        else if (link.match(/veoh\.com/i)) { type = 'veoh'; videoId = link.split('/'); videoId = videoId[4]; }
        else if (link.match(/viddler\.com/i)) { type = 'viddler'; }
        else if (link.match(/vimeo\.com/i)) { type = 'vimeo'; }
        else if (link.match(/\#box_/i)) { type = 'inline'; }
        else { type = link.substr(link.lastIndexOf('.') + 1).toLowerCase(); }

        // set coptions based on relcoptions (modal, wmode, fullscreen, controls, bgcolor, autoplay, width, height) / mod[eVolve]
        if (hash.get('modal') != null) { coptions.modal = hash.get('modal'); }
        if (hash.get('wmode') != null) { coptions.wmode = hash.get('wmode'); }
        if (hash.get('fullscreen') != null) { coptions.fullscreen = hash.get('fullscreen'); }
        if (hash.get('controls') != null) { coptions.controls = hash.get('controls'); }
        if (hash.get('bgcolor') != null) { coptions.bgcolor = hash.get('bgcolor'); }
        if (hash.get('autoplay') != null) { coptions.autoplay = hash.get('autoplay'); }
        if (hash.get('width') != null) { coptions.width = hash.get('width'); }
        if (hash.get('height') != null) { coptions.height = hash.get('height'); }
        if (hash.get('version') != null) { coptions.version = hash.get('version'); }
        if (hash.get('minor') != null) { coptions.minor = hash.get('minor'); }

        // set item format based on coptions
        if (!coptions.modal) { overlay.setStyles({ cursor: 'pointer' }).removeEvent('click', close).addEvent('click', close); }  // Allow Overlay to not close lightbox / mod[eVolve]
        else { overlay.setStyles({ cursor: 'default' }).removeEvent('click', close); }      // Dis-Allow Overlay to not close lightbox / mod[eVolve]

        if (item.getChildren().length > 0) { item.empty(); }

        switch (type) {
            case 'jpg':
            case 'gif':
            case 'png':
            case 'bmp':
                flash = false;
                loaded = false;
                obj = new Image();
                obj.src = link;
                obj.onload = function() {
                    loaded = true;
                    coptions.width = obj.width;
                    coptions.height = obj.height;
                }
                break;
            case 'swf':
                flash = true;
                obj = new Swiff(link, { id: 'swf', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: {} });
                break;
            case 'flv':
            case 'f4v':
            case 'vp6':
            case 'mp3':
            case 'mp4':
            case 'aac':
                flash = true;
                obj = new Swiff(coptions.mediaPlayer, { id: 'flv', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: { file: link, autostart: coptions.autoplay, fullscreen: coptions.fullscreen, controlbar: coptions.controls} });
                break;
            case 'inline':
                flash = false;
                var inlinearray = link.split('#');
                var inline = $(inlinearray[1]);
                if (inline == null) { obj = new Element('div', { id: 'lbInline' }).set('html', '<p>Error</p><p>The content cannot be found</p>'); }
                else { obj = new Element('div', { id: 'lbInline' }).set('html', inline.get('html')); }
                break;
            case 'ajax':
                flash = true;
                obj = new Element('div', { id: 'lbInline' }).set('html', '<div style="padding:10px;"><p>Error</p><p>Feature not yet implemented</p></div>');
                break;
            case 'mov':
                flash = true;
                obj = new Element('div', { id: 'lbInline' }).set('html', '<div style="padding:10px;"><p>Error</p><p>Feature not yet implemented</p></div>');
                break;
            case 'dailymotion':
                flash = true;
                obj = new Swiff(link + '&autoplay=' + (coptions.autoplay ? '1' : '0'), { id: 'dailymotion', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: {} });
                break;
            case 'flickr':
                flash = true;
                obj = new Element('div', { id: 'lbInline' }).set('html', '<div style="padding:10px;"><p>Error</p><p>Feature not yet implemented</p></div>');
                break;
            case 'google':
                flash = true;
                obj = new Swiff('http://video.google.com/googleplayer.swf?docId=' + videoId + '&autoplay=' + (coptions.autoplay ? '1' : '0') + '&fs=' + coptions.fullscreen, { id: 'google', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: {} });
                break;
            case 'metacafe':
                flash = true;
                obj = new Swiff('http://www.metacafe.com/fplayer/' + videoId + '.swf', { id: 'metacafe', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: { playerVars: 'showStats=no|autoPlay=' + (coptions.autoplay ? 'yes' : 'no')} });
                break;
            case 'myspacetv':
                flash = true;
                obj = new Swiff('http://mediaservices.myspace.com/services/media/embed.aspx/m=' + videoId + ',t=1,mt=video,ap=' + (coptions.autoplay ? '1' : '0'), { id: 'myspacetv', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: {} });
                break;
            case 'revver':
                flash = true;
                obj = new Swiff('http://flash.revver.com/player/1.0/player.swf?mediaId=' + videoId, { id: 'revver', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: { allowFullScreen: coptions.fullscreen, autoStart: coptions.autoplay} });
                break;
            case 'youtube':
                flash = true;
                obj = new Swiff('http://www.youtube.com/v/' + videoId + '&autoplay=' + (coptions.autoplay ? '1' : '0') + '&fs=' + (coptions.fullscreen ? '1' : '0'), { id: 'youtube', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: {} });
                break;
            case 'veoh':
                flash = true;
                obj = new Swiff('http://www.veoh.com/veohplayer.swf?permalinkId=' + videoId + '&videoAutoPlay=' + (coptions.autoplay ? '1' : '0') + '&allowFullScreen=' + coptions.fullscreen, { id: 'veoh', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: { allowFullScreen: coptions.fullscreen, autoStart: coptions.autoplay} });
                break;
            case 'viddler':
                flash = true;
                obj = new Element('div', { id: 'lbInline' }).set('html', '<div style="padding:10px;"><p>Error</p><p>Feature not yet implemented</p></div>');
                break;
            case 'vimeo':
                flash = true;
                obj = new Element('div', { id: 'lbInline' }).set('html', '<div style="padding:10px;"><p>Error</p><p>Feature not yet implemented</p></div>');
                break;
            default:    // iframe
                flash = false;
                obj = new Element('iframe', { id: 'lbFrame_' + new Date().getTime(), width: coptions.width, height: coptions.height, frameBorder: 0, scrolling: 'auto', src: link });
                break;
        }

        // if content is flash check version and if not high enough show express install
        if (flash && (Browser.Plugins.Flash.version < coptions.version || (Browser.Plugins.Flash.version == coptions.version && Browser.Plugins.Flash.number < coptions.minor))) {
            obj = new Swiff(coptions.expressInstall, { id: 'express', width: coptions.width, height: coptions.height, params: { wmode: coptions.wmode, bgcolor: coptions.bgcolor, allowfullscreen: coptions.fullscreen }, vars: {} });
        }

        item.adopt(obj);
        item.setStyle('display', '');

        // use setInterval to wait on content type of Image to load so we can get the correct width and height then call nextEffect
        iId = setInterval(function() {
            if (loaded) {
                clearInterval(iId);
                $$(item, bottom).setStyle('width', coptions.width + 'px');
                $$(item).setStyle('height', coptions.height + 'px');
                nextEffect();
            }
        }, 500);
    }

    function nextEffect() {
        switch (state++) {
            case 2:
                caption.set('html', items[activeItem][1] || '');
                number.set('html', (options.showCounter && (items.length > 1)) ? options.counterText.replace(/{x}/, activeItem + 1).replace(/{y}/, items.length) : '');

                if (prevItem >= 0) preloadPrev.src = items[prevItem][0];
                if (nextItem >= 0) preloadNext.src = items[nextItem][0];

                if (center.clientHeight != item.offsetHeight) {
                    fx.resize.start({ height: item.offsetHeight });
                    break;
                }
                state++;
            case 3:
                if (center.clientWidth != item.offsetWidth) {
                    fx.resize.start({ width: item.offsetWidth, marginLeft: -item.offsetWidth / 2 });
                    break;
                }
                state++;
            case 4:
                bottomContainer.setStyles({ top: top + center.clientHeight + (center.getStyle('border-top-width').replace(/px/, '') - 0), marginLeft: center.style.marginLeft, visibility: 'hidden', display: '' });
                fx.item.start(1);
                center.set('class', '');
                break;
            case 5:
                if (prevItem >= 0) { prevLink.set('class', ''); prevLink.removeEvent('click', previous).addEvent('click', previous); } else { prevLink.set('class', 'disabled'); prevLink.removeEvent('click', previous); }
                if (nextItem >= 0) { nextLink.set('class', '').removeEvent('click', next).addEvent('click', next); } else { nextLink.set('class', 'disabled').removeEvent('click', next); }
                if (options.animateCaption) {
                    fx.bottom.set(-bottom.offsetHeight).start(0);
                }
                bottomContainer.style.visibility = '';
                state = 1;
        }
    }

    function close() {
        if (state) {
            state = 0;
            if (item.getChildren().length > 0) { item.empty(); }      // if item area has children clear / mod[eVolve]
            for (var f in fx) fx[f].cancel();
            $$(center, bottomContainer).setStyle('display', 'none');
            fx.overlay.chain(setup).start(0);
        }

        return false;
    }

    // get hash of options passed in rel= / mod[eVolve]
    function getOptionHash(rel) {
        var hash = new Hash();
        var regex = '{[A-Za-z0-9,:]+}';
        var opt = rel.match(regex);

        if (opt != null) {
            var s = opt[0].replace(/^\{+|\}+$/g, '');

            var itemOptions = s.split(',');
            itemOptions.each(function(e) {
                var itemOptions2 = e.split(':');
                hash.set(itemOptions2[0], itemOptions2[1]);
            });
        }

        return hash;
    }

})();

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() 
{
	var links = $$('a').filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	});
	
	$$(links).slimbox({/* Put custom options here */}, null, function(el) {
		var regex = 'lightbox(\[[A-Za-z0-9]+\])?';  // regular expression to find lightbox and any grouping info / mod[eVolve]
		
		// get array of matches, [0] is lightbox[group], [1] is [group] / mod[eVolve]
		var open = this.rel.match(regex);       // clicked item    
		var each = el.rel.match(regex);         // each item
		
		// return item if same or arry of items that match with [group] / mod[eVolve]
		return (this == el) || (open[0] != 'lightbox' && open[0] == each[0]);
	});
};

window.addEvent('domready', Slimbox.scanPage);