$(document).ready(function() {
	$.ajax({
		type: 'GET',
		url: 'http://www.shemenskifoundation.org/index.php/site/photos',
		dataType: ($.browser.msie) ? "text" : "xml", //if Browser is internet explorer, the datatype is text, otherwise xml.
		cache: false,
		data: '',
		success: getXML,
		complete: function() {
			
			$('#photos li:first').addClass('active');
			
			$('#next').click(function() {
				var current = $('li.active');
				var nextLi = $(current).next('li');
				
				//If there is no next item, go to the first.
				if (!nextLi.length) {
					nextLi = $('#photos li:first');
				}
				
				var title = $(nextLi).find('img').attr('alt');
				var caption = $(nextLi).find('img').attr('title');
				$('#title').text(title);
				$('#caption').text(caption);
				
				$(current).stop().animate({opacity: 0});
				$(current).removeClass('active');
				
				$(nextLi).stop().animate({opacity: 1});
				$(nextLi).addClass('active');
				
			});
			
			$('#prev').click(function() {
				var current = $('li.active');
				var prevLi = $(current).prev('li');
				
				//If there is no prev item, go to the last.
				if (!prevLi.length) {
					prevLi = $('#photos li:last');
				}
				
				var title = $(prevLi).find('img').attr('alt');
				var caption = $(prevLi).find('img').attr('title');
				$('#title').text(title);
				$('#caption').text(caption);
				
				$(current).stop().animate({opacity: 0});
				$(current).removeClass('active');
				
				$(prevLi).stop().animate({opacity: 1});
				$(prevLi).addClass('active');
				
			});
			
			getFirstTitles();
			
		}
	});
});

function getXML(xml) {
	//For IE, the xml has to be converted to an Active X object that IE understands.  Even IE8.
	if ($.browser.msie) {
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(xml);
		xml = xmlDoc;
	}
	 
	//Get info from the XML file and create the <li>'s for the photo gallery.
	$(xml).find('photo').each(function() {
		var caption = $(this).find('caption').text();
		var title = $(this).find('title').text();
		var imgSrc = $(this).find('imgSrc').text();
		
		var photo = '<li tabindex="100"><img src="' + imgSrc +'" title="' + caption + '" alt="' + title + '" /></li>';
		$(photo).appendTo('#photos');
	});
}

//Initialize the titles and captions.
function getFirstTitles() {
	//Fetches the first caption and title for the image.
	var title = $('.active').find('img').attr('alt');
	var caption = $('.active').find('img').attr('title');
	$('#title').text(title);
	$('#caption').text(caption);
}
