/**
 * GLOBALS, YUKK
 */

var SampleVoting;

/**
 * SLIDER CLASS
 */

var Slider = new Class({

	Implements: Options,
	
	options: {
		childSelector: 'div.books',
		fxDuration: 500,
		fxTransition: 'sine:out',
		paginationColors: ['#ccc', '#666'],
		perPage: 1
	},
	
	initialize: function(container, options)
	{
		this.setOptions(options);

		this.container = $(container);

		if(!this.container)
		{
			return;
		}
		
		this.current = 0;
		this.enabled = true;

		this.container.setStyle('overflow', 'hidden');

		this.containerSize = this.container.getSize();

		this.wrapper = new Element('div', {
			styles: {
				overflow: 'hidden',
				position: 'relative'
			}
		}).inject(this.container);

		this.holder = new Element('div', {
			styles: {
				left: 0,
				position: 'absolute',
				top: 0
			}	
		}).adopt(this.container.getElements(this.options.childSelector)).inject(this.wrapper);

		var c = this.holder.getChildren().length;
		// auf gerade zahl bringen
		c = c % 2 == 0 ? c : c + 1;

		var f = this.holder.getFirst();
		var size = $H(f.getSize());
		size.include('marginTop', f.getStyle('margin-top').toInt());
		size.include('marginRight', f.getStyle('margin-right').toInt());
		size.include('marginBottom', f.getStyle('margin-bottom').toInt());
		size.include('marginLeft', f.getStyle('margin-left').toInt());

		var w = (size.x + size.marginRight + size.marginLeft) * c;
		var h = (size.y + size.marginTop + size.marginBottom);

		this.pageWidth = (size.x + size.marginRight + size.marginLeft) * this.options.perPage;

		this.pages = (this.holder.getChildren().length / this.options.perPage).round() - 1;

		this.wrapper.setStyle('height', h);

		this.holder.setStyles({
			height: h,
			width: w
		});

		if(this.pages < 1)
		{
			return;
		}

		this.createButtons();
		this.createPagination();
	},
	
	/**
	 * Buttons
	 */
	
	createButtons: function()
	{
		this.buttonLeft = new Element('span', {
			'class': 'button-left',
			events: {
				'click': this.back.bindWithEvent(this)
			}
		}).inject(this.wrapper);

		var top = ((this.containerSize.y / 2) - (this.buttonLeft.getWidth() / 2)).round();

		this.buttonLeft.setStyles({
			left: 0,
			top: top
		});

		this.buttonRight = new Element('span', {
			'class': 'button-right',
			events: {
				'click': this.forward.bindWithEvent(this)
			}
		}).inject(this.wrapper);

		this.buttonRight.setStyles({
			left: this.containerSize.x - this.buttonRight.getWidth(),
			top: top
		});

	},
	
	back: function()
	{
		if(this.current == 0)
		{
			return;
		}
		this.goToPage(0, this.current-1);
	},
	
	forward: function()
	{
		if(this.current >= this.pages)
		{
			return;
		}
		this.goToPage(0, this.current+1);
	},
	
	goToPage: function(o, i)
	{
		if(!this.enabled)
		{
			return;
		}
		this.enabled = false;
		this.setPage(i);
		this.slide(this.pageWidth * i * -1);
	},
	
	slide: function(left)
	{
		new Fx.Tween(this.holder, {
			duration: this.options.fxDuration,
			transition: this.options.fxTransition
		}).start('left', left).chain(function(){
			this.enabled = true;
		}.bind(this));
	},
	
	/**
	 * Pages
	 */
	
	createPagination: function()
	{
		this.PagnationHolder = new Element('div', {
			'class': 'pagination'
		}).inject(this.container);

		(this.pages+1).each(function(i){
			new Element('span', {
				events: {
					'click'	: this.goToPage.bindWithEvent(this, i)
				},
				html: '&bull;'
			}).inject(this.PagnationHolder);
		}, this);
		
		this.setPage(this.current);
	},
	
	setPage: function(i)
	{
		var spans = this.PagnationHolder.getElements('span');
		
		new Fx.Tween(spans[this.current]).start('color', this.options.paginationColors[0]);
		
		new Fx.Tween(spans[i]).start('color', this.options.paginationColors[1]);

		this.current = i;
	}
	
});

var Voting = new Class({
    
	Implements: Options,
	
    options: {
        animate: true,
		barClass: 'voting-bar',
        barColors: ['#ffe74d', '#e1071c'],
        containerClass: '.voting',
		cookieContent: '',
        cookieName: 'sample_voting',
        delay: 1,
        fxDuration: 500,
        id: null,
        postVars: null,
        responseText: false,
        scoreSelector: '.voting-score',
		stars: 5,
        starStyles: {},
        textSelector: '.hover-text',
        url: null,
        wrapperClass: '.voting-wrapper'
    },

	anchors: null,
	cookie: null,
	disabled: false,
	rating: 0,
	voting: 0,
	width: 0,
    
    initialize: function(container, options)
    {
        this.setOptions(options);

        if(!container || this.voted())
        {
            return;
        }
        this.container = $(container);		

		this.build();

		this.setVoting();

		this.attach();
    },
    
	/**
	 * GETTER
	 */
	
	getBar: function()
    {
        return this.container.getElement('span.voting-score');
    },
	
	getTextContainer: function()
	{
		return this.container.getElement(this.options.textSelector);	
	},
	
	/**
	 * SETTER
	 */
	
    setId: function(id)
    {
        this.options.set('id', id);
    },
    
    setPostVars: function(vars)
    {
        this.options.set('postVars', vars);
    },
	
	setVoting: function()
	{
		this.voting = this.container.getElement('.'+this.options.scoreSelector).getWidth() / this.width * 100;
	},
	
	/**
	 * BUILD
	 */
    
    build: function()
    {
		var left = 0;
		var target = this.container.getElement('.'+this.options.barClass);

        this.anchors = [];

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

            target.adopt(this.anchors[i]);

			this.anchors[i].setStyle('left', left).setStyles(this.options.starStyles);
			
			left+= this.anchors[i].getWidth();
			this.width = left;
        }
    },
	
    attach: function(el)
    {	
		this.anchors.each(function(a, i ){
			a.addEvents({
				'click': function(e){
					e.stop();
					this.vote(i+1);
				}.bind(this),
                'mouseover': function(){
					if(!this.disabled)
					{
	                    this.mouseWithin = true;
						this.resizeBar(i);
						this.setText(i);
					}
				}.bind(this),
                'mouseout': function(){
                    this.mouseWithin = false;
                }.bind(this)
			});
		}, this);

		this.container.addEvent('mouseout', function(){
			this.setText(false);
			this.resetRating();
		}.bind(this));
    },	

	/**
	 * VOTING / BAR / RATING
	 */

	enable: function()
    {
		var voted = this.voted();
		if(voted)
		{
			return;
		}
		this.disabled = false;
    },

	disable: function()
    {
		this.disabled = true;
    },
	
	getRating: function()
	{
		var data = $H({
			book_id: this.options.id,
			request: 'get_rating'
		});

		new Request.JSON({
			onSuccess: function(json){
				this.voting = json.voting > 0 ? json.voting * 10 * 2 : 0;
				this.setRating();
			}.bind(this),
			url: this.options.url
		}).send(data.toQueryString());
	},

	setRating: function()
    {
		if(this.mouseWithin)
		{
			return;
		}
        var bar = this.getBar();

		bar.setStyles({
            backgroundColor: this.options.barColors[1],
            width: this.voting+'%'
        });
    },
	
	resetRating: function()
	{
		this.setRating();
		this.setText(false);
	},
	
	resizeBar: function(i)
    {
        var bar = this.getBar();
        var width = this.anchors[i].getWidth() * (i+1);
        bar.setStyles({
            backgroundColor: this.options.barColors[0],
            width: width
        });
    },
	
	vote: function(i)
	{
		if(this.disabled)
		{
			return;
		}

		this.setText(false);

		this.disable();		

		var data = $H({
			book_id: this.options.id,
			request: 'vote',
			voting: i
		});
		
		new Request.JSON({
			onSuccess: function(json){
				this.voting = json.voting ? json.voting * 10 * 2 : 0;

				this.showResponse();
				this.mouseWithin = false;
				this.setRating();
				this.setCookie();
			}.bind(this),
			url: this.options.url
		}).send(data.toQueryString());
	},
    
	
	/**
	 * TEXT
	 */
	
	setText: function(i)
	{
		if(this.disabled)
		{
			return;
		}

		var target = this.getTextContainer();

		target.setStyle('display', 'block');

		target.getElements('span').setStyle('display', 'none');
		
		if(i !== false)
		{
			target.getElements('span')[i].setStyle('display', 'block');	
		}
	},
	
	showResponse: function()
	{
		var textCon = this.getTextContainer();
		
		textCon.setStyle('display', 'none');
		
		var responseEl = this.container.getElement('.voting-thanks');
		
		responseEl.setStyles({
			display: 'block',
			opacity: 0	
		}).fade(1);
		
		(function(){
			responseEl.fade(0);
		}).delay(3000);
	},
    
	/**
	 * COOKIE
	 */
	
    setCookie: function()
    {
		var cc = this.getCookieContent();

		var data = cc != undefined && cc != '' ? cc+',' : '';

		//data+= this.options.cookieContent;
		data+= this.options.id;

		Cookie.write(this.options.cookieName, data, {
			duration: 0
		});
    },
    
    getCookieContent: function()
    {
        return Cookie.read(this.options.cookieName);
    },
    
    voted: function()
    {
		var cc = this.getCookieContent();

		var r = false;

		if(cc)
		{
			cc.split(',').each(function(item){
				if(item == this.options.id)
				{
					r = true;
				}
			}, this);
		}

		return r;
    }
    
});

var updateSample = function(el)
{
	new Fx.Scroll(window).toElement($('beispielbuch'));

	var id = el.get('id') ? el.get('id').split('-')[1] : false;

	var a = el.getElement('a');

	if(a.get('href') != $('beispielbuch').get('src'))
	{
		if(id)
		{
			// update id
			SampleVoting.options.id = id;
			// get rating and enable it
			SampleVoting.getRating();
			SampleVoting.enable();
			// update views / clicks
			new Request({
				url: ajax_url
			}).send('request=view&book_id='+id);
		}
		// set iframe source
		$('beispielbuch').set('src', a.get('href'));
	}
};

window.addEvent('domready', function(){

	new Slider($$('.sample-category .sample-books')[0]);
	
	$$('.sample-books a').addEvent('click', function(e){
		e.stop();
		updateSample(this.getParent('div'));		
	});
	
	var firstSample = $$('.voting');
	
	if(firstSample[0])
	{
		var id = firstSample[0].get('id').split('-')[1];

		SampleVoting = new Voting($E('.voting'), {
			id: id,
			url: ajax_url
		});
	}

	var sliderButtons = $$('.button-left', '.button-right');

	if(sliderButtons && !Browser.Engine.trident)
	{
		sliderButtons.setStyle('opacity', .6);

		sliderButtons.addEvents({
			mouseover: function(){
				this.fade(1);
			},
			mouseout: function(){
				this.fade(.6);
			}
		});
	}
});