showIndicator = function() { 
	YAHOO.util.Dom.setStyle('indicator', 'display', 'block'); 
} 
hideIndicator = function() { 
	YAHOO.util.Dom.setStyle('indicator', 'display', 'none'); 
}
fnCustomFormatter = function(oResultItem, sQuery) {
        var sKey = oResultItem[0];
        var nStatus = oResultItem[2];
        var re = new RegExp('(' + sQuery + ')', 'i');
        var sKeyHighlighted = sKey.replace(re, '<strong>$1</strong>');
        var aMarkup = [sKeyHighlighted,
			" <span class='status-"+nStatus+"'>",
			nStatus,
			"</span>"];
        return (aMarkup.join(""));
};

SearchGroups = function() {
	var oACDS;
	var auto;
	
	return {
        doFocus: function() {
            if ($('inSearch').value == 'enter group name') {
                $D.setStyle('inSearch', 'color', '#000');
                $('inSearch').value = '';
            }
        },

        doBlur: function() {
            if ($('inSearch').value == '') {
                $D.setStyle('inSearch', 'color', '#666');
                $('inSearch').value = 'enter group name';
            }
        },

		init: function() {
            SearchGroups.doBlur();

            $E.on('inSearch', 'focus', SearchGroups.doFocus);
            $E.on('inSearch', 'blur', SearchGroups.doBlur);

			// Setup autocomplete data source 
			oACDS = new YAHOO.widget.DS_XHR('/js/groups/groups_yui.php', ["\n", "\t"], {responseType: YAHOO.widget.DS_XHR.prototype.TYPE_FLAT, maxCacheEntries: 60, scriptQueryParam: 'name'}); 

            if ($('includeNew') && $('includeNew').value) {
                oACDS.scriptQueryAppend = 'new=1';
            }

			// Setup autocomplete itself 
			auto = new YAHOO.widget.AutoComplete("inSearch", "auto", oACDS); 
			auto.formatResult = fnCustomFormatter;

            // Disable the browser's built-in autocomplete caching mechanism
            auto.allowBrowserAutocomplete = false;

			// User typed in the name field, and a request has been made for matching drawing names 
			auto.dataRequestEvent.subscribe(showIndicator); 

			/* Autocomplete data (suggested drawing name matches) have come back 
			* auto.dataReturnEvent does not fire if you quickly tab away from the autocomplete 
			* after you type something, whereas ds.getResultsEvent always fires! 
			*/ 
			oACDS.getCachedResultsEvent.subscribe(hideIndicator); 
			oACDS.getResultsEvent.subscribe(hideIndicator); 

			// Autocomplete data have come back and there are no suggested matching drawing names 
			oACDS.dataErrorEvent.subscribe(hideIndicator); 

			// The user has selected one of the autocomplete options 
			auto.itemSelectEvent.subscribe(function (evt, args) {
				/* where you would set hidden ID element */
				var id = args[2][1];

				if($('group_id')) {
					$('group_id').value = id;
				}
			});
		} // init
	}; //return
}();


YAHOO.util.Event.addListener(window, 'load', SearchGroups.init);
