function gallerySort(a, b) {
    if (a.name < b.name) {
	return 1;
    }
    return -1;
};

function imgSort(a, b) {
    if (a > b) {
	return 1;
    }
    return -1;
};

function loadImages(imageList, imgs, index) {
    if(index < imgs.length) {
	var url = imgs[index];
	var img = new Asset.image(url, {
	    onload: function() {
	    	img.inject(imageList);
	    	var imgWidth = img.width + img.getStyle("margin-left").toInt() + img.getStyle("margin-right").toInt();
	    	imageList.setStyle("width", imageList.getStyle("width").toInt() + imgWidth);
	    	refreshSize(imageList.getParent());
	    	loadImages(imageList, imgs, index + 1);
	    }
	});
    }
};

function refreshSize(content) {
    var children = content.getChildren();
    content.setStyle("width", children[0].offsetWidth + children[1].offsetWidth);
}

window.addEvent("domready", function() {
    
    // sort the galleries
    
    galleries.sort(gallerySort);
    
    // create the menu
    var menu = $("menu");    
    var imageList = $("imageList");
    var text = $("text");
    
    var loadTextRequest = new Request.HTML({
	update: text,
	onComplete: function() {
	    var display = (text.hasChild() || text.get("text").length > 0);
	    text.setStyle("display", display ? "block" : "none");
	    refreshSize(text.getParent()); 
    	}
    });
    
    var uri = new URI(window.location.href);
    var file = uri.get("file");
    var g = uri.getData("g");
    var found = false;
    
    for(var i=0; i<galleries.length; i++) {
    	var gallery = galleries[i];
    	gallery.imgs.sort(imgSort);
    	if(gallery.name.toLowerCase() == "home") {
    	    if(imageList && !$chk(g)) {
        	    loadTextRequest.get(gallery.text);
                imageList.setStyle("width", 0);
                loadImages(imageList, gallery.imgs, 0);
                found = true;
        	}
    	} else {
            var li = new Element("li");
            li.inject(menu, "top");
            var gName = gallery.name.slice(3);
            var urlLink = gName.replace(" ","");
            var item = new Element("a", {
                "href": "index.html?g=" + urlLink
            }).set("text", gName).inject(li);
            item.addEvent("click", function(event) {
                event.stop();
                window.location.href = this.href;
            });
            if(!found && imageList && $chk(g) && g == urlLink) {      
                loadTextRequest.get(gallery.text);
                imageList.setStyle("width", 0);
                loadImages(imageList, gallery.imgs, 0);
                found = true;
            }
    	}
    }
    
    if(imageList && !found && galleries.length > 0) {
    	var item = menu.getChildren()[0].getFirst();
    	window.location.href = item.href;
    }
    
});

