// JavaScript Document

/* 
	Standard helper functions
*/
function isNull(a) {
    // Is the passed variable null (as opposed to 0 or an empty string '')?
	return typeof a == 'object' && !a;
}

/* 
	XML import functions
*/
function importXML(url) {
	// code for Mozilla, Safari, Opera, etc.
	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=xmlhttpChange;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}
	// code for IE
	else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		if (xmlhttp) {
			xmlhttp.onreadystatechange=xmlhttpChange;
			xmlhttp.open("GET",url,true);
			xmlhttp.send();
		}
	}
}

function xmlhttpChange() {
	// if xmlhttp shows "loaded"
	if (xmlhttp.readyState==4) {
		// if "OK"
		if (xmlhttp.status==200) {
			// Load the slideshow!
			xmlDoc = xmlhttp.responseXML;
			loadImages();
		}
	  	else {
			alert("Problem retrieving XML data")
		}
	}
}

/* 
	Basic slideshow functions
*/

var slides = new Array; // array for slides, obviously (elements are images)
var captions = new Array; // array for captions
var titles = new Array; // array for page titles
var credits = new Array; // array for image credits
var currentSlide = null; // global variable to keep track of the slide currently displayed
var crossFade = false; // we want the images to cross-fade on swap (or not)

function loadImages() {
	// This is the function that builds the slideshow from retrieved XML data.
	
	// Create image holder div (displays "loading..." message
	//var div = document.createElement('DIV');
	//div.setAttribute('id','slideholder');
	var div = document.getElementById('slideholder');
	
	var pageTitle = document.createElement('H2');
	var titleText = document.createTextNode('');
	pageTitle.appendChild(titleText);

	var caption = document.createElement('P');
	caption.setAttribute('id','caption');
	var captionText = document.createTextNode('');
	caption.appendChild(captionText);
	
	var credit = document.createElement('P');
	credit.setAttribute('id','credit');
	var creditText = document.createTextNode('');
	credit.appendChild(creditText);
	
	var writeroot = document.getElementById('slideshow');
	
	// Read XML!

	// First, get the slideshow metadata
	var admin = xmlDoc.getElementsByTagName('admin')[0];
	for( i=0; i<admin.childNodes.length; i++ ) {
		if (admin.childNodes[i].nodeType != 1) continue;
		varname = admin.childNodes[i].nodeName;
		value = admin.childNodes[i].firstChild.nodeValue;
		eval(varname + '="' + value + '"');
	}
	
	// Display placeholder
	div.style.height = minheight + 'px';
	//writeroot.appendChild(div);
		
	// Display caption
	var sidebar = document.getElementById('side');
	sidebar.insertBefore(credit,sidebar.firstChild);
	sidebar.insertBefore(caption,sidebar.firstChild);
	sidebar.insertBefore(pageTitle,sidebar.firstChild);

	// Show everything!
	var frame = document.getElementById('frame');
//	frame.style.display = 'block';

	// Set up controls
	var controls = document.createElement('DIV');
	controls.setAttribute('id','controls');
	
	var buttons = document.createElement('UL');
	buttons.setAttribute('id','buttons');
	
	var listItem = document.createElement('LI');
	var slideLink = document.createElement('A');
	slideLink.setAttribute('href','javascript:startAutoplay();');
	slideLink.setAttribute('id','autoplay');
	slideLink.setAttribute('class','button');
	linkText = document.createTextNode(autoplayStartText);
	slideLink.appendChild(linkText);
	listItem.appendChild(slideLink);
	buttons.appendChild(listItem);
	
	listItem = document.createElement('LI');
	slideLink = document.createElement('A');
	slideLink.setAttribute('href','javascript:advanceSlide(1);');
	listItem.setAttribute('id','nextButton');
	slideLink.setAttribute('class','button');
	linkText = document.createTextNode('Next');
	slideLink.appendChild(linkText);
	listItem.appendChild(slideLink);
	buttons.appendChild(listItem);
	
	listItem = document.createElement('LI');
	slideLink = document.createElement('A');
	slideLink.setAttribute('href','javascript:advanceSlide(-1);');
	listItem.setAttribute('id','prevButton');
	slideLink.setAttribute('class','button');
	linkText = document.createTextNode('Previous');
	slideLink.appendChild(linkText);
	listItem.appendChild(slideLink);
	buttons.appendChild(listItem);
	
	var	slider = document.getElementById('slider-container');
	slider.parentNode.removeChild(slider);
	buttons.appendChild(slider);
	
	controls.appendChild(buttons);
	
	var list = document.createElement('OL');
	list.setAttribute('id','slideNav');
	controls.appendChild(list);
	
	// Next, get the image metadata
	var x = xmlDoc.getElementsByTagName('image');
	for( i=0; i<x.length; i++ ) {
		// Load images
		var uri = x[i].getElementsByTagName('uri')[0].firstChild.nodeValue;
		var width = x[i].getElementsByTagName('width')[0].firstChild.nodeValue;
		var height = x[i].getElementsByTagName('height')[0].firstChild.nodeValue;
		if( height > minheight ) {
			// Resize image to fit slideshow container -- width can vary but height is fixed
			width = Math.ceil(width * (minheight/height));
			height = minheight;
		}
		slides[i] = new Image(width,height);
		slides[i].src = uri;
		captions[i] = x[i].getElementsByTagName('caption')[0].firstChild.nodeValue;
		titles[i] = x[i].getElementsByTagName('title')[0].firstChild.nodeValue;
		credits[i] = x[i].getElementsByTagName('credit')[0].firstChild.nodeValue;
				
		// Create slideshow navigation
		var listItem = document.createElement('LI');
		var slideLink = document.createElement('A');
		slideLink.setAttribute('href',"javascript:selectImage('" + i + "');");
		var linkText = document.createTextNode(i+1);
		slideLink.appendChild(linkText);
		listItem.appendChild(slideLink);
		list.appendChild(listItem);
	}
	
	// Create image
	slide = document.createElement('IMG');
	slide.setAttribute('id','slide');
	slide.setAttribute('width',width);
	slide.setAttribute('height',height);
	slide.onclick = function(){advanceSlide(1);};
		
	// Replace notice with image
	div.appendChild(slide);
	
	// Display navigation
	writeroot.appendChild(controls);
	
	selectImage(0);
}

function selectImage(i) {
	// Load a particular image into the slideshow
	var slide = document.getElementById('slide');
	var caption = document.getElementById('caption');
	var credit= document.getElementById('credit');
	var pageTitle = document.getElementById('frame').getElementsByTagName('h2')[0];

	// Enable/disable next/previous buttons
	var prevButton = document.getElementById('prevButton');
	var prevLink = prevButton.getElementsByTagName('A')[0];
	if( i == 0 ) {
		prevLink.setAttribute('href','javascript:void(0);');
		prevLink.className = 'disabled';
	}
	else {
		prevLink.setAttribute('href','javascript:advanceSlide(-1)');
		prevLink.className = '';
	}
	var nextButton = document.getElementById('nextButton');
	var nextLink = nextButton.getElementsByTagName('A')[0];
	if( i == slides.length - 1 ) {
		nextLink.setAttribute('href','void(0)');
		nextLink.className = 'disabled';
	}
	else {
		nextLink.setAttribute('href','javascript:advanceSlide(+1)');
		nextLink.className = '';
	}

	// For cross-fading only...
	if( crossFade == true && !isNull(currentSlide) ) {
		// Create new image
		slide.setAttribute('id','oldSlide');
		oldSlide = slide;
		slide = document.createElement('IMG');
		slide.setAttribute('id','slide');
	}

	// Swap image
	slide.style.visibility = 'hidden';
	slide.setAttribute('width',slides[i].width);
	slide.setAttribute('height',slides[i].height);
	//slide.style.paddingTop = ((minheight - slides[i].height)/2) + 'px';
	//slide.style.paddingBottom = ((minheight - slides[i].height)/2) + 'px';
	slide.style.paddingLeft = (((Number(maxwidth) + 0) - slides[i].width)/2) + 'px';
	slide.style.paddingRight = (((Number(maxwidth) + 0) - slides[i].width)/2) + 'px';
	slide.src = slides[i].src;
	slide.style.visibility = 'visible';
	
	// Display caption
	titleText = document.createTextNode(titles[i]);
	pageTitle.removeChild(pageTitle.childNodes[0]);
	pageTitle.appendChild(titleText);
	captionText = document.createTextNode(captions[i]);
	caption.removeChild(caption.childNodes[0]);
	caption.appendChild(captionText);
	if( credits[i].indexOf('http://') == 0 ) {
		creditText = document.createElement('A');
		creditText.href = credits[i];
		creditText.appendChild(document.createTextNode('Image credit'));
	}
	else {
		creditText = document.createTextNode(credits[i]);
	}
	credit.removeChild(credit.childNodes[0]);
	credit.appendChild(creditText);
	
	// Reset navigation 
	var list = document.getElementById('slideNav');
	var listItems = list.getElementsByTagName('li');
		
	// Remove link to selected slide; mark as selected
	var slideLink = listItems[i].getElementsByTagName('a')[0];
	var text = slideLink.childNodes[0];
	listItems[i].replaceChild(text,slideLink);
	listItems[i].setAttribute('class','selected');
	
	// Replace link to previously selected slide
	if( !isNull(currentSlide) ) {
		var slideLink = document.createElement('A');
		slideLink.setAttribute('href',"javascript:selectImage('" + currentSlide + "');");
		var linkText = listItems[currentSlide].childNodes[0];
		listItems[currentSlide].replaceChild(slideLink,linkText);
		slideLink.appendChild(linkText);
		listItems[currentSlide].setAttribute('class','');
	}
	
	// Add the new slide overtop of the old slide for crossfading
	if( crossFade == true && !isNull(currentSlide) ) {
		var slideholder = document.getElementById('slideholder');
		slideholder.appendChild(slide,oldSlide);
	}
	// Fade image in if the slideshow is starting up or crossfading is set
	if( crossFade == true || isNull(currentSlide) ) {
		initImage();
	}
	
	currentSlide = i;
}

/* 
	Autoplay functions
*/

var timerID = 0;

function setAutoplayInterval(t) {
	autoplayInterval = t;
}

function advanceSlide(increment) {
	var slide = document.getElementById('slide');
	currentSlide = parseInt(currentSlide) // make sure we treat the current slide number as an integer before adding 1
	if( currentSlide + increment >= slides.length || currentSlide + increment < 0 ) {
		//selectImage(0);
	}
	else {
		selectImage(currentSlide + increment);
	}
}

function showArrow() {
	
}

function nextImage() {
	// Load the next image in sequence via autoplay, and continues autoplay
	currentSlide = parseInt(currentSlide) // make sure we treat the current slide number as an integer before adding 1
	if( currentSlide + 1 >= slides.length ) {
		// If we're at the end, autoplay will start the show over
		selectImage(0);
	}
	else {
		advanceSlide(1);
	}
	// Set timer for next advance
	timerID  = setTimeout("nextImage()", autoplayInterval*1000);
}
function startAutoplay() {
	// Replace autoplay link
	a = document.getElementById('autoplay');
	newText = document.createTextNode(autoplayStopText);
	a.setAttribute('href','javascript:stopAutoplay();');
	a.replaceChild(newText,a.childNodes[0]);
	
	// Switch controls
	var nextButton = document.getElementById('nextButton');
	var prevButton = document.getElementById('prevButton');
	prevButton.style.display = 'none';
	nextButton.style.display = 'none';
	var slider = document.getElementById('slider-container');
	slider.style.display = 'block';

	// Autoplay
	nextImage();
}
function stopAutoplay() {
	// Unset timer
	if(timerID) {
		clearTimeout(timerID);
		timerID = 0;
	}
	
	// Replace autoplay link
	a = document.getElementById('autoplay');
	newText = document.createTextNode(autoplayStartText);
	a.setAttribute('href','javascript:startAutoplay();');
	a.replaceChild(newText,a.childNodes[0]);
	
	// Switch controls
	var nextButton = document.getElementById('nextButton');
	var prevButton = document.getElementById('prevButton');
	prevButton.style.display = 'block';
	nextButton.style.display = 'block';
	var slider = document.getElementById('slider-container');
	slider.style.display = 'none';
}

/* 
	Functions to fade in images
*/

document.write("<style type='text/css'>#slide {visibility:hidden;} </style>");

function initImage() {
	imageId = 'slide';
	var image = document.getElementById(imageId);
	var imageHolder = image.parentNode;
	setOpacity(image, 0);
	image.style.visibility = 'visible';
	fadeIn(imageId, 0);
}

function setOpacity(obj, opacity) {
	opacity = (opacity == 100) ? 99.999 : opacity;
  
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
  
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
  
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
  
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}
function fadeIn(objId,opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity <= 100) {
			setOpacity(obj, opacity);
			opacity += 2.5;
			//fadeIn(objId,opacity);
			window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 5);
		}
	}
}



