<?php

/**
 * http://openlayers.org/dev/examples/wps.html
 * http://geoinformatyka.com.pl/usluga-wfs-jak-to-dziala/
 * 
 * TODO: brak ModifyFeature - html btn: olControlModifyFeatureItemInactive
 */

function OPEN_LAYERS_WPS() {

	$task = V::get('task', '', $_GET);
	switch ($task) {
		case 'proxy': {
			$url = V::get('url', '', $_GET);
			// 1. http%3A%2F%2Fbiuro.biall-net.pl%2Fwps%3FSERVICE%3DWPS%26REQUEST%3DGetCapabilities
			// 2. http%3A%2F%2Fbiuro.biall-net.pl%2Fwps%3FSERVICE%3DWPS%26REQUEST%3DDescribeProcess%26VERSION%3D1.0.0%26IDENTIFIER%3Dpozdrawiam
			header('Content-Type: application/xml; charset=utf-8');
			$urlParts = parse_url($url);
			$urlQuery = array();
			$urlQueryTmp = V::get('query', '', $urlParts);
			$urlQueryTmp = explode('&', $urlQueryTmp);
			foreach ($urlQueryTmp as $vQuery) {
				$parts = explode('=', $vQuery, 2);
				$urlQuery[$parts[0]] = $parts[1];
			}

			if ('WPS' == V::get('SERVICE', '', $urlQuery)) {
				$req = V::get('REQUEST', '', $urlQuery);
				$wps = new WpsServer();
				$methodName = "{$req}Action";
				if (method_exists($wps, $methodName)) {
					$wps->$methodName($urlQuery);
				}
			}
			else {
				$wps = new WpsServer();
				$wps->parseXMLRequest();
			}
			exit;

			break;
		}
		case 'import_from_postgis': {

			$gis_zas_id = 13102;
			$pgDB = DB::getDB($gis_zas_id);

			$db = DB::getDB();
		//	POSTGIS_to_MYSQL_Tables('BUILDINGS','geoportal_gml_punkty_adr_gml_id','MK_Budynki','geoportal_gml_punkty_adr_gml_id');

		//	function POSTGIS_to_MYSQL_Tables($local_table_mysql,$local_key,$remote_table_postgis,$remote_key){
		//		global $db,$gdb;
			$local_table_mysql = 'BUILDINGS';
			$local_key = 'geoportal_gml_punkty_adr_gml_id';
			$remote_table_postgis = 'MK_Budynki';
			$remote_key = 'geoportal_gml_punkty_adr_gml_id';
			// BUG: ST_AsEWKT @see http://postgis.org/docs/ST_AsEWKT.html
			$pgSql = <<<SQL
				select "{$remote_key}"
			--		, ST_AsEWKT(the_geom) as the_geom  -- The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText
					, ST_AsText(the_geom) as the_geom
				from "{$remote_table_postgis}"
				where "{$remote_key}"!=''
					and "{$remote_key}" is not null
					and the_geom != ''
					and the_geom is not null
SQL;
			$pgRes = $pgDB->query($pgSql);
			echo '<pre>';
			echo "Start...\n";
			while ($r = $pgDB->fetch($pgRes)) {
				$r->{$remote_key} = trim($r->{$remote_key});
				$sql = "update `{$local_table_mysql}` set `the_geom`=GeomFromText('{$r->the_geom}')
					where `{$local_key}`='{$r->$remote_key}'
						and `{$local_key}`!=''
						and `{$local_key}` is not null
						and (`the_geom`='' or `the_geom` is null)
				";
				//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
				echo "Fethed remote_key: {$remote_key}={$r->$remote_key}| ";

				$testRow = null;
				$testSql = "select t.`ID`, t.`{$local_key}`, AsWKT(t.`the_geom`) as the_geom from `{$local_table_mysql}` as t where t.`{$local_key}`='{$r->$remote_key}' ";
				//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">testSql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($testSql);echo'</pre>';
				$testRes = $db->query($testSql);
				if ($testRow = $db->fetch($testRes)) {
					echo " mysql row exists in table `{$local_table_mysql}` (ID={$testRow->ID}) ";
					echo " | the_geom is ";
					echo (!empty($testRow->the_geom))? " set " : " not set ";
				} else {
					echo " mysql row not exists in table `{$local_table_mysql}`! ";
				}
				//echo'<pre style="max-height:200px;overflow:auto;border:1px solid green;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($testRow);echo'</pre>';

				$res = $db->query($sql);
				if (!$res) {
					echo "| ERROR: problem with query!";
					echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
				}
				else {
					echo "| done ";
				}

				echo "\n";
			}
			echo '</pre>';
			break;
		}
		default:
	}
	

//$_POST['url'] = 'http://demo.opengeo.org/geoserver/wfs';
//$entityBody = file_get_contents('php://input');
	$url = V::get('_url', '', $_GET);
	if ($url) {// @see OpenLayers/examples/proxy.cgi
		$allowedHosts = array('www.openlayers.org', 'openlayers.org', 
										'labs.metacarta.com', 'world.freemap.in', 
										'prototype.openmnnd.org', 'geo.openplans.org',
										'sigma.openplans.org', 'demo.opengeo.org',
										'www.openstreetmap.org', 'sample.azavea.com',
										'v2.suite.opengeo.org', 'v-swe.uni-muenster.de:8080',
										'vmap0.tiles.osgeo.org', 'www.openrouteservice.org',
										'maps.wien.gv.at');

		if (!empty($_POST)) {
			//	qs = os.environ["QUERY_STRING"]
			//	d = cgi.parse_qs(qs)
			//	if d.has_key("url"):
			//			url = d["url"][0]
			//	else:
			//			url = "http://www.openlayers.org"
		}
		else {
			//	fs = cgi.FieldStorage()
			//	url = fs.getvalue('url', "http://www.openlayers.org")
		}

		$host = explode('/', $url);
		$host = $host[2];
		if (!in_array($host, $allowedHosts)) {
			header("Status: 502 Bad Gateway");
			header("Content-Type: text/plain");
			echo "\nThis proxy does not allow you to access that location ({$host}).";
			exit;
		}
		else if (substr($url, 0, 7) == 'http://' || substr($url, 0, 8) == 'https://') {
			$ch = curl_init(); 
			
			if (!empty($_POST)) {
/*
            length = int(os.environ["CONTENT_LENGTH"])
            headers = {"Content-Type": os.environ["CONTENT_TYPE"]}
            body = sys.stdin.read(length)
            r = urllib2.Request(url, body, headers)
            y = urllib2.urlopen(r)
 */
			}
			else {
				curl_setopt($ch, CURLOPT_URL, $url);

				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// return the transfer as a string
				//curl_setopt($ch, CURLOPT_VERBOSE, 1);
				curl_setopt($ch, CURLOPT_HEADER, 1);

				$response = curl_exec($ch);

				// Then, after your curl_exec call:
				$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
				$header = substr($response, 0, $header_size);
				$body = substr($response, $header_size);
				curl_close($ch);

				$contentType = 'text/plain';
				$headers = explode("\n", $header);
				foreach ($headers as $vHeader) {
					if (substr($vHeader, 0, 13) == 'Content-Type:') {
						$contentType = trim(substr($vHeader, 14));
					}
				}

				header("Content-Type: {$contentType}");
				echo $body . "\n";
			}
		}
		else {
			header("Content-Type: text/plain");
			echo "\nIllegal request.";
			exit;
		}
		exit;
	}

	?>
    <link rel="stylesheet" href="stuff/open-layers/theme/default/style.css" type="text/css">
	<link rel="stylesheet" href="stuff/open-layers/style.css" type="text/css">
    <style type="text/css">
         .olControlEditingToolbar .olControlModifyFeatureItemInactive { 
             background-image: url(stuff/open-layers/theme/default/img/draw_point_off.png); 
         } 
         .olControlEditingToolbar .olControlModifyFeatureItemActive { 
             background-image: url(stuff/open-layers/theme/default/img/draw_point_on.png); 
         } 
        .olControlRefresh {
        	 background-image: url(stuff/open-layers/theme/default/img/save_features_off.png);
         }
        .olControlZoomToPoly {
        	 background-image: url(stuff/open-layers/theme/default/img/ruler.png);
         }
        .olControlLayerSwitcher .layersDiv {
            border-radius: 10px 0 0 10px;
            opacity: 0.75;
            filter: alpha(opacity=75);
        }
        textarea {
            display: block;
            width: 100%;
            height: 3em;
        }
        label {
            display: block;
        }
        .notsupported {
            color: red;
        }
        button {
            display: block;
            margin-top: 10px;
        }
    </style>

		<div id="TreeTableMap"></div>

    <script src="stuff/open-layers/OpenLayers.js"></script>
<!--    <script src="stuff/open-layers/wps.js"></script> -->
    <script>
(function ( $ ) {
	var TableAjaxMap = function() {
		var priv = {}; //private api
		var publ = {}; //public api

		priv.options = {};
		var defaults = {
			wpsUrl: '',
			wfsUrl: '',
			domProcessId: '',
			urlInit: true, // try to load services on init
			preloadData: null,
			menuid: '',
			debug: false
		};

		var _nodeMapId;
		var _nodeMap;
		var _nodeProcesses;
		var _nodeAbstract;
		var _nodeInput;
		var _nodeOutput;
		var _capabilities;
		var _process;
		var _layer;
		/*
		 initialize the plugin.
		 */
		priv.init = function() {
			console.log('test jQuery plugin init...', priv);
			// create dom:
			/*
        <div id="map" class="smallmap"></div>

        <div>
            <select id="processes"><option>Select a process</option></select>
            <p id="abstract"></p>
            <div id="input"></div>
            <div id="output"></div>
        </div>
			 */
			_nodeMapId = 'Map-' + Math.random(1).toString().substr(2);
			_nodeMap = $('<div id="' + _nodeMapId + '" class="smallmap"></div>');
			_nodeProcesses = $('<select></select>');
			_nodeProcesses.append('<option>Wybierz funkcję</option>');
			_nodeAbstract = $('<p></p>');
			_nodeInput = $('<div></div>');
			_nodeOutput = $('<div></div>');
			var div = $('<div></div>');
			div.append(_nodeProcesses);
			div.append(_nodeAbstract);
			div.append(_nodeInput);
			div.append(_nodeOutput);
			$(priv.options.id).append(_nodeMap);
			$(priv.options.id).append(div);

			_nodeProcesses.on('change', function() {
				console.log("onchange this:", this, this.selectedIndex, this.options);
				var selection = this.options[this.selectedIndex].value;
				if (this.selectedIndex > 0) {
					OpenLayers.Request.GET({
						url: priv.options.wpsUrl,
						params: {
							"SERVICE": "WPS",
							"REQUEST": "DescribeProcess",
							"VERSION": _capabilities.version,
							"IDENTIFIER": selection
						},
						success: function(response) {
							_process = new OpenLayers.Format.WPSDescribeProcess().read(
								response.responseText
							).processDescriptions[selection];
							console.log("Process:", _process);
							priv.buildForm();
						}
					});
				}
			});
			priv.getCapabilities();

			var style = new OpenLayers.Style();

			var rule = new OpenLayers.Rule({
			  symbolizer: {strokeWidth: 4}
			});

			style.addRules([rule]);
			
			_layer = new OpenLayers.Layer.Vector("Warstwa rysowania", {
				strategies:  [new OpenLayers.Strategy.BBOX(), new OpenLayers.Strategy.Cluster( {distance: 15, threshold: 2})],
				projection: new OpenLayers.Projection("EPSG:4326"),
				styleMap: new OpenLayers.StyleMap(style),
				protocol: new OpenLayers.Protocol.WFS({
					version: "1.1.0",
					srsName: "EPSG:4326",
					url: priv.options.wfsUrl,
					featureNS :  "http://opengeo.org",
					featureType: "restricted",
					geometryName: "the_geom",
					schema: "http://demo.opengeo.org/geoserver/wfs/DescribeFeatureType?version=1.1.0&typename=og:restricted"
				})
			});

			var toolbar = new OpenLayers.Control.EditingToolbar(_layer);
			toolbar.addControls([new OpenLayers.Control.ModifyFeature(_layer, {
				title: "Wybierz",
				mode: OpenLayers.Control.ModifyFeature.DRAG | OpenLayers.Control.ModifyFeature.RESHAPE		
			})]);					    
			    	
 			var btnZoomToPoly = new OpenLayers.Control.Button({
 				displayClass: "olControlZoomToPoly", 
                title: "Zbliz",
 				trigger: 
 					function() {
 				   		var multiPolygon = OpenLayers.Geometry.fromWKT(
 			                    "MULTIPOLYGON(((2072016.74395199 7234076.79293037,2072016.74395199 7234115.01144451,2072131.3994944 7234115.01144451,2072131.3994944 7234076.79293037,2072016.74395199 7234076.79293037)))"
 			                ).getBounds(); 		
 						map.zoomToExtent(multiPolygon);
	                }
 			});
 				toolbar.addControls([btnZoomToPoly]);	

			var btnRefresh = new OpenLayers.Control.Button({
			    displayClass: "olControlRefresh", 
	            title: "Odswiez",
			    trigger: 
			    	function() {
						_layer.refresh({force:true});
			    }
			});
			toolbar.addControls([btnRefresh]);

			var deleteFeatureControl = new OpenLayers.Control.SelectFeature(_layer, OpenLayers.Handler.Path, {
               clickout: false,
               toggle: false,
               displayClass: "olControlDelete",
               title: "Usun"
            });
               
            deleteFeatureControl.events.register("featurehighlighted", this, function(e) {
               if (confirm('Czy na pewno chcesz usunąć ten obiekt?')) {
                   _layer.removeFeatures([e.feature]);
                   deleteFeatureControl.deactivate();
               } else {
                   deleteFeatureControl.unselect(e.feature);
               }
            });

    		toolbar.addControls([deleteFeatureControl]);
	            
			var extent = new OpenLayers.Bounds(
				2035059.4410645328, 7200979.560689885, 2113330.958028555, 7279251.0776539035
			);

			var gphy =  new OpenLayers.Layer.OSM("Mapa", null, {
		        resolutions: [156543.03390625, 78271.516953125, 39135.7584765625,
		                      19567.87923828125, 9783.939619140625, 4891.9698095703125,
		                      2445.9849047851562, 1222.9924523925781, 611.4962261962891,
		                      305.74811309814453, 152.87405654907226, 76.43702827453613,
		                      38.218514137268066, 19.109257068634033, 9.554628534317017,
		                      4.777314267158508, 2.388657133579254, 1.194328566789627,
		                      0.5971642833948135, 0.25, 0.1, 0.05],
		        serverResolutions: [156543.03390625, 78271.516953125, 39135.7584765625,
		                            19567.87923828125, 9783.939619140625,
		                            4891.9698095703125, 2445.9849047851562,
		                            1222.9924523925781, 611.4962261962891,
		                            305.74811309814453, 152.87405654907226,
		                            76.43702827453613, 38.218514137268066,
		                            19.109257068634033, 9.554628534317017,
		                            4.777314267158508, 2.388657133579254,
		                            1.194328566789627, 0.5971642833948135],
		        transitionEffect: 'resize'
		    });
	
			var map = new OpenLayers.Map(_nodeMapId, {
				projection: new OpenLayers.Projection("EPSG:4326"),
				displayProjection: new OpenLayers.Projection("EPSG:4326"),
				restrictedExtent: extent,
				controls: [
					toolbar,
					new OpenLayers.Control.ZoomPanel(),
					new OpenLayers.Control.PanPanel(),
					new OpenLayers.Control.LayerSwitcher(),
					new OpenLayers.Control.ScaleLine(),
					new OpenLayers.Control.KeyboardDefaults()
				//	new OpenLayers.Control.MousePosition()				
				], layers: [gphy]
			});
			map.addLayer(_layer);
		
			map.events.register("zoomend", this, function(e) {
				var zoom = map.getZoom();
				console.log("Zoom = "  + zoom);
				console.log(_layer.strategies[1]);
				if (zoom > 15 && _layer.strategies[1].active) {
 					_layer.strategies[1].deactivate();					
 					_layer.refresh({force:true});
 				} else if (zoom <= 15 && !_layer.strategies[1].active) {
 					_layer.strategies[1].activate();					
 					_layer.refresh({force:true});
 				}
				//	map.addLayer(_layer);
				//} else if (zoom == 11){
				//	var myLayer = map.getLayersByName('Warstwa rysowania');
				//	myLayer[0].destroy();

				//	_layer.destroy();					
				//	map.removeLayer(_layer, false);	
				//	console.log("costam: "+ map.getLayer());
				//	map.addLayer(_layer);	
				//	_layer.setVisibility(false);
				
				//	map.addLayer(_layer);
				
				//	map.removeLayer(_layer, false);
					
				//	map.refresh();
			});   

			
			map.zoomToMaxExtent();

			};

	
		

		// using OpenLayers.Format.WPSCapabilities to read the capabilities
		priv.getCapabilities = function() {
			OpenLayers.Request.GET({
				url: priv.options.wpsUrl,
				params: {
					"SERVICE": "WPS",
					"REQUEST": "GetCapabilities"
				},
				success: function(response){
					_capabilities = new OpenLayers.Format.WPSCapabilities().read(
						response.responseText
					);
					var dropdown = _nodeProcesses;
					var offerings = _capabilities.processOfferings, option;
					// populate the dropdown
					for (var p in offerings) {
						option = document.createElement("option");
						option.innerHTML = offerings[p].identifier;
						option.value = p;
						dropdown.append(option);
					}
				}
			});
		};

		priv.buildForm = function() {
			_nodeAbstract.html(_process["abstract"]);
			_nodeInput.html("<h3>Input:</h3>");
			_nodeOutput.html('');

			var inputs = _process.dataInputs, supported = true,
				sld = "text/xml; subtype=sld/1.0.0",
				input;
			for (var i = 0, ii = inputs.length; i < ii; ++i) {
				input = inputs[i];
				if (input.complexData) {
					var formats = input.complexData.supported.formats;
					if (formats["application/wkt"]) {
						priv.addWKTInput(input);
					} else if (formats["text/xml; subtype=wfs-collection/1.0"]) {
						priv.addWFSCollectionInput(input);
					} else if (formats["image/tiff"]) {
						//priv.addRasterInput(input);
					} else if (formats[sld]) {
						priv.addXMLInput(input, sld);
					} else {
						supported = false;
					}
				} else if (input.boundingBoxData) {
					priv.addBoundingBoxInput(input);
				} else if (input.literalData) {
					priv.addLiteralInput(input);
				} else {
					supported = false;
				}
				if (input.minOccurs > 0) {
					_nodeInput.append(document.createTextNode("* "));
				}
			}
			
			if (supported) {
				var executeButton = document.createElement("button");
				executeButton.innerHTML = "Execute";
				_nodeInput.append(executeButton);
				executeButton.onclick = priv.execute;
			} else {
				_nodeInput.html('<span class="notsupported">' +
					"Sorry, the WPS builder does not support the selected process." +
					"</span>");
			}
		};

		// helper function to dynamically create a textarea for geometry (WKT) data
		// input
		priv.addWKTInput = function(input, previousSibling) {
			var name = input.identifier;
			var container = _nodeInput.get(0);
			var label = document.createElement("label");
			label["for"] = name;
			label.title = input["abstract"];
			label.innerHTML = name + " (select feature, then click field):";
			previousSibling && previousSibling.nextSibling ?
				container.insertBefore(label, previousSibling.nextSibling) :
				container.appendChild(label);
			var field = document.createElement("textarea");
			field.onclick = function () {
				if (_layer.selectedFeatures.length) {
					this.innerHTML = new OpenLayers.Format.WKT().write(
						_layer.selectedFeatures[0]
					);
					console.log('_layer.selectedFeatures[0]: ', _layer.selectedFeatures[0]);
				}
				priv.createCopy(input, this, priv.addWKTInput);
			};
			field.onblur = function() {
				input.data = field.value ? {
					complexData: {
						mimeType: "application/wkt",
						value: this.value
					}
				} : undefined;
			};
			field.title = input["abstract"];
			field.id = name;
			previousSibling && previousSibling.nextSibling ?
				container.insertBefore(field, previousSibling.nextSibling.nextSibling) :
				container.appendChild(field);
		};

		// helper function for xml input
		priv.addXMLInput = function(input, type) {
			var name = input.identifier;
			var field = document.createElement("input");
			field.title = input["abstract"];
			field.value = name + " (" + type + ")";
			field.onblur = function() {
				input.data = field.value ? {
					complexData: {
						mimeType: type,
						value: this.value
					}
				} : undefined;
			};
			_nodeInput.append(field);
		};

		// helper function to dynamically create a WFS collection reference input
		priv.addWFSCollectionInput = function(input) {
			var name = input.identifier;
			var field = document.createElement("input");
			field.title = input["abstract"];
			field.value = name + " (layer on demo server)";
			priv.addValueHandlers(field, function() {
				input.reference = field.value ? {
					mimeType: "text/xml; subtype=wfs-collection/1.0",
					href: "http://geoserver/wfs",
					method: "POST",
					body: {
						wfs: {
							version: "1.0.0",
							outputFormat: "GML2",
							featureType: field.value
						}
					}
				} : undefined;
			});
			_nodeInput.append(field);
		};

		// helper function to dynamically create a raster (GeoTIFF) url input
		priv.addRasterInput = function(input) {
			var name = input.identifier;
			var field = document.createElement("input");
			field.title = input["abstract"];
			var url = window.location.href.split("?")[0];
			field.value = url.substr(0, url.lastIndexOf("/")+1) + "data/tazdem.tiff";// TODO: file path to options
			document.getElementById("input").appendChild(field);
			(field.onblur = function() {
				input.reference = {
					mimeType: "image/tiff",
					href: field.value,
					method: "GET"
				};
			})();
		};

		// helper function to dynamically create a bounding box input
		priv.addBoundingBoxInput = function(input) {
			var name = input.identifier;
			var field = document.createElement("input");
			field.title = input["abstract"];
			field.value = "left,bottom,right,top (EPSG:4326)";
			_nodeInput.append(field);
			priv.addValueHandlers(field, function() {
				input.boundingBoxData = {
					projection: "EPSG:4326",
					bounds: OpenLayers.Bounds.fromString(field.value)
				};
			});
		};

		// helper function to create a literal input textfield or dropdown
		priv.addLiteralInput = function(input, previousSibling) {
			var name = input.identifier;
			var container = _nodeInput.get(0);
			var anyValue = input.literalData.anyValue;
			// anyValue means textfield, otherwise we create a dropdown
			var field = document.createElement(anyValue ? "input" : "select");
			field.id = name;
			field.title = input["abstract"];
			previousSibling && previousSibling.nextSibling ?
				container.insertBefore(field, previousSibling.nextSibling) :
				container.appendChild(field);
			if (anyValue) {
				var dataType = input.literalData.dataType;
				field.value = name + (dataType ? " (" + dataType + ")" : "");
				priv.addValueHandlers(field, function() {
					input.data = field.value ? {
						literalData: {
							value: field.value
						}
					} : undefined;
					priv.createCopy(input, field, priv.addLiteralInput);
				});
			} else {
				var option;
				option = document.createElement("option");
				option.innerHTML = name;
				field.appendChild(option);
				for (var v in input.literalData.allowedValues) {
					option = document.createElement("option");
					option.value = v;
					option.innerHTML = v;
					field.appendChild(option);
				}
				field.onchange = function() {
					priv.createCopy(input, field, priv.addLiteralInput);
					input.data = this.selectedIndex ? {
						literalData: {
							value: this.options[this.selectedIndex].value
						}
					} : undefined;
				};
			}
		};

		// if maxOccurs is > 1, this will add a copy of the field
		priv.createCopy = function(input, field, fn) {
			if (input.maxOccurs && input.maxOccurs > 1 && !field.userSelected) {
				// add another copy of the field - we don't check maxOccurs
				field.userSelected = true;
				var newInput = OpenLayers.Util.extend({}, input);
				// we recognize copies by the occurrence property
				newInput.occurrence = (input.occurrence || 0) + 1;
				_process.dataInputs.push(newInput);
				fn(newInput, field);
			}
		};

		// helper function for adding events to form fields
		priv.addValueHandlers = function(field, onblur) {
			field.onclick = function() {
				if (!this.initialValue) {
					this.initialValue = this.value;
					this.value = "";
				}
			};
			field.onblur = function() {
				if (!this.value) {
					this.value = this.initialValue;
					delete this.initialValue;
				}
				onblur.apply(this, arguments);
			};
		};

		// execute the process
		priv.execute = function() {
			var output = _process.processOutputs[0];
			var input;
			// remove occurrences that the user has not filled out
			for (var i = _process.dataInputs.length - 1; i >= 0; --i) {
				input = _process.dataInputs[i];
				if ((input.minOccurs === 0 || input.occurrence) && !input.data && !input.reference) {
					OpenLayers.Util.removeItem(_process.dataInputs, input);
				}
			}
			_process.responseForm = {
				rawDataOutput: {
					identifier: output.identifier
				}
			};
			if (output.complexOutput && output.complexOutput.supported.formats["application/wkt"]) {
				_process.responseForm.rawDataOutput.mimeType = "application/wkt";
			}
			OpenLayers.Request.POST({
				url: priv.options.wpsUrl,
				data: new OpenLayers.Format.WPSExecute().write(_process),
				success: priv.showOutput
			});
		}

		// add the process's output to the page
		priv.showOutput = function(response) {
			var result = _nodeOutput.get(0);
			result.innerHTML = "<h3>Output:</h3>";
			var features;
			var contentType = response.getResponseHeader("Content-Type");
			if (contentType == "application/wkt") {
				features = new OpenLayers.Format.WKT().read(response.responseText);
			} else if (contentType == "text/xml; subtype=wfs-collection/1.0") {
				features = new OpenLayers.Format.WFST.v1_0_0().read(response.responseText);
			}
			if (features && (features instanceof OpenLayers.Feature.Vector || features.length)) {
				_layer.addFeatures(features);
				result.innerHTML += "The result should also be visible on the map.";
			}
			result.innerHTML += "<textarea>" + response.responseText + "</textarea>";
		}


		publ.init = function(options) {
			if (priv.options.debug) console.log('TableAjaxMap initialization...');
			//merge supplied options with defaults
			$.extend(priv.options, defaults, options);
			priv.init();
			return publ;
		};
		return publ;
	};

	$.fn.TableAjaxMap = function(options) {
		options = options || {};
		return this.each(function() {
			options.id = this;
			$(this).data('TableAjaxMap', new TableAjaxMap().init(options));
		});
		return this;
	};
}(jQuery));
    </script>
    <script>
OpenLayers.ProxyHost = "index.php?FUNCTION_INIT=<?php echo __FUNCTION__; ?>&HEADER_NOT_INIT=YES&task=proxy&url=";

jQuery('#TreeTableMap').TableAjaxMap({
	wpsUrl: 'http://biuro.biall-net.pl/wps',
	wfsUrl: 'http://biuro.biall-net.pl/wps'
});
    </script>
	<?php
}


class WpsActionBase {

	public $title = '';
	public $description = '';
	public $dataInputs = array();

	public function execute($args) {
		var_dump($args);
	}

}

class WpsActionPrzypiszDoRekordu extends WpsActionBase {

	public function __construct() {
		$this->title = 'Przypisz';
		$this->description = 'Przypisuje położenie do wybranego rekordu w tabeli.';

		$this->dataInputs['geom'] = new stdClass();
		$this->dataInputs['geom']->title = 'geom';
		$this->dataInputs['geom']->description = 'Input geometry';
		$this->dataInputs['geom']->type = 'geom';// CoomplexData

		$this->dataInputs['idTable'] = new stdClass();
		$this->dataInputs['idTable']->title = 'geom';
		$this->dataInputs['idTable']->description = 'Table ID';
		$this->dataInputs['idTable']->type = 'integer';// LiteralData: xs:integer

		$this->dataInputs['idRecord'] = new stdClass();
		$this->dataInputs['idRecord']->title = 'idRecord';
		$this->dataInputs['idRecord']->description = 'Record ID';
		$this->dataInputs['idRecord']->type = 'integer';// LiteralData: xs:integer
	}

}

class WfsAction {

	/**
	 * example: MULTIPOLYGON(((2072016.74395199 7234076.79293037,2072016.74395199 7234115.01144451,2072131.3994944 7234115.01144451,2072131.3994944 7234076.79293037,2072016.74395199 7234076.79293037)))
	 */
	public function generateGmlFromWKT($wkt) {
		$gml = '';

		$wktParts = explode('(', $wkt, 2);
		ob_start();
		switch ($wktParts[0]) {
			case 'MULTIPOLYGON':
			case 'POLYGON': {
				$points = trim($wktParts[1], '() ');
				$points = str_replace(',', "\n", $points);
				?>
					<gml:boundedBy>
						<gml:Envelope srsDimension="2" srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
							<gml:lowerCorner>-180 -90</gml:lowerCorner>
							<gml:upperCorner>180 90</gml:upperCorner>
						</gml:Envelope>
					</gml:boundedBy>
					<og:the_geom>
						<gml:MultiSurface srsDimension="2" srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
							<gml:surfaceMember>
								<gml:Polygon srsDimension="2">
									<gml:exterior>
										<gml:LinearRing srsDimension="2">
											<gml:posList>
												<?php echo $points; ?>
											</gml:posList>
										</gml:LinearRing>
									</gml:exterior>
								</gml:Polygon>
							</gml:surfaceMember>
						</gml:MultiSurface>
					</og:the_geom>
				<?php
				}
				break;
			default:
		}
		$gml = ob_get_contents();
		ob_clean();

		return $gml;
	}

	public function execute($args) {
/*
 * Mapa odczytywanie punktów: http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
 * 
 * CI50:
			18.613243103027344 54.33614429135817
			18.613243103027344 54.33634445792519
			18.614273071289062 54.33634445792519
			18.614273071289062 54.33614429135817
 */
		$tblId = 16;// `BUILDINGS`
		$buildingsGml = array();
		$db = DB::getDB();
		$sql = "select b.`ID`, AsWKT(b.`the_geom`) as the_geom
			from `BUILDINGS` as b
			where b.`the_geom` is not null and b.`the_geom`!=''
			limit 10;
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$buildingsGml[$r->ID] = $this->generateGmlFromWKT($r->the_geom);
		}

		/**
		 * <og:recordId><?php echo $kId; ?></og:recordId>
		 * <og:tblId><?php echo $tblId; ?></og:tblId>
		 * 
		 * goes to js: @see priv.addWKTInput _layer.selectedFeatures[0]
		 * 
		 *	attributes: Object
					recordId: "1130"
					tblId: "16"
		 */

		echo '<?xml version="1.0" encoding="UTF-8"?>';
		?>
<wfs:FeatureCollection xmlns:nasa="http://nasa.gov" xmlns:topp="http://www.openplans.org/topp" xmlns:usgs="http://www.usgs.gov/" xmlns:ogc="http://www.opengis.net/ogc" xmlns:wfs="http://www.opengis.net/wfs" xmlns:ows="http://www.opengis.net/ows" xmlns:ne="http://naturalearthdata.com" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gml="http://www.opengis.net/gml" xmlns:osm="http://openstreemap.org" xmlns:nurc="http://www.nurc.nato.int" xmlns:og="http://opengeo.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" numberOfFeatures="4" timeStamp="2014-07-16T13:22:43.307Z" xsi:schemaLocation="http://opengeo.org http://demo.opengeo.org:80/geoserver/wfs?service=WFS&amp;version=1.1.0&amp;request=DescribeFeatureType&amp;typeName=og%3Arestricted http://www.opengis.net/wfs http://demo.opengeo.org:80/geoserver/schemas/wfs/1.1.0/wfs.xsd">
  <gml:boundedBy>
    <gml:Envelope srsDimension="2" srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
      <gml:lowerCorner>-180 -90</gml:lowerCorner>
			<gml:upperCorner>180 90</gml:upperCorner>
    </gml:Envelope>
  </gml:boundedBy>
  <gml:featureMembers>
		<?php foreach ($buildingsGml as $kId => $vGml) : ?>
			<og:restricted gml:id="restricted.<?php echo $kId; ?>">
				<?php echo $vGml; ?>
				<og:recordId><?php echo $kId; ?></og:recordId>
				<og:tblId><?php echo $tblId; ?></og:tblId>
			</og:restricted>
		<?php endforeach; ?>
  </gml:featureMembers>
</wfs:FeatureCollection>
		<?php
	}
}

class WpsServer {

	private $_fun;// config for identifiers

	public function __construct() {
		$this->_fun['przypiszDoRekordu'] = new WpsActionPrzypiszDoRekordu();
		$this->_wfsAction = new WfsAction();
	}

	public function parseXMLRequest() {
		$data = array();
		$reqContent = file_get_contents('php://input');
		$xml = new SimpleXMLElement($reqContent);

		if ('GetFeature' == $xml->getName()) {
			// TODO: parse xml and set query params
			$this->_wfsAction->execute($data);
		}
		else if (isset($xml->children('ows', TRUE)->Identifier)) {
			$identifier = (string)$xml->children('ows', TRUE)->Identifier;
			if (array_key_exists($identifier, $this->_fun)) {

				foreach ($xml->children('wps', TRUE)->DataInputs->children('wps', TRUE) as $input) {
					$inputIdentifier = (string)$input->children('ows', TRUE)->Identifier;
					if (array_key_exists($inputIdentifier, $this->_fun[$identifier]->dataInputs)) {
						$inputType = (string)$this->_fun[$identifier]->dataInputs[$inputIdentifier]->type;
						switch ($inputType) {
							case 'integer':
								$data[$inputIdentifier] = (string)$input->children('wps', TRUE)->Data->LiteralData;
								break;
							case 'geom':
								$data[$inputIdentifier] = (string)$input->children('wps', TRUE)->Data->ComplexData;
								break;
							default:
								
						}
					} else {
						// brak zdefiniowanego inputa
					}
				}

				$this->_fun['przypiszDoRekordu']->execute($data);

			} else {
				echo "TODO: brak zdefiniowanej funkcji '{$identifier}'";
				var_dump($identifier);
			}
		}
		else {
			echo "TODO: '" . $xml->getName() . "' ...";
		}
	}

	public function getCapabilitiesAction() {
		echo '<?xml version="1.0" encoding="UTF-8"?>';
		?>
<wps:Capabilities xmlns:wps="http://www.opengis.net/wps/1.0.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:lang="en" service="WPS" version="1.0.0" xsi:schemaLocation="http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd">
    <ows:ServiceIdentification>
        <ows:Title>Prototype GeoServer WPS</ows:Title>
        <ows:Abstract />
        <ows:Keywords>
            <ows:Keyword>wps</ows:Keyword>
            <ows:Keyword>geoserver</ows:Keyword>
        </ows:Keywords>
        <ows:ServiceType>WPS</ows:ServiceType>
        <ows:ServiceTypeVersion>1.0.0</ows:ServiceTypeVersion>
        <ows:Fees>NONE</ows:Fees>
        <ows:AccessConstraints>NONE</ows:AccessConstraints>
    </ows:ServiceIdentification>
    <ows:ServiceProvider>
        <ows:ProviderName>GeoServer</ows:ProviderName>
        <ows:ProviderSite />
        <ows:ServiceContact />
    </ows:ServiceProvider>
    <ows:OperationsMetadata>
        <ows:Operation name="GetCapabilities">
            <ows:DCP>
                <ows:HTTP>
                    <ows:Get xlink:href="http://demo.opengeo.org:80/geoserver/wps" />
                    <ows:Post xlink:href="http://demo.opengeo.org:80/geoserver/wps" />
                </ows:HTTP>
            </ows:DCP>
        </ows:Operation>
        <ows:Operation name="DescribeProcess">
            <ows:DCP>
                <ows:HTTP>
                    <ows:Get xlink:href="http://demo.opengeo.org:80/geoserver/wps" />
                    <ows:Post xlink:href="http://demo.opengeo.org:80/geoserver/wps" />
                </ows:HTTP>
            </ows:DCP>
        </ows:Operation>
        <ows:Operation name="Execute">
            <ows:DCP>
                <ows:HTTP>
                    <ows:Get xlink:href="http://demo.opengeo.org:80/geoserver/wps" />
                    <ows:Post xlink:href="http://demo.opengeo.org:80/geoserver/wps" />
                </ows:HTTP>
            </ows:DCP>
        </ows:Operation>
    </ows:OperationsMetadata>
    <wps:ProcessOfferings>
			<?php foreach($this->_fun as $kFun => $vFun) : ?>
        <wps:Process wps:processVersion="1.0.0">
            <ows:Identifier><?php echo $kFun; ?></ows:Identifier>
            <ows:Title><?php echo $vFun->title; ?></ows:Title>
            <ows:Abstract><?php echo $vFun->description; ?></ows:Abstract>
        </wps:Process>
			<?php endforeach; ?>
    </wps:ProcessOfferings>
    <wps:Languages>
        <wps:Default>
            <ows:Language>en-US</ows:Language>
        </wps:Default>
        <wps:Supported>
            <ows:Language>en-US</ows:Language>
        </wps:Supported>
    </wps:Languages>
</wps:Capabilities>

		<?php
	}

	public function describeProcessAction($args) {
		// TODO: xml z opiesem procese $args['IDENTIFIER']
		/**
		 * should work like JTS:densify - geom field (map object) and integer field (record ID)
		 * http://openlayers.org/dev/examples/proxy.cgi?url=http%3A%2F%2Fdemo.opengeo.org%2Fgeoserver%2Fwps%3FSERVICE%3DWPS%26REQUEST%3DDescribeProcess%26VERSION%3D1.0.0%26IDENTIFIER%3DJTS%253Adensify
		 * http://demo.opengeo.org/geoserver/wps?SERVICE=WPS&REQUEST=DescribeProcess&VERSION=1.0.0&IDENTIFIER=JTS%3Adensify
		 */
		echo '<?xml version="1.0" encoding="UTF-8"?>';

		if (array_key_exists($args['IDENTIFIER'], $this->_fun)) {
			$identifier = $this->_fun[$args['IDENTIFIER']];
		?>
<wps:ProcessDescriptions xmlns:wps="http://www.opengis.net/wps/1.0.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:lang="en" service="WPS" version="1.0.0" xsi:schemaLocation="http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd">
  <ProcessDescription wps:processVersion="1.0.0" statusSupported="true" storeSupported="true">
    <ows:Identifier><?php echo $args['IDENTIFIER']; ?></ows:Identifier>
    <ows:Title><?php echo $identifier->title; ?></ows:Title>
    <ows:Abstract><?php echo $identifier->description; ?></ows:Abstract>
    <DataInputs>
			<?php foreach ($identifier->dataInputs as $kInput => $vInput) : ?>
				<Input maxOccurs="1" minOccurs="1">
					<ows:Identifier><?php echo $kInput; ?></ows:Identifier>
					<ows:Title><?php echo $vInput->title; ?></ows:Title>
					<ows:Abstract><?php echo $vInput->description; ?></ows:Abstract>
					<?php if ($vInput->type == 'geom') : ?>
						<ComplexData>
							<Default>
								<Format>
									<MimeType>text/xml; subtype=gml/3.1.1</MimeType>
								</Format>
							</Default>
							<Supported>
								<Format>
									<MimeType>text/xml; subtype=gml/3.1.1</MimeType>
								</Format>
								<Format>
									<MimeType>text/xml; subtype=gml/2.1.2</MimeType>
								</Format>
								<Format>
									<MimeType>application/wkt</MimeType>
								</Format>
								<Format>
									<MimeType>application/gml-3.1.1</MimeType>
								</Format>
								<Format>
									<MimeType>application/gml-2.1.2</MimeType>
								</Format>
							</Supported>
						</ComplexData>
					<?php elseif ($vInput->type == 'integer') : ?>
						<LiteralData>
							<ows:DataType>xs:integer</ows:DataType>
							<ows:AnyValue />
						</LiteralData>
					<?php else : ?>

					<?php endif; ?>
				</Input>
			<?php endforeach; ?>
    </DataInputs>
    <ProcessOutputs>
      <Output>
        <ows:Identifier>result</ows:Identifier>
        <ows:Title>result</ows:Title>
        <ComplexOutput>
          <Default>
            <Format>
              <MimeType>text/xml; subtype=gml/3.1.1</MimeType>
            </Format>
          </Default>
          <Supported>
            <Format>
              <MimeType>text/xml; subtype=gml/3.1.1</MimeType>
            </Format>
            <Format>
              <MimeType>text/xml; subtype=gml/2.1.2</MimeType>
            </Format>
            <Format>
              <MimeType>application/wkt</MimeType>
            </Format>
            <Format>
              <MimeType>application/gml-3.1.1</MimeType>
            </Format>
            <Format>
              <MimeType>application/gml-2.1.2</MimeType>
            </Format>
          </Supported>
        </ComplexOutput>
      </Output>
    </ProcessOutputs>
  </ProcessDescription>
</wps:ProcessDescriptions>
			<?php
		} else {
			echo 'TODO: brak funkcji';
		}
	}

}
