
$(document).ready(function() {

    $.address.init(function(event) {
/*
        if (event.value == '/') {
            var gallery_id = $('.nav_album:first').attr('id');
            $.address.value(gallery_id);
        }
*/ 
    });

    $.address.change(function(event) {  
         // do something depending on the event.value property, e.g.
        loadAlbum();
    });

/*
    $('.nav_album').click(function() {
        $.address.value('?album_id=' + $(this).attr('id') + '&photo_id=' +  $(this).attr('photo_id'));
    });
*/

    $('.nav_album a').click(function() {
        $.address.value('?album_id=' + $(this).closest('.nav_album').attr('id') + '&photo_id=1');
        return false;
    });


    $('#prev').click(function() {
        prevPhoto();
    });

    $('#next').click(function() {
        nextPhoto();
    });
});

function track(tracker) {
    var dir = location.pathname.substring(0,location.pathname.lastIndexOf('/'));
    Sundance.tracking.flashAction(dir, tracker, 1);
}

function getAlbumId() {
    var album_id = $.address.parameter('album_id');
    
    if (album_id == undefined) {
        album_id = $('.nav_album:first').attr('id');
    }

    return album_id;

}

function getPhotoId() {
    var album_id = getAlbumId();
    var photo_id = $.address.parameter('photo_id');
 
    if (photo_id == undefined) {
        photo_id = 1; 
    }

    return photo_id;
}

function nextPhoto() {
    var album_id = getAlbumId();
    var photo_id = parseInt(getPhotoId()) + 1;
    var album = $('#album_' + album_id);
  

    if (photo_id > album.children().length) {
        photo_id = 1;
    }     

    $.address.value('?album_id=' + album_id + '&photo_id=' + photo_id);


}

function prevPhoto() {
    var album_id = getAlbumId();
    var photo_id = getPhotoId() - 1;

    if (photo_id < 1) {
        var album = $('#album_' + album_id);
        photo_id = album.children().length;
    }

    $.address.value('?album_id=' + album_id + '&photo_id=' + photo_id);

}

function update_counter(active) {
    var total = active.parent().children().size();
    var current = active.prevAll().size() + 1;
    $('#photo_counter').text(current + ' of ' + total + ' photos');
}

function loadAlbum() {
    var album_id = getAlbumId();
    var photo_id = getPhotoId();
   
    // alert('load: ' + album_id + '/' + photo_id);
 
    album = $('#' + album_id); 


    $(".nav_album").removeClass('curr_album');
    $(album).addClass('curr_album');
    

    var active = $('.curr_photo');
    active.removeClass('curr_photo');
  
    var photo = $('#album_' + album_id + ' li:eq(' + (photo_id - 1) + ')');
    photo.addClass('curr_photo');


    active.hide();
    photo.fadeIn(500);
    track(photo.attr('tracker'))

    update_counter(photo);
}


