//fred 2010
var format;
var formatWMTS;

var xsltMetadata = "";

$(document).ready(function() {

    OpenLayers.ProxyHost = "../cgi-bin/proxy.php?url=";
    //alert(OpenLayers.ProxyHost);

    formatWMTS = new OpenLayers.Format.WMTSCapabilities({
        /**
         * This particular service is not in compliance with the WMTS spec and
         * is providing coordinates in y, x order regardless of the CRS.  To
         * work around this, we can provide the format a table of CRS URN that
         * should be considered y, x order.  These will extend the defaults on
         * the format.
         */
        yx: {
            "urn:ogc:def:crs:EPSG::900913": true
        }
    });
	
    $.get('/mosy/theme/mosy/resources/websig/metadata/metadata.js', null,
            function(data){
                    xsltMetadata = data;						
            },
            'text'
    );	
		

    $("#table-wms-results").on("click", "span", function(event) {
        var url = $(this).attr('data-url');
        var version = $(this).attr('data-service-version');
        var layer_name = $(this).attr('data-layer-name');
        var layer_title = $(this).attr('data-layer-title') || $(this).attr('data-layer-name');
        var layer_crs = $(this).attr('data-layer-crs');
        var service_type = $(this).attr('data-service-type');

        if (service_type == "wms") {
            var wms = addWMSLayer(url, osmaps, layer_name, 'image/png', true, layer_title, layer_crs, false, version);
            //layerControl.addOverlay(wms, layer_title);
            layerControl.addOverlay(wms, layer_title, {groupName: "WMS", expanded: true});
        } else if (service_type == "wmts") {
            var tilematrixset = "EPSG:900913";

            var wmts = addWMTSLayer(url, osmaps, layer_name, tilematrixset, 'image/png', true, layer_title, version);
            layerControl.addOverlay(wms, layer_name, {groupName: "WMTS", expanded: true});
        } else if (service_type == "wfs") {
			var featureNS = $(this).attr('data-layer-namespace');
		
			var wfs = addWFSLayer(url, osmaps, layer_title, featureNS, layer_name, layer_crs, version);						
			layerControl.addOverlay(wfs, layer_title, {groupName: "WFS", expanded: true});
		}

    });


    // conf wms window
    $("#mmc_serviceType").on("change", function(event) {
        var svc_type = $("#mmc_serviceType").val();
        if (svc_type === "wms") {
            $("#mmc_serviceVersion").empty();
            $("#mmc_serviceVersion").append(new Option("1.1.1", "1.1.1", true, true));
            $("#mmc_serviceVersion").append(new Option("1.3.0", "1.3.0"));
        } else if (svc_type === "wmts") {
            $("#mmc_serviceVersion").empty();
            $("#mmc_serviceVersion").append(new Option("1.0.0", "1.0.0"));
        } else if (svc_type === "wfs") {
            $("#mmc_serviceVersion").empty();
            //$("#mmc_serviceVersion").append(new Option("1.0.0", "1.0.0"));
            $("#mmc_serviceVersion").append(new Option("1.1.0", "1.1.0"));
            $("#mmc_serviceVersion").append(new Option("2.0.0", "2.0.0"));
        }
    });
    $("#mmc_serviceType").trigger( "change" );
});


function getWMSCapabilities(version, url) {

    var xhr = OpenLayers.Request.GET({
        url: url,
        params: {
            SERVICE: "WMS",
            VERSION: version || "1.3.0",
            REQUEST: "GetCapabilities"
        },
        success: function(request) {			
            $('#table-wms-results').empty();
            $('#div-wms-results-glass').toggle();

            var doc = request.responseXML;
            if (!doc || !doc.documentElement) {
                doc = request.responseText;
            }

            var readCapabilities = function(doc, version) {
                var caps = null;

                var format = new OpenLayers.Format.WMSCapabilities({
                    version: version,
                    profile: "INSPIRE",
                    allowFallback: true
                });

                try {
                    caps = format.read(doc);
                } catch (err) {
                }

                return caps;
            }

            var capabilities = null;

            capabilities = readCapabilities(doc, version);
            if (capabilities == null && version == '1.3.0') {
                capabilities = readCapabilities(doc, "1.1.1");
            }

            if (capabilities && capabilities.capability && capabilities.capability.layers) {
                if (capabilities.capability.inspire && capabilities.capability.inspire.metadataUrl) {
                    $("#mmc_btnGetMetadata").data("action", capabilities.capability.inspire.metadataUrl.url);
					//$("#mmc_btnGetMetadata").data("action", "http://idealg.ccdr-alg.pt/IDE/Pages/Metadata.aspx?uuid=idealg_ccdr.alg_000962svc&catalog=IDEAlg");
				}

                var layers = capabilities.capability.layers;
                for (var i = 0; i < layers.length; i++) {
                    var layer = layers[i];

                    if (layer.nestedLayers == null || layer.nestedLayers.length == 0) {
                        //$("#table-wms-results", _parentId).append(_createWMSLayerRecord(capabilities.version, capabilities.capability, layers[i]));
                        $("#table-wms-results").append(createLayerRecord(capabilities.version, capabilities.capability, layers[i]));
                    }
                }

                //$('#div-wms-results', _parentId).show();
            } else {
                //$('.msg-error', '#div-wms-error').html($.T('Service not found or unknown response'));
                //$('#div-wms-error', _parentId).show();

                console.log("...error...");
            }

            HideLoading('#addLayerCatalog');
        },
        failure: function() {
            console.log("...error...");
            HideLoading('#addLayerCatalog');
        }
    });

    ShowLoading('#addLayerCatalog', true, xhr);
}

function getWMTSCapabilities(version, url) {


    OpenLayers.Request.GET({
        url: url,
        params: {
            SERVICE: "WMTS",
            VERSION: version || "1.0.0",
            REQUEST: "GetCapabilities"
        },
        success: function(request) {
            $('#table-wms-results').empty();
            $('#div-wms-results-glass').toggle();

            var doc = request.responseXML;
            if (!doc || !doc.documentElement) {
                doc = request.responseText;
            }
            var capabilities = formatWMTS.read(doc);
            var layers = capabilities.contents.layers;

            for (var i = 0; i < layers.length; i++) {
                $("#table-wms-results").append(createWMTSLayerRecord(url, version || "1.0.0", layers[i]));
            }
        },
        failure: function() {
            alert("Trouble getting capabilities doc");
            OpenLayers.Console.error.apply(OpenLayers.Console, arguments);
        }
    });
}

function getWFSCapabilities(version, url) {

    var xhr = OpenLayers.Request.GET({
        url: url,
        params: {
            SERVICE: "WFS",
            VERSION: version || "1.1.0",
            REQUEST: "GetCapabilities"
        },
        success: function(request) {
            $('#table-wms-results').empty();
            $('#div-wms-results-glass').toggle();

            var doc = request.responseXML;
            if (!doc || !doc.documentElement) {
                doc = request.responseText;
            }

            var readCapabilities = function(doc, version) {
                var caps = null;

                var format = new OpenLayers.Format.WFSCapabilities({
                    version: version,
                     profile: "INSPIRE",
                     allowFallback: true
                });

                try {
                    caps = format.read(doc);
                } catch (err) {
                }

                return caps;
            }

            var capabilities = null;

            capabilities = readCapabilities(doc, version);
            if (capabilities == null && version == '1.1.0') {
                capabilities = readCapabilities(doc, "1.0.0");
            }

            if (capabilities && capabilities.featureTypeList && capabilities.featureTypeList.featureTypes) {
                if (capabilities.operationsMetadata.ExtendedCapabilities && capabilities.operationsMetadata.ExtendedCapabilities.inspire && capabilities.operationsMetadata.ExtendedCapabilities.inspire.metadataUrl) {
                    $("#mmc_btnGetMetadata").data("action", capabilities.operationsMetadata.ExtendedCapabilities.inspire.metadataUrl.url);
					//$("#mmc_btnGetMetadata").data("action", "http://idealg.ccdr-alg.pt/IDE/Pages/Metadata.aspx?uuid=idealg_ccdr.alg_000962svc&catalog=IDEAlg");
				}
				
                var layers = capabilities.featureTypeList.featureTypes;
                for (var i = 0; i < layers.length; i++) {
                    var layer = layers[i];					
					$("#table-wms-results").append(createWFSLayerRecord(capabilities.version, capabilities, layers[i]));
                }

                //$('#div-wms-results', _parentId).show();
            } else {
                //$('.msg-error', '#div-wms-error').html($.T('Service not found or unknown response'));
                //$('#div-wms-error', _parentId).show();

                console.log("...error...");
            }

            HideLoading('#addLayerCatalog');
        },
        failure: function() {
            console.log("...error...");
            HideLoading('#addLayerCatalog');
        }
    });

    ShowLoading('#addLayerCatalog', true, xhr);
}

function createLayerRecord(version, capability, layer) {
    var snippet = "<tr><td>";
    var options = "";
    var links = "";

    var supported = false;
    var crs = "";

    if (layer.name && layer.name != "") {
        var req = capability.request.getmap.get.href;

        $.each(layer.srs, function(key, value) {
            if (key == "EPSG:3857") {
                supported = true;
                crs = key;
                return false;
            }
        });
        if (!supported) {
            $.each(layer.srs, function(key, value) {
                if (key == "EPSG:900913") {
                    supported = true;
                    crs = key;
                    return false;
                }
            });
        }

        if (supported) {
            links += '<span class="btn btn-primary btn-sm" data-service-type="wms" data-service-version="' + version + '" data-url="' + req + '" data-layer-name="' + layer.name  + '" data-layer-title="' + layer.title + '" data-layer-crs="' + crs + '" >Add to map</span>';
        } else {
            links += '<div class="alert alert-danger">Sistema de coordenadas não suportado</div>';
        }
    }

    title2 = '<a class="a-record" title="' + layer.title + '" href="#">' + layer.title + '</a>';
    snippet += '<h5>' + title2 + '</h5>';
    snippet += '<h5>' + layer.abstract + '</h5>';
    
    if (layer.publisher !== undefined) {
        snippet += '<em><strong>Publisher</strong>: ' + layer.publisher + '</em><br/>';
    }
    if (layer.date !== undefined) {
        snippet += '<small><strong>Date</strong>: ' + layer.date + '</small><br/>';
    }

    snippet += options;
    snippet += links;
    snippet += '</td></tr>';

    return snippet;
}

function createWMTSLayerRecord(url, version, layer) {
    var snippet = "<tr><td>";
    var links = "";

    if (layer.identifier && layer.identifier != "") {
        var req = url;

        links += '<span class="btn btn-primary btn-sm" data-service-type="wmts" data-service-version="' + version + '" data-url="' + req + '" data-layer-name="' + layer.identifier  + '" data-layer-title="' + layer.title + '" >Add to map</span>';
    }

    title2 = '<a class="a-record" title="' + layer.title + '" href="#">' + layer.title + '</a>';
    snippet += '<h5>' + title2 + '</h5>';
    snippet += links;
    snippet += '</td></tr>';

    return snippet;
}

function createWFSLayerRecord (version, capabilities, layer) {
	var snippet = '<tr><td>';
	var options = '';
	var links = '';

	var crs = '';	
	
	if(layer.name && layer.name!='') {

		var url = '';
			
		if (version < '1.1.0') {
			url = capabilities.capability.request.getfeature.href.get;
		} else {
			url = capabilities.operationsMetadata.GetFeature.dcp.http.get[0].url;
		}
	
		crs = layer.srs;

		links += '<span class="btn btn-primary btn-sm" data-service-type="wfs" data-service-version="' + version + '" data-url="' + url + '" data-layer-namespace="' + layer.featureNS + '" data-layer-name="' + layer.name + '" data-layer-title="' + layer.title + '" data-layer-crs="' + crs + '" >Add to map</span>';
	}
	
	title2 = '<a class="a-record" title="' + layer.title + '" href="#">' + layer.title + '</a>';
	snippet += '<h5>' + title2 + '</h5>';
	snippet += options;
	snippet += links;
	snippet += '</td></tr>';
	
	return snippet;
}


function onEachFeature(feature, layer) {
    var popupContent = "<p>Popup!</p>";
    if (feature.properties && feature.properties.popup)
        popupContent = feature.properties.popup;
    layer.bindPopup(popupContent);
}


function addWMSLayer(url, map, layers, format, transparent, attribution, crs, tiled, version, styles) {

    var wms = null;

    var options = {
        layers: layers,
        version: version || '1.3.0',
        format: format,
        transparent: transparent,
        attribution: attribution
    };

    if (typeof styles !== 'undefined') {
        options["styles"] = styles;
    }

    if (tiled) {
        if (crs != null && crs != '') {
            options.crs = L.CRS[crs.replace(':', '')];
        }
        wms = L.tileLayer.wms(url, options);
    } else {
        options.tiled = false;
        var crsKey = parseFloat(options.version) >= 1.3 ? 'crs' : 'srs';
        options[crsKey] = crs;
        wms = L.imageOverlay.wms(url, options);
    }

    wms.ExtendedLayerControl = {
        removable: true,
        layerTypeName: "External WMS",
        layerTypeId: 100,
        haveProperties: true,
        activeIdentify: true
    }

    wms.addTo(map);

    return wms;
}

function addWMTSLayer(url, map, layers, tilematrixset, format, transparent, attribution, version) {
    var wmts = new L.TileLayer.WMTS(url, {
        layer: layers,
        tilematrixSet: tilematrixset,
        format: format,
        attribution: attribution
    });

    wmts.addTo(map);

    return wmts;
}

function addWFSLayer(url, map, title, featureNS, featureType, srsName, version) {
	var geoJsonUrl = url + "?service=WFS&version=" +  version + "&request=GetFeature&typeName=" + featureType + "&maxFeatures=2000&outputFormat=application/json&srsName=EPSG:4326";	
	//"http://localhost:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=teste_pol&maxFeatures=1000&outputFormat=application/json"
	
	var wfs = null;
		
	function loadGeoJson(data) {
		
		wfs = new L.geoJson(data, {
			/*style: function (feature) {
				return {color: feature.properties.color};
			},*/
			onEachFeature: function (feature, layer) {
				var html = "<div style='margin: 10px'>";				
				for (var prop in feature.properties) {
					html = html + prop + ": " + feature.properties[prop] + "</br>";
				}				
				html = html + "</div>";		
				layer.bindPopup(html);
			}
		});
		
		wfs.ExtendedLayerControl = {
			removable: true,
			layerTypeName: "External WFS",
			layerTypeId: -100,
			haveProperties: false,
			activeIdentify: false
		}
		
		wfs.addTo(map);
	};			
	
	$.ajax({ 
		url: OpenLayers.ProxyHost + encodeURIComponent(geoJsonUrl),
		dataType : 'json',
		async: false,
		success: loadGeoJson,
    });
	
	return wfs;		
}
