$( function() {
  $('.thumbnails > img').css({'cursor': 'pointer'});
  
  $('.thumbnails > img').click( function () {
    $('#overlay_image').empty();
    var h = ($('html').height() > $('body').height())? $('html').height() : $('body').height();
    $('#overlay,#overlay > .background').css({
      height: ($.clientCoords().height > h)? $.clientCoords().height : h, 
      width: '100%'
    });
    $('#overlay > .background').fadeTo(0, 0.9);
    $('#overlay').fadeIn(300);
    var src = $(this).attr('src');
    src = src.replace('thumbs', '');
    imageLoader(src, $(this).attr('alt'), 'overlay_image', $(this).offset().top);
    offset = $('body').scrollTop();
  });
    
  $('#overlay > .background').click( function () {
    $('#overlay').fadeOut(300);
  });

  $('#overlay_image_container > .close').click( function () {
    $('#overlay').fadeOut(300);

    return false;
  });
  if ($('.thumbnails > img').length < 2)
  {
    $('#overlay_image_container > .next,#overlay_image_container > .previous').fadeTo(0, 0.2).css({'cursor': 'default'});
    $('#overlay_image_container > .next,#overlay_image_container > .previous').click( function () {
      return false;
    });
  } else {

    $('#overlay_image_container > .next').click( function () {
      var new_elem = getNextImage($('#overlay_image > img').attr('src'));
      $('.img_description').empty();
      $('#overlay_image > img').fadeTo(500, 0, function () {
        $('#overlay_image > img').hide();
        imageLoader(new_elem.attr('src').replace('thumbs', ''), new_elem.attr('alt'), 'overlay_image');
      });
      return false;
    });

    $('#overlay_image_container > .previous').click( function () {
      var new_elem = getPrevImage($('#overlay_image > img').attr('src'));
      $('.img_description').empty();
      $('#overlay_image > img').fadeTo(500, 0, function () {
        $('#overlay_image > img').hide();
        imageLoader(new_elem.attr('src').replace('thumbs', ''), new_elem.attr('alt'), 'overlay_image');
      });

      return false;
    });
    
  }
  
  $.clientCoords = function() {
       var dimensions = {width: 0, height: 0};
       if (window.innerWidth && window.innerHeight) {
           dimensions.width = window.innerWidth;
           dimensions.height = window.innerHeight;
       } else if (document.documentElement) {
           dimensions.width = document.documentElement.offsetWidth;
           dimensions.height = document.documentElement.offsetHeight;
       }
       return dimensions;
  };
  
  $('#overlay_image_container,#overlay_image').css({
    width: 100,
    height: 100,
    left: ($.clientCoords().width-100)/2,
    top: ($.clientCoords().height-100)/2
  });
  
});

function getThumbClass (src) {
  var cl = src.substring(src.lastIndexOf('/')+1, src.indexOf('.'));
  return 'thumb_'+cl;
}

function getThumbParentClass (src) {
  var parent = $(".thumbnails > img."+getThumbClass(src))
                .parent('div.thumbnails').attr('class').split(' ');
  return parent[1];
}

function getNextImage (src) {
  var parent = getThumbParentClass(src);
  var new_elem = $("."+parent+" > img."+getThumbClass(src)).next();
  if (new_elem.attr('src') == undefined)
  {
    new_elem = $('.'+parent+' > img:first');
  }
  return new_elem;
}

function getPrevImage (src) {
  var parent = getThumbParentClass(src);
  var new_elem = $("."+parent+" > img."+getThumbClass(src)).prev();
  if (new_elem.attr('src') == undefined)
  {
    new_elem = $('.'+parent+' > img:last');
  }
  return new_elem;
}

function imageLoader(src, alt, div, pos) {
  var img = new Image();
  
  $(img)
    .load(function () {
      $(this).hide();
      var elem = $(this);
      var vOffset = ($('html').scrollTop() > $('body').scrollTop())? $('html').scrollTop() : $('body').scrollTop();
      var top = ($.clientCoords().height-img.height)/2-32+vOffset;
      var left = ($.clientCoords().width-img.width)/2-32+$('body').scrollLeft();

      $('#overlay_image_container').animate(
        { left: left,
          top: top,
          width: img.width+8,
          height: img.height+74
         },
        500, function () {}
        );
        $('#'+div).html(img);
        elem.fadeIn(500);
        $('#overlay_image').animate(
          { width: img.width+8,
            height: img.height+8 },
          500, function () {
            $('#'+div).append('<p class="img_description">'+urldecode(alt)+'</p>');
          }
        );
    })

    .error(function () {
    })

    .attr('src', src).attr('alt', alt);
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret); // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}
