var data;

$(document).ready(function()
{
 /***** keyword search *******************************************************/

 $("input[name='textsearch']").autocomplete(
	{
		"minLength":2,
		"source":"/cgi-bin/barlive/olc/ac-search.p"
	}); // autocomplete()

 /***** style code entry *****************************************************/

 /* limit autocomplete results */
 var max = 20; // limit of results to display;

 $.ui.autocomplete.prototype._renderMenu = function( ul, items )
 {
  var self = this;

  $.each( items, function( index, item )
  {
   if (index < max) // here we define how many results to show
    self._renderItem( ul, item );
  });
 }

 $(function()
 {
  $.ajax(
  {
   url: "/96live/style-list.xml",
   dataType: "xml",
   success: function( xmlResponse )
   {
    data = $( "style", xmlResponse ).map(function()
    {
     return {"value":$(this).text(),"id":$(this).text()};
    }).get();

    data.sort(function(a,b)
    {
     var sortA = getSortKey(a);
     var sortB = getSortKey(b);

     if ( sortA > sortB )
      return 1;
     else if (sortA < sortB)
      return -1;
     else
      return 0;
    });

    $("input[name='style']").autocomplete(
    {
     source: beginsMatch,
     minLength: 1,
     max:10
    }); // autocomplete()

    $("input[name='style2']").autocomplete(
    {
     source: beginsMatch,
     minLength: 1,
     max:10
    }); // autocomplete()

    $("input[name='txtStyle']").autocomplete(
    {
     source: beginsMatch,
     minLength: 1,
     max:10
    }); // autocomplete()

   } // success

  }); // $.ajax()

 }); // $(function())

}); // document.ready

/*****************************************************************************/

function beginsMatch(req,responseFn)
{
 /* Need to use a function for the source so that we can filter the
    data object to only match items using begins instead of the default
    jQuery UI algorithm that uses matches *term* since Larry's sorting
    algorithm only works for begins searches. */
 var re = $.ui.autocomplete.escapeRegex(req.term);
 var matcher = new RegExp( "^" + re, "i" );
 var a = $.grep(data, function(item,index)
 {
  return matcher.test(item.value);
 });
 responseFn( a );

} // beginsMatch()

/*****************************************************************************/

function getSortKey(styleObj)
{
 /* Larry's algorithm for sorting letters before numbers */

 var style = styleObj.value;
 var i = 0;
 var oldOrder = "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
 var newOrder = "qrstuvwxyz0123456789abcdefghijklmnop0123456789abcdefghijklmnop";
 var j = -1;
 var sortKey  = "";
 var c = "";

 for (i=0;i<style.length;i++)
 {
  c = style.substring(i,i+1).toLowerCase();
  j = oldOrder.indexOf(c);

  if ( j > -1)
   sortKey += newOrder.substring(j,j+1);
  else
   sortKey += c;
 }

 return sortKey;

} // getSortKey()


