var slideshow = function(options) {
	if (options === undefined) {
		options = new Object();
	}  
	if (options.slideWidth) {
		this.slideWidth = options.slideWidth;
	}
	if (options.prefix) {
		this.prefix = options.prefix;
	}
	this.name = options.name;
	var slides = $('.slide' + this.prefix);
	slides.css({'float' : 'left', 'width' : this.slideWidth});
	this.total = slides.length;	

	this.get('slidesContainer').css('overflow', 'hidden');
	this.get('slideInner').css({'width' : this.slideWidth * this.total});
	this.get('leftControl').bind('click', {parent : this, delta : -1}, this.onGo);
	this.get('rightControl').bind('click', {parent : this, delta : 1}, this.onGo);
	this.reset();
	if (options.autoplay) {
		this.autoplay();
	}
	this.timeout = null;
}

slideshow.prototype.position = 0;
slideshow.prototype.total = 0;
slideshow.prototype.slideWidth = 730;
slideshow.prototype.prefix = "";

slideshow.prototype.autoplay = function(instant) {
	if (this.timeout !== null) {
		clearTimeout(this.timeout);
	}
	this.timeout = setTimeout("slideshow.get('" + this.name + "').autoplay(true)", 6000);
	if (instant) {
		this.go(1);
	}
}

slideshow.prototype.onGo = function(event) {
	event.data.parent.go(event.data.delta);
}

slideshow.prototype.go = function(delta) {
	if (this.timeout !== null) {
		this.autoplay();
	}
	this.position += delta;
	if (this.position >= this.total) {
		this.position = 0;
	} else if (this.position < 0) {
		this.position = this.total - 1;
	}
  this.reset();
	this.get('slideInner').animate({'marginLeft' : this.slideWidth * -this.position});
}

slideshow.prototype.goTo = function(position) {	
	this.go(position - this.position);
}

slideshow.prototype.reset = function() {
	this.get('leftControl').css("display", this.position == 0 ? "none" : "");
	this.get('rightControl').css("display", this.position == this.total - 1 ? "none" : "");
	var el = this.get("handle" + this.position);
	if (el) {
		el.parent().find("a").removeClass("active");
		el.addClass("active");
	}
}

slideshow.prototype.get = function(id) {
	return $('#' + id + this.prefix);
}

slideshow.instances = {};

slideshow.get = function(name) {
	if (!slideshow.instances[name]) {
		var options = {"name" : name};
		if (name === "shops") {
			options.slideWidth = 960;
			options.prefix = "2";
		} else {
			options.autoplay = true;
		}
		slideshow.instances[name] = new slideshow(options);
	}
	return slideshow.instances[name];
}
