var photos = [];
var photosCount = 0;
var currentPhoto = 0;

function changePhoto( offset, jump ) {
  if ( offset != 0) {
    currentPhoto += offset;
    if ( currentPhoto < 0 )
      currentPhoto += photosCount;
    else if (currentPhoto >= photosCount)
      currentPhoto -= photosCount;
  } else {
    currentPhoto = jump;
  }
  $('.gallery-full').attr('src', $(photos[currentPhoto]).parent('a').attr("href"));
  $('.gallery-photo span.title').text($(photos[currentPhoto]).attr("title"));
}
function initGallery() {
  $('.gallery .photo').each(function() { photos.push(this); });
  photosCount = photos.length;
  if (photosCount) {
    currentPhoto = 0;
    $(photos[currentPhoto]).show();
    $('.gallery-photo .prev').click(function() { changePhoto(-1); return false; });
    $('.gallery-photo .next').click(function() { changePhoto(+1); return false; });
    $('.gallery a').click(function () { changePhoto(0, parseInt($(this).attr('rel').replace('photo-', ''))); return false; });
  }
}

$(document).ready( initGallery );
