// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG RATING MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Looks for all raters (div.rater) and creates a new rater class to attach
// - which will take care of the rest
//fields
pdRatingsModule.prototype._transport;
pdRatingsModule.prototype._user;
pdRatingsModule.prototype._channelId = 'site.ratings';

function pdRatingsModule() {}

pdRatingsModule.prototype.initialize = function(transport, user){
  	//this function is called back during module registration
	this._transport = transport;
	this._user = user;
	
	var me = this; //set reference to current class to pass within Starbox constructor
	var callBack = this.saveRating.bind(this);

	//find all raters and create a new starbox for each
	$$('div.rater').each(function(rater){
		new Starbox(rater.identify(),
			rater.readAttribute('currentRating'), {
			rerate: false,
			ghosting: true,
			indicator: '#{average} rating from #{total} votes',
			total: rater.readAttribute('totalRatings'),
			onRate: callBack
		});	
	});
}

pdRatingsModule.prototype.saveRating = function(element, info){
	var indicator = element.down('.indicator');
	var postid = info.identity.split('_')[1];
	var rated = info.rated.toFixed(0);
	var request = {contentId:postid, rating:rated};	
	this._transport.transmitRequest('site.shared', 'setrating', request, this.onSaveRatingCompleted.bindAsEventListener(this, rated, indicator));	
}

pdRatingsModule.prototype.onSaveRatingCompleted = function(objResponse, rated, indicator){
	var success = (objResponse.rating == '0') ? false : true;			
	if(success){
		indicator.update('You rated ' + rated);		
		window.setTimeout(function() {indicator.update('Thanks for voting') }, 2000);
		pd_globalSiteFramework.trackEvent('Ratings', 'You rated ' + rated);
	}else{
		indicator.update('You already rated this post');
		pd_globalSiteFramework.trackEvent('Ratings', 'You already rated this post');
	}	
}
