/* 

	SearchField 
	written by Alen Grakalic, provided by Css Globe (cssglobe.com)
	please visit http://cssglobe.com/post/1202/style-your-websites-search-field-with-jscss/ for more info
	
*/

this.searchfield = function(){
	
	// CONFIG 
	
	// this is id of the search field you want to add this script to. 
	// You can use your own id just make sure that it matches the search field in your html file.
	var id = "searchfield";
	
	// Text you want to set as a default value of your search field.
	var defaultText = "Enter Keyword or SKU";	
	
	// set to either true or false
	// when set to true it will generate search suggestions list for search field based on content of variable below
	var suggestion = true;
	
	// static list of suggestion options, separated by comma
	// replace with your own
	var suggestionText = "Greens 8000, Goldenseal, 40000, 5-HTP, AAKG, Acai, Acerola, Acetyl, Acetyl-L, Acetyl-L-Carnitine, Acid, Acidophilus, Activated, ActivJoint, ADAM™, Additional, Advanced, Agar, AHCC, Air, Alfalfa, Allibiotic, Allspice, Almased, Aloe, Alpha, American, Amino, Amylase, Anise, Apple, Apricot, Arnica, Arth, Arth-X, Artichoke, Ascorbate-C, Ascorbic, Ascorbyl, Ashwaganda, Astragalus, Astraglalus, Atlas, Aussie, Avocado, Awe-Slim™, B-1, B-12, B-50, B-6, Balsam, Barleans, Barley, Basil, Bay, Bee, Beef, Bentonite, Bergamot, BerryDophilus, Beta, Betaine, Bilberry, Bioflavonoid, Biotin, Black, Blessed, Blood, Blue, Bone, Borage, Boron, Boswellin, Boswellin, Bovine, Brain, Branch, Branched, Brewer's, Broccology™, Bromelain, Burdock, Butchers, Butterbur, Buy, C-1000, Cal/Mag, Cal/Mag/Zinc, Calcium, Cal-Mag, Camphor, Cand., Carbo, Cascara, Cassia, Castor, Cat's, Cayenne, Cedarwood, Celadrin, Celadrin, CellEnergy, Chamomile, Chamomille, Chickweed, Chitosan, Chlorella, Chlorophyll, Chocolate, Cholestatin, Cholesterol, Choline, Chondroitin, ChromeMate, Chromium, Cider, Cinnamon, Citric, Citronella, Citrus, CLA, Clary, Clove, CM, Cocoa, Coconut, Cod, Co-Enzyme, Cold, Colloidal, Colostrum, Comforting, Complete, Concentrace, Co-Q10, CoQ10, CoQsol, Coral, Cranberry, Creatine, Crouching, Curcumin, Cypress, Daily, Dairy, Damiana, Dandelion, DefendAir, Delicious, Derma, Detox, Devils, D-Flame™, DGL, DHA, DHA-250, DHEA, Diet, Digestive, DMAE, D-Mannose, DMG, Dong, Dream, D-Ribose, Dulse, E-400, Echinacea, Echinacea/Goldenseal, Echinacea-Goldenseal, Eco-Green, Effer-C™, EGCg, EggWhite, Elderberry, Elder-Zinc, Electro, Electrolyte, Electro-Vita-Min, Eleuthero, E-Liquid, Endure, Enzogenol, E-Oil, Esiak, Ester-C, Ester-C, Eucalyptus, European, Eve, Evening, Eye, Eyebright, Female, Fennel, Fenugreek, Fermented, Feverfew, Fiber, Flax, Flex, Flush-Free, Folic, Fo-Ti, Frankincense, Fresh, Full, Fyre-120, G.I., GABA, Garlic, Geranium, Ginger, Ginkgo, Ginseng, GliSODin, GlucoFit™, Glucosamine, Glucosamine/Chondroitin, Glucosamine/Chondroitin/MSM, Glucosamine/MSM/Arnica, Glucose, Glutathione, Gluten, Glyconutrient, Goji, Gotu, Gourmet, Gr8-Dophilus™, Grape, Grapefruit, Grapeseed, Graviola, Greens, Guar, Guggul, Gymnema, Hawthorn, Healthy, Heart, Hemp, Hempshake, Herbal, Holy, Homocysteine, Hyaluronic, Hyssop, IGF-1, IGF-1+, Immune, Indole-3-Carbinol, Inland, Inositol, Instant, Inulin, Ionic, Ipriflavone, Iron, Jasmine, Jojoba, Juniper, Kava, Kelp, Kids, KIDVITS, Kool-Mint, Krill, Lactase, L-Arginine, L-Arginine/Ornithine, Lavender, L-Carnosine, L-Citrulline, L-Cysteine, Lecithin, Lemon, Lemon-Eucalyptus, Lemongrass, L-Glutamine, L-Glycine, Licorice, Life-Flo, Lime, Lipase, Lipo, Liver, L-Lysine, L-Methionine, L-Norvaline, L-Ornithine, L-Phenylalanine, L-Proline, L-Taurine, L-Theanine, L-Tryptophan, L-Tyrosine, Lutein, Lycopene, Maca, Macadamia, Mag-Cal-Zinc, Magnesium, Magnesium/Calcium/Zinc, Magnesium/Potassium, Maitake, Mangoni™, Mangosteen, Marjoram, Marshmallow, MATRIX, MCT, Mega, Mega-Potassium, Melatonin, Menopause, Men's, Molecularly, Mullein, Mushroom, Myrrh, NAD, Nattokinase, Natural, Nature's, Neem, Neroli, Nettle, NEW, Niacin, Niacinamide, Night, Nightime, Noni, Northern, Now, Nutmeg, Nutra, Nutritional, Nutritonal, Oat, Octacosanol, Odor, Odorless, Olive, Omega, Omega-3, Opti-L-Zinc, Optimal, Orange, Oregano, Organic, OsteoBoron, Oystershell, P-5-P, PABA, Palmarosa, Panax, Pancreatin, Pantethine, Pantothenic, Papaya, Parsley, Patchouli, Pennyroyal, Peppermint, Perfect, Phosphatidyl, Pine, Plant, Play, Policosanol, Pomeratrol™-, Pre-Natal, Probiotic, Probiotics, Pro-Gainer, Progesterone, Propolis, Prostate, Protease, Psyllium, Pumpkin, Pure, Pure-Gar, Pycnogenol, Pygeum/Saw, Pyruvate, Quercitin, Quinn's, Red, Reds, Rei-Shi, Relora, Relora, Resilience, Resolve, Respir-All, Rhodiola, Rose, Rosemary, Rosewater, Rosewood, Sage, Salmon, SAMe, Sanhelios, Selenium, Senna, Serrazimes, Shark, Shea, Silica, Silymarin, Silymarin/Artichoke/Dandelion, Slimaluma™, Slippery, Sodium, Sore, Soy, Spearmint, Special, Spirulina, Stabilized, Stevia, Strawberry, Stress, Stress-X, Super, Sweet, Syntrax, Sytrinol, Tangerine, test, TestoJack, Thyme, Thyroid, TMG, Tocotrienols/Vit, Total, Transend, Tri-Amino, Tribulus, Tri-Chromium™, Triphala, Tru-C, True, Tru-E, Ubiquinol, Ulcetrol™, Ultimate, Ultra, Valerian, Vanilla, Vegetable, Veggie, Vein, Vetiver, Vinpocetine, Virgin, VitaBerry, Vitamin, Vitex, Vit-Min, Weight, Wheat, Whey, Wintergreen, Within, WomenBeauty, Wormwood, Wrinkle, Xanthan, Xylitol, XyliWhite™, Yerba, Ylang, Yucca, ZMA"; 
	
	// END CONFIG (do not edit below this line, well unless you really, really want to change something :) )
	
	// Peace, 
	// Alen

	var field = document.getElementById(id);	
	var classInactive = "sf_inactive";
	var classActive = "sf_active";
	var classText = "sf_text";
	var classSuggestion = "sf_suggestion";
	this.safari = ((parseInt(navigator.productSub)>=20020000)&&(navigator.vendor.indexOf("Apple Computer")!=-1));
	if(field && !safari){
		field.value = defaultText;
		field.c = field.className;		
		field.className = field.c + " " + classInactive;
		field.onfocus = function(){
			this.className = this.c + " "  + classActive;
			this.value = (this.value == "" || this.value == defaultText) ?  "" : this.value;
		};
		field.onblur = function(){
			this.className = (this.value != "" && this.value != defaultText) ? this.c + " " +  classText : this.c + " " +  classInactive;
			this.value = (this.value != "" && this.value != defaultText) ?  this.value : defaultText;
			clearList();
		};
		if (suggestion){
			
			var selectedIndex = 0;
						
			field.setAttribute("autocomplete", "off");
			var div = document.createElement("div");
			var list = document.createElement("ul");
			list.style.display = "none";
			div.className = classSuggestion;
			list.style.width = field.offsetWidth + "px";
			div.appendChild(list);
			field.parentNode.appendChild(div);	

			field.onkeypress = function(e){
				
				var key = getKeyCode(e);
		
				if(key == 13){ // enter
					selectList();
					selectedIndex = 0;
					return false;
				};	
			};
				
			field.onkeyup = function(e){
			
				var key = getKeyCode(e);
		
				switch(key){
				case 13:
					return false;
					break;			
				case 27:  // esc
					field.value = "";
					selectedIndex = 0;
					clearList();
					break;				
				case 38: // up
					navList("up");
					break;
				case 40: // down
					navList("down");		
					break;
				default:
					startList();			
					break;
				};
			};
			
			this.startList = function(){
				var arr = getListItems(field.value);
				if(field.value.length > 0){
					createList(arr);
				} else {
					clearList();
				};	
			};
			
			this.getListItems = function(value){
				var arr = new Array();
				var src = suggestionText;
				var src = src.replace(/, /g, ",");
				var arrSrc = src.split(",");
				for(i=0;i<arrSrc.length;i++){
					if(arrSrc[i].substring(0,value.length).toLowerCase() == value.toLowerCase()){
						arr.push(arrSrc[i]);
					};
				};				
				return arr;
			};
			
			this.createList = function(arr){				
				resetList();			
				if(arr.length > 0) {
					for(i=0;i<arr.length;i++){				
						li = document.createElement("li");
						a = document.createElement("a");
						a.href = "javascript:void(0);";
						a.i = i+1;
						a.innerHTML = arr[i];
						li.i = i+1;
						li.onmouseover = function(){
							navListItem(this.i);
						};
						a.onmousedown = function(){
							selectedIndex = this.i;
							selectList(this.i);		
							return false;
						};					
						li.appendChild(a);
						list.setAttribute("tabindex", "-1");
						list.appendChild(li);	
					};	
					list.style.display = "block";				
				} else {
					clearList();
				};
			};	
			
			this.resetList = function(){
				var li = list.getElementsByTagName("li");
				var len = li.length;
				for(var i=0;i<len;i++){
					list.removeChild(li[0]);
				};
			};
			
			this.navList = function(dir){			
				selectedIndex += (dir == "down") ? 1 : -1;
				li = list.getElementsByTagName("li");
				if (selectedIndex < 1) selectedIndex =  li.length;
				if (selectedIndex > li.length) selectedIndex =  1;
				navListItem(selectedIndex);
			};
			
			this.navListItem = function(index){	
				selectedIndex = index;
				li = list.getElementsByTagName("li");
				for(var i=0;i<li.length;i++){
					li[i].className = (i==(selectedIndex-1)) ? "selected" : "";
				};
			};
			
			this.selectList = function(){
				li = list.getElementsByTagName("li");	
				a = li[selectedIndex-1].getElementsByTagName("a")[0];
				field.value = a.innerHTML;
				clearList();
			};			
			
		};
	};
	
	this.clearList = function(){
		if(list){
			list.style.display = "none";
			selectedIndex = 0;
		};
	};		
	this.getKeyCode = function(e){
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		return code;
	};
	
};

// script initiates on page load. 

this.addEvent = function(obj,type,fn){
	if(obj.attachEvent){
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn](window.event );}
		obj.attachEvent('on'+type, obj[type+fn]);
	} else {
		obj.addEventListener(type,fn,false);
	};
};
addEvent(window,"load",searchfield);

