(function(){
	
	$ = window.jQuery;
	
	var gallery = {
		
		init: function(){
			
			if($("#gallery").length < 1){
				this.forceQuit();
				return false;
			}
			
			$.ajax({
			  type: "GET",
			  url: "js/gallery.xml?"+Math.random(),
			  dataType: "xml",
			  success: this.parseGallery,
			  error: this.forceQuit
			});
			
		},
		
		forceQuit: function(){
			
			$("#gallery").remove();
			
		},
		
		parseGallery: function(xml){
			
			ul = $("ul.gallery")	
			
			photos = $("gallery > photo", xml);
			count = photos.length
			
			n = 0;
			
			for(var idx in photos){
				
				if(typeof photos[idx] != "object"){ count--; continue; }

				photo = $(photos[idx]);
				
				if($("image", photo).length != 1){ count--; continue; }
				
				image = $("image", photo).get(0).firstChild.nodeValue;
				
				ul.append("<li><img src=\""+image+"\" class=\"border no_margin\" width=\"100\" /></li>")
				
				$("li:last-child", ul).bind("click", {"photo": photo}, window.gallery.showImage);
				
				n++;
			}
			
			$("li:first-child", ul).trigger("click");
			
		},
		
		showImage: function(e){
						
			photo = e.data['photo'];
			
			image = $("image", photo).get(0).firstChild.nodeValue;
			title = $("title", photo).get(0).firstChild.nodeValue;
			comment = (!$("comment", photo).get(0).firstChild)? "&nbsp;" : $("comment", photo).get(0).firstChild.nodeValue;
			
			$("#gallery img").attr("src", image);
			$("#gallery .comment .gallery_title").html(title);
			$("#gallery .comment .gallery_comment").html(comment);
			
		}
			
		
	}
	
	$(document).ready(function(){
		
		window.gallery = gallery;
		
		gallery.init();
		
	});
	
})();