﻿Tesla.UI.DropDown = function(id, separatorTemplate, selectionColor, textColor, textFont, uniqueID, placeHolder)
{
    var dropValue = $Get(uniqueID);
    var dropValueIndex = $Get(uniqueID + 'Index');
    var dropItems = $Get(id + 'Items');
    var dropButton = $Get(id + 'Button');
    var dropTextBox = $Get(id + 'TextBox');
    var dropItemsHtml = $Get(id + 'ItemsHtml');
    var opened = false;
    var items = [];
    var autoCompleteItems = null;
    var value = null;
    var text = null;
    this.ID = id;
    this.BindProperty = $$(placeHolder, 'BindProperty');
    var self = this;

    dropTextBox.readOnly = true;

    dropTextBox.onclick = function()
    {
        if (self.IsOpened())
            self.__close();
        else
            self.__open();
        return false;
    }

    this.IsOpened = function()
    {
        return Tesla.UI.DropDown.CurrentDropDown == this;
    }

    this.IsEnabled = function()
    {
        return !dropTextBox.disabled;
    }
    this.Clear = function()
    {
        dropValue.value = null;
        dropValueIndex.value = -1;
        items = [];
        dropTextBox.value = '';
        dropItemsHtml.innerHTML = '';
    }
    this.Add = function(value, text)
    {
        var item = {};
        item.value = value;
        item.text = text;
        items.push(item);
        autoCompleteItems = null

        dropTextBox.value = items[0].text;
        dropValue.value = items[0].value;
        dropValueIndex.value = 0;

        BindItems(items);
    }
    this.Bind = function(dataSource, valueProperty, textProperty, selectOption, preserveItems, p1, p2, p3)
    {
        dropValueIndex.value = 0;
        if (!String.IsNullOrEmpty(selectOption))
        {
            dropTextBox.value = selectOption;
            dropValue.value = selectOption;

        }
        else
        {
            dropTextBox.value = (dataSource.length > 0 ? dataSource[0][textProperty] : '');
            dropValue.value = (dataSource.length > 0 ? dataSource[0][valueProperty] : null);
            this.value = dropValue.value;
        }

        items = [];
        autoCompleteItems = null;

        if (dataSource.GetEnumerator)
        {
            var en = dataSource.GetEnumerator();
            while (en.MoveNext())
            {
                var item = {};
                item.value = valueProperty ? en.Current[valueProperty] : en.Current;
                item.text = textProperty ? en.Current[textProperty] : en.Current;
                item.__NoSeparator = en.Current['__NoSeparator'];

                if (p1) item[p1] = en.Current[p1];
                if (p2) item[p2] = en.Current[p2];
                if (p3) item[p3] = en.Current[p3];

                items.push(item);
            }
        }
        BindItems(items);
    }

    this.click = function()
    {
        if (dropTextBox.disabled)
        {
            dropItems.style.display = 'none';
            return;
        }

        if (this.IsOpened())
            this.__close();
        else
            this.__open();
    }

    this.__open = function()
    {
        dropItems.style.display = '';

        autoCompleteItems = null;
        dropTextBox.select();
        setTimeout(String.Format('Tesla.UI.DropDown.CurrentDropDown = page.{0};', this.ID), 50);
    }

    this.__close = function()
    {
        dropItems.style.display = 'none';
        Tesla.UI.DropDown.CurrentDropDown = null;
    }
    this.focus = function()
    {
        this.__open();
    }
    function GetText(txt)
    {
        var rt = "";
        var ignorar = false;

        for (var i = 0; i < txt.length; i++)
        {
            var caracter = txt.charAt(i);

            if (caracter == '<')
            {
                ignorar = true;
                continue;
            }
            if (caracter == '/')
                continue;

            if (caracter == '>')
            {
                ignorar = false;
                continue;
            }
            if (ignorar == true)
                continue;

            rt += txt.charAt(i);

        }

        return rt;
    }
    this.SetSelectedIndex = function(idx, ignoreOnChange)
    {
        dropValueIndex.value = Math.max(idx, -1);
        if (idx < 0)
        {
            dropTextBox.value = _items && _items.length ? _items[0].text : '';
            this.value = '';
            dropValue.value = '';
            this.selectedValue = '';
            this.selectedIndex = -1;
            if (!ignoreOnChange && this.onchange)
                this.onchange();
            return;
        }
        var _items = autoCompleteItems || items;
        dropTextBox.value = GetText(_items[idx].text);
        dropValue.value = _items[idx].value;
        this.__close();

        this.value = _items[idx].value;
        this.selectedValue = this.value;
        this.selectedIndex = idx;
        if (!ignoreOnChange && this.onchange)
            this.onchange();
    }
    this.SetSelectedValue = function(value)
    {
        var arr = autoCompleteItems || items;

        for (var i = 0; i < arr.length; i++)
        {
            if (arr[i].value == value)
            {
                this.SetSelectedIndex(i);
                return;
            }
        }
        this.SetSelectedIndex(-1);
    }
    this.SelectedValue = function()
    {
        return dropValue.value;
    }
    this.SelectedText = function()
    {
        return dropTextBox.value;
    }
    this.SetText = function(text)
    {
        dropTextBox.value = text;
        dropValue.value = text;
    }
    this.SetDisabled = function()
    {
        dropTextBox.disabled = true;
        dropButton.childNodes[0].src = this.ImageLocation + '/drop_botao_off.gif';
    }
    this.SetEnabled = function()
    {
        dropTextBox.disabled = false;
        dropButton.childNodes[0].src = this.ImageLocation + '/drop_botao.gif';
    }
    function BindItems(arr)
    {
        self.options = arr;
        var html = new Tesla.StringBuilder();
        var div = String.Format('<div style="width:95%;" onmouseover="this.style.backgroundColor=\'{0}\'" onmouseout="this.style.backgroundColor=\'\';"><a href="#" style="width:100%;text-decoration:none;color:{1};font-family:{2}" onclick="return Tesla.UI.DropDown.SelectItem', selectionColor, textColor, textFont);
        for (var i = 0; i < arr.length; i++)
        {
            html.Append(div);
            html.Append(String.Format('(\'{0}\', {1});"><div style="width:90%;cursor:Hand">', id, i));
            html.Append(arr[i].text);
            html.Append('</div></a></div>');
            if (separatorTemplate && !arr[i].__NoSeparator && i < arr.length - 1)
                html.Append(separatorTemplate);
        }
        dropItemsHtml.innerHTML = html.toString();
    }
}
Tesla.UI.DropDown.HTML = '<input name="{4}" id="{4}" type="hidden" /><input name="{4}Index" id="{4}Index" type="hidden" /><table border="0" cellpadding="0" cellspacing="0"><tr><td><img src="{3}/drop_esquerda{5}.gif" alt="" /></td><td style="background-image:url({3}/drop_meio.gif);background-position:top right;width:{1}px;height:25px;"><input id="{0}TextBox" type="text" style="background-color:Transparent;border:0px;width:99%" /></td><td><img src="{3}/drop_direita{5}.gif" alt="" /></td><td><a id="{0}Button" href="javascript: Tesla.UI.DropDown.Click(\'{0}\');" style="position:relative;left:-22px;"><img src="{3}/drop_botao.gif" border="0" alt="" style="z-index:2" /></a></td></tr></table><table id="{0}Items" border="0" cellpadding="0" cellspacing="0" style="position:absolute;height:0px;display:none;z-index:2"><tr style="height:1px;"><td></td></tr><tr ><td><img src="{3}/drop_itens_esquerda.gif" alt="" /></td><td style="width:99%;background-image:url({3}/drop_itens_meio.gif);background-position:top right;width:{2}px;height:25px;vertical-align:top"><div id="{0}ItemsHtml" style="overflow-y:auto;overflow-x:hidden;height:190px;width:{2}px;margin-top:5px;" ></div></td><td><img src="{3}/drop_itens_direita.gif" alt="" /></td></tr></table>';
Tesla.UI.DropDown.Load = function(uniqueID, id, separatorTemplate, selectionColor, textColor, textFont, width, imageLocation, borderBackGround)
{
	var placeHolder = $Get(id + 'PlaceHolder');
	if (borderBackGround && borderBackGround.length)
		borderBackGround = '_' + borderBackGround;

	placeHolder.innerHTML = String.Format(Tesla.UI.DropDown.HTML, id, (width || 90), (width || 90) + 20, imageLocation || '', uniqueID, borderBackGround);

	var idArray = id.Split('.');

	var ctrlObj = page;
	for (var i = 0; i < idArray.length - 1; i++)
		ctrlObj = ctrlObj[idArray[i]];

	var drop = new Tesla.UI.DropDown(id, separatorTemplate, selectionColor, textColor, textFont, uniqueID, placeHolder);

	ctrlObj[idArray[idArray.length - 1]] = drop;
	drop.ImageLocation = imageLocation;

	if (!Tesla.UI.DropDown.HasOnClickHandler)
	{
		page.AddOnClick(Tesla.UI.DropDown.CloseCurrentDropDown);
		Tesla.UI.DropDown.HasOnClickHandler = 1;
	}
}

Tesla.UI.DropDown.CloseCurrentDropDown = function(p)
{
	if (!p && Tesla.UI.DropDown.CurrentDropDown)
	{
		Tesla.UI.DropDown.IsClosing = 1;
		setTimeout('Tesla.UI.DropDown.CloseCurrentDropDown(1);', 10);
		return;
	}
	else if (Tesla.UI.DropDown.CurrentDropDown && Tesla.UI.DropDown.IsClosing)
	{
		Tesla.UI.DropDown.CurrentDropDown.__close();
	}
}

Tesla.UI.DropDown.SelectItem = function(id, idx)
{
	var drop = page.FindControl(id);
	if (drop.onchanging && !drop.onchanging(idx))
	{
		setTimeout('Tesla.UI.DropDown.IsClosing = 0', 1);
		return;
	}

	drop.SetSelectedIndex(idx);
	return false;
}
Tesla.UI.DropDown.Click = function(id)
{
	Tesla.UI.DropDown.IsClosing = 0;
	var drop = page.FindControl(id);

	if (Tesla.UI.DropDown.CurrentDropDown && Tesla.UI.DropDown.CurrentDropDown != drop)
	{
		Tesla.UI.DropDown.CurrentDropDown.__close();
	}

	drop.click();
}
