// JavaScript Document
var Rating = Class.create();

Rating.prototype = {
	initialize: function(container, options){
		this.container = $(container);
		this.options = options || {};		
		this.options.root = options.root || '/rating';
		this.options.url = options.url || window.location.href;
		
		this.button = new Element('div');
		this.button.setStyle({
			fontSize:'16px',
			fontWeight:'bold',
			color:'#fff',
			height:'22px',
			float:'left',
			padding:'2px 7px 0'
		});
		
		this.result = new Element('div');
		this.result.setStyle({
			backgroundColor:'#878686',
			fontSize:'16px',
			fontWeight:'bold',
			color:'#fff',
			height:'22px',
			float:'left',
			padding:'2px 7px 0'
		});
		
		this.getResult(0);
		this.container.insert(this.button);
		this.container.insert(new Element('div').setStyle({
			backgroundImage:'url(' + this.options.root + '/arrow.png)',
			backgroundRepeat:'no-repeat',
			backgroundPosition:'right center',
			width:'4px',
			height:'24px',
			float:'left'
		}));
		this.container.insert(this.result);

		//this.button.observe("click", (function(event){ event.stop(); this.getResult(1); }).bind(this));
	},
	getResult: function(mode){
		var params = this.options;
		this.options.mode = mode;
		new Ajax.Request(this.options.root + '/rating.php', {
			method: 'post',
			parameters: this.options,
			encoding: 'UTF-8',
			onComplete: (function(transport) {
				var resp = transport.responseText.evalJSON();
				this.result.update(resp.val);
				if (resp.state == 0) {
					this.button.setStyle({backgroundColor:'#b27e0d',cursor:'pointer'});
					this.button.update('Голосую!');
					this.button.observe("click", (function(event){ event.stop(); this.getResult(1); }).bind(this));
				}
				if (resp.state == 1) {
					this.button.setStyle({backgroundColor:'#878686',cursor:'default'});
					this.button.update('Рейтинг:');
					this.button.stopObserving();
				}
			}).bind(this),
			onFailure: (function(transport) {
				alert('Error');
			}).bind(this)
		});
	}
};

