/*

	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 = "Search...";

	// 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 = "famous, widely used, talked about, authentic, trusted by, trend setting, first choice of, widely, widely recognized as, endorsed by, well-known, , famed, renowned, eminent, prominent, illustrious, legendary, reliable, dependable, legitimate, popular, distinguished, renowned, notable, distinguished, well-known, recognized, reputed, one and only, exclusive, premium, the best, elite, unrivaled, distinguished, the top, second to none, distinctive, exceptional, number 1, undisputed, best quality, top quality, unparalleled, superior, special, extraordinary, out of the ordinary, singular, unique, outstanding, sole, only one of its kind, inimitable, matchless, incomparable, one and only, peerless, unmatched, without equal, beyond compare, unrivaled, unsurpassed, first-class, first-rate, superlative, excellent, unbeatable, advanced, outstanding, exceptional, superb, easy to, simple to, safe and simple, uncomplicated, plain and simple, trouble-free, straightforward, undemanding, minimal, minimum, clear-cut, down to earth, clean, unpretentious, effortless, Effortless, plain, unproblematic, unadorned, natural, smooth, without a hitch, unembellished, without ornamentation, sticking to the facts, usual, normal, ordinary, unfussy, unsophisticated, with both feet on the ground, straight-thinking, precise, unambiguous, clear, explicit, definite, unequivocal, indisputable, must have, indispensable, powerful, essential, vital, crucial, critical, magnificent, vibrant, compelling, awesome, superb, explode, terrific, extremely, splendid, vital, necessary, requisite, obligatory, central, very important, essential, compulsory, indispensable, fundamental, imperative, mandatory, required, influential, commanding, prevailing, dominant, potent, significant, superior, overriding, governing, principal, major, noteworthy, considerable, superseding, overruling, dominant, prime, paramount, principal, main, you, urgent, at last, attention, discover, learn, new, now available!, secrets revealed!, earn, for the first time, risk free, just released, announcing, decide now, order now, buy now, get it now!, act now, now is the time, don’t miss, don’t wait, immediately, right now, this instant, limited supply, now or never, attractive, gorgeous, stunning, enchanting, appealing, sleek, dazzling, mystical, satisfying, sensual, glowing, handsome, beautiful, radiant, wonderful, crave, tantalizing, yearn, good-looking, nice-looking, striking, eye-catching, lovely, pleasing, remarkable, startling, dazzling, pretty, exquisite, charming, divine, astonishing, amazing, astounding, alluring, incredible, glamorous, superb, outstanding, terrific, splendid, fabulous, marvelous, fantastic, pleasing, enjoyable, stunning, spectacular, startling, magnificent, amazing, astonishing, modern, current, contemporary, fresh, new, forward-looking, advanced, enlightened, forward-thinking, ahead of its time, futuristic, revolutionary, ultramodern, current, up-to-date, up-to-the-minute, recent, state-of-the-art, brand-new, the latest, at the height of fashion, fashionable, trendy, topical, hot, high-tech, unused, spanking-new, pristine, hip, all-the-rage, modish, stylish, chic, classy, original, ahead of its time, unconventional, alternative, unusual, exceptional, odd, quirky, different, appealing to take action: affordable, challenging, alert, competitive edge, allure, comprehensive, applause, compromise, avoiding, concept, crucial, big, billboard, daring, block busting, danger, bonanza, destiny, boom, dirty, bottom line, distinguished, brain picking, dividends, bravo, dynamics, breakthrough, buy, eager, buyer’s guide, easy, eat, giant, economic needs, good-looking, effective, growth, emerging growth, gut feelings, endurance, energy, happy, enterprising, heritage, envision, high tech, epidemic, high yield, excitement, hit, exercising, hopless, expert, hot property, explain, hybrid, exploit, hurry, favorable, idea, find out, imagination, flex, inflation-beating, flourishes, innovative, focus, investigative, foothold, instatiable, forecast, formula, just in time, fueling, fundamentals, keepin touch, funny, kidding, gaining, last-minute, gallery, lare-breaking, generic, launching, get, liberated, lifeblood, pioneering, lively, portfolio, longevity, preppie, lucky, profitable decision, luxury, promising, mainstream, recruiting, make, remarkable, mania, reminiscent, marvelous, renaissance spirit, masterpiece, reviewing, measure up, revisited, medicine, revolution, merit, rewards, monitor, rich, monumental, right now, naked, sampler, nest egg, save,new,sawy, newswire, school of thought, next frontier, scorecard, nostalgic, security, novel, show me, shrewd, obession, simplistic, opportunities, skill, overrated, slash, smart, perspective, spiral, philosophy,soar, specialized, test-drive, speed up, timely, spotlight, top dog, stardom, traces, starter kit,stop, ultimate, stubborn, underpriced, successful switch, unlock, surefire, upscale, surging, survival,value, tax-resistant, willpower, tech revolution, word-of-mouth, technolog, tell, young, alcohol, bar, booze, cat, cash, car, boat, beer, cool, couch, dude, death, dare, dorm, fun, fast, fancy, good, great, gossip, hot, high, intense, idiot, joke, kwik trip, loot, love, loons, money, nothing, nice, night, open, old, odd, pool, purse, people, public, party, quote, role, real, red, roof, soul, sew, sold, sell, sex, top, ten, tool, taxi, toilet, town, university, under cover, vent, venue, voice, weather, win, won, well, we, western, xtreme, you, young, yellow, your, zebra";

	// 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);
