function State(owner, variable, states, active_state) {
    if (!arguments.length)
        return
    this.owner = owner
    this.varname = variable
    this.state = states
    if (active_state != undefined)
        this.set(active_state)
}

State.prototype.get_active_state = function() {
    return this.owner[this.varname]
}

/* Rules for changing from one state to another */
State.prototype.check_change_rules = function(new_state, old_state) {
    if (this.state.indexOf(new_state) == -1)
        return false
    return true
}

/* Trigger actions on state change */
State.prototype.change = function(new_state, old_state) {
    this.owner.refresh()
}

State.prototype.set = function(state) {
    if (this.state.indexOf(state) == -1) {
        //throw "Invalid key: " + state
        //return
        this.state.push(state)
        create_node("option", state, {}, this.sel)
    }

    var old_key = this.get_active_state()
    if (!this.check_change_rules(state, old_key))
        return
    this.owner[this.varname] = state
    this.change(state, old_key)

    this.html_change(state)
}


SelectState.prototype = new State
SelectState.prototype.constructor = SelectState
SelectState.prototype.super = State

function SelectState(owner, variable, states, active_state, label, config) {
    this.label = label.capitalize()
    this.node = document.createElement("div")
    this.node.classList.add("SelectView")

    var n = create_node("label", "", {}, this.node)
    create_node("h2", this.label + ":", {}, n)
    var sel = create_node("select", "", config, this.node)
    this.sel = sel
    for (var i = 0; i < states.length; i++) {
        create_node("option", states[i], {}, sel)
        if (states[i] == active_state)
            sel.selectedIndex = i
    }

    sel.addEventListener("change", (function(that) {
        return function() {
            that.set(this.options[this.selectedIndex].value)
        }
    })(this))

    this.super.apply(this, arguments)
}

SelectState.prototype.dom = function() {
    return this.node
}

SelectState.prototype.html_change = function(state) {
    for (var i = 0; i < this.sel.options.length; i++)
        if (this.sel.options[i].value == state)
            this.sel.selectedIndex = i
}

SelectState.prototype.activate = function(state) {
    this.html_change(state)
    this.set(state)
}

SelectState.prototype.add_state = function(state, activate) {
    create_node("option", state, {}, this.sel)
    if (activate)
        this.activate(state)
}

