$(document).ready(function() {
  $('#large-image').click(function(){
    $('#large-image-div').fadeOut(500);
    $("#page-comments").show();
    setTimeout(500, function() { $('#large-image').attr('src', '../images/misc/1x1.gif') });
  });
  
  $('#gallery img').click(function(){
    var src = $(this).attr('src');
    var large = small_to_large(src);
    var title = $(this).attr('title');
    $("#large-image").attr('src', large);
    $("#desc-image").text(title);
    $(this).fadeOut(200);
    $(this).fadeIn(1);
    $(this).attr('border', '1px solid #fff');
    $("#large-image").load(function() {
      if ($(this).attr('src') == '../images/misc/1x1.gif')
        return;
      $("#large-image-div").fadeIn(500);
      $("#page-comments").hide();
    });
    next_image_button(next_image(this));
    $('html, body').animate( { scrollTop: 0 }, 'fast' );
  });

  load_comments();
  load_contact_form();

  like_url();
});

function like_url() {
  $('#fcbklk').attr('src', "http://www.facebook.com/plugins/like.php?href=" + document.location.href);
}

function small_to_large(str) {
  if (str == undefined) return str;
  return str.replace('/small/', '/large/');  
}

function next_image(img) {
  var current_img_idx = $("#gallery img").index(img);
  if (current_img_idx < 0) return undefined;
  var selector = "#gallery img:gt(" + current_img_idx + "):first"
  if ($(selector).attr('src') == undefined) return undefined;
  return $(selector);
}

function next_image_button(img) {
  text = (img == undefined) ? 'CLOSE' : 'NEXT';
  $('#next-image').text(text);
  $('#next-image').unbind('click');
  $('#next-image').click(function(){
    if (img == undefined) {
      $('#large-image').click();      
    } else {
      var src = small_to_large(img.attr('src'));
      var title = img.attr('title')
      $("#large-image").attr('src', src);
      $("#desc-image").text(title);
      next_image_button(next_image(img));
    }
  });
}


function load_comments() {
  comments_url = '../comments.php?page=' +
                  $.encoding.digests.hexSha1Str('' + document.location);
  $('#page-comments').load(comments_url);
}

function load_contact_form() {
  $('#page-contact').load('../contact.php');
}
