/*
WICK: Web Input Completion Kit
http://wick.sourceforge.net/
Copyright (c) 2004, Christopher T. Holland
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Christopher T. Holland, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
/* start dhtml building blocks */
function freezeEvent2(e) {
	if (e.preventDefault) e.preventDefault();
	e.returnValue = false;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	return false;
}//freezeEvent2

function isWithinNode2(e,i,c,t,obj) {
	answer = false;
	te = e;
	while(te && !answer) {
		try {
			if	((te.id && (te.id == i)) || (te.className && (te.className == i+"Class"))
					|| (!t && c && te.className && (te.className == c))
					|| (!t && c && te.className && (te.className.indexOf(c) != -1))
					|| (t && te.tagName && (te.tagName.toLowerCase() == t))
					|| (obj && (te == obj))
				) {
				answer = te;
			} else {
				te = te.parentNode;
			}
		} catch(e) {}
	}
	return te;
}//isWithinNode2

function getEvent2(event) {
	return (event ? event : window.event);
}//getEvent2()

function getEventElement2(e) {
	return (e.srcElement ? e.srcElement: (e.target ? e.target : e.currentTarget));
}//getEventElement2()

function findElementPosX2(obj) {
	curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}//if offsetParent exists
	else if (obj.x)
		curleft += obj.x
	return curleft;
}//findElementPosX2

function findElementPosY2(obj) {
	curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}//if offsetParent exists
	else if (obj.y)
		curtop += obj.y
	return curtop;
}//findElementPosY2

/* end dhtml building blocks */

function handleKeyPress2(event) {
	e = getEvent2(event);
	eL = getEventElement2(e);

	upEl = isWithinNode2(eL,null,"wick2Enabled",null,null);

	kc = e["keyCode"];

	if (siw2 && ((kc == 13) || (kc == 9))) {
		siw2.selectingSomething = true;
		if (siw2.isSafari) siw2.inputBox.blur();   //hack to "wake up" safari
		siw2.inputBox.focus();
		siw2.inputBox.value = siw2.inputBox.value.replace(/[ \r\n\t\f\s]+$/gi,' ');
		hideSmartInputFloater2();
	} else if (upEl && (kc != 38) && (kc != 40) && (kc != 37) && (kc != 39) && (kc != 13) && (kc != 27)) {
		if (!siw2 || (siw2 && !siw2.selectingSomething)) {
			processSmartInput2(upEl);
		}
	} else if (siw2 && siw2.inputBox) {
		siw2.inputBox.focus(); //kinda part of the hack.
	}

}//handleKeyPress2()


function handleKeyDown2(event) {
	e = getEvent2(event);
	eL = getEventElement2(e);

	if (siw2 && (kc = e["keyCode"])) {
		if (kc == 40) {
			siw2.selectingSomething = true;
			freezeEvent2(e);
			if (siw2.isGecko) siw2.inputBox.blur(); /* Gecko hack */
			selectNextSmartInputMatchItem2();
		} else if (kc == 38) {
			siw2.selectingSomething = true;
			freezeEvent2(e);
			if (siw2.isGecko) siw2.inputBox.blur();
			selectPreviousSmartInputMatchItem2();
		} else if ((kc == 13) || (kc == 9)) {
			siw2.selectingSomething = true;
			activateCurrentSmartInputMatch2();
			freezeEvent2(e);
		} else if (kc == 27)  {
			hideSmartInputFloater2();
			freezeEvent2(e);
		} else {
			siw2.selectingSomething = false;
		}
	}

}//handleKeyDown2()

function handleFocus2(event) {
	e = getEvent2(event);
	eL = getEventElement2(e);
	if (focEl = isWithinNode2(eL,null,"wick2Enabled",null,null)) {
		if (!siw2 || (siw2 && !siw2.selectingSomething)) processSmartInput2(focEl);
	}
}//handleFocus2()

function handleBlur2(event) {
	e = getEvent2(event);
	eL = getEventElement2(e);
	if (blurEl = isWithinNode2(eL,null,"wick2Enabled",null,null)) {
		if (siw2 && !siw2.selectingSomething) hideSmartInputFloater2();
	}
}//handleBlur2()

function handleClick2(event) {
	e2 = getEvent2(event);
	eL2 = getEventElement2(e2);
	if (siw2 && siw2.selectingSomething) {
		selectFromMouseClick2();
	}
}//handleClick2()

function handleMouseOver2(event) {
	e = getEvent2(event);
	eL = getEventElement2(e);
	if (siw2 && (mEl = isWithinNode2(eL,null,"matchedSmartInputItem2",null,null))) {
		siw2.selectingSomething = true;
		selectFromMouseOver2(mEl);
	} else if (isWithinNode2(eL,null,"siw2Credit",null,null)) {
		siw2.selectingSomething = true;
	} else if (siw2) {
		siw2.selectingSomething = false;
	}
}//handleMouseOver2

function showSmartInputFloater2() {
	if (!siw2.floater.style.display || (siw2.floater.style.display=="none")) {
		if (!siw2.customFloater) {
			x = findElementPosX2(siw2.inputBox);
			y = findElementPosY2(siw2.inputBox) + siw2.inputBox.offsetHeight;
			//hack: browser-specific adjustments.
			if (!siw2.isGecko && !siw2.isWinIE) x += 8;
			if (!siw2.isGecko && !siw2.isWinIE) y += 10;
			siw2.floater.style.left = x;
			siw2.floater.style.top = y;
		} else {
		//you may
		//do additional things for your custom floater
		//beyond setting display and visibility
		}
		siw2.floater.style.display="block";
		siw2.floater.style.visibility="visible";
	}
}//showSmartInputFloater2()

function hideSmartInputFloater2() {
	if (siw2) {
		siw2.floater.style.display="none";
		siw2.floater.style.visibility="hidden";
		siw2 = null;
	}//siw2 exists
}//hideSmartInputFloater2

function processSmartInput2(inputBox) {
	if (!siw2) siw2 = new smartInputWindow2();
	siw2.inputBox = inputBox;

	classData = inputBox.className.split(" ");
	siw2Directives = null;
	for (i=0;(!siw2Directives && classData[i]);i++) {
		if (classData[i].indexOf("wick2Enabled") != -1)
			siw2Directives = classData[i];
	}

	if (siw2Directives && (siw2Directives.indexOf(":") != -1)) {
		siw2.customFloater = true;
		newFloaterId = siw2Directives.split(":")[1];
		siw2.floater = document.getElementById(newFloaterId);
		siw2.floaterContent = siw2.floater.getElementsByTagName("div")[0];
	}

	setSmartInputData2();
	if (siw2.matchWickcol2 && (siw2.matchWickcol2.length > 0)) {
		selectSmartInputMatchItem2(0);
	}

	contentXYZ = getSmartInputBoxContent2();
	if (contentXYZ) {
		modifySmartInputBoxContent2(contentXYZ);
		showSmartInputFloater2();
	} else hideSmartInputFloater2();
}//processSmartInput2()

function smartInputMatch2(cleanValue, value) {
	this.cleanValue = cleanValue;
	this.value = value;
	this.isSelected = false;
}//smartInputMatch2

function simplify2(s) {
	return s.toLowerCase().replace(/^[ \s\f\t\n\r]+/,'').replace(/^[éèêë]+/,'e').replace(/^[àâ]+/,'a').replace(/^[oôö]+/,'o').replace(/^[ùû]+/,'u').replace(/^[ïî]+/,'i');
}//simplify2

function getUserInputToMatch2(s) {
	a = s;
	fields = s.split(",");
	if (fields.length > 0) a = fields[fields.length - 1];
	return a;
}//getUserInputToMatch2

function getUserInputBase2() {
	s = siw2.inputBox.value;
	a = s;
	if ((lastComma = s.lastIndexOf(",")) != -1) {
		a = a.replace(/^(.*\,[ \r\n\t\f\s]*).*$/i,'$1');
	}
	else
		a = "";
	return a;
}//getUserInputBase2()

function runMatchingLogic2(userInput, standalone) {
	userInput = simplify2(userInput);
	uifc = userInput.charAt(0).toLowerCase();
	if (uifc == '"') uifc = (n = userInput.charAt(1)) ? n.toLowerCase() : "z";
	if (standalone) userInput = uifc;
	if (siw2) siw2.matchWickcol2 = new Array();
	pointerToWickcol2ToUse = wickcol2;
	if (siw2 && siw2.revisedWickcol2 && (siw2.revisedWickcol2.length > 0) && siw2.lastUserInput && (userInput.indexOf(siw2.lastUserInput) == 0)) {
		pointerToWickcol2ToUse = siw2.revisedWickcol2;
	} else if (wickcol2Index[userInput] && (wickcol2Index[userInput].length > 0)) {
		pointerToWickcol2ToUse = wickcol2Index[userInput];
	} else if (wickcol2Index[uifc] && (wickcol2Index[uifc].length > 0)) {
		pointerToWickcol2ToUse = wickcol2Index[uifc];
	} else if (siw2 && (userInput.length == 1) && (!wickcol2Index[uifc])) {
		siw2.buildIndex = true;
	} else if (siw2) {
		siw2.buildIndex = false;
	}
	
	tempWickcol2 = new Array();

	re1m = new RegExp("^([ \"\>\<\-]*)("+userInput+")","i");
	re2m = new RegExp("([ \"\>\<\-]+)("+userInput+")","i");
	re1 = new RegExp("^([ \"\}\{\-]*)("+userInput+")","gi");
	re2 = new RegExp("([ \"\}\{\-]+)("+userInput+")","gi");
	
	for (i=0,j=0;(i<pointerToWickcol2ToUse.length);i++) {
		displayMatches = ((!standalone) && (j < siw2.MAX_MATCHES));
		entry = pointerToWickcol2ToUse[i];
		mEntry = simplify2(entry);
		if (!standalone && (mEntry.indexOf(userInput) == 0)) {
			userInput = userInput.replace(/\>/gi,'\\}').replace(/\< ?/gi,'\\{');
			re = new RegExp("(" + userInput + ")","i");
			if (displayMatches) {
				siw2.matchWickcol2[j] = new smartInputMatch2(entry, mEntry.replace(/\>/gi,'}').replace(/\< ?/gi,'{').replace(re,"<b>$1</b>"));
			}
			tempWickcol2[j] = entry;
			j++;		
		} else if (mEntry.match(re1m) || mEntry.match(re2m)) {
			if (!standalone && displayMatches) {
				siw2.matchWickcol2[j] = new smartInputMatch2(entry, mEntry.replace(/\>/gi,'}').replace(/\</gi,'{').replace(re1,"$1<b>$2</b>").replace(re2,"$1<b>$2</b>"));
			}
			tempWickcol2[j] = entry;
			j++;
		}
	}//loop thru wickcol2
	if (siw2) {
		siw2.lastUserInput = userInput;
		siw2.revisedWickcol2 = tempWickcol2.join(",").split(",");
		wickcol2Index[userInput] = tempWickcol2.join(",").split(",");
	}
	if (standalone || siw2.buildIndex) {
		wickcol2Index[uifc] = tempWickcol2.join(",").split(",");
		if (siw2) siw2.buildIndex = false;
	}
}//runMatchingLogic2

function setSmartInputData2() {
	if (siw2) {
		orgUserInput = siw2.inputBox.value;
		orgUserInput = getUserInputToMatch2(orgUserInput);
		userInput = orgUserInput.toLowerCase().replace(/[\r\n\t\f\s]+/gi,' ').replace(/^ +/gi,'').replace(/ +$/gi,'').replace(/ +/gi,' ').replace(/\\/gi,'').replace(/\[/gi,'').replace(/\(/gi,'').replace(/\./gi,'\.').replace(/\?/gi,'');
		if (userInput && (userInput != "") && (userInput != '"')) {
			runMatchingLogic2(userInput);
		}//if userinput not blank and is meaningful
		else {
			siw2.matchWickcol2 = null;
		}
	}//siw2 exists ... uhmkaaayyyyy
}//setSmartInputData2

function getSmartInputBoxContent2() {
	a = null;

	if (siw2 && siw2.matchWickcol2 && (siw2.matchWickcol2.length > 0)) {
		a = '';
		for (i = 0;i < siw2.matchWickcol2.length; i++) {
			selectedString = siw2.matchWickcol2[i].isSelected ? ' selectedSmartInputItem2' : '';
			a += '<p class="matchedSmartInputItem2' + selectedString + '" onmouseover="handleMouseOver2(event);" onmouseup="handleClick2(event)">' + siw2.matchWickcol2[i].value.replace(/\{ */gi,"&lt;").replace(/\} */gi,"&gt;") + '</p>';
		}//
	}//siw2 exists

	return a;
}//getSmartInputBoxContent2

function modifySmartInputBoxContent2(content) {
	//todo: remove credits 'cuz no one gives a shit ;] - done
	siw2.floaterContent.innerHTML = '<div id="smartInputResults2">' + content + (siw2.showCredit ? ('<p class="siw2Credit">Powered By: <a target="PhrawgBlog" href="http://chrisholland.blogspot.com/?from=smartinput&ref='+escape(location.href)+'">Chris Holland</a></p>') : '') +'</div>';
	siw2.matchListDisplay = document.getElementById("smartInputResults2");
}//modifySmartInputBoxContent2()

function selectFromMouseOver2(o) {
	currentIndex = getCurrentlySelectedSmartInputItem2();
	if (currentIndex != null) deselectSmartInputMatchItem2(currentIndex);
	newIndex = getIndexFromElement2(o);
	selectSmartInputMatchItem2(newIndex);
	modifySmartInputBoxContent2(getSmartInputBoxContent2());
}//selectFromMouseOver2

function selectFromMouseClick2() {
	activateCurrentSmartInputMatch2();
	siw2.inputBox.focus();
	hideSmartInputFloater2();
}//selectFromMouseClick2

function getIndexFromElement2(o) {
	index = 0;
	while(o = o.previousSibling) {
		index++;
	}//
	return index;
}//getIndexFromElement2

function getCurrentlySelectedSmartInputItem2() {
	answer = null;
	for (i = 0; ((i < siw2.matchWickcol2.length) && !answer) ; i++) {
		if (siw2.matchWickcol2[i].isSelected)
			answer = i;
	}//
	return answer;
}//getCurrentlySelectedSmartInputItem2

function selectSmartInputMatchItem2(index) {
	siw2.matchWickcol2[index].isSelected = true;
}//selectSmartInputMatchItem2()

function deselectSmartInputMatchItem2(index) {
	siw2.matchWickcol2[index].isSelected = false;
}//deselectSmartInputMatchItem2()

function selectNextSmartInputMatchItem2() {
	currentIndex = getCurrentlySelectedSmartInputItem2();
	if (currentIndex != null) {
		deselectSmartInputMatchItem2(currentIndex);
		if ((currentIndex + 1) < siw2.matchWickcol2.length)
			selectSmartInputMatchItem2(currentIndex + 1);
		else
			selectSmartInputMatchItem2(0);
	} else {
		selectSmartInputMatchItem2(0);
	}
	modifySmartInputBoxContent2(getSmartInputBoxContent2());
}//selectNextSmartInputMatchItem2

function selectPreviousSmartInputMatchItem2() {
	currentIndex = getCurrentlySelectedSmartInputItem2();
	if (currentIndex != null) {
		deselectSmartInputMatchItem2(currentIndex);
		if ((currentIndex - 1) >= 0)
			selectSmartInputMatchItem2(currentIndex - 1);
		else
			selectSmartInputMatchItem2(siw2.matchWickcol2.length - 1);
	} else {
		selectSmartInputMatchItem2(siw2.matchWickcol2.length - 1);
	}
	modifySmartInputBoxContent2(getSmartInputBoxContent2());
}//selectPreviousSmartInputMatchItem2

function activateCurrentSmartInputMatch2() {
	baseValue = getUserInputBase2();
	if ((selIndex = getCurrentlySelectedSmartInputItem2()) != null) {
		addedValue = siw2.matchWickcol2[selIndex].cleanValue;
//		theString = (baseValue ? baseValue : "") + addedValue + ", ";
		theString = (baseValue ? baseValue : "") + addedValue + "";
		siw2.inputBox.value = theString;
		runMatchingLogic2(addedValue, true);
	}
}//activateCurrentSmartInputMatch2

function smartInputWindow2 () {
	this.customFloater = false;
	this.floater = document.getElementById("smartInputFloater2");
	this.floaterContent = document.getElementById("smartInputFloaterContent2");
	this.selectedSmartInputItem2 = null;
	this.MAX_MATCHES = 30;
	this.isGecko = (navigator.userAgent.indexOf("Gecko/200") != -1);
	this.isSafari = (navigator.userAgent.indexOf("Safari") != -1);
	this.isWinIE = ((navigator.userAgent.indexOf("Win") != -1 ) && (navigator.userAgent.indexOf("MSIE") != -1 ));
	this.showCredit = false;
}//smartInputWindow2 Object

function registerSmartInputListeners2() {
	inputs = document.getElementsByTagName("input");
	texts = document.getElementsByTagName("textarea");
	allinputs = new Array();
	z = 0;
	y = 0;
	while(inputs[z]) {
	allinputs[z] = inputs[z];
	z++;
	}//
	while(texts[y]) {
		allinputs[z] = texts[y];
		z++;
		y++;
	}//

	for (i=0; i < allinputs.length;i++) {
		if ((c = allinputs[i].className) && (c == "wick2Enabled")) {
			allinputs[i].setAttribute("autocomplete","OFF");
			allinputs[i].onfocus = handleFocus2;
			allinputs[i].onblur = handleBlur2;
			allinputs[i].onkeydown = handleKeyDown2;
			allinputs[i].onkeyup = handleKeyPress2;
		}
	}//loop thru inputs
}//registerSmartInputListeners2

siw2 = null;

/*if (document.addEventListener) {
	document.addEventListener("keydown", handleKeyDown2, false);
	document.addEventListener("keyup", handleKeyPress2, false);
	document.addEventListener("mouseup", handleClick2, false);
	document.addEventListener("mouseover", handleMouseOver2, false);
} else {
	document.onkeydown = handleKeyDown2;
	document.onkeyup = handleKeyPress2;
	document.onmouseup = handleClick2;
	document.onmouseover = handleMouseOver2;
}*/
Event.observe(document,"keydown",handleKeyDown2);
Event.observe(document,"keyup",handleKeyPress2);
Event.observe(document,"mouseup",handleClick2);
Event.observe(document,"mouseover",handleMouseOver2);

registerSmartInputListeners2();

/*document.write (
'<table id="smartInputFloater" class="floater" cellpadding="0" cellspacing="0"><tr><td id="smartInputFloaterContent" nowrap="nowrap">'
+'<\/td><\/tr><\/table>'
);
*/


//note: instruct users to the fact that no commas should be present in entries.
//it would make things insanely messy.
//this is why i'm filtering commas here:
for (x=0;x<wickcol2.length;x++) {
	wickcol2[x] = wickcol2[x].replace(/\,/gi,'');
}//

wickcol2Index = new Array();

ds = "";
function debug(s) {
	ds += ( s + "\n");
}

