﻿//+
//- DropDownTextBox -//
if (typeof Instinct == 'undefined') { Instinct = {}; }
Instinct.DropDownListUpdater = Class.create({
    //- main -//
    initialize: function(init) {
        if (init) {
            if (init.controlId) {
                this.controlId = init.controlId;
                if (!$(this.controlId)) {
                    throw 'Control (select/DropDownList) with ID ' + this.controlId + ' was not found.';
                }
            } else {
                throw 'controlId is required.';
            }
            if (init.endpointId) {
                this.endpointId = init.endpointId;
            } else {  
                throw 'endpointId is required.';
            }
            if (init.key) {
                this.key = init.key;
            } else {
                throw 'key is required.';
            }
            if (init.onSuccess) {
                this.onSuccess = init.onSuccess;
            }
            else {
                this.onSuccess = this._onSuccess;
            }
            if (init.method) {
                this.method = init.method;
            } else {  
                this.method = 'Exec~cKey,nValue';
            }
        }
        else {
            throw 'init is required.';
        }
        $(this.controlId).observe('change', this._update.bind(this));
    },
    
    //- _onSuccess -//
    _onSuccess: function(data) {
        var optionList = this.cachedOptionArray;
        var select = $(this.controlId);
        select.options.length = 0;
        for (var optionIndex = 0; optionIndex < optionList.length; optionIndex++) {
            var option = optionList[optionIndex];
            if (option) {
                var isSelect = !!option.selected;
                select.options[select.options.length] = new Option(option.text, option.value, isSelect, isSelect);
            }
        }
        this.cachedOptionArray = [];
    },

    //- _update -//
    _update: function() {
        var endpoint = window.registeredEndpointList[this.endpointId];
        if (endpoint) {
            var value = $F(this.controlId);
            this.cachedOptionArray = [];
            var optionArray = $(this.controlId).options;
            for (var optionIndex = 0; optionIndex < optionArray.length; optionIndex++) {
                var option = optionArray[optionIndex];
                if (option) {
                    this.cachedOptionArray.push({
                        value: option.value,
                        text: option.text,
                        selected: option.selected
                    });
                }
            }
            optionArray.length = 0;
            optionArray[0] = new Option('Updating...', 0);
            endpoint.executeContract(this.onSuccess.bind(this), this.method, this.key, value);
        }
    }
});