if (typeof(op) != 'undefined') {
	if (typeof(op.rail) == 'undefined') { op.rail = {}; }
	
	op.rail.use = false;
	op.rail.async = true;
	
	/*
	 * RAIL SECTION
	 */
	op.rail.init = function(form){
		// The selection identifier for the surrounding form of the rail section
		op.rail.contextSel = '#formbox #' + form.contentid;
		
		// Global switch for enable and dable rail functionality
		op.rail.use = true;
		
		op.rail.includeBahnName = 'includeBahn';
		op.rail.includeBahnSel = '[name="' + op.rail.includeBahnName + '"]';
		
		// The selection identifier for the rail section container
		op.rail.containerSel = (op.rail.contextSel + ' #bahnContainer');
		
		// The selection identifier for the inner container of the rail section
		op.rail.innerContainerSel = (op.rail.containerSel + ' #bahnInnerContainer');
		
		// The selection identifier for the checkbox to show/hide rail section
		op.rail.showBahnSel = (op.rail.containerSel + ' #showBahn');
		var showBahn = $(op.rail.showBahnSel);
		showBahn.is(':checked') ? '' : $(op.rail.innerContainerSel).addClass('dn');
		
		// The selection identifiers for adult, children and infants subsections of the rail section
		op.rail.adultsSubsectionsSel = (op.rail.containerSel + ' .subsectionBahn.adult');
		op.rail.childrenSubsectionsSel = (op.rail.containerSel + ' .subsectionBahn.child');
		op.rail.infantsSubsectionsSel = (op.rail.containerSel + ' .subsectionBahn.infant');
				
		// The selection identifier for adults, children and infants
		op.rail.adultsSel = (op.rail.contextSel + ' .part-reisende [name="numberOfAdults"]');
		op.rail.childrenSel = (op.rail.contextSel + ' .part-reisende [name="numberOfChildren"]');
		op.rail.infantsSel = (op.rail.contextSel + ' .part-reisende [name="numberOfInfants"]');
				
		//
		$.each([op.rail.adultsSel, op.rail.childrenSel, op.rail.infantsSel], function(index, value){
			$(value).change(function(event){
				op.rail.update();
			});
		});
		
		op.rail.departureTrainStationName = 'departureTrainStation';
		op.rail.arrivalTrainStationName = 'arrivalTrainStation';
		
		op.rail.departureTrainStationSel = (op.rail.contextSel + ' [name="' + op.rail.departureTrainStationName + '"]');
		op.rail.arrivalTrainStationSel = (op.rail.contextSel + ' [name="' + op.rail.arrivalTrainStationName + '"]');
		
		$(op.rail.departureTrainStationSel + ',' + op.rail.arrivalTrainStationSel).change(function(){
			var self = $(this);
			$(op.rail.contextSel + ' [name="' + self.attr('name') + 'Text"]').val(self.find('option:selected').text());
		});
		
		//
		op.rail.isValidDepartureAirportCode = false;
		op.rail.isValidArrivalAirportCode = false;
		
		op.rail.departureCodeName = 'departureAirportCode';
		op.rail.arrivalCodeName = 'arrivalAirportCode';
		
		$(op.rail.contextSel + ' [name="' + op.rail.departureCodeName + '"],' 
			+ op.rail.contextSel + ' [name="' + op.rail.arrivalCodeName + '"]').change(function(event){
			op.rail.validateDestination(this);
		});
		
		
		op.rail.departureName = 'departureAirport';
		op.rail.arrivalName = 'arrivalAirport';
		
		$(op.rail.contextSel + ' [name="' + op.rail.departureName + '"],' 
			+ op.rail.contextSel + ' [name="' + op.rail.arrivalName + '"]').keyup(function(event){
				
			//~ alert('Code: ' + event.keyCode);
			var self = $(this);
			var val = self.val().toUpperCase();
			if(val.length == 3){
				$(op.rail.contextSel + ' [name="' + self.attr('name') + 'Code"]').val(val).change();
			}
		});
		
		// The selection identifier for the 'to'-datpicker
		op.rail.dpToSel = (op.rail.contextSel + ' #' + form.dpToId);
		
		$(op.rail.contextSel + ' #' + form.dpTriggerToId).change(function(event){
			op.rail.update();
		});
		
		// The current amount of traveler, adults, children and infants
		// chosen by the customer
		op.rail.traveler = 0;
		op.rail.adults = 0;
		op.rail.children = 0;
		op.rail.infants = 0;
		
		// The maximum traveler allowed for rail
		op.rail.maxTraveler = 5;
		
		// The maximum Date in the future for rail in days
		op.rail.maxDateInFuture = new Date().setDate(92);
		
		$(op.rail.showBahnSel).click(function(){
			$(op.rail.innerContainerSel).toggleClass('dn');
			$(op.rail.includeBahnSel).val((($(this).is(':checked')) ? 'true' : '' )); 
			$(op.rail.includeBahnSel).val((($(this).is(':checked')) ? $('#flights_flexible').attr('disabled', 'disabled')  : 	$('#flights_flexible').removeAttr('disabled') )); 
		});
		
		var bahnInput = $('<input name="' + op.rail.includeBahnName + '" type="hidden" value=""/>');
		$(op.rail.contextSel).prepend(bahnInput);
		
		// Travelers section initialize
		op.rail.travelersInit();
		
		op.rail.bahnCardOptions = $(op.rail.containerSel + ' .bahnCard').first().html();
		
		// Class change
		$(op.rail.containerSel + ' [name="bahnClass"]').change(
			function(){
				var railClassSelected = $(this).find('option:selected');
				var text = railClassSelected.text();
				var val = railClassSelected.val();
				$(op.rail.containerSel + ' .bahnCard').each(
					function(index, element){
						var card = $(element);
						var selectedText = card.find('option:selected').text();
						var options = $(op.rail.bahnCardOptions);
						card.empty().append($(options));
						if(val != ''){
							card.find('option').remove(':not(:contains(' + text + '))');
							card.prepend(options.first());
						}
						card.find(':contains(' + selectedText + ')').attr('selected',true);
					}
				);
			}
		);
		
		// Bahncard change
		$(op.rail.containerSel + ' .bahnCard').change(
			function(){
				var card = $(this);
				var val = card.val();
				if(val != ''){
					var type = (val.indexOf(25) != -1) ? 25 : 50;
				}
				$(op.rail.containerSel + ' .bahnCard').each(
					function(index, element){
						var card = $(element);
						var selectedText = card.find('option:selected').text();
						var options = $(op.rail.bahnCardOptions);
						card.empty().append($(options));
						var classObj = $(op.rail.containerSel + ' [name="bahnClass"]').find('option:selected');
						var classText = classObj.text();
						var classValue = classObj.val();
						// classValue != '' ? card.find('option').remove(':not(:contains(' + text + '))') : '';
						if(val != ''){
							classValue != '' ? classObj.change() : '';
							card.find('option').remove(':not(:contains(' + type + '))');
							card.prepend(options.first());
						}
						card.find(':contains(' + selectedText + ')').attr('selected',true);
					}
				);
			}
		);
	}
	
	op.rail.travelersInit = function(){
		var ageSel = ' .bahnAge';
		
		$(op.rail.adultsSubsectionsSel + ' .bahnAge,'
			+ op.rail.childrenSubsectionsSel + ' .bahnAge').each(
				function(index, element){
					var tmp = $(element);
					tmp.find('option:last').attr('selected',true);
				}
			);
		
		op.rail.addTravelerText($(op.rail.adultsSubsectionsSel + ':first' + ageSel));
		op.rail.addTravelerText($(op.rail.infantsSubsectionsSel + ageSel));
	}
	
	op.rail.addTravelerText = function(elem){
		elem.each(function(index, element){
			var tmp = $(element);
			var travelerAge = $('<p class="left bahnTravelerAge"></p>');
			var text = tmp.find(' option:last').text();
			travelerAge.text(text);
			tmp.hide();
			tmp.after(travelerAge);
		});
	}

	op.rail.update = function(){
		var railContainer = $(op.rail.containerSel);
		if(op.rail.requirementsFulfilled()){
			if(typeof(s) != 'undefined') {
				s.events = 'event37';
			}
			$('#flights_flexible').attr('disabled', 'disabled');
			$(op.rail.includeBahnSel).val('true');
			railContainer.removeClass('dn');
			
			if($(op.rail.showBahnSel).is(':checked')){
				$(op.rail.innerContainerSel).removeClass('dn');
				var adultsSections = $(op.rail.adultsSubsectionsSel);
				adultsSections.removeClass('dn').addClass('dn');
				var childrenSections = $(op.rail.childrenSubsectionsSel);
				childrenSections.removeClass('dn').addClass('dn');
				var infantsSections = $(op.rail.infantsSubsectionsSel);
				infantsSections.removeClass('dn').addClass('dn');
				for(var i = 0; i < op.rail.adults; i++){
					var section = $(adultsSections[i]);
					section.removeClass('dn');
				}
				for(var i = 0; i < op.rail.children; i++){
					var section = $(childrenSections[i]);
					section.removeClass('dn');
				}
				for(var i = 0; i < op.rail.infants; i++){
					var section = $(infantsSections[i]);
					section.removeClass('dn');
				}
			}
		} else {
			if(typeof(s) != 'undefined') {
				s.events = 'event38';
			}
			railContainer.addClass('dn');
			$('[name="' + op.rail.includeBahnName + '"]').val('');
			$('#flights_flexible').removeAttr('disabled');			
		}
	}

	op.rail.updateTraveler = function(){
		op.rail.adults = parseInt($(op.rail.adultsSel).val());
		op.rail.children = parseInt($(op.rail.childrenSel).val());
		op.rail.infants = parseInt($(op.rail.infantsSel).val());
		op.rail.traveler = (op.rail.adults + op.rail.children + op.rail.infants);
	}

	op.rail.requirementsFulfilled = function(){
		// op.rail.use must be true for including rail
		var bool = op.rail.use;
		// departureAirportCode and arrivalAirportCode must be in the list of rail destinations
		var toDate = $(op.rail.dpToSel).datepicker('getDate');
		op.rail.updateTraveler();
		if(bool){
			bool = (op.rail.isValidDepartureAirportCode 
				&& op.rail.isValidArrivalAirportCode
				&& (op.rail.traveler <= op.rail.maxTraveler)
				&& op.rail.isValidDate(toDate))
				? true : false;
		}
		return bool;
	}

	op.rail.validateDestination = function(obj){
		var self = $(obj);
		var code = self.val().toUpperCase();
		var bool = (code != '' && code != 'undefined') ? true : false;
		var name = self.attr('name');
		if(bool){
			var type = '';
			var ajaxOptions = {
				url: op.paths.railStation,
				dataType: 'text/html; charset=ISO-8859-1',
				async: op.rail.async
			};
			switch(name){
				case op.rail.departureCodeName:
					type = 'departure';
					ajaxOptions.success = function(data){
						op.rail.isValidDepartureAirportCode = 
							op.rail.processResult(op.rail.departureTrainStationName, data);
						op.rail.update();
					}
					break;
				case op.rail.arrivalCodeName:
					type = 'arrival';
					ajaxOptions.success = function(data){
						op.rail.isValidArrivalAirportCode = 
							op.rail.processResult(op.rail.arrivalTrainStationName, data);
						op.rail.update();
					}
					break;
			}
			ajaxOptions.data = {locationCode: code, outInType: type};
			$.ajax(ajaxOptions);
		} else {
			switch(name){
				case op.rail.departureCodeName:
					op.rail.isValidDepartureAirportCode = bool;
					break;
				case op.rail.arrivalCodeName:
					op.rail.isValidArrivalAirportCode = bool;
					break;
			}
			op.rail.update();
		}
	}
	
	op.rail.processResult = function(selString, data){
		var dataObj = $(data);
		var options = dataObj.find('option:not([value="-1"])');

		var elem = $(op.rail.contextSel).find('[name="' + selString + '"]');
		elem.html($(options));
		var sel = elem.find('option[selected]');
		sel.attr('selected',true).change();
		elem.after($('<input type="hidden" name="' + selString + 'Text" value="' + sel.text() + '" />'));
		return (options.length > 0) ? true : false;
	}

	op.rail.isValidDate = function(date){
		var tmpDate = (((op.rail.maxDateInFuture - Date.parse(date)) >= 0) ? true : false);
		return tmpDate;
	}
}
