//
// ---------- INITS ----------
//

addEvent(window, 'load', init);


//
// ---------- FUNCTIONS ----------
//

function init(){  // called by load event
  // init system components only when Gmap canvas is present! 
  if(document.getElementById("map_canvas")!=null){
    addEvent(window, 'unload', GUnload);
    initSys();
    initMap();
    searchUpdate();
  }
}


function initSys(){  // called by load event -> init()

  // GLOBAL CONFIG
  
  gInitCenter = [49.366456, 6.866822];
  gInitZoom   = 9;
  gClickZoom  = 13;

  gTypes = ['3', '12', 'X'];
  gCnt3=0, gCnt12=0, gCntX=0;
  
  
  // global var init
  gMap = null;

  gMarkers = [];
  gPolyIds3  = [];
  gPolyIds12 = [];
  gPolyIdsX  = [];
  
  gPoints = [];
  gHtmls = [];
  
  gFiltMinObj   = document.getElementById('filterSizeMin');
  gFiltMaxObj   = document.getElementById('filterSizeMax');
  gFiltDistrObj = document.getElementById('filterDistrict');
  gFiltMuniObj  = document.getElementById('filterMunicipal');


  // init estate lists
  for(var ti=0; ti<gTypes.length; ti++)  makeListHTML(gTypes[ti]);
}

function initMap() {  // called by load event -> init()
  var i,k;
  if (GBrowserIsCompatible()) {
    // Display the map, with some controls and set the initial location 
    gMap = new GMap2(document.getElementById("map_canvas"));
    //var myIconBig = MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: "#DA1442", strokeColor: "#333333"});
//ACHTUNG: MEHR MÖGLICHKEITEN MIT DIESEN NEUEN PINS:
//http://econym.org.uk/gmap/chartpins.htm
//http://groups.google.com/group/google-chart-api/web/chart-types-for-map-pins
//ABER ACHTUNG: WIE IN ERSTEM LINK BESCHRIEBEN, ERSCHEINEN DIE PINS MANCHMAL NICHT!
//EVTL MAL NACH 3D-PINS IN DIESEM DEMO SCHAUEN:  http://econym.org.uk/gmap/label.htm

//VIELEN EINZELLÖSUNGEN HIER http://econym.org.uk/gmap/  (z.B. Restricting the range of map zooms and pans)
// - Using cookies to remember the map state.   http://econym.org.uk/gmap/cookies.htm

    gIcon3  = MapIconMaker.createMarkerIcon({width: 26, height: 26, primaryColor: "#0000FF", strokeColor: "#000000"});
    gIcon12 = MapIconMaker.createMarkerIcon({width: 26, height: 26, primaryColor: "#02DC00", strokeColor: "#000000"});
    gIconX  = MapIconMaker.createMarkerIcon({width: 26, height: 26, primaryColor: "#FFFF00", strokeColor: "#000000"});
    
    _mPreferMetric = true;  // undocumented! metric units on top (instead of below) for GScaleControl
// CURRENTLY OFF TO IMPROVE PERFORMANCE
    gMap.addControl(new GOverviewMapControl());

    // ZUM EINBAU VON CHECKBOXEN (z.B. WP & Panoramico) ETC.:  statt GMapTypeControl verwendet man GHierarchicalMapTypeControl
    // SIEHE:  http://code.google.com/intl/de-DE/apis/maps/documentation/controls.html#Control_Modification
    // gMap.addControl(new GHierarchicalMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(3,17)));

    // NOW DONE BY gMap.setUIToDefault(); - see below
    //gMap.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(3,17)));
    //gMap.addControl(new GLargeMapControl3D());
    //gMap.addControl(new GScaleControl());
    //gMap.enableScrollWheelZoom();
    //gMap.enableContinuousZoom();
    
    // activate map!
    gMap.setCenter(new GLatLng(gInitCenter[0], gInitCenter[1]), gInitZoom);
    gMap.setUIToDefault();


// BAD WORKAROUND TO INCREASE PERFORMANCE:
// IMAGE OVERLAY INSTEAD OF KML VECTOR FILES
//gKMLground = new GGeoXml('http://gewiss.strukturholding.de/typo3conf/ext/dl_gewiss_gmaps/data/test_groundoverlay_09lres.kml');
//gMap.addOverlay(gKMLground);
    
    // KMLs to show on live & testing system

    // PART 1 of 2 of strategy against interfering infowindows of markers and KML layer polies:
    // --
    // The infowindow contents can be modified as it opens.
    // THIS IS UNDOCUMENTED!!!
    // See  http://econym.org.uk/gmap/interceptor.htm  and  http://econym.org.uk/gmap/gevent.htm
    GEvent.addListener(gMap,"infowindowprepareopen", function(iwtabs) {
      var infoHtm = iwtabs[0].contentElem.innerHTML;
      var infoTxt = infoHtm.replace(/<[^>]+>/g, '').replace(/^\s+/, '').replace(/\s+$/, '');
      
      // InfoWin empty -> force to close info win immediatelly
      // InfoWin contains %d+ (flächen code) -> replace infowin content with the html content of that poly
      // otherwise -> content is HTML, so show the infowin unchanged
      var now = new Date();
      if(infoTxt==''){
        // empty
        gInfoWinForceClose = true;
      }else if(infoTxt.search(/^\d+$/)>=0){
        // flächen code
        for(i=0; i<gPolys.length; i++){
          if(gPolys[i].f==infoTxt)  break;
        }
        if(i<gPolys.length){
          iwtabs[0].contentElem.innerHTML = buildPolyInfoHtml(gPolys[i]);
          gInfoWinForceClose = false;
        }else{
          gInfoWinForceClose = true;
        }
      }else{
        // content is HTML
        gInfoWinForceClose = false;
      }
    });
    
    GEvent.addListener(gMap,"infowindowopen", function() {
      if(gInfoWinForceClose)  gMap.closeInfoWindow();
      gInfoWinForceClose = false;
    });

    gKMLnwlinkList=[];
    for(var f in gNwlinkFiles)  gKMLnwlinkList[f] = new GGeoXml(gNwlinkFiles[f]);
    gMap.addOverlay(gKMLnwlinkList[0]);
    gKMLdistrActive=0;  // which of the files in the above list is currently addOverlayed?


   
    // KMLs to show only on live system
    if(location.href.indexOf('.dl1.de')==-1 && location.href.indexOf('.dllt3.de')==-1){
    }

    //DEBUG: show bounds of current map
    //alert(gMap.getBounds());

    // put the assembled gList?Html contents into the side_bar div
    document.getElementById('gwListProgress3').style.visibility =
    document.getElementById('gwListProgress12').style.visibility =
    document.getElementById('gwListProgressX').style.visibility = 'hidden';

  }
  
  // display a warning if the browser was not compatible
  else {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }
}





function makeListHTML(t){
  var s;
  s ='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">';
  s+='<html>';
  s+='<head>';
  s+='<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
  s+='<link href="/fileadmin/templates/gewiss/css/central.css" rel="stylesheet" type="text/css" >'
  s+='</head>';
  s+='<body class="gwIfrmBody'+t+'">';
  s+='<div id="listDiv" class="gwListData">&nbsp;</div>';
  s+='</body>';
  s+='</html>';
  var ifd = window['ifd'+t] = window['ifr'+t].document;
  ifd.write(s);
  ifd.close();
}
function writeList(t, s){
  if(window['ifd'+t].getElementById('listDiv')!=null){
    window['ifd'+t].getElementById('listDiv').innerHTML = s;
    setIfrmHeight();
  }
}
function writeListMsg(s, d){
  if(d!=undefined)  s=s.split('%s').join(d);
  lm = document.getElementById('gwListMsg');
  lm.style.display = (s==''?'none':'block');
  lm.innerHTML = s;
}

function setIfrmHeight(){
  var hRemain = 239;
  if(navigator.userAgent.indexOf("MSIE")>=0)  hRemain -= 6;
  var hAddGap = 5;
  var tArr = ['3','12','X'];
  for(i=0; i<tArr.length; i++){
    t=tArr[i];
    var hNeed = window['ifd'+t].getElementById('listDiv').offsetHeight+hAddGap;
    var hMax = hRemain/tArr.length;
    if(hNeed <= hMax){
      // needed height for this block is less than available height (= total height/count of blocks)
      // => this block gets all the height it needs, is taken out of the list and subtracted from available height, and loop is restarted
      document.getElementById('ifr'+t).height = hNeed;
      tArr.splice(i,1);
      hRemain -= hNeed;
      i=-1;  // restart loop
    }else{
      // block higher than available space. Give it the available height (= total height/count of blocks)
      // => will have a scroll bar
      document.getElementById('ifr'+t).height = hMax;
    }
  }
}

function callListUpdate(){
//  alert("callListUpdate!!!");
  document.getElementById('gwListProgress3').style.visibility =
  document.getElementById('gwListProgress12').style.visibility=
  document.getElementById('gwListProgressX').style.visibility = 'visible';
  document.getElementById('list3').innerHTML =
  document.getElementById('list12').innerHTML =
  document.getElementById('listX').innerHTML = '';
  var url = "index.php";
  var sizeMin =   gFiltMinObj.value;
  var sizeMax =   gFiltMaxObj.value;
  var municipal = gFiltMuniObj.value;
  var pars = "eID=dl_gewiss_gmaps&action=listUpdate&sizeMin="+sizeMin+"&sizeMax="+sizeMax+"&municipal="+municipal;
  var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: listUpdate});
}
 
 
function listUpdate(orgRequest){
  var result;
  var xmldoc = orgRequest.responseXML;
  document.getElementById('gwListProgress3').style.visibility =
  document.getElementById('gwListProgress12').style.visibility=
  document.getElementById('gwListProgressX').style.visibility = 'hidden';
  result = xmldoc.getElementsByTagName("data3")[0].firstChild.data;
  document.getElementById('list3').innerHTML = result;
  result = xmldoc.getElementsByTagName("data12")[0].firstChild.data;
  document.getElementById('list12').innerHTML = result;
  result = xmldoc.getElementsByTagName("dataX")[0].firstChild.data;
  document.getElementById('listX').innerHTML = result;
}


function searchUpdate(){
  var i;       
  
  if(gParams.markerlight){
    var maxMarkers = 500;
  }else{
    var maxMarkers = 150;
  }

//  // show progress indicators
//  document.getElementById('gwListProgress3').style.visibility =
//  document.getElementById('gwListProgress12').style.visibility=
//  document.getElementById('gwListProgressX').style.visibility = 'visible';

  // clear estate lists
  writeList('3',  '');
  writeList('12', '');
  writeList('X',  '');
  writeListMsg('');
  // clear estate cnts
  document.getElementById('listCntTotal').innerHTML = 
  document.getElementById('listCnt3').innerHTML  = 
  document.getElementById('listCnt12').innerHTML = 
  document.getElementById('listCntX').innerHTML  = '';
  // hide markers
  while(gMarkers.length>0){
    var marker = gMarkers.shift();
    
    //GEvent.removeListener(marker.listenHandle);
    GEvent.clearNode(marker);
    
    gMap.removeOverlay(marker);
  }
  // clear poly lists
  gPolyIds3  = [];
  gPolyIds12 = [];
  gPolyIdsX  = [];
  
  // read filter settings - part A
  var district  = gFiltDistrObj.value;

  // muni drop not yet initialized or district changed? => (re)build muni drop
  if(gFiltMuniObj.options.length==0 || gMuniDropDistr!=district){
    // store current  muni selection
    var oldMuniVal = gFiltMuniObj.value;
    // clear existing list
    gFiltMuniObj.options.length=0;
    if(district==0){
      // all munis
      for(i=0; i<gMunis.length; i++){
        gFiltMuniObj.options[i] = new Option(gMunis[i], i, i==0, i==oldMuniVal);
      }
    }else{
      // only munis in district
      var curMunis = gDistrMunis[district];
      gFiltMuniObj.options[0] = new Option('[alle]', 0, true);
      for(i=0; i<curMunis.length; i++){
        gFiltMuniObj.options[i+1] = new Option(gMunis[curMunis[i]], curMunis[i], false, false);
      }
    }
    // store new muni drop district
    gMuniDropDistr = district;
  }
   if(gKMLdistrActive!=district){
     // hide any old KML networklink file
     gMap.removeOverlay(gKMLnwlinkList[gKMLdistrActive]);
     // show KML networklink file matching current district
     gMap.addOverlay(gKMLnwlinkList[district]);
     gKMLdistrActive=district;
   }
  
  // read filter settings - part B
  var sizeMin =   parseInt(gFiltMinObj.value);
  var sizeMax =   parseInt(gFiltMaxObj.value);
  var municipal = gFiltMuniObj.value;

  // any filters used?
  if(sizeMin==0 && sizeMax>1000000 && district==0 && municipal==0){
    // -- no filters active
    // hide/unhide CEs with class ce_on_when_filters/ce_off_when_filters
    $$('.ce_on_when_filters' ).each(function(s){s.style.display='none';});
    $$('.ce_off_when_filters').each(function(s){s.style.display='';});
    // clear result panes
    for(var ti=0; ti<gTypes.length; ti++)  writeList(gTypes[ti], '<p>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;</p>');
  }else{
    // -- filters active
    // unhide/hide CEs with class ce_on_when_filters/ce_off_when_filters
    $$('.ce_on_when_filters' ).each(function(s){s.style.display='';});
    $$('.ce_off_when_filters').each(function(s){s.style.display='none';});
    // fill result panes...
    // build poly lists matching filter settings
    for(i=0; i<gPolys.length; i++){
      var py = gPolys[i];
      if(parseInt(py.g)>=sizeMin && parseInt(py.g)<=sizeMax && (district==0 || py.f.substr(0,2)==district) && (municipal==0 || py.m==municipal))  window['gPolyIds'+py.t].push(i);
    }
    // calc total match cnt
    var cntTotal = gPolyIds3.length+gPolyIds12.length+gPolyIdsX.length;
    
    
    if(cntTotal>maxMarkers){
      // to many results - show warning
      writeListMsg(gTxts.toManyRes, maxMarkers);
      
      for(var ti=0; ti<gTypes.length; ti++){
        var t=gTypes[ti];
        writeList(t, '<p style="color:red;">...</p>');
      }
    }else{
      // result cnt ok - show them
      for(var ti=0; ti<gTypes.length; ti++){
        var t=gTypes[ti];
        var s='';
        var ids = window['gPolyIds'+t];
        for(i=0; i<ids.length; i++){
          py = gPolys[ids[i]];

          if(gParams.markerlight){
            var marker = createPolyMarkerLight(py);
          }else{
            var marker = createPolyMarker(py);
          }
          gMarkers.push(marker);
          s+='<a class="gwListItem" href="javascript:parent.mClick('+(gMarkers.length-1)+')"><b>'+py.n+'</b><br>ca. '+addNumDot(py.g)+'m² – '+py.a+'</a>';
          gMap.addOverlay(marker);
//s+='<a class="gwListItem" href="javascript:void(0);"><b>'+py.n+'</b><br>ca. '+addNumDot(py.g)+'m² – '+py.a+'</a>';

        }
        writeList(t, s);
      }
    }
    document.getElementById('listCntTotal').innerHTML = '&nbsp;('+(cntTotal)+')';
    document.getElementById('listCnt3').innerHTML  = '&nbsp;('+gPolyIds3.length+')';
    document.getElementById('listCnt12').innerHTML = '&nbsp;('+gPolyIds12.length+')';
    document.getElementById('listCntX').innerHTML  = '&nbsp;('+gPolyIdsX.length+')';
  }

//  // hide progress indicators
//  document.getElementById('gwListProgress3').style.visibility =
//  document.getElementById('gwListProgress12').style.visibility=
//  document.getElementById('gwListProgressX').style.visibility = 'hidden';
}


// This function picks up the click and opens the corresponding info window
function mClick(n) {
  parent.gMarkers[n].showBubl(false, gClickZoom);  
  //gMap.openInfoWindowHtml(gPoints[i], gHtmls[i]);
}



function filterAdaptSizeMin(){
  while(parseInt(gFiltMinObj.value) >= parseInt(gFiltMaxObj.value))  --gFiltMinObj.selectedIndex;
}

function filterAdaptSizeMax(){
  while(parseInt(gFiltMinObj.value) >= parseInt(gFiltMaxObj.value))  ++gFiltMaxObj.selectedIndex;
}


// 123456.789 --> 123.456,789
function addNumDot(n){
  return n.toString().replace(/^(\d*?)(\d{1,3})([\.,](\d*))?$/, function($1,$2,$3,$4,$5){return ($2!=undefined&&$2!=''?$2+'.':'') + $3 + ($5!=undefined&&$5!=''?','+$5:'') }); //alert($1+'---'+ $2+'---'+ $3+'---'+ $4+'---'+ $5)});
}


function buildPolyInfoHtml(py){
  var earthRad = 6371000;
  var avail = '';
  switch(py.t){
    case '3':
      avail = 'Verfügbar innerhalb 3 Monaten<br>';
      break;
    case '12':
      avail = 'Verfügbar innerhalb 12 Monaten<br>';
      break;
    case 'X':
      avail = 'Verfügbar in frühestens 12 Monaten<br>';
      break;
  }
  var st = 
    '<b>'+py.n+'</b><br>'+
    'Flächennr. '+py.f+'<br>'+
    'Größe ca. '+addNumDot(py.g)+'m²<br>'+
    'Ausweisung '+py.a+'<br>'+
    avail+
    'Ausdehnung ca. '+10*Math.round(0.1*earthRad*Math.cos(py.u*Math.PI/180)*2*Math.PI/360*(py.r-py.l))+'m O-W, '+10*Math.round(0.1*earthRad*2*Math.PI/360*(py.o-py.u))+'m N-S'
  return st;
}

// A function to create the marker and set up the event window
function createPolyMarker(py) {
  //new GLatLng(py.c[0], py.c[1]), py.n, ''
  var markOpts = {};
  markOpts.icon = window['gIcon'+py.t];
  markOpts.title = py.n;
  var marker = new GMarker(new GLatLng(py.c[0], py.c[1]), markOpts);
  var html = buildPolyInfoHtml(py);
   
  marker.listenHandle = GEvent.addListener(marker, "click", marker.showBubl=function(point, minZoom){
    if(minZoom!=undefined && minZoom>gMap.getZoom()+2)  gMap.setZoom(minZoom);  // add 2, so zoom kicks in only at larger differences
    marker.show();
    marker.openInfoWindowHtml(html);
  });
  // save the info we need to use later for the side_bar
//  var i=gGmarkers.length;
//  gGmarkers[i] = marker;
//  gHtmls[i] = html;
  // add a line to the side_bar html
//  gListHtml += '<a class="gwListItem" href="javascript:myclick(' + i + ')"><b>' + label + '</b><br>' + data + '</a>';
  return marker;
}


// A function to create the marker and set up the event window - MARKERLIGHT VERSION!
function createPolyMarkerLight(py) {
  //new GLatLng(py.c[0], py.c[1]), py.n, ''

  var markOpts = {};
  var allowAs = '|G|GE|GI|SO|MI|';
  var myA = py.a.toUpperCase();
  if(allowAs.indexOf('|'+myA+'|')<0) myA='';
  markOpts.image = '/typo3conf/ext/dl_gewiss_gmaps/res/js/markerlight/pin'+py.t+myA+'.gif';
  markOpts.width  = 16;
  markOpts.height = 18;
  //markOpts.icon = window['gIcon'+py.t];
  //markOpts.title = py.n;
  var marker = new MarkerLight(new GLatLng(py.c[0], py.c[1]), markOpts);
  var html = buildPolyInfoHtml(py);
   
  marker.listenHandle = GEvent.addListener(marker, "click", marker.showBubl=function(point, minZoom){
    if(minZoom!=undefined && minZoom>gMap.getZoom()+2)  gMap.setZoom(minZoom);  // add 2, so zoom kicks in only at larger differences
    
    // PART 2 of 2 of strategy against interfering infowindows of markers and KML layer polies:
    //--
    // show delayed info bubble. 
    // This way we avoid the event to bubble up to the kml layer and open up another info window which overrides our marker info.
    //gMap.openInfoWindowHtml(marker.getPoint(), html);
    gMap.closeInfoWindow();
    setTimeout(function(){gMap.openInfoWindowHtml(marker.getPoint(), html)}, 300);
  });

  // save the info we need to use later for the side_bar
//  var i=gGmarkers.length;
//  gGmarkers[i] = marker;
//  gHtmls[i] = html;
  // add a line to the side_bar html
//  gListHtml += '<a class="gwListItem" href="javascript:myclick(' + i + ')"><b>' + label + '</b><br>' + data + '</a>';
  return marker;
}

/*
// NOT USED!!!
function createPoly(py, n){
  // count and limit the polies of each type (using window[] to address global dynamic vars)
//  if(++window['gCnt'+py.t] >10)  return null;

  // add a line to the side_bar html
  window['gList'+py.t+'Html']  += '<a class="gwListItem" href="javascript:myclick('+n+')"><b>'+py.n+'</b><br>ca. '+py.g+'m² – '+py.a+'</a>';

  var lcol = '#000000';
  var lwid = 0.5;
  var lopa = 1;
  var fcol = {c3:'#0000ff', c12:'#02dc00', cX:'#ffff00'}['c'+py.t];
  var fopa = 0.5;
  // read each point on that line
  var pts = [];
  for(var i=0; i<py.p.length; i+=2)  pts[i] = new GLatLng(py.p[i],py.p[i+1]);
  var myPoly = new GPolygon(pts,lcol,lwid,lopa,fcol,fopa);
  gMap.addOverlay(myPoly);
  var myPoint= new GLatLng(py.m[0], py.m[1]);
  var earthRad = 6371000;
  var myHtml = '<b>'+py.n+'</b><br>Flächennr. '+py.f+'<br>Größe ca. '+py.g+'m²<br>Ausweisung '+py.a+'<br>Ausdehnung ca. '+Math.round(earthRad*Math.cos(py.u*Math.PI/180)*2*Math.PI/360*(py.r-py.l))+'m O-W, '+Math.round(earthRad*2*Math.PI/360*(py.o-py.u))+'m N-S';
  function showInfoBubble() { gMap.openInfoWindowHtml(myPoint, myHtml); };
  // click event shows info bubble
  GEvent.addListener(myPoly, "click", showInfoBubble);
  
  // save the info we need to use later for the side_bar
  gHtmls[n] = myHtml;
  gPoints[n]= myPoint;
  return myPoly
}

// NOT USED!!!
function randomPoly(){
  // count and limit the polies of each type (using window[] to address global dynamic vars)
//  if(++window['gCnt'+py.t] >10)  return null;

  var lcol = '#000000';
  var lwid = 2.0;
  var lopa = 1;
  var fcol = '#ff0000';
  var fopa = 0.5;
  // read each point on that line
  var pts = [];
  for(var i=0; i<150; i++)  pts[i] = new GLatLng(49.36077+(-0.5+Math.random())*0.7, 7.01898+(-0.5+Math.random())*1);
  pts[i]=pts[0]; // close poly
  var myPoly = new GPolygon(pts,lcol,lwid,lopa,fcol,fopa);

  if(typeof(gRandomPoly)!='undefined'){
    gMap.removeOverlay(gRandomPoly);
  }
  gRandomPoly = myPoly;
  gMap.addOverlay(gRandomPoly);

  return myPoly
}
*/
