
/**
 * JavaScript for the wmsGoogleMap
 * 
 */

//general vars

var googleMap;
var geocoder = null;
var ewindow;
var menuForm;
var infoWinUrl = "showkpinfo.php?gid=";
var mm;
var gmarkersA = [];      
var srs = "";
var bbox;
var imgW=1210;
var imgH=1170;
var imgT;
var imgL;
var copyr = "Nieuwland 2007";
var mode = "";

var Astartzoom = 13;

var mercZoomLevel = 11;
var overlaysouthwest;
var overlaynortheast;

var images=new Array();
var idx;
var currlyr = "";
var ovrly;
//var rectWaas;
var ovrlytransp = 35;
var waasrecttransp = 0.5;
var waasrect;
var updateImage=false; 

var iconRed = new GIcon(); 
    iconRed.image = 'images/icons/vrood.png';
    //iconRed.shadow = 'images/icons/vis_shadow.png';
    iconRed.iconSize = new GSize(25, 15);
    iconRed.shadowSize = new GSize(13, 13);
    iconRed.iconAnchor = new GPoint(6, 6);
    iconRed.infoWindowAnchor = new GPoint(5, 1);
var iconGreen = new GIcon(); 
    iconGreen.image = 'images/icons/vgroen.png';
    //iconGreen.shadow = 'images/icons/vis_shadow.png';
    iconGreen.iconSize = new GSize(25, 15);
    iconGreen.shadowSize = new GSize(13, 13);
    iconGreen.iconAnchor = new GPoint(6, 6);
    iconGreen.infoWindowAnchor = new GPoint(5, 1);
var iconYellow = new GIcon(); 
    iconYellow.image = 'images/icons/vgeel.png';
   // iconYellow.shadow = 'images/icons/vis_shadow.png';
    iconYellow.iconSize = new GSize(25, 15);
    iconYellow.shadowSize = new GSize(32, 20);
    iconYellow.iconAnchor = new GPoint(6, 6);
    iconYellow.infoWindowAnchor = new GPoint(5, 1);

var customIcons = [];
customIcons["kp"] = iconRed;
customIcons["kp2"] = iconGreen;
customIcons["kp3"] = iconYellow;

//customIcons["bar"] = iconBlue;

//test getfeatureinfo
function toggleInfo(){
  GEvent.clearListeners(googleMap,"click");
  if(mode == "info"){
    mode = "";
    if (ovrly) ovrly.img_.style.cursor = ""; 
  //  var bar = $("bg");
  //  bar.src = codebase+"images/static.png";
    return;
    }
  mode = "info";
  if (ovrly) ovrly.img_.style.cursor = "help"; 
  GEvent.addListener(googleMap,"click", function (overlay, point){
      if(overlay){ return; }
      var pt = new GLatLng(point.y,point.x);
      addInfoTipMarker(pt);
      }
    ); 
  };
  
function addInfoTipMarker(point){
  var arr = createInfoTipTabs(point);
  googleMap.openInfoWindowTabsHtml(point, arr);    
  };
  
  function createInfoTipTabs(pt) {
  /*var b = googleMap.getBounds();
  var sw = b.getSouthWest();
  var ne = b.getNorthEast();
  var w = sw.lng();
  var e = ne.lng();
  var n = ne.lat();
  var s = sw.lat();*/
  //bbox is defined globally
  if (bbox != null)
  {
      var bboxarr = bbox.split(",");
      var w = bboxarr[0];
      var s = bboxarr[1];
      var e = bboxarr[2];
      var n = bboxarr[3];
      //we werken alleen in NL, dus..
    
    /*
      var ts = s;
      var tw = w;
      if(n<s) { s=n; n = ts; }
      if(e<w){ w=e; e = tw; }
      if(s<-90){ s=-90; }
      if(n>90){n=90;}
      if(e>180){ e=180; }
      if(w<-180){ w=-180; }
      */
    
      var span_ew = Math.abs(e - w);
      var span_ns = Math.abs(n - s);
      
      
      
      /*
      var width;
      var height;
      if(span_ew < span_ns){
        width  = 1024*span_ew/span_ns;
        height = 1024;
        }
      else {
        width = 1024;
        height = 1024*span_ns/span_ew
        }
     */
    
    var mapx = pt.x;
    var mapy = pt.y;
      if (googleMap.getZoom()<= mercZoomLevel)
      {
        //convert to Mercator
        mapx=ovrly.dd2MercMetersLng(mapx);
        mapy=ovrly.dd2MercMetersLat(mapy);
    }
      var x = Math.round((mapx - w) * imgW/span_ew);
      var y = Math.round((n - mapy) * imgH/span_ns);
      //alert(bbox);
      //alert ('x = '+x+'y = '+y+'\n pt.x='+pt.x+'mapx='+mapx+'\n pt.y='+pt.y+'mapy='+mapy+'\n span_ew='+span_ew+', span_ns='+span_ns+'\n imgW = '+imgW+'imgH = '+imgH+'imgT = '+imgT+'imgL = '+imgL+'\n w = '+w+'s = '+s+'e = '+e+'n = '+n);
      
      
      var infoWindows = [];
      if (currlyr == "") return;
      
      var Requests = currlyr.split(",");
      //alert(currlyr);
      //alert(Requests.length);
      
      if(Requests.length<1){ return; }
      for(var r = 0;r<Requests.length;r++){
        var htm ="";
        var lyr = Requests[r];
        var lyrlab = lyr.substring(0,10);
      
        //label = label.substring(0,10);
        //var featureinfourl = MapServerURL + "&REQUEST=GetFeatureInfo&VERSION=1.1.1&LAYERS="+lyr+"&SRS="+srs+"&BBOX="+w+","+s+","+e+"," + n + "&X=" + parseInt(x,10) +"&Y="+ parseInt(y,10) +"&WIDTH="+parseInt(width,10)+"&HEIGHT="+ parseInt(height,10)+"&INFO_FORMAT=text/html&FEATURE_COUNT=1&ietype=.html&QUERY_LAYERS="+lyr;
        var featureinfourl = MapServerURL + "&REQUEST=GetFeatureInfo&VERSION=1.1.1&LAYERS="+lyr+"&SRS="+srs+"&BBOX="+w+","+s+","+e+"," + n + "&X=" + x +"&Y="+ y +"&WIDTH="+imgW+"&HEIGHT="+ imgH+"&INFO_FORMAT=text/html&FEATURE_COUNT=1&ietype=.html&QUERY_LAYERS="+lyr;
        //alert(featureinfourl);
        //document.getElementById("fiurl").value=featureinfourl;
        htm += "<iframe style=\"border:1px solid #fff;width:450px;height:200px\" src=\""; 
        htm += featureinfourl;
        htm += "\" ></iframe>";
        var m = new GInfoWindowTab(lyrlab,htm);
        infoWindows.push(m);
        }
      return infoWindows;
  }
};
  
  

function updateZoomlevelInfo()
{   

  zoomlvl = googleMap.getZoom();
  infotxt = "Klik op een icoontje om informatie op te vragen";
    zminfodiv = document.getElementById("zoomInfoDiv");
    if (zminfodiv)
    {
      if (zoomlvl < Astartzoom)
      {
        infotxt = "Knelpuntinformatie niet beschikbaar op dit zoomniveau, zoom verder in voor een vollediger beeld ";
      }
      zminfodiv.innerHTML = infotxt;
    }
    
};


function updateRectangleBackground(){
  //alert('update rect');
  var bounds = googleMap.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var lngDelta = (northEast.lng() - southWest.lng()) *2;
  var latDelta = (northEast.lat() - southWest.lat()) *2;
  var rectBounds = new GLatLngBounds(
      new GLatLng(southWest.lat() + latDelta, southWest.lng() + lngDelta),
      new GLatLng(northEast.lat() - latDelta, northEast.lng() - lngDelta));

  if (waasrect!=null)
  {
    //Tbv IE6&7, steeds de oude waas weghalen en een nieuwe maken
    googleMap.removeOverlay(waasrect); 
  }
  waasrect=new Rectangle(rectBounds);
  googleMap.addOverlay(waasrect);
  setwaastrans(waasrecttransp);
};

function setwaastrans(trsp)
{
  if (waasrect !=null)
  {
    waasrecttransp = trsp;
    waasrect.setOpacity(trsp);
    //Bewaar de laatste gebruikte transparantie waarde
    waasrecttransp = trsp;
  }
};

/**
 * Is called at initialization via the body onload.
 * Opens the googleMap
 */
function init() {



  if (GBrowserIsCompatible()) {
    geocoder = new GClientGeocoder();
    googleMap = new GMap2(document.getElementById("myGoogleMap"));
    googleMap.enableDoubleClickZoom();
    //the large  scale control
    googleMap.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(5,50)));
    //control for map/satellite/Hybrid
    
    //test jansen
    //googleMap.addControl(new GMapTypeControl());
    googleMap.addMapType(G_PHYSICAL_MAP);
    var mapControl = new GHierarchicalMapTypeControl();

    // Set up map type menu relationships
    mapControl.clearRelationships();
    mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Toon labels", false);
    //mapControl.addRelationship(G_PHYSICAL_MAP);
    
    // Add control after you've specified the relationships
    googleMap.addControl(mapControl);
    //einde test
    
    //control to show the overview
    googleMap.addControl(new GOverviewMapControl(new GSize(110,110)));
    
    
  /*  //dragzoom
    var otherOpts = { 
      buttonStartingStyle: {background: '#FFF', paddingTop: '4px', paddingLeft: '4px', border:'1px solid black'},
      buttonHTML: '<img title="Zoom in dmv het trekken van een rechthoek met de muis" src="images/icons/zoomin.gif">',
      buttonStyle: {width:'25px', height:'23px'},
      buttonZoomingHTML: 'Trek een rechthoek om naar in te zoomen (klik om te annuleren)',
      buttonZoomingStyle: {background:'white',width:'75px', height:'100%'},
      backButtonHTML: '<img title="Terug uitzoomen" src="images/icons/zoomout.gif">',  
      backButtonStyle: {display:'none',marginTop:'5px',width:'25px', height:'23px'},
      backButtonEnabled: true, overlayRemoveTime: 1000
    };


    //googleMap.addControl(new DragZoomControl(null, otherOpts,null ), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,15)));
    xu(otherOpts);
      
    */
    
    //center and show
    googleMap.setCenter(initLatLng, initZoom);
    // voeg markermanager toe
    //addKnelpuntMarkerManager();
    addGXmlHttp();
    
    var bounds = googleMap.getBounds();
    updateZoomlevelInfo();

  //updateRectangleBackground();


//changeWMSOverlaySlice();
    //add a listener to restrict zooming
    GEvent.addListener(googleMap, "zoomend", function() {
    
      if ( (maxZoom!=null)&&(googleMap.getZoom()>maxZoom) ) {
      
        updateImage=true;
        //ovrly.setTransparency(100);
        ovrly.remove();
        ovrly=null;
        //alert('zoomend ovrly.remove');
        googleMap.setZoom(maxZoom);
      }
      if ( (minZoom!=null)&&(googleMap.getZoom()<minZoom) ){
        
        updateImage=true;
        //ovrly.setTransparency(100);
        ovrly.remove();
        ovrly=null;
        //alert('zoomend ovrly.remove');
        googleMap.setZoom(minZoom);
        
        
      }
      //ovrly.remove();
      //ovrly=null;
      if (ovrly != null) {
        ovrly.img_.style.opacity=0;
      }   
      //images=new Array();
      updateImage=true;
      
      //achtergrond waas
      if (waasrect != null)
      {
        updateRectangleBackground();
      }
      //zoomlevel info
      updateZoomlevelInfo();
      
      changeWMSOverlaySlice();
    });


      //add a listener to panning
      GEvent.addListener(googleMap, "moveend", function() {
      
      //  checkBounds();
        newsouthWest = googleMap.getBounds().getSouthWest();
        newnorthEast = googleMap.getBounds().getNorthEast();
        if ((overlaysouthwest!=null)&&(overlaysouthwest.lng()>newsouthWest.lng())){
            
            updateImage=true;
        }
        else if ((overlaynortheast!=null)&&(overlaynortheast.lng()<newnorthEast.lng())){
          
          updateImage=true;

        }
        else if ((overlaysouthwest!=null)&&(overlaysouthwest.lat()>newsouthWest.lat())){
          
          updateImage=true;

        }
        else if ((overlaynortheast!=null)&&(overlaynortheast.lat()<newnorthEast.lat())){
          
          updateImage=true;

        }
        
        if (updateImage)
        {
          if (waasrect != null)
          {
          updateRectangleBackground();
          }
          //images=new Array();
          changeWMSOverlaySlice();

        }
        
    });


  if (googleMap.isLoaded())
  {
    setCheckedLayers();
  }
  }
  else
    alert('Your browser is not compatible');
};


function setOvrlyTransp(t) {
  ovrlytransp = t;
  if (ovrly != null) ovrly.setTransparency(t);
};



function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              googleMap.setCenter(point, 13);
              //var marker = new GMarker(point);
              //googleMap.addOverlay(marker);
              //googleMap.openInfoWindowHtml(address);
            }
          }
        );
      }
    };


function openinfowin(gid)
{
  infourl = infoWinUrl + gid;
  infow =  window.open(infourl, "_blank", "toolbar=0,location=1,menubar=0,directories=0,scrollbars=1,resizable=1,height=700,width=940");
};

function openfotowin(url)
{
  infow =  window.open(url, "_blank", "toolbar=0,location=1,menubar=0,directories=0,scrollbars=1,resizable=1,height=300,width=400");
};

function toggleLM(vis)
{
  lm = document.getElementById("maploading");
  if (lm) 
  { 
    if (vis) 
      lm.style.display = 'block';
    else
    lm.style.display = 'none';
  }
};


function createMarkerMax(point, name, periode, prioriteit, voorz, gid) {
      if (voorz.toUpperCase() == 'NEE') icontype = 'kp'; 
      else if (voorz.toUpperCase() == 'JA') icontype = 'kp2'; 
      else icontype = 'kp'; 
      var marker = new GMarker(point, customIcons[icontype]);
      var html = "<div class='infopopupje'> <h5>" + name + "</h5><p>Is hier een vismigratievoorziening? : " + voorz + "<br />In welke periode wordt hier een vismigratievoorziening gerealiseerd?:" + periode + "<br/> <br /><a href=# onclick='googleMap.getInfoWindow().maximize();'>Meer informatie</a></p></div>";

          GEvent.addListener(marker, 'click', function() {
          var maxContentDiv = document.createElement('div');
          maxContentDiv.innerHTML = 'Ophalen data...';
          marker.openInfoWindowHtml(html,
            {maxContent: maxContentDiv, 
             maxTitle: "Info over knelpunt "+name});

          var iw = googleMap.getInfoWindow();
          GEvent.addListener(iw, "maximizeclick", function() {
            GDownloadUrl(infoWinUrl+gid, function(data) {
              maxContentDiv.innerHTML = data;
              
            });
          });
        });
      return marker;
    };




function createMarker(point, name, periode, prioriteit, voorz, gid) {
      if (voorz.toUpperCase() == 'NEE') icontype = 'kp'; 
      else if (voorz.toUpperCase() == 'JA') icontype = 'kp2'; 
      else icontype = 'kp3'; 
      var marker = new GMarker(point, customIcons[icontype]);
      var html = "<div class='infopopupje'> <h5>" + name + "</h5><p>periode:" + periode + "<br/>prioriteit: " + prioriteit + "</p><a href=# onclick='openinfowin("+gid+")'>meer info</a></div>";
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    };
    


function addGXmlHttp(){

  //alert('GXmlHttp.create');
    toggleLM(true);
    var request = GXmlHttp.create();
    request.open("GET", "getmarkers.php", true);
    request.onreadystatechange = function() {
      if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
      var markers = xmlDoc.getElementsByTagName("marker");
      markerElementsLen = markers.length;
      for (var i = 0; i < markers.length; ++i) {
                    // obtain the attributes of each marker
      var lat = parseFloat(markers[i].getAttribute("lat"));
      var lng = parseFloat(markers[i].getAttribute("lng"));
      var point = new GLatLng(lat,lng);
      var name = markers[i].getAttribute("nme");
     // var zoomlevel = markers[i].getAttribute("zl");
      var periode = markers[i].getAttribute("per");
      var prioriteit = markers[i].getAttribute("pri");
      var voorz = markers[i].getAttribute("vrz");
      var gid = markers[i].getAttribute("id");

      // split the markers into four arrays, with different GIcons

         var marker = createMarkerMax(point,name,periode,prioriteit,voorz, gid);
         gmarkersA.push(marker);

        }

        //add markers when ready
        managerInit();


      }
    };
    request.send(null);

};

    
function removeWMSLayerDiv() {
  var d = document.getElementById('wmslayersdiv');
  var wmstbl = document.getElementById("wmstable");
  if (wmstbl) 
  { 
    d.removeChild(wmstbl);
    wmstbl = null;
  }
};
    
function AddWMSLayerDiv(lyrsarr)
{

var numlayers = lyrsarr.length;
var div=document.getElementById("wmslayersdiv");
var rows=numlayers;
var columns=1;
var tbl=document.createElement("table");
tbl.setAttribute("id","wmstable");
//tbl.style.borderWidth="1px";
//tbl.style.borderStyle="solid";
//tbl.style.borderColor="#ccc";
tbl.style.position="relative";
var tb=document.createElement("tbody");
for (var i=0;i<rows;i++)
    {
    tr=document.createElement("tr");
var lyr = lyrsarr[i];
var LayerName = lyr[0];
var LayerTitle = lyr[1];

tr.setAttribute("id",LayerName);


    for (var j=0;j<columns;j++)
        {
        var td=document.createElement("td");
        var legdivtitle =document.createElement('div');
        var contents="<a href=\"#\" onclick=\"setCheckedLegend('" + LayerName + "', 'legimg_"+LayerName+"');showLegenda('legenda_"+LayerName+"');\">" + LayerTitle + "</a>";
        legdivtitle.innerHTML = contents;
        td.style.backgroundColor="#fff";
        td.style.padding="2px";
        
        
        var chk = "<input id=\"legend_checklist\" type=\"checkbox\" value=\"" + LayerName + "\" name=\"legend_checklist\" onclick=\"setCheckedLayers(this.value, this.checked)\"/>";
        var chkdivtitle =document.createElement('div');
        chkdivtitle.innerHTML = chk;
        td.appendChild(chkdivtitle);
            
        //var contentsNode=document.createTextNode(contents);
        //td.appendChild(contentsNode);
        var legdiv =document.createElement('div');
        legdiv.setAttribute('id', 'legenda_'+LayerName); 
        legdiv.setAttribute('class', 'legenda_graphic');
        legdiv.style.display="none";
        var legimg=document.createElement("img");
        legimg.setAttribute('id', 'legimg_'+LayerName); 
        legimg.src="";
        legdiv.appendChild(legimg);
        var tdcontent=document.createElement("td");
        tdcontent.appendChild(legdivtitle);
        tdcontent.appendChild(legdiv);
        tr.appendChild(td);
        tr.appendChild(tdcontent);
     }
    tb.appendChild(tr);
    }
tbl.appendChild(tb);
div.appendChild(tbl);
};

function addWMSCapab(capabfile){

        
  var request = GXmlHttp.create();

  request.open("GET", capabfile, true);
  request.onreadystatechange = function() {
  if (request.readyState == 4) {
    var xmlDoc = request.responseXML;
    var markers = xmlDoc.getElementsByTagName("Layer");
    markerElementsLen = markers.length;
    var lyrsarr = [];

    for (var i = 0; i < markers.length; ++i) {


      // obtain the attributes of each marker
      var name = markers[i].getElementsByTagName("Name")[0].firstChild.nodeValue;
      var title = markers[i].getElementsByTagName("Title")[0].firstChild.nodeValue;
      var srs = markers[i].getElementsByTagName("SRS")[0].firstChild.nodeValue;
      //alert (name + " " + title + " " + srs );
      lyr = new Array(name, title, srs);
      lyrsarr.push(lyr);
    }

    //write the table
    AddWMSLayerDiv(lyrsarr);


    }
  };
request.send(null);

};


function managerInit()
{
  mm = new MarkerManager(googleMap);
        //mm = new GMarkerManager(googleMap, {borderPadding:1});
        //alert ('gmarkersA.length' + gmarkersA.length + ' gmarkersB.length ' + gmarkersB.length + ' gmarkersC.length ' + gmarkersC.length + ' gmarkersD.length ' + gmarkersD.length);
        mm.addMarkers(gmarkersA,Astartzoom,17);
      
        mm.refresh();
        toggleLM(false);
};
    
  

function toggleKnelpuntMarkers(vis) {
  toggleLM(true);
  if (vis) {
    
        mm.addMarkers(gmarkersA,Astartzoom,17);
        
    mm.refresh();
   
  }
  else {
    mm.clearMarkers(); 
   
  }
 toggleLM(false);
};



//---wms methods----

function setLayer(newlyr) {
  if (newlyr!=currlyr) {
    
    if (newlyr != "")
    {
      updateRectangleBackground();
      setwaastrans(waasrecttransp);
      
    }
  else
    {
      if (waasrect != null)
      {
        waasrect.remove();
        waasrect=null;
      }
    }

    images=new Array();
    currlyr=newlyr;
    if (ovrly) 
    {
      ovrly.remove();
      ovrly=null;
    }
    updateImage = true;
    //alert(currlyr);
    changeWMSOverlaySlice();
    //googleMap.addCopyright(copyr);

  }

};


function changeWMSOverlaySlice() {

  southWest = googleMap.getBounds().getSouthWest();
  northEast = googleMap.getBounds().getNorthEast();

  var overlayBounds = new GLatLngBounds(southWest, northEast);

  if (ovrly==null) {
    ovrly = new WMSOverlay(overlayBounds,0.2,'#888888');
    googleMap.addOverlay(ovrly);
  }
  else
  {
    ovrly.redraw(true);
  }

};

function WMSOverlay(bounds, opt_transparency, opt_color) {
  this.bounds_ = bounds;
  this.transparency_ = opt_transparency || 0.5;

};

/** WMSOverlay prototype */
WMSOverlay.prototype = new GOverlay();
WMSOverlay.prototype.initialize = function(map) {

  var img = document.createElement("img");
  img.style.opacity = this.transparency_;
  img.style.position = "absolute";
  map.getPane(G_MAP_MAP_PANE).appendChild(img);
  this.map_ = map;
  this.img_ = img;
  this.img_.style.zIndex = "12";
  
};

WMSOverlay.prototype.remove = function() {
if (this.img_!=null&&this.img_.parentNode!=null)
  this.img_.parentNode.removeChild(this.img_);
};

WMSOverlay.prototype.copy = function() {
  return new WMSOverlay(this.bounds_, this.transparency_, this.color_, this.backgroundColor_, this.opacity_);
};

WMSOverlay.prototype.redraw = function(force) {
  
  if (!force) return;

  if (!updateImage) return;

  if (this.map_!=null) {
    var b = googleMap.getBounds();
    //bounds_ (van het plaatje) moet gelijkgesteld worden aan de bounds van de kaart
    if (updateImage==true){
      this.bounds_=b;
      this.testbounds_=b;
    }
    
  
    
    var idx = 0;
    overlaysouthwest = this. bounds_.getSouthWest();
    overlaynortheast = this.bounds_.getNorthEast();
    //
    var borderdifference = (overlaynortheast.lat()-overlaysouthwest.lat())/1.5;
    

    overlaysouthwest = new GLatLng(overlaysouthwest.lat()-borderdifference,overlaysouthwest.lng()-borderdifference);
    overlaynortheast = new GLatLng(overlaynortheast.lat()+borderdifference,overlaynortheast.lng()+borderdifference);
    var c1  = this.map_.fromLatLngToDivPixel(overlaysouthwest);
    var c2  = this.map_.fromLatLngToDivPixel(overlaynortheast);

    var w = Math.abs(c2.x - c1.x);
    var h = Math.abs(c2.y - c1.y);
    var l = Math.min(c2.x, c1.x);
    var t = Math.min(c2.y, c1.y);
    
    imgW = w;
    imgH = h;
    imgT = t;
    imgL = l;

    var z = this.map_.getZoom();
    //this.img_.style.opacity=0;
    this.img_.style.visibility="hidden";
  
    var lngSpan = overlaynortheast.lng() - overlaysouthwest.lng();
    var latSpan = overlaynortheast.lat() - overlaysouthwest.lat();
    
  //  if (images==null||images[idx]==null) {
     if ((currlyr!="") && (ovrly != null)) {
      
        
      if (googleMap.getZoom()<= mercZoomLevel)
      {
        bbox=Math.round(this.dd2MercMetersLng(overlaysouthwest.lng()))+
        ","+Math.round(this.dd2MercMetersLat(overlaysouthwest.lat()))+
        ","+Math.round(this.dd2MercMetersLng(overlaynortheast.lng()))+
        ","+Math.round(this.dd2MercMetersLat(overlaynortheast.lat()));
        srs = "EPSG:54004";
      }
      else 
      {
        bbox=overlaysouthwest.lng()+","+overlaysouthwest.lat()+","+overlaynortheast.lng()+","+overlaynortheast.lat();
        srs = "EPSG:4326";
      }
      
      
        //display loading img
        //alert ('show LM redraw');
        toggleLM(true);
        url=MapServerURL+"&REQUEST=GetMap&SERVICE=WMS&VERSION=1.1.0&LAYERS="+currlyr+"&STYLES=default&FORMAT=image/gif&BGCOLOR=0xFFFFFF&TRANSPARENT=TRUE&SRS="+srs+"&BBOX="+bbox+"&WIDTH="+imgW+"&HEIGHT="+imgH;
        this.img_.src=url;
        //alert(url);
        if (images[idx] == null) 
        {
          images[idx] = new Image();
        }
        images[idx].src=ovrly.getImageSrc();
      
    }

    this.img_.style.width = w + "px";
    this.img_.style.height = h + "px";
    this.img_.style.left = l + "px";
    this.img_.style.top = t + "px";
    this.img_.onload=makevis;
    //Image is opgevraagd, op false tot volgende request
    updateImage = false;
    
  }
};

//
// Maak het plaatje zichtbaar zodra deze geladen is.
//
function makevis() {
  if (ovrly)
  {
    //ovrly.setTransparency(35);
    ovrly.img_.style.visibility = "visible";
    ovrly.setTransparency(ovrlytransp);
    //hide loading img
    toggleLM(false);
  }
  
};


WMSOverlay.prototype.getImageSrc = function(){
  return this.img_.src;
};

WMSOverlay.prototype.setTime = function(time){
  this.imagetime=time;
};

WMSOverlay.prototype.setTransparency = function(t) {
if (ovrly!=null&&ovrly.img_!=null){
    ovrly.img_.style.opacity = 1-(t/100);
    ovrly.img_.style.filter = "alpha(opacity="+(100-t)+")";
  }
};




WMSOverlay.prototype.MAGIC_NUMBER = 6356752.3142;
WMSOverlay.prototype.WGS84_SEMI_MAJOR_AXIS = 6378137.0;
WMSOverlay.prototype.WGS84_ECCENTRICITY = 0.0818191913108718138;

WMSOverlay.prototype.dd2MercMetersLat = function(latitude) {
  var rads = latitude * Math.PI / 180.0;
  return this.WGS84_SEMI_MAJOR_AXIS * Math.log(
    Math.tan((rads+Math.PI/2)/2) * 
    Math.pow(((1-this.WGS84_ECCENTRICITY*Math.sin(rads))/(1+this.WGS84_ECCENTRICITY*Math.sin(rads))), this.WGS84_ECCENTRICITY/2));
};
WMSOverlay.prototype.dd2MercMetersLng = function(longitude) { 
  return this.WGS84_SEMI_MAJOR_AXIS * (longitude * Math.PI / 180.0);
};



function xu(otherOpts)
{
  googleMap.addControl(new DragZoomControl({}, otherOpts, {}), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,15)));
};
