function generate_name(){
    var result, i, j;
    result = '';
    for(j=0; j<8; j++){
        i = Math.floor(Math.random()*16).toString(16).toUpperCase();
        result = result + i;
    }
    return result
}

function HistoryObj(){
    this.oldln = null;
    this.newln = null;
    
    this.setNew = function (obj){
        this.oldln = this.newln;
        this.newln = obj;
        if (this.oldln) $(this.oldln).removeClass('selected');
        if (this.newln) $(this.newln).addClass('selected');
    }
    this.getPrev = function (){
        return this.oldln;
    }
    this.getCur = function (){
        return this.newln;
    }
    this.reset = function (){
        if (this.oldln) $(this.oldln).removeClass('selected');
        this.oldln = null;
        this.newln = null;
    }
}



function SearchBox(qbase, input_el, master_el, on_control_load){
    var dropdown_created = false;
    if (typeof(master_el) != 'undefined')
        var master = master_el;
    else
        var master = null;
    var old = input_el;
    var old_onchange = old.onchange;
    var old_form = old.form;
    $(old).before('<input autocomplete="off" type="text" name="sf_'+old.name+'" value="" id="sf_'+old.id+'" />');
    //+ '<input type="hidden" name="'+old.name+'" value="'+old.value+'" id="'+old.id+'" />');
    var raw_id_input = document.getElementById(old.id);
    //var raw_id_input = document.createElement("input");
    //raw_id_input.setAttribute("type", "hidden");
    //raw_id_input.setAttribute("name", old.name);
    //raw_id_input.setAttribute("value", old.value);
    //raw_id_input.setAttribute("id", old.id);
    //old_form.appendChild(raw_id_input);
    var input = document.getElementById('sf_' + old.id);
    raw_id_input.old_onchange = old_onchange;
    input.query_base = qbase;
    if (raw_id_input.value){
        $.post(input.query_base,
                {'id': raw_id_input.value},
                function(json){
                    eval('data='+json);
                    if (data && data['current'])
                        input.value = data['current'];
                        if (raw_id_input.old_onchange)
                            raw_id_input.old_onchange();
                    //if (typeof(on_control_load) != 'undefined' && on_control_load){
                        //on_control_load();
                    //}
                });
    }
    // init
    $(input).after('<div class="dropdown-hold"><div id="dropdown_' + generate_name() +'" class="dropdown"></div></div>');
    input.drop_down_div = $(input).next('div').children('div.dropdown')[0];
    input.currentSelected = new HistoryObj();
    var curren_coof = 1;
    var div_clicked = false;
    $(input.drop_down_div).parent('div').mouseover(function(){
        if (!div_clicked)
            div_clicked = true;
    });
    
    $(input.drop_down_div).parent('div').mouseout(function(){
        div_clicked = false;
    });
    
    $(input.drop_down_div).parent('div').click(function(){
        input.focus();
    });
    
    input.onblur = function (){
        if (!div_clicked)
            this.hideDropDown();
    }
    
    input.hideDropDown = function (){
        $(this.drop_down_div).parent('div').hide();
        this.currentSelected.reset();
    }
    
    input.setDropDownDivPosition = function(count){
        var ddown = this.drop_down_div.style;
        //var toppos = this.offsetTop;
        //var leftpos = this.offsetLeft;
        //var heightpos = count * 14;
        //var obj = this;
        //while((obj = obj.offsetParent) != null){
            //toppos += obj.offsetTop;
            //leftpos += obj.offsetLeft;
        //}
        //if ($(window).height() - toppos + $(document).scrollTop() > heightpos){
            //ddown.top = toppos + this.offsetHeight + 'px';
            //ddown.left = leftpos + 'px';
        //}
        //else{
            //ddown.top = toppos - heightpos + 'px';
            //ddown.left = leftpos + 'px';
        //}
        $(this.drop_down_div).parent('div').css({width: this.offsetWidth-2 + 'px'});
        $(this.drop_down_div).css({width: this.offsetWidth-27 + 'px'});
    }
    
    input.currentSelected = new HistoryObj();
    
    input.highlightSelected = function(){
        var lnobj = this.currentSelected.getCur();
        if (!lnobj)
            return;
        $(lnobj).addClass('selected')
        var lnobj = this.currentSelected.getPrev();
        if (!lnobj)
            return;
        $(lnobj).removeClass('selected')
    }
    
    input.delayed_exec = function(func, wait){
        if (this.timer)
            clearTimeout(this.timer);
        this.timer = setTimeout(func, wait);
    }
    
    input.onkeypress = function (event){
        if (typeof(event) == 'undefined')
            event = window.event;
        switch (event.keyCode){
            case 27: this.hideDropDown(); break;
            //case 38: this.prevLine(); break;
            //case 40: this.nextLine(); break;
            case 13: this.acceptSelected(); return false;
            case 9: this.hideDropDown(); break;
            default: this.delayed_exec(this.getSearchList, 500);
        }
        this.focus();
    }

    // получить список похожих строк
    input.getSearchList = function(){
        lookup = {'word': input.value};
        if (master)
            eval('lookup.' + master.id + ' = ' + master.value + ';')
        $.post(input.query_base,
            lookup,
            function(json) {
                eval('data=' + json + ';');
                if (typeof(data) != 'undefined')
                    input.ajax_onLoad(data);
            });
    }
    // перемещение по списку
    input.nextLine = function(){
        $search_list = $(this.drop_down_div).find('div.scroll-content').children('div');
        var cur = this.currentSelected.getCur();
        if ($search_list.length == 0)
            return;
        if (!cur){
            this.currentSelected.setNew($search_list[0]);
            //this.highlightSelected();
            return;
        }
        var nxt = $(cur).next('div')[0];
        if (nxt){
            this.currentSelected.setNew(nxt);
            //this.highlightSelected();
        }
        if (nxt.offsetTop + nxt.offsetHeight + $(nxt).parent('div')[0].offsetTop > $(nxt).parent('div').parent('div')[0].offsetHeight){
            $(nxt).parent('div').css('top', $(nxt).parent('div')[0].offsetTop - nxt.offsetHeight);
            $('div.scroll-slider').css('top', - $(nxt).parent('div')[0].offsetTop * curren_coof);
            //$('div.scroll-down').mousedown();
            //$('div.scroll-down').mouseup();
        }
    }
    
    input.prevLine = function(){
        $search_list = $(this.drop_down_div).find('div.scroll-content').children('div');
        var cur = this.currentSelected.getCur();
        if ($search_list.length == 0)
            return;
        if (!cur){
            this.currentSelected.setNew($search_list[$search_list.length-1]);
            //this.highlightSelected();
            return;
        }
        
        var prv = $(cur).prev('div')[0];
        if (prv){
            this.currentSelected.setNew(prv);
            //this.highlightSelected();
        }
        if ($(prv)[0].offsetTop + $(prv).parent('div')[0].offsetTop < 0){
            //$('div.scroll-up').mousedown();
            //$('div.scroll-up').mouseup();
        }
    }
    
    input.acceptSelected = function(){
        var cur = this.currentSelected.getCur();
        if (!cur)
            return;
        this.value = cur.innerHTML;//cur.innerText.replace(/^\s*/, '').replace(/\s*$/, '');
        if (raw_id_input){
            raw_id_input.value = cur.id;
            if (raw_id_input.old_onchange)
                raw_id_input.old_onchange();
        }
        this.hideDropDown();
    }
    
    // ajax_onLoad >
    input.ajax_onLoad = function(data){
        streets = data['list'];
        s = '';
        if (streets.length > 0){
            for (i=0; i < streets.length; i++){
                s += '<div class="search-item" id="' + streets[i][1] + '">' + streets[i][0] + '</div>';
            }
            
            this.setDropDownDivPosition(streets.length);
            this.drop_down_div.innerHTML = s;
            //if ($(this.drop_down_div).find('div.search-item').length > 10){
                $(this.drop_down_div).css({height: '200px'});
            //}
            $(this.drop_down_div).parent('div').show();
            if (!dropdown_created){
                $(this.drop_down_div).customScrollV({lineWidth: 25});
                dropdown_created = true;
            }else{
                $(this.drop_down_div).next('div.scroll-bar').remove();
                $(this.drop_down_div).customScrollV({lineWidth: 25});
            }
            $(this.drop_down_div).next('div.scroll-bar').show();
            
            if ($(this.drop_down_div).find('div.search-item').length <= 10){
                $(this.drop_down_div).next('div.scroll-bar').find('div.scroll-slider').hide();
            }else{
                curren_coof = (this.drop_down_div.offsetHeight - 40 - 62) / $('div.scroll-content')[0].offsetHeight;
            }
            
            $(this.drop_down_div).find('div.search-item').each(function(){
                $(this).unbind('mouseenter').mouseenter(function(){
                    input.currentSelected.setNew($(this)[0]);
                });
                
                $(this).unbind('click').click(function(){
                    input.value = $(this).html(); //cur.innerText.replace(/^\s*/, '').replace(/\s*$/, '');
                    if (raw_id_input){
                        raw_id_input.value = $(this).attr('id');
                        if (raw_id_input.old_onchange)
                            raw_id_input.old_onchange();
                    }
                    input.hideDropDown();
                });
            });
            this.currentSelected.reset();
            this.currentSelected.setNew($(this.drop_down_div).find('div.search-item:first')[0]);
        }else
            this.hideDropDown();
        
    };
}


