/**
* Mobilitaetsportal Rheinland-Pfalz
* 
* @version $Id: openlayers_init_verkehrslage.js 762 2011-09-15 18:59:49Z  $
*/


/* globals: Layer */ 
var map,rlp,bgtile,labelingtile,rlpbeschriftung,rlplos,mzlos,rlplostile,kllos,rlptile,lcl,webcams,viz,baustellen,parkplatz,gmaicon,dwd,dwdicon,karllos,adac_parkplatz; 
var popup;

function init(){
  /* set map height */
  FensterResize();
  
  // proxy host
  OpenLayers.ProxyHost = "/www/cgi-bin/proxy.cgi?url=";
  
  var options = {
                maxExtent: new OpenLayers.Bounds(2365887,5310674,2817545,5762332)
                ,maxResolution: "auto"
                ,scales: [1000000,500000,250000,100000,50000,25000,10000]
                ,units: 'm'
                ,projection: 'EPSG:31466'
                ,controls: []
                };

  map = new OpenLayers.Map('map', options);
  OpenLayers.IMAGE_RELOAD_ATTEMPTS = 10;
  OpenLayers.Util.onImageLoadErrorColor = "transparent";

                 
  /* Background tiles*/
  bgtile = new OpenLayers.Layer.WMS(
                "Background Tile"
                ,urlArray
                ,{
                  layers:'bg',
                  format:'image/png',
                  projection:'EPSG:31466'
                }
                ,{'buffer':0, transitionEffect: 'resize'}
                );
         
  /* Overlays: transparent: true */
  /* Labeling tiles */
  labelingtile = new OpenLayers.Layer.WMS(
                "Beschriftung"
                ,urlArray
                ,{
                  layers:'labeling',
                  format:'image/png', 
                  projection:'EPSG:31466',
                  transparent: true
                 }
                ,{'buffer':0}
                );  
  

  /* Level of Service */
  losurl=urlMapserver+"map=../map/los_201008.map";
  rlplos = new OpenLayers.Layer.WMS(
                "LOS"
                ,losurl
                ,{
                  layers:'los_0,los_1,los_2,los_centerline,los_1_mz,los_2_mz,los_centerline_mz,los_1_kl,los_2_kl,los_centerline_kl,maske',
                  format:'image/png',
                  projection:'EPSG:31466',
                  transparent: true
                 }
                ,{'singleTile': true}
                );
  rlplos.setVisibility(true);
  
  /* Level of Service Karlsruhe */
  loskarlurl=urlMapserver+"map=../map/karlsruhe_wfs.map";
  karllos =  new OpenLayers.Layer.WMS(
                "Karlsruhe LoS"
                ,loskarlurl
                ,{
                  layers:'LevelofService,los_centerline',
                  format:'image/png',
                  projection:'EPSG:31466',
                  transparent: true
                 }
                ,{'singleTile': true}
                );               
  karllos.setVisibility(true);                 
               

  /* DWD Wetterwarnungen Landkreise Polygone*/
  if (browser.isIE6){
    dwdurl=urlMapserver+"map=../map/dwdIE6.map";
  } else {
    dwdurl=urlMapserver+"map=../map/dwd.map";
  }
  
  dwd = new OpenLayers.Layer.WMS(
                "DWD"
                ,dwdurl
                ,{
                  layers:'dwd,maske',
                  format:'image/png',
                  projection:'EPSG:31466',
                  transparent: true
                 }
                //,{'alpha': true }
                ,{'singleTile': true}
                );
  dwd.setVisibility(true);


  /* Baustellen aus Textfile */
  baustellen = new EnhancedTextLayer( "Baustellen", {location: "syncdata/baustellen.txt"+"?"+Math.random()} );
  baustellen.setVisibility(false);

  /* Verkehrsmeldungen aus Textfile */
  viz = new EnhancedTextLayer( "Verkehrsmeldungen", {location: "syncdata/verkehrsmeldungen.txt"+"?"+Math.random()} );
  viz.setVisibility(true);

  /* ADAC-Parkplatzbelegung aus Textfile */
  adac_parkplatz = new EnhancedTextLayer( "ADAC-Parkplatz", {location: "syncdata/adac_parkplatz.txt"+"?"+Math.random()} );
  adac_parkplatz.setVisibility(true);

  /* Parkplatz aus Textfile */
  parkplatz = new EnhancedTextLayer( "Parkplatz", {location: "syncdata/parkplatz.txt"+"?"+Math.random()} );
  parkplatz.setVisibility(true);

  /* Webcams aus Textfile */
  webcams = new EnhancedTextLayer( "Webcams", {location: "syncdata/webcams.txt"+"?"+Math.random()} );
  webcams.setVisibility(false);

  /* gma aus Textfile */
  gmaicon = new EnhancedTextLayer( "GMA-Icon", {location: "syncdata/gma.txt"+"?"+Math.random()} );
  gmaicon.setVisibility(false);

  /* dwd aus Textfile */
  dwdicon = new EnhancedTextLayer( "DWD-Icon", {location: "syncdata/weather_warnings.txt"+"?"+Math.random()} );
  dwdicon.setVisibility(true);

  /* Add Layers */		
  map.addLayers([bgtile, dwd, rlplos, karllos, labelingtile,  dwdicon, gmaicon, viz, baustellen, webcams, parkplatz, adac_parkplatz]);



  /* Controls */			
  map.addControl(new OpenLayers.Control.PanZoomBar());
  map.addControl(new OpenLayers.Control.MouseDefaults());
  map.addControl(new OpenLayers.Control.Permalink('permalink'));
  //map.addControl(new OpenLayers.Control.MousePosition());
  //map.addControl(new OpenLayers.Control.Scale());


  /* Popup-style 259,160*/
  OpenLayers.Popup.HEIGHT = 240;
  OpenLayers.Popup.WIDTH = 280;
  OpenLayers.Popup.COLOR = "#f8f8f8";
  OpenLayers.Popup.BORDER = "1px #386090 solid";
  OpenLayers.Popup.OPACITY = "1.0";


  /* set startpoint and zoom */ 
  //map.setCenter(new OpenLayers.LonLat(2592821,5561988),1);
  //map.setCenter(new OpenLayers.LonLat(2597584,5535000),0);
  if(!map.getCenter()) map.zoomToMaxExtent();
  
  
  
  /* update timestamps */
  requestRlpTimestamp('rlp_timestamp');
  //updateTimestamp('rlp_timestamp');
  //updateTimestamp('time_loskl');
  //updateTimestamp('time_losmz');
  //updateTimestamp('time_dwd');
  //updateTimestamp('time_gma');
  //updateTimestamp('time_roadworks');
  //updateTimestamp('time_viz');
  //updateTimestamp('time_parkplatz');

  /* update checkbuttons */
  updateCheckButtons();
  
  /* timer für reload */
  new update("", 100, 'time_los', updateLayerRlplos, 1000, true);
  //new update("", 100, 'time_loskl', updateLayerKllos, 1000, true);
  //new update("", 100, 'time_losmz', updateLayerMzlos, 1000, true);
  new update("", 900, 'time_dwd', updateDwd, 1000, true);
  new update("", 900, 'time_roadworks', updateIconBaustellen, 1000, true);
  new update("", 150, 'time_viz', updateIconViz, 1000, true);
  new update("", 300, 'time_parkplatz', updateIconParkplatz, 1000, true);
  new update("", 300, 'time_adac_parkplatz', updateIconAdacParkplatz, 1000, true);
  new update("", 900, 'time_gma', updateIconGma, 1000, true);
  new update("", 150, 'time_webcams', updateIconWebcams, 1000, true);
 
 
  /* register mouseclick for tooltips: removes tooltip */
  map.events.register('click', map, function (e) {  
    if(this.popups.length>0){
      for (var i = this.popups.length - 1; i >= 0; --i) {
        this.removePopup(this.popups[i]);
      }
    } else {
     //
    }
  }); 
 
 
}




/*#################################################################*/
/* toggle visibility */
/*#################################################################*/
function toggleVisibility(layer, buttonname){
  if(document.getElementById(buttonname).checked==false){
    layer.setVisibility(false);
  } else {
    layer.setVisibility(true);
  }
}
function toggleIcon(layer, buttonname, element, iconon, iconoff){
  if(document.getElementById(buttonname).checked==false){
    document.getElementById(element).src=iconon;
  } else {
    document.getElementById(element).src=iconoff;
  }
}




/*#################################################################*/
/* Update Iconlayer */
/*#################################################################*/
/* usage:
updateIconLayer(baustellen, "Baustellen", "baustellen.txt") ;
TODO: this generic function does't work, may be because of the layername...! 
*/
function updateIconLayer(layer, layername, file){
  // update Textlayer : destroy -> create new
  isVisible = layer.getVisibility();
  layer.destroy();
  //layer = new OpenLayers.Layer.Text( layername , {location: file+"?"+Math.random()} );
  layer = new EnhancedTextLayer( layername , {location: file+"?"+Math.random()} );
  map.addLayers([layer]);
  //layer.setVisibility(isVisible);
}

/* so update each Icon-Layer manually...*/
function updateIconBaustellen(){
  isVisible = baustellen.getVisibility();
  baustellen.destroy();
  baustellen = new EnhancedTextLayer( "Baustellen" , {location: "syncdata/baustellen.txt"+"?"+Math.random()} );
  map.addLayers([baustellen]);
  baustellen.setVisibility(isVisible);
}
function updateIconGma(){
  isVisible = gmaicon.getVisibility();
  gmaicon.destroy();
  gmaicon = new EnhancedTextLayer( "GMA-Icon" , {location: "syncdata/gma.txt"+"?"+Math.random()} );
  map.addLayers([gmaicon]);
  gmaicon.setVisibility(isVisible);
}
function updateIconParkplatz(){
  isVisible = parkplatz.getVisibility();
  parkplatz.destroy();
  parkplatz = new EnhancedTextLayer( "Parkplatz" , {location: "syncdata/parkplatz.txt"+"?"+Math.random()} );
  map.addLayers([parkplatz]);
  parkplatz.setVisibility(isVisible);
}
function updateIconAdacParkplatz(){
  isVisible = adac_parkplatz.getVisibility();
  adac_parkplatz.destroy();
  adac_parkplatz = new EnhancedTextLayer( "ADAC-Parkplatz" , {location: "syncdata/adac_parkplatz.txt"+"?"+Math.random()} );
  map.addLayers([adac_parkplatz]);
  adac_parkplatz.setVisibility(isVisible);
}
function updateIconViz(){
  isVisible = viz.getVisibility();
  viz.destroy();
  viz = new EnhancedTextLayer( "Verkehrsmeldungen" , {location: "syncdata/verkehrsmeldungen.txt"+"?"+Math.random()} );
  map.addLayers([viz]);
  viz.setVisibility(isVisible);
}
function updateIconDwd(){
  isVisible = dwdicon.getVisibility();
  dwdicon.destroy();
  dwdicon = new EnhancedTextLayer( "DWD-Icon" , {location: "syncdata/weather_warnings.txt"+"?"+Math.random()} );
  map.addLayers([dwdicon]);
  dwdicon.setVisibility(isVisible);
}
function updateIconWebcams(){
  isVisible = webcams.getVisibility();
  webcams.destroy();
  webcams = new EnhancedTextLayer( "Webcams" , {location: "syncdata/webcams.txt"+"?"+Math.random()} );
  map.addLayers([webcams]);
  webcams.setVisibility(isVisible);
}

/* Update WMS Layer */
function updateLayer(layer){
    layer.mergeNewParams({'uniqueName': Math.random()});
}

function updateLayerRlplos(){
    rlplos.mergeNewParams({'uniqueName': Math.random()});
    karllos.mergeNewParams({'uniqueName': Math.random()});
    requestRlpTimestamp('rlp_timestamp');
}
function updateLayerKllos(){
    kllos.mergeNewParams({'uniqueName': Math.random()});
}
function updateLayerMzlos(){
    mzlos.mergeNewParams({'uniqueName': Math.random()});
}
function updateLayerDwd(){
    dwd.mergeNewParams({'uniqueName': Math.random()});
}

/* Meta-update */
function updateDwd(){
  updateLayerDwd();
  updateIconDwd();
}


/*#################################################################*/
/* update Date */
/*#################################################################*/
function updateDate(){
  var element = document.getElementById("today_date");
  var today = new Date();
  var tage=new Array("Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag","Sonntag");

  element.innerHTML=tage[today.getDay()]+", "+today.getDate()+"."+(today.getMonth()+1)+"."+today.getFullYear();
}

function leadingzero (number) {
    return (number < 10) ? '0' + number : number;
}

function updateTimestamp(elementid){
  var element = document.getElementById(elementid);
  var today = new Date();

  var h,m,s;
  h=leadingzero(today.getHours());
  m=leadingzero(today.getMinutes());
  s=leadingzero(today.getSeconds());

  //element.innerHTML="Verkehrslage: "+h+":"+m+":"+s;
  element.innerHTML=""+h+":"+m+"Uhr";
  
}

// timestamp
function requestRlpTimestamp(elementid){
  var element = document.getElementById(elementid);
  
  OpenLayers.loadURL(urlInfo, '', this, setRlpTimestamp);

  function setRlpTimestamp(response){
    if(element!=null){
      element.innerHTML=response.responseText;      
    }
  }
}


//<input id=check_kllos type=checkbox name=\"check_klplos\"
function updateCheckButtons(){

    document.getElementById('check_roadworks').checked=baustellen.getVisibility();
    document.getElementById('check_dwd').checked=dwd.getVisibility();
    document.getElementById('check_gmaicon').checked=gmaicon.getVisibility();
    document.getElementById('check_viz').checked=viz.getVisibility();
    document.getElementById('check_webcams').checked=webcams.getVisibility();
    document.getElementById('check_rlplos').checked=rlplos.getVisibility();
    //document.layerform.check_mzlos.checked=mzlos.getVisibility();
    //document.layerform.check_kllos.checked=kllos.getVisibility();
    document.getElementById('check_beschriftung').checked=labelingtile.getVisibility();
 
}




Function.prototype.Timer = function (interval, calls, onend) {
  var count = 0;
  var payloadFunction = this;
  var startTime = new Date();
  var callbackFunction = function () {
    return payloadFunction(startTime, count);
  };
  var endFunction = function () {
    if (onend) {
      onend(startTime, count, calls);
    }
  };
  var timerFunction =  function () {
    count++;
    if (count < calls && callbackFunction() != false) {
      window.setTimeout(timerFunction, interval);
    } else {
      endFunction();
    }
  };
  timerFunction();
}

/* 
generic update function 
new update(label, countdown-interval, html-tag-id, update-function, step);

example: 
new update("Sperrungen in ", 120, 'roadworksCounter', updateRoadworks, 1000, true);
*/
function update(label, interval, target, func, step, show) {
  var element = document.getElementById(target);
  var count = 0;
  var doSomething = function () {
    if (count < interval-1) {
      // do this every step
      if(show && element){
      element.innerHTML=label+" "+(interval-count-1)+"s";
      }
	  count++;
    } else {
      if(show && element){
      element.innerHTML=label+" "+(interval-count-1)+"s";
      }
	  count=0;
      if(func){ 
	    func();
	  }
    }
  };
  var completed = function () {
  };
  // set counting step to 1 sec per default
  if( !step ){ 
    step = 1000;
  } 
  
  doSomething.Timer(step, Infinity, completed);
};






