// This file contains the api for Flamingo. It consists of 3 parts:
// 1. The private attributes and methods.
// 2. The public callback methods.
// 3. The public "call" methods.

//---------------------------------------------------

// Part 1. Internal API
// Don't modify or override these attributes and methods, as that may damage the working of the Flamingo api.

var identifyResult = null;
var nrConfigsComplete = 0;

// *** dummies ***
function dispatchEventJS() {}

function map_onMouseDown() {}
function map_onMouseMove() {}
function map_onMouseUp() {}
function map_onMouseWheel() {}

function mapOverview_onMouseDown() {}
function mapOverview_onMouseMove() {}
function mapOverview_onMouseUp() {}
function mapOverview_onMouseWheel() {}

//*** end dummies ***

function mapOverview_onReallyChangedExtent(map, extent0) {
    var app = document.getElementById("mainFlamingoEmbed");
    var overview = null;
    if (typeof Ext != "undefined") {
      overview = Ext.fly('overviewFlamingoEmbed');
    }

    if(typeof Ext == "undefined" || !(overview.getHeight()==0 && overview.getWidth()==0)) {
      var extent1 = app.call("map", "getExtent");
      if (!extentsAreEqual(extent0, extent1)) {
          app.call("map", "moveToExtent", extent0, 0, 0);
      }
  }
}

function map_onReallyChangedExtent(map, extent0) {
  var app = document.getElementById("overviewFlamingoEmbed");

    var overview = null;
    if (typeof Ext != "undefined") {
      overview = Ext.fly('overviewFlamingoEmbed');
    }

    if(typeof Ext == "undefined" || !(overview.getHeight()==0 && overview.getWidth()==0)) {
      var extent1 = app.call("mapOverview", "getExtent");
      if (!extentsAreEqual(extent0, extent1)) {
          app.call("mapOverview", "moveToExtent", extent0, 0, 0);
          //alert("extent0 = " + extent0.minx + "," + extent0.miny + "," + extent0.maxx + "," + extent0.maxy);
      }
    }
}

function extentsAreEqual(extent0, extent1) {
  if(extent0 === undefined || extent1 === undefined) {
    return false;
  }
  else if ((extent0.minx == extent1.minx) && (extent0.miny == extent1.miny)
     && (extent0.maxx == extent1.maxx) && (extent0.maxy == extent1.maxy)) {
        return true;
    }
    return false;
}

function map_onError(map, type, error, layer) {
    console.warn("ONERROR " + type + " " + error);
}

function map_onIdentifyComplete(map) {

    if (identifyResult == null) {
        identifyResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        identifyResult += "<IdentifyResult xmlns=\"http://www.vrom.nl/ro-online-identify-result\">\n";
        identifyResult += "<layerResults>\n";
    }

    identifyResult += "</layerResults>\n</IdentifyResult>\n";
    var localSoTemp = identifyResult;
    identifyResult = null;
    onIdentify(localSoTemp);
}

function map_onIdentifyData(map, layer, data, extent, numLayersIdentified, numLayersTotal) {
    if (identifyResult == null) {
        identifyResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        identifyResult += "<IdentifyResult xmlns=\"http://www.vrom.nl/ro-online-identify-result\">\n";
        identifyResult += "<layerResults>\n";
    }

    var layerName = layer.substr(layer.indexOf("_") + 1);
    identifyResult += "<LayerResult>\n<Layer name=\"" + layerName + "\"/>\n<results>\n";

    var features = null;
    var feature = null;
    for (var sublayer in data) {
        features = data[sublayer];
        identifyResult += "<Result layerName=\"" + sublayer + "\">\n";
        identifyResult += "<NumFeatures>" + features.length + "</NumFeatures>\n";

        for (var i = 0; i < features.length; i++) {
            feature = features[i];
            identifyResult += parseFeature(feature);
        }
        identifyResult += "</Result>\n";
    }
    identifyResult += "</results>\n</LayerResult>\n";
}

function map_onMaptipFeatures(map, layer, data) {
  var maptipResult = [];

    for (var oPlan in data) {
        var features = data[oPlan];

        for (var i = 0; i < features.length; i++) {
            maptipResult[maptipResult.length] = features[i]['plangebied'];
        }
    }
    onMaptipFeatures(maptipResult);
}

function parseFeature(feature, properties) {
    var s = "";
    s += "<Feature>\n<properties>\n";
    var propArray = null;
    if (properties != null) {
        propArray = properties.split(",");
    }
    for (var propertyName in feature) {
        var propFound = true;
        if (propArray != null) {
            propFound = false;
            for (var p=0; p < propArray.length; p++) {
                if (propArray[p].toUpperCase() == propertyName.toUpperCase()) {
                    propFound = true;
                    break;
                }
            }
        }
        if (propFound) {
            if ((feature[propertyName] == null) || (feature[propertyName] == "null")) {
                s += "<Property name=\"" + propertyName + "\"/>\n";
            } else {
                var propVal = feature[propertyName];
                s += "<Property name=\"" + propertyName + "\">\n";
                if (typeof(feature[propertyName]) == "string") {
                    s += "<Value>" + xmlEncode(feature[propertyName]) + "</Value>\n";
                } else if (feature[propertyName]["featureCollection"] != "true") {
                    s += parseFeature(feature[propertyName]);
                } else {
                    for (var subfeature in feature[propertyName]) {
                        if (subfeature != "featureCollection") {
                            s += parseFeature(feature[propertyName][subfeature]);
                        }
                    }
                }
                s += "</Property>\n";
            }
        }
    }
    s += "</properties>\n</Feature>\n";
    return s;
}

function xmlEncode(string) {
  return string.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace("'",'&apos;').replace('"','&quot;');
}

function map_onInit(map) {
    onInit();
}

function map_onResize(map) {
    //alert("ONRESIZE");
}

function map_onUpdateProgress(map, numLayersUpdated, numLayersTotal) {
    if (numLayersTotal > 0) {
        var percentage = 100 * numLayersUpdated / numLayersTotal;
        //alert("ONUPDATEPROGRESS " + percentage);
    }
}

//function flamingo_onConfigProgress(map, nrloaded, nrtotal, rest, nrconfigs) {
//    alert("map_onConfigProgress, nrloaded = " + nrloaded + " nrtotal = " + nrtotal + " rest = " + rest + " nrconfigs = " + nrconfigs);
//}

function flamingo_onInit() {
    //alert("FLAMINGO ONINIT");
}

function flamingo_onConfigComplete() {
    nrConfigsComplete = nrConfigsComplete + 1;
    //alert("nrConfigsComplete = " + nrConfigsComplete);
    if (nrConfigsComplete == 2) {
        onFlamingoInitialized();
    }
}

function filterButton_onButtonPress() {
    openFilterWindow();
}

function filterButton_onButtonRelease() {
    closeFilterWindow();
}

function planTreeButton_onButtonPress() {
    openPlanTreeWindow();
}

function planTreeButton_onButtonRelease() {
    closePlanTreeWindow();
}

//function flamingo_onConfig(File) {
//    alert("FLAMINGO onConfig, file=" + File);
//}

/** ---------------------------------------------------
Part 2. Callback Methods
Override and implement these callback methods to receive events from Flamingo.

function onInit() {}

function onIdentify(identifyResult) {}

function onMaptipFeatures(maptipResult) {
  alert(maptipResult);
}

function onFlamingoInitialized() {}

function openFilterWindow() {
    alert("filter window open");
}

function closeFilterWindow() {
    alert("filter window close");
}

function openPlanTreeWindow() {
    alert("plantree window open");
}

function closePlanTreeWindow() {
    alert("plantree window close");
}

------------------------------------------------- */

// Part 3. Methods
// Call these methods to influence the state of Flamingo. Don't modify or override them.

function moveToCoord(x, y) {
    moveToExtent(x - 1000, y - 1000, x + 1000, y + 1000);
}

function moveToExtent(minX, minY, maxX, maxY) {
    var extent = new Object();
    extent.minx = minX;
    extent.miny = minY;
    extent.maxx = maxX;
    extent.maxy = maxY;
    var app = document.getElementById("mainFlamingoEmbed");

    if(app) {
      app.call("map", "moveToExtent", extent, 0, 0);
  }
}

function getExtent() {
    var app = document.getElementById("mainFlamingoEmbed");
    if (app) {
        return app.call("map", "getCurrentExtent");
    }
    return null;
}

function setLocation(x, y, name) {
    var extent = new Object();
    extent.minx = x;
    extent.miny = y;
    extent.maxx = x;
    extent.maxy = y;
    extent.name = name;
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) { app.call("map", "identify", extent); }
}

function removeLocation() {
    var app = document.getElementById("mainFlamingoEmbed");
    app.call("locations", "removeLocation");
}

function setLayersVisible(playerName, mapName, layerNamesString, visible) {
    var app = document.getElementById(playerName);
    if (app) {
      var layerNames = layerNamesString.split(",");
      for (var i = 0; i < layerNames.length; i++) {
          app.call(mapName + "_" + layerNames[i], "setVisible", visible);
      }
    }
}

function addFilter(name, filter, update) {
    var app = document.getElementById("mainFlamingoEmbed");
  if(app) { app.call("filterLayer", "addFilter", name, filter, update); }
    app = document.getElementById("overviewFlamingoEmbed");
    if(app) { app.call("filterLayer", "addFilter", name, filter, update); }
}

function removeFilter(name, update) {
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) {app.call("filterLayer", "removeFilter", name, update); }
    app = document.getElementById("overviewFlamingoEmbed");
    if(app) { app.call("filterLayer", "removeFilter", name, update); }
}

function highlightFeature(wmsUrl, sldServletUrl, featureTypeName, propertyName, value, alpha, name) {
    var app = document.getElementById("mainFlamingoEmbed");
    if (app) { app.call("highlightLayer", "highlightFeature", wmsUrl, sldServletUrl, featureTypeName, propertyName, value, alpha, name); }
}

function highlightLayerVVP(wmsUrl, layerName, alpha, name) {
    var app = document.getElementById("mainFlamingoEmbed");
    if (app) { app.call("highlightLayer", "highlightLayerVVP", wmsUrl, layerName, alpha, name); }
}

function resetFeature(name) {
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) { app.call("highlightLayer", "resetFeature", name); }
}

/**
* Highlights the object in the supplied layer, not the objects in sublayers
* @wmsUrl url of the wms serving nice maps of vormvrije plannen
* @layername name of the layer to be highlighted. The object within the layer is highlighted, not the objects in sublayers
* @alpha transparency (100=opaque, 0=transparent
* @name optional, identification of the lighlight, to be used with resetFeature() to remove the highlight identified by name
**/
function highlightLayerVVvP(wmsUrl, layername, alpha, name ) {
    var app = document.getElementById("mainFlamingoEmbed");
    if (app) { app.call("highlightLayer", "highlightLayerVVvP", wmsUrl, layername, alpha, name); }
}

/**
* Draws a specific wms layer within the layer for objects in vormvrije plannen
* @layername name of layer to be drawn. When zero-length string vvvpLayer is "cleared"
**/
function drawLayerVVvP(layername ) {
    var app = document.getElementById("mainFlamingoEmbed");
    if (app) {
      if  (layername == "" || layername == null) {
        app.call("map_" + "vvvpLayer", "setVisible", false);
      }
      else {
        app.call("map_" + "vvvpLayer", "setLayers", layername);
        app.call("map_" + "vvvpLayer", "setQueryLayers", layername);
        app.call("map_" + "vvvpLayer", "setVisible", true);
      }
      app.call("map_" + "vvvpLayer", "update");
    }
}

function showEnkelBestemmingHoofdgroepen(bestemmingshoofdgroepen) {
    var app = document.getElementById("mainFlamingoEmbed");
    var sldParam = "";
    if (bestemmingshoofdgroepen != null && bestemmingshoofdgroepen != "") {
        sldParam = "bestemmingshoofdgroep=" + bestemmingshoofdgroepen;
    } else {
        sldParam = "bestemmingshoofdgroep=xyz-geen-xyz";
    }
    if(app) {
      app.call("map_bpHoofdgroepenLayer", "setSLDparam", sldParam);
    }
}

function showDubbelBestemmingen(hoofdDubbelbestemmingen) {
    var sldParam = "";
    var groepen = "";
    var functies = "";
    var bestemmingArray = [];
    if (hoofdDubbelbestemmingen != undefined && hoofdDubbelbestemmingen != "") {
      bestemmingArray = hoofdDubbelbestemmingen.split(",");
    }
    for (var i=0; i<bestemmingArray.length; i++) {
      if (bestemmingArray[i].toLowerCase() == "leiding") {
        groepen += ",leiding";
        functies += ",kabel";
      }
      else if (bestemmingArray[i].toLowerCase() == "waarde") {
        groepen += ",waarde";
        functies += ",+++";
      }
      else if (bestemmingArray[i].toLowerCase() == "onbekend") {
        groepen += ",null";
        functies += ",null";
      }
      else if (bestemmingArray[i].toLowerCase() == "waterstaat") {
        groepen += ",waterstaat";
      }
      else if (bestemmingArray[i].toLowerCase() == "waterkering") {
        functies += ",waterkeren";
      }
      else if (bestemmingArray[i].toLowerCase() == "waterverkeer") {
        functies += ",waterverkeer";
      }
      else if (bestemmingArray[i].toLowerCase() == "aanvliegroute") {
        functies += ",lucht";
      }
      else if (bestemmingArray[i].toLowerCase() == "archeologie-cultuur") {
        functies += ",cultuur";
      }
      else if (bestemmingArray[i].toLowerCase() == "stads-dorpsgezicht") {
        functies += ",stads-/dorpsgezicht";
      }
      else if (bestemmingArray[i].toLowerCase() == "geluidszone") {
        functies += ",geluidzonering";
      }
      else if (bestemmingArray[i].toLowerCase() == "militaire-voorzieningen") {
        functies += ",militaire voorzieningen";
      }
      else if (bestemmingArray[i].toLowerCase() == "straalpad") {
        functies += ",straalpad";
      }
    }
    var groepen_len = groepen.length;
    var functies_len = functies.length;

    // Filter op een niet bestaande groep als geen enkele groep of
    // functie is geselecteerd om te voorkomen dat er invalid sld gegenereerd wordt.
    // Flamingo weet nl. niet dat een lege string voor sldParam betekent dat
    // er niets geselecteerd wordt.
    if (groepen_len == 0 && functies_len == 0) {
      groepen = "xyz-geen-xyz";
      groepen_len = groepen.length;
    }

    if (groepen_len > 0) {
      sldParam = "dubbelbestemmingshoofdgroep=" + groepen.substr(1);
    }
    if (groepen_len > 0 && functies_len > 0) {
      sldParam += "&";
    }
    if (functies_len > 0) {
      sldParam += "hoofdfunctie=" + functies.substr(1);
    }
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) {
      app.call("map_bpDubbelbestemmingLayer", "setSLDparam", sldParam);
    }
}

function setAlpha(layer, value) {
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) {
      app.call("map_" + layer, "setAlpha", value);
    }
}
/**
* @layer name of layer where maptip should be switched on/off
* @onOff boolean indicating if maptip must be switched on (=true) or off (=false)
*/
function enableMaptip(layer, onOff) {
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) {
      app.call("map_" + layer, "enableMaptip", onOff);
    }
}

function releaseFilterButton() {
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) {
      app.call("filterButton", "onHide");
    }
}

/** Releases the planTree button, to be called when plantree window is closed
*
**/
function releasePlanTreeButton() {
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) {
      app.call("planTreeButton", "onHide");
    }
}

/**
* Sets the visibility of a button
* @but id of button in Flamingo config, e.g. "filterButton" or "planTreeButton"
* @vis boolean if button should be made visible (=true) or invisible (=false)
**/
function setButtonVisible(but, vis) {
    var app = document.getElementById("mainFlamingoEmbed");
    if(app) {
      app.call(but, "setVisible", vis);
    }
}

