var Pipe = Pipe || {};
Pipe.createList = function (field, entity, dispAttr, sysAttr, filter) {
    var el = document.getElementById('el_' + field);
    var pc, pt, pi;
    if (el.isPiped !== undefined && el.isPiped != null) {
        pc = document.getElementById('pc_' + field);
        if (pc != null)
            el.parentNode.removeChild(pc);
        pt = document.getElementById('pt_' + field);
        if (pt != null)
            el.parentNode.removeChild(pt);
        pi = document.getElementById('pi_' + field);
        if (pi != null)
            el.parentNode.removeChild(pi);
        el.isPiped = null;
    }

    if (dispAttr == null)
        dispAttr = 'DisplayName';
    if (sysAttr == null)
        sysAttr = 'SystemName';

    pc = document.createElement('div');
    pc.id = 'pc_' + field;
    pc.className = 'pipeContainer';

    pt = document.createElement('input');
    pt.type = 'text';
    pt.id = 'pt_' + field;
    pt.className = 'pipeTextInput';

    pi = document.createElement('div');
    pi.id = 'pi_' + field;
    pi.style.overflow = 'hidden';
    pi.style.border = '0';
    pi.style.fontSize = '0.8em';
    pi.style.height = '100px';

    pc.appendChild(pt);
    pc.appendChild(pi);

    el.parentNode.appendChild(pc);
    el.style.display = 'none';

    var highlighted = 'highlightlookuprow';
    pc.onclick = function () { pt.focus(); };
    var i, rows;

    pt.onkeyup = function (e) {
        e = e || window.event;

        if (e.keyCode == 13) { //Enter Pressed
            if (pi.firstChild == null)
                return;
            rows = pi.getElementsByTagName('tr');
            for (i = 0; i < rows.length; i++) {
                if (rows[i].className == highlighted) {
                    addPipeItem(rows[i]);
                    return;
                }
            }
            return;
        }

        if (e.keyCode == 40) { //Down Pressed
            if (pi.firstChild == null)
                return;
            rows = pi.getElementsByTagName('tr');
            for (i = 0; i < rows.length - 1; i++) {
                if (rows[i].className == highlighted) {
                    rows[i].className = null;
                    rows[i + 1].className = highlighted;
                    return;
                }
            }
            return;
        }

        if (e.keyCode == 38) { //Up Pressed
            if (pi.firstChild == null)
                return;
            rows = pi.getElementsByTagName('tr');
            for (i = 1; i < rows.length; i++) {
                if (rows[i].className == highlighted) {
                    rows[i].className = null;
                    rows[i - 1].className = highlighted;
                    return;
                }
            }
            return;
        }

        if (e.keyCode != 9 && e.keyCode != 16) { //For all except Shift and Tab
            while (pi.childNodes.length > 0)
                pi.removeChild(pi.lastChild);
            if (pt.value == '')
                return;
            var data = getDataTable(pt.value);
            pi.appendChild(data);
            rows = pi.getElementsByTagName('tr');
            if (rows.length > 0)
                rows[0].className = highlighted;
        }
    };

    pi.onclick = function (e) {
        e = e || window.event;
        var row = e.target || e.srcElement;

        while (row.nodeName != 'TR' && row.nodeName != 'DIV')
            row = row.parentNode;
        if (row.nodeName != 'TR') {
            pt.focus();
            return;
        }
        addPipeItem(row);
    };

    function addPipeItem(row) {
        var newVal = row.getAttribute('data-value');
        appendPipeItem(row.firstChild.innerHTML, newVal);
        var oldVals = (el.value != '') ? el.value : '|';
        el.value = oldVals + newVal + '|';
        Famark.triggerChange(el);
    }

    function appendPipeItem(text, value) {
        var span = document.createElement('span');
        span.className = 'pipeItem';
        var txt = document.createTextNode(text);
        span.appendChild(txt);
        var spanClose = document.createElement('span');
        spanClose.className = 'pipeItemClose';
        spanClose.innerHTML = 'x';
        spanClose.onclick = function () { removePipeItem(span); };
        span.appendChild(spanClose);
        span.setAttribute('data-value', value);
        pc.insertBefore(span, pt);

        while (pi.childNodes.length > 0)
            pi.removeChild(pi.lastChild);

        pt.value = '';
        pt.focus();
        return span;
    }

    function removePipeItem(span) {
        pc.removeChild(span);
        var remVal = '|' + span.getAttribute('data-value') + '|';
        remVal = remVal.toUpperCase();
        var allVals = el.value.toUpperCase();
        var remIndex = allVals.indexOf(remVal);
        if (remIndex >= 0) {
            el.value = el.value.substring(0, remIndex) + el.value.substring(remIndex + remVal.length - 1);
            if (el.value == '|')
                el.value = '';
            Famark.triggerChange(el);
        }
    }

    var url, http, result, records;
    var spnError;

    function getDataTable(key) {

        url = 'Data.ashx?entity=' + entity + '&columns=' + dispAttr + ',' + sysAttr + '&pageSize=4&pageIndex=0' +
                     '&search=' + window.encodeURIComponent(key);

        var fullFilter;
        if (el.value != '') {
            var exFilter = sysAttr + '=!' + el.value;
            if (filter != null) {
                var ucFilter = '&' + filter.toUpperCase();
                var ucSysAttr = '&' + sysAttr.toUpperCase() + '=';

                fullFilter = (ucFilter.indexOf(ucSysAttr) < 0) ? filter + '&' + exFilter : filter;
            } else {
                fullFilter = exFilter;
            }
        } else
            fullFilter = filter;

        if (fullFilter != null)
            url += '&filter=' + window.encodeURIComponent(fullFilter);

        http = new XMLHttpRequest();
        http.open("GET", url, false);
        http.send();
        result = Famark.parseJSON(http.responseText);

        if (result.ErrorMessage == null || result.ErrorMessage == '') {
            records = result.Output;
            if (records.length > 0) {
                var table = document.createElement('table');
                for (i = 0; i < records.length; i++) {
                    var tr = table.insertRow(i);
                    var td = tr.insertCell(0);
                    td.innerHTML = records[i].Fields[0].Value;
                    tr.setAttribute('data-value', records[i].Fields[1].Value);
                }
                return table;
            }
            return document.createElement('span');
        }

        spnError = document.createElement('span');
        spnError.innerHTML = result.ErrorMessage;
        return spnError;
    }

    el.setPipeList = function () {
        while (pc.childNodes.length > 2)
            pc.removeChild(pc.firstChild);

        if (el.value == '')
            return;

        if (el.value == '|') {
            el.value = '';
            return;
        }

        if (el.value === '********') {
            el.value = '';
            pt.value = '********';
            pt.style.backgroundColor = '#dddddd';
            pc.style.backgroundColor = '#dddddd';
            return;
        }

        if (el.value.indexOf('|') != 0)
            el.value = '|' + el.value;
        if (el.value.lastIndexOf('|') != (el.value.length - 1))
            el.value = el.value + '|';

        url = 'Data.ashx?entity=' + entity + '&columns=' + dispAttr + ',' + sysAttr;
        if (filter != null)
            url += '&filter=' + window.encodeURIComponent(filter + '&' + sysAttr + '=' + el.value);
        else
            url += '&filter=' + window.encodeURIComponent(sysAttr + '=' + el.value);

        http = new XMLHttpRequest();
        http.open("GET", url, false);
        http.send();
        result = Famark.parseJSON(http.responseText);
        if (result.ErrorMessage == null || result.ErrorMessage == '') {
            records = result.Output;
            var items = el.value.split('|');
            items.shift();
            items.pop();
            for (i = 0; i < records.length; i++) {
                var itemVal = records[i].Fields[1].Value;
                appendPipeItem(records[i].Fields[0].Value, itemVal);
                var itemIndex = items.indexOf(itemVal);
                items.splice(itemIndex, 1);
                if (items.length == 0)
                    break;
            }
            for (i = 0; i < items.length; i++) {
                var erSpan = appendPipeItem(items[i], items[i]);
                erSpan.style.backgroundColor = 'red';
            }
        }
        else {
            spnError = document.createElement('span');
            spnError.innerHTML = result.ErrorMessage;
            pi.appendChild(spnError);
        }
    };

    el.disablePipeList = function (isTrue) {
        var pis = Famark.getElementsByClassName('pipeItemClose', 'span', pc);

        if (isTrue) {
            pc.className = 'pipeContainerDisabled';
            for (i = 0; i < pis.length; i++)
                pis[i].style.visibility = 'hidden';
            pt.style.visibility = 'hidden';
            return;
        }

        pc.className = 'pipeContainer';
        for (i = 0; i < pis.length; i++)
            pis[i].style.visibility = 'visible';
        pt.style.visibility = 'visible';
    };

    el.changePipeFilter = function (newFilter) {
        filter = newFilter;
        el.setPipeList();
    };

    window.setTimeout(el.setPipeList, 200);
    el.isPiped = 'true';
};