/* hafas_rp_v7_ajaxmaps.js */


function e(id){
  return document.getElementById(id);
}

function bitfield(field,array) {
  var result = "";
  for (var i=0; ((i < field.length) && (field.length == array.length)); i++) {
    result = result + array[i] + ((field.substr(i,1) == '1') ? "=yes" : "=no") + ((i+1 < field.length) ? "," : "");
  }
  return result;
}

/* open a popup-window with any content */
function openPopup(url,windowname,topPosition,leftPosition,width,height,flags) {
   var popUpSwitches = new Array("location","menubar","scrollbars","status","resizable","toolbar");
   flags = bitfield(flags,popUpSwitches)

   // URL Korrektur um JavaScript Security Error zu vermeiden
   // gleichen Hostnamen von PopUp und Opener
   var startIndex = url.indexOf("//");
   if (startIndex >= 0) {
      var newUrl = url.substring(0, startIndex);

      url = url.substring(startIndex+2, url.length);
      startIndex = url.indexOf("/");
      url = url.substring(startIndex, url.length);

      var first = newUrl.concat("//");
      var second = first.concat(window.location.host);
      var third = second.concat(url);
      url = third;
   }

   var newwin = window.open(url,windowname,"top="+topPosition+",left="+leftPosition+",width="+width+",height="+height+flags);
   newwin.focus(self);
}


/* Returns the absolute x-position of element el */
function absLeft(el) {
    return (el.offsetParent)?
        el.offsetLeft+absLeft(el.offsetParent) : el.offsetLeft;
}

/* Returns the absolute y-position of element el */
function absTop(el) {
    return (el.offsetParent)?
        el.offsetTop+absTop(el.offsetParent) : el.offsetTop;
}

/* Removes the div with id "tipDiv" if mouseEvent is outside this div. */
function tooltipActiveMouseMove( mouseEvent )
{
    if ( !mouseEvent )
        mouseEvent = window.event;

    var tipDiv = document.getElementById( "tipDiv" );
    var tipFrame = document.getElementById( "tipFrame" );

    var tipX1 = absLeft( tipDiv );
    var tipY1 = absTop( tipDiv );

    var tipX2 = tipX1 + tipDiv.offsetWidth;
    var tipY2 = tipY1 + tipDiv.offsetHeight;

    scrollPos = getScrollPos();

    var evX = mouseEvent.clientX + scrollPos.x;
    var evY = mouseEvent.clientY + scrollPos.y;

    if ( (evX < tipX1) || (evX > tipX2 ) ||
         (evY < tipY1) || (evY > tipY2 ) )
        {
        document.onmousemove = null;
        document.body.removeChild( tipDiv );

        if ( tipFrame )
            document.body.removeChild( tipFrame );
        }
}

/* Returns the window's width */
function getWindowWidth()
{
    if (self.innerWidth) // all except Explorer
        {
        return self.innerWidth;
        }
    else if (document.documentElement && document.documentElement.clientWidth)
  // Explorer 6 Strict Mode
        {
        return document.documentElement.clientWidth;
        }
    else if (document.body) // other Explorers
        {
  return document.body.clientWidth;
        }
}

/* Returns the window's height */
function getWindowHeight()
{
    if (self.innerHeight) // all except Explorer
        {
  return self.innerHeight;
        }
    else if (document.documentElement && document.documentElement.clientHeight)
  // Explorer 6 Strict Mode
        {
        return document.documentElement.clientHeight;
        }
    else if (document.body) // other Explorers
        {
  return document.body.clientHeight;
        }
}

// returns the scroll left and top for the browser viewport.
function getScrollPos() {
   if ( document.body.scrollTop != undefined ) {  // IE model
      var ieBox = document.compatMode != "CSS1Compat";
      var cont = ieBox ? document.body : document.documentElement;
      return { x : cont.scrollLeft, y : cont.scrollTop };
   }
   else {
      return { x : window.pageXOffset, y : window.pageYOffset };
   }
}
/*
   Shows a tooltip at position "mouseEvent".
   The content is taken from "tip".
   Creates a div with id "tipDiv".

   If "linkText" is defined, the function tries to find an "a" tag, that
   is the target of the mouse event. If an "a"-tag is found and has an "href"
   link the link will be included at the bottom of the tooltip with link's
   text = "linkText".
*/
function tooltip( mouseEvent, tip, linkText )
{
    if ( !mouseEvent )
        mouseEvent = window.event;

    var tipElem = document.getElementById( tip );

    var tipContent = tipElem.innerHTML;

    var tipDiv = document.getElementById( "tipDiv" );
    var tipFrame = document.getElementById( "tipFrame" );

    // Remove old tooltip:
    if ( tipDiv )
        {
        document.body.removeChild( tipDiv );
        }
    if ( tipFrame )
        {
        document.body.removeChild( tipFrame );
        }

    tipDiv = document.createElement( "div" );

    scrollPos = getScrollPos();

    tipDiv.setAttribute( "id", "tipDiv" );
    tipDiv.className = "tooltip";

    tipDiv.style.display="block";
    tipDiv.style.visibility="visible";

    document.body.appendChild( tipDiv );

    tipDiv.innerHTML = tipContent;

    if ( undefined != linkText )
        {
        var targetLink = mouseEvent.target;
        if ( !targetLink )
            {
            targetLink = mouseEvent.srcElement;
            }

        while ( targetLink && ((targetLink.nodeName != "A") && (targetLink.nodeName != "a") ))
            {
            targetLink = targetLink.parentNode;
            }

        if( targetLink && (undefined != targetLink.href) )
            {
            tipDiv.innerHTML += "<div>"
                + "<a href=\""
                + targetLink.href
                + "\" >"
                + linkText
                + "</a></div>" ;
            }
        }

    tipDiv.style.top  = mouseEvent.clientY + 5 + scrollPos.y - tipDiv.offsetHeight + "px";
    tipDiv.style.left = mouseEvent.clientX - 5 + scrollPos.x + "px";

    // Exploder hack to hide selects behind the tooltip
    if ( navigator.appName.search(/Explorer/) != -1 )
        {
        tipFrame = document.createElement( "iframe" );

        tipFrame.setAttribute( "id", "tipFrame" );
        tipFrame.setAttribute( "src", "about:blank" );
        tipFrame.setAttribute( "scrolling", "no" );
        tipFrame.setAttribute( "frameborder", "0" );

        tipFrame.style.top    = tipDiv.style.top;
        tipFrame.style.left   = tipDiv.style.left;
        tipFrame.style.width  = tipDiv.offsetWidth;
        tipFrame.style.height = tipDiv.offsetHeight;


        tipFrame.style.position = "absolute";
        tipFrame.style.zIndex = 254;

        document.body.appendChild( tipFrame );
        }

    document.onmousemove = tooltipActiveMouseMove;
}


/* HAFAS BASIC - External Javascript (based on: R4 v1.9)         */
/* v1.0  created May 2002 by MB supported by Anton & Friedrich   */
/* v1.9  changed 25.09.2002 - latest R4 version                  */
/* v2.0  changed 24.10.2002 - locType can be 'LIST' or 'RADIO'   */
/* v2.1  changed 13.11.2002 - function popUp administrates also  */
/*       new style 'loc' to replace formerly function openInfo   */
/* v2.2  changed 29.01.2003 by JF - TripleID value added         */
/* v2.3  changed 28.02.2007 by CAG - new function                */
/* v2.4  changed 28.02.2007 by ghe - new functions               */


/* Select stations from history-list */
function useHistory(varselect,currentLocation,selectLocType){
    var index  = eval("document.forms[0]."+ varselect +"select.selectedIndex;");
    var text   = eval("document.forms[0]."+ varselect +"select.options[index].text;");
    var triple = eval("document.forms[0]."+ varselect +"select.options[index].value;");
    var type = 7;

    var tokens = triple.split("#");
    for (var index = 0; index < tokens.length; index++)
      {
      // Typ der Location //
      if (tokens[index].charAt(0) == 'A')
        {
        type = tokens[index].charAt(2);
        }
      // Ausgabename der Location //
      if (tokens[index].charAt(0) == 'O')
        {
        var length = 2;
        if (isNaN(tokens[index].charAt(1)) == false)
          {
          length = 3;
          }
        var text = tokens[index].substring(length, tokens[index].length);
        }
      }

    if(triple=="x")
      {eval("document.forms[0]."+ varselect +"select.options[0].selected=true;");}
    else
      {
       /* Set Location Name */
       eval("document.forms[0].REQ0JourneyStops"+currentLocation+"0G.value = text;");
       eval("document.forms[0].REQ0JourneyStops"+currentLocation+"0ID.value = triple;");
       if(type==7) var ttc = 0; else if(type==1) var ttc = 1; else
       if(type==2) var ttc = 2; else if(type==4) var ttc = 3;
       if(selectLocType == "LIST")
         eval("document.forms[0].REQ0JourneyStops"+currentLocation+"0A.selectedIndex = ttc;");
       else if(selectLocType == "RADIO")
         eval("document.forms[0].REQ0JourneyStops"+currentLocation+"0A[ttc].checked = true;");
         }
      /* Reset select list*/
      eval("document.forms[0]."+ varselect +"select.selectedIndex = 0;");
    }
/* Link to open a popup-window with any content */
function popUp(url,windowname,style)
    {
    var standard = "top=20,left=200,resizable=no,status=no,toolbar=no,menubar=no,location=no";
    if (style=="pro" || style=="int" || style=="sef") var size = ",scrollbars=yes,width=600,height=500";
    else if (style=="poi") var size = ",scrollbars=yes,width=500,height=480";
    else if (style=="pri") var size = ",scrollbars=yes,width=685,height=600";
    else if (style=="cms") var size = ",scrollbars=yes,width=980,height=560";
    else if (style=="loc") var size = ",scrollbars=no,width=305,height=355";
    else if (style=="help") var size = ",resizable=yes,scrollbars=yes,width=850,height=560";
    else if (style=="popupRP4") var size = ",scrollbars=no,width=403,height=333";
    else if (style=="map"){
      var size = ",scrollbars=yes,width=630,height=650";
    }
    newwin = window.open(url,windowname,standard+""+size);
    newwin.focus(self);
    }

/* Show Calendar or Servicedays in Popup */
function openCalendar(url,windowname,journeystatus){
    var standard = "scrollbars=no,resizable=no,status=no,toolbar=no,menubar=no,location=no";
    var size = ",width=320,height=400";

    if (url != "about:blank") {
      var startIndex = url.indexOf("//");
      var newUrl = url.substring(0, startIndex);

      url = url.substring(startIndex+2, url.length);
      startIndex = url.indexOf("/");
      url = url.substring(startIndex, url.length);

      var first = newUrl.concat("//");
      var second = first.concat(window.location.host);
      var third = second.concat(url);
      url = third;
    }

    newwin = window.open(url,windowname+""+journeystatus,standard+""+size);
    newwin.creator = self;
    }

/* Set Date by JavaScript */
function getjsDate(type){
    var ndate = new Date();
    var t = ndate.getDate();
    var m = 1+(1*ndate.getMonth());
    var g = "g"+ndate.getFullYear();
    var j = g.substring(3,5);
    if(t<10) t = "0"+t;
    if(m<10) m = "0"+m;
    if(j<10) j = "0"+1*j;
    if(type=="full")
      {var date = t+"."+m+"."+j; return date;}
    else
      {var date = new Array(t,m,j); return date;}
    }

function checkWeekday(count,journeyType,returnDateOnly){
    var getcDate = eval("document.hafasform.REQ"+journeyType+"JourneyDate.value.toLowerCase();");
    if(getcDate == ""){var nix = 0;} else
    if((getcDate.length > 2) || (getcDate.indexOf("+")!= -1)) /* Abfrage auf '+' benoetigt ??? */
      {changeDate(count,journeyType,returnDateOnly);}
    else
      {doWeekday(journeyType,getcDate,returnDateOnly);}
    }

function useOutwardDate(wDay)
   {
   var getcDate = eval("document.hafasform.REQ0JourneyDate.value.toLowerCase();");
   var reg = eval("/^ *("+wDay+")\, */");
   var cDate = getcDate.replace(reg,"");
   var t = (cDate.substring(0,cDate.indexOf(".")));
   var m = (cDate.substring((cDate.indexOf(".")+1),cDate.lastIndexOf(".")));
   var j = (cDate.substring((cDate.lastIndexOf(".")+1),cDate.length));
   var date = new Array(t,m,j);
   return date;
   }

function doWeekday(journeyType,getcDate,returnDateOnly){
   var wDayOri = eval("document.hafasform.wDayExt"+journeyType+".value;");
   var wDay = eval("document.hafasform.wDayExt"+journeyType+".value.toLowerCase();");
   if(journeyType == 0 && returnDateOnly == "yes")
      {var dateField = getjsDate('field');}
   else if(journeyType == 1 && returnDateOnly == "yes")
      {var dateField = useOutwardDate(wDay);}
   else /* if(journeyType == 1 && returnDateOnly == "no") */
      {var dateField = getjsDate('field');}

   var reg = eval("/^ *("+wDay+") */");
   var test = getcDate.match(reg);
   if(test!=null)
      {
      var days = getDaysSince1980((1*("20"+dateField[2])),(1*dateField[1]),(1*dateField[0]));
      var cwd = (wDay.substr((3*(1*days%7)),2));
      var nwd = test[0];
      var nwdidx  = (wDay.indexOf(test[0])/3);
      var cwdidx  = (wDay.indexOf(cwd)/3);
      if(nwdidx < cwdidx)
         {nwdidx = nwdidx + 7 - cwdidx;}
      else
         {nwdidx = nwdidx - cwdidx;}
      var newDay = nwdidx;
      var gDate = gregDate(1*newDay+1*(getDaysSince1980((1*("20"+dateField[2])),(1*dateField[1]),(1*dateField[0]))));
      var days = (1*+newDay+1*getDaysSince1980((1*("20"+dateField[2])),(1*dateField[1]),(1*dateField[0])));
      setNewDate(journeyType,gDate,getcDate,wDayOri,days);
      }
   }

/* Get and Calculate new date */
function changeDate(count,journeyType,returnDateOnly,weekdayTexts,formFieldName){
    if (typeof weekdayTexts != 'undefined') {
      if (weekdayTexts == true) {
        var wDay = eval("document.hafasform.wDayExt"+journeyType+".value;");
      } else {
        var wDay = "";
      }
    } else {
      /* mimic old behavior */
        var wDay = eval("document.hafasform.wDayExt"+journeyType+".value;");
    }

    if (typeof formFieldName != 'undefined') {
      var getcDate = eval("document.hafasform."+formFieldName+".value;");
    } else {
      var getcDate = eval("document.hafasform.REQ"+journeyType+"JourneyDate.value;");
    }

    var reg = eval("/^ *("+wDay+")\, */");
    if(getcDate=="" && journeyType==1 && returnDateOnly=="no")  {var getcDate = getjsDate('full');}
    if(getcDate=="" && journeyType==1 && returnDateOnly=="yes") {var getcDate = eval("document.hafasform.REQ0JourneyDate.value;");}
    var cDate = getcDate.replace(reg,"");
    var ctg = 1*(cDate.substring(0,cDate.indexOf(".")));
    var cmt = 1*(cDate.substring((cDate.indexOf(".")+1),cDate.lastIndexOf(".")));
    var cjr = (cDate.substring((cDate.lastIndexOf(".")+1),cDate.length));
    if(ctg=="" || cmt=="" || cjr=="")
      {/* NIX */}
    else
      {
       if(cjr.length==4){cjr = cjr.substring(2,4);};
       var gDate = gregDate(1*count+1*(getDaysSince1980((1*("20"+cjr)),cmt,ctg)));
       var days = (1*count+1*(getDaysSince1980((1*("20"+cjr)),cmt,ctg)));
       setNewDate(journeyType,gDate,cDate,wDay,days,weekdayTexts,formFieldName);
       }
    }

function setNewDate(journeyType,gDate,cDate,wDay,days,weekdayTexts,formFieldName)
   {
   if(gDate[0]<10){gDate[0]="0"+gDate[0];}
   if(gDate[1]<10){gDate[1]="0"+gDate[1];}

   if (typeof weekdayTexts != 'undefined') {
     if (weekdayTexts == true) {
       var nwd = (wDay.substr((3*(1*days%7)),2))+", ";
     } else {
       var nwd = "";
     }
   } else {
      /* mimic old behavior */
       var nwd = (wDay.substr((3*(1*days%7)),2))+", ";
   }
   var nDate = nwd+gDate[0]+"."+gDate[1]+"."+gDate[2];
   if(nDate.indexOf("NaN")!=-1) var nDate = cDate;

   if (typeof formFieldName != 'undefined') {
     eval("document.hafasform."+formFieldName+".value =\""+nDate+"\";");
   } else {
     eval("document.hafasform.REQ"+journeyType+"JourneyDate.value =\""+nDate+"\";");
   }
}

function getDaysSince1980(y, m, d){
   var daysInMonth = new Array(0,31,59,90,120,151,181,212,243,273,304,334);
   var returnDays = (y-1980)*365;
   returnDays    += (y-1980+3)/4;
   returnDays    += daysInMonth[m-1];
      if(m>2 && isLeapYear(y)==true) returnDays ++;
   returnDays += d;
   returnDays = parseInt(returnDays);
   return returnDays;
   }

function isLeapYear(y){if((y%4)==0 && (y%100)!=0 || (y%400)==0) return true;}

function gregDate(daysSince1980){
   var daysSince1980 = parseInt(daysSince1980);
   var daysInMonth = new Array(0,31,59,90,120,151,181,212,243,273,304,334);
   var daysInYear = 366;
   var years      = 0;
   var february_29;
   var n = 11;
   if(daysSince1980 < 0) daysSince1980 = 0;
   while(daysSince1980> daysInYear){
      years ++;
      daysSince1980 -= daysInYear;
      if((years%4)==0) {daysInYear = 366;} else {daysInYear = 365;}
      }
   if((years%4)==0 && daysSince1980>=60)
      {february_29 = true; daysSince1980 --;} else
      {february_29 = false;}

   while(n>0 && daysInMonth[n]>=daysSince1980) n--;
   if(february_29==true && daysSince1980 == 59) daysSince1980 ++;
   var d = (daysSince1980-daysInMonth[n]);
   var m = n+1;
   var ty = (years + 1980).toString();
   var y = ty.substring(2,4);
   var gDate = new Array(d,m,y);
   return gDate;
   }


  /**
   *  controls display of date and time for return journey
   *  if return journey isn't displayed, names of date and time fields are changed,
   *  so they won't be submitted as return date
   */
  var returnDateShown = "no";
  function displayReturnDate(flag){
    var returnJourneyBlock = document.getElementById("returnJourneyBlock");
    var returnDate = document.getElementById("dato1");
    var returnTime = document.getElementById("klokken1");
    var returnDep = document.getElementById("afgradio1");
    var returnArr = document.getElementById("ankradio1");
    var bothDirectionsFlag = document.getElementById("special_search_both");
    var singleDateCaption = document.getElementById("singleDateCaption");
    var outwardDateCaption = document.getElementById("outwardDateCaption");
    if(flag == "yes") {
      returnJourneyBlock.style.display = "block";
      returnDate.disabled = false;
      returnTime.disabled = false;
      returnDep.disabled = false;
      returnArr.disabled = false;
      bothDirectionsFlag.disabled = false;
      singleDateCaption.style.display = "none";
      outwardDateCaption.style.display = "inline";
      if((returnTime.value == "") && (returnDateShown == "no")){
         var outwardTime = document.getElementById("klokken0").value;
         if(outwardTime != ""){
            returnTime.value = outwardTime;
         }

      }
      returnDateShown = "yes";
    }
    else {
      returnJourneyBlock.style.display = "none";
      returnDate.disabled = true;
      returnTime.disabled = true;
      returnDep.disabled = true;
      returnArr.disabled = true;
      bothDirectionsFlag.disabled = true;
      singleDateCaption.style.display = "inline";
      outwardDateCaption.style.display = "none";
    }
  }


  /**
   *  controls selection of product groups
   *  selects/deselects groups of products and all products
   */
  function checkProducts(groupId,first,last,mode){
    var globalValue = document.getElementById(groupId).checked;
    for(i = first; i <= last; i++){
      if(!((mode == 'comodal') && (i==9))){
        if(document.getElementById("prod_"+i).checked != globalValue)
          currentNrOfProducts['allProductsChecked'] = (globalValue) ? currentNrOfProducts['allProductsChecked']+1 : currentNrOfProducts['allProductsChecked']-1;
        document.getElementById("prod_"+i).checked = globalValue;
        }
    }
    //currentNrOfProducts['allProductsChecked'] = (globalValue) ? currentNrOfProducts['allProductsChecked']+last-first+1 : currentNrOfProducts['allProductsChecked']+first-last-1;
    currentNrOfProducts[groupId] = (globalValue) ? nrOfProducts[groupId] : 0;
    if(groupId == 'allProductsChecked'){
      document.getElementById('allTrainsChecked').checked = globalValue;
      document.getElementById('allBussesChecked').checked = globalValue;
      currentNrOfProducts['allTrainsChecked'] = (globalValue) ? nrOfProducts['allTrainsChecked'] : 0;
      currentNrOfProducts['allBussesChecked'] = (globalValue) ? nrOfProducts['allBussesChecked'] : 0;
    }
    else if(currentNrOfProducts['allProductsChecked'] == nrOfProducts['allProductsChecked'])
      document.getElementById('allProductsChecked').checked = true;
    else
      document.getElementById('allProductsChecked').checked = false;
  }

  /**
   *  controls selection of groups checkboxes
   *  selects/deselects group checkboxes of products according to their products
   */
  function checkProduct(groupId,productNr){
    var newValue = document.getElementById("prod_"+productNr).checked;
    currentNrOfProducts[groupId] = (newValue) ? currentNrOfProducts[groupId]+1 : currentNrOfProducts[groupId]-1;
    if(currentNrOfProducts[groupId] == nrOfProducts[groupId])
      document.getElementById(groupId).checked = true;
    else
      document.getElementById(groupId).checked = false;

    if(groupId != 'allProductsChecked'){
      currentNrOfProducts['allProductsChecked'] = (newValue) ? currentNrOfProducts['allProductsChecked']+1 : currentNrOfProducts['allProductsChecked']-1;
      if(currentNrOfProducts['allProductsChecked'] == nrOfProducts['allProductsChecked'])
        document.getElementById('allProductsChecked').checked = true;
      else
        document.getElementById('allProductsChecked').checked = false;
      }

  }

  /**
   *  checkbox "avoid ferries" in comodal version
   */
  function toggleAvoidFerry(){
    var currentValue = $('dummyAvoidFerryCheckboxID').checked;

    // status: use or avoid ferries
    if(currentValue == true){
      $('avoidFerryParameter').value='yes';
      $('prod_9').checked = false;
    } else {
      $('avoidFerryParameter').value='no';
      $('prod_9').checked = true;
    }
  }

  /**
   *  controls display of intermodal distances
   *  controls display of all intermodal distance-boxes, showing only the selected means of transport
   */
  function adaptDistanceBox(stop){
    var currentIntermodal = document.getElementById("REQ0Journey"+stop+"_Foot_enable").value;
    var currentIntermodalValue = currentIntermodal.split("&");
    if(currentIntermodalValue[1] == "REQ0Journey"+stop+"_Foot_enable=1"){
      document.getElementById("intermodal"+stop+"_1").style.display = "block";
      document.getElementById("intermodal"+stop+"_2").style.display = "none";
    }
    else {
      document.getElementById("intermodal"+stop+"_1").style.display = "none";
      document.getElementById("intermodal"+stop+"_2").style.display = "block";
    }
  }


  /**
   *  controls display of advanced search parameter
   *  controls display of blocks of advanced search parameter.
   *  If the number of blocks exceeds 10, this parameter must be adapted
   *  If the number of blocks shown only in basic search exceeds 3, this parameter must be adapted
   */
  function openAdvanced(flag){
    if(flag == "true"){
      var displayAdvanced = "block";
      var displayBasic = "none";
      document.getElementById("advancedSearchModeToggle").disabled = false;
    }
    else {
      var displayAdvanced = "none";
      var displayBasic = "block";
      document.getElementById("advancedSearchModeToggle").disabled = true;
    }
    var i = 1;
    var advancedContent = document.getElementById("advancedContent"+i);

    while(i < 10){
      if(advancedContent){
        if((advancedContent.nodeName == "SPAN") && (displayAdvanced == "block"))
          advancedContent.style.display = "inline";
        else
          advancedContent.style.display = displayAdvanced;
      }
      i++;
      advancedContent = document.getElementById("advancedContent"+i);
    }

    var i = 1;
    var basicContent = document.getElementById("basicContent"+i);

    while(i < 3){
      if(basicContent){
        if((basicContent.nodeName == "SPAN") && (displayBasic == "block"))
          basicContent.style.display = "inline";
        else
          basicContent.style.display = displayBasic;
      }
      i++;
      basicContent = document.getElementById("basicContent"+i);
    }
  }


  /**
   *  resets "did you mean anything else?"- select box to input field
   */
  function resetLocation(location,loc2){
     var selectBox = document.getElementById("REQ0JourneyStops"+location+"0ID");
     var container = selectBox.parentNode;
     var inputField = document.getElementById("hafas"+loc2);
     inputField.style.display = "inline";
     inputField.size = 30;
     var inputID = document.createElement("input");
     inputID.type = "hidden";
     inputID.name = selectBox.name;
     inputID.value = selectBox.value;
     container.replaceChild(inputID,selectBox);
     selectBox = null;
     var inputType = document.createElement("input");
     inputType.type = "hidden";
     inputType.name = "REQ0JourneyStops"+location+"0A";
     inputType.value = 71;
     container.appendChild(inputType);
     var resetLocationTD = document.getElementById("resetLocation"+location);
     resetLocationTD.parentNode.removeChild(resetLocationTD);
     resetLocationTD = null;
     var hintRow = document.getElementById("didYouMeanAnythingElseHint"+location);
     hintRow.parentNode.removeChild(hintRow);
     hintRow = null;
  }

  /**
   *  selects current connection
   *  selects a connection and deselects the previous selected connection
   */
  function selectConnection(elementId, connectionId, mode){
    var tableRows = document.getElementsByTagName("tr");
    var checkBoxName = mode+"connection";
    var pseudoRadioButton = "TicketRadio"+mode;
    var selectClassname = "tr"+mode+connectionId;
    var deselectClassname = "ovBgSelected";
    var unselectedClassname = "ovBgBasic";
    var firstRowClassname = "ovConFirstRow";
    var firstRowSelect = null;
    var firstRowDeselect = null;
    var classnames;

    // search for relevant rows
    // ========================

    for (var i = 0; i < tableRows.length; i++){
      // test if the searched classNames are part of the className attribute
      classnames = " "+tableRows[i].className+" ";
      if((classnames.indexOf(" "+deselectClassname+" ") != -1) && (classnames.indexOf(mode) != -1)){
         tableRows[i].className = tableRows[i].className.split(deselectClassname).join(" ");
         tableRows[i].className += " "+unselectedClassname;
         if(firstRowSelect == null)
            firstRowSelect = tableRows[i];
      }
      if(classnames.indexOf(" "+selectClassname+" ") != -1){
         tableRows[i].className = tableRows[i].className.split(unselectedClassname).join(" ");
         tableRows[i].className += " "+deselectClassname;
         if(firstRowDeselect == null)
            firstRowDeselect = tableRows[i];
      }
    }

    // control relevant information of the selected connection for "buy ticket" functionality and design issues
    // ========================

    // control hidden checkbox, that includes relevant information for the "buy ticket" button
    var checkBoxes = document.getElementsByName (checkBoxName);
    // control "radio buttons", that are displayed but are NOT relevant for the "buy ticket" button (only for design issues)
    var pseudoRadioButtons = document.getElementsByName (pseudoRadioButton);
    // control red borders of "radio buttons", in case of an "buy ticket" errormessage
    var buyTicketError = document.getElementsByClassName('ticketOrderErrorBoxOn');

    // control checkbox-value and "radio-button"-layout
    if (checkBoxes != null)
        {
        for (var i = 0; i < checkBoxes.length; i++)
            {
            if (checkBoxes[i].id != elementId)
                {
                checkBoxes[i].checked = false;
                if(buyTicketError[0])
                    {
                    pseudoRadioButtons[i].innerHTML = jsRadioButtonErrorPassive;
                    }
                else
                    {
                    pseudoRadioButtons[i].innerHTML = jsRadioButtonStandardPassive;
                    }
                }
            else
                {
                checkBoxes[i].checked = true;
                if(buyTicketError[0])
                    {
                    pseudoRadioButtons[i].innerHTML = jsRadioButtonErrorActive;
                    }
                else
                    {
                    pseudoRadioButtons[i].innerHTML = jsRadioButtonStandardActive;
                    }
                }
            }
        }


    // update "buy ticket" button(s)
    for(var i=0; i<jsConnectionIDOutward.length; i++){
      if(jsConnectionIDOutward[i] == connectionId){
        for(var j=1; j<3; j++){
          if($('smsTicket_Button_'+j))
            {
            // SMS-Ticket
            if(jsConnectionOutwardTicket_Url[i] != null){
              // update onclick-handler of ticket sms-ticket button!!!
              if(jsConnectionOutwardTicket_Url_onclick[i] != null)
                {
                $('smsTicket_Button_'+j).onclick = jsConnectionOutwardTicket_Url_onclick[i];
                }
              // update URL of ticket sms-ticket button!!!
              $('smsTicket_Button_'+j).href = jsConnectionOutwardTicket_Url[i];
              $('smsTicket_Button_'+j).className = 'enabledTicketButton';
              $('fcTicketButton_'+j).className = 'disabledTicketButton';
              $('dsbTicketButton_'+j).className = 'disabledTicketButton';
              $('dsbReturnTicketButton_'+j).className = 'disabledTicketButton';

            // DSB...
            } else {

              // ... findAPrice
              if (jsFindAPrice == true){
                $('smsTicket_Button_'+j).className = 'disabledTicketButton';
                $('fcTicketButton_'+j).className = 'enabledTicketButton';
                $('dsbTicketButton_'+j).className = 'disabledTicketButton';
                $('dsbReturnTicketButton_'+j).className = 'disabledTicketButton';

              // ... single ride
              } else if (jsReturnJourneyExists == false){
                $('smsTicket_Button_'+j).className = 'disabledTicketButton';
                $('fcTicketButton_'+j).className = 'disabledTicketButton';
                $('dsbTicketButton_'+j).className = 'enabledTicketButton';
                $('dsbReturnTicketButton_'+j).className = 'disabledTicketButton';

              // ... return journey
              } else if (jsReturnJourneyExists == true){
                $('smsTicket_Button_'+j).className = 'disabledTicketButton';
                $('fcTicketButton_'+j).className = 'disabledTicketButton';
                $('dsbTicketButton_'+j).className = 'disabledTicketButton';
                $('dsbReturnTicketButton_'+j).className = 'enabledTicketButton';
              }
            }
          }
        }
      }
    }

    // Set SMSTicket connection times
    setSMSTicketConnectionTimes(connectionId, mode);

    // call hafaswai-function
    changeSelection(connectionId, mode);

    // change url of sms-ticket-button
    changeTicketButtonUrl(connectionId, mode);
  }


  function setSMSTicketConnectionTimes(connectionId,mode)
    {
    if(mode == "RETURN")
      {
      for(var i=0; i<jsConnectionIDReturn.length; i++)
        {
        if(jsConnectionIDReturn[i] == connectionId)
          {
          SMSTicketReturnTimes = jsConnectionReturnTicket_Times[i];
          }
        }
      }
    else
      {
      for(var i=0; i<jsConnectionIDOutward.length; i++)
        {
        if(jsConnectionIDOutward[i] == connectionId)
          {
          SMSTicketOutwardTimes = jsConnectionOutwardTicket_Times[i];
          }
        }
      }
    }


  /**
   * change url of each sms-ticket-button
   */
  function changeTicketButtonUrl(connectionId, mode) {
      for(var j=1; j<3; j++){
          // is it a sms-ticket-button?
          //if(typeof $('smsTicket_Button_'+j) != undefined) {
          if($('smsTicket_Button_'+j) != null) {
              var currentUrl = $('smsTicket_Button_'+j).href;

              // Update basic array urls -> they are used for button initialisation e.g. if another ticker type then SMS-ticket was used!
              var suchMuster = (mode == "RETURN") ? /retConId=([A-Z0-9-]+)/ : /outConId=([A-Z0-9-]+)/;
              for(var i=0; i<jsConnectionOutwardTicket_Url.length; i++)
                  {
                  if(jsConnectionOutwardTicket_Url[i] != null)
                    {
                    var oldConnectionId = suchMuster.exec(jsConnectionOutwardTicket_Url[i]);
                    if(oldConnectionId)
                      {
                      jsConnectionOutwardTicket_Url[i] = jsConnectionOutwardTicket_Url[i].replace(oldConnectionId[1], connectionId);
                      }
                    }
                  }

              // check if second mode is used
              var searchResult = currentUrl.search(/L=vs_ticket_order/);
              if(searchResult != -1) {

                  // return journey
                  if(mode == "RETURN") {
                      var suchMuster = /retConId=([A-Z0-9-]+)/;
                      var oldConnectionId = suchMuster.exec(currentUrl);
                      var newUrl = currentUrl.replace(oldConnectionId[1], connectionId);

                      if(typeof SMSTicketOutwardTimes != "undefined" && SMSTicketOutwardTimes != "")
                        {
                        // Outward dep time
                        var suchMuster = /depTimeOut=([0-9:]+)/;
                        var oldDepTimeOut = suchMuster.exec(newUrl);
                        var newUrl = newUrl.replace(oldDepTimeOut[0], SMSTicketOutwardTimes.split("|")[0]);
                        // Outward arr time
                        var suchMuster = /arrTimeOut=([0-9:]+)/;
                        var oldArrTimeOut = suchMuster.exec(newUrl);
                        var newUrl = newUrl.replace(oldArrTimeOut[0], SMSTicketOutwardTimes.split("|")[1]);
                        }

                      if(typeof SMSTicketReturnTimes != "undefined" && SMSTicketReturnTimes != "")
                        {
                        // Return dep time
                        var suchMuster = /depTimeRet=([0-9:]+)/;
                        var oldDepTimeRet = suchMuster.exec(currentUrl);
                        var newUrl = newUrl.replace(oldDepTimeRet[0], SMSTicketReturnTimes.split("|")[0]);
                        // Return arr time
                        var suchMuster = /arrTimeRet=([0-9:]+)/;
                        var oldArrTimeRet = suchMuster.exec(newUrl);
                        var newUrl = newUrl.replace(oldArrTimeRet[0], SMSTicketReturnTimes.split("|")[1]);
                        }

                      $('smsTicket_Button_'+j).href = newUrl;

                  // outward connection
                  } else if(mode == "OUTWARD") {
                      // Con ID
                      var suchMuster = /outConId=([A-Z0-9-]+)/;
                      var oldConnectionId = suchMuster.exec(currentUrl);
                      var newUrl = currentUrl.replace(oldConnectionId[1], connectionId);

                      if(typeof SMSTicketOutwardTimes != "undefined" && SMSTicketOutwardTimes != "")
                        {
                        // Outward dep time
                        var suchMuster = /depTimeOut=([0-9:]+)/;
                        var oldDepTimeOut = suchMuster.exec(newUrl);
                        var newUrl = newUrl.replace(oldDepTimeOut[0], SMSTicketOutwardTimes.split("|")[0]);
                        // Outward arr time
                        var suchMuster = /arrTimeOut=([0-9:]+)/;
                        var oldArrTimeOut = suchMuster.exec(newUrl);
                        var newUrl = newUrl.replace(oldArrTimeOut[0], SMSTicketOutwardTimes.split("|")[1]);
                        }

                      if(typeof SMSTicketReturnTimes != "undefined" && SMSTicketReturnTimes != "")
                        {
                        // Return dep time
                        var suchMuster = /depTimeRet=([0-9:]+)/;
                        var oldDepTimeRet = suchMuster.exec(newUrl);
                        var newUrl = newUrl.replace(oldDepTimeRet[0], SMSTicketReturnTimes.split("|")[0]);
                        // Return arr time
                        var suchMuster = /arrTimeRet=([0-9:]+)/;
                        var oldArrTimeRet = suchMuster.exec(newUrl);
                        var newUrl = newUrl.replace(oldArrTimeRet[0], SMSTicketReturnTimes.split("|")[1]);
                        }


                      $('smsTicket_Button_'+j).href = newUrl;
                  }
              }
          }
      }
  }


  /**
   *  check if return journey is shown if selected, needed if back-button was hit
   */
  function checkOnBack(){
      var returnRadio = document.getElementById("showReturnDateYes");
      if(returnRadio){
        if(returnRadio.checked == true)
          displayReturnDate('yes');
        }
  }

  /**
   *  needed if back-button was hit:
   *  check, if location input fields are actually displayed (no list or fixed value)
   *  and then, if they are already filled with content (text)
   *  -> if so, don't display input hints
   */
  function blurInputHintOnBack(){

    /* start in tp/tb/eu */
    if(document.getElementsByName('REQ0JourneyStopsS0G')[0]){
      if(document.getElementsByName('REQ0JourneyStopsS0G')[0].value != ''){
        blurInputHint('inputHintFrom','NONE');
      }
    }

    /* destination in tp/tb/eu */
    if(document.getElementsByName('REQ0JourneyStopsZ0G')[0]){
      if(document.getElementsByName('REQ0JourneyStopsZ0G')[0].value != ''){
        blurInputHint('inputHintTo','NONE');
      }
    }

    /* park&ride stop in comodal */
    if(document.getElementsByName('REQ0JourneyStopsC0G')[0]){
      if(document.getElementsByName('REQ0JourneyStopsC0G')[0].value != ''){
        blurInputHint('inputHintParkride','NONE');
      }
    }

    /* station in sq */
    if($('hafasStation')){
      if($('hafasStation').value != ''){
        blurInputHint('inputHintStation','NONE');
      }
    }

    /* direction in sq */
    if($('hafasDirection')){
      if($('hafasDirection').value != ''){
        blurInputHint('inputHintDirection','NONE');
      }
    }
  }

  /**
   *
   */
  function showSelectedCons(){
     var outConId = getCheckBoxGroupValue ("hafasresults", "OUTWARDconnection");
     var retConId = getCheckBoxGroupValue ("hafasresults", "RETURNconnection");

     if (outConId)
         {
         selectConnection('vCtrl_connection_overviewOut_'+outConId, outConId,'OUTWARD');
         }
     if (retConId)
         {
         selectConnection('vCtrl_connection_overviewRet_'+retConId, retConId,'RETURN');
         }
  }


  function showWaitIcon(id){
     document.getElementById('searchWaitScreen').style.display='block';
     document.getElementById(id).style.display='none';
  }
  function hideWaitIcon(){
     document.getElementById('searchWaitScreen').style.display='none';
     document.getElementById('queryInputButtons').style.display='block';
  }

  /**
   *  controls display of any container
   *  if container is hidden all input fields are disabled
   *  so they won't be submitted (cag)
   */
  function displayEnableContainer(container, flag){
    var returnDateContainer = document.getElementById(container);
    var i = 0;
    if(flag == "yes") {
      returnDateContainer.style.display = "block";
      for(i=0;i<returnDateContainer.getElementsByTagName("input").length;i++){
        returnDateContainer.getElementsByTagName("input")[i].disabled = false;
      }
      for(i=0;i<returnDateContainer.getElementsByTagName("textarea").length;i++){
        returnDateContainer.getElementsByTagName("textarea")[i].disabled = false;
      }
    }
    else {
      returnDateContainer.style.display = "none";
      for(i=0;i<returnDateContainer.getElementsByTagName("input").length;i++){
        returnDateContainer.getElementsByTagName("input")[i].disabled = true;
      }
      for(i=0;i<returnDateContainer.getElementsByTagName("textarea").length;i++){
        returnDateContainer.getElementsByTagName("textarea")[i].disabled = true;
      }
    }
  }

  /**
   *  exchanges current content inside an element with a given "id" with the "newContent" given
   */
  function exchangeContent(id,newContent){
    $(id).innerHTML = newContent;
  }

  /**
   *  exchanges current class name of an element with a certain "id" with the "newClassName" given
   *  requires, that the element has an id- AND class-attribute!
   */
  function exchangeClassName(id,newClassName){
    $(id).className = newClassName;
  }

  /**
   *  toggle display status (visible/hidden) of two elements, of those only one has to be displayed
   *  requires two parameters: id of element actually be displayed, id of element to show now
   */
  function toggleContent(idToHide,idToShow){
    $(idToHide).style.display='none';
    $(idToShow).style.display='block';
  }

  /**
   *  switches an element of a given id on or off, corresponding to the status given
   *  requires two parameters: id of element to be switched on or off, status 'on' or 'off'
   */
  function switchContentOnOrOff(idToSwitch,switchStatus){
    if(switchStatus == 'on'){
      $(idToSwitch).style.display='inline';
    } else if (switchStatus == 'off'){
      $(idToSwitch).style.display='none';
    } else if (switchStatus == 'inline'){
      $(idToSwitch).style.display='inline';
    } else if (switchStatus == 'block'){
      $(idToSwitch).style.display='block';
    }
  }

  /**
   * close specific element of a given id
   */
  function closeElement(id){
    $(id).style.display = "none";
  }


  /**
   *  disables or enables an element of a given id, corresponding to the ability status given
   *  requires two parameters: id of element to be en- or disabled, status 'enable' or 'disable'
   */
  function enableOrDisableElement(idOfElement,abilityStatus){
    if(abilityStatus == 'enable'){
      $(idOfElement).disabled = false;
    } else if (abilityStatus == 'disable'){
      $(idOfElement).disabled = true;
    }
  }

  /**
   *  blurs hint texts of input fields and sets focus on corresponding input field
   */
  function blurInputHint(idToBlur,idToFocus){
    if($(idToBlur)){
      $(idToBlur).style.display='none';
      if(idToFocus != 'NONE'){
        $(idToFocus).focus();
      }
    }
  }

  /**
   *  check, if location-type-combination in EU-Spirit is valid. Invalid are:
   *  airport/airport; station abroad/airport; airport/station abroad
   */
  function checkEUForm(euErrMsgText){

      //  Airport for start selected?
      var euFromAirportSelected = false;
      if($("euLocType_fromAir")){
        if($("euLocType_fromAir").checked){
          euFromAirportSelected = true;
        }
      } else if ($("from_sel_element").value == 1000) {
          euFromAirportSelected = true;
      }

      //  Airport for destination selected?
      var euToAirportSelected = false;
      if($("euLocType_toAir")){
        if($("euLocType_toAir").checked){
          euToAirportSelected = true;
        }
      } else if ($("to_sel_element").value == 1000) {
          euToAirportSelected = true;
      }

      //  European station for start selected?
      var euFromEuropeanStationSelected = false;
      if($("from_sel_element").value == 8080){
        euFromEuropeanStationSelected = true;
      }

      //  European station for destination selected?
      var euToEuropeanStationSelected = false;
      if($("to_sel_element").value == 8080){
        euToEuropeanStationSelected = true;
      }

      // should hint of forbidden EU combination be shown?
      var showEuCombinationHint = false;
      if((euFromAirportSelected == true) && (euToAirportSelected == true)){
        showEuCombinationHint = true;
      } else if ((euFromAirportSelected == true) && (euToEuropeanStationSelected == true)) {
        showEuCombinationHint = true;
      } else if ((euFromEuropeanStationSelected == true) && (euToAirportSelected == true)) {
        showEuCombinationHint = true;
      }
      if(showEuCombinationHint == true){
        hideWaitIcon();
        alert(unescape(euErrMsgText));
        return false;
      }
  }

  /**
   *  toggle status of p2w-query page. parameter "type" may have the values "basic" or "advanced"
   */
  function p2wQueryPageMode(type){
    if(type == 'basic'){
      switchContentOnOrOff('tbQueryAdvanced','off');
      switchContentOnOrOff('showLinkTbAdvanced','on');
      switchContentOnOrOff('showLinkTbBasic','off');
      switchContentOnOrOff('showLinkTbReset','off');
      enableOrDisableElement('checkTBRequestStep2','disable');
    } else if(type == 'advanced'){
      switchContentOnOrOff('tbQueryAdvanced','on');
      switchContentOnOrOff('showLinkTbAdvanced','off');
      switchContentOnOrOff('showLinkTbBasic','on');
      switchContentOnOrOff('showLinkTbReset','on');
      enableOrDisableElement('checkTBRequestStep2','enable');
    }
  }

  /**
   * oresund search mode: toggle direction between "from oresund" and "to oresund"
   * requires id of selection list; updates selection and values of "start" and "destination" region
   */
  function updateOresundDirection(id){
    var currentDirection  = $(id).options[$(id).selectedIndex].value;
    if(currentDirection == 'fromSkane'){

      // start location definitions (skane active, dk off)
      $('rowLocatioType_from').style.display = "";
      $('dk_fromAll').disabled = true;
      $('oresund_fromBhf').disabled = false;
      $('oresund_fromAdr').disabled = false;
      $('oresund_fromPoi').disabled = false;
      $('oresund_sel_from_region').value = '741';

      // destination location definitions (dk active, skane off)
      $('rowLocatioType_to').style.display = "none";
      $('dk_toAll').disabled = false;
      $('oresund_toBhf').disabled = true;
      $('oresund_toAdr').disabled = true;
      $('oresund_toPoi').disabled = true;
      $('oresund_sel_to_region').value = '86';

    } else if (currentDirection == 'toSkane') {

      // start location definitions (dk active, skane off)
      $('rowLocatioType_from').style.display = "none";
      $('dk_fromAll').disabled = false;
      $('oresund_fromBhf').disabled = true;
      $('oresund_fromAdr').disabled = true;
      $('oresund_fromPoi').disabled = true;
      $('oresund_sel_from_region').value = '86';

      // destination location definitions (skane active, dk off)
      $('rowLocatioType_to').style.display = "";
      $('dk_toAll').disabled = true;
      $('oresund_toBhf').disabled = false;
      $('oresund_toAdr').disabled = false;
      $('oresund_toPoi').disabled = false;
      $('oresund_sel_to_region').value = '741';
    }
  }

  /**
   * close customer banner and safe status in a cookie
   */
  function closePromoBanner(id,versionNumber){
    closeElement(id);
    // writes the id of the latest Banner into a cookie
    document.cookie = 'bannerViewed=' + versionNumber+';';
  }

  function checkPromoBanner(id){
     var bannerviewed = getCookie('bannerViewed');
     if(id == bannerviewed){
        closeElement('promoBanner');
     }
  }
  function toggleRoute(conId){
    var columns = $('carRoutecarOnly'+conId).getElementsByTagName("tr");
     for(var i=0;i < columns.length; i++){
         columns[i].style.display = '';
     }
     $('showCompleteRoute'+conId).style.display = 'none';
  }
  /**
   * toggle display and intermodal settings for park&ride
   */
  function toggleParkRide()
  {
    // display
    var currentValue = $("parkride").checked;
    $("parkriderow").style.display = currentValue ? "":"none";
    $("parkrideNo").checked = !(currentValue);
    $('intermodal_dep_ParkRide').value = (currentValue)? '1':'0';
    if($("hafasC")){
      $("hafasC").disabled = !(currentValue);
    }
    if($("hafasC0K")){
      $("hafasC0K").disabled = !(currentValue);
    }
    if(!(currentValue)){
      if($("hafasC")){
        $("hafasC").value = "";
      }
    }
  }

  function catenateIVCostParameters(mode){
    if(typeof(comodalIVURL) == "undefined")
      comodalIVURL = $("comodalIVCostButton"+mode).href;
    var anchor = $("REQ0Total_KissRide_cost"+mode);
    var currentValue = anchor.value;
    currentValue = currentValue.replace(/,/,".");
    currentValue = parseFloat(currentValue);
    currentValue *= 100;

    var currentParams = anchor.name+"="+currentValue;
    currentParams += "&REQ0JourneyDep_KissRide_cost="+currentValue;
    currentParams += "&REQ0JourneyDest_KissRide_cost="+currentValue+"&";
    $("comodalIVCostButton"+mode).href = comodalIVURL+currentParams;
    return currentParams;
  }

  /**
   * save form input field's content when changing language
   */
  function changeFormData(url)
  {

    // change name of submit-button
    document.getElementsByName('start')[0].setAttribute('name', 'changeRequestProperties');

    // change action of hafasform
    document.hafasform.setAttribute("action", url);

    // submit form
    document.hafasform.submit();

  }

  /**
   * creating complete json object for sms realtime push service
   */
  function createSmsRealtimePushContent(conId, smsText, url, voText, sectionInfoContent, viaInfo) {
    var phoneNumber = $('smsPushPhoneNo_' + conId).value;
    phoneNumber = phoneNumber.replace (/ /g, '');
    var sendContent = (phoneNumber == '') ? false : true;
    url = encodeURIComponent(url);
    smsText = encodeURIComponent(smsText);

    // phone number given
    if(sendContent == true) {
        smsRealtimePushContent = '{\
          "consections": [' + sectionInfoContent + '],\
          "monitorFlags": {\
              "af": true,\
              "cf": true,\
              "df": true,\
              "dv": true,\
              "of": true,\
              "pf": true\
          },\
          "phoneNumber": "' + phoneNumber + '",\
          "smsText": "' + smsText + '",\
          "url": "' + url + '",\
          "vo": "' + voText + '",\
          "viaWaitTimes": [' + viaInfo + ']\
        }';

        sendSMSRealtimePushContent(conId, smsRealtimePushContent);
    }

    // phone number not given
    else {
      // create new error text element, if not defined
      if(!($('errorTextSMSPush_' + conId))) {
        var errorText = document.createElement("p");
        errorText.setAttribute("id", "errorTextSMSPush_" + conId);
        errorText.setAttribute("class", "errormessage");
        errorText.innerHTML = "<b>" + gRTSMS_Err_NoPhoneNumberGiven + "</b>";
        $('smsPushContent_' + conId).appendChild(errorText);
      }
    }
  }

  /**
   * send smsRealtimePushContent via AJAX
   */
  function sendSMSRealtimePushContent(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
          $('smsPushContent_' + conId).update("<p><b>" + gRTSMS_Confirmation + "</b></p>");
        }

        else {
          // removes form content
          $('smsPushContent_' + conId).update("<p><b>" + gRTSMS_Err_UnspecificMsg + "</b></p>");
        }
      }
    });
  }


  /**
   * log clicks
   */
  function logClicks(clickedElement,source){

    // Count clicks or show statistics result?
    if(typeof(clickArrayMaxIdx) != "undefined"){
      for (n = 1; n <= clickArrayMaxIdx; n++) {
        if (clickId[n] == clickedElement) {
        // Show result
        alert("Number of '"+clickDescription[n]+"': "+clickCount[n]);
        return; // Don't count this click
        }
      }
    }

    // check, if click-base-url is not defined
    if(typeof(gClickExe_BaseUrl) == "undefined"){
      return;
    } else {
      // don't count clicks on 'close' links
      if((source) && (source.nodeName == "A") && (source.id) && (source.id.match(/^link/)) && (source.className.match(/\bclose\b/)))
        {
          return;
        }
      // additional parameter for creation of unique url to avoid MSIE6 cache bug
      var now = new Date();
      var Tag = now.getDate();
      var uniqueParam = now.getMilliseconds().toString() + now.getSeconds().toString() + now.getMinutes().toString() + now.getHours().toString();

      // prepare url and submit
      var currentClickExeUrl = gClickExe_BaseUrl + 'app=' + gClickExe_Application + '&site=' + gClickExe_Site + '&id=' + clickedElement + '&L=' + gClickExe_Layout + '&ident=' + gClickExe_Session + '&unique=' + uniqueParam;
      new Ajax.Request(currentClickExeUrl,
        {
          method:'get',
          encoding:'UTF-8',
          onSuccess:function(){
            return true;
          }
        });
    }
  }


  /**
   * avoid submit of empty P&R via field
   */
  function checkParkRideVia(){

    // disable ParkRide-Via?
    var disableParkRideVia = false;
    if($('parkriderow').style.display == 'none'){
      disableParkRideVia = true;
    // 5476: don't uncheck P&R, if field is empty
    //} else if($('hafasC')){
    //  if($('hafasC').value == ''){
    //    disableParkRideVia = true;
    //  }
    }

    // do it
    if(disableParkRideVia == true){
      $('intermodal_dep_ParkRide').value = '0';
      $("parkride").checked = false;
      toggleParkRide();
    }
  }


  /**
   * check addthis availability/include external script
   */
  function checkAddThis(){
    if(typeof jsAddThisIsAvailable != 'undefined') {
      if(jsAddThisIsAvailable == true) {
          var addThisSCRIPT = document.createElement("script");
          addThisSCRIPT.setAttribute("type","text/javascript");
          addThisSCRIPT.setAttribute("src","http://s7.addthis.com/js/152/addthis_widget.js");
          $('bookmarkWidget').appendChild(addThisSCRIPT);
      }
    }
  }
