Eniro.Layer.Themes = OpenLayers.Class(OpenLayers.Layer.TMS, {

    type: 'png',

    isBaseLayer: false,

    metaTileSize: 3,

    alpha: true,

    buffer: 0,

    namespace: 'eniro',

    backendProjection: new OpenLayers.Projection('EPSG:4326'),

    initialize: function () {
	    OpenLayers.Layer.TMS.prototype.initialize.apply(this, arguments);
    },
    
    getBBOX: function (xy, range) {
		var map = this.map;
	    var llMin = map.getLonLatFromPixel(new OpenLayers.Pixel(xy.x-range, xy.y-range));
        var llMax = map.getLonLatFromPixel(new OpenLayers.Pixel(xy.x+range, xy.y+range));

        var mapProjection = map.getProjectionObject();
		
        llMin.transform(mapProjection, this.backendProjection);
        llMax.transform(mapProjection, this.backendProjection);
        return 'BBOX(geom,' + (llMin.lat) + ',' + (llMin.lon) + ',' + (llMax.lat) + ',' + (llMax.lon) + ')';
	  },
	
	getURL: function (bounds) {
		var url = OpenLayers.Layer.TMS.prototype.getURL.apply(this, arguments);
		var hash = "";
        var re = /.*\/([0-9]+)\/([0-9]+)\/([0-9]+)\.[a-z]+$/i.exec(url);
        if (re) {
            var x = Math.floor(parseInt(re[2], 10) / this.metaTileSize), y = Math.floor(parseInt(re[3], 10) / this.metaTileSize);
            hash = "?c=" + Eniro.Crypto.crc32(re[1] + "/" + x + "/" + y);
        }
        var tileVersion = Eniro.Config["tile.version"];
		return url + hash + (!(tileVersion === null || tileVersion === undefined) ? "&v=" + tileVersion : "");
    },

    CLASS_NAME: 'Eniro.Layer.Themes',

    SUPER: 'Eniro.Layer.TMS'
});


/**
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Handler/Click.js
 * @requires OpenLayers/Handler/Hover.js
 * @requires OpenLayers/Request.js
 */
Eniro.ShowOnMapControl = OpenLayers.Class(Eniro.Control, {
	/**
	* Where to get Images
	*/
	mediaUrl: '/Js/Frameworks/EniroMapAPI-1.2.4/media/',
	/**
	* Where to reach the WFS service for the themelayers
	*/
    wfsURL: 'http://map.eniro.com/geoserver/wfs?callback=?',
	
	//wfsURL: 'http://test-mapfront02.eniromaps.net:8080/geoserver/wfs?callback=?',
    
	map: this.map,
	
    /**
     * Minimum zoom level where this control is active
     * @type Number
     * @default 4
     */
    minZoom: 4,

    /**
     * Maximum number of features to return from a WFS query. This sets the MaxFeatures parameter on WFS GetFeature requests.
     * @type Number
     * @default 3
     */
    maxFeatures: 3,

    /**
     * The {@link Eniro.ShowOnMapLayer} layers to query for feature info.
     * @type Array
     * @default []
     */
    layers: [],
    subLayers: [],
    /**
     * Reference to the click handler for this control
     * @type OpenLayers.Handler.Click
     * @default null
     * @private
     */
    clickHandler: null,

    /**
     * Reference to the popup for this control
     * @type Eniro.Popup.ShowOnMap
     * @private
     */
    popup: null,

    /**
     * The position of the mouse click
     * @type OpenLayers.Pixel
     * @default null
     * @private
     */
    mouseLoc: null,

    /**
     * Private property to hold visible layers temporary
     * @type Array
     * @default []
     * @private
     */
    visibleLayers: [],

    /**
     * @constructs
     * @param {Object} [options] Options to set to the instance.
     */
    initialize: function(options) {
	    options = options || {};
        Eniro.Control.prototype.initialize.apply(this, [options]);
        this.layers = [];
            var control = this;
				this.ThemesLayer = {
                    id: 'Themes',
                    visible: false,
                    control: control,
                    grocerySelected: false,
                    sportSelected: false,
                    schoolSelected: false,
                    child1Selected: false,
                    child2Selected: false,
					child3Selected: false,

                    draw: function() {
                        var ThemesDiv = [
                            '<div id="ThemesControlContainer">',
								'<div class="eniro-showonmapcontrol-Themes-list-item eniro-showonmapcontrol-Themes-list-item-grocery">',
									'<a href="#" onclick="smc.toggleLayer(dk_grocery);"><img id="indkoebgif" src="' + control.mediaUrl + 'markers/themes/indkoeb_20x20neg.gif" alt="Indkøb"></a><span class="eniro-showonmapcontrol-Themes-list-item-grocery-text">Indkøb</span>',
								'</div>',
								'<div class="eniro-showonmapcontrol-Themes-list-item eniro-showonmapcontrol-Themes-list-item-sport">',
									'<a href="#" onclick="smc.toggleLayer(dk_sport);"><img id="sportgif" src="' + control.mediaUrl + 'markers/themes/sport_20x20neg.gif" alt="Sport"></a><span class="eniro-showonmapcontrol-Themes-list-item-sport-text">Sport</span>',
								'</div>',
								'<div class="eniro-showonmapcontrol-Themes-list-item eniro-showonmapcontrol-Themes-list-item-school">',
									'<a href="#" onclick="smc.toggleLayer(dk_school);"><img id="skolegif" src="' + control.mediaUrl + 'markers/themes/skole_20x20neg.gif" alt="Skoler"></a><span class="eniro-showonmapcontrol-Themes-list-item-school-text">Skoler</span>',
								'</div>',
								'<div class="eniro-showonmapcontrol-Themes-list-item eniro-showonmapcontrol-Themes-list-item-child1">',
									'<a href="#" onclick="smc.toggleLayer(dk_child1);"><img id="vuggestuegif" src="' + control.mediaUrl + 'markers/themes/vuggestue_20x20neg.gif" alt="Vuggestuer"></a><span class="eniro-showonmapcontrol-Themes-list-item-child1-text">Vuggestuer</span>',
								'</div>',
								'<div class="eniro-showonmapcontrol-Themes-list-item eniro-showonmapcontrol-Themes-list-item-child2">',
									'<a href="#" onclick="smc.toggleLayer(dk_child2);"><img id="intgrinstgif" src="' + control.mediaUrl + 'markers/themes/intinst_20x20neg.gif" alt="Integrerede institutioner"></a><div class="eniro-showonmapcontrol-Themes-list-item-child2-text">Integrerede<br/>institutioner</div>',
								'</div>',
								'<div class="eniro-showonmapcontrol-Themes-list-item eniro-showonmapcontrol-Themes-list-item-child3">',
									'<a href="#" onclick="smc.toggleLayer(dk_child3);"><img id="boernehavegif" src="' + control.mediaUrl + 'markers/themes/boernehave_20x20neg.gif" alt="Børnehaver"></a><span class="eniro-showonmapcontrol-Themes-list-item-child3-text">Børnehaver</span>',
								'</div>',
                            '</div>'
                        ].join('');

                        return ThemesDiv;
                    }   
                };
                this.layers.push(this.ThemesLayer);
      
            var layername;
       
            this.clickHandler = new OpenLayers.Handler.Click(this, {
               click: this.handleClick 
			});
			
   },

    /**
     * Application event handler for event MODE_SWITCH
     * @param {Object} obj The event
     * @see Eniro.Events.MODE_SWITCH
     * @private
     */
/*    onModeSwitch: function(obj) {
        var i, n;
        if (obj.mode === 'streetview' || obj.mode === 'oblique') {
            jQuery(this.div).hide();
            if (this.visibleLayers.length === 0) {
                this.visibleLayers = this.getVisibleLayers();
            }
            for (i=0,n=this.layers.length;i<n;++i) {
                if (this.layers[i].map) {
                    this.hideLayer(this.layers[i]);
                }
            }
        }
        else {
            jQuery(this.div).show();
            for (i=0,n=this.visibleLayers.length;i<n;++i) {
                this.showLayer(this.visibleLayers[i]);
            }
            this.visibleLayers = [];
        }
    },*/


	getPoiLayerNames: function(layernames) {
		var poilayernames = [];
		for(var l = 0; l < layernames.length; l++) {
			layername = layernames[l];
			if(layername != "map" && layername != "search" && layername != "aerial" && layername != "hybrid"){
				poilayernames.push(layername);
			}
		}
				
		return poilayernames;
	},
	
	
    /**
     * Search for POI on the coordinated where the click occured in the map
     * @param {OpenLayers.Event} evt The event
     * @private
     */
    handleClick: function (evt) {
		if (this.map.getZoom() < this.minZoom) {
            return;
        }
        var layers = this.map.getVisibleLayers();
		if (layers.length === 0) {
            return;
        }
			
        this.mouseLoc = this.map.getLonLatFromPixel(evt.xy);
        var names = this.getLayerNames(layers);
		var numBaseLayers = 2;
		
		var popupSearchRange;
		if(map.getZoom() >= 14){
			popupSearchRange = 10;
		}else{
			popupSearchRange = 4;
		}
		
        var layer;
        var filter = '';
        for (var i = 0; i < layers.length; i++) {   //don't loop map/aerial, hybrid and search layer
            layer = layers[i];
			if(layer.layername != "map" && layer.layername != "aerial" && layer.layername != "hybrid" && layer.layername != "search"){
				filter += layer.getBBOX(evt.xy, popupSearchRange);
				if (layer.getCQLFilter) {
					layerCQL = layer.getCQLFilter();
					if (layerCQL) {
						filter += ' AND (' + layerCQL + ')';
					}
				}
				if (i < layers.length - 1) {
					filter += ';';
				}
			}
			if(layer.layername === "hybrid"){
				numBaseLayers = 3;
			}
		}
		
        var maxFeatures = this.maxFeatures;
        var propertyNames = [];
        var visibleLayers = this.getVisibleLayers();
		if(names.length > numBaseLayers){ 
			jQuery.getJSON(
				this.wfsURL,
				{
					SERVICE: 'WFS',
					VERSION: '1.1.0',
					REQUEST: "GetFeature",
					TYPENAME: this.getPoiLayerNames(names).join(","),//names[2],//
					OUTPUTFORMAT: 'JSON',
					FORMAT_OPTIONS: 'callback:smc.handleClickResponse', //&format_options=callback:myCallback
					PROPERTYNAME: propertyNames.join(","),
					MAXFEATURES: maxFeatures,
					CQL_FILTER: filter
				},OpenLayers.Function.bind(this.handleClickResponse, this) //smc.handleClickResponse
			);	
		}
	},

	/**
     * Handles the response from JSON request
     * @param {JSON} json
     * @private
     */
	handleClickResponse: function (json) {
  	    if (json.features.length === 0) {
 			return;
       }

        var i;
        
		var layers = map.getVisibleLayers();

        var feature;
        var layer;
        var popupInfo = [];
        var coordinates = [0, 0];
        var zoomLinkClass = '';
        if (smc.popup === null) { // Only generate once
		    zoomLinkClass = smc.getSingleCssClassName('zoom');
        }
        else {
            zoomLinkClass = smc.popup.zoomLinkClass;
        }

        for (i = 0; i < json.features.length; i++) {
            feature = json.features[i];
            coordinates[0] += feature.geometry.coordinates[0];
            coordinates[1] += feature.geometry.coordinates[1];
        }
			
        var n = 1;
        if (map.getZoom() >= 14) { //13// If below zoomlevel 10 show everything
            n = json.features.length;
        }

        for (i = 0; i < n; i++) {
            feature = json.features[i];
            layer = smc.getLayerFromFeatureId(layers, feature);
			this.onFeatureSelect(feature);
	    }
	},


    /**
     * Destroys the popup of the instance
     */
    popupDestroy: function () {
        if (this.popup) {
            this.popup.destroy();
            this.popup = null;
        }
    },

    /**
     * Set the map property for the control.
     * @param {OpenLayers.Map} map The map instance
     * @see OpenLayers.Control#setMap
     * @private
     */
     setMap: function (map) {
        map.addLayers([dk_grocery,dk_school,dk_sport,dk_child1,dk_child2,dk_child3]);
			
		dk_grocery.setVisibility(false);
		dk_school.setVisibility(false);
		dk_sport.setVisibility(false);
		dk_child1.setVisibility(false);
		dk_child2.setVisibility(false);
		dk_child3.setVisibility(false);
		
		Eniro.Control.prototype.setMap.apply(this, arguments);
		this.map.events.on({
            mousemove: this.onMouseMove,
            click: this.handleClick,
            scope: this
        });
		
    },

    /**
     * Get the visible layers
     * @returns {Array} An array containing all the currently visible layers.
     */
    getVisibleLayers: function () {
 	    var layers = [];
        var candidates = this.layers;
        for (var i = 0, len = candidates.length; i < len; ++i) {
		    if (!candidates[i].name) { // Skip fake layers
                continue;
			}
            if (candidates[i].map && candidates[i].getVisibility()) { // If added to map and visible
                layers.push(candidates[i]);
            }
        }
   		candidates = this.subLayers;
		for (i = 0, len = candidates.length; i < len; ++i) {
            if (!candidates[i].name) { // Skip fake layers
                continue;
            }
            if (candidates[i].map && candidates[i].getVisibility()) { // If added to map and visible
                layers.push(candidates[i]);
            }
        }
        return layers;
    },
 
	getLayerFromFeatureId: function (layers, feature) {
		for(var i = 0, len = layers.length; i < len; ++i) {
            var layerName = this.getLayerName(layers[i]);
            layerName = layerName.substr(layerName.indexOf(":") + 1);
            if (feature.id.substr(0, layerName.length) === layerName) {
                return layers[i];
            }
        }
        return null;
    },

    /**
     * Tool: Gets the layer with the given name
     * @param {String} layerName
     * @returns {Object} The layer with the given name or null if not found
     */
    getLayerFromName: function (layerName) {
       var candidates = this.layers;
        for(var i = 0, len = candidates.length; i < len; ++i) {
            if (this.getLayerName(candidates[i]) === layerName) {
                return candidates[i];
            }
        }
        return null;
    },

    /**
     * Tool: Get the names of all the layers
     * @returns {Array} All the names
     */
    getLayerNames: function (layers) {
        var names = [];
        for(var i = 0, len = layers.length; i < len; ++i) {
            names.push(this.getLayerName(layers[i]));
        }
        return names;
    },

    /**
     * Tool: Gets the layer with the given ID
     * @param {String} id
     * @returns {Object} The layer with the given ID or null if no layer was found.
     */
    getLayerById: function(id) {
        for (var i = 0, n = this.layers.length; i < n; ++i) {
            if (this.layers[i].id === id) {
                return this.layers[i];
            }
        }
        return null;
    },

    /**
     * Get the name of the given layer
     * @returns {String} The name of the layer
     */
    getLayerName: function(layer) {
	    if (layer.layername) {
            return layer.layername;
        }
        else {
            return layer.params.LAYERS;
        }
    },

    /**
     * Hides the given layer
     * @param {Object} layer A layer
     */
    hideLayer: function (layer) {
        if (layer.getVisibility()) {
            layer.setVisibility(false);
            if (layer.popupDestroy) {
                layer.popupDestroy();
            }
            this.popupDestroy();
        }
		
		switch(layer.name)
			{
			case 'dk_grocery - TMS':
			  jQuery('#indkoebgif').attr('src',this.mediaUrl + 'markers/themes/indkoeb_20x20neg.gif');
			  break;
			case 'dk_sport - TMS':
			  jQuery('#sportgif').attr('src',this.mediaUrl + 'markers/themes/sport_20x20neg.gif');
			  break;
			case 'dk_school - TMS':
			  jQuery('#skolegif').attr('src',this.mediaUrl + 'markers/themes/skole_20x20neg.gif');
			  break;
			case 'dk_child1 - TMS':
			  jQuery('#vuggestuegif').attr('src',this.mediaUrl + 'markers/themes/vuggestue_20x20neg.gif');
			  break;
			case 'dk_child2 - TMS':
			  jQuery('#intgrinstgif').attr('src',this.mediaUrl + 'markers/themes/intinst_20x20neg.gif');
			  break;
			case 'dk_child3 - TMS':
			  jQuery('#boernehavegif').attr('src',this.mediaUrl + 'markers/themes/boernehave_20x20neg.gif');
			  break;
			default:
			}
		
    },

    /**
     * Shows the given layer
     * @param {Object} layer A layer
     */
    showLayer: function(layer) {
        if (layer.name) {
            var isInMap = map.getLayersByName(layer.name).length > 0;
            if (!isInMap) {
                map.addLayer(layer);
            }
        }

        layer.setVisibility(true);
		
		switch(layer.layername)
			{
			case 'dk_grocery':
			  jQuery('#indkoebgif').attr('src',this.mediaUrl + 'markers/themes/indkoeb_20x20.gif');
			  break;
			case 'dk_sport':
			  jQuery('#sportgif').attr('src',this.mediaUrl + 'markers/themes/sport_20x20.gif');
			  break;
			case 'dk_school':
			  jQuery('#skolegif').attr('src',this.mediaUrl + 'markers/themes/skole_20x20.gif');
			  break;
			case 'dk_child1':
			  jQuery('#vuggestuegif').attr('src',this.mediaUrl + 'markers/themes/vuggestue_20x20.gif');
			  break;
			case 'dk_child2':
			  jQuery('#intgrinstgif').attr('src',this.mediaUrl + 'markers/themes/intinst_20x20.gif');
			  break;
			case 'dk_child3':
			  jQuery('#boernehavegif').attr('src',this.mediaUrl + 'markers/themes/boernehave_20x20.gif');
			  break;
			default:
			}
		
    },

    /**
     * Draws an HTML DIV element based on the given layer and also sets relevant classname values to the layer reference itself.
     * @param {Object} layer The layer to create the list item for.
     * @returns {String} An HTML string representing the list item for the given layer.
     */
    drawLayerListItem: function(layer) {
 	    var id;
        if (!layer.name && layer.id) { // Faked layers, like GPS. Used to avoid having potential clash in real layers on the map with the same name/id, as both those properties are set on real layers.
            id = layer.id;
        }
        else if (layer.name) {
            id = layer.name.replace(/\./gi, '_');
        }
        else { // Just in case...
            id = OpenLayers.Util.createUniqueID(this.id + 'layer_');
        }

        layer.itemActiveClass = this.getSingleCssClassName('item', null, {
            id: id,
            selected: true
        }); // Cache the specific classname for an active item

        layer.itemClass = this.getSingleCssClassName('item', null, {
            id: id
        }); // Cache the specific classname for an item

        layer.poweredbyClass = this.getSingleCssClassName('poweredby');

        var html = '<div class="' + this.getCssClassName('item', null, {
            id: id
        }) + '">';

        if (layer.draw) {
            html += layer.draw();
        }

        html += '</div>';

        return  html;
    },

    /**
     * @see OpenLayers.Control#draw
     */
    draw: function() {
        if (this.layers.length > 0) {

            this.div = this.createDiv();

            this.itemActiveClass = this.getSingleCssClassName('item', null, {
                selected: true
            }); // Cache the generic classname for an active item

            this.headerActiveClass = this.getSingleCssClassName('header-open');
            this.cssClasses.header = this.getCssClassName('header');
            this.cssClasses.item = this.getCssClassName('item');
            this.cssClasses.list = this.getCssClassName('list');
            var list = jQuery('<div id="themesControlHeader" class="themesControlHeader"><div id="ShowOnMapToggler"><div id="themesTogglerHeaderLeft">&nbsp;<div id="themesTogglerHeaderText" class="eniro-buttonbar-inner eniro-zoombar-inner">Vis&nbsp;p&aring;&nbsp;kort<img id="ThemesControlFoldind" onclick="smc.toggleShowOnMapControl();" src="' + this.mediaUrl + 'popup/toggler_right.gif" alt="Fold ind"><span id="themesTogglerHeaderRight" /></div></div></div><div></div></div>');
		
            if (this.layers.length > 0) {
                var layers = ['<div class="' + this.cssClasses.list + '">'];
                for (var i = 0, n = this.layers.length; i < n; ++i) {
                    layers.push(this.drawLayerListItem(this.layers[i]));
                }
                layers.push('</div>');
                layers = jQuery(layers.join(''));
                list.children().eq(1).append(layers);
            }
			jQuery(this.div).append(list);
            return this.div;
        }
        return null;
    },

	/**
	* Function to toggle a layer
	*@param {Object} layer
	*/
	toggleLayer: function(layer) {
		if(selectedFeature){
			this.onFeatureUnselect(selectedFeature);
		}
		if (layer.getVisibility()) {
			this.hideLayer(layer);
		}else{
			this.showLayer(layer);
		}
	},
	
	/**
	* Function to toggle entire control
	*/
	toggleShowOnMapControl:	function() {
		jQuery('.eniro-showonmapcontrol-list').toggle();
		
		var murl;
		murl = jQuery('#ShowOnMapToggler img').attr('src').split('toggler_');
		//fold in
		if (murl[1] === 'right.gif'){
			jQuery('#ShowOnMapToggler img').attr('src',this.mediaUrl + 'popup/toggler_left.gif');
			jQuery('.eniro-showonmapcontrol').css('height','0px');
			jQuery('#themesTogglerHeaderLeft').css('height','24px');
			jQuery('#themesTogglerHeaderRight').css('height','24px');
		}
		else{//fold out
			jQuery('#ShowOnMapToggler img').attr('src',this.mediaUrl + 'popup/toggler_right.gif');
			jQuery('.eniro-showonmapcontrol').css('height','168px');
			jQuery('#themesTogglerHeaderLeft').css('height','20px');
			jQuery('#themesTogglerHeaderRight').css('height','20px');
		}
	},

	/*from openlayers*/
	onFeatureSelect: function (feature) {
		if(selectedFeature){
			this.onFeatureUnselect(selectedFeature);
		}
		selectedFeature = feature;
		var lonlat = new OpenLayers.LonLat(selectedFeature.geometry.coordinates[1] , selectedFeature.geometry.coordinates[0] );
        var transformed = lonlat.transform(map.backendProjection, map.getProjectionObject());
        
		var popupHtml =	[
			'<div class="FeatureName">',
			feature.properties.navn,
			'<br /></div><div class="FeatureInfo">',
			feature.properties.vejnavn +'&nbsp;'+ feature.properties.husnr,
			'<br /></div><div class="FeatureInfo">',
			feature.properties.postdistrikt +'&nbsp;'+ feature.properties.postnr,
			'<br /></div>'
        ].join('');

		popup = new Eniro.Popup.ShowOnMap(transformed, popupHtml, {closeBox: true, resultType: "route"});
		
		feature.popup = popup;
		popup.feature = feature;
		map.addPopup(popup); 
	},
	
	onFeatureUnselect: function (feature) {
		if(feature.popup){
			map.removePopup(feature.popup);
			feature.popup.destroy();
			feature.popup = null;
		}
	}, 

    CLASS_NAME: "Eniro.ShowOnMapControl"
});

		
/**
 * @requires OpenLayers/Popup/Framed.js
 */
Eniro.Popup = OpenLayers.Class(OpenLayers.Popup.Framed, /** @lends Eniro.Popup.prototype */ {
    
    contentDisplayClass: "olFramedCloudPopupContent olEniroIgnoreHandlers",
    
    autoSize: true,
    
    keepInMap: false,
    
    panMapIfOutOfView: false,
    
    imageSize: new OpenLayers.Size(700, 912),
    
    isAlphaImage: true,
    
    fixedRelativePosition: false,
    
    minSize: new OpenLayers.Size(46, 66), /* Use only divisible dimensions, due to IE6 */
    
    maxSize: new OpenLayers.Size(600, 500), /* Use only divisible dimensions, due to IE6 */
    
    resultType: 'draw',
    
    /**
     * The size to line wrap the popups content to.
     * @type Number
     * @default 100
     */
    lineWrapLength: 100,

    /**
     * The order of "blocks" matters. 0 = top left, 1 = top right, 2 = bottom left, 3 = bottom right.
     * The value of the property 'position' in a block will be based of the same corner as the relative position, i.e. 'tl', 'tr', 'bl, 'br'.
     * This is different than from OL who always uses top-left corner.
     * @see OpenLayers.Popup.Framed#updateBlocks
     * @private
     */
    positionBlocks: {
        "tl": {
            'offset': new OpenLayers.Pixel(0, 14),
            'padding': new OpenLayers.Bounds(14, 16, 30, 11),
            'blocks': [
                { // top-left
                    size: new OpenLayers.Size('auto', 'auto'),
                    anchor: new OpenLayers.Bounds(0, 16, 36, 0),
                    position: new OpenLayers.Pixel(-22, 0)
                },
                { // top-right
                    size: new OpenLayers.Size(14, 'auto'),
                    anchor: new OpenLayers.Bounds(null, 48, 22, null),
                    position: new OpenLayers.Pixel(-22, 0)
                },
                { // bottom-left
                    size: new OpenLayers.Size('auto', 16),
                    anchor: new OpenLayers.Bounds(0, 0, 36, null),
                    position: new OpenLayers.Pixel(-22, -255)
                },
                { // bottom-right (stem)
                    size: new OpenLayers.Size(36, 48),
                    anchor: new OpenLayers.Bounds(null, 0, 0, null),
                    position: new OpenLayers.Pixel(0, -131)
                }
            ]
        },
        "tr": {
            'offset': new OpenLayers.Pixel(0, 14),
            'padding': new OpenLayers.Bounds(36, 16, 8, 11),
            'blocks': [
                { // top-left
                    size: new OpenLayers.Size('auto', 'auto'),
                    anchor: new OpenLayers.Bounds(0, 48, 14, 0),
                    position: new OpenLayers.Pixel(-1, 0)
                },
                { // top-right
                    size: new OpenLayers.Size(14, 'auto'),
                    anchor: new OpenLayers.Bounds(null, 16, 0, null),
                    position: new OpenLayers.Pixel(-22, 0)
                },
                { // bottom-left (stem)
                    size: new OpenLayers.Size('auto', 48),
                    anchor: new OpenLayers.Bounds(0, 0, 14, null),
                    position: new OpenLayers.Pixel(-1, -193)
                },
                { // bottom-right
                    size: new OpenLayers.Size(14, 16),
                    anchor: new OpenLayers.Bounds(null, 0, 0, null),
                    position: new OpenLayers.Pixel(-22, -255)
                }
            ]
        },
        "bl": {
            'offset': new OpenLayers.Pixel(0, -36),
            'padding': new OpenLayers.Bounds(14, 16, 30, 11),
            'blocks': [
                { // top-left
                    size: new OpenLayers.Size('auto', 'auto'),
                    anchor: new OpenLayers.Bounds(0, 16, 36, 0),
                    position: new OpenLayers.Pixel(-22, 0)
                },
                { // top-right (stem)
                    size: new OpenLayers.Size(36, 48),
                    anchor: new OpenLayers.Bounds(null, null, 0, 0),
                    position: new OpenLayers.Pixel(0, -863)
                },
                { // bottom-left
                    size: new OpenLayers.Size('auto', 16),
                    anchor: new OpenLayers.Bounds(0, 0, 36, null),
                    position: new OpenLayers.Pixel(-22, -255)
                },
                { // bottom-right
                    size: new OpenLayers.Size(14, 'auto'),
                    anchor: new OpenLayers.Bounds(null, 0, 22, 48),
                    position: new OpenLayers.Pixel(-22, -255)
                }
            ]
        },
        "br": {
            'offset': new OpenLayers.Pixel(0, -36),
            'padding': new OpenLayers.Bounds(36, 16, 8, 11),
            'blocks': [
                { // top-left (stem)
                    size: new OpenLayers.Size('auto', 48),
                    anchor: new OpenLayers.Bounds(0, null, 14, 0),
                    position: new OpenLayers.Pixel(-1, -794)
                },
                { // top-right
                    size: new OpenLayers.Size(14, 'auto'),
                    anchor: new OpenLayers.Bounds(null, 16, 0, null),
                    position: new OpenLayers.Pixel(-22, 0)
                },
                { // bottom-left
                    size: new OpenLayers.Size('auto', 'auto'),
                    anchor: new OpenLayers.Bounds(0, 0, 14, 48),
                    position: new OpenLayers.Pixel(-1, -255)
                },
                { // bottom-right
                    size: new OpenLayers.Size(14, 16),
                    anchor: new OpenLayers.Bounds(null, 0, 0, null),
                    position: new OpenLayers.Pixel(-22, -255)
                }
            ]
        }
    },
    
    /**
     * @constructs
     */
    initialize: function(id, lonlat, contentSize, contentHTML, anchor, closeBox, closeBoxCallback, options) {
        OpenLayers.Util.extend(this, options);
        
        if (!this.imageSrc) {
		    this.imageSrc = this.mediaUrl + 'popup/yellow-popup.png';
        }
       
        OpenLayers.Popup.Framed.prototype.initialize.apply(this, [id, lonlat, contentSize, contentHTML, anchor, closeBox, closeBoxCallback]);
    },
 
    updateSize: function() {
        // determine actual render dimensions of the contents by putting its
        // contents into a fake contentDiv (for the CSS) and then measuring it
        var preparedHTML = "<div class='" + this.contentDisplayClass + "'>" +
        this.contentDiv.innerHTML +
        "</div>";
        
        // Container element overriden here 
        var containerElement = (this.map) ? this.map.viewPortDiv : document.body;
        var realSize = OpenLayers.Util.getRenderedDimensions(preparedHTML, null, {
            displayClass: this.displayClass,
            containerElement: containerElement
        });
        
        // is the "real" size of the div is safe to display in our map?
        var safeSize = this.getSafeContentSize(realSize);
        
        var newSize = null;
        if (safeSize.equals(realSize)) {
            //real size of content is small enough to fit on the map,
            // so we use real size.
            newSize = realSize;           
        }
        else {
        
            //make a new OL.Size object with the clipped dimensions
            // set or null if not clipped.
            var fixedSize = new OpenLayers.Size();
            fixedSize.w = (safeSize.w < realSize.w) ? safeSize.w : null;
            fixedSize.h = (safeSize.h < realSize.h) ? safeSize.h : null;
            
            if (fixedSize.w && fixedSize.h) {
                //content is too big in both directions, so we will use
                // max popup size (safeSize), knowing well that it will
                // overflow both ways.
                newSize = safeSize;
            }
            else {
                //content is clipped in only one direction, so we need to
                // run getRenderedDimensions() again with a fixed dimension
                var clippedSize = OpenLayers.Util.getRenderedDimensions(preparedHTML, fixedSize, {
                    //displayClass: this.contentDisplayClass,
                    displayClass: this.displayClass,
                    containerElement: containerElement
                });
                
                //if the clipped size is still the same as the safeSize,
                // that means that our content must be fixed in the
                // offending direction. If overflow is 'auto', this means
                // we are going to have a scrollbar for sure, so we must
                // adjust for that.
                var currentOverflow = OpenLayers.Element.getStyle(this.contentDiv, "overflow");
                if ((currentOverflow != "hidden") &&
                (clippedSize.equals(safeSize))) {
                    var scrollBar = OpenLayers.Util.getScrollbarWidth();
                    if (fixedSize.w) {
                        clippedSize.h += scrollBar;
                    }
                    else {
                        clippedSize.w += scrollBar;
                    }
                }
                
                newSize = this.getSafeContentSize(clippedSize);
            }
        }
        
        if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7) {
            if (newSize.w % 2 === 0) {
                newSize.w += 1;
            }
            if (newSize.h % 2 === 0) {
                newSize.h += 1;
            }
        }
        this.setSize(newSize);
    },
    
    /**
     * IE6 does not understand height:100% randomly...
     * Just set the group div height to the same as the wrapper div
     * @private
     */
    setSize: function() {
       OpenLayers.Popup.Framed.prototype.setSize.apply(this, arguments);
        this.groupDiv.style.height = this.div.style.height;
        // We need to trigger hidden overflow as to eliminate the scrollbars that appear at random, even though the contents would fit without them.
        var oldOverflow = this.contentDiv.style.overflow;
        this.contentDiv.style.overflow = 'hidden';
        this.contentDiv.style.overflow = oldOverflow;
    },
    
    /**
     * Override to set the position of images to originate from the respective block position
     * TODO: Send upstream?
     * @see OpenLayers.Popup.Framed#updateBlocks
     * @private
     */
    updateBlocks: function() {
      if (!this.blocks) {
            this.createBlocks();
        }
        
        if (this.size && this.relativePosition) {
            var position = this.positionBlocks[this.relativePosition];
            for (var i = 0; i < position.blocks.length; i++) {
            
                var positionBlock = position.blocks[i];
                var block = this.blocks[i];
                
                // adjust sizes
                var l = positionBlock.anchor.left;
                var b = positionBlock.anchor.bottom;
                var r = positionBlock.anchor.right;
                var t = positionBlock.anchor.top;
                
                //note that we use the isNaN() test here because if the
                // size object is initialized with a "auto" parameter, the
                // size constructor calls parseFloat() on the string,
                // which will turn it into NaN
                
                var w = (isNaN(positionBlock.size.w)) ? this.size.w - (r + l) : positionBlock.size.w;               
                var h = (isNaN(positionBlock.size.h)) ? this.size.h - (b + t) : positionBlock.size.h;
                
                block.div.style.width = (w < 0 ? 0 : w) + 'px';
                block.div.style.height = (h < 0 ? 0 : h) + 'px';
                block.div.style.left = (l !== null) ? l + 'px' : '';
                block.div.style.bottom = (b !== null) ? b + 'px' : '';
                block.div.style.right = (r !== null) ? r + 'px' : '';
                block.div.style.top = (t !== null) ? t + 'px' : '';
                
                var x = 'left';
                var y = 'top';
                if (i === 2 || i === 3) {
                    y = 'bottom';
                }
                if (i === 1 || i === 3) {
                    x = 'right';
                }
                block.image.style[x] = positionBlock.position.x + 'px';
                block.image.style[y] = positionBlock.position.y + 'px';
            }
            
            this.contentDiv.style.left = this.padding.left + "px";
            this.contentDiv.style.top = this.padding.top + "px";
        }
    },
    
    CLASS_NAME: "Eniro.Popup"
});

 
/**
 * @requires OpenLayers/Popup/Framed.js
 */ 
/** @lends Eniro.Popup.ShowOnMap.prototype */
Eniro.Popup.ShowOnMap = OpenLayers.Class(Eniro.Popup, {
	
	mediaUrl: '/Js/Frameworks/EniroMapAPI-1.2.4/media/',

	maxSize: new OpenLayers.Size(360, 500), /* Use only divisible dimensions, due to IE6 */
    
    resultType: 'route',
    
    closeBox: false,
	
	initialize: function(position, content, options) {
        this.positionBlocks = jQuery.extend(true, {}, this.positionBlocks);
        this.positionBlocks.tl.offset = new OpenLayers.Pixel(0, 36);
        this.positionBlocks.tr.offset = new OpenLayers.Pixel(0, 36);
        this.positionBlocks.br.offset = new OpenLayers.Pixel(0, -14);
        this.positionBlocks.bl.offset = new OpenLayers.Pixel(0, -14);

        options = options || {};
        var defaultArgs = {
            id: OpenLayers.Util.createUniqueID(this.CLASS_NAME.replace(/[\._]/g, '-').toLowerCase() + '-'),
            lonlat: position,
            contentSize: null,
            contentHTML: content,
            anchor: {
                offset: new OpenLayers.Pixel(2, -7),
                size: new OpenLayers.Size(0, 0)
            },
            closeBox: this.closeBox
        };

        OpenLayers.Util.extend(defaultArgs, options);
        Eniro.Popup.prototype.initialize.apply(this, [
            defaultArgs.id,
            defaultArgs.lonlat,
            defaultArgs.contentSize,
            defaultArgs.contentHTML,
            defaultArgs.anchor,
            defaultArgs.closeBox,
            defaultArgs.closeBoxCallback
        ]);
		this.events.on({
            mouseover: this.onMouseOver,
            mouseout: this.onMouseOut,
            mousemove: this.onMouseMove,
            scope: this
        });
	},
	
	destroy: function() {
        this.events.un({
            mouseover: this.onMouseOver,
            mouseout: this.onMouseOut,
            mousemove: this.onMouseMove,
            scope: this
        });
        Eniro.Popup.prototype.destroy.apply(this, arguments);
    },

    onclick: function(){},

    onMouseOver: function(evt) {
        this.stuck = true;
    },

    onMouseOut: function(evt) {
        OpenLayers.Popup.Framed.prototype.onmouseout.apply(this, arguments);
        if (Eniro.Util.mouseLeft(evt, this.div)) {
            this.stuck = false;
        }
    },

    onMouseMove: function(evt) {
        OpenLayers.Event.stop(evt, true);
    },
 
    CLASS_NAME: "Eniro.Popup.ShowOnMap"	
	});


/********definitions********/

//Initiate control	
var smc = new Eniro.ShowOnMapControl();

var selectedFeature;        

var addThemesControl = function(_map){
	//Add control to map
	map = _map;
	map.addControl(smc);
}

//Define Layers for themes
var dk_sport = new Eniro.Layer.Themes("dk_sport - TMS", 
//"http://map04.eniro.com.test.eniromaps.net/geowebcache/service/tms",
	"http://map.eniro.com/geowebcache/service/tms",
	{
		srs: 'EPSG:4326',
		layername: 'dk_sport',
		format:	'image/png',
		transparent: 'true'
	},
	{
		visibility: false,
		singleTile : false,
		isBaseLayer : false
	} ); 
var dk_grocery = new Eniro.Layer.Themes("dk_grocery - TMS", 
	"http://map.eniro.com/geowebcache/service/tms",
	{
		srs: 'EPSG:4326',
		layername: 'dk_grocery',
		format:	'image/png',
		transparent: 'true'
	},
	{
		visibility: false,
		singleTile : false,
		isBaseLayer : false
	} ); 
var dk_child1 = new Eniro.Layer.Themes("dk_child1 - TMS", 
	"http://map.eniro.com/geowebcache/service/tms",
	{
		srs: 'EPSG:4326',
		layername: 'dk_child1',
		format:	'image/png',
		transparent: 'true'
	},
	{
		visibility: false,
		singleTile : false,
		isBaseLayer : false
	} ); 				
var dk_child2 = new Eniro.Layer.Themes("dk_child2 - TMS", 
	"http://map.eniro.com/geowebcache/service/tms",
	{
		srs: 'EPSG:4326',
		layername: 'dk_child2',
		format:	'image/png',
		transparent: 'true'
	},
	{
		visibility: false,
		singleTile : false,
		isBaseLayer : false
	} ); 

var dk_child3 = new Eniro.Layer.Themes("dk_child3 - TMS", 
	"http://map.eniro.com/geowebcache/service/tms",
	{
		srs: 'EPSG:4326',
		layername: 'dk_child3',
		format:	'image/png',
		transparent: 'true'
	},
	{
		visibility: false,
		singleTile : false,
		isBaseLayer : false
	} ); 			
	
var dk_school = new Eniro.Layer.Themes("dk_school - TMS", 
	"http://map.eniro.com/geowebcache/service/tms",
	{
		srs: 'EPSG:4326',
		layername: 'dk_school',
		format:	'image/png',
		transparent: 'true'
	},
	{
		visibility: false,
		singleTile : false,
		isBaseLayer : false
	} ); 
