/**
 *  Flickr-slideshow for Marga van den Meydenberg
 */

var flickrSlideshow;

$(document).ready(function() {
	flickrSlideshow = new FlickrSlideshow();
});

function FlickrSlideshow() {
	var self = this;
	
	this.photos = [];
	this.titles = [];
	
	this.images = [];
	
	this.currentPhoto = 0;
	this.lastPhoto = 0;
	
	/* Show photo */
	//
	
	this.showCurrentPhoto = function() {
		var img;
		var title;
		
		if(!self.images[self.currentPhoto]) {
			img = document.createElement('img');
			img.src = self.photos[self.currentPhoto];
			self.images[self.currentPhoto] = img;
			
			title = self.titles[self.currentPhoto];
		}
		
		else {
			img = self.images[self.currentPhoto];
			title = self.titles[self.currentPhoto];
		}
		
//		alert(img.outerHTML + '\n' + title.outerHTML);
		
		$('.flickr-slideshow .photo').contents().remove();
		$('.flickr-slideshow .photo').append(img).append('<h2>' + title + '</h2>');
	}
	
	/* Show next photo */
	//
	
	this.showNextPhoto = function() {
		self.currentPhoto++;
		
		if(self.currentPhoto > self.lastPhoto) {
			self.currentPhoto = 0;
		}
		
		self.showCurrentPhoto();
		
		if(self.running) {
			self.timeout = setTimeout(self.showNextPhoto, 5000);
		}
	}
	
	/* Show previous photo */
	//
	
	this.showPreviousPhoto = function() {
		self.currentPhoto--;
		
		if(self.currentPhoto < 0) {
			self.currentPhoto = self.lastPhoto;
		}
		
		self.showCurrentPhoto();
	}
	
	/* Start slideshow */
	//
	
	this.startSlideshow = function() {
		self.running = true;
		
		self.timeout = setTimeout(self.showNextPhoto, 5000);
	}
	
	/* Stop slideshow */
	//
	
	this.stopSlideshow = function() {
		self.running = false;
		
		clearTimeout(self.timeout);
	}
	
	/* Toggle slideshow */
	//
	
	this.toggleSlideshow = function() {
		self.running ? self.stopSlideshow() : self.startSlideshow();
	}
	
	/* Constructor */
	//
	
	var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
	
	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 4) {
			var response = eval('(' + xmlHttp.responseText + ')');
			
			self.lastPhoto = response.photos.photo.length - 1;
			
			for(var n = 0; n < response.photos.photo.length; n++) {
				with(response.photos.photo[n]) {
					self.photos.push('http://farm' + farm + '.static.flickr.com/' + server + '/' + id + '_' + secret + '.jpg');
					self.titles.push(title);
				}
			}
			
			self.showCurrentPhoto();
			
			$('.flickr-slideshow .navigation .previous a').click(function() {
				self.showPreviousPhoto();
				return false;
			});
			
			$('.flickr-slideshow .navigation .next a').click(function() {
				self.showNextPhoto();
				return false;
			});
			
			$('.flickr-slideshow .navigation .slideshow a').click(function() {
				$(this.parentNode).toggleClass('running');
				self.toggleSlideshow();
				return false;
			});
		}
	};
	
	xmlHttp.open('GET', 'http://meydenberg.com/flickr-slideshow/get-photos.ajax.php', true);
	xmlHttp.send(null);
}

