/**
 * Script: auto-select.js
 * Purpose: object for creating drop down autocomplete select field 
 * Author: Ben Sorohan
 * 
 * Depends: YAHOO { yahoo.util, yahoo.dom, yahoo.event }
 */

AutoSelect = function(inputFieldId,containerId,data,conf) 
{   
    if (typeof conf == 'undefined') {
        // default conf
        conf = {
                autoHighlight:false,
                prehighlightClassName:"yui-ac-prehighlight",
                useShadow:true,
                queryDelay:0,
                minQueryLength:0,
                animVert:.01,
                maxResultsDisplayed:100
            };
    }
    
    this.inputFieldId = inputFieldId;
    this.containerId = containerId;
    this.data = data;
    this.config = conf;
    this.test = 'A';
    
    // Use a LocalDataSource
    this.oDS = new YAHOO.util.LocalDataSource(this.data);

    // first, put 2, count 'em 2, divs around the input
    var firstDiv = document.createElement('div');
    var secondDiv = document.createElement('div');
    firstDiv.className = 'yui-skin-sam';
    firstDiv.appendChild(secondDiv);
    YAHOO.util.Dom.get(this.inputFieldId).parentNode.insertBefore(
            firstDiv,
            YAHOO.util.Dom.get(this.inputFieldId)
    );
    secondDiv.appendChild(YAHOO.util.Dom.get(this.inputFieldId));
    
    // verifiy containerId
    if (YAHOO.util.Dom.get(this.containerId)==null) {
        // create a container
        var container = document.createElement('div');
        container.setAttribute('id',this.containerId);
    }
    else {
        var container = YAHOO.util.Dom.get(this.containerId);
    }
    secondDiv.appendChild(
        container
    );
    
    // Instantiate the AutoComplete
    this.oAC = new YAHOO.widget.AutoComplete(this.inputFieldId, this.containerId, this.oDS, this.config);
    
    // register the toggler
    YAHOO.util.Event.addListener( YAHOO.util.Dom.get(this.inputFieldId),
                                 'focus',
                                 this.toggle,
                                 this,
                                 true 
    );
    YAHOO.util.Event.addListener( YAHOO.util.Dom.get(this.inputFieldId),
                                 'click',
                                 this.toggle,
                                 this,
                                 true 
    );
        
    // focus the input on select
    this.oAC.itemSelectEvent.subscribe(this.focus,this,true);
};

AutoSelect.prototype = {
        
    // create a toggler
    toggle : function(e) 
    {
        // Is open
        if(this.oAC.isContainerOpen()) {
            // don't collapse on toggle
        }
        // Is closed
        else {
            this.oAC.getInputEl().focus(); // Needed to keep widget active
            this.oAC.sendQuery('');
        }
    },
    
    focus : function (e)
    {
        YAHOO.util.Dom.get(this.inputFieldId).focus();        
    },
    
    toString : function()
    {
        return 'AutoSelect';
    }

};
