/**
 * @author Eike Pierstorff
 *
 * Utilities für McDonalds. Benötigt Mootools 1.2
 *
 * Flash-Callbacks und Ajax
 *
 */

if(Browser.Plugins.Flash.version > 8) {
                 document.write('<style type="text/css">h1.sifr {visibility:hidden;}</style>');
}

var Mcdo_utils = new Class({
        /*
         * Um Klarheit zu vermeiden hat IE6 die Engine Version 4, IE7 Engine Version 5
         */
        isIE: function() {
                if(Browser.Engine.trident)        {
                        return  parseInt(Browser.Engine.version);
                }
                return false;
        },

        /*
         * @param string funcname
         *
         * Callback für Actionscriptfunktionen
         * Loopt durch die Liste der Filme und versucht die Funktion funcname im SWF aufzurufen
         */
        asCallback: function(funcname){ // Actionscript Callback
        movies = this._collectMovies();
        movies.each(function(n){
                        try {
                                eval("n." + funcname + "()");
                        } catch(e) {
                                //
                        }
        })
    },

    /*
     * freeze
     *
     * Hält die Ausführung der SWF-Filme an
     */
    freeze: function(){ // shortcut für asCallback zum anhalten der Filme
                this.asCallback('freeze');
    },

    /*
     * unfreeze
     *
     * Startet die Ausführung der SWF-Filme
     */
    unfreeze: function(){ // shortcut für asCallback zum start der Filme
        this.asCallback('unfreeze');
    },

        /*
         * loadDivByID
         *
         * @param string loadurl                URL der Seite die via Ajax geladen werden soll
         * @param string loadDiv                id des Div das aus der Seite extrahiert werden sollen
         * @param string updateDiv                id des Divs in das die Response geschrieben werden soll
         *
         * versucht ein Div mit einer bestimmten id
         */
    loadDivByID: function(loadurl, loadDiv, updateDiv){ // lädt aus eine externen Dokument loadurl das div mit der id loadDiv und setzt es in updateDiv ein
            var loadRequest = new Request({
            url: loadurl,
            method: 'get',
            onSuccess: function(responseText, responseXML){
                this._processHTML(responseText, loadDiv).inject($(updateDiv));
            } .bind(this),
            onError: function(responseText, responseXML){
                    // do nothing
            }.bind(this)
        }, this);
        loadRequest.send();
    },

        /*
         * _processHTML
         *
         *  @params string responsetext
         *  @params loadDiv
         *
         *  intern. extrahiert das Div loaddiv aus dem responsetext
         *
         */

    _processHTML: function(responseText, loadDiv){
                pattern = new RegExp("<!-- Start Here //-->([\\s\\S]*?)<!-- End Here //-->");
            var match = responseText.match(pattern);
                if(!$chk(match) ) {
                        pattern = new RegExp("<div id=\"" + loadDiv + "\">([\\s\\S]*?)</div>");
                        var match = responseText.match(pattern);
                }
                text = (match) ? match[1] : err;
                /* IE needs an extra ending div */
               if(Browser.Engine.trident)        {
                        text = text + '</div>';
                }
        var container = new Element('div');
                container.addClass('mcdo_layercenter');

        return $try(function(){
            var root = '<root>' + text + '</root>', doc;
            if (Browser.Engine.trident) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = false;
                doc.loadXML(root);
            }
            else {
                doc = new DOMParser().parseFromString(root, 'text/xml');
            }
            root = doc.getElementsByTagName('root')[0];
            for (var i = 0, k = root.childNodes.length; i < k; i++) {
                var child = Element.clone(root.childNodes[i], true, true);
                if (child)
                    container.grab(child);
            }
            return container;
        }) || container.set('html', text);
    },

    _collectMovies: function(){ // intern, sucht alle Flashmovies indem es nach Objekten sucht deren Name auf 'myId' endet
       return $(document.body).getElements('object[name$=myId]')
    }
});

window.addEvent('domready', function(){

        var Mcdo_gallery = new Class({
            Implements: [Options,Mcdo_utils],
            options: {
                galleryname:                 'mcdo_gallery',
                        menuname:                         'mcd_primarynavigation',
                        classZoom:                        'mcdo_gallery_zoom',
                        classAudio:                        'mcdo_gallery_audio',
                        classVideo:                        'mcdo_gallery_video',
                        classZoomHover:                'mcdo_gallery_zoom_hover',
                        classAudioHover:        'mcdo_gallery_audio_hover',
                        classVideoHover:        'mcdo_gallery_video_hover',
                prevImg:                         'siteimages/smallgallery_back.png',
                nextImg:                         'siteimages/smallgallery_forward.png',
                prevImgOver:                 'siteimages/smallgallery_back_over.png',
                nextImgOver:                 'siteimages/smallgallery_forward_over.png',
                prevImgIE6:                 'siteimages/smallgallery_back_ie6.png',
                nextImgIE6:                 'siteimages/smallgallery_forward_ie6.png',
                prevImgOverIE6:         'siteimages/smallgallery_back_over.png',
                nextImgOverIE6:         'siteimages/smallgallery_forward_ie6_over.png',
                        overLay:                         'siteimages/videoplay.png',
                        overLayIE6:                         'siteimages/videoplay_ie6.png',
                        offsetZindex:                 1
                },

            initialize: function(options){
                        this.setOptions(options);
                        this.ImgPath = "/design_nd/"; // current url
                        this.gallery = $(this.options.galleryname);
                        if(!$chk(this.gallery)) { // wenn es keine Galerie gibt steigen wir aus
                                return;
                        }

                        this.galleryItems = this.gallery.getElements('li');

                        this.galleryLinks = this.gallery.getElements('li a');
                        this.count = this.galleryItems.length;
                        z = this.options.offsetZindex; // z-index
                        this.galleryItems.each(function(n) {
                                this._setTween(n,1000);
                                n.setStyle('opacity',0);
                                n.setStyle('z-index',z++); // damit ist das erste Bilder der Liste auch das erste Bild der Galerie

                                // Zoom-Icons (und potentiell andere Icons) werden in Abhängigkeit vom rel-Attribut der Verlinkung vergeben
                                type = n.getFirst('a').get('rel');
                                switch(type) {
                                        case('lightbox[gallery]'):
                                        case('lightbox'):
                                                iconClass = this.options.classZoom;
                                                iconClassHover = this.options.classZoomHover;
                                        break;
                                        default:
                                                iconClass = "noicon";
                                                iconClassHover = "noicon";
                                        break;
                                }

                                n.addEvent('mouseenter', function(e){
                                        if($defined(n.getElement("."+iconClass)))
                                                n.getElement("."+iconClass).addClass(iconClassHover);
                                              this.clr();
                         }.bind(this));

                                n.addEvent('mouseleave', function(e){
                                        if($defined(n.getElement("."+iconClass)))
                                                n.getElement("."+iconClass).removeClass(iconClassHover);
                         }.bind(this));

                                if (n.getElement('a')) {
                                        zoom = new Element('a');
                                        zoom.addClass(iconClass);
                                        zoom.cloneEvents(n.getElement('a'));
                                        zoom.inject(n);
                                }
                        }, this);


                        /*
                         * Videoteaser in der Galerie kriegen ein Overlay-Icon
                         */


                        if($chk(this.isIE()) && this.isIE() < 5)        {
                                overlay = this.ImgPath + this.options.overLayIE6;
                        } else {
                                overlay = this.ImgPath + this.options.overLay;
                        }

                        // für den Overlay wird das Original in den Hintergrund gesetzt und der overlay in den Image-Tag geschrieben
                        $each($$('.mcdo_press_video_preview'), function(el) {
                                el.getParent().setStyles({backgroundImage:'url('+el.get('src') + ')',width:230,height:130,display:'block'});
                                el.set('src',overlay);
                        }.bind(this));

                        this.galleryItems[0].setStyle('opacity',1);

                        if (this.galleryItems.length < 2) { // Wenn es weniger als 2 Bilder gibt muss nichts rotieren
                                return;
                        }

                        this.navigation();

                        this.pagecount();
                        this.rotationTimer = this.rotate.periodical(3000, this);

                        this.galleryLinks.each(function(n) {
                                n.addEvent('click', function(e){
                                              this.clr();
                         }.bind(this));
                        }, this)
                },

                pagecount: function() {
                        offset = this._getCur();
                        cnt = (offset+1) + " von " + this.count;
                        $('mcdo_gallery_pagecount').set('text',cnt);
                },

                navigation: function() {

                        if($chk(this.isIE()) && this.isIE() < 5) {
                                this.options.prevImg                =  this.options.prevImgIE6;
                                this.options.prevImgOver        =  this.options.prevImgOverIE6;
                                this.options.nextImg                =  this.options.nextImgIE6;
                                this.options.nextImgOver        =  this.options.nextImgOverIE6;
                        }

                        wrapper = new Element('div');
                        navContainer = new Element('div');
                        navContainer.set('id','mcdo_gallery_navContainer');
                        navContainer.inject(wrapper);

                        navArea         =  new Element('div');
                        navArea.set('id','mcdo_gallery_navArea');

                           var prevImg = new Element('img');
                prevImg.set({
                    src: this.ImgPath + this.options.prevImg
                });

                           $(prevImg).addEvent('click', function(e){
                                  this.previous();
                 }.bind(this));

                           $(prevImg).addEvent('mouseenter', function(e){
                              $(prevImg).set('src',this.ImgPath + this.options.prevImgOver);
                 }.bind(this));

                           $(prevImg).addEvent('mouseleave', function(e){
                             $(prevImg).set('src',this.ImgPath + this.options.prevImg);
                 }.bind(this));


                        $(prevImg).inject(navArea);

                           var nextImg = new Element('img');
                nextImg.set({
                    src: this.ImgPath + this.options.nextImg
                });

                           $(nextImg).addEvent('click', function(e){
                           this.next();
                }.bind(this));

                           $(nextImg).addEvent('mouseenter', function(e){
                             $(nextImg).set('src',this.ImgPath + this.options.nextImgOver);
                 }.bind(this));

                           $(nextImg).addEvent('mouseleave', function(e){
                              $(nextImg).set('src',this.ImgPath + this.options.nextImg);
                 }.bind(this));

                        $(nextImg).inject(navArea);

                        pageCounter = new Element('div');
                        pageCounter.set('id','mcdo_gallery_pagecount');

                        wrapper.wraps(this.gallery);
                        navContainer.inject(wrapper);
                        navArea.inject(navContainer);
                        pageCounter.inject(navContainer);

                },

                show: function(index) {
                        this.galleryItems[index].get('tween').start(0,1);
                },

                hide: function(index) {
                        this.galleryItems[index].get('tween').start(1,0);
                },

                next: function() {
                        this.clr();
                        offset = this._getCur();
                        offset++;

                        if (offset  >= (this.count)) {
                                  offset  = 0;
                                  this.hide(this.count-1);
                        }

                        if($chk(this.galleryItems[offset].getPrevious())) {
                                this.hide(offset -1);
                        }

                        this.show(offset);
                },

                previous: function() {
                        this.clr();
                        offset  = this._getCur();
                        offset--;

                        if (offset < 0) {
                                  offset = (this.count-1);
                                  this.hide(0);
                        }

                        if($chk(this.galleryItems[offset].getNext())) {
                                 this.hide(offset+1);
                        } else {
                                this.hide(0);
                        }
                        this.show(offset);

                },

                clr: function() {
                         $clear(this.rotationTimer);
                },

                rotate: function() {
                        offset  = this._getCur();
                        offset++;
                        if (offset >= (this.count)) {
                                offset = 0;
                        }
                        if($chk(this.galleryItems[offset].getPrevious())) {
                                this.hide(offset-1);
                        } else if($chk(this.galleryItems.getLast())) {
                                this.hide(this.count-1);
                        }
                        this.show(offset);

                },

                _setTween: function(obj,dur) {
                        obj.set('tween', {
                    property: 'opacity',
                    duration: dur,
                                onComplete: function() {
                                        this.pagecount();
                                }.bind(this)
                },this);
                },

                _getCur: function() {
                        for(i=0,l=this.galleryItems.length;i<l;i++) {
                                op = this.galleryItems[i].getStyle('opacity');
                                if(op > 0.5)
                                        return i;
                        }
                        return 0;
                }
        });

                // mcd_gal = new Mcdo_gallery(); muss nach der Lightbox aufgerufen werden
        /**
         * @author Eike Pierstorff
         *
         * Layer-Skript für McDonalds. Benötigt Mootools 1.2
         *
         */

        var Mcdo_layercontrol = new Class({
            Implements: [Options,Mcdo_utils],
                options: {
                        menuname:                                         'mcd_primarynavigation',
                        defaultParent:                                'mcd_content_container',
                        defaultLayername:                        'defLyr',                                                // wie heisst der Layer der neu angelegt wird
                        defaultLoadLayer:                        'mcdo_stage_middle',                        // wie heisst der Layer der per Ajax aus einem Dokument gezogen wird
                        defaultcssClass:                        'mcdo_dynamicLayer',                        // wie heisst die KLasse wenn sonst keine angegeben ist
                        defaultVideocssClass:                'mcdo_videoLayer',                                // wie heisst die KLasse wenn sonst keine angegeben ist
                        closeButton:                                        'siteimages/schliessen_x.png',
                        closeButtonFallback:                        'siteimages/schliessen_x_ie6.png',
                        closeButtonHover:                                'siteimages/schliessen_x_over.png',
                        closeButtonHoverFallback:                'siteimages/schliessen_x_ie6_over.png',
                        closeButtonVideo:                                'siteimages/schliessen_x_2.png',
                        closeButtonVideoFallback:                'siteimages/schliessen_x_2_ie6.png',
                        closeButtonVideoHover:                        'siteimages/schliessen_x_2_over.png',
                        closeButtonVideoHoverFallback:        'siteimages/schliessen_x_2_ie6_over.png',
                        assetBaseUrl:                                 'styles/',
                        zIndex:                                                9001,
                        appRun:                                                'files/swf/apprunner.swf',
                        videoWidth:                                        960,
                        videoHeight:                                501,
                flvars: {                                                                                                  /* flashvars für den Videolayer*/
                                xmldata:                        "files/config/standalonevideoplayer/settings.xml"
                },
               params: {                                                                                                         /* Parameter für den Videolayer*/
                        menu: "false",
                        wmode: "opaque"
               },
               attributes: {                                                                                                 /* attributes für den Videolayer*/

                   }
                },

                initialize: function(options) {
                        this.setOptions(options);
                        this.addOverlay();
                        this.ImgPath = "/design_nd/"; // current url

                        this.options.appRun                                = this.ImgPath+this.options.appRun;
                        this.options.flvars.xmldata         = this.ImgPath+this.options.flvars.xmldata;

                        $(document.body).getElements('a[rel=openLayer]').each(function(n) {
                                this.setLink(n,this.options.defaultcssClass,this.options.defaultParent,this.options.defaultLayername);
                        },this)
                        $(document.body).getElements('a[rel=openInlineLayer]').each(function(n) {
                                this.setLink(n,this.options.defaultcssClass,this.options.defaultParent,this.options.defaultLayername);
                        },this)
                        $(document.body).getElements('a[rel=openVideoLayer]').each(function(n) {
                                this.setVideoLink(n,n.get('href'),this.options.defaultVideocssClass,this.options.defaultParent,this.options.defaultLayername);
                        },this)
                },

                addOverlay: function(){
                        this.overlay = new Element('div', {
                                'class': 'videoOverlay',
                                'id':          'videoOverlay',
                                styles: {
                                        zIndex:this.options.zIndex
                                }

                        });
                        this.overlay.inject(document.body,'bottom');
                        this.fx = {
                                overlay: new Fx.Tween(this.overlay, {
                                        property: 'opacity',
                                        duration: 500
                                }).set(0)
                        }
                },

                position: function(){
                        this.overlay.setStyles({
                                'top': window.getScroll().y,
                                'height': window.getSize().y
                        });
                },

                setup: function(open){
                        var elements = $$('object, iframe');
                        elements.extend($$(Browser.Engine.trident ? 'select' : 'embed'));
                        var fn = open ? 'addEvent' : 'removeEvent';
                        window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
                        document[fn]('keydown', this.eventKeyDown);
                        this.step = 0;
                },

                mkLayerVideo: function(movie,id,cssClass,parent) {
                        this.position();
                        this.setup();
                        this.overlay.addEvent('click', function(){
                                this.dstLayer(id);
                        }.bind(this));
                        this.fx.overlay.start(0.8);
                        this.options.flvars.video                = movie;

                        var lyr = new Element('div');
                        lyr.set("id",id);
                        lyr.set("class",cssClass);

                        // das ginge auch eleganter aber nicht am Tag vor dem Launch
                        this.options.closeButton =                                 this.options.closeButtonVideo;
                        this.options.closeButtonHover =                 this.options.closeButtonVideoHover;
                        this.options.closeButtonFallback =                 this.options.closeButtonVideoFallback;
                        this.options.closeButtonHoverFallback = this.options.closeButtonVideoHoverFallback;

                        closeBtn = this.closeButton(id);
                        closeBtn.inject($(lyr),'top');

                        flashembed = new Element('div');
                        flashembed.set("id",'mcdo_videoembed');
                        flashembed.inject(lyr);

                        lyr.inject(document.body,'bottom');
                        swfobject.embedSWF(this.options.appRun, 'mcdo_videoembed', this.options.videoWidth, this.options.videoHeight, "9.0.28", "", this.options.flvars, this.options.params, this.options.attributes);

                },

                mkLayerClass: function(id,cssClass,parent) {         // erzeuge einen Layer dessen layout per CSS-Klasse erzeugt wird

                        if($(id) != null ) { // wenn es das element schon gibt wird es nicht neu erzeugt, nur geleert
                                lyr = $(id);
                                lyr.empty();
                        } else {
                                var lyr = new Element('div');
                                lyr.set("id",id);
                                lyr.set("class",cssClass);
                        }

                        closeBtn = this.closeButton(id);
                        closeBtn.inject($(lyr),'top');
                        lyr.inject($(parent));
                },

                // loesche layer id
                dstLayer: function(obj) {
                        if($chk($(obj))) {
                                 $(obj).destroy();
                        }
                        this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
                        this.unfreeze(); // Flash anhalten
                },

                setLink: function(obj,cssClass, parent,updateDiv) { // alle links in parent laden per Ajax ihre Url in loadDiv
                        obj.addEvent('click', function(n){
                                hrf =  obj.get('href').split('#');        // die url wird geladen und ein div mit id=hash geladen
                                if(hrf[1] == null) {
                                        hrf[1] = this.options.defaultLoadLayer
                                }
                                this.mkLayerClass(updateDiv,cssClass,parent);        // erzeuge einen neuen Layer
                                this.loadDivByID(hrf[0],hrf[1],updateDiv);        // link, hash als ID für den zu ladenden layer , div in das geladen werden soll

                                this.freeze(); // Flash anhalten
                                return false; // soll dem klick nicht folgen
                        }.bind(this))
                },

                setVideoLink: function(obj,movie,cssClass, parent, id) { // alle links in parent laden per Ajax ihre Url in loadDiv
                        obj.addEvent('click', function(n){
                                this.mkLayerVideo(movie,id,cssClass,parent);
                                this.freeze(); // Flash anhalten
                                return false; // soll dem klick nicht folgen
                        }.bind(this))
                },

                closeButton: function(lyrName) {

                        var closeBtn = new Element('img');

                        img                         = this.ImgPath + this.options.closeButton;
                        imgHover                = this.ImgPath + this.options.closeButtonHover;
                        if($chk(this.isIE()) && this.isIE() < 5) {
                                img                 = this.ImgPath + this.options.closeButtonFallback;
                                imgHover        = this.ImgPath + this.options.closeButtonHoverFallback;
                        }

                        closeBtn.set('src',img);
                        closeBtn.set('class',"mcdo_lyrClose");

                        closeBtn.addEvent('mouseenter', function(n){
                                closeBtn.set('src',imgHover);
                        }.bind(this));

                        closeBtn.addEvent('mouseleave', function(n){
                                closeBtn.set('src',img);
                        }.bind(this));

                        closeBtn.addEvent('click', function(n){
                                this.dstLayer(lyrName);
                        }.bind(this));
                        return closeBtn;
                },

                openLink: function(url,target) {
                        if(target == null) {
                                window.location = url;
                        } else {
                                hrf =  url.split('#');
                                if(!$chk(hrf[1])) {
                                        hrf[1] = this.options.defaultLoadLayer;
                                }
                                this.freeze(); // Flash anhalten
                                this.mkLayerClass(this.options.defaultLayername,this.options.defaultcssClass,this.options.defaultParent);
                                this.loadDivByID(hrf[0],hrf[1],this.options.defaultLayername);

                        }
                },

                openVideoLink: function(movie) {
                                this.freeze(); // Flash anhalten
                                this.mkLayerVideo(movie,this.options.defaultLayername,this.options.defaultVideocssClass,this.options.defaultParent);
                },


                closeLayer: function(obj) {
                        if(!$chk(obj)) {
                                obj = $(this.options.defaultLayername);
                        }
                        // Diese Funktion wird aus dem Flash aufgerufen, statt erst den Status des Layers zu ermitteln versuchen wir ihn zu schliessen und fangen gegebenfalls den Fehler ab
                        try {
                                this.dstLayer(obj);
                        } catch(e) {
                                // pop says the weasel
                        }
                },

                // Ein Layer der verborgens ins Markup gerendert wird soll sichtbar werden
                showInlineLayer: function(obj) {
                        $(obj).addClass('mcdo_dynamicLayer');
                        hideBtn = mcd_layerControl.hideButton(obj);
                        hideBtn.inject($(obj),'top');
                        pos = (window.getScroll().y + 110) + "px";
                        $(obj).setStyles({
                                display:        'block',
                                top:                pos
                        });
                },

                // lösche den Layer nicht sondern blendet ihn aus
                hideButton: function(lyrName) {

                        var closeBtn = new Element('img');
                        if ($chk($('mcdo_lyrClose'+lyrName))) { // wenn es einen closebutton gibt wird kein zweiter eingefügt
                                return $('mcdo_lyrClose'+lyrName);
                        }

                        img                         = this.ImgPath + this.options.closeButton;
                        imgHover                = this.ImgPath + this.options.closeButtonHover;
                        if($chk(this.isIE()) && this.isIE() < 5) {
                                img                 = this.ImgPath + this.options.closeButtonFallback;
                                imgHover        = this.ImgPath + this.options.closeButtonHoverFallback;
                        }

                        closeBtn.set('src',img);
                        closeBtn.set('id',"mcdo_lyrClose"+lyrName);
                        closeBtn.set('class',"mcdo_lyrClose");

                        closeBtn.addEvent('mouseenter', function(n){
                                closeBtn.set('src',imgHover);
                        }.bind(this));

                        closeBtn.addEvent('mouseleave', function(n){
                                closeBtn.set('src',img);
                        }.bind(this));

                        closeBtn.addEvent('click', function(n){
                                $(lyrName).setStyle('display','none');
                        }.bind(this));
                        return closeBtn;
                }

        });

                mcd_layerControl = new Mcdo_layercontrol();


        /*
         * Lightbox clone for MooTools.
         * Christophe Beyls (http://www.digitalia.be); MIT-style license.
         * Inspired by the original Lightbox v2 by Lokesh Dhakar: http://www.huddletogether.com/projects/lightbox2/.
         * Refactored by Aaron Newton
         *
         * Anpassungen sind gekennzeichnet #ep
        */
        var Lightbox = new Class({
                Implements: [Options, Events,,Mcdo_utils], // #ep Implementiert die Utilties (freeze etc)
                options: {
                        menuname: 'mcd_primarynavigation',
                        top: 110,
                        resizeDuration: 1000,
                        resizeTransition: false,
                        initialWidth: 250,
                        initialHeight: 250,
                        zIndex: 15000,
                        animateCaption: false,
                        showCounter: false,
                        autoScanLinks: true,
                        relString: 'lightbox',
                        useDefaultCss: true,
                        assetBaseUrl: 'styles/',
                        overlayStyles: {}
                },

                initialize: function(options){
                        this.setOptions(options);
                        this.ImgPath = "/design_nd/"; // current url
                        this.options.assetBaseUrl = this.ImgPath + this.options.assetBaseUrl; // #ep Pfad zum Style Directory

                        this.anchors = this.options.anchors || arguments[1];
                        if (this.options.autoScanLinks && !this.anchors) {
                                this.anchors = [];
                                $$('a[rel^='+this.options.relString+']').each(function(el){
                                        if(!el.retrieve('lightbox')) this.anchors.push(el);
                                }, this);
                        }
                        if(!$$(this.anchors).length) return; //no links!
                        this.addAnchors(this.anchors);
                        this.init();
                },

                init: function(){
                        if(this.options.useDefaultCss) this.addCss();
                        this.eventKeyDown = this.keyboardListener.bind(this);
                        this.eventPosition = this.position.bind(this);
                        window.addEvent('domready', this.addHtmlElements.bind(this));
                        return this;
                },

                addAnchors: function(anchors){
                        $$(anchors).each(function(el){
                                if(!el.retrieve('lightbox')) {
                                        el.store('lightbox', this);
                                        el.addEvent('click', function(e){
                                                e.stop();
                                                this.click(el);
                                        }.bind(this));
                                }
                        }.bind(this));
                },

                addHtmlElements: function(){
                        this.overlay = new Element('div', {
                                'class': 'lbOverlay',
                                styles: {
                                        zIndex:this.options.zIndex
                                }
                        });
                        this.overlay.inject(document.body).setStyles(this.options.overlayStyles);
                        this.center = new Element('div', {
                                styles: {
                                        width: this.options.initialWidth,
                                        height: this.options.initialHeight,
                                        marginLeft: (-(this.options.initialWidth/2)),
                                        display: 'none',
                                        zIndex:this.options.zIndex+1
                                }
                        }).inject(document.body).addClass('lbCenter');
                        this.image = new Element('div', {
                                'class': 'lbImage'
                        }).inject(this.center);


                        this.prevLink = new Element('a', {
                                'class': 'lbPrevLink',
                                href: 'javascript:void(0);' ,
                                styles: {'display': 'none'}
                        }).inject(this.image);
                        this.nextLink = this.prevLink.clone().removeClass('lbPrevLink').addClass('lbNextLink').inject(this.image);
                        this.prevLink.addEvent('click', this.previous.bind(this));
                        this.nextLink.addEvent('click', this.next.bind(this));

                        this.bottomContainer = new Element('div', {
                                'class': 'lbBottomContainer',
                                styles: {
                                        display: 'none',
                                        zIndex:this.options.zIndex+1
                        }}).inject(document.body);
                        this.bottom = new Element('div', {'class': 'lbBottom'}).inject(this.bottomContainer);
                        new Element('a', {
                                'class': 'lbCloseLink',
                                href: 'javascript:void(0);'
                        }).inject(this.bottom).addEvent('click', this.close.bind(this));
                        this.overlay.addEvent('click', this.close.bind(this));
                        this.caption = new Element('div', {'class': 'lbCaption'}).inject(this.bottom);
                        this.number = new Element('div', {'class': 'lbNumber'}).inject(this.bottom);
                        // new Element('div', {'styles': {'clear': 'both'}}).inject(this.bottom); #ep
                        var nextEffect = this.nextEffect.bind(this);
                        this.fx = {
                                overlay: new Fx.Tween(this.overlay, {property: 'opacity', duration: 500}).set(0),
                                resize: new Fx.Morph(this.center, $extend({
                                        duration: this.options.resizeDuration,
                                        onComplete: nextEffect},
                                        this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
                                image: new Fx.Tween(this.image, {property: 'opacity', duration: 500, onComplete: nextEffect}),
                                immediate: new Fx.Tween(this.image, {property: 'opacity', duration: 0, onComplete: nextEffect}),        // #ep um Elemente ohne Verzögerung zu zeigen
                                bottom: new Fx.Tween(this.bottom, {property: 'margin-top', duration: 400, onComplete: nextEffect})
                        };

                        this.preloadPrev = new Element('img');
                        this.preloadNext = new Element('img');
                },

                addCss: function(){
                        window.addEvent('domready', function(){
                                if($('LightboxCss')) return;
                                new Element('link', {
                                        rel: 'stylesheet',
                                        media: 'screen',
                                        type: 'text/css',
                                        href: this.options.assetBaseUrl + 'slimbox.css',
                                        id: 'LightboxCss'
                                }).inject(document.head);
                        }.bind(this));
                },

                click: function(link){
                        link = $(link);
                        var rel = link.get('rel')||this.options.relString;
                        if (rel == this.options.relString) return this.show(link.get('href'), link.get('title'));

                        var j, imageNum, images = [];
                        this.anchors.each(function(el){
                                if (el.get('rel') == link.get('rel')){
                                        for (j = 0; j < images.length; j++) if(images[j][0] == el.get('href')) break;
                                        if (j == images.length){
                                                images.push([el.get('href'), el.get('title')]);
                                                if (el.get('href') == link.get('href')) imageNum = j;
                                        }
                                }
                        }, this);
                        return this.open(images, imageNum);
                },

                show: function(url, title){
                        return this.open([[url, title]], 0);
                },

                open: function(images, imageNum){
                        this.freeze(); // Flash anhalten
                        this.fireEvent('onDisplay');
                        this.images = images;
                        this.position();
                        this.setup(true);
                        // this.top = (window.getScroll().y + (window.getSize().y / 15)).toInt();
                        this.top = this.options.top;
                        this.center.setStyles({
                                top: this.top,
                                display: ''
                        });
                        this.fx.overlay.start(0.8);
                        return this.changeImage(imageNum);
                },

                position: function(){
                        this.overlay.setStyles({
                                'top': window.getScroll().y,
                                'height': window.getSize().y
                        });
                },

                setup: function(open){
                        var elements = $$('object, iframe');
                        elements.extend($$(Browser.Engine.trident ? 'select' : 'embed'));
                        elements.each(function(el){
//                                if (open) el.store('lbBackupStyle', el.getStyle('visibility'));
//                                var vis = (open ? 'hidden' : el.retrieve('lbBackupStyle'));
//                                el.setStyle('visibility', vis);
                        });
                        var fn = open ? 'addEvent' : 'removeEvent';
                        window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
                        document[fn]('keydown', this.eventKeyDown);
                        this.step = 0;
                },

                keyboardListener: function(event){
                        switch (event.code){
                                case 27: case 88: case 67: this.close(); break;
                                case 37: case 80: this.previous(); break;
                                case 39: case 78: this.next();
                        }
                },

                previous: function(){
                        return this.changeImage(this.activeImage-1);
                },

                next: function(){
                        return this.changeImage(this.activeImage+1);
                },

                changeImage: function(imageNum){
                        this.fireEvent('onImageShow', [imageNum, this.images[imageNum]]);

                        // if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
                        if(this.step) return false;
                        if(imageNum < 0) { imageNum = (this.images.length-1) } // #ep es wird durch die Bilder geloopt
                        if(imageNum >= this.images.length) { imageNum = 0 }

                        this.step = 1;
                        this.activeImage = imageNum;

                        this.center.setStyle('backgroundColor', '');
                        this.bottomContainer.setStyle('display', 'none');

                        // this.prevLink.setStyle('display', 'none'); #ep die Links sind immer sichtbar und benutzbar
                        // this.nextLink.setStyle('display', 'none');

                        if (this.images.length > 1) { // wenn es mehr als ein Bild gibt werden die Links gezeigt
                                this.prevLink.setStyle('display', '');
                                this.nextLink.setStyle('display', '');
                        }

                        this.fx.image.set(0);
                        this.center.addClass('lbLoading');
                        this.preload = new Element('img', {
                                events: {
                                        load: function(){
                                                this.nextEffect.delay(100, this)
                                        }.bind(this)
                                }
                        });
                        this.preload.set('src', this.images[imageNum][0]);
                        return false;
                },

                nextEffect: function(){
                        switch (this.step++){
                        case 1:
                                this.image.setStyle('backgroundImage', 'url('+this.images[this.activeImage][0]+')');
                                this.image.setStyle('width', this.preload.width);
                                this.bottom.setStyle('width',this.preload.width);
                                this.image.setStyle('height', this.preload.height);
                                this.prevLink.setStyle('height', this.preload.height);
                                this.nextLink.setStyle('height', this.preload.height);

                                this.caption.set('html',this.images[this.activeImage][1] || '');
                                this.number.set('html',(!this.options.showCounter || (this.images.length == 1)) ? '' : 'Image '+(this.activeImage+1)+' of '+this.images.length);

                                if (this.activeImage) $(this.preloadPrev).set('src', this.images[this.activeImage-1][0]);
                                if (this.activeImage != (this.images.length - 1))
                                        $(this.preloadNext).set('src',  this.images[this.activeImage+1][0]);
                                if (this.center.clientHeight != this.preload.height){ // #ep this.preload.height statt this.image.offsetHeight
                                        this.fx.resize.start({height: this.preload.height});
                                        break;
                                }
                                this.step++;
                        case 2:
                                if (this.center.clientWidth != this.image.offsetWidth){
                                        // this.fx.resize.start({width: this.image.offsetWidth, marginLeft: -this.image.offsetWidth/2});
                                        this.fx.resize.start({width: this.preload.width, marginLeft: -this.preload.width/2}); // #ep
                                        break;
                                }
                                this.step++;
                        case 3:
                                this.bottomContainer.setStyles({
                                        // top: (this.top + this.center.getSize().y),
                                        top: (this.top-40), // #ep closebutton oben statt unten
                                        height: 0,
                                        marginLeft: this.center.getStyle('margin-left'),
                                        display: ''
                                });
                                this.fx.immediate.start(1); // #ep button soll ohne Effekt sofort gezeigt werden
                                break;
                        case 4:
                                // this.center.style.backgroundColor = '#000'; #ep
                                if (this.options.animateCaption){
                                        this.fx.bottom.set(-this.bottom.offsetHeight);
                                        this.bottomContainer.setStyle('height', '');
                                        this.fx.bottom.start(0);
                                        break;
                                }
                                this.bottomContainer.style.height = '';
                        case 5:
                                if (this.activeImage) this.prevLink.setStyle('display', '');
                                if (this.activeImage != (this.images.length - 1)) this.nextLink.setStyle('display', '');
                                this.step = 0;
                        }
                },

                close: function(){
                        this.unfreeze(); // Flash anhalten
                        this.fireEvent('onHide');
                        if (this.step < 0) return;
                        this.step = -1;
                        if (this.preload) this.preload.destroy();
                        for (var f in this.fx) this.fx[f].cancel();
                        this.center.setStyle('display', 'none');
                        this.bottomContainer.setStyle('display', 'none');
                        this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
                        return;
                }
        });


                if($(document.body).get('html').match(/rel=?.lightbox/i)) {
                        new Lightbox()
                }
                mcd_gal = new Mcdo_gallery();
});
