
var matchvalues = new Array;
var DOWNKEY = 40;
var UPKEY = 38;
var ENTERKEY = 13;
var BG_COLOR = "#FFF1E5";// #FFF1E5 = pale orange, #EEFFEA = pale green, #ECEEEF = WC light gray 
var browser = navigator.appName;
var version = navigator.appVersion;

function autocomplete(input,event){
    var keycode = event.keyCode;
    var textvalue = input.value;
    var suggdiv = document.getElementById("autocomplete");

    if(!suggdiv){
        return;    
    }
    var divstyle = suggdiv.style;
    
    //get the suggestions and, if present, the selected selection
    var selected = document.getElementById('selectedsuggestion');
    var spans = document.getElementsByName('suggestions');


    if (browser == "Microsoft Internet Explorer"){
        spans = iegetelementsbynamefix('suggestions');
    }

    divstyle.overflow = "visible";

        //if nothing is in the text box, keep suggestions hidden
    if (textvalue == "" || textvalue.length == 0){
        divstyle.visibility = "hidden";
        //if the down key is pressed...
    } else if (keycode == DOWNKEY && document.getElementById('autocompsel')){
        //check to see if one is already highlighted...
        if (selected != null){
            for (var i = 0; i < spans.length; i++){
                if (i == spans.length - 1)
                    break;
                if (spans[i].id == 'selectedsuggestion'){
                    spans[i].id = "";
                    spans[i + 1].id = 'selectedsuggestion';
                    unhilightselection(spans[i]);
                    hilightselection(spans[i + 1]);
                    break;
                }
            }
			//if not, select the first one.
        }else{
            selectfirstelement(spans);
        }
        document.getElementById(input.id).focus();
		//if the up key is pressed...
    }else if ((keycode == UPKEY && document.getElementById('autocompsel'))){
        //check to see if one is already highlighted...
        if (selected != null){
            for (var b = spans.length - 1; b > 0; b--){
                if (spans[b].id == 'selectedsuggestion'){
                    spans[b].id = "";
                    spans[b - 1].id = 'selectedsuggestion';
                    unhilightselection(spans[b]);
                    hilightselection(spans[b - 1]);
                    break;
                }
            }
			//if not, select the first one.
        }else{
            selectfirstelement(spans);
        }
        document.getElementById(input.id).focus();
		//if the enter key is pressed, insert the highlighted suggestion into the text box, if no selection is hilighted, submit the form (if given).
    }else if (keycode == ENTERKEY){
        if(document.getElementById('selectedsuggestion')){
            selectsuggestion(input.id, document.getElementById('selectedsuggestion').innerHTML);
        }// else if (document.getElementById(sourceId)){
//            document.getElementById(sourceId).submit();
//        }else if (document.getElementById("clickonOptionYes")){
//            editvalue(sourceId,recordId);
//        }
        //all other keys...
    }else if (textvalue.length > 1){
        var textarray;
            //checks for a comma and starts the suggestions with the characters after the comma
        if (textvalue.indexOf(",") > -1){
            textarray = textvalue.split(",");
            textvalue = trimSpaces(textarray[textarray.length - 1]);
        }
        //after the second letter is entered, go get suggestion list
        if (textvalue.length == 2){
            var url = document.URL.replace("http://", "");
            var spliturl = url.split("/");
            var date = new Date();
            jQuery.get("http://" + spliturl[0] + "/quickTags",
                {query:'allrecords',maxrecords:100,srchtrm:textvalue,time:date.toTimeString()},
                function(data){
                        matchvalues = data.split(",");
                        makesuggestionbox(textvalue,input,textarray,divstyle,suggdiv);
                    }
                );
        } else makesuggestionbox(textvalue,input,textarray,divstyle,suggdiv);
    }
}

function makesuggestionbox(textvalue,input,textarray,divstyle,suggdiv){

    var divhtml = "";
	var numofsugg = 0;
    var MAXSUGGESTIONS = 12
    if (textvalue.length >= 2){

        //for each suggestion in the master list...
        for (var c = 0; c < matchvalues.length; c++){
            if (matchvalues[c]){
                //get the characters that correspond to the number of characters in the textbox...
                var submatch = matchvalues[c].substr(0, textvalue.length);
                //if they match...
                if(numofsugg < MAXSUGGESTIONS){
					if (submatch.indexOf(textvalue) > -1 && !arrayContains(textarray,matchvalues[c]) && textvalue.charAt(textvalue.length - 1) != ","){
						//make the matching letters bold...
//						var selection = matchvalues[c].replace(submatch, "<strong>" + submatch + "</strong>");
                        var selection = matchvalues[c].replace(submatch, "<b>" + submatch + "</b>");
						//and add the suggestion to the main div
						divhtml += "<span onclick='selectsuggestion(\"" + input.id + "\",\"" + matchvalues[c] + "\")' onmouseover='hilightselection(this)' onmouseout='unhilightselection(this)' name='suggestions'>&nbsp;" + selection + "</span><br />";
                        numofsugg++;
					}
				}
			}
		}

        //if there are no items, keep the suggestion div hidden
        if (numofsugg == 0){
            divstyle.visibility = "hidden";
        }else{
            //get the position of the textbox
            var left = findPosX(input);
            var top = findPosY(input) + findHeight(input);
            var width = findWidth(input) - 2;

            //use the position information to place the suggestion div,
            divhtml = "<span style='width:" + width + "px;background-color:"+ BG_COLOR +";z-index:100;border:solid 1px;border-top:none;position:absolute;top:" + top + "px;left:" + left + "px' id='autocompsel' onkeyup='enterselectsuggestion(\"" + input.id + "\",this,event)'>" + divhtml;
            suggdiv.innerHTML = divhtml + "</span>";
            divstyle.visibility = "visible";
            //give focus back to the textbox
            document.getElementById(input.id).focus();
        }
    }else{
        divstyle.visibility = "hidden";
    }
}

function hidesuggbox(){
    if(!document.getElementById('selectedsuggestion') && document.getElementById("autocomplete")){
        var suggdiv = document.getElementById("autocomplete");
        var divstyle = suggdiv.style;
        divstyle.visibility = "hidden";
    }
}

function selectsuggestion(id, spanValue){
    var suggdiv = document.getElementById("autocomplete");
    var divstyle = suggdiv.style;
    var textvaluebox = document.getElementById(id);
        //remove formatting informaton
    if (spanValue.indexOf("<strong>") > -1 || spanValue.indexOf("<STRONG>") > -1){
        spanValue = spanValue.replace("<strong>", "");
        spanValue = spanValue.replace("</strong>", "");
        spanValue = spanValue.replace("<STRONG>", "");
        spanValue = spanValue.replace("</STRONG>", "");
        spanValue = spanValue.replace("&nbsp;", "");
    }
    if (spanValue.indexOf("<b>") > -1 || spanValue.indexOf("<B>") > -1){
        spanValue = spanValue.replace("<b>", "");
        spanValue = spanValue.replace("</b>", "");
        spanValue = spanValue.replace("<B>", "");
        spanValue = spanValue.replace("</B>", "");
        spanValue = spanValue.replace("&nbsp;", "");
    }
	//fix encoded ampersand
    spanValue = spanValue.replace('&amp;','&');
    //spanValue = spanValue.replace('&amp','&');
	//check to see if its the first value
    if (textvaluebox.value.indexOf(",") > -1){
        //get the textbox value
        var textvalue = textvaluebox.value;
        var textarray = textvalue.split(",");
        var textbox = "";
			//for each value but the last in the textbox separated by a comma...
        for (var i = 0; i < textarray.length - 1; i++){
            textbox += textarray[i];
				//remove whitespace...
            while (textvalue.substr(0, 1) == " "){
                textvalue = textvalue.substr(1, textvalue.length);
            }
				//make the list again...
            textbox = textbox + ",";
        }
			//and replace the partial word with the selected suggestion
        textvaluebox.value = textbox + spanValue;
		//if not, just replace the text in the textbox with the suggestion
    }else{
        textvaluebox.value = spanValue;
    }
		//hide the suggestion box, return focus to the textbox, and put cursor at the end of the text
    if(document.getElementById("selectedsuggestion")){
        var span = document.getElementById("selectedsuggestion");
        span.id = "";
    }
    divstyle.visibility = "hidden";
    textvaluebox.focus();
    setcaretposition(textvaluebox);
}

function enterselectsuggestion(id, select, event){
    var keycode = event.keyCode;
    if (keycode == 13){
        selectsuggestion(id, select);
    }
}

function hilightselection(selection){
    if(document.getElementById("selectedsuggestion")){
        var span = document.getElementById("selectedsuggestion");
        span.id = "";
    }
    var style = selection.style;
    style.background = "#000000";
    style.color = BG_COLOR;
    selection.id = "selectedsuggestion";
}

function unhilightselection(selected){
    selected.id = "";
    var style = selected.style;
    style.background = BG_COLOR;
    style.color = "#000000";
}

function setcaretposition(textbox){
    var text = textbox.value;
    if (textbox.setSelectionRange){
        textbox.focus();
        textbox.setSelectionRange(text.length, text.length);
    }else if (textbox.createTextRange){
        var range = textbox.createTextRange();
        range.collapse(true);
        range.moveEnd('character', text.length);
        range.moveStart('character', text.length);
        range.select();
    }
}

function iegetelementsbynamefix(name){
    var elem = document.getElementsByTagName('span');
    var arr = new Array();
    for (var i = 0,iarr = 0; i < elem.length; i++){
        var att = elem[i].getAttribute("name");
        if (att == name){
            arr[iarr] = elem[i];
            iarr++;
        }
    }
    return arr;
}

function selectfirstelement(elements){
    var firstspan = elements[0];
    hilightselection(firstspan);
    firstspan.id = "selectedsuggestion";
}

function disablekeys(event){
    var keycode = event.keyCode;
    return !(keycode == ENTERKEY || keycode == DOWNKEY)//{
        //return false;
    //}else return true;
}

function findPosX (obj){
    var curleft = 0;
    var input = obj;

    if (obj.offsetParent){
        while (obj.offsetParent){
            curleft += obj.offsetLeft
            obj      = obj.offsetParent;
        }
    }else if (obj.x)
        curleft += obj.x;

	if (browser == "Microsoft Internet Explorer" && version.indexOf("MSIE 6") == -1 && input.id != "soc-tag-add"){
		curleft += 1;
	} else if (browser == "Microsoft Internet Explorer" && input.id == "soc-tag-add"){
        curleft -= 11;
    }

    if(input.id == "soc-tag-add"){
        return curleft + 3;
    } else {
        return curleft;
    }
}

function findPosY (obj){
    var curtop = 0;
    var input = obj;
    if (obj.offsetParent){
        while (obj.offsetParent){
            curtop += obj.offsetTop
            obj     = obj.offsetParent;
        }
    }else if (obj.y)
        curtop += obj.y;

    if(browser == "Microsoft Internet Explorer" && version.indexOf("MSIE 6") == -1 && input.id != "soc-tag-add"){
        return curtop + 2.5;
    } else {
        return curtop;
    }
}

function findHeight (obj){
    return (obj.style.pixelHeight? obj.style.pixelHeight : obj.offsetHeight);
}

function findWidth (obj){
    return (obj.style.pixelWidth? obj.style.pixelWidth : obj.offsetWidth);
}

function arrayContains(ary, value){
    for(var i in ary){
        if(trimSpaces(ary[i]) == value){
            return true;
        }
    }
    return false;
}

function trimSpaces(string){
    string = string.toString();
    while(string.substr(0, 1) == " "){
        string = string.substr(1, string.length);
    }

    while(string.substr(string.length - 1, string.length) == " "){
        string = string.substr(0, string.length - 1);
    }

    return string;
}