ImageCaptcha = Class.create({
  initialize: function() {
	
	this.image = this.down('.captiaImage');
	
	
	this.imageX = this.image.positionedOffset()[0];
	this.imageWidth = this.image.getHeight();
	this.fullWidth = this.image.getWidth();
	
	this.captchaField = this.down('.selection');
	
	this.hover = this.down('.hover');
	this.hover.style.width = this.imageWidth + 'px';
	this.hover.style.height = this.imageWidth + 'px';
	this.hover.absolutize();
	this.hover.observe('click', this.onClick.bind(this));
	
	
	
	
	this.selector = this.down('.selector');
	this.selector.style.width = this.imageWidth + 'px';
	this.selector.style.height = this.imageWidth + 'px';
	this.selector.absolutize();
	
	
	this.image.observe('mousemove', this.onMouseMove.bind(this));
	this.image.observe('click', this.onClick.bind(this));
	this.image.observe('mouseout', this.onMouseOut.bind(this));
	this.hover.observe('mouseout', this.onMouseOut.bind(this));
	this.hover.observe('click', this.onClick.bind(this));
	
  },
  onMouseMove: function(event){
	  this.imageX = this.image.positionedOffset()[0];
	  this.imageWidth = this.image.getHeight();
	  this.fullWidth = this.image.getWidth();
	  
	  var mx = event.pointerX() - this.image.cumulativeOffset()[0];
	  var idx = Math.floor(mx / this.imageWidth);
	 
	  if(((idx+1) * this.imageWidth) > this.fullWidth)
		  idx--;
	  
	 
	  this.hover.show();
	  this.hover.clonePosition(this.image);
	  this.hover.style.width = this.imageWidth + 'px';
	  var sx = this.imageX + (idx * this.imageWidth);
	  this.hover.style.left = sx + 'px';
  }
  ,
  onClick: function(event){
	  this.imageX = this.image.positionedOffset()[0];
	  this.imageWidth = this.image.getHeight();
	  this.fullWidth = this.image.getWidth();
	  
	  var mx = event.pointerX() - this.image.cumulativeOffset()[0];
	  var idx = Math.floor(mx / this.imageWidth);
	 
	  if(((idx+1) * this.imageWidth) > this.fullWidth)
		  idx--;
	  this.captchaField.value = idx;
	  this.adjustSelection();
  },
  onMouseOut: function(event){
	 if(event.relatedTarget != this.hover && event.relatedTarget != this.image && event.relatedTarget != this.selector)
		 this.hover.hide();
	  
  },
  adjustSelection: function(){
	  this.hover.hide();
	  var idx = this.captchaField.value;
	  this.selector.show();
	  this.selector.clonePosition(this.image);
	  this.selector.style.width = this.imageWidth + 'px';
	  var sx = this.imageX + (idx * this.imageWidth);
	  this.selector.style.left = sx + 'px';
  }
});

