var TreeSelectController = new Class({

    options: $H({
        child: null,
        parent: null,
        id: null,
	select_title: null,
	select_options: []
    }),
    initialize: function(field, options){
        this.field = field
        this.options.extend(options);
        this.container = $(this.getContainerId());
	this.createElement();
    },
    getContainerId: function(){
        return 'container-'+this.field.options.field_name+'-'+this.field.options.typeId+'-'+this.options.id;
    },
    createElement: function(){
        if(!this.container){
            this.container = new Element('div', {'id': this.getContainerId()});
            this.select =  new Element('select', {
	                             'class':this.field.options.select_class_name,
				     'disabled':true});
            this.select.inject(this.container);	    
            this.options.select_options.each(function(value){
                var option = new Element('option', 
	                                {'value': value[0],'html': value[1]});
                option.inject(this.select);
            }.bind(this));
            this.container.inject(this.options.parent.container,'after');
        }else{
            this.select = this.container.getElement('select');
        }
        this.select.addEvent('change', this.onSelect.bind(this));
        this.select.disabled=false;
    },
    onSelect: function(event){
        var new_value = event.target.value;
        if(this.options.child)
            this.options.child.destroyElement()
	if(!parseInt(new_value)){
	    this.field.input.value = 0;
	    return;
	}
        option = this.getOption(new_value)
        if(this.field.cache.has(new_value)){
            this.options.child = this.field.cache[new_value];
	    if(this.options.child)
                this.options.child.createElement();
        }else{
            this.sendRequest();
        }
	this.field.input.value = new_value;	
	this.afterSelect(new_value);
    },
    afterSelect: function(new_value){
    },
    destroyElement: function(){
        if(this.container){
            this.container.destroy()
	    this.container = null;
	}
        if(this.options.child)
            this.options.child.destroyElement()
    },
    sendRequest: function(){
        this.field.disableSelects(true);
        var jsonRequest = new Request.JSON({
                url: this.field.options.url+this.select.value+"/",
                onSuccess: this.onSuccess.bind(this),
                onFailure: function(err){alert(err.status);}
        }).get({"ajax":1}); //ajax=1 only for cashing    
    },
    getOption: function(id){
        this.options.select_options.each(function(value){
            if(value[0]==parseInt(id))
                return [value[1],value[2]];
        })
    },
    createChild: function(id, select_options){
        var options = $H({});
        options.extend(this.options);
	options['id'] = id;
	options['select_options'] = select_options;
	options['parent'] = this;
	this.field.cache[id] = new this.field.options.itemClass(this.field, options);
        this.options.child = this.field.cache[id]; 
	return this.options.child
    },
    onSuccess: function(response){
        if(!response.childs.length){
            this.field.cache[this.select.value] = 0;
        }else{
            this.createChild(this.select.value, response.childs);
        }
        this.field.disableSelects(false);
    }
})


var TreeField = new Class({
    Implements: [Options],

    options: {
        url: null,
        typeId: null,
        field_name: null,
	select_class_name: null,
	itemClass: TreeSelectController
    },
    cache: $H({}),
    
    initialize: function(container, options){
       this.setOptions(options);
       this.container = container;
       this.input = $('input-'+this.options.field_name);
       this.initFromHTML();
    },
    initFromHTML:function(){
         var parentController = 0; 
         this.container.getElements('.treeSelectContainer').each(function(container){
             var select_options=[];
             container.getElements('option').each(function(option, index){
                select_options.include([option.value, option.innerHTML]);
             });
             parts = container.id.split('-')
             id = parts[3];
	     if(parentController){
	         parentController = parentController.createChild(id, select_options);
	     }else{
	         parentController = new this.options.itemClass(this,{
		     'id': id, 
	             'select_options': select_options
		 });
	     }
	 }.bind(this));
    },
    disableSelects: function(value){
        this.container.getElements('select').each(function(el){
	    el.disabled=value
	});
    }
});

var RegionController = new Class({
    Extends:TreeSelectController,
    indexes_options: $H({}),
    initialize: function(field, options, indexes_options){
        if(indexes_options)
            this.indexes_options = indexes_options;
        this.parent(field, options);
    },
    onSuccess: function(response){
        this.indexes_options[this.select.value] = response.indexes;
	try{
	this.createIndexes(this.select.value);
	}catch(err){console.log(err)}
        if(!response.childs.length){
            this.field.cache[this.select.value] = 0;
        }else{
            child = this.createChild(this.select.value, response.childs);
	} 
        this.field.disableSelects(false);
    },
    afterSelect: function(new_value){
        if(this.indexes_options.has(new_value)){
            this.createIndexes(new_value)
        }
    },
    createIndexes: function(value){
        this.field.indexes_select.getElements('option').each(function(option, index){
            option.destroy()
        });
        if(this.indexes_options[value].length){
            this.indexes_options[value].each(function(value, index){
                var option = new Element('option', 
	                                {'value': value[0],'html': value[index?0:1]});
                option.inject(this.field.indexes_select);
            }.bind(this));
	    this.field.indexes_select.setStyle('display','block');
	}
	else
	    this.field.indexes_select.setStyle('display','none');
    }
});

var RegionField = new Class({
        Extends:TreeField,
        initialize: function(container, options){
	    this.indexes_select= $('field-post_office');
	    this.parent(container,options);
	}
});

window.addEvent('domready', function(){
    new TreeField($('maincontainer-section'),{
            'url': prefix + '/mail/themes/',
	    'typeId':6,
	    'field_name': 'section',
	    'select_class_name': 'section_select',
	    'itemClass':TreeSelectController
    });
    new RegionField($('maincontainer-region'),{
            'url': prefix + '/mail/regions/',
	    'typeId':7,
	    'field_name': 'region',
	    'select_class_name': 'w45',
	    'itemClass':RegionController
    });
});
