/*
 * ItemProvider.js
 *
 * @type Object
 * @author Thomas Monzel | Apparat-Hamburg
 * @description Auswählen von Items
 */

function ItemProvider() {
    this.items = [];
    this.count = function() {
        return this.items.length;
    }
       
    this.add = function(item) {
        this.items.push(item);
    }

    this.remove = function(index) {
        this.items.remove(index);
    }

    this.find = function(condition) {
        
    }

    this.get = function(index) {
        return this.items[index];
    }

    this.selectedIndex = null;
    this.selected = null;
    this.select = function(index) {
        this.selectedIndex = index;
        this.selected = this.items[index];
    }

    this.deselect = function() {
        this.selectedIndex = null;
        this.selected = null;
    }

    this.each = function(fn) {
        return $.each(this.items, fn);
    }

    this.getIndexByProperty = function(name, value) {
        var r = null;
         $.each(this.items, function(index, v) {
            if(v[name] == value) {
                r = index;
            }
        });
        return r;
    }

    this.hasItemProperty = function(name, value) {
        return this.getIndexByProperty(name, value) !== null ? true : false;
    }

    this.getItemByProperty = function(name, value) {
        return this.get(this.getIndexByProperty(name, value));
    }

    this.selectNext = function() {
        this.select(this.getNextIndex());
    }

    this.selectPrevious = function() {
        this.select(this.getPreviousIndex());
    }

    this.getNext = function() {
        return this.items[this.getNextIndex()];
    }

    this.getPrevious = function() {
        return this.items[this.getPreviousIndex()];
    }

    this.getNextIndex = function() {
        var index = this.selectedIndex+1;
        if(index > this.items.length-1) {
            index = 0;
        }
        return index;
    }

    this.getPreviousIndex = function() {
        var index = this.selectedIndex-1;
        if(index < 0) {
            index = this.items.length-1;
        }
        return index;
    }
}
