/*
 * LOOP.js
 * by Luca Bertaiola
 * 
 */

function Loop(_index, _maxIndex)
{
    
    // public
    
    this.next = function(_set) // _set default true
    {
        if(this._isOk())
        {
            var _set = (_set == false)? false : true;
            var _nextIndex = null;
            
            if(this.direction == 1)
            {
                // incremental
                _nextIndex = ((this.index + 1) > this.maxIndex)? 0 : this.index + 1;
            }
            else
            {
                // decremental
                _nextIndex = ((this.index - 1) < 0)? this.maxIndex : this.index - 1;
            }
            
            if(_set)
            {
                this.index = _nextIndex;
            }
            return _nextIndex;
        }
        return false;
    }
    
    this.last = function()
    {
        if(this._isOk())
        {
            if(this.direction == 1)
            {
                // incremental
                _lastIndex = ((this.index - 1) < 0)? this.maxIndex : this.index - 1;
            }
            else
            {
                // decremental
                _lastIndex = ((this.index + 1) > this.maxIndex)? 0 : this.index + 1;
            }
            return _lastIndex;
        }
        return false;
    };
    
    // private
    
    this._isOk = function()
    {
        if((isFinite(this.index) && isFinite(this.maxIndex)) && (this.index <= this.maxIndex))
        {
            return true;
        }
        
        return false;
    }
    
    this._setInt = function(_value)
    {
        _value = parseInt(_value);
        if(isNaN(_value))
        {
            return undefined;
        }
        return _value;
    }
    
    // vars
    
    this.index = this._setInt(_index);
    this.maxIndex = this._setInt(_maxIndex);
    this.direction = 1; // 0: decremental, 1: incremental
    
}
