
/*
Necessary ingredients for the type-ahead search functionality:
* <input type="hidden" name="txtUserValue" ID="hidden1">
* <input type=""text"" id=""txtUserInput"" name=""txtUserInput"" value=""Enter your search word(s) here"" size=30 class=""inputText"">
* loadSearch() and highLightSearch(); are called on load
* MainForm is the name of the form and AUTOCOMPLETE="off" for the form and txtUserInput (for firefox)
* these files:
<LINK href="css/azStyleSiteSearch.css" type="text/css" rel="stylesheet">
<SCRIPT language="javascript" src="js/azSearch.js"></SCRIPT>
<SCRIPT language="javascript" src="js/aznet.js"></SCRIPT>
<script language="JavaScript1.2">

*/

var sServerPath; /// ="http://dev2.crlaurence.com";
var sHttp= "https://" + window.location.hostname;
var iKeys;
var iDelayKey;
var iDelayPic;
var iMatches;
var iKeyTimeOut;
var isKeyTiming;
var isTiming = false;
var iTimeOut;
//var iIndex;
var arrOptions = new Array();
var strLastValue = "";
var bMadeRequest;
var theTextBox;
var objLastActive;
var currentValueSelected;
var bNoResults = false;
var arrWaitWords;
var arrMatchOpt;
var sTipUrl;


window.onerror=tellerror
function tellerror(msg, url, linenumber)
{
    //throw new Error("test this error");
    //throw "test this error";
    //throw new Error(err.Description);
    //alert('Error message= ' + msg + '\nURL= ' + url + '\nLine Number= ' + linenumber)
    if (objLogBox)
    {
        var s = objLogBox.value;

        if (s.length != 0){s = s + "\n";}
        s = s + "\n***ERROR*** ON LINE: " + linenumber;
        s = s + "\n: " + msg;
        objLogBox.value = s;
        //objLogBox.doScroll();
    }
    return true
}

function doLog(sMess)
{
    //if (objLogBox)
    //{
    //    var s = objLogBox.value;
    //    if (s.length != 0){s = s + "\n";}
    //    objLogBox.value = s + sMess;
    //    //objLogBox.doScroll();
    // }
    // else
	//{
    if (document.getElementById("txtLog"))
    {
	    var s = document.getElementById("txtLog").value;
        if (s.length != 0){s = s + "\n";}
        document.getElementById("txtLog").value = s + sMess;
    }
	//}
}

function defineVars()
{
	var s = document.getElementById(varPrefix + "WaitWords").value.toLowerCase();
	arrWaitWords = s.split(",");
	iKeys = document.getElementById(varPrefix + "KeyNumber").value;
	iDelayKey = document.getElementById(varPrefix + "DelayKeystroke").value;
	iDelayPic = document.getElementById(varPrefix + "DelayPic").value;
	iMatches = 0;
	iTimeOut = 0;
	objLogBox = document.getElementById(varPrefix + "txtLog");
    iarrOptionsIndex = -1;
	iKeyTimeOut = 0;
	sTipUrl = "/siteimages/buttons/tip.gif";
	//doLog("iDelayKey: " + iDelayKey);
}

function goSearch()
{
	HideTheBox();
	var sText = document.getElementById("<%=txtUserInput.ClientID%>").value;
	document.MainForm.action = "/apps/SiteSearch/Search.aspx?query=" + sText;
	document.MainForm.target = "_top";
	document.MainForm.submit();
}

function loadSearch()
{
	defineVars();

	var elemSpan = document.createElement("div");
	elemSpan.id = "spanOutput";
	elemSpan.className = "spanTextDropdown";
	document.body.appendChild(elemSpan);

	var elemSpan1 = document.createElement("span");
	elemSpan1.id = "noMatchData";
	elemSpan1.className = "noMatching";
	document.body.appendChild(elemSpan1);

	//document.getElementById("<%=txtUserInput.ClientID%>").obj =
		//SetProperties(document.getElementById("<%=txtUserInput.ClientID%>"),
		//document.MainForm.txtUserValue,'/apps/SiteSearch/AjaxTypeAhead.aspx',
		//true,true,false,true,"No matching Data",false,null);
	HideTheBox();
}

function SetProperties(xElem,xHidden,xserverCode,
    xignoreCase,xmatchAnywhere,xmatchTextBoxWidth,
    xshowNoMatchMessage,xnoMatchingDataMessage,xuseTimeout,
    xtheVisibleTime)
{
    var props=
    {
		elem: xElem,
		hidden: xHidden,
		serverCode: xserverCode,
		regExFlags: ( (xignoreCase) ? "i" : "" ),
		regExAny: ( (xmatchAnywhere) ? "" : "^" ),
		matchAnywhere: xmatchAnywhere,
		matchTextBoxWidth: xmatchTextBoxWidth,
		theVisibleTime: xtheVisibleTime,
		showNoMatchMessage: xshowNoMatchMessage,
		noMatchingDataMessage: xnoMatchingDataMessage,
		useTimeout: xuseTimeout
    };
    xElem.select();
	xElem.focus();
    AddHandler(xElem);
    return props;
}

var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!= -1);
function AddHandler(objText)
{
	objText.onkeyup = GiveOptions;
	objText.onblur = function()
	{
		if(this.obj.useTimeout)StartTimeout();
	}
	if(isOpera)objText.onkeypress = GiveOptions;
}


 //theTextBox.value.indexOf(strLastValue) != 0

function checkWaitWord(sEntry)
{
	sEntry = sEntry.toLowerCase();
	for (var i = 0; i < arrWaitWords.length; i++)
	{
		if (arrWaitWords[i].indexOf(sEntry, 0) == 0)
		{
			return false;
		}
		else
		{
				var sLeft = sEntry.substring(0, arrWaitWords[i].length);
				if (sLeft ==  arrWaitWords[i])
				{
						if (sEntry.length < arrWaitWords[i].length + 3) //wait till 3rd keystroke

						{
							return false;
						}
						else
						{
							return true;
						}
				}
		}
	}
	return true;
}

function GiveOptions(e)
{

	if(isKeyTiming)EraseKeyTimeout();
	HidePic();
	document.getElementById("noMatchData").style.display = "none";
	var intKey = -1;
	if(window.event)
	{
		intKey = event.keyCode;
		theTextBox = event.srcElement;
	}
	else
	{
		intKey = e.which;
		theTextBox = e.target;
	}

	var sText;
	//doLog("key: " + intKey);

	if(intKey == 32) //delete any leading spaces
	{
		sText = theTextBox.value;
		if (sText == " ")
		{
			theTextBox.value = "";
			strLastValue = "";
			return false;
		}
	}

	if(theTextBox.obj.useTimeout)
	{
		if(isTiming)EraseTimeout();
		StartTimeout();
	}
	//if(theTextBox.value.length == 0 && !isOpera)
	//doLog("GiveOptions theTextBox.value.length= " + theTextBox.value.length);

	if(intKey == 187 || intKey == 16 || intKey == 190) //"+<> cause problems
	{
		sText = theTextBox.value;
		sText  = sText.replace(/\"/g, "&quot;");
		//theTextBox.value = sText.substring(0, sText.length-1);
		sText = sText.replace(/</g, "");
		sText = sText.replace(/>/g, "");
		sText = sText.replace(/\+/g, "");
		strLastValue = sText;
		theTextBox.value = sText;
		return false;
	}

	if(theTextBox.value.length < iKeys && !isOpera)
	{
		arrOptions = new Array();
		iMatches = 0;
		HideTheBox();
		strLastValue = "";
		return false;
	}
	else{}

	if (checkWaitWord(theTextBox.value) == false)
	{
		if (theTextBox.value.length <= strLastValue.length)
		{
			HideTheBox();
			arrOptions = new Array();
			iMatches = 0;
		}
		strLastValue = theTextBox.value;
		return false;
	}

    
	if(objLastActive == theTextBox)
	{
		if(intKey == 13)     //they hit enter
		{
			GrabHighlighted();
			theTextBox.blur();
			return false;
		}
		else if(intKey == 38)  //up arrow
		{
			MoveHighlight(-1);
			return false;
		}
		else if(intKey == 40) //down arrow
		{
			MoveHighlight(1);
			return false;
		}
		else{}
    }

/*
        if(objLastActive != theTextBox ||
           theTextBox.value.indexOf(strLastValue) != 0 ||
           ((arrOptions.length==0 || arrOptions.length==15 ) && !bNoResults) ||
           (theTextBox.value.length <= strLastValue.length))
*/

		if (iMatches<=15 || theTextBox.value.length <= strLastValue.length || theTextBox.value.indexOf(strLastValue) != 0)
        {
			objLastActive = theTextBox;
			HidePic();
            //moved bMadeRequest = true; to TypeAhead. 10/1/2007 dp. User typing ahead would not keep highlighting after first word or so.
            //bMadeRequest = true;
			sText = theTextBox.value;
			sText  = sText.replace(/\"/g, "&quot;");
			StartKeyTime(sText)
			//TypeAhead(sText);
        }
        else if(bMadeRequest == false)
        {
			sText = theTextBox.value;
			sText  = sText.replace(/\"/g, "&quot;");
			BuildList(sText);
        }
        else{}
		sText = theTextBox.value;
		sText  = sText.replace(/\"/g, "&quot;");
        strLastValue = sText;
}

function HideTheBox() {
	document.getElementById("noMatchData").style.display = "none";
	document.getElementById("spanOutput").style.display = "none";
	currentValueSelected = -1;
	if(isTiming)EraseTimeout();
	HidePic();
}

function EraseTimeout()
{
	clearTimeout(isTiming);
	isTiming = false;
}

function TypeAhead(xStrText)
{
	//moved bMadeRequest = true; to here from GiveOptions. 10/1/2007 dp
    bMadeRequest = true;
    //doLog("TypeAhead server call: " + xStrText);
	document.getElementById("hdnURL").value = xStrText;
	var strParams = "q=" + xStrText + "&where=" + theTextBox.obj.matchAnywhere;
	var loader1 = new net.ContentLoader(theTextBox.obj.serverCode, BuildChoices,null,"POST",strParams);
}

function BuildChoices()
{
    //doLog("BuildChoices");
	var strText = this.req.responseText;
	eval(strText);
	BuildList(strLastValue);
	bMadeRequest = false;
    //doLog("BuildChoices bMadeRequest: " + bMadeRequest);
	document.getElementById("pnlResult").className = "clsHide";
}

function BuildList(theText)
{
	SetElementPosition(theTextBox);
	//doLog("BuildList");
	theMatches = MakeMatches(theText);
	//theMatches[i] is the row number of arrOptions[i][]
	//display only the first 20
	var iTop = 20;
	if (theMatches.length < iTop){iTop = theMatches.length}
	//for(i=0;i<theMatches.length;i++)
	for(i=0;i<iTop;i++)
	{
		theMatches[i] = highlightSearchWords(theMatches[i], theText);
	}

	theMatches = theMatches.join().replace(/\,/gi,"");
	//doLog("BuildList theMatches.length= " + theMatches.length);
	if(theMatches.length > 0)
	{
		document.getElementById("spanOutput").innerHTML = theMatches;
		document.getElementById("OptionsList_0").className=	"spanHighElement";
		currentValueSelected = 0;
		bNoResults = false;
		document.getElementById("noMatchData").style.display = "none";
		SetHighColor(0);
		document.getElementById("imgTypeAhead").src = sTipUrl;
		document.getElementById("imgTypeAhead").style.display = "block";
		document.getElementById("pnlImage").style.display = "block";
	}
	else
	{
			currentValueSelected = -1;
			bNoResults = true;
			document.getElementById("noMatchData").style.display = "none";
			if(theTextBox.obj.showNoMatchMessage)
			{
				document.getElementById("noMatchData").innerHTML = "<span class='noMatchData'>" + theTextBox.obj.noMatchingDataMessage + "</span>";
				document.getElementById("noMatchData").style.display = "block";
				document.getElementById("spanOutput").style.display = "none";
			}
			else HideTheBox();
	}
}

var undeStart = "<span class='spanMatchText'>";
var undeEnd = "</span>";
function highlightSearchWords(iIndex, theText)
{
	var strReplace = arrOptions[iIndex][0];
	var regExp = new RegExp(theTextBox.obj.regExAny + theText, theTextBox.obj.regExFlags);
	var aStart = strReplace.search(regExp);
	var matchedText = strReplace.substring(aStart, aStart + theText.length);
	strReplace = strReplace.replace(regExp, undeStart + matchedText + undeEnd)
	strReplace= AddJava(strReplace, iIndex);
	return strReplace;
}

var selectSpanStart;
var selectSpanEnd = "</span>";
function AddJava(xStr, xVal)
{
	selectSpanStart = "<span style='width:100%;display:block;' class='spanNormalElement' onmouseover='ShowRow(this)'";
	selectSpanMid = "onclick='SetText(" + xVal + ")'" + "id='OptionsList_" +  countForId + "' theArrayNumber='"+ xVal +"'>";
//doLog("id: OptionsList_" +  countForId);	
//doLog("theArrayNumber: " + xVal);	
	countForId++;
	return selectSpanStart + selectSpanMid + xStr + selectSpanEnd;
}

function SetElementPosition(theTextBoxInt)
{
	var selectedPosX = 0;
	var selectedPosY = 0;
	var theElement = theTextBoxInt;
	if (!theElement) return;
	var theElemHeight = theElement.offsetHeight;
	var theElemWidth = theElement.offsetWidth;
	while(theElement != null)
		{
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
		}
	xPosElement = document.getElementById("spanOutput");
	xPosElement.style.left = selectedPosX;

	if(theTextBoxInt.obj.matchTextBoxWidth)
		xPosElement.style.width = theElemWidth;
	xPosElement.style.top = selectedPosY + theElemHeight;
	xPosElement.style.display = "block";
	if(theTextBoxInt.obj.useTimeout)
		{
			xPosElement.onmouseout = StartTimeout;
			xPosElement.onmouseover = EraseTimeout;
		}
	else
		{
			xPosElement.onmouseout = null;
			xPosElement.onmouseover = null;
		}

	xPosElementA = document.getElementById("noMatchData");
	xPosElementA.style.left = selectedPosX;

	if(theTextBoxInt.obj.matchTextBoxWidth)
		xPosElementA.style.width = theElemWidth;
	xPosElementA.style.top = selectedPosY + theElemHeight;
	xPosElementA.style.display = "block";
	if(theTextBoxInt.obj.useTimeout)
		{
			xPosElementA.onmouseout = StartTimeout;
			xPosElementA.onmouseover = EraseTimeout;
		}
	else
		{
			xPosElementA.onmouseout = null;
			xPosElementA.onmouseover = null;
		}
}
var countForId = 0;
function MakeMatches(xCompareStr)
{
	countForId = 0;
	var theMatch;
	matchArray = new Array();
	arrMatchOpt = new Array();
	iMatches = 0;
	for(i=0;i<arrOptions.length;i++)
	{
			var regExp = new RegExp(theTextBox.obj.regExAny + xCompareStr, theTextBox.obj.regExFlags);
			theMatch = arrOptions[i][0].match(regExp);
			if(theMatch)
			{
				iMatches = iMatches + 1;
				arrMatchOpt[arrMatchOpt.length] = i;
				//matchArray[matchArray.length]= arrOptions[i][0];
				matchArray[matchArray.length]= i;
			}
			//if (matchArray.length==20)
		    //break;
	}

	return matchArray;
}

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}


function MoveHighlight(xDir)
{
	if(currentValueSelected >= 0)
	{
		newValue = parseInt(currentValueSelected) + parseInt(xDir);
		if(newValue > -1 && newValue < countForId)
		{
			currentValueSelected = newValue;
			/*SetHighColor (null);*/
			ShowRow(null);
		}
	}
}

//function SetHighColor(theTextBox)
function SetHighColor(theTextBox)
{
	if(theTextBox)
	{
		currentValueSelected = theTextBox.id.slice(theTextBox.id.indexOf("_")+1,theTextBox.id.length);
	}
	for(i = 0; i < countForId; i++){
		document.getElementById('OptionsList_' + i).className =	'spanNormalElement';
	}
	document.getElementById('OptionsList_' + currentValueSelected).className = 'spanHighElement';
}

function SetText(xVal)
{
	theTextBox.value = arrOptions[xVal][0];
	var sLeft = arrOptions[xVal][0];
	sLeft = sLeft.toLowerCase();
	sLeft = sLeft.substring(0,5);
	var iDoc=(arrOptions[xVal][0].toLowerCase().indexOf("view additional"));
	if (sLeft == "page ")
	{
		sPath  =  arrOptions[xVal][2] + "\"";;
		//sPath  = sPath.replace(/&quot;/g, "\"");
		theTextBox.obj.hidden.value = sPath;
		//document.MainForm.action = sPath;
		 window.open(sPath);
		 return false;
	}
	else if (iDoc > -1)
	{
		sPath  =  arrOptions[xVal][2];
		theTextBox.obj.hidden.value = sPath;
		document.MainForm.action = sPath;
	}
	else
	{

		var sURL = arrOptions[xVal][1].toLowerCase();		
		theTextBox.obj.hidden.value = sURL
		//document.MainForm.action = "/apps/SiteSearch/Search.aspx?query=" + sURL;
        document.MainForm.action = "/apps/SiteSearch/Search.aspx?typeahead=" + sURL;
	}
	document.getElementById("spanOutput").style.display = "none";
	currentValueSelected = -1;

	// move document.MainForm.action = "/apps/SiteSearch/Search.aspx?query=" + sURL;
	document.MainForm.target = "_top";
	document.MainForm.submit();
}

function GrabHighlighted()
{
    if(currentValueSelected >= 0)
    {
          var xVal = document.getElementById("OptionsList_" + currentValueSelected).getAttribute("theArrayNumber");
          SetText(xVal);
          HideTheBox();
    }
}

function ShowRow(theTextBox)
{
	SetHighColor(theTextBox);
	var spanObject = document.getElementById('OptionsList_' + currentValueSelected);
	//This doesn't work in firefox:
	//var iIndex = document.getElementById('OptionsList_' + currentValueSelected).theArrayNumber;
	var iIndex = arrMatchOpt[currentValueSelected];
	//doLog("currentValueSelected/arrMatchOpt/iIndex: " + currentValueSelected + "/" + arrMatchOpt[currentValueSelected] + "/" + iIndex);
	doPic(iIndex);
}
function AjaxThePic(strParams)
{
    //doLog("AjaxThePic strParams: " + strParams);
    //iarrOptionsIndex is set for ShowThePic
	var loader1 = new net.ContentLoader("/apps/SiteSearch/AjaxPic.aspx", ShowThePic,null,"POST",strParams);
}

function LoadThePic(sURL)
{
	HidePic();
	document.getElementById("imgTypeAhead").src = sURL;
	var iVisibileDelay = setTimeout("visibleThePic()", 50); //try to allow time for resizing.
}

function visibleThePic()
{
	document.getElementById("pnlImage").style.display = "block";
	document.getElementById("imgTypeAhead").style.display = "block";
}

function ShowThePic()
{
	var sURL = this.req.responseText;
	arrOptions[iarrOptionsIndex][4]= sURL;
	//doLog("ShowThePic sURL: " + sURL);
	LoadThePic(sHttp + sURL);
}

function HidePic()
{
    document.getElementById(varPrefix + "imgTypeAhead").style.display = "none";
}


function StartPicTime()
{
    iTimeOut += 1;
    //doLog("StartTimeout: " + iTimeOut);
    HidePic();
	var strParams = "qPic=" + arrOptions[iarrOptionsIndex][1];
    isTiming = setTimeout("AjaxThePic('" + strParams + "')", iDelayPic);
}

function doPic(iIndex)
{
    if(isTiming)EraseTimeout();
	iarrOptionsIndex = iIndex;
	//iIndex = document.getElementById("OptionsList_" + currentValueSelected).getAttribute("theArrayNumber");
	var sProdNumber = arrOptions[iIndex][1];
	sLeft = sProdNumber.toLowerCase();
	sLeft = sLeft.substring(0,5);
	var sPath;
	var iDoc=(arrOptions[iIndex][0].toLowerCase().indexOf("view additional"));

	if (sLeft == "page ")
	{
			//doLog("page");
			LoadThePic("/productimages/catalogs/" + arrOptions[iIndex][4] + ".gif");
	}
	else if (iDoc > -1)
	{
			//doLog("document");
			sPath = "/productimages/catalogs/additionalinfo.gif";
			LoadThePic(sPath);
	}
	else
	{

			//doLog("product");
			if (arrOptions[iIndex][4] == "")
			{
				StartPicTime();
			}
			else
			{
				LoadThePic(arrOptions[iIndex][4]);
			}
	}
}
function EraseTimeout()
{
    clearTimeout(isTiming);
    isTiming = false;
}

function EraseKeyTimeout()
{
    clearTimeout(isKeyTiming);
    isKeyTiming = false;
}

function StartKeyTime(sText)
{
    iKeyTimeOut += 1;
    isKeyTiming = setTimeout("TypeAhead('" + sText + "')", iDelayKey);
}
