var lay_cross;

/* парсинг XML данных */
var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

function parsXML(X){
	console.log('XML! - ', X );
	console.log('elByName[0] - ', X.getElementsByTagName("way")[0].childNodes[0]);
	console.log('elByName[0]nd - ', X.getElementsByTagName("way")[0].getElementsByTagName("nd"));
}
/* парсинг geoJSON данных */
function parsOSM(J){
    //sound_play('data/traffic_jam.mp3');// пробка / затор
	//var J = JSON.parse( json_txt );
	//console.log('Recive OSM of ',json_txt);
    if(!J.elements) return;
    lay_cross.getSource().clear(true);
	//console.log('Recive OSM of ',J.elements.length);
	var jn = J.elements;
	//console.log(' Journa for OBJ-ID ',jobj.id);
	// если type=node и присуствует tags - это иконка
	// ... интерес представляют type=way где в tags присуствуют lanes (но вместо координат там nodes)
	for(var i=0;i<jn.length;i++){
		//console.log(' fields ',jn[i].type);
		//if((!jn[i].tags)&&(jn[i].lon))
		//if((jn[i].lon))
		if(!jn[i].tags) continue;
		var tags = jn[i].tags;
		if(!tags.highway) continue;
		var geom = jn[i].geometry;
		var w = 1; var f = 0;
		if(tags.lanes) w = tags.lanes*4;
		//if(tags.lanes:forward) f=tags.lanes:forward;
		if(geom)
		{
			//'crossing'
			console.log(' tags # ' + i, tags, geom);
			var pts = [];
			for(var j=0;j<geom.length;j++){
				pts.push(ol.proj.fromLonLat([geom[j].lon,geom[j].lat]));//
			};
			if(tags.natural) g = new ol.geom.Polygon( pts );
			else if(tags.building) g = new ol.geom.Polygon( pts ); 
				else g = new ol.geom.LineString( pts );
			
			var txt = new ol.style.Text({scale:2, text: i + " " });
			if(tags.lanes) txt.setText( i + " L:" + tags.lanes);
			var fill = new ol.style.Fill({color: [255,0,0,0.7]});
			var style;
			//if(tags.lanes)
			style = new ol.style.Style({ stroke: new ol.style.Stroke({width: w, color: [64, 64, 64, 0.5]}), fill: new ol.style.Fill({color: [255,0,0,0.7]}), text: txt });
			//else if(f>0) style = new ol.style.Style({ stroke: new ol.style.Stroke({width: w, color: [255, 64, 64, 0.5]}) });
			//	else style = new ol.style.Style({ stroke: new ol.style.Stroke({width: 2, color: [64, 64, 255, 0.5]}) });

			//g = new ol.geom.Polygon( [pts] );
			//g = new ol.geom.Point(pts[0]);
			var feature = new ol.Feature({
				//type: 'removable',
				//name: 'new_line-'+i,
				//style: new ol.style.Style({ fill: new ol.style.Fill({color: [255, 255, 255, 0.5]}) }),
				//style: style,
				geometry: g
			});
			lay_cross.getSource().addFeature(feature);
			feature.setStyle(style);
			//t = jn[i].id;
			//if(jn[i].lon) { addMark(c,t); };

		};
	};

};

function getCom_URL(url, json){
    //setRequestHeader('Content-Type', 'application/json');
	var request = new XMLHttpRequest();
    request.open( "GET", url );
	if(json) request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
	//request.onerror = function () { note({ content: "Locked", type: "error",	time: 2	}); return; };
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
		//alert(request.status);
		if(request.status>400) return;
		var cont_type = request.getResponseHeader('Content-Type');
		//console.log('GET > responseType! - ', cont_type );
		// cont_type.includes в IE не работает
		if(cont_type.indexOf('application/json')>=0) {
			//console.log('GET > responseText! - ', request.responseText );
			parsOSM( JSON.parse(request.responseText) )
//				parseResponse( request.responseText )
			} else	{
				//alert(request.responseText);
				console.log('GET > responseType! - ', cont_type );
				console.log('GET > responseText! - ', request.responseText );
				parsXML(parseXml(request.responseText));
			}; 
		//return request.responseText;
		}
	};
    if(json) request.send(JSON.stringify(json)); else request.send();
	//.catch(() => console.log("Can’t access " + routeUrl + " response. Blocked by browser?"));
	//console.log('GET ', url );
};

function getCSDfromOSM(view, bb) {
	//console.log('bb ', bb );
	var fExtent = bb.getExtent();
	var cc = ol.proj.transformExtent(fExtent, 'EPSG:3857', 'EPSG:4326');
	//console.log('bb ', cc );
	var bbox = (cc[1]) + ',' + (cc[0]) + ',' + (cc[3]) + ',' + (cc[2]);
	console.log(' bbox ', bbox );
	//urlA = 'http://overpass-api.de/api/interpreter?data=[out:json];';
	urlA = 'https://overpass.openstreetmap.ru/api/interpreter?data=[out:json];';
	//urlA = 'https://overpass.openstreetmap.ru/api/interpreter?data=[out:xml];';
	
	//urlB = '(node('+ bbox +'););out geom;';
	//urlB = '(node('+bbox+');way('+bbox+'););(._;<;);out geom;';
	//urlB = '(way('+ bbox +');>;);out geom;';
	//urlB = '(node('+bbox+');<;way('+bbox+');<;rel('+bbox+');<;);(._;<;>;);out geom;';
	//urlB = '(node('+bbox+');rel(bn)->.x;way(bn);rel(bw););(._;way(r););(._;node(r)->.x;node(w););out geom;';
	//urlB = '(node('+bbox+');<;rel(bn);<;way('+bbox+');node(w);<;);(._;<;);out geom;';
	urlB = 'way('+bbox+');out geom;';
	jsn = getCom_URL( urlA + urlB );
	//alert('getCom_URL');
	//return;
	//AddBoxLL(lay_cross, c, feature);
	
    var writer = new ol.format.GeoJSON();
	var twriter = new ol.format.TopoJSON();
	//найти всё что попадает BBOX
	//src = lay_cross.getSource();
//	features = src.getFeaturesInExtent(fExtent);
	//for(i=0;i<features.length;i++) features[i].set('obj',obj);
	//удалить сам BBOX
//	var i = features.indexOf(feature);
	//if(i>=0) features.slice(i,1);
//    var geojsonStr = writer.writeFeatures(features);
//	jsn = JSON.parse(geojsonStr);
	
//	var topojsonObject = topojson.topology({
//      world: jsn
//    });
	//geojsonStr = twriter.writeFeatures(features);
//	console.log('TopoJSON', topojsonObject );	
	
	//jsn = writer.writeFeaturesObject(features);
	//jsn.features[0].id=feature.getId();
//	for(i=0;i<jsn.features.length;i++)
//	{
	//console.log('geojsonStr.features['+i+'] :', jsn.features[i].properties );	
//	delete jsn.features[i].properties.obj;
	//console.log('geojsonStr.features['+i+'] :', jsn.features[i] );
//	}
//	console.log('geojsonStr.jsn :', jsn);
//	postCom_URL(cgiURL + 'new_cross.cgi', jsn);
	//
//	for(i=0;i<features.length;i++) features[i].set('obj',obj);
}