var lookAheadArray = null;
var suggestionDiv = null;
var cursor;
var inputTextField;
var urlbase = '/school'; 


function createDiv(){
    suggestionDiv = document.createElement("div");
    suggestionDiv.style.zIndex = "2";
    suggestionDiv.style.opacity ="0.8";
    suggestionDiv.style.repeat = "repeat";
    suggestionDiv.style.filter = "alpha(opacity=80)";
    suggestionDiv.className = "suggestions";
    suggestionDiv.style.visibility = "hidden";
    suggestionDiv.style.width = inputTextField.offsetWidth - 2;
    suggestionDiv.style.backgroundColor = "white";
    suggestionDiv.style.autocomplete = "off";
    suggestionDiv.style.backgroundImage = "url(transparent50.png)";
    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a inputTextField
    suggestionDiv.onmouseup = function() 
    {
        inputTextField.focus();
    }
    suggestionDiv.onmouseover = function(inputEvent) 
    {
        inputEvent = inputEvent || window.event;
        sugTarget = inputEvent.target || inputEvent.srcElement;
        highlightSuggestion(sugTarget);
    }
    suggestionDiv.onmousedown = function(inputEvent) 
    {
        inputEvent = inputEvent || window.event;
        sugTarget = inputEvent.target || inputEvent.srcElement;
        inputTextField.value = sugTarget.firstChild.nodeValue;
        hideSuggestions();
    }
    document.body.appendChild(suggestionDiv);
}

function keyDownHandler(inEvent ){

    switch(inEvent.keyCode) {
        /* up arrow */
        case 38: 
            if (suggestionDiv.childNodes.length > 0 && cursor > 0) 
            {
                var highlightNode = suggestionDiv.childNodes[--cursor];
                highlightSuggestion(highlightNode);
                   inputTextField.value = highlightNode.firstChild.nodeValue;   
            }
        break;
        /* Down arrow */
        case 40: 
             if (suggestionDiv.childNodes.length > 0 && cursor < suggestionDiv.childNodes.length-1) 
             {
                 var newNode = suggestionDiv.childNodes[++cursor];
                highlightSuggestion(newNode);
                inputTextField.value = newNode.firstChild.nodeValue; 
             }
        break;
        /* Enter key = 13 */
        case 13: 
        //var lookupName = inputTextField.value;
        hideSuggestions();
        break;
    }
}

function keyUpHandler(inEvent) {

    var potentials = new Array();
    var enteredText = (inputTextField.value).toLowerCase();
    var iKeyCode = inEvent.keyCode;
       
    if (iKeyCode == 32 || iKeyCode == 8 || ( 45 < iKeyCode && iKeyCode < 112) || iKeyCode > 123) /*keys to consider*/
    { 
        if (enteredText.length > 0){
            for (var i=0; i < lookAheadArray.length; i++) { 
                //alert(enteredText);
                //alert(lookAheadArray[i].indexOf(enteredText));
                if (lookAheadArray[i].indexOf(enteredText) == 0 ) 
                {
                    potentials.push(lookAheadArray[i]);
            
                } 
            }
                showSuggestions(potentials);
        }
        if (potentials.length > 0) 
        {
            if (iKeyCode != 46 && iKeyCode != 8) 
            {
                typeAhead(potentials[0]);
            }
            showSuggestions(potentials);
        } 
        else 
        {
            hideSuggestions();
           }
    }
}

function hideSuggestions () 
{
    suggestionDiv.style.visibility = "hidden";
}

function highlightSuggestion(suggestionNode) 
{
    for (var i=0; i < suggestionDiv.childNodes.length; i++) 
    {
        var sNode = suggestionDiv.childNodes[i];
        if (sNode == suggestionNode) 
        {
            sNode.className = "current"
        } 
        else if (sNode.className == "current") 
        {
            sNode.className = "";
        }
    }
}

function init (field) 
{
   //alert('init:'+field);
   inputTextField = document.getElementById(field); 
   cursor = -1;
    fillArrayWithAllUsernames();
    inputTextField.onkeyup = function (inEvent) 
    {
    
        if (!inEvent) 
        {
            inEvent = window.event;
        }    
        keyUpHandler(inEvent);
    }
    
    inputTextField.onkeydown = function (inEvent) 
    {
        if (!inEvent) 
        {
            inEvent = window.event;
        }    
        keyDownHandler(inEvent);
    }
    inputTextField.onblur = function () 
    {
        hideSuggestions();
    }

    createDiv();
}

function selectRange(start , end ) 
{
    if (inputTextField.createTextRange) {
        var sRange = inputTextField.createTextRange(); 
        sRange.moveStart("character", start); 
        sRange.moveEnd("character", end - inputTextField.value.length);      
        sRange.select();
    } else if (inputTextField.setSelectionRange) {
        inputTextField.setSelectionRange(start, end);
    }     
    inputTextField.focus();      
} 

function showSuggestions(suggestions) 
{
    var sDiv = null;
    suggestionDiv.innerHTML = "";  
    
    for (i=0; i < suggestions.length; i++) 
    {
        sDiv = document.createElement("div");
        sDiv.appendChild(document.createTextNode(suggestions[i]));
        suggestionDiv.appendChild(sDiv);
    }
    suggestionDiv.style.top = (inputTextField.offsetTop+inputTextField.offsetHeight) + 15 + "px";
    suggestionDiv.style.left = inputTextField.offsetLeft + 10 + "px";

    suggestionDiv.style.visibility = "visible";
}


function typeAhead(suggestion) 
{
    if (inputTextField.createTextRange || inputTextField.setSelectionRange)
    {
        var iLen = inputTextField.value.length; 
        inputTextField.value = suggestion; 
        selectRange(iLen, suggestion.length);
    }
}

function fillArrayWithAllUsernames()
{ 
    var url = urlbase+"/lookup"; //*: DB¿¡ ÀÖ´Â °ÍÀ» ¸ðµÎ °¡Á®¿Í¶ó, 3: nodeType
    //alert('url submitting:'+url);
    if (window.XMLHttpRequest)
    { 
        req = new XMLHttpRequest(); 
    } 
       else if (window.ActiveXObject)
    { 
        req = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    req.open("Get",url,true); 
    req.onreadystatechange =  callbackFillUsernames;
    req.send(null);
} 
    
   
function callbackFillUsernames()
{ 
    if (req.readyState==4)
    { 
       if (req.status == 200)
        { 
            populateUsernames();
        } 
       } 
} 
   
function populateUsernames()
{
    var nameString = req.responseText;
    var lowerString = nameString.toLowerCase();
    var nameArray = lowerString.split('/');
    
    lookAheadArray = nameArray;
}
