

var MainSearchAjaxCall = function(method,postBody,ptrFucntion){
    $.ajax(method,{onSuccess :     function func(Result){
        if (isFirstRow(Result,"true")){
            var str = GetTextBlock(Result,'#MEK:Friends')
            ptrFucntion(str);
        }    
    },PostBody: postBody})
}
var MainAutoComp = {
    inptSearchFriend : 'inptMainSearch',
    timeStamp :null,
    IsLogged : function(){
        return IsLogin;
    },
    SearchBox: {
        DefaultStr : 'חיפוש חברים',
        PrevTxt : 'חיפוש חברים',
        GetTxt : function(){
            return $val(MainAutoComp.inptSearchFriend);
        },
        ClearTxt : function(){
            if($val(MainAutoComp.inptSearchFriend) == MainAutoComp.SearchBox.DefaultStr){
                $get(MainAutoComp.inptSearchFriend).style.color = '#000';
                $get(MainAutoComp.inptSearchFriend).value = '';
            }
        },
        Focus : function(){
            if(!MainAutoComp.IsLogged()){ // if user if offline
                MainAutoComp.SearchBox.ClearTxt();
                return;
            }
            if(MainAutoComp.Result.arrFriendList == null){
                MainSearchAjaxCall('FriendSearch',[],MainAutoComp.Result.HandleResult );
            }
            if( MainAutoComp.SearchBox.IsEmpty() ){
                MainAutoComp.SearchBox.ClearTxt();
                $get(MainAutoComp.inptSearchFriend).value = MainAutoComp.SearchBox.DefaultStr;
            }else{
                if( $val(MainAutoComp.inptSearchFriend) == MainAutoComp.SearchBox.DefaultStr ){
                    MainAutoComp.SearchBox.ClearTxt();
                    
                }else if ($get(MainAutoComp.Result.dvFriendsList).innerHTML != ''){
                    MainAutoComp.Result.Open();
                }
            }
        },
        Blur : function(){

            if(MainAutoComp.SearchBox.GetTxt() == ''){
                $get(MainAutoComp.inptSearchFriend).style.color = '#d1d1d1';
                $get(MainAutoComp.inptSearchFriend).value = MainAutoComp.SearchBox.DefaultStr;
            }else{
                if(!MainAutoComp.IsLogged()){ // if user if offline
                    return;
                }
                MainAutoComp.Result.Close();
            }
        },
        IsEmpty : function(){
            if($val(MainAutoComp.inptSearchFriend) == ''){
                return true
            }else return false;            
        },
        Search : function(obj,event){
        
            var e = event || window.event;
            var type = e.type.toString();
            var key = e.keyCode || e.charCode;
            var key = Number(key);
            var postBody = [];
            if (MainAutoComp.SearchBox.GetTxt().length > 0 ){
                if ( (key != 13) && (key != 40) && (key != 38) ){
                    if ( MainAutoComp.SearchBox.GetTxt() == MainAutoComp.SearchBox.PrevTxt ){
                        return;
                    }
                    //MainAutoComp.timeStamp = setTimeout("MainSearchAjaxCall('FriendSearch',['FriendCount=" + MainAutoComp.Result.MaxResults + "','FriendName=" + MainAutoComp.SearchBox.GetTxt() + "'],MainAutoComp.Result.HandleResult )",300);
                    //MainAutoComp.timeStamp = setTimeout("MainSearchAjaxCall('FriendSearch',['FriendCount=" + MainAutoComp.Result.MaxResults + "','FriendName=" + encodeURIComponent(MainAutoComp.SearchBox.GetTxt()) + "'],MainAutoComp.Result.HandleResult )",200);
                    clearInterval(MainAutoComp.timeStamp);
                    if(MainAutoComp.IsLogged()){
                        MainAutoComp.timeStamp = setTimeout('MainAutoComp.Result.GetUserList()',50);
                    }
                }else if(e.type == 'keydown'){ // if  Enter,KeyUp,KeyDown was pressed
                    switch(key){
                        case 38 : MainAutoComp.Result.KeyUp();break;
                        case 40 : MainAutoComp.Result.KeyDown();break;
                        case 13 : MainAutoComp.Result.Select(e);break;
                    }
                }
            }else{ 
                MainAutoComp.Result.Close();
                clearInterval(MainAutoComp.timeStamp);
            }
            MainAutoComp.SearchBox.PrevTxt = $val(MainAutoComp.inptSearchFriend);
            
        }
    },
    Result : {
        dvFriendsList : 'dvMainSearchFilterResults',
        CurRow : null,
        ListOpen : false,
        MaxResults : 6,
        arrFriendList : null,
        SelectedRowClass : 'SelectedRow', NotSelectedRowClass : 'NotSelectedRow',
        HandleResult : function(str){
            MainAutoComp.Result.arrFriendList = eval("(" + str + ")");
        },
        GetUserList : function(){
            // get and show user list
            MainAutoComp.Result.Clear();
            var max = 0;
            var inputTxt = MainAutoComp.SearchBox.GetTxt()
            if(MainAutoComp.Result.arrFriendList == null) return;
            for(var i=0;i<MainAutoComp.Result.arrFriendList.length;i++){
                var name = MainAutoComp.Result.arrFriendList[i].fname + ' ' + MainAutoComp.Result.arrFriendList[i].lname;
                if( (name.indexOf(inputTxt) == 0 ) || ( MainAutoComp.Result.arrFriendList[i].fname.indexOf(inputTxt) == 0 ) || ( MainAutoComp.Result.arrFriendList[i].lname.indexOf(inputTxt) == 0) ){
                    MainAutoComp.Result.Add(MainAutoComp.Result.arrFriendList[i]);
                    max++;
                    if(max >= MainAutoComp.Result.MaxResults){break;}  
                }
            }
            if ($get(MainAutoComp.Result.dvFriendsList).innerHTML != ''){
                MainAutoComp.Result.Open();
            };
        },
        IsEmpty : function(){
            if($get(MainAutoComp.Result.dvFriendsList).innerHTML == ''){
                return true
            }else return false;
        },
        Add : function(person){
            MainAutoComp.Result._BuildFriendsList(person);
            MainAutoComp.SearchBox.PrevTxt =  MainAutoComp.SearchBox.GetTxt();

        },
        Clear : function(){
            $get(MainAutoComp.Result.dvFriendsList).innerHTML = '' ;
            MainAutoComp.Result.Close();
            MainAutoComp.Result.SetCurrent(null);
        },
        Open : function(){
            MainAutoComp.Result._SetPos();
            $show(MainAutoComp.Result.dvFriendsList);
            MainAutoComp.Result.ListOpen = true;
        },
        Close : function(){
            $hide(MainAutoComp.Result.dvFriendsList);
            MainAutoComp.Result.ListOpen = false;
        },
        Select : function(e){
            //$get(MainAutoComp.inptSearchFriend).disabled = true;
            var element,name;
            MainAutoComp.Result.Close();
            $get(MainAutoComp.inptSearchFriend).disabled = true;
            if(!MainAutoComp.IsLogged()){
                MoveToPage(DomainURL + 'PublicSearch.aspx?Name=' + MainAutoComp.SearchBox.GetTxt());
                return cancelDefault(e);
            };
            if( ( $get(MainAutoComp.Result.dvFriendsList).innerHTML == '' ) || ( !MainAutoComp.Result.GetCurrent() ) ){
                MoveToPage(DomainURL + 'Search.aspx?Custom=1&ResultsPerPage=10&FirstName=' + MainAutoComp.SearchBox.GetTxt() + '&SearchSortBy=4&SearchOrder=1');
            }else{
                element = $get( MainAutoComp.Result.GetCurrent() );
                name = element.getElementsByTagName('input')[0].value;
                $get(MainAutoComp.inptSearchFriend).value = name;
                MoveToPage(DomainURL + 'Profile.aspx?MemberID=' + $get(MainAutoComp.Result.GetCurrent()).id );
            }
            return cancelDefault(e);
            
        },
        SetCurrent : function(id){
            MainAutoComp.Result.CurRow = id;
        },
        GetCurrent : function(){
            return MainAutoComp.Result.CurRow;
        },
        _SetPos: function(){
            var element = $get('dvMainSearchContainer');
            var autoComp = $get(MainAutoComp.Result.dvFriendsList);
            elementtDim = GetDimension(element);
            elementPos = GetElementPos(element);
            autoComp.style.left = elementPos[0] - Math.abs(elementtDim[0] - 180) + 4 + "px"; //width of the auto
            autoComp.style.top = elementPos[1] + elementtDim[1] + 2 + "px";        
            
        },
        MarkRow : function(obj){
            if (MainAutoComp.Result.GetCurrent()){
                var userid = MainAutoComp.Result.GetCurrent();
                $get(userid).className = 'dvRow';
            }
            obj.className = 'dvRowSelected';
            MainAutoComp.Result.SetCurrent(obj.id);
        },
        UnMarkRow : function(obj){
            obj.className = 'dvRow';
            MainAutoComp.Result.SetCurrent(false);
        },
        KeyUp : function(){
            var id = MainAutoComp.Result.GetCurrent();
            if(id){
                var dvUserid = $get(id);
                dvUserid = previousNode(dvUserid);
                if(dvUserid){
                    MainAutoComp.Result.MarkRow(dvUserid);
                }else{
                    MainAutoComp.Result.UnMarkRow($get(id));
                }
            }
        },
        KeyDown : function(){
            var id = MainAutoComp.Result.GetCurrent();
            if(id){
                var dvUserid = $get(id);
                dvUserid = nextNode(dvUserid);
                if(dvUserid){
                    MainAutoComp.Result.MarkRow(dvUserid);
                }
            }else if(!MainAutoComp.Result.IsEmpty()){
                var dvUserid = firstNode(MainAutoComp.Result.dvFriendsList);
                MainAutoComp.Result.MarkRow(dvUserid);
            }
        },
        _BuildFriendsList : function(person){
            var str = '';
            var fname = person.fname ; 
            var lname = person.lname;
            var inputValue = MainAutoComp.SearchBox.GetTxt();
            var splitName = [];
            var splitInputName = [];
            str = '<div  id="{0}" class="dvRow" onmouseover="MainAutoComp.Result.MarkRow(this)"  onclick="MainAutoComp.Result.Select(event)" style="z-index:99999;overflow:hidden;">';
            str += '<img style="vertical-align:middle;width:30px;height:30px;margin-left:10px;padding:1px;" src="{1}"\/>';
            str +=  '<a href="' + DomainURL + 'Profile.aspx?MemberID={0}" style="text-decoration:none;"><span class="UserName">{2}<\/span></a>';
            str += '<input type="hidden" value="{3}"/>'
            str += '<\/div>'
            str = str.replace(/\{0\}/g,+ person.id );
            str = str.replace(/\{1\}/g,person.img);
            //name = CutLongText(person.name,17);
            //splitName = name.split(" ");
            splitInputName = inputValue.split(" ");
            str = str.replace(/\{3\}/g,CutLongText(fname + ' ' + lname)); 
            for (var i=0;i<splitInputName.length;i++){
                fname = fname.replace(new RegExp('^' + splitInputName[i],"i"),'<span class="spnSelected">' + splitInputName[i] + '</span>')
                lname = lname.replace(new RegExp('^' + splitInputName[i],"i"),'<span class="spnSelected">' + splitInputName[i] + '</span>')
                /*                
                fname = fname.replace(splitInputName[i],'<span class="spnSelected">' + splitInputName[i] + '</span>')
                lname = lname.replace(splitInputName[i],'<span class="spnSelected">' + splitInputName[i] + '</span>')
                */
                
            };
            //splitName = splitName.join(" ");
            //splitInputName = splitInputName.join(" ");
            str = str.replace(/\{2\}/g,CutLongText(fname + ' ' + lname)); 
            $get(MainAutoComp.Result.dvFriendsList).innerHTML += str ;
                   
        }
    }
}
