var OrbVoting = Class.create({
    
    options: $H({
        animate: true,
        barColors: ['#ff0', '#f00'],
        containerClass: '.orb-voting',
        cookieName: 'star_voting',
        delay: 1,
        fxDuration: 500,
        id: null,
        postVars: '',
        responseText: false,
        stars: 5,
        starStyles: {
            padding: '0 2px 0 0',
            width: '20px'
        },
        text: {
            title: 'Vote',
            'suffix': 's'
        },
        textSelector: '.orb-text',
        thumbnailSelector: '.star-voting-thumbs p a',
        url: null,
        wrapperClass: '.orb-wrapper'
    }),
    
    initialize: function(container, options)
    {
        this.options.update(options || {});

        if(!container)
        {
            return;
        }
        this.container = $(container).select(this.options.get('wrapperClass'))[0];

        this.initResponse();
        
        this.getRating();

        $$(this.options.get('containerClass')).each(function(el){
            this.build(el.select('div')[0]);
            this.attach(el.select('div')[0]);
        }.bind(this));
        
        this.checkVote();
        this.mouseWithin = false;
        //this.getVotes();
        this.getVotesByClass();
    },
    
    setId: function(id)
    {
        this.options.set('id', id);
    },
    
    setPostVars: function(vars)
    {
        this.options.set('postVars', vars);
    },    
    
    build: function(el)
    {
        el.insert(new Element('span').addClassName('orb-bar'));

        this.anchors = [];
        
        for(var i = 0; i < this.options.get('stars'); i++)
        {
            this.anchors[i] = new Element('a', {
                'href': '#'
            });

            el.insert(this.anchors[i]);
            
            var left = 0;
            el.select('a').each(function(a){
                left+=a.getWidth();
            });

            this.anchors[i].observe(
                'mouseover', function(i){
                    return function(e){
                        this.mouseWithin = true;
                        this.resizeBar(i);
                    }.bind(this)
                }.bind(this)(i)
            ).observe(
                'mouseout', function(){
                    this.mouseWithin = false;
                }.bind(this)
            ).setStyle({
                'left': left+'px'
            }).setStyle(this.options.get('starStyles'));
        }

    },
    
    getBar: function()
    {
        return this.container.select('span')[0];
    },
    
    getRating: function()
    {
        if(!this.container)
        {
            return;
        }
        var params = this.options.get('postVars') != '' ? '&'+this.options.get('postVars') : '';
        new Ajax.Request(this.options.get('url'), {
           postBody: 'id='+this.options.get('id')+params,
           onSuccess: function(transport)
           {
                var json = transport.responseJSON;

                this.rating = json.rating;
                this.count = json.votes;

                this.setRating();
           }.bind(this)
        });  
    },
    
    setRating: function()
    {
        var bar = this.getBar();
        var max = this.options.get('stars');
        var percent = this.rating * 100 / max
        var width = Math.round(this.container.getWidth() * (percent/100), 0);
        
        this.animate(bar, this.options.get('barColors')[0], width);

        var vote_count = this.count + ' ' + this.options.get('text').title;
        vote_count+= this.count == 1 ? '' : this.options.get('text').suffix;
        
        $$(this.options.get('textSelector')+' p')[0].update(vote_count);
        
    },
    
    resizeBar: function(i)
    {
        var bar = this.getBar();
        var width = $(this.anchors[i]).getWidth() * (i+1);
        bar.setStyle({
            backgroundColor: this.options.get('barColors')[1],
            'width': width+'px'
        });
    },
    
    resetBar: function()
    {
        (function(){
            this.setRating();    
        }.bind(this)).delay(.5);
    },
    
    attach: function(el)
    {
        this.container.select('a').each(function(a,i){
            a.observe('click', function(e){
                Event.stop(e);
                this.vote(i+1);
            }.bind(this))
        }.bind(this));

        this.container.observe('mouseout', this.resetBar.bind(this));
    },
    
    disableVoting: function()
    {
        this.mouseWithin = false;
        this.container.select('a').each(function(a){
            a.hide(); 
        });
    },
    
    enableVoting: function()
    {
        if(!this.container)
        {
            return;
        }
        this.container.select('a').each(function(a){
            a.show(); 
        });
    },
    
    vote: function(i){
        this.addCookieData(this.options.get('id'));
        this.disableVoting();
        this.sendVoting(i);
    },
    
    sendVoting: function(i)
    {
        var params = this.options.get('postVars') != '' ? '&'+this.options.get('postVars') : '';
        new Ajax.Request(this.options.get('url'), {
           postBody: 'vote='+i+'&id='+this.options.get('id')+params,
           onSuccess: function(transport)
           {
                var json = transport.responseJSON;
                
                this.rating = json.rating;
                this.count = json.votes;
                
                this.toggleResponse();
                this.setRating();
           }.bind(this)
        });
    },
    
    initResponse: function()
    {
        if(!this.options.get('responseText'))
        {
            return;
        }

        var container = $$(this.options.get('textSelector'))[0];

        container.insert(
            new Element('p')
        ).insert(
            new Element('p')
        );

        var p = container.select('p');
        p[1].update(this.options.get('responseText')).hide();
    },
    
    toggleResponse: function()
    {
        if(!this.options.get('responseText'))
        {
            return;
        }
        var p = $$(this.options.get('textSelector')+' p');
        p[0].hide();
        p[1].show();
        (function(){
            p[0].show();
            p[1].hide();
        }).delay(5);
    },
    
    animate: function(bar, color, width)
    {
        if(this.mouseWithin)
        {
            return;
        }
        if(!this.options.get('animate'))
        {
            bar.setStyle({
                backgroundColor: color,
                width: width+'px'
            });
        }
        else
        {
            new Effect.Morph(bar, {
                style: {
                    background: color,
                    width: width+'px'
                },
                duration: .5
            });
        }
    },
    
    setCookie: function(data)
    {
        var expires = '';

        var today = new Date();
        expires = 1 * 86400000;
        expires = ';expires=' + new Date(today.getTime() + expires);

        document.cookie = this.options.get('cookieName')+'=' + data + expires;
    },
    
    addCookieData: function()
    {
        var data = this.getCookieData() != undefined && this.getCookieData() != '' ? this.getCookieData()+',' : '';

        this.setCookie(data + this.options.get('id'));
    },
    
    getCookieData: function()
    {
        var data = '';
        var cookies = document.cookie.split(';');

        for(var i = 0; i < cookies.length; i++)
        {
            var c = cookies[i].split('=');
            if(c[0].strip() == this.options.get('cookieName'))
            {
                data = c[1];
            }
        }
        return data;
    },
    
    checkVote: function()
    {
        if(this.getCookieData().split(',').indexOf(this.options.get('id')) > -1)
        {
            this.disableVoting();
            return;
        }
        this.enableVoting();
    },
    
    reset: function(id)
    {
        voting.setId(id);
        voting.getRating();
        voting.checkVote();
        voting.initResponse();
    },
    
    getThumbnails: function()
    {
        return $$(this.options.get('thumbnailSelector'));
    },
    
    getVotes: function()
    {
        var params = this.options.get('postVars')+'&thumbs=';
        var thumbs = this.getThumbnails();
        thumbs.each(function(thumb, i){
            params+= i > 0 ? ',' : '';
            var href = thumb.href;
            params+= href.split('/')[4].split('.')[0];
        });
        new Ajax.Request(this.options.get('url'), {
            postBody: params,
            onSuccess: function(transport)
            {
                var json = transport.responseJSON;
                this.setThumbVotings(json);
            }.bind(this)
        });  
    },
    
    setThumbVotings: function(data)
    {
        var c = 0;

        this.getThumbnails().each(function(a){
            var p = a.parentNode;
            var sname = (a.href).substr(0, (a.href.length-1)).split('\/').last();
            var wrapper = $(p).select('.orb-wrapper');

            data.each(function(item){
                if(item.name == sname)
                {
                    var v = new Element('span').addClassName('orb-bar');
                    wrapper[0].insert(v);

                    var delay = this.options.get('delay') * c;
                    var max = this.options.get('stars');
                    var percent = item.rating * 100 / max;
                    var width = Math.round(wrapper[0].getWidth() * (percent/100), 0);
                    
                    (function(){
                        this.animate(v, this.options.get('barColors')[0], width);
                    }.bind(this)).delay(delay);
                    c++;
                }
            }.bind(this));
        }.bind(this));
    },
    
    getVotesByClass: function()
    {
        var c = 0;
        this.getThumbnails().each(function(a){
            var votingContainer = a.next();
            var wrapper = votingContainer.select('.orb-wrapper');
            var cssClasses = (votingContainer.className).split(' ');
            
            cssClasses.each(function(item){
                if(item.startsWith('voting-'))
                {
                    var delay = .75 * c;
                    var v = new Element('span').addClassName('orb-bar');
                    wrapper[0].insert(v);
                    var percent = item.split('-')[1];
                    var width = Math.round(wrapper[0].getWidth() * (percent/100), 0);
                    (function(){
                        this.animate(v, this.options.get('barColors')[0], width);
                    }.bind(this)).delay(delay);
                    c++;
                }
            }.bind(this));
        }.bind(this));
    }
    
});


var Views = Class.create({
    
    options: $H({
        url: '/ajax/views.php'
    }),
    
    initialize: function(lang, id, options)
    {
        this.lang = lang;
        this.id = id;
        this.options.update(options || {});
    },
    
    update: function()
    {
        new Ajax.Request(this.options.get('url'), {
            postBody: 'id='+this.id+'&lang='+this.lang,
            onSuccess: function(transport){
                this.showViews(transport.responseJSON[0]);
            }.bind(this)
        });
    },
    
    showViews: function(json)
    {
        var e = json.views == 1 ? '' : 'e';
        $$('div.orb-text')[0].title = json.views+' Aufruf'+e;

    }
    
});