var tjs_w3c = (document.getElementById)  ? true : false;
var tjs_ie4 = (document.all && !tjs_w3c) ? true : false;
var tjs_ie5 = (document.all &&  tjs_w3c) ? true : false;
var tjs_ns4 = (document.layers) ? true : false;
var mouseX = 0;
var mouseY = 0;
var maxPolygonPunktAnzahl = 15;
var wmsoebvi;
var delay = 1;
var control_panel;
var withOebvi;
var widthoutOebvi;
var hover_control;
var WFS_VERSION='1.0.0';
var oebviMarker;
var tree = null;

// mappings for oebvi layer
var oebviMapping = {};
oebviMapping["Alle"] = "Alle";
oebviMapping["PotsdamMittelmark"] = "PM";
oebviMapping["DahmeSpreewald"] = "LDS";
oebviMapping["Oberhavel"] = "OHV";
oebviMapping["Uckermark"] = "UM";
oebviMapping["OberspreewaldLausitz"] = "OSL";
oebviMapping["OderSpree"] = "LOS";
oebviMapping["Barnim"] = "BAR";
oebviMapping["TeltowFlaeming"] = "TF";
oebviMapping["Havelland"] = "HVL";
oebviMapping["Potsdam"] = "P";
oebviMapping["OstprignitzRuppin"] = "OPR";
oebviMapping["FrankfurtOder"] = "FF";
oebviMapping["Cottbus"] = "CB";
oebviMapping["Prignitz"] = "PR";
oebviMapping["MaerkischOderland"] = "MOL";
oebviMapping["SpreeNeisse"] = "SPN";
oebviMapping["ElbeElster"] = "EE";
oebviMapping["BrandenburgHavel"] = "BRB";

// counter for GetFeatureInfo-Requests
var getFeatureInfoCounter = 0;

//OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";


OpenLayers.Control.Hover = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
        'delay': 3000,
        'pixelTolerance': 10,
        'stopMove': false
    },

    initialize: function(options) {
        this.handlerOptions = OpenLayers.Util.extend(
            {}, this.defaultHandlerOptions
        );
        OpenLayers.Control.prototype.initialize.apply(
            this, arguments
        );
        this.handler = new OpenLayers.Handler.Hover(
            this,
            {
                'pause': this.onPause,
                'move': this.onMove
            },
            this.handlerOptions
        );
    },

    onPause: function(evt) {
        if(hover_control != undefined)
            hover_control.deactivate();

        var layers = fetchOebviLayer();
            if(layers.length == 0)
                  return;
         
        for(var i = 0; i < layers.length; i++) {

            var url =  layers[i].getFullRequestString({
                REQUEST: "GetFeatureInfo",
                EXCEPTIONS: "application/vnd.ogc.se_xml",
                BBOX: layers[i].map.getExtent().toBBOX(),
                X: evt.xy.x,
                Y: evt.xy.y,
                INFO_FORMAT: 'text/html',
                QUERY_LAYERS: oebviMapping[layers[i].params.LAYERS],
                WIDTH: wmsoebvi.map.size.w,
                HEIGHT: wmsoebvi.map.size.h
            });
//alert(url);
            getFeatureInfoCounter++;
            OpenLayers.loadURL(url, '', this, setHTML);
        } 
    
    },

    onMove: function(evt) {
        // if this control sent an Ajax request (e.g. GetFeatureInfo) when
        // the mouse pauses the onMove callback could be used to abort that
        // request.

        //Tooltip loeschen
        tt_obj.hideWithDelayTT(1000);
    }
});


function fetchOebviLayer() {

    var oebvi = [];
    var layers = map.layers;

    for(var lay in layers) {
        var layer = layers[lay];
        
        // Oebvi layers are WMS layer, so skip other
        if(!(layer instanceof OpenLayers.Layer.WMS))
            continue;

        // fetch visible Oebvi layers only
        if(layer.visibility.toString().toLowerCase() == "false")
            continue;

        var url = layer.url;
        // if the substring oebvi is not in the url, the layer is not a
        // OEBvI layer
        if(url != undefined && url.search('oebvi') == -1)
            continue;

        // if the oebvi layer, containing all regions, is selected, we dont need
        // to search for further oebvi layers
        if(layer.params.LAYERS == "Alle") {
            oebvi = [];
            oebvi.push(layer);
            return oebvi;
        }

        oebvi.push(layer);
    }

    return oebvi;
}


function initMap(){

//loading();

    options = {
        maxExtent: new OpenLayers.Bounds(3140000.0, 5590000.0, 3590000.0, 6030000.0),
        scales: [1600000,600000,300000,100000,30000,15000,7000,3500,1200,500],
        units: "m",
        projection: "EPSG:325833"
    };

    ov_options = {
        maxExtent: new OpenLayers.Bounds(3140000.0, 5590000.0, 3590000.0, 6030000.0),
        scales: [8000000,3500000],
        units: "m",
        projection: "EPSG:325833"
    };

    map = new OpenLayers.Map('map', { controls: [] });
    map.setOptions(options);

   // Hinzufügen des Layers "Logo" und die Position bestimmen
    var hoehe = parseInt(document.getElementById('map').style.height) -55;
	map.addControl(new OpenLayers.Control.Attribution({position: new OpenLayers.Pixel(3,hoehe)}));
    
    map.addControl(new OpenLayers.Control.PanZoomBar({position: new OpenLayers.Pixel(5,30)}));
    map.addControl(new OpenLayers.Control.MouseDefaults());
    map.addControl(new OpenLayers.Control.ScaleLine());
    
    var container = document.getElementById("mouse");
	var mouse = new OpenLayers.Control.MousePosition({element:OpenLayers.Util.getElement('MOUSEPOS'),numDigits:2, div: container});
	map.addControl(mouse);

    // Add loadingpanel
    var loading_indicator =  document.getElementById("loading");
    var loadingpanel = new OpenLayers.Control.LoadingPanel({div:loading_indicator});
    map.addControl(loadingpanel);

    

    // XXX The following line causes problems when using Ext and MapFish
    //map.addControl(new OpenLayers.Control.KeyboardDefaults());

    var controlOptions = {
          mapOptions: ov_options
      };

    var ov = new OpenLayers.Control.OverviewMap(controlOptions);
    map.addControl(ov);

    /*
     * Dienste definieren
     */
    // DNM-WMS als Base Layer
    wms = new OpenLayers.Layer.WMS(
        "Topographie - Standard",
        "http://isk.geobasis-bb.de/ows/dnm.php",
        {
            layers: "bg,vegetation,gewaesser,siedlung,bln,brb,verkehrsobjekte,transport,strassennamen,ortsnamen,gewaessernamen",
            format: "image/png",
            BGCOLOR: '0xFFFFFF' },
        {
            isBaseLayer: true,
            buffer: 0, 
            opacity: 0.7,
            visibility: true,
            attribution: legendHtml,
            transitionEffect: 'resize',
            singleTile: true
        }
    );

    // DOP-WMS als Base Layer
    dop20c = new OpenLayers.Layer.WMS(
        "Digitale Orthophotos 20cm",
        "http://isk.geobasis-bb.de/ows/dop20c.php",
        {
            layers: "18000,19000",
            format: "image/png",
            BGCOLOR: '0xFFFFFF'
        },
        {
            isBaseLayer: true,
            buffer: 0,
            tileSize: new OpenLayers.Size(300,300), 
            visibility: true,
            attribution: legendHtml
        }
    );
    
    // DOP-WMS als Base Layer
    dop40g = new OpenLayers.Layer.WMS(
        "Digitale Orthophotos 40cm",
        "http://isk.geobasis-bb.de/ows/dop40.php",
        {
            layers: "18000",
            format: "image/png",
            BGCOLOR: '0xFFFFFF'
        },
        {
            isBaseLayer: true,
            buffer: 0,
            tileSize: new OpenLayers.Size(300,300), 
            visibility: true,
            attribution: legendHtml
        }
    );

    // DNM-WMS als Base Layer
    wms_amt = new OpenLayers.Layer.WMS(
        "Topographie - Vollton",
        "http://isk.geobasis-bb.de/ows/dnm.php",
        {
            layers: "bg,vegetation,gewaesser,siedlung,bln,brb,transport,verkehrsobjekte,ortsnamen,strassennamen,gewaessernamen",
            format: "image/png",
            BGCOLOR: '0xFFFFFF',
            styles: "2"
        },
        {
            isBaseLayer: true,
            buffer: 0,  
            visibility: true,
            attribution: legendHtml,
            transitionEffect: 'resize',
            singleTile: true
        }
    );

    // DNM-WMS als Base Layer
    wms_grau = new OpenLayers.Layer.WMS(
        "Topographie - Grauton",
        "http://isk.geobasis-bb.de/ows/dnm.php",
        {
            layers: "bg,vegetation,gewaesser,siedlung,bln,brb,transport,verkehrsobjekte,ortsnamen,strassennamen,gewaessernamen",
            format: "image/png",
            BGCOLOR: '0xFFFFFF',
            styles: "3"
        },
        {
            isBaseLayer: true,
            buffer: 0, 
            visibility: true,
            attribution: legendHtml,
            transitionEffect: 'resize',
            singleTile: true
        }
    );
    
    
    // DNM-WMS als Base Layer
    wms_dtk10 = new OpenLayers.Layer.WMS(
        "DTK10",
        "http://isk.geobasis-bb.de/ows/dtk10.php",
        {
            layers: "18000,19000",
            format: "image/png",
            BGCOLOR: '0xFFFFFF'
        },
        {
            isBaseLayer: true,
            buffer: 0,
            tileSize: new OpenLayers.Size(300,300), 
            visibility: true,
            attribution: legendHtml
        }
    );
    
    // DNM-WMS als Base Layer
    wms_dtk25 = new OpenLayers.Layer.WMS(
        "DTK25",
        "http://isk.geobasis-bb.de/ows/dtk25.php",
        {
            layers: "18000,19000",
            format: "image/png",
            BGCOLOR: '0xFFFFFF'
        },
        {
            isBaseLayer: true,
            buffer: 0,
            tileSize: new OpenLayers.Size(300,300), 
            visibility: true,
            attribution: legendHtml
        }
    );


    // DNM-WMS als Base Layer
    wms_dtk50 = new OpenLayers.Layer.WMS(
        "DTK50",
        "http://isk.geobasis-bb.de/ows/dtk50.php",
        {
            layers: "18000,19000",
            format: "image/png",
            BGCOLOR: '0xFFFFFF'
        },
        {
            isBaseLayer: true,
            buffer: 0,
            tileSize: new OpenLayers.Size(300,300), 
            visibility: true,
            attribution: legendHtml
        }
    );
    
    // DNM-WMS als Base Layer
    wms_dtk100 = new OpenLayers.Layer.WMS(
        "DTK100",
        "http://isk.geobasis-bb.de/ows/rk100.php",
        {
            layers: "RK100_farbe",
            format: "image/png",
            BGCOLOR: '0xFFFFFF'
        },
        {
            isBaseLayer: true,
            buffer: 0,
            tileSize: new OpenLayers.Size(300,300), 
            visibility: true,
            attribution: legendHtml
        }
    );
    
    // Verwaltungsgrenzen-WMS als Overlay
    wms_vg = new OpenLayers.Layer.WMS(
        "Verwaltungsgrenzen",
        "http://isk.geobasis-bb.de/ows/dnmvg.php",
        {
            layers: "vgrz",
            transparent: true,
            format: "image/png"
        },
        {
            visibility: false,
            buffer: 0,
            tileSize: new OpenLayers.Size(300,300), 
            attribution:''
        }
    );

    // VerwaltungsgrenzenNamen-WMS als Overlay
    wms_nvg = new OpenLayers.Layer.WMS(
        "Verwaltungsnamen",
        "http://isk.geobasis-bb.de/ows/dnmvg.php",
        {
            layers: "nvgrz",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0,
            visibility: false,
            attribution: '',
            minScale: 500000
        }
    );


    // VerwaltungsgrenzenNamen-WMS als Overlay
    wms_otl = new OpenLayers.Layer.WMS(
        "Ortsteile",
        "http://isk.geobasis-bb.de/ows/dnmvg.php",
        {
            layers: "otl,notl",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0,
            visibility: false,
            attribution: '',
            minScale: 30000
        }
    );

    // ALK-WMS als Overlay
    wms_alk = new OpenLayers.Layer.WMS(
        "ALK",
        "http://isk.geobasis-bb.de/ows/alk.php",
        {
            layers: "alk",
            transparent: true,
            format: "image/png"
        },
        {
            
            singleTile: true, 
            buffer: 0,
        //    tileSize: new OpenLayers.Size(400,400), 
            visibility: false,
            attribution: '',
            minScale: 2000
        }
    );

    // Postleitzahlen-WMS als Overlay
    wms_plz = new OpenLayers.Layer.WMS(
        "Postleitzahlen",
        "http://isk.geobasis-bb.de/ows/dnmvg.php",
        {
            layers: "plz",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0,
            visibility: false,
            attribution: '',
            minScale: 150000
        }
    );
    
    // Vorwahlnummern-WMS als Overlay
    wms_onkz = new OpenLayers.Layer.WMS(
        "Vorwahlnummern",
        "http://isk.geobasis-bb.de/ows/dnmvg.php",
        {
            layers: "onkz",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0, 
            visibility: false,
            attribution: '',
            minScale: 150000
        }
    );
    
    // Blattschnitte 1:10000-WMS als Overlay
    wms_bstk10 = new OpenLayers.Layer.WMS(
        "BS TK10",
        "http://isk.geobasis-bb.de/ows/dnmbs.php",
        {
            layers: "tk10",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0, 
            visibility: false,
            attribution: ''
        }
    );
    
    // Blattschnitte 1:25000-WMS als Overlay
    wms_bstk25 = new OpenLayers.Layer.WMS(
        "BS TK25",
        "http://isk.geobasis-bb.de/ows/dnmbs.php",
        {
            layers: "tk25",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0, 
            visibility: false,
            attribution: ''
        }
    );
    
    // Blattschnitte 1:50000-WMS als Overlay
    wms_bstk50 = new OpenLayers.Layer.WMS(
        "BS TK50",
        "http://isk.geobasis-bb.de/ows/dnmbs.php",
        {
            layers: "tk50",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0, 
            visibility: false,
            attribution: ''
        }
    );

    // Blattschnitte 1:50000AS-WMS als Overlay
    wms_bstk50as = new OpenLayers.Layer.WMS(
        "BS TK50AS",
        "http://isk.geobasis-bb.de/ows/dnmbs.php",
        {
            layers: "tk50as",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0,
            visibility: false,
            attribution: ''
        }
    );

    // FIS-Online Lagefestpunkte als Overlay
    wms_fistp = new OpenLayers.Layer.WMS(
        "FIS TP",
        "http://isk.geobasis-bb.de/ows/fis_fp.php",
        {
            layers: "TP-Exz-VL-akt,TP-Exz-akt,TP-akt",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0,
            visibility: false,
            attribution: '',
            minScale: 250000
        }
    );

    // FIS-Online Höhenfestpunkte als Overlay
    wms_fisniv = new OpenLayers.Layer.WMS(
        "FIS NIV",
        "http://isk.geobasis-bb.de/ows/fis_fp.php",
        {
            layers: "NivP-akt-oird",
            transparent: true,
            format: "image/png"
        },
        {
            singleTile: true,
            buffer: 0,
            visibility: false,
            attribution: '',
            minScale: 250000
        }
    );


    // Highlight Layer Style
    var highlightStyles = new OpenLayers.StyleMap(
        'highlight',
        {
            fillColor: "#FF9900",
            fillOpacity: 0.2,
            strokeColor: "#FF0000",
            strokeWidth: 2,
            strokeOpacity: 1
        }
    );

    //------------------------------------------------------------------------------------
    // OebVI als Overlays
    //-----------------------------------------------------------------------------------
    wmsoebvi = new OpenLayers.Layer.WMS( "Alle ÖbVI",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "Alle",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: true,
                                        singleTile: true,
                                        opacity: 0.8 }
                                     );
    wmsoebvi.events.register('visibilitychanged', wmsoebvi, toggleOEBVI);

    wmsoebvibrb = new OpenLayers.Layer.WMS( "Brandenburg a.d. Havel",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "BrandenburgHavel",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvibrb.events.register('visibilitychanged', wmsoebvibrb, toggleOEBVI);

    wmsoebvic = new OpenLayers.Layer.WMS( "Cottbus",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                      { layers:"Cottbus",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvic.events.register('visibilitychanged', wmsoebvic, toggleOEBVI);

    wmsoebviff = new OpenLayers.Layer.WMS( "Frankfurt (Oder)",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "FrankfurtOder",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebviff.events.register('visibilitychanged', wmsoebviff, toggleOEBVI);

    wmsoebvip = new OpenLayers.Layer.WMS( "Potsdam",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "Potsdam",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvip.events.register('visibilitychanged', wmsoebvip, toggleOEBVI);

    wmsoebvibar = new OpenLayers.Layer.WMS( "Barnim",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "Barnim",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvibar.events.register('visibilitychanged', wmsoebvibar, toggleOEBVI);

    wmsoebvilds = new OpenLayers.Layer.WMS( "Dahme-Spreewald",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "DahmeSpreewald",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvilds.events.register('visibilitychanged', wmsoebvilds, toggleOEBVI);

    wmsoebviee = new OpenLayers.Layer.WMS( "Elbe-Elster",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "ElbeElster",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebviee.events.register('visibilitychanged', wmsoebviee, toggleOEBVI);

    wmsoebvihvl = new OpenLayers.Layer.WMS( "Havelland",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "Havelland",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvihvl.events.register('visibilitychanged', wmsoebvihvl, toggleOEBVI);

    wmsoebvimol = new OpenLayers.Layer.WMS( "Märkisch-Oderland",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "MaerkischOderland",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvimol.events.register('visibilitychanged', wmsoebvimol, toggleOEBVI);

    wmsoebviohv = new OpenLayers.Layer.WMS( "Oberhavel",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "Oberhavel",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebviohv.events.register('visibilitychanged', wmsoebviohv, toggleOEBVI);

    wmsoebviosl = new OpenLayers.Layer.WMS( "Oberspreewald-Lausitz",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "OberspreewaldLausitz",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebviosl.events.register('visibilitychanged', wmsoebviosl, toggleOEBVI);

    wmsoebvilos = new OpenLayers.Layer.WMS( "Oder-Spree",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "OderSpree",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvilos.events.register('visibilitychanged', wmsoebvilos, toggleOEBVI);

    wmsoebviopr = new OpenLayers.Layer.WMS( "Ostprignitz-Ruppin",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "OstprignitzRuppin",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebviopr.events.register('visibilitychanged', wmsoebviopr, toggleOEBVI);

    wmsoebvipm = new OpenLayers.Layer.WMS( "Potsdam-Mittelmark",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "PotsdamMittelmark",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvipm.events.register('visibilitychanged', wmsoebvipm, toggleOEBVI);

    wmsoebvipr = new OpenLayers.Layer.WMS( "Prignitz",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "Prignitz",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvipr.events.register('visibilitychanged', wmsoebvipr, toggleOEBVI);

    wmsoebvispn = new OpenLayers.Layer.WMS( "Spree-Neiße",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "SpreeNeisse",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvispn.events.register('visibilitychanged', wmsoebvispn, toggleOEBVI);

    wmsoebvitf = new OpenLayers.Layer.WMS( "Teltow-Fläming",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "TeltowFlaeming",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvitf.events.register('visibilitychanged', wmsoebvitf, toggleOEBVI);

    wmsoebvium = new OpenLayers.Layer.WMS( "Uckermark",
                                      "http://isk.geobasis-bb.de/ows/oebvi.php",
                                      { layers: "Uckermark",
                                        format: "image/png",
                                        transparent: true
                                        },
                                      { visibility: false,
                                        singleTile: true }
                                     );
    wmsoebvium.events.register('visibilitychanged', wmsoebvium, toggleOEBVI);

     // Highlight Layer
    highlightLayer = new OpenLayers.Layer.Vector("Highlight Layer");
    highlightLayer.displayInLayerSwitcher = false;
    highlightLayer.setVisibility(false);
    highlightLayer.style = highlightStyles;

    zoomToSearch = new OpenLayers.Layer.Vector("ZoomToSearch",
                {isBaseLayer:false, features:[], visibility:false }
    );

    map.addLayers([
        wms, wms_grau, wms_amt, dop20c, dop40g, wms_dtk10, wms_dtk25,
        wms_dtk50, wms_dtk100, wms_vg, wms_nvg, wms_otl, wms_alk, wms_plz, wms_onkz,
        wms_bstk10, wms_bstk25, wms_bstk50, wms_bstk50as,
        wms_fistp, wms_fisniv,
        highlightLayer,wmsoebvi, wmsoebvibrb, wmsoebvic, wmsoebviff,
        wmsoebvip, wmsoebvibar, wmsoebvilds, wmsoebviee, wmsoebvihvl,
        wmsoebvimol, wmsoebviohv, wmsoebviosl, wmsoebvilos, wmsoebviopr,
        wmsoebvipm, wmsoebvipr, wmsoebvispn, wmsoebvitf, wmsoebvium, zoomToSearch
    ]);

    //Soll vorgegebene Geometrie (bei Navigation) als Startextent dienen
    if(startGeom!=null) addGeomToLayer(startGeom);

    //wenn Geometriepunkt übergeben wird - bei Geoadresse)
    var search = window.location.search;
      if (search.indexOf('?')== "0")
         URL_splitten();


    //Wenn kein Startextent vorgegeben ist dann Zoom zu Maxextent
    if (!map.getCenter()) map.zoomToMaxExtent();

    setRegion();  //on startup auch Gebiet initialisiere

    /*
     * my New Control Button
     */
    var toolListeners = {
        "activate": selectControl,
        "deactivate": unselectControl
    };

    var button_koord = new OpenLayers.Control({displayClass: "MyKoordInput", title: "Koordinateneingabe", eventListeners: toolListeners});
    var button_find  = new OpenLayers.Control({displayClass: "MyAdressFinder", title: "Ortssuche", eventListeners: toolListeners});
    var button_hilfe = new OpenLayers.Control({displayClass: "MyHilfe", title: "Hilfe", eventListeners: toolListeners});
    var logo_viewer  = new OpenLayers.Control({displayClass: "Logo", title: "Logo" });
	button_oebvi  = new OpenLayers.Control({displayClass: "MyOebviFinder", title: "ÖbVI-Suche", eventListeners: toolListeners});

    control_panel = new OpenLayers.Control.Panel();
    withOebvi = [
        new OpenLayers.Control.ZoomToMaxExtent({title: "Gesamtansicht"}),
        new OpenLayers.Control.DragPan({title: "Verschieben"}),
        new OpenLayers.Control.ZoomBox({title: "Fensterzoom"}),
        button_koord,
        button_find,
        button_hilfe,
        button_oebvi,
        logo_viewer
    ];
    withoutOebvi = [
        new OpenLayers.Control.ZoomToMaxExtent({title: "Gesamtansicht"}),
        new OpenLayers.Control.DragPan({title: "Verschieben"}),
        new OpenLayers.Control.ZoomBox({title: "Fensterzoom"}),
        button_koord,
        button_find,
        button_hilfe,
        logo_viewer
    ];

    control_panel.addControls(withoutOebvi);
    map.addControl(control_panel);

    initTree();

    // define hover effects
    var controls = {
        'long': new OpenLayers.Control.Hover({
            handlerOptions: {
                'delay': delay
            }
        })
    };
    
    // add hover effects to map and activate them
    var control;
    for(var key in controls) {
        control = controls[key];
        control.key = key;
        map.addControl(control);
        hover_control = control;
    }

    oebviMarker = new OpenLayers.Layer.Markers(
        "ÖbVI Ergebnis",
        {
            displayInLayerSwitcher: false
        }
    );
    map.addLayer(oebviMarker);
}

function getNodeByText(root, text) {
    var retNode;
    root.cascade(function (node) {
        if (node.text == text) {
            retNode = node;
            return false;
        }
    });
    return retNode;
}

function toggleLayerLink (text) {
    var rootnode = tree.getRootNode();
    node = getNodeByText(rootnode, text);

   // just set node checked and zoom to layer if node is NOT disabled
    if (node.attributes.checked == false) {
        tree.setNodeChecked(node);
        var lk = node.id.toUpperCase();
        var layers = fetchOebviLayer();

        for(var i = 0; i < layers.length; i++) {
            var praefix = oebviMapping[layers[i].params.LAYERS];
            
            // only search for OEbVI-layers, other only switch on.
            if(praefix == lk) {
                // This search searches the WFS and filters on basis of the
                // featuretype 'landkreis', which is identical to the given ids in
                // the Ext.tree. URI is currently hardcoded...
                var uri = "http://isk.geobasis-bb.de/ows/oebvi.php";
                uri += "?VERSION="+WFS_VERSION;
                uri += "&SERVICE=WFS";
                uri += "&REQUEST=GetFeature";
                uri += "&TYPENAME=alle";
                uri += "&maxFeatures=100";
                uri += "&FILTER=<Filter><PropertyIsLike wildcard='*' singleChar='.' escape='!'>";
                uri += "<PropertyName>landkreis</PropertyName>";
                uri += "<Literal>" + lk + "</Literal>"; 
                uri += "</PropertyIsLike></Filter>";

                var wfsCall = encodeURI(uri);

                OpenLayers.loadURL(wfsCall, '', this, getLkExtent);
            }
        }
    } 
}



// Callback-Function to zoomTo the boundingBox of the result.
function getLkExtent(response) {

    var format   = new OpenLayers.Format.GML();
    var features = format.read(response.responseText);
//console.log(features);

    if(features.length == 0) {
        return;
    }

    zoomToSearch.destroyFeatures(); // empty first
    zoomToSearch.addFeatures(features);
    map.zoomToExtent(zoomToSearch.getDataExtent());


    _pos = response.responseText.indexOf("TYPENAME=")+9;
    featureType = response.responseText.slice(_pos,response.responseText.indexOf("&", _pos));
    for(var i = 0 ; i < features.length; i++) {
        var feat = features[i];


   // only Hauskoordinaten 
   if(featureType == 'app:Hauskoordinaten' ) {

    for(feat in features) {
        if(features[feat].attributes == null)
            continue;

        var lonlat = features[feat].geometry.clone().getBounds().getCenterLonLat();
    }

    for(var i = 0 ; i < features.length; i++) {
       
        var feat = features[i];
        var markers = new OpenLayers.Layer.Markers( "Markers",{ 
                                             visibility: true } );
        map.addLayer(markers);
        var size = new OpenLayers.Size(20,30);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var icon = new
        OpenLayers.Icon('http://isk.geobasis-bb.de/BrandenburgViewer/open_layers/theme/default/img/point.png',size,offset);
        markers.addMarker(new OpenLayers.Marker(lonlat,icon));
  
        map.addLayers(markers);
    }
  }


/*  // other features
  if(featureType != 'app:Hauskoordinaten') {

    for(feat in features) {
        if(features[feat].attributes == null)
            continue;


  }
*/
 }

}


function initTree() {
    Ext.BLANK_IMAGE_URL = './ext/resources/images/default/s.gif';

    var model = [
    {
    text: "Geobasisdaten",
    expanded: true,
    icon: Ext.BLANK_IMAGE_URL,
    children: [{
        text: "Kartenpräsentation",
        expanded: true,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
            text: "Standard",
            checked: true,
            id: "standard",
            href: "javascript:toggleLayerLink('Standard')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Topographie - Standard"
        },
        {
            text: "Vollton",
            checked: false,
            id: "vollton",
            href: "javascript:toggleLayerLink('Vollton')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Topographie - Vollton"
        },
        {
            text: "Grauton",
            checked: false,
            id: "grauton",
            href: "javascript:toggleLayerLink('Grauton')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Topographie - Grauton"
        }]
    },
    {
        text: "Digitale Orthophotos (Luftbilder)",
        expanded: false,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
            text: "farbig (DOP20c-Bbg.)",
            checked: false,
            id: "farbig",
            href: "javascript:toggleLayerLink('farbig (DOP20c-Bbg.)')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Digitale Orthophotos 20cm"
        },
        {
            text: "grau (DOP40g)",
            checked: false,
            id: "sw",
            href: "javascript:toggleLayerLink('grau (DOP40g)')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Digitale Orthophotos 40cm"
        }]
    },
    {
        text: "Digitale Topographische Karten",
        expanded: false,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
            text: "1 : 10 000",
            checked: false,
            id: "dtk10",
            href: "javascript:toggleLayerLink('1 : 10 000')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "DTK10",
            maxScale: 30000
        },
        {
            text: "1 : 25 000",
            checked: false,
            id: "dtk25",
            href: "javascript:toggleLayerLink('1 : 25 000')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "DTK25",
            minScale: 5000,
            maxScale: 50000
        },
        {
            text: "1 : 50 000",
            checked: false,
            id: "dtk50",
            href: "javascript:toggleLayerLink('1 : 50 000')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "DTK50",
            minScale: 10000
       }]
    },
    {
        text: "Automatisierte Liegenschaftskarte",
        expanded: false,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
            text: "ALK",
            checked: false,
            id: "alk",
            href: "javascript:toggleLayerLink('ALK')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "ALK",
            maxScale: 3000
        }]
    }]
    
    },
    {
    text: "Geofachdaten",
    expanded: true,
    icon: Ext.BLANK_IMAGE_URL,
    children: [{   
        text: "Grenzen",
        expanded: false,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
            text: "Verwaltungsgrenzen",
            checked: false,
            id: "verwaltungsgrenzen",
            href: "javascript:toggleLayerLink('Verwaltungsgrenzen')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Verwaltungsgrenzen"
        },
        {
            text: "Verwaltungsnamen",
            checked: false,
            id: "verwaltungsnamen",
            href: "javascript:toggleLayerLink('Verwaltungsnamen')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Verwaltungsnamen",
            maxScale: 500000
        },
        {
            text: "Ortsteile (inklusive Namen)",
            checked: false,
            id: "otl",
            href: "javascript:toggleLayerLink('Ortsteile (inklusive Namen)')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Ortsteile",
            maxScale: 30000
        },
        {
            text: "Postleitzahlen",
            checked: false,
            id: "postleitzahlen",
            href: "javascript:toggleLayerLink('Postleitzahlen')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Postleitzahlen",
            maxScale: 150000
        },
        {
            text: "Vorwahlnummern",
            checked: false,
            id: "vorwahlnummern",
            href: "javascript:toggleLayerLink('Vorwahlnummern')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "Vorwahlnummern",
            maxScale: 150000
        }]
    },
    {
        text: "Festpunkte des Raumbezugs",
        expanded: false,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
            text: "Lagefestpunkte",
            checked: false,
            id: "tp",
            href: "javascript:toggleLayerLink('Lagefestpunkte')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "FIS TP",
            maxScale: 250000
        },
        {
            text: "Höhenfestpunkte",
            checked: false,
            id: "nivp",
            href: "javascript:toggleLayerLink('Höhenfestpunkte')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "FIS NIV",
            maxScale: 250000
        },
        {
            text: "TK50AS (für Punktkennzeichen)",
            checked: false,
            id: "bstk50as",
            href: "javascript:toggleLayerLink('TK50AS (für Punktkennzeichen)')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "BS TK50AS"
        }]
    },
    {
        text: "Blattschnitte",
        expanded: false,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
            text: "TK10",
            checked: false,
            id: "bstk10",
            href: "javascript:toggleLayerLink('TK10')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "BS TK10"
        },
        {
            text: "TK25",
            checked: false,
            id: "bstk25",
            href: "javascript:toggleLayerLink('TK25')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "BS TK25"
        },
        {
            text: "TK50",
            checked: false,
            id: "bstk50",
            href: "javascript:toggleLayerLink('TK50')",
            icon: Ext.BLANK_IMAGE_URL,
            layerName: "BS TK50"
        }]
    },
    {
        text: "Vermessungsbüros (ÖbVI)",
        expanded: false,
        icon: Ext.BLANK_IMAGE_URL,
        children: [{
           text: "Alle ÖbVI",
           checked: false,
           id: "alle",
           href: "javascript:toggleLayerLink('Alle ÖbVI')",
           icon: Ext.BLANK_IMAGE_URL,
           layerName: "Alle ÖbVI"
        },
        {   
           text: "einzelne Landkreise",
           expanded: false,
           icon: Ext.BLANK_IMAGE_URL,
           children: [{
               
               text: "Brandenburg a.d. Havel",
               checked: false,
               id: "brb",
               href: "javascript:toggleLayerLink('Brandenburg a.d. Havel')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Brandenburg a.d. Havel"
            },
            {
               text: "Cottbus",
               checked: false,
               id: "cb",
               href: "javascript:toggleLayerLink('Cottbus')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Cottbus"
            },
            {
               text: "Frankfurt (Oder)",
               checked: false,
               id: "ff",
               href: "javascript:toggleLayerLink('Frankfurt (Oder)')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Frankfurt (Oder)"
            },
            {
               text: "Potsdam",
               checked: false,
               id: "p",
               href: "javascript:toggleLayerLink('Potsdam')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Potsdam"
            },
            {
               text: "Barnim",
               checked: false,
               id: "bar",
               href: "javascript:toggleLayerLink('Barnim')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Barnim"
            },
            {
               text: "Dahme-Spreewald",
               checked: false,
               id: "lds",
               href: "javascript:toggleLayerLink('Dahme-Spreewald')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Dahme-Spreewald"
            },
            {
               text: "Elbe-Elster",
               checked: false,
               id: "ee",
               href: "javascript:toggleLayerLink('Elbe-Elster')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Elbe-Elster"
            },
            {
               text: "Havelland",
               checked: false,
               id: "hvl",
               href: "javascript:toggleLayerLink('Havelland')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Havelland"
            },
            {
               text: "Märkisch-Oderland",
               checked: false,
               id: "mol",
               href: "javascript:toggleLayerLink('Märkisch-Oderland')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Märkisch-Oderland"
            },
            {
               text: "Oberhavel",
               checked: false,
               id: "ohv",
               href: "javascript:toggleLayerLink('Oberhavel')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Oberhavel"
            },
            {
               text: "Oberspreewald-Lausitz",
               checked: false,
               id: "osl",
               href: "javascript:toggleLayerLink('Oberspreewald-Lausitz')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Oberspreewald-Lausitz"
            },
            {
               text: "Oder-Spree",
               checked: false,
               id: "los",
               href: "javascript:toggleLayerLink('Oder-Spree')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Oder-Spree"
            },
            {
               text: "Ostprignitz-Ruppin",
               checked: false,
               id: "opr",
               href: "javascript:toggleLayerLink('Ostprignitz-Ruppin')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Ostprignitz-Ruppin"
            },
            {
               text: "Potsdam-Mittelmark",
               checked: false,
               id: "pm",
               href: "javascript:toggleLayerLink('Potsdam-Mittelmark')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Potsdam-Mittelmark"
            },
            {
               text: "Prignitz",
               checked: false,
               id: "pr",
               href: "javascript:toggleLayerLink('Prignitz')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Prignitz"
            },
            {
               text: "Spree-Neiße",
               checked: false,
               id: "spn",
               href: "javascript:toggleLayerLink('Spree-Neiße')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Spree-Neiße"
            },
            {
               text: "Teltow-Fläming",
               checked: false,
               id: "tf",
               href: "javascript:toggleLayerLink('Teltow-Fläming')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Teltow-Fläming"
            },
            {
               text: "Uckermark",
               checked: false,
               id: "um",
               href: "javascript:toggleLayerLink('Uckermark')",
               icon: Ext.BLANK_IMAGE_URL,
               layerName: "Uckermark"
           }]
        }]    
    }]
    }];

//    var tree = new mapfish.widgets.LayerTree({
   tree = new mapfish.widgets.LayerTree({
        map: map,
        el:  'tree',
        model: model,
        plugins: [
            mapfish.widgets.LayerTree.createContextualMenuPlugin([
                'opacitySlide'
            ]),
            // Attention: 72.0, because OpenLayers.DOTS_PER_INCH == 72.0
            // Important for calculating the scale
            mapfish.widgets.LayerTree.createDisableLayersPlugin(72.0)
        ]
    });
    tree.render();

    // hack to adjust visibility of layers in layertree depending on minScale
    // and maxScale
    var zoomLevel = map.getZoom();
    map.zoomTo(zoomLevel+1);
    map.zoomTo(zoomLevel);

}

/**
 * Method to switch the layertree on and off.
 * Little tricky: changing the visibility of the layertree's div container 
 * leaves pieces of its content visible. Workaround: Put the container with 
 * the layertree into a DOM element outside the visible range of the screen when
 * closing it.
 */
function switcher() 
{
    // the layertree is invisible and placed initially in the div container 
    // with the id 'place'. When closing the tree, its div container with id
    // 'tree' is moved into div container with id 'my_junk'.
    var my_place  = document.getElementById('place');
    var my_div    = document.getElementById('tree');
    var my_parent = my_div.parentNode;

    var max = OpenLayers.Util.getElement('OpenLayers_MaximizeDiv');

    // initial case at application startup, layertree positioned in a div
    // container over the map but NOT visible
    if (my_div.style.visibility != 'visible') 
    {
        my_div.style.visibility = 'visible';

        // change the open/close buttons for switching the layertree
        max.style.backgroundImage = "url(open_layers/img/button_menu_on.png)";
    }
    // layertree is invisible, placed in a div container outside the visible
    // range of the screen
    else if (my_parent != my_place)
    {
        my_parent.removeChild(my_div);
        my_place.appendChild(my_div);

        // change the open/close buttons for switching the layertree
        max.style.backgroundImage = "url(open_layers/img/button_menu_on.png)";
    }
    // layertree is visible, placed in a div container lying on the map
    else
    {
        var my_junk  = document.getElementById('my_junk');
        my_place.removeChild(my_div);
        my_junk.appendChild(my_div);

        // change the open/close buttons for switching the layertree
        max.style.backgroundImage = "url(open_layers/img/button_menu_off.png)";
    }
}

/**
 * Switch the hover effect showing information about OEbVIs on and off, and add
 * or remove the control button to search for OEbVIs.
 * This method should be called when layer changed. The effect/control should be
 * deactivated if no more OEbVI layer is selected.
 */
function toggleOEBVI() {
    if(hover_control == undefined)
        return;

    var layers = map.layers;
    for(i = 0 ; i < layers.length; i++) {
        var layer = layers[i];

        // continue when layer is activated only
        if(!layer.getVisibility())
            continue;
        
        var url = layer.url;
        
        // if the substring oebvi is not in the url, the layer is not a
        // OEBvI layer
        if(url != undefined && url.search('oebvi') != -1) {
            // enable oebvi search, little ugly, but to keep the button order
            // necessary
            for(var con in withoutOebvi) {
                OpenLayers.Util.removeItem(control_panel.controls, withoutOebvi[con]);
            }
            control_panel.addControls(withOebvi);
            control_panel.redraw();

            // enable hover effect
            hover_control.activate();
            return;
        }
    }
    
    // disable oebvi search, little ugly, but to keep the button order
    // necessary
    for(var con in withOebvi) {
        OpenLayers.Util.removeItem(control_panel.controls, withOebvi[con]);
    }
    control_panel.addControls(withoutOebvi);
    control_panel.redraw();

    // disable hover effect
    hover_control.deactivate();
}

  function URL_splitten(){
  	var url = String(window.location);
  	
  	var teil = url.split("?");
  	var arg = teil[1].split("&");
 	
  	for(i=0;i<arg.length;i++){
  		var a = arg[i].split("=");

            if( (a[0] == 'strasse') || (a[0] == 'ort') || (a[0] == 'plz') ){
             
                if(a[0] == 'strasse'){
                   var strasse = a[1];
                }
                if(a[0] == 'ort'){
                   var ort = a[1];
                }
                if(a[0] == 'plz'){
                   var plz = a[1];
                }

              //var adressfilter = strasse+','+ort+','+plz;
              //Orte_suchen(adressfilter);

             }

                if(a[0] == 'adresse'){
                   var adresse = a[1];
                   adresse = "http://isk.geobasis-bb.de/tmp/"+adresse;
                   OpenLayers.loadURL(adresse, ' ', null, getLkExtent); 
                }
  		if(a[0] == 'x'){
  		   var x = a[1];
  		}
  		if(a[0] == 'y'){
  		   var y = a[1];
                   punkt_anzeigen(x,y);
  		}	


           //  if( (a[0] == 'strasse') || (a[0] == 'ort') || (a[0] == 'plz') ){
           //   var adressfilter = strasse+','+ort+','+plz;
           //   Orte_suchen(adressfilter);
           //  }
  	}

        if( strasse || ort || plz ){
              var adressfilter = strasse+','+ort+','+plz;
              Orte_suchen(adressfilter);
             }

}


function Orte_suchen(adressfilter){

        var gaz_url = "http://isk.geobasis-bb.de/ows/easyToUseGazetteer.php?";

        var gazCall = gaz_url+"Filter="+adressfilter+"&Typename=adresse&srsName=EPSG:325833&maxFeatures=50";
        if(this.xmlHttpRequest) this.xmlHttpRequest.abort();

        //loading();
        this.xmlHttpRequest = OpenLayers.loadURL(gazCall, ' ', null, Suche_erfolgreich, Suche_fehlerhaft);
}

// function loading(){
// 
//         var loading = Ext.get('loading');
//                  var mask = Ext.get('loading-mask');
//                  mask.setOpacity(.2);
//                  mask.shift({
//                                  xy:loading.getXY(),
//                                  width:loading.getWidth(),
//                                  height:loading.getHeight(),
//                                  remove:true,
//                                  duration:1,
//                                  opacity:.3,
//                                  //easing:'bounceOut',
//                                  callback : function(){
//                                  loading.fadeOut({duration:.2,remove:true});
//                                 }
//             });
// 
// }

function Suche_fehlerhaft(request) {
alert("Fehler bei der Verarbeitung");

}

function Suche_erfolgreich(request) {
//alert("alles super");
    var format = new OpenLayers.Format.XML();
    var doc = null;

    if(!request.responseXML.documentElement) {
        doc = format.read(request.responseText);
    } else {
        doc = request.responseXML;
    }

    var featureNodes = format.getElementsByTagNameNS(doc, "", "Feature");
    var resultNodes  = format.getElementsByTagNameNS(doc, "", "SearchResults");
    var responseNodes = format.getElementsByTagNameNS(doc, "", "SearchResponse");

    for(var i=0; i<featureNodes.length; ++i) {
        var featureType = format.getAttributeNS(featureNodes[i],"", "typeName");
        var featureReturned = format.getAttributeNS(resultNodes[i],"", "numberOfRecordsReturned");
        var featureFound = format.getAttributeNS(resultNodes[i],"", "numberOfRecordsMatched");
        var url = format.getAttributeNS(responseNodes[i],"", "url");

        OpenLayers.loadURL(url, ' ', null, getLkExtent);
    }

}



function punkt_anzeigen(x,y){

  var bbox = new OpenLayers.Bounds();
			bbox.left = parseInt(x)-100;
			bbox.right = parseInt(x)+100;
			bbox.top = parseInt(y)-100;
			bbox.bottom = parseInt(y)+100;	
			var koordinaten = bbox.clone();	
  //alert(koordinaten);
  var markers = new OpenLayers.Layer.Markers( "Markers",{ 
                                           visibility: true } );
  
  map.addLayer(markers);
  
  var size = new OpenLayers.Size(20,30);
  var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
  var icon = new OpenLayers.Icon('http://isk.geobasis-bb.de/BrandenburgViewer/open_layers/theme/default/img/point.png',size,offset);
  markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(x,y),icon));
  markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(x,y),icon.clone()));
  
  map.zoomToExtent(koordinaten);	
  //	feature = new OpenLayers.Feature(wms, new OpenLayers.LonLat(3369435,5805064));
  	 //     feature.data.icon = icon.clone();
  //    var marker = feature.createMarker();
//      marker.setOpacity(0.8);
    //  markers.addMarker(marker);
 //   alert(feature);
   //   html += "<a href=\"javascript:zoomToFeature(highlightLayer, '"+features[feat].geometry+"');\" >"
   //  alert(html);
  }


function selectControl(event) {
    element = event.object.displayClass;
    if(element=="MyKoordInput") {
        showKoordinput();
        element = "select";
    }
    else if(element=="MyAdressFinder") {
        showAdressinput();
    }
    else if(element=="MyHilfe") {
        showHilfe();
    }
    else if(element=="MyOebviFinder") {
        showOebviinput();
    }
    for(key in controls) {
        var control = controls[key];
        if(element == key) {
            control.activate();
        }
        else {
            control.deactivate();
        }
    }
}


function unselectControl(event) {
    for(key in controls) {
        var control = controls[key];
        control.deactivate();
    }
}


function onFeatureSelect(feature) {
    var u = Math.pow(10,2);
    var area = feature.geometry.getArea()/1000000;
    area = parseInt(area * u + 0.5) / u;
    var umfang = feature.geometry.getLength()/1000;
    umfang = parseInt(umfang * u + 0.5) / u;
    link_edit = "<a href='javascript:showKoordinput(true)' style='textdecoration:none'>Bearbeiten</a>";
    link_delete = "<a href='javascript:delFeature()' style='textdecoration:none'>Löschen</a>";

    popup = new OpenLayers.Popup.Anchored(
        "chicken",
        feature.geometry.getBounds().getCenterLonLat(),
        new OpenLayers.Size(200,60),
        "<div style='font-size:9px'>Fläche ca.: " + area +" km²<br />Umfang ca.: " + umfang +" km<br /><br />"+link_edit+"&nbsp;&nbsp;"+link_delete+"</div>",
        null, true);

    popup.setBackgroundColor("#FAEBD7");
    popup.setOpacity(0.9);
    popup.setBorder("1px solid");

    feature.popup = popup;
    map.addPopup(popup, true);
}


function onFeatureUnselect(feature) {
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}


function delFeature() {
    if (vectors && vectors.features[0]) {
        if(vectors.features[0].popup)
            onFeatureUnselect(vectors.features[0]);

        vectors.removeFeatures(vectors.features[0]);
    }

    setRegion();
}


/*
 * Show information about OEbVI an in a popup dialog from a http response.
 */
function setHTML(response) {

    var format = new OpenLayers.Format.XML();
    var doc = null;
    if(!response.responseXML.documentElement) {
        doc = format.read(response.responseText);
    } else {
        doc = response.responseXML;
    }

    var layers = fetchOebviLayer();
    var alle = [];

    for(var i = 0; i < layers.length; i++) {
        var praefix = oebviMapping[layers[i].params.LAYERS];
        praefix = praefix == "Alle" ? "alle" : praefix;

        var tag = praefix+"_feature";

        alle = format.getElementsByTagNameNS(doc, "", tag);

        if(alle.length != 0)
            break;
    }  

   if(alle.length == 0) {
       getFeatureInfoCounter--;

        if(getFeatureInfoCounter == 0)
            hover_control.activate();  
       return; 
    }

    var content = "<div style='width: 300px; height:200px; overflow: auto'>";
    content += '<table height="180" width="300"><tr>';

    for(var i = 0; i < alle.length; i++) {
        var vorname_elem = format.getElementsByTagNameNS(doc, "", "vorname");
        var vorname = vorname_elem[i].firstChild.data;

        var nachname_elem = format.getElementsByTagNameNS(doc, "", "nachname");
        var nachname = nachname_elem[i].firstChild.data;

        var strasse_elem = format.getElementsByTagNameNS(doc, "", "strasse");
        var strasse = strasse_elem[i].firstChild.data;

        var plz_elem = format.getElementsByTagNameNS(doc, "", "plz");
        var plz = plz_elem[i].firstChild.data;

        var ort_elem = format.getElementsByTagNameNS(doc, "", "ort");
        var ort = ort_elem[i].firstChild.data;

        var telefon_elem = format.getElementsByTagNameNS(doc, "", "telefon");
        var telefon = telefon_elem[i].firstChild.data;

        var fax_elem = format.getElementsByTagNameNS(doc, "", "fax");
        if(fax_elem && fax_elem[i] && fax_elem[i].firstChild && fax_elem[i].firstChild.data) {
            var fax_text = fax_elem[i].firstChild.data;
        }
        else {
            var fax_text = "Keine Fax-Nr. vorhanden";
        }

           var e_mail_elem = format.getElementsByTagNameNS(doc, "", "e_mail");
        if(e_mail_elem && e_mail_elem[i] && e_mail_elem[i].firstChild && e_mail_elem[i].firstChild.data) {
            var e_mail_text = e_mail_elem[i].firstChild.data;
        }
        else {
            var e_mail_text = "Keine E_Mail vorhanden";
        }

           var homepage_elem = format.getElementsByTagNameNS(doc, "", "homepage");
        if(homepage_elem && homepage_elem[i] && homepage_elem[i].firstChild && homepage_elem[i].firstChild.data) {
            var homepage_url  = homepage_elem[i].firstChild.data;
            var homepage_text = '<a href="'+homepage_url+'" target="_blank">'+homepage_url+'</a>';
        }
        else {
            var homepage_url  = "Keine Homepage vorhanden";
            var homepage_text = '<a href="#">'+homepage_url+'</a>';
        }

        var ostw_elem = format.getElementsByTagNameNS(doc, "", "ostwert");
        var ostw = ostw_elem[i].firstChild.nodeValue;

        var nordw_elem = format.getElementsByTagNameNS(doc, "", "nordwert");
        var nordw = nordw_elem[i].firstChild.nodeValue;

        popup_text  = '<td style="height:170px; width: 300px;"><div style="height:170px; width: 300px;">';
        popup_text += "<b>ÖbVI Dipl.-Ing. "+vorname+" "+nachname+"</b><br><br>";
        popup_text += strasse+ " <br> "+plz+ " "+ort;
        popup_text += "<br><br>Tel: "+telefon;
        popup_text += "<br>Fax: "+fax_text;
        popup_text += "<br><br>"+e_mail_text;
        popup_text += "<br>"+homepage_text+"</div></td>";

        content += popup_text;

    }
    content += "</tr></table></div>";

    OpenLayers.Popup.FramedCloud.OPACITY=0.9;

    mypopup = new OpenLayers.Popup.FramedCloud(
        "OEbVI",
        new OpenLayers.LonLat(ostw,nordw),
        new OpenLayers.Size (300,200),
        content,
        null,
        true,
        function() { getFeatureInfoCounter--; hover_control.activate(); mypopup.destroy(); } 
    );
    mypopup.fixedRelativePosition=true;

    map.addPopup(mypopup);
    mypopup.show();
}

function setRegion() {

  //Funktion ist nur relevant fuer den Geobroker deshalb hier keine weitere Verarbeitung...
  return;
}


function writeLink(response) {
    OpenLayers.Util.getElement('nodeList').innerHTML = response.responseText;
}


function zeigeFlaecheBerechnungsgrundlage(wert) {
    if(map) {
        wposLayer.setVisibility(wert);

        vectors.redraw();
        wposLayer.redraw();
    }
}


function showKoordinput(withGeom) {
    var u = Math.pow(10,0);  //Rundungsparameter = ohne Kommastellen

    //Wenn Vectorlayer gezeichnet wurde dann Geometrie zur Koordinateneingabe einlesen
    if (withGeom && vectors && vectors.features[0] ) {
        liste = new Array();
        polygon = vectors.features[0].geometry+" ";
        polygon = polygon.substring( polygon.indexOf("((")+2, polygon.lastIndexOf("))"));

        xy_paare = polygon.split(",");
        for(i=0;i<xy_paare.length-1;i++) //absichtlich minus 1 da letzter Wert == erster Wert
        {
            xy_value = xy_paare[i].split(" ");
            liste[i] = new Object();
            liste[i]["x"] = parseInt(xy_value[0] * u + 0.5) / u;
            liste[i]["y"] = parseInt(xy_value[1] * u + 0.5) / u;
        }
        atkl_obj.setKoordinaten(liste);
    }

    if(atkl_obj != null) {
        oskl_obj.hide();
        hil_obj.hide();
        oebvi_obj.hide();
        atkl_obj.render();
    }
}

function showAdressinput() {
    if(oskl_obj != null) {
        atkl_obj.hide();
        hil_obj.hide();
        oebvi_obj.hide();
        oskl_obj.render();
    }
}

function showHilfe() {
    if(hil_obj != null) {
        atkl_obj.hide();
        oskl_obj.hide();
        oebvi_obj.hide();
        hil_obj.render();
    }
}

function showOebviinput() {
    if(oebvi_obj != null) {
        atkl_obj.hide();
        oskl_obj.hide();
        hil_obj.hide();
        oebvi_obj.render();
    }
}

function hideWindow(control) {
    if(oskl_obj != null) {
        oskl_obj.hide();
    }
    if(atkl_obj != null) {
        atkl_obj.hide();
    }
    if(hil_obj != null) {
        hil_obj.hide();
    }
    if(oebvi_obj != null) {
      oebvi_obj.hide();
    }
    // Deactivate all controls by default when hiding any window. This
    // should not harm in any cases.
    for(var e=0; e<control_panel.controls.length; ++e) {
        control_panel.controls[e].deactivate();
    }

    return false;
}


function prozessKoordinput() {
    if(atkl_obj != null) {
        liste = atkl_obj.getKoordinaten();

        if(liste == false || liste.length < 1 )
            return;

        else if(liste.length == 2) {
            //mache Rechteck draus!
            var geom = "POLYGON((";
            geom    += liste[0]["x"]+" "+liste[0]["y"]+", ";
            geom    += liste[0]["x"]+" "+liste[1]["y"]+", ";
            geom    += liste[1]["x"]+" "+liste[1]["y"]+", ";
            geom    += liste[1]["x"]+" "+liste[0]["y"]+", ";
            geom    += liste[0]["x"]+" "+liste[0]["y"];
            geom    += "))";
        }

        else {
            var geom = "POLYGON((";
            for(var i=0; i<liste.length; ++i) {
              geom    += liste[i]["x"]+" "+liste[i]["y"]+", ";
            }
            geom    += liste[0]["x"]+" "+liste[0]["y"];  //polygon schliessen
            geom    += "))";
        }

        addGeomToLayer(geom);
    }
}


function addGeomToLayer(geom) {
    features_wkt = new OpenLayers.Format.WKT();

    var features = features_wkt.read(geom);
    var bounds;
    if(features) {
        if(features.constructor != Array) {
            features = [features];
        }
        for(var i=0; i<features.length; ++i) {
            if (!bounds) {
                bounds = features[i].geometry.getBounds();
            }

            else {
                bounds.extend(features[i].geometry.getBounds());
            }

        }
        map.zoomToExtent(bounds);
      //  vectors.addFeatures(features);  //auskommentiert, da kein Vektorlayer benötigt
    }
}

/*
 * Klasse fuer das Handling der Koordinateneingabe und Verarbeitung
 */
function Koordinateneingabe(haupt_containerId, koordinaten_containerId){
    this.id = koordinaten_containerId;
    this.ober_body = document.getElementById(haupt_containerId);
    this.body = document.getElementById(koordinaten_containerId);
    this.ecoLink = document.getElementById("ecolink");
    this.koordinatenZeilenAnzahl = 0;
    this.artikel = new Array();

    if(this.artikel.length==0) {
        this.addInputZeile("k"+this.koordinatenZeilenAnzahl,"","");
        this.addInputZeile("k"+this.koordinatenZeilenAnzahl,"","");
        this.addInputZeile("k"+this.koordinatenZeilenAnzahl,"","");
        this.addInputZeile("k"+this.koordinatenZeilenAnzahl,"","");
    }

    this.win = new Ext.Window({
        contentEl: this.body.id,
        title: 'Koordinateneingabe',
        layout:'fit',
        width:500,
        height:300,
        shadow: false,
        closable: true,
        closeAction: 'hide',
        listeners: {
            hide: function() { hideWindow();}
        },

        buttons: [
        {
            scope: this,
            text: 'Schließen',
            handler: function() { hideWindow() }
        },
        {
            scope: this,
            text: 'Anzeigen',
            handler: function() { prozessKoordinput() }
        }]
    });
}

Koordinateneingabe.prototype.render=function(){
    this.win.show();

    //Linkanpassung
    eingabe = this.getKoordinaten();

    //sind mehr Eingabezeilen erforderlich?
    if(eingabe.length == this.artikel.length) {
        this.addInputZeile("k"+this.koordinatenZeilenAnzahl,"","");
    }
}

Koordinateneingabe.prototype.hide=function(){
    if(this.win.isVisible())
        this.win.hide();
}

Koordinateneingabe.prototype.addInputZeile=function(elemID,x,y){
    if(this.koordinatenZeilenAnzahl < maxPolygonPunktAnzahl-1) {
        var spanElem = document.createElement("div");

        var ostInput  = '<label for="'+elemID+'x">Ostwert:</label>';
        ostInput     += '<input id="'+elemID+'x" type="text" name="'+elemID+'x" size="10" maxlength="7" value="'+x+'"/>';
        var nordInput = '<label for="'+elemID+'y">Nordwert:</label>';
        nordInput    += '<input id="'+elemID+'y" type="text" name="'+elemID+'y" size="10" maxlength="7" value="'+y+'"/>';

        spanElem.id =  elemID;
        spanElem.className = 'lineNormal';
        spanElem.innerHTML = '<img onclick="atkl_obj.delArtikel(\''+elemID+'\')" style="border: 0px solid ;" src="./grafik/loeschen.gif" height="11" width="9" alt"löschen">&nbsp;';
        spanElem.innerHTML += ostInput;
        spanElem.innerHTML += nordInput;
        this.body.appendChild(spanElem);

        var array_laenge = this.artikel.length;
        this.artikel[array_laenge] = new Object();
        this.artikel[array_laenge]["aID"] = elemID;
        this.artikel[array_laenge]["x"] = x;
        this.artikel[array_laenge]["y"] = y;

        this.koordinatenZeilenAnzahl++;
    }
}

Koordinateneingabe.prototype.getKoordinaten=function(){
    var koordinatenliste = new Array();
    for(var index=0; index<this.artikel.length; index++) {

        x_id = this.artikel[index]["aID"]+"x";
        y_id = this.artikel[index]["aID"]+"y";

        if( document.getElementById(x_id).value && document.getElementById(y_id).value) {
            xVal = document.getElementById(x_id).value;
            yVal = document.getElementById(y_id).value;

            //Koordinatenvalidierung
            var chkK = 1;
            if( (xVal < "3230000") || (yVal < "5670000") ||
                (xVal > "3530000") || (yVal > "5950000") )
            {
              alert("Nicht alle Koordinaten liegen innerhalb des Landes Brandenburg!");
              document.getElementById(this.artikel[index]["aID"]).className = 'lineError';
              window.setTimeout("atkl_obj.markiereArtikel('"+this.artikel[index]["aID"]+"', 'lineNormal')", 5000);
              return false;
            }
            if( (xVal.length < "7") || (yVal.length < "7") )
            {
                alert("Bitte geben Sie die Koordinaten 7-stellig an!");
                document.getElementById(this.artikel[index]["aID"]).className = 'lineError';
                window.setTimeout("atkl_obj.markiereArtikel('"+this.artikel[index]["aID"]+"', 'lineNormal')", 5000);
                return false;
            }

            koordinatenliste[index] = new Object();
            koordinatenliste[index]["x"] = xVal;
            koordinatenliste[index]["y"] = yVal;
        }
    }
    return koordinatenliste;
}

Koordinateneingabe.prototype.setKoordinaten=function(koordinatenliste){
    id = new Array();
    if(koordinatenliste.length>1) {
        //vorhandene Eingaben loeschen
        for(var index=0; index<this.artikel.length; index++) {
            id[index] = this.artikel[index]["aID"];
        }
        for(var i=0; i<id.length; i++) {
            atkl_obj.delArtikel(id[i]);
        }

        //neu eintragen
        for(var index=0; index<koordinatenliste.length; index++) {
            this.addInputZeile("k"+this.koordinatenZeilenAnzahl,koordinatenliste[index]["x"],koordinatenliste[index]["y"]);
        }
    }
}

Koordinateneingabe.prototype.markiereArtikel=function(artikelID,stylename){
    if(document.getElementById(artikelID)!=null) {
        document.getElementById(artikelID).className = stylename;
    }
}

Koordinateneingabe.prototype.delArtikel=function(artikelID){
    if(document.getElementById(artikelID)!=null) {
        artikelElem = document.getElementById(artikelID);
        artikelElem.parentNode.removeChild(artikelElem);
        this.koordinatenZeilenAnzahl--;

        //TODO: remove Artikel von arraylist
        var tmpArtikel = new Array().concat(this.artikel);
        this.artikel.length = 0;

        for(var index=0; index<tmpArtikel.length; index++) {
            if(tmpArtikel[index]["aID"] != artikelID) {
                this.artikel[this.artikel.length] = tmpArtikel[index];
            }
        }
    }
}

function MyHilfe (haupt_containerId, hilfe_containerId){
    this.id = hilfe_containerId;
    this.ober_body = document.getElementById(haupt_containerId);
    this.body = document.getElementById(hilfe_containerId);

    this.win = new Ext.Window({
        contentEl: this.body.id,
        title: 'Hilfe',
        layout:'fit',
        width:500,
        height: 300,
        autoScroll: true,
        shadow: false,
        closable: true,
        closeAction: 'hide',
        listeners: {
            hide: function() { hideWindow();}
        },

        buttons: [
        {
            scope: this,
            text: 'Schließen',
            handler: function() { hideWindow(); }
        }]
    });
}

MyHilfe.prototype.render=function(response){
    OpenLayers.loadURL('hilfe_gis.html',' ',this,hil_obj.anzeigen);

    this.win.show();
}


MyHilfe.prototype.hide=function(){
    if(this.win.isVisible())
        this.win.hide();
}

MyHilfe.prototype.anzeigen=function(response){
    var url = response.responseText;
    document.getElementById('hilfetext').innerHTML = url;
}


/*
 * Klasse fuer das Handling der Ortssuche
 */
function Ortssuche(haupt_containerId, koordinaten_containerId){
    this.id = koordinaten_containerId;
    this.body = document.getElementById(haupt_containerId);

    this.gaz_url = "";
    this.srsName = "EPSG:325833";
    this.maxFeature = 50;

    this.textSucheNachAdresse = "Straße, PLZ oder Ort";
    this.textSucheNachKatasteradr = "Gemarkungsname oder Flurkennzeichen";
    this.textSucheNachKarte = "Kartenblattname";
    this.searchBoxElemId = "searchBox";

    this.textBeispielAdressen = "Beispiel: Heinrich-Mann-Allee 103, Potsdam";
    this.textBeispielKataster = "Beispiel: Ahrensfelde oder 121601001";
    this.textBeispielKarte    = "Beispiel: 3550-SW";

    this.seachBoxTyp  = "0";
    this.seachBoxValue = this.textSucheNachAdresse;
    this.minimum_input_length = 3;

    this.xmlHttpRequest = null;

    this.win = new Ext.Window({
        contentEl: this.body.id,
        title: 'Ortssuche',
        layout:'fit',
        width:500,
        height: 300,
        autoScroll: true,
        padding: 10,
        shadow: false,
        closable: true,
        closeAction: 'hide',
        listeners: {
            hide: function() { hideWindow();}
        },

        buttons: [
        {
            scope: this,
            text: 'Schließen',
            handler: function() { hideWindow() ; }
        },
        {
            scope: this,
            text: 'Suchen',
            handler: function() { this.suche() }
        }]
    });
   
}

Ortssuche.prototype.render=function(){
    if(!this.win.isVisible()) {
       this.win.show();
    }
}

Ortssuche.prototype.hide=function(){
    if(this.win.isVisible()) {
        this.win.hide();
    }
}

Ortssuche.prototype.ChangeSearchBoxes=function(_b){
    if(_b.value==this.seachBoxValue){
        _b.value="";
    }
}

Ortssuche.prototype.ChangeBack=function(_e){
    if(_e.value==""){
        _e.value=this.seachBoxValue;
    }
}

Ortssuche.prototype.changeInputElem=function(_v){
    switch(_v){
        case "0":
            document.getElementById("searchBox").style.display = "inline";
            document.getElementById("searchBox").removeAttribute("disabled");
            document.getElementById("searchBox_2").style.display = "none";
            document.getElementById("searchBox_2").setAttribute("disabled","disabled");
            document.getElementById("searchBox_3").style.display = "none";
            document.getElementById("searchBox_3").setAttribute("disabled","disabled");
            this.seachBoxValue = this.textSucheNachAdresse;
            this.searchBoxElemId = "searchBox";

            document.getElementById("beispielText").innerHTML = this.textBeispielAdressen;
            break;
        case "1":
            document.getElementById("searchBox").style.display = "none";
            document.getElementById("searchBox").setAttribute("disabled","disabled");
            document.getElementById("searchBox_2").style.display = "inline";
            document.getElementById("searchBox_2").removeAttribute("disabled");
            document.getElementById("searchBox_3").style.display = "none";
            document.getElementById("searchBox_3").setAttribute("disabled","disabled");
            this.seachBoxValue = this.textSucheNachKatasteradr;
            this.searchBoxElemId = "searchBox_2";

            document.getElementById("beispielText").innerHTML = this.textBeispielKataster;
            break;
        case "2":
            document.getElementById("searchBox").style.display = "none";
            document.getElementById("searchBox").setAttribute("disabled","disabled");
            document.getElementById("searchBox_2").style.display = "none";
            document.getElementById("searchBox_2").setAttribute("disabled","disabled");
            document.getElementById("searchBox_3").style.display = "inline";
            document.getElementById("searchBox_3").removeAttribute("disabled");
            this.seachBoxValue = this.textSucheNachKarte;
            this.searchBoxElemId = "searchBox_3";

            document.getElementById("beispielText").innerHTML = this.textBeispielKarte;
            break;
    }
    this.seachBoxTyp = _v;
}
Ortssuche.prototype.CheckSeachBoxes=function(){
    if(document.getElementById(this.searchBoxElemId).value==this.seachBoxValue){
        return false;
    }
    if(document.getElementById(this.searchBoxElemId).value.length < this.minimum_input_length)
        return false;
    return true;
}

/**
 * Search when Return was pressed within the search window
 */
Ortssuche.prototype.sucheEnter=function(e){
    var keycode;
    if (window.event) { //IE
        keycode = window.event.keyCode;
    } else if (e) { //FF
        keycode = e.which;
    } else {
        return true;
    }
    
    if (keycode == 13) {
       this.suche();
       return false;
    } else {
       return true;
    }
}

Ortssuche.prototype.suche=function(){
    if(this.CheckSeachBoxes()) {

        var filter  = document.getElementById(this.searchBoxElemId).value;
        var gazCall = encodeURI(this.gaz_url+"Filter="+filter+"&Typename="+this.seachBoxTyp+"&srsName="+this.srsName+"&maxFeatures="+this.maxFeature);

        if(this.xmlHttpRequest) this.xmlHttpRequest.abort();

        document.getElementById("orte").style.display = "block";
        document.getElementById("orte").style.backgroundPosition = "50% 20px";
        document.getElementById("orte").style.backgroundImage = 'url("./open_layers/theme/default/img/loading.gif")';
        document.getElementById("orte").innerHTML = '<hr style="width:99%; height:3px;"/>';

        this.xmlHttpRequest = OpenLayers.loadURL(gazCall, ' ', null, loadSuccess, loadFailure);
    }
}

function loadFailure(request) {
    document.getElementById("orte").innerHTML += "Fehler bei der Verarbeitung.";

    //Ladegrafik verstecken
    document.getElementById("orte").style.backgroundImage = "";
}

function loadSuccess(request) {
    var format = new OpenLayers.Format.XML();
    var doc = null;

    if(!request.responseXML.documentElement) {
        doc = format.read(request.responseText);
    } else {
        doc = request.responseXML;
    }

    var featureNodes = format.getElementsByTagNameNS(doc, "", "Feature");
    var resultNodes  = format.getElementsByTagNameNS(doc, "", "SearchResults");
    var responseNodes = format.getElementsByTagNameNS(doc, "", "SearchResponse");

    for(var i=0; i<featureNodes.length; ++i) {
        var featureType = format.getAttributeNS(featureNodes[i],"", "typeName");
        var featureReturned = format.getAttributeNS(resultNodes[i],"", "numberOfRecordsReturned");
        var featureFound = format.getAttributeNS(resultNodes[i],"", "numberOfRecordsMatched");
        var url = format.getAttributeNS(responseNodes[i],"", "url");

        if( featureFound == featureReturned )
          anzahl_string = '<span style="font-size:smaller; color:#808000;">[Anzahl: '+featureReturned+"]</span>";
        else
          anzahl_string = '<span style="font-size:smaller; color:#808000;">[Anzahl: '+featureReturned+" von "+featureFound+"]</span>";

        html =  "<fieldset><legend>" + featureType.replace(/app:|dog:/,"") + " " + anzahl_string + "</legend>";
        html += '<div id="'+featureType+'"><span align="center" style="font-style:italic; color:#808000;">lade '+featureReturned+' von '+featureFound+' Datensätzen</span></div>';
        html += "</fieldset>";
        document.getElementById("orte").innerHTML += html;

        OpenLayers.loadURL(url, ' ', null, parseWfsData);

    }
    if(featureNodes.length == 0)
      document.getElementById("orte").innerHTML += "Leider keine Ergebnisse vorhanden.";

    //Ladegrafik verstecken
    document.getElementById("orte").style.backgroundImage = "";
}


// Funktion Highlight - onmouseover
function zeigeHighlightErgebnis(sichtbar,geometry) {
    features_wkt = new OpenLayers.Format.WKT();
    var features = features_wkt.read(geometry);
    highlightLayer.addFeatures(features);
    highlightLayer.setVisibility(sichtbar);
}

// Funktion Highlight entfernen - onmouseout, destroyFeatures - OpenLayers Funktion
function destroyHighlight(){
    highlightLayer.destroyFeatures();
}

function parseWfsData(req) {
    g =  new OpenLayers.Format.GML();
    html = ""
    features = g.read(req.responseText); //Array(OpenLayers.Feature.Vector)

    _pos = req.responseText.indexOf("TYPENAME=")+9;
    featureType = req.responseText.slice(_pos,req.responseText.indexOf("&", _pos));
    for(var i = 0 ; i < features.length; i++) {
        var feat = features[i];

      // Ortsergaenzung ermitteln
        var ortErgaenzung = "";
        if(feat.attributes["parentIdentifier"])
            ortErgaenzung = " ("+feat.attributes["parentIdentifier"]+")";
        else if(feat.attributes["parentGeographicIdentifier"])
            ortErgaenzung = " ("+feat.attributes["parentGeographicIdentifier"]+")";
        else if(feat.attributes["kreis"] && feat.attributes["kreis"].length > 3)
            ortErgaenzung = " ("+feat.attributes["kreis"]+")";
        else if(feat.attributes["Gemarkungsname"])
            ortErgaenzung = " ("+feat.attributes["Gemarkungsname"]+")";
        else if(feat.attributes["Flurname"])
            ortErgaenzung = " ("+feat.attributes["Flurname"]+")";

        //Bei Hauskoordinaten bitte keine Ergaenzung da Text sonst zu lang!
        if(featureType == 'app:Hauskoordinaten') ortErgaenzung = "";

        //Highlight Layer onmouseover, onmouseout
        html += "<a href=\"javascript:map.zoomToExtent(new OpenLayers.Bounds("+feat.geometry.getBounds().toBBOX()+"));\" style=\"textdecoration:none\" onmouseover='zeigeHighlightErgebnis(1,\""+feat.geometry.clone()+"\")' onmouseout='destroyHighlight()'>"+feat.attributes["geographicIdentifier"]+ortErgaenzung+"</a><br/>";
    }
    document.getElementById(featureType).innerHTML = html;
}


/*
 * Klasse fuer das Handling der Oebvisuche
 */
function Oebvisuche(haupt_containerId, koordinaten_containerId){
    this.id = koordinaten_containerId;
    this.body = document.getElementById(haupt_containerId);

    this.oebvi_url = "";
    this.srsName = "EPSG:4326";
    this.maxFeature = "";

    this.textSuchNachNachname = "Nachname";
    this.textSuchNachLandkreis = "Landkreis";
    this.textSuchNachOrt = "Ortsname";
    this.searchBoxElemId = "searchBox1";

    this.textBeispielNachname = "Beispiel: Schulze";
    this.textBeispielLandkreis = "Beispiel: Potsdam-Mittelmark";
    this.textBeispielOrt    = "Beispiel: Potsdam";

    this.seachBoxTyp  = "1";
    this.seachBoxValue = this.textSuchNachNachname;
    this.minimum_input_length = 1;
    this.searchstr;

    this.xmlHttpRequest = null;
    
    this.win = new Ext.Window({
        contentEl: this.body.id,
        title: 'ÖbVI-Suche',
        layout:'fit',
        width:500,
        autoScroll: true,
        height:300,
        padding: 10,
        shadow: false,
        closable: true,
        closeAction: 'hide',
        listeners: {
            hide: function() { hideWindow();}
        },

        buttons: [
        {
            scope: this,
            text: 'Schließen',
            handler: function() { hideWindow(); }
        },
        {
            scope: this,
            text: 'Suchen',
            handler: function() { this.suche() }
        }]
    });

}

Oebvisuche.prototype.setSearchStr = function(value) {
    this.searchstr = value;
}

Oebvisuche.prototype.getSearchStr = function() {
    return this.searchstr;
}

Oebvisuche.prototype.render=function(){
    if(!this.win.isVisible()) {
       this.win.show();
    }
}

Oebvisuche.prototype.hide=function(){
    if(this.win.isVisible()) {
        this.win.hide();
    }
}

Oebvisuche.prototype.ChangeSearchBoxes=function(_b){
    if(_b.value==this.seachBoxValue){
        _b.value="";
    }
}

Oebvisuche.prototype.ChangeBack=function(_e){
    if(_e.value==""){
        _e.value=this.seachBoxValue;
    }
}

Oebvisuche.prototype.changeInputElem=function(_v){
    switch(_v){
        case "3": // Namenssuche
            document.getElementById("searchBox1").style.display = "inline";
            document.getElementById("searchBox1").removeAttribute("disabled");
            document.getElementById("searchBox2").style.display = "none";
            document.getElementById("searchBox2").setAttribute("disabled","disabled");
            document.getElementById("searchBox3").style.display = "none";
            document.getElementById("searchBox3").setAttribute("disabled","disabled");
            this.seachBoxValue = this.textSuchNachNachname;
            this.searchBoxElemId = "searchBox1";

            document.getElementById("beispielTextOebvi").innerHTML = this.textBeispielNachname;
            break;
        case "4": // Landkreis
            document.getElementById("searchBox1").style.display = "none";
            document.getElementById("searchBox1").setAttribute("disabled","disabled");
            document.getElementById("searchBox2").style.display = "inline";
            document.getElementById("searchBox2").removeAttribute("disabled");
            document.getElementById("searchBox3").style.display = "none";
            document.getElementById("searchBox3").setAttribute("disabled","disabled");
            this.seachBoxValue = this.textSuchNachLandkreis;
            this.searchBoxElemId = "searchBox2";

            document.getElementById("beispielTextOebvi").innerHTML = this.textBeispielLandkreis;
            break;
        case "5": // Ortssuche
            document.getElementById("searchBox1").style.display = "none";
            document.getElementById("searchBox1").setAttribute("disabled","disabled");
            document.getElementById("searchBox2").style.display = "none";
            document.getElementById("searchBox2").setAttribute("disabled","disabled");
            document.getElementById("searchBox3").style.display = "inline";
            document.getElementById("searchBox3").removeAttribute("disabled");
            this.seachBoxValue = this.textSuchNachOrt;
            this.searchBoxElemId = "searchBox3";

            document.getElementById("beispielTextOebvi").innerHTML = this.textBeispielOrt;
            break;
    }
    this.seachBoxTyp = _v;
}

Oebvisuche.prototype.CheckSeachBoxes=function(){
    if(document.getElementById(this.searchBoxElemId).value==this.seachBoxValue){
        return false;
    }
    if(document.getElementById(this.searchBoxElemId).value.length < this.minimum_input_length)
        return false;
    return true;
}

/**
 * Search when Return was pressed within the search window
 */
Oebvisuche.prototype.sucheEnter=function(e){
    var keycode;
    if (window.event) { //IE
        keycode = window.event.keyCode;
    } else if (e) { //FF
        keycode = e.which;
    } else {
        return true;
    }
    
    if (keycode == 13) {
       this.suche();
       return false;
    } else {
       return true;
    }
}

/**
 * Search for OEbVIs on a WFS via filter encoding.
 * We fetch OEbVIs matching the searchstr only, and maximum 100 features.
 */
Oebvisuche.prototype.suche=function(){
    if(this.CheckSeachBoxes()) {
        var id            = this.searchBoxElemId;

        this.setSearchStr(document.getElementById(id).value.replace(/ä/g, "ae"));
        var searchstring = this.getSearchStr();

        searchstring = searchstring.replace(/Ä/g, "ae");
        searchstring = searchstring.replace(/ü/g, "ue");
        searchstring = searchstring.replace(/Ü/g, "ue");
        searchstring = searchstring.replace(/ö/g, "oe");
        searchstring = searchstring.replace(/Ö/g, "oe");
        searchstring = searchstring.replace(/ß/g, "sz");

        searchstring = searchstring.toUpperCase(); 
//        this.setSearchStr(document.getElementById(id).value.toUpperCase());


//alert(searchstring);
        // create Filter as HTTP Get Request
        var uri = this.oebvi_url;
        uri += "?VERSION="+WFS_VERSION;
        uri += "&SERVICE=WFS";
        uri += "&REQUEST=GetFeature";
        uri += "&TYPENAME=alle";
        uri += "&maxFeatures=100";
        uri += "&FILTER=<Filter><PropertyIsLike wildcard='*' singleChar='.' escape='!'>";
        
        var searchcol = "name_norm";
        switch(this.seachBoxTyp){
            case "3": // Namenssuche
                searchcol = "name_norm";
                break;
            case "4": // Landkreis
                searchcol = "lk_norm";
                break;
            case "5": // Ortssuche
                searchcol = "ort_norm";
                break;
        }

        uri += "<PropertyName>"+searchcol+"</PropertyName>";
        uri += "<Literal>" + searchstring + "*</Literal>"; 
        uri += "</PropertyIsLike></Filter>";

        var oebviCall = encodeURI(uri);

        if(this.xmlHttpRequest) this.xmlHttpRequest.abort();

        //Ergebniss Element loeschen und Ladegrafik anzeigen
        document.getElementById("oebvi").style.display = "block";
        document.getElementById("oebvi").style.backgroundPosition = "50% 20px";
        document.getElementById("oebvi").style.backgroundImage = 'url("./open_layers/theme/default/img/loading.gif")';
        document.getElementById("oebvi").innerHTML = '<hr style="width:99%; height:3px;"/>';

        var x = this;
        this.xmlHttpRequest = OpenLayers.loadURL(
            oebviCall, ' ', null, 
            function(request) {
                x.loadOebviSuccess(request, x);
            },
            this.loadOebviFailure);
    }
}

/**
 * An error occured while loading OEbVIs from a WFS.
 * Shows a warning message.
 */
Oebvisuche.prototype.loadOebviFailure=function(request) {
    document.getElementById("oebvi").innerHTML += "Fehler bei der Verarbeitung.";

    //Ladegrafik verstecken
    document.getElementById("oebvi").style.backgroundImage = "";
}

/**
 * Successfully loaded some OEbVI features from a WFS. Add the attributes of all
 * features to the search panel.
 */
Oebvisuche.prototype.loadOebviSuccess=function(response, obj) {
    var str      = obj.getSearchStr();
    var format   = new OpenLayers.Format.GML();
    var features = format.read(response.responseText);

    // no matches, show an information
    if(features.length == 0) {
     //   document.getElementById("oebvi").innerHTML = "Kein ÖbVI mit dem Namen '" + str + "' vorhanden.";
        if(this.seachBoxTyp==3)
        document.getElementById("oebvi").innerHTML = "Kein ÖbVI mit dem Namen '" + str + "' vorhanden.";
        
        if(this.seachBoxTyp==4)
        document.getElementById("oebvi").innerHTML = "Kein Landkreis mit dem Namen '" + str + "' vorhanden.";
        
        if(this.seachBoxTyp==5)
        document.getElementById("oebvi").innerHTML = "Kein Ort mit dem Namen '" + str + "' vorhanden.";
           
 
        document.getElementById("oebvi").style.backgroundImage = "";
        return;
    }

    // add all OEbVIs to the panel
    for(var feat in features) {
        if(features[feat].attributes == null)
            continue;

        var vorname    = features[feat].attributes['vorname'];
        var nachname   = features[feat].attributes['nachname'];
        var strasse    = features[feat].attributes['strasse'];
        var plz        = features[feat].attributes['plz'];
        var ort        = features[feat].attributes['ort'];
        var tele       = features[feat].attributes['tele'];
        var email      = features[feat].attributes['email'];
        var landkreis  = features[feat].attributes['landkreis'];

        var lonlat = features[feat].geometry.clone().getBounds().getCenterLonLat();
        var html_text = "<a href=\"javascript:map.zoomToExtent(new OpenLayers.Bounds("+features[feat].geometry.getBounds().toBBOX()+"));\" style=\"textdecoration:none\" onmouseover='zeigeOebviErgebnis("+lonlat.lon+","+lonlat.lat+")' onmouseout='destroyOebviErgebnis()'>";
        html_text += "<b>ÖbVI Dipl.-Ing. " + vorname + " " + nachname + "</b><br>";
        html_text += "</a>";
        if(strasse != undefined)
            html_text += strasse + "<br>";
        if(plz != undefined)
            html_text += plz + " ";
        if(ort != undefined)
            html_text += ort + "<br>";
        if(tele != undefined)
            html_text += "Tel: " + tele + "<br>";
        if(email != undefined)
            html_text += email + "<br>";
        if(landkreis != undefined)
            html_text += "Landkreis:" + landkreis + "<br>";
        html_text += "<hr>";

        document.getElementById("oebvi").innerHTML += html_text;
        document.getElementById("oebvi").style.backgroundImage = "";
    }

} // End of class Oebvisuche

/**
 * Add a marker to the marker layer at lon/lat
 * Used to show position of OEbVI in the map when moving the mouse cursor over
 * the entry in the OEbVI search.
 */
function zeigeOebviErgebnis(lon, lat) {
    var lonlat = new OpenLayers.LonLat(lon, lat);
    var size = new OpenLayers.Size(21,25);
    calculateOffset = function(size) {
                        return new OpenLayers.Pixel(-(size.w/2), -size.h); };
    var icon = new OpenLayers.Icon(
        './open_layers/img/marker-gold.png',
        size, null, calculateOffset
    );

    oebviMarker.addMarker(
        new OpenLayers.Marker(
            lonlat,
            icon
        )
    );
}

/**
 * Remove all markers from marker layer.
 * Used when the mouse cursor leaves an entry of a OEbVI in the OEbVI search.
 */
function destroyOebviErgebnis(){
    var markers = oebviMarker.markers;
    for(var marker in markers) {
        oebviMarker.removeMarker(markers[marker]);
    }
}


function MyToolTip(elem) {
    this.mytt_timerId = null;
    this.mytt_halten = false;

    var elemId = document.getElementById(elem);

    this.mytt = document.createElement("div");
    this.mytt.className='tooltip';
    elemId.appendChild(this.mytt);
    var txtNode=document.createTextNode("Tooltip wird geladen...");
    this.mytt.appendChild(txtNode);

    this.mytt.onmouseover=function(){tt_obj.mytt_halten = true;};
    this.mytt.onmouseout=function(){tt_obj.mytt_halten = false; tt_obj.hideWithDelayTT(1000);};
}

MyToolTip.prototype.showTT=function(){
    if (this.mytt != null) {
        if(this.mytt.innerHTML != "") {
            this.mytt.style.display = "block";

            this.mytt_timerId = null;
        }
    }
}

MyToolTip.prototype.hideTT=function(){
    if (this.mytt != null && (this.mytt_halten==false)) {
        this.mytt.style.display = "none";
    }
    this.mytt_timerId = null;
}

MyToolTip.prototype.hideWithDelayTT=function(time){
    if (this.mytt != null && this.mytt_timerId == null) {
        this.mytt_timerId = window.setTimeout("tt_obj.hideTT()", time);
    }
}

MyToolTip.prototype.setPos=function(x, y){
    if (this.mytt != null) {
        this.mytt.style.left = (x + 15) + "px";
        this.mytt.style.top  = (y - 10) + "px";
    }
}

MyToolTip.prototype.setText=function(text, append){
    if(append==null) append=false;

    if (this.mytt != null) {
        this.mytt.innerHTML = (append==true?this.mytt.innerHTML+text:text);
    }
}

function tjs_trackMouseEvent( evt ) {
    if( !tjs_ie4 && !tjs_ie5 ) {
        mouseX = parseInt(evt.pageX);
        mouseY = parseInt(evt.pageY);
    }

    else {
        mouseX = parseInt(evt.clientX);
        mouseY = parseInt(evt.clientY);

        if( document.body.scrollLeft ) {
            mouseX += document.body.scrollLeft;
        }
        if( document.body.scrollTop  ) {
            mouseY += document.body.scrollTop;
        }
    }
    return false;
} // End of class MyTooltip
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:

