if(typeof(mtbanners) == "undefined") mtbanners = {};


mtbanners.createUniqueId = function createUniqueId(prefix, suffix) {
	var id = prefix + (new Date().getTime()) + suffix;
	while(document.getElementById(id) != null) {
		id = prefix + (new Date().getTime()) + suffix;
	}
	return id;
};

// Create a banner matching the default markup for
// the given image data. If an `onload` function is
// supplied, it will be attached to the img tag's
// `onload` event.
mtbanners.createDefaultBanner = function createDefaultBanner(data, onload) {
	var banner = document.createElement('div');
	banner.className = 'mtbanner';

	var imageMap = null;
	var imgContainer = banner;
	if (data.hotspot_href) {
		if (data.hotspot_shape == '') {
			a = document.createElement('a');
			a.href = data.hotspot_href;
			banner.appendChild(a);
			imgContainer = a;
		} else if (data.hotspot_shape != 'none') {
			imageMap = document.createElement('map');
			imageMap.name = mtbanners.createUniqueId('mtbanners', '-map');
			var area = document.createElement('area');
			area.shape = data.hotspot_shape;
			area.coords = data.hotspot_coords;
			area.href = data.hotspot_href;
			area.alt = data.hotspot_alt;
			imageMap.appendChild(area);
			banner.appendChild(imageMap);
		}
	}

	var img = document.createElement('img');
	img.width = data.width;
	img.height = data.height;
	img.className = 'mtbanner-image';
	if(imageMap) {
		img.useMap = '#' + imageMap.name;
	}
	if(onload) {
		if(img.addEventListener) {
			img.addEventListener("load", onload, false);
		} else if(img.attachEvent) {
			img.attachEvent("onload", onload);
		}
	}
	img.src = data.image_url;
        img.alt = data.alt_text;
	imgContainer.appendChild(img);

	if(data.copy) {
		var copy = document.createElement('div');
		copy.className = 'mtbanner-copy';
		copy.innerHTML = data.copy;
		banner.appendChild(copy);
	}
	return banner;
};


mtbanners.createCycleBanner = function(containerId, config, images) {
	new mtbanners.CycleBannerController(containerId, config, images);
};


mtbanners.CycleBannerController = function CycleBannerController(containerId, config, images) {
	if(images.length == 0) return;

	this.containerId = containerId;
	this.config = config;
	this.width = images[0].width;
	this.height = images[0].height;

	var ready = []; // Banners which are loaded;
	var banners = [];

	if(config.random_order) {
		var shuffledImages = [];
		while(images.length > 0) {
			var index = Math.floor(Math.random() * images.length);
			shuffledImages.push(images[index]);
			images.splice(index, 1);
		}
		images = shuffledImages;
	}

	if(config.display_count > 0 && config.display_count < images.length) {
		images.splice(config.display_count, images.length - config.display_count);
	}

	// Create the banners, and mark each as ready when its images have loaded.
	for(var i = 0; i < images.length; i++) {
		ready[i] = false;
		banners[i] = mtbanners.createDefaultBanner(
			images[i],
			(function(j) {
				return function() {
					ready[j] = true;
				};
			})(i)
		);
	}

	this.images = images;
	this.ready = ready;
	this.banners = banners;
	if(config.random_start) {
		this.setBanner(Math.floor(Math.random() * images.length), false);
	} else {
		this.setBanner(0, false);
	}

	this.startCycling();
};


mtbanners.CycleBannerController.prototype.startCycling = function startCycling() {
	if(this.interval) return;

	var self = this;
	var boundNextBanner = function() {
		self.nextBanner();
	};
	window.setInterval(boundNextBanner,
		(this.config.display_duration + this.config.effect_duration) * 1000);
};


mtbanners.CycleBannerController.prototype.stopCycling = function stopCycling() {
	if(this.interval) {
		window.clearInterval(this.interval);
		this.interval = null;
	}
};


mtbanners.CycleBannerController.prototype.setBanner = function setBanner(index, animate) {
	if (index == this.currentIndex) return;
	this.currentIndex = index;

	var container = document.getElementById(this.containerId);
	if(container) {
		var existingBanner = container.firstChild;
		while(existingBanner && !(/\bmtbanner\b/).test(existingBanner.className)) {
			existingBanner = existingBanner.nextSibling;
		}

		if(existingBanner) {
			this.transition(existingBanner, this.banners[this.currentIndex], animate);
		}
	}
};


mtbanners.CycleBannerController.prototype.nextBanner = function nextBanner() {
	// Find the next ready banner

        if (this.banners.length != 1){
            var i = (this.currentIndex + 1) % this.banners.length;
	    while(i != this.currentIndex && !this.ready[i]) {
		    i = (i + 1) % this.banners.length;
	    }
	    this.setBanner(i, true);
        }

};


mtbanners.CycleBannerController.prototype.transition = function transition(existingBanner, newBanner, animate) {
	var transition = mtbanners.CycleBannerController.Transitions[this.config.effect];
	if (!transition) transition = mtbanners.CycleBannerController.Transitions.none;
	transition(this, existingBanner, newBanner, animate);
};


mtbanners.CycleBannerController.Transitions = {
	none: function replaceTransition(controller, existingBanner, newBanner, animate) {
		var container = existingBanner.parentNode;
		container.removeChild(existingBanner);
		container.appendChild(newBanner);
	},

	_generic: function _genericTransition(controller, existingBanner, newBanner, animate, update) {
		var container = existingBanner.parentNode;
		newBanner.style.position = 'absolute';
		newBanner.style.left = existingBanner.offsetLeft + "px";
		newBanner.style.top = existingBanner.offsetTop + "px";

		update(0);
		container.appendChild(newBanner);

		var start = new Date().getTime();
		var end = start + controller.config.effect_duration * 1000;
		if (end <= start || !animate) {
			update(1);
			newBanner.style.position = 'static';
			container.removeChild(existingBanner);
		} else {
			controller.effectInterval = setInterval(function() {
				var t = new Date().getTime();
				progress = Math.min((t - start) / (end - start), 1);
				update(progress);
				if (progress == 1) {
					newBanner.style.position = 'static';
					container.removeChild(existingBanner);
					clearInterval(controller.effectInterval);
					delete controller.effectInterval;
				}
			}, 30);
		}
	},


	fade: function fadeTransition(controller, existingBanner, newBanner, animate) {
		var setOpacity;
		if ('opacity' in newBanner.style) {
			setOpacity = function(opacity) {
				newBanner.style.opacity = opacity;
				if (opacity == 0) {
					newBanner.style.visibility = 'hidden';
				} else {
					newBanner.style.visibility = 'visible';
				}
			};
		} else if ('filter' in newBanner.style) {
			setOpacity = function(opacity) {
				if (opacity == 1) {
					newBanner.style.filter = '';
				} else {
					newBanner.style.filter = 'alpha(opacity=' + opacity * 100 + ')';
				}
				if (opacity == 0) {
					newBanner.style.visibility = 'hidden';
				} else {
					newBanner.style.visibility = 'visible';
				}
			};
		}

		mtbanners.CycleBannerController.Transitions._generic(controller, existingBanner, newBanner, animate, setOpacity);
	},


	slideInLeft: function slideInLeftTransition(controller, existingBanner, newBanner, animate) {
		var setSlide = function(amount) {
			newBanner.style.left = (existingBanner.offsetLeft + controller.width * (1 - amount)) + "px";
		};

		mtbanners.CycleBannerController.Transitions._generic(controller, existingBanner, newBanner, animate, setSlide);
	},


	slideInRight: function slideInRightTransition(controller, existingBanner, newBanner, animate) {
		var setSlide = function(amount) {
			newBanner.style.left = (existingBanner.offsetLeft - controller.width * (1 - amount)) + "px";
		};

		mtbanners.CycleBannerController.Transitions._generic(controller, existingBanner, newBanner, animate, setSlide);
	}
};
