var OpenWindows = {};
var container	= document.getElementById('popup');
var content	= document.getElementById('popup-content');
var closer	= document.getElementById('popup-closer');
var sanSalvador	= ol.proj.fromLonLat([-89.0000, 13.6990]);
var laLibertad	= ol.proj.fromLonLat([-89.3213, 13.4888]);
var atiquizaya	= ol.proj.fromLonLat([-89.7552, 13.9760]);
var overlay = new ol.Overlay({
    element: container,
    autoPan: true,
    autoPanAnimation: {
      duration: 250
    }
});
closer.onclick = function() {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

var view = new ol.View({
    center: sanSalvador,
    zoom: 9.4
});
var bingMapsAerial = new ol.layer.Tile({
  preload: Infinity,
  source: new ol.source.BingMaps({
    key: 'AqGsAuRDjXHYrRrLeHXRICtHWKgKpCwZGzS9aGnz55FaqZgj5JtK6-lkG-fAoBjp',
    imagerySet: 'AerialWithLabelsOnDemand',
  })
});			
var osmLayer = new ol.layer.Tile({
    preload: 4,
    source: new ol.source.OSM()
});
var wmsSource = new ol.source.TileWMS({
	url: document.getElementById("url").value,
	params: {
		'LAYERS': document.getElementById("layer").value,
	},
	serverType: 'geoserver'
});
var wmsLayer = new ol.layer.Tile({
	source: wmsSource
});
var map = new ol.Map({
    target: 'map',
    //layers: [osmLayer,wmsLayer],
		//layers: [bingMapsRoad,bingMapsAerial,wmsLayer],
		layers: [bingMapsAerial,wmsLayer],		
    overlays: [overlay],
    loadTilesWhileAnimating: true,
    view: view
});
map.on('singleclick', function(evt) {
	var coordinate 		= evt.coordinate;
	var view            = map.getView();
	var source          = wmsLayer.getSource();
	var viewResolution  = view.getResolution();
	var viewProjection  = view.getProjection();
	var url             = source.getGetFeatureInfoUrl(evt.coordinate, viewResolution, viewProjection,{'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 50});
	if (url) {
		//var parser = new ol.format.GeoJSON();
		var r = new XMLHttpRequest();
		r.open("GET",url, true);
		r.onreadystatechange = function () {
			if (r.readyState != 4 || r.status != 200) return;
			data = JSON.parse(r.responseText);
			//console.log(data);
			showContent(data.features[0].properties);
		};
		r.send();
	}
	overlay.setPosition(coordinate);
});
function showContent(d){
	console.log(d);
	var rowset = "<tr><th>RTM ID</th><td>"+d.RTM_SIM+"</td><td><a href=\"#\" onclick='openInmueble(\""+d.RTM_SIM+"\")'>Inmueble</a></td></tr>";
		rowset+= "<tr><th>PROPIETARIO</th><td>"+d.Propietari+"</td><td><a href=\"#\" onclick='openExpediente(\""+d.RTM_SIM+"\")'>Expediente</a></td></tr>";
		rowset+= "<tr><th>DIRECCION</th><td>"+d.Direccion+"</td><td><a href=\"#\" onclick='openBalance(\""+d.RTM_SIM+"\")'>Estado Cuenta</a></td></tr>";
		rowset+= "<tr><th>MUNICIPIO</th><td>"+d.Municipio+"<td><a href=\"#\" onclick='openAbonos(\""+d.RTM_SIM+"\")'>Historial Abonos</a></td></tr>";
		rowset+= "<tr><th>SECTOR</th><td>"+d.Sector+"</td><td><a href=\"#\" onclick='openMapaVinculacion(\""+d.Sector+"\",\""+d.Parcela+"\",\""+d.RTM_SIM+"\")'>Registro Mapa</a></td></tr>";
		rowset+= "<tr><th>PARCELA</th><td>"+d.Parcela+"</td><td></td></tr>";
		rowset+= "<tr><th>AREA CALCULADA</th><td>"+d.Area_cal+"</td><td></td></tr>";
		rowset+= "<tr><th>PERIMETRO</th><td>"+d.Perimetro+"</td><td></td></tr>";
		rowset+= "<tr><th>ANTECEDENTE</th><td>"+d.Antecedent+"</td><td></td></tr>";
		content.innerHTML = "<table id='grid'><th width='17%'>CAMPO</th><th>DATO</th><th width='17%'>ENLACES</th>"+rowset+"</table>";
}
function openInmueble(eid){
	eid = eid.replace(/<td>/g,'');
	eid = eid.replace(/<\/td>/g,'');
	eid = eid.replace(/ /g,'');
	if (eid!="") {
		var winame = "Inmueble";
		if (!OpenWindows[winame] || OpenWindows[winame].closed){
			//alert(eid);
			var win ="window.open('/cgi-bin/RTM_v30/bin/comm.pl?lan=es&appid=RTM_v30&clase=inmuebles&id="+eid+"','Inmueble_Win','left=20,top=20,width=20,height=20,scrollbars=yes,toolbar=no,menubar=no,resizable=yes,location=no,status=no')";
			OpenWindows[winame]=eval(win);
		}else{OpenWindows[winame].focus();}
	}
}
function openExpediente(eid){
	eid = eid.replace(/<td>/g,'');
	eid = eid.replace(/<\/td>/g,'');
	eid = eid.replace(/ /g,'');
	if (eid!="") {
		var winame = "Expediente";
		if (!OpenWindows[winame] || OpenWindows[winame].closed){
			var win ="window.open('/cgi-bin/RTM_v30/bin/rept.pl?lan=es&appid=RTM_v30&clase=inmuebles&id="+eid+"','Expediente_Win','left=20,top=20,width=1024,height=700,scrollbars=yes,toolbar=no,menubar=no,resizable=yes,location=no,status=no')";
			OpenWindows[winame]=eval(win);
		}else{OpenWindows[winame].focus();}
	}
}
function openBalance(eid){
	eid = eid.replace(/<td>/g,'');
	eid = eid.replace(/<\/td>/g,'');
	eid = eid.replace(/ /g,'');
	if (eid!="") {
		var winame = "Balance";
		if (!OpenWindows[winame] || OpenWindows[winame].closed){
			var win ="window.open('/cgi-bin/RTM_v30/bin/bsws.pl?lan=es&appid=RTM_v30&clase=inmueble&id="+eid+"','Balance_Win','left=20,top=20,width=20,height=20,scrollbars=yes,toolbar=no,menubar=no,resizable=yes,location=no,status=no')";
			OpenWindows[winame]=eval(win);
		}else{OpenWindows[winame].focus();}
	}
}
function openAbonos(eid){
	eid = eid.replace(/<td>/g,'');
	eid = eid.replace(/<\/td>/g,'');
	eid = eid.replace(/ /g,'');
	if (eid!="") {
		var winame = "Abonos";
		if (!OpenWindows[winame] || OpenWindows[winame].closed){
			var win ="window.open('/cgi-bin/RTM_v30/bin/asws.pl?lan=es&appid=RTM_v30&clase=inmueble_abonos&id="+eid+"','Abonos_Win','left=20,top=20,width=20,height=20,scrollbars=yes,toolbar=no,menubar=no,resizable=yes,location=no,status=no')";
			OpenWindows[winame]=eval(win);
		}else{OpenWindows[winame].focus();}
	}
}
function openMapaVinculacion(sid,pid,eid){
	sid = sid.replace(/<td>/g,'');
	sid = sid.replace(/<\/td>/g,'');
	sid = sid.replace(/ /g,'');
	pid = pid.replace(/<td>/g,'');
	pid = pid.replace(/<\/td>/g,'');
	pid = pid.replace(/ /g,'');
	if (sid!="" && pid!="") {
		var winame = "Mapa";
		if (!OpenWindows[winame] || OpenWindows[winame].closed){
			var win ="window.open('/cgi-bin/RTM_v30/pl/mapa.vinculacion.p.pl?lan=es&appid=RTM_v30&clase=inmueble_abonos&sid="+sid+"&pid="+pid+"&eid="+eid+"','Mapa_Win','left=20,top=20,width=20,height=20,scrollbars=yes,toolbar=no,menubar=no,resizable=yes,location=no,status=no')";
			OpenWindows[winame]=eval(win);
		}else{OpenWindows[winame].focus();}
	}
}
function flyTo(location, done) {
	var duration = 4000;
	//var zoom    = 14.2;
	var zoom    = 18.5;
	var parts   = 4;
	var called  = false;
	function callback(complete) {
		--parts;
		if (called) {
		  return;
		}
		if (parts === 0 || !complete) {
		  called = true;
		  done(complete);
		}
	}
	view.animate({
		center: location,
		duration: duration
	}, callback);
	view.animate({
		zoom: zoom - 1,
		duration: duration / 2
	}, {
		zoom: zoom,
		duration: duration / 2
	}, callback);
}