/*
*  site_util
*
*  Created by John Hunter <john@johnhunter.info> on 2007-10-22
*  Licence CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*  Modified for hardcoded zoomify JH: 08-01-06
*  
*/

Event.observe(window, 'load', function () {
	if ($('viewer')) {
		slideshow.init('viewer', 4.0, 2.0);
		slideshow.parse('viewer-data');
		slideshow.start();
	}

	if ($('image-carousel')) {
		imageCarousel.init('image-carousel','carousel-info','carousel-prev','carousel-next');
		imageCarousel.parse('image-carousel-data');
	}
	
	if ($('zoom-display')) {
		imageZoom.init('zoom-display', 'zoom-viewer', 'zoom-control-show', 'content');
	}
	
	setBackLinks();
	
	if($('the-form')) {
		initLoadingIndicator('images/loading_ball.gif', 'submitting...');
		Event.observe('the-form', 'submit', function() {
			new Effect.Appear('overlay', { duration: 0.5, from: 0.0, to: 0.6 });
		});
	}
	
	var hasArchive = archiveContent.init(['archive-info', 'archive-info-related']);
	
});

// generic link template
var controlHtmlTmpl = new Template('<a href="\##{label}" onclick="#{methodcall}; return false">#{label}</a>');



/*
 * Create javascript back links
 */
function setBackLinks () {
	$$('span.back-link').each(function (i) {
		i.innerHTML = controlHtmlTmpl.evaluate({
			label: 'go back', 
			methodcall: 'window.history.back()'
		});
	});
}



function initLoadingIndicator (animationImage, messageText) {
	var arrayPageSize = getPageSize();
	var indicator = $('indicator');
	if (indicator) {
		indicator.appendChild(Builder.node('div', {id: 'overlay', style: 'display:none; width:'+ arrayPageSize[0] +'px; height:'+ arrayPageSize[1] +'px;'}, [
			Builder.node('div', {style: 'top: '+ (arrayPageSize[3] / 2 - 50) +'px'}, [
				Builder.node('img', {src: animationImage, width:'32px', height:'32px'}),
				Builder.node('p', messageText)
			])
		]));
		Event.observe(window, 'unload', function () {
			$$('#indicator div.overlay').invoke('hide');
		});
	}
};



/*
 * archiveContent -  loads hidden archive content into the right-land page column
 */
var archiveContent = {
	imageSrcs: [],
	orginal: {},
	itemIdPref: 'info-view-',
	
	init: function (containerIds) {
		// get the items
		this.items = [];
		var container,
			hasContainer;
		for (var i = 0; i < containerIds.length; i++) {	
			container = $(containerIds[i]);
			if (container) {
				hasContainer = true;
				this.items = this.items.concat(container.getElementsBySelector('li'));
			}
		}
		if (!hasContainer) return false;
		
		// parse the links
		var link;
		for (var i = 0; i < this.items.length; i++) {
			this.items[i].id = this.itemIdPref + i;
			link = this.items[i].down('a');
			this.imageSrcs[i] = link.readAttribute('href');
			link.href = '#info-viewer';
			link.down('img').setAttribute('alt', 'See more information on this page');
			Event.observe(link, 'click', archiveContent.show);
		}
		
		//save original
		this.orginal = new ArchiveContent(
			$('info-viewer-image').readAttribute('src'),
			$('zoom-display').down('var.data').innerHTML,
			$('info-viewer-content').innerHTML
		);
		
		return true;
	},
	show: function (e) {
		var that = window.archiveContent;
		var item = Event.findElement(e, 'li');
		var index = item.id.substring(that.itemIdPref.length);
		
		// get the content
		var zoomData = item.down('var.data');
		zoomData = zoomData ? zoomData.innerHTML : '';
		that.display(new ArchiveContent(
			that.imageSrcs[index],
			zoomData,
			item.down('.content').innerHTML
		));
	},
	display: function (content) {
		// console.log("New content is %o",content );
		$('info-viewer-image').src = content.imageSrc;
		$('zoom-display').down('var.data').innerHTML = content.zoomFile;
		$('info-viewer-content').innerHTML = content.content;
		
		if (imageZoom) imageZoom.setup();
	}
};

// archive data class
function ArchiveContent (imageSrc, zoomFile, content) {
	this.imageSrc = imageSrc;
	this.zoomFile = zoomFile;
	this.content = content;
}



/*
 * imageZoom - load a flash movie over the top of the page
 */
var imageZoom = {
	so: null,
	launchControl: null,
	swfElementId: 'zoomifyViewer',
	
	init: function (containerId, viewerId, launchControlId, contentBoxId) {
		this.container = $(containerId) || null;
		this.viewerId = viewerId;
		this.control = $('zoom-control') || null;
		this.contentBox = $(contentBoxId);
		this.originalContentHeight = 0;
		this.launchControl = $(launchControlId);
		this.setup();
	},
	setup: function () {
		var zoomifyImagePath = String(this.container.down('var.data').innerHTML).strip();
		var swfPath = zoomifyImagePath + '.swf';
		// console.log('swf path is %s', swfPath)
		if (zoomifyImagePath) {
			this.so = new SWFObject(swfPath, this.swfElementId, "800", "660", "7", "#e0dccd");
			this.so.addVariable("flashVarText", "zoomifyImagePath=" + zoomifyImagePath + "&amp;zoomifySlider=0");
			this.so.addVariable("allowScriptAccess", "sameDomain");
			this.so.useExpressInstall('swfobject/expressinstall.swf');
			
			if (this.launchControl) {
				this.launchControl.update(controlHtmlTmpl.evaluate({
					label: 'Zoom into image', 
					methodcall: 'window.imageZoom.show()'
				}));
			}
			
			if (this.control) {
				this.control.update(controlHtmlTmpl.evaluate({
					label: 'Close zoom view', 
					methodcall: 'window.imageZoom.hide()'
				}));
			}
			this.originalContentHeight = this.contentBox.getHeight();
		}
		else {
			this.launchControl.update('&nbsp;');
		}
	},
	show: function (e) {
		// console.log('the so is %o', this.so);
		this.so.write(this.viewerId);
		this.container.show();
		var contentHeight = Math.max(this.originalContentHeight, this.container.getHeight());
		this.container.setStyle({height: contentHeight + 'px'});
		this.contentBox.setStyle({height: contentHeight + 'px'});
		if (e) { Event.stop(e); }
	},
	hide: function (e) {
		if (/msie 6/.test(navigator.userAgent.toLowerCase())) location.reload();
		
		this.container.hide();
		$(this.swfElementId).remove();
		this.contentBox.setStyle({height: this.originalContentHeight + 'px'});
		if (e) { Event.stop(e); }
	}
};



/*
 * imageCarousel - click through a list of images
 */
var imageCarousel = {
	init: function (containerId, infoId, prevId, nextId) {
		this.data = new Array();
		this.currentIndex = 0;
		this.datalength = 0;
		this.container = $(containerId);
		this.infoDisplay = $(infoId);
		this.imageTmpl = new Template('<img src="#{src}" alt="#{alt}" />');
		this.countTmpl = new Template('Image #{current} of #{total} <br>#{alt}');
		if (this.container) {
			Event.observe($(nextId).show(), 'click', this.showImageByOffset.bindAsEventListener(this, +1));
			Event.observe($(prevId).show(), 'click', this.showImageByOffset.bindAsEventListener(this, -1));
		}
	},
	parse: function (dataListId) {
		this.data = parseListData (dataListId);
		this.datalength = this.data.length;
		this.updateDisplay();
	},
	showImage: function (index) {
		index = getIndexInBounds (index, this.data.length);
		var item = this.data[index];
		if (item) {
			this.container.update(this.imageTmpl.evaluate({src:item.src, alt:item.title}));
			this.currentIndex = index;
			this.updateDisplay();
		}
	},
	updateDisplay: function () {
		var item = this.data[this.currentIndex];
		this.infoDisplay.update(this.countTmpl.evaluate({current: this.currentIndex + 1, total: this.datalength, alt: item.title}));
	},
	showImageByOffset: function (e, offset) { 
		this.showImage(this.currentIndex + offset);
		if (e) {
			Event.element(e).blur();    
			Event.stop(e);
		}
	}
};



/*
 * slideshow - an automoated image slideshow with fading transitions
 */
var slideshow = {
	init: function (containerId, displayTime, transitionTime) {
		this.data = new Array();
		this.currentIndex = 0;
		this.container = $(containerId);
		this.control = $('viewer-control');
		this.running = false;
		this.isTransitioning = false;
		this.displayTime = displayTime;
		this.transitionTime = transitionTime;
	},
	parse: function (dataListId) {
		this.data = parseListData (dataListId);
	},
	showSlide: function (index) {
		var index = getIndexInBounds (index, this.data.length);
		var item = this.data[index];
		if (item) {
			this.container.appendChild(Builder.node('img', { 
				id:'slide'+index, src:item.src, alt:item.title, style:'display: none', 'class': 'dynamic' 
			}));
			new Effect.Appear('slide'+index, { 
				duration: this.transitionTime, delay: this.displayTime, limit: 1,
				afterFinish: function(obj) {
					this.isTransitioning = false; 
					obj.element.previous().remove();
					slideshow.showNextSlide();
				}
			});
		}
		this.currentIndex = index;
		this.isTransitioning = true;
	},
	showSlideByOffset: function (offset) {
		offset = offset || 1;
		this.showSlide(this.currentIndex + offset);
	},
	showNextSlide: function () {
		if (this.running) {
			this.showSlide(this.currentIndex + 1);
		}
	},
	start: function () {
		this.running = true;
		if (this.control) {
			this.control.update(controlHtmlTmpl.evaluate({
				label: 'Stop animation', 
				methodcall: 'window.slideshow.stop()'
			}));
		}
		this.showNextSlide();
	},
	stop: function () { 
		this.running = false;
		if (this.control) {
			this.control.update(controlHtmlTmpl.evaluate({
				label: 'Start amimation', 
				methodcall: 'window.slideshow.start()'
			}));
		}
		if (this.isTransitioning) $('slide'+ this.currentIndex).remove();
		Effect.Queue.each(function(i) { i.cancel(); });
		this.isTransitioning = false;
	}
};


function parseListData (dataListId) {
	var dataObj = new Array();
	$(dataListId).getElementsBySelector('li a').each(function(i) {
		dataObj.push({ src: i.readAttribute('href'), title: i.innerHTML });
	});
	return dataObj;
}

function getIndexInBounds (index, listLength) {
	listLength--;
	if (index > listLength) index = 0;
	if (index < 0) index = listLength;
	return index;
}

// Core code from ppk - quirksmode.com
// Edit for Firefox by pHaez for Lightbox
function getPageSize () {
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}

