/*global YAHOO, window, document, Event, Dom */

var MULTIPAGEBANNER = {
	data: {
		buttons:    [],
		banners:    [],
		bannerData: [],
		resources:  '/Content/MultipageBanner/HomePage/',
		fadeIn:     null,
		fadeOut:    null,
		root:       'MULTIPAGEBANNER-container',
		idx:        0,
		prevIdx:    -1,
		timer:      null,
		delay:      9000,
		loaded:     0,

		xml:
			'/xml/Generated/DOCG00001.xml' +
			'?Date=' + encodeURIComponent(new Date().toString())
	},

	immediate: function () {
		YAHOO.util.Connect.asyncRequest('GET', this.data.xml, {
			scope: this,
			failure: function () {
				if (window.console && window.console.log &&
				typeof window.console.log === 'function') {
					window.console.log('Unable to load xml file.');
				}
				return false;
			},
			success: function (o) {
				this.processXML(o.responseXML);
			}
		});
	},

	processXML: function (xml) {
		var x, bannerData = xml.getElementsByTagName('Banner');

		// Read the XML into an array
		this.data.bannerData = [];
		for (x = 0; x < bannerData.length; x++) {
			this.data.bannerData[x] = {
				image: bannerData[x].getAttribute("Filename"),
				link:  bannerData[x].getAttribute("Link")
			};

			// The banner immediately increments to the next idx, so make the
			// starting idx the last item on the list.
			this.data.idx = x;
		}

		this.data.loaded += 1;
		if (this.data.loaded === 2) {
			this.build();
		}
	},

	init: function () {
		this.data.root = document.getElementById(this.data.root);

		this.data.loaded += 1;
		if (this.data.loaded === 2) {
			this.build();
		}
	},

	build: function () {
		var node, root = this.data.root,
		resources = this.data.resources,
		scope = this;

		while (root.firstChild) {
			root.removeChild(root.firstChild);
		}

		node = root.appendChild(document.createElement('div'));
		node.id = 'MULTIPAGEBANNER-banner-wrapper';

		this.data.banners = this.data.bannerData.map(function (data, idx) {

			var wrapper = node.appendChild(document.createElement('div')),
			contents = wrapper.appendChild(document.createElement('div')),
			img = contents.appendChild(document.createElement('img')),
			map = contents.appendChild(document.createElement('map')),
			area = map.appendChild(document.createElement('area'));

			wrapper.id = 'MULTIPAGEBANNER-contents-wrapper-' + idx;
			wrapper.className = 'MULTIPAGEBANNER-banner-content-wrapper';
			wrapper.style.zIndex = '3';

			contents.id = 'MULTIPAGEBANNER-contents-' + idx;
			contents.className = 'MULTIPAGEBANNER-banner-content';

			img.useMap = '#map' + idx;
			img.src = '/doc/uploads/' + data.image;

			map.name = map.id = 'map' + idx;

			area.shape = 'rect';
			area.id = 'BANNER-area' + idx + 'A';
			area.coords = '34,204,201,246';
			area.href = data.link;

			area = map.appendChild(document.createElement('area'));
			area.shape = 'rect';
			area.id = 'BANNER-area' + idx + 'B';
			area.coords = '212,204,379,246';
			area.href = 'contact';

			return wrapper;
		});

		node = root.appendChild(document.createElement('div'));
		node.id = 'MULTIPAGEBANNER-buttons';
		node.style.zIndex = '8';

		node = node.appendChild(document.createElement('img'));
		node.className = 'MULTIPAGEBANNER-individual-button';
		node.id = 'MULTIPAGEBANNER-PageButton-0';
		node.style.zIndex = '8';
		node.src = resources + 'Multipage_Banner_Button_Selected.png';
		node.setAttribute('data-idx', '0');
		Event.addListener(node, 'click', this.doClick_Button, this, true);

		this.data.buttons.push(node);

		this.data.bannerData.slice(1).forEach(function (data, idx) {

			idx++;
			node = node.parentNode.appendChild(document.createElement('img'));
			node.className = 'MULTIPAGEBANNER-individual-button';
			node.id = 'MULTIPAGEBANNER-PageButton-' + idx;
			node.src = resources + 'Multipage_Banner_Button_Unselected.png';
			node.style.zIndex = '8';
			node.setAttribute('data-idx', idx.toString());

			Event.addListener(node, 'click',
				scope.doClick_Button, scope, true);

			scope.data.buttons.push(node);
		});


		this.data.banners[0].style.zIndex = '8';
		this.data.banners[this.data.banners.length - 1].style.zIndex = '7';

		this.data.fadeOut = new YAHOO.util.Anim(
			this.data.banners[this.data.banners.length - 1],
			{ opacity: { to: 0 } }, 1);

		this.data.fadeIn = new YAHOO.util.Anim(
			this.data.banners[0],
			{ opacity: { to: 1 } }, 1);

		this.data.prevIdx = 0;
		this.data.idx = 0;
		this.data.fadeIn.onStart.subscribe(this.swapBanners, this, true);
		this.data.fadeIn.onComplete.subscribe(this.reorderBanners, this, true);
		this.play();
	},

	swapBanners: function () {
		// Locate the next banner that we need.
		if (this.data.idx >= this.data.bannerData.length) {
			this.data.idx = 0;
		}

		var i,
		currentBanner = this.data.banners[this.data.idx],
		prevBanner = this.data.banners[this.data.prevIdx];

		for (i = 0; i < this.data.bannerData.length; i++) {
			this.data.banners[i].style.zIndex = 3;
		}

		currentBanner.style.zIndex = 6;
		prevBanner.style.zIndex = 7;

		this.data.fadeIn.setEl(currentBanner);
		this.data.fadeOut.setEl(prevBanner);

		this.data.prevIdx = this.data.idx;
	},

	reorderBanners: function () {
		var i,
		currentBanner = this.data.banners[this.data.idx];

		for (i = 0; i < this.data.bannerData.length; i++) {
			this.data.banners[i].style.zIndex = 3;
			Dom.setStyle(this.data.banners[i], 'opacity', 0);
		}

		currentBanner.style.zIndex = 6;
		Dom.setStyle(currentBanner, 'opacity', 1);
	},

	play: function () {
		window.clearTimeout(this.data.timer);
		this.data.timer = null;
		this.data.fadeIn.onComplete.unsubscribe(this.wait);
		this.data.fadeIn.onComplete.subscribe(this.wait, this, true);
		this.wait();
	},

	wait: function () {
		var scope = this;
		this.data.timer = window.setTimeout(function () {
			scope.data.idx++;
			scope.data.fadeIn.animate();
			scope.data.fadeOut.animate();
			scope.updateButtons();
		}, this.data.delay);
	},

	doClick_Button: function (e) {
		var img = Event.getTarget(e),
		idx = parseInt(img.getAttribute('data-idx'), 10);

		// If the timer is still going (i.e., we are in play mode)...
		if (this.data.timer !== null) {
			window.clearTimeout(this.data.timer);
			this.data.fadeIn.onComplete.unsubscribe(this.wait);
			this.data.timer = null;
		}

		if (this.data.idx === idx ||
		this.data.fadeIn.isAnimated() ||
		this.data.fadeOut.isAnimated()) {
			return;
		}
		this.data.idx = idx;

		this.data.fadeIn.animate();
		this.data.fadeOut.animate();
		this.updateButtons();
	},

	updateButtons: function () {

		var targetIdx = this.data.idx,
		path = this.data.resources;

		this.data.buttons.forEach(function (img, idx) {

			img.src =
			(idx === targetIdx) ?
			path + 'Multipage_Banner_Button_Selected.png' :
			path + 'Multipage_Banner_Button_Unselected.png';

		});

	}

};

MULTIPAGEBANNER.immediate();
Event.onDOMReady(MULTIPAGEBANNER.init, MULTIPAGEBANNER, true);

