/* Gestisce le operazioni che riguardano i comportamenti di un controllo */
Class.create('Behavior', {
    classMembers: {
        // Crea il comportamento specificato
        create: function(name, description) {
            var behavior = new Function();
            
            // Aggiunge tutti i membri specificati nella descrizione
            for (var member in description) {
                behavior[member] = description[member];
            }
            
            // Registra il comportamento nella pagina
            eval(name + ' = behavior;');
        },
        
        // Crea un delegato del metodo per l'oggetto specificato
        createDelegate: function(instance, method) {
            return function() {
                method.apply(instance, arguments);
            };
        },
        
        // Attacca un comportamento complesso all'oggetto
        attach: function(object, behavior) {
            object = Utilities.get(object);
            behavior = Utilities.get(behavior);
        
            if (object == null) {
                throw new Error('Behavior.attach: l\'oggetto di destinazione non è stato specificato.');
            }
  
            if (behavior == null) {
                throw new Error("Behavior.attach: il comportamento da assegnare non è stato specificato.");
            }
            
            // Aggiunge tutti gli elementi del comportamento all'oggetto
            for (var item in behavior) {
                Behavior.attachEvent(object, item.substr(2), behavior[item]);
            }
        },

        // Attacca un singolo evento all'oggetto
        attachEvent: function(object, eventName, delegate) {
            object = Utilities.get(object);

            if (!object) {
                throw new Error('Behavior.attachEvent: l\'oggetto di destinazione non è stato specificato.');
            }
            
            if (!eventName) {
                throw new Error('Behavior.attachEvent: il nome dell\'evento non è stato specificato.');
            }
            
            if (!delegate) {
                throw new Error('Behavior.attachEvent: la funzione di gestione dell\'evento non è stata specificata.');
            }
            
            // Aggiunge l'evento con il metodo corretto
            if (object.addEventListener) {
                object.addEventListener(eventName, delegate, false);
            }
            else if (object.attachEvent) {
                object.attachEvent("on" + eventName, delegate);
            }
            else if (object["on" + eventName]) {
                object["on" + eventName] = delegate;
            }
        }
    }
});
