// define global functions
// TODO move functions to an (annonymous) object, in order to prevent cluttering of the global namespace

function createCookie(name,value,days,domain) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";

	if (domain) {
		path = "; path="+domain;
	} else {
		path = '';
	}
	document.cookie = name+"="+value+expires+path;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function decode64(input) {
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}


// define custom qtip styles

$.fn.qtip.styles.aoeBookingformInfo = {
	name: 'light',
	tip: {
		corner: 'rightTop',
		size: {
			x: 10,
			y :10
		}
	},
	border: {
		radius: 5,
		color: '#142b59'
	},
	fontSize: '11px',
	lineHeight: '14px',
	color: '#fff',
	backgroundColor: '#314979'
};

$.fn.qtip.styles.aoeBookingformValidationError = {
	name: 'aoeBookingformInfo',
	tip: {
		corner: 'bottomMiddle',
		size: {
			x: 20,
			y :10
		}
	}
};


// initialize form

$(document).ready( function () {

	var selectedTabIndex = 0;
	$('#booking-form > ul li a').each( function (i) {
		var classNames = $(this).attr("class").split(' ');
		var currentURL = false;
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j].substring(0,9)=='ajaxLink_') {
				currentURL = decode64(classNames[j].substring(9).replace(/\./g, '+').replace(/_/g, '/').replace(/-/g, '='));
				break;
			}
		}

		var title = $(this).attr('title');
		title = title.replace(/Ä/g, 'AE').replace(/Ö/g, 'OE').replace(/Ü/g, 'UE');
		title = title.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue');
		title = title.replace(/ß/g, 'ss');

		$(this).attr('href', currentURL ).attr('title', title);

		// the currently selected tab is already present, so make sure it does not get reloaded by ajax
		if ( $(this).closest('li').hasClass('ui-tabs-selected') )
		{
			selectedTabIndex = i;
			title = title.replace(/ /g, '_');
			$(this).attr('href', '#'+title);
			$(this).closest('#booking-form').find('> div:first').attr('id', title);
		}
	});

	// loading calendar first used on the first tab

	calendar.setSettings();

	airlineForm.registerToggle();
	flightCities.setSettings();
	flightCitiesY.setSettings();


	$('#input_origin').focus();
		// case if car sharing standalone
	if ($('#mietwagen-form')) {
		self.setTimeout('mietwagen.iniAllExtern()',1000);
	}

	var bookingForm = $("#booking-form");
	bookingForm.tabs({
		spinner : aoe_labels['form.loading'],
		selected : selectedTabIndex,
		cache : true
	});

	bookingForm.bind('tabsselect', function (event, ui) {
		$('.qtip').qtip("hide");
		resetValidationError({target:currentErrorTip});
		currentErrorTip = null;
	});

	bookingForm.bind('tabsshow', function (event, ui) {
		$('.cal').datepicker("destroy");
		
		// Issue: TV-1170. REMOVED Due to Page spring while switching tabs
		// location.hash = $(ui.tab).attr('href');

		self.setTimeout('airlineForm.registerToggle()',500);
		self.setTimeout('flightCities.setSettings()',700);
		self.setTimeout('calendar.setSettings()',900);

		if ($(ui.tab).attr('href') == '#MIETWAGEN' || $(ui.tab).attr('href') == '#RENTAL_CARS') {
			self.setTimeout('mietwagen.iniAllExtern()',1000);
		}

		t = $('#input_origin, #nach, #von2, #nach2');
		t.each(function(i) {
			if (t[i].id) {
				value = readCookie(t[i].id);
				if(value != null){
					t[i].value = value;
				}
			}
		});

		var currentForm = $(ui.panel).find('form');

		addQTipsToForm(currentForm);

		processSubmitButtonStates('div#booking-form div.ui-tabs-panel:visible div.ui-tabs-panel form');

		currentForm.find('input, select, button').focus(resetValidationError);

		currentForm.submit(function () {
				//updateHiddenTerminFields(this);
			t = $('#input_origin, #nach, #von2, #nach2');
			t.each(function(i) {
				if (t[i].id)
					createCookie(t[i].id,t[i].value,0,null);
			});
			return validateFields(this);
		});


	});

	t = $('#input_origin, #nach, #von2, #nach2');
	t.each(function(i) {
		if (t[i].id) {
			value = readCookie(t[i].id);
			if(value != null){
				t[i].value = value;
			}
		}
	});

	var resetValidationError = function(event) {
		if (event.target!=null) {
			if ($(event.target).hasClass('validationError')) {
				$(event.target).removeClass('validationError').qtip('hide');
			} else {
				$(event.target).siblings('.validationError').removeClass('validationError').qtip('hide');
			}
		}
	};

	var currentErrorTip = null;

	var validateFields = function(currentForm) {
		var erwachseneField = $(currentForm).find('select[name=adultCount]');
		resetValidationError({target:erwachseneField});
		var noError = true;
		if (erwachseneField.val()==0 && $('#j2_12').val()>0) {
			currentErrorTip = erwachseneField;
			erwachseneField.qtip({
				content: erwachseneField.siblings('.validationErrorTooltip.noAdultsError'),
				style: 'aoeBookingformValidationError',
				position: {
					corner: {
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					}
				},
				prerender: true,
				show: false,
				hide: false
			});
			erwachseneField.addClass('validationError').qtip('show');
			noError = false;
		}
		if (erwachseneField.val()==10) {
			currentErrorTip = erwachseneField;
			erwachseneField.qtip({
				content: erwachseneField.siblings('.validationErrorTooltip.groupError'),
				style: 'aoeBookingformValidationError',
				position: {
					corner: {
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					}
				},
				prerender: true,
				show: false,
				hide: false
			});
			erwachseneField.addClass('validationError').qtip('show');
			noError = false;
		}

		// open new Window for morehotels.de
		if (noError == true && $("#searchHotelsAswellOption").is(':checked'))
		{
			var destination = $("#nach").val();
			destination = destination.split('[');
			destination = destination[0].split(',');
			datefrom = $("#datefrom_von").val();
			dateto = $("#datefrom_nach").val();
			anz = $("#erwachsene").val();
			var win2 = window.open("http://morehotels.de/r3hotel/airlinedirektde/Hotelstart.aspx?"+
						"_as=true&"+
						"_a=499070&"+
						"_dl=true&"+
						"destination="+destination[0]+"&"+
						"cin="+datefrom+"&"+
						"cout="+dateto+"&"+
						"cat=1&"+
						"dummy_count="+anz+"&"+
						"dummy_type=SR10222&"+
						"r1=1SR10222&"+
						"r2=0TW20222&"+
						"r3=0TW20222",
						"_blank",
						"scrollbars=yes");
			win2.blur();
			window.focus();
		}

		return noError;
	};

	var addQTipsToForm = function(currentForm) {
		currentForm.find('.tooltip').each(function () {
			//check if element has a not empty tooltip text
			if($(this).text() != '') {
				var target = $(this).prev();
				//if so, display infoIcon if element with that class exists
				if(target.is('.infoIcon')){
					target.css('visibility', 'visible');
				}
				//if tooltip text is not empty, build the tooltip
				if($(this).is('.tooltipRight')) {
					target.qtip({
						content: $(this),
						style: {
							name: 'aoeBookingformInfo',
							tip: {
								corner: 'leftTop'
							}
						},
						position: {
							corner: {
								target: 'rightTop',
								tooltip: 'leftTop'
							},
							adjust: {
								x: 2,
								y: 10
							}
						},
						hide: {
							fixed: true
						}
					});
				} else {
					target.qtip({
						content: $(this),
						style: 'aoeBookingformInfo',
						position: {
							corner: {
								target: 'leftTop',
								tooltip: 'rightTop'
							},
							adjust: {
								x: -2,
								y: 10
							}
						},
						hide: {
							fixed: true
						}
					});
				}
			}
		});
	};

	var currentForm = $('div#booking-form form');

	addQTipsToForm(currentForm);
	currentForm.find('input, select, button').focus(resetValidationError);

	currentForm.submit(function () {

		//delete the invalid parameters from url, which has not value
		if($('#booking-form #fluge-form2').css('display') == 'block'){
			for (var i=4;i>1;i--){
				if(currentForm.find('#from_'+i).val()== ''){
					currentForm.find('#from_'+i).remove();
					currentForm.find('#to_'+i).remove();
					currentForm.find('#day_'+i).remove();
					currentForm.find('#month_'+i).remove();
				}
			}
			return true;
		}

			//updateHiddenTerminFields(this);
		t = $('#input_origin, #nach, #von2, #nach2');
		t.each(function(i) {
			if (t[i].id)
				createCookie(t[i].id,t[i].value,0,null);
		});
		return validateFields(this);
	});

	checkGabelflug();
	processSubmitButtonStates('div#booking-form form');

	fillLocationFieldFromParameter($('#fluge-form').find("#input_origin"), 'origin');
	fillLocationFieldFromParameter($('#fluge-form').find("#nach"), 'destination');
	
	fillLocationFieldFromParameter($('.landingPageInfoBox').find('.origin'), 'origin');
	fillLocationFieldFromParameter($('.landingPageInfoBox').find('.destination'), 'destination');

});

function processSubmitButtonStates(formCSSSelector) {
	inputs = $(".submitbuttons input");
	if (inputs.length==0) {
		setTimeout("processSubmitButtonStates('"+formCSSSelector+"')", 100);
	}

	inputs.each( function () {
		if ($(this).attr('processed')!=1) {
			$(this).attr('processed', 1);
			var classNames = $(this).attr("class").split(' ');
			var currentURL = false;
			var cache = [];
			$(this).attr('custom_onclick', 0);
			/*
			 * extract state images and
			 * add them to the preloader
			 */
			for (var i = 0; i < classNames.length; i++) {
				if (classNames[i].substring(0,6)=='hover_') {
					state_img = decode64(classNames[i].substring(6).replace(/\./g, '+').replace(/_/g, '/').replace(/-/g, '='));
					$(this).attr('hover_state', state_img);
					cacheImage = document.createElement('img');
					cacheImage.src = state_img;
					cache.push(cacheImage);
				}
				if (classNames[i].substring(0,5)=='down_') {
					state_img = decode64(classNames[i].substring(5).replace(/\./g, '+').replace(/_/g, '/').replace(/-/g, '='));
					$(this).attr('down_state', state_img);
					cacheImage = document.createElement('img');
					cacheImage.src = state_img;
					cache.push(cacheImage);
				}
				if (classNames[i].substring(0,5)=='wait_') {
					state_img = decode64(classNames[i].substring(5).replace(/\./g, '+').replace(/_/g, '/').replace(/-/g, '='));
					$(this).attr('wait_state', state_img);
					cacheImage = document.createElement('img');
					cacheImage.src = state_img;
					cache.push(cacheImage);
				}
				if (classNames[i]=='custom_onclick') {
					$(this).attr('custom_onclick', 1);
				}
			}

			$(this).attr('normal_state', $(this).attr('src'));
			$(this).attr('clicked', 0);
			/*
			 * mouse down state
			 */
			if ($(this).attr('down_state')) {
				$(this).bind("mousedown", function() {
					if ($(this).attr('clicked')!=1)
						$(this).attr('src', $(this).attr('down_state'));
				});
			}
			/*
			 * mouse over state
			 */
			if ($(this).attr('hover_state')) {
				$(this).bind("mouseenter", function() {
					if ($(this).attr('clicked')!=1)
						$(this).attr('src', $(this).attr('hover_state'));
				});
			}
			/*
			 * mouse leave state
			 */
			$(this).bind("mouseleave", function() {
				if ($(this).attr('clicked')!=1)
					$(this).attr('src', $(this).attr('normal_state'));
			});
			/*
			 * click state
			 */
			if ($(this).attr('wait_state') && $(this).attr('custom_onclick')==0) {
				form1 = 'div#booking-form form';
				form2 = 'div#booking-form div.ui-tabs-panel:visible div.ui-tabs-panel form';

				$(this).bind("click", function() {
					$(this).attr('clicked', 1);
					$(this).attr('src', $(this).attr('wait_state'));
						//marking which form should be submitted
					$('form').attr('submitted', 0);
					$(this).parents('form:first').attr('submitted', 1);
						//delaying submition for 100ms
					setTimeout('$(\'form[submitted=1]\').submit();', 100);
					return false;
				});
			}
		}

	});
};



function registerSubmit() {

	var currentForm = $('div#booking-form div.ui-tabs-panel:visible div.ui-tabs-panel form');
	currentForm.submit(function () {
		updateHiddenTerminFields(this);

	var data = $("input[name='termin']", this).attr('value') + " - " + $("input[name='ruecktermin']", this).attr('value');

	});
}
		var airlineForm = {
			registerToggle: function() {
				$("#show-adv").click(function() {
					 $("#advanced_form").show();
					 $("#show-adv").hide();
				});

				$("#show-adv0").click(function() {
					 $("#advanced_form0").show();
					 $("#show-adv0").hide();
				});

				$("#show-advZ").click(function() {
					 $("#advanced_formZ").show();
					 $("#show-advZ").hide();
				});

				$("#show-flightsearch_2").click(function() {
					 $("#flightsearch_2").show();
					$("#show-flightsearch_2").hide();
				});

                if ($('#fluggesellschaft').val() == '') {
					$("#show-flightsearch_3").click(function() {
						$('.qtip').qtip("hide");
						$("#flightsearch_3").fadeIn("slow");
						$("#show-flightsearch_3").hide();
					});
                } else {
						$("#flightsearch_3").show();
						$("#show-flightsearch_3").hide();
                }

				$("#hinflug, #hinflug2").click(function() {
					stopFormAnimations();

					if ( $('#fluge-form2:visible').size() > 0 ) {
						$('#fluge-form2').fadeOut(10);
						$('#fluge-form').fadeIn(1000, function(){ $(this).css('opacity', '1'); });
						$('#hinflug').attr('checked','checked');
					}

					 $("#flightsearch_ruckf").fadeOut(1000);
					 $("#flightsearch_part").fadeOut(1000);
					 $("#sp1f").hide();
					 $("#sp2f").hide();
					 $("#flightsearch_part1").fadeOut(1000);
					 $("#flightsearch_part2").fadeOut(1000);
					 $("#flightsearch_part3").fadeOut(1000);
					 $("#show-flightsearch_4").fadeOut(1000);
					 $('#suche input.cal').css('width','90px');
					 $("#time1").fadeIn(1000);
					 $("#uhrzeit_von").fadeIn(1000);
					 $("#time2").fadeIn(1000);
					 $("#uhrzeit_von2").fadeIn(1000);
				});

				$("#hin_ruck, #hin_ruck2").click(function() {

					stopFormAnimations();

					if ( $('#fluge-form2:visible').size() > 0 ) {
						$('#fluge-form2').fadeOut(10);
						$('#fluge-form').fadeIn(1000, function(){ $(this).css('opacity', '1'); });
						$('#hin_ruck').attr('checked','checked');
					}


					if ($('#flightsearch_ruckf div').length == 0){
						$('#flightsearch_part div[name="datefrom_nach_day"]').appendTo($('#flightsearch_ruckf'));
						$('#flightsearch_part div[name="datefrom_nach_time"]').appendTo($('#flightsearch_ruckf'));
					}
					$("#flightsearch_ruckf").fadeIn(1000);
					$("#flightsearch_part").fadeOut(1000);
					$("#sp1f").hide();
					$("#sp2f").hide();
					$("#flightsearch_part1").fadeOut(1000);
					$("#flightsearch_part2").fadeOut(1000);
					$("#flightsearch_part3").fadeOut(1000);
					$("#show-flightsearch_4").hide();
					$('#suche input.cal').css('width','90px');
					$("#time1").fadeIn(1000);
					$("#uhrzeit_von").fadeIn(1000);
					$("#time2").fadeIn(1000);
					$("#uhrzeit_von2").fadeIn(1000);
				});

				$("#gabelflug, #gabelflug2").click(function() {

					showGabelflugForm();
				});

				$("#mehrere_strecken").click(function() {
					if(this.checked) {
						stopFormAnimations();
						$('#fluge-form2').fadeIn(1000, function(){ $(this).css('opacity', '1'); });
						$('#fluge-form').fadeOut(10);
						$("#flightsearch_part1").fadeIn(1000);
						$("#flightsearch_part1").css('width','307px');//dirty hack for IE
						$("#flightsearch_part2").fadeIn(1000);
						$("#flightsearch_part2").css('width','307px');//dirty hack for IE
						$("#flightsearch_part3").fadeIn(1000);
						$("#show-flightsearch_4").fadeIn(1000);
						$('#sp1f').show();
						$('#sp2f').show();
						$('#suche input.cal').css('width','150px');
						$('#mehrere_strecken2').attr('checked', 'checked');
					}
				});

				$("#show-more-flights").click(function() {

					if($('#flightsearch_part1').css('display') != 'block'){
						stopFormAnimations();
						$("#flightsearch_part1").show();
						$('#show-less-flights').show();
						$('#from_2').attr('name', 'from_2');
						$('#to_2').attr('name', 'to_2');
						$('#day_2').attr('name', 'day_2');
						$('#month_2').attr('name', 'month_2');
					}
					else if ($('#flightsearch_part2').css('display') != 'block'){
						stopFormAnimations();
						$("#flightsearch_part2").show();
						$('#show-less-flights').show();
						$('#from_3').attr('name', 'from_3');
						$('#to_3').attr('name', 'to_3');
						$('#day_3').attr('name', 'day_3');
						$('#month_3').attr('name', 'month_3');
					}
					else if ($('#flightsearch_part3').css('display') != 'block'){
						stopFormAnimations();
						$("#flightsearch_part3").show();
						$('#show-more-flights').hide();
						$('#from_4').attr('name', 'from_4');
						$('#to_4').attr('name', 'to_4');
						$('#day_4').attr('name', 'day_4');
						$('#month_4').attr('name', 'month_4');
					}
				});

				$("#show-less-flights").click(function() {

					if($('#flightsearch_part3').css('display') != 'none'){
						stopFormAnimations();
						$("#flightsearch_part3").hide();
						$('#show-more-flights').show();
						$('#from_4').removeAttr('name');
						$('#to_4').removeAttr('name');
						$('#day_4').removeAttr('name');
						$('#month_4').removeAttr('name');
					}
					else if ($('#flightsearch_part2').css('display') != 'none'){
						stopFormAnimations();
						$("#flightsearch_part2").hide();
						$('#show-more-flights').show();
						$('#from_3').removeAttr('name');
						$('#to_3').removeAttr('name');
						$('#day_3').removeAttr('name');
						$('#month_3').removeAttr('name');
					}
					else if ($('#flightsearch_part1').css('display') != 'none'){
						stopFormAnimations();
						$("#flightsearch_part1").hide();
						$('#show-less-flights').hide();
						$('#from_2').removeAttr('name');
						$('#to_2').removeAttr('name');
						$('#day_2').removeAttr('name');
						$('#month_2').removeAttr('name');
					}
				});

				$("#show-flightsearch_child").click(function() {
					$("#flightsearch_child").fadeIn("slow");
					$("#show-flightsearch_child").hide();
				});

				if ($('#fluggesellschaft_for_mehererStrecke').val() == '') {
					$("#show-flightsearch_option").click(function() {
						$('.qtip').qtip("hide");
						$("#flightsearch_option").fadeIn("slow");
						$("#show-flightsearch_option").hide();
					});
                } else {
						$("#flightsearch_option").show();
						$("#show-flightsearch_option").hide();
                }

			}
		};

		var calendarSettingsAirlineDirect = {
			monthNames: [aoe_labels['month.full.january'], aoe_labels['month.full.february'], aoe_labels['month.full.march'], aoe_labels['month.full.april'], aoe_labels['month.full.may'], aoe_labels['month.full.june'], aoe_labels['month.full.july'], aoe_labels['month.full.august'], aoe_labels['month.full.september'], aoe_labels['month.full.october'], aoe_labels['month.full.november'], aoe_labels['month.full.december']],
			monthNamesShort: [aoe_labels['month.short.january'], aoe_labels['month.short.february'], aoe_labels['month.short.march'], aoe_labels['month.short.april'], aoe_labels['month.short.may'], aoe_labels['month.short.june'], aoe_labels['month.short.july'], aoe_labels['month.short.august'], aoe_labels['month.short.september'], aoe_labels['month.short.october'], aoe_labels['month.short.november'], aoe_labels['month.short.december']],
			dayNames: [aoe_labels['day.full.sunday'],aoe_labels['day.full.monday'],aoe_labels['day.full.tuesday'],aoe_labels['day.full.wednesday'],aoe_labels['day.full.thursday'],aoe_labels['day.full.friday'],aoe_labels['day.full.saturday']],
			dayNamesMin: [aoe_labels['day.short.sunday'],aoe_labels['day.short.monday'],aoe_labels['day.short.tuesday'],aoe_labels['day.short.wednesday'],aoe_labels['day.short.thursday'],aoe_labels['day.short.friday'],aoe_labels['day.short.saturday']],
			numberOfMonths: 2,
			dateFormat: aoe_labels['date.format'],
			firstDay: 1,
			changeFirstDay: false,
			minDate: "+0d",
			maxDate: "+361d",
			defaultDate: +7,
			changeMonth: false,
			changeYear: false,
			showStatus: false,
			statusForDate: describeDate,
			initStatus: this.title,
			prevText: '',
			nextText: '',
			onSelect: function(){
				reDefineDatePickers(this.id,this.value);
				setHiddenDateFields(this.id, this.value);
			},
			beforeShow: function(){
				document.getElementById("ui-datepicker-div").title=this.title;
				self.setTimeout('changeDatePickerHeader()',100);
				setHiddenDateFields(this.id, this.value);
			},
			onChangeMonthYear: function() {
				self.setTimeout('changeDatePickerHeader()',100);
				setHiddenDateFields(this.id, this.value);
			}
		};

		var calendarSettingsAirlineDirect48von = calendarSettingsAirlineDirect;
		calendarSettingsAirlineDirect48von.minDate = "+2d";

		var calendarSettingsAirlineDirect48nach = calendarSettingsAirlineDirect;
		calendarSettingsAirlineDirect48nach.minDate = "+0d";

		var calendar = {
			setSettings: function () {
				$(".cal").datepicker( calendarSettingsAirlineDirect );
				if( $('#datefrom_von').size() ) {
					reDefineDatePickers('datefrom_von',$('#datefrom_von').val());
				}

				$('#datefrom_vonZ2_h2,#datefrom_von2d').datepicker( calendarSettingsAirlineDirect48von );
				$('#datefrom_nachZ2_h2, #datefrom_nach2d').datepicker( calendarSettingsAirlineDirect48nach );
			}
		};

		var flightCities = {
			setSettings: function(){
				$('#fluge-form').find("#input_origin,#nach,#von2,#nach2").focus(function() {
					this.select();
				});
				$('#fluge-form').find("#input_origin,#nach,#von2,#nach2").autocomplete({
					source: airportSource,
					minLength: 3,
					delay: 150
				});
			}
		};

		var flightCitiesY = {
			setSettings: function(){
				$('.searchFormTBooker').find("#input_origin,#nach,#von2,#nach2,#from_1,#to_1,#from_2,#to_2,#from_3,#to_3,#from_4,#to_4").focus(function() {
					this.select();
				});

				$('.searchFormTBooker').find("#input_origin,#nach,#von2,#nach2,#from_1,#to_1,#from_2,#to_2,#from_3,#to_3,#from_4,#to_4").autocomplete({
						source: airportSource,
						minLength: 3,
						delay: 150
				});
			}
		};

		var airportSource = function (request, callback) {
			if( request != null && request.term != null){
				var language = $('input[name=language]').val();
				$.get("/airport-data.js", {type : "array", q : request.term, lang : language}, function(data) {
					var results = data.split('\n');
					results = $.map( results, function(entry) {
						if( $.trim(entry) == '' ) {
							return;
						}
						if($('#fluge-form').css('display') == 'block') {
							return entry;
						}
						if($('#fluge-form2').css('display') == 'block') {
							return entry.replace( /\[/, "(" ).replace( /\]/, ")" );
						}
					} );
					if(results.length > 10){var resultsCut = results.slice(0,10); callback(resultsCut);}
					else {callback(results);}
	
				});
			}
		};

		var fadeInSuggestion = function(suggestionBox, suggestionIframe) {
		 	$(suggestionBox).fadeTo(300,0.95);
		};
		var fadeOutSuggestion = function(suggestionBox, suggestionIframe) {
		 	$(suggestionBox).fadeTo(300,0);
		};

		var mietwagen = {
			iniAllExtern: function(){
				var isel=0;
				var lastiso='';
				if(document.Stations){
					emptyDD(document.Stations.Country);
					for(var i=0;i<land.length;i++) {
							if (land[i][1]!=lastiso){
								addOptDD(document.Stations.Country, land[i][0], land[i][1]);
								lastiso=land[i][1];
							}
						}
				 		if (document.Stations.setCountry){
							if (document.Stations.setCountry.value!=''){
								selIt(document.Stations.Country, document.Stations.setCountry.value, 'v');
								getOrteExtern();
							}
						}
						disabledOrt();
				}
			}
		};

		function stopFormAnimations() {
			$("#fluge-form, #fluge-form2, #flightsearch_ruckf, #flightsearch_part, #sp1f, #sp2f, #flightsearch_part1, #flightsearch_part2, #flightsearch_part3, #show-flightsearch_4, #time, #uhrzeit_von, #time2, #uhrzeit_von2, #show-less-flights, #show-more-flights, #flightsearch_child, #show-flightsearch_child, #flightsearch_option, #show-flightsearch_option, #gabelflug, #gabelflug2, #hin_ruck, #hin_ruck2, #mehrere_strecken").stop(true, true);
		}

		function describeDate(){
			var calTitle=document.getElementById("ui-datepicker-div").title;
			return calTitle;
		}


    /**
     * Policy function, users should not be able to select a flight,
     * which starts in less than 24h from now.
     */
    function flightBookingIsOnlyAllowedIn24HoursFromNow() {
        var now = new Date();
        var minDate = new Date(now.getTime() + 1000 * 60 * 60 * 24);

        // day
        var currentMinDate = $('#datefrom_von').datepicker('option', 'minDate');

        if (!(currentMinDate instanceof Date) || currentMinDate > minDate) {
            $('#datefrom_von').datepicker('option', 'minDate', minDate);
        }

        // hour
        var datepickerDate = $('#datefrom_von').datepicker('getDate');

        if (datepickerDate.getDate() == minDate.getDate()
            && datepickerDate.getMonth() == minDate.getMonth()
            && datepickerDate.getFullYear() == minDate.getFullYear()) {

            if ($('#datefrom_von').data('hourSelectOptions') === undefined) {
                $('#datefrom_von').data('hourSelectOptions', $('#uhrzeit_von').clone(true));
            }

            for (var i = 0, max = minDate.getHours(); i <= max; i++) {
                var timeValue = ':00';
                timeValue = i + timeValue;
                if (i < 10) {
                    timeValue = '0' + timeValue;
                }
                $('#uhrzeit_von > option[value="' + timeValue + '"]').remove();
            }

            $('#datefrom_von').data('modifiedOptions', true);
        } else if ($('#datefrom_von').data('modifiedOptions') === true) {
            $('#uhrzeit_von').replaceWith($('#datefrom_von').data('hourSelectOptions').clone(true));
            $('#datefrom_von').data('modifiedOptions', false);
        }
    }

	function reDefineDatePickers(id,value){
        var mydate;

		if( value.indexOf(".") != -1 ) {
			var dateParts=value.split('.');
			mydate = dateParts[1] + '/' + dateParts[0] + '/' + dateParts[2];

		} else {
			mydate = value;
		}

		var curDate = new Date(DateAdd(mydate, "D", 0));

        if (id == 'datefrom_von') {
            // this is already done on dom.ready, so something forces us to do it here again
            flightBookingIsOnlyAllowedIn24HoursFromNow();
        }

		if(id.indexOf('von')!=-1) {
            // prepare data to compare the both dates wich are depends on each other
            var localv1 = id;
            var firstDate    = $('#'+localv1).val().split('.');
            var secondDate   = $('#'+localv1.replace(/von/gi, 'nach')).val();
            if (secondDate != '') {
                secondDate = secondDate.split('.');
                    // get timestamp
                var firstDateMS  = Date.UTC(firstDate[2],firstDate[1],firstDate[0],0,0,0);
                var secondDateMS = Date.UTC(secondDate[2],secondDate[1],secondDate[0],0,0,0);
            } else { // data to compare if second field is empty
                firstDateMS = 1;
                secondDateMS = 0;
            }
            
            var currentDaySec = $("#"+id).datepicker("getDate").getTime();
            //var targetDaySec = currentDaySec + 1000 * 60 * 60 * 24;
            var targetDaySec = currentDaySec;
            var targetDay = new Date(targetDaySec);


            if($(".timeFields .cal").length == 0){
            	$("#" + id.replace(/von/gi,'nach')).datepicker("destroy");
            }
			$("#" + id.replace(/von/gi,'nach')).datepicker(
					$.extend(
							{},
							calendarSettingsAirlineDirect,
							{ minDate: targetDay }
					)
			);
            // used for the second return flight date field on first tab "flights"
			if($(".timeFields .cal").length == 0){
				$("#" + id.replace(/von/gi,'nach2')).datepicker("destroy");
			}


			$("#" + id.replace(/von/gi,'nach2')).datepicker(
					$.extend(
							{},

							calendarSettingsAirlineDirect,
							{ minDate: targetDay }

					)
			);


			// used for the return date field on tab "Hotels"
			var v1Date = $("#"+id).datepicker("getDate");
			$("#datefrom_nachZ2_h2").datepicker('option', 'minDate', new Date(v1Date.getFullYear(), v1Date.getMonth(),v1Date.getDate() + 1));

            // update second date field only if the first date higher or equals to the second one
            if (firstDateMS >= secondDateMS) {
            	
            	var returnDatedd = new Date();
            	returnDatedd.setTime(curDate.getTime()+(24*60*60*1000));
            	
                $("#" + id.replace(/von/gi,'nach')).val(twoNum(returnDatedd.getDate()) + '.' + twoNum(1+returnDatedd.getMonth()) + '.' + returnDatedd.getFullYear());
                    // used for the second return flight date field on first tab "flights"
                $("#" + id.replace(/von/gi,'nach2')).val(twoNum(returnDatedd.getDate()) + '.' + twoNum(1+returnDatedd.getMonth()) + '.' + returnDatedd.getFullYear());
            }
		}
	}

	function setHiddenDateFields(id, val) {

		 //mehrere strecken

        if (id.substr(0,7) == 'flug_am') {
        	var dateArray = val.split('.');
        	if (dateArray.length == 3) {
        		$('#day_'+id.substr(7,8)).val(dateArray[0]);
        		$('#month_'+id.substr(7,8)).val(dateArray[1]+'-'+dateArray[2]);
        	}
        }

		if (id.substr(0,9) == 'datefrom_') {

			if( val.indexOf(".") != -1 ) {
				var dateArray= val.split('.');
			} else {
				var dateArray = val.split('/');
			}

			if (dateArray.length == 3) {

                // tabs flight
                if (id == 'datefrom_von') {
                    $('#'+id+'2').val(val);
                    $('#datefrom_von_day').val(dateArray[0]);
                    $('#datefrom_von_monthyear').val(dateArray[1]+'-'+dateArray[2]);
                    // depends return flight field
                    var datefrom_nachDateArray = $('#datefrom_nach').val().split('.');
                    $('#datefrom_nach2').val($('#datefrom_nach').val());
                    $('#datefrom_nach2_day').val(datefrom_nachDateArray[0]);
                    $('#datefrom_nach2_monthyear').val(datefrom_nachDateArray[1]+'-'+datefrom_nachDateArray[2]);
                    $('#datefrom_nach_day').val(datefrom_nachDateArray[0]);
                    $('#datefrom_nach_monthyear').val(datefrom_nachDateArray[1]+'-'+datefrom_nachDateArray[2]);
                }

                if (id == 'datefrom_nach' || id == 'datefrom_nach2' ) { // return date
                    var datefrom_nachDateArray = $('#'+id).val().split('.');
                    $('#datefrom_nach_day').val(datefrom_nachDateArray[0]);
                    $('#datefrom_nach_monthyear').val(datefrom_nachDateArray[1]+'-'+datefrom_nachDateArray[2]);
                }

                if (id == 'datefrom_von2d' ) {
                	$('#datefrom_von_day').val(dateArray[0]);
                    $('#datefrom_von_monthyear').val(dateArray[1]+'-'+dateArray[2]);
                }
                if (id == 'datefrom_nach2d' ) {
                	var datefrom_nachDateArray = $('#'+id).val().split('/');
                    $('#datefrom_nach_day').val(datefrom_nachDateArray[0]);
                    $('#datefrom_nach_monthyear').val(datefrom_nachDateArray[1]+'-'+datefrom_nachDateArray[2]);
                }



                // tabs package tours
                if (id == 'datefrom_vonZ2') {
                    $('#'+id+'2').val(val);
                    $('#termin_pt').val(dateArray[0]+'.'+dateArray[1]+'.'+dateArray[2]);
                    //$('#datefrom_vonZ2_day').val(dateArray[0]);
                    //$('#datefrom_vonZ2_monthyear').val(dateArray[1]+'.'+dateArray[2]);
                    $('#datefrom_vonZ2_day').val('');
                    $('#datefrom_vonZ2_monthyear').val('');
                    // depends return flight field
                    var datefrom_vonZ2_nachDateArray = $('#datefrom_nachZ2').val().split('.');
                    //$('#datefrom_nachZ2_day').val(datefrom_vonZ2_nachDateArray[0])
                    //$('#datefrom_nachZ2_monthyear').val(datefrom_vonZ2_nachDateArray[1]+'.'+datefrom_vonZ2_nachDateArray[2]);
                    $('#ruecktermin_pt').val(datefrom_vonZ2_nachDateArray[0]+'.'+datefrom_vonZ2_nachDateArray[1]+'.'+datefrom_vonZ2_nachDateArray[2]);
                    $('#datefrom_nachZ2_day').val('');
                    $('#datefrom_nachZ2_monthyear').val('');
                } if (id == 'datefrom_nachZ2') { // return date
                    var datefrom_vonZ2_nachDateArray = $('#datefrom_nachZ2').val().split('.');
                	//$('#datefrom_nachZ2_day').val(datefrom_vonZ2_nachDateArray[0])
                    //$('#datefrom_nachZ2_monthyear').val(datefrom_vonZ2_nachDateArray[1]+'.'+datefrom_vonZ2_nachDateArray[2]);
                	$('#ruecktermin_pt').val(datefrom_vonZ2_nachDateArray[0]+'.'+datefrom_vonZ2_nachDateArray[1]+'.'+datefrom_vonZ2_nachDateArray[2]);
                    $('#datefrom_nachZ2_day').val('');
                    $('#datefrom_nachZ2_monthyear').val('');
                }

                // tabs hotels2
                if (id == 'datefrom_vonZ2_h2') {
                    $('#termin_pt_h2').val(dateArray[0]+'.'+dateArray[1]+'.'+dateArray[2]);
                    // depends return flight field
                    var datefrom_vonZ2_nachDateArray = $('#datefrom_nachZ2_h2').val().split('.');
                    $('#ruecktermin_pt_h2').val(datefrom_vonZ2_nachDateArray[0]+'.'+datefrom_vonZ2_nachDateArray[1]+'.'+datefrom_vonZ2_nachDateArray[2]);
                } if (id == 'datefrom_nachZ2_h2') { // return date
                    var datefrom_vonZ2_nachDateArray = $('#datefrom_nachZ2_h2').val().split('.');
                	$('#ruecktermin_pt_h2').val(datefrom_vonZ2_nachDateArray[0]+'.'+datefrom_vonZ2_nachDateArray[1]+'.'+datefrom_vonZ2_nachDateArray[2]);
                }

                // tabs last minute
                if (id == 'datefrom_res_von') {
                    $('#'+id+'2').val(val);
                    $('#termin_lm').val(dateArray[0]+'.'+dateArray[1]+'.'+dateArray[2]);
                	$('#datefrom_res_von_day').val('');
                    $('#datefrom_res_von_monthyear').val('');
                    //$('#datefrom_res_von_day').val(dateArray[0])
                    //$('#datefrom_res_von_monthyear').val(dateArray[1]+'.'+dateArray[2]);
                    // depends return flight field
                    var datefrom_res_nachDateArray = $('#datefrom_res_nach').val().split('.');
                    $('#ruecktermin_lm').val(datefrom_res_nachDateArray[0]+'.'+datefrom_res_nachDateArray[1]+'.'+datefrom_res_nachDateArray[2]);
                    $('#datefrom_res_nach_day').val('');
                    $('#datefrom_res_nach_monthyear').val('');
                    //$('#datefrom_res_nach_day').val(datefrom_res_nachDateArray[0])
                    //$('#datefrom_res_nach_monthyear').val(datefrom_res_nachDateArray[1]+'.'+datefrom_res_nachDateArray[2]);
                } if (id == 'datefrom_res_nach') { // return date
                    var datefrom_res_nachDateArray = $('#datefrom_res_nach').val().split('.');
                    $('#ruecktermin_lm').val(datefrom_res_nachDateArray[0]+'.'+datefrom_res_nachDateArray[1]+'.'+datefrom_res_nachDateArray[2]);
                    $('#datefrom_res_nach_day').val('');
                    $('#datefrom_res_nach_monthyear').val('');
                    //$('#datefrom_res_nach_day').val(datefrom_res_nachDateArray[0])
                    //$('#datefrom_res_nach_monthyear').val(datefrom_res_nachDateArray[1]+'.'+datefrom_res_nachDateArray[2]);
                }

                // tabs hotels
                if (id == 'datefrom_res1_von') {
                    $('#'+id+'2').val(val);
                    $('#datefrom_res1_von_day').val(dateArray[0]);
                    if ($('#datefrom_res1_von_monthyear'))
                    	$('#datefrom_res1_von_monthyear').val(dateArray[1]+'.'+dateArray[2]);
                    if ($('#datefrom_res1_von_yearmonth'))
                    	$('#datefrom_res1_von_yearmonth').val(dateArray[2]+'-'+dateArray[1]);
                    // depends return flight field
                    var datefrom_res1_nachDateArray = $('#datefrom_res1_nach').val().split('.');
                    $('#datefrom_res1_nach_day').val(datefrom_res1_nachDateArray[0]);
                    if ($('#datefrom_res1_nach_monthyear'))
                    	$('#datefrom_res1_nach_monthyear').val(datefrom_res1_nachDateArray[1]+'.'+datefrom_res1_nachDateArray[2]);
                    if ($('#datefrom_res1_nach_yearmonth'))
                    	$('#datefrom_res1_nach_yearmonth').val(datefrom_res1_nachDateArray[2]+'-'+datefrom_res1_nachDateArray[1]);
                } if (id == 'datefrom_res1_nach') { // return date
                    var datefrom_res1_nachDateArray = $('#datefrom_res1_nach').val().split('.');
                    $('#datefrom_res1_nach_day').val(datefrom_res1_nachDateArray[0]);
                    if ($('#datefrom_res1_nach_monthyear'))
                    	$('#datefrom_res1_nach_monthyear').val(datefrom_res1_nachDateArray[1]+'.'+datefrom_res1_nachDateArray[2]);
                    if ($('#datefrom_res1_nach_yearmonth'))
                    	$('#datefrom_res1_nach_yearmonth').val(datefrom_res1_nachDateArray[2]+'-'+datefrom_res1_nachDateArray[1]);
                }

                // tabs hire car
                if (id == 'datefrom_m_von') {
                    $('#'+id+'2').val(val);
                    $('#datefrom_m_von_day').val(dateArray[0]);
                    $('#datefrom_m_von_monthyear').val(dateArray[2]+'-'+dateArray[1]);
                    // depends return flight field
                    var datefrom_m_nachDateArray = $('#datefrom_m_nach').val().split('.');
                    $('#datefrom_m_nach_day').val(datefrom_m_nachDateArray[0]);
                    $('#datefrom_m_nach_monthyear').val(datefrom_m_nachDateArray[2]+'-'+datefrom_m_nachDateArray[1]);
                } if (id == 'datefrom_m_nach') { // return date
                    var datefrom_m_nachDateArray = $('#datefrom_m_nach').val().split('.');
                    $('#datefrom_m_nach_day').val(datefrom_m_nachDateArray[0]);
                    $('#datefrom_m_nach_monthyear').val(datefrom_m_nachDateArray[2]+'-'+datefrom_m_nachDateArray[1]);
                }
			}
		}
	}


	function twoNum(val){
        return (val < 10)? '0' + val : val;
    }

	function selectItem(li) {
		if (li.extra) {
			alert("That's '" + li.extra[0] + "' you picked.");
		}
	}
	function formatAItem(row) {
		return row[0] + "<br><i>" + row[1] + "</i>";
	}

	function changeDatePickerHeader(){
		var htmlStr = '<div class="ui-datepicker-control"><p>' + $("#ui-datepicker-div").attr('title') + '</p>' + '<p class="ui-datepicker-close"><a onclick="jQuery.datepicker._hideDatepicker();">' + aoe_labels['form.close'] + ' &#187;</a> </p></div>';
		$(htmlStr).insertBefore('#ui-datepicker-div .ui-datepicker-group-first');
	}

	var formContentToSet;
	function aoeSetContentForIE(targetElement) {
		var repeatSetContent = "aoeSetContentForIE(\'" + targetElement + "\')";

		if ($(targetElement).html() == '') {
			$(targetElement).html(formContentToSet);
				airlineForm.registerToggle();
				flightCities.setSettings();
				calendar.setSettings();
		} else {
			setTimeout(
				repeatSetContent,
				100
			);
		}
	}

function updateHiddenTerminFields(currentForm) {

 var fieldVon = $('input.cal[id*="von"]', currentForm);
 var fieldNach = $('input.cal[id*="nach"]', currentForm);

 if (fieldVon.attr('id').indexOf('von') != -1) {
  $("input[name='termin']", currentForm).attr('value', fieldVon.attr('value'));
 }

 if ( fieldNach.attr('id').indexOf('nach') != -1) {
  $("input[name='ruecktermin']", currentForm).attr('value', fieldNach.attr('value'));
 }
}




// function extension for "mehrere Strecken" form+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

var calendarSettingsTBookerYpsilon = {
		monthNames: [aoe_labels['month.full.january'], aoe_labels['month.full.february'], aoe_labels['month.full.march'], aoe_labels['month.full.april'], aoe_labels['month.full.may'], aoe_labels['month.full.june'], aoe_labels['month.full.july'], aoe_labels['month.full.august'], aoe_labels['month.full.september'], aoe_labels['month.full.october'], aoe_labels['month.full.november'], aoe_labels['month.full.december']],
		monthNamesShort: [aoe_labels['month.short.january'], aoe_labels['month.short.february'], aoe_labels['month.short.march'], aoe_labels['month.short.april'], aoe_labels['month.short.may'], aoe_labels['month.short.june'], aoe_labels['month.short.july'], aoe_labels['month.short.august'], aoe_labels['month.short.september'], aoe_labels['month.short.october'], aoe_labels['month.short.november'], aoe_labels['month.short.december']],
		dayNames: [aoe_labels['day.full.sunday'],aoe_labels['day.full.monday'],aoe_labels['day.full.tuesday'],aoe_labels['day.full.wednesday'],aoe_labels['day.full.thursday'],aoe_labels['day.full.friday'],aoe_labels['day.full.saturday']],
		dayNamesMin: [aoe_labels['day.short.sunday'],aoe_labels['day.short.monday'],aoe_labels['day.short.tuesday'],aoe_labels['day.short.wednesday'],aoe_labels['day.short.thursday'],aoe_labels['day.short.friday'],aoe_labels['day.short.saturday']],
		numberOfMonths: 2,
		dateFormat: aoe_labels['date.format'],
		firstDay: 1,
		changeFirstDay: false,
		minDate: "+1d",
		maxDate: "+361d",
		defaultDate: +7,
		changeMonth: false,
		changeYear: false,
		showStatus: false,
		statusForDate: describeDate,
		initStatus: this.title,
		onSelect: function(){
			reDefineDatePickers(this.id,this.value);
			setHiddenDateFieldsY(this.id, this.value);
		},
		beforeShow: function(){
			document.getElementById("ui-datepicker-div").title=this.title;
			self.setTimeout('changeDatePickerHeader()',100);
			setHiddenDateFieldsY(this.id, this.value);
		},
		onChangeMonthYear: function() {
			self.setTimeout('changeDatePickerHeader()',100);
			setHiddenDateFieldsY(this.id, this.value);
		}
	};

var calendarY = {
		setSettings: function () {
			var myDate = new Date();

			if ( $.browser.msie && ($.browser.version < 7) ) {
				$(".cal").datepicker({
					'showAnim': 'show',
					'duration'   : ''
				});
			} else {
				$(".cal").datepicker( calendarSettingsTBookerYpsilon );
			}

		}
	};

function setHiddenDateFieldsY(id, val) {
	var count = id.substr(7,1);
	var dateArray = val.split('.');
	if (dateArray.length == 3) {

        $('#fluge-form2 '+id).val(val);
        $('#day_' + count).val(dateArray[0]);
        $('#month_' + count).val(dateArray[1]+'-'+dateArray[2]);
	}
}

(function($) {
    $(document).ready(function() {
        // fix history back
        flightBookingIsOnlyAllowedIn24HoursFromNow();
    })
})(jQuery);


function showGabelflugForm() {

	stopFormAnimations();

	if ( $('#fluge-form2:visible').size() > 0 ) {
		$('#fluge-form2').fadeOut(10);
		$('#fluge-form').fadeIn(1000, function(){ $(this).css('opacity', '1'); });
		$('#gabelflug').attr('checked','checked');
	}

	$("#flightsearch_part").fadeIn(1000);
	$('#sp1f').show();
	$('#sp2f').show();
	$("#flightsearch_ruckf .nrw").insertAfter('#flightsearch_part .nrw:first');
	$("#flightsearch_ruckf").fadeOut(1000);
	$("#show-flightsearch_4").fadeOut(1000);
	$('#suche input.cal').css('width','90px');
	$("#time1").fadeIn(1000);
	$("#uhrzeit_von").fadeIn(1000);
	$("#time2").fadeIn(1000);
	$("#uhrzeit_von2").fadeIn(1000);
}

function checkGabelflug() {

	if( $('#gabelflug,#gabelflug2').is(':checked') ) {
		showGabelflugForm();
	}
}

function fillLocationFieldFromParameter( field, paramName ){
	
	var $field = $(field);
	if ($field.length > 0){
		var paramValue = getURLParameter(paramName);
		airportSource({term:paramValue}, function(result){
			if ($.isArray(result)){
				if (result.length > 0 && result[0] != null){
					if($field.is('input')){
						$field.val(result[0]);
					} else {
						$field.text(result[0]);
					}
					
				}
			}
		} );
	}

	/**
	 * utility function 
	 */
	function regExpEscape(text) {
	    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
	};

	/**
	 * utility function that gets url parameter values by name
	 */
	function getURLParameter(name) {
		var parameterParts = location.search.match( new RegExp('(^|\\?|&)' + regExpEscape( encodeURIComponent(name) ) + '=(.*?)(&|$)') );
		if ( parameterParts ) {
	    	return decodeURIComponent( parameterParts[2] ); 
		}
		return null;
	};
	
}

