var selArray_title = false;
var dynamic_ab = {};

document.onclick = function (e) {
    if (typeof(e) == 'undefined') { // IE code
        e = window.event;
    }
    var obj;
    if (typeof(e.srcElement) != 'undefined') {
        obj = e.srcElement;
    }
    else if (typeof(e.target) != 'undefined') {
        obj = e.target;
    }
    if (typeof(obj) == 'undefined') {
        return;
    }
    for (var fieldname in dynamic_ab) {
        var ab = ab_get(fieldname);
        if (typeof(ab) != 'undefined') {
            if ((obj.id != 'dynamic_ab_'+fieldname) && (obj.id != 'ab_compose_'+fieldname)) {
                ab.hide();
            }
        }
    }
}

function ab_keyup (field, e) {
    var ab = ab_get(field);
    switch (e.keyCode) {
        // action keys
        case 27: // Esc
            ab.hide();
            return false;
        case 13: // Enter
            ab.insert();
            return false;
        case 38: // Up
        case 40: // Down
        case 33: // Page Up
        case 34: // Page Down
            if (ab.is_show()) {
                return false;
            }
            else if (ab.found) {
                ab.show();
                ab.movetop();
                return false;
            }
        case 37: // Left
        case 39: // Right
        case 35: // End
        case 36: // Home
            return true;
        case 9:  // Tab
            ab.hide();
            return true;
        case 8:  // Backspace
        default:
            ab.draw();
            break;
    }
}

function ab_keydown (field, e) {
    var ab = ab_get(field);
    switch (e.keyCode) {
        case 27: // Esc
            ab.hide();
            return false;
        case 38: // Up
            ab.moveup();
            return false;
        case 40: // Down
            ab.movedown();
            return false;
        case 33: // Page Up
            ab.movetop();
            return false;
        case 34: // Page Down
            ab.movebottom();
            return false;
        case 13: // Enter
            ab.insert();
            return false;
        case 9:  // Tab
            ab.hide();
            return true;
        default:
            return true;
    }
}

function ab_keypress (field, e) {
    return (e.keyCode == 13) ? false : true;
}

function ab_click (field, e) {
    var ab = ab_get(field);
    if (ab.is_show()) {
        ab.hide();
    }
    else if (ab.found) {
        ab.draw();
    }
}

function ab_mouseover (field_name, index) {
    var ab = ab_get(field_name);
    ab.mouseover(index);
}

function ab_mouseclick (field_name, index) {
    var ab = ab_get(field_name);
    ab.insert(index);
}

function ab_get (field) {
    if (typeof(field) != 'object') {
        field = document.getElementById('ab_compose_'+field);    
    }
    if (typeof(field.name) == 'undefined') {
        return false;
    }
    if (typeof(dynamic_ab[field.name]) == 'undefined') {
        dynamic_ab[field.name] = new AB(field);
    }
    ab_setid(field);
    return dynamic_ab[field.name];
}


// AB object

function AB (field) {
    this.ab = document.createElement('div');
    this.ab.id = 'dynamic_ab_' + field.name;
    this.ab.className = 'dynamic_ab';
    this.field = field;

    var div = document.createElement('div');
    div.className = 'dynamic_ab_placeholder';

    this.field.parentNode.appendChild(div);
    div.appendChild(this.ab);

    this.show = AB_show;
    this.hide = AB_hide;
    this.is_show = AB_is_show;
    this.draw = AB_draw;
    this.select = AB_select;
    this.moveup = AB_moveup;
    this.movedown = AB_movedown;
    this.movetop = AB_movetop;
    this.movebottom = AB_movebottom;
    this.mouseover = AB_mouseover;
    this.insert = AB_insert;
    //this.setid = AB_setid;

    this.index = 0;
    this.search = '';
    this.found = 0;
    this.is_drawing = false;
    this.items = selArray.length;
    this.hidemask = new Array(this.items);
}

function AB_show () {
    this.ab.style.display = 'block';
}

function AB_hide () {
    this.ab.style.display = 'none';
}

function AB_is_show () {
    return (this.ab.style.display == 'block') ? 1 : 0;
}

function AB_moveup () {
    if (this.is_show() && this.found) {
        var index = this.index;
        while (true) {
            index--;
            if (index < 0) {
                index = this.items - 1;
            }
            if (this.hidemask[index] == 0) {
                break;
            }
        }
        this.select(index);
    }
}

function AB_movedown () {
    if (this.is_show() && this.found) {
        var index = this.index;
        while (true) {
            index++;
            if (index >= this.items) {
                index = 0;
            }
            if (this.hidemask[index] == 0) {
                break;
            }
        }
        this.select(index);
    }
}

function AB_movetop () {
    if (this.is_show() && this.found) {
        var index = 0;
        while (true) {
            if (this.hidemask[index] == 0) {
                break;
            }
            index++;
        }
        this.select(index);
    }
}

function AB_movebottom () {
    if (this.is_show() && this.found) {
        var index = this.items - 1;
        while (true) {
            if (this.hidemask[index] == 0) {
                break;
            }
            index--;
        }
        this.select(index);
    }
}

function AB_mouseover (index) {
    this.select(index);
}

function AB_draw () {
    if (this.is_drawing) {
        alert('busy');
        return true;
    }
    // enter critical section
    this.is_drawing = true;
    // get search pattern
    var search = this.field.value;
    var insert_pos;
    if ((insert_pos = search.lastIndexOf(',')) > 0) {
        search = search.substr(insert_pos + 1);
    }
    search = search.replace(/^\s+/, '');

    var re_space = new RegExp('\\S');
    if (!re_space.test(search)) {
        this.hide();
        this.search = '';
        this.found = 0;
        this.is_drawing = false;
        return true;
    }
    if (search != this.search) {
    this.search = search;
//    var search_re = '(^|\\s|<|\\")' + search.replace(/([\\\^\$\*\+\?\{\}\.\(\)\|\[\]])/g, "\\$1");
    var search_re = '(^|<|\\")' + search.replace(/([\\\^\$\*\+\?\{\}\.\(\)\|\[\]])/g, "\\$1");
    var search_re1 = '(^|<|\\")' + 'GA-' + search.replace(/([\\\^\$\*\+\?\{\}\.\(\)\|\[\]])/g, "\\$1");
    var search_re2 = '(^|<|\\")' + 'GV-' + search.replace(/([\\\^\$\*\+\?\{\}\.\(\)\|\[\]])/g, "\\$1");
    var re = new RegExp(search_re, 'i');
    var re1 = new RegExp(search_re1, 'i');
    var re2 = new RegExp(search_re2, 'i');
    var html = '';
    var found = 0;
    // search for matches
    var matches = 0;
    for (var i in selArray) {
        if ((selArray[i].search(re1) != -1 || selArray[i].search(re) != -1 || selArray[i].search(re2) != -1) && selArray[i] != search && matches < 100) {
            found += 1;
            this.hidemask[i] = 0;
            matches++;
        }
        else {
            this.hidemask[i] = 1;
        }
    }
    this.found = found;
    // select next visible matching item (if needed)
    if (found) {
        while (true) {
            if (this.hidemask[this.index] == 1) {
                this.index++;
                if (this.index >= this.items) {
                    this.index = 0;
                }
            }
            else {
                break;
            }
        }
        for (var i in selArray) {
            if (this.hidemask[i] == 0) {
                var item_html = html_escape(selArray[i]);
//                html += '<tr><td'+((i==this.index)?' class="active"':'')+' onmouseover="ab_mouseover(\''+this.field.name+'\','+i+');" onclick="ab_mouseclick(\''+this.field.name+'\','+i+');" id="ab_entry_'+this.field.name+'_'+i+'" nowrap><a href="#">'+item_html+'</a></td></tr>';
                html += '<tr><td'+((i==this.index)?' class="active"':'')+' onmouseover="ab_mouseover(\''+this.field.name+'\','+i+');" onclick="ab_mouseclick(\''+this.field.name+'\','+i+');" id="ab_entry_'+this.field.name+'_'+i+'" nowrap>'+item_html+'</td></tr>';
            }
        }
        this.ab.innerHTML = '<div class="dynamic_ab_list"><table width="100%" cellspacing="0" cellpadding="2" border="0" class="drowned"><tr><td><table width="100%" cellspacing=0 cellpadding=0 border=0 bgcolor="#FFFFFF">'+((selArray_title != false) ? '<tr><td class=title nowrap>'+selArray_title+':</td></tr>' : '') +html+'</table></td></td></table></div>';
        this.ab.childNodes[0].style.height = (found > 7) ? '15.2em': 'auto';
        if (!this.is_show()) {
            this.show();
        }
    }
    else {
        // hide selArray
        this.hide();
        this.ab.innerHTML = '';
    }
    }
    else if (this.found) {
        this.show();
    }
    // leave critical section
    this.is_drawing = false;
}

function AB_select (index) {
    if (this.index == index) {
        return true;
    }
    if (index < 0 || index >= this.items) {
        return false;
    }
    var oldentry = document.getElementById('ab_entry_' + this.field.name + '_'+ this.index);
    if (typeof(oldentry) == 'object') {
        oldentry.className = '';
    }
    var newentry = document.getElementById('ab_entry_' + this.field.name + '_'+ index);
    if (typeof(newentry) == 'object') {
        newentry.className = 'active';
        newentry.focus(); // IE, Opera, Firefox, Netscape
//        if ((navigator.userAgent.indexOf('MSIE') != -1) || (navigator.userAgent.indexOf('Opera') != -1)) {
//            newentry.focus(); // IE
//        } else {
//            newentry.childNodes[0].focus(); // Firefox
//        }
        this.field.focus();
    }
    this.index = index;
    return true;
}

function AB_insert () {
    if (!this.is_show()) {
        return false;
    }
    var value = this.field.value;
    var insert_pos = value.lastIndexOf(',');
    if (insert_pos > 0) {
        value = value.substr(0, insert_pos + 1);
        value += ' ';
    } else {
        value = '';
    }
    value += selArray[this.index];

    this.hide();
    this.index = 0;
    this.search = '';
    this.found = 0;
    this.field.value = value;
    this.field.focus();

    return true;
}

function ab_setid(field) {
    var field_id = document.getElementById(field.name+'_id');
    if (!field_id) {
        return false;
    }
    field_id.value = '0';
    for (var i in selArray) {
        if (field.value.toLowerCase() == selArray[i].toLowerCase())
        {
            //set hidden id field
            field_id.value = selArray_id[i];
            return true;
        }
    }
    return false;
}

function html_escape (text) {
    var html = '';
    for (var i=0; i < text.length; i++) {
        switch (text.charAt(i)) {
            case '&':
                html += '&amp;';
                break;
            case '"':
                html += '&quot;';
                break;
            case '>':
                html += '&gt;';
                break;
            case '<':
                html += '&lt;';
                break;
            case '%':
                html += '&#037;';
                break;
            case '\'':
                html += '&#039;';
                break;
            default:
                html += text.charAt(i);
                break;
        }
    }
    return html;
}
