<link rel="stylesheet" href="http://openlayers.org/en/v3.17.1/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.17.1/build/ol.js" type="text/javascript"></script>
<script type="text/javascript">

  document.addEventListener("DOMContentLoaded", function(event) {

  	document.getElementById('preview_map').setAttribute("style", "height:600px");

    {% if resource.bbox_string %}
    var bbox = [{{ resource.bbox_string }}];
    {% else %}
    var bbox = null;
    {% endif %}

    source = null;
    {% if resource.get_tiles_url %}
    source = new ol.source.XYZ({
    	url: '{{ resource.get_tiles_url|safe }}'
    });

    {% elif resource.ptype == 'gxp_wmscsource' %}
    source = new ol.source.TileWMS({
    	url: '{{ resource.ows_url|safe }}',
    	params: {'LAYERS': '{{ resource.alternate }}'}
    });

    {% elif resource.ptype == 'gxp_arcrestsource' %}
    source = new ol.source.TileArcGISRest({
    	url: '{{ resource.ows_url|safe }}',
        params: {'LAYERS': '{{ resource.alternate }}'}
    });

    {% endif %}

    var crs = '{{ crs }}'

    if (crs != 'EPSG:4326') {
        crs = 'EPSG:3857';
    }
    if (source != null) {
    	var layers = [
        	new ol.layer.Tile({
            	source: new ol.source.OSM()
          	}),
          	new ol.layer.Tile({
            	source: source
          	})
    	];

    	var map = new ol.Map({
        	layers: layers,
          	target: 'preview_map',
          	view: new ol.View({
            	center: [0, 0],
            	zoom: 2,
            	projection: crs
            })
    	});

    	if (bbox != null) {
    	    if (crs != 'EPSG:4326') {
    		    bbox = ol.proj.transformExtent(bbox, 'EPSG:4326', 'EPSG:3857');
    		}
    		map.getView().fit(bbox, map.getSize());
    	}
    }
  });

</script>
