$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "galleries.php?postcard="+gallery_name,
        //data: {"postcard",gallery_name},
        dataType: "json",
        success: handleResponse
    });
});

function handleResponse (data) {
    $('#galleries').empty();
    for (i = 0; i < data.galleries.length; i++) {
        var new_gallery_li = $('<li></li>');
        $(new_gallery_li).html(data.galleries[i].title);
        $(new_gallery_li).click(function (e) {
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
            $(this).siblings().children().children().fadeOut('slow');
            $(this).siblings().children().fadeOut('slow');
            $('ul', this).show();
            $('ul li', this).fadeIn('slow');
        });
        $('#galleries').append(new_gallery_li);
        
        if (data.galleries[i].images.length > 0) {
            var new_gallery_ul = $('<ul></ul>');
            $(new_gallery_li).append(new_gallery_ul);
            
            for (j = 0; j < data.galleries[i].images.length; j++) {
                //alert(i + ' ' + j);
                var new_image_li = $('<li></li>');
                $(new_gallery_ul).append(new_image_li);
                var new_image_link = $('<a></a>');
                $(new_image_link).attr('href', data.galleries[i].images[j].url);
                $(new_image_link).attr('title', data.galleries[i].images[j].caption);
                var new_image = $('<img />');
                $(new_image).attr('src', './phpthumb/phpThumb.php' + '?src=.' + encodeURI(data.galleries[i].images[j].url) + '&zc=1&w=81&h=81');
                $(new_image).attr('alt', data.galleries[i].images[j].caption);
                $(new_image).attr('title', data.galleries[i].images[j].caption);
                $(new_image_li).append(new_image_link);
                $(new_image_link).append(new_image);
            }
            
            $(new_gallery_li).trigger('click');
        }
    }
    
    setupZoom();
}