/** JMSlider - JoomlaMarket's Image Slider
* Version: 1.0
* Author: Jens Rieks 
* Copyright (C) 2008 Jaser Bratzadeh/JoomlaMarket. All rights reserved.
*/
if(!Fx.JM) {
	Fx.JM = {};
}
Fx.JM.Slider = function(elemName, cfg) {
	var self = this;
	var mode = cfg["mode"]
	var count = cfg["count"] * 1;
	var scroll = cfg["scroll"] * 1;
	var elem = $(elemName);
	var images = elem.getElements('img');
	//var user = eval(cfg['userTransition']);
	var transition = eval(cfg['transition']);
	var fx0 = new Fx.Scroll(elemName, {
		duration: 0,
		wheelStops: false
	});
	var fx = new Fx.Scroll(elemName, {
		duration: cfg['transDelay']*1,
		transition: transition,
		wheelStops: false
	});
	var ilen = images.length;
	var icount = ilen/2;
	//var mod = icount - count + 1;
	var img = 0;
	if(scroll > 0) {
		img = 0;
	} else if(mode=="reverse") {
		img = icount-count;
	} else {
		img = icount;
	}
	
	this.nextImage = function () {
		img += scroll;
		// allow scroll to be negative:
		if(img < 0) {
			img += icount * Math.ceil(-img / icount);
		}
		if(mode == "start") {
			if(scroll > 0 ) {
				img %= icount - count + 1;
			}
		} else if(mode == "reverse") {
			if((scroll < 0 && img == 0) || (scroll > 0 && img == icount-count)) {
				scroll *= -1;
			}
			img += 10*ilen;
			img %= ilen;
		} else {
			img %= ilen;
		}
		fx.toElement(images[img]).chain(
			function(){
				if(mode == "endless") {
					if(scroll > 0 && img >= icount) {
						img -= icount;
						fx0.toElement(images[img]);
					} else if(scroll < 0 && img <= (count)) {
						img += icount;
						fx0.toElement(images[img]);
					}
				}
				if(mode == "start") {
					if(scroll < 0 && img <= count) {
						img += icount;
						fx0.toElement(images[img]);
					}
				}
				self.start();
			}
		);
	}
	this.timeout = function () {
		this.nextImage();
	}
	this.timer = null;
	this.stop = function () {
		if(this.timer != null) {
			$clear(this.timer);
			this.timer = null;
		}
	}
	this.start = function () {
		self.stop();
		self.timer = self.timeout.delay(cfg.nextDelay, self);
	}
	fx0.toElement(images[img]);
	this.start.delay(cfg['initialDelay']);
	return this;
};

