// Finds the gallery entry with the specified thumbnail
function findGalleryAnchor(id) {   
  var list;           

  list = document.getElementById('gallery');
  if (list == null) return; 

  for (var i = 0; i < list.children.length; i++) {   
    a = list.children[i].firstElementChild;
    if (a == null) continue;     
    
    img = a.firstElementChild;
    if (img == null) continue;    

    if (img.name == id)    
      return a;      
  }
}

var galleryList;

function initGallery(parent) {
	var mainblock;
	var dd;
	
	mainblock = document.getElementById(parent);
	if (mainblock == null) return;   
	dd = mainblock.children[1];
	if (dd == null) return;

	galleryList = document.createElement('ul');
	galleryList.setAttribute('class', 'tiles');
	galleryList.setAttribute('id', 'gallery');
	dd.appendChild(galleryList);
}

function galleryAdd(id, filename, desc) {
	if (galleryList == null) return;

	var li;
	var a;
	var img;
	var span;
	var text;

	li = document.createElement('li');
	galleryList.appendChild(li);

	a = document.createElement('a');
	a.setAttribute('href', './attachment/'+id+'/'+filename);
	a.setAttribute('title', desc);                          
	a.setAttribute('rel', 'lightbox[gallery]');                
	a.setAttribute('class', 'loading');
	li.appendChild(a);

	img = document.createElement('img');
	img.setAttribute('alt', desc);  
	img.setAttribute('src', './attachment/'+id+'/'+filename+'/minithumb');
	img.setAttribute('name', id);
	a.appendChild(img);

	span = document.createElement('span');
	span.setAttribute('class', 'title');  
	a.appendChild(span);

	text = document.createTextNode(desc);
	span.appendChild(text);
 
	// Preload real image	
	preloader = new Image();
	preloader.name = id;
	preloader.src = './attachment/'+id+'/'+filename+'/minithumb';
	
	preloader.onload = (function(){		
		var a;								
 		var img;    

		a = findGalleryAnchor(this.name);				
		if (a == null) return;
		
		img = a.firstElementChild;      				
		if (img == null) return;

		img.src = this.src;
		a.removeAttribute('class');		
	});
}
