﻿function ListModel(elements)
{
    this.elements           = elements;
    this.onElementInserted  = new EventDelegate();
    this.onElementRemoved   = new EventDelegate();
    this.onElementChanged   = new EventDelegate();
    
    extend(this, WebObject);
};

ListModel.prototype = new WebObject;

// public void insert(int index, Object element);
ListModel.prototype.insert = function(index, element)
{
    if(index < 0 || index > this.elements.length)
    {
        throw new Error("ListModel.insert(index = " + index + ") - index out of bounds");
    } else if(!element)
    {
        throw new Error("ListModel.insert(..., item = null) - parameter 'element' cannot be null");
    } else 
    {
        if(index == this.elements.length)
        {
            this.elements.push(element);
        } else
        {
            for(var i = this.elements.length; i >= index; i--)
            {
                this.elements[i] = this.elements[i - 1];
            }
            
            this.elements[index] = element;
        }
        
        this.onElementInserted.fireEvent(this, element, index);
    }
};

// public void add(Object element);
ListModel.prototype.add = function(element)
{
    this.insert(this.elements.length, element);
};

// public void removeAt(int index);
ListModel.prototype.removeAt = function(index)
{
    if(index < 0 || index >= this.elements.length)
    {
        throw new Error("ListModel.remove(index + " + index + ") - index out of bounds");
    } else
    {
        var object = this.elements[index];
        this.elements.splice(index, 1);
        this.onElementRemoved.fireEvent(this, object, index);
    }
};

// public void remove(Object object);
ListModel.prototype.remove = function(object)
{
    var index = this.getIndexOf(object);
    
    if(index != -1)
    {
        this.removeAt(index);
    }
};

// public int getIndexOf(Object object);
ListModel.prototype.getIndexOf = function(object)
{
    for(var i = 0; i < this.elements.length; i++)
    {
        if(this.elements[i] == object)
        {
            return i;
        }
    }
    
    return -1;
};

// public int getElementCount();
ListModel.prototype.getElementCount = function()
{
    return this.elements.length;
};

// public Object getElementAt = function(int index);
ListModel.prototype.getElementAt = function(index)
{
    if(index < 0 || index >= this.elements.length)
    {
        throw new Error("ListModel.getElementAt(index = " + index + ") - index out of bounds");
    } else
    {
        return this.elements[index];
    }
};

ListModel.prototype.toString = function()
{
	return "ListModel [elements = " + this.elements + "]";
}
