var startMarker = null;
var destMarker = null;
var bigConnMap;

// ngr 2009-12-21: bool if big detail map (=true) or mapsearch (=false) is opened; default false
var bigMapOpened = false;


////////////////////////////////////////////////////////////
// Der IE hat 2 verschiedene Objekte für den strict und quirks Mode.
function getBody(w)
{
    return (w.document.compatMode && w.document.compatMode == "CSS1Compat") ? w.document.documentElement : w.document.body || null;
}

function openSuggestListManually(g,findex,loc,keymode){
    currentKC=(g)?g.keyCode:window.event.keyCode;
    if((currentKC==13) || (keymode == false)) {
        SLs.sls = eval(loc+'sls');
        SLs.inputField=document.getElementById(loc);
        fieldIndex=findex;
        gFSuggestInstances[fieldIndex].showSuggestionList = true;
        SLs.showSuggestion(fieldIndex,false);
        document.getElementById(loc).focus();
    }
}
function toggleMapMenu(id){
    if(document.getElementById(id).style.height != '16px') {
        document.getElementById(id).style.height = '16px';
        document.getElementById(id+'Content').style.display = 'none';
        document.getElementById(id+'Arrow').src = document.getElementById(id+'Arrow').src.replace("up","down");
    }else{
        document.getElementById(id).style.height = '';
        document.getElementById(id+'Content').style.display = 'block';
        document.getElementById(id+'Arrow').src = document.getElementById(id+'Arrow').src.replace("down","up");
    }
}


function $for(obj, callback){
 var proto = obj.constructor.prototype,
  h = obj.hasOwnProperty, key;
 for(key in obj) {
  if((h && h.call(obj,key)) || proto[key] !== obj[key])
   callback(key, obj[key]);
 }
};

function cssTest(){
  var CSStestDiv = document.getElementById('cssTest');
  if(CSStestDiv !== undefined){
       if(CSStestDiv.offsetHeight === 2){
       // CSS verfügbar
       }else{
          document.getElementById('mapLayer').innerHTML = '';
       }
       document.body.removeChild(document.getElementById('cssTest'));
  }
}

function addMapParameters(obj,multi){
   if(typeof AjaxMaps != 'undefined') {
       addMapParams = '';
       $for(AjaxMaps, function(key, value){
           var currStr = AjaxMaps[key].getJMapURLParams();
           currStr = currStr.replace(/MapCenterX/g,"MapCenterX"+key);
           currStr = currStr.replace(/MapCenterY/g,"MapCenterY"+key);
           currStr = currStr.replace(/MapScaling/g,"MapScaling"+key);
           addMapParams += currStr;
          // alert(AjaxMaps[key].getURLParams());
           //addMapParams += '&'+key+getMapIcons(key);

       });
       if((typeof openedMapWindows != 'undefined') && (typeof multi == 'undefined')) {
         var count = 0;
         for(var i=0; i < openedMapWindows.length; i++){
          if(typeof connMap[openedMapWindows[i]] != 'undefined') {
              if(openedMapStatus[openedMapWindows[i]]==true) {
                  if(count==0) {
                     addMapParams += "&mapDisplay=ajaxmap&performGis=1&"
                  }
                  addMapParams += "REQMap"+count+"ConnectionId="+openedMapWindows[i]+"&"; // ConnId
                  if(openedMapWindows[i].indexOf("IV") != -1) {
                       addMapParams += "REQMap"+count+"ConnectionSection=COMPLETE&"; // Section
                   }else{
                       if(typeof connMap[openedMapWindows[i]].conn.sections[0].gisRouteType != "undefined") {
                          if(connMap[openedMapWindows[i]].conn.sections[0].gisRouteType == 2){
                            addMapParams += "REQMap"+count+"ConnectionSection=START&"; // Section
                          }
                       }
                       if(typeof connMap[openedMapWindows[i]].conn.sections[(connMap[openedMapWindows[i]].conn.sections.length-1)].gisRouteType != "undefined") {
                           if(connMap[openedMapWindows[i]].conn.sections[(connMap[openedMapWindows[i]].conn.sections.length-1)].gisRouteType == 2){
                             addMapParams += "REQMap"+count+"ConnectionSection=END&"; // Section
                          }
                       }
                   }
                   addMapParams += "REQMap"+count+"ConnectionDisplayModeGis=ROUTING&"; // GisMode Type
                   addMapParams += "REQMap"+count+"Output=TPL&";
                   count++;
              }
          }
         }
       }
       obj.href += '&'+addMapParams;
   }
}


function placeMarker(map,x,y,image){

}
function openLayerMap(inputf,connid,mapparam){
  $('mapLayer').style.display = 'block';
  $('mapSearchHeadline').style.display = 'block';
  $('walkStartLink').style.display = 'none';
  $('stationStartLink').style.display = 'none';
  $('walkEndLink').style.display = 'none';
  $('stationEndLink').style.display = 'none';
  $('routeLink').style.display = 'none';
  $('location').value = "";  
  if((navigator.userAgent.toLowerCase().indexOf('msie') != -1) && (navigator.userAgent.toLowerCase().indexOf('6.0') != -1)) {
     $('depOrArr').style.width = '0px';
     $('journeyDate').style.width = '0px';
  } 
  $('mapLayer').style.left = '40px';
  if(typeof window.pageYOffset == 'undefined') {
     var windowScrolled = document.documentElement.scrollTop;
  }else{
     var windowScrolled = window.pageYOffset;
  }
  document.getElementById('mapLayer').style.top = 40 + windowScrolled + 'px';
  document.getElementById('mapLayer').style.width = (document.body.clientWidth-100)+'px';
  if(typeof window.innerHeight != 'undefined') {
     var windowheight = window.innerHeight;
  }else{
       var obj = getBody(window);
       var windowheight = parseInt(obj.clientHeight);
  }
  $('mapLayer').style.height = (windowheight-90)+'px';
  $('map').style.width = (document.body.clientWidth-100)+'px';
  $('map').style.height = (windowheight-210)+'px';
  document.getElementById('mapDisplayBox').style.marginTop = '';
  document.getElementById('mapDisplayBoxContent').style.marginTop = '';
  $('mapLayerGreyedOut').style.height = document.documentElement.scrollHeight + 'px';
  $('mapHeadline').style.display = 'none';
  if($('mapLayer')!=null){
      $('mapLayerGreyedOut').style.display = 'block';
      $('mapLayerGreyedOut').style.height = document.documentElement.scrollHeight + 'px';
      // ngr 2009-12-09: no if-condition to avoid dependencies between start and destination location
      if(typeof Map_map == 'undefined') {
          showAjaxMap_map();
          //var result = '';
          for(var i=0;i < imap_content_checkbox_datamap.length;i++) {
              if(typeof imap_content_checkbox_datamap[i] != 'undefined') {
                 imap_content_checkbox_setstate(i, "checkeddisabled",imap_content_checkbox_datamap); 
              }
          }

      }
      
      // ngr 2009-12-21: leave it as false, when it's just mapsearch
      bigMapOpened = false;

      if(typeof connid != 'undefined') {
          // ngr 2009-12-21: big detail map -> set new status
          bigMapOpened = true;
          if(navigator.userAgent.toLowerCase().indexOf('msie') != -1) {
              document.getElementById('mapDisplayBox').style.marginTop = '-70px';
              document.getElementById('mapDisplayBoxContent').style.marginTop = '-70px';
          }else{
              document.getElementById('mapDisplayBox').style.marginTop = '-55px';
              document.getElementById('mapDisplayBoxContent').style.marginTop = '-55px';
          }
          document.getElementById('map').style.height = parseInt(document.getElementById('map').style.height)+60+'px';
          document.getElementById('mapSearchHeadline').style.display = 'none';
          var realid = connid.replace("-","_");
          document.getElementById('mapLayer').style.height = parseInt(document.getElementById('mapLayer').style.height) + 15 + "px";
          bigConnMap = new CHafasConnectionMap( Map_map, eval("jsonObj"+realid), {showGisRouteType0:false,opacityfactor:1.0} );
          //Map_map.disableRightClick();
          document.getElementById('mapHeadline').style.display = 'block';
          document.getElementById('mapCenterOptions').style.display = 'block';
          // Determine which Links should be displayed under the map
          document.getElementById('routeLink').style.display = 'inline';
          document.getElementById('routeLink').onclick = function(){
              bigConnMap.centerRoute();
          };
          if(bigConnMap.conn.sections[0].type == "GIS_ROUTE") {
              document.getElementById('walkStartLink').style.display = 'inline';
              document.getElementById('walkStartLink').onclick = function(){
                 bigConnMap.centerStart();
              };
          }else{
              document.getElementById('stationStartLink').style.display = 'inline';
              document.getElementById('stationStartLink').onclick = function(){
                 bigConnMap.centerStart();
              };
          }
          if(bigConnMap.conn.sections[bigConnMap.conn.sections.length-1].type == "GIS_ROUTE") {
              document.getElementById('walkEndLink').style.display = 'inline';
              document.getElementById('walkEndLink').onclick = function(){
                  bigConnMap.centerEnd();
              };
          }else{
              document.getElementById('stationEndLink').style.display = 'inline';
              document.getElementById('stationEndLink').onclick = function(){
                  bigConnMap.centerEnd();
              };
          }
          bigConnMap.show();
          // getZoomLevel
          mapparam.match(/MapScaling=(\d+)/);
          Map_map.setZoom(RegExp.$1);
          mapparam.match(/MapCenterX=(\d+)/);
          var centerX = RegExp.$1;
          mapparam.match(/MapCenterY=(\d+)/);
          var centerY = RegExp.$1;
          Map_map.centerToGeo(new CCoord({lon:centerX,lat:centerY}));
      }
  }
  if((inputf != null) && (document.getElementById(inputf).value.length > 0)) {
     document.getElementById('location').value = document.getElementById(inputf).value;
     searchOnMap();
  }
  Map_map.updateSize();

}

function getCurrentHeight(){


}

function getProductFilter(prodclass){
   var prodclass = parseInt(prodclass).toString(2);
   var prodclassDelta = 10 - prodclass.length;
   prodclass = prodclass.split("").reverse().join("");

   for(var i=0;i < prodclassDelta; i++) {
       prodclass+='0';
   }
   return prodclass;
}

function getCheckboxValues(id){
   var obj = eval('imap_content_checkbox_data'+id);
   var result = '';
   for(var i=0;i < obj.length;i++) {
       if(typeof obj[i] != 'undefined') {
          imap_content_checkbox_setstate(i-1, obj[i].state,imap_content_checkbox_datamap);
       }
   }
}

function closeLayerMap(){
  if(document.getElementById('mapLayer')!=null){
      if(bigConnMap != null) {
       bigConnMap.hide();
      }
      document.getElementById('mapLayer').style.display = 'none';
      document.getElementById('mapLayerGreyedOut').style.display = 'none';
      if((navigator.userAgent.toLowerCase().indexOf('msie') != -1) && (navigator.userAgent.toLowerCase().indexOf('6.0') != -1)) {
         document.getElementById('depOrArr').style.width = '';
         document.getElementById('journeyDate').style.width = '';
      }

  }
}

function placePin(type,x,y,img){
 Map_map.hideContent(eval(type+'Marker'));
 Map_map.removeContent(eval(type+'Marker'));
   var pin = Map_map.createContent({
      type:"location",
      hotspot:{x:23,y:34},
      coord: new CCoord({
        lon:x,lat:y
      }),
      imageurl:img
   });
   if(type == 'start') { startMarker = pin; }
   else if(type == 'dest') { destMarker = pin; }
   Map_map.showContent(pin);
   closeLayerMap();
}

function decodeName(at){
    var t = at.replace(/&ouml;/g, 'ö');
      t = t.replace(/&auml;/g, 'ä');
      t = t.replace(/&uuml;/g, 'ü');
      t = t.replace(/&Auml;/g, 'Ä');
      t = t.replace(/&Uuml;/g, 'Ü');
      t = t.replace(/&Ouml;/g, 'Ö');
      t = t.replace(/&#252;/g, 'ü');
      t = t.replace(/&#246;/g, 'ö');
      t = t.replace(/&#228;/g, 'ä');
      t = t.replace(/&#226;/g, 'â');
      t = t.replace(/&#223;/g, 'ß');
      t = t.replace(/&#196;/g, 'Ä');
      t = t.replace(/&#214;/g, 'Ö');
      t = t.replace(/&#220;/g, 'Ü');
      t = t.replace(/&#248;/g, 'ø');
      t = t.replace(/&#216;/g, 'Ø');
      t = t.replace(/&#229;/g, 'å');
      t = t.replace(/&#197;/g, 'Å');
      t = t.replace(/&#230;/g, 'æ');
      t = t.replace(/&#198;/g, 'Æ');
      t = t.replace(/&#233;/g, 'é');
      t = t.replace(/&#232;/g, 'è');
      t = t.replace(/&#156;/g, 'œ');
      t = t.replace(/&#140;/g, 'Œ');
      //t = t.replace(/&#/g, '');
      return t;
};

function searchOnMap(){
      var searchterm = $('location').value;
      if(tempLocation != null){
          Map_map.hideContent(tempLocation);
          Map_map.removeContent(tempLocation);
      }
      var url = gUrlAjaxGetStop + '&suggestMethod=none&start=1&iER=yes&tpl=stopsugg2json&getstop=1&REQ0JourneyStopsS0A=255&REQ0JourneyStopsB=1&S='+searchterm+'&js=true&';
      new Ajax.Request(url,{
          method: 'post',
          onComplete: function(o){
              //  obj = eval('('+o.responseText+')');
              //  obj.value = obj.value.replace(/&#x0028;/g,"(");
              //  obj.value = obj.value.replace(/&#x0029;/g,")");
                eval(o.responseText);
                obj = SLs.sls.suggestions[0];

                $('location').value = obj.value;

                obj.id.match(/L=(\d+)/);
                obj.evaId = RegExp.$1;

                var image;
                var locparams = {
                   type:'location',
                   coord: new CCoord({x:obj.xcoord,y:obj.ycoord}),
                   imagewidth: 19,
                   imageheight: 19,
                   hotspot: {x:9,y:9}
                };
                switch(parseInt(obj.type)){
                    case 1:
                    locparams.infocontent=infotextstation({map:Map_map,extId:obj.evaId,name:obj.value.toString(),x:obj.xcoord,y:obj.ycoord,productFilter:getProductFilter(obj.prodClass)}); //map,extId,puic,name,x,y
                    locparams.infotitle= "<table><tr><td>"+obj.value.toString()+"</td></tr></table>";
                    locparams.imageurl = gImagePath+'location.png';
                    break;
                    case 2:
                    locparams.infocontent=infotextaddress({map:Map_map,extId:obj.evaId,name:obj.value.toString(),x:obj.xcoord,y:obj.ycoord}); //map,extId,puic,name,x,y
                    locparams.infotitle=obj.value.toString();
                    locparams.imageurl = gImagePath+'location.png';
                    break;
                    case 4:
                    locparams.infocontent=infotextpoi({map:Map_map,extId:obj.evaId,name:obj.value.toString(),x:obj.xcoord,y:obj.ycoord}); //map,extId,puic,name,x,y
                    locparams.infotitle= "<table><tr><td>"+obj.value.toString()+"</td></tr></table>";
                    locparams.imageurl = gImagePath+'location.png';
                    break;
                }
                if(typeof infotextpoi=='undefined')alert("2 infotextpoi not defined");
                tempLocation = Map_map.createContent(locparams);
                Map_map.showContent(tempLocation);
                Map_map.centerToContent(tempLocation);
                Map_map.setZoom(1100);
          }
      });
  }
