var google_phys, google_sat, google_hybr, google_str;
var whi_cntr, whi_whi08, whi_whi90,whi_sterb,whi_unter,whi_unterern, wfs_world;

var OL_proj_4326 = new OpenLayers.Projection("EPSG:4326");
var OL_proj_900913 = new OpenLayers.Projection("EPSG:900913");
var lon = 0;
var lat = 3763310.62714465;
var zoom = 2;
var extent = new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34);


function setBase(layer)
{
    if (NABU.MAP.setBaseLayer(layer) === false) 
    {
        NABU.MAP.setBaseLayer(layer);
        layer.redraw(true);
        return true;
    }
    else 
    {
        //NABU.MAP.setBaseLayer(layer) == false;
        NABU.MAP.setBaseLayer(layer);
    }
}

function setLayer(layer, ignore_dependency)
{
    var _ignore_dependency = ignore_dependency || false;
    
    var closeLayers = new Array (whi_whi08,whi_whi90);
    for (a=0;a<closeLayers.length;a++) {
     if (closeLayers[a] !== layer) {
      closeLayers[a].setVisibility(false);
      jQuery('#' +closeLayers[a].tree_id).attr('checked', '');
      jQuery('#leg_' +closeLayers[a].tree_id).hide();
     }
    }
    
        if (layer.tree_id && layer.tree_id !== '') 
        {
            if (layer.getVisibility()) 
            {
                jQuery('#' + layer.tree_id).attr('checked', '');
		jQuery('#leg_' + layer.tree_id).hide();
            }
            else 
            {
                jQuery('#' + layer.tree_id).attr('checked', 'checked');
		jQuery('#leg_' + layer.tree_id).show();
            }
        }
        if (layer.getVisibility() === false) 
        {
            layer.setVisibility(true);
        }
        else 
        {
            layer.setVisibility(false);
        }
        if (!_ignore_dependency && layer.dependent_layer_names && (layer.dependent_layer_names).constructor === Array) 
        {
            jQuery.each(layer.dependent_layer_names, function(i, n)
            {
                setLayer(window[n]);
            });
        }
}

function showClass(alayer,tlayer,low,gre) {
  alayer.mergeNewParams(
   {
    'lowt' : low,
    'gret' : gre,
    'layers': tlayer
   });
}

/**
 * -------------------------------------------------------------------
 * feature_info_hover
 * function to hover a feature open a new pop up window and destroy
 * it after 3000 milliseconds
 *
 * @feature
 * -------------------------------------------------------------------
*/ 
function feature_info_hover(feature, myWfsLayer)
{
    if (this.popup && NABU.MAP && NABU.MAP.popups && NABU.MAP.popups.length > 0) 
    {
        window.clearTimeout(this.autodestroy);
        this.popup.destroy();
        this.popup = null;
    }
    //*
    var myFeature = myWfsLayer.getFeatureById(feature.id);
    
    if (myFeature) 
    {
    
        var window_position = new OpenLayers.LonLat(myFeature.data.cx, myFeature.data.cy);

        this.popup = new OpenLayers.Popup("ol-info-popup", window_position, null, '<div class="map-kurzinfo-popup"><span onclick="javascript:askInfo(\'' + myFeature.data.cx + '\',\'' + myFeature.data.cy + '\')" style="cursor:pointer;">' + myFeature.data.land + '</span>', false);
        this.popup.autoSize = true;
        NABU.MAP.addPopup(this.popup, true);
        this.autodestroy = window.setTimeout(function()
        {
            if (NABU.MAP && NABU.MAP.popups && NABU.MAP.popups.length > 0) 
            {
                var len = NABU.MAP.popups.length;
                for (var i = 0; i < len; i++) 
                {
                    if (NABU.MAP.popups[i] && NABU.MAP.popups[i].destroy) 
                    {
                        NABU.MAP.popups[i].destroy();
                    }
                }
            }
        }, 3000);
    }
}


    function setHTML(response) {
       jQuery.unblockUI();
       if (response.responseText && response.responseText != '') {
         jQuery('#info_result').html(response.responseText);
         jQuery('#feature-info-container').dialog('open');
      } else {
         jQuery('#info_result').html(response);
         jQuery('#feature-info-container').dialog('open');      
      }
   }


    function setWHI() {    
         jQuery('#info_result').html("<table><tr><td><b>Welthunger-Index</b><br>Der <b>Welthunger-Index</b> misst die Situation von Hunger und Unterern&auml;hrung in &uuml;ber 80 L&auml;ndern weltweit. Er basiert auf <b>drei Indikatoren</b>: Der <b>Kindersterblichkeit</b> unter f&uuml;nf Jahren, der Rate <b>untergewichtiger Kinder</b> unter f&uuml;nf Jahren und dem Anteil der <b>Unterern&auml;hrten</b> in der Bev&ouml;lkerung. Das International Food Policy Research Institute (IFPRI) gibt den Index in Zusammenarbeit mit der Welthungerhilfe und Concern Worldwide heraus. </td></tr><tr><td><a href='http://www.welthungerhilfe.de/whi2008-uebersicht.html' target='_empty'>->Mehr zum Thema</a></td></tr></table>");
         jQuery('#feature-info-container').dialog('open');
  }
    function handleMeasurements(event) {
            var geometry = event.geometry;
            var units = event.units;
            var order = event.order;
            var measure = event.measure;
            var out = "";
            if(order == 1) {
	        out += "Strecke: ";
                out += " " + measure.toFixed(3) + " " + units;
		//out += " " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
            } else {
	        out += "Fl&auml;che: ";
		out += " " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";	     
	    }
	    
            jQuery('#measure_result').html(out);
     }

/**
 *  Feature Info
 */
OpenLayers.Control.FeatureInfoClick = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
        'single': true,
        'double': false,
        'pixelTolerance': 3,
        'stopSingle': false,
        'stopDouble': false
    },
    
    initialize: function(options)

    {
        this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.handler = new OpenLayers.Handler.Click(this, {
            'click': this.trigger
        }, this.handlerOptions);
    },
    
    //whi_whi08,whi_sterb,whi_unter,whi_unterern
    trigger: function(e)
    {
            var url =  whi_whi08.getFullRequestString({
                            REQUEST: "GetFeatureInfo",
                            EXCEPTIONS: "application/vnd.ogc.se_xml",
                            BBOX: whi_whi08.map.getExtent().toBBOX(),
                            X: e.xy.x,
                            Y: e.xy.y,
                            INFO_FORMAT: 'text/html',
                            QUERY_LAYERS: whi_whi08.params.LAYERS + "," + whi_whi90.params.LAYERS,
                            WIDTH: whi_whi08.map.size.w,
                            HEIGHT: whi_whi08.map.size.h});
			    jQuery.blockUI( { message: "<div style='z-index:9999999999999999;'><img src='./images/spinner.gif' /><br><span class='header'><h2>Daten werden geladen</h2></span><br><span class='smalltext'>Bitte haben Sie einen Moment Geduld</span><div>" } );
            OpenLayers.loadURL(url, '', this, setHTML);
            
            //OpenLayers.Event.stop(e);
    }
});


/*

*/

function askInfo(x,y) {

var xxyy = new OpenLayers.LonLat(x,y);
var px = NABU.MAP.getPixelFromLonLat(xxyy).x;
var py = NABU.MAP.getPixelFromLonLat(xxyy).y;

var url =  whi_whi08.getFullRequestString({
                            REQUEST: "GetFeatureInfo",
                            EXCEPTIONS: "application/vnd.ogc.se_xml",
                            BBOX: whi_whi08.map.getExtent().toBBOX(),
                            X: px,
                            Y: py,
                            INFO_FORMAT: 'text/html',
                            QUERY_LAYERS: whi_whi08.params.LAYERS + "," + whi_whi90.params.LAYERS,
                            WIDTH: whi_whi08.map.size.w,
                            HEIGHT: whi_whi08.map.size.h});
	    //jQuery.blockUI( { message: "<img src='./images/spinner.gif' /><br><span class='header'><h2>Daten werden geladen</h2></span><br><span class='smalltext'>Bitte haben Sie einen Moment Geduld</span>" } );
            jQuery.blockUI( { message: "<div style='z-index:9999999999999999;'><img src='./images/spinner.gif' /><br><span class='header'><h2>Daten werden geladen</h2></span><br><span class='smalltext'>Bitte haben Sie einen Moment Geduld</span><div>" } );
            OpenLayers.loadURL(url, '', this, setHTML);
}

/**
 *  SetCenterClick
 */
OpenLayers.Control.SetCenterClick = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions: {
        'single': true,
        'double': false,
        'pixelTolerance': 0,
        'stopSingle': false,
        'stopDouble': false
    },
    
    initialize: function(options)
    {
        this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.handler = new OpenLayers.Handler.Click(this, {
            'click': this.trigger
        }, this.handlerOptions);
    },
    
    trigger: function(e)
    {
        var lonlat      = this.map.getLonLatFromViewPortPx(e.xy);
	var actZoom = this.map.getZoom();
	 this.map.setCenter(new OpenLayers.LonLat(lonlat.lon, lonlat.lat), actZoom);
    }
});

/**
 * -------------------------------------------------------------------
 * initialize_openLayers
 *
 * main openLayers function
 *
 * -------------------------------------------------------------------
 */
function initialize_openLayers()
{
    var options = {
        controls: [],
        projection: OL_proj_900913,
        // displayProjection: OL_proj_4326,
        units: "m",
        numZoomLevels: 12,
        maxResolution: "auto",
        minResolution: "auto",
	restrictedExtent: extent,
        maxExtent: extent,
        minExtent: extent,
	'tileSize': new OpenLayers.Size(800,800)
    };
    NABU.MAP = new OpenLayers.Map('map', options);
    
    google_phys = new OpenLayers.Layer.Google("Google Gel&auml;ndekarte", {
        type: G_PHYSICAL_MAP,
        'minZoomLevel': 0,
        'maxZoomLevel': 19,
        'sphericalMercator': true
    }, {
        //'units': 'm',
        tree_id: 'base_layer_google_phys'
    });
    
    google_sat = new OpenLayers.Layer.Google("Google Satellite", {
        type: G_SATELLITE_MAP,
        'minZoomLevel': 0,
        'maxZoomLevel': 19,
        'sphericalMercator': true
    }, {
        //'units': 'm',
        tree_id: 'base_layer_google_sat'
    });
    
    google_hybr = new OpenLayers.Layer.Google("Google Hybrid", {
        type: G_HYBRID_MAP,
        'minZoomLevel': 1,
        'maxZoomLevel': 19,
        'sphericalMercator': true
    }, {
        //'units': 'm',
        tree_id: 'base_layer_google_hybr'
    });
    
    google_str = new OpenLayers.Layer.Google("Google Street", {
        type: G_NORMAL_MAP,
        'minZoomLevel': 1,
        'maxZoomLevel': 19,
        'sphericalMercator': true
    }, {
        //'units': 'm',
        tree_id: 'base_layer_google_str'
    });

    
   NABU.MAP.addLayers([google_phys, google_hybr, google_str, google_sat]);
  
  
  
    whi_cntr = new OpenLayers.Layer.WMS("World", "http://www.webmapcenter.de/cgi-bin/mapserv?map=/var/data/www.webmapcenter.de/whi2009/mapfiles/whi.map", {
        layers: 'whi_cntr',
        transparent: 'true',
        format: 'image/png'
    }, {
        /* singleTile: 'FALSE', */
	gutter : 30,
	buffer: 1,
        projection: 'EPSG:900913',
        units: 'm',
        tree_id: 'whi_cntr'
    });
    
   NABU.MAP.addLayer(whi_cntr);

/*
    whi_unterern = new OpenLayers.Layer.WMS("Proteste", "http://www.webmapcenter.de/cgi-bin/mapserv?map=/var/data/www.webmapcenter.de/whi2009/mapfiles/whi.map", {
        layers: 'whi_protest',
        transparent: 'true',
        format: 'image/png'
    }, {
	gutter : 30,
	buffer: 1,
        projection: 'EPSG:900913',
        units: 'm',
        tree_id: 'whi_unterern'
    });
    
   NABU.MAP.addLayer(whi_unterern);
*/
/*
   whi_unter = new OpenLayers.Layer.WMS("Einkommen", "http://www.webmapcenter.de/cgi-bin/mapserv?map=/var/data/www.webmapcenter.de/whi2009/mapfiles/whi.map", {
        layers: 'whi_income',
        transparent: 'true',
        format: 'image/png'
    }, {
	gutter : 30,
	buffer: 1,
        projection: 'EPSG:900913',
        units: 'm',
        tree_id: 'whi_unter'
    });
   NABU.MAP.addLayer(whi_unter);
  */
/*
   whi_sterb = new OpenLayers.Layer.WMS("Getreide Netto", "http://www.webmapcenter.de/cgi-bin/mapserv?map=/var/data/www.webmapcenter.de/whi2009/mapfiles/whi.map", {
        layers: 'whi_getreide',
        transparent: 'true',
        format: 'image/png'
    }, {
	gutter : 30,
	buffer: 1,
        projection: 'EPSG:900913',
        units: 'm',
        tree_id: 'whi_sterb'
    });
   NABU.MAP.addLayer(whi_sterb);

*/     

 wfs_world = new OpenLayers.Layer.WFS("World","http://www.webmapcenter.de/geoserver/wfs", {
      typename: 'world_r'
    }, {
      projection: new OpenLayers.Projection("EPSG:900913"),
      typename: "world_r",
           styleMap: new OpenLayers.StyleMap({
 	    fillColor: "#ffcc66",
            pointRadius: 6,
            fillOpacity: 0.0
        }),
      extractAttributes: true
  });
  NABU.MAP.addLayer(wfs_world);


    whi_whi08 = new OpenLayers.Layer.WMS("WHI08", "http://www.webmapcenter.de/cgi-bin/mapserv?map=/var/data/www.webmapcenter.de/whi2009/mapfiles/whi.map", {
        layers: 'whi_whi08',
        transparent: 'true',
        format: 'image/png'
    }, {
	gutter : 30,
	buffer: 1,
        projection: 'EPSG:900913',
        units: 'm',
        tree_id: 'whi_whi08'
    });

   NABU.MAP.addLayer(whi_whi08);
   

    whi_whi90 = new OpenLayers.Layer.WMS("WHI08", "http://www.webmapcenter.de/cgi-bin/mapserv?map=/var/data/www.webmapcenter.de/whi2009/mapfiles/whi.map", {
        layers: 'whi_whi90',
        transparent: 'true',
        format: 'image/png'
    }, {
	gutter : 30,
	buffer: 1,
        projection: 'EPSG:900913',
        units: 'm',
        tree_id: 'whi_whi90'
    });
    
   NABU.MAP.addLayer(whi_whi90);
    
   whi_cntr.setVisibility(false);
   //whi_sterb.setVisibility(false);
   //whi_unterern.setVisibility(false);
   //whi_unter.setVisibility(false);
   whi_whi08.setVisibility(true);
   whi_whi90.setVisibility(false);
   jQuery('#leg_whi_whi90').hide();
/**
     * generated with http://www.webmapcenter.de/olstyle/generator.php
     */
    var nabuStyleObject = new OpenLayers.StyleMap({
        "default": new OpenLayers.Style({
            strokeColor: '#40494F',
            strokeWidth: 3,
            strokeOpacity: 1,
            fillColor: '#1C76BC',
            fillOpacity: 0.8,
            pointRadius: 6
        }),
        "select": new OpenLayers.Style({
            fillColor: "#66ccff",
            strokeColor: "#3399ff"
        }),
        "hover": new OpenLayers.Style({
            fillColor: "#66ccff",
            strokeColor: "#3399ff"
        })
    });
    
    
    /**
     * -------------------------------------------------------------------
     * layer for the transactional wfs-t
     *
     * points, lines and polygons
     * -------------------------------------------------------------------
     */
    
      //** HOVER CONTROL **//
  hoverCtrl =  new OpenLayers.Control.SelectFeature(
                  wfs_world, 
                 {callbacks: {'over': function(){ feature_info_hover(arguments[0],wfs_world) }}}
  );
  NABU.MAP.addControl(hoverCtrl);
  hoverCtrl.activate();

    scaleline = new OpenLayers.Control.ScaleLine({
        displaySystem: "metric",
        minWidth: 100,
        maxWidth: 200,
        divisions: 4,
        subdivisions: 4,
        align: "center"
    });
    NABU.MAP.addControl(new OpenLayers.Control.PanZoomBar());
   /* NABU.MAP.addControl(new OpenLayers.Control.LayerSwitcher({
        'ascending': false
    }));
    */
    NABU.CTRL.DEFAULT = new OpenLayers.Control.MouseDefaults();
    NABU.MAP.addControl(NABU.CTRL.DEFAULT);
    NABU.CTRL.DEFAULT.deactivate();
    
    NABU.MAP.addControl(scaleline);
    
    
    NABU.MAP.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
    
    
    NABU.CTRL.ZOOM_BOX = new OpenLayers.Control.ZoomBox();
    NABU.MAP.addControl(NABU.CTRL.ZOOM_BOX);
    NABU.CTRL.ZOOM_BOX.deactivate();
    
    NABU.CTRL.SET_CENTER = new OpenLayers.Control.ZoomBox();
    NABU.MAP.addControl(NABU.CTRL.SET_CENTER);
    NABU.CTRL.SET_CENTER.deactivate();
    
    NABU.PERMALINK = new OpenLayers.Control.Permalink('map-permalink');
    NABU.MAP.addControl(NABU.PERMALINK);
    
    NABU.MOUSE_POSITION = new OpenLayers.Control.MousePosition();
    NABU.MAP.addControl(NABU.MOUSE_POSITION);
    

    /**
     * -------------------------------------------------------------------
     * define digit-button funciontallity
     * -------------------------------------------------------------------
     */
    
    //Feature-Info
    NABU.CTRL.GET_FI = new OpenLayers.Control.FeatureInfoClick();
    NABU.MAP.addControl(NABU.CTRL.GET_FI);
    NABU.CTRL.GET_FI.activate();


    //Measure
    NABU.CTRL.MEASURE = new OpenLayers.Control.Measure(OpenLayers.Handler.Path, options);
    NABU.CTRL.MEASURE.events.on({
                    "measure": handleMeasurements,
                    "measurepartial": handleMeasurements
     });
    NABU.MAP.addControl(NABU.CTRL.MEASURE);
    NABU.CTRL.MEASURE.deactivate();
    
 
    //SetCenterClick
    NABU.CTRL.SET_CENTER = new OpenLayers.Control.SetCenterClick();
    NABU.MAP.addControl(NABU.CTRL.SET_CENTER);
}