/* ##########################################################################
Copyright 2007 	Daniel Skinner
Contact: www.destiny-denied.co.uk/contact/

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
########################################################################### */

var ImageRoller = Class.create();
ImageRoller.prototype = {
	prefix: "image_roller_",
	loadCount: 0,
	imageCount: 0,
	initialize: function (c,options) {
		this.setOptions(options);
		this.outEvent=function(i){ return this.out.bindAsEventListener(this,i);}.bind(this);
		this.overEvent=function(i){ return this.over.bindAsEventListener(this,i);}.bind(this);
		this.imageCount = $A($$("img."+c)).length;
		$A($$("img."+c)).each(function(image) {
			Object.extend(image.parentNode.style,{backgroundRepeat:'no-repeat',cursor:'pointer',cursor:'hand',display:'block',width:image.width+'px',height:image.height+'px'});
			var temp={};
			if (image.parentNode.style && image.parentNode.style.backgroundImage) {
  		  var re = new RegExp("[(](.*)[)]");
  		  temp.src = re.exec(image.parentNode.style.backgroundImage)[1];
  			temp.ele=image;
  			var rollImage = new Image();
  			Event.observe(rollImage,'load',this.applyBehaviours.bindAsEventListener(this,temp,rollImage));	
  			rollImage.src=temp.src;	
  		} else {
  		  this.imageCount--;
  		}
		}.bind(this));	
	},
	//Private Initialisation
	setOptions: function(options) {
		this.options = Object.extend({
      onComplete:function(){},
      duration:0.1
    },(options || {}));
	},
	applyBehaviours: function(e,temp,rollImage) {
	  //apply event handling
		Event.observe(temp.ele, 'mouseover', this.overEvent(temp));
		Event.observe(temp.ele, 'mouseout', this.outEvent(temp));
		//add to the loaded image count
		this.loadCount++;
		//check if this was the last loaded image
		if (this.loadCount == this.imageCount) this.options.onComplete();
	},
  out: function(e,temp) {
			new Effect.Opacity(temp.ele,{duration:this.options.duration, from:0.0, to: 1.0,queue:{position:'end',scope:'sc'+temp.src,limit:2}});  
			Event.stop(e);
  },
  over: function(e,temp) {
			new Effect.Opacity(temp.ele,{duration:this.options.duration, from:1.0, to:0.0,queue:{position:'end',scope:'sc1'+temp.src,limit:2}});   
			Event.stop(e);
  }
}
