/**
 * DB Bahn PORTAL JavaScript
 * Copyright (c) 2009, DB Vertrieb GmbH. All rights reserved.
 */

var PORTAL = {
	
	aCampaignImg: [], // new Array for Campaign Images

	bcbToolTipData: [], // new Array for BahnCard-Berater teaser tooltips
	
	init: function() {
		// Enable accordeon function in "Schnelleinstieg" on home page
		PORTAL.initHomeSchnelleinstieg();
		// Enable buttons to scroll through offers on start page
		PORTAL.carouselInit();
		// Marketingkanal als Cookie setzen
		PORTAL.initDbCmf();
		// FAQ in neuem Fenster oeffnen
		PORTAL.initFAQ();
		// POPUP in neuem Fenster oeffnen
		PORTAL.initPOPUP();
		// Clicktracker bei Omniture fuer Links
		PORTAL.initClickTracker();
		// Servicemenu Selector
		PORTAL.initServicemenu();
		// Toggle view - QF Stadtverkehr
		PORTAL.initQuickfinderStadtverkehr();
		// Tochtersite RegioSelect
		PORTAL.initRegioSelect();
		// Folding boxes
		PORTAL.initAccordionBox();
		// Stage menu
		PORTAL.initStageMenu();
		// Kundenberaterfinder
		PORTAL.initKundenberaterfinder();
		// Fahrgastrechte
		PORTAL.initFormFahrgastrechte();
		// Initialize Berater Tools Functions
		PORTAL.initBeraterToolsWidget();
		// Enable BahnCard-Berater tooltips
		PORTAL.initBcbToolTips();
		// Init BahnCard-Berater form submit
		PORTAL.initBcbFormSubmit();
		// Initialize the campaign tool on a start page and pre-load images after the rest of the page is ready
		jQuery( window ).load( PORTAL.initCampaignTool );
		
	},

	/*******************************************************************/
	/***** Cookie fuer Marktforschungen *****/
	/*******************************************************************/

	initDbCmf: function() {
		var regex = /dbkanal_(\d*)/;
		var matches = regex.exec(document.URL);
		
		if(matches != null) {
			var tld = window.location.hostname;
			if(tld != 'localhost') {
				tld = tld.split(".");
				tld.shift();
				tld = '.' + tld.join('.');
			}
			
			jQuery.cookie( 'bahn-cmf', matches[0], { expires: 1, path: '/', domain: tld } );
		}
	},

	/*******************************************************************/
	/***** Open new window if target="faq" *****/
	/*******************************************************************/

	initFAQ: function() {
		jQuery("a[target='faq']").click( function( event ) {
			if ( window.open ) {
				window.open(this.href, 'FAQ', 'menubar=no,status=no,location=no,resizeable=no,toolbar=no');
				return false;
			}
		});
	},

	/*******************************************************************/
	/***** Open new window if target="popup" *****/
	/*******************************************************************/

	initPOPUP: function() {
		jQuery("a[target='popup']").click( function( event ) {
			if ( window.open ) {
				window.open(this.href, 'popup', 'menubar=no,status=no,location=no,resizeable=no,toolbar=no');
				return false;
			}
		});
	},

	/*******************************************************************/
	/***** Clicktracker - SocialMedia Bookmarks and more *****/
	/*******************************************************************/

	initClickTracker: function() {
		jQuery(".clicktracker").click( function( event ) {
			// Set variables
			var oTarget = BAHN.getTarget( event );
			var pagename = jQuery( oTarget ).attr( 'id' );
			var s = s_gi( s_account );
			
			// get id from parent if event target has no id attribute
			if ( pagename.length == 0 ) {
				pagename = jQuery( oTarget ).parent().attr( 'id' );
			}
			
			// Track click
			s.tl(this, 'o', pagename);
		});
	},

	/************************************************************************/
	/***** Enable accordeon function in "Schnelleinstieg" on home page *****/
	/***********************************************************************/
	initHomeSchnelleinstieg: function() {
		jQuery( '#schnelleinstieg h3' ).each( function( i ) {
			jQuery(this).attr('aria-controls', 's-content-' + (i + 1) );
		}).attr( BAHN.nTabindex(), '0' ).removeClass('open');
		jQuery( '#schnelleinstieg h3.first' ).addClass('open');
		jQuery( '#schnelleinstieg' ).mouseover( function( event ) {
				PORTAL.accordeonHover( event );
				jQuery(this).oneTime(BAHN.rowOpenerTimeout, 'rowopener', function() { PORTAL.accordeonClick( event ) });
			})
			.focus( PORTAL.accordeonHover )
			.mouseout( function( event ) {
				PORTAL.accordeonHover( event );
				jQuery( this ).stopTime( 'rowopener' );
			})
			.blur( PORTAL.accordeonHover )
			.click( function( event ) {
				PORTAL.accordeonClick( event );
				jQuery( this ).stopTime( 'rowopener' );
			})
			.keydown( PORTAL.accordeonClick );
	},
	// Accordeon hover in "Schnelleinstieg" on home page
	accordeonHover: function( event ) {
		// Set variables
		var oTarget = BAHN.getTarget( event ), sType = event.type, nodeName = oTarget.nodeName.toLowerCase();
		// Return if event happened on an irrelevant element
		if ( nodeName !== 'h3' ) {
			return;
		} else {
			// Set jQuery target object
			oTarget = jQuery( oTarget );
			// Check event type and if div is open
			var bOverType = ( sType === 'mouseover' || sType === 'focus');
			var bDisplay = ( oTarget.next().css( 'display' ) === 'block' );
			if ((bOverType && bDisplay) || (!bOverType && !bDisplay)) {
				oTarget.removeClass('open'); // show closed icon
			} else {
				oTarget.addClass('open'); // show open icon
			}
		}
	},
	// Accordeon click in "Schnelleinstieg" on home page
	accordeonClick: function( event ) {
		// Set variables
		var oTarget = BAHN.getTarget( event ), sType = event.type, nodeName = oTarget.nodeName.toLowerCase(), bAltKey = event.altKey, iKey = event.keyCode, bKeydown = (!bAltKey && (iKey === BAHN.key_return || iKey === BAHN.key_down || iKey === BAHN.key_space));
		// Return if event happened on an irrelevant element or wrong key was pressed
		if ( nodeName !== 'h3' || ( sType === 'keydown' && bKeydown === false ) ) {
			return;
		} else {
			// Remove openess from all h3 and div children
			jQuery( 'h3', '#schnelleinstieg' ).removeClass('open');
			jQuery( 'div', '#schnelleinstieg' ).hide();
			jQuery( 'div.foldingBoxRow', this ).hide();
			// Add open class to h3 and show div
			jQuery( oTarget ).addClass('open').next().show();
			// Update screenreader buffer
			BAHN.updateBuffer();
			return false;
		}
	},

	/* Carousel function based on jCarouselLite 1.0.1
	 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
	 * Dual licensed under the MIT and GPL licenses:
	 * http://www.opensource.org/licenses/mit-license.php
	 * http://www.gnu.org/licenses/gpl.html */
	carouselInit: function() {
		var o = jQuery( '#carousel' ), iKey;
		if ( o.length > 0 ) {
			( function($) {
				jQuery.fn.jCarouselLite = function( o ) {
					o = jQuery.extend( {
						btnPrev: jQuery('#carousel-prev'), btnNext: jQuery('#carousel-next'), btnGo: null, mouseWheel: false, auto: null,
						speed: 300, easing: null,
						vertical: false, circular: true, visible: 2, start: 0, scroll: 2,
						beforeStart: null, afterEnd: null, autorotate: true
					}, o || {} );
					return this.each ( function() {
						var running = false, animCss = 'left', sizeCss = 'width';
						var div = jQuery( '#carousel-wrapper' ), ul = jQuery( '#carousel' ), tLi = ul.children( 'li' ), tl = tLi.size(), v = o.visible;

						// Allow circular carousel
						ul.prepend( tLi.slice( tl - v - 1 + 1 ).clone() ).append( tLi.slice( 0, v ).clone() );
						o.start += v;

						var li = ul.children( 'li' ), itemLength = li.size(), curr = o.start;
						div.css('visibility', 'visible');
						BAHN.setTabindex( vis() );

						var liSize = BAHN.width( li );
						var ulSize = liSize * itemLength + 16;
						ul.css( sizeCss, ulSize + 'px' ).css( animCss, -(curr * liSize) );

						if ( o.btnPrev ) {
							jQuery( o.btnPrev ).removeAttr( 'aria-disabled' ).attr( BAHN.nTabindex(), 0 ).click( function() {
								// Stop autorotate
								window.clearInterval(autorotateInterval);
								autorotateStatus = false;
								jQuery( '#carousel-pause' ).attr('title', 'Fortfahren');
								return go( curr - o.scroll );
							}).keydown( function( event ) {
								if (!event.altKey) {
									if ((iKey = event.keyCode) && (iKey == BAHN.key_return || iKey == BAHN.key_left || iKey == BAHN.key_up)) {
										return go(curr - o.scroll);
									} else if ( iKey == BAHN.key_right || iKey == BAHN.key_down ) {
										return go(curr + o.scroll);
									} else {
										return;
									}
								}
							});
						}
						if ( o.btnNext ) {
							jQuery( o.btnNext ).removeAttr( 'aria-disabled' ).attr( BAHN.nTabindex(), 0 ).click( function() {
								// Stop autorotate
								window.clearInterval(autorotateInterval);
								autorotateStatus = false;
								jQuery( '#carousel-pause' ).attr('title', 'Fortfahren');
								return go( curr + o.scroll );
							}).keydown( function( event ) {
								if (!event.altKey) {
									if ((iKey = event.keyCode) && (iKey == BAHN.key_return || iKey == BAHN.key_right || iKey == BAHN.key_down)) {
										return go(curr + o.scroll);
									} else if ( iKey == BAHN.key_left || iKey == BAHN.key_up ) {
										return go(curr - o.scroll);
									} else {
										return;
									}
								}
							});
						}
						if ( jQuery('#carousel-pause') ) {
							jQuery( '#carousel-pause' ).removeAttr( 'aria-disabled' ).attr( BAHN.nTabindex(), 0 ).click( function() {
								if( autorotateStatus ) {
								// Stop autorotate
								window.clearInterval(autorotateInterval);
									autorotateStatus = false;
									jQuery( '#carousel-pause' ).attr('title', 'Fortfahren');
								}else{
									go( curr + o.scroll );
									autorotateInterval = window.setInterval(function() {
																				go( curr + o.scroll );
																			}, autorotateTime);
									autorotateStatus = true;
									jQuery( '#carousel-pause' ).attr('title', 'Anhalten');
								}
							});
						}

						function vis() {
							return li.slice( curr ).slice( 0, v );
						}

						function go( to ) {
							if (!running) {
								if (to <= o.start - v - 1) { // If first, then goto last
									ul.css(animCss, -((itemLength - (v * 2)) * liSize) + 'px');
									// If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
									curr = (to == o.start - v - 1) ? itemLength - (v * 2) - 1 : itemLength - (v * 2) - o.scroll;
								} else if (to >= itemLength - v + 1) { // If last, then goto first
									ul.css(animCss, -((v) * liSize) + "px");
									// If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
									curr = (to == itemLength - v + 1) ? v + 1 : v + o.scroll;
								} else {
									curr = to;
								}

								running = true;

								ul.animate(
									{ left: -(curr * liSize) }, o.speed, o.easing,
									function() {
										BAHN.setTabindex( vis() );
										BAHN.updateBuffer();
										running = false;
									}
								);
							}
							return false;
						}

						// Autorotate
						var autorotateInterval;
						var autorotateStatus = false;
						var autorotateTime = 9000;
						if( o.autorotate ) {
							autorotateInterval = window.setInterval(function() {
																		go( curr + o.scroll );
																	}, autorotateTime);
							autorotateStatus = true;
						}
					});
				};
			}) ( jQuery );
			o.jCarouselLite();
		}
	},

	/*******************************************************************/
	/***** Servicemenu *****/
	/*******************************************************************/

	// Initialize all Functions for the Servicemnu
	initServicemenu: function() {
		// Draw select-box
		PORTAL.initServiceSelect();
	},
	// Draws the select-box on init
	initServiceSelect: function() {
		jQuery('#frmservicemenu').append('<select id="0data_servicegroup_basis" onchange="PORTAL.setServicemenu(this.value)">');
		jQuery('#0data_servicegroup_basis').append('<option value="0">Alle Services</option>');
		jQuery('#0data_servicegroup_basis').append('<option value="3">Vielfahrer und Pendler</option>');
		jQuery('#0data_servicegroup_basis').append('<option value="1">Gesch&auml;ftlich unterwegs</option>');
		jQuery('#0data_servicegroup_basis').append('<option value="4">Reisen mit Kindern</option>');
		jQuery('#0data_servicegroup_basis').append('<option value="8">Senioren</option>');
		jQuery('#0data_servicegroup_basis').append('<option value="6">Barrierefreies Reisen</option>');
		//jQuery('#0data_servicegroup_basis').append('<option value="2">Privat (alleine)</option>');
		//jQuery('#0data_servicegroup_basis').append('<option value="5">In einer Gruppe</option>');
		//jQuery('#0data_servicegroup_basis').append('<option value="7">International</option>');
		jQuery('#frmservicemenu').append('</select>');
	},
	setServicemenu: function(val) {
		if (val == '0')	{
			jQuery('.threeColumnRow').find('li').removeClass('inactive');
		}
		else {
			jQuery('.threeColumnRow').find('li').each(function (el) {
				rel = this.getAttribute('rel');
				bit = rel.substr(val-1,1);
				if (bit == '1') {
					this.className='';
				}
				else {
					this.className='inactive';
				}
			});
		}
	},

	/*******************************************************************/
	/***** Initialize the campaign tool on the start page *****/
	/*******************************************************************/

	initCampaignTool: function() {
		var obj = document.getElementById( 'kampagnen' );
		var oKeyvisual = document.getElementById( 'key-visual-content' );
		// Run only when the campaign tool is present
		if ( obj ) {
			// Get values from hidden input fields
			jQuery( 'input.cvalue', '#kampagnen-defaults' ).each( function(i) {
				var aValues = jQuery( this ).val().split('::');
				// Pre-load images in cache
				PORTAL.aCampaignImg[i] = new Image;
				PORTAL.aCampaignImg[i].src = aValues[0];
				PORTAL.aCampaignImg[i].alt = aValues[1];
				PORTAL.aCampaignImg[i].longdesc = aValues[2];
			});
			// Add event listeners
			jQuery( obj ).mouseover( PORTAL.campaignHover ).mouseout( PORTAL.campaignOut ).bind( 'focusin', PORTAL.campaignHover ).bind( 'focusout', PORTAL.campaignOut );
			if (obj.addEventListener) {
				obj.addEventListener('focus', PORTAL.campaignHover, true);
				obj.addEventListener('blur', PORTAL.campaignOut, true);
			}
			if (obj.attachEvent) {
				obj.attachEvent('focus', PORTAL.campaignHover);
				obj.attachEvent('blur', PORTAL.campaignOut);
			};
		}
	},
	
	// Mouseover for campaign tool
	campaignHover: function( event ) {
		// Set variables
		var oDOMTarget = BAHN.getTarget( event ), nodeName = oDOMTarget.nodeName.toLowerCase(), oTarget = jQuery( oDOMTarget ), sId = oTarget.attr( 'id' );
		if ( nodeName === 'a' ) {
			PORTAL.campaignReplaceImage( sId );
		}
	},

	campaignOut: function( event ) {
		// Set variables
		var oDOMTarget = BAHN.getTarget( event ), nodeName = oDOMTarget.nodeName.toLowerCase(), oTarget = jQuery( oDOMTarget ), sId = oTarget.attr( 'id' ), iTarget = BAHN.qfInteger( sId );
		if ( nodeName === 'a' ) {
			PORTAL.campaignMarkLink( oTarget );
		}
	},

	campaignReplaceImage: function( id ) {
		var iTarget = BAHN.qfInteger( id ), oImg = PORTAL.aCampaignImg[iTarget - 1];
			// Do something only if image is available
			if ( oImg ) {
				jQuery( '#key-visual-content' ).attr( 'href', oImg.longdesc ); // Change URI
				jQuery( '#key-visual img' ).attr( 'alt', oImg.alt ); // Change alt-text
				// Append new image
				var oReplacement = document.createElement( 'img' );
				oReplacement.src = oImg.src;
				oReplacement.id = 'key-visual-replacement';
				document.getElementById( 'key-visual' ).appendChild( oReplacement );
				// Swap images
				jQuery( '#key-visual-content img' ).fadeOut('fast', function() {
					jQuery( '#key-visual-content img' ).show().attr( 'src', oImg.src ).css( 'opacity', '1' ); // Show swapped image
					jQuery( '#key-visual-replacement' ).remove(); // Remove temporary image
				});
			}
	},

	campaignMarkLink: function( target ) {
		target.parent().attr( 'class', 'active' ); // Mark active
		jQuery( '#kampagnen a' ).not( jQuery( target ) ).parent().removeAttr( 'class' ); // Mark inactive
			BAHN.updateBuffer(); // Update screen reader buffer
	},

	/*******************************************************************/
	/***** Quickfinder Stadtverkehr *****/
	/*******************************************************************/

	initQuickfinderStadtverkehr: function() {
		jQuery( '#quickfinder-stadtverkehr ul.tablist a' ).click( function(ev) {
			ev.preventDefault();
			jQuery( '#quickfinder-stadtverkehr div.wrapper' ).toggleClass( 'with-linklist' );
			jQuery( '#qf-stadtverkehr-content' ).toggle();
		} );
	},
	
	/*******************************************************************/
	/***** Tochtersites Regioselect *****/
	/*******************************************************************/

	initRegioSelect: function() {
		if(jQuery("#regioselect")){

			jQuery("#regiomap area").mouseover(function(ev){
				var e = (ev) ? ev : window.event;
				var mouseX = e.clientX+jQuery('html').scrollLeft()-jQuery("#regioselect").offset()['left'];
				var mouseY = e.clientY+jQuery('html').scrollTop()-jQuery("#regioselect").offset()['top'];

				var curId = jQuery(this).attr("rel");
				var ttHeight = jQuery("#"+curId+"-tt").outerHeight()+10;
				var ttWidth = jQuery("#"+curId+"-tt").outerWidth();
				var mapHeight = jQuery("#regioselect").outerHeight();
				var mapWidth = jQuery("#regioselect").outerWidth()-2;

				var top = (mouseY-ttHeight > 0) ? mouseY-ttHeight : (mouseY+ttHeight>mapHeight) ? mapHeight-ttHeight+5 : mouseY+10;
				var left = (mouseX-ttWidth*0.75 < 0) ? 2 : (mouseX+ttWidth*0.25 > mapWidth) ? mapWidth-200 : mouseX-ttWidth*0.75;

				jQuery("#"+curId).show();
				jQuery("#"+curId+"-tt").css('top',top).css('left',left).show();
			});

			jQuery("#regiomap area").mouseout(function(){
				var curId = jQuery(this).attr("rel");
				jQuery("#"+curId+", #"+curId+"-tt").hide();
			});
		}
	},

	// Enable accordion function in folding boxes on 'Tochtersites'
	initAccordionBox: function() {
		jQuery( '.foldingBox.accordeon h3' )
			/*.each( function( i ) {
				jQuery(this).attr('aria-controls', 's-content-' + (i + 1) );
			})*/
			.attr( BAHN.nTabindex(), '0' ).removeClass('open');
		jQuery( '.foldingBox.accordion h3.first' ).addClass('open');
		jQuery( '.foldingBox.accordion' ).mouseover( PORTAL.accordeonHover )
			.focus( PORTAL.accordeonHover )
			.mouseout( PORTAL.accordeonHover )
			.blur( PORTAL.accordeonHover )
			.click( PORTAL.accordeonClick )
			.keydown( PORTAL.accordeonClick );
	},
	
	/*******************************************************************/
	/***** Formular Fahrgastrechte *****/
	/*******************************************************************/

	initFormFahrgastrechte: function() {
		if(jQuery( '#cf-fahrgastrechte' )) {
			jQuery( '#cf-fahrgastrechte-ausfallversp' ).change( function() {
				var selectedValue = jQuery(this).val();

				if( selectedValue.length === 0) {
					jQuery( '#cf-fahrgastrechte-zugausfall' ).hide();
					jQuery( '#cf-fahrgastrechte-anschlussverpasst' ).hide();
				}

				if( selectedValue === 'verspaetet' ) {
					jQuery( '#cf-fahrgastrechte-zugausfall' ).hide();
					jQuery( '#cf-fahrgastrechte-anschlussverpasst' ).show();
				}

				if( selectedValue === 'ausgefallen' ) {
					jQuery( '#cf-fahrgastrechte-zugausfall' ).show();
					jQuery( '#cf-fahrgastrechte-anschlussverpasst' ).hide();
				}
			}).change();

			jQuery( '#cf-fahrgastrechte-entschaedigung' ).change( function() {
				var selectedValue = jQuery(this).val();

				if( selectedValue.length === 0 || selectedValue === 'gutscheinvk25' || selectedValue === 'auszahlungvk26') {
					jQuery( '#cf-fahrgastrechte-persdata' ).hide();
					jQuery( '#cf-fahrgastrechte-bankverbindung' ).hide();
				}

				if( selectedValue === 'gutscheinpost27' ) {
					jQuery( '#cf-fahrgastrechte-persdata' ).show();
					jQuery( '#cf-fahrgastrechte-bankverbindung' ).hide();
				}

				if( selectedValue === 'ueberwsg28' ) {
					jQuery( '#cf-fahrgastrechte-persdata' ).show();
					jQuery( '#cf-fahrgastrechte-bankverbindung' ).show();
				}
			}).change();
		}
	},
	
	/*******************************************************************/
	/***** Tablist *****/
	/*******************************************************************/

	// Initialize all Functions for the Widget
	initBeraterToolsWidget: function() {
		// Activate tab navigation
		PORTAL.initTabs();
		// Init Datepickers
		PORTAL.initBeraterToolDatepickers();
		// Filter Regions by Country selection
		PORTAL.initFilterRegionByCountry();
		// Filter Hinflug/Rueckflug
		PORTAL.initFilterFlugTyp();
		// Formular Submit
		PORTAL.initBeraterFormSubmit();
		// Calendar navigation pervious / next
		jQuery( '#content-shadow span.calendar-nav a, #berater-widget span.calendar-nav a' ).click( PORTAL.tabSetDate );
		// set first radio as checked on first load
		//if ( jQuery( '#berater-widget ul.tablist li input.radio' ).length > 0 ) {
		//	jQuery( '#berater-widget ul.tablist li input.radio:first' ).attr('checked', 'checked')
		//}
		// Tarifberater
		PORTAL.initTarifberater();
	},

	initTabs: function() {
		var aTablist = jQuery( '#berater-widget ul.tablist' ), i = 0;
		jQuery( '#berater-widget ul.tablist li' ).attr( BAHN.nTabindex(), '-1' );
		jQuery( '#berater-widget ul.tablist li.active' ).attr( BAHN.nTabindex(), '0' );
		// disable a links in tablist
		jQuery( '#berater-widget ul.tablist a' ).attr('rel','link').removeAttr('href').click(function () { jQuery(this).parent('li').focus(); return false; });

		// make radio clickable an focus the tab element (does not work with IE)
		jQuery( '#berater-widget ul.tablist input:radio' ).click(function () { jQuery(this).parent('li').focus(); return true; });

		// remove the A and NOBR element to fix the "clickability" problems in the internet explorer browser
		jQuery('#berater-widget ul.tablist a').replaceWith();
		jQuery('#berater-widget ul.tablist nobr').replaceWith();

		// make the input.radio element and the a-element clickable
		jQuery('#berater-widget ul.tablist input.radio, #berater-widget ul.tablist a').click(function(){
			jQuery(this).parent().bind('click', PORTAL.onTabClick).click();
		});
		while ( aTablist[i] ) {
			if ( aTablist[i].addEventListener ) {
				aTablist[i].addEventListener('click', PORTAL.onTabClick, true);
				aTablist[i].addEventListener('focus', PORTAL.onTabClick, true);
				aTablist[i].addEventListener('keydown', PORTAL.onTabKeydown, false);
				aTablist[i].addEventListener('keypress', PORTAL.onTabKeypress, false);
			}
			else if ( aTablist[i].attachEvent ) {
				jQuery( '#berater-widget ul.tablist' ).bind('click', PORTAL.onTabClick).keydown( PORTAL.onTabKeydown ).keypress( PORTAL.onTabKeypress );
			}
			i++;
		}
	},
	onTabClick: function( e ) {
		if ( typeof e.type !== 'undefined' ) var event = e || window.event;
		var oTarget = ( typeof event !== 'undefined' ) ? BAHN.getTarget( event ) : e;
		// Find the active sibling
		var oActive = jQuery( oTarget ).siblings( 'li.active' );
		// If the clicked tab wasn't the active tab, proceed
		if (oActive.length > 0) {
			// Adjust class name, change tabindex on former active element
			oActive.removeClass('active').attr(BAHN.nTabindex(), '-1');
			// Hide corresponding tabpanel
			var iActivePanelId = oActive.attr('id').replace(/(tab-)([0-9])/, "tabpanel-$2");
			jQuery('#' + iActivePanelId).removeClass('active');

			// Add class name, change tabindex on new active element
			jQuery(oTarget).addClass('active').attr(BAHN.nTabindex(), '0').focus();
			// Show corresponding tabpanel
			iActivePanelId = jQuery(oTarget).attr('id').replace(/(tab-)([0-9])/, "tabpanel-$2");
			jQuery('#' + iActivePanelId).addClass('active');

			// check to select the radio button
			jQuery(oTarget).children('input.radio').addClass('checked').attr('checked','checked');
			//BAHN.checkRadioButton( jQuery(oTarget) );

			// Update screenreader buffer
			BAHN.updateBuffer();
		}
	},
	// alle Kalender initialisieren
	initBeraterToolDatepickers: function() {
		// Einstellungen fuer alle Kalender
		initBeraterToolCalendar();
		jQuery( '#content-shadow span.date-picker a, #berater-widget span.date-picker a' ).each(
				function(i){
					var inputId = jQuery(this).attr('aria-controls');
					var inputName = jQuery('#' + inputId).attr('name');
					var calId, refId;
					var add_to_id = 0;
					do {
						calId = i+8+add_to_id;
						refId = 'callink' + calId;
						add_to_id++;
					} while (calman.calcons[refId] !== undefined || jQuery('#'+refId).length);

					jQuery(this).attr('id', refId);

					qfInitCalendar(calId.toString(), inputId, inputName);
					jQuery(this).click(function(){return calman.toggleDisplay(refId);});
				}
		);
    } ,
	// Set previous or next day on calendar input field
	tabSetDate: function( event ) {
		var oTarget = BAHN.getTarget( event ), dNewDate;
		oTarget = ( oTarget.nodeName.toLowerCase() == 'img' ) ? jQuery( oTarget ).parent() : jQuery( oTarget );
		var sId = oTarget.attr( 'aria-controls' );
		var oControls = jQuery( '#' + sId );

		var aCurDate = new Array();
		var aNewDate = new Array();

		aCurDate[sId] = PORTAL.tabGetDate( oControls );
		aNewDate[sId] = aCurDate[sId] = ( oTarget.attr( 'class' ).indexOf( 'next' ) != -1 ) ? new Date( aCurDate[sId].getTime() - 24 * 3600 * 1000 ) : new Date( aCurDate[sId].getTime() + 24 * 3600 * 1000 );

		// Concat date string
		var sD = aNewDate[sId].getDate(),
			sDay = ( sD < 10 ) ? ( '0' + sD ) : sD,
			sM = aNewDate[sId].getMonth() + 1,
			sMonth = ( sM < 10 ) ? ( '0' + sM ) : sM;
		// Output date string in input field
		oControls.val( sDay + '.' + sMonth + '.' + aNewDate[sId].getFullYear() );
		return false;
	},
	tabGetDate: function( obj ) {
		var aDate = obj.val().split('.');
		var dCurDate = new Date();
		dCurDate.setYear(aDate[2]);
		dCurDate.setMonth(aDate[1]-1);
		dCurDate.setDate(aDate[0]);
		return dCurDate;
	},
	onTabKeydown: function( e ) {
		var event = e || window.event, k = new PORTAL.KeyObject( event );
		var iNum = k.oTarget.id.match(/[tab-]([0-9]*)/), iNum = iNum[1];
		// Previous tab
		if ( ( ( k.iKey === BAHN.key_left || k.iKey === BAHN.key_up ) && !k.bAltKey && !k.bShiftKey && !k.bCtrlKey )
			|| ( k.iKey === BAHN.key_tab && k.bCtrlKey && k.bShiftKey ) ) {
			if ( jQuery( k.oTarget ).is( ':first-child' ) ) {
				PORTAL.onTabClick( jQuery( k.oTarget ).siblings(':last') );
			}
			else {
				PORTAL.onTabClick( jQuery( k.oTarget ).prev() );
			}
			PORTAL.stopPropagation( event );
		}
		// Next tab
		else if ( ( ( k.iKey === BAHN.key_right || k.iKey === BAHN.key_down ) && !k.bAltKey && !k.bShiftKey && !k.bCtrlKey )
			|| ( k.iKey === BAHN.key_tab && k.bCtrlKey && !k.bShiftKey ) ) {
			if ( jQuery( k.oTarget ).is( ':last-child' ) ) {
				PORTAL.onTabClick( jQuery( k.oTarget ).siblings(':first') );
			}
			else {
				PORTAL.onTabClick( jQuery( k.oTarget ).next() );
			}
			PORTAL.stopPropagation( event );
		}
	},
	onTabKeypress: function( e ) {
		var event = e || window.event, k = new PORTAL.KeyObject( event );
		if ( ( ( k.iKey === BAHN.key_left || k.iKey === BAHN.key_up || k.iKey === BAHN.key_right || k.iKey === BAHN.key_down ) && !k.bAltKey && !k.bShiftKey && !k.bCtrlKey ) || ( k.iKey === BAHN.key_tab && k.bCtrlKey ) ) {
			PORTAL.stopPropagation( event );
		}
	},
	stopPropagation: function ( event ) {
		// Prevent scrolling
		if (event.stopPropagation) event.stopPropagation();
		if (event.preventDefault) event.preventDefault();
		event.cancelBubble = true;
		event.returnValue = false;
	    return false;
	},
	KeyObject: function( event ) {
		var obj = {
			iKey: event.keyCode,
			bCtrlKey: event.ctrlKey,
			bAltKey: event.altKey,
			bShiftKey: event.shiftKey,
			oTarget: BAHN.getTarget( event )
		}
		return obj;
	},
	checkRadioButton: function( obj ) {
		var checkedRadio = obj + ' > input.radio';
		//if (jQuery(obj).hasClass('active') ) alert('active: '+jQuery(obj));
		//if (jQuery(obj).children('.radio')) alert('radio: '+jQuery(obj));

		if (jQuery(obj).hasClass('active') && jQuery(obj).children('.radio')) {
			jQuery(checkedRadio).attr('checked','checked');
			//alert(jQuery(checkedRadio));
			//for (a in jQuery(checkedRadio)) alert(a);
		}
		//if (jQuery(obj).attr('rel')=='link') {
		//	jQuery(obj).click(function () {
		//		alert('ein toter link');
		//		jQuery(this).prev(':radio').attr("checked", "checked");
		//	});
		//}
	},

	// Select Box Land kommuniziert mit Region
	initFilterRegionByCountry: function() {
		if (jQuery('#berater-widget select.land').length) {
			var original_options = '';
			jQuery('#berater-widget select.land').change(function () {
				var selected_value = this.value;
				var selected_split = selected_value.split('_');
				// die ID der abhaengigen Select Box wird mit dem rel-Attribut uebergeben
				var select_option_filter = '#' + jQuery(this).attr('rel');
				// einen moeglichen Filter wieder zuruecksetzen
				if (selected_value == '' && original_options != '') {
					jQuery(select_option_filter).html(original_options);
				}
				// Filtern, wenn 2stelliger Laendercode gefunden wurde
				else if (selected_split.length > 2) {
					// Auswahl Land ermitteln
					var countries = new Array();
					var j = 0;
					for (var i = 0; i < selected_split.length; ++i) {
						// nach 2stelligen Laendercodes suchen
						if (selected_split[i].length == 2 && selected_split[i] === selected_split[i].toUpperCase()) {
							countries[j++] = '_' + selected_split[i] + '_';
						}
					}
					// Filter Region
					if (jQuery(select_option_filter).length) {
						if (original_options != '') jQuery(select_option_filter).html(original_options);
						var options = jQuery(select_option_filter).children('option');
						var new_options = '';
						var all_options = '';
						var j = 0;
						// alle Option Eintraege durchsuchen
						for (var i = 0; i < options.length; ++i) {
							//new_options[j++] = options[i].value + '--' + options[i];
							all_options += '<option value="' + options[i].value + '">' + options[i].innerHTML + '</option>';
							// nach allen moeglichen Regionen suchen
							for (var x = 0; x < countries.length; ++x) {
								var showme = options[i].value.indexOf(countries[x]);
								if (showme > 0) new_options += '<option value="' + options[i].value + '">' + options[i].innerHTML + '</option>';
							}
						}
						jQuery(select_option_filter).html('<option value="">beliebig</option>' + new_options);
						if (original_options == '') original_options = all_options;
					}
				}
			});
		}
	},
	// Hinflug / Rueckflug Filter
	initFilterFlugTyp: function() {
		if (jQuery('#berater-widget select.onewayswitch').length) {
			jQuery('#berater-widget select.onewayswitch').change(function () {
				// bei "nur Hinflug" wird das Rueckdatum ausgeblendet
				if (this.value==1) {
					// die ID der abhaengigen Select Box wird mit dem rel-Attribut uebergeben
					jQuery('#' + jQuery(this).attr('rel')).hide();
				} else {
					jQuery('#' + jQuery(this).attr('rel')).show();
				}
			});
		}
	},
	// Formular Submit
	initBeraterFormSubmit: function() {
		// Grauer Hintergrund beim Stoebern
		if (jQuery('#berater-widget form input[name=MEWurl]').length) {
			jQuery('#berater-widget form input[name=MEWurl]').click(function () {
				jQuery(this).parent().parent().children('label').removeClass('checked');
				jQuery(this).parent().addClass('checked');
				jQuery('#wid-trip-type-form').submit();
			});
		}
		// Klick auf den Link Erweiterte Suche
		if (jQuery('#berater-widget input.link').length) {
			jQuery('#berater-widget input.link').click(function () {
				// ohne Parameter Start
				if (jQuery('#berater-widget input[name=start]').length) {
					jQuery('#berater-widget input[name=start]').val('');
				}
			});
		}
		// Fomular Submit
		if (jQuery('#berater-widget .tabpanel form').length) {
			jQuery('#berater-widget .tabpanel form').submit(function () {
				// Parameter fdyfr, fmofr, fdyto und fmoto fuellen
				var f_fr = jQuery('[name=f-fr]',this).val();
				var f_to = jQuery('[name=f-to]',this).val();
				if (f_fr && f_fr.length) {
					jQuery('[name=fdyfr]',this).val(f_fr.substr(0,2));
					jQuery('[name=fmofr]',this).val(f_fr.substr(6,4) + f_fr.substr(3,2));
				}
				if (f_to && f_to.length) {
					jQuery('[name=fdyto]',this).val(f_to.substr(0,2));
					jQuery('[name=fmoto]',this).val(f_to.substr(6,4) + f_to.substr(3,2));
				}
				// Parameter startDateDay, startDateMonth, startDateYear, endDateDay, endDateMonth und endDateYear fuellen
				var start_date = jQuery('[name=startDate1]',this).val();
				var end_date = jQuery('[name=endDate1]',this).val();
				if (start_date && start_date.length) {
					jQuery('[name=startDateDay]',this).val(start_date.substr(0,2));
					jQuery('[name=startDateMonth]',this).val(start_date.substr(3,2));
					jQuery('[name=startDateYear]',this).val(start_date.substr(6,4));
					jQuery('[name=startDate]',this).val(start_date.substr(6,4) + '-' + start_date.substr(3,2) + '-' + start_date.substr(0,2));
				}
				if (end_date && end_date.length) {
					jQuery('[name=endDateDay]',this).val(end_date.substr(0,2));
					jQuery('[name=endDateMonth]',this).val(end_date.substr(3,2));
					jQuery('[name=endDateYear]',this).val(end_date.substr(6,4));
					jQuery('[name=endDate]',this).val(start_date.substr(6,4) + '-' + end_date.substr(3,2) + '-' + end_date.substr(0,2));
				}
				// Parameter day, month_1, RetDay und month_2 fuellen
				var start_date2 = jQuery('[name=startDate2]',this).val();
				var end_date2 = jQuery('[name=endDate2]',this).val();
				if (start_date2 && start_date2.length) {
					if (start_date2.substr(0, 1) === '0') jQuery('[name=Day]', this).val('0' + start_date2.substr(1, 1));
					else jQuery('[name=Day]', this).val(start_date2.substr(0, 2));
					// --- add "day" fuer neue ibe
					if (start_date2.substr(0, 1) === '0') jQuery('[name=day]', this).val('0' + start_date2.substr(1, 1));
					else jQuery('[name=day]', this).val(start_date2.substr(0, 2));
					// --- end add "day"
					if (start_date2.substr(3,1)==='0') jQuery('[name=month_1]',this).val('0' + start_date2.substr(4,1) + '-' + start_date2.substr(6,4));
					else jQuery('[name=month_1]',this).val(start_date2.substr(3,2) + '-' + start_date2.substr(6,4));
				}
				if (end_date2 && end_date2.length) {
					if (end_date2.substr(0,1)==='0') jQuery('[name=RetDay]',this).val('0' + end_date2.substr(1,1));
					else jQuery('[name=RetDay]',this).val(end_date2.substr(0,2));
					// --- add "retDay" fuer neue ibe
					if (end_date2.substr(0,1)==='0') jQuery('[name=retDay]',this).val('0' + end_date2.substr(1,1));
					else jQuery('[name=retDay]',this).val(end_date2.substr(0,2));
					// --- end add "retDay"
					if (end_date2.substr(3,1)==='0') jQuery('[name=month_2]',this).val('0' + end_date2.substr(4,1) + '-' + end_date2.substr(6,4));
					else jQuery('[name=month_2]',this).val(end_date2.substr(3,2) + '-' + end_date2.substr(6,4));
				}
				jQuery('input[type=text]', this).each(function() {
				    if (jQuery(this).attr('placeholder').length && jQuery(this).attr('placeholder') == jQuery(this).val()) {
				        jQuery(this).val('');
				    }
				});
			});
		}
	},
	
	/*******************************************************************/
	/***** BahnCard Berater *****/
	/***** DEPRECATED  *****/
	/*******************************************************************/

	// Enable BahnCard-Berater tooltips
	initBcbToolTips: function() {
		PORTAL.addBcbToolTip(251);
		PORTAL.addBcbToolTip(252);
		PORTAL.addBcbToolTip(501);
		PORTAL.addBcbToolTip(502);
	},
	addBcbToolTip: function(id) {
		if(jQuery('#bcbLinkBc'+id) && jQuery('#bcbTipBc'+id)) {
			PORTAL.bcbToolTipData[id] = [];
			PORTAL.bcbToolTipData[id]['linkHover'] = false;
			PORTAL.bcbToolTipData[id]['tipHover'] = false;
			jQuery('#bcbLinkBc'+id).mouseover(function() {
				PORTAL.bcbToolTipData[id]['linkHover'] = true;
				PORTAL.bcbToolTipData[id]['tipHover'] = false;
				jQuery('#bcbTipBc'+id).show();
				window.clearTimeout(BAHN.bcbToolTipData[id]['timeout']);
			}).focus(function() {
				PORTAL.bcbToolTipData[id]['linkHover'] = true;
				PORTAL.bcbToolTipData[id]['tipHover'] = false;
				jQuery('#bcbTipBc'+id).show();
				window.clearTimeout(BAHN.bcbToolTipData[id]['timeout']);
			}).mouseout(function() {
				PORTAL.bcbToolTipData[id]['linkHover'] = false;
				PORTAL.bcbToolTipData[id]['timeout'] = window.setTimeout("BAHN.removeBcbToolTip"+id+"()", 10);
			}).blur(function() {
				//BAHN.bcbToolTipData[id]['linkHover'] = false;
				//BAHN.bcbToolTipData[id]['timeout'] = window.setTimeout("BAHN.removeBcbToolTip"+id+"()", 10);
			});
			jQuery('#bcbTipBc'+id).mouseover(function() {
				PORTAL.bcbToolTipData[id]['tipHover'] = true;
				PORTAL.bcbToolTipData[id]['linkHover'] = false;
				jQuery('#bcbTipBc'+id).show();
				window.clearTimeout(BAHN.bcbToolTipData[id]['timeout']);
			}).mouseout(function() {
				PORTAL.bcbToolTipData[id]['tipHover'] = false;
				PORTAL.bcbToolTipData[id]['timeout'] = window.setTimeout("BAHN.removeBcbToolTip"+id+"()", 10);
			});
			jQuery('#bcbTipBc'+id+' a.link-highlight').focus(function() {
				PORTAL.bcbToolTipData[id]['tipHover'] = true;
				PORTAL.bcbToolTipData[id]['linkHover'] = false;
				jQuery('#bcbTipBc'+id).show();
				window.clearTimeout(BAHN.bcbToolTipData[id]['timeout']);
			}).blur(function() {
				PORTAL.bcbToolTipData[id]['tipHover'] = false;
				PORTAL.bcbToolTipData[id]['timeout'] = window.setTimeout("BAHN.removeBcbToolTip"+id+"()", 10);
			});
			jQuery('#bcbTipBc'+id+' > a.closeButton').click(function() {
				PORTAL.bcbToolTipData[id]['linkHover'] = false;
				PORTAL.bcbToolTipData[id]['tipHover'] = false;
				jQuery('#bcbTipBc'+id).hide();
			});
		}
	},
	removeBcbToolTip251: function() {
		if(PORTAL.bcbToolTipData[251]['linkHover'] == false && PORTAL.bcbToolTipData[251]['tipHover'] == false) {
			jQuery('#bcbTipBc251').hide();
		}
	},
	removeBcbToolTip501: function() {
		if(PORTAL.bcbToolTipData[501]['linkHover'] == false && PORTAL.bcbToolTipData[501]['tipHover'] == false) {
			jQuery('#bcbTipBc501').hide();
		}
	},
	removeBcbToolTip252: function() {
		if(PORTAL.bcbToolTipData[252]['linkHover'] == false && PORTAL.bcbToolTipData[252]['tipHover'] == false) {
			jQuery('#bcbTipBc252').hide();
		}
	},
	removeBcbToolTip502: function() {
		if(PORTAL.bcbToolTipData[502]['linkHover'] == false && PORTAL.bcbToolTipData[502]['tipHover'] == false) {
			jQuery('#bcbTipBc502').hide();
		}
	},
	// Init BahnCard-Berater form submit
	initBcbFormSubmit: function() {
		if (jQuery('#bcbForm')) {
			jQuery('#bcbForm button[type=reset]').click(function () {
				jQuery('div.bcbResult').hide();
				jQuery('#bcbStart').show();
			});

			jQuery('#bcbForm button[type=submit]').click(function () {
				if(!(jQuery('input[@name=travelBehaviour]:checked').length)) {
					jQuery('#bcbForm div.questionContainer p.bcbError:eq(0)').show().fadeOut(2000);
					return false;
				}

				if(!(jQuery('input[@name=travelDistance]:checked').length)) {
					jQuery('#bcbForm div.questionContainer p.bcbError:eq(1)').show().fadeOut(2000);
					return false;
				}

				if(!(jQuery('input[@name=travelFrequence]:checked').length)) {
					jQuery('#bcbForm div.questionContainer p.bcbError:eq(2)').show().fadeOut(2000);
					return false;
				}

				if(!(jQuery('input[@name=travelPreferences]:checked').length)) {
					jQuery('#bcbForm div.questionContainer p.bcbError:eq(3)').show().fadeOut(2000);
					return false;
				}

				var a = [];
				var id = '';
				a[0] = jQuery('input[@name=travelBehaviour]:checked').val()
				a[1] = jQuery('input[@name=travelDistance]:checked').val()
				a[2] = jQuery('input[@name=travelFrequence]:checked').val()
				a[3] = jQuery('input[@name=travelPreferences]:checked').val()

				if(a[0] == 'spontaneous' && a[1] == 'supraRegional'  && a[2] == 'often') {
					id = 'bcb50';
				}else if(a[1] == 'supraRegional'  && a[2] == 'veryOften') {
					id = 'bcb50';
				}else{
					id = 'bcb25';
				}

				if(a[3] == 'comfort') {
					id += '1';
				}else{
					id += '2';
				}

				jQuery('div.bcbResult').hide();
				jQuery('#bcbStart').hide();
				jQuery('#' + id).show();
				return false;
			});
		}
	},

	initTarifberater: function() {
		// Tarifberater
		var tarifvergleich_button = jQuery( '#inhalt #tarifvergleich button' );
		var tarifvergleich_checkboxes = jQuery( '#inhalt #tarifvergleich input.checkbox' );
		var tarifvergleich_error = jQuery( '#inhalt #tarifvergleich p.error-msg, #tarifvergleich-ergebnis p.error-msg' )
		if( tarifvergleich_button.length > 0 ) {
			tarifvergleich_button.click(function() {
				var tarifvergleich_checked = jQuery( '#inhalt #tarifvergleich input:checked' );

				if( tarifvergleich_checked.length > 1 ) {
					tarifvergleich_error.hide();

					jQuery('#tarifvergleich-ergebnis table').show();
					jQuery('#tarifvergleich-ergebnis thead th').hide();
					jQuery('#tarifvergleich-ergebnis tbody td').hide();
					jQuery('#tarifvergleich-ergebnis tfoot td').hide();

					tarifvergleich_checked.each(function() {
						var checkbox_value = jQuery(this).val();
						jQuery('#tarifvergleich-ergebnis thead th[id=' + checkbox_value + ']').show();
						jQuery('#tarifvergleich-ergebnis tbody td[headers=' + checkbox_value + ']').show();
						jQuery('#tarifvergleich-ergebnis tfoot td[headers=' + checkbox_value + ']').show();
					});
				}
				else {
					tarifvergleich_error.show();
					jQuery('#tarifvergleich-ergebnis table').hide();
				}
			});
		};
		if( tarifvergleich_checkboxes.length > 0 ) {
			tarifvergleich_checkboxes.change(function() {
				var tarifvergleich_checked = jQuery( '#inhalt #tarifvergleich input:checked' );
				if (tarifvergleich_checked.length > 1) {
					tarifvergleich_error.hide();
					tarifvergleich_button.removeClass('no-thickbox');
				}
				else {
					tarifvergleich_button.addClass('no-thickbox');
				}
			});
		};
	},
	
	
	/*******************************************************************/
	/***** Urlaubsseite - Stagemodul *****/
	/*******************************************************************/
	
	initStageMenu: function() {
		if (jQuery("#stage_menu li").length) {
			jQuery("#stage_menu li").click(function () {
				if (jQuery(this).attr("class").indexOf("moreCities") == -1) {
					jQuery("#stage_menu li").removeClass("active");
					jQuery(this).addClass("active");
					jQuery(".stage_content").hide();
					jQuery(".stage_content").eq(jQuery("#stage_menu li").index(this)).show();
				} else {
					jQuery("#stage_menu li.toggle").toggle(0);
				}
			});
		}
	},
	
	/*******************************************************************/
	/***** Urlaubsseite - Stagemodul *****/
	/*******************************************************************/
	
	initKundenberaterfinder: function() {
		if (jQuery('#kundenberater_form').length) {

			// Submit handler für Formular
			var form = jQuery('#kundenberater_form');
			form.submit(function(ev) {
				ev.preventDefault();

				// PLZ zum Server senden und Name zurück erwarten
				jQuery.post(form.attr('action'), { plz: jQuery('#plz').val() }, PORTAL.showKundenberater);

/*
				//Magic: get id from Perl script
				var id = jQuery('.kundenberater:eq(' + ( ( jQuery('#plz').val() || 0 ) -1 ) + ')').attr('id');
				BAHN.showKundenberater(id);
*/
			});

/*
			var match_result = location.href.match(/(?:&?)?name=(.+?)(&.+)?$/);
			if (match_result) {
				BAHN.showKundenberater(match_result[1]);
			}
*/
		}
	},

	showKundenberater: function(id) {
		jQuery('.kundenberater').hide();
		jQuery('#' + id).show();
	}
};

jQuery(document).ready(function() {
	PORTAL.init();
});

