/*
  dojo includes
*/
dojo.require("esri.map");
dojo.require("esri.toolbars.draw");
dojo.require("esri.tasks.query");
dojo.require("esri.tasks.geometry");
dojo.require("esri.toolbars.navigation");

dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.Button");
dojo.require("dijit.Toolbar");
dojo.require("dijit.Dialog");

dojo.require("dijit.form.FilteringSelect");

dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojo.parser");  // scan page for widgets and instantiate them

dojo.require("dojo.fx");
dojo.require("dijit.ProgressBar");
dojo.require("dijit.form.Slider");

dojo.require("dojo.io.iframe");

dojo.require("dijits.overview.OverviewMap");
// 100% height Hack DoJo
dojo.require("dijit.dijit"); // optimize: load dijit layer
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");

dojo.require("dojo.dnd.Moveable");

/* Globale variablen 


*/

/* Namespacing globals */
var AquaWT = {
  map : null,
  imageParameters : null,
  navToolbar : null,
  drawToolbar : null,
  searchWS : null,
  searchCM : null,
  searchPC : null,
  fullExtent : null,
  dynaZoom : true,
  planArea : null
};

// Schaal waarop mag worden getekend.
var DRAW_SCALE_ALLOWED = 50000; 
var DRAW_SCALE_LEVEL = 3; // default

// Schaal waarop plangebied wordt getoond 
var SNAPSHOT_SCALE = 5000; // default
var SNAPSHOT_SCALE_LEVEL = 8; // default

// Minimaal planoppervlak in m2
var MIN_PLANAREA = 1; 

// MapLayer id voor kaartlaag
var TOETSLAYER = 'kaartlaag';

var INDEX_LIM = 0;

var TOP10NL = 'top10NL';

// MapLayer id
var ACHTERGROND = 'achterGrond';
var KADASTER = 'kadasterWMS'; 
var OVERVIEW = 'overviewLayer';

// Layer ids in MapLayer achtergrond
var INDEX_CM = 2;
var INDEX_WS = 0;
var INDEX_ZP = 3;

// Published keys
var LARGEST_INTERSECTED_WATERBOARD = "LIW";
var LARGEST_INTERSECTED_COMMUNITY = "LIC";
var LAYERS_WATERBOARD = "LWB";
var GEOMETRYINWATERSCHAP = "GIW";
var PROJECTEDREADY = "PRJ";
var ERROR_INTERSECTED_COMMUNITY = "ERROR_INT_CM";
var ERROR_INTERSECTED_WATERBOARD = "ERROR_INT_WS";
var CALCULATE_AREA_READY = "AREA_READY";

// Naam van de host
var serverHost = "http://www.dewatertoets.nl"; 
//var serverHost = "http://localhost"; 
//var serverHost = "http://watero"; 

// URLs van map- en geoprocessing services
var mapServer = serverHost === null ? "http://localhost" : serverHost;
var waterToetsService = mapServer + "/ArcGIS/rest/services/Watertoets/";
var achtergrondLayerUrl = waterToetsService + "achtergrond/MapServer";
var overviewLayerUrl = waterToetsService + "overview/MapServer";
var toetsLayerUrl = waterToetsService + "beperkingen/MapServer"
var topoLayerUrl = mapServer + "/ArcGIS/rest/services/TOPKaarten/MapServer";
//var topoLayerUrl = mapServer + "/ArcGIS/rest/services/Top10NL/TOP10NL/MapServer";
var kadasterLayerUrl = waterToetsService + "Kadaster/MapServer";
var geometryServiceUrl = waterToetsService + "Geometry/GeometryServer";
var gpServiceUrl = waterToetsService + "GPWatertoets/GPServer";
var gpUploaderUrl = waterToetsService + "UploadShape/GPServer";

// URLs van bestandslocaties en overige services

// Locatie van geuploade plangebieden
var uploadDataLocation = serverHost + "/aquagis/upload/data/";

// URL van de annotator service (gebruikt in SnapShotBuilder) 
var _annotatorBase = serverHost + "/imageannotator/";

// URL van de kadaster service (gebruikt in SearchGeocode) 
var kadasterUrl = "/kadaster/geocode.ashx";

var enableInfoWindow = true;

var visible = [];
var resizeTimer;
            
/*
  Initialisatie watertoets mapservices
*/
function initWatertoets(){
  AquaWT.fullExtent = new esri.geometry.Extent({
    xmin: 12500.0, //-2965.46778564454,
    ymin: 283750.0,
    xmax: 280000.0,//291644.427990723,
    ymax: 640000.0,//640937.50012207,
    spatialReference: {
      wkid: 28992
    }
  });
  
  
  esriConfig.defaults.map.panDuration = 1000; //time in milliseconds; default panDuration:250
  esriConfig.defaults.map.panRate = 100; //refresh rate of zoom animation; default panRate:25
  esriConfig.defaults.map.slider = {
    left: "10px",
    bottom: "10px",
    width: null,
    height: "200px"
  };
  
  
  AquaWT.map = new esri.Map("mapDiv", {
    //extent: AquaWT.fullExtent,
    slider: true,
    nav: false
  });
  AquaWT.map.level = 0;
  dojo.connect(AquaWT.map, "onLoad", initSearchFunctionality);
  
  // Om performance redenen is de overview map er destijds voor IE6 uitgelaten.
  // Indien de mapservice voor de overview eenvoudig wordt gehouden gaat het wel goed. 
  //if(dojo.isIE > 6 || !dojo.isIE) {
  //  dojo.connect(AquaWT.map, "onLayerAdd", initOverview);
  //}
  //else {
  //  console.log('ie ' + dojo.isIE);
  //}
  dojo.connect(AquaWT.map, "onExtentChange", extentChangeHandler);

  //set the image type to PNG8 of PNG32, note default is PNG8. PNG24 wordt in IE6 slecht weergegeven
  AquaWT.imageParameters = new esri.layers.ImageParameters();
  AquaWT.imageParameters.format = "png"; 
  AquaWT.imageParameters.transparent = true;

  // TODO: weghalen in definitieve versie!!
  if (mapServer === "http://localhost") {
    console.log("Lokale mapservices");
    
    //topoLayerUrl = mapServer + "/ArcGIS/rest/services/Top10NL/TOP10NL/MapServer";
    topoLayerUrl = mapServer + "/ArcGIS/rest/services/TOPKaarten/MapServer";

    var topoLayer = new esri.layers.ArcGISTiledMapServiceLayer(topoLayerUrl, {
      "imageParameters": AquaWT.imageParameters,
      id: TOP10NL
    });
    if (topoLayer.loaded) {
      buildScaleList(topoLayer)
    }
    else {
      dojo.connect(topoLayer, "onLoad", buildScaleList);
    }
    AquaWT.map.addLayer(topoLayer);

    var achtergrondLayer = new esri.layers.ArcGISDynamicMapServiceLayer(achtergrondLayerUrl, {
      "imageParameters": AquaWT.imageParameters,
      id: ACHTERGROND
    });
    /*if (achtergrondLayer.loaded) {
      buildScaleList(achtergrondLayer)
    }
    else {
      dojo.connect(achtergrondLayer, "onLoad", buildScaleList);
    }*/

    AquaWT.map.addLayer(achtergrondLayer);
  }
  else {
    var topoLayer = new esri.layers.ArcGISTiledMapServiceLayer(topoLayerUrl, {
      "imageParameters": AquaWT.imageParameters,
      id: TOP10NL
    });
    if (topoLayer.loaded) {
      buildScaleList(topoLayer)
    }
    else {
      dojo.connect(topoLayer, "onLoad", buildScaleList);
    }
    AquaWT.map.addLayer(topoLayer);

    var achtergrondLayer = new esri.layers.ArcGISDynamicMapServiceLayer(achtergrondLayerUrl, {
      "imageParameters": AquaWT.imageParameters,
      id: ACHTERGROND
    });
    //achtergrondLayer.setOpacity(0.8);
    AquaWT.map.addLayer(achtergrondLayer);
  }

  // Kadaster lagen
  console.log('Laad kadaster laag');
  var kadasterLayer = new esri.layers.ArcGISDynamicMapServiceLayer(kadasterLayerUrl, {
    "imageParameters": AquaWT.imageParameters, 
    id : KADASTER
  });
  kadasterLayer.setOpacity(0.8);

  if (kadasterLayer.loaded) {
    AquaWT.map.addLayer(kadasterLayer);
  }
  else {
    dojo.connect(kadasterLayer, "onLoad", function() {
      AquaWT.map.addLayer(kadasterLayer);
    });
  }

  // Beperkingen kaartlagen
  console.log('Laad toetskaartlaag');
  var toetsLayer = new esri.layers.ArcGISDynamicMapServiceLayer(toetsLayerUrl, {
    "imageParameters": AquaWT.imageParameters, 
    id : TOETSLAYER
  });
  toetsLayer.setOpacity(0.8);
  if (toetsLayer.loaded) {
    toetsLayer.setVisibleLayers([]);
  }
  else {
    dojo.connect(toetsLayer, "onLoad", function() {toetsLayer.setVisibleLayers([])});
  }
  AquaWT.map.addLayer(toetsLayer);

  // Maak infowindow iets kleiner  
  AquaWT.map.infoWindow.resize(220,150);
}


/***************************************************************************************************************************
 * Overview functionaliteit
 */
var overviewMapDijit = null;
var createOverviewMap = null;
function initOverview() {
  var overviewLayer = new esri.layers.ArcGISTiledMapServiceLayer(overviewLayerUrl, {
    "imageParameters": AquaWT.imageParameters,    
    id: OVERVIEW
  });

  createOverviewMap = function() {
    overviewMapDijit = new dijits.overview.OverviewMap({
      map: AquaWT.map,
      id: 'overview_id',
      baseLayer: overviewLayer,
      width: 140,
      height: 140,
      attachTo: "top-right",
      expandFactor: 2.0
    });
    overviewMapDijit.startup();
  };

  if (overviewLayer.loaded) {
    createOverviewMap();
  }
  else {
    dojo.connect(overviewLayer, "onLoad", createOverviewMap);
  }
}

function updateOverview() {
  //alert('Overview');
  if(AquaWT.map === null) return false;

  console.log(AquaWT.map.getLevel()); 
  
  if(AquaWT.map.getLevel() >= 3) {
    initOverview();
  }
  else {
    if (overviewMapDijit !== null) {
      try {
        overviewMapDijit.destroy();
        overviewMapDijit = null;
      }
      catch(e) {
        
      }
    }
  }
  
}

//*****************************************************************************************************************************
function initResizer(){
  dojo.connect(window, 'onresize', function(){
    resizeMap();
  });
}

//Handle resize of browser
function resizeMap() {
  //console.debug('resizing');
  getheightandpushmap(); // commonstuff.js
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {
      AquaWT.map.resize();
      AquaWT.map.reposition();
  }, 800);
}

//===================================================================
//  Legenda sliding
  var legendSlideAmount = dojo.isIE == 6 ? 120 : 132;
  var legendAnimationPlaying = false;
  var legendIsShown = true;
  var legendDiv = "legenda";

  /*
   * Slide legend animatie vervangen door setten van style right.
   */
  function slideLegend(){
    legendIsShown = !legendIsShown;
    dojo.style(legendDiv, "right", (legendIsShown ? 5 : (-legendSlideAmount + 5)) + "px");
  }

/*
 * Bepaal de index van de layernaam binnen de service
 * 
 * Structuur en naamgeving:
 * map
 *  +-layers        Dit zijn de mapservices
 *    +-layerInfos  Dit zijn de kaartlagen binnen een mapservice
 *      +-subLayers Layers binnen een grouplayer 
 */
function getLayerIndexByName(serviceId,layerName) {
  var serviceLayer = getMapLayerById(serviceId);
  var layerInfos = serviceLayer.layerInfos;
  for(var j = 0; j < layerInfos.length; j++) {
    var layer = layerInfos[j];
    if(layer.name === layerName) {
      console.log(layer.name);
      return j;
    } 
  }
}

/*
 * Bepaal de mapservicelayer (type esri.layers.Layer)  
 */
function /*esri.layers.Layer*/getMapLayerById(serviceId) {
  return AquaWT.map.getLayer(serviceId);
}

function buildScaleList(/*esri.layers.Layer*/layer) {
  //use layer's scales to display as slider labels
  var labels = [];
  var lods = layer.tileInfo.lods;
  for (var i = 0, il = lods.length; i < il; i++) {
    labels[i] = "1:" + lods[i].scale;
    
    if(lods[i].scale >= DRAW_SCALE_ALLOWED) {
      DRAW_SCALE_LEVEL = i;
    }

    if(lods[i].scale == SNAPSHOT_SCALE) {
      SNAPSHOT_SCALE_LEVEL = i;
    }

  }
  
  esriConfig.defaults.map.sliderLabel = {
    tick: 0,
    labels: labels,
    style: "width:2em; font-family:Verdana; font-size:75%; color:#000; padding-left:2px;"
  };

  
  if(labels.length > 0) {
    AquaWT.dynaZoom = false;
  }
  
}

/*
 * Bouw een lijstje op van kaartlagen in de mapservicelayer
 */
function buildLayerList(/*esri.layers.Layer*/layer) {
  var infos = layer.layerInfos, info;
  var items = "";
  console.log('Buildlayerlist');
  for (var i=0, il=infos.length; i<il; i++) {
    info = infos[i];
    if (info.defaultVisibility) {
      console.log(info.name);
      visible.push(info.id);
    }
    items += "<input type='checkbox' class='list_item' checked='" + (info.defaultVisibility ? "checked" : "") + 
               "' id='" + info.id +"' onclick='updateLayerVisibility();' /><label for='" + info.id + "'>" + info.name + "</label><br/>";
  }
  
  dojo.byId("layer_list").innerHTML = items;

  layer.setVisibleLayers(visible);
}

/*
 * Zet kaartlagen binnen de mapservicelayer aan of uit
 */
function updateLayerVisibility() {
  var layer = getMapLayerById(TOETSLAYER);
  if(layer === null) {
    console.log("toetsLayer niet gevonden");
    return;
  }

  console.log("Layer gevonden"+layer.id);

  var inputs = dojo.query(".list_item"), input;
  visible = [];
  for (var i=0, il=inputs.length; i<il; i++) {
    if (inputs[i].checked) {
      visible.push(inputs[i].id);
    }
  }
  console.log("Update layervisibility"+layer.id);

  layer.setVisibleLayers(visible);
}

/*
 * Override de cursor setting van de pan tool
 */
function activatePan(){
  dojo.style(AquaWT.map._container, "cursor", "move");
}

/*
 * Zoom naar full extent
 */
function zoomAll(){
  disableEventHandlers();

  var handle = dojo.connect(AquaWT.map, "onExtentChange", function() {
    if(AquaWT.searchWS) AquaWT.searchWS.showGraphics();
    dojo.disconnect(handle);
  });

  AquaWT.map.setExtent(AquaWT.fullExtent);
}

/*
 * Evenet handler om de schaalbalk te updaten bij een wijziging van de extent 
 */
function extentChangeHandler () {
  updateScaleBar();
  updateLegenda();
  //updateOverview();
}

function zoomEndHandler() {
  console.log('zoomEndHandler');
  if ((AquaWT.planArea === null) || (AquaWT.planArea !== null && AquaWT.planArea._planGebied === null)) {
    AquaWT.map.graphics.clear();
  } 
}



/******************************************************************************************
 * 
 * @param {boolean} show
 */
function toggleMapOnly(/*boolean*/show){
  // Alleen kaart tonen: dus bfSurvey div uitzetten  
  if (show) {
    activateDiv('none');
  }
  else {
    hideToolBar();
  }
}

/**
 * 
 * @param {string} divId
 */
function activateDiv(/*string*/divId) {
  activateSearch(false);
  activateToets(false);
  activateResults(false);
  activateUpload(false);
  activateSearchResults(false);
  hideInfo();
  
  if (divId === 'none') {
    showToolBar();
  }
  else {
    hideToolBar();
  }
  
  switch (divId) {
    case 'toetsDiv':
      activateToets(true);
      break;
    case 'searchDiv':
      activateSearch(true);
      break;
    case 'searchResultsDiv':
      activateSearchResults(true);
      break;
    case 'toetsResultDiv':
      activateResults(true);
      break;
    case 'uploadDiv':
      activateUpload(true);
      break;
  }

}

function activateSearch(/*boolean*/show){
  toggleElement("searchDiv",show);
  if (show) {
    var el = dijit.byId('waterschapOID');
    if (el) {
      el.textbox.value = "";
    }

    var el = dijit.byId('gemeenteOID');
    if (el) {
      el.textbox.value = "";
    }

  }
}

function activateDraw(show){
}


function enableToetsBtn() {
  var el = dojo.byId('planGebiedCorrect');
  var btn = dojo.byId('btnToets');

  if (el.checked) {
     btn.disabled = false;
  }
  else {
    btn.disabled =true;
  }
}

function activateToets(show){
   toggleElement("toetsDiv",show);
}

function activateSearchResults(show){
   toggleElement("searchResultsDiv",show);
}

function activateResults(show){
  //console.log("activateResults: " + show);
  toggleElement("toetsResultDiv",show);
}

function enableUploadBtn(uploadFile) {
  //alert(uploadFile.value);
  if (uploadFile.value !== '') {
    var el = dojo.byId('uploadBtn');
    el.disabled = false;
  }

}

function activateUpload(show){
  console.log("activateUpload: " + show);

  if (show) {
    var el = dojo.byId('uploadFile');
    el.value = "";
    var el = dojo.byId('uploadBtn');
    el.disabled = true; 
  }
  toggleElement("uploadDiv",show);
}

/**
 * Toggle visibility van element
 * @param {string} elementId
 * @param {boolean} show
 */
function toggleElement(/*string*/elementId,/*boolean*/show) {
  var el = dojo.byId(elementId);
  if(typeof el === 'undefined' || el === null) {
    return;
  } 

  if (show) {
    el.style.display = 'block';
    el.style.visibility = 'visible';
  }
  else {
    el.style.visibility = 'hidden';
    el.style.display = 'none';
  }
}

function setInputValue(id,value) {
  var el = dojo.byId(id);
  
  if(typeof el !== 'undefined' && el !== null) {
    el.value = value;
    
    console.debug("Waarde '" + value + "' weggeschreven in hidden field: " + id);
    return;
  }
  console.log("Hidden field: " + id + " niet gevonden!");
  
}

function getInputValue(id) {
  var el = dojo.byId(id);
  
  if(typeof el !== 'undefined' && el !== null) {
    console.debug(el.value + " uit hidden field: " + id);
    return el.value;
  }

  console.debug("hidden field: " + id + " bestaat niet!");
  return null;
}


/*
  Eventhandler voor onExtentHistoryChange van navToolbar
*/
function extentHistoryChangeHandler() {
  //dojo.byId("zoomprev").disabled = AquaWT.navToolbar.isFirstExtent();
  //dojo.byId("zoomnext").disabled = AquaWT.navToolbar.isLastExtent();
}

/* onclick functies voor buttons */
function toggleInfo() {
  enableInfoWindow = enableInfoWindow ? false : true;
}

function clearGraphics() {
  if (AquaWT.planArea) {
    AquaWT.planArea.removeDrawing();
  }
  AquaWT.map.graphics.clear();
  
  //destroySession();
}


function destroySession() {
  var destroyUrl = serverHost + "/joomla/sessiondestroy.php";

  dojo.xhrGet({
      url: destroyUrl,
      load: onDestroySucces,
      error: onDestroyError
  });
}

function onDestroySucces(data) {
//  /alert(data);
}

function onDestroyError(data, error) {
    console.log(data);
    console.log(error);
}


function deactivate() {
  AquaWT.drawToolbar.deactivate();
  AquaWT.map.showZoomSlider();
}

function tekenPlanGebied() {
  editLayer.clear();
  AquaWT.drawToolbar.activate(esri.toolbars.Draw.POLYGON);
  AquaWT.map.hideZoomSlider();
}

function highLight(element) {
  dojo.addClass(element,'highlight');
}

function unhighLight(element) {
  dojo.removeClass(element,'highlight');
  dojo.removeClass(element,'pressed');
}

function pressed(element) {
  dojo.removeClass(element,'unpressed');
  dojo.addClass(element,'pressed');
}

function unpressed(element) {
  dojo.removeClass(element,'pressed');
  dojo.addClass(element,'unpressed');
}


function zoomIn(isZoomIn){
  if(AquaWT.dynaZoom) {
    zoomDynaIn(isZoomIn);
  }
  else {
    zoomSliderIn(isZoomIn);
  }
}

function zoomDynaIn(isZoomIn){
  var curExtent = AquaWT.map.extent;
  var zoomFactor = isZoomIn ? 0.8 : 1.2;
  var newExtent = curExtent.expand(zoomFactor);
  AquaWT.map.setExtent(newExtent);
}

function zoomSliderIn(isZoomIn){
  var curLevel = AquaWT.map.getLevel();
  var newLevel = isZoomIn ? curLevel + 1 : curLevel - 1;
  AquaWT.map.setLevel(newLevel);
}

/* animaties */
var ANIM = {
  SEARCH_OUT : 5,
  TB_SHOW : 7, 
  TB_HIDE : 8, 
  LEG_HIDE : 9, 
  LEG_SHOW : 10, 
  TOC_OUT : 11, 
  TOC_IN : 12, 
  INFO_HIDE : 13, 
  INFO_SHOW : 14 
}
var currentAnimation;

function toggleToolBar() {
  console.log("Toolbar: " + toolBarVisible);
  if(toolBarVisible) {
    hideToolBar();
  }
  else {
    showToolBar();
  }
}

function hideToolBar() {
  unsubscribeHandle(toolbarHandle);
  toolbarHandle = null;
  //console.log("unsubscribed toolbarhandle " + toolbarHandle);
  if(!toolBarVisible) return;
  doAnimation(ANIM.TB_HIDE);
  //dojo.byId('tbopenclose').className = "aquaTb aquaOpenIcon";
  toolBarVisible = false;
  console.log('hideToolBar');
}

function showToolBar() {
  unsubscribeHandle(toolbarHandle);
  toolbarHandle = null;
  //console.log("unsubscribed toolbarhandle " + toolbarHandle);
  if(toolBarVisible) return;
  doAnimation(ANIM.TB_SHOW);
  //dojo.byId('tbopenclose').className = "aquaTb aquaCloseIcon";
  toolBarVisible = true;
  console.log('showToolBar');
}

/* Show and hide legend */

function toggleLegend()
{
	slideLegend();
  updateLegendHandle();
}

/*
function toggleLegend() {
  console.log("Legenda: " + legendVisible);
  if(legendVisible) {
    hideLegend();
  }
  else {
    showLegend();
  }
}
*/

function updateLegendHandle() {
  var el = dojo.byId('legendopenclose');

  if(legendIsShown) {
    el.className = "aquaCloseBoxIcon";
    el.title = "Sluit legenda";
  }
  else {
    el.className = "aquaOpenBoxIcon";
    el.title = "Open legenda";
  }
}


function hideLegend() {
  unsubscribeHandle(legendHandle);
  legendHandle = null;
  if(!legendVisible) return;
  doAnimation(ANIM.LEG_HIDE);
  var el = dojo.byId('legendopenclose');
  //el.className = "aquaOpenBoxIcon";
  el.title = "Open legenda";
  legendVisible = false;
  console.log("hideLegend");
}

function showLegend() {
  unsubscribeHandle(legendHandle);
  legendHandle = null;
  if(legendVisible) return;
  doAnimation(ANIM.LEG_SHOW);
  var el = dojo.byId('legendopenclose');
  el.className = "aquaCloseBoxIcon";
  el.title = "Sluit legenda";
  legendVisible = true;
  console.log("showLegend");
}

/* Show and hide legend */
function toggleInfo() {
  console.log("Info: " + infoVisible);
  if(infoVisible) {
    hideInfo();
  }
  else {
    showInfo();
  }
}

function hideInfo() {
  unsubscribeHandle(infoHandle);
  infoHandle = null;
  if(!infoVisible) return;
  infoVisible = false;
  doAnimation(ANIM.INFO_HIDE);
  var el = dojo.byId('infoopenclose');
  //el.className = "aquaOpenBoxIcon";
  //el.title = "Open info";
  console.log("hideInfo");
}

function showInfo() {
  unsubscribeHandle(infoHandle);
  infoHandle = null;
  if(infoVisible) return;
  infoVisible = true;
  doAnimation(ANIM.INFO_SHOW);
  var el = dojo.byId('infoopenclose');
  //el.className = "aquaCloseBoxIcon";
  //el.title = "Sluit info";
  console.log("showInfo");
}


var showTTHandle = null;
var ttid = 'toetsTTA';
function showInfoStep(step){
  ttid = 'toetsTT'+step; 
  showInfo();
  showTTHandle = dojo.subscribe('infoReady', showTT);
  return;
}

function showTT(){
  unsubscribeHandle(showTTHandle);
  var tt = dijit.byId(ttid);
  if(tt) tt.open();
}

function hideTT(){
  unsubscribeHandle(showTTHandle);
  var tt = dijit.byId(ttid);
  if(tt) tt.close();
}



/* Show / hide table of contents */
function toggleToc() {
  console.log("Toc: " + tocVisible);
  if(tocVisible) {
    hideToc();
  }
  else {
    showToc();
  }
}

function hideToc() {
  if(!tocVisible) return;
  doAnimation(ANIM.TOC_OUT);
  var el = dojo.byId('tocopenclose');
  //el.className = "aquaOpenBoxIcon";
  el.title = "Open toc";
  tocVisible = false;
}

function showToc() {
  if(tocVisible) return;
  doAnimation(ANIM.TOC_IN);
  var el = dojo.byId('tocopenclose');
  //el.className = "aquaCloseBoxIcon";
  el.title = "Sluit toc";
  tocVisible = true;
}


function doAnimation(index) {
  var slideRight = dojo.fx.slideTo({node: "searchDiv",duration: 1000, left: 300, top: 100});
  var slideLeft = dojo.fx.slideTo({node: "searchDiv",duration: 1000, left: 0, top:100});
//  var wipeOut = dojo.fx.wipeOut({node: "aquaToolbar",duration: 500});
//  var wipeIn = dojo.fx.wipeIn({node: "aquaToolbar",duration: 500});

  var rightLocation = dojo.byId('gispluginDiv').clientWidth;
  var topLocation = dojo.byId('gispluginDiv').clientHeight;

//  var slideTbShow = dojo.fx.slideTo({node: "aquaToolbar", duration: 500, left: rightLocation - 374, top: 10});
//  var slideTbHide = dojo.fx.slideTo({node: "aquaToolbar", duration: 500, left: rightLocation - 16, top: 10});

//TODO: positiebepalen refactoren naar een functie 
  var legtop = 390;
  var legwidth = dojo.byId("legenda").offsetWidth;
  var legheight = dojo.byId("legenda").offsetHeight;
  var legtop = topLocation - legheight - 5;
  var legShowLeft = rightLocation - legwidth - 5;
  var legHideLeft = rightLocation - 16;
  var slideLegendHide = dojo.fx.slideTo({node: "legenda", duration: 500, left: legHideLeft, top: legtop });
  var slideLegendShow = dojo.fx.slideTo({node: "legenda", duration: 500, left: legShowLeft, top: legtop });

//  var infotop = 100;
//  var infowidth = dojo.byId("infoDiv").offsetWidth;
//  var infoheight = dojo.byId("infoDiv").offsetHeight;
//  //var infotop = topLocation - infoheight - 5;
//  var infoShowLeft = rightLocation - 318;
//  var infoHideLeft = rightLocation - 16;
//  var slideInfoHide = dojo.fx.slideTo({node: "infoDiv", duration: 500, left: infoHideLeft, top: infotop });
//  var slideInfoShow = dojo.fx.slideTo({node: "infoDiv", duration: 500, left: infoShowLeft, top: infotop });

  var toctop = dojo.byId("toc").offsetTop;
  var tocwidth = 123;
  //console.log(toctop + ' - '+ tocwidth);
  var slideTocOut = dojo.fx.slideTo({node: "toc", duration: 500, left: rightLocation, top: toctop });
  var slideTocIn = dojo.fx.slideTo({node: "toc", duration: 500, left: rightLocation - tocwidth -8, top: toctop });

  while(currentAnimation && currentAnimation.status() != "stopped"){
    return;
  }

  var publishKey = 'animationReady';          

  //console.log("doAnimation " + index);
  switch(index) {
    case 1:
      currentAnimation = slideRight;
      break;
    case 2: 
      currentAnimation = slideLeft;          
      break;
    case 3:
      currentAnimation = wipeIn;
      break;
    case 4: 
      currentAnimation = wipeOut;          
      break;
    case ANIM.SEARCH_OUT:
      //Chain two animations to run in sequence.
      //Note the array passed as an argument.
      currentAnimation = dojo.fx.chain([wipeOut]);        
      break;
    case 6:
      //Chain two animations to run in sequence.
      //Note the array passed as an argument.
      currentAnimation = dojo.fx.chain([wipeIn]);        
      break;
    case ANIM.TB_HIDE: 
      //currentAnimation = slideTbHide;          
      //publishKey = 'toolbarReady';          
      break;
    case ANIM.TB_SHOW: 
      //currentAnimation = slideTbShow;          
      //publishKey = 'toolbarReady';          
      break;
    case ANIM.LEG_HIDE: 
      currentAnimation = slideLegendHide;
      publishKey = 'legendReady';          
      break;
    case ANIM.LEG_SHOW: 
      currentAnimation = slideLegendShow;          
      publishKey = 'legendReady';          
      break;
    case ANIM.INFO_HIDE: 
      //currentAnimation = slideInfoHide;          
      //publishKey = 'infoReady';          
      break;
    case ANIM.INFO_SHOW: 
      //currentAnimation = slideInfoShow;          
      //publishKey = 'infoReady';          
      break;
    case ANIM.TOC_OUT: 
      currentAnimation = slideTocOut;
      publishKey = 'tocReady';          
      break;
    case ANIM.TOC_IN: 
      currentAnimation = slideTocIn;          
      publishKey = 'tocReady';          
      break;
    default:
      console.log('Onbekend animatienummer');
      return;
  }
  
  if (currentAnimation) {
    //Play the animation. Without this call, it will not run.
    var handle = dojo.connect(currentAnimation, "onEnd", function(){
      currentAnimation = null;
      dojo.disconnect(handle);
      dojo.publish(publishKey);
    });
    currentAnimation.play();
  }
}

var msgBox = {
  _msgBox : null,
  /*
   * Simpele messagebox functionaliteit
   */
  initMsgBox: function(){
    this._msgBox = dojo.byId('searchMessage');
  },
  
  setMessage: function(msg){
    if (this._msgBox) 
      this._msgBox.innerHTML = msg;
  },
  
  clear: function(){
    if (this._msgBox) 
      this._msgBox.innerHTML = "";
  } // Geen comma aan het eind!
}

function setProgressBar(newValue){
  dijit.byId("progressId").update({
    progress: newValue
  });
  console.log(newValue);
}  

function setProgressBarMax(newValue){
  dijit.byId("progressId").update({
    maximum: newValue
  });
}  

function toggleProgressBar(text) {
    var progressbar_container = dojo.byId("progressbar_container");

    if (progressbar_container.style.display == "block") {
      hideProgressBar();
    }
    else {
      showProgressBar(text);
    }
}    

function showProgressBar(text) {
    var tekst = dojo.byId('progresstext');
    tekst.innerHTML = text;

    var progressbar_container = dojo.byId("progressbar_container");
    progressbar_container.style.display = "block";
    progressbar_container.style.visibility = "visible";
}

function hideProgressBar() {
    var tekst = dojo.byId('progresstext');
    tekst.innerHTML = '';
    
    var progressbar_container = dojo.byId("progressbar_container");
    progressbar_container.style.display = "none";
    progressbar_container.style.visibility = "hidden";
}

function disableControls() {
  var lg = dojo.byId('legenda');
  lg.style.visibility = 'hidden';
  
  var tb = dojo.byId('maptoolbar_disablebuttons');
  tb.style.display = 'block';
  tb.style.zIndex = 210;
}

function enableControls() {
  var id = dojo.byId('infoDiv');
  id.style.visibility = 'visible';
  id.style.display = 'block';

  var lg = dojo.byId('legenda');
  lg.style.visibility = 'visible';
  
  var tb = dojo.byId('maptoolbar_disablebuttons');
  tb.style.display = 'none';
}

var legendHandle = null;
var toolbarHandle = null;
var infoHandle = null;
var showHandle = null;

function unsubscribeHandle(handle) {
  if (handle !== null) {
    dojo.unsubscribe(handle);
  }
  handle = null;
}


/*
  Functies die bij de onload worden geladen
*/
dojo.addOnLoad(initWatertoets);
dojo.addOnLoad(initResizer);

esriConfig.defaults.io.proxyUrl = "proxy.php";
esriConfig.defaults.io.alwaysUseProxy = false;

//alert("Watertoets: watertoets_common loaded");
console.log("Watertoets: watertoets_common.js loaded. Proxy: "+esriConfig.defaults.io.proxyUrl);

/** EOF **/

