/**
 * class	CS_ImageScrubber
 * author	Paul Kruijt
 */
var CS_ImageScrubber = new Class({
	
	/**
	 * initialize
	 * @param	string	root_node_id
	 * @param	string	scrubbed_tag
	 * @return	void
	 */
	initialize: function(root_node_id, scrubbed_tag)
	{
		// id's
		this.root_node_id	= root_node_id;
		
		// nodes
		this.root_node		= $(this.root_node_id);
		
		// settings
		this.scrubbed_tag		= !scrubbed_tag ? 'img' : scrubbed_tag;
		this.active_image_index	= 0;
	},
	
	/**
	 * start image scrubber
	 * @return void
	 */
	start: function()
	{
		if (this.root_node)
		{
			var _this	= this;
			
			// get all images
			var image_nodes			= $$('#'+this.root_node_id+' '+this.scrubbed_tag);
			var total_image_nodes	= image_nodes.length;
			
			if (total_image_nodes > 0 && image_nodes[0])
			{
				// show main image
				var main_image	= image_nodes[this.active_image_index];
				main_image.setStyle('display', 'block');
				
				for (var a=0; a<image_nodes.length; a++)
				{
					var image_node = image_nodes[a];
					
					// set events
					image_node.removeEvents();
					image_node.addEvents(
					{
						'mousemove' : function(event)
						{
							_this.swap(this, total_image_nodes, event);
						}
					});
					
					/* OLD WAY
					image_node.onmousemove = function(event)
					{
						alert();
						 var event = new Event(event);
						_this.swap(this, total_image_nodes, event);
					}
					*/
				}
			}
		}
	},
	
	/**
	 * swap image
	 * @param	object	image_node
	 * @param	integer	total_image_nodes
	 * @param	void	event
	 * @return	void
	 */
	swap: function(image_node, total_image_nodes, event)
	{
		// get coordinates of image
		var image_node_coordinates	= image_node.getCoordinates();
		var image_node_width		= parseInt(image_node_coordinates.width);
		var image_node_height		= parseInt(image_node_coordinates.height);
		var image_node_pos_left		= parseInt(image_node_coordinates.left);
		var image_node_pos_top		= parseInt(image_node_coordinates.top);
		
		// get coordinates of mouse
		var mouse_pos_left			= event.client.x - image_node_pos_left;
		var mouse_pos_top			= event.client.y - image_node_pos_top;
		
		// set ratio
		var ratio_amount	= Math.floor(image_node_width / total_image_nodes);
		
		var current_image_index	= Math.floor(mouse_pos_left / ratio_amount);
		current_image_index		= current_image_index >= total_image_nodes ? total_image_nodes - 1 : current_image_index;
		
		if (current_image_index != this.active_image_index) 
		{
			var image_nodes		= $$('#'+this.root_node_id+' '+this.scrubbed_tag);
			
			// disable active image
			var active_image	= image_nodes[this.active_image_index];
			active_image.setStyle('display', 'none');
			
			// activate image
			var current_image	= image_nodes[current_image_index];
			current_image.setStyle('display', 'block');
			
			// set new active index
			this.active_image_index = current_image_index;
		}
	}
});