/**
 * @author Antonio G Greco, updated by Peter Chamberlin 05/10
 */
 
 var initRatings=function() 
 {
    if ($$('.rate')[0]) {
      new Ajax.Request('/getrating', {
            method:     'post',
            parameters:   {object_id:$F('object_id'),object_type:$F('object_type')},
              asynchronous:   true,
              evalScripts:    false,
              onSuccess:      function(request, json) {
              var rating_a = new Rating({json: json, container: '.rate'});
              }
          }
          
          );
    }
};

/** */
 if(/MSIE 6/i.test(navigator.userAgent))
 {
  //according to r44923, window load is required for IE6 - I'm not going to argue. EC.
    Event.observe(window, 'load', initRatings); 
 }
 else
 {
   //everyone else can use dom load, much quicker!
   Event.observe(document, "dom:loaded", initRatings);  
 }
 


Rating = Class.create({
	
	mainContainer: 	null,
	loader: 		null,
	hoverText: 		null,
	unorderedList: 	null,
	form:          	null,
	lastScoreClass:	null,
	
	createOLElement: function(num){
		this.orderedList = new Element('ol', {'class':'score-'+num});
		liElement = new Element('li');
		pElement = new Element('p');
		this.orderedList.insert(liElement);
		liElement.insert(pElement);
		this.mainContainer.insert(this.orderedList);
	},

	initialize: function(opt){
		if (opt.json.voteCount == null) throw ('Rating(): a rating vote count needs to be specified.');
		if (opt.json.score == null) throw ('Rating(): a rating score needs to be specified.');
		if (opt.json.scoreClass == null) throw ('Rating(): a rating score class needs to be specified.');
		if (opt.container == null) throw ('Rating(): a rating container needs to be specified.');
		this.voteCount = opt.json.voteCount;
		this.score = opt.json.score;
		this.scoreClass = opt.json.scoreClass;
		this.mainContainer = $($$(opt.container)[0]);
		if (!this.mainContainer.down('ol.set-rating')) return;
		this.applyRating();
	},
	
	applyRating:function(){
		
		$('rating-count').update(this.voteCount);
		$('rating-count').innerHTML;

		$('rating-score').update(this.score);
		$('rating-score').innerHTML;
		
		$('set-rating-a').addClassName(this.scoreClass);
	
		this.form = this.mainContainer.down('.rating-range');
		var rated = this.hasRated();
		this.mainContainer.down('ol.set-rating').select('a').each(function(item){
			if (!rated) {
				item.observe('mouseover', this.hoverOver.bindAsEventListener(this, item));
				item.observe('mouseout', this.hoverOut.bindAsEventListener(this, item));
				item.observe('click', this.sendRating.bindAsEventListener(this, item));
			}
			else {
				item.hide();
			}
		}.bind(this));
		if (rated) {
			this.mainContainer.down('p.rating-response').show();
			this.mainContainer.down('p.rateTextInline').hide();
		}
	},
	
	hoverOver: function(event, item){
		item.up('ol').addClassName(item.className);
	},
	
	hoverOut: function(event, item){
		item.up('ol').removeClassName(item.className);
	},
    
	sendRating: function(event, item){
		var idNum = item.className.split('-');
		var score = idNum[1];
		this.loading(score);
		new Ajax.Request('/rate', {
      		method:			'get',
      		parameters:		{object_id:$F('object_id'),object_type:$F('object_type'),score:score},
            asynchronous: 	true,
            evalScripts:  	false,
            onSuccess:    	function(request, json) {
      			this.loaded(request, json);
            }.bind(this)
        });
	},
	
	loading: function(num){
		this.mainContainer.down('ol.set-rating').remove();
		this.mainContainer.down('p.rateTextInline').innerHTML = 'Please wait...';
		this.createOLElement(num);
		this.loader = new Element('p', {'class':'loader'});
		this.mainContainer.insert(this.loader);
	},
	
	loaded:function(response, json){
		this.mainContainer.removeChild(this.loader);
		this.mainContainer.down('p.rating-response').show();
		this.mainContainer.down('p.rateTextInline').hide();
		this.voteCount = json.voteCount;
		this.score = json.score;
		this.lastScoreClass = this.scoreClass;
		this.scoreClass = json.scoreClass;
		this.removeRef();
		this.applyRating();
	},
	
	error: function(response){
		this.mainContainer.removeChild(this.unorderedList);
		this.mainContainer.removeChild(this.loader);
		this.removeRef();
	},
	
	removeRef: function(){
		delete this.mainContainer;
		delete this.hoverText;
		delete this.loader;
		delete this.unorderedList;
		this.mainContainer = null;
		this.loader = null;
		this.unorderedList = null;
	},

	/* Make an array from the cookie, check our form value is in the array
	 */
	hasRated: function() {
		var cookieVal = JAMLite.utils.readCookie('ratingsRated');
		var rated = []; 
		if(!cookieVal) return;
		cookieVal.scan(/\d+-\w+/, function(crumb) {rated.push(crumb[0])});
		currentRating = $F(this.form.elements['object_id']) + '-' + $F(this.form.elements['object_type']);
		return rated.include(currentRating);
	}

});

