/**
 * Replaces a DOM Element with another, but keeps the classes and IDs of the old one.
 * usage example:  jQuery('a#fooid').replaceWith('<span></span>');
 * before:         <a id="fooid" class="whatever">some text</a>
 * after:          <span id="fooid" class="whatever">some text</span>
 */
jQuery.fn.replaceWith = function(replacement) {
	return this.each (function() {
        var $this = jQuery(this);
        if (replacement === undefined) {
            $this.parent().append($this.html());
        }
        else {
            $this.after(replacement).next().html($this.html());
			for (var i = 0; i < this.attributes.length; i++) {
                $this.next().attr(this.attributes[i].nodeName, this.attributes[i].nodeValue);
			}
		}
        $this.remove();
    });
};

/**
 * Get the anchor from the uri
 */
jQuery.fn.extend({
	getAnchor: function(){
		if(window.location.href.indexOf("#") != -1){
			var url = window.location.href;
			var uanchor = window.location.href.split("#");
			if(uanchor[1]){
				return uanchor[1];
			}
		}
	}
});

/**
 * Init configuration for the calendartool
 */
function initBeraterToolCalendar() {
 var ms = jQuery('input#qf-months-texts').val();
 var ma = "";
 if (ms) {
     ma = ms.split(",");
 }

 var ws = jQuery('input#qf-weekday-texts-short').val();
 var wa = "";
 if (ws) {
     wa = ws.split(",");
 }

 var cs = jQuery('input#qf-cal-close-text').val();

 calman.config = {
     "today"           : new Date(),
     "viewPeriodS"     : parseUserDateInput("01.01.1900"),
     "viewPeriodE"     : parseUserDateInput("31.12.2099"),
     "dataPeriodS"     : parseUserDateInput("01.01.1900"),
     "dataPeriodE"     : parseUserDateInput("31.12.2099"),
     "monthsTexts"     : ma,
     "weekdaysTexts"   : wa,
     "closeText"       : cs,
     "showShortYear"   : false,
     "styleClass"      : "calendardiv",
     "useWeekdays"     : false
 }
}

/**
 * DB Bahn JavaScript
 * Copyright (c) 2008, namics (deutschland) gmbh. All rights reserved.
 * Code licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * */

/** verhindern von Konflikten mit dem '$' anderer JS-Bibliotheken wie z. B. Prototype */
jQuery.noConflict();

var BAHN = {
	key_tab: 9,
	key_return: 13,
	key_space: 32,
	key_backspace: 8,

	key_pageup: 33,
	key_pagedown: 34,

	key_left: 37,
	key_up: 38,
	key_right: 39,
	key_down: 40,

	key_minus: 86,
	key_plus: 93,
	key_add: 132,
	key_substract: 140,

	rowOpenerTimeout: 1000,

	// Initialize
	init: function() {
		// Handle fields with default values
		BAHN.initDefaults();
		BAHN.initHoverOverButton();
		// Language Selector
		BAHN.initLanguageSelection();
		// Handle row opening in FAQ
		BAHN.initRowOpener();
		// Handle Tab opening in Content
		BAHN.initTabElement();
		// Initialize the main navigation
		BAHN.initNav();
		// Initialize the autocomplete
		BAHN.initAutocomplete();
		// Font resizr
		BAHN.initFontResize();
		// Handle Toggling Elements
		BAHN.initClapContent();
		// Init Countryselector
		BAHN.initCountrySelect();
		// Tooltips
		BAHN.initTooltips();
		// Init Scramblecode
		BAHN.initScramblecode();
		// Set international location cookie
		BAHN.setIntLocationCookie();
		// Add pseudo hover to buttons
		BAHN.initIE6ButtonHover();
		// Add abbr element in IE 6-7
		document.createElement('abbr');
		// Remove alt-text as tool-tips in IE
		//jQuery( 'img' ).attr( 'title', '' );
		// Initialize the search lightbox
		if ( typeof search_tb_init !== 'undefined' ) {
			search_tb_init('#search');
		}
		BAHN.initModalLayer();
	},

	// init fields with default values
	initDefaults: function() {
		// Set event listeners to input elements with default text
		jQuery('input.hasDefault, textarea.hasDefault')
			.blur( BAHN.inputDefaults )
			.focus( BAHN.inputDefaults )
			.click( BAHN.inputDefaults );
		// Defaulttexte in Eingabefeldern anzeigen
		jQuery('input.hasDefault, textarea.hasDefault').blur();
		// Defaulttexte eines Forms durch Klick eines Submitbuttons (Button o. Input) mit dieser CSS-Klasse loeschen
		jQuery('button.deleteDefaults').click(BAHN.delInputDefaults);
		jQuery('input.deleteDefaults').click(BAHN.delInputDefaults);
		jQuery('textarea.deleteDefaults').click(BAHN.delInputDefaults);
	},

	// Handle row opening in FAQ
	initRowOpener: function() {
		// FAQ pages:
		var preventOnce = 0;

		//var thisElement = jQuery(this);
		//var jQuery(this).parent() = thisElement.parent();
		//var jQuery(this).parent().next() = thisElement.parent().next();

		BAHN.setFaqTabindex();

		// open all rows
		jQuery('#openAll').click(function(){
			BAHN.openRow();
		}).keydown(function(event){
			if(BAHN.isKeyOk(event) === true) {
				BAHN.openRow();
			}
		}).mouseover(function(){
			jQuery(this).toggleClass('active');
		}).mouseout(function(){
			jQuery(this).toggleClass('active');
		});


		// close all rows
		jQuery('#closeAll').click(function(){
			BAHN.closeRow();
		}).keydown(function(event){
			if(BAHN.isKeyOk(event) === true) {
				BAHN.closeRow();
			}
		}).mouseover(function(){
			jQuery(this).toggleClass('active');
		}).mouseout(function(){
			jQuery(this).toggleClass('active');
		});

		// toggle points
		// mod: to become more generic and to be able to use the opener class outside the threeColumnContainer
		//jQuery('h2.opener, h3.opener', 'div.threeColumnContainer').click(function() {
		jQuery('h2.opener, h3.opener').click(function() {
			jQuery( this ).stopTime( 'rowopener' );
			if (preventOnce == 1) {
				preventOnce = 0;
				jQuery(this).toggleClass('openerActive');
			}
			jQuery(this).next().toggle();
			jQuery(this).next().next().toggle();
			preventOnce = 1;
		}).keydown(function(event) {
			if(BAHN.isKeyOk(event) === true) {
				jQuery(this).next().toggle();
				jQuery(this).next().next().toggle();
				jQuery(this).toggleClass('openerActive');
			}
		}).mouseover(function() {
			if (preventOnce == 1) {
				preventOnce = 0;
			} else {
				jQuery(this).toggleClass('openerActive');
			}
			triggerElement = jQuery( this );
			jQuery( this ).oneTime(BAHN.rowOpenerTimeout, 'rowopener', function() { jQuery( this ).click(); });
		}).mouseout(function() {
			jQuery( this ).stopTime( 'rowopener' );
			if (preventOnce == 1) {
				preventOnce = 0;
			} else {
				jQuery(this).toggleClass('openerActive');
			}
		}).attr( BAHN.nTabindex(), '0' );

		if (jQuery('#content h2.opener').length > 0)  {
			var indexToOpen = parseInt(jQuery(document).getAnchor());
			if (indexToOpen > 0) {
				var elementToOpen = jQuery("h2.opener:eq(" + (indexToOpen-1) + ")");
				elementToOpen.toggleClass('openerActive');
				elementToOpen.next().toggle();
				elementToOpen.next().next().toggle();
			}
		}

		//Sitemap
		jQuery('h2.openSection, a.openSection, h3.openerSection').click(function() {
			BAHN.openSitemapSection(this);
		}).keydown(function(event){
			if(BAHN.isKeyOk(event) === true) {
				BAHN.openSitemapSection(this);
			}
		}).mouseover(function(event){
			//jQuery(this).toggleClass('openerActive');
		});

		jQuery('h2.closeSection, a.closeSection, h3.closeSection').click(function() {
			BAHN.closeSitemapSection(this);
		}).keydown(function(event){
			if(BAHN.isKeyOk(event) === true) {
				BAHN.closeSitemapSection(this);
			}
		});

		// toggle points in tables
		jQuery('td.opener').click(function() {
			jQuery(this).parent().next().children('td.opener-content').children('div.more').toggle();
			if (jQuery(this).parent().next().children('td.opener-content').children('div.more').length) {
				jQuery(this).parent().toggleClass('active');
				jQuery(this).parent().next().toggleClass('active');
			}
		}).keydown(function( event ){
			if(BAHN.isKeyOk(event) === true) {
				jQuery(this).parent().next().children('td.opener-content').children('div.more').toggle();
				if (jQuery(this).parent().next().children('td.opener-content').children('div.more').length) {
					jQuery(this).parent().toggleClass('active');
					jQuery(this).parent().next().toggleClass('active');
				}
			}
		}).mouseover(function() {
			jQuery(this).parent().toggleClass('hover');
		}).mouseout(function() {
			jQuery(this).parent().toggleClass('hover');
		}).attr( BAHN.nTabindex(), '0' );

		// A-Z Index
		jQuery( '#a-z-show-hide-button a' ).click( function( event ) {
			var sNewValue = jQuery( '#a-z-toggle-description' ).val();
			var sCurValue = jQuery( '#a-z-show-hide-button a span' ).text();
			//alert(sNewValue + '|' + sCurValue);
			jQuery( '#a-z-toggle-description' ).val(sCurValue);
			jQuery( '#a-z-show-hide-button a span' ).text(sNewValue);
			event.preventDefault();
			jQuery( 'div.a-z li li p' ).toggle();
		});

		BAHN.updateBuffer();
	},

	// Handle tab opening in tabelements
	initTabElement: function() {
		jQuery( 'ul.reiterlist' ).each( function () {
			jQuery(this).removeClass('hide');
		});
		jQuery( 'ul.reiterlist li.first' ).each( function () {
			jQuery(this).addClass('active');
		});
		jQuery( 'div.tabcontent' ).hide();
		//jQuery( 'ul.reiterlist' ).next().show();
		jQuery( 'div.t-content-1' ).show();
		jQuery( 'ul.reiterlist li a' ).each( function () {
			jQuery(this).click( BAHN.tabClick );
			jQuery(this).keydown( BAHN.tabClick );
		});

		// Update screenreader buffer
		BAHN.updateBuffer();
	},

	// Tab click in tabelement
	tabClick: 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 !== 'a' || ( sType === 'keydown' && bKeydown === false ) ) {
			return;
		} else {
			// Remove active class from all li-elements and hide tabcontent
			var oTargetTag = jQuery( oTarget );
			oTargetTag.parents( 'ul.reiterlist li' ).siblings().removeClass('active');
			oTargetTag.parents( 'ul.reiterlist' ).siblings( 'div.tabcontent' ).hide();
			// Add active class to li-element and show tabcontent
			oTargetTag.parents( 'ul.reiterlist li' ).addClass('active');
			var dTargetTag = oTargetTag.parents( 'div.tabelement ul.reiterlist' ).siblings( 'div.' + oTargetTag.attr('aria-controls') );
			dTargetTag.show();
			// Update screenreader buffer
			BAHN.updateBuffer();
			return false;
		}
	},

	isKeyOk: function (event) {
		var iKey = event.keyCode;
		if (iKey == BAHN.key_right || iKey == BAHN.key_down || iKey == BAHN.key_left || iKey == BAHN.key_up || iKey == BAHN.key_return || iKey == BAHN.key_space) {
			return true;
		}
		return false;
	},

	openSitemapSection: function( object ) {
		var oContainer = jQuery(object).parent().prev();
		oContainer.find("div.threeColumnRow").show();
		oContainer.find("div.liner").hide();
		oContainer.find("h2.opener").addClass('openerActive');
	},
	closeSitemapSection: function (object) {
		var oContainer = jQuery(object).parent().prev();
		oContainer.find("div.threeColumnRow").hide();
		oContainer.find("div.liner").show();
		oContainer.find("h2.opener").removeClass('openerActive');
	},
	openRow: function() {
		jQuery('div.threeColumnContainer div.threeColumnRow').show();
		jQuery('div.threeColumnContainer div.oneColumnContainerAnswer').show();
		jQuery('div.foldingBox.simple div.foldingBoxRow').show();
		jQuery('div.liner').hide();
		jQuery('h2.opener, h3.opener').addClass('openerActive');
	},
	closeRow: function() {
		jQuery('div.threeColumnContainer div.threeColumnRow').hide();
		jQuery('div.threeColumnContainer div.oneColumnContainerAnswer').hide();
		jQuery('div.foldingBox.simple div.foldingBoxRow').hide();
		jQuery('div.liner').show();
		jQuery('h2.opener, h3.opener').removeClass('openerActive');
	},

	initHoverOverButton: function() {
		jQuery('button.linkButton').mouseover( function() {
			jQuery('button.linkButton').toggleClass('linkButtonHover');
		});
		jQuery('button.linkButton').mouseout( function() {
			jQuery('button.linkButton').toggleClass('linkButtonHover');
		});
	},

	// return integer
	qfInteger: function( sId ) {
		return sId ? parseFloat( sId.replace(/[^\d]*/, '') ) : false;
	},

	// Toggle between input field defaults and selected input text
    // (für eSuite wird diese Variante der Funktion benötigt!)
	inputDefaults: function( event ) {
		// Get default value from hidden input element
		var sDefaultValue = jQuery( '#' + this.id + '-default' ).val();
		// If field is empty on blur, fill with default value
		if ( event.type === 'blur' && this.value === '' ) {
			jQuery( this ).val( sDefaultValue );
		}
		// field is clicked on, remove default value
		else if ( (event.type === 'click' || event.type === 'focus') && this.value === sDefaultValue ) {
			this.value = '';
			return false;
		}
	},

    // Inputfelder leeren
    delInputDefaults: function(event) {
        // geklickter Button
        oTarget = BAHN.getTarget(event);

        // var oForm = oTarget.form || oTarget;
        // Das reicht für Safari nicht bei unserem HTML-Konstrukt für Buttons mit Javascript (<button><span>buttontext</span></button>).
        // (Deswegen klappt auch allgemeinerer Safari-Fix in getTarget() nicht, da dann das <span> statt buttontext gefunden wird, 
        // aber zu <span>-Tags ist in JS das form-Attribut nicht gefüllt - nur bei Eingabeelementen).
        // Daher folgender Ansatz, um das Form-Tag zu finden, in dem der Buttonklick stattfand:
        var oForm = oTarget;
        // die Parents des Buttons hinaufsteigen bis zum 1. Form-Element
        while (oForm && oForm.tagName.toUpperCase() !== 'FORM') {
            oForm = oForm.parentNode;
        }
        
        // Klick in alle Felder mit Default-Texten des aktuellen Formulars,
        // wodurch (nur!) die Default-Texte geloescht werden
        jQuery('#' + oForm.id + ' :input.hasDefault').click();
    },

	/* Rollover Navigation
	 * Add events to 1st level a-tag */
	initNav: function() {
		var lastId = false;

		// Add events to the first level navigation
		jQuery( '#main-nav a.jhover' ).mouseover( function() {

			//var thisElement = jQuery(this);
		    //var jQuery(this).parent() = thisElement.parent();
		    var thisparentid = jQuery(this).parent().attr('id');

			jQuery(this).parent().addClass( 'rollover' );


			if ( lastId && lastId !== thisparentid ) {
				jQuery( '#' + lastId ).removeClass( 'rollover' );
			}
			lastId = thisparentid;
		}).focus( function() {
			jQuery( this ).parent().addClass( 'rollover' );
		}).blur( function() {
			if ( lastId ) {
				jQuery( '#' + lastId ).removeClass('rollover');
			}
			jQuery( this ).parent().removeClass( 'rollover' );
		});

		// Add events to layers in the left part of the main navigation
		jQuery( '#main-nav-left li h3, #main-nav-left li ul' ).mouseout( function() {
			if ( lastId ) {
				jQuery( '#' + lastId ).removeClass( 'rollover' );
			}
			jQuery( this ).parents( 'li' ).removeClass( 'rollover' );
		}).mouseover( function() {
			jQuery( this ).parents( 'li' ).addClass( 'rollover' );
		}).bgiframe(); // Fix z-index bug in IE6

		// Add events to login layer
		jQuery( '#main-nav-right li h3, #main-nav-right li ul' ).mouseover( function() {
			jQuery( this ).parent().addClass( 'rollover' );
		});
		// Add events to some div container to fix login layer
		jQuery('#key-visual, #header, #content').mouseover(function(){
			jQuery('#mn-login').removeClass('rollover');
		}).bgiframe(); // Fix z-index bug in IE6

		// Add keyboard events to new layer a-tags */
		jQuery( '#main-nav ul ul a' ).focus( function() {
			jQuery( this ).parent().parent().parent().addClass( 'rollover' );
			lastId = jQuery( this ).parents( 'li' ).attr( 'id' );
		}).blur( function() {
			if ( lastId ) {
				jQuery( '#' + lastId ).removeClass('rollover');
			}
			jQuery( this ).parent().parent().parent().removeClass( 'rollover' );
		});

		// Special events for login layer
		jQuery( '#main-nav li#mn-login a.jhover' ).mouseover( function() {
			jQuery( '#mn-login-username' ).focus();
		}).focus( function() {
			jQuery( '#mn-login-username' ).focus();
			jQuery(this).next().addClass( 'rollover' );
			jQuery(this).next().next().addClass( 'rollover' );
		});

		// Language Selector
		jQuery( '#language-selector-layer span' ).click( function( event ) {
			jQuery(this).parent().toggleClass('active');
		}).focus( function( event ) {
			jQuery(this).parent().toggleClass('active');
		}).keydown(function( event ){
			if(BAHN.isKeyOk(event) === true) {
				jQuery(this).parent().toggleClass('active');
			}
		}).attr( BAHN.nTabindex(), '0' );
		jQuery( '#language-selector-layer' ).mouseover( function() {
			jQuery(this).addClass('hover');
		}).mouseout( function() {
			jQuery(this).removeClass('hover');
		});

		// Site Actions
		jQuery( '#link-print' ).click( function( event ) {
			if ( window.print ) {
				window.print();
				return false;
			}
		});

		jQuery( '#link-close' ).click( function( event ) {
			if ( window.close ) {
				window.close();
				return false;
			}
		});
	},

	// init function for the input field in the header
	initAutocomplete: function() {
		if( jQuery( '#search-ac' ).length > 0 && jQuery( '#search-ac' ).val() == 1) {
			jQuery( '#search-query' ).autocomplete( null, {	multiple: true,
															multipleSeparator: ' ',
															customcacheUrl: '/q/l',
															customcacheSite: jQuery( '#search-site' ).val(),
															customcacheLang: jQuery( '#search-lang' ).val(),
															formatItem: function(row) { return row; }
												});

			if(jQuery.browser.safari || (jQuery.browser.msie && jQuery.browser.version < 7)) {
				jQuery( '#search-query' ).keydown( function( event ) {
					if(event.keyCode == BAHN.key_backspace && jQuery( '#search-query' ).val().length-1 > 0) {
						jQuery( '#search-query' ).search();
					}
				});
			}
		}
	},

	// init function for the input field in the ajax searchresult
	initContentSearch: function() {
		if( jQuery( '#search-ac' ).length > 0 && jQuery( '#search-ac' ).val() == 1) {
			jQuery( '#contentSearch-query' ).autocomplete( null, {	multiple: true,
																	multipleSeparator: ' ',
																	customcacheUrl: '/q/l',
																	customcacheSite: jQuery( '#contentSearch-site' ).val(),
																	customcacheLang: jQuery( '#contentSearch-lang' ).val(),
																	formatItem: function(row) { return row; }
														});

			if(jQuery.browser.safari || (jQuery.browser.msie && jQuery.browser.version < 7)) {
				jQuery( '#contentSearch-query' ).keydown( function( event ) {
					if(event.keyCode == BAHN.key_backspace && jQuery( '#contentSearch-query' ).val().length-1 > 0) {
						jQuery( '#contentSearch-query' ).search();
					}
				});
			}
		}
	},

	initIE6ButtonHover: function() {
		if ( jQuery.browser.msie && jQuery.browser.version < 7 ) {
			jQuery( 'button' ).mouseover( function() {
				jQuery(this).addClass('hover');
			}).mouseout( function() {
				jQuery(this).removeClass('hover');
			});
		}
	},

	initLanguageSelection: function() {
		if(jQuery( '#country-select' ).length > 0) {
			jQuery( '#country-select' ).selectbox();
		}else if(jQuery( '#language-select' ).length > 0) {
			jQuery( '#language-select' ).change( function() {
				location.href = jQuery( '#language-select' ).val();
			});
		}
	},

	// Font resize
	initFontResize: function() {
		jQuery( '#font-sizer' ).click( BAHN.fontResize );
		var fontSize = jQuery.cookie( 'bahn-font' );
		// Resize font if cookie is set and font size hasn't been set by the backend
		if ( fontSize !== '' ) {
			BAHN.fontResize( null, fontSize );
		}
	},
	fontResize: function( event, fontSize ) {
		// Set variables
		var oTarget = BAHN.getTarget( event ), fontsize = ( event ) ? jQuery( oTarget ).attr( 'class' ) : fontSize;

		// Generate servername
		var tld = window.location.hostname;
		if(tld != 'localhost') {
			tld = tld.split(".");
			tld.shift();
			tld = '.' + tld.join('.');
		}

		// Set font size
		jQuery( 'body' ).attr( 'class', fontsize );
		jQuery.cookie( 'bahn-font', fontsize, { expires: '', path: '/', domain: tld } );
		return false;
	},

	css: function( elm, prop ) {
		return parseInt( jQuery.css( elm[0], prop ), 10 ) || 0;
	},

	width: function( elm ) {
		return elm[0].offsetWidth + BAHN.css( elm, 'marginLeft' ) + BAHN.css( elm, 'marginRight' );
	},

	/****************************
	 * General helper functions *
	 ****************************/

	// Force screen reader buffer update
	updateBuffer: function() {
		jQuery( '#bufferUpdater' ).val( Math.random() );
	},

	// Return the event target element, not a text node
	getTarget: function( event, resolveTextNode ) {
		if (!event) {
			return false;
		}
		var t = event.target || event.srcElement;
        // defeat Safari text node bug (http://www.quirksmode.org/js/events_properties.html)
        // if (t.nodeType == 3) {t = t.parentNode};
		return t;
	},

	// Set the tabindex on all carousel links to -1, except for those of the active items
	setTabindex: function( aElms ) {
		jQuery( '#carousel a' ).attr( BAHN.nTabindex(), '-1' );
		jQuery('a', aElms).removeAttr( BAHN.nTabindex() );
	},

	// Normalize tabindex attribute
	nTabindex: function() {
		return jQuery.browser.msie ? 'tabIndex' : 'tabindex';
	},

	setFaqTabindex: function() {
		jQuery('h2.opener').attr(BAHN.nTabindex(), '0');
		jQuery('h2#openAll').attr(BAHN.nTabindex(), '0');
		jQuery('h2#closeAll').attr(BAHN.nTabindex(), '0');
	},

	// Sortierfunktion fuer Selectboxoptionen nach ihrem Anzeigetext
        optionTextSorter: function(o1, o2) {
                return o1.text !== o2.text ? (o1.text < o2.text ? -1 : 1 ) : 0;
	},

	/*******************************************************************/
	/***** Initialise Scramblecode *****/
	/*******************************************************************/

	// Initialize
	initScramblecode: function() {
		BAHN.initScramblecodeRCP();
		BAHN.initScramblecodeRCPSND();
        BAHN.initScramblecodeFM();
	},
	// Check recipient
	initScramblecodeRCP: function() {
		if (jQuery('form.validate-rcp input.rcp')) {
			jQuery('form.validate-rcp input.rcp').change(function() {
				var url = '/pbin/scramble.pl?m=a;X=R:' + encodeURI(jQuery('form.validate-rcp input.rcp').val());
				jQuery.getJSON(url,
					function(data){
						jQuery("form.validate-rcp img.scramble").attr({
							src: data.img,
							width: data.width,
							heigth: data.height
				        });
						jQuery('form.validate-rcp input.scramble').val(data.scramble);
						jQuery('form.validate-rcp div.jsscramble').removeClass('jsscramble');
				})
			});
		}
	},
	// Check recipient and sender
	initScramblecodeRCPSND: function() {
		if (jQuery('form.validate-rcp-snd input.rcp') && jQuery('form.validate-rcp-snd input.snd')) {
			jQuery('form.validate-rcp-snd input.rcp').change(function() {
				if(jQuery('form.validate-rcp-snd input.rcp').val().length == 0 || jQuery('form.validate-rcp-snd input.snd').val().length == 0) return;

				var url = '/pbin/scramble.pl?m=a;X=R:' + encodeURI(jQuery('form.validate-rcp-snd input.rcp').val()) +
						  ';X=S:' + encodeURI(jQuery('form.validate-rcp-snd input.snd').val());
				jQuery.getJSON(url,
					function(data){
						jQuery("form.validate-rcp-snd img.scramble").attr({
							src: data.img,
							width: data.width,
							heigth: data.height
				        });
						jQuery('form.validate-rcp-snd input.scramble').val(data.scramble);
						jQuery('form.validate-rcp-snd div.jsscramble').removeClass('jsscramble');
				})
			});
			jQuery('form.validate-rcp-snd input.snd').change(function() {
				if(jQuery('form.validate-rcp-snd input.rcp').val().length == 0 || jQuery('form.validate-rcp-snd input.snd').val().length == 0) return;

				var url = '/pbin/scramble.pl?m=a;X=R:' + encodeURI(jQuery('form.validate-rcp-snd input.rcp').val()) +
						  ';X=S:' + encodeURI(jQuery('form.validate-rcp-snd input.snd').val());
				jQuery.getJSON(url,
					function(data){
						jQuery("form.validate-rcp-snd img.scramble").attr({
							src: data.img,
							width: data.width,
							heigth: data.height
				        });
						jQuery('form.validate-rcp-snd input.scramble').val(data.scramble);
						jQuery('form.validate-rcp-snd div.jsscramble').removeClass('jsscramble');
				})
			});
		}
	},
	// Check for fields from Formmodule (FM)
	initScramblecodeFM: function() {
		var scramble_fields = [];
		jQuery('form .scramblethis').each(function() {
			scramble_fields[jQuery(this).attr('name')] = 1;
			jQuery(this).change(function() {
				var all_filled = 1;
				var uri_params = '';

				/* Spezialbehandlung Checkboxen und Radiobuttons:
				 *  - Pr?fen, ob min. 1 angehakt/ausgew?hlt ist
				 *  - Parameter an URI h?ngen
				 */
				var something_checked_for = [];
				jQuery('form input.scramblethis[type=checkbox], form input.scramblethis[type=radio]').each(function() {
					if (jQuery(this).is(':checked')) {
						something_checked_for[jQuery(this).attr('name')] = 1;
						uri_params += ';X=' + jQuery(this).attr('name') + ':' + encodeURI(jQuery(this).val());
					} else if (something_checked_for[jQuery(this).attr('name')] == undefined) {
						something_checked_for[jQuery(this).attr('name')] = 0;
					}
				});

				/* Spezialbehandlung fortsetzen:
				 *  - Pr?fen, ob von jedem Feld min. 1 angehakt/ausgew?hlt ist
				 *  - wenn nicht, all_filled auf 0 setzen
				 */
				for (var i in something_checked_for) {
					if (!something_checked_for[i]) {
						all_filled = 0;
					}
				}

				/* Spezialbehandlung Selects, Textareas und normale Inputs:
				 *  - Auf L?nge pr?fen
				 */
				jQuery('form select.scramblethis, form textarea.scramblethis, form input.scramblethis[type!=checkbox][type!=radio]').each(function() {
					if (jQuery(this).val().length == 0) {
						all_filled = 0;
					}
					uri_params += ';X=' + jQuery(this).attr('name') + ':' + encodeURI(jQuery(this).val());
				});
				
				if (!all_filled) {
					return;
				}

				var url = '/pbin/scramble.pl?m=a' + uri_params;
				jQuery.getJSON(url,
					function(data){
						jQuery("form img.scramble").attr({
							src: data.img,
							width: data.width,
							heigth: data.height
						});
						jQuery('form input.scramble').val(data.scramble);
						jQuery('form div.jsscramble').removeClass('jsscramble');
						jQuery('form fieldset.jsscramble_forms').removeClass('jsscramble_forms');
				})
			});
		});
	},
		/**
	 * Handle Toggling Elements
	 *
	 * Adds an Event to <h2> and <h3> with the specified className "clap"
	 * and opens/closes the next <div> Element with the className "clap-content"
	 * with mouseOver it adds the className "clap-active" to the <h2>/<h3> element.
	 *
	 * Second and third functionality is the open-all-clap-content and
	 * close-all-clap-content thing.
	 */
	initClapContent: function() {
		if ( jQuery('#inhalt h2.clap').length || jQuery('#inhalt h3.clap').length ) {
			var preventOnce = 0;
			jQuery('#inhalt h2.clap, #inhalt h3.clap').click(function() {
				if (preventOnce == 1) {
					preventOnce = 0;
					jQuery(this).toggleClass('clap-active');
				}
				if ( jQuery(this).children('div.clap-content').length ) jQuery(this).children('div.clap-content').toggle();
				else if ( jQuery(this).parent().next().children('div.clap-content').length ) jQuery(this).parent().next().children('div.clap-content').toggle();
				preventOnce = 1;
			}).keydown(function(event) {
				if(BAHN.isKeyOk(event) === true) {
					if ( jQuery(this).children('div.clap-content').length ) jQuery(this).children('div.clap-content').toggle();
					else if ( jQuery(this).parent().next().children('div.clap-content').length ) jQuery(this).parent().next().children('div.clap-content').toggle();
					jQuery(this).toggleClass('clap-active');
				}
			}).mouseover(function() {
				if (preventOnce == 1) {
					preventOnce = 0;
				} else {
					jQuery(this).toggleClass('clap-active');
				}
			}).mouseout(function() {
				if (preventOnce == 1) {
					preventOnce = 0;
				} else {
					jQuery(this).toggleClass('clap-active');
				}
			}).attr( BAHN.nTabindex(), '0' );
		}
		if ( jQuery('#inhalt #open-all-clap-content').length && jQuery('#inhalt div.clap-content').length &&
			 ( jQuery('#inhalt h2.clap').length || jQuery('#inhalt h3.clap').length) ) {
			jQuery('#open-all-clap-content').click(function() {
				if ( jQuery('#inhalt h2.clap').length ) jQuery('#inhalt h2.clap').addClass('clap-active');
				else if ( jQuery('#inhalt h3.clap') ) jQuery('#inhalt h3.clap').addClass('clap-active');
				jQuery('#inhalt div.clap-content').show();
			}).keydown(function(event){
				if(BAHN.isKeyOk(event) === true) {
					if ( jQuery('#inhalt h2.clap').length ) jQuery('#inhalt h2.clap').addClass('clap-active');
					else if ( jQuery('#inhalt h3.clap') ) jQuery('#inhalt h3.clap').addClass('clap-active');
					jQuery('#inhalt div.clap-content').show();
				}
			}).mouseover(function(){
				jQuery( this ).toggleClass('clap-active');
			}).mouseout(function(){
				jQuery( this ).toggleClass('clap-active');
			});
		}
		if ( jQuery('#inhalt #close-all-clap-content').length && jQuery('#inhalt div.clap-content').length &&
			 ( jQuery('#inhalt h2.clap').length || jQuery('#inhalt h3.clap').length) ) {
			jQuery('#close-all-clap-content').click(function() {
				if ( jQuery('#inhalt h2.clap').length ) jQuery('#inhalt h2.clap').removeClass('clap-active');
				else if ( jQuery('#inhalt h3.clap') ) jQuery('#inhalt h3.clap').removeClass('clap-active');
				jQuery('#inhalt div.clap-content').hide();
			}).keydown(function(event){
				if(BAHN.isKeyOk(event) === true) {
					if ( jQuery('#inhalt h2.clap').length ) jQuery('#inhalt h2.clap').removeClass('clap-active');
					else if ( jQuery('#inhalt h3.clap') ) jQuery('#inhalt h3.clap').removeClass('clap-active');
					jQuery('#inhalt div.clap-content').hide();
				}
			}).mouseover(function(){
				jQuery( this ).toggleClass('clap-active');
			}).mouseout(function(){
				jQuery( this ).toggleClass('clap-active');
			});
		}
	},


	/*******************************************************************/
	/***** Tooltip *****/
	/*******************************************************************/

	initTooltips: function() {
		jQuery('.showtt' ).each(
			function() {
				var el = jQuery(this);
				el.tooltip({
					track: true,
				    delay: 0,
				    fade: 250
				});
			}
		);
	},

	/*******************************************************************/
	/***** CountrySelect *****/
	/*******************************************************************/

	initCountrySelect: function() {
		//Array mit Kuerzeln der Laender, die mehrsprachig sind:
		var multipleLanguageCountries = [ "che", "bel", "deu" ];

		if(jQuery("#country-select-large")){

			jQuery("#country-map area").click(function(ev){
				var country = jQuery(this).attr("country");

				//wenn über ein Land das in multipleLanguageCountries definiert ist, wird die Sprachauswahl eingeblendet
				if ( jQuery.inArray(country, multipleLanguageCountries) != "-1" ) {
					ev.preventDefault();
					BAHN.showCountryLanguagesLayer(ev, country);
				}
			});

			jQuery("#country-map area").mouseover(function(ev){
				var country = jQuery(this).attr("country");

				//Andere eventuell eingeblendete Karten de-highlighten
				jQuery("div#country-select-large .map").hide();

				//Gehighlightete Länderkarte einblenden
				jQuery("#country_"+country).show();

				//Hover in der Länder UL für das entsprechende Land setzen
				jQuery("ul.countries span."+country).addClass("lihover");

				//Sonderfall bei Other countries
				if(country == 'oc') {
					jQuery("ul.countries span.usa").addClass("lihover");
				}
			});

			jQuery("#country-map area").mouseout(function(ev){
				var country = jQuery(this).attr("country");
				jQuery("#country_"+jQuery(this).attr("country")).hide();
				jQuery("ul.countries span."+country).removeClass("lihover");

				//Sonderfall bei Other countries
				if(country == 'oc') {
					jQuery("ul.countries span.usa").removeClass("lihover");
				}
			});

			/* Mouseover für Länderliste-UL */
			jQuery("ul.countries li span").mouseover(function(ev){
				var country = jQuery(this).attr("class");

				//Sonderfall bei USA
				if(country == 'usa') {
					country = 'oc';
				}

				jQuery("#country_"+country).show();
			});

			/* Mouseout für Länderliste-UL */
			jQuery("ul.countries li span").mouseout(function(ev){
				var country = jQuery(this).attr("class");

				//Sonderfall bei USA
				if(country == 'usa') {
					country = 'oc';
				}

				jQuery("#country_"+country).hide();
			});

			jQuery(".countries .bel").click(function(ev){
				ev.preventDefault();
				BAHN.showCountryLanguagesLayer(ev, "bel");
			});

			jQuery(".countries .che").click(function(ev){
				ev.preventDefault();
				BAHN.showCountryLanguagesLayer(ev, "che");
			});

			jQuery(".countries .deu").click(function(ev){
				ev.preventDefault();
				BAHN.showCountryLanguagesLayer(ev, "deu");
			});

			jQuery("div.close").click(function(){
				jQuery(".country-languages-layer, #country-select-large .map").hide();
				jQuery("ul.countries span.bel").removeClass("lihover");
				jQuery("ul.countries span.che").removeClass("lihover");
				jQuery("ul.countries span.deu").removeClass("lihover");
			});

			// Drecksbrowser
			if(jQuery.browser.msie && jQuery.browser.version < 7) {
				jQuery( '#country-map area' ).trigger( 'mouseout' );
			}
		}
	},

	showCountryLanguagesLayer: function (ev, country) {
		var e = (ev) ? ev : window.event;
		var mouseX = e.clientX+jQuery('html').scrollLeft()-jQuery("#country-select-large").offset()['left'];
		var mouseY = e.clientY+jQuery('html').scrollTop()-jQuery("#country-select-large").offset()['top'];
		var ttHeight = jQuery(".country-languages-layer").outerHeight()+10;
		var ttWidth = jQuery(".country-languages-layer").outerWidth();
		var mapHeight = jQuery("#country-select-large").outerHeight();
		var mapWidth = jQuery("#country-select-large").outerWidth()-2;
		var top = (mouseY-ttHeight > 0) ? mouseY-ttHeight : (mouseY+ttHeight>mapHeight) ? mapHeight-ttHeight+5 : mouseY-70;
		var left = (mouseX-ttWidth*0.75 < 0) ? 2 : (mouseX+ttWidth*0.25 > mapWidth) ? mapWidth-200 : mouseX;

		//erstmal "alle" (eventuell) vorhandenen Sprachauswahlen ausblenden
		jQuery(".country-languages-layer").hide();

		//Die Sprachauswahl einblenden
		jQuery("#country-languages-layer_"+country).css('top',top-20).css('left',left).show();

		//Während über die SPrachauswahl gehovert wird muss auch das Land fortwährend eingeblendet werden.
		jQuery("#country-languages-layer_"+country).mouseover(function(ev){
			jQuery("#country_"+country).show();
		});

		//den Unterstrich unter der Länder-ul einblenden
		jQuery("ul.countries span."+country).addClass("lihover");
	},


	/*******************************************************************/
	/***** Auslandsvertrieb Cookie *****/
	/*******************************************************************/

	setIntLocationCookie: function() {
		if ( jQuery( '#p-intredirect' ).length > 0 && jQuery( '#p-intredirect' ).val() == 1 ) {
			var domain = 'http://www.bahn.de';
			var noRedirectCultures = [ 'DEUT/de', 'MLT/ml' ];
			var culture = jQuery.cookie( 'bahn-intlocation' );
			
			if (culture.length > 0 && jQuery.inArray(culture, noRedirectCultures) == -1) {			
				window.location.replace(domain + '/i/view/' + culture + '/index.shtml');
			}
		}else if ( jQuery( '#p-intlocation' ).length > 0 ) {
			jQuery.cookie( 'bahn-intlocation', jQuery( '#p-intlocation' ).val(), { expires: '', path: '/' } );
		}
	} ,

	/**
	 * Layer für Details bei Prämienbestellung
	 */
	initPraemienlayer: function() {
		var inputLayerContentIdElement = jQuery("input#layer-content-id");
		var inputLayerPraemiendetailsUrl = jQuery("input#layer-praemiendetails-url");
		if ( inputLayerContentIdElement.length > 0 && inputLayerContentIdElement.val() == "praemienlayer-content" && inputLayerPraemiendetailsUrl.length > 0 ) {
			jQuery("div.cf-praemien a.praemie").click(function(ev) {
				ev.preventDefault();
				BAHN.modalLayer.loadJSONP(inputLayerPraemiendetailsUrl.val() + '?q=' + this.href);
			});
		}
	},

	/*******************************************************************/
	/***** Modaler Layer *****/
	/*******************************************************************/

	initModalLayer: function() {

		BAHN.modalLayer = new ModalLayer();
		BAHN.modalLayer.configure();

		// Spezifische ModalLayer-Einstellungen
		BAHN.initPraemienlayer();
	}
};

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

