YAHOO.namespace('rsii');
YAHOO.rsii.HeaderImage = function(container, options) {
	this.images = [ ];
	this.containerString = container;
	this.container = new YAHOO.util.Element(container);
	this.idx = null;
	this.inDuration = options.inDuration;
	this.outDuration = options.outDuration;
	this.images = options.images;
	this.totalImages = this.images.length;
		
	this.attrsIn = {
		opacity: {
			from: 0,
			  to: 1
		}
	}
	
	this.attrsOut = {
		opacity: {
			from: 1,
			  to: 0
		}
	}
			
	this._rand = function()
	{	
		return Math.floor(Math.random() * this.totalImages);
	}
	
	this.randomImage = function()
	{
		this.idx = this._rand();
		this.run();
	}
	
	this.nextImage = function()
	{
		if (this.idx < this.totalImages - 1) {
			this.idx = this.idx + 1;
		} else {
			this.idx = 0;
		}
		this.run();
	}
	

	this.previousImage = function()
	{
		if (this.idx > 0) {
			this.idx = this.idx - 1;
		} else {
			this.idx = (this.totalImages - 1);
		}
		this.run();
	}
	
	this.run = function()
	{
		var sticky = YAHOO.util.Cookie.get('sticky');
		if (this.idx == null) {
			if (sticky == null) {
				this.idx = this._rand();
			} else {
				this.idx = parseInt(sticky);
			}
		}
		var c  = this.container;
		var i  = this.getImage();
		var a1 = new YAHOO.util.Anim(this.containerString, this.attrsOut, this.outDuration, YAHOO.util.Easing.easeOut);
		var a2 = new YAHOO.util.Anim(this.containerString, this.attrsIn, this.inDuration, YAHOO.util.Easing.easeIn);
		a1.onComplete.subscribe(function() {
			c.setStyle('background', 'black url(' + i + ') no-repeat');
			a2.animate();
		});
		a1.animate();
		
	}
	
	this.sticky = function()
	{
		YAHOO.util.Cookie.set("sticky", this.idx, {
			path: "/",
			domain: "randys.org"
		});
	}
	
	this.getImage = function()
	{
		var img = new Image();
			img.src = this.images[this.idx];
		return img.src;
	}
	
	// return this;
}

var options = {
	totalImages: 28,
	imagePath: '/wp-content/themes/rsii/images/headers/',
	imageExtension: '.jpg',
	inDuration: 1,
	outDuration: 1,
	images: rsii_images
}
var header = new YAHOO.rsii.HeaderImage('header-image', options);
var stikcy = YAHOO.util.Cookie.get("stikcy");
YAHOO.util.Event.onAvailable('header-image', function(ev){
	header.run();
});
var intId = null;
if (null != stikcy) {
	intId = setInterval("header.randomImage()", 120000); // every 2 minutes
}

YAHOO.util.Event.addListener('next-image-button', 'click', function(ev) {
	if (null != intId) {
		clearInterval(intId);
	}
	header.nextImage();
});
YAHOO.util.Event.addListener('previous-image-button', 'click', function(ev) {
	if (null != intId) {
		clearInterval(intId);
	}
	header.previousImage();
});

YAHOO.util.Event.addListener('sticky-image-button', 'click', function(ev) {
	if (null != intId) {
		clearInterval(intId);
	}
	header.sticky();
});
