
ICore.controls.Select = function (container, fieldObj) {
    this.fieldObj = fieldObj;
    ICore.controls.Select.superclass.constructor.call(this, container);

    ICore.controls.selectsGlobal.push(this);
};

ICore.controls.selectsGlobal = [];

ICore.extend(ICore.controls.Select, ICore.controls.Control, {
    onDropdown: null,
    onCloseup: null,
    onChange: null,

    items: null,
    itemsContainer: null,
    itemsScroll: null,
    itemsList: null,

    captionContainer: null,
    captionLink: null,
    captionSpan: null,
    captionObj: null,

    afterConstruction: function () {
        this.bufferKey = '';
        
        this.items = [];

		this.droppedDown = false;

		this.selectedIndex = -1;
        this.timeout;

        this.onDropdown = new ICore.events.Event(this);
        this.onCloseup = new ICore.events.Event(this);
        this.onChange = new ICore.events.Event(this);
    },

    setup: function () {
        ICore.controls.Select.superclass.setup.call(this);
        
        var me = this;

        this.captionContainer = ICore.dom.getByClass('icore-select-caption', this.container)[0];
        if (!this.captionContainer) {
            this.captionContainer = ICore.dom.createEl('div');
            this.captionContainer.className = 'icore-select-caption';
            this.container.appendChild(this.captionContainer);
        }
        
        this.captionLink = ICore.dom.getByTag('a', this.captionContainer)[0];
        if (!this.captionLink) {
            this.captionLink = ICore.dom.createEl('a');
            this.captionContainer.appendChild(this.captionLink);
        }
        this.captionLink.href = 'javascript:;';
        $(this.captionLink)
            .focus(function (e) {
           	    //me.dropdown();
            });
        var $captionLink = $(this.captionLink);
		$captionLink
			.click(function (e) {
				if (me.droppedDown) {
					me.closeup();
				} else {
	            	me.dropdown();
				}
				e.stopPropagation();
				e.preventDefault();
			})
/*			.find('*').click(function (e) {
				if (me.droppedDown) {
					me.closeup();
				} else {
	            	me.captionLink.focus();
				}
				e.stopPropagation();
				e.preventDefault();
	        })*/;
        ICore.dom.addListener(this.captionLink, ICore.events.CLICK, this.linkClick, this);

        this.captionObj = this.captionSpan = ICore.dom.getByTag('span', this.captionLink)[0];
        if (!this.captionSpan) {
            this.captionObj = this.captionSpan = ICore.dom.createEl('span');
            this.captionLink.appendChild(this.captionSpan);
        }

        this.itemsContainer = ICore.dom.getByClass('icore-select-items', this.container)[0];
        if (!this.itemsContainer) {
            this.itemsContainer = ICore.dom.createEl('div');
            this.itemsContainer.className = 'icore-select-items';
            this.container.appendChild(this.itemsContainer);
        }

        this.itemsScroll = ICore.dom.getByClass('icore-select-scroll', this.itemsContainer)[0];
        if (!this.itemsScroll) {
            this.itemsScroll = ICore.dom.createEl('div');
            this.itemsScroll.className = 'icore-select-scroll';
            this.itemsContainer.appendChild(this.itemsScroll);
        }

        this.itemsList = ICore.dom.getByTag('ul', this.itemsScroll)[0];
        if (!this.itemsList) {
            this.itemsList = ICore.dom.createEl('ul');
            this.itemsScroll.appendChild(this.itemsList);
        }

        var is = ICore.dom.getByTag('li', this.itemsList);
        var tmp;
        for (var i = 0; i < is.length; i++) {
            tmp = new ICore.controls.SelectItem(this, is[i]);
            tmp = this.addItemObj(tmp)-1;

            if (is[i].getAttribute('class') == "selected") { 
                this.setSelectedIndex(tmp);
            }

            else if (is[i].getAttribute('selected')) {
                this.setSelectedIndex(tmp);
            }
        }
    },

    documentClick: function (e) {
        this.closeup();
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
    },

    keyDown: function (e) {
        switch (e.keyCode) {
            case KEY.DOWN: {
                if (this.getSelectedIndex()+1 < this.items.length) {
                    this.setSelectedIndex(this.getSelectedIndex()+1);
                }
            } break;
            case KEY.UP: {
                if (this.getSelectedIndex() > 0) {
                    this.setSelectedIndex(this.getSelectedIndex()-1);
                }
            } break;
            case KEY.RETURN: {
                this.closeup();
            } break;
            case KEY.ESC: {
                if (this.oldSelectedItem) {
                    this.setSelectedIndex(this.oldSelectedItem);
                }
                this.closeup();
            } break;
            default: {
                if (e.keyCode == KEY.BACKSPACE) {
                    this.setBufferKey(this.bufferKey.substring(0, this.bufferKey.length-1));
                } else if (/[a-z0-9 _\/*-+]/i.test(String.fromCharCode(e.keyCode))) {
                    this.setBufferKey(this.bufferKey + String.fromCharCode(e.keyCode));
                } else {
                    return;
                }
                this.restartBufferClear();
            } break;
        }
        if (e.preventDefault) {
            e.preventDefault();
        }
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        e.returnValue = false;
        e.cancelBubble = true;
    },
    
    setBufferKey: function (newbuffer) {
        if (newbuffer != '') {
            for (var i = 0; i < this.items.length; i++) {
                if (newbuffer.toLowerCase() == this.items[i].getCaption().substring(0, newbuffer.length).toLowerCase()) {
                    this.setSelectedIndex(i);
                    break;
                }
            }
        }
        this.bufferKey = newbuffer;
    },
    
    restartBufferClear: function () {
        clearTimeout(this.timerClearBuffer);
        this.timerClearBuffer = setTimeout(this.clearBuffer, 1000);
    },

    clearBuffer: function () {
        for (var i = 0; i < ICore.controls.selectsGlobal.length; i++) {
            ICore.controls.selectsGlobal[i].setBufferKey('');
        }
    },

    linkClick: function (e) {
        var t = e.srcElement || e.target;
        t = ICore.dom.findParent(t, function (el){ return el.tagName == 'A'; });
        if (ICore.util.isUndefined(t)) {
            throw new Error('Link não encontrado.');
        } else {
			//this.dropdown();
			if (e.stopPropagation) {
				e.stopPropagation();
			}
			e.cancelBubble = true;
        }
    },

    dropdown: function () {
		this.droppedDown = true;
		this.oldSelectedItem = this.getSelectedIndex();
		ICore.dom.removeListener(document, ICore.events.KEYDOWN, this.keyDown, this);
		ICore.dom.removeListener(document, ICore.events.CLICK, this.documentClick, this);
		ICore.dom.addListener(document, ICore.events.KEYDOWN, this.keyDown, this);
		ICore.dom.addListener(document, ICore.events.CLICK, this.documentClick, this);
		for (var i = 0; i < ICore.controls.selectsGlobal.length; i++) {
			if (ICore.controls.selectsGlobal[i] != this) {
				ICore.controls.selectsGlobal[i].closeup();
			}
		}
		$(this.itemsContainer).animate({
			height: 'show'
		}, 'fast');
		this.itemsContainer.style.width = this.getContainer().offsetWidth + 'px';
		this.onDropdown.fire();
    },

    closeup: function () {
		this.droppedDown = false;

        $(this.itemsContainer).animate({
            height: 'hide'
        }, 'fast');
        
        ICore.dom.removeListener(document, ICore.events.KEYDOWN, this.keyDown, this);
        ICore.dom.removeListener(document, ICore.events.CLICK, this.documentClick, this);
        
        this.container.blur();
        this.onCloseup.fire();
    },

    setSelectedIndex: function (value) {
        var tmp, item, oldItem = this.items[this.selectedIndex];
        if (value instanceof ICore.controls.SelectItem) {
            tmp = this.items.indexOf(value);
            if (tmp > -1) {
                this.setCaption(value.getCaption());
                this.selectedIndex = tmp;
                item = value;
            } else {
                throw new Error('Índice não adicionado ao select.');
            }
        } else {
            tmp = this.items[value];
            if (tmp) {
                this.setCaption(tmp.getCaption());
                this.selectedIndex = value;
                item = tmp;
            } else {
                throw new Error('Índice foram do limite.');
            }
        }

        if (oldItem) {
            ICore.dom.removeClass(oldItem.getItem(), 'icore-select-selected');
        }
        ICore.dom.addClass(item.getItem(), 'icore-select-selected');
        var f = ICore.util.object(this.fieldObj);
        if (f) {
            f.value = item.getValue();
			this.onChange.fire();
        }
    },

    getFieldObj: function () {
        return this.fieldObj;
    },

    setFieldObj: function (value) {
        this.fieldObj = value;
        this.setSelectedIndex(this.getSelectedIndex());
    },

    getSelectedIndex: function () {
        return this.selectedIndex;
    },

    addItem: function (value, caption) {
        if (ICore.util.isArray(value)) {
            var c, v;
            for (var i = 0; i < value.length; i++) {
                c = (ICore.util.isArray(value[i])?value[i][0]:value[i]);
                v = ((ICore.util.isArray(value[i]) && (value[i][1]))?value[i][1]:c);
                this.addItem(c, v);
            }
        } else {
            var r = new ICore.controls.SelectItem(this, null, value, caption);
            this.addItemObj(r);
            return r;
        }
    },

    addItemObj: function (item) {
        if (item instanceof ICore.controls.SelectItem) {
            if (item.getSelect() != this) {
                this.itemsList.appendChild(item.getContainer());
            }
            return this.items.push(item);
        } else {
            throw new Error('Tipo do ítem inválido.');
        }
    },

    clearItems: function () {
        for (var i = 0; i < this.items.length; i++) {
            this.items[i].getContainer().removeChild(this.items[i].getItem());
        }
        this.items = [];
    },

    getCaption: function () {
        return this.captionObj.innerHTML;
    },

    setCaption: function (value) {
        this.captionObj.innerHTML = value;
    },

    getValue: function () {
        var r = this.items[this.selectedIndex];
        if (r) {
            return r.getValue();
        }
    }
});

ICore.controls.SelectItem = function (select, item, value, caption) {
    this.select = select;
    this.item = item;
    this.tmpCaption = caption;
    this.tmpValue = value;

    ICore.controls.SelectItem.superclass.constructor.call(this, select.itemsList);
};

ICore.extend(ICore.controls.SelectItem, ICore.controls.Control, {
    caption: null,
    captionObj: null,
    htmlValue: null,
    link: null,
    item: null,
    select: null,
    setup: function () {
        ICore.controls.Select.superclass.setup.call(this);

        if (!this.item) {
            this.item = ICore.dom.createEl('li');
            this.container.appendChild(this.item);
        }

        this.link = ICore.dom.getByTag('a', this.item)[0];
        if (!this.link) {
            this.link = ICore.dom.createEl('a');
            this.link.href = 'javascript:;';
            this.item.appendChild(this.link);
        }
        $(this.container).find('a').attr('tabIndex', -1);
        ICore.dom.addListener(this.link, ICore.events.CLICK, this.linkClick, this);

        this.captionObj = ICore.dom.getByTag('span', this.link)[0];
        if (!this.captionObj) {
            this.captionObj = ICore.dom.createEl('span');
            this.link.appendChild(this.captionObj);
        }

        this.captionObj.item = this.link.item = this.item.item = this;

        if (this.tmpCaption) {
            this.setCaption(this.tmpCaption);
        }

        if (this.tmpValue) {
            this.setValue(this.tmpValue);
        }
    },

    setCaption: function (value) {
        this.captionObj.innerHTML = value;
    },

    getCaption: function () {
        return this.captionObj.innerHTML;
    },

    setSelect: function (value) {
        if (value != this.select) {
            if (typeof this.select != 'undefined') {
                this.select.removeItem(this);
            }
            this.select = value;
        }
    },

    getSelect: function () {
        return this.select;
    },

    getItem: function () {
        return this.item;
    },

    linkClick: function (e) {
        var t = e.srcElement || e.target;
        t = ICore.dom.findParent(t, function (el){ return el.tagName == 'A'; });
        if (ICore.util.isUndefined(t)) {
            throw new Error('Link não encontrado.');
        } else {
            this.select.setSelectedIndex(this);
        }
    },

    getValue: function () {
        if (typeof this.item.getAttribute('title') != 'undefined' && this.item.getAttribute('title')) {
            return this.item.getAttribute('title');
        }
        else if (typeof this.item.getAttribute('valor') != 'undefined') {
            return this.item.getAttribute('valor');
        } else {
            return this.getCaption();
        }
    },

    setValue: function (value) {
        this.item.setAttribute('title', value);
    }
});
