Ext.ns('Ext.ux');
Ext.ux.Lightbox = Ext.extend(Ext.util.Observable, {
    // Needed Options
    // AjaxCallUrl, picsPerSite, numAllPics, IdFunction

	// Optional Options
    images : {
        next: "/img/arw_right_inaktiv.png",
        prev: "/img/arw_left_inaktiv.png",
        start: "/img/arw_play_inaktiv.png",
        stop: "/img/arw_stop_inaktiv.png",
        close: "/img/arw_close_inaktiv.png",
        save: "/img/save.png"
	},
    autoplayEnabled : true,
    autoplayDuration : 2500,
    preloading : true,

    currentIndex : 0,
    currentImage : new Array(),

    // elements = Ext.select string
    constructor : function(elements, config) {
        Ext.apply(this, config);
        Ext.ux.Lightbox.superclass.constructor.call(this);

        var template = new Ext.Template(
        		'<div class="shadow" >&nbsp;</div>', 
    			'<div id="lightbox">', 
    				'<div class="lightboxNavi">', 
    					'<div class="bottons">', 
        					'<span class="prev"><a id="prev" href="javascript:void(0)"><img src="{prev}" alt="previous" /></a></span>', 
        					'<span class="stop"><a id="stop" href="javascript:void(0);"><img src="{stop}" alt="stop" /></a></span>', 
        					'<span class="start"><a id="start" href="javascript:void(0);"><img src="{start}" alt="play" /></a></span>', 
        					'<span class="next"><a id="next" href="javascript:void(0)"><img src="{next}" alt="next" /></a></span>', 
    					'</div>', 
    					'<div class="legend">', 
        					'<span id="fotoIDdesc">Foto-ID:</span>', 
        					'<span id="fotoID">&nbsp;</span>',  
        					'<span id="copysymbol">&nbsp;</span>', 
        					'<span id="copyright">&nbsp;</span>', 
    					'</div>', 
					'</div>', 
					'<div class="image">&nbsp;</div>',
					'<a id="save" href="javascript:void(0);"><img src="{save}" alt="save" /></a>', 

					'<div id="description">',
 					'<span id="text">&nbsp;</span>',
                                        '<p>&nbsp;</p></div>', 
					'<span class="close"><a id="close" href="javascript:void(0);"><img src="{close}" alt="close" /></a></span>',
					'<div id="preloader">&nbsp;</div>');

        template.insertFirst(document.body, {
            prev: this.images.prev,
            stop: this.images.stop,
            start: this.images.start,
            next: this.images.next,
            save: this.images.save,
            close: this.images.close            
        });

        this.el = Ext.select(elements);
        this.init();
    },

    // Current Image Index (getter / setter)
    getCurrentIndex : function() {
        return parseInt(this.currentIndex);
    },

    setCurrentIndex : function(index) {
        this.currentIndex = index;
    },

    // Init
    init : function() {
        var overlay = Ext.select('.shadow');
        var lightbox = Ext.get('lightbox');
        var box = this;

        this.el.each(function() {
            var triggerId = box.IdFunction(this)
            this.set( {
                'href' : 'javascript:void(0);'
            });

        	// Click on Thumbnail Event
            this.on('click', function() {
                box.setCurrentIndex(triggerId);

                box.preload('next');
                var options = {
                    id : triggerId,
                    target : '#lightbox span#copyright',
                    type : 'copyright',
                    next : {
                        id : triggerId,
                        target : '#lightbox div#description p',
                        type : 'legend',
                        next : {
                          id : triggerId,
                          target : '#lightbox span#fotoID',
                          type : 'fotoID',
                      	  next : {
                              id : triggerId,
                              target : '#lightbox span#text',
                              type : 'text'
                            }
                        },
                    }
                };
                box.requestData(triggerId, '#lightbox div.image', 'image', options);
                lightbox.setStyle('display', 'block');
                
                overlay.fadeIn( {
                    endOpacity : 0.7,
                    duration : 0.2
                });
                
                if (!Ext.isIE) {
                	overlay.setStyle('display', 'block');
                }

//                if (!Ext.isIE) {
//                    overlay.fadeIn( {
//                        endOpacity : 0.7,
//                        duration : 0.2
//                    });
//                } else {
//                    overlay.setStyle('display', 'block');
//                }

                box.manageDimensions();
                box.showDownload();

            });
        });

	    // Click on Overlay Event
	    overlay.on('click', function() {
	        box.closeLightbox();
	    });
	    
	    // autoplay Options? //
	    if (this.autoplayEnabled == true) {
	        var autoplay = {
	            run : function() {
	                if (box.getCurrentIndex() + 2 <= box.numAllPics) {
	                    box.nextImage();
	                }
	            },
	            interval : box.autoplayDuration
	        };
	
	        overlay.on('click', function() {
	            Ext.TaskMgr.stop(autoplay);
	        });
	
	        Ext.fly('start').on('click', function() {
	            Ext.TaskMgr.start(autoplay);
	        });
	
	        Ext.fly('stop').on('click', function() {
	            Ext.TaskMgr.stop(autoplay);
	        });
	    }
	
	    // Click on Image Event
	    lightbox.select('.image').on('click', function() {
	        if (box.getCurrentIndex() + 2 <= box.numAllPics) {
	            box.nextImage();
	        }
	    });
	
	    // Click on Next Event
	    Ext.fly('next').on('click', function() {
	        if (box.getCurrentIndex() + 2 <= box.numAllPics) {
	            box.nextImage();
	        }
	    });
	
	    // Click on Save Event
	    Ext.fly('save').on('click', function() {
	        box.saveFullImage();
	    });
	    
	    // Click on Close Event
	    Ext.fly('close').on('click', function() {
	    	box.closeLightbox();
	    });
	
	    // Click on Previous Event
	    Ext.fly('prev').on('click', function() {
	        if (box.getCurrentIndex() > 0) {
	            box.prevImage();
	        }
	    });
    },

    // Send either a ajax-request to server or fetches allready
    // requested data out of an Array
    requestData : function(id, target, type, callback) {
        this.currentIndex = id;
        var me = this;

        if (this.currentImage[id] == undefined) {
            Ext.Ajax.request( {
                url : this.AjaxCallUrl,
                params : {
                    getImage : id
                },
                method : 'GET',
                success : function(result, request) {
                    me.currentImage[id] = Ext.util.JSON.decode(result.responseText);
                    Ext.select(target).item(0).dom.innerHTML = me.currentImage[id][type];
                },
                callback : function() {
                    if (callback != undefined) {
                        me.requestData(callback.id, callback.target, callback.type, callback.next);
                    }
                },
                disableCaching : false
            });
        } else {
            Ext.select(target).item(0).dom.innerHTML = this.currentImage[id][type];

            if (callback != undefined) {
                me.requestData(callback.id, callback.target, callback.type, callback.next);
            }
        }

    },

    // Center the Lightbox
    manageDimensions : function() {
	    setTimeout(function() {
	        var lightbox = Ext.fly('lightbox');
	
	        if (!Ext.isIE) {
	            lightbox.setStyle('margin-top', Math.round(lightbox.getHeight() / 2) * -1);
	        }
	
	        var calcedWidth = Math.round(Ext.getBody().getWidth() / 2) - (lightbox.getWidth() / 2);
	        lightbox.setStyle('left', calcedWidth + 'px');
	
	        var img = Ext.select('#lightbox > div.image > img');
	        lightbox.setStyle('width', img.getWidth() + 2);
	        lightbox.setStyle('height', img.getHeight() + 2);
	    }, 50);
    },

    // Preloads the next Image
    preload : function(direction) {
        if (this.preloading == true) {
            var i = (direction === 'prev') ? -1 : 1;
            var preloadId = this.getCurrentIndex() + i;
            
            if (preloadId >= 0 && preloadId < this.numAllPics) {
                this.requestData(preloadId, '#preloader', 'image');
                this.setCurrentIndex(preloadId - i);
            }
        }
    },

    // Close the Lightbox and the black overlay
    closeLightbox : function() {
        if (!Ext.isIE) {
            Ext.select('.shadow').fadeOut( {
                duration : 0.2
            });
        } else {
            Ext.select('.shadow').setStyle('display', 'none');
        }

        Ext.get('lightbox').setStyle('display', 'none');
    },

    // load the next Image
    nextImage : function() {
    	var nextId = this.getCurrentIndex() + 1
        var callback = {
            id : nextId,
            target : '#lightbox div#description p',
            type : 'legend',
            next : {
                id : nextId,
                target : '#lightbox span#fotoID',
                type : 'fotoID',
                next : {
                  id : nextId,
                  target : '#lightbox span#copyright',
                  type : 'copyright',
            	  next : {
                      id : nextId,
                      target : '#lightbox span#text',
                      type : 'text'
                    }
                }
            }  
        };
        this.requestData(nextId, '#lightbox div.image', 'image', callback);
        this.showDownload();
        this.preload('next');
        this.manageDimensions();
    },

    // load the previous Image
    prevImage : function() {
        var prevId = this.getCurrentIndex() - 1;
        var callback = {
            id : prevId,
            target : '#lightbox div#description p',
            type : 'legend',
            next : {
                id : prevId,
                target : '#lightbox span#copyright',
                type : 'copyright',
                next : {
                  id : prevId,
                  target : '#lightbox span#fotoID',
                  type : 'fotoID',
            	  next : {
                      id : prevId,
                      target : '#lightbox span#text',
                      type : 'text'
                    }
                }                
            }
        };
        this.requestData(prevId, '#lightbox div.image', 'image', callback);
        this.showDownload();
        this.preload('prev');
    },

    // Show Download icon?
    showDownload : function() {
        var me = this;
        setTimeout(function() {
            if (me.currentImage[me.getCurrentIndex()].download == true) {
                Ext.fly('save').setStyle('visibility', 'visible');
            } else {
                Ext.fly('save').setStyle('visibility', 'hidden');
            }
        }, 75);
    },

    // Open the fullresolution Image in a new window
    saveFullImage : function() {
        if (this.currentImage[this.getCurrentIndex()] != undefined) {
            if (this.currentImage[this.getCurrentIndex()].download == true) {
                window.open('?download=' + this.currentImage[this.getCurrentIndex()].downloadUrl, 'Download', '');
            }
        }
    }
});
