function SearchinputKeyDown(ev)
{
    if (!ev)
        ev = window.event;

    if (ev.keyCode == 13)
        submitSearch();
}

function isInExtent(GPoint)
{
    for (var i = 0; i < legalExtent.length; i++)
    {
        if (GPoint.lng() > legalExtent[i][0] && GPoint.lat() > legalExtent[i][1] && GPoint.lng() < legalExtent[i][2] && GPoint.lat() < legalExtent[i][3])
        {
            return true;
        }
    }


    return false;
}

function addLocal(t)
{
    var repl = [
        {'onm': 'Bornheim', 'z': 'Pfalz'},
        {'onm': 'Brühl', 'z': 'Baden'},
        {'onm': 'Altdorf', 'z': 'Pfalz'},
        {'onm': 'Fürth', 'z': 'Odenwald'},
        {'onm': 'Essingen', 'z': 'Pfalz'},
        {'onm': 'Malsch', 'z': 'bei Wiesloch'},
        {'onm': 'Meckenheim', 'z': 'Pfalz'},
        {'onm': 'Lindenberg', 'z': 'Pfalz'},
        {'onm': 'Mühlhausen', 'z': 'Kraichgau'},
        {'onm': 'Laudenbach', 'z': 'Bergstraße'},
        {'onm': 'Lautertal', 'z': 'Odenwald'},
        {'onm': 'Neunkirchen', 'z': 'Baden'},
        {'onm': 'Oberhausen', 'z': 'Baden'},
        {'onm': 'Schönau', 'z': 'Baden'},
        {'onm': 'Rimbach', 'z': 'Odenwald'},
        {'onm': 'Rosenberg', 'z': 'Odenwald'},
        {'onm': 'Schwarzach', 'z': 'Odenwald'},
        {'onm': 'Schönbrunn', 'z': 'Baden'},
        {'onm': 'Rohrbach', 'z': 'Pfalz'},
        {'onm': 'Römerberg', 'z': 'Pfalz'},
        {'onm': 'Winden', 'z': 'Pfalz'},
        {'onm': 'Waldsee', 'z': 'Pfalz'},
        {'onm': 'Walldorf', 'z': 'Baden'},
        {'onm': 'Aspach', 'z': 'Württemberg'},
        {'onm': 'Benningen', 'z': '71726'},
        {'onm': 'Eschenbach', 'z': 'Württemberg'},
        {'onm': 'Hemmingen', 'z': 'Württemberg'},
        {'onm': 'Grafenau', 'z': 'Württemberg'},
        {'onm': 'Winterbach', 'z': 'Württemberg'},
        {'onm': 'Wangen', 'z': 'Göppingen'},
        {'onm': 'Battenberg', 'z': 'Pfalz'},
        {'onm': 'Berg', 'z': 'Pfalz'},
        {'onm': 'Freimersheim', 'z': 'Pfalz'},
        {'onm': 'Hirschhorn', 'z': 'Neckar'},
        {'onm': 'Hochstadt', 'z': 'Pfalz'},
        {'onm': 'Kirrweiler', 'z': 'Pfalz'},
        {'onm': 'Lautertal', 'z': 'Odenwald'},
        {'onm': 'Weingarten', 'z': 'Pfalz'},
        {'onm': 'Wernau', 'z': 'Neckar'},
        {'onm': 'Westheim', 'z': 'Pfalz'}
    ];

    for (var i = 0; i < repl.length; i++)
    {
    	//var m1 = '/' + repl[i].onm+ '/i';
    	var m1=new RegExp(repl[i].onm, "i");
    	//if (t.match(/Wangen/i))
    	if (t.search(m1) > -1)
    	{
    		//alert("m2!");
	    	var m2a = new RegExp("\\s" + repl[i].onm + "$", "i");
	    	var m2b = new RegExp("^" + repl[i].onm + "\\s", "i");
	    	var m2c = new RegExp("^" + repl[i].onm + "$", "i");
	    	var m2d = new RegExp("\\s" + repl[i].onm + "\\s", "i");
    	if (t.search(m2a) > -1 || t.search(m2b) > -1 || t.search(m2c) > -1 || t.search(m2d) > -1)
      {
    			//alert("m3!");
    			if (t.indexOf(repl[i].z) < 0)
    			{
    				//return t.replace(r1, repl[i].onm + " (" + repl[i].z + ")");
    				return t.replace(m1, repl[i].onm + " (" + repl[i].z + ")");
    			} else
    			{
						//alert("already in!");
    			}

    		}
    	}

    }


    return t;
}


//Zwingenberg		Zwingenberg (Bergstraße)
//            	Zwingenberg (Baden-Württemberg)
//Altdorf			Altdorf bei Böblingen
//					Altdorf bei Esslingen


function submitSearch()
{
    // TODO Zwingenberg, Altdorf...Popup?

    if (modus == 'Immoref')
    {
        submitGeocode(addLocal(document.getElementById('searchinput').value));
    }
 
    if (document.getElementById('searchinput').value == '')
        return false;

    removeSearchResults();
    document.getElementById('waitani').style.visibility = 'visible';
    geocoder.getLocations(addLocal(document.getElementById('searchinput').value),georet);

}

function submitGeocode(adr)
{
    if (adr == '')
        return;

    removeSearchResults();
    geocoder.getLocations(adr,function(points) {georet_geocode(points, strasse, objectid, nutzung, objektname)});

}


function georet(point)
{
        //alert(point.Placemark.length);
        document.getElementById('waitani').style.visibility = 'hidden';
        var matches = [];
        var BBox = new GLatLngBounds();

        if (!point || point.Status.code != 200) {
            //alert(txt["searchNotFound"]);
            jAlert(txt["searchNotFound"], txt["alert"]);
        } else {
            for (var i = 0; i < point.Placemark.length; i++)
            {
                var pnt = new GLatLng(point.Placemark[i].Point.coordinates[1], point.Placemark[i].Point.coordinates[0]);
                if (isInExtent(pnt))
                {
                  matches.push(point.Placemark[i]);
                  
                }
            }

            if (matches.length == 1)
            {
                showMatch(matches[0].Point.coordinates[0], matches[0].Point.coordinates[1], matches[0].address, true, false);
                return true;
            }
            if (matches.length >1)
            {
                //var ih = '<img src="img/x.gif" onclick="document.getElementById(\'searchresultslist\').style.display = \'none\';" style="cursor: pointer;">';
                //var ih = '<img src="img/x.gif" onclick="$(\'#searchresultslist\').hide(\'fold\');" style="cursor: pointer;">';
                var ih = '<img src="img/x.gif" onclick="$(\'#searchresultslist\').fadeOut();" style="cursor: pointer;">';
                ih += '<ul>';
                
                for (var i = 0; i < matches.length; i++)
                {
                    BBox.extend(new GLatLng(matches[i].Point.coordinates[1], matches[i].Point.coordinates[0]));
                    ih += '<li class="searchresultlink" onmouseover="searchMarkers[' + i + '].openInfoWindowHtml(\'<exposeelink>' + matches[i].address.replace(/,/g, ',<br>') + '</exposeelink>\', {\'noCloseOnClick\': true} );" onclick="showMatch(' + matches[i].Point.coordinates[0] + ', ' + matches[i].Point.coordinates[1] + ', \'' + matches[i].address + '\'); document.getElementById(\'searchresultslist\').style.display = \'none\';">' + matches[i].address + "</li>";
                    showMatch(matches[i].Point.coordinates[0], matches[i].Point.coordinates[1], matches[i].address, false, false);
                }
                //alert(ih);
                //document.getElementById('searchresultslist').style.display = 'block';
                document.getElementById('searchresultslist').innerHTML = ih + "</ul>";
                $('#searchresultslist').fadeIn();
                //$('#searchresultslist').show('fold');

                //mapObject.setCenter(BBox.getCenter());
                mapObject.setCenter(BBox.getCenter(), mapObject.getBoundsZoomLevel(BBox) > 15 ? 15 : mapObject.getBoundsZoomLevel(BBox)-1);

                return true;
            }


        }

        //alert(txt["searchNotFound"]);
        jAlert(txt["searchNotFound"], txt["alert"]);
        return false;

}

function georet_geocode(point, strasse, objectid, nutzung, objectname)
{
        //alert(point.Placemark.length);
        document.getElementById('waitani').style.visibility = 'hidden';
        
        var matches = [];

        if (!point || point.Status.code != 200) {
            //alert(txt["geocodeNotFound"]);
            jAlert(txt["geocodeNotFound"], txt["alert"]);
        } else {
            for (var i = 0; i < point.Placemark.length; i++)
            {
                var pnt = new GLatLng(point.Placemark[i].Point.coordinates[1], point.Placemark[i].Point.coordinates[0]);
                if (isInExtent(pnt))
                {
                  matches.push(point.Placemark[i]);
                }
            }

            if (matches.length == 1)
            {
                

                if (matches[0].AddressDetails.Accuracy < 6)
                {
                    showMatch(matches[0].Point.coordinates[0], matches[0].Point.coordinates[1], matches[0].address, true, false);
                    //alert(txt["geocodeGmdResult"]);
                    jAlert(txt["geocodeGmdResult"], txt["alert"]);
                } else
                {
                    showMatch(matches[0].Point.coordinates[0], matches[0].Point.coordinates[1], matches[0].address, true, nutzung);
                    Immoref(null, new GLatLng(matches[0].Point.coordinates[1], matches[0].Point.coordinates[0]));
                }
                return true;
            }

            if (matches.length >1)
            {
                var minstrdist = 9999;
                var bestmatch = -1;

                for (var i = 0; i < matches.length; i++)
                {
                    if (levenshtein(strasse, matches[i].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) < minstrdist)
                        bestmatch = i;

                }

                

                if (matches[bestmatch].AddressDetails.Accuracy < 6)
                {
                    showMatch(matches[bestmatch].Point.coordinates[0], matches[bestmatch].Point.coordinates[1], matches[bestmatch].address, true, false);
                    //alert(txt["geocodeGmdResult"]);
                    jAlert(txt["geocodeGmdResult"], txt["alert"]);
                } else
                {
                    showMatch(matches[bestmatch].Point.coordinates[0], matches[bestmatch].Point.coordinates[1], matches[bestmatch].address, true, nutzung);
                    Immoref(null, new GLatLng(matches[bestmatch].Point.coordinates[1], matches[bestmatch].Point.coordinates[0]));
                }

                return true;
            }


        }

        //alert(txt["geocodeNotFound"]);
        jAlert(txt["geocodeNotFound"], txt["alert"]);
        return false;
}

function showMatch(lon, lat, address, zoomTo, nutzung)
{
    if (nutzung)
    {
        var opts = {
            'title': address,
                "icon": new GIcon({
            'iconSize': new GSize(14,12),
            'image': iconsArray[nutzung],
            'iconAnchor': new GPoint(7,6),
            'infoWindowAnchor': new GPoint(7,6)
            })};

        var mm = new GMarker(new GLatLng(lat, lon), opts);
    }  else
    {
        var mm = new GMarker(new GLatLng(lat, lon), {'title': address});
    }

    if (zoomTo)
        mapObject.setCenter(new GLatLng(lat, lon), nutzung ? 16 : 14);

    mm.nutzung = 'searchresult';
    searchMarkers.push(mm);
    mapObject.addOverlay(mm);
    mm.openInfoWindowHtml("<exposeelink>" + address.replace(/,/g, ',<br>') + "</exposeelink>", {'noCloseOnClick': true} );
}

function removeSearchResults()
{
    var n = 0;
    //for (var i = 0; i < searchMarkers.length; i++)
    //{
    while (searchMarkers.length > 0 && n < 1000){
        try {
          searchMarkers.pop().remove();
          //var deli = searchMarkers.pop()
          //deli.closeInfoWindow();
          //.remove();
        } catch(ex)
        {

        }
        n++;
    }
    //}
}




