// JavaScript Document
// JavaScript Document
// test oblique photo's
//Author: Jan Jansen, 2009

var eenkeertjedelegendageopend = false;
var clickPopup = null;
var vectormarkers = null;
var geocoder = null;
var maaiplankaart = null;
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
// op basis van zoomlevel worden de waterlopen gegeneraliseerd. Is geen lineair verband..
var generalizeFeaturesArray = new Array();
generalizeFeaturesArray[7] = 5000;
generalizeFeaturesArray[8] = 3000; 
generalizeFeaturesArray[9] = 2000;
generalizeFeaturesArray[10] = 1000;
generalizeFeaturesArray[11] = 500;
generalizeFeaturesArray[12] = 100;
generalizeFeaturesArray[13] = 50;
generalizeFeaturesArray[14] = 10;
generalizeFeaturesArray[15] = 5;
generalizeFeaturesArray[16] = 5;
generalizeFeaturesArray[17] = 2;
generalizeFeaturesArray[18] = 1;
generalizeFeaturesArray[19] = 1;
generalizeFeaturesArray[20] = 1;

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
                defaultHandlerOptions: {
                    'single': true,
                    'double': false,
                    'pixelTolerance': 0,
                    'stopSingle': false,
                    'stopDouble': false
                },

                initialize: function(options) {
                    this.handlerOptions = OpenLayers.Util.extend(
                        {}, this.defaultHandlerOptions
                    );
                    OpenLayers.Control.prototype.initialize.apply(
                        this, arguments
                    ); 
                    this.handler = new OpenLayers.Handler.Click(
                        this, {
                            'click': this.trigger
                        }, this.handlerOptions
                    );
                }, 

                trigger: function(e) {
                  resetMap();
                }

            });

function init() {
  geocoder = new GClientGeocoder();
  var defBox= new OpenLayers.Bounds(620000,6580000,690000,6660000);
  //init maaiplan object
  maaiplankaart = new maaiplannerkaart('EPSG:900913', 'm', 9, defBox, 'map', 'wtgnameholder', 'Maaiplanning Watergangen ');
  //init maaiplan map object 
  maaiplankaart.initMap();
  
  var click = new OpenLayers.Control.Click();
  maaiplankaart.Map.addControl(click);
  click.activate();
  
  if (!maaiplankaart.Map.getCenter()) maaiplankaart.Map.zoomToMaxExtent();

};

function resetMap(){
  //triggered als op de kaart geklikt wordt, en wanneer er opnieuw gezocht wordt naar waterloop
                    if (maaiplankaart == null) return;
                    if (maaiplankaart.Map == null) return; 
                    //popuplabel en selectie verbergen
                   	maaiplankaart.labelobj.style.display = 'none';
										maaiplankaart.clearSelection();
										resetPlanningDiv();
}


function maaiplannerkaart(strSRS, strUnits, defzoom, bounds, divname, labeldivname, wtgname) {

//depends on ajax functions ajax.js
  this.SRS = strSRS;
  this.units = strUnits;
  this.divname = divname;
  this.labeldivname = labeldivname;
  this.mapbounds = bounds;
  this.defzoom = defzoom;
  this.busyRequestwtg = false;
  this.minWGZoomlevel = 13; //zoomlevel switch between raster and feature
  this.numZoomLevels = 20;
  this.maxResolution = 2200;
  this.WTGselectie = "";
  this.wtgLayername = wtgname;
  this.app_url = location.protocol+"//"+location.host+"/";
  this.watergangsearch_url = this.app_url+'php/searchwatergangen.php?';
  this.planning_url = this.app_url+'php/planning.php?';
  this.wms_url = this.app_url+'cgi-bin/mapserv?map=/srv/www/webdata/mapfiles/roerovermaas.map';
  this.wtgWMS = null;
  this.bgWMS = null;
  this.wtgFeatures = null;
  this.zoomtoext = false; //boolean indicates whether map should zoom to features extent when requested
  //this.wtgSelectie = null;
  this.selectedWLID = "";
  this.selfeature = null;
  this.selfeatureOL = null;
  this.selfeaturehover = null;
  this.wtgoptions_select = {multiple: false, clickout:true, toggle:true, box:false, hover:true,  callbacks: {'over':showwatergangname, 'out':hidewatergangname, 'click': getPlanning}};
  this.Map = null;
  this.labelobj = null; 
  this.romStylesArr = null; // array with styles
  this.control_select = null; //openLayers select control for features wtg layer

  this.initMap = function (){
  
    //init styles , strokeDashstyle: "dashdot"
    tmpa = new Array();
    tmpa["0"] = { strokeWidth: 6,  strokeColor: "#63ACFF", strokeOpacity: 0.8,  pointRadius: 6,  cursor: "default" };
    tmpa["1"] = { strokeWidth: 8,  strokeColor: "#339966",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["2"] = { strokeWidth: 8,  strokeColor: "#00FF00",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["3"] = { strokeWidth: 8,  strokeColor: "#00FF00",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["4"] = { strokeWidth: 8,  strokeColor: "#FFFF00",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["5"] = { strokeWidth: 8,  strokeColor: "#FFFF00",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["6"] = { strokeWidth: 8,  strokeColor: "#FF0000",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["7"] = { strokeWidth: 8,  strokeColor: "#FF0000",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["8"] = { strokeWidth: 8,  strokeColor: "#CC99FF",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["9"] = { strokeWidth: 8,  strokeColor: "#CC99FF",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["10"] = { strokeWidth: 8,  strokeColor: "#800000",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["sel_style"] = { strokeWidth: 4,  strokeColor: "#58FAF4",  strokeOpacity: 0.8,  pointRadius: 6,  cursor: "pointer" };
    tmpa["sel_style_vet"] = { strokeWidth: 8,  strokeColor: "#58FAF4",   strokeOpacity: 0.9,  pointRadius: 6,  cursor: "pointer" };
    tmpa["sel_style_vet_rand"] = { strokeWidth: 10,  strokeColor: "#000000",   strokeOpacity: 0.9,  pointRadius: 6,  cursor: "pointer" };
    tmpa["default"] = { strokeWidth: 8,  strokeColor: "#63ACFF",  strokeOpacity: 0.6,  pointRadius: 6,  cursor: "default" };
    this.romStylesArr = tmpa;
    
    //init label obj
    this.labelobj = document.getElementById(this.labeldivname);
    if (this.labelobj == null){
      alert('Div voor labelobject niet gevonden');
    }
    
    //init map object
    var mapOptions = {eventListeners: {"zoomend": requestWatergangen, "moveend": requestWatergangen},projection:this.SRS, units: this.units, maxExtent: this.mapbounds, numZoomLevels: this.numZoomLevels, minZoomLevel: 0, maxZoomLevel: this.numZoomLevels, maxResolution: this.maxResolution}; // EPSG:900913
    this.Map = new OpenLayers.Map(this.divname, mapOptions);
    this.Map.addControl(new OpenLayers.Control.LayerSwitcher);
    this.Map.addControl(new OpenLayers.Control.MouseDefaults());
   
     //add google layers to map
    
		 var gnorm = new OpenLayers.Layer.Google(
                    "Straten",
                    {type: G_NORMAL_MAP, numZoomLevels: 20, 'sphericalMercator': true}
                );
    this.Map.addLayer(gnorm);
		 var ghyb = new OpenLayers.Layer.Google(
                    "Luchtfoto",
                    {type: G_HYBRID_MAP, numZoomLevels: 20, 'sphericalMercator': true}
                );
    this.Map.addLayer(ghyb);
   
    //WMS layer watergangen
     this.wtgWMS = new OpenLayers.Layer.WMS.Untiled("Watergangen",
            this.wms_url, 
            {'layers': 'watergangen', transparent: true, format: 'image/png'},
            {'displayInLayerSwitcher':true},
            {isBaseLayer: false}
        );
    
    //var options_wtgWMS = {layername: 'Gemeentegrenzen,Watergangen', layerdesc: 'Watergangen', baselayer: false, visible: true, format:'image/png'};
    //this.wtgWMS = new OpenLayers.Layer.WMS.Untiled( 'Watergangen',  this.wms_url, options_wtgWMS, {buffer:0});
     
    //this.wtgWMS = this.getwtgWMS();
    this.Map.addLayer(this.wtgWMS);
    
      //additional WMS layers beheersgebied en gemeentegrenzen
      this.bgWMS = new OpenLayers.Layer.WMS.Untiled("Beheersgebied en Gemeentegrenzen",
            this.wms_url, 
            {'layers': 'Gemeentegrenzen,Waterschapsgrens', transparent: true, format: 'image/png'},
            {'displayInLayerSwitcher':true},
            {isBaseLayer: false}
        );
    
      //var options_wtgWMS = {layername: 'Gemeentegrenzen,Watergangen', layerdesc: 'Watergangen', baselayer: false, visible: true, format:'image/png'};
      //this.wtgWMS = new OpenLayers.Layer.WMS.Untiled( 'Watergangen',  this.wms_url, options_wtgWMS, {buffer:0});
       
      //this.wtgWMS = this.getwtgWMS();
      this.Map.addLayer(this.bgWMS);
    
 
    };
    

    
    this.removewtgLayer = function (){

     if (this.wtgFeatures != null){
       //alert('client_lyr_roads != null');
         this.Map.removeLayer(this.wtgFeatures);
         this.wtgFeatures = null;
      }
    };
    
     this.hideWMSLayer = function (){

     if (this.wtgWMS != null){
     if (this.wtgWMS.getVisibility()){
        // alert('hideWMSLayer');
         this.wtgWMS.setVisibility(false);
         }
      }
    };
    
    this.showWMSLayer = function (){

     if (this.wtgWMS != null){
         if (!this.wtgWMS.getVisibility()){
          // alert('showWMSLayer');
           this.wtgWMS.setVisibility(true);
           }
         }
    };
    
    this.clearSelection = function(){
      if (this.wtgFeatures == null) return;
      this.wtgFeatures.removeFeatures(maaiplankaart.selfeature);
     	this.wtgFeatures.removeFeatures(maaiplankaart.selfeatureOL);
      this.selfeature = null;
      this.selfeatureOL = null;
      this.selfeaturehover = null;
    
    }
  
    
  this.getStyle = function (feature){
    if (feature == null) return;
    var tmpstyle = null;
    try {
       tmpstyle = this.romStylesArr[feature.attributes.wtgtype];
    }
    catch(e)
    {
        tmpstyle = this.romStylesArr["default"];
    }
    return tmpstyle;
};
	//enable click event on a layer
	this.enableSelectForLayer = function(layerObj,callBack){
		var control = new OpenLayers.Control.SelectFeature(layerObj, {hover: false, clickout: true, onSelect: callBack});
		this.Map.addControl(control);
		control.activate();
	}

};

function resetWaterLoopNaam() {

  frm = document.getElementById('zoekform');
  frm.wlinput.value = "";
  maaiplankaart.WTGselectie = "";
  requestWatergangen();

}

function postWaterLoopNaam() {

  frm = document.getElementById('zoekform');

  maaiplankaart.WTGselectie = frm.wlinput.value;
  //alert( maaiplankaart.WTGselectie);
  resetMap();
      
    
  maaiplankaart.zoomtoext = true;
  requestWatergangen();
         
};

function requestWatergangen() {
  //check zoekform

    if (maaiplankaart != null){
      //verberg labelobject, just in case
      maaiplankaart.labelobj.style.display = 'none';
     
     
      if (maaiplankaart.Map != null){
      
        
        if (maaiplankaart.Map.getZoom() < maaiplankaart.minWGZoomlevel &&  maaiplankaart.WTGselectie == "") {
        
          //remove featurelayer watergangen and show WMS layer
          maaiplankaart.removewtgLayer();
          maaiplankaart.showWMSLayer();
          //verbergen legenda onderhouds info
          $("#info-onderhoud").hide();
         
        }
        else
        { 
          
          
            //bepaal simplify factor adhv zoomlevel          
            zl = maaiplankaart.Map.getZoom();
            zlgen = generalizeFeaturesArray[zl];
            
            //show tabblad met legenda
            if (!eenkeertjedelegendageopend){
              $("#tabs").tabs('select', 1);
              eenkeertjedelegendageopend = true;
            }
            //tonen legenda onderhouds info
            $("#info-onderhoud").show();
            
           if (maaiplankaart.WTGselectie != "")
           {
            maaiplankaart.showWMSLayer();
            //wanneer er een watergang naam is ingevuld, laat alleen onderhoudsvakken van die waterloop zien
              paramstr = 'zlgen='+ zlgen+ '&action=SEL&naam='+maaiplankaart.WTGselectie;
              
           }
           else
           {  
              maaiplankaart.zoomtoext = false;
              maaiplankaart.hideWMSLayer();
              ext = maaiplankaart.Map.getExtent().toBBOX().toString().split(",");
              paramstr = 'zlgen='+ zlgen+ '&action=ALL&bbox='+ext[0] + " " + ext[1] + "," + ext[2] + " " + ext[3];
           }
            
            
             if (!maaiplankaart.busyRequestwtg){
              
              //alert('!maaiplankaart.busyRequestwtg');
              maaiplankaart.busyRequestwtg = true; 
              sendAjaxRequest('POST',maaiplankaart.watergangsearch_url, paramstr, handleLoadWaterg);
            }
        }
      }
    }
    else
    {
     alert('maaiplankaart.Map = null');
    }
 
  };
  

function handleLoadWaterg(data){

     var jsonresp = data.responseText;
     
    //Test if the json layer exists, either wipe or create it
     maaiplankaart.removewtgLayer();
  
     //Add the vector layer to the map
     maaiplankaart.wtgFeatures = new OpenLayers.Layer.Vector(maaiplankaart.wtgLayername);
    
     maaiplankaart.wtgFeatures.displayInLayerSwitcher = true;
     maaiplankaart.Map.addLayer(maaiplankaart.wtgFeatures);
      
    
     var geojson_format = new OpenLayers.Format.GeoJSON();
     //Add all json features to the vector layer    var featuresSelected = null;
     featuresSelected = geojson_format.read(jsonresp);
        
     
     if (featuresSelected != null) {
     //alert ( ' featuresSelected != null' );
       for (var i = 0; i < featuresSelected.length; i++) {
        
         featuresSelected[i].style = maaiplankaart.getStyle(featuresSelected[i]);
         maaiplankaart.wtgFeatures.addFeatures([featuresSelected[i]]);
        }
     
     }
     //als er een selectie was, voeg deze weer toe aan de kaart
     if (maaiplankaart.selfeature != null) {  
       maaiplankaart.wtgFeatures.addFeatures(maaiplankaart.selfeatureOL);
       maaiplankaart.wtgFeatures.addFeatures(maaiplankaart.selfeature);
     } 
     	 
    maaiplankaart.busyRequestwtg = false;
     	//check whether to zoom to features extent
	 	if ( maaiplankaart.zoomtoext)
	 	{
     
      wtg_ext = maaiplankaart.wtgFeatures.getDataExtent();
     // alert(wtg_ext);
      if (wtg_ext != null) maaiplankaart.Map.zoomToExtent(wtg_ext);
      maaiplankaart.zoomtoext = false;
     }
        

	 	
	 
	 // var wtgoptions_select = maaiplankaart.wtgoptions_select;
		control_select = new OpenLayers.Control.SelectFeature( maaiplankaart.wtgFeatures, maaiplankaart.wtgoptions_select);
		maaiplankaart.Map.addControl(control_select);
		control_select.activate();
		

		   
  };
  
 
  
  
  

 function getPlanning (feature)
   {
     //alert('get planning for id ' + feature.attributes.id);
     //select waterloop
     //	maaiplankaart.wtgFeatures.removeFeatures(maaiplankaart.selfeature);
     	//maaiplankaart.wtgFeatures.removeFeatures(maaiplankaart.selfeatureOL);
     	maaiplankaart.clearSelection();
     
      maaiplankaart.selfeature = feature.clone();
      maaiplankaart.selfeatureOL = feature.clone();
      maaiplankaart.selfeature.style = maaiplankaart.romStylesArr["sel_style_vet"];
      maaiplankaart.selfeatureOL.style = maaiplankaart.romStylesArr["sel_style_vet_rand"];
      maaiplankaart.wtgFeatures.addFeatures(maaiplankaart.selfeatureOL);
      maaiplankaart.wtgFeatures.addFeatures(maaiplankaart.selfeature);

     
     
     var paramstr = 'gid='+feature.attributes.id;
     sendAjaxRequest('POST',maaiplankaart.planning_url, paramstr, handlePlanning);
     
   };
   
function handlePlanning(data){
  
    var htmlresp = data.responseText;
    document.getElementById('wg-planning').innerHTML = htmlresp;
    // switch to first tab
  	$("#tabs").tabs('select', 0);
  };
   
  function showwatergangname (feature)  {
	
      //Test if a feature is selected
      if (feature == null) return;
    
    //add feature with selection style
    	maaiplankaart.wtgFeatures.removeFeatures(maaiplankaart.selfeaturehover);
      maaiplankaart.selfeaturehover = feature.clone();
      maaiplankaart.selfeaturehover.style = maaiplankaart.romStylesArr["sel_style"];
      maaiplankaart.wtgFeatures.addFeatures(maaiplankaart.selfeaturehover);
    
    //search the div for the label text
    
      if (maaiplankaart.labelobj == null) return;
    
      //Zoek de mouse position
      for(var i=0; i< maaiplankaart.Map.controls.length; i++) {
        var control = maaiplankaart.Map.controls[i];
        if (control.CLASS_NAME == "OpenLayers.Control.MouseDefaults") {
          break;
        }
      }
    
      var mouse = maaiplankaart.Map.controls[i].mousePosition;
      var pos = findPos(document.getElementById(maaiplankaart.divname));
      var offsety = pos[1];
      var offsetx = pos[0] + 15;
    
      //styling label
      maaiplankaart.labelobj.style.top = (mouse.y + offsety) + 'px';
      maaiplankaart.labelobj.style.left = (mouse.x + offsetx) + 'px';
			maaiplankaart.labelobj.style.padding = '5px';
			maaiplankaart.labelobj.style.borderWidth = '3px';
			maaiplankaart.labelobj.style.textAlign = 'left';
			maaiplankaart.labelobj.style.height = '30px';
			if (feature.attributes.wtgtype != "0") {
	  		maaiplankaart.labelobj.style.borderColor = maaiplankaart.romStylesArr[feature.attributes.wtgtype].strokeColor;}
      else {
	  		maaiplankaart.labelobj.style.borderColor = maaiplankaart.romStylesArr["default"].strokeColor;}
			
      var htmltext = "<div id=\"label"+ feature.attributes.wtgtype+ "\">";
      htmltext += "<p><b>Waterloop</b>: " + feature.attributes.name + "</p>";
      if (feature.attributes.wtgtype != "0") htmltext += "<b>Onderhoudsvaknummer</b>: " + feature.attributes.wtgnr;
      else htmltext += " (Geen onderhoud) </br>";
			htmltext += "</div>";
      maaiplankaart.labelobj.innerHTML = htmltext;
      maaiplankaart.labelobj.style.display = 'block';
  
  };

  function hidewatergangname(feature)  {
    	//Place the memoholder at the calculated position
    	maaiplankaart.wtgFeatures.removeFeatures(maaiplankaart.selfeaturehover);
    	maaiplankaart.labelobj.style.display = 'none';
  };

//Find the current position of the active element
  function findPos(obj) 
  {
    var curleft = curtop = 0;
    if (obj.offsetParent)
    {
      curleft = obj.offsetLeft
      curtop = obj.offsetTop
      while (obj = obj.offsetParent)
      {
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
      }
    }
    return [curleft,curtop];
  };


function showAddress(address) {

	addressnl = address.replace(',the netherlands',' ');

  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(addressnl + " niet gevonden");
        } else {
					var punt = new OpenLayers.Geometry.Point(point.lng(),point.lat());
					var proj_900913 = new OpenLayers.Projection("EPSG:900913");
					var proj_4326 = new OpenLayers.Projection("EPSG:4326");
					var newGeom = punt.transform(proj_4326,proj_900913);
					var newLonLat = new OpenLayers.LonLat(newGeom.x,newGeom.y);
					
					maaiplankaart.Map.setCenter(newLonLat,maaiplankaart.minWGZoomlevel);
					
					var zoekStyles = new OpenLayers.StyleMap({
              "default": new OpenLayers.Style({
                  pointRadius: "10",
                  fillColor: "#ff0000",
                  strokeColor: "#cc0000",
                  strokeWidth: 2
              }),
              "select": new OpenLayers.Style({
                  fillColor: "#66ccff",
                  strokeColor: "#3399ff"
              })
          });
					
				vectormarkers = new OpenLayers.Layer.Vector('wl-marker', {styleMap: zoekStyles});
				maaiplankaart.Map.addLayer(vectormarkers);
				feature = new OpenLayers.Feature.Vector(newGeom);
				adres = address;
				vectormarkers.addFeatures(feature);
				maaiplankaart.enableSelectForLayer(vectormarkers,showPopup);
			}
      }
    );
  }
};

function showPopup(feature){
	
	if (clickPopup) clickPopup.destroy();
	
	//construct the html
	htmlpostcode = "<span id=\"straat\" class=\"ui-corner-all\">";
  htmlpostcode += "<table border='0' cellspacing='0' cellpadding='0' width='200'>";
  htmlpostcode += "<tr><td>";
  htmlpostcode += "<table border='0' cellspacing='0' cellpadding='0' width='200'>";
  htmlpostcode += "<tr><th class='title' colspan='2'>Zoek resultaat</th></tr>";
  htmlpostcode += "<tr><th>Adres</th><td>" + adres + "</td></tr>";
  htmlpostcode += "</table>";
  htmlpostcode += "</td></tr></table>";
  htmlpostcode += "</span>";

	clickPopup = new OpenLayers.Popup(
                      "chicken",
                      new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y),
											new OpenLayers.Size(200,50),
                      htmlpostcode,
                      true
                  );		
	maaiplankaart.Map.addPopup(clickPopup);
}

//clear all features on a layer
function clearDrawing(layerObj) {
	if (layerObj != null)
  layerObj.removeFeatures(layerObj.features);
}
