/**
* Creates a new object to manage rating stars objects
*
* @author				Matt Gifford
* @copyright			2008 Timeshifting Interactive Limited
*/
function RatingStars()
	{
	// Step 1. Define Properties

	var _instance = this;
	this.ratingStarNodes = [];


	// Step 2. Define Public Methods

	/**
	* Sets up the initial page state and event handlers
	*/
	this.init = function()
		{
		// Add event handlers to objects available at load time
		this.add( dojo.query('div.ratingStars') );
		}


	/**
	* Adds event handlers to rating star nodes
	*
	* @param		nodes		The array of nodes to process
	*/
	this.add = function(nodes)
		{
		// Add the event handlers
		for (var x = 0; x < nodes.length; x++)
			{
			// Check if the node is active
			if (nodes[x].className.indexOf('active') != -1 && nodes[x].className.indexOf('inactive') == -1)
				{
				// Node active
				nodes[x].onclick = this.eventHandlerSetRating;
				nodes[x].onmouseover = this.eventHandlerSaveRating;
				nodes[x].onmouseout = this.eventHandlerRevertRating;
				nodes[x].onmousemove = this.eventHandlerPreviewRating;

				// Log processed node
				if (typeof(console)!='undefined')console.log('Ratings Stars Added: ' + nodes[x].className);
				}
			}
		}


	/**
	* Sets the new rating in the ui and sends the new rating to the backend via ajax
	*
	* @param		event		The browser event object
	*/
	this.eventHandlerSetRating = function(event)
		{
		// Get the widget a unique id
		if (this.id == '')
			{
			this.id = 'ratingStarsWidget' + (new Date()).getTime();
			}

		// Save the previous rating
		var previousAverageRating = this.getAttribute('previousStars').replace(/\D+/g, '') * 1;

		// Save the current stars
		this.setAttribute('previousStars', this.firstChild.className);
		var newRating = (this.firstChild.className.replace(/\D+/g, '') * 1);

		// Show the updating message
		this.firstChild.className += ' starsUpdating';

		// Disable further rating
		this.onclick = null;
		this.onmouseover = null;
		this.onmouseout = null;
		this.onmousemove = null;

		// Get the video id
		var id = this.className.substring(this.className.indexOf('video')+5, this.className.length).split(' ')[0];

		// Update the rating count and average
		var average = previousAverageRating;
		var nodes = dojo.query('b.ratingsCount' + id);
		for (var x = 0; x < nodes.length; x++)
			{
			average = Math.round((previousAverageRating + newRating) / ((nodes[x].innerHTML * 1)+1));
			nodes[x].innerHTML = (nodes[x].innerHTML * 1) + 1;
			}

		// Update 

		console.log('setRating');
		// Send the update request
		dojo.xhrGet(
			{
//			url: '/ajax/ratings.php?action=setStarRating&id=' + id + '&widget_id=' + this.id + '&average=' + average + '&stars=' + newRating,
			url: '/index/ratevideo/id/' + id + '/rating/' + newRating,
			preventCache: true,
			handleAs: "text",
				load: function(data)
					{
					// Find all the rating stars widget for this listing
					var widgets = dojo.query('div.ratingStars');
					if (widgets.length)
						{
						if (data.indexOf('Success') != -1)
							{
							// Updates stars
							widgets[0].firstChild.className = 'stars' + data.replace(/\D+/g, '');
							}
						else
							{
							// Display error message
							widgets[0].firstChild.className = widgets[0].firstChild.className.replace('starsUpdating', '');
							alert(data);
							}
						}
					},
				error: function(error)
					{
					}
				}
			);
		}


	/**
	* Event Hander: Previews the new rating stars setting
	*
	* @param		event		The browser event object
	*/
	this.eventHandlerPreviewRating = function(event)
		{
		var event = !!event ? event : window.event;

		// Check if we have the object's left position saved
		var leftPosition = 0;
		if (this.getAttribute('absLeftPosition') == '' || this.getAttribute('absLeftPosition') == null)
			{
			var obj = this;
			var x = 0;
			do
				{
				if (obj.offsetLeft)
					{
					x += obj.offsetLeft;
					}
				}
			while ( obj = obj.offsetParent );
			this.setAttribute('absLeftPosition', x);
			}

		// Get the saved left position
		var leftPosition = this.getAttribute('absLeftPosition') * 1;

		// Check for missed save of original class name
		if (this.firstChild.className.indexOf('Preview') == -1)
			{
			this.setAttribute('previousStars', this.firstChild.className);
			}

		// Get the star value
		if (!!(window.attachEvent && !window.opera))
			{
			// Add the mouse position and current scroll position
			var mousePosition = event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
			}
		else
			{
			var mousePosition = event.pageX;
			}
		var starValue = (Math.round(((mousePosition - leftPosition) / 88) * 5) * 2);
		this.firstChild.className = 'starsPreview' + starValue;
		}


	/**
	* Event Handler: Saves the current rating
	*/
	this.eventHandlerSaveRating = function()
		{
		if (this.firstChild.className.indexOf('Preview') == -1)
			{
			this.setAttribute('previousStars', this.firstChild.className);
			}
		}


	/**
	* Event Hander: Reverts the rating stars to their currently set value
	*/
	this.eventHandlerRevertRating = function()
		{
		this.firstChild.className = this.getAttribute('previousStars');
		}


	// Step 4. Initialize Class
	this.init();
	}
