
var flexibleImages = new (function() {

  var self = this;
  var baseExpression = '';

  this.init = function(be) {

    baseExpression = be;

    $(baseExpression+' img').each(function(i) {
      var img = $(this);
      var iw = this.originalWidth = img.width();
      var ih = this.originalHeight = img.height();

      var cw = img.closest(baseExpression).width() - 1;

      if (this.originalWidth > cw) {
        img.css({
          'cursor': 'move',
          'width': cw+'px',
          'height': Math.round(ih * cw / iw)+'px'
        });
        img.bind('click', self.clickOne);
      }
    });

    $(window).bind('resize', function(e) {
      self.resizeAll();
    });

  }

  this.clickOne = function(e) {

    var img = $(e.target);

    // that clone for IE8
    if (img.hasClass('flexibleImages-clone')) {
      img = img.next();
    }

    var iw = img.width();
    var ih = img.height();

    var con = img.closest(baseExpression);
    var cw = con.width() - 1;

    //if (!img.hasClass('flexibleImages-clicked')) {
    if (iw > cw) {
      img.removeClass('flexibleImages-expanded').css({
        'position': '',
        'z-index': '',
        'width': cw+'px',
        'height': Math.round(ih * cw / iw)+'px'
      })
      // that clone for IE8
      .prev('.flexibleImages-clone').remove();

      con.css({
        'overflow-x': 'auto',
        'overflow-y': 'hidden'
      });
    } else {
      img.addClass('flexibleImages-expanded').css({
        'position': 'relative',
        'z-index': 100,
        'width': e.target.originalWidth+'px',
        'height': e.target.originalHeight+'px'
      })
      // that clone for IE8
      .clone(true).insertBefore(this).addClass('flexibleImages-clone').css({
        'position': 'absolute',
        'z-index': 99
      });

      con.css({
        'overflow-x': 'visible',
        'overflow-y': 'visible'
      });
    }
    //}

  }

  this.resizeAll = function() {

    $(baseExpression+' img').each(function(i) {
      var img = $(this);
      var cw = img.closest(baseExpression).width() - 1;

      if (this.originalWidth > cw) {
        if (!img.hasClass('flexibleImages-expanded')) {
          img.css({
            'cursor': 'move',
            'width': cw+'px',
            'height': Math.round(this.originalHeight * cw / this.originalWidth)+'px'
          })

          img.bind('click', self.clickOne);
        }
      } else {
        img.removeClass('flexibleImages-expanded').css({
          'cursor': '',
          'width': this.originalWidth+'px',
          'height': this.originalHeight+'px'
        })
        // that clone for IE8
        .prev('.flexibleImages-clone').remove();

        img.unbind('click', self.clickOne);
      }
    });

  }

});
