Vertis.Values = {
  //albumWidth: 137,
  //albumHeight: 200,
  albumThreshold: 30
}

Vertis.Loader = function (obj, eventname, parentt, wrapperr, loadFirst) {

  var wrapper = $(wrapperr),  
      scrollParent = $(parentt);

  var that = this;
  that.blankImage = "/images/blank.gif";
  that.obj = $(obj);
  that.parentt = $(parentt);
  that.lastScroll = that.parentt.scrollTop();
  that.additionalRows = 2; // how many rows should be rendered after each scroll

  /**
   * size of list  
   */
  that.fullsize = {
    height: wrapper.height(),
    width: wrapper.width()
  };

  /**
   * size of img holder
   */
  that.imgHolder = {
    height: that.obj.outerHeight(true),
    width:  that.obj.outerWidth(true)
  };

  /**
   * size of box in which we can see images  
   */
  that.viewport = {
    height: scrollParent.height() - (wrapper.offset() !== null ? wrapper.offset().top : 0),
    width: wrapper.width()
  };

  
  that.threshold = that.imgHolder.height - Vertis.Values.albumThreshold;   // tells about the number of pixels after scroll event is taken into account

  scrollParent.bind(eventname, function (e) {
    that.eventHandler(e);
  });

  if (loadFirst) {
    that.loadVisible(); // load images which are visible on page load
  }
};

Vertis.Loader.prototype = {
  /**
   * Event handler, called when scroll occured 
   */
  eventHandler: function (e) {
    var currScroll = this.parentt.scrollTop();
    var diffScroll = currScroll - this.lastScroll;
    var images = this.obj.find('img[src*="' + this.blankImage + '"]');

    if(diffScroll > this.threshold) {
        // in case user wanted to drag the scroller very fast in his browser
        var howManyTimes = parseInt(diffScroll / this.threshold);
        var additionalRows = this.additionalRows * howManyTimes;
        var nrOfPhotosInRow = Math.floor(this.viewport.width / this.imgHolder.width);
        var nrOfPhotosToShow = additionalRows * nrOfPhotosInRow;

        for (var i = 0; i < nrOfPhotosToShow && i < images.length; i++) {
          var img = images.eq(i);
          img.attr('src', img.attr('src2'));
        }
        this.lastScroll = currScroll;
    }
  },

  /**
   * Load images which are visible on page load (first x images) 
   */
  loadVisible: function() {
    var nrOfPhotosInRow = Math.floor(this.viewport.width / this.imgHolder.width);
    var nrOfVisibleRows = Math.ceil(this.viewport.height / this.imgHolder.height);
    var nrOfPhotosToShow = nrOfPhotosInRow * nrOfVisibleRows;
    var images = this.obj.find('img[src*="' + this.blankImage + '"]');

    for (var i = 0; i < nrOfPhotosToShow && i < images.length; i++) {
      var img = images.eq(i);
      img.attr('src', img.attr('src2'));
    }
  }
};

