var f=0;
function configuration(SearchBoxId,SuggestionBoxId,SearchButtonId){
    this.SearchBoxId = SearchBoxId;
    this.SuggestionBoxId = SuggestionBoxId;
    this.HighLightedClass = 'current';
    this.SuggestionTableId = 'Table_'+SuggestionBoxId;
    this.isTextBoxFocused = false;
    this.SearchButtonId = SearchButtonId;

    this.hideSuggestionsAfter=function (timeout){
    setTimeout ( 'document.getElementById("'+this.SuggestionBoxId+'").style.visibility="hidden"', timeout );
    }

    this.hideSuggestions=function (){
        $('#'+this.SuggestionBoxId).css('visibility','hidden');
    }

    this.getLeft=function (oNode){
        var iLeft = 0;
        while(oNode.tagName != "BODY" && oNode.tagName != "HTML" ) {
            iLeft += oNode.offsetLeft;
            oNode = oNode.offsetParent;        
        }
        return iLeft;
    }

    this.getTop=function (oNode){
        var iTop = 0;
        while(oNode.tagName != "BODY" && oNode.tagName != "HTML") {
            iTop += oNode.offsetTop;
            oNode = oNode.offsetParent;
        }
        return iTop;
    }

    this.CreateDropDownMenu=function (oEvent){
        var val = $('#'+this.SearchBoxId).val();
		var arr=val.split(" ");
		val=arr[arr.length-1];
        var iKeyCode = oEvent.keyCode;
        //for backspace (8) and delete (46), shows suggestions without typeahead
        if (iKeyCode == 8 || iKeyCode == 46) {
            this.getSuggestion(val,this);
        //make sure not to interfere with non-character keys
        }
		else if (iKeyCode == 32) {
			f=1;
			//alert(f);
            //this.getSuggestion(val,this);
        //make sure not to interfere with non-character keys
        }
		else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
            //ignore
        } else {
			if(f){
				//alert('val='+val);
				var arr=val.split(" ");
				//alert('value='+arr[arr.length-1]);
				this.getSuggestion(arr[arr.length-1],this);
				f=0;
				}
			else{
            	this.getSuggestion(val,this);
			}
        }
    }

    this.getSuggestion=function (str,Conf){
        var p = /^\s*$/;
        var THIS = this;
        if(!p.test(str)){
            var prefix,url;
            prefix="/include/";
            url = "auto-suggestion-ajax.php";
            $.post(
                prefix+url, 
                { SearchFor: str, MaxLength: 35,TableId: this.SuggestionTableId },
                function(data,textStatus){
//                        alert(typeof(data.suggestion)+data.suggestion.length);
//                        return false;
                    var p = /^\s*$/;
                    var val = $('#'+THIS.SearchBoxId).val();
                    if(THIS.isTextBoxFocused && !p.test(val)){
                        if(typeof(data.suggestion)=='object' && data.suggestion.length > 0){
                            var suggest='',tbl='';
                            tbl+='<table width="100%" class="auto_suggest" id="'+THIS.SuggestionTableId+'" >';
                            for(var i=0;i<data.suggestion.length;i++){
                                var suggest = data.suggestion[i].suggestion;
                                var text = suggest;
                                var re = new RegExp(data.search, "g");
                                text = text.replace(re, '<b>'+data.search+'</b>');
                                tbl+='<tr><td>'+text+'<input type="hidden" value="'+suggest+'" ></td></tr>';
                            }
                            tbl+='</table>';
                            
                            var txtBox = document.getElementById(THIS.SearchBoxId);
                            var left = THIS.getLeft(txtBox)-155;
                            var top  = 22+THIS.getTop(txtBox);
                            var browsr = whichBrs();
//                            if(browsr == 'Internet Explorer')   {left=173;top=540;}
//                            else if(browsr == 'Firefox')        {left=173;top=532;}
                            

                            $('#'+THIS.SuggestionBoxId).html(tbl).css('visibility','visible').css('left',''+left+'px').css('top',''+top+'px');
                            $('#'+THIS.SuggestionBoxId+' td:not(.SuggestionType)').mouseover(function(){
                                $('#'+THIS.SuggestionBoxId+' td:not(.SuggestionType)').removeClass(THIS.HighLightedClass);
                                $(this).addClass(THIS.HighLightedClass);
                            });
                            $('#'+THIS.SuggestionBoxId+' td:not(.SuggestionType)').click(function(){
                            
                                THIS.appendSuggestion($(this).children('input').val());
                                /*var current_suggestion = $(this).children('input').val();
                                var arr=$('#'+THIS.SearchBoxId).val().split(" ");
								arr[arr.length-1]=null;
								arr=arr.join(" ");
                                $('#'+THIS.SearchBoxId).val(arr+current_suggestion);
                                $('#'+THIS.SearchButtonId).click();*/
                            });
                        }
                        else{
                            $('#'+THIS.SuggestionBoxId).css('visibility','hidden');
                        }
                    }
                    
                },
                "json"
            );
        }else{
            $('#'+this.SuggestionBoxId).css('visibility','hidden');
        } 
    }
    
    this.appendSuggestion=function(current_suggestion){
//        var current_suggestion = $(this).children('input').val();
        var arr=$('#'+this.SearchBoxId).val().split(" ");
        arr[arr.length-1]=null;
        arr=arr.join(" ");
        $('#'+this.SearchBoxId).val(arr+current_suggestion).focus();
//        $('#'+this.SearchButtonId).click();
    }


    this.HighLightSuggestion=function (oEvent){
        var iKeyCode = oEvent.keyCode;
        var Visibility = $('#'+this.SuggestionBoxId).css('visibility');
        if(Visibility != 'hidden'){
            switch(iKeyCode) {
                case 38: //up arrow
                    this.previousSuggestion();
                    break;
                case 40: //down arrow 
                    this.nextSuggestion();
                    break;
                case 27: //escape
                    this.hideSuggestions();
                    break;
                case 13: //enter
                    //alert(this);
//                    var cell=this.selectCurrentSuggestion();
//                    if(cell!=null){this.selectAsset(cell);}
//                    $('#'+this.SuggestionBoxId+' td:not(.SuggestionType)').click();
					this.hideSuggestions();
                    return false;
//                    return true;
                    break;
            }
        }
        else {
            if(iKeyCode==13){
                return false;
            }
        }
        return true;
    }

    this.previousSuggestion=function (){
        var Table = document.getElementById(this.SuggestionTableId);
        var Rows = Table.childNodes[0].rows;
        var Length = Table.childNodes[0].rows.length;

        if(Length>0){
                if(this.getSelectedIndex()==-1){
                    $(Rows[Length-1].cells[0]).addClass(this.HighLightedClass);
                    this.selectCurrentSuggestion();
                    return true;
                }

                for(i=0;i<Length;i++){
                    var Class = Rows[i].cells[0].className;
                    if(Class.indexOf(this.HighLightedClass)!=-1){
                        if(i>0){
                            $(Rows[i].cells[0]).removeClass(this.HighLightedClass);
                            if(Rows[i-1].cells[0].className.indexOf(this.SuggestionType)==-1){
                                $(Rows[i-1].cells[0]).addClass(this.HighLightedClass);
                            }
                            else{
                                $(Rows[i-2].cells[0]).addClass(this.HighLightedClass);
                            }
                            break;
                        }
                    }
                }

                this.selectCurrentSuggestion();
        }
        return true;
    }

    this.nextSuggestion=function (){
        var Table = document.getElementById(this.SuggestionTableId);
        var Rows = Table.childNodes[0].rows;
        if(!Rows){return true;}
        var Length = Table.childNodes[0].rows.length;

        if(Length>0){
                if(this.getSelectedIndex()==-1){
                    $(Rows[0].cells[0]).addClass(this.HighLightedClass);
                    this.selectCurrentSuggestion();
                    return true;
                }
                
                for(i=0;i<Length;i++){
                    var Class = Rows[i].cells[0].className;
                    if(Class.indexOf(this.HighLightedClass)!=-1){
                        if(i!=Length-1){
                            $(Rows[i].cells[0]).removeClass(this.HighLightedClass);
                            if(Rows[i+1].cells[0].className.indexOf(this.SuggestionType)==-1){
                                $(Rows[i+1].cells[0]).addClass(this.HighLightedClass);
                            }
                            else{
                                $(Rows[i+2].cells[0]).addClass(this.HighLightedClass);
                            }
                            break;
                        }
                    }
                }

                this.selectCurrentSuggestion();
        }
        return true;
    }

    this.getSelectedIndex=function (){
        var Table = document.getElementById(this.SuggestionTableId);
        var Length = Table.childNodes[0].rows.length;
        var Rows = Table.childNodes[0].rows;
        var i;
        
        for(i=0;i<Length;i++){
            var Class = Rows[i].cells[0].className;
            if(Class.indexOf(this.HighLightedClass)!=-1){
                return i;
            }
        }
        return -1;
    }


    this.selectCurrentSuggestion=function (){

        var Table = document.getElementById(this.SuggestionTableId);
        var Length = Table.childNodes[0].rows.length;
        var Rows = Table.childNodes[0].rows;
        var i,cell=null;
        
        for(i=0;i<Length;i++){
            var Class = Rows[i].cells[0].className;
            if(Class.indexOf(this.HighLightedClass)!=-1){
                cell = Rows[i].cells[0];
                this.appendSuggestion($(cell).children('input').val());
                break;
            }
        }
        return cell;
    }
    
    //end configuration
}

function ClickHandler(Conf){
}

function KeyUpHandler(Conf,e){
    Conf.CreateDropDownMenu(e);
}

function KeyDownHandler(Conf,e){
    return Conf.HighLightSuggestion(e);                     
}

function BlurHandler(Conf){
    Conf.hideSuggestionsAfter(250);
    Conf.isTextBoxFocused = false;
}

function FocusHandler(Conf){
    Conf.isTextBoxFocused = true;
}


function configureAutoSuggest(Conf){
    $('#'+Conf.SearchBoxId).click(function (e){ClickHandler(Conf,e)});     
    $('#'+Conf.SearchBoxId).keyup(function (e){KeyUpHandler(Conf,e)});     
    $('#'+Conf.SearchBoxId).keydown(function (e){return KeyDownHandler(Conf,e)});     
    $('#'+Conf.SearchBoxId).blur(function (e){BlurHandler(Conf,e)});     
    $('#'+Conf.SearchBoxId).focus(function (e){FocusHandler(Conf,e)});     
}

function whichBrs() {
    var agt=navigator.userAgent.toLowerCase();
    if (agt.indexOf("opera") != -1) return 'Opera';
    if (agt.indexOf("staroffice") != -1) return 'Star Office';
    if (agt.indexOf("webtv") != -1) return 'WebTV';
    if (agt.indexOf("beonex") != -1) return 'Beonex';
    if (agt.indexOf("chimera") != -1) return 'Chimera';
    if (agt.indexOf("netpositive") != -1) return 'NetPositive';
    if (agt.indexOf("phoenix") != -1) return 'Phoenix';
    if (agt.indexOf("firefox") != -1) return 'Firefox';
    if (agt.indexOf("safari") != -1) return 'Safari';
    if (agt.indexOf("skipstone") != -1) return 'SkipStone';
    if (agt.indexOf("msie") != -1) return 'Internet Explorer';
    if (agt.indexOf("netscape") != -1) return 'Netscape';
    if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
    if (agt.indexOf('\/') != -1) {
    if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
    return navigator.userAgent.substr(0,agt.indexOf('\/'));}
    else return 'Netscape';} else if (agt.indexOf(' ') != -1)
    return navigator.userAgent.substr(0,agt.indexOf(' '));
    else return navigator.userAgent;
}