var Site = {};

var Carousel = new Class({
	Implements: [Events, Options],
	
	options: {
		slideSelector: ".item",
		activeClass: "carousel_active",
		interval: 3000,
		stopOnEnter: true,
		startFrame: 0
	},
	
	initialize: function(el, nav, opts) {
		this.setOptions(opts);	
		
		this.parent = el;
		this.nav = new Element("ul").inject(nav || new Element("div"));
		this.navItems = [];
		
		this.nextBtn = $("carousel_next").addEvent("click", function() {
			this.next();
		}.bind(this));
		this.prevBtn = $("carousel_previous").addEvent("click", function() {
			this.prev();
		}.bind(this));
	
		this.slides = this.parent.getElements(this.options.slideSelector);
		
		var len = this.slides.length;
		this.slides.each(function(el, i) {
			var img = el.getElement("img");
			
			el.setStyles({
				background: "url(" + img.get("src") + ") no-repeat left top",
				left: 0,
				position: "absolute",
				top: 0,
				zIndex: len - i
			}).set("opacity", (this.options.startFrame == i) ? 1 : 0);
			
			img.destroy();
			
			var li = new Element("li", {
				html: "<a href='javascript:void(0);'>" + (i + 1) + "</a>",
				"class": (this.options.startFrame == i) ? this.options.activeClass : "",
				events: {
					"click": function() {
						this.showFrame(i);
					}.bind(this)
				}
			});
			
			this.navItems.push(li);
			this.nav.adopt(li);
			
		}, this);
		
		this.curr = this.options.startFrame;
		this.timer = this.next.periodical(this.options.interval, this);
		
		this.parent.addEvents({
			"mouseenter": function() {
				if (this.options.stopOnEnter) this.pause();				
				this.fireEvent("onEnter");
			}.bind(this),
			"mouseleave": function() {
				if (this.options.stopOnEnter) this.resume();				
				this.fireEvent("onExit");
			}.bind(this)			
		});
	},
	
	showFrame: function(index) {
		if (this.curr == index) return;
		this.slides[this.curr].fade("out");
		this.navItems[this.curr].removeClass(this.options.activeClass);
		
		this.slides[index].fade("in");
		this.navItems[index].addClass(this.options.activeClass);
		
		this.curr = index;
	},
	
	next: function() {
		var next = (this.curr + 1 > this.slides.length - 1) ? 0 : this.curr + 1;
		this.showFrame(next);
	},
	
	prev: function() {
		var prev = (this.curr - 1 < 0) ? this.slides.length - 1 : this.curr - 1;
		this.showFrame(prev);
	},
	
	pause: function() {
		$clear(this.timer);
	},
	
	resume: function() {
		this.timer = this.next.periodical(this.options.interval, this);
	}

});
