﻿OpenState = { Open: 1, Close: 2 };
LowerCase = function(val)
{
    if (!val) return val;
    return val.toLowerCase();
}
DropDown = function(clientID)
{
    this.clientID = clientID;
    this.state = OpenState.Close;
    this.CloseController = null;
    this.OnItemClick = null;
    this.SelectedValue = null;
    this.enabled = null;
    this.IsLoaded = false;

    this.GetDiv = function()
    {
        return document.getElementById(this.clientID + '_div');
    }
    this.GetUL = function()
    {
        return document.getElementById(this.clientID + '_ul');
    }
    this.StartCloseController = function()
    {
        if (this.state == OpenState.Close) return;
        this.ClearCloseController();
        this.CloseController = setTimeout(this.clientID + '.DivClick()', 500);
    }
    this.ClearCloseController = function()
    {
        if (this.CloseController)
            clearTimeout(this.CloseController);
    }
    this.DivClick = function(obj)
    {
        // Apenas executa o evento se o combo estiver enabled
        if (this.GetEnabled())
        {
            var div = this.GetDiv();
            if (this.state == OpenState.Close)
            {
                var hierarchy = GetHierarchy(div);
                PopupFields.CloseAll(hierarchy);
                FloatingWindows.CloseAll(hierarchy);

                ReplaceClassName(div, 'combo_box', 'combo_box_on');
                this.state = OpenState.Open;
            }
            else
            {
                ReplaceClassName(div, 'combo_box_on', 'combo_box');
                this.state = OpenState.Close;
            }
        }
    }
    this.GetItems = function()
    {
        var items = [];

        for (var i = 0; i < ul.childNodes.length; i++)
        {
            if (LowerCase(ul.childNodes[i].tagName) == 'li')
            {
                for (var j = 0; j < ul.childNodes[i].childNodes.length; j++)
                {
                    if (LowerCase(ul.childNodes[i].childNodes[j].tagName) == 'a')
                    {
                        items.push(ul.childNodes[i].childNodes[j]);
                    }
                }
            }
        }

        return items;
    }
    
    this.DataBind = function(dataSource, dataValueField, dataTextField, selectedValue)
    {
        this.SelectedValue = null;
        if (dataSource && dataSource.length > 0)
        {
            var content = new Tesla.StringBuilder();
            var itemTemplate = new Tesla.UI.Template('<li><a href="#" title="(% DataItem.' + dataTextField + ' %)" value="(% DataItem.' + dataValueField + ' %)" >(% DataItem.' + dataTextField + ' %)</a></li>');

            for (var i = 0; i < dataSource.length; i++)
                content.Append(itemTemplate.DataBind(dataSource[i], i, dataSource));

            ul.innerHTML = content.toString();
            this.SetItemsSettings();

            if (selectedValue == undefined)
                this.SelectFirstItem();
            else
            {
                this.SelectItem(selectedValue);
                if (this.SelectedValue == null)
                    this.SelectFirstItem();
            }
        }
        else
            this.Clear();
    }
    this.Clear = function()
    {
        this.SelectedValue = null;
        ul.innerHTML = '';
        this.SetText('');
    }
    this.ItemClick = function(obj)
    {
        this.SetText(obj.innerHTML);

        var oldValue = this.SelectedValue;
        this.SelectedValue = $GetAttr(obj, 'value');

        if (this.IsLoaded && this.OnItemClick)
        {
            var args = { Item: obj, Cancel: false, OldValue: oldValue, NewValue: this.SelectedValue };
            this.OnItemClick(this, args);
        }
    }
    this.SetText = function(text)
    {
        var div = this.GetDiv();
        for (var i = 0; i < div.childNodes.length; i++)
        {
            var ctrl = div.childNodes[i];
            if (LowerCase(ctrl.tagName) == 'span')
            {
                var pixelPorLetra = 6;
                if (div.offsetWidth > 0 && (text.length * pixelPorLetra) > (div.offsetWidth - 12))
                {
                    var qtd = parseInt((div.offsetWidth - 12) / pixelPorLetra);
                    if (qtd > 5)
                        ctrl.innerHTML = text.substr(0, qtd - 4) + ' ...';
                    else
                        ctrl.innerHTML = text.substr(0, qtd);
                }
                else
                {
                    ctrl.innerHTML = text;
                }
            }
        }
    }
    this.SetItemsSettings = function()
    {
        for (var i = 0; i < ul.childNodes.length; i++)
        {
            if (LowerCase(ul.childNodes[i].tagName) == 'li')
            {
                for (var j = 0; j < ul.childNodes[i].childNodes.length; j++)
                {
                    if (LowerCase(ul.childNodes[i].childNodes[j].tagName) == 'a')
                    {
                        ul.childNodes[i].childNodes[j].dropDown = this;
                        ul.childNodes[i].childNodes[j].onclick = new Function('obj', 'this.dropDown.ItemClick(this); return false;');
                    }
                }
            }
        }
    }
    this.SelectItem = function(value)
    {
        if (value == null)
        {
            this.SelectedValue = null;
            this.SetText('');
        }
        else
        {
            var items = this.GetItems();
            for (var i = 0; i < items.length; i++)
            {
                if ($GetAttr(items[i], 'value') == value)
                {
                    this.ItemClick(items[i]);
                    break;
                }
            }
        }
    }
    this.SelectFirstItem = function()
    {
        var items = this.GetItems();
        if (items.length > 0)
            this.ItemClick(items[0]);
    }
    this.SetEnabled = function(value)
    {
        var div = this.GetDiv();

        if (this.enabled == null || this.enabled != value)
        {
            this.enabled = value;
            if (value)
                ReplaceClassName(div, 'combo_box_off', 'combo_box');
            else
                ReplaceClassName(div, 'combo_box', 'combo_box_off');
        }
    }
    this.GetEnabled = function()
    {
        return this.enabled;
    }
    var ul = this.GetUL();
    if (!ul)
        ul = null;
    this.SetItemsSettings();
    this.GetDiv().onclick = new Function(this.clientID + ".DivClick(); return false;");
    this.GetDiv().onmouseout = new Function(this.clientID + '.StartCloseController()')
    this.GetDiv().onmouseover = new Function(this.clientID + '.ClearCloseController()')
    this.SetEnabled(true);
}

DropDown.Create = function(clientID, id)
{
    page[id] = new DropDown(clientID);
    return page[id];
}

PopupFields = {};
PopupFields.Opened = [];
PopupFields.CloseAll = function(exceptionList)
{
    if (!exceptionList) exceptionList = [];
    var naoFechar = false;

    for (var i = PopupFields.Opened.length - 1; i >= 0; i--)
    {
        for (var j = 0; j < exceptionList.length; j++) if (exceptionList[j].id == PopupFields.Opened[i].divId) naoFechar = true;

        if (naoFechar) continue;
        PopupFields.Opened[i].Close();
    }
    PopupFields.Opened.length = 0;
}
PopupFields.Open = function(item)
{
    var hierarchy = GetHierarchy($Get(item.divId));
    PopupFields.CloseAll(hierarchy);
    FloatingWindows.CloseAll(hierarchy);
    PopupFields.Opened.push(item);
}
PopupField = function(divId, aId, spanId, okId, closeId) {
    this.divId = divId;
    this.aId = aId;
    this.spanId = spanId;
    this.okId = okId;
    this.closeId = closeId;
    this.restoreStateOnClose = true;
    this.OnOKClick = null;
    this.enabled = null;
    this.controlState = null;
    this.OnSaveControlState = null;
    this.OnRestoreControlState = null;
    this.OnFirstOpen = null;
    this.Data = null;
    this._isFirstOpen = true;

    this.SaveControlState = function() {
        if (this.OnSaveControlState) {
            var args = { State: null };
            this.OnSaveControlState(this, args);
            this.controlState = args.State;
        }
    }

    this.RestoreControlState = function() {
        if (this.OnRestoreControlState) {
            var args = { State: this.controlState };
            this.OnRestoreControlState(this, args);
        }
    }

    this.Open = function() {
        if (this._isFirstOpen) {
            if (this.OnFirstOpen)
                this.OnFirstOpen(this, null);

            this._isFirstOpen = false;
        }

        this.restoreStateOnClose = true;
        this.SaveControlState();

        PopupFields.Open(this);
        var par = $Get(divId);
        if (par) AddClassName(par.parentNode, 'zi10');
        RemoveClassName($Get(divId), 'dn');
    }
    this.Close = function() {
        var par = $Get(divId);
        if (par) RemoveClassName(par.parentNode, 'zi10');
        AddClassName($Get(divId), 'dn');

        if (this.restoreStateOnClose)
            this.RestoreControlState();
    }
    this.OKClick = function(obj) {
        if (this.OnOKClick) {
            var args = { Cancel: false };
            this.OnOKClick(this, args);
            if (args.Cancel)
                return;
        }

        this.restoreStateOnClose = false;
        this.Close();
    }
    this.SetText = function(text) {
        var actrl = $Get(aId);
        var ctrl = $Get(spanId);
        var pixelPorLetra = 6;
        if (actrl.offsetWidth > 0 && (text.length * pixelPorLetra) > (actrl.offsetWidth - 18)) {
            var qtd = parseInt((actrl.offsetWidth - 18) / pixelPorLetra);
            if (qtd > 5)
                ctrl.innerHTML = text.substr(0, qtd - 4) + ' ...';
            else
                ctrl.innerHTML = text.substr(0, qtd);
        }
        else {
            ctrl.innerHTML = text;
        }
    }
    this.GetEnabled = function() {
        return this.enabled;
    }
    this.SetEnabled = function(value) {
        if (this.enabled == null || this.enabled != value) {
            this.enabled = value;
            var obj = $Get(aId);
            if (value)
                ReplaceClassName(obj, 'item_box_off', 'item_box');
            else
                ReplaceClassName(obj, 'item_box', 'item_box_off');
        }
    }

    $Get(aId).PopupField = this;
    $Get(spanId).PopupField = this;
    $Get(divId).PopupField = this;
    $Get(okId).PopupField = this;
    $Get(closeId).PopupField = this;
    $Get(closeId).onclick = new Function('this.PopupField.Close(); return false;');
    $Get(okId).onclick = new Function('obj', 'this.PopupField.OKClick(this); return false;');

    this.SetEnabled(true);
}

PopupField.Create = function(divId, aId, spanId, okId, closeId, id)
{
    page[id] = new PopupField(divId, aId, spanId, okId, closeId);
    return page[id];
}

Tabs = {};
Tabs.TabControllers = {};
Tabs.PickMe = function(item, selectedPanel, tabController)
{
    if (PickMe_running) return;
    PickMe_running = true;
    var _ul = item.parentNode;
    for (var i = 0; i < _ul.childNodes.length; i++) if (GetTagName(_ul.childNodes[i]) == 'li') RemoveClassName(_ul.childNodes[i], 'selected');
    Tabs.SelectTab(tabController, selectedPanel);
    AddClassName(item, 'selected');
    PickMe_running = false;
}
Tabs.SelectTab = function(tabController, selectedPanel)
{
    var panels = Tabs.TabControllers[tabController];
    for (var i = 0; i < panels.length; i++)
        $Get(panels[i]).style.display = 'none';
    
    if ($Get(selectedPanel) !== null)
        $Get(selectedPanel).style.display = '';
}
Tabs.HighlightMe = function(item)
{
    if (HighlightMe_running || PickMe_running) return;
    HighlightMe_running = true;
    var _ul = item.parentNode;
    for (var i = 0; i < _ul.childNodes.length; i++) if (GetTagName(_ul.childNodes[i]) == 'li') RemoveClassName(_ul.childNodes[i], 'highlighted');
    if ('selected' != item.className) AddClassName(item, 'highlighted');
    HighlightMe_running = false;
}
Tabs.LeaveMe = function(item)
{
    if (LeaveMe_running || PickMe_running) return;
    LeaveMe_running = true;
    var _ul = item.parentNode;
    for (var i = 0; i < _ul.childNodes.length; i++) if (GetTagName(_ul.childNodes[i]) == 'li') RemoveClassName(_ul.childNodes[i], 'highlighted');
    LeaveMe_running = false;
}
PickMe_running = false;
HighlightMe_running = false;
LeaveMe_running = false;


FloatingWindows = {};
FloatingWindows.Opened = [];

FloatingWindows.CloseAll = function(exceptionList)
{
    if (!exceptionList) exceptionList = [];
    var naoFechar = false;

    for (var i = FloatingWindows.Opened.length - 1; i >= 0; i--)
    {
        for (var j = 0; j < exceptionList.length; j++) if (exceptionList[j].id == FloatingWindows.Opened[i].divId) naoFechar = true;

        if (naoFechar) continue;
        FloatingWindows.Opened[i].Close();
    }
    FloatingWindows.Opened.length = 0;
}

FloatingWindows.Open = function(item)
{
    var div = $Get(item.divID);
    var hierarchy = GetHierarchy(div);

    PopupFields.CloseAll(hierarchy);    
    FloatingWindows.CloseAll(hierarchy);
    FloatingWindows.Opened.push(item);
    
    RemoveClassName(div, 'dn');
    AddClassName(div, 'zi10');
}

FloatingWindows.Close = function(item)
{
    var div = $Get(item.divID);
    AddClassName(div, 'dn');
    RemoveClassName(div, 'zi10');
}

FloatingWindow = function(divID, divContID, lnkCloseID, lblID)
{
    this.divID = divID;
    this.divContID = divContID;
    this.lnkCloseID = lnkCloseID;
    this.lblID = lblID;
 
    this.Open = function()
    {
        FloatingWindows.Open(this);
    }
    
    this.Close = function()
    {
        FloatingWindows.Close(this);
    }

    this.RemoveContentHeight = function()
    {
        var divCont = $Get(this.divContID);

        if (divCont)
            divCont.style.height = '';
    }

    this.SetContentHeight = function(height)
    {
        var divCont = $Get(this.divContID);

        if (divCont)
            divCont.style.height = height;
    }
    
    this.SetTitle = function(text)
    {
        $Get(this.lblID).innerHTML = text;
    }
    
    this.GetTitle = function()
    {
        return $Get(this.lblID).innerHTML;
    }

    $Get(this.divID).FloatingWindow = this;
    $Get(this.lnkCloseID).FloatingWindow = this;
    $Get(this.lnkCloseID).onclick = new Function('this.FloatingWindow.Close(); return false;');
}

FloatingWindow.Create = function(divID, divContID, lnkCloseID, lblID, id)
{
    page[id] = new FloatingWindow(divID, divContID, lnkCloseID, lblID);
    return page[id];
}

