function VSearchWidget() {
    return this;
}

var VSearchWidget = function(_map, _element)
{
    this.map = _map;
    this.element = _element;
    this._listeners = [];
}
VSearchWidget.prototype._listeners;

VSearchWidget.prototype.output_element;
VSearchWidget.prototype.search_form_element;
VSearchWidget.prototype.butt_element;
VSearchWidget.prototype._marker;
VSearchWidget.prototype._geo;
VSearchWidget.prototype.lastSearchValue;

VSearchWidget.SEARCH = [];
VSearchWidget.SEARCH["ru"] = 'Найти';
VSearchWidget.SEARCH["ua"] = 'Пошук';
VSearchWidget.SEARCH["en"] = 'Search';

VSearchWidget.SAMPLE = [];
VSearchWidget.SAMPLE["ru"] = 'Киев, Крещатик';
VSearchWidget.SAMPLE["ua"] = 'Київ, Хрещатик';
VSearchWidget.SAMPLE["en"] = 'Kiev, Kreschatyk';

VSearchWidget.WAIT = [];
VSearchWidget.WAIT["ru"] = 'Пожалуйста, подождите...';
VSearchWidget.WAIT["ua"] = 'Зачекайте будь ласка...';
VSearchWidget.WAIT["en"] = 'Please wait...';

VSearchWidget.NOTFOUND = [];
VSearchWidget.NOTFOUND["ru"] = 'Ничего не найдено';
VSearchWidget.NOTFOUND["ua"] = 'Нічого не знайдено';
VSearchWidget.NOTFOUND["en"] = 'Nothing found';

VSearchWidget.DEFAULT_COUNTRY = [];
VSearchWidget.DEFAULT_COUNTRY["ru"] = 'Украина';
VSearchWidget.DEFAULT_COUNTRY["ua"] = 'Україна';
VSearchWidget.DEFAULT_COUNTRY["en"] = 'Ukraine';


VSearchWidget.prototype.content =
'<a name="search_widjet">' +
'<table width="100%" height="100%" cellspacing="-2">'+
'<tr>'+
'<td width="100%" id=#search_formCont#>'+
'</td>'+
'<td id=#buttonCont#>'+
'</td>'+
'</tr>'+
'<tr width="100%" height ="100%">'+
'<td colspan=2 id=#outputCont#>'+
'</td>'+
'</tr>'+
'</table>';


VSearchWidget.prototype.show = function() {
    var _this = this;

    var idSearch_formCont = String(Math.random());
    this.content = this.content.replace("#search_formCont#", idSearch_formCont);

    var idButtonCont = String(Math.random());
    this.content = this.content.replace("#buttonCont#", idButtonCont);

    var idOutputCont = String(Math.random());
    this.content = this.content.replace("#outputCont#", idOutputCont);

    this.element.innerHTML = this.content;

    this.search_formCont_element = document.getElementById(idSearch_formCont);
    this.buttCont_element = document.getElementById(idButtonCont);
    this.outputCont_element = document.getElementById(idOutputCont);

    // создание поля ввода
    var idSearch_form = String(Math.random());
    var search_form = document.createElement("input");
    search_form.id = idSearch_form;
    search_form.value = VSearchWidget.SAMPLE[this.map.language()];
    search_form.style.color = "gray";
    search_form.type = "text";
    search_form.style.width = "100%";
    search_form.href = "#";
    search_form.onfocus = function() {
        if (search_form.value == VSearchWidget.SAMPLE[_this.map.language()])
        {
            search_form.value = "";
            search_form.style.color = "black";
            _this.output_element.innerHTML = "";
        }
    }
    search_form.onkeyup = function(e) {
        if(!e) e = window.event;
        if (e.keyCode != '13') return;

        _this.getList();
    }
    this.search_formCont_element.appendChild(search_form);
    this.search_form_element = document.getElementById(idSearch_form);

    // создание кнопки
    var submitButt = document.createElement("input");
    submitButt.type = "button";
    submitButt.style.width = "65px";
    submitButt.value = VSearchWidget.SEARCH[this.map.language()];
    submitButt.href = "#";
    submitButt.onclick = function() {
        if (search_form.value != "" && search_form.value != _this.lastSearchValue)
        {
            _this.getList();
            _this.lastSearchValue = search_form.value;
        }
    }
    this.buttCont_element.appendChild(submitButt);

    // создание поля вывода
    var idOutput = String(Math.random());
    var outputForm = document.createElement("div");
    outputForm.id = idOutput;
    outputForm.style.width = this.element.offsetWidth  + "px";
    outputForm.style.height = this.element.offsetHeight - this.search_form_element.offsetHeight + "px";
    outputForm.style.border = '1px dotted gray';
    outputForm.style.fontFamily = "Arial";
    outputForm.style.overflow = "auto"; 
    outputForm.style.fontSize = "80%";
    outputForm.href = "#";
    this.outputCont_element.appendChild(outputForm);
    this.output_element = document.getElementById(idOutput);
}

VSearchWidget.prototype.onSelect = function(listener) {
    if (!this._listeners['select']) this._listeners['select'] = [];
    this._listeners['select'].push(listener);
}

VSearchWidget.prototype.onChangeCoords = function(listener) {
    if (!this._listeners['change_coords']) this._listeners['change_coords'] = [];
    this._listeners['change_coords'].push(listener);
}


VSearchWidget.prototype.fire = function(event, params) {
    if (!this._listeners[event]) return this;
    
    for (var i in this._listeners[event])
        this._listeners[event][i](params);
    return this;
}

VSearchWidget.prototype.mapCenter = function(coords, zoom) {
    if (this._marker != null) this.map.remove(this._marker);
    this._marker = new VMarker(coords);
    this._marker.draggable(true);
    
    var _this = this;
    this._marker.enddrag(function(m)
    {
        _this.fire("change_coords", m.coords() );
    });
    
    this.map.add(this._marker);
    zoom ? this.map.center(coords, zoom || 16) : this.map.center(coords);
}

VSearchWidget.prototype.clear = function() {
    this.output_element.innerHTML = '';
    this.map.remove(this._geo);
    this.map.remove(this._marker);
}

VSearchWidget.prototype.showObjectOnMap = function(href) {
    if (href._obj.coords() == null) return;
    if (this._geo != null)
        this.map.remove(this._geo);
    
    this.mapCenter(href._obj.bounds().center(), 16);
    
    this._marker.info(href.innerHTML, {
        width: 250,
        height: 40
    });
    
    if (href._obj.coords().length != 2)
    {
        this._geo = new VMultiLine(href._obj.coords());
        this._geo.color("#ff0000");
        this._geo.lineWidth(4);
        this._geo.opacity(0.7);
        this.map.add(this._geo);
    }
    
    this._marker.enddrag();
    
    this.map.repaint();
}

VSearchWidget.prototype.getList = function () {
    var _this = this;

    this.output_element.innerHTML = "";
    this.output_element.innerHTML = VSearchWidget.WAIT[this.map.language()];

    VRemoteCall.request("address", _this.search_form_element.value,
        function callback(layer) {
            if (layer.childs().length == 0) {
                _this.output_element.innerHTML = VSearchWidget.NOTFOUND[_this.map.language()];
                return;
            }
            
            _this.output_element.innerHTML = "";

            var countries = [];
            var data = [];
            for (var i = 0; i < layer.childs().length; i++)
            {
                var obj = layer.childs(i);

                if (obj.country == undefined)
                    obj.country = VSearchWidget.DEFAULT_COUNTRY[_this.map.language()];

                if (countries.indexOf(obj.country) < 0)
                    countries.push(obj.country);
                
                if (data[obj.country] == null)
                    data[obj.country] = [];
                data[obj.country].push(obj);
            }
            countries = countries.sort().reverse();
            
            for (i = 0; i < countries.length; i++) {
                var country_ = countries[i];

                if(typeof(country_) != "string") continue;

                var klop = document.createElement("div");
                klop.style.paddingBottom = '8px';
                klop.style.fontSize = '14px';
                klop.style.marginTop = '10px';
                klop.style.marginBottom = '7px';
                klop.innerHTML = country_;
                _this.output_element.appendChild(klop);

                for (i = 0; i < data[country_].length; i++) {
                    var obj = data[country_][i];

                    var href = document.createElement("a");
                    href.style.textDecoration = 'none';
                    
                    var name = [];
                    if (obj.settlement) name.push(obj.settlement);
                    if (obj.street) name.push(obj.street);
                    if (obj.name) name.push(obj.name);
                    name = name.join(", ");

                    var description = [];
                    if (obj.district) description.push(obj.district);
                    if (obj.region) description.push(obj.region);
                    if (description.length > 0)
                        description = "(" + description.join(", ") + ")";
                    else
                        description = "";

                    href.innerHTML = "<div style='padding-bottom: 2px;'>" +
                                        name +
                                        "<div style='font-size: 90%; color: gray;'>" +
                                        description +
                                        "</div>" +
                                     "</div>";

                    href.href = "javascript: ";
                    href._obj = obj;
                    href.onclick = function() {
                        _this.showObjectOnMap(this);
                    }
                    _this.output_element.appendChild(href);
                }
            }
        }
    );
    
}