
var AC = new Class({
    initialize: function(inputId, cityInput, postalcodeinput, rappuInput, autocompleteDiv, keepCityInAddress) {

        this.div = $(autocompleteDiv);

        var c = $(inputId).getCoordinates();

        var top = c.top + c.height;
//        var mleft = c.left;
        top = 0; // uusi leiska hajoitti jotain

        var mleft = 0;
        var width = c.width - 11;

        this.div.setStyle("margin-left", mleft  + "px");
        this.div.setStyle("top", top + "px");
        this.div.setStyle("width", width + "px");

        this.aclist = new Element("ul", {
            'id': 'bgDiv'
        });
//        this.aclist.addEvent("mousedown", function (event) {
//            alert("jihuu");
//            event.stop();
//        });
        this.div.adopt(this.aclist);

        this.index = 0;
        this.size = 0;
        this.shown = false;

        this.param = $(inputId);
        this.param.setAttribute("autocomplete", "off");

        this.city = $(cityInput);
        this.postalcode = $(postalcodeinput);
        this.rappu = $(rappuInput);

        this.keepCityInAddress = $(keepCityInAddress);//saatavuus-portletia varten, kaupunki pitää säilyttää suluissa katuosoitteen perässä

        this.minShow = 2;
        this.maxShow = 10;

        var ac = this;

        this.param.addEvent("keydown", function (event) {
            ac.handleOnKeyDown(event);
        });

        this.param.addEvent("blur", function () {
//            ac.close();
        });

    },

    setSearchTypes: function(types) {
        this.options.searchTypes = types;
    },

    search: function() {
        var s = this.param.value.trim();
        if (s.length > 0) {
            var ac = this;
            AutocompleteSearch.search(s, function (data) {
                ac.setList(data)
            });
        } else
            this.close();
    },

    setList: function(data) {
        try {

            this.index = 0;
            var i = 0;
            this.aclist.innerHTML = "";
            var ac = this;

            $each(data, function(value) {
                i++;
                var li = new Element("li");
                li.id = i;
                li.className = "";
                li.innerHTML = value;

                li.addEvent('mouseenter', function () {
                    ac.select(li)
                });
                li.addEvent('mouseleave', function () {
                    ac.unselect(li)
                });
                li.addEvent('mousedown', function () {
                    ac.setParam(li);
                    ac.close();
                });
                ac.aclist.appendChild(li);
            });

            this.size = i;

            if (this.size > 0) {
                this.show();
            } else {
                this.close();
            }

        } catch (err) {
            alert(err);
        }
    },

    select: function(li) {
        this.index = li.id;
        li.className = "over";
    },

    unselect: function(li) {
        if (li)
            li.className = "";
    },

    setParam: function(li) {
        var txt;
        if (li.getChildren() && li.getChildren().length == 3) {
            txt = $("h" + li.id).innerHTML.replace('&amp;', '&');;
        } else {
            txt = li.innerHTML.replace('&amp;', '&');
        }

        while (txt.indexOf('&amp;') > -1)
            txt = txt.replace('&amp;', '&');


        if(keepCityInAddress == 'true'){
            this.param.value = txt;            
        }else{
            this.param.value = txt.substr(0, txt.indexOf("(")).trim();
        }

        var ac = this;
        AutocompleteSearch.select(txt, function (data) {
            if  (data) {

                /*
                    jos käyttäjä valitse osoitteen listasta ->
                    asetetaan postinumero ja postitoimipaikka, ja asetetaan kentät readonly-tilaan
                */
                ac.city.value = data.city;
                ac.city.readOnly = true;

                ac.city.className += ' readonlyText';
//                ac.city.onfocus = ac.city.blur;
//                ac.city.onfocus = skipFocus(ac.city);
                ac.city.tabIndex = -1;//skipataan kenttä tabilla

                ac.postalcode.value = data.postalcode;
                ac.postalcode.readOnly = true;
                ac.postalcode.className += ' readonlyText';
//                ac.postalcode.onfocus = ac.postalcode.blur;
//                ac.postalcode.onfocus = skipFocus(ac.postalcode);
                ac.postalcode.tabIndex = -1;//skipataan kenttä tabilla

                if(ac.rappu != null){
                    ac.rappu.focus();//siirretään focus rappu-kenttään
                }
            }
        });
    },

    close: function() {
        this.shown = false;
        this.index = 0;
        this.size = 0;
        this.aclist.innerHTML = "";
        this.div.style.display = "none";
    },

    show: function() {
        this.shown = true;
        this.div.style.display = "block";
    },

    handleOnKeyDown: function(e) {
        e = new Event(e);

        switch (e.code) {
            case 16: // shift
            case 9: // tab
                if (this.index > 0) {
                    this.setParam($(this.index + ""));                    
                }
                this.close();
                break;
            case 39: // right
            case 37: // left
                break;
            case 13: // return
                if (this.index > 0) {

                    this.setParam($(this.index + ""));
                    this.close();
                    e.stop();
//                    return false;
                } else {
                    this.close();
                    if (Browser.Engine.trident) {
                        if (this.options.categorySearch) {
                            categorySearch();
                        } else {
                            submitSearchForm();
                        }
                        e.stop();
                    }
                }
                break;
            case 27: // esc
                this.close();
                this.index = 0;
                break;
            case 38: // up
                if (this.index > 0) {
                    this.unselect($(this.index + ""));
                    this.index--;
                }

                if (this.index > 0) {
                    this.select($(this.index + ""));

                    if (this.index == this.minShow && this.div.scrollTop > 0) {
                        this.maxShow--;
                        this.minShow--;
                        this.div.scrollTop = this.div.scrollTop - $(this.index + "").offsetHeight;
                    }
                }

                e.returnValue = false;
                if (e.preventDefault)
                    e.preventDefault();
                break;
            case 40: // down

                if (this.index > 0)
                    this.unselect($(this.index + ""));
                if (this.index < this.size) {
                    this.index++;

                    if (this.index == this.maxShow && this.index < this.size) {
                        this.maxShow++;
                        this.minShow++;
                        this.div.scrollTop = this.div.scrollTop + $(this.index + "").offsetHeight;
                    }
                }

                this.select($(this.index + ""));

                e.returnValue = false;
                if (e.preventDefault)
                    e.preventDefault();
                break;
            default:
                var ac = this;

                /*
                    jos käyttäjä kirjoittaa osoitekenttään ->
                    tyhjennetään postinumero ja postitoimipaikka ja palautetaan kentät takaisin muokattaviksi
                */
                if(this.city.readOnly == true){
                    ac.city.readOnly = false;
                    ac.city.value = '';
                    ac.city.className = this.city.className.replace('readonlyText', '');
                    ac.city.onfocus = null;
                    ac.city.tabIndex = ac.param.tabIndex;//palautetaan alkuperäinen tabIndex (hieman rumaa, mutta works so far)
                }
                if(this.postalcode.readOnly == true){
                    ac.postalcode.readOnly = false;
                    ac.postalcode.value = '';
                    ac.postalcode.className = this.postalcode.className.replace('readonlyText', '');
                    ac.postalcode.onfocus = null;
                    ac.postalcode.tabIndex = ac.param.tabIndex;//palautetaan alkuperäinen tabIndex (hieman rumaa, mutta works so far)
                }
                    
                setTimeout(function() {
                    ac.search();
                }, 0);
        }
    }
});

//function skipFocus(inputField){
//    var next = inputField.tabIndex;
//    if (next < inputField.form.length){
//        inputField.form.elements[next].focus();
//    }
//}
