var ratingStars = new Class({
//	Implements: [Events, Options],
	options: {
		flatfile: "../js/results.txt",
		name: false,
		header: "rate this concept",
		max: 5,
		cookie: false,
		ip: false,
		ua: false,
		uvSep: "|",
		rateSep: ":::",
		opacity: 1,
		togglebox: true,
		closebox: false,
		bottomelement: null,
		slidein: true,
		released: false
	},
	initialize: function(element, options){
		this.ratingStars = element;
		this.data = null;
		this.setOptions(options);
		this.voteCount = 0;
		this.voteSum = 0;
		this.rate = 0;
		this.rateRound = 0;
		this.vote = false;
		this.imgloc = "../images/core/rating/";
		this.options.name = this.options.name.toLowerCase();
		this.httpObject = this.getHTTPObject();
		this.readRates(); // going to parse the vote file
	},
	getHTTPObject: function(){
		if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); }
		else if (window.XMLHttpRequest) { return new XMLHttpRequest(); }
		else { return null; }
	},
	readRates: function(){
	  this.httpObject.open("GET", this.options.flatfile + "?ts=" + $time(), true);
	  this.httpObject.send(null);
	  this.httpObject.onreadystatechange = this.fileReady.bind(this);
	},
	fileReady: function(){
		if(this.httpObject.readyState == 4){
			var data = this.httpObject.responseText.trim().split("\n");
			this.parseContent(data, this); // text stream in memory, now parsing it
		}
	},
	parseContent: function(e, self){
		var rating = null;
		var uniqueVisitor = null;
		e.each(function(item, index){
			rating = item.split(self.options.rateSep);
			if (rating.length == 3 && rating["0"].toLowerCase() == self.options.name){
				uniqueVisitor = rating["1"].split(self.options.uvSep);
				if (!self.vote && ( uniqueVisitor["0"] == self.options.cookie || (uniqueVisitor['1'] == self.options.ip && uniqueVisitor['2'] == self.options.ua))){
					self.vote = rating["2"];
				}
				self.voteSum += rating["2"].toInt();
				self.voteCount++ ;
			}
		});
		this.getRating();
	},
	getRating: function(){
		if (this.voteCount > 0){
			this.rate = (this.voteSum / this.voteCount).round(2);
			this.rateRound = this.rate.round();
		}
		this.makeRateBox();
	},
	makeRateBox: function(){
		var icon = null;
		var staricon = null;
		var boxToggle = null;
		var boxClose = null;
		var starObj = null;
		var rateBox = null;
		var rateCont  = null;
		var uselessDiv = null;
		var daddyDiv = null;
		var slideControl = null;
		starObj = new Element('div',{id: 'bloody-rate'});
		if (this.options.header!== false) starObj.adopt(new Element('div',{id: 'rateheader'}).appendText(this.options.header));
		rateBox = new Element('div',{id: 'ratingbox'});
		for (var i = 1;i<=this.options.max;i++){
			i > this.rateRound ? staricon = 'w.gif' : staricon = 'y.gif';
			icon = new Element ("img",{src: this.imgloc + staricon,alt: i, id: this.options.name + "_" + i, "class": "star"});
			rateBox.adopt(icon);
		}
		starObj.adopt(rateBox);
		starObj.adopt(new Element("div",{id: "voting"}).setStyle("align","left").appendText("user rating: " + this.rate + "/" + this.options.max + " (" + this.voteCount + " votes)" ));
		if(this.vote !== false){ starObj.adopt(this.voteMessage()); }
		rateCont = (this.options.released === false) ? new Element('div', {id: 'content', 'class': 'transbox'}) : new Element('div', {id: 'content', 'class': 'relcovtransbox'});
		if (this.options.opacity < 1){ rateCont.setStyle('opacity',this.options.opacity);}
		rateCont.adopt(starObj);
		if (this.options.bottomelement != null){ rateCont.adopt(this.options.bottomelement); }
		if(this.options.togglebox === true){ boxToggle = new Element('span',{id: 'minimizer', title: 'toggle this box'}).appendText('-'); }
		if(this.options.closebox === true){ boxClose = new Element('span',{id: 'closer', title: 'close this box'}).appendText('X'); }
		if (boxToggle != null || boxClose != null){
			slideControl = new Element('div', {id: 'close_er_up', 'class': 'boxcontroller'});
			if (this.options.opacity < 0.95){ slideControl.setStyle('opacity',this.options.opacity + 0.05); }
			if ( boxClose !== null ){ slideControl.adopt(boxClose); }
			if ( boxToggle !== null ){ slideControl.adopt(boxToggle); }
			$(this.ratingStars).adopt(slideControl);
		}
		this.ratingStars.adopt(rateCont);
		if (this.options.slidein === true){ this.rateSlide = new Fx.Slide('content',{duration: 1000, transition: Fx.Transitions.Bounce.easeOut});
		this.rateSlide.hide(); }
		this.setRateBoxEvents();
		if (!this.vote){ this.setEvents(); }
		if (this.options.slidein === true){ this.rateSlide.toggle(); }
	},
	setRateBoxEvents: function(){
		var that = this;
		if(this.options.togglebox === true){
			$('minimizer').addEvent('click', function(e){
				e = new Event(e);
				that.rateSlide.toggle();
				e.stop();
			});
		}
		if(this.options.closebox === true){
			$('closer').addEvent('click', function(e){
				e = new Event(e);
				that.rateSlide.hide();
				e.stop();
				$('close_er_up').setStyle('display','none');
			});
		}
		return
	},
	setEvents: function(){
		var that = this;
		var starRay = $$('.star');
		for (var j=0;j<starRay.length;j++){
			starRay[j].setStyle('cursor','pointer');
		}
		// mouse over event
		var eventMo = function(e){
			var malt = this.getProperty('alt').toInt();
			for (var i = 0;i<malt;i++){
				starRay[i].setProperty('src', that.imgloc + 'b.gif');
			}
		}
		$$('.star').addEvent('mouseover', eventMo);
		// mouse out event
		var eventMou = function(e){
			var malt = this.getProperty('alt').toInt();
			for (var i = malt -1;i>= that.rateRound;i--){
				starRay[i].setProperty('src', that.imgloc + 'w.gif');
			}
			for (i = that.rateRound-1;i>=0;i--){
				starRay[i].setProperty('src', that.imgloc + 'y.gif');
			}
		}
		$$('.star').addEvent('mouseout', eventMou);
		// onclick event
		$$('.star').addEvent('click', function(e){
			for (var i=0;i<starRay.length;i++){
				starRay[i].removeEvents();
				i < that.rateRound ? starRay[i].setProperty('src',that.imgloc + 'y.gif') : starRay[i].setProperty('src',that.imgloc + 'w.gif');
				starRay[i].setStyle('cursor','default');
			}
			cvote = this.getProperty('alt').toInt();
			pagerate.submitRating(that.options.name, cvote, that.options.max, that.options.cookie + "|" + that.options.ip + "|" + that.options.ua);
		});
		return
	},
	voteMessage: function(){
		return new Element("div").appendText("your rate: " + this.vote + " bloody stars!");
	},
	write: function(url, content, httpobj) {
		if (httpobj != null){
			httpobj.onreadystatechange=function(){
				if(httpobj.readyState == 4){
				// nothing for now, alert("sent " + url + " " + content);
				}
			};
			httpobj.open("POST", url, true);
			httpobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			httpobj.send(content);
			pageTracker._trackEvent("Designs", "Rate", this.options.name, this.vote);
			this.setOutput();
		}
	},
	submitRating: function(item,rate,max,uv){
	   	actualItem = item;
	   	this.vote = rate;
		this.write("../js/ajax-post-text.php", "file=" + this.options.flatfile + "&content=" + item + ":::" + uv + ":::" + rate + "\n", this.httpObject);
   },
	setOutput: function(){
		this.httpObject = null;
		this.voteSum += this.vote;
		this.voteCount++;
		this.rate = (this.voteSum / this.voteCount).round(2);
		this.showStars();
	},
	showStars: function(){
		var arSt = $$('.star');
		for (var i=0;i< arSt.length;i++){
			i < this.rate ? arSt[i].setProperty('src',this.imgloc + 'y.gif') : arSt[i].setProperty('src',this.imgloc + 'w.gif') ;
		}
		this.updateTextRating();
	},
	updateTextRating: function(){
	   	var statup = new Element("div", {id: "voting"}).appendText("user rating: " + this.rate + "/" + this.options.max + " (" + this.voteCount + " votes)");
		statup.adopt(this.voteMessage());
	   	statup.replaces($("voting"));
	}
});
ratingStars.implement(Options, Events);