var RezeptGallery = new Class({
    
    options: $H({
        borderColors: ['#ccc', '#cc0009'],
        classLeftButton: 'slider-left',
        classRightButton: 'slider-right',
        fadeOutDisabledButtons: false,
        onClick: function(){ $empty() },
        setTitle: false,
        slideFxDuration: 500,
        slideFxTransition: 'quad:out',
        slideOpacity: false,
        visibleImages: 3
    }),
    
    initialize: function(holder, options)
    {
        // extend default options
        this.options.extend(options || {});
        // Init vars
        this.currentThumbnailNo = 0;
        this.gallery = $$('.galerie')[0];
        this.holder = $(holder);
        this.images = $H({});
        this.thumbnails = this.getThumbnails();
        // init slider
        this.wrap();        
        this.attach();
    },

    /**
     * Getter Methods
     */

    getThumbnailPosition: function(img)
    {
        return img.getPosition(img.getParent('div'));
    },

    getThumbnails: function()
    {
        return this.holder.getElements('img');
    },
    
    getWidthForImageWrapper: function()
    {
        var w = 0;
        this.thumbnails.each(function(el){
            var p = el.getParent();
            w+= p.getWidth() + p.getStyle('margin-left').toInt() + p.getStyle('margin-right').toInt() + p.getStyle('padding-left').toInt() + p.getStyle('padding-right').toInt();
        });
        return w;
    },

    /**
     * Events
     */
    
    attach: function()
    {
        this.thumbnails.each(function(el, i){
            
            var p = el.getParent();
            
            el.store('fxInstance', new Fx.Tween(el, {
                duration: 250
            }));

            p.addEvents({
                'click': function(e){
                    e.stop();
                    this.toggleImage(p);
                }.bind(this),
                'mouseover': function(){
                    this.toggleBackgroundColor(el, 1);
                    this.setTitle(el);
                }.bind(this),
                'mouseout': function(){
                    this.toggleBackgroundColor(el, 0);
                    this.setTitle(el);
                }.bind(this)
            })
        }, this);
    },
    
    setTitle: function(thumb)
    {
        this.imageTitle.set('html', thumb.getParent().get('title'));
    },
    
    toggleImage: function(el)
    {
        var img = el.getElement('img');
        var src = img.get('src');
        var title = src.split('/').getLast().split('.')[0];

        new Request.JSON({
            url: config.base_url+'ajax/getRezeptDetails',
            onSuccess: function(json){
                this.toggleRezept(el, json);
            }.bind(this)
        }).send('title='+title);        
    },
    
    toggleRezept: function(el, json)
    {
        // Details
        var details = $('details').getElement('.content');
        var dim = details.getSize();
        new Element('div', {
            'class': 'loading',
            styles: {
                height: dim.y,
                opacity: .5,
                width: dim.x
            }
        }).inject(details);       

        // Image
        var image = this.gallery.getElement('.image');
        var title = this.gallery.getElement('.title');

        if(!this.gallery.getElement('.loading'))
        {
            var loading = new Element('div', {
                'class': 'loading',
                styles: {
                    opacity: 0
                }
            }).inject(image);
            loading.fade(.5);
        }
        else
        {
            var loading = this.gallery.getElement('.loading');
            loading.fade(.5);
        }

        var link = config.base_url+'rezepte/'+json.kurz;

        new Fx.Tween(title, {}).start('left', (title.getWidth()*-1)).chain(function(){
            title.empty().setStyle('backgroundColor', '#fff').adopt(
                new Element('h2').grab(new Element('a', {
                    href: link,
                    text: json.name
                }))
            );
            RGBa(title);
            (function(){
                new Fx.Tween(title, {}).start('left', 0);
            }).delay(250);
        });
        
        image.getElement('a').set('href', link);
        var img = image.getElement('img');
        var asset = new Asset.image(config.base_url+'resources/img/rezepte/l/'+json.kurz+'.jpg', {
            alt: json.name,
            onload: function(){
                asset.replaces(img);
                loading.fade(0);
            },
            title: img.get('title')
        });

        this.updateDetails(json);

    },
    
    updateDetails: function(json)
    {
        var details = $('details').getElement('.content');

        details.setStyle('position', 'relative');        

        var category = details.getElement('.category');
        category.set('text', category.get('text').split(' ')[0]+' '+json.kategorie);

        var difficulty = details.getElement('.grad');
        difficulty.set('text', difficulty.get('text').split(' ')[0]+' '+json.grad+' / 3');

        var comments = details.getElement('.comments');
        comments.set('text', comments.get('text').split(' ')[0]+' '+json.comments);

        var tags = details.getElement('.tags');
        tags.set('text', tags.get('text').split(' ')[0]+' ');

        json.tags.each(function(tag,i ){
            tags.innerHTML+= i > 0 ? ', ' : '';
            new Element('a', {
                href: config.base_url+'tags/'+tag.toLowerCase(),
                rel: 'tag',
                text: tag
            }).inject(tags);
        });
        
        details.getElement('.loading').dispose();
    },
    
    /**
     * Slider / Pagination
     */
    
    wrap: function()
    {
        var width = this.getWidthForImageWrapper();
        var target = this.holder.getParent();
        this.wrapper = new Element('div', {
            'class': 'wrapper'
        }).adopt(
            new Element('div', {
                'class': 'image-slide'
            }).grab(
                new Element('div', {
                    'styles': {
                        width: width
                    }
                }).grab(
                    this.holder
                )
            )
        ).inject(target);

        // define global fx for the slider
        this.slideFx = new Fx.Morph(this.wrapper.getElement('div div'), {
            duration: this.options.slideFxDuration,
            transition: this.options.slideFxTransition
        });
        
        this.wrapper.addEvent('mousewheel', function(e) {
            e.stop();
            /* Mousewheel UP */
            if(e.wheel > 0) {
                this.prev();
            } 
            /* Mousewheel DOWN*/
            else if (e.wheel < 0) {
                this.next();
            }
        }.bind(this));

        this.createButtons();
        this.createTitleHolder();
    },
    
    createButtons: function()
    {
        // return if buttons are not necessary
        if(this.thumbnails.length <= this.options.visibleImages)
        {
            return;
        }
        this.leftButton = new Element('span', {
            'class': this.options.classLeftButton,
            events: {
                'click': function()
                {
                    this.prev();
                }.bind(this)
            },
            html: '&laquo;'
        }).inject(this.wrapper);

        this.rightButton = new Element('span', {
            'class': this.options.classRightButton,
            events: {
                'click': function()
                {
                    this.next();
                }.bind(this)
            },
            html: '&raquo;'
        }).inject(this.wrapper);
        this.toggleButtons();
    },
    
    next: function()
    {
        // images left after slide
        var va = this.thumbnails.length - ( this.currentThumbnailNo + this.options.visibleImages );

        this.currentThumbnailNo = va >= this.options.visibleImages ? this.currentThumbnailNo + this.options.visibleImages : this.thumbnails.length - this.options.visibleImages;
        this.slide();
    },
    
    prev: function()
    {
        this.currentThumbnailNo = (this.currentThumbnailNo- this.options.visibleImages).limit(0, this.thumbnails.length);
        this.slide();
    },    
    
    toggleButtons: function()
    {
        if(!this.options.fadeOutDisabledButtons)
        {
            return;
        }

        // first thumb is visible
        var isFirst = this.currentThumbnailNo == 0;
        var opaqueLeft =  isFirst ? .5 : 1;
        this.leftButton.fade(opaqueLeft);
        var cursorLeft = isFirst ? 'default' : 'pointer';
        this.leftButton.setStyle('cursor', cursorLeft);

        // last thumb is visible
        var isLast = ( this.currentThumbnailNo + this.options.visibleImages ) == this.thumbnails.length;
        var opaqueRight = isLast ? .5 : 1;
        this.rightButton.fade(opaqueRight);
        var cursorRight = isLast ? 'default' : 'pointer';
        this.rightButton.setStyle('cursor', cursorRight);

    },
    
    toggleBackgroundColor: function(el, i)
    {
        var fxInstance = el.retrieve('fxInstance');
        fxInstance.cancel();
        fxInstance.start('backgroundColor', this.options.borderColors[i]);
    },

    slide: function()
    {
        // image to scroll to
        var img = this.thumbnails[this.currentThumbnailNo];
        var imgPos = this.getThumbnailPosition(img);

        var newPos = imgPos.x * -1;

        this.slideFx.start({
            left: newPos    
        });

        this.toggleButtons();
    },
    
    createTitleHolder: function()
    {
        if(!this.options.setTitle)
        {
            return;
        }
        this.titleHolder = new Element('p').inject(this.wrapper, 'after');
    },
    
    setTitle: function(img)
    {
        if(!this.options.setTitle)
        {
            return;
        }
        this.titleHolder.set('html', img.title);
    }

});
