/*
 *
 */

var albumViewerOptions = Object.extend({
    fileLoadingImage:           'images/loading.gif',
    fileBottomNavCloseImage:    'images/closelabel.gif',
    'url':  $H({
        albumviewer: 'albumviewer.ajax.php',
        domain: 'marienstift.local',
        rootFolder: '/'
    }),
    thumbExt: '.thumb',
    debug: false,

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 10         //if you adjust the padding in the CSS, you will need to update this variable

}, window.albumViewerOptions || {});

var albumviewer = new Class({

    initialize: function(handle,options) {
        this.debug = albumViewerOptions.debug;
        options = options || $H({});
        this.options = new Hash();
        this.parseOptions(options);
        if(!this.options.get('startFolder'))return;
        
        this.loading = true;
        if(!this.checkHandle(handle)) return;
        this.handle = $(handle);

        if(!albumViewerOptions.url) return;
        this.url = albumViewerOptions.url;

        this.handle.setStyle('position','relative');
        this.createLoadDisplay();
        this.startFolder = this.options.get('startFolder');
        this.getElements(this.options.get('startFolder'));
        
    },
    parseOptions: function(options){
        $H(options).each(function(value, key){
            this.options.set(key,value);
        },this);
    },
    checkHandle: function(handle){
        if(!$(handle)) return(false);
        if($(handle).tagName != "DIV") return(false);
        return(true);
    },
    getElements: function(dir){
        //this.loadTimer = this.loaded();
        this.currentFolder = dir;
        this.loadTimer = function(){
            this.loaded();
        };
        //this.loadTimer.periodical(1000,this);
        new Request({
            url: this.url.get('albumviewer'),
            method: 'get',
            onSuccess: function(transport){
                //if(this.debug) alert(transport);
                this.processResponse(JSON.decode(transport));
            }.bind(this)
        }).send('dir='+dir);
    },
    processResponse: function(response){
        if(this.debug)
            alert($H(response).toQueryString());
        if($H(response).get('entries')){
            this.albumEntries = $A($H(response).get('entries'));
        }
        if(this.albumEntries){
            this.createAlbum();
            //alert("currentFolder: "+this.currentFolder);
            if(this.currentFolder != this.startFolder){
                this.createBackElement();
            }
        }else this.loading = false;
    },
    clearAlbum: function(){
        if(this.albumBack) this.albumBack.dispose();
        if(this.albumContainer) this.albumContainer.dispose();
        if(this.entryContainer) this.entryContainer.dispose();
    },
    createAlbum: function(){
        this.clearAlbum();
        this.entryContainer = new Element('div',{'id':'entries'});
        this.handle.grab(this.entryContainer);
        this.albumContainer = new Element('ul',{'id':'albums'});
        this.handle.grab(this.albumContainer);
        
        if(!this.albumEntries) return;
        /**
         * Contains Images in a Album
         */
        this.images = {};

        /**
         * Create
         */
        this.albumEntries.each(function(entry, index){
            this.createElement($H(entry));
        },this);
        this.resizeNoImage();
        this.slideShow = new Slideshow(
            this.entryContainer,
            this.images,
            {
                controller: true,
                height: 300,
                hu: this.getImagePath(),
                replace: [/(\.[^\.]+)$/, albumViewerOptions.thumbExt+'$1'],
                thumbnails: true,
                width: 400
            }
        );

        this.thumbnailSlide = $$('#entries .slideshow-thumbnails')[0];
        this.thumbnailOverlayLeft = new Element('div',{
            'class':'thumbnailOverlayLeft'
        }).inject(this.handle);
        this.thumbnailOverlayRight = new Element('div',{
            'class':'thumbnailOverlayRight'
        }).inject(this.handle);
        this.thumbnailOverlayLeft.style.top = this.thumbnailSlide.offsetTop;
        this.thumbnailOverlayRight.style.top = this.thumbnailSlide.offsetTop;
    },
    createElement: function(el){
        if(!el.get('src')) return;
        switch(el.get('type')){
            case 'dir':
                //alert(el.get('title'));
                this.createFolderElement(el);

            break;

            case 'image':
                this.createImageElement(el);
            break;
        }


        
    },
    createImageElement: function(el){
        if(!this.images) return;
        this.images[el.get('src')] = {
            caption: el.get('title')
        };
    },
    getImagePath: function(){
        var path = 'http://' + this.url.get('domain') + this.url.get('rootFolder') + "/" + this.url.get('albumviewer') + "?image=";
        return(path);
    },
    createFolderElement: function(el){
        var elContainer = new Element('li');
        this.albumContainer.grab(elContainer);
        elContainer.addClass(el.get('type'));
        elContainer.addClass('albumEntry');
        //alert(el.get('thumb'));
        if(el.get('thumb')){
            var thumb = new Element('img',{
                'src':this.url.get('albumviewer') + "?image="+el.get('thumb')
            }).addEvent('load',function(){
                //thumb.setStyle
            }.bind(this));
            elContainer.grab(thumb);
            elContainer.addClass('albumThumb');
        }else{
            if(!this.noImage){
                this.noImage = new Element('img',{
                    'src':this.options.get('noImage') || 'styles/images/noimage.png',
                    'class': 'albumNoImage'
                });
                elContainer.grab(this.noImage);
            }else
                elContainer.grab(this.noImage.clone());
        }
        if(el.get('title')){
            //elContainer.store('tip:title',el.get('title'));
            elContainer.setProperty('title',el.get('title'));
        }
        //if(el.get('description'))  elContainer.store('tip:text',el.get('description'));

        /*
        this.albumTooltips = new Tips('.albumThumb',{
            className: 'tooltips',
            fixed: true,
            hideDelay: 50,
            showDelay: 50
        });
        */

        elContainer.addEvent('click',function(){
            this.getElements(el.get('src'));
        }.bind(this));

    },
    resizeNoImage: function(){
        if(!this.noImage) return;
        this.noImage.addEvent('load',function(){
            this.albumContainer.getElements('.albumNoImage').each(function(el){
                el.setStyle('height',this.getNoImageSize('height')+"px");
                el.setStyle('width',this.getNoImageSize('width')+"px");
            }.bind(this));
        }.bind(this));

    },
    createBackElement: function(){
        this.albumBack = new Element('div',{
            'id':'albumBack'
        });
        this.handle.grab(this.albumBack);
        this.albumBack.addEvent('click',function(){
            this.getElements(this.getUpFolder());
        }.bind(this));
    },
    getUpFolder: function(){
        var folders = this.currentFolder.split("/");
        var newFolder = "/";
        var folderCounter = 1;
        folders.each(function(folder){
            folderCounter++;
            if(folders.length > folderCounter){
                if(folder.length){
                    if(newFolder == "/")  newFolder = newFolder + folder;
                    else newFolder = newFolder + "/" + folder;
                }
            }
        }.bind(this));
        return(newFolder);
    },
    getNoImageSize: function(ax){
        if(!this.noImage) return;
        var maxHeight = this.options.get('elementHeight') || '160';
        var maxWidth = this.options.get('elementWidth') || '160';
        var height = this.noImage.height;
        var width = this.noImage.width;
        var newHeight = height;
        var newWidth = width;

        if(height > maxHeight){
            var factor = height / maxHeight;
            if(factor > 1){
                newWidth = width / factor;
                newHeight = maxHeight;
            }
        }

        if(newWidth > maxWidth){
            var factor = newWidth / maxWidth;
            if(factor > 1){
                newWidth = maxWidth;
                newHeight = newHeight / factor;
            }
        }


        if(ax == "height") return(newHeight);
        else if(ax == "width") return(newWidth);

        return(false);
    },
    loaded: function(){
        if(!this.loading) $clear(this.loadTimer);
    },
    loadMessage: function(){
        alert("Loading...");
    },
    createLoadDisplay: function(){
        this.overlayDuration = 0.2;
        this.overlay = new Element('div',{id:'overlay'});
        this.handle.grab(this.overlay);
        this.overlay.hide().addEvent('click', (function() { this.loadMessage(); }).bind(this));

        this.loadBox = new Element('div',{id:'loadBox'});
        this.handle.grab(this.loadBox);
        this.loadBox.hide().addEvent('click', (function() { this.loadMessage(); }).bind(this));
    },
    // Erstellt einen Layer, der über alles liegt und zeigt eine Lade-Anzeige
    startLoadDisplay: function(){
        // stretch overlay to fill page and fade in
        this.overlay.setStyle({ width: this.handle.getWidth() + 'px', height: this.handle.getHeight() + 'px' });
	new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: albumViewerOptions.overlayOpacity });
        this.loadBox.show();
    },
    // Beendet die Ladeanzeige und gibt die Bedienung frei
    closeLoadDisplay: function(){
        this.loadBox.hide();
        new Effect.Fade(this.overlay, { duration: this.overlayDuration });
    }
});

