window.addEvent("domready",function(){
	var albums = $$(".album");
	for( var i = 0; i < albums.length; i++ )
	{
		albums[i].addEvent("click",function(){
			closeAlbums();
			$("album_body_" + this.getAttribute("albumid")).setStyle("display","block");
			clearElement($("album_body_" + this.getAttribute("albumid")));
			
			var loading = new Element("img");
			loading.src = "images/loading.gif";
			$("album_body_" + this.getAttribute("albumid")).appendChild(loading);
			
			loadImages(this.getAttribute("albumid"));
			
		});
	}
	
});

function closeAlbums()
{
	var albums = $$(".album");
	for( var i = 0; i < albums.length; i++ )
	{
		$("album_body_" + albums[i].getAttribute("albumid")).setStyle("display","none");
	}
}

function clearElement(element)
{
	while( element.firstChild != null )
	{
		element.removeChild(element.firstChild);
	}
}

function loadImages(albumId)
{
	var request = new Request.JSON({
		url: $("photoalbumholder").getAttribute("jsonentryurl"),
		onSuccess: function(jsonObject){
			if( jsonObject.result != "OK" )
			{
				alert("loadImages returned " + jsonObject.result);
			}
			else
			{
				renderImages(albumId,jsonObject.images);
			}
		},
		onFailure: function(instance){
			alert("loadImages onFailure");
		},
		onException: function(headerName,value){
			alert("loadImages onException");
		}
	});
	request.instance = this;

	var sendArg = new Object();
	sendArg.method = "loadImages";
	sendArg.albumId = albumId;
	request.send("JSONData=" + JSON.encode(sendArg));
}

function renderImages(albumId,images)
{
	clearElement($("album_body_" + albumId));
	for( var i = 0; i < images.length; i++ )
	{	
		var photo = new Element("a");
		photo.addClass("photo");
		photo.href = images[i][4];
		photo.setAttribute("title",images[i][2]);
		photo.setAttribute("rel","milkbox[gall1]");
		
		var thumbContainer = new Element("div");
		thumbContainer.addClass("imagecontainer");
		photo.appendChild(thumbContainer);
		
		var thumb = new Element("img");
		thumb.src = images[i][3];
		thumbContainer.appendChild(thumb);

		$("album_body_" + albumId).appendChild(photo);
		
		if( (i+1) % 5 == 0 )
		{
			var clearer = new Element("div");
			clearer.addClass("clear");
			$("album_body_" + albumId).appendChild(clearer);
		}
	}
	//milkbox.reloadGalleries();
	milkbox = new Milkbox();
}