// Rollover - requires Mootools 1.2

var Rollover = new Class({
	options: {css:false, makeTransparent:false},	

	initialize: function(selector, suffix, options){
		this.setOptions(options);
		this.elements = $$(selector);
		this.suffix = suffix;
		this.objects = new Hash();
		this.imgs = [];
		this.elements.each(function(el){
			var obj = {
				element:'',
				active:true,
				offsrc:'',
				onsrc:'',
				currentState:'off'
			}
			obj.offsrc = this.options.css ? el.getStyle('background-image') : el.src;
			obj.onsrc = this.options.css && this.options.makeTransparent ? 'transparent' : this.swap(obj.offsrc);
			if(!el.id){ el.id = $random(1, 10000).toString(); }
			obj.element = el.id;
			this.objects.set(el.id, obj);
			if(this.options.css == true){
				el.addEvent('mouseover', this.cssmouseover.bindWithEvent(el, this.objects) );
				el.addEvent('mouseout', this.cssmouseout.bindWithEvent(el, this.objects));
			}else{
				el.addEvent('mouseover', this.mouseover.bindWithEvent(el, this.objects) );
				el.addEvent('mouseout', this.mouseout.bindWithEvent(el, this.objects));
			}
			this.preload.attempt(el.id, this );
		}, this);
	},

	preload: function(elid){
		var obj = this.objects.get(elid);
		var i = this.imgs.length;
		var newsrc;
		this.imgs[i] = new Image();
		if(this.options.css==true){
			newsrc = obj.onsrc.replace('url(', '');
			newsrc = newsrc.replace(')', '');
		}else{
			newsrc = obj.onsrc;
		}
		this.imgs[i].src = newsrc;
	},
	
	swap: function(str){
		return str.replace(/(\.jpg|\.jpeg|\.png|\.gif)/i, this.suffix + '$1');
	},
	
	mouseover:function(e, objs){
		var obj = objs.get(this.id);
		if(obj.active == true) this.src = obj.onsrc;
	},
	
	mouseout:function(e, objs){
		var obj = objs.get(this.id);
		if(obj.active == true) this.src = obj.offsrc;
	},
	
	cssmouseover:function(e, objs){
		var obj = objs.get(this.id);
		if(obj.active == true) this.setStyle('background-image', obj.onsrc);
	},
	
	cssmouseout:function(e, objs){
		var obj = objs.get(this.id);
		if(obj.active == true) this.setStyle('background-image', obj.offsrc);
	},
	
	disable: function(id){
		var obj = this.objects.get(id);
		obj.active = false;
	},
	
	enable: function(id){
		var obj = this.objects.get(id);
		obj.active = true;
	},
	
	swapImg: function(id, to){
		var obj = this.objects.get(id);
		var el = $(id);
		if(to == 'on'){
			el.src = obj.onsrc;
		}else{
			el.src = obj.offsrc;
		}
	}
	
	

});

Rollover.implement(new Options);
