/**
 * AutoComplete Field - JavaScript Code
 *
 * This is a sample source code provided by fromvega.
 * Search for the complete article at http://www.fromvega.com
 *
 * Enjoy!
 *
 * @author fromvega
 *
 */

// global variables
var acListTotal   =  0;
var acListCurrent = -1;
var acSearchId    = null;
var acResultsId   = null;
var acSearchField = null;
var acResultsDiv  = null;
var dataTypes = new Array();

function setAutoComplete(field_id, results_id, dataArray) {
    // initialize vars
    dataTypes = dataArray;
    acSearchId = "#" + field_id;
    acResultsId = "#" + results_id;

    // create the results div
    $("body").append('<div id="' + results_id + '"></div>');

    // register mostly used vars
    acSearchField = $(acSearchId);
    acResultsDiv = $(acResultsId);

    // reposition div
    repositionResultsDiv();

    // on blur listener: timeout is needed otherwise clicking on a result div would blur,
    // and therefore killing all the divs first!
    acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });

    var didTabCompletion = false;
    // on key down listener
    acSearchField.keydown(function (e) {
        // get keyCode (window.event is for IE)
        var keyCode = e.keyCode || window.event.keyCode;
        if (keyCode == 9 && acResultsDiv.children().length != 0) {
            acSearchField.val(acResultsDiv.children().eq(0).html());
            didTabCompletion = true;
            clearAutoComplete();
            return false;
        }
    });

    // on key up listener
    acSearchField.keyup(function (e) {
        var inputText = acSearchField.val();
        // get keyCode (window.event is for IE)
        var keyCode = e.keyCode || window.event.keyCode;
        // check an treat up and down arrows
        if (updownArrow(keyCode)){
            return;
        }
        // check for an ENTER or ESC
        if (keyCode == 13 || keyCode == 27){
            clearAutoComplete();
            return;
        }

        if (didTabCompletion && keyCode == 9) {
           return false;
        }

        // If input is text, call autoComplete. Note that input is lowercased
        autoComplete(inputText.toLowerCase());
    });
}

// treat the auto-complete action (delayed function)
function autoComplete(inputText)
{
    // if it's empty clear the resuts box and return
    if (inputText == ''){
        clearAutoComplete();
        return;
    }

    // get the total of results
    var ansLength = acListTotal = dataTypes.length;
    // if there are results populate the results div
    if (ansLength == 0) {
        clearAutoComplete();
        return;
    }

    var newData = '';
    // create a div for each result
    for (i = 0; i < ansLength; i++) {
        if (-1 != dataTypes[i].toLowerCase().indexOf(inputText)) {
            newData += '<div class="unselected">' + dataTypes[i] + '</div>';
        }
    }

    // update the results div
    acResultsDiv.html(newData);
    acResultsDiv.css("display","block");
            
    // for all divs in results
    var divs = $(acResultsId + " > div");
       
    // on click copy the result text to the search field and hide
    divs.click(function() {
        acSearchField.val(this.childNodes[0].nodeValue);
        clearAutoComplete();
    });
 
    // on mouse over clean previous selected and set a new one
    divs.mouseover(function() {
        divs.each(function(){ this.className = "unselected"; });
        this.className = "selected";
    });
}

// clear auto complete box
function clearAutoComplete()
{
    acResultsDiv.html('');
    acResultsDiv.css("display","none");
}

// reposition the results div accordingly to the search field
function repositionResultsDiv()
{
    // get the field position
    var sf_pos    = acSearchField.offset();
    var sf_top    = sf_pos.top;
    var sf_left   = sf_pos.left;

    // get the field size
    var sf_height = acSearchField.height();
    var sf_width  = acSearchField.width();

    // apply the css styles - optimized for Firefox
    acResultsDiv.css("position","absolute");
    acResultsDiv.css("left", sf_left - 2);
    acResultsDiv.css("top", sf_top + sf_height + 5);
    acResultsDiv.css("width", sf_width - 2);
    // acResultsDiv.css("z-index", "100");
    // acResultsDiv.children().css("z-index", "200");
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
    if(keyCode == 40 || keyCode == 38){

        if(keyCode == 38){ // keyUp
            if(acListCurrent == 0 || acListCurrent == -1){
                acListCurrent = acListTotal-1;
            }else{
                acListCurrent--;
            }
        } else { // keyDown
            if(acListCurrent == acListTotal-1){
                acListCurrent = 0;
            }else {
                acListCurrent++;
            }
        }

        // loop through each result div applying the correct style
        acResultsDiv.children().each(function(i){
            if(i == acListCurrent){
                acSearchField.val(this.childNodes[0].nodeValue);
                this.className = "selected";
            } else {
                this.className = "unselected";
            }
        });

        return true;
    } else {
        // reset
        acListCurrent = -1;
        return false;
    }
}
