/**
 * GLOBALS, YUKK
 */

var SampleVoting;

/**
 * Comments
 */

var getComments = function(id)
{
	$('Comments').setStyle('height', 0);
	
	var perPage = 5;

	new Request.JSON({
		onSuccess: function(json) {
			$E('.show-comments').set('text', json.length+' '+$E('.show-comments').get('text').split(' ')[1]);

			var target = $('Comments').getElement('.comment-holder div');
			target.empty();

			var display = json.length > 0 ? 'none' : 'block';
			target.getNext('p').setStyle('display', display);

			json.each(function(obj){
				new Element('div', {
					html: '<strong>'+obj.author+', '+obj.date+'</strong><span>'+obj.text+'</span>'	
				}).inject(target);
			});

			var f = $('Comments').getElement('form');

			f.getElements('input, textarea').removeClass('error').removeProperty('disabled');

			f.getElements('input[type=text], textarea').set('value', '');

			if(f.getHeight() == 0)
			{
				f.setStyles({
					height: 'auto',
					opacity: 1
				});

				$('Comments').getElement('.response').setStyle('display', 'none');
			}

			var comment_pagination = new Pagination(target, target.getElements('div'), 5);

			comment_pagination.addEvent('change', function(){
				var height = target.getHeight();
				if(height > $('Comments').getHeight())
				{
					new Fx.Tween($('Comments'), {
						duration: 500
					}).start('height', height);
				}
			});
		},
		url: ajax_url
	}).send('request=get_comments&book_id='+id);
	
	$('Comments').getElement('div form input[name=comment_book_id]').set('value', id);
}

/**
 * Pagination
 */

var Pagination = new Class({

	Implements: Events,

	currentPage: 0,

	initialize: function(element, childSelector, perPage)
	{
		this.element = $(element);
		this.children = $$(childSelector);
		this.perPage = perPage;

		this.pages = Math.ceil(this.children.length/this.perPage);

		this.createNavigation();
		this.showPage(0);
	},
	
	createNavigation: function()
	{
		if(this.pages < 2)
		{
			return;
		}
		this.navigation = new Element('ul').inject(this.element);
		
		this.pages.each(function(i){
			new Element('li', {
				events: {
					'click': function(){
						this.showPage(i);
					}.bind(this)
				},
				text: i+1
			}).inject(this.navigation);
		}, this);

		this.navigation.getElement('li').addClass('current');	
	},
	
	setDisplay: function()
	{
		this.children.each(function(el, i){
			var display = 'none';
			if(i >= this.perPage*this.currentPage && i < (this.perPage*this.currentPage)+this.perPage)
			{
				display = 'block';
			}
			el.setStyle('display', display);
		}, this);

		this.change();
	},
	
	showPage: function(i)
	{
		this.currentPage = i;
		if(this.pages > 1)
		{
			this.navigation.getElement('li.current').removeClass('current')
			this.navigation.getElements('li')[i].addClass('current');
		}
		this.setDisplay();
	},
	
	change: function()
    {
        this.fireEvent('change');
    }
	
});

/**
 * 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;
	}
	
});

/**
 * TAGS
 */

var getTags = function(id)
{
	var target = $$('.sample-tags span')[0];

	new Request.JSON({
		onSuccess: function(json){
			target.empty();
			json.each(function(el,i){
				if(i > 0)
				{
					target.innerHTML+= ', ';
				}
				new Element('a', {
					href: tag_url+'?tag='+el,
					text: el
				}).inject(target);
			});
		},
		url: ajax_url
	}).send('request=get_tags&book_id='+id);
};

/**
 * VOTING
 */

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,
	initialized: false,
	rating: 0,
	voting: 0,
	width: 0,
    
    initialize: function(container, options)
    {
        this.setOptions(options);

        this.container = $(container);		

		this.build();
		this.setVoting();
		this.attach();
		if(this.voted())
		{
			this.disable();
		}
    },
    
	/**
	 * GETTER
	 */
	
	getBar: function()
    {
        return this.container.getElement(this.options.scoreSelector);
    },
	
	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));
		
		this.initialized = true;
    },	

	/**
	 * 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();
				this.disable();
			}.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;
    },
	
	/**
	 * Reset
	 */
	
	reset: function(id)
	{
		this.options.id = id;
		// get rating and enable it
		this.getRating();
		this.enable();
	}
    
});

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

	var elId = el.get('id');

	var id = elId ? elId.split('-')[1] : false;
	var country = elId ? elId.split('-')[2] : false;

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

	if(a.get('href') != $('beispielbuch').get('src'))
	{	
		// set iframe source
		$('beispielbuch').set('src', a.get('href'));
		
		if(id && country)
		{
			// update voting
			// SampleVoting.reset(id); //!!! Fehler wird geworfen 2011-05-18 Tino
			// update views / clicks
			new Request({
				url: ajax_url
			}).send('request=view&book_id='+id+'&country='+country);
			// get tags
			if($$('.sample-tags')[0])
			{
				getTags(id);
			}
			// hide comments
			if($('Comments'))
			{
				getComments(id);
			}
		}

	}
};

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);
			}
		});
	}

	if($('Comments') && $E('.show-comments'))
	{
		if($('Comments').hasClass('hide'))
		{
			$('Comments').setStyles({
				height: 0,
				overflow: 'hidden'
			});
		}

		getComments($E('.show-comments').get('id').split('-')[1]);
		
		$E('.show-comments').addEvent('click', function(e){
			e.stop();

			var height = $('Comments').getHeight() == 0 ? $('Comments').getElement('div').getHeight() : 0;

			new Fx.Tween($('Comments'), {
				duration: 500
			}).start('height', height);

		});
		
		var f = $('Comments').getElement('div form');
		
		f.addEvent('submit', function(e){
			e.stop();

			var inputs = f.getElements('input, textarea');

			var valid = true;

			f.getElements('input[type=text], textarea').each(function(el){
				el.removeClass('error');

				if(el.get('value').trim() == '')
				{
					el.addClass('error');
					valid = false;
				}
			});

			if(!valid)
			{
				return;
			}

			inputs.set('disabled', 'disabled');

			var formData = $H();

			inputs.each(function(el){
				formData.include(el.get('name'), el.get('value'));
			});
			
			formData.include('request', 'post_comment');
			
			new Request({
				onSuccess: function(){
					$('Comments').getElement('form').morph({height: 0, opacity: 0});
					$('Comments').getElement('.response').setStyle('display', 'block');
				},
				url: ajax_url	
			}).send(formData.toQueryString());
		});
	}
	
});
