Ext.ns('Swix');

Swix.FotoGallery = Ext.extend(Object, {
   
    overlayColor: '#000000',
    overlayDuration: 0.3,
    overlayOpacity: 0.6,
    
    imageBgColor: '#000000',
    imageBgOpacity: 0.65,
    imageBgBorder: 10,
    
    imageFadeInDuration: 0.3,
    
    dynamicSizing: false,
        
    loaderImage: 'loader-bright.gif',
    closeBtnImage: 'close.png',
      
    el: null,
    fotos: [],
    currentIndex: 0,
    
    labelImage: 'Foto',
    labelOf: 'von',
    labelColor: '#FFFFFF',
    
	constructor: function(config) {
		Ext.apply(this, config);
		
        this.fotos = this.el.select('a');
        this.fotos.on('click', this.onFotoClick, this);        
	},
    onFotoClick: function(e, t, o) {
        e.stopEvent();
        
        var targetEl = new Ext.get(e.getTarget('a')); 
        this.currentIndex = this.fotos.indexOf(targetEl);

        this.open();
    },
    setOverlay: function() {
		var viewSize = this.getViewSize();
        
        this.overlay.setStyle({
			width: Ext.getBody().getWidth() + 'px',
			height: viewSize[1] + 'px'
		});
    },
    fadeInOverlay: function() {
        this.overlay.fadeIn({
            duration: this.overlayDuration,
            endOpacity: this.overlayOpacity,
            scope: this,
            callback: function() {
                this.posImageBg();
                this.posLoader();
                this.imageBg.setOpacity(this.imageBgOpacity);
                this.imageBg.show();
                this.loader.show();
                this.setImage(this.currentIndex);
                this.enableKeyNav();
            }
        });
    },
    setImage: function(index) {
        this.image.hide();
        this.closeBtn.hide();
        this.label.hide();
        this.posLoader();
        this.loader.show();
        this.prevContainer.setOpacity(0);
        this.nextContainer.setOpacity(0);
        
        var src = this.fotos.item(index).getAttribute('href');
       
        if (this.dynamicSizing) {                   
            src = src.match(/getimage\/(.*?)\/(.*)/);
            if (src.length >= 2) {
                var size = Ext.lib.Dom.getViewHeight(false) * 0.9;
                size = Math.floor(size / 100) * 100;          
                this.image.dom.src = '/getimage/w' + size + '_h' + size + '/' + src[2];
            }
        } else {
            this.image.dom.src = src;
        }        
        this.currentIndex = index;
    },
    setImageCount: function() {       
        if (this.fotos.getCount() > 1) {
            var label = this.labelImage + ' ' + (this.currentIndex + 1) + ' ' + this.labelOf + ' ' + this.fotos.getCount();
            this.imageCount.update(label);
        }
    },
    setLabel: function() {
        var label = this.fotos.item(this.currentIndex).getAttribute('title');
        
        label = label.split(' - ');
        
        $html = "";
        if (label[0]) {
            $html = $html + '<div class="title">' + label[0] + '</div>';
        }
        if (label[1]) {
            $html = $html + '<div class="description">' + label[1] + '</div>';
        }            
        this.description.update($html);
       
        this.setImageCount();
        this.posLabel();
    },
    open: function() {
        Ext.EventManager.on(window, 'resize', this.setOverlay, this);
        Ext.EventManager.on(window, 'scroll', this.onWindowScroll, this);
                
        this.render();
        this.setOverlay();
        this.fadeInOverlay();
    },
	enableKeyNav: function() {
		Ext.fly(document).on('keydown', this.keyNavAction, this);
	},

	disableKeyNav: function() {
		Ext.fly(document).un('keydown', this.keyNavAction, this);
	},
	keyNavAction: function(ev) {
		var keyCode = ev.getKey();

		if (
			keyCode == 88 || // x
			keyCode == 67 || // c
			keyCode == 27
		) {
			this.close();
		}
		else if (keyCode == 80 || keyCode == 37){ // display previous image
			this.navPrev();
		}
		else if (keyCode == 78 || keyCode == 39){ // display next image
            this.navNext();        
		}
	},
    navPrev: function() {
		if (this.currentIndex != 0){
			this.setImage(this.currentIndex - 1);
		}
    },
    navNext: function() {
    	if (this.currentIndex != (this.fotos.getCount() - 1)){
    		this.setImage(this.currentIndex + 1);
    	}
    },
    render: function() {
        var tpl = new Ext.Template(
            '<div id="fotogallery">',
                '<div id="overlay">',
                '</div>',
                '<div id="imagebg">',
                '</div>',
                '<img id="loader" src="/frontend/template/fotogallery/images/' + this.loaderImage + '" />',
                '<img id="image" src="" />',
                '<div id="label">',
                    '<div id="imagetext"></div>',
                    '<div id="imagecount"></div>',
                '</div>',
                '<div id="prevcontainer">',
                '</div>',
                '<div id="nextcontainer">',
                '</div>',
                '<img id="closebtn" src="/frontend/template/fotogallery/images/' + this.closeBtnImage + '" />',
            '</div>'
        );
        
        this.el = tpl.append(Ext.getBody(), [], true);
        this.overlay = this.el.down('#overlay');
        this.imageBg = this.el.down('#imagebg');
        this.loader  = this.el.down('#loader');
        this.loader.hide();
        
        this.image = this.el.down('#image');
        this.image.hide();
        Ext.get(this.image).on('load', function() {
            this.setLabel();
            this.setImageBgSize(this.image.getWidth(), this.image.getHeight());
        }, this);
        
        this.closeBtn = this.el.down('#closebtn');
        this.closeBtn.hide();
        this.closeBtn.on('click', this.close, this);

        this.label = this.el.down('#label');
        this.label.hide();
        
        this.imageCount  = this.el.down('#imagecount');
        this.description = this.el.down('#imagetext');          
        
        this.overlay.setOpacity(0);
        this.overlay.setStyle({
			'background-color': this.overlayColor
		});
        
        this.imageBg.hide();
        this.imageBg.setStyle({
			'background-color': this.imageBgColor
		});
        
        this.prevContainer = this.el.down('#prevcontainer');
        this.prevContainer.setOpacity(0);
        this.prevContainer.on('click', this.navPrev, this);
        
        this.nextContainer = this.el.down('#nextcontainer');
        this.nextContainer.setOpacity(0);
        this.nextContainer.on('click', this.navNext, this);
                
        this.overlay.on('click', this.close, this);
    },
	getViewSize: function() {
		return [Ext.lib.Dom.getViewWidth(false), Ext.lib.Dom.getViewHeight(true)];
	},
    close: function() {
        this.disableKeyNav();
        this.el.remove();
    },
    posImageBg: function() {
        this.imageBg.setStyle({
            left: Math.floor((Ext.getBody().getWidth() - this.imageBg.getWidth()) / 2) + 'px',
            top: (Ext.getBody().getScroll().top + (Ext.lib.Dom.getViewHeight(false) -  this.imageBg.getHeight()) / 2) + 'px'
		});
    },
    posLoader: function() {
        this.loader.setStyle({
            left: this.imageBg.getX() + Math.floor((this.imageBg.getWidth() - this.loader.getWidth()) / 2) + 'px',
            top: this.imageBg.getY() + Math.floor((this.imageBg.getHeight() - this.loader.getHeight()) / 2) + 'px'
        });
    },
    posCloseBtn: function() {
        this.closeBtn.setStyle({
            left: this.imageBg.getX() + this.imageBg.getWidth() - this.closeBtn.getWidth() + this.imageBgBorder / 2 + 'px',
            top: this.imageBg.getY() - this.imageBgBorder / 2 + 'px'
        });
    },
    onWindowScroll: function() {
        this.posImageBg();
        this.posLoader();
        this.posCloseBtn();
        this.posLabel();
        this.setButtons();

        this.loader.setStyle({
            top: this.imageBg.getY() + Math.floor((this.imageBg.getHeight() - this.loader.getHeight()) / 2) + 'px'
        });       
        
        this.posImage();
    },
    setImageBgSize: function(width, height) {
        
        var left = Math.floor((Ext.getBody().getWidth() - width - this.imageBgBorder * 2) / 2);
        var top  = Ext.getBody().getScroll().top + (Ext.lib.Dom.getViewHeight(false) - height - this.imageBgBorder * 2) / 2;
        width = width + 2 * this.imageBgBorder;
        height = height + 2 * this.imageBgBorder + this.label.getHeight();
        
        this.imageBg.animate({
            left: {to: left},
            top: {to: top},
            width: {to: width},
            height: {to: height}
        }, null, this.onImageLoaded.createDelegate(this));
    },
    onImageLoaded: function() {
        this.loader.hide();
        this.posImage();
        this.setButtons();
        this.posLabel();
        this.image.fadeIn({
            duration: this.imageFadeInDuration
        });
        this.label.show();
        this.posCloseBtn();
        this.closeBtn.show();
    },
    posImage: function() {
        this.image.setX(this.imageBg.getX() + this.imageBgBorder);
        this.image.setY(this.imageBg.getY() + this.imageBgBorder);
    },
    posLabel: function() {
        this.label.setStyle({
            left: this.image.getX() + 'px',
            top: this.image.getY() + this.image.getHeight() + 'px',
            width: this.image.getWidth() + 'px',
            'padding-top': Math.ceil(this.imageBgBorder / 2) + 'px'
		});
        
        this.description.setStyle({
            width: this.image.getWidth() - this.imageCount.getWidth() - 10 + 'px'       
        })
    },
    setButtons: function() {
        
        this.prevContainer.setStyle({
            left: this.imageBg.getX() - 45 + 'px',
            top: this.imageBg.getY() + 'px',
            width: Math.floor(this.imageBg.getWidth() / 2) + 45 + 'px',
            height: this.imageBg.getHeight() + 'px'
        });
        
        this.nextContainer.setStyle({
            left: this.imageBg.getX() + Math.floor(this.imageBg.getWidth() / 2) + 'px',
            top: this.imageBg.getY() + 'px',
            width: Math.floor(this.imageBg.getWidth() / 2) + 45 + 'px',
            height: this.imageBg.getHeight() + 'px'
        });
        
		if (this.currentIndex != 0){
            this.prevContainer.setOpacity(0.3);
		} else {
            this.prevContainer.setOpacity(0);
		}
        
    	if (this.currentIndex != (this.fotos.getCount() - 1)){
            this.nextContainer.setOpacity(0.3);
		} else {
            this.nextContainer.setOpacity(0);
		}
    }
});

Swix.FotoGalleryManager = Ext.extend(Object, {

    fotoGalleries: [],

	constructor: function(config) {
		Ext.apply(this, config);
        
        Ext.select('.fotogallery').each(function(item){
            var fotoGallery = new Swix.FotoGallery({
                el: Ext.get(item.dom)
            });
              
            this.fotoGalleries[this.fotoGalleries.length] = fotoGallery; 
        }, this);
	}
})

Ext.onReady(function(){
    Swix.FotoGalleryManager = new Swix.FotoGalleryManager();
}, this);
