var showACEnabled = false;


var AC = new Class({
    options: {
        historyCookie: "inoa_search_history",
        searchTypes: [1, 2, 3, 4],
        categorySearch: false
    },

    initialize: function(inputId, autocompleteDiv, searchHistoryType, options) {
        this.setOptions(options);

        this.div = $(autocompleteDiv);
        
        this.aclist = new Element("ul", {
            'id': 'bgDiv'
        });
        
        if (Browser.Engine.trident) {
        	var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
        	if (isIE6) {
		        this.div.addClass('select-free');
		        this.div.appendChild(new Element('iframe', {'id':'iefixiframe','frameborder':'0'}));     
        	}  
        }
        
        this.div.adopt(this.aclist);

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

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

        this.minShow = 2;
        this.maxShow = 5;

        var ac = this;

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

        this.param.addEvent("blur", function () {
            showACEnabled = false;
            ac.close();
        });

        this.param.addEvent("click", function () {
            showACEnabled = true;
            ac.showHistory();
        });

    },

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

    search: function() {
        var s = this.param.value.trim();
        if (s.length > 0 && this.options.searchTypes != null) {
            var ac = this;
            AutoCompleteRemote.search(s, this.options.searchTypes, 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) {
                if (!Browser.Engine.trident || (Browser.Engine.trident && i<7)) {
                    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;', '&');
        this.param.value = txt;
    },

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

    show: function() {
        if (showACEnabled) {
            var c = this.param.getCoordinates();

            var top = c.top + c.height + 4;
            var mleft = c.left;
            var width = c.width - 8;

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

            this.shown = true;
            this.div.style.display = "block";
        } else
            this.close();
    },

    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;
                setTimeout(function() {
                    ac.search();
                }, 0);
        }
    },

    showHistory: function() {
        var history = new Hash.Cookie(this.options.historyCookie, {path: "/", duration: 365});
		if (history.get('sw'+ this.swType)) {
			var searchWords = history.get('sw'+ this.swType);

			var searchHistory = [];
			var timestamps = [];
			for (var i=0; i<searchWords.length; i++) {
				searchHistory[ searchWords[i][1] ] = searchWords[i][0];
				timestamps[i] = searchWords[i][1];
			}

			timestamps.sort();
			timestamps.reverse();
			var listedWords = [];

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

            var tyyppi = this.swType;

            if (timestamps.length > 0) {
                var t = new Element("div", {
                   "class": "acHeader"
                });
                t.innerHTML = "viimeaikaisia_hakuja".localize();

                t.adopt([
                    new Element("a", {
                        'styles' : {
                            'position' : 'absolute',
                            'right' : '4px',
                            'top' : '1px',
                            'font-weight' : 'normal',
                            'text-decoration' : 'underline',
                            'color' : '#6e634e',
                            'margin' : '0',
                            'padding' : '0',
                            'cursor' : 'pointer'
                        },
                        'class': "clearFrommap",
                        'events' : {
                            'mousedown' : function (event) {
                                event = new Event(event);
                                event.stop();
                                emptySearchwordHistory(tyyppi);
                                ac.close();
                                return false;
                            }
                        }
                    }).set('text', "clear".localize())
                ]);

                ac.aclist.appendChild(t);
            }

            var count = 0;
            $each(timestamps, function(value) {
				if (listedWords[ searchHistory[ value ] ] != 1 && ++count < 7) {

					listedWords[ searchHistory[ value ] ] = 1;

                    var s = searchHistory[ value ].trim();

                    var date = new Date();
					date.setTime(value);
					var d = formatDateToStringNoTime(date);

                    id++;
                    var li = new Element("li");
                    li.id = id;
                    li.className = "";
//                    li.innerHTML = s;
                    li.data = s;

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

                    if (s.indexOf(",") == 0) {
                        s = s.substring(1);
                    } else if (s.indexOf(",") == s.length - 1) {
                        s = s.substring(0, s.length - 1);
                    }
                    
                    var left = new Element("div", {
                        'id': 'h' + id,
                        'class': 'left'
                    });
                    left.innerHTML = s;

                    var right = new Element("div", {
                        'class': 'right'
                    });
                    right.innerHTML = '';
//                    right.innerHTML = d;

                    var clean = new Element("div", {
                        'class': 'CleanRight'
                    });
                    clean.innerHTML = "";

                    li.adopt([left, right, clean]);

                    ac.aclist.appendChild(li);
                }
			});

            this.size = id;

            if (this.size > 0) {
                this.show();
            } else {
                this.close();
            }
        }
    }
});
AC.implement(new Options);


var MapAC = new Class({
    Extends: AC,
    initialize: function(inputId, secondInputId, isStreetAC, autocompleteDiv, searchHistoryType, options) {
        this.parent(inputId, autocompleteDiv, searchHistoryType, options);

        this.isStreetAC = isStreetAC;

        if (secondInputId == "") {
            this.secondInput = null;
        } else {
            this.secondInput = $(secondInputId);
            this.secondInput.setAttribute("autocomplete", "off");
        }
//        this.streetInputFocus = false;

        var ac = this;

        this.param.addEvent("focus", function () {
            showACEnabled = true;
            ac.search();
        });

//        this.secondInput.addEvent("focus", function () {
////            ac.showHistory();
////            ac.streetInputFocus = true;
//            ac.search();
//        });
//
//        this.secondInput.addEvent("blur", function () {
//            ac.close();
////            ac.streetInputFocus = false;
//        });
//
//        this.secondInput.addEvent("keydown", function (event) {
//            ac.handleOnKeyDown(event);
//        });
    },

    setParam: function(li) {
        var txt;
        if (li.data != undefined) {
            txt = li.data;
        }
        else 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;', '&');
        }

        var locality, street;
        if (txt.indexOf(",") == -1) {
            locality = txt;
            street = '';
        } else {
            locality = txt.substring(txt.indexOf(",") + 1, txt.length).trim();
            street = txt.substring(0, txt.indexOf(",")).trim();
        }

        if (this.isStreetAC) {
            this.param.value = street;
            if (this.secondInput != null)
                this.secondInput.value = locality;
        } else {
            this.param.value = locality;
            if (this.secondInput != null)
                this.secondInput.value = street;
        }
    },

    search: function() {
        var secValue = this.secondInput == null ? '' : this.secondInput.value.trim();
        var s = this.isStreetAC ? secValue : this.param.value.trim();
        var k = this.isStreetAC ? this.param.value.trim() : secValue;

        if (!this.isStreetAC && (s.length > 0 || (k.length > 2 && k != "katuosoite".localize()))) {
            var ac = this;
            if (k == "katuosoite".localize())
                k = null;

            MapRemote.geocodeAddressAC(k, s, function (data) {
                ac.setList(data)
            });
        } else if (/*this.streetInputFocus && */k.length == 2) {
//            this.showHistory();
        } else if (/*this.streetInputFocus && */k.length > 2) {
            this.close();
        } else {
//            this.showHistory();
        }
    }

});


//hakuhistoria: types: yritykset, paattajat, ostoopas, kartat
function addSearchwordToHistory(s, defaultText, type) {
    try {
        s = s.replace(/</g, "&lt;").replace(/>/g, "&gt;");
        s = s.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g, "\"\"");
        s = s.replace(/iframe(.*)/g, "");
        s = s.replace(/embed(.*)/g, "");
        s = s.replace(/script(.*)/g, "");
        s = s.replace(/eval\((.*)\)/g, "");

        if (s != null && s.length > 0 && s != defaultText) {
            var history = new Hash.Cookie('inoa_search_history', {path: "/", duration: 365});
            var searchWords = null;
            if (history.get('sw' + type)) {
                searchWords = history.get('sw' + type);
            } else {
                searchWords = new Array();
            }

            searchWords.push([s, $time()]);

            if (searchWords.length > 10)
                searchWords = searchWords.slice(searchWords.length - 10, searchWords.length);

            history.set("sw" + type, searchWords);
        }
    } catch (err) {
//        alert(err);
    }
    return true;
}

function emptySearchwordHistory(type) {
    var history = new Hash.Cookie('inoa_search_history', {duration: 365});
    history.set("sw" + type, new Array());
//    updateHistoryList();
}


function formatDateToStringNoTime(date) {
    return (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '.' + ((1 + date.getMonth()) < 10 ? '0' + (1 + date.getMonth()) : (1 + date.getMonth()) ) + '.' + date.getFullYear();
}



