﻿
/*

Diese Klasse verhält sich ähnlich wie die bekannte Lightbox.
Für Beispielcode scrolle ganz nach unten.

*/

var mooImageBox = new Class({
    Implements: Options,
    options: {
        cssprefix: 'box',       // css prefix für verschiedene css klassen (bsp: .box_headline)
        rel: 'imagebox',        // es werden alle bilder angezeigt die rel=imagebox definiert haben. name kann hier angepasst werden.
        imageresizeurl: null,   // url zu unserem image-resize-service. wenn angegeben wird bild damit zugeschnitten und die optimale grösse für den bildschirm gesucht.
        cutHorizontal: 100,     // beim zuschneiden des bildes wird der angegebene wert abgezogen in der horizontalen
        cutVertical: 100,       // beim zuschneiden des bildes wird der angegebene wert abgezogen in der vertikalen
        imageloadingurl: 'grafik/mooImageBox/loading.gif'     // pfad des ladebalken bildes       

    },

    /* constructor */
    initialize: function(options) {

        this.setOptions(options);

        this.isOverlayLoaded = false;
        this.imgIndex = 0;

        // hole alle links
        this.linkArr = $(document.body).getElements('a[rel="' + this.options.rel + ']');

        // speichere objekt im body
        $(document.body).store("imagebox", this);

        // füge dieses objekt zu jedem link  
        for (var i = 0; i < this.linkArr.length; i++)
            this.linkArr[i].store('imagebox', this);

        // wenn auf link geklickt wird dann öffne nicht bildurl sondern lade das bild entsprechend
        this.linkArr.removeEvents("click").addEvent("click", this.handleClick.bind(this));

    },

    /* setze alles auf schwarzen hintergrund */
    loadOverlay: function() {

        // helle box in der mitte
        this.whitebox = document.createElement("div");
        this.whitebox.id = "light";
        this.whitebox.className = "white_content";

        // dunkler overlay-effekt
        var el2 = document.createElement("div");
        el2.id = "fade";
        el2.className = "black_overlay";

        // mootools
        this.whitebox = $(this.whitebox);
        el2 = $(el2);

        // füge beide elemente am beginn des DOM ein
        document.body.insertBefore(el2, document.body.firstChild);
        document.body.insertBefore(this.whitebox, document.body.firstChild);

        // setze beides sichtbar (todo: mit effekt)
        document.getElementById('light').style.display = 'block';
        document.getElementById('fade').style.display = 'block';

        
        // berücksichtige aktuelle scrollposition des fensters
        this.whitebox.style.marginTop = window.getScroll().y + "px";
        el2.style.top = window.getScroll().y + "px";

        // wird auf dunkle Fläche geklickt, dann schliesse imagebox
        el2.addEvent("click", function(event) {
            $(document.body).retrieve("imagebox").close();
        });

        // unterbinde scrolling wenn imagebox geladen wurde
        this.whitebox.addEvent('mousewheel', function() { return false; });
        el2.addEvent('mousewheel', function() { return false; });

        // overlay ist geladen
        this.isOverlayLoaded = true;

        // lade die einzelnen navigations-elemente, etc.
        this.loadElements(this.whitebox);


        // höre auf tastatureingaben
        $(document.body).addEvent("keydown", function(event) {
            var imagebox = $(document.body).retrieve("imagebox");
            switch (event.code) {
                case 27: // Esc
                case 88: // 'x'
                case 67: // 'c'
                    imagebox.close();
                    break;
                case 37: // Left arrow
                case 80: // 'p'
                    imagebox.prevImage();
                    break;
                case 39: // Right arrow
                case 78: // 'n'
                    imagebox.nextImage();
            }
            // Prevent default keyboard action (like navigating inside the page)
            return false;

        });

    },

    /* der Überblendeffekt wird entfernt */
    hideOverlay: function() {
        var el1 = document.getElementById("light");

        if (el1 != null)
            document.body.removeChild(el1);

        var el2 = document.getElementById("fade");

        if (el2 != null)
            document.body.removeChild(el2);

        this.isOverlayLoaded = false;

        $(document.body).removeEvents("keydown");
    },

    /* ladet alle Navigationselemente und container. Darstellung kann über CSS definiert werden */
    loadElements: function(parentdiv) {


        this.el_container = new Element("div", { id: "boxcontainer", 'class': this.options.cssprefix + "_container" });
        this.el_head = new Element("div", { id: "boxheadline", 'class': this.options.cssprefix + "_headline" });
        this.el_nav = new Element("div", { id: "boxnav", 'class': this.options.cssprefix + "_nav" });
        this.el_prev = new Element("div", { id: "btleft", 'class': this.options.cssprefix + "_btprev" });
        this.el_next = new Element("div", { id: "btright", 'class': this.options.cssprefix + "_btnext" });
        this.el_close = new Element("div", { id: "btclose", 'class': this.options.cssprefix + "_btclose" });
        this.el_title = new Element("div", { id: "boxtitle", 'class': this.options.cssprefix + "_title" });
        this.el_comment = new Element("div", { id: "boxcomment", 'class': this.options.cssprefix + "_comment" });
        this.el_img = new Element("img", { id: "boximg", 'class': this.options.cssprefix + "_img" });
        this.el_loading = new Element("img", { id: "boxload", 'class': this.options.cssprefix + "_loading", 'src': this.options.imageloadingurl });

        this.el_next.store('imagebox', this);
        this.el_prev.store('imagebox', this);
        this.el_close.store('imagebox', this);

        this.el_next.addEvent('click', function(ev) {
            ev.target.retrieve('imagebox').nextImage();
        });

        this.el_prev.addEvent('click', function(ev) {
            ev.target.retrieve('imagebox').prevImage();
        });

        this.el_close.addEvent('click', function(ev) {
            ev.target.retrieve('imagebox').close();
        });

        if (this.linkArr.length < 2) {
            this.el_prev.style.visibility = 'hidden';
            this.el_next.style.visibility = 'hidden';
        }

        // bei IE6.0 muss die höhe des schwarzen hintergrundes per javascript gesetzt werden
        if (Browser.Engine.trident && Browser.Engine.version < 5) {
            $('fade').style.height = window.getSize().y;
        }
        
        if(Browser.Engine.trident){
        	this.el_head.style.height = "20px";
        }


        parentdiv.grab(this.el_container);

        this.el_container.grab(this.el_head);
        this.el_head.grab(this.el_nav);
        this.el_nav.grab(this.el_title);
        this.el_nav.grab(this.el_prev, "top");
        this.el_nav.grab(this.el_next, "bottom");
        this.el_head.grab(this.el_close);
        this.el_container.grab(this.el_img);
        this.el_container.grab(this.el_comment);
        this.el_container.grab(this.el_loading);

        // special for IE 7
        if (Browser.Engine.trident == true && navigator.appVersion.indexOf('MSIE 7.0')) {
            this.el_img.setStyle("margin-top", '10px');
        }
    },

    /* zeigt das Bild mit der angegeben Url an */
    showImageByUrl: function(url) {

        // lade überblendeffekt falls noch nicht geladen
        if (this.isOverlayLoaded == false)
            this.loadOverlay();

        // für jeden link
        for (var i = 0; i < this.linkArr.length; i++) {
            if (this.linkArr[i].href == url) {
                this.showImage(i);
                return;
            }
        }

    },

    /* was tun wenn auf link oder kleines bild geklickt wurde. Zeige imagebox */
    handleClick: function(ev) {

        var e = new Event(ev);
        this.showImageByUrl(e.target.parentNode.getProperty('href'));
        return false;
    },

    /* zeigt einen ladebalken */
    nextEffect: function() {
    		this.el_comment.style.display = 'none';
    		this.el_loading.setStyle('left', (this.el_container.getSize().x/2));
    		this.el_loading.setStyle('top', (this.el_container.getSize().y/2));
        this.el_loading.style.display = 'none';
    },

    /* stoppt und macht den ladebalken unsichtbar */
    stopEffect: function() {
        this.el_img.style.display = 'block';
        this.el_loading.style.display = 'none';
        this.el_comment.style.display = 'block';
        this.fitWhiteBoxToImage();
        
    },

    /* zeigt das bild dass sich in dem index befindet */
    showImage: function(index) {
				
        // lade überblendeffekt falls noch nicht geladen
        if (this.isOverlayLoaded == false)
            this.loadOverlay();

			  // ladebalken start
        this.nextEffect();
        // ladebalken ende
        this.el_img.onload = this.stopEffect.bind(this);
        
        // bild ausblenden
        this.el_img.style.display = 'none';

			  // bild zuschneiden
        if (this.options.imageresizeurl != null) {
            var maxy = $(document.body).getSize().y - this.whitebox.getPosition().y - this.whitebox.getStyle('padding-top').toInt() - this.whitebox.getStyle('padding-bottom').toInt() - this.options.cutVertical;
            var maxx = $(document.body).getSize().x - this.whitebox.getStyle('padding-left').toInt() - this.whitebox.getStyle('padding-right').toInt() - this.options.cutHorizontal;

            if (maxy < 0)
                maxy = 0;

            this.el_img.src = this.options.imageresizeurl + "?w=" + maxx + "&h=" + maxy + "&url=" + this.linkArr[index].href;
        } else {
            this.el_img.src = this.linkArr[index].href;
        }

				// titel des bildes
        this.el_title.innerHTML = this.linkArr[index].getFirst().getProperty('alt');

        if (this.el_title.innerHTML == "null")
            this.el_title.innerHTML = "";

				
				// kommentar zum bild
        if (this.linkArr[index].getProperty('alt') != null) {
            this.el_comment.innerHTML = this.linkArr[index].getProperty('alt');
            this.el_comment.style.display = 'block';
            this.el_comment.className = this.el_comment.className;

        } else {
            this.el_comment.innerHTML = "";
            this.el_comment.style.display = 'none';
        }
        
        // setze index
        this.imgIndex = index;


    },

    nextImage: function(url) {

        this.imgIndex++;

        if (this.imgIndex >= this.linkArr.length)
            this.imgIndex = 0;

        this.showImage(this.imgIndex);
    },

    prevImage: function(url) {
        this.imgIndex--;

        if (this.imgIndex < 0)
            this.imgIndex = this.linkArr.length - 1;

        this.showImage(this.imgIndex);
    },

    close: function() {
        this.hideOverlay();
        
        if(this.lo != null)
        {
	        this.lo.destroy();
	        this.ro.destroy();
	        this.lu.destroy();
	        this.ru.destroy();
      	}
      	
      	this.lo = null;
      	this.ro = null;
      	this.lu = null;
      	this.ru = null;
    },

    fitWhiteBoxToImage: function() {
        var winw = $(document.body).getSize().x;

        // es muss weisse box an bild angepasst werden
        this.whitebox.style.width = ((this.el_img.getSize().x)) + "px";
        this.whitebox.style.height = ((this.whitebox.getSize().y-this.whitebox.getStyle("padding-top").toInt()-this.whitebox.getStyle("padding-bottom").toInt())) + "px";

        this.whitebox.style.left = ((winw - this.whitebox.getSize().x) / 2).toInt() + "px";

        if (navigator.userAgent.indexOf("MSIE 8.0") != -1)
            this.roundEdges();
    },

    roundEdges: function() {


        if (this.lo == null) {
            this.lo = new Element('img', { 'src': 'grafik/mooImageBox/Links_oben.png', 'style': 'position:absolute;top:0px;left:0px;z-index:9999' });
            document.body.appendChild(this.lo);
        }
        if (this.ro == null) {
            this.ro = new Element('img', { 'src': 'grafik/mooImageBox/rechts_oben.png', 'style': 'position:absolute;top:0px;left:0px;z-index:9999' });
            document.body.appendChild(this.ro);
        }
        if (this.lu == null) {
            this.lu = new Element('img', { 'src': 'grafik/mooImageBox/links_unten.png', 'style': 'position:absolute;top:0px;left:0px;z-index:9999' });
            document.body.appendChild(this.lu);
        }
        if (this.ru == null) {
            this.ru = new Element('img', { 'src': 'grafik/mooImageBox/rechts_unten.png', 'style': 'position:absolute;top:0px;left:0px;z-index:9999' });
            document.body.appendChild(this.ru);
        }


        this.lo.setStyle("left", this.whitebox.getPosition().x);
        this.lo.setStyle("top", this.whitebox.getPosition().y);


        this.ro.setStyle("left", this.whitebox.getPosition().x + this.whitebox.getSize().x - this.ro.getSize().x);
        this.ro.setStyle("top", (this.whitebox.getPosition().y));


        this.lu.setStyle("left", this.whitebox.getPosition().x);
        this.lu.setStyle("top", this.whitebox.getPosition().y + this.whitebox.getSize().y - this.ro.getSize().y);


        this.ru.setStyle("left", this.whitebox.getPosition().x + this.whitebox.getSize().x - this.ru.getSize().x);
        this.ru.setStyle("top", this.whitebox.getPosition().y + this.whitebox.getSize().y - this.ru.getSize().y);

        //        this.whiteback = new Element('div', { 'style': 'position:absolute;top:0px;left:0px;z-index:1002;background-color:white' });
        //        this.whiteback.setStyle("width", this.whitebox.getSize().x + 12);
        //        this.whiteback.setStyle("height", this.whitebox.getSize().y + 12);
        //        this.whiteback.setStyle("left", this.whitebox.getPosition().x - 4);
        //        this.whiteback.setStyle("top", this.whitebox.getPosition().y - 4);
        //        document.body.appendChild(this.whiteback);

    }

});


/*

HTML:

<a rel="imagebox" href="PathToMyBigImageWithDog" alt="This is a dog.">Click here for Image of Dog.</a>
<a rel="imagebox" href="PathToMyBigImageWithCat" alt="This is a cat.">Click here for Image of Cat.</a>
<a rel="imagebox" href="PathToMyBigImageWithHorse" alt="This is a horse.">Click here for Image of Horse.</a>

JAVASCRIPT:

<script type="text/javascript">
   window.addEvent('domready', function() {
        new mooImageBox();
    });
</script>

*/
