/* 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 04.04.2006 by MHEI                              */
/*         regular expression used to detect given date          */

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);
}

/* 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.formular.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.formular.REQ0JourneyDate.value.toLowerCase();");
   var reg = eval("/^ *("+wDay+")\, */");
   var cDate = getcDate.replace(reg,"");
   var date = cdate.split(".");
   return date;
   }

function doWeekday(journeyType,getcDate,returnDateOnly){
   var wDayOri = eval("document.formular.wDayExt"+journeyType+".value;");
   var wDay = eval("document.formular.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){
    var wDay = eval("document.formular.wDayExt"+journeyType+".value;");
    var getcDate = eval("document.formular.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.formular.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);};
       if(cjr.length==1){cjr = "0"+cjr;};
       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);
       }
    }

function setNewDate(journeyType,gDate,cDate,wDay,days)
   {
   var nwd = (wDay.substr((3*(1*days%7)),2));
   if(gDate[0]<10){gDate[0]="0"+gDate[0];}
   if(gDate[1]<10){gDate[1]="0"+gDate[1];}
   var nDate = nwd+", "+gDate[0]+"."+gDate[1]+"."+gDate[2];
   if(nDate.indexOf("NaN")!=-1) var nDate = cDate;
   eval("document.formular.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; else return false;}

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;
   }

/* 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;
        }
  return 0;
}

/* 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;
        }
  return 0;

}

// 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();

    //    alert( "scroll position " + scrollPos.x + "/" + scrollPos.y );

    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";


//     alert( "bottom/left= " + tipDiv.style.bottom + "/" + tipDiv.style.left + "\n"
//            + "scrollPos = " + scrollPos.x + "/" + scrollPos.y + "\n"
//            + "tipDiv.offsetHeight = " + tipDiv.offsetHeight);

    // 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;
}

// show wait icon when button was clicked
function showWaitIcon(id){
   if((typeof(cWaitIdSuffix) != "undefined") && ($('searchWaitScreen'+cWaitIdSuffix)))
     {
        $('searchWaitScreen'+cWaitIdSuffix).style.display='block';
       if((id != null) && ($(id+cWaitIdSuffix)))
           $(id+cWaitIdSuffix).style.display='none';
     }
   else
     {
       if($('searchWaitScreen')) {
          $('searchWaitScreen').style.display='block';
     }
     if((id != null) && ($(id))) {
         $(id).style.display='none';
     }
     }
}

// hide wait icon
function hideWaitIcon(id){
   if($('searchWaitScreen')) {
        $('searchWaitScreen').style.display='none';
   }
   if((id != null) && ($(id))) {
       $(id).style.display='block';
   }
}


// functions for display/hide return journey form content
function showReturnJourney() {
  $('HFS_date_REQ1').removeAttribute('disabled');
  $('HFS_time_REQ1').removeAttribute('disabled');
  $('HFS_timesel_REQ1').removeAttribute('disabled');
  $('returnJourney').style.display = 'block';
  $('showReturnJourneyLink').style.display = 'none';
  $('hideReturnJourneyLink').style.display = 'inline';
  $('special_search_both').setAttribute('checked', 'checked');
}

function hideReturnJourney() {
  $('HFS_date_REQ1').setAttribute('disabled', 'disabled');
  $('HFS_time_REQ1').setAttribute('disabled', 'disabled');
  $('HFS_timesel_REQ1').setAttribute('disabled', 'disabled');
  $('returnJourney').style.display = 'none';
  $('showReturnJourneyLink').style.display = 'inline';
  $('hideReturnJourneyLink').style.display = 'none';
  $('special_search_both').removeAttribute('checked');
}


// check which products are included in bitfield
function getProductsFromBitfield(bitfield) {
    var productArray = new Array();
    for(var i=0; i<productBitsArray.length; i++) {
        var tmpBitfield = parseInt(bitfield);
        if(tmpBitfield &= productBitsArray[i]) {
            productArray.push(productBitsArray[i]);
        }
    }

    return productArray;
}

// for each fix for prototype, use this instead of for each(var i in obj)
function $for(obj, callback){
   var proto = obj.constructor.prototype,
    h = obj.hasOwnProperty, key;
   for(key in obj) {
    if((h && h.call(obj,key)) || proto[key] !== obj[key])
     callback(key, obj[key]);
   }
};
// get All Elements containing a certain class
function getElementsByClass( searchClass, domNode, tagName) {
    if (domNode == null) domNode = document.body;
    if (tagName == null) tagName = '*';
    var el = new Array();
    var tags = domNode.getElementsByTagName(tagName);
    var tcl = ''+searchClass+'';
    for(i=0,j=0; i < tags.length; i++) {
    var test = " " + tags[i].className + " ";
    if (tags[i].className.indexOf(searchClass) != -1)
        el[j++] = tags[i];
    }
    return el;
}

// functions for personalization
function removeInputFromInputField(varSelect){
  if(document.getElementById("resa"))
     document.getElementById("resa").selectedIndex = 0;

  var inputField = document.getElementById("stops"+varSelect);
  var currentLoc = inputField.value;

//..set SID/ZID to current value ... and ..//
  document.getElementById("HFS_"+varSelect+"ID").value = currentLoc;
//.. ...rename SPID/ZPID so that query ignore this input..//
  document.getElementById("stops"+varSelect).name="Enabled_PID";

  var startIndex = currentLoc.indexOf("O=");
  var startIndexType = currentLoc.indexOf("A=");
  if(startIndex > 0)
    {
    var endIndex = currentLoc.indexOf("@",startIndex);
    var endIndexType = currentLoc.indexOf("@",startIndexType);
    endIndex = (endIndex >= 0) ? endIndex : currentLoc.length;
    endIndexType = (endIndexType >= 0) ? endIndexType : currentLoc.length;
    var textDep = currentLoc.substring(startIndex+2,endIndex);
    var typeDep = parseInt(currentLoc.substring(startIndexType+2,endIndexType));
    document.getElementById("HFS_"+varSelect).value = textDep;
    setType(varSelect,typeDep);
    }
}

function resetStops(){
  var methodDELFIKeyName  = "B=";
  var methodDELFIKeyValue = 4;

  if((document.getElementById("resa")) &&(document.getElementById("resa").value != ""))
  {
  var currentRoute = document.getElementById("resa").value;
  var selectBox = document.getElementById("stopsfrom");
  if(selectBox)
    selectBox.selectedIndex = 0;
  selectBox = document.getElementById("stopsto");
  if(selectBox)
    selectBox.selectedIndex = 0;

  var startIndex = currentRoute.indexOf("O=");
  var startIndexType = currentRoute.indexOf("A=");
  var startIndexMethod = currentRoute.indexOf(methodDELFIKeyName);
  if(startIndex > 0)
    {
   var endIndex = currentRoute.indexOf("@",startIndex);
    var endIndexType = currentRoute.indexOf("@",startIndexType);
    var endIndexMethod = currentRoute.indexOf("@",startIndexMethod);
    endIndex = (endIndex >= 0) ? endIndex : currentRoute.length;
    endIndexType = (endIndexType >= 0) ? endIndexType : currentRoute.length;
    var textDep = currentRoute.substring(startIndex+2,endIndex);
    var typeDep = parseInt(currentRoute.substring(startIndexType+2,endIndexType));
    var methodDep = parseInt(currentRoute.substring(startIndexMethod+2,endIndexMethod));

    document.getElementById("HFS_from").value = textDep;
    setType("from",typeDep);

    startIndex = currentRoute.indexOf("O=",endIndex);
    startIndexType = currentRoute.indexOf("A=",endIndexType);
    if(startIndex > 0)
      {
      endIndex = currentRoute.indexOf("@",startIndex);
      endIndexType = currentRoute.indexOf("@",startIndexType);
    endIndexMethod = currentRoute.indexOf("@",startIndexMethod);
      endIndex = (endIndex >= 0) ? endIndex : currentRoute.length;
      endIndexType = (endIndexType >= 0) ? endIndexType : currentRoute.length;
      var textArr = currentRoute.substring(startIndex+2,endIndex);
      var typeArr = parseInt(currentRoute.substring(startIndexType+2,endIndexType));
    var methodArr = parseInt(currentRoute.substring(startIndexMethod+2,endIndexMethod));
      document.getElementById("HFS_to").value = textArr;
      setType("to",typeArr);
      }
   var delfiCheckbox = document.getElementById("ringSearchSwitch");
   if(delfiCheckbox != null)
     {
     if (methodDep == methodDELFIKeyValue && methodArr == methodDELFIKeyValue)
       {
       delfiCheckbox.checked = true;
        }
     else
        {
       delfiCheckbox.checked = false;
        }
     }
    }
  }
}

function resetStop(varSelect){
  document.getElementById("stops"+varSelect).selectedIndex = 0;

  if(document.getElementById("resa"))
    document.getElementById("resa").selectedIndex = 0;
}

function setType(varSelect,type) {
  var baseId = "HFS_locType_"+varSelect+"_";
  var i = 1;
  for(i = 1; i< 10; i++)
    {
    if((document.getElementById(baseId+i)) && (document.getElementById(baseId+i).value == type)){
      document.getElementById(baseId+i).checked = true;
      return;
      }
    }

}

function callQueryWithSelectedRelation(lObject)
{
window.location = urlTravelPlannerRelative + "SRID="+ lObject.options[lObject.selectedIndex].value;
}

function handleHelpClick_bak(id)
{
  if((typeof(currentDivId)!='undefined') && (currentDivId != null))
    {
    classNameAdd(eID(currentDivId),'hide');
    if(currentDivId=="helpCon_"+id)
      {
      delete currentDivId;
      return false;
      }
    }
  currentDivId="helpCon_"+id;
  classNameRemove(eID(currentDivId),'hide');
  eID(currentDivId).focus();
  return false;
}

function handleHelpClick(id)
{
  var dimmer = eID("helpDimmer");
  if(dimmer == null)
    {
    dimmer = document.createElement("div");
    dimmer.id = "helpDimmer";
    dimmer.className = "layerMapOverlay";
    document.body.appendChild(dimmer);
    }
  var helpBox = eID("HFShelpBox");
  if(helpBox == null)
    {
    helpBox = document.createElement("div");
    helpBox.id = "HFShelpBox";
    document.body.appendChild(helpBox);
    }
  helpBox.style.display = "block";
  currentDivId = "helpCon_"+id;
  helpBox.innerHTML = "";
  var helpBoxCloser = document.createElement("div");
  helpBoxCloser.innerHTML = "&nbsp;";
  helpBoxCloser.id = "helpBoxCloser";
  if(typeof(t_Close) == "string")
    helpBoxCloser.title = t_Close;
  helpBox.appendChild(helpBoxCloser);
  //helpBoxCloser.onclick = function(){eID('HFShelpBox').style.display='none';eID('dimmer').style.display='none';};
  window.setTimeout('listenToEvent(eID("helpBoxCloser"),"click",closeHelpBox);',200);
  window.setTimeout('listenToEvent(eID("helpDimmer"),"click",closeHelpBox);',200);
  helpBox.innerHTML += eID(currentDivId).innerHTML;
  var helpBoxCloseLink = document.createElement("a");
  if(typeof(t_Close) == "string")
    helpBoxCloseLink.innerHTML = t_Close;
  helpBoxCloseLink.href = "javascript:closeHelpBox()";
  helpBox.appendChild(helpBoxCloseLink);
  helpBoxCloseLink.focus();
  helpBoxCloseLink.style.visibility = "hidden";
  currentHelpTopic = id;
  dimmer.style.display = "block";
  dimmer.style.height = document.documentElement.clientHeight + 'px';
  classNameRemove(helpBox,'hide');
  // 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;
  helpBox.style.top = (Math.max(y, 150) + 50) + "px";
  return false;
}

function closeHelpBox(){
  eID('HFShelpBox').style.display='none';
  eID('helpDimmer').style.display='none';
  eID("help_"+currentHelpTopic).focus();
}

