var coreRate = {
	done : false,
	before : false,

	init : function() {
		coreRate._init();
	},

	_init : function() {
		this.help = $('#rateHelp');

		this.stars = document.getElementById('rateStars');
		this.jstars = $(this.stars);

		this.jstars.hover(this.over, this.out);

		this.jstars.click(this.rate);

		this.starbox = $('#rateMyBox');

		this.mystars = document.getElementById('rateMyStars');
		this.jmystars = $(this.mystars);


		this.items = window['rateItems'];

		this.rateURL = window['rateURL'];
		this.rateVars = window['rateVars'];
	},

	rate : function(ev) {
		coreRate._rate(ev);

	},

	_rate : function(ev) {
		if (this.done) return;

		var pos = jQuery.iUtil.getPosition(this.stars);
		var size = jQuery.iUtil.getSize(this.stars);

		this.starPos = pos.x;
		this.starWidth = size.wb;

		this.oneStar = size.wb / this.items.length;

		if (this.oneStar <= 1) {
			return;
		}

		var currentPointer = jQuery.iUtil.getPointer(ev);

		var dx = currentPointer.x - this.starPos;

		var rate = 0;

		while (dx > this.oneStar) {
			++rate;
			dx -= this.oneStar;
		}

		this.jstars.unbind('click', this.rate);
		this.done = true;

		var gv = this.rateVars;
		gv.rate = this.items[rate];

		$.get(this.rateURL, gv, this.rateCallback, 'json');

		this.help.hide();

		this.before = false;
		this.stop();
	},

	rateCallback : function(d) {
		coreRate._rateCallback(d);
	},

	_rateCallback : function(d) {

		if (d.myRating !== undefined) {
			this.mystars.className = 'starsRate stars' + d.myRating + '0';
			this.starbox.show();

		}

		if (d.newRating !== undefined) {
			this.stars.className = 'starsRate stars' + d.newRating;

		}
	},

	over : function() {
		if (coreRate.done) return;

		coreRate.start();
	},

	out : function() {
		coreRate.stop();

	},

	start : function() {
		var pos = jQuery.iUtil.getPosition(this.stars);
		var size = jQuery.iUtil.getSize(this.stars);

		this.starPos = pos.x;
		this.starWidth = size.wb;

		this.oneStar = size.wb / 6;

		if (this.oneStar <= 1) {
			return;
		}

		this.before = this.stars.className;

		this.jstars.bind('mousemove', this.move);

	},

	stop : function() {
		this.jstars.unbind('mousemove', this.move);

		if (this.before) {
			this.stars.className = this.before;
			this.before = false;
		}
	},

	move : function(ev) {
		coreRate._move(ev);
	},

	_move : function(ev) {
		var currentPointer = jQuery.iUtil.getPointer(ev);

		var dx = currentPointer.x - this.starPos;

		var rate = 1;

		while (dx > this.oneStar) {
			++rate;
			dx -= this.oneStar;
		}

		var newclass = "starsRate stars" + (rate*10);

		this.stars.className = newclass;

	}
};

$().ready(coreRate.init);
