var map, layer;
if( !tick ) { 
    var tick = function(){};
}
function windowSize() {
    var size = {width: 0, height: 0};
    if (window.innerWidth && window.innerHeight) {
        size.width = window.innerWidth;
        size.height = window.innerHeight;
    } else if (document.documentElement.clientWidth > 0){
        size.width = document.documentElement.clientWidth;
        size.height = document.documentElement.clientHeight;
    } else {
        size.width = document.body.offsetWidth;
        size.height = document.body.offsetHeight;
    }
    return size;
}

function resizeMap() {
    var map_el = document.getElementById('map');
    size = windowSize();
    
    map_el.style.width = size.width - 24 + "px";
    map_el.style.height = size.height - 110 + "px";
}

function resizeAndUpdateMap() {
    resizeMap();
    if (typeof(map) != "undefined") {
        map.updateSize();
    }
}

function init_demo() {
    resizeMap();
    init_map();
    OpenLayers.Event.observe(window, 'resize',
                  function () {resizeAndUpdateMap();});
}

function init_map(){
    var options = {
                  projection: new OpenLayers.Projection("EPSG:900913"),
                  units: "m",
                  maxResolution: 156543.0339,
                  restrictedExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34,
                                                     20037508.34, 20037508.34),
                  maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34,
                                                   20037508.34, 20037508.34),
                  numZoomLevels: 19,
                  controls: [],
                  displayProjection: new OpenLayers.Projection("EPSG:4326")
              };
    
    
    var lon = 9.59884;
    var lat = 51.1495;
    var zoom = 6;
    
    var tms_hosts = ["http://a.osm.omniscale.net/proxy/tiles/",
                     "http://b.osm.omniscale.net/proxy/tiles/",
                     "http://c.osm.omniscale.net/proxy/tiles/",
                     "http://d.osm.omniscale.net/proxy/tiles/"];
    var osm_copyright = '&copy; 2010 <a href="http://omniscale.de">Omniscale</a>, '
                        + 'Map Data: <a href="http://openstreetmap.org">OpenStreetMap</a> Contributors, '
                        + 'License: <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-SA-BY</a>';

    map = new OpenLayers.Map( 'map', options );
    var google = new OpenLayers.Layer.Google( "Google & OpenStreetMap", { type: G_SATELLITE_MAP,
            "sphericalMercator": true} );
    var osm_tms = new OpenLayers.Layer.TMS( "OpenStreetMap (TMS)", tms_hosts,
            {layername: 'osm_EPSG900913', type:'png', buffer:1,
             attribution: osm_copyright});
    var osm_wms = new OpenLayers.Layer.WMS("OpenStreetMap (WMS)",
            ["http://osm.omniscale.net/proxy/service?"],
            {layers: 'osm', format: 'image/png', "sphericalMercator": true}, {singleTile: true, ratio: 1});
    var osm_roads_tms = new OpenLayers.Layer.TMS( "OpenStreetMap Straßen (TMS)", tms_hosts,
               {layername: 'osm_roads_EPSG900913', type:'png', isBaseLayer: false, 
                buffer: 1, visibility: false, displayInLayerSwitcher: false,
                attribution: "<span class='inverse'>" + osm_copyright + "</span>"});
 
 
    OpenLayers.Control.LayerSwitcher.prototype.onInputClick = function(e) {
         if (!this.inputElem.disabled) {
             this.layer.map.layers[3].setVisibility(false);
             this.layer.map.setBaseLayer(this.layer);
             if (this.layer.CLASS_NAME == 'OpenLayers.Layer.Google') {
                 this.layer.map.layers[3].setVisibility(true);
                 $('.terms-of-use-link').css('display', 'inline');
             }
         }
        OpenLayers.Event.stop(e);
    },
    
    OpenLayers.Control.LayerSwitcher.prototype.maximizeControl =  function(e) {

        this.div.style.width = "40em";
        this.div.style.height = "";

        if (e != null) {
            OpenLayers.Event.stop(e);                                            
        }
    },

    OpenLayers.Control.LayerSwitcher.prototype.redraw = function() {
        //if the state hasn't changed since last redraw, no need 
        // to do anything. Just return the existing div.
        if (!this.checkRedraw()) { 
            return this.div; 
        } 
        //clear out previous layers 
        this.clearLayersArray("base");
        this.clearLayersArray("data");
        
        var containsOverlays = false;
        var containsBaseLayers = false;
        var len = this.map.layers.length;
        this.layerStates = new Array(len);
        for (var i=0; i <len; i++) {
            var layer = this.map.layers[i];
            this.layerStates[i] = {
                'name': layer.name, 
                'visibility': layer.visibility,
                'inRange': layer.inRange,
                'id': layer.id
            };
        }    

        var layers = this.map.layers.slice();
        if (!this.ascending) { layers.reverse(); }
        for(var i=0, len=layers.length; i<len; i++) {
            var layer = layers[i];
            var baseLayer = layer.isBaseLayer;
            
            if (layer.displayInLayerSwitcher) {

                if (baseLayer) {
                    containsBaseLayers = true;
                } else {
                    containsOverlays = true;
                }    

                // only check a baselayer if it is *the* baselayer, check data
                //  layers if they are visible
                var checked = (baseLayer) ? (layer == this.map.baseLayer)
                                          : layer.getVisibility();
                                    
                // create input element
                var inputElem = document.createElement("span");
                inputElem.id = this.id + "_input_" + layer.name;
                inputElem.name = layer.name;
                inputElem.value = layer.name;
                inputElem.innerHTML = layer.name;
                inputElem.style.paddingTop = "3px";
                inputElem.style.paddingBottom = "3px";
                inputElem.style.paddingLeft = "6px";
                inputElem.style.paddingRight = "6px";
                inputElem.style.marginRight = "8px";
                inputElem.style.color = "white";
                inputElem.style.backgroundColor = this.activeColor;   
                inputElem.style.cursor = "pointer";     
                
                if (checked == true) {
                    inputElem.style.color = "#F4B032";
                }                
                
                var context = {
                    'inputElem': inputElem,
                    'layer': layer,
                    'layerSwitcher': this
                };

                OpenLayers.Event.observe(inputElem, "click", 
                      OpenLayers.Function.bindAsEventListener(this.onInputClick,
                                                              context)
                 );
                 var groupDiv = (baseLayer) ? this.baseLayersDiv
                                           : this.dataLayersDiv;
                 groupDiv.appendChild(inputElem);
            }
        }
        return this.div;
    },
    
    OpenLayers.Control.LayerSwitcher.prototype.showControls =  function(minimize) {},
    
    OpenLayers.Control.LayerSwitcher.prototype.loadContents =  function() {
           //configure main div
           this.div.style.position = "absolute";
           this.div.style.top = "5px";
           this.div.style.right = "0px";
           this.div.style.left = "";
           this.div.style.fontFamily = "sans-serif";
           this.div.style.fontWeight = "bold";
           this.div.style.marginTop = "3px";
           this.div.style.marginLeft = "3px";
           this.div.style.marginBottom = "3px";
           this.div.style.fontSize = "0.7em";   
           this.div.style.color = "black"; 
           this.div.style.backgroundColor = "transparent";

           OpenLayers.Event.observe(this.div, "mouseup", 
               OpenLayers.Function.bindAsEventListener(this.mouseUp, this));
           OpenLayers.Event.observe(this.div, "click",
                         this.ignoreEvent);
           OpenLayers.Event.observe(this.div, "mousedown",
               OpenLayers.Function.bindAsEventListener(this.mouseDown, this));
           OpenLayers.Event.observe(this.div, "dblclick", this.ignoreEvent);

           // layers list div        
           this.layersDiv = document.createElement("div");
           this.layersDiv.id = this.id + "_layersDiv";
           // this.layersDiv.style.paddingTop = "5px";
           this.baseLayersDiv = document.createElement("div");
           this.dataLayersDiv = document.createElement("div");
           this.layersDiv.appendChild(this.dataLayersDiv);
           this.layersDiv.appendChild(this.baseLayersDiv);
           this.div.appendChild(this.layersDiv);
           this.maximizeControl();
    };
    
    OpenLayers.Control.LayerSwitcher.prototype.draw  = function() {
        OpenLayers.Control.prototype.draw.apply(this);

        // create layout divs
        this.loadContents();

        // populate div with current info
        this.redraw();    

        return this.div;
    },
    
    OpenLayers.Control.PanZoomBar.prototype.draw = function(px) {
        OpenLayers.Control.prototype.draw.apply(this, arguments);
        px = this.position.clone();
        this.buttons = [];
        var sz = new OpenLayers.Size(18,18);
        var centered = new OpenLayers.Pixel(px.x+sz.w/2, px.y);
        var wposition = sz.w;
        px.y = centered.y+sz.h;
        this._addButton("zoomin", "zoom-plus-mini.png", centered.add(0,sz.h-15), sz);
        centered = this._addZoomBar(centered.add(0, sz.h+3));
        this._addButton("zoomout", "zoom-minus-mini.png", centered, sz);
        return this.div;
    }    
    
    map.addLayer(osm_tms);
    map.addLayer(osm_wms);
    map.addLayer(google);
    map.addLayer(osm_roads_tms);
    // map.addLayer(osm_roads_wms);
    // 
    map.addControl(new OpenLayers.Control.Navigation());
    map.addControl(new OpenLayers.Control.PanZoomBar());
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.Attribution(
      {div: OpenLayers.Util.getElement('attribution')}));
    map.addControl(new OpenLayers.Control.Permalink('permalink'));
    
    if (!map.getCenter()) {
      var lonlat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
      map.setCenter(lonlat, zoom);
    }
}
