$.extend(Function.prototype, {
    use: function() {
		var method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
		return function() {
			return method.apply(object, args.concat(Array.prototype.slice.call(arguments)));
		}
    },
    useEL: function() {
        var method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
        return function(event) {
            return method.apply(object, [event || window.event].concat(Array.prototype.slice.call(arguments)));
        }
    }
});

Rotator = function() {
	this.element = $(Rotator.element);
	
	this.slides = [];
	var self = this;
	$(Rotator.element+' li').each(function() {
		self.slides.push(this);
		$(this).css({'visibility': 'hidden'});
	});
	
	this.current = this.slides.length-1;
	this.next = this.current-1;
	
	$(this.slides[this.current]).css({'visibility': 'visible'});

	this.startTimer(Rotator.initDelay);
};
$.extend(Rotator.prototype, {
	advance: function(key) {
		$(this.slides[this.current]).fadeOut(Rotator.speed);
		$(this.slides[this.next]).css({'visibility': 'visible'}).fadeIn(Rotator.speed);
		
		if(key) {
			this.current = key;
		} else if(this.current == 0) {
			this.current = this.slides.length-1;
		} else {
			this.current--;
		}
		this.next = (this.current == 0) ? this.slides.length-1 : this.next-1;

		this.startTimer();
	},
	startTimer: function(delay) {
	    delay = (delay) ? delay : 0;
		this.timer = setTimeout(function() {
    	    setTimeout(function() {
        		var nextImage = this.slides[this.next];
        		if(nextImage) {
     				this.advance();
        		} else {
        			this.advance(this.slides.length-1);
        		}
		    }.use(this), delay)
		}.use(this), Rotator.delay);
	}
});
$.extend(Rotator, {
    initDelay: 2000,
	delay: 6000,
	speed: 1400,
	element: '#homeRotator',
	init: function() {
		Rotator.instance = new Rotator();
	}
});


$(document).ready(Rotator.init);