var currentLayerMap = ''; // determines the current opened

// Hilfsfunktionen
function eID(id){
  return document.getElementById(id);
}

function eName(name){
  return document.getElementsByName(name);
}

function classNameAdd(node,className){
  var regString = "\\s"+className+"\\s";
  var regExClass = new RegExp(regString,"g");
  if((node) && ((" "+node.className+" ").match(regExClass) == null))
    node.className += " "+ className;
}

function classNameRemove(node,className){
  var regString = "\\b"+className+"\\b";
  var regExClass = new RegExp(regString,"g");
  if(node)
    node.className = node.className.replace(regExClass," ").replace(/^\s/,"").replace(/\s$/,"").replace(/\s+/g," ");
}

function listenToEvent(node,eventHandler,func){
  if(node.addEventListener)
    {
    node.addEventListener(eventHandler,function(){func.apply(node,arguments);},false);
    }
  else if(node.attachEvent)
    {
    node.attachEvent("on"+eventHandler,function(){func.apply(node,arguments);});
    }
}

function enableAllChildren(root, state){
  var childNodes = root.childNodes;

  for(var i = 0; i < childNodes.length; i++)
  {
  var node = childNodes[i];
  if(typeof(node.disabled) != "undefined")
    node.disabled = state;
  enableAllChildren(node,state);
  }
}

function showAndHide(event,showEl, hideEl){
  classNameRemove(eID(showEl),'hide');
  classNameAdd(eID(hideEl),'hide');
  // convince IE to show link
  eID('flap'+showEl).focus();
  eID('flap'+showEl).blur();
  if (event.preventDefault)
    {
    event.preventDefault();
    event.stopPropagation();
    }
  else
    {
    event.returnValue = false;
    event.cancelBubble = true;
    }
}

// default input values
// --------------------

// delete default value of input field
function delDefaultValue(ereignis){
  var currentDefaultValue = defaultStringIndex[this.name];
  if(this.value.replace(/^\s+/, "").replace(/\s+$/, "") == defaultString[currentDefaultValue])
    this.value = "";
}

// set default value of input field if it's empty
function setDefaultValue(ereignis){
  if((typeof(adjustProductLabels) != "undefined") && (typeof(adjustLabel) != "undefined"))
    {
    var labelsAdjusted = false;
    var direction = this.name.charAt(3);
    var section = this.name.charAt(this.name.length-2);
    if(section == "0")
      section = this.name.charAt(this.name.length-3);
    var cname = this.value.replace(/^\s+/, "").replace(/\s+$/, "");
    if(cname != "")
      {
      var idField = eName(this.name.replace(/G$/,"ID"))[0];
      if((idField) && (idField.value!= "") && (idField.value.indexOf("="+cname+"@") >= 0))
        {
        adjustProductLabels("add",direction,section,cname);
        labelsAdjusted = true;
        }
      }
    if(!labelsAdjusted)
      adjustProductLabels("del",direction,section);
    }
  var currentDefaultValue = defaultStringIndex[this.name];
  var currentInput = "";
  if(this.value.replace(/^\s+$/, "") == "")
  {
    this.value = defaultString[currentDefaultValue];
    if(this.name == "REQ0JourneyStopsS0G")
      currentInput = "S";
    else if(this.name == "REQ0JourneyStopsZ0G")
      currentInput = "Z";
    if(currentInput != "")
    {
      var currentInputField = eName("REQ0JourneyStops"+currentInput+"ID")[0];
      if(currentInputField != null)
        currentInputField.value ="";
    }

  }
  else if((this.name == "REQ0JourneyStops1G") && !(sectionStatus[0][1]))
  {
   // special for 1st via
   sectionStatus[0][1] = true;
   eID("prod_sec_0_0_moreSections").className = "";
   eID("prod_sec_0_0_oneSection").className = "hide";
   if(productsDetailed)
     {
     showProductRow(0,1);
     if((diffMOTRet) && (!sectionStatus[1][1]))
        showProductRow(1,1);
     }
   if((typeof(adjustProductLabels) != "undefined") && (typeof(adjustLabel) != "undefined"))
     adjustProductLabels("shift");
  }
  else if(this.name == "REQ0JourneyStopsS0G")
    currentInput = "S";
  else if(this.name == "REQ0JourneyStopsZ0G")
    currentInput = "Z";
  /*
  if((currentInput != "") && (typeof(intermodalStatus) != "undefined"))
  {
    // check if input is an address
    var currentInputField = eName("REQ0JourneyStops"+currentInput+"0ID")[0];
    if(currentInputField != null)
    {
      var regExpression = /A=(\d)@/;
      var regExprResult = regExpression.exec(currentInputField.value);
      var flag = ((regExprResult != null) && ((regExprResult[1] == 2) || (regExprResult[1] == 4)))
      //showIntermodal(currentInput,flag);
    }
  }
  */
}

function checkViaG(viaField){
  if(!(viaField.value.match(/\S/)))
    {
    var idField = eID(viaField.id+"ID");
    if(idField)
      idField.value = "";
    }
}

function removeDefaultValues(flag){
  for(var i = 0; i < inputFields.length; i++)
  {
    var inputField = eName(inputFields[i].name)[0];
    if(typeof(inputField) != "undefined")
    {
      if(flag)
      {
        if(inputField.value.replace(/^\s+/, "").replace(/\s+$/, "") == defaultString[inputFields[i].strIndex])
          inputField.value = "";
      }
      else
      {
        if(inputField.value.replace(/^\s+$/, "") == "")
          inputField.value = defaultString[inputFields[i].strIndex];

        defaultStringIndex[inputFields[i].name] = inputFields[i].strIndex;
        listenToEvent(inputField,"focus",delDefaultValue);
        listenToEvent(inputField,"blur",setDefaultValue);
      }
    }
  }
  return true;
}

/**
 *  resets location - select box to input field
 */
function resetLocation(direction,reslocation,index){
  if(typeof(index) == "undefined")
    index = 0;
  if(isNaN(reslocation))
    var selectBox = eID("REQ"+direction+"JourneyStops"+reslocation+index+"K");
  else
    var selectBox = eID("REQ"+direction+"JourneyStops"+reslocation+"K");
  var container = selectBox.parentNode;
  container.removeChild(selectBox);
  container.className = container.className.replace(/\blocInput\b/," ");
  selectBox = null;
  if(isNaN(reslocation))
    var inputField = eID("loc"+reslocation+index);
  else
    var inputField = eID("locREQ"+direction+"JourneyStops"+reslocation+"K");
  inputField.style.display = "inline";
  inputField.disabled = false;
  if(isNaN(reslocation))
    var inputID = eID("loc"+reslocation+index+"ID");
  else
    var inputID = eID("locREQ"+direction+"JourneyStops"+reslocation+"KID");
  inputID.disabled = false;
  var inputTypeName = inputField.name.replace(/G$/,"A");
  if(eName(inputTypeName))
    {
    var inputField = eName(inputTypeName)[0];
    if(inputField.nodeName == "SELECT")
      {
      inputField.style.display = "inline";
      inputField.disabled = false;
      }
    }
  else
    {
    var inputType = document.createElement("input");
    inputType.type = "hidden";
    inputType.name = inputTypeName;
    inputType.value = 7;
    container.appendChild(inputType);
    }
  var resetLocationTD = eID("resetLocation"+index+"_"+reslocation);
  resetLocationTD.parentNode.removeChild(resetLocationTD);
  resetLocationTD = null;
  if(isNaN(reslocation))
    {
    if(eID("errormsg_"+reslocation))
      {
        var errorDiv = eID("errormsg_"+reslocation);
        if(errorDiv)
          {
          var errorParent = errorDiv.parentNode;
          errorParent.removeChild(errorDiv);
          errorDiv = null;
          }
      }
    else
      {
        var errorDiv = eID("errormsg_"+index+reslocation);
        if(errorDiv)
          {
          // reisemappe: table cell instead of div
          errorDiv.innerHTML = "";
          errorDiv.className = "";
          }
      }
    }
  else
    {
    var errorDiv = eID("errormsg_"+direction+"_"+reslocation);
    if(errorDiv)
      {
      errorDiv.innerHTML = "";
      }
    }
}

function adaptLocInputSizes(direction,reslocation,index,jmErrorMsgIndex){
  jmErrorMsg[jmErrorMsgIndex]--;
  if(jmErrorMsg[jmErrorMsgIndex] <= 0)
    eID('errormsg_'+index+reslocation).parentNode.className='hide';
  else if(index == 1)
    {
    var otherIndex = (index == 0) ? 1 : 0;
    if(eID("REQ"+direction+"JourneyStops"+reslocation+otherIndex+"K"))
      {
      var selectBox = eID("REQ"+direction+"JourneyStops"+reslocation+otherIndex+"K");
      selectBox.className = selectBox.className.replace(/\blocInput\b/,"locInputSmall");
      selectBox.parentNode.className = selectBox.className.replace(/\blocInput\b/,"locInputSmall");
      }
    }
}

function checkHWAIUsage()
{

  var useHWAI = true;
  try
    {
    new XMLHttpRequest();
    }
  catch(w3c)
    {
    try
      {
      new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch(msie)
      {
      try
        {
        new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch(msie_alt)
        {
        useHWAI = false;
        }
      }
    }
  return useHWAI;
}

function decode( 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, 'è');
  return t;
}

/* HafasInfoBox*/
function openHafasInfoBox(evt,param){
  var xVal = (typeof evt.pageX != 'undefined')?evt.pageX:evt.clientX;
  var yVal = (typeof evt.pageY != 'undefined')?evt.pageY:evt.clientY;
  if($('hafasInfoBox') == null) {
     var infobox = document.createElement("div");
     infobox.id = 'hafasInfoBox';
     var closeBtn = '<div style="position:absolute;right: 4px; top: 9px;"><a href="javascript:closeHafasInfoBox();"><img src="'+gImagePath+'close_button.png"/></a></div>';
     infobox.innerHTML = '<div id="hafasInfoBoxTitle">'+ param.name +'</div>'+closeBtn+infotextstation({x:param.x,y:param.y,extId:param.evaId});
     document.body.appendChild(infobox);
   }else{
     var closeBtn = '<div style="position:absolute;right: 4px; top: 9px;"><a href="javascript:closeHafasInfoBox();"><img src="'+gImagePath+'close_button.png"/></a></div>';
     $('hafasInfoBox').innerHTML = '<div id="hafasInfoBoxTitle">'+ param.name +'</div>'+closeBtn+infotextstation({x:param.x,y:param.y,extId:param.evaId});
   }
   $('hafasInfoBox').style.left = xVal+'px';
   $('hafasInfoBox').style.top = yVal+'px';
}
function closeHafasInfoBox(){
   if($('hafasInfoBox') != null) {
     $('hafasInfoBox').parentNode.removeChild($('hafasInfoBox'));
   }
}



/* Map functions / interactions with a map*/
// shows the layermap
function openLayerMap(type){
  currentLayerMap = type;
  var dimmer = eID("dimmer");
  if(dimmer == null) {
    dimmer = document.createElement("div");
    dimmer.id = "dimmer";
    dimmer.className = "layerMapOverlay";
    document.body.appendChild(dimmer);
  }
  eID('dimmer').style.display = 'block';
  window.setTimeout('listenToEvent(eID("dimmer"),"click",closeLayerMap);',200);
  eID('location').value = '';
  eID('layerMapWrap').style.display = 'block';
  var mapDiv = eID('layerMapWrap');
  if(mapDiv.parentNode.nodeName.toLowerCase() != "body")
    {
    mapDiv.parentNode.removeChild(mapDiv);
    document.body.appendChild(mapDiv);
    }
  // position of layer
  // get current scroll offset
  var y = 0;
  if (self.pageYOffset) // all except Explorer
    y = self.pageYOffset;
  else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
    y = document.documentElement.scrollTop;
  else if (document.body) // all other Explorers
    y = document.body.scrollTop;
  mapDiv.style.top = (Math.max(y, 150) + 50) + "px"
  if(typeof Map_layerMap == 'undefined') {
    showAjaxMap_layerMap();
  }
  if(type == 'start') {
       fillLayerMapInputField('HFS_from');
  }else if(type == "dest"){
       fillLayerMapInputField('HFS_to');
  }
  resizeMap(Map_layerMap);
}

function fillLayerMapInputField(id){
  if(eID(id).value.length > 0) {
    eID('location').value = eID(id).value;
    var sid = eID(id+'ID').value;
       sid.match(/@O=([^@]+)@/);
       var name = RegExp.$1;
       if(name == $('location').value) {
           sid.match(/@X=(\d+)/);
           var x = RegExp.$1;
           sid.match(/@Y=(\d+)/);
           var y = RegExp.$1;
           sid.match(/A=(\d+)/);
           var type = RegExp.$1;
           sid.match(/@L=(\d+)/);
           var extId = RegExp.$1;
           var locparams = getLocParamsLocationMarker({
              xcoord:x,
              ycoord:y,
              id: sid,
              evaId: extId,
              value: name,
              type: type
           });

           deleteMapLocationMarker();
           tmpMapMarker = Map_layerMap.createContent(locparams);
           Map_layerMap.showContent(tmpMapMarker);
           Map_layerMap.centerToContent(tmpMapMarker);
           Map_layerMap.setZoom(2500);
       }else{
           var aUrl = gUrlAjaxGetStop + "REQ0JourneyStopsS0A=255&REQ0JourneyStopsB=1&suggestMethod=none&REQ0JourneyStopsS0G=" + eID(id).value + "?&"
           new Ajax.Request(aUrl,{
              onSuccess:function(o){
                  eval(o.responseText);
                  SLs.sls.suggestions[0].id.match(/@L=(\d+)/);
                  var extId = RegExp.$1;
                  var locparams = getLocParamsLocationMarker({
                  xcoord:SLs.sls.suggestions[0].xcoord,
                  ycoord:SLs.sls.suggestions[0].ycoord,
                  id: SLs.sls.suggestions[0].id,
                  evaId: extId,
                  value: SLs.sls.suggestions[0].value,
                  type: SLs.sls.suggestions[0].type
                 });
                  deleteMapLocationMarker();
                  $('location').value = SLs.sls.suggestions[0].value;
                  tmpMapMarker = Map_layerMap.createContent(locparams);
                  Map_layerMap.showContent(tmpMapMarker);
                  Map_layerMap.centerToContent(tmpMapMarker);
                  Map_layerMap.setZoom(2500);
              }
           });
       }
  }
}

function closeLayerMap(){
  if(eID('dimmer') != null)
  eID('dimmer').style.display = 'none';
  if(eID('layerMapWrap') != null)
  eID('layerMapWrap').style.display = 'none';
  //Map_layerMap.hideAllInfoBoxes();
  currentLayerMap = '';
  if( (typeof Map_layerMap != 'undefined') && (typeof Map_layerMap.hideAllInfoBoxes != 'undefined') ) {
    Map_layerMap.hideAllInfoBoxes();
  }
}

function resizeMap(map){
  if(typeof map.map.updateSize == 'function'){
    map.map.updateSize();
  }
}


function chooseLocation(id,value,tupelid,typeId){
  var tmpDiv = document.createElement("div");
  tmpDiv.innerHTML = value;
  eID(id).value = tmpDiv.innerHTML;        // sets the name of the location
  tmpDiv.innerHTML = tupelid;
  eID(id+'ID').value = tmpDiv.innerHTML; // sets the tripleID as value of the hidden field
  if(eID(id+"_select"))
    {
      classNameRemove(eID(id),"error");
      classNameAdd(eID(id+"_eMsg"),"hide");
      classNameAdd(eID(id+"_loc_fixed"),"hide");
      classNameAdd(eID(id+"_type_fixed"),"hide");
      classNameRemove(eID(id+"_loc_free"),"hide");
      classNameRemove(eID(id+"_type_free"),"hide");
      eID(id).disabled = false;
      eID(id+"ID").disabled = false;
    }
  if(typeId != null)
    {
    var type;
    tupelid.match(/A=(\d)@/);
    type = RegExp.$1;

    var typeField = eID(typeId)
    if(typeField != null)
      {
      typeField.value = type
      }
    else if(eID(typeId+"_1") != null)
      {
      var c = 1;
      while(typeField = eID(typeId+"_"+c))
        {
        if(typeField.value & type)
          {
          typeField.checked = true;
          break;
          }
        c++;
        }

      }

    }
  closeLayerMap();
}


/* MAP FUNKTIONEN HAFAS 2010*/
/* all relevant products in the current Connection */
function getAllProductsForConnection(id){
      var jsID = id.replace("-","_");
      eval('allJourneyArr'+jsID +'= new Array();');
      if($('liveAllJourneys'+id).checked) {
         var map = eval('Map_'+id.replace("-","_"));
         for(var i=0;i < connMapArray[id].conn.sections.length;i++) {
           if(typeof connMapArray[id].conn.sections[i].trainId != 'undefined'){
             var livemap = eval('Livemap_'+jsID);
             livemap.addSingleJourney(connMapArray[id].conn.sections[i].trainId,Math.pow(2,connMapArray[id].conn.sections[i].productcode));
           }
         }
      }else{
         for(var i=0;i < connMapArray[id].conn.sections.length;i++) {
           if(typeof connMapArray[id].conn.sections[i].trainId != 'undefined'){
             var livemap = eval('Livemap_'+jsID);
             livemap.removeSingleJourney(connMapArray[id].conn.sections[i].trainId);
           }
         }
      }

}
function clearAllJourneys(id){
  var jsID = id.replace("-","_");
  if(eval('typeof allJourneyArr'+jsID) != 'undefined') {
    var currArr = eval('allJourneyArr'+jsID);
    var map = eval('Map_'+jsID);
    for(var i=currArr.length-1;i >= 0;i--) {
         map.hideContent(currArr[i]);
         map.removeContent(currArr[i]);
         currArr.pop();
    }
    $('liveJourneyAllJourneys'+id).innerHTML = '';
  }
}
function getResultForProduct(id,map,icon,trainid){
    var jsID = id.replace("-","_");
    var aUrl = gUrlTravelPlannerJSON+'y?performLocating=8&tpl=singletrain2json&look_trainid='+trainid+'&look_nv=get_rtstop&unique='+ new Date();
    var request = new Ajax.Request(aUrl,{
          method:'post',
          onSuccess:function(o){
             var obj = eval('('+o.responseText + ')');
             var param = {
                type:'location',
                imagewidth:16,
                imageheight:16,
                imageurl:gImagePath+'products/sel_prod_'+icon+'.png',
                coord: new CCoord({lon:obj.look.singletrain[0].x,lat:obj.look.singletrain[0].y}),
                hotspot:{x:8,y:8},
                text: obj.look.singletrain[0].name +' nach ' + obj.look.singletrain[0].lstopname
             };
             var tmp = map.createContent(param);
             map.showContent(tmp);
             var currArr = eval('allJourneyArr'+jsID);
             currArr.push(tmp);
             var currentInfo = document.createElement("div");
             currentInfo.innerHTML = '<img src="'+gImagePath+'products/sel_prod_'+icon+'.png"/><strong>'+obj.look.singletrain[0].name +'</strong> nach ' + obj.look.singletrain[0].lstopname;
             $('liveJourneyAllJourneys'+id).appendChild(currentInfo);
          }
       });
}
/* in development show current train/product of selected journey*/
/* param: @id: -> Connection ID der Verbindung */
singleVehicle = null;
singleVehicleAnimate = false;
singleVehicleUpdater = null;
singleVehicleContainer = null;
invisCenterPoly = null;
nextStopIcon = null;
currentSection = 0;
function toggleLiveMapFurtherOptions(id){
   if($('liveMapFurtherOptions'+id).style.display == 'none') {
      $('liveMapFurtherOptions'+id).style.display = 'block';
      $('liveMapFurtherOptionsLink'+id).style.display = 'none';
      $('liveMapLessOptionsLink'+id).style.display = 'block';
      $('liveMapDetailContainer'+id).style.display = 'block';
      $('liveMapDetailContainer'+id).className = 'liveMapLinkClose inactive';
      $('liveMapLessOptionsLink'+id).className = 'liveMapLinkClose';
      $('liveMapCloseContainer'+id).style.display = 'block';
      switchToOverview(id);
   }else{
     $('liveMapFurtherOptions'+id).style.display = 'none';
     $('liveMapFurtherOptionsLink'+id).style.display = 'block';
     $('liveMapLessOptionsLink'+id).style.display = 'none';
     $('liveMapDetailContainer'+id).style.display = 'none';
     $('liveMapCloseContainer'+id).style.display = 'none';
   }
}
function toggleAllTrafic(id){
    var livemap = eval("Livemap_"+id);
    var realId = id.replace("_","-");
    if(eID('liveAllTraffic'+realId).checked) {
      livemap.enableAll();
      eval("toggleAnimationButton"+id+"();");
    }else{
      livemap.disableAll();
    }
}
function switchToLiveMapDetails(id){
    var realid = id.replace("-","_");
    $('detail_'+realid+'_div').style.display = 'block';
    $('liveMapDetailContainer'+id).className = 'liveMapLinkClose';
    $('overview_'+realid+'_div').style.display = 'none';
    $('liveMapLessOptionsLink'+id).className = 'liveMapLinkClose inactive';
}
function switchToLiveMapOptions(id){
    var realid = id.replace("-","_");
    $('detail_'+realid+'_div').style.display = 'none';
    $('liveMapDetailContainer'+id).className = 'liveMapLinkClose inactive';
    $('overview_'+realid+'_div').style.display = 'block';
    $('liveMapLessOptionsLink'+id).className = 'liveMapLinkClose';
}
function switchToOverview(id){
    var realid = id.replace("-","_");
    $('detail_'+realid+'_div').style.display = 'none';
    $('overview_'+realid+'_div').style.display = 'block';
}
function showCurrentJourneyProduct(id){
  var map = eval('Map_'+id.replace("-","_"));
  if((singleVehicleUpdater == null) && ($('liveJourney'+id).checked)) {
    for(var i=0;i < connMapArray[id].conn.sections.length;i++) {
       if(typeof connMapArray[id].conn.sections[i].trainId != 'undefined') {
          var track = connMapArray[id].conn.sections[i].trainId;
          var currTime = new Date();
          var depTime = new Date();
          var currTimeStamp = Date.UTC(currTime.getFullYear(), currTime.getMonth(), currTime.getDay(), currTime.getHours(), currTime.getMinutes(), 00);
          var depArr = connMapArray[id].conn.sections[i].locations[0].dep.split(":");
          depTime.setHours(depArr[0]);
          depTime.setMinutes(depArr[1]);
          var depTimeStamp = Date.UTC(depTime.getFullYear(), depTime.getMonth(), depTime.getDay(), depTime.getHours(), depTime.getMinutes(), 00);
          var arrTime = new Date();
          var arrArr = connMapArray[id].conn.sections[i].locations[connMapArray[id].conn.sections[i].locations.length-1].arr.split(":");
          arrTime.setHours(arrArr[0]);
          arrTime.setMinutes(arrArr[1]);
          var arrTimeStamp = Date.UTC(arrTime.getFullYear(), arrTime.getMonth(), arrTime.getDay(), arrTime.getHours(), arrTime.getMinutes(), 00)
          //alert(arrTimeStamp + '|' + currTimeStamp);
          //  && (currTimeStamp >= depTime)
          //console.log("%s | %s",currTimeStamp,depTimeStamp);
          if((arrTimeStamp > currTimeStamp)&& (currTimeStamp >= depTimeStamp)) {
               $('mapDtl_tr_'+id+'_'+i+'_top').className = $('mapDtl_tr_'+id+'_'+i+'_top').className + ' active';
               $('mapDtl_tr_'+id+'_'+i+'_bottom').className = $('mapDtl_tr_'+id+'_'+i+'_bottom').className + ' active';
               fireSingleVehicleRequest(track,connMapArray[id].conn.sections[i].icon,id,i);
               singleVehicleUpdater = window.setInterval(function(){
                   currentSection=i;
                   fireSingleVehicleRequest(track,connMapArray[id].conn.sections[i].icon,id,i);
               }.bind(this),3000);
               singleVehicleAnimate = true;
               break;
          }else{
              if(i == connMapArray[id].conn.sections.length-1){
                alert("Tracking not possible. " + connMapArray[id].conn.sections[i].name + " is probably not running right now...");
                $('liveJourney'+id).checked = false;
                break;
              }else{
                continue;
              }
          }
       }
    }
  }else{
    window.clearInterval(singleVehicleUpdater);
    singleVehicleUpdater = null;
    singleVehicleAnimate = false;
    connMapArray[id].centerRoute();
    map.hideContent(singleVehicle);
    map.removeContent(singleVehicle);
    map.hideContent(nextStopIcon);
    map.removeContent(nextStopIcon);
    map.hideContent(singleVehicleContainer);
    map.removeContent(singleVehicleContainer);
    map.hideContent(invisCenterPoly);
    map.removeContent(invisCenterPoly);
    $('mapDtl_tr_'+id+'_'+currentSection+'_top').className = $('mapDtl_tr_'+id+'_'+currentSection+'_top').className.replace('active','');
    $('mapDtl_tr_'+id+'_'+currentSection+'_bottom').className = $('mapDtl_tr_'+id+'_'+currentSection+'_bottom').className.replace('active','');
    currentSection = 0;
    nextStopIcon = null;
    singleVehicle = null;
    singleVehicleContainer = null;
    //$('mapDtl_tr_'+id+'_'+i+'_top').className = $('mapDtl_tr_'+id+'_'+i+'_top').className.replace('active','');
    //$('mapDtl_tr_'+id+'_'+i+'_bottom').className = $('mapDtl_tr_'+id+'_'+i+'_bottom').className.replace('active','');
  }
}
function getNextCurrentLocation(section,narr){
     for(var i=0; i < section.locations.length;i++) {
         if(section.locations[i].arr == narr) {
            return section.locations[i];
         }
     }
     return null;
}
function fireSingleVehicleRequest(trainid,icon,connid,section){
      var map = eval('Map_'+connid.replace("-","_"));
      var aUrl = gUrlTravelPlannerJSON+'y?performLocating=8&tpl=singletrain2json&look_trainid='+trainid+'&look_nv=get_rtstop&unique='+ new Date();
      var request = new Ajax.Request(aUrl,{
        method:'post',
        onSuccess:function(o){
            var obj = eval('('+o.responseText+')');
            var nextStop = getNextCurrentLocation(connMapArray[connid].conn.sections[section],obj.look.singletrain[0].narr);
            // Aktuelle Zeit
            var currTime = new Date();
            var currTimeStamp = Date.UTC(currTime.getFullYear(), currTime.getMonth(), currTime.getDay(), currTime.getHours(), currTime.getMinutes(), currTime.getSeconds());
            // Datum/Zeit der ersten Haltestelle
            var arrTime = new Date();
            var arrArr = nextStop.arr.split(":");
            arrTime.setHours(arrArr[0]);
            arrTime.setMinutes(arrArr[1]);
            var arrTimeStamp = Date.UTC(arrTime.getFullYear(), arrTime.getMonth(), arrTime.getDay(), arrTime.getHours(), arrTime.getMinutes(), 00);
            var deltaTime = arrTimeStamp - currTimeStamp;
            // ms in sekunden umrechnen
            deltaTime = (deltaTime / 1000);
            if(deltaTime > 60) {
              var saveDeltaTime = deltaTime;
              deltaTime = parseInt(deltaTime / 60) + ' Min.';
              if((deltaTime % 60) != 0){
                 deltaTime += (saveDeltaTime % 60) + ' Sec.';
              }
            }else{
              deltaTime = deltaTime + ' Sec.';
            }
            //
            var currCoord = new CCoord({
                  lon:obj.look.singletrain[0].x,
                  lat:obj.look.singletrain[0].y
               });
            var param = {
               type:'location',
               imagewidth:16,
               imageheight:16,
               imageurl:gImagePath+'products/sel_prod_'+icon+'.png',
               coord: currCoord,
               hotspot:{x:8,y:8},
               text: obj.look.singletrain[0].name +' nach ' + obj.look.singletrain[0].lstopname
            };
            var paramHighlight = {
               type:'location',
               imagewidth:20,
               imagewidth:20,
               imageurl:gImagePath+'radar_ani_ontime.gif',
               coord: new CCoord({lon:nextStop.x,lat:nextStop.y}),
               hotspot:{x:11,y:10}
            };
            // Next stop blink Radar
            if(nextStopIcon == null) {
              nextStopIcon = map.createContent(paramHighlight);
              map.showContent(nextStopIcon);
            }else{
              map.updateContent(nextStopIcon,null,paramHighlight);
            }
            // Vehicle und Infocontainer!
            var paramContainer = {
                 type:'container',
                 coord:currCoord,
                 html:'<div class="trainInfoContainer">'+
                         '<div class="trainHeadline">'+obj.look.singletrain[0].name+' '+ obj.look.singletrain[0].lstopname +'</div>'+
                         '<div class="trainNextStop"><strong>Next stop:</strong>'+obj.look.singletrain[0].narr +' ' + obj.look.singletrain[0].nstopname+'</div>'+
                         '<div class="trainNextStop">Arrival in '+deltaTime + '</div>'+
                      '</div>',
                 hotspot:{x:-10,y:10}
             };
            if(singleVehicle != null) {
              map.updateContent(singleVehicle,null,param);
              map.updateContent(singleVehicleContainer,null,paramContainer);
            }else{
              singleVehicle = map.createContent(param);
              singleVehicleContainer = map.createContent(paramContainer);
              map.showContent(singleVehicleContainer);
              map.showContent(singleVehicle);
            }
            if(invisCenterPoly != null)
               map.hideContent(invisCenterPoly);
            invisCenterPoly = null;
            // auf Zug und nächsten Halt centern!
            invisCenterPoly = map.createContent({
               type:'polyline',
               coords:[new CCoord({lon:obj.look.singletrain[0].x,lat:obj.look.singletrain[0].y}),
                       new CCoord({lon:nextStop.x,lat:nextStop.y})],
               width:5,
               opacity:0.7,
               color:"7CBF23"
            });
            map.showContent(invisCenterPoly);
            map.centerToContent(invisCenterPoly);
        }
      })
}

function showTrainroute(trainNo)
{
  var container = eID("HFS_train_"+trainNo);
  var link = eID("HFS_trainlink_"+trainNo);
  classNameAdd(link,"hide");
  classNameRemove(container,"hide");
}

/************************************
 * functions for connection ranking *
 ************************************/

/* rank the connections */
function doConRanking(field, imgPath, currentOVGroup) {

  // save array in help array
  var currentRankingArr = (currentOVGroup == 'return') ? rankingArrRet : rankingArrOut;

  if(typeof currentRankingArr != 'undefined') {

    // parse CO2 value to float
    for(var i=0; i<currentRankingArr.length; i++) {
      if(currentRankingArr[i]['ecology']) {
        if(isNaN(currentRankingArr[i]['ecology'])) {
          currentRankingArr[i]['ecology'] = currentRankingArr[i]['ecology'].replace(",", ".");
          currentRankingArr[i]['ecology'] = parseFloat(currentRankingArr[i]['ecology']);
        }
      }
    }

    // reset previous sort order, sort by position within array
    currentRankingArr.sort(
      function (a, b){
        return a['position'] > b['position'] ? 1 : a['position'] < b['position'] ? -1 : 0;
      }
    );

    // sort by field
    currentRankingArr.sort(
      function (a, b){
        return a[field] > b[field] ? 1 : a[field] < b[field] ? -1 : 0;
      }
    );

    // add ranking to table
    var conCount = 5;
    for(var i=0; i < currentRankingArr.length; i++) {
      $('rankingCol' + currentRankingArr[i]['id']).innerHTML = '';
      var starCount = conCount - i;
      if(starCount > 0) {
        var content = '';
        for(var j=0; j<starCount; j++) {
          content += '<img src="' + imgPath + '" alt="" width="20" height="20" class="rankingStar" />'
        }
        $('rankingCol' + currentRankingArr[i]['id']).innerHTML = content;
      }
    }
  }
}

/* remove ranking */
function removeRankingStars(currentOVGroup) {
  var currentRankingArr = (currentOVGroup == "return") ? rankingArrRet : rankingArrOut;
  if(typeof currentRankingArr != 'undefined') {
    for(var i=0; i < currentRankingArr.length; i++) {
      $('rankingCol' + currentRankingArr[i]['id']).innerHTML = '';
    }
  }
}


/***********************************
 * functions for connection filter *
 ***********************************/

/* initialize all at once */
function initializeAllSliders(showOVGroup, setInitializeStatus) {
  if(showOVGroup == 'return') {
    if(slidersInitializedReturn == false) {
      initializeSlider(showOVGroup, 'departure');
      initializeSlider(showOVGroup, 'arrival');
      initializeSlider(showOVGroup, 'duration');
      initializeSlider(showOVGroup, 'changes');
    }
    if(setInitializeStatus == true) {
      slidersInitializedReturn = true;
    }
  } else {
    if(slidersInitializedOutward == false) {
      initializeSlider(showOVGroup, 'departure');
      initializeSlider(showOVGroup, 'arrival');
      initializeSlider(showOVGroup, 'duration');
      initializeSlider(showOVGroup, 'changes');
    }
    if(setInitializeStatus == true) {
      slidersInitializedOutward = true;
    }
  }
}

/* initialize the different sliders */
function initializeSlider(showOVGroup, field) {

  // set width for product and station column to avoid "jump effect"
  // temporary for AWT 2010!!!
  if(($('hafasOVProducts')) && ($('hafasOVProducts').style.width == "")) {
    $('hafasOVProducts').style.width = "330px";
  }
  if(($('hafasOVStop')) && ($('hafasOVStop').style.width == "")) {
    $('hafasOVStop').style.width = "440px";
  }

  if(showOVGroup == '') return false;

  var detailsArr = (showOVGroup == 'return') ? detailsArrRet : detailsArrOut;

  if(typeof detailsArr != 'undefined') {

    var minVal = 9999999999999999999999999999999;
    var maxVal = 0;
    var sliderValue = 0;

    // create minVal, maxVal and sliderValue
    for (var i=0; i<detailsArr.length; i++) {
      if (detailsArr[i][field] > maxVal) {
        maxVal = parseInt(detailsArr[i][field]);
      }
      if (detailsArr[i][field] < minVal) {
        minVal = parseInt(detailsArr[i][field]);
      }
      if($('trOverview' + detailsArr[i]['id']).hasClassName("hide" + field) == false) {
        if (detailsArr[i][field] > sliderValue) {
          sliderValue = parseInt(detailsArr[i][field]);
        }
      }
    }

    // set current maximum into text
    if(field == "duration") {
      $(field + 'Displayed_' + showOVGroup).innerHTML = getTimeFromMinutes(sliderValue);
    }
    else if((field == "departure") || (field == "arrival")) {
      var dateTimeArr = getNiceDateFromTimestamp(sliderValue);
      $(field + 'DisplayedDate_' + showOVGroup).innerHTML = dateTimeArr[0];
      $(field + 'DisplayedTime_' + showOVGroup).innerHTML = dateTimeArr[1];
    }
    else {
      $(field + 'Displayed_' + showOVGroup).innerHTML = sliderValue;
    }

    // call function to create slider
    createSlider(field, minVal, maxVal, sliderValue, showOVGroup, detailsArr);
  }
}

/* create the different sliders */
function createSlider(field, curMin, curMax, sliderValue, showOVGroup, detailsArr) {

  // initialize variables
  var slider = $(field + '_' + showOVGroup + '_slider');
  var values = new Array();
  for(var i=curMin;i <= curMax; i++) {
    values.push(i);
  }

  // create a new slider
  new Control.Slider(slider.down('.handle'), slider, {
    range: $R(curMin, curMax),
    sliderValue: sliderValue,
    values: values,
    onChange: function(value) {
      displayConnections(value, field, detailsArr);
      sliderValue = value;
      if(field == "duration") {
        $(field + 'Displayed_' + showOVGroup).innerHTML = getTimeFromMinutes(value);
      }
      else if((field == "departure") || (field == "arrival")) {
        var dateTimeArr = getNiceDateFromTimestamp(value);
        $(field + 'DisplayedDate_' + showOVGroup).innerHTML = dateTimeArr[0];
        $(field + 'DisplayedTime_' + showOVGroup).innerHTML = dateTimeArr[1];
      }
      else {
        $(field + 'Displayed_' + showOVGroup).innerHTML = value;
      }
    }
  });
}

function initializeProductBitStatus() {
  var inputArr = $$('.productBitsFilterCheckbox');
  for(var i=0; i<inputArr.length; i++) {
    var id = inputArr[i].id;
    var value = $(id).value;
    var splitArr = id.split("_");
    var number = splitArr[1];
    var checkStatus = $(id).checked;

    if(typeof detailsArrOut != 'undefined') {
      displayConnections(new Array(value, number, checkStatus), 'bits', detailsArrOut);
    }
    if(typeof detailsArrRet != 'undefined') {
      displayConnections(new Array(value, number, checkStatus), 'bits', detailsArrRet);
    }
  }
}

/* display or hide the connections */
function displayConnections(value, field, detailsArr) {
  var className = "hide" + field;
  for(var i=0; i < detailsArr.length; i++) {
    // special behaviour for bitfields
    if(field == 'bits') {
      var bitValue = value[0];
      var number = value[1];
      var status = value[2];
      var className = "hide" + field + "_" + number;
      var completeBits = parseInt(detailsArr[i]['bits']);
      if((completeBits &= bitValue) && ($('trOverview'+detailsArr[i]['id']).hasClassName(className) != true) && (status == false)) {
        // hide table rows
        $('trOverview'+detailsArr[i]['id']).addClassName(className);
        $('trOverviewSpaceTop'+detailsArr[i]['id']).addClassName(className);
        $('tr'+detailsArr[i]['id']).addClassName(className);
        $('trOverviewSpaceBottom'+detailsArr[i]['id']).addClassName(className);
      }
      else {
        // show table rows
        $('trOverview'+detailsArr[i]['id']).removeClassName(className);
        $('trOverviewSpaceTop'+detailsArr[i]['id']).removeClassName(className);
        $('tr'+detailsArr[i]['id']).removeClassName(className);
        $('trOverviewSpaceBottom'+detailsArr[i]['id']).removeClassName(className);
      }
    }
    // everything else
    else {
      if(parseInt(detailsArr[i][field]) > value) {
        // hide table rows
        $('trOverview'+detailsArr[i]['id']).addClassName(className);
        $('trOverviewSpaceTop'+detailsArr[i]['id']).addClassName(className);
        $('tr'+detailsArr[i]['id']).addClassName(className);
        $('trOverviewSpaceBottom'+detailsArr[i]['id']).addClassName(className);
      }
      else {
        // show table rows
        $('trOverview'+detailsArr[i]['id']).removeClassName(className);
        $('trOverviewSpaceTop'+detailsArr[i]['id']).removeClassName(className);
        $('tr'+detailsArr[i]['id']).removeClassName(className);
        $('trOverviewSpaceBottom'+detailsArr[i]['id']).removeClassName(className);
      }
    }
  }
}

/* get the time out of minutes */
function getTimeFromMinutes(minutes) {
  var tmpHours = parseInt(minutes/60);
  var tmpMinutes = minutes % 60;
  var tmpMinutes = (tmpMinutes < 10) ? "0" + tmpMinutes : tmpMinutes;
  var tmpTime = tmpHours + ":" + tmpMinutes;

  return tmpTime;
}

/* get the timestamp of date and time */
function getTimestampFromDateTime(date, time) {
  var dateArr = date.split(".");
  var timeArr = time.split(":");
  var newDate = new Date();
  newDate.setYear("20" + dateArr[2]);
  newDate.setMonth(dateArr[1] - 1);
  newDate.setDate(dateArr[0]);
  newDate.setHours(timeArr[0]);
  newDate.setMinutes(timeArr[1]);
  newDate.setSeconds(0);

  return parseInt(newDate.getTime()/1000);
}

/* get a "nice" date from timestamp */
function getNiceDateFromTimestamp(timestamp) {
  var date = new Date(timestamp * 1000);
  var dateString = date.getDate() + "." + (date.getMonth()+1) + "." + date.getFullYear();
  var newHours = (date.getHours() < 10) ? "0" + date.getHours() : date.getHours();
  var newMinutes = (date.getMinutes() < 10) ? "0" + date.getMinutes() : date.getMinutes();
  var timeString = newHours + ":" + newMinutes;

  return new Array(dateString, timeString);
}


function showNextVia(cViaNr, viaButton)
{
  var nViaNr = cViaNr + 1;
  if(eID("HFSInputVia_"+nViaNr))
    {
    classNameRemove(eID("HFSInputVia_"+nViaNr),"hide");
    enableAllChildren(eID("HFSInputVia_"+nViaNr),false);
    }
  if(viaButton)
    {
    classNameAdd(viaButton,"hide");
    if(eID("viaButtonFront_"+nViaNr))
      {
      classNameAdd(eID("viaButtonFront_"+nViaNr),"hide");
      }
    }
  }


function shiftTime(id,offset)
{
  var timefield = eID(id);
  if(timefield == null)
    return false;
  var ctime = timefield.value;
  var hour,minute;
  if(ctime.match(/^([0-2]?\d):?(\d\d)?$/) == null)
    return false;
  var tmpH = RegExp.$1*1;
  var tmpM = RegExp.$2*1;
  if((ctime.indexOf(":") < 0) && (ctime < 1000))
    {
    if(ctime <=24)
      {
      hour = ctime*1;
      minute = 0;
      }
    else
      {
      hour = Math.floor(ctime / 100);
      minute = ctime % 100;
      }
    }
  else
    {
    hour = tmpH;
    minute = tmpM;
    if((hour > 24) || (minute > 59))
      return;
    }
  if(minute != 0)
    {
    minute = 0;
    if(offset < 0)
      offset += 1;
    }
  hour += offset;
  hour %= 24;
  if(hour < 0)
    hour += 24;
  if(hour < 10)
    ctime = "0"+hour+":00";
  else
    ctime = hour+":00";
  timefield.value = ctime;

}

function advancedProducts(button)
{
  classNameAdd(eID("HFSInputProductsDetailButton"),"hide");
  classNameRemove(eID("HFSInputProductDetail"),"hide");
  var generalProductList = eID("REQProduct_list_0");
  if(generalProductList) generalProductList.parentNode.removeChild(generalProductList);
  enableAllChildren(eID("HFSInputProductDetail"),false);
  var newField = document.createElement("input");
  newField.type = "hidden";
  newField.name = button.name;
  newField.id = "advancedProductsSwitch";
  newField.value = button.value;
  button.parentNode.appendChild(newField);
  button.name = "advancedProducts";
  button.onclick = function(){toggleOptions(eID('HFSInputProductsDetailButton'),eID('HFSInputProductDetail'),'advancedProducts'); return false;};
  //button.disabled = true;
  // eID("HFSInputProductDetail").focus();
}

function advancedOptions(button)
{
  classNameAdd(eID("HFSQueryNotAdvanced"),"hide");
  classNameRemove(eID("HFSQueryAdvanced"),"hide");
  enableAllChildren(eID("HFSQueryAdvanced"),false);
  var newField = document.createElement("input");
  newField.type = "hidden";
  newField.name = button.name;
  newField.id = "advancedSwitch";
  newField.value = button.value;
  button.parentNode.appendChild(newField);
  button.name = "advanced";
  button.onclick = function(){toggleOptions(eID('HFSQueryNotAdvanced'),eID('HFSQueryAdvanced'),'advanced'); return false;};
  //button.disabled = true;
}

function HideAdvancedOptions(button)
{
  classNameRemove(eID("HFSQueryNotAdvanced"),"hide");
  classNameAdd(eID("HFSQueryAdvanced"),"hide");
  enableAllChildren(eID("HFSQueryAdvanced"),false);
  var newField = document.createElement("input");
  newField.type = "hidden";
  newField.name = button.name;
  newField.value = button.value;
  button.parentNode.appendChild(newField);
  //button.disabled = true;
}

function intermodalOptions(button)
{
  classNameAdd(eID("HFSQueryNotIntermodal"),"hide");
  classNameRemove(eID("HFSQueryIntermodal"),"hide");
  enableAllChildren(eID("HFSQueryIntermodal"),false);
  var newField = document.createElement("input");
  newField.type = "hidden";
  newField.name = button.name;
  newField.id = "intermodalSwitch";
  newField.value = button.value;
  button.parentNode.appendChild(newField);
  button.name = "intermodal";
  button.onclick = function(){toggleOptions(eID('HFSQueryNotIntermodal'),eID('HFSQueryIntermodal'),'intermodal'); return false;};
  //button.disabled = true;
}

function toggleOptions(button,options,hwaiName)
{
  if(button.className.match(/\bhide\b/))
    {
    classNameRemove(button,"hide");
    classNameAdd(options,"hide");
    if(hwaiName)
      {
      if(!(eID(hwaiName+"Switch")))
        {
        var newField = document.createElement("input");
        newField.type = "hidden";
        newField.name = "HWAI=~QUERY!"+hwaiName+"=yes!&dummy";
        newField.id = hwaiName+"Switch";
        newField.value = "";
        button.parentNode.appendChild(newField);
        }
      else
        eID(hwaiName+"Switch").name = "HWAI=~QUERY!"+hwaiName+"=yes!&dummy";
      }
    }
  else
    {
    classNameAdd(button,"hide");
    classNameRemove(options,"hide");
      {
      if(!(eID(hwaiName+"Switch")))
        {
        var newField = document.createElement("input");
        newField.type = "hidden";
        newField.name = "HWAI=QUERY!"+hwaiName+"=yes!&dummy";
        newField.id = hwaiName+"Switch";
        newField.value = "";
        button.parentNode.appendChild(newField);
        }
      else
        eID(hwaiName+"Switch").name = "HWAI=QUERY!"+hwaiName+"=yes!&dummy";
      }
    }
}

function baimOptions(button)
{
  classNameAdd(eID("HFSQueryNotBaim"), "hide");
  classNameRemove(eID("HFSQueryBaim"), "hide");
  var newField = document.createElement("input");
  newField.type = "hidden";
  newField.name = button.name;
  newField.value = button.value;
  newField.id = "baimSwitch";
  button.parentNode.appendChild(newField);
  button.name = "baim";
  //button.disabled = true;
  enableAllChildren(eID("HFSQueryBaim"), false);
  if(typeof(baimUrl) == "string")
    button.form.action = baimUrl;
  if(eID("HFS_from_select"))
    {
    //eID("HFS_from").name = eID("HFS_from").name.replace(/K$/,"G");
    eID("HFS_from").disabled = false;
    var selIndex  = eID("HFS_from_select").selectedIndex;
    var selOption = eID("HFS_from_select").options[selIndex];
    eID("HFS_from").value = selOption.text.match(/[^\[]*/);
    selOption.value = selOption.text.match(/[^\[]*/);
    eID("HFS_from_select").disabled = true;
    classNameAdd(eID("HFS_from_loc_fixed"),"hide");
    classNameRemove(eID("HFS_from_loc_free"),"hide");
    classNameAdd(eID("HFS_from_type_fixed"),"hide");
    classNameRemove(eID("HFS_from_type_free"),"hide");
    }
  if(eID("HFS_to_select"))
    {
    eID("HFS_to").disabled = false;
    var selIndex  = eID("HFS_to_select").selectedIndex;
    var selOption = eID("HFS_to_select").options[selIndex];
    eID("HFS_to").value = selOption.text.match(/[^\[]*/);
    selOption.value = selOption.text.match(/[^\[]*/);
    eID("HFS_to_select").disabled = true;
    classNameAdd(eID("HFS_to_loc_fixed"),"hide");
    classNameRemove(eID("HFS_to_loc_free"),"hide");
    classNameAdd(eID("HFS_to_type_fixed"),"hide");
    classNameRemove(eID("HFS_to_type_free"),"hide");
    }
}

function deselectBaim()
{
  var baimSwitchOn = eID("baimSwitchOn");
  var baimInput = eID("baimSwitch");
  if(baimInput != null)
    {
    baimSwitchOn.name = baimInput.name;
    baimInput.parentNode.removeChild(baimInput);
    }
  enableAllChildren(eID("HFSQueryBaim"), true);
  classNameRemove(eID("HFSQueryNotBaim"), "hide");
  classNameAdd(eID("HFSQueryBaim"), "hide");
  if(typeof(queryUrl) == "string")
    baimSwitchOn.form.action = queryUrl;
}

// email push service
/**
* creating complete json object for email realtime push service
*/
function createEmailRealtimePushContent(conId, emailText, url, voText, sectionInfoContent, viaInfo) {
  var emailAddress = $('emailAddressPush_' + conId).value;
  emailAddress = emailAddress.replace (/ /g, '');
  var sendContent = (emailAddress == '') ? false : true;
  //url = encodeURIComponent(url);
  emailText = encodeURIComponent(emailText);

  // phone number given
  if(sendContent == true)
  {
    emailRealtimePushContent = '{\
    "consections": [' + sectionInfoContent + '],\
    "monitorFlags": {\
    "af": true,\
    "cf": true,\
    "df": true,\
    "dv": true,\
    "of": true,\
    "pf": true\
    },\
    "eMail": "' + emailAddress + '",\
    "eMailRemoved": "' +gRTSMS_NoConnectionText + '",\
    "eMailTextUrl": "' + url + '",\
    "vo": "' + voText.toUpperCase() + '",\
    "viaWaitTimes": [' + viaInfo + ']\
    }';

    sendEmailRealtimePushContent(conId, emailRealtimePushContent);
  }

  // phone number not given
  else
  {
    // create new error text element, if not defined
    if(!($('errorTextEmailPush_' + conId)))
    {
      var errorText = document.createElement("p");
      errorText.setAttribute("id", "errorTextEmailPush_" + conId);
      errorText.setAttribute("class", "errormessage");
      errorText.innerHTML = "<b>" + gRTSMS_Err_NoEmailGiven + "</b>";
      $('emailPushContent_' + conId).appendChild(errorText);
    }
  }
}

/**
* send smsRealtimePushContent via AJAX
*/
function sendEmailRealtimePushContent(conId, jsonString) {
  new Ajax.Request(gRTSMS_SubscribeUrl,
  {
  method:'post',
  parameters: jsonString,
  contentType: 'application/x-www-form-urlencoded',
  encoding: 'UTF-8',
  onSuccess: function(transport)
  {
    var ajaxResponse = eval('(' + transport.responseText + ')');
    var resultCode = ajaxResponse.resultCode;
    var controlStamp = ajaxResponse.controlStamp;
    var currentSubscriptionCount = ajaxResponse.currentSubscriptionCount;
    var maxSubscriptionCount = ajaxResponse.maxSubscriptionCount;
    if(resultCode == "OK")
    {
      // removes form content
      $('emailPushContent_' + conId).update("<p><b>" + gRTSMS_Confirmation + "</b></p>");
    }

    else
    {
      // removes form content
      $('emailPushContent_' + conId).update("<p><b>" + gRTSMS_Err_UnspecificMsg + "</b></p>");
    }
  }
  });
}

// BAIM
// ====



function showAntiVia()
{
  for (var i = 1; i <= 2; i++)
    {
    if(eID("HFSInputantiVia_"+i))
      {
      classNameRemove(eID("HFSInputantiVia_"+i),"hide");
      enableAllChildren(eID("HFSInputantiVia_"+i),false);
      }
    }
  }

