function AutoCompleteDB()
{
        // set the initial values.
        this.bEnd = false;
        this.nCount = 0;
        this.aStr = new Object;
}

AutoCompleteDB.prototype.add = function(str)
{
        // increment the count value.
        this.nCount++;

        // if at the end of the string, flag this node as an end point.
        if ( str == "" )
                this.bEnd = true;
        else
        {
                // otherwise, pull the first letter off the string
                var letter = str.substring(0,1);
                var rest = str.substring(1,str.length);

                // and either create a child node for it or reuse an old one.
                if ( !this.aStr[letter] ) this.aStr[letter] = new AutoCompleteDB();
                this.aStr[letter].add(rest);
        }
}

AutoCompleteDB.prototype.getCount = function(str, bExact)
{
        // if end of search string, return number
        if ( str == "" )
                if ( this.bEnd && bExact && (this.nCount == 1) ) return 0;
                else return this.nCount;

        // otherwise, pull the first letter off the string
        var letter = str.substring(0,1);
        var rest = str.substring(1,str.length);

        // and look for case-insensitive matches
        var nCount = 0;
        var lLetter = letter.toLowerCase();
        if ( this.aStr[lLetter] )
                nCount += this.aStr[lLetter].getCount(rest, bExact && (letter == lLetter));

        var uLetter = letter.toUpperCase();
        if ( this.aStr[uLetter] )
                nCount += this.aStr[uLetter].getCount(rest, bExact && (letter == uLetter));

        return nCount;
}

AutoCompleteDB.prototype.getStrings = function(str1, str2, outStr)
{
        if ( str1 == "" )
        {
                // add matching strings to the array
                if ( this.bEnd )
                        outStr.push(str2);

                // get strings for each child node
                for ( var i in this.aStr )
                        this.aStr[i].getStrings(str1, str2 + i, outStr);
        }
        else
        {
                // pull the first letter off the string
                var letter = str1.substring(0,1);
                var rest = str1.substring(1,str1.length);

                // and get the case-insensitive matches.
                var lLetter = letter.toLowerCase();
                if ( this.aStr[lLetter] )
                        this.aStr[lLetter].getStrings(rest, str2 + lLetter, outStr);

                var uLetter = letter.toUpperCase();
                if ( this.aStr[uLetter] )
                        this.aStr[uLetter].getStrings(rest, str2 + uLetter, outStr);
        }
}


function AutoComplete(aStr, oText, oDiv, nMaxSize)
{
        // initialize member variables
        this.oText = oText;
        this.oDiv = oDiv;
        this.nMaxSize = nMaxSize;

        // preprocess the texts for fast access
        this.db = new AutoCompleteDB();
        var i, n = aStr.length;
        for ( i = 0; i < n; i++ )
        {
                this.db.add(aStr[i]);
        }

        // attach handlers to the text-box
        oText.AutoComplete = this;
        oText.onkeyup = AutoComplete.prototype.onTextChange;
        oText.onblur = AutoComplete.prototype.onTextBlur;
}

AutoComplete.prototype.onTextBlur = function()
{
        this.AutoComplete.onblur();
}

AutoComplete.prototype.onblur = function()
{
        this.oDiv.style.visibility = "hidden";
}

AutoComplete.prototype.onTextChange = function()
{
        this.AutoComplete.onchange();
}

AutoComplete.prototype.onDivMouseDown = function()
{
        this.AutoComplete.oText.value = this.innerHTML;
}

AutoComplete.prototype.onDivMouseOver = function()
{
        this.className = "AutoCompleteHighlight";
}

AutoComplete.prototype.onDivMouseOut = function()
{
        this.className = "AutoCompleteBackground";
}

AutoComplete.prototype.onchange = function()
{
        var txt = this.oText.value;

        // count the number of strings that match the text-box value
        var nCount = this.db.getCount(txt, true);

        // if a suitable number then show the popup-div
        if ( (this.nMaxSize == -1 ) || ((nCount < this.nMaxSize) && (nCount > 0)) )
        {
                // clear the popup-div.
                while ( this.oDiv.hasChildNodes() )
                        this.oDiv.removeChild(this.oDiv.firstChild);

                // get all the matching strings from the AutoCompleteDB
                var aStr = new Array();
                this.db.getStrings(txt, "", aStr);

                // add each string to the popup-div
                var i, n = aStr.length;
                for ( i = 0; i < n; i++ )
                {
                        var oDiv = document.createElement('div');
                        this.oDiv.appendChild(oDiv);
                        oDiv.innerHTML = aStr[i];
                        oDiv.onmousedown = AutoComplete.prototype.onDivMouseDown;
                        oDiv.onmouseover = AutoComplete.prototype.onDivMouseOver;
                        oDiv.onmouseout = AutoComplete.prototype.onDivMouseOut;
                        oDiv.AutoComplete = this;
                }
                this.oDiv.style.visibility = "visible";
        }
        else // hide the popup-div
        {
                this.oDiv.innerHTML = "";
                this.oDiv.style.visibility = "hidden";
        }
}

function createAutoComplete()
{
        var aNames =
        [
"Body Care", "Acne", "Aging", "Aromatherapy", "Bath", "Breath Freshener", "Cosmetics", "Dental", "Floss OR Picks", "Mouthwash", "Toothbrushes", "Toothpaste", "Deoderant", "Ear Care", "Essential Oils", "Lavender", "Acidophilus", "Organic Oils", "Tea Tree Oil", "Eye Care", "Facial", "Cleansers OR Exfoliants", "Masks", "Toners OR Astringents", "Foot Care", "Fragrance", "Hair", "Baby", "Children", "Coloring", "Conditioner", "Shampoo", "Styling", "Insect Repellent", "Children", "Lip Care", "Lotions OR Creams", "Aloe", "Baby", "Coconut", "Massage Oils", "Nails", "Nasal", "Relaxation OR Meditation", "Gifts", "Soap", "Baby", "Bar", "Cleanser", "Liquid", "Sun Screen", "Supplies", "Asian Aisle", "Condiments", "Noodles", "Baby Aisle", "Baby Food", "Cereal", "Diapers OR Wipes", "Teething", "Baking", "Baking Mixes", "Bars", "Beverages", "Bottled Teas", "Fruit Juices", "Hot Chocolate", "Milk", "Non-Dairy", "Sodas", "Soy Rice Drinks", "Vegetable Juices", "Waters", "Books", "Breakfast", "Granola OR Pastry Bars", "Hot Cereals", "Pancake OR Waffle Mixes", "Chocolate OR Carob", "Flour OR Powder", "Diet", "Bread OR Buns", "Crispbreads", "Ener OR G", "Cold Cereals", "Granola", "Condiments", "Hot Sauce", "Marinades", "Mayonnaise", "Crispy Snacks", "Specialty Chips", "Vegetable Chips", "Fruits", "Canned", "Sauces OR Cups", "Household Supplies", "Air fresheners", "Cleaning", "Olives OR Peppers", "Salad Dressing", "Cooking", "Flour OR Powders", "Oils", "Supplies", "Vinegar", "Cookies", "Corn Chips", "Crackers", "Pita Chips", "Potato Chips", "Pretzels", "Puffs OR Popcorn", "Rice Cakes", "Rice Chips", "Soup OR Broth", "Broth", "Soup", "Chili", "Mixes", "Feminine Products", "Laundry", "Paper Goods", "Indian Aisle", "Jams OR Spreads", "Nut Butters", "Jerky", "Meat Alternatives", "Mexican Aisle", "Salsa", "Middle Eastern", "Mixes", "Nuts and Seeds", "Trail Mix", "Pasta", "Long Pasta", "Mixes OR Dishes", "Non OR Wheat Pasta", "Sauce", "Short Pasta", "Pet Supplies", "Canned Cat Food", "Canned Dog Food", "Dog Treats", "Dry Cat Food", "Dry Dog Food", "Rice", "Seafood", "Seasonings", "Extracts Flavorings", "Herbs Spices", "Salt Substitutes", "Noodle Bowls", "Sweeteners", "Honey", "Sugar Substitutes", "Stevia", "Sugar", "Syrups", "Xylitol", "Sweets", "Candy", "Chocolate", "Toppings", "Fruit Leather", "Mints", "Teas OR Coffees", "Accessories", "Black Tea", "Chai Mate Rooibos", "Coffee", "Diet Tea", "Green Tea", "Herbal Tea", "Amino Acids", "L-Glutamine", "L-Lysine", "Antioxidants", "Calcium", "Cal OR Mag OR Zinc", "Cold, Flu, OR Immune", "Echinacea", "Vegetables", "Beans", "Tomato", "Acidophilus", "Allergy", "Aloe", "Alpha Lipoic Acid", "DLPA", "GABA", "Glutathione", "L-Arginine", "L-Carnitine", "L-Tyrosine", "NAC", "Taurine", "Antioxidant Creams", "Betacarotene Carotenoids", "Bilberry OR Lutein", "Bioflavonoids", "Cherries", "Grape Seed", "Green Tea", "Lycopene", "Mangosteen Acai Noni", "Quercetin", "Rutin", "Vitamins ACE", "Bee Products", "Bee Pollen", "Propolis", "Royal Jelly", "Blood Sugar", "Brain OR Memory", "Headaches", "Herbal Formulas", "Herbal Singles", "Cal Boron", "Cal OR Mag", "Cal OR Mag OR Potassium", "Chewable", "Liquid", "Childrens Health", "Acidophilus", "Cold OR Flu", "Homeopathic", "Teething", "Vitamins", "Cholesterol", "Circulation", "Pycnogenol", "Astalagus", "Cats Claw", "Colostrum", "Elderberry", "Goldenseal", "Homeopathic", "Lozenges OR Sprays", "Maitake Shitake", "Olive Leaf", "CoQ10", "Detox OR Cleansing", "Diet OR Weight Loss", "Apple Ciders", "Chitosan", "CLA", "Hoodia", "Slimstyles", "reSet", "Digestive Aids", "Apple Cider", "Betaine", "Bromelain", "Charcoal", "Colostrum", "Gas Aids", "HCL", "Lactase", "Acidophilus", "Herbal Formulas", "Garlic", "Oregon Grape", "Passionflower", "Joint Health", "Stress OR Sleep", "Valerian", "Supplement Oils", "Salmon Oil", "Supplies", "Capsules", "Vision OR Eyes", "Pancreatin", "Papaya", "Peppermint", "DIM", "Ear Care", "Energy", "Fiber", "Psyllium", "Glandular", "Adrenal Formulas", "Thymus Formulas", "Thyroid Formulas", "Glucosamine OR Chondroitin", "MSM", "Green Food", "Alfalfa", "Algae", "Chlorella Chlorophyll", "Kelp", "Spirulina", "Heart Health", "Artichoke", "Circulation", "Cranberry", "Curcumin", "Damiana", "Dandelion", "Dandilion", "Devils Claw", "Eyebright", "Fennel", "Fenugreek", "Feverfew", "Gensing", "Ginger", "Ginkgo", "Gotu Cola", "Green Tea", "Guggul", "Holy Basil", "Horsetail", "Licorice", "Lobelia", "Maca", "Marshmallow", "Milk Thistle", "Motherwort", "Nettle", "Oregano", "Red Clover", "Rosemary", "Single Herbs", "Slippery Elm", "Stevia", "Turmeric", "White Willow", "Wild Yam", "Homeopathic", "30c 30x", "Ointments", "Immune", "Colostrum", "Anti Inflamatory", "Cartilage", "Celadrin", "MSM", "Lecithin", "Liver", "Mens Health", "Saw Palmetto", "Milk Thistle", "Minerals", "Boron", "Chromium", "Iron", "Liquid", "Mag OR Potassium", "Magnesium", "Manganese", "Mineral Complex", "Potassium", "Selenium", "Zinc", "Miscellaneous", "Womens Health", "Menopause", "Mood Formulas", "5-HTP", "SAMe", "St Johns Wort", "Noni", "Multivitamins", "Childrens", "Iron Free", "Men", "Natal", "Prenatal", "Seniors", "Teen", "Women", "Optimal Health", "Pain", "Headache", "Powders", "Creatine", "Egg", "Protein", "Soy", "Spirutein", "Whey", "Prostate Health", "Respiratory", "Salves OR Ointments", "Sexual Health", "Skin OR Hair", "Specialty Formulas", "RNA OR DNA", "Yeast", "Sports Performance", "Creatine", "Chamomile", "Kavakave", "Melatonin", "Black Currant Oil", "Borage Oil", "Castor Oil", "Cod Liver Oil", "Coromega", "DHA Oil", "EPA", "Essential Fatty Acids OR EFA", "Evening Primrose Oil", "Fish Oil", "Flax Oil", "GLA", "Lignan", "Omega", "Teas OR Coffees", "Green Tea", "Urinary Health", "Cranberry", "Kidney Health", "Vitamin B", "B-1", "B-12", "B-2", "B-6", "B-Complex", "Biotin", "B-Stress", "Choline", "Folic Acid", "Homocysteine", "Inositol", "Liquid B", "Malic Acid", "Therapeutic creams", "Other", "Niacin", "Paba", "Pantethine", "Vitamin C", "Acerola", "Ascorbyl Ascorbates", "Bioflavonoids", "Buffered Vitamin C", "C 1000", "C 1500", "C 500", "C Complex", "Chewable", "Emergen C", "Ester C", "Liquid C", "Rose Hips", "Vitamin E", "Dry Vitamin E", "E 100", "E 1000", "E 200", "E 400", "E Complex", "Liquid E", "Vitamins ADK", "Vitamin A", "Vitamin D", "Vitamin K", "Vitamins A OR D", "Candida", "Herbal Formulas", "Natal", "PMS", "Sexual Health", "Enzymatic Therapy", "Desert Essence", "Derma E", "Avalon Natural Products", "NOW", "Wyndmere", "Aura Cacia", "Para Laboratories", "Masada", "Hair Doc", "Hain", "Solaray", "Bach Original Flower Essences", "Optimum Nutrition", "Juice Beauty", "Thursday Plantation", "Tea Tree Therapy", "Tom's of Maine", "Jason", "Terra Dent", "Peelu", "Auromere", "Kiss My Face", "Nature's Gate", "Vita-myr", "Xlear", "Earth Science", "Herbs Etc.", "BHI", "Clear Conscience", "Reviva Labs", "Aubrey", "Zia Cosmetics", "Rachel Perry", "TN Dickensons", "Burt's Bees", "Alba Botanica", "Annemarie Borlind", "Home Health", "Heritage", "Yakshi Fragrance", "California Baby", "Light Mountain Natural", "Naturtint", "Beauty Without Cruelty", "Giovanni", "Giovanni Hair Care", "Healthy Times", "Biotene", "Collective Well Being", "All Terrain", "Boericke & Tafel", "Bite Blocker", "Sun Dog", "un-petroleum", "Carlson", "Badger", "Nature's Life", "Country Comfort", "Emerald Labs", "Jarrow Formulas", "Quantum", "Queen Helene", "Shikai", "Sunshine Spa", "Better Botanicals", "My Chelle", "Nonie Of Beverly Hills", "Neo Cell Labs", "Nature's Way", "Alta Health", "Nature's Plus", "Vitamin Cottage", "Ancient Secrets", "Crystal Journey", "Dr Bronners", "Chandrika", "Sappo Hill", "Indigo Wild", "Mountain Ocean", "Organic Essential", "Eden", "Maine Coast Sea Vegetables", "Native Forest", "Thai Kitchen", "Annie Chuns", "Kitchens Of India", "Earths Best Baby Food", "Seventh Generation", "Bobs Red Mill", "Oetker Simple Organics", "Arrowhead Mills", "Pamelas", "Gluten Free Pantry", "Namaste Foods", "Balance", "Larabar", "Honest Tea", "Tazo", "Biotta", "Santa Cruz", "Lakewood", "Knudsen", "Vruit", "Ginger People", "Dynamic Health", "Izze", "Ah!Laska", "Rapunzel", "Dagoba", "Meyenburg", "Santini", "Blue Diamond", "Pacific", "Blue Sky", "Deep Rock", "White Wave", "Better Than Milk", "Westbrae Natural", "Rice Dream", "Imagine Foods", "Horizon", "Arrowhead", "Gerolsteiner", "Essentia Water", "Penta Water", "Icelandic Glacial", "Nutri-Books", "Health Valley", "Natures Path", "Kashi", "Erewhon", "Pocono", "John McCanns", "Ancient Harvest", "Alvera", "Crystal Deodorant", "Deodorant Stones of America", "Naturally Fresh", "Natural Crystal", "Natural Care", "Camocare", "Lily of the Desert", "Organix", "Lamas Botanicals", "Bee and Flower", "Clearly Natural", "Chatfield", "Sunspire", "Chocolove", "Ghirardelli", "Fearn", "Rumford", "Lewis Laboratories", "Ener-G", "Think", "Bear Valley", "Kind Bars", "Nutiva", "Clif", "Wasa", "Kavli", "Ryvita", "Rudis Bakery", "Dimmer Home Bakery", "Glutino", "Cascadian Farm", "Mothers", "Barbaras", "Familia", "Peace Cereal", "Golden Temple", "Religious Experience", "Brother Bru-bru's", "Green Mountain Gringo", "Frontera", "Muir Glen", "Wizard's", "Pataks", "Spectrum", "Nasoya", "Annies Naturals", "Stacys Pita Chips", "Terra Chips", "Woodstock Farms", "Good Health", "Wymans", "Natural Value", "Columbia Gorge", "Solana Gold", "Air Scense", "Orange Mate", "Citra-Solv", "Napoleon", "Santa Barbara Olive Co", "Mediterranean Organics", "Cardinis", "Seeds of Change", "Drews All Natural", "Captain Toady's", "Grown Right", "Bragg", "San-J", "Ohsawa", "Purity Farms", "Jungle Products", "Trace Minerals Research", "Gaeta", "Aptera", "Newmans Own Organics", "Napa Valley Naturals", "Bionaturae", "Yogourmet", "Great Lakes", "Harolds Kitchen", "Mi-del", "Heaven Scent", "Wellshire Farms", "Nanas Cookies", "Annies Homegrown", "Grace's Best Cookies Llc", "Martines Muffins", "Loacker", "Guiltless Gourmet", "Garden of Eatin", "Have'a Corn Chips", "Que Pasa", "Mexi-Snax", "ak-mak", "Internatural Foods", "Real Foods", "Back To Nature", "Late July", "Mary's Gone Crackers", "Edward & Sons", "New Morning", "Waleeds Mediterranean Food", "Michael Seasons", "Kettle Chips", "Boulder Canyon", "Vitaspelt", "Roberts American Gourmet", "Yayas", "Lundberg", "Masuya Naturally", "Life Tree", "Ecover", "Bio-Pac", "Earth Friendly Products", "Better Than Bouillon", "Amy's Kitchen", "Sheltons", "Walnut Acres Organic Farms", "Natracare", "Country Save", "Bio Kleen", "New Wave Enviro Products", "Jyoti", "Tasty Bite", "Maranatha", "Roaster Fresh", "I.m. Healthy", "Naturally More", "Crofters", "St Dalfour", "Joyva", "Applegate Farms", "Dales Wild West", "Primal Spirit", "Fantastic Foods", "Mori-Nu", "Hatch Natural Mexican", "Bearitos", "Frontier", "Casbah", "Near East", "Simply Organic", "DeBoles", "Tinkyada", "Breeders Choice", "Wysong", "Solid Gold", "Chicken Soup For The Pet Lovers", "Dancing Paws", "Greenies", "Red Barn", "Zukes", "Nutrition Now", "Halo", "Lotus Foods", "Crown Prince", "Bela Olhao", "Natural Sea", "Raincoast Trading", "Wildcatch", "Bioforce", "Flavorganics", "Gaylord Housers", "Real Salt", "La Baleine", "Hearthland Foods", "Nile Spice", "Madhavas Mountain Gold", "Nectar Honey Co", "Wholesome Sweetners", "Kal", "Wisdom of the Ancients", "Florida Crystals", "Shady Maple Farms", "Plantation", "Reeds", "Turtle Island Foods, Inc", "Planet Harmony", "Panda", "Sunridge Farms", "Endangered Species Chocolate", "Terra Nostra", "Honey Gardens", "Stretch Island", "Xylichew", "Historical Remedies", "Betty Lous", "If You Care", "Good Earth", "Choice", "Celestial Seasonings", "Yogi Tea", "Guayaki", "Oregon Chai", "Eco Teas", "Daz Bog", "Cafe Altura", "Mt Hagen", "Pero", "Natural Touch", "Teeccino", "Laci Le Beau", "Triple Leaf Tea", "Traditional Medicinals", "Numi Tea", "Brassica", "Stash", "Sportea", "Dragon Herbs", "Alvita", "Country Life", "Twinlab", "Natural Factors", "Natures Answer", "The Republic of Tea", "Source Naturals", "Kyolic", "Futurebiotics", "MegaFood", "Natren", "American Health", "Renew Life", "Garden Of Life", "New Chapter", "Dolisos", "Similisan", "Hyland's Homeopathic", "Ridgecrest Herbals", "Natra-Bio", "Pure Essence Laboratories", "Georges", "Cyto Charge", "Rainbow Light", "Green Foods", "Tahiti Traders", "Sambazon", "Bluebonnet", "Michaels Naturopathic Programs", "Lifevantage", "Imperial Elixir", "Natures Herbs", "Natural Balance", "Natrol", "Kroeger Herbs", "Super Nutrition", "Baywood", "Flora", "Licata Vitamin Cottage", "Ethical Nutrients", "Nutrina", "Nutricology", "Herbs for Kids", "Superior Health", "Enzymedica", "Symbiotics", "Eclectic Institute", "Ecological Formulas", "Boiron", "Thayers", "Zand", "Naturade", "Herbon", "Japan Health", "Crystal Star", "Gaia Herbs", "Moducare", "OHCO", "Nutribiotic", "Aerobic Life", "Planetary Formulas", "Yerba Prima", "Health Plus", "Natures Secret", "MD Labs", "Sonnes", "Natural Max", "Health From the Sun", "Lumina Health Products", "Action Labs", "Beano", "American Biologics", "Natures Sources", "Alacer Corp.", "Vitaminder", "Maximum Living", "Naturally", "Natural Sources", "Pines", "Nutritech", "Perfect 7", "Organic Frog", "Sunny Green", "Barleans", "Bernard Jensens", "Pure Planet", "Orange Peel Enterprises", "Earthrise", "Nutrex", "Or Wild Harvest", "Prima Vu", "Herb Pharm", "North American Herb And Spice", "NuNaturals", "Nelsons", "Dr Franks", "Liquid Health", "Always Young", "BioTech Corp", "South Of France", "Nordic Naturals", "Vitamin Cottage Custom", "Vitanica", "Optimox", "Marco Pharma International", "Esteem", "The Ultimate Life", "Natural Sport", "Tiger Balm", "Turtle Island Herbs", "DMSO", "Olbas", "Liddell", "Natraflex", "Healthy n Fit", "Coromega", "The Key Company", "Vc Logo", "Highland Labs", "B Total", "World Organic", "Emerita", "Life-Flo", "Superior Source", "Mother Love", "Bear Naked", "Biokplus", "Brooke Rose", "Color Organics", "Egyptian", "Food For Life", "Health Concerns", "White Dove Herbals", "King Bio", "Life Balance", "Lily Organics", "Maisie Jane's", "Manitoba Harvest", "Miltons", "Miso Master", "Nu-age", "Odwalla", "Ojibwa", "Organic Food Bars Inc", "Organic Valley", "Seawind", "Tropical Biomedics", "Udi The Sandwich Man"
        ];
        new AutoComplete(
                aNames,
                document.getElementById('q'),
                document.getElementById('theDiv'),
                25
        );
}