/**
* LightBox Advanced
*
* This script will create an lightbox for each link who contain the rel attribute set to a
* specific function present in this script
*
* @author        David Zeller <zellerda01@gmail.com>
*/

var Lightbox = Class.create();

Lightbox = Object.extend(
{
    options: 
    { 
        path: '_js/lightbox', // Path form the document : use relative if you can
        plugins: ['image', 'ajax', 'youtube', 'dailymotion', 'iframe'],
        margin: 10
    },
    
    objLink: 0,
    plugin: 0,
    firstLoad: true,
    
    /**
     * Lightbox constructor
     */
    initialize: function()
    {
        this.autoload();
        this.listenLinks();
        this.draw();
    },
    
    /**
     * Load the associed scripts on the page and the plugins
     */
    autoload: function()
    {
        var objBody = $$('body')[0];
        var path = this.options['path'];
        
        // Add the rounded script
        objBody.appendChild(Builder.node('script', { type:'text/javascript', language: 'javascript', src: this.options['path'] + '/dd_roundies.js' }));
    },
    
    /**
     * Create the elements on the page
     */
    draw: function()
    {
        var objBody = $$('body')[0];

        objBody.appendChild(Builder.node('div',{id:'overlay'}));

        objBody.appendChild(Builder.node('div',{id:'lightbox'},
            Builder.node('div',{id:'lb_container'}, [
                Builder.node('div',{id:'lb_content'}),
                Builder.node('div',{id:'lb_loading'}, 
                    Builder.node('img', {src: this.options['path'] + "/images/loading.gif"})
                ),
                Builder.node('div', {id:'lb_control'})
            ])
        ));
        
        $('overlay').hide();
        $('lightbox').hide();
        $('lb_container').setStyle({ width: "250px", height: "250px" });
        
        var th = this;
        (function(){
            var ids = 'overlay lightbox lb_container lb_content lb_loading lb_control';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();
        
        this.place(250, 250, true);
    },
    
    /**
     * Add the controls to the control box
     */
    addControl: function(content)
    {
        if(!content)
        {
            this.lb_control.appendChild(Builder.node('div', {}, [
                Builder.node('img',{ src: this.options['path'] + '/images/close_large.png', onclick: 'Lightbox.close()', align: 'right', style: 'cursor: pointer; margin-top: 5px;' }),
                Builder.node('div', { id: 'lb_title' }),
                Builder.node('div', { id: 'lb_cc' })
            ]));
        }
        else
        {
            this.lb_control.appendChild(content);
        }
        
    },
    
    /**
     * Update the links, with rel attribute, click event to load the lightbox
     */
    listenLinks: function()
    {
        this.updateLinks = Prototype.emptyFunction;

        document.observe('click', (function(event){
            var target = event.findElement('a');
            if (target && target.rel != '') {
                event.stop();
                this.objLink = target;
                this.load(target);
            }
        }).bind(this));
    },
    
    /**
     * Show the lightbox through
     */
    load: function(element)
    {
        var relArray = element.rel.split("[");
        var parameters = relArray[1].replace(/]/g, '').replace(/ /g, '').replace(/\,/g, '&').replace(/:/g, '=');
        
        this.plugin = relArray[0].capitalize();
        
        if(typeof(DD_roundies) != 'undefined')
        {
            DD_roundies.addRule('#lb_container', '10px', true);
        }
        
        try
        {
            eval('Lightbox' + relArray[0].capitalize() + 'Plugin.initialize("' + parameters + '")');   
        }
        catch(ex)
        {
            alert('Plugin "' + relArray[0].capitalize() + '" not found');
        }
    },
    
    /**
     * Show the lightbox
     */
    appear: function()
    {   
        this.lightbox.show();
        this.hideElements();
        
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
        
        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('overlay').setStyle({ width: '100%', height: arrayPageSize[1] + 'px' });
        
        new Effect.Appear(this.overlay, { duration: 0.5 });
        new Effect.Appear(this.lightbox, { duration: 0.5 });
    },
    
    /**
     * Place the lightbox on the page
     */
    place: function(width, height, no_morph)
    {        
        var arrayViewportSize = this.getViewportSize();
        var m_height = (arrayViewportSize[1] / 2) - ((height + (this.options['margin'] * 3)) / 2);
        
        var scrollX, scrollY;

        if (document.all)
        {
            if (!document.documentElement.scrollTop)
                scrollY = document.body.scrollTop;
            else
                scrollY = document.documentElement.scrollTop;
        }   
        else
        {
            scrollY = window.pageYOffset;
        }    
        
        if(no_morph)
        {
            $('lb_container').setStyle({ top: Math.round(m_height + scrollY) + 'px' });
        }
        else
        {
            this.lb_container.morph('top: ' + Math.round(m_height + scrollY) + 'px');
        }
        
    },
    
    /**
     * Set the content to the lightbox
     */
    setContent: function(content)
    {
        this.lb_content.update(content);
    },
    
    /**
    * Show the content
    */
    showContent: function()
    {       
        this.lb_loading.hide();
        new Effect.Appear(this.lb_content, { duration: 0.5, queue: 'end'});
        new Effect.BlindDown(this.lb_control, { duration: 0.2, queue: 'end'});
    },
    
    /**
    * Hide elements during transition 
    */
    hideElements: function()
    {
        this.lb_loading.show();
        this.lb_content.hide();
        this.lb_control.hide();
        this.clean();
    },
    
    /**
    * Hide the lightbox
    */
    close: function()
    {
        this.lightbox.hide();
        this.hideElements();
        new Effect.Fade(this.overlay, { duration: 0.2 });
        this.lb_content.setStyle({ overflow: 'hidden' });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    },
    
    /**
    * Clean the html in lbContent
    */
    clean: function()
    {
        this.lb_content.innerHTML = '';
        this.lb_control.innerHTML = '';
    },
    
    /**
    * Resize the lightbox
    */
    resize: function(width, height) 
    {
        width = parseInt(width);
        height = parseInt(height);
        
        height += (32 + this.options['margin']);

        this.place(width, height);
        
        // get current width and height
        var widthCurrent  = this.lb_container.getWidth();
        var heightCurrent = this.lb_container.getHeight();
        
        // get new width and height
        var widthNew  = (width + (this.options['margin'] * 2));
        var heightNew = (height + (this.options['margin'] * 2));

        // scalars based on change from old to new
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;

        // calculate size difference between new and old image, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.lb_container, yScale, {scaleX: false, duration: 0.5, delay: 0.5 }); 
        if (wDiff != 0) new Effect.Scale(this.lb_container, xScale, {scaleY: false, duration: 0.5, delay: 0.5 }); 

        // if new and old image are same size and no scaling transition is necessary, 
        // do a quick pause to prevent image flicker.
        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)){
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;   
        }

        (function(){
            this.lb_control.setStyle({ width: (widthNew - (this.options['margin'] * 2)) + 'px' });
            this.showContent();
        }).bind(this).delay(timeout / 1000);
    },
    
    /**
    * Get the size of the viewport
    */
    getViewportSize: function()
    {
        var windowWidth, windowHeight;
        
        if (self.innerHeight) {    // all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }    

        arrayPageSize = new Array(windowWidth,windowHeight) 
        return arrayPageSize;
    },
    
    /**
    * Get the page size
    */
    getPageSize: function()
    {
        var xScroll, yScroll;
        
        if (window.innerHeight && window.scrollMaxY) {    
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
        
        var windowWidth, windowHeight;
        
        if (self.innerHeight) {    // all except Explorer
            if(document.documentElement.clientWidth){
                windowWidth = document.documentElement.clientWidth; 
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }    
        
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else { 
            pageHeight = yScroll;
        }
    
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){    
            pageWidth = xScroll;        
        } else {
            pageWidth = windowWidth;
        }

        return [pageWidth,pageHeight];
    }
    
}, window.Lightbox || {});

// Autoload
document.observe('dom:loaded', function () { Lightbox.initialize(); });

LightboxAjaxPlugin = Object.extend(
{
    options: { 
        width: 640, 
        height: 480,
        autoSize: 'false'
    },
    
    parameters: 0,
    objLink: 0,
    
    initialize: function(params)
    {
        this.parameters = params.toQueryParams();

        this.objLink = Lightbox.objLink;
        Lightbox.appear();
        
        this.load();
    },
    
    getParam: function(name)
    {
        if(this.parameters[name])
        {
            return this.parameters[name];
        }
        else
        {
            if(this.options[name])
            {
                return this.options[name];
            }
            else
            {
                alert('Parameter "' + name + '" not found');
                return false;
            }
        }
    },
    
    load: function()
    {
        var height = this.getParam('height');
        var width = this.getParam('width');
        
        if(eval(this.getParam('autoSize')))
        {
            var view = Lightbox.getViewportSize(); 
            
            width = view[0] - ((Lightbox.options['margin'] * 2) + 50);
            height = view[1] - ((Lightbox.options['margin'] * 3) + 82);
        }
        
        $('lb_content').innerHTML = '<div id="lb_ajax"></div>';
        $('lb_ajax').setStyle({ overflowY: "auto", overflowX: 'hidden', height: height + "px" });
        
        new Ajax.Request( this.objLink.href ,{ 
            evalScripts: true,
            method: 'get',
            onComplete: (function(transport) {
                
                var content = transport.responseText;
                $('lb_ajax').update(content);
                
                Lightbox.addControl();
                
                Lightbox.resize(width, height);
                
            }).bind(this)
        });
    }
    
}, window.LightboxAjaxPlugin || {})

LightboxDailymotionPlugin = Object.extend(
{
    options: { 
        width: 480, 
        height: 381
    },
    
    parameters: 0,
    objLink: 0,
    
    initialize: function(params)
    {
        this.parameters = params.toQueryParams();

        this.objLink = Lightbox.objLink;
        Lightbox.appear();
        
        this.load();
    },
    
    getParam: function(name)
    {
        if(this.parameters[name])
        {
            return this.parameters[name];
        }
        else
        {
            if(this.options[name])
            {
                return this.options[name];
            }
            else
            {
                alert('Parameter "' + name + '" not found');
                return false;
            }
        }
    },
    
    load: function()
    {
        var size = [this.getParam('width'), this.getParam('height')];
        
        var lb_dailymotion_link = this.objLink.href;
        
        Lightbox.setContent('<div><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="' + size[0] + '" height="' + size[1] + '"><param name="movie" value="' + lb_dailymotion_link + '"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed src="' + lb_dailymotion_link + '" type="application/x-shockwave-flash" width="' + size[0] + '" height="' + size[1] + '" allowFullScreen="true" allowScriptAccess="always"></embed></object>');
        
        Lightbox.addControl();
        Lightbox.resize(this.getParam('width'), this.getParam('height'));
    }
    
}, window.LightboxDailymotionPlugin || {})

LightboxIframePlugin = Object.extend(
{
    options: { 
        width: 640, 
        height: 480,
        autoSize: 'false'
    },
    
    parameters: 0,
    objLink: 0,
    
    initialize: function(params)
    {
        this.parameters = params.toQueryParams();

        this.objLink = Lightbox.objLink;
        Lightbox.appear();
        
        this.load();
    },
    
    getParam: function(name)
    {
        if(this.parameters[name])
        {
            return this.parameters[name];
        }
        else
        {
            if(this.options[name])
            {
                return this.options[name];
            }
            else
            {
                alert('Parameter "' + name + '" not found');
                return false;
            }
        }
    },
    
    load: function()
    {
        var height = this.getParam('height');
        var width = this.getParam('width');
        
        if(eval(this.getParam('autoSize')))
        {
            var view = Lightbox.getViewportSize(); 
            
            width = view[0] - ((Lightbox.options['margin'] * 2) + 50);
            height = view[1] - ((Lightbox.options['margin'] * 3) + 82);
        }
        
        var lw_iframe = document.createElement("iframe");
        lw_iframe.setAttribute('id','lbIframe');
        lw_iframe.style.border = 0;
        
        // FOR IE
        lw_iframe.onreadystatechange = (function(){
            
            if (lw_iframe.readyState == "interactive"){
                
                Lightbox.resize(width, height);
            }
        }).bind(this);
            
        // FOR FF
        lw_iframe.onload = (function(){
            
            Lightbox.resize(width, height);
        }).bind(this);
        
        lw_iframe.src = this.objLink.href;
        
        lw_iframe.style.width = width + "px";
        lw_iframe.style.height = height + "px";
        
        Lightbox.setContent(lw_iframe);
        Lightbox.addControl();
    }
    
}, window.LightboxIframePlugin || {})

LightboxImagePlugin = Object.extend(
{
    parameters: 0,
    objLink: 0, 
    imageArray: [],
    activeImage: 0,
    controlDetails: 'Image %current% of %of%',
    
    initialize: function(params)
    {
        this.parameters = params.toQueryParams();
        this.objLink = Lightbox.objLink;
        this.createGallery();
    },
    
    createGallery: function()
    {
        Lightbox.appear();
        
        var imageNum = 0; 
         
        if (!this.parameters['gallery'])
        {
            // if image is NOT part of a set, add single image to imageArray
            this.imageArray.push([this.objLink.href, this.objLink.title]);         
        } 
        else 
        {
            // if image is part of a set..
            this.imageArray = 
                $$(this.objLink.tagName + '[href][rel="' + this.objLink.rel + '"]').
                collect(function(anchor){ return [anchor.href, anchor.title]; }).
                uniq();
            
            while (this.imageArray[imageNum][0] != this.objLink.href) { imageNum++; }
        }
        
        this.change(imageNum);
    },
    
    change: function(imageNum)
    {
        if (imageNum < 0){
            
            imageNum = this.imageArray.length - 1;
        }
        
        if (imageNum > this.imageArray.length - 1){
            
            imageNum = 0;
        }
        
        this.activeImage = imageNum; // update global var
        
        Lightbox.hideElements();
        
        var lb_image = document.createElement("img");
        lb_image.setAttribute('id','lb_image');
        Lightbox.lb_content.appendChild(lb_image);

        var imgPreloader = new Image();
        
        // once image is preloaded, resize image container
        imgPreloader.onload = (function(){
            $('lb_image').src = this.imageArray[this.activeImage][0];
            this.resize(imgPreloader, $('lb_image'));
            this.control();
        }).bind(this);
        
        imgPreloader.src = this.imageArray[this.activeImage][0];
    },
    
    /**
    * Load an image or an image gallery
    *
    * @param        object    objImage        The image element
    */
    resize: function(objImage){
        
        var width, height, viewportSize, windowWidth, windowHeight, diviser;
        
        width = objImage.width;
        height = objImage.height;
        
        viewportSize = Lightbox.getViewportSize();
        
        windowWidth = viewportSize[0];
        windowHeight = viewportSize[1];
        
        if (width > windowWidth){
            
            diviser = width / (windowWidth - (Math.round(windowWidth / 4)));
            
            width = width / diviser;
            height = height / diviser;
        }
        
        if ((height + 40) > windowHeight){
            
            diviser = height / (windowHeight - (Math.round(windowHeight / 4)));
            
            width = width / diviser;
            height = height / diviser;
        }
        
        $('lb_image').style.width = Math.round(width) + "px";
        $('lb_image').style.height = Math.round(height) + "px";

        Lightbox.resize(Math.round(width), Math.round(height));
    },
    
    control: function()
    {
        var path = Lightbox.options['path'];
        var controls = Builder.node('div', {}, [
            Builder.node('img',{ src: path + '/images/close_large.png', onclick: 'Lightbox.close()', align: 'right', style: 'cursor: pointer; margin-top: 5px;' }),
            Builder.node('div', { id: 'lb_title' }),
            Builder.node('div', { id: 'lb_cc' })
        ]);

        Lightbox.addControl(controls);
        
        var details = this.controlDetails.replace(/\%current\%/, this.activeImage + 1).replace(/\%of\%/, this.imageArray.length);
        var nav = '&nbsp;&nbsp;|&nbsp;&nbsp;<img id="inner_prev" src="' + path + '/images/inner_prev.png" align="absmiddle" style="cursor: pointer;" /> <img id="inner_next" src="' + path + '/images/inner_next.png" align="absmiddle" style="cursor: pointer;" />';
        
        var cc = details;
        
        if(this.imageArray.length > 1)
        {
            cc += nav;
        }
        
        $('lb_title').update(this.imageArray[this.activeImage][1]);
        $('lb_cc').update(cc);
        
        if(this.imageArray.length > 1)
        {
            $('inner_prev').observe('click', (function(event) { event.stop(); this.change(this.activeImage - 1); }).bindAsEventListener(this));
            $('inner_next').observe('click', (function(event) { event.stop(); this.change(this.activeImage + 1); }).bindAsEventListener(this));
        }
    }
    
}, window.LightboxImagePlugin || {})

LightboxYoutubePlugin = Object.extend(
{
    options: { 
        width: 425, 
        height: 355
    },
    
    parameters: 0,
    objLink: 0,
    
    initialize: function(params)
    {
        this.parameters = params.toQueryParams();

        this.objLink = Lightbox.objLink;
        Lightbox.appear();
        
        this.load();
    },
    
    getParam: function(name)
    {
        if(this.parameters[name])
        {
            return this.parameters[name];
        }
        else
        {
            if(this.options[name])
            {
                return this.options[name];
            }
            else
            {
                alert('Parameter "' + name + '" not found');
                return false;
            }
        }
    },
    
    load: function()
    {
        var size = [this.getParam('width'), this.getParam('height')];
        
        var lb_youtube_link = this.objLink.href.replace("http://www.youtube.com/watch?v=", "");
        
        Lightbox.setContent('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="' + size[0] + '" height="' + size[1] + '"><param name="movie" value="http://www.youtube.com/v/' + lb_youtube_link + '&hl=fr&rel=0"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' + lb_youtube_link + '&hl=fr&rel=0" type="application/x-shockwave-flash" wmode="transparent" width="' + size[0] + '" height="' + size[1] + '"></embed></object>');
        
        Lightbox.addControl();
        Lightbox.resize(this.getParam('width'), this.getParam('height'));
    }
    
}, window.LightboxYoutubePlugin || {})