﻿var constAutoCompletePopupID = '_AutoCompletePopup';
var constAutoCompleteID = '_AutoComplete';
var constAutoCompletePopupTime = 500;
var isAutoCompleteSuppress = false;
var isControlInFocus = false;    
var isAutoCompleteListOpen = false;
var scrollbarWidth = 0;

String.prototype.trim  = _trim;

function _trim() { return this.replace(/^\s+|\s+$/g, ""); }

function getScrollBarWidth () 
{
	var inner = document.createElement('p');
	inner.style.width = "100%";
	inner.style.height = "200px";

	var outer = document.createElement('div');
	outer.style.position = "absolute";
	outer.style.top = "0px";
	outer.style.left = "0px";
	outer.style.visibility = "hidden";
	outer.style.width = "200px";
	outer.style.height = "150px";
	outer.style.overflow = "hidden";
	outer.appendChild (inner);

	document.body.appendChild (outer);
	var w1 = inner.offsetWidth;
	outer.style.overflow = 'scroll';
	var w2 = inner.offsetWidth;
	if (w1 == w2) w2 = outer.clientWidth;

	document.body.removeChild (outer);

	return (w1 - w2);
}

function isAutoCompleteChanged(source, data) {
    return ((data.options.length > 0) &&
           (source.value != data.options[data.selectedIndex].text));
}

function openAutoCompleteList(source, data, e) {
    var opener = e.srcElement ? e.srcElement : e.target;

    if (source.disabled == true) return;
    if (data.options.length == 0) return;

    if (opener.id != source.getAttribute('parent'))
    {
        if (!isAutoCompleteListOpen) 
        {
            buildAutoCompleteList(source, data, e, true);
            isAutoCompleteListOpen = true;
            isAutoCompleteSuppress = true;
            source.select();
        }
        else
        {
            hideAutoCompleteList();
        }
        source.focus();
    }
}

function setAutoCompleteValue(source, data, e)
{    
    var popup = top.document.getElementById(constAutoCompletePopupID);   
    if (!popup) return;
    
    var lastValue = source.value;

    data.selectedIndex = popup.firstChild.options[popup.firstChild.selectedIndex].value;

    if (isAutoCompleteChanged(source, data) 
        && data.onchange != null)
        data.onchange();    
    
    source.value = data.options[data.selectedIndex].text;
    
    if (lastValue != source.value)
        source.setAttribute('lastValue',source.value);
        
    source.focus();
}

function setAutoCompleteValueEquals(source, data, e) {
    try {
        var popup = top.document.getElementById(constAutoCompletePopupID);
        var lastValue = source.value;
        var updateCurrentValue = (data) ? true : false;

        if (data.options.length == 0)
            source.value = '';
        
        if (!isAutoCompleteChanged(source, data))
            return;            

        if (popup) {
            if (source.value == popup.firstChild.options[popup.firstChild.selectedIndex].text)
                data.selectedIndex = popup.firstChild.options[popup.firstChild.selectedIndex].value;

            if (data.options[data.selectedIndex].value != '-1') {
                if (source.value != popup.firstChild.options[popup.firstChild.selectedIndex].text &&
                    !isControlInFocus)
                    source.value = data.options[data.selectedIndex].text;

                if (data.onchange != null)
                    data.onchange();

                updateCurrentValue = false;
            }
        }

        if (updateCurrentValue &&
                source.value != data.options[data.selectedIndex].text) {
            source.value = data.options[data.selectedIndex].text;
        }

        if (lastValue != source.value) {
            source.setAttribute('lastValue', source.value);
        }
    }
    catch (ex) {
    }
}

function setCurrentAutoCompleteValueEquals()
{
    var popup = getCurrentAutoCompleteListProperties();
    if (!popup) return;
    
    var source = popup[1];
    var data = popup[2];
    
    setAutoCompleteValueEquals(source,data);
}

function closeCurrentAutoCompleteList()
{
    setCurrentAutoCompleteValueEquals();
    deleteAutoCompleteList();    
}

function getCurrentAutoCompleteListProperties()
{
    var popup = top.document.getElementById(constAutoCompletePopupID);
    if (!popup) return;
    
    var frameName = popup.getAttribute("frameName");
    if (!frameName) return [popup];
    
    var parent = popup.getAttribute("parent") ? top.frames[frameName].document.getElementById(popup.getAttribute("parent")) : null;
    if (!parent) return [popup];    
    
    var data = popup.getAttribute("dataObject") ? top.frames[frameName].document.getElementById(popup.getAttribute("dataObject")) : null;
    if (!data) return [popup, parent];
    
    return [popup, parent, data];
}

function hideAutoCompleteList()
{
    var popup = getCurrentAutoCompleteListProperties();
    if (!popup) return;
    
    popup[0].style.display = 'none';
    isAutoCompleteListOpen = false;
}

function deleteAutoCompleteList()
{
    var popup = getCurrentAutoCompleteListProperties();
    if (!popup) return;
        
    popup[0].parentNode.removeChild(popup[0]);
    isAutoCompleteListOpen = false;
}

function deleteAutoCompleteListByTimeout(source, data)
{
    if (!isControlInFocus)
    {
        setAutoCompleteValueEquals(source, data);
        deleteAutoCompleteList();
    }
}

function createAutoCompleteList(oList, obj)
{
    if (top.isLoading)
        return;

    deleteAutoCompleteList();
    
    var popup = top.document.createElement('div');
    var table = obj.parentNode.parentNode;
    var elementPosition = top.findPos(table);
    var frame = document.getElementById(obj.getAttribute("frameName"));
    var framePosition = frame ? top.findPos(frame) : [0, 0];
    var frameScrolling = ((!top.isChrome) && (!top.isFirefox) && frame.getAttribute('scrolling').toLowerCase() == 'yes') ? scrollbarWidth : 0;

    var offsety = framePosition[1] + obj.offsetHeight + 1;
    var offsetx = framePosition[0] + frameScrolling;

    popup.id = constAutoCompletePopupID;
    popup.style.position = "absolute";
    popup.style.zindex = "10000";   
    popup.style.left = elementPosition[0] + offsetx + 'px';
    popup.style.top = elementPosition[1] + offsety + 'px';
    popup.style.width = table.offsetWidth + 'px';
    top.document.body.appendChild(popup);

    popup.innerHTML = '';
    popup.appendChild(oList);
    popup.style.display = 'block';    
    popup.setAttribute("parent", obj.getAttribute("parent"));
    popup.setAttribute("frameName", obj.getAttribute("frameName"));
    popup.setAttribute("dataObject", obj.getAttribute("dataObject"));
    
    isAutoCompleteListOpen = true;
}

function bindControlFocus(source, data, e)
{
    if (top.EnterSuppress != null)
        top.EnterSuppress = true;

    if (data.options.length > 0)
    {
        if (source.value == data.options[0].text) 
              source.select();
              
    }
    
    isControlInFocus = true;
    openAutoCompleteList(source, data, e);
}

function bindControlBlur(source, data, e)
{
    if (top.EnterSuppress != null)
            top.EnterSuppress = false;
          
    if (isControlInFocus == false) 
        return;
          
    isControlInFocus = false;

    var popup = top.document.getElementById(constAutoCompletePopupID);
    if (popup && popup.style.display == 'none')
    {
        setAutoCompleteValueEquals(source, data, e);

        if (data && data.onblur) 
            data.onblur();    
    }
    else
    {    
        setTimeout(function() { top.deleteAutoCompleteListByTimeout(source, data); if (data && data.onblur) data.onblur(); },constAutoCompletePopupTime);
    }
    
}

function bindAutoCompleteFocus(source, data, e) {
    isControlInFocus = true;
}

function bindAutoCompleteBlur(source, data, e)
{
    isControlInFocus = false;
    setTimeout(function() { top.deleteAutoCompleteListByTimeout(source, data); },constAutoCompletePopupTime);
}

function bindAutoCompleteClick(source, data, e)
{
    hideAutoCompleteList();
    setAutoCompleteValue(source, data, e);
}

function AutoCompleteSelectDeltaItem(delta)
{
    var popup = top.document.getElementById(constAutoCompletePopupID);
    if (!popup) return;
    
    popup.firstChild.selectedIndex += delta;
}

function bindControlKeydown(source, data, e)
{
    var popup = top.document.getElementById(constAutoCompletePopupID);
    switch (e.keyCode)
    {
        case 40:
          if (popup && popup.firstChild.selectedIndex < popup.firstChild.options.length - 1)
            popup.firstChild.selectedIndex += 1;
          break;
        case 38:
          if (popup && popup.firstChild.selectedIndex > 0)
              popup.firstChild.selectedIndex -= 1;
          break;
        case 13:
        case 9:
            if (popup && popup.style.display != 'none')
                source.value = popup.firstChild.options[popup.firstChild.selectedIndex].text;
            hideAutoCompleteList();
            setAutoCompleteValueEquals(source, data, e);
            if (data.onchange != null)
                data.onchange();
            break;
        default:
          break;
    }
}

function buildAutoCompleteList(source, data, e, overrideDisplay)
{
    var oList = top.document.createElement('select');
    var selected = -1;
    
    if (!data || !source || e.keyCode == 13)
        return;
        
    var sourceLastText = source.getAttribute("lastValue") ? source.getAttribute("lastValue").toUpperCase().trim() : '';
    var sourceText = source.value.toUpperCase().trim();    
    
    if (sourceText == '' &&  sourceText != sourceLastText) 
        overrideDisplay = true;
    
    if (!overrideDisplay && sourceLastText == sourceText)
        return;

    source.setAttribute('lastValue',source.value);
    
    oList.dir = source.getAttribute("isRightToLeft") ? 'rtl' : 'ltr';
    oList.style.width = '100%';
    oList.style.fontSize = '12px';

    oList.onfocus = function() { top.bindAutoCompleteFocus(source, data, e); };
    oList.onblur = function() { top.bindAutoCompleteBlur(source, data, e); };
    oList.onclick = function() { top.bindAutoCompleteClick(source, data, e); };
    
    for (var i=0; i < data.options.length; i++)
    {
        var text = data.options.item(i).text;
        var value = data.options.item(i).value;
       
        if ((value < 0 && sourceText.length != 0 && !overrideDisplay) || (value == -99)) continue;
        
        var index = text.toUpperCase().indexOf(sourceText);

        if (index>=0 || overrideDisplay)
        {
            if (index == 0 && selected == -1)
                selected = oList.length;
            
            oList.options[oList.length] = new Option(data.options[i].text, i, false, false);
        }
    }
    
    if (oList.length == 0)
    {
        hideAutoCompleteList();
        return;
    }
    
    oList.options[selected != -1 ? selected : 0].selected = true;
    
    oList.size = (oList.length > 10) ? '10' : ((oList.length == 1) ? '2' : oList.length);

    createAutoCompleteList(oList,source);

    if (oList.length == 1 && oList.options[0].text.toUpperCase() == sourceText)
    {
        hideAutoCompleteList();
        
        if (oList.length == 1)
             setAutoCompleteValue(source, data, e);
    }
}



function bindAutoCompleteControl(frameName, srcObjectID, dataObjectID, isRightToLeft, locked)
{
    var source = top.frames[frameName].document.getElementById(srcObjectID);
    var data = top.frames[frameName].document.getElementById(dataObjectID);
    
    if (!source)
        return;
        
    var controlID = constAutoCompleteID + '_' + source.id;
    var control = top.frames[frameName].document.getElementById(controlID);
    
    if (!data)
    {
        source.style.display = 'none';
        return;
    }    
    
    if (scrollbarWidth == 0)
        scrollbarWidth = getScrollBarWidth();
    
    var _onkeydown = source.onkeydown ? source.onkeydown : function() { };
    var _onkeyup  = source.onkeyup ? source.onkeyup : function() {  };
    var _onfocus = source.onfocus ? source.onfocus : function() {  };
    var _onblur = source.onblur ? source.onblur : function() {  };
    var _onchange = source.onchange ? source.onchange: function() { };
    
    source.onkeydown = function(e) { top.bindControlKeydown(source, data, (e ? e : top.frames[frameName].window.event)); _onkeydown(); };
    source.onkeyup = function(e) { top.buildAutoCompleteList(source, data, (e ? e : top.frames[frameName].window.event)); _onkeyup(); };
    source.onfocus = function(e) { top.bindControlFocus(source, data, (e ? e : top.frames[frameName].window.event)); _onfocus(); };
    source.onblur = function(e) { top.bindControlBlur(source, data, e ? e : top.frames[frameName].window.event); _onblur(); };
    source.onchange = function(e) { top.setAutoCompleteValueEquals(source, data, (e ? e : top.frames[frameName].window.event)); _onchange(); };

    source.setAttribute("parent", source.id);
    source.setAttribute("frameName", frameName);    
    source.setAttribute("dataObject", data.id);    
    source.setAttribute("isRightToLeft", isRightToLeft);    
   
    source.value = data.options[data.selectedIndex].text;
    source.setAttribute('lastValue', source.value);
    
    data.setAttribute("bindTextbox", source.id);
    data.style.display = 'none';
    
    var div;
    if (!control)
    {
        source.parentNode.removeChild(source);
        
        var table = top.frames[frameName].document.createElement("table");

        table.id = controlID;
        table.cellPadding = '0';
        table.cellSpacing = '0';
        table.className = 'clsAutocompleteTable';
        

        table.style.margin = '0';
        table.style.padding = '0';    
        table.style.borderCollapse = 'collapse';
        
        table.style.width = source.clientWidth + 15 + 'px';
        
        data.parentNode.appendChild(table);    
       
        var row = table.insertRow(0);
        var columnSource = row.insertCell(0);
        var columnButton = row.insertCell(1);    

        source.style.border = '1px solid white';
        
        columnSource.appendChild(source);

        var div = top.frames[frameName].document.createElement("div");
        
        div.style.background = 'url(Images/se1.gif) no-repeat center center';
        div.style.width = 15 + 'px';
        div.style.height = 17 + 'px';
        div.style.border = '1px solid white';
        
        div.onmouseover = function() { this.style.backgroundImage = 'url(Images/se2.gif)'; };
        div.onmouseout = function() { this.style.backgroundImage = 'url(Images/se1.gif)'; };
        
        
        columnButton.style.padding = '1px 0px';       
        columnButton.appendChild(div);
        
        table.style.width = table.clientWidth + 'px';
        
    }
    else
    {
        div = control.rows[0].cells[1].firstChild;
    }

    div.onclick = function(e) { top.openAutoCompleteList(source, data, (e ? e : top.frames[frameName].window.event)); };
    div.setAttribute("parent", source.id);
    div.setAttribute("frameName", frameName);    

   if (locked)
   {
        source.value = data.options.length > 0 ? data.options[0].text : '';
        lockAutoComplete(source);
   }
}

function resetAutoCompleteControl()
{    
    var popup = getCurrentAutoCompleteListProperties();
    if (!popup) return;

    popup[1].value = popup[2].options[popup[2].selectedIndex].text;
}

function getDocumentByFrame(frameName)
{
    return frameName ? top.frames[frameName].document : document;
}

function getElementByFrame(frameName, elementID)
{
    return getDocumentByFrame(frameName).getElementById(elementID);
}

function getFrameEvent(frameName)
{
    return frameName ? top.frames[frameName].window.event : window.event;
}

function getAutoCompleteTableCells(source) {
    var table = source;
    while (table = table.parentNode) {
        if (table.tagName.toLowerCase() == 'tr')
            return table.getElementsByTagName('td');
    }
}

function getAutoCompleteTable(source) {
    var table = source;
    while (table = table.parentNode) {
        if (table.tagName.toLowerCase() == 'table')
            return table;
    }
}

function getAutoCompleteDataObject(source) {
    var frameName = source.getAttribute("frameName");
    return getElementByFrame(frameName, source.getAttribute("dataObject"));    
}


function lockAutoComplete(source) {
    var button = getAutoCompleteTableCells(source)[1].firstChild;

    button.disabled = true;
    source.disabled = true;
}

function unlockAutoComplete(source, value) {
    var button = getAutoCompleteTableCells(source)[1].firstChild;

    button.disabled = false;
    source.disabled = false;
   
    var data = getAutoCompleteDataObject(source);
    if (data && data.options.length > 0) {
        source.value = data.options[data.selectedIndex].text;
    }
}

function refreshAutoComplete(frame, data, locked)
{
   if (!data) return;
   var sourceName = data.getAttribute('bindTextbox');       
   if (!sourceName) return;
   var source = getElementByFrame(frame, sourceName);       
   if (!source) return;
   
   if (locked)
   {
        source.value = data.options.length > 0 ? data.options[0].text : '';
        lockAutoComplete(source);
        return;
   }
   
   if (data.options.length > 0) 
   {           
        source.value = data.options[data.selectedIndex].text;
        unlockAutoComplete(source);
   }
}
