/*!
 * jRoulette
 * Создаёт объект контролирующий цикличную горизонтальную прокрутку элементов.
  <div id="somename" style="overflow: hide;...">
    <ul id="somename_line" style="width: 50000px; position: absolute;...">
      <li>...</li>
      ...
    </ul>
    <a id="somename_prev" class="prev" href="#" style="float: left;..."><img src="images/somename-prev.png" alt="[<]" /></a>
    <a id="somename_next" class="next" href="#" style="float: right;..."><img src="images/somename-next.png" alt="[>]" /></a>
    <script type="text/javascript">roulette('somename', 1, 3);</script>
  </div>
 * Copyright 2010, evrone.ru
 * All rights reserved.
 **/

function roulette(target_id, e_move, e_view) {
  var _this = this;
  this.elements_position = 0;
  this.elements_move = e_move;
  this.elements_view = e_view;

  target_id = '#' + target_id;
  this._line = $(target_id + '_line')
  this._prev = $(target_id + '_prev');
  this._next = $(target_id + '_next');

  var _boxes = this._line.children();
  this.elements_count = _boxes.size();
  this.elements_width = _boxes.first().next().position().left;

  this.suction_prev = function() {
    var _last;
    for(var i = 1; i <= this.elements_move; i++ ) {
      _last = this._line.children().last();
      _last.insertBefore(this._line.children().first());
      this._line.css('left', this._line.position().left - this.elements_width);
    }
  }

  this.suction_next = function() {
    var _first;
    for( i = 1; i <= this.elements_move; i++ ) {
      _first = this._line.children().first();
      _first.insertAfter(this._line.children().last());
      this._line.css('left', this._line.position().left + this.elements_width);
    }
  }

  this._prev.click(function() {
    $(this).hide();
    var _pos = _this.elements_position - _this.elements_move;
    if (_pos < 0) _this.suction_prev(); else _this.elements_position = _pos;
    _this._line.animate({'left': '+=' + _this.elements_width * _this.elements_move}, 'slow', 'swing', function() {_this._prev.show();});
  });

  this._next.click(function() {
    $(this).hide();
    var _pos = _this.elements_position + _this.elements_move;
    if ((_pos + _this.elements_view) > _this.elements_count) _this.suction_next(); else _this.elements_position = _pos;
    _this._line.animate({'left': '-=' + _this.elements_width * _this.elements_move}, 'slow', 'swing', function() {_this._next.show();});
  });
}
