/**
MlsPhotoSwitcher
A class for switching between Mls photos for a property.
*/
function MlsPhotoSwitcher(el, photos, onchangeCallback) {
	this.index = 0;
	this.el = $(el);
	this.photos = photos;
	this.onchangeCallback = onchangeCallback;
	this.loaded_photos = new Array(photos.length);
	this.loading = false;
	this.preload(0);
}
MlsPhotoSwitcher.prototype = {
	next: function() {
		if (!this.loading) {
			this.index++;
			if (this.index > this.photos.length-1)
				this.index = 0;
			this.preload(this.index);
		}
	},
	prev: function() {
		if (!this.loading) {
			this.index--;
			if (this.index < 0)
				this.index = this.photos.length-1;
			this.preload(this.index);
		}
	},
	load: function(index) {
		if (!this.loading) {
			if (index < 0) index = this.photos.length-1;
			else if (index > this.photos.length-1) index = 0;
			this.index = index;
			this.preload(this.index);
		}
	},
	preload: function(index) {
		if (index >= 0 && index < this.photos.length) {
			if (!this.loaded_photos[index]) {
				// not loaded yet so load it
				this.loading = true;
				this.el.addClassName('loading');
				var oImage = new Image;
				this.loaded_photos[index] = oImage;
				oImage.onload = function() { this.preloadComplete(this.index); }.bind(this);
				oImage.src = this.photos[this.index];
			} else {
				this.preloadComplete(index);
			}
		}
	},
	preloadComplete: function(index) {
		if (this.loaded_photos[index]) {
			this.loading = false;
			this.el.removeClassName('loading');
			this.el.src = this.loaded_photos[index].src;
			if (this.onchangeCallback)
				this.onchangeCallback(this.el.src);
		}
	}
}
