
var isOpera = navigator.userAgent.indexOf('Opera') > -1;
var isIE = navigator.userAgent.indexOf('MSIE') > 1 && !isOpera;
var isMoz = navigator.userAgent.indexOf('Mozilla/5.') == 0 && !isOpera;
var doSubmit = false;
var globalSearchFieldValue = "";
var iLen;
var searchField;
var lastKeyCode;



function textboxSelect (searchField, iStart, iEnd) {
    switch(arguments.length) {
        case 1:
            searchField.select();
            break;
        case 2:
            iEnd = searchField.value.length;
            /* don't break - want to process as if 3 args passed */
        case 3:
            if (isIE) {
                var oRange = searchField.createTextRange();
                oRange.moveStart("character", iStart);
                oRange.moveEnd("character", -searchField.value.length + iEnd);
                oRange.select();
            } else if (isMoz){
                searchField.setSelectionRange(iStart, iEnd);
            }
    }
    searchField.focus();
}

function textboxReplaceSelect (searchField, sText) {
    if (isIE) {
        var oRange = document.selection.createRange();
        oRange.text = sText;
        oRange.collapse(true);
        oRange.select();
    } else if (isMoz) {
        var iStart = searchField.selectionStart;
        searchField.value = searchField.value.substring(0, iStart) + sText + searchField.value.substring(searchField.selectionEnd, searchField.value.length);
        searchField.setSelectionRange(iStart + sText.length, iStart + sText.length);
    }
    searchField.focus();
}

function autocompleteMatch (sText, arrValues) {
    var retArray = new Array();
    for (var i=0; i < arrValues.length; i++) {
    	var searched=arrValues[i].toLowerCase();
        if (searched.indexOf(sText) == 0) {
            retArray[retArray.length] = arrValues[i];
        //   alert(arrValues[i]);
        }
        i++;
    }
    return retArray;
}

function autocomplete(searchField, oEvent, arrValues) {
    var suggestionSet = false;
    resultsDiv = (isMoz) ? document.getElementById("searchResultsDiv"): document.all.searchResultsDiv;
    resultsDiv.style.visibility = "hidden";
    if(arrValues.length == 0){
        // quit function as nothing to match on
        return false
    }
    switch (lastKeyCode) { // oEvent.keyCode
        case 37: //left arrow
        case 39: //right arrow
        case 33: //page up
        case 34: //page down
        case 36: //home
        case 35: //end
        case 9: //tab
        case 27: //esc
        case 16: //shift
        case 17: //ctrl
        case 18: //alt
        case 20: //caps lock
        case 46: //delete
        case 8: //backspace
            if (searchField.value.length == 0 ) {
                showHideAutoComplete(false);
            }
            return true;
            break;
        case 13: //enter
            // Check to see if there is a value in the field and if so, submit the form.
            if(searchField.value.length > 0 ){
                doSubmit = true;
                getSearchResults(searchField.value);
            }
            return true;
            break;
        case 38: //up arrow
            if ((showDiv = document.getElementById("autoComplete")) && showDiv.className == "suggestVisible" ) {
                if(showDiv.hasChildNodes()){
                    startLoop = showDiv.childNodes.length -1;
                    for(j=startLoop;j>=0;j--){
                        thisChild = showDiv.childNodes[j];
                        if(thisChild.className == "suggestHigh") {
                            thisChild.className = "suggestLow";
                            if (j != 0) {
                                thisChild.previousSibling.className = "suggestHigh";
                                thisChild = thisChild.previousSibling;
                            } else {
                                showDiv.lastChild.className = "suggestHigh";
                                thisChild = showDiv.lastChild;
                            }
                            break;
                        }
                    }
                    if (j==0){
                        showDiv.lastChild.className = "suggestHigh";
                        showDiv.firstChild.className = "suggestLow";
                        thisChild = showDiv.lastChild;
                    }
                }
                searchField.value = URLDecode(thisChild.innerHTML);
            }
            return true;
            break;
        case 40: //down arrow
            if ((showDiv = document.getElementById("autoComplete")) && showDiv.className == "suggestVisible" ) {
                if(showDiv.hasChildNodes()){
                    for(j=0;j<showDiv.childNodes.length;j++){
                        thisChild = showDiv.childNodes[j];
                        if(thisChild.className == "suggestHigh") {
                            thisChild.className = "suggestLow";
                            if (j !=showDiv.childNodes.length - 1) {
                                thisChild.nextSibling.className = "suggestHigh";
                                thisChild = thisChild.nextSibling;
                            } else {
                                showDiv.firstChild.className = "suggestHigh";
                                thisChild = showDiv.firstChild;
                            }
                            break;
                        }
                    }
                    if (j==showDiv.childNodes.length){
                        showDiv.lastChild.className = "suggestLow";
                        showDiv.firstChild.className = "suggestHigh";
                        thisChild = showDiv.firstChild;
                    }
                }
                searchField.value = URLDecode(thisChild.innerHTML);
            }
            return true;
            break;
        default:
            globalSearchFieldValue = document.forms.searchForm.searchField.value;
            searchText = String.fromCharCode(isIE ? oEvent.keyCode : oEvent.charCode);
            textboxReplaceSelect(searchField, searchText);
            if (getSuggestions(searchText, arrValues) ){
                showHideAutocomplete(true);
            }
            return false;
    }
}

function showHideAutoComplete(boolDisplay){
    autoCompDiv = (isMoz) ? document.getElementById("autoComplete") : document.all.autoComplete;
    autoCompDiv.className = (boolDisplay) ? "suggestVisible" : "suggestHidden";
 noThing = (isMoz) ? document.getElementById("nothingThing") : document.all.nothingThing;
    noThing.className = (boolDisplay) ? "suggestVisible" : "suggestHidden";
}


function showHideNothing(boolDisplay){
    nothingDiv = (isMoz) ? document.getElementById("nothingThing") : document.all.nothingThing;
    nothingDiv.className = (boolDisplay) ? "nothingVisible" : "nothingHidden";
}

function createSolutionList(docForm){
    searchField = docForm.searchField;
    searchField.value = "";
    docForm.solution.options.length = 1;
    for(i=0;i<solutionsArray.length;i++){
        newOpt = new Option (solutionsArray[i],solutionsTOT[i]);
		// newOpt = new Option (solutionsArray[i],solutionsTOT[i]);
        docForm.solution.options[docForm.solution.options.length] = newOpt;
    }
	 if(searchField.createTextRange) {
        searchField.onkeyup=new Function("return keyUpHandler(event);");
    } else {
        searchField.onkeyup=keyUpHandler;
    }
    document.onkeydown=keyDownHandler;
}

keyUpHandler = function(e){lastKeyCode=e.keyCode;};

function keyDownHandler(event){
    if(!event&&window.event) {
        event=window.event;
    }
    if(event) {
        lastKeyCode=event.keyCode;
    }
    if (isIE && lastKeyCode < 46){
        autocomplete(searchField,event,selectionArray);
    }
}

function get_sol(){location.href=document.forms["searchForm"].id.value;}

function updateAutoComplete(selEl){
str=selEl.value
var comma=str.indexOf(",");
var id_num=str.slice(0,comma);
var id = "solution_"+id_num+".shtml";
str=str.slice(comma+1,str.length);
document.forms["searchForm"].id.value=id;
//alert(""+id);
    showHideAutoComplete(false);
    searchField.style.visibility = "visible";
   document.getElementById("getResults").style.visibility = "visible";
  if(id_num<44){document.getElementById("all").style.visibility = "visible";}
  else{document.getElementById("all").style.visibility = "hidden";}
    selEl.form.searchField.value = "";
    // selEl.form.searchField.onmouseover = function () {showHideAutoComplete(false);};
    if(selEl.selectedIndex > 0 ){
        selEl.form.searchField.disabled = false;
        selEl.form.searchField.focus();
        if(selectionArray.length > 0){
            selectionArray.length = 0;
        }
        for(i=0;i<solutionsArray[str].length;i++){
            selectionArray[selectionArray.length] = solutionsArray[str][i];

        }
    } else {
    	searchField.disabled = "disabled";
	    document.getElementById("getResults").disabled = "disabled";
		document.getElementById("all").disabled = "disabled";
	}
}

function searchResults(arrayList){
    resultsDiv = (isMoz) ? document.getElementById("searchResultsDiv"): document.all.searchResultsDiv;
    while(resultsDiv.childNodes.length>0) resultsDiv.removeChild(resultsDiv.childNodes[0]);

    for(i=0;i<arrayList.length; i++){
        newDiv = document.createElement("DIV");
        newDiv.className = "searchResults";
        newUrl = document.createElement("A");
		// append the spans created for the Title and Supplier
        newTitle = document.createElement("SPAN");
        newTitle.appendChild(document.createTextNode(arrayList[i][1]));
        newTitle.className = "resultsTitle";

        newUrl.className = "resultsLink";
        newUrl.href = arrayList[i][4];
        newDiv.appendChild(newUrl);
		 newUrl.appendChild(newTitle);
        newSupplier = document.createElement("SPAN");
        newSupplier.appendChild(document.createTextNode(" " +arrayList[i][2]));
        newSupplier.className = "resultsSupplier";
        newDiv.appendChild(newSupplier);
        issue = document.createElement("SPAN");
        issue.appendChild(document.createTextNode(" - "+arrayList[i][3]));
        issue.className = "resultsIssue";
        newDiv.appendChild(issue);
        resultsDiv.appendChild(newDiv);
    }
    resultsDiv.style.visibility = "visible";
    resultsDiv.style.display = "block";
}

function getSearchResults(searchText){
    /*    Function that intercepts form submission and displays div listing results instead    */
    showHideAutoComplete(false); // make sure auto complete DIV is hidden
    if(searchText != "" && doSubmit ){
        for(i=0;i<selectionArray.length;i++){
            if (selectionArray[i] == searchText) {
                break;
            }
        }
        if (i == selectionArray.length) return false;
        // Try to display results if search text is provided
        displayList = searchResults(selectionArray[++i]);
    }
    // return false; // stop the form from submitting
    if (!doSubmit) searchText.focus();
}

function getSuggestions(strToMatch, arrValues){
    autoDiv = (isMoz) ? document.getElementById("autoComplete") : document.all.autoComplete ;
    populateDiv(autoDiv, arrValues);
}

function populateDiv(container,suggestArray){
    // Repopulates the autocomplete div with span elements containing the new query results
    var tempSearchValue;
    searchField = (!searchField) ? document.forms.searchForm.searchField : searchField;
    var iLen = searchField.value.length;
    var searcher=searchField.value.toLowerCase();
    var matchSuggest = autocompleteMatch(searcher,suggestArray);
    while(container.childNodes.length>0) container.removeChild(container.childNodes[0]);
    for(var lineNo=0;lineNo<matchSuggest.length;lineNo++){
        var nextChild=document.createElement("DIV");
        nextChild.className = "suggestLow";
        nextChild.onmousedown = function() {

        	this.className="suggestPick";
        	searchField.value = URLDecode(this.innerHTML);
        	iLen=searchField.value.length;
        	textboxSelect(searchField, iLen, searchField.value.length);
        	doSubmit=true;
        	getSearchResults(searchField.value);

        };
        nextChild.onmouseover = function() { this.className="suggestHigh";
        this.tempText=searchField.value;
        searchField.value= URLDecode(this.innerHTML);
        textboxSelect(searchField, iLen, searchField.value.length);
        };
        nextChild.onmouseout = function() {
		this.className="suggestLow";
		//commented out by Andy
		//searchField.value=this.tempText;
		this.tempText="";
if(isIE){event.cancelBubble = true;event.returnValue=false;}
};
        nextChild.innerHTML = matchSuggest[lineNo]; // Increment the line no to avoid the features link list
       container.appendChild(nextChild);
    }
     if(matchSuggest.length>0){
	autoCompDiv = (isMoz) ? document.getElementById("autoComplete") : document.all.autoComplete;
	if(matchSuggest.length>17){len=16}
	else{len=matchSuggest.length}
	if(isMoz){autoCompDiv.style.height=10+(12*len);}
	else{autoCompDiv.style.height=10+(13*len);}
	showHideAutoComplete(true);
	showHideNothing(false);}
	else{showHideAutoComplete(false);
	showHideNothing(true);}
}


function URLDecode (encodedString) {
  var output = encodedString;

    output = output.replace("&amp;","&");

  return output;
}
