var Slider = new Class({
	
	initialize: function(el,options){
		
		if (!$defined( $(el)))
			return;
			
		this.element = $(el);
	
		this.run = true;
		this.bind = false;
		
		this.index = 0;
		this.link = options.link;
		
		this.speed = options.speed;
		
		this.element.addClass('image_iterator_container');
		
		this.element.setStyles({
		    width: options.width,
		    height: options.height
		});
		
		
		this.element.addEvents({
			'mouseover': function(){
				this.run = false;
				if (this.index > 0)
					this.index = (--this.index % this.max);
			}.bind(this),
			'mouseout': function(){
				this.run = true;
				if (!this.bind)
					this.next();
			}.bind(this)
		});
		
		this.req = new Request.JSON({
			url: this.link, 
			onSuccess: function(response){
				if(response.success){
					if (!$defined(response.data))
						return;
					
					this.max = response.data.length;
					
					response.data.each(function(item, i){
					   	//alert(item.src); 
					    var elem1 = (new Element('div', {
							'id': this.element.id + '_image_' + i, 
							'class': 'images',
							'styles': {'background-image': 'url(' + escape(item.src) + ')', 'width': options.width, 'height': options.height},
							 events: {
						        click: function(){
									window.location = item.link;
						        }
							}

						})).inject(this.element);						
					 
					    (new Element('span',{
							'html' : item.name
						})).inject((new Element('span')).inject(elem1));
					 
					}.bind(this));
					
					this.next();
				}
			}.bind(this)
		}).post();
	},
	
	next : function(){
		this.bind = false;
		
		//this.element.getElements('div.images').fade(0);
		this.element.getElements('div.images').setStyle('display', 'none');
		this.index = (++this.index % this.max);
		
		if (!$defined($( this.element.id + '_image_' + this.index)))
			return;
		
		//$(this.element.id + '_image_' + this.index).fade(1);
		$(this.element.id + '_image_' + this.index).setStyle('display', 'inline');
		
		if (this.run){
			this.bind = true;
			this.next.bind(this).delay(this.speed * 1000);;
		}
	}
	
});

window.addEvent('domready', function() {
	var slider1 = new Slider('image-iterator',{link:'/template/image-iterator/doc/get.php', 'speed' : 5, 'width': 400, 'height': 350});
});

