// JScript File
// When debug, please comment out "input_box.onblur=hideDropDown;" in initInputBox() function.
//
//jason var ACQ_SERVER='//quote.morningstar.com';
var ACQ_SERVER = '';

// FOR DEBUG
//var ACQ_SERVER='http://localhost';
//var TAB_KEY = false;

//jason var ACQHandlerURL = "/acindex/acq.ashx?callback=j_callback&out=j&key=";
var ACQHandlerURL = "/newport/tickercomplete.ashx?callback=j_callback&out=j&key=";
var ACQ_ROW_DELIMITER = "}]";
var ACQ_COL_DELIMITER = "[|";
var HEADER_ROWS = 3;
var Current_Value = "";
var CACHE_SIZE = 30;
var Cache = new Array(CACHE_SIZE);
var NextCachePos = 0;
var MAX_SHOWN = 20;
var ShownEntries = new Array(MAX_SHOWN);
var SelectedIndex = -1;
var NumShownEntries = 0;
var DataPrefix = "ACDEntry_";
var DPLen = DataPrefix.length;

var ENTRY_SELECT_COLOR = '#D7E7FC';
var ENTRY_COLOR = 'white';

var KEY_DELIMITER = ',';
var HIDE_DELAY_MS = 200;
var KEYS_DELAY_MS = 500;
var KeysIn = 0;
var REFOCUS_DELAY_MS = 50;

var QUOTE_SERVER = 'http://quote.morningstar.com/switch.html?pgid=hetopquote&ticker=';

var ACINPUT_ID = 'AutoCompleteBox';
var ACINPUT_ID_CONSTANT = 'AutoCompleteBox';
var ACDROPDOWN_ID = 'AutoCompleteDropDown';
var ACMESSAGE_ID = 'AutoCompleteMessage';

var IgnoreFuncKey = false;
var IgnoreAppleArrowKey = false;
var DoubleEvtForArrow = false;
var UseAppleWebKit = false;
var FireFoxOnMac = false;
var JRequests = new Array();
var AlertFlag = document.getElementById('ASXCode_hdn2');

try{
AlertFlag.value = false;
}
catch (err)
{
}

var ACQMoreURL = "/Search/MoreResults/";

initAutoCompleteBox();

function CheckOSBrowser() {
    var agent = navigator.userAgent;
    if (agent != null) {
        //alert(agent);
        var start = agent.indexOf("AppleWebKit/");
        if (start > 0) {
            UseAppleWebKit = true;
            var awk_ver = agent.substr(start + 12, 3);
            if (awk_ver < 500) {
                DoubleEvtForArrow = true;
            }
        } else {
            // special handleing needed for firefox on mac
            start = agent.indexOf("Mac OS");
            if (start > 0) {
                start = agent.indexOf("Firefox");
                if (start > 0) {
                    FireFoxOnMac = true;
                }
            }
        }
    }
}

function leftTrim(str) {
    //alert('left')
    a = str.replace(/^\s+/, '');
    // return a.replace(/\s+$/, '');
    return a;
}

function initCache() {
    for (var c = 0; c < CACHE_SIZE; c++) {
        Cache[c] = null;
    }
    //alert('init cache done.');
}

function resetShownEntries() {
    for (var i = 0; i < MAX_SHOWN; i++) {
        ShownEntries[i] = null;
    }

    NumShownEntries = 0;

    //alert('ShownEntries reset');
}

function initAutoCompleteBox() {
    ACQHandlerURL = ACQ_SERVER + ACQHandlerURL;
    CheckOSBrowser();
    initCache();
    resetShownEntries();
    initInputBox();
    //initDropDown();    
}

function initInputBox() {
    var input_box;
    displayMessage(false);
    try {
        //input_box = document.getElementById(ACINPUT_ID);
        var inputBoxes = document.getElementsByTagName("input");
        for (var i = 0; i < inputBoxes.length; i++) {
            var inputBox = inputBoxes[i];
            if (inputBox.type != "text") continue;
            var isAutoComplete = inputBox.getAttribute("tickerComplete");
            var addFeature = !(!isAutoComplete || isAutoComplete.toUpperCase() != "ON");
            if (inputBox.id == ACINPUT_ID_CONSTANT) {
                inputBox.onkeydown = inputBox.onkeyup = inputBox.onblur = null;
                addFeature = true;
            }
            if (addFeature == false) continue;
            addListener(inputBox, "keydown",
				function(evt) {
				    var srcEle = (evt.srcElement ? evt.srcElement : evt.target);
				    ACINPUT_ID = srcEle.id;
				    var result = checkFuncKey(evt);
				    if (result == true) return true;
				    if (evt.stopPropagation)	//for firefox
				        evt.preventDefault();
				    else
				        evt.returnValue = false;
				    return false;
				}
			);
            addListener(inputBox, "keyup", j_sendQuery);
            addListener(inputBox, "blur", loseFocus);
        }
        //alert('initInputBox done.');
    }
    catch (ae) {
    }
}

function loseFocus(ev) {
    // must use a timed delay in case the mouse clicked the drop down.
    window.setTimeout(hideDropDown, HIDE_DELAY_MS);
}

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl, jsid) {
    // REST request path
    this.fullUrl = fullUrl;
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = jsid;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function() {

    // Create the script tag
    this.scriptObj = document.createElement("script");

    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}

// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function() {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function() {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

function MyJRequester() {
}

MyJRequester.prototype.setTimer = function(curentkeys, key, src) {
    var myClass = this;

    function timerRelay() {
        myClass.handleTimer(curentkeys, key, src);
    }

    setTimeout(timerRelay, KEYS_DELAY_MS);
}

MyJRequester.prototype.handleTimer = function(curentkeys, key, src) {

    if (curentkeys == KeysIn) {
        displayMessage(true);
        var jsid = 'JD' + JSONscriptRequest.scriptCounter;
        JSONscriptRequest.scriptCounter++;
        var url = ACQHandlerURL + encodeURIComponent(key) + '&js=' + jsid;
       // alert("vid=" + src.getAttribute("viewid"));
       // if (src.getAttribute("viewid") == "44") {
        //    url = url + '&viewid=' + src.getAttribute("viewid");
       //              document.getElementById('ASXCode_hdn2').value = true;
           
       // } else {
 
        document.getElementById('ASXCode_hdn2').value = false;
      //  }


        var Req = new JSONscriptRequest(url, jsid);

        Req.buildScriptTag();
        JRequests[JRequests.length] = Req; // append to the request queue
        Req.addScriptTag();  // call it.
        // alert("2.ALLOKUP=" + this.isAlertLookup);
    } else {
    }
}

function j_sendQuery(kp) {

    if ((kp.srcElement ? kp.srcElement : kp.target).id != ACINPUT_ID) return;
    var key = '';
    var input_box;
    var ret = false;

    //alert(IgnoreFuncKey);
    if (IgnoreFuncKey) {
        IgnoreFuncKey = false;
        return ret;
    }
    if (IgnoreAppleArrowKey) {
        IgnoreAppleArrowKey = false;
        return ret;
    }

    key = getCurrentKey();

    //alert(key);

    key = key.toLowerCase();

    if (key == Current_Value) {
        // same value, nothing to be done.
        return ret; //ret;
    }

    if (key.length == 0) {
        Current_Value = "";
        displayRecord(null);
        SelectedIndex = -1;
        return ret; // ret;
    }


    Current_Value = key;

    // check cache.
    if (document.getElementById('ASXCode_hdn2').value != 'true') {
        initCache();
        var cache_hit = 1;
        for (var i = 0; i < CACHE_SIZE; i++) {
            cache_hit = isRecordHit(key, Cache[i]);
            if (cache_hit == 0) {
                //alert('cache hit');
                displayRecord(Cache[i]);
                return ret; // ret;
            }
        }
    }
    KeysIn = KeysIn + 1;
    //alert('query server');
    var c = new MyJRequester();
    c.setTimer(KeysIn, key, kp.target);

    return ret;
}




function j_callback(resultset) {



    //alert('callback');
    var jdata = resultset.ResultSet;
    if (jdata.result.length > 0) {
        processResult(jdata.result);
    }

    // remove the request node.
    var Req = null;
    for (var i = 0; i < JRequests.length; i++) {
        if (JRequests[i] != null) {
            //alert(JRequests[i].scriptId + ' : ' + jdata.jsid);
            if (JRequests[i].scriptId == jdata.jsid) {
                Req = JRequests[i];
                break;
            }
        }
    }

    if (Req != null) {
        //alert('found');
        JRequests.splice(i, 1); // remove this entry.
        Req.removeScriptTag();
    }

}

function delayedHideDropDown() {
    if (Current_Value.length != 0) {
        Current_Value = "";
        displayRecord(null);
    }
}

function hideDropDown() {
    // remove focus
    var input_box = document.getElementById(ACINPUT_ID);
    if (input_box && ACINPUT_ID == ACINPUT_ID_CONSTANT) {
        input_box.blur();
    }

    if (Current_Value.length != 0) {
        Current_Value = "";
        displayRecord(null);
    }
}
function moveArrow(delta) {
    //alert('move arrow' + delta + ' ' + SelectedIndex);
    var idx = SelectedIndex;

    if (delta > 0) {
        idx++;
    } else if (delta < 0) {
        idx--;
    }
    if (idx < 0) {
        //        if (SelectedIndex == -1) {
        //            idx = NumShownEntries - 1;
        //        } else {
        //            idx = -1;
        //        }
        idx = NumShownEntries - 1;
    }
    else if (idx >= NumShownEntries) {
        //        if (SelectedIndex == NumShownEntries - 1) {
        //            idx = -1;
        //        } else {
        //            idx = 0;
        //        }
        idx = 0;
    }
    ACDSelectEntry(DataPrefix + idx);
    //alert(SelectedIndex);
    //    if (UseAppleWebKit) {
    //    	// for apple, we need to manually move the cursor to the end
    //    	setCaretToEnd(ACINPUT_ID);
    //    }
}

function setCaretToEnd(objid) {
    var obj = document.getElementById(objid);
    if (obj == null) {
        return;
    }
    var pos = obj.value.length;
    if (obj.createTextRange) {
        /* Create a TextRange, set the internal pointer to  
        a specified position and show the cursor at this  
        position  
        */
        var range = obj.createTextRange();
        range.move("character", pos);
        range.select();
    } else if (obj.selectionStart) {
        /* Gecko is a little bit shorter on that. Simply  
        focus the element and set the selection to a  
        specified position  
        */
        obj.focus();
        obj.setSelectionRange(pos, pos);
    }
}
function fallbackSearch(content) {
    //  alert('fallback');
    // NOTICE: This part ONLY works under with the page that has searchForm
    var sf = document.searchForm;
    if (sf != null) {
        sf.SrchTerm.value = escape(content);
        sf.action = "http://search.morningstar.com/MstarSrch/MstarSrch2.aspx?pgid=hetopsearch";
        sf.submit();
    }
}
function quoteSearch(content) {
    var newURL = QUOTE_SERVER + escape(content);
    //alert(newURL);
    top.location = newURL;
}

function trySubmit() {

   // alert('Try/Submit ' + this.isAlertLookup);
    if (SelectedIndex >= 0) {
        replaceCurrentKey(SelectedIndex);
    }


    


    if (ACINPUT_ID != ACINPUT_ID_CONSTANT) return;

    var quoteInput = document.getElementById(ACINPUT_ID);
    if (quoteInput != null) {
        var line = quoteInput.value;
        line = removeLastDelimiter(line);
        // alert(line);
        if (line != null) {
            var str = leftTrim(line);
            if (str.length > 0) {
                var didx = str.indexOf(KEY_DELIMITER);
                if (didx >= 0) {
                    // treat as multiple tickers.
                    // still submit the whole line, not the trimmed string
                    quoteSearch(line);
                } else {
                    if (SelectedIndex >= 0 && SelectedIndex < NumShownEntries) {
                        var entry = ShownEntries[SelectedIndex];
                        if (entry.ticker == null || entry.ticker.length == 0) {
                            // there is no ticker.
                            fallbackSearch(line);
                        } else {
                            quoteSearch(line);
                        }
                    } else {
                        quoteSearch(line);
                    }
                }
            }
        }
    }
    return false; // make sure the original event is cancelled
}

function reFocus() {
    var acinput = document.getElementById(ACINPUT_ID);
    if (acinput) {
        acinput.focus();
        setCaretToEnd(ACINPUT_ID);
    }
}
//function checkFuncKey(keyID)
function checkFuncKey(kp) {
    var ret = true; // default.
    //    alert('Check');
    //    var keyID = (window.event) ? event.keyCode : kp.keyCode;
    var keyID = (window.event) ? kp.keyCode : kp.which ? kp.which : kp.charCode;

    switch (keyID) {
        case 13:            // Enter key
            if (ACINPUT_ID != ACINPUT_ID_CONSTANT) {
                trySubmit();
                hideDropDown();
                IgnoreFuncKey = true;
                return true;
            }
            return true;
        case 9:             // tab key
            if (ACINPUT_ID != ACINPUT_ID_CONSTANT) {
                trySubmit();
                hideDropDown();
                //IgnoreFuncKey = true;
                return true;
            }
            if (SelectedIndex >= 0) {
                replaceCurrentKey(SelectedIndex)
                if (UseAppleWebKit) {
                    // for apple, we need to manually move the cursor to the end
                    setCaretToEnd(ACINPUT_ID);
                } else if (FireFoxOnMac) {
                    window.setTimeout(reFocus, REFOCUS_DELAY_MS)
                }

                //debug
                //                TAB_KEY = true;
                //                setCaretToEnd(ACINPUT_ID);

                IgnoreFuncKey = true;
            }
            ret = false;
            return ret;
        case 38:            // up arrow
            moveArrow(-1);
            ret = false;
            IgnoreFuncKey = true;
            if (DoubleEvtForArrow) {
                IgnoreAppleArrowKey = true;
            }
            return ret;
        case 40:            // down arrow
            moveArrow(1);
            ret = false;
            IgnoreFuncKey = true;
            if (DoubleEvtForArrow) {
                IgnoreAppleArrowKey = true;
            }

            return ret;
        case 188:           // comma
            IgnoreFuncKey = true;
            ret = true;
            return ret;
    }

    return ret;
}

function getCurrentKey() {
    var key;
    var wholekey;
    var start = 0;
    try {
        //  alert("OLD CurrentKey");
        var input_box = document.getElementById(ACINPUT_ID);
        wholekey = input_box.value;
        if (ACINPUT_ID != ACINPUT_ID_CONSTANT) return wholekey;

        start = wholekey.lastIndexOf(KEY_DELIMITER);

        if (start >= wholekey.length) {
            key = '';
        } else {
            start++;
            key = wholekey.substr(start);
            key = leftTrim(key);
        }
        //alert(key);
    }
    catch (ae) {
        key = '';
    }

    return key;
}

function removeLastDelimiter(wholekey) {
    if (wholekey == null) {
        return null;
    }
    // get rid of the last KEY_DELIMITER if it is the last letter
    if (wholekey.length > 0) {
        var pos = wholekey.length - 1;
        if (wholekey.charAt(pos) == KEY_DELIMITER) {
            wholekey = wholekey.substr(0, pos);
        }
    }

    return wholekey;
}
function replaceCurrentKey(idx) {

    if (document.getElementById('ASXCode_hdn2').value == 'true') {
       // alert("ASXCode_hdn2");
         var entry2 = ShownEntries[idx];
         var b = document.getElementById('AlertASXCodes');
         if (b.value.length > 0) { b.value = b.value + ', ' + entry2.link; }
         else
         { b.value = b.value + entry2.link; }
         // flash field to show user interaction
        
       
        return;
     }


    var wholekey;
    var start = 0;
    var prefix = '';
    try {
        var input_box = document.getElementById(ACINPUT_ID);
        wholekey = input_box.value;
        wholekey = removeLastDelimiter(wholekey);
        start = wholekey.lastIndexOf(KEY_DELIMITER);
        if (start > 0) {
            // if equal to 0, then it's safe to ignore the first part.
            prefix = wholekey.substr(0, start) + KEY_DELIMITER;
        }

        if (idx == -1) {
            wholekey = prefix + Current_Value;
            input_box.value = wholekey;
        } else if (idx >= 0 && idx < NumShownEntries) {
            var entry = ShownEntries[idx];
            if (entry.ticker != null && entry.ticker.length > 0) {
                wholekey = prefix + entry.ticker;
                if (ACINPUT_ID == ACINPUT_ID_CONSTANT) wholekey = wholekey + KEY_DELIMITER;
                input_box.value = wholekey;

                if (entry.type == "fund") {
                    input_box.value = entry.name;
                }

                //jason
                var input_box_hdn = document.getElementById(ACINPUT_ID + "_hdn");
                input_box_hdn.value = entry.link;
                //alert("input_box_hdn.value: " + input_box_hdn.value);
                //jason
            } else if (entry.name != null && entry.name.length > 0) {
                wholekey = prefix + entry.name;
                if (ACINPUT_ID == ACINPUT_ID_CONSTANT) wholekey = wholekey + KEY_DELIMITER;
                input_box.value = wholekey;
            }
        }
    }
    catch (ae) {

    }
}

function Record(rkey, rpos, leaf, data) {
    this.key = rkey;
    this.startPos = rpos;
    this.isLeaf = leaf;
    this.data = data;
}

function DataEntry(Dticker, Dname, Dcountry, Dsrc, Dtype, Dlink) {
    this.ticker = Dticker;
    this.name = Dname;
    this.country = Dcountry;
    this.src = Dsrc;
    this.type = Dtype;
    this.link = Dlink;
}

function processResult(result) {
    //alert('processResult called');
    var record;

    var rows = result.split(ACQ_ROW_DELIMITER);
    record = new Record("", 0, 'true', null);

    //alert(rows.length);
    if (rows.length >= HEADER_ROWS) {
        // the first row is the corresponding key
        record.key = rows[0];
        // second row is the start position
        record.startPos = rows[1];
        // leaf node?
        record.isLeaf = rows[2];

        // get data.
        record.data = null;
        var size = rows.length - HEADER_ROWS;
        if (size > 0) {
            record.data = new Array(size);
            for (var i = HEADER_ROWS; i < rows.length; i++) {
                record.data[i - HEADER_ROWS] = rows[i];
            }
        }

        // put it into the cache.
        //jason if (record.data != null) {
        //Check the first row. If the search was successful, there shouldn't be an empty string.
        //Somehow this is a bug for us but not the US. 
        if ((record.data != null) && (record.data[0].length > 0)) {
            //alert(record.data.length);
            Cache[NextCachePos] = record;
            NextCachePos++;
            if (NextCachePos == CACHE_SIZE) {
                NextCachePos = 0;
            }
        }

        // display it if needed.
        var hit = isRecordHit(Current_Value, record);
        if (hit == 0) {
            displayRecord(record);
        }
    }
}
function displayMessage(yesno) {
    dropdown = document.getElementById(ACMESSAGE_ID);
    if (dropdown != null && yesno == true) {
        var inputBox = document.getElementById(ACINPUT_ID);
        if (inputBox == null) return;
        var inputBoxHDN = document.getElementById(ACINPUT_ID + '_hdn');
        if (inputBoxHDN == null) return;
        inputBoxHDN.value = ''; // to clear hidden value if change in autocomplete is happened.       
        var position = findPosition(inputBox);
        dropdown.style.left = position[0] - 9 + "px";
        dropdown.style.top = position[1] + inputBox.offsetHeight + "px";
        dropdown.style.display = 'block';
    }
    else if (dropdown != null && yesno == false) dropdown.style.display = 'none';
}


function displayRecord(record) {

    displayMessage(false);
    var dropdown = null;
    try {
        dropdown = document.getElementById(ACDROPDOWN_ID);
        if (dropdown != null) dropdown.style.display = 'none';

        //alert(dropdown);
        if (dropdown != null) {
            if (record == null) {
                dropdown.innerHTML = "";
                SelectedIndex = -1;
                if (NumShownEntries > 0) {
                    resetShownEntries();
                }
            } else {
                resetShownEntries();
                SelectedIndex = -1;
                dropdown.innerHTML = generateContentFromRecord(Current_Value, record);
                //alert('get record');
            }

            if (dropdown.innerHTML.length == 0) {
                //dropdown.visibility = 'hidden';
                dropdown.style.display = 'none';
                if (typeof (showdrop) != 'undefined') {
                    showdrop('drop');
                }
            } else {
                if (typeof (hidedrop) != 'undefined') {
                    hidedrop('drop');
                }
                SelectedIndex = -1;

                var inputBox = document.getElementById(ACINPUT_ID);
                if (inputBox == null) return;
                var position = findPosition(inputBox);
                dropdown.style.left = position[0] - 9 + "px";
                dropdown.style.top = position[1] + inputBox.offsetHeight + "px";
                dropdown.style.display = 'block';
                //alert(dropdown.style.top);
                //dropdown.visibility = 'visible';
                //                if (SelectedIndex != -1)
                //                {
                //                    ACDSelectEntry(DataPrefix + SelectedIndex);
                //                }
            }
        }
    } catch (e) {
        //alert(e);
    }
    //alert(dropdown.visibility);
}


function generateContentFromRecord(key, record) {
    //alert('generateContentFromRecord called');
    var content = "";
    if (record.data == null) {
        return content;
    }
    var size = record.data.length;
    if (size == 0) {
        return content;
    }

    var tmpstr = "";
    var partial = "";

    for (var i = 0; i < size; i++) {
        partial = generateContentForRow(key, record.data[i]);
        if (partial.length > 0) {
            tmpstr += partial;
            AddNewShownEntry(record.data[i]);
            //num_shown++;

            if (NumShownEntries >= MAX_SHOWN) {
                break;
            }
        }
    }

    if (tmpstr.length > 0) {
        var addString = "";
        var quoteInput = document.getElementById(ACINPUT_ID);
        var isMoreButton = quoteInput.getAttribute("tickerCompleteMoreButton");
        if ((isMoreButton && isMoreButton.toUpperCase() == "ON")) {

            addString = "<tr id='idmore' style='' onmouseout=\"this.style.backgroundColor='" + ENTRY_COLOR + "'\" onmouseover=\"ACDSelectEntry('idmore')\" onclick=\"window.location='" + ACQMoreURL + key + "/" + "'\"><td class=\"ACDropDownStyle\">&nbsp;More</td></tr>";
             if (document.getElementById('ASXCode_hdn2').value == 'true')  { addString = ""; }
        }
        content += "<table border=1px><tr><td style='border-style:none; padding: 9px 5px 7px 5px;'><table class='ACDropDownStyle'>" + tmpstr + "</table></td></tr>" +
              addString + "</table>"
    }
    return content;
}

function AddNewShownEntry(data) {
    //alert('AddNewShownEntry');
    var entry = data.split(ACQ_COL_DELIMITER);
    //alert('after split ' + NumShownEntries + ' ' + ShownEntries);
    ShownEntries[NumShownEntries] = new DataEntry(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5]);
    NumShownEntries++;
}

function isRecordHit(key, record) {
  
   // alert('isRecordHit' + key + ' ' + record);
    var pos;
    if (record == null) {
        return 1; // not hit.
    }
    if (key.length >= record.key.length) {
        if (key == record.key) {
            return 0; // hit
        }
        pos = key.indexOf(record.key);
        if (pos == 0) {
            if (record.isLeaf == 1) {
                return 0; // hit because this is a leaf for the same prefix
            }
            return 1; // no hit.
        }
        return 1; // no hit
    } else {
        if (key.length < record.startPos) {
            return 1; // no hit
        }
        // key is shorter
        pos = record.key.indexOf(key);
        if (pos == 0) {
            return 0; // hit
        }
        return 1; // no hit
    }
}

function clickEntry(myID) {
    var sid = myID.substr(DPLen);
    //chooseEntry(sid);
    SelectedIndex = sid;
    //replaceCurrentKey(SelectedIndex);
    trySubmit();
}

function ACDSelectEntry(myID) {
    var entry;
    var sid = myID.substr(DPLen);
    if (sid != SelectedIndex && SelectedIndex >= 0 && SelectedIndex < NumShownEntries) {
        // unselect the existing one.
        var cur_entry = document.getElementById(DataPrefix + SelectedIndex);
        if (cur_entry != null) {
            cur_entry.style.backgroundColor = ENTRY_COLOR;
        }
    }

    if (sid >= 0) {
        entry = document.getElementById(myID);
        if (entry != null) {
            entry.style.backgroundColor = ENTRY_SELECT_COLOR;
            //replaceCurrentKey(sid);
        }
    }
    //    else {
    //        replaceCurrentKey(-1); // recover
    //    }

    SelectedIndex = sid;
}


function generateContentForRow(key, row) {
    //alert('key ' + key + '   row ' + row);
    var ret = "";
    var cells = row.split(ACQ_COL_DELIMITER);

    //jason
    var ticker = cells[0];
    var name = cells[1];
    var type = cells[4];

    /*if(type=="fund")
    {
    cells[0] = name;
    cells[1] = ticker;
    }*/
    ///jason

    var found_match = false;
    var tmp;
    var pos;
    var MAX_MATCH_IDX = 2;
    var NAME_IDX = 1;
    var replaced = false;
    if (cells.length > MAX_MATCH_IDX) {
        var myid = DataPrefix + NumShownEntries;
        //+ "')\" onmouseout=\"ACDUnSelectEntry('" + myid 
        ret = "<tr id='" + myid + "' style='' onmouseover=\"ACDSelectEntry('" + myid + "')\" onclick=\"clickEntry('" + myid + "')\">"
        for (var j = 0; j < MAX_MATCH_IDX; j++) {
            if (!found_match) {
                tmp = cells[j].toLowerCase();
                pos = tmp.indexOf(key, 0)
                //alert(tmp);
                //alert('tmp ' + tmp + ' pos ' + pos + ' key ' + key);
                if (pos >= 0) {
                    found_match = true;
                    ret += generateMatchTd(cells[j], key, pos);
                    replaced = true;
                } else if ((j == NAME_IDX) && (tmp.indexOf(".") >= 0)) {
                    // check it without the . for name
                    tmp = tmp.replace(/\./g, '');
                    pos = tmp.indexOf(key, 0)
                }

                if (!replaced) {
                    if (pos >= 0) {
                        found_match = true;
                        ret += generateMatchTd(cells[j].replace(/\./g, ''), key, pos);
                    } else {
                        ret += "<td class='ACDropDownStyle'>" + cells[j] + "</td>";
                    }
                }
            } else {
                ret += "<td class='ACDropDownStyle'>" + cells[j] + "</td>";
            }
        }
        ret += "</tr>";

        //alert(ret);
    }

    if (!found_match) {
        // ignore this line
        return "";
    }
    return ret;
}

function generateMatchTd(str, key, pos) {
    var prefix = "";
    var suffix = "";
    if (pos > 0) {
        prefix = str.substring(0, pos - 1);
    }
    if (pos + key.length < str.length) {
        suffix = str.substring(pos + key.length);
    }

    var ret = "<td class='ACDropDownStyle'>" + prefix
    + "<b>" + str.substring(pos, pos + key.length)
    + "</b>" + suffix + "</td>";

    //alert(ret);
    return ret;
}


function findPosition(pElement) {
    var curleft = curtop = 0;
    if (pElement.offsetParent) {
        curleft = pElement.offsetLeft
        curtop = pElement.offsetTop
        while (pElement = pElement.offsetParent) {
            curleft += pElement.offsetLeft
            curtop += pElement.offsetTop
        }
    }
    return [curleft, curtop];
}

function addListener(pElement, type, fn) {
    if (pElement.attachEvent) {
        //FIXME: We ignore cancle_bubble for IE... could be a problem?
        pElement.attachEvent("on" + type, fn);
    }
    else if (pElement.addEventListener)
        pElement.addEventListener(type, fn, false);
}