﻿var LoaderPath = 'img/mini_loader.gif';
var ContainerElementID ='container';
var AjaxClassHandler = 'AjaxManager';
var HelpItem = Class.create();
HelpItem.prototype={
    initialize:function(accord,value,rank,help)
    {
        this.Accord=accord;
        this.Value = value;
        this.Help =help;
        this.Rank=rank;
        this.Helper=null;
        this.ID ='ish_0';
    }
}
var hv = new Array(0);
var isDocumentLoad = false;
jq(document).ready(function(){
    isDocumentLoad = true;
})
var SearchHelper =Class.create();
SearchHelper.prototype={
    initialize: function(inputID,hsItemClass,hsItemSelectClass,code,selectCode,serverFunc,serverParams,isAppend,isVisibleHelp)
    {        
        var varName = 'hv['+hv.length+']';
        var helperID = 'sh_hv['+hv.length+']';
        if(isAppend!='undefined' && isAppend!=undefined)
            this.IsAppend=isAppend;
        else
            this.IsAppend = false;    
            
        if(isVisibleHelp!='undefined' && isVisibleHelp!=undefined)
            this.IsVisibleHelp=isVisibleHelp;
        else
            this.IsVisibleHelp = true;          
            
        this.SelectedItem = null;
        this.VarName=varName;
        this.InputID = inputID;
        this.ExecCode = code;
        this.IsExecCode=false;
        this.SelectCode = selectCode;
        this.ServerFunction = serverFunc;
        this.ServerParams = serverParams;
        this.ItemClass = hsItemClass;        
        this.ItemSelectClass= hsItemSelectClass;
        this.Items = new Array();
        this.IsCache = false;
        this.TempCache = new Array();
        this.CacheTitle ='';
        this.TimerHandler = null;
        this.Cache = $H();
        this.ID = helperID;
        this.CurrentItemID=null; 
        this.IDLoader = helperID+'_loader';
        var el = $(inputID);
        var z_index=el.getStyle('z-index');
        while(el.tagName.toLowerCase()!='body' && (z_index=='' || z_index==null || z_index=='undefined'))
        {
            
            el = el.up();            
            z_index=el.getStyle('z-index');           
        }
        if(z_index==null)
            z_index='';
        else 
            z_index='z-index:'+z_index+';';   
            
        hv.push(this); 
               
        if(isDocumentLoad)
        {            
            try{
                eval(varName+'=this;');                
                var bodySH = '<div id='+helperID+' style="'+z_index+' background-color:white; padding:0px; margin:0px; width:'+$(inputID).getDimensions().width+'px; position:absolute; display:none;"></div>';
                var bodySHLoader = '<div id='+helperID+'_loader style="'+z_index+' padding:0px; margin:0px; position:absolute; display:none;"><img src="'+LoaderPath+'" alt=""></div>';
                if($(helperID)==null || $(helperID)=='undefined')
                {
                    new Insertion.Bottom($(ContainerElementID),bodySH+bodySHLoader);
                }
                else
                {
                    $(helperID).remove();
                    $(helperID+'_loader').remove();
                    new Insertion.Bottom($(ContainerElementID),bodySH+bodySHLoader);
                }                
                eval('Event.observe($("'+inputID+'"), "keyup", '+varName+'.Handler.bindAsEventListener('+varName+'));');
            }
            catch(e){};
        }
        else
        {
            Event.observe(window, 'load', function() 
            {
                try{               
                    eval('isDocumentLoad=true;');
                    var bodySH = '<div id='+helperID+' style="'+z_index+' background-color:white; padding:0px; margin:0px; width:'+$(inputID).getDimensions().width+'px; position:absolute; display:none;"></div>';
                    var bodySHLoader = '<div id='+helperID+'_loader style="'+z_index+'padding:0px; margin:0px; position:absolute; display:none;"><img src="'+LoaderPath +'" alt=""></div>';                    
                    new Insertion.Bottom($(ContainerElementID),bodySH+bodySHLoader); 
                    eval('Event.observe($("'+inputID+'"), "keyup", '+varName+'.Handler.bindAsEventListener('+varName+'))');
                }
                catch(e){};
            });
        }        
    },
    Handler: function(e)
    {        
        var code;        
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;		
		
		var text = $(this.InputID).value;		
		if (code == 38 && $(this.ID).visible())//up
		{
		    this.PrevItem();		    
		}
		else if (code == 40 && $(this.ID).visible())//down
		{ 		    
			this.NextItem();
		}
		else if(code==13 && $(this.ID).visible() && this.IsPreSelected())
		{
		    this.SelectItem();
		}
		else if((code<=57 && code>=48)
		        || (code>=96 && code<=111) 
		        || (code>=65 && code<=90) 
		        || code==61 || code==220 || code==192 || code==219
		        || code==221 || code==59 || code==222
		        || code==188 || code==190 || code==191 || code==32
		        || (code==8 && $(this.ID).visible()) 
		        || (code==8 && text.strip()!='') 
		        || (code==46 && text.strip()!='')
		        || (code==46 && $(this.ID).visible())) 
		{
		    if(text.strip()=='')	
		    {	     
		        this.Close();
		        return;
		    }
		        
		    this.IsCache = false;
		    var keys =this.Cache.keys(); 
		    if(keys!=null && keys!=undefined)
		    {
		        for(var i=0;i<keys.length;i++)
		        {
		            var key = keys[i];
		            if(text==key)
		            {
                       this.Items = this.Cache[key].clone();                    
                       this.IsCache = true;
                       this.CacheTitle = 'from cache key='+key;
                       break;
                   }
                }
            }
            if(!this.IsCache)
            {         
                var pos =Position.cumulativeOffset($(this.InputID));
                var dim =$(this.InputID).getDimensions();
                var dim_loader =$(this.IDLoader).getDimensions();
                $(this.IDLoader).setStyle({ 
                    'left':pos[0]+dim.width-dim_loader.width+'px',
                    'top':pos[1]+'px'
                });
                var var_name = this.VarName;              
                        
                AjaxPro.onLoading = function(b)
                {        
                    if(b)
                    {
                        eval('$('+var_name+'.IDLoader).show();');                       
                    }
                }    
                if(this.TimerHandler!=null)
                    clearTimeout(this.TimerHandler);                
                this.TimerHandler = setTimeout(AjaxClassHandler+'.'+this.ServerFunction+'('+this.ServerParams+text.toJSON()+',"'+this.VarName+'",'+this.VarName+'.SearchCallback);',200);
            }
            else
            {
                if(this.Items!=null && this.Items.length>0)
                    this.Show();
                else
                    this.Close();
            }
		}
		else if(code == 27 && $(this.ID).visible())
		{
		    this.Close();
		}
		else if((code == 13 && !$(this.ID).visible())
		        ||(code==13 && !this.IsPreSelected()) )
		{
		    this.Close();
		    this.IsExecCode=true;
		    eval(this.ExecCode);
		}	
    },
    ClearCache: function()
    {
         this.Cache = $H();
    },
    SearchCallback: function(result)
    {
        var res = result.value;
         //---conflict zone (variable names)
        var res = result.value;
        var text = res.rs3;
        var var_name= res.rs4;
        var values =  res.rs1.split('$');   
        var helps =  res.rs2.split('$');        
        //-----------     
        
        eval(var_name+'.TempCache.clear();');
        eval('$('+var_name+'.IDLoader).hide();');
        eval('if($('+var_name+'.InputID).value=='+text.toJSON()+') '+var_name+'.DeleteItems();');
        //eval('if($('+var_name+'.InputID).value=="'+text+'") '+var_name+'.AddHelpItem(new HelpItem("",'+text.toJSON()+',-1,""));');
        for(var i =0; i<values.length;i++)
        {            
            if(values[i]!='' && values[i]!=null)
                eval(var_name+'.AddHelpItemToTempCache(new HelpItem("",'+values[i].toJSON()+','+i+',"'+helps[i]+'"));');
        }     
            
       eval(var_name+'.Cache['+text.toJSON()+']='+var_name+'.TempCache.clone();');       
       eval('if($('+var_name+'.InputID).value=='+text.toJSON()+'){ '+var_name+'.Items='+var_name+'.TempCache.clone(); if('+var_name+'.Items!=null && '+var_name+'.Items.length>0) '+var_name+'.Show(); else '+var_name+'.Close(); }');
    },
    IsPreSelected: function()
    {
        for(var i=0; i<this.Items.length;i++)
        {
            if($(this.Items[i].ID).className == this.ItemSelectClass)
                return true;
        }
        return false;
    },
    AddHelpItem: function(helpItem)
    {
        helpItem.Helper=this;
        helpItem.ID=this.ID+'_ish_'+(this.Items.length+1);
        this.Items.push(helpItem); 
        this.Items.sort(this._compareItems);       
        
    },  
    AddHelpItemToTempCache: function(helpItem)
    {
        helpItem.Helper=this;
        helpItem.ID=this.ID+'_ish_'+(this.TempCache.length+1);
        this.TempCache.push(helpItem); 
        this.TempCache.sort(this._compareItems);
    },    
    _compareItems: function(a,b)
    {
        if(a.Rank<b.Rank)
            return -1;
        if(a.Rank>b.Rank)
            return 1;
        return 0;
    },
    DeleteItems: function()
    {
        this.Items.clear();
    },
    MouseClick: function(event)
    {
        var elt = Event.element(event);
        if(elt!=$(this.InputID))
        {            
            this.Close();
        }
    },
    Close: function()
    {   
        $(this.ID).hide();     
        this.DeleteItems();
        Event.stopObserving(document.body, 'click', this.bMouseClick);
    },
    GetItemById: function(idItem)
    {
        for(var i=0; i<this.Items.length; i++)
        {
            var item = this.Items[i];
            if(item.ID == idItem)
            {
                return item;
            }
        }
        return null;
    },
    ClearItems: function()
    {
        for(var i=0; i<this.Items.length;i++)
        {
            $(this.Items[i].ID).className=this.ItemClass;
        }
    },
    NextItem: function()
    {
        if(this.Items.length>0)
        {
            var nextItemId = 0;
            for(var i=0; i<this.Items.length;i++)
            {
                if($(this.Items[i].ID).className == this.ItemSelectClass)
                {                   
                   if(i== this.Items.length-1)
                        nextItemId=0;            
                   else
                        nextItemId=i+1;
                   break;                    
                }
            }
            this.ClearItems();
            $(this.Items[nextItemId].ID).className = this.ItemSelectClass;
        }        
    },   
    PrevItem: function()
    {
        if(this.Items.length>0)
        {
            var nextItemId = this.Items.length-1;
            for(var i=0; i<this.Items.length;i++)
            {
                if($(this.Items[i].ID).className == this.ItemSelectClass)
                {                   
                   if(i== 0)
                        nextItemId=this.Items.length-1;            
                   else
                        nextItemId=i-1;
                   break;                    
                }
            }
            this.ClearItems();
            $(this.Items[nextItemId].ID).className = this.ItemSelectClass;
        }
    }, 
    PreSelectItem: function(idItem)
    {
        this.ClearItems();
        var item = this.GetItemById(idItem);        
        $(item.ID).className = this.ItemSelectClass;
    },    
    SelectItem: function()
    {
        for(var i=0; i<this.Items.length;i++)
        {
            var item =this.Items[i];
            if($(item.ID).className==this.ItemSelectClass)
            {                
                this.SelectedItem =item; 
                if(this.IsAppend)
                {
                    var vals =$(this.InputID).value.split(',');
                    var result = new String();
                    var isFirst = 1;
                    for(var i=0;i<vals.length-1;i++)
                    {
                        if(vals[i].strip()!='')
                        {
                            if(isFirst==1)
                            {
                                result+=vals[i].strip();
                                isFirst=0;
                            }
                            else
                            {
                                result+=','+vals[i].strip();
                            }
                        }
                    }
                    if(isFirst==1)
                    {
                        result+=item.Value;
                        isFirst=0;
                    }
                    else
                    {
                        result+=','+item.Value;
                    }
                    $(this.InputID).value=result+',';
                }
                else
                    $(this.InputID).value=item.Value;
                    
                eval(this.SelectCode);
                this.Close();
                break;
            }
        }
    },
    LeaveItem: function(idItem)
    {
       this.ClearItems();
       var item = this.GetItemById(idItem);       
       $(item.ID).className = this.ItemClass;
    },    
    Show: function()
    {
        //if(this.IsExecCode)
          //  return;

        this.SelectedItem = null;
        var pos =Position.cumulativeOffset($(this.InputID));
	    var dim =$(this.InputID).getDimensions();
	    $(this.ID).setStyle({ 
            'left':pos[0]+'px',
            'top':pos[1]+dim.height +'px'
        });
        var items_context='';       
        for(var i=0; i<this.Items.length; i++)
        {
            var item = this.Items[i];
            items_context+='<div class='+this.ItemClass+' id='+item.ID+
                            ' onmouseover=\'javascript:'+this.VarName+'.PreSelectItem("'+item.ID+'");\''+                             
                            ' onclick=\'javascript:'+this.VarName+'.SelectItem();\'><table width=100% cellspacing=0 cellpadding=3><tr><td>'+item.Value+'</td><td style="text-align:right; color:gray;">'+
                            '<div style="float:right;'+(this.IsVisibleHelp?'':' display:none;')+'">'+item.Help+'</div></td></tr></table></div>';
                                      
        }        
        $(this.ID).update(items_context);
        $(this.ID).show();

        this.bMouseClick = this.Close.bindAsEventListener(this);
        Event.stopObserving(document.body, 'click', this.bMouseClick);
        Event.observe(document.body, 'click', this.bMouseClick);
    }
}
