jQuery.fn.autocomplete2 = function(url, geographyCodeInput, geographyControlGUID, settings) {
    return this.each(function()//do it for each matched element
    {
        //this is the original input
        var textInput = $(this);
        //create a new hidden input that will be used for holding the return value when posting the form, then swap names with the original input
        textInput.after('<input type=hidden name="' + textInput.attr("name") + '"/>').attr("name", textInput.attr("name") + "_text");
        var valueInput = $(this).next();
        //create the ul that will hold the text and values
        valueInput.after('<ul class="autocomplete"></ul>');
        var list = valueInput.next().css({ top: textInput.offset().top + textInput.outerHeight(), left: textInput.offset().left, width: textInput.width() });
        var oldText = '';
        var oldInput = '';
        var oldGUID = '';
        var typingTimeout;
        var size = 0;
        var selected = 0;

        settings = jQuery.extend(//provide default settings
        {
            minChars: 1,
            timeout: 500,
            parameters: { 'inputName': valueInput.attr('name'), 'inputId': textInput.attr('id') }
        }, settings);

        function getData(text) {
            window.clearInterval(typingTimeout);
            if (text != oldText && (settings.minChars != null && text.length >= settings.minChars)) {
                clear();
                $.get(url + "?text=" + text, function(data) {
                    var items = '';
                    if (data) {
                        var result = new Array();
                        result = data.split('|');
                        size = result.length;
                        for (i = 0; i < result.length; i++)//iterate over all options
                        {
                            items += result[i];
                            list.html(items);
                            //on mouse hover over elements set selected class and on click set the selected value and close list
                            list.show().children().
                                hover(function() { $(this).addClass("selected").siblings().removeClass("selected"); }, function() { $(this).removeClass("selected") }).


				// РЕАКЦИЯ НА КЛИК ПО ВЫБРАННОМУ ПУНКТУ
                                click(function() { valueInput.val($(this).attr('value')); var textSelected = $(this).text(); var divideLocator = textSelected.lastIndexOf("#"); oldGUID = textSelected.substr(divideLocator + 1); $(geographyCodeInput).val(oldGUID); oldInput = textSelected.substr(0, divideLocator); $(geographyControlGUID).val($(geographyCodeInput).val()); textInput.val(oldInput); clear(); 


                         	c = $("#ct_cnt").attr("value");					
				if (c<3){
					
                                	$("#selected_cities_to").append("<tr><td>"+oldInput+"<input type=\"hidden\" name=\"city_to_id[]\" value=\""+oldGUID+"\"></td><td><a onclick=\"$(this).parent().parent().remove(); minus_ct_cnt(); return false;\"><img border=\"0\" src=\"/tariffs_cl/minus.gif\"></a></td></tr>");
					$("#ct_cnt").attr("value", c*1+1);

                                
				} else {
                       			alert ("Вы можете выбрать не более 3 городов доставки!"); 
				}

				});

				


                        }
                    }
                }
                );
                oldText = text;
            }
        }

        function clear() {
            list.hide();
            size = 0;
            selected = 0;
        }

        textInput.keydown(function(e) {
            window.clearInterval(typingTimeout);
            if (e.which == 27)//escape
            {
                if (list.css("display") != "none") {
                    textInput.val(oldInput);
                    $(geographyCodeInput).val(oldGUID);
                }
                clear();
            }
            else if (e.which == 13)//enter
            {
                if (list.css("display") == "none")//if the list is not visible then make a new request, otherwise hide the list
                {
                    getData(textInput.val());
                } else {
                    if (selected == 0) {


			// РЕАКЦИЯ НА ЭНТЕР ПО ВЫБРАННОМУ ПУНКТУ	

                        var textSelected = list.children().eq(selected).text();
                        var divideLocator = textSelected.lastIndexOf("#");
                        oldGUID = textSelected.substr(divideLocator + 1);
                        $(geographyCodeInput).val(oldGUID);
                        oldInput = textSelected.substr(0, divideLocator);
                        textInput.val(oldInput);
                        valueInput.val(list.children().eq(selected).attr('value'));
                        $(geographyControlGUID).val($(geographyCodeInput).val());





			//	$("#selected_cities_to").append("<tr><td>"+oldInput+"<input type=\"hidden\" name=\"city_to_id[]\" value=\""+oldGUID+"\"></td><td><a onclick=\"$(this).parent().parent().remove(); return false;\"><img border=\"0\" src=\"/tariffs_cl/minus.gif\"></a></td></tr>");

                         	c = $("#ct_cnt").attr("value");					
				if (c<3){
					
                                	$("#selected_cities_to").append("<tr><td>"+oldInput+"<input type=\"hidden\" name=\"city_to_id[]\" value=\""+oldGUID+"\"></td><td><a onclick=\"$(this).parent().parent().remove(); minus_ct_cnt(); return false;\"><img border=\"0\" src=\"/tariffs_cl/minus.gif\"></a></td></tr>");
					$("#ct_cnt").attr("value", c*1+1);
                                
				} else {
                       			alert ("Вы можете выбрать не более 3 городов доставки!"); 
				}





                    }
                    clear();
                }
                e.preventDefault();
                return false;
            }
            else if (e.which == 9)//tab
            {
                if (list.css("display") != "none") {
                    var textSelected = list.children().eq(selected).text();
                    var divideLocator = textSelected.lastIndexOf("#");
                    oldGUID = textSelected.substr(divideLocator + 1);
                    $(geographyCodeInput).val(oldGUID);
                    oldInput = textSelected.substr(0, divideLocator);
                    textInput.val(oldInput);
                    valueInput.val(list.children().eq(selected).attr('value'));
                    $(geographyControlGUID).val($(geographyCodeInput).val());
                }
                clear();
                return true;
            }
            else if (e.which == 40 || e.which == 38)//move up, down 
            {
                if (list.css("display") != "none") {
                    switch (e.which) {
                        case 40:
                        case 9:
                            selected = selected >= size - 1 ? 0 : selected + 1; break;
                        case 38:
                            selected = selected <= 0 ? size - 1 : selected - 1; break;
                        default: break;
                    }
                    e.preventDefault();
                    //set selected item and input values
                    var textSelected = list.children().removeClass('selected').eq(selected).addClass('selected').text();
                    var divideLocator = textSelected.lastIndexOf("#");
                    $(geographyCodeInput).val(textSelected.substr(divideLocator + 1));
                    textInput.val(textSelected.substr(0, divideLocator));
                    valueInput.val(list.children().eq(selected).attr('value'));
                    $(geographyControlGUID).val($(geographyCodeInput).val());
                }
            } else {
                //invalidate previous selection
                valueInput.val('');
                typingTimeout = window.setTimeout(function() { getData(textInput.val()) }, settings.timeout);
            }
        });
    });
};

