$(document).ready(function(){

  var openGallery = function(images){
    var index = 0;
    var lightBox = $("<div id=\"lightBox\"><div>" + (images.length > 1 ? "<a class=\"previous\" href=\"#\">←</a><span class=\"counter\">" + "1/" + images.length + "</span><a class=\"next\" href=\"#\">→</a>" : "") + 
    "<a class=\"close\" href=\"#\">X</a><img /></div></div>");

    $("body").css("overflow", "hidden");
    $(lightBox).css("top", $("body").scrollTop());

    var showImage = function(){
      var image = $(images[index]);
      $("img", lightBox).attr("src", image.attr("src"));
      $(".counter", lightBox).text((index + 1) + "/" + images.length);
      $("div", lightBox).height(image.height() + 40);
      $("div", lightBox).width(image.width());
    };
    var closeGallery = function(){
      $(lightBox).remove();
      $(document).unbind("keyup", checkKeyboardInput);
    };
    var showNext = function(){
      index = (index + 1) % images.length;
      showImage();
    };
    var showPrevious = function(){
      index = (index - 1) % images.length;
      if(index < 0){
        index = images.length - 1;
      }
      showImage();
    };

    $("a.next", lightBox).click(function(){
      showNext();
      return false;
    });
    $("a.previous", lightBox).click(function(){
      showPrevious();
      return false;
    });
    $("a.close", lightBox).click(function(){
      closeGallery();
      return false;
    });

    var checkKeyboardInput = function(e) {
      if(e.keyCode == 27){
        closeGallery();
      }
      if(e.keyCode == 39){
        showNext();
      }
      if(e.keyCode == 37){
        showPrevious();
      }
    };

    $(document).bind("keyup", checkKeyboardInput);

    $("body").append(lightBox);
    showImage(0);
  };

  $(".start .gallery").each(function(){
    $("img:gt(0)", this).hide();
    $("img:first", this).click(function(){
      var images = [this].concat($.makeArray($(this).siblings()));
      openGallery(images);
    });
  });

  $("a.oE").each(function(){
    var a = $(this);
    var oldHref = a.attr("href").split("|");
    var newHref = "";
    for(var s in oldHref){
      newHref += String.fromCharCode(parseInt(oldHref[s]) / 3);
    }
    a.attr("href", newHref);
  });

  $("a").each(function(){
    if($(this).text().length > 52){
      $(this).text($(this).text().substring(0, 50) + "…");
    }
  });


});
