$(function() {

    //get tag feed
    $.getJSON("data/tagcloud.php", function(data) {
        //create list for tag links
        $("<ul>").attr("id", "tagList").appendTo("#tagCloud");

        //create tags
        $.each(data.tags, function(i, val) {
            //create item
            var li = $("<li>");

            //create link
            $("<a>").text(val.tag)
                .attr({
                    title:"Photos tagged with \"" + val.tag + "\"",
                    href:"#"
                    })
                .click(function(e) {
                    var imagelist;

                    e.preventDefault();
                    $('#image-container a:all').remove();   // clears existing links
                    
                    // get image list in ajax request, load to image div, and lightbox
                    // synchronous json required
                    $.ajax({
                        type: 'GET',
                        url : "data/photos.php?searchby=tag&searchfor=" + val.tag,
                        dataType : 'json',
                        success: function(json) {
                            imagelist = json;
                        },
                        async:false
                    });

                    // run through image list and add links to the image-container
                    if (imagelist.photos.length > 0) {
                        var i = 0;
                        for (i=0; i<imagelist.photos.length; i++) {
                            var imageclass;
                            if (i==0) {
                                imageclass = 'lightbox lightbox-first';
                            } else {
                                imageclass = 'lightbox';
                            }
                            $("<a />")
                            .html('')
                            .attr('href', imagelist.photos[i].image )
                            .attr('class', imageclass)
                            .attr('title', imagelist.photos[i].title + '<br/><a href="' + imagelist.photos[i].source_url + '" target="_blank">NAA: A3560, ' + imagelist.photos[i].control_symbol + '</a>')

                            .appendTo("#image-container");
                        }
                    }

                    // add lightbox to each link element
                    $('a.lightbox').lightBox(); 
                    // trigger click event
                    $('a.lightbox-first').trigger('click');
                    // for some reason lightbox wants to show this div, so hide again
                    $('#image-container').hide();
                    return false;
                  })
                .appendTo(li);

            li.children().css("fontSize", (val.freq / 200 < 1) ? val.freq / 200 + 1 + "em": (val.freq / 200 > 2) ? "2em" : val.freq / 200 + "em");

            //add to list
            li.appendTo("#tagList");
        });
    });

});

