/**
 * jQuery script for the Ajax photo browsing.
 */
$(document).ready(function(){
    // define a helper function to update the DOM
    function update_dom(json){
        // update the current image
        $(".gallery-photo").fadeOut(250, function(){
            $(".gallery-photo img").attr('src', json.display_url).load(function(){
                if(this.complete){
                    $(".gallery-photo a").attr('href', json.image_url);
                    $(".gallery-photo .title").html(json.title);
                    $(".gallery-photo .caption").html(json.caption);
                    $(".gallery-photo").fadeIn(250);
                }
            });
        });

        // update the Prev / Next links and the image count
        $(".gallery-navigation .prev-next a:eq(0)").attr('href', json.previous_in_gallery);
        $(".gallery-navigation .prev-next a:eq(1)").attr('href', json.next_in_gallery);
        $(".gallery-navigation .count").html(json.order_in_gallery + '/' + json.gallery_count);
    }

    // define a helper function for Ajax/Json request
    function get_info(title_slug){
        $.getJSON("/photologue/photo_info/?photo_title_slug=" + title_slug, update_dom);
    }

    // define a handler for Prev / Next clicks
    function handler(){
        url_elements = $(this).attr('href').split('/');
        title_slug = url_elements[url_elements.length - 2];
        if(title_slug){
            get_info(title_slug);
        }
        return false;
    }


    // define the listener for the Prev button
    $(".gallery-navigation .prev-next a:eq(0)").click(handler);

    // define the listener for the Next button
    $(".gallery-navigation .prev-next a:eq(1)").click(handler);
});
