/**
 * @category Application
 * @package reisen.de
 * @author Unister GmbH <teamleitung-dev@unister-gmbh.de>
 * @version $Id: forms.js 13045 2011-12-23 13:50:26Z m.zander $
 * @copyright Copyright (c) 2006-2008, Unister GmbH
 * @license this code is property of company Unister GmbH and unterlays internal
 *          rules of company.
 * @link http://www.reisen.de
 *
 * @version $Rev: 13045 $
 * @author $Author: m.zander $
 * @id $Id: forms.js 13045 2011-12-23 13:50:26Z m.zander $
 */
var calselect = false;
var ibeForm = {

	area : null,
	/**
	 * regions by ibePort
	 */
	regions : {},

	selectedDefaultDest : null,
	/**
	 * params for switchForm
	 */
	switchFormParams : {
		displayForm : {
			standard : 'divTT',
			hotel : 'divHotel',
			linienfluege : 'divScheduledFlight'
		},
		lastminuteDateDep : lastminuteDateDep,
		lastminuteDateRet : lastminuteDateRet,
		hotelDateDep : hotelDateDep,
		hotelDateRet : hotelDateRet,
		earlybookersDateDep : earlybookersDateDep,
		earlybookersDateRet : earlybookersDateRet,
		linienfluegeDateDep : flightDateDep,
		linienfluegeDateRet : flightDateRet,
		defaultDateDep : defaultDateDep,
		defaultDateRet : defaultDateRet,
		pauschalDateDep : pauschalDateDep,
		pauschalDateRet : pauschalDateRet,
		packageDateDep : packageDateDep,
		packageDateRet : packageDateRet,
		ownarrivalDateDep : ownarrivalDateDep,
		ownarrivalDateRet : ownarrivalDateRet,
		charterflightDateDep: charterflightDateDep,
        charterflightDateRet: charterflightDateRet,
        vacationhomeDateDep:  vacationhomeDateDep,
        vacationhomeDateRet:  vacationhomeDateRet,
        winterDateDep:  winterDateDep,
        winterDateRet:  winterDateRet,

		ports : {
			ownarrival : 653,
			vacationhome : 655,
			standard : 654,
			hotelonly : 653,
			charterflight : 652
		},
		dateDifference : {
			ownarrival : 56,
			vacationhome : 56,
			earlybird : 91,
			earlybookers : 91,
			lastminute : 42,
			standard : 56,
			linienfluege : 7,
			charterflight : 91,
			hotel : 1
		},
		'duration' : {
			days : 22,
			daysElements : [ 'ownarrival', 'charterflight' ],
			standard : [ '9|1 - 4 Tage', '6_1|1 Tag', '6_2|2 Tage',
					'6_3|3 Tage', '6_4|4 Tage', '10|5 - 8 Tage', '6_5|5 Tage',
					'6_6|6 Tage', '6_7|1 Woche', '6_8|8 Tage', '7|9 - 12 Tage',
					'3|13 - 15 Tage', '6_14|2 Wochen', '12|16 - 22 Tage',
					'6_21|3 Wochen', '13|> 22 Tage' ]
		},
		disableFields : {
		// ownarrival : ['ibeDepAirportIn'],
		// vacationhome : ['ibeDepAirportIn']
		},
		hiddenFields : {
			vacationhome : [ 'ibeInputChild1', 'ibeInputChild2',
					'ibeInputChild3', 'ibeOptChild', 'ibeOptMeal',
					'ibeOptMealSel', 'ibeOptCategory', 'hotelCategorie',
					'ibeInputOptRoom', 'ibeDepAirportIn', 'ibeDepAirportInHide' ],
			allinclusive : [ 'ibeOptMealSel', 'roomtype', 'holidayTheme', 'divHolidayTheme',
					'ibeDepAirportInHide' ],
			charterflight : [ 'hotelOptions', 'specialOptions',
					'ibeInputOptRoom', 'ibeOptMealSel', 'ibeOptCategory',
					'hotelCategorie', 'ibeDepAirportInHide' ],
			ownarrival : [ 'depAirportIn', 'roomtype', 'ibeDepAirportIn' ],
			hotelonly : [ 'depAirportIn', 'roomtype' ],
			lastminute : [ 'roomtype', 'holidayTheme', 'divHolidayTheme', 'ibeDepAirportInHide' ],
			earlybookers : [ 'roomtype', 'holidayTheme', 'divHolidayTheme', 'ibeDepAirportInHide' ],
			pauschal : [ 'holidayTheme', 'roomtype', 'divHolidayTheme', 'ibeDepAirportInHide' ],
			'package' : [ 'holidayTheme', 'roomtype', 'divHolidayTheme', 'ibeDepAirportInHide' ],
			roundtrip : [ 'ibeInput_dest', 'ibeDepAirportInHide' ]
		},
		calendarLabel : {
			vacationhome : [ 'Früheste Anreise:', 'Späteste Abreise:' ],
			hotel : [ 'Anreise:', 'Abreise:' ],
			hotelonly : [ 'Früheste Anreise:', 'Späteste Abreise:' ],
			ownarrival : [ 'Früheste Anreise:', 'Späteste Abreise:' ],
			linienfluege : [ 'Abflugdatum:', 'Rückflugdatum:' ],
			charterflight : [ 'Früheste Anreise:', 'Späteste Abreise:' ],
			'package' : [ 'Früheste Anreise:', 'Späteste Abreise:' ]
		},
		roomtype : {
			vacationhome : {
				0 : 'Haus',
				1 : 'Ferienhaus',
				2 : 'Anlage',
				3 : 'Ferienwohnung'
			},
			hotel : false,
			linienfluege : false
		},
		destination : {
			655 : {
				10034 : 'Andorra',
				10000 : 'Belgien',
				10001 : 'Bulgarien',
				10003 : 'Deutschland',
				10002 : 'Dänemark',
				10004 : 'Finnland',
				10005 : 'Frankreich',
				10006 : 'Griechenland',
				10007 : 'Großbritannien',
				10008 : 'Irland',
				10009 : 'Island',
				10010 : 'Italien',
				10012 : 'Kroatien',
				10037 : 'Litauen',
				10014 : 'Luxemburg',
				10036 : 'Malta / Gozo',
				10015 : 'Niederlande',
				10017 : 'Norwegen',
				10018 : 'Oesterreich',
				10019 : 'Polen',
				10020 : 'Portugal',
				10021 : 'Schweden',
				10022 : 'Schweiz',
				10024 : 'Slowakei',
				10031 : 'Spanien Balearen',
				10030 : 'Spanien Festland / Andorra',
				10032 : 'Spanien Kanaren',
				10026 : 'Tschechien',
				10027 : 'Türkei',
				10029 : 'USA',
				10028 : 'Ungarn'
			},
			653 : {
				30029 : 'Ägypten',
				30020 : 'Arabische Halbinsel',
				30018 : 'Australien',
				30006 : 'Benelux',
				30000 : 'Deutschland Nord',
				30001 : 'Deutschland Ost',
				30002 : 'Deutschland Süd',
				30003 : 'Deutschland West',
				30009 : 'Frankreich',
				30023 : 'Großbritannien / Irland',
				30033 : 'Indischer Ozean',
				30031 : 'Island',
				30008 : 'Italien',
				30027 : 'Karibik',
				30014 : 'Kroatien',
				30028 : 'Neuseeland',
				30024 : 'Malta',
				30004 : 'Oesterreich',
				30025 : 'Osteuropa',
				30012 : 'Polen',
				30022 : 'Portugal',
				30005 : 'Schweiz',
				30007 : 'Skandinavien',
				30011 : 'Slowakei / Tschechien',
				30015 : 'Slowenien',
				30010 : 'Spanien',
				30032 : 'Südafrika',
				30030 : 'Südsee',
				30021 : 'Türkei',
				30013 : 'Ungarn',
				30016 : 'USA / Kanada',
				30026 : 'Zypern'
			},
			family : 655,
			earlybook : 'package',
			hotel : false,
			linienfluege : false,
			lastminuteAllInclusive : 655
		}
	},

	/**
	 * options for calender
	 */
	calenderOptions : {
		dateFormat : 'dd.mm.yy',
		firstDay : 1,
		maxDate : '+1y',
		minDate : new Date(),
		monthNames : [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
				'Juli', 'August', 'September', 'Oktober', 'November',
				'Dezember' ],
		monthNamesShort : [ 'Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul',
				'Aug', 'Sep', 'Okt', 'Nov', 'Dez' ],
		dayNamesMin : [ 'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' ],
		numberOfMonths : 2,
		buttonImage : ((typeof HOME_URL != 'undefined') ? HOME_URL : '')
				+ 'img/travel/calendar.gif',
		buttonImageOnly : true,
		buttonText : '',
		dateHiddenFormat : 'yy-mm-dd',
		showOn : 'button',
		onSelect : function(dateText, inst, calElement) {
			ibeForm.calOnSelect(dateText, inst, calElement);
		},

		onClose : function(dateText, inst, calElement) {
			calselect = false;
		},
		beforeShow : function(dateText, inst, calElement) {
			calselect = true;
		}
	},

	/**
	 * Set Stars for HotelCategory
	 *
	 * @param {String}
	 *            kat
	 */
	starDirect : function(kat) {
		jQuery('#katInput').val(kat);
		jQuery('#txtKat')
				.html(
						kat == -1 ? 'egal' : 'mind. ' + (parseInt(kat) + 2)
								+ ' Sterne');
		jQuery('#imageKat').attr(
				'src',
				((typeof HOME_URL != 'undefined') ? HOME_URL : '')
						+ 'img/travel/'
						+ ((kat == -1) ? 0 : (parseInt(kat) + 2)) + '.gif');
	},
	/**
	 * Switch Form by Event
	 *
	 * @param {Object}
	 *            traveltype
	 */
	switchForm : function(radioElement) {
		/**
		 * set style active | inactiv
		 */
		jQuery('label[class~=checked]').removeClass('checked');
		jQuery(radioElement).next().addClass('checked');
		/**
		 * display selected form
		 */
		var displayForm = 'standard';
		if (typeof this.switchFormParams.displayForm[radioElement.id] != 'undefined') {
			displayForm = radioElement.id;
		}
		/**
		 * update calender date
		 */

		this.setCalenderDate(radioElement.id);

		/**
		 * @TODO refactor
		 */

		if (radioElement.id === 'vacationhome') {
			jQuery('#ibeInputOptHotel').prev().html(
					'Objektname <span>(nur eintragen, falls bekannt)</span>');
		} else {
			if (jQuery('#ibeInputOptHotel').prev().html() === 'Objektname <span>(nur eintragen, falls bekannt)</span>') {
				jQuery('#ibeInputOptHotel')
						.prev()
						.html(
								'Hotelname <span>(nur eintragen, falls bekannt)</span>');
			}
		}
		/**
		 * update hidden port
		 */
		this.setPortToInputHidden();
		this.setTripTypeToInputHidden();
		this.fillDuration();

		this.showFields();
		this.hideFields();

		this.enableFields();
		this.disableFields();

		this.setCalenderLabel(radioElement.id);
		var tripType = this.getCurrentTripType();
		if (this.switchFormParams.roomtype[tripType] !== false) {
			this.setRoomType();
		}
		if (this.switchFormParams.destination[tripType] !== false) {
			this.setDestination();

		}
		;
		jQuery.each(this.switchFormParams.displayForm, function(key, formId) {
			if (key != displayForm) {
				jQuery('#' + formId).hide();
			} else {
				jQuery('#' + formId).show();
			}
		});

		jQuery('#quickSearchSub').removeClass();
		jQuery('#quickSearchSub').addClass(radioElement.id);

	},

	/**
	 * addRegionsFromArray for ibePort from data
	 *
	 * @param {Object}
	 *            port
	 * @param {Object}
	 *            regions
	 */
	addRegionsFromArray : function(port, regions) {

		var port = port;
		regions.sort();
		this.regions[port] = {};
		jQuery.each(regions, function(index, region) {
			var regionArray = region.split('|');
			if (typeof ibeForm.regions[port][regionArray[2]] == 'undefined') {
				ibeForm.regions[port][regionArray[2]] = {};
			}
			ibeForm.regions[port][regionArray[2]][regionArray[1]] = {
				'name' : regionArray[0],
				'topregion' : regionArray[3]
			};
		});
	},

	/**
	 * add RegionsObject
	 *
	 * @param {Number}
	 *            port
	 * @param {Object}
	 *            data
	 */
	addRegions : function(port, data) {
		this.regions[port] = data;
	},

	/**
	 *
	 * @param {String}
	 *            name
	 * @param {Object}
	 *            data
	 */
	addDestination : function(name, data) {
		this.switchFormParams.destination[name] = data;
	},

	addOption : function(element, option, attribute) {

		if (typeof attribute == 'object') {
			jQuery.each(attribute, function(name, value) {
				jQuery(option).attr(name, value);
			});
		}
		if (this.msie) {
			element[0].add(option);
		} else {
			element[0].appendChild(option);
		}
	},

	checkAirports : function() {
		var message = '';
		if (jQuery('#sflight #depCity').val() == '') {
			message = 'den Abflughafen';
		}
		if (jQuery('#sflight #arrCity').val() == '') {
			if (message != '') {
				message += ' und den Zieflughafen';
			} else {
				message = 'Zieflughafen';
			}
		}
		if (message != '') {
			message = 'Sie m\xFCssen ' + message
					+ ' eingeben um Ergebnisse zu erhalten!';
			alert(message);
			return false;
		}
		return true;
	},

	/**
	 * fill selectbox duration
	 *
	 * @param {String}
	 *            tripType
	 */
	fillDuration : function() {
		var tripType = this.getCurrentTripType();

		var durationElement = jQuery('#' + this.getCurrentForm()
				+ " select[name$='ibeInput[duration]']");
		var selectedVal = '';
		if (durationElement.length > 0) {
			selectedVal = jQuery(durationElement).val();

			jQuery(durationElement).empty();
			if (jQuery.browser.msie) {
				durationElement[0].add(new Option('beliebig', '-1'));
			} else {
				durationElement[0].appendChild(new Option('beliebig', '-1'));
			}
			if (jQuery.inArray(tripType,
					this.switchFormParams.duration.daysElements) != -1) {
				for ( var i = 0; i < this.switchFormParams.duration.days; ++i) {
					var val = i + 1;
					var days = ' Tage';
					if (i == 0) {
						days = ' Tag';
					}
					if (val == this.switchFormParams.duration.days) {
						ibeForm.addOption(durationElement, new Option(
								'> 22 Tage', '13'));
					} else {
						ibeForm.addOption(durationElement, new Option(val
								+ days, '6_' + val));
					}
				}
			} else {
				jQuery.each(this.switchFormParams.duration.standard, function(
						index, option) {
					var split = option.split('|');
					ibeForm.addOption(durationElement, new Option(split[1],
							split[0]));
				});
			}
			if (selectedVal != '-1' && selectedVal != 'beliebig') {
				jQuery(durationElement).find(
						'option[value="' + selectedVal + '"]').attr('selected',
						'selected');
			}
		}
	},

	/**
	 * Format date from dateHiddenFormat to dateFormat format can be set in
	 * calenderOptions
	 *
	 * @param string
	 *            date
	 * @returns string
	 */
	formatDate : function(date) {
		try {
			var dateObject = jQuery.datepicker.parseDate(
					this.calenderOptions.dateHiddenFormat, date);
			return jQuery.datepicker.formatDate(
					this.calenderOptions.dateFormat, dateObject);
		} catch (e) {
			return date;
		}
	},

	/**
	 * get current form
	 */
	getCurrentForm : function() {
		if (typeof this.switchFormParams.displayForm[this.getCurrentTripType()] == 'undefined') {
			return this.switchFormParams.displayForm['standard'];
		}
		return this.switchFormParams.displayForm[this.getCurrentTripType()];
	},

	/**
	 * get date difference
	 */
	getDateDifference : function(type) {
		if (!this.switchFormParams.dateDifference[type]) {
			return this.switchFormParams.dateDifference['standard'];
		}

		return this.switchFormParams.dateDifference[type];
	},

	/**
	 * get current selected tripType
	 *
	 * @return {String}
	 */
	getCurrentTripType : function() {
		if (jQuery("input[type=radio][name$='traveltype']").length > 0) {
			return jQuery("input[type=radio][name$='traveltype']:checked")
					.val();
		} else {
			return jQuery("input[type=hidden][name$='traveltype']").val();
		}
	},

	getCurrentOfferType : function() {
		return jQuery("input[type=hidden][name$='ibeInput[offerType]']").val();
	},
	
	getCurrentPort : function() {
		return +jQuery("input[type=hidden][name$='ibeInput[port]']").val();
	},

	getDestinationOptions : function() {
		if (typeof this.switchFormParams.destination[this.getCurrentOfferType()] != 'undefined') {
			options = this.switchFormParams.destination[this
					.getCurrentOfferType()];
			if (typeof options != 'object') {
				options = this.switchFormParams.destination[options];
			}
			return options;
		}

		if (typeof this.switchFormParams.destination[this
				.getPortFromInputHidden()] != 'undefined') {
			return this.switchFormParams.destination[this
					.getPortFromInputHidden()];
		}
		return this.defaultDestination;
	},

	/**
	 * get depdate for selected trip
	 *
	 * @param {String}
	 *            tripType
	 */
	getDepDate : function(asDateObject) {
		var tripType = this.getCurrentOfferType();


		if (tripType) {
			switch (tripType) {
			case 'lastminuteAllInclusive':
			case 'lastminuteFerienhotel':
			case 'cheap':
				tripType = 'lastminute';
				break;
			case 'earlybookers':
				tripType = 'earlybookers';
				break;
			case 'packagetour':
			case 'wellness':
			case 'themepark':
				tripType = this.getCurrentTripType();
				break;
			case 'club': 
			case 'family':
			case 'earlybook':
			case 'flycheap':
			case 'citytravelgolf':
			case 'golf':
			case 'luxury':
			case 'holidayhotel':
				tripType = 'pauschal';
				break;
			case 'roundtrip':
				tripType = 'vacationhome';
				break;
			case 'holidayhotel':
				tripType = 'hotelonly';
				break;
			default: 
				tripType = 'pauschal';
				break;
			
			}
		} else if (tripType == '') {
			var depDate = jQuery("input[type=text][id$='ibeInput[depDate]']").val();
//			switch (this.getCurrentTripType()) {
//	            
//	            case '654':
//	            	tripType = 'lastminute';
//	                break;
//	            case '650':	 /* Break intentionally omitted */
//	            case '651':	 /* Break intentionally omitted */
//	            case '652':    /* Break intentionally omitted */
//	            case '653':    /* Break intentionally omitted */
//	            
//	            	tripType = 'pauschal';
//	                break;
//	            default:
//	            	tripType = 'pauschal';
//	                break;
	        
		} else {
			tripType = this.getCurrentTripType();
		}
		
		if (typeof depDate == 'undefined') {
			if (typeof this.switchFormParams[tripType + 'DateDep'] != 'undefined') {
				var depDate = this.switchFormParams[tripType + 'DateDep'];
			} else {
				var depDate = this.switchFormParams.defaultDateDep;
			}
			
			var dateObject = jQuery.datepicker.parseDate('yy-mm-dd', depDate);
		} else {
			var dateObject = jQuery.datepicker.parseDate('dd.mm.yy', depDate);
		}

		
		if (asDateObject) {
			return dateObject;
		}
		try {
			return jQuery.datepicker.formatDate(
					this.calenderOptions.dateFormat, dateObject);
		} catch (e) {
			return this.formatDate(dateObject);
		}
	},

	/**
	 * get port from input hidden
	 *
	 * @return {String}
	 */
	getPortFromInputHidden : function() {
		return jQuery(
				'#' + this.getCurrentForm()
						+ " input[type=hidden][name$='ibeInput[port]']").val();
	},

	/**
	 * get retdate for selected trip
	 *
	 * @param {String}
	 *            tripType
	 * @param {DOMObject}
	 *            calElement
	 */
	getRetDate : function(asDateObject, calElement) {
		
		var tripType = this.getCurrentOfferType();


		if (tripType) {
			switch (tripType) {
			case 'lastminuteAllInclusive':
			case 'lastminuteFerienhotel':
			case 'cheap':
				tripType = 'lastminute';
				break;
			case 'earlybookers':
				tripType = 'earlybookers';
				break;
			case 'packagetour':
			case 'wellness':
			case 'themepark':
				tripType = this.getCurrentTripType();
				break;
			case 'club': 
			case 'family':
			case 'earlybook':
			case 'flycheap':
			case 'citytravelgolf':
			case 'golf':
			case 'luxury':
			case 'holidayhotel':
				tripType = 'pauschal';
				break;
			case 'roundtrip':
				tripType = 'vacationhome';
				break;
			case 'holidayhotel':
				tripType = 'hotelonly';
				break;
			default: 
				tripType = 'pauschal';
				break;
			
			}
		} else if (tripType == '') {
			var retDate = jQuery("input[type=text][id$='ibeInput[retDate]']").val();
		} else {
			tripType = this.getCurrentTripType();
		}
		
		if (calElement) {
			var retDateObject = jQuery.datepicker.parseDate(
					this.calenderOptions.dateFormat, jQuery(calElement).val());
			var retDate = jQuery.datepicker.formatDate(
					this.calenderOptions.dateHiddenFormat, retDateObject);
		} else if (typeof retDate == 'undefined') {
			if (typeof this.switchFormParams[tripType + 'DateRet'] != 'undefined') {
				var retDate = this.switchFormParams[tripType + 'DateRet'];
			} else {
				var retDate = this.switchFormParams.defaultDateRet;
			}
			var dateObject = jQuery.datepicker.parseDate(
					this.calenderOptions.dateHiddenFormat, retDate);
		} else {
			var dateObject = jQuery.datepicker.parseDate('dd.mm.yy', retDate);
		}

		
		if (asDateObject) {
			return dateObject;
		}
		return jQuery.datepicker.formatDate(this.calenderOptions.dateFormat,
				dateObject);
	},

	/**
	 * Disable fields which not use by tripType
	 */
	disableFields : function() {
		this.disabledFields = [];
		if (typeof this.switchFormParams.disableFields[this
				.getCurrentTripType()] != 'undefined') {
			jQuery.each(this.switchFormParams.disableFields[this
					.getCurrentTripType()], function(index, field) {
				jQuery('[#' + field).attr('disabled', 'disabled');
				ibeForm.disabledFields[index] = field;
			});
		}
	},

	/**
	 * Enable all fields which where disabled
	 */
	enableFields : function() {
		if (this.disabledFields && this.disabledFields.length > 0) {
			jQuery.each(this.disabledFields, function(index, field) {
				jQuery('#' + field).removeAttr('disabled');
			});
		}
	},

	/**
	 * hide fields which not use by tripType
	 */
	hideFields : function() {
		this.hiddenFields = [];
		if (typeof this.switchFormParams.hiddenFields[this.getCurrentTripType()] != 'undefined') {
			var hiddenFields = this.switchFormParams.hiddenFields[this
					.getCurrentTripType()];
			if (typeof this.switchFormParams.hiddenFields[this
					.getCurrentOfferType()] != 'undefined') {
				hiddenFields = hiddenFields
						.concat(ibeForm.switchFormParams.hiddenFields[ibeForm
								.getCurrentOfferType()]);
			}

			jQuery.each(hiddenFields, function(index, field) {
				jQuery('#' + field).hide();
				jQuery("label[for='" + field + "']").hide();
				ibeForm.hiddenFields[index] = field;
			});
		}
	},

	/**
	 * show all fields which where hidden
	 */
	showFields : function() {
		if (this.hiddenFields && this.hiddenFields.length > 0) {
			jQuery.each(this.hiddenFields, function(index, field) {
				jQuery('#' + field).css('display', 'block');
				jQuery("label[for='" + field + "']").css('display', 'block');
			});
		}
	},

	/**
	 * calendar "onselect" event
	 */
	calOnSelect : function(dateText, inst, calElement) {
		jQuery('#ui-datepicker-div').hide();
		ibeForm.setDateToInputHidden(dateText, calElement);
		if (jQuery(calElement).hasClass('first')) {
			var tripType = ibeForm.getCurrentTripType();

			if (ibeForm.switchFormParams.displayForm[tripType]) {
				var parent = ibeForm.switchFormParams.displayForm[tripType];
			} else {
				var parent = ibeForm.switchFormParams.displayForm['standard'];
			}
			var cal = jQuery('#' + parent + " input[type=text][name$='retVal']");
			ibeForm.setCalenderRetMinDate(calElement, cal);
		}
	},

	/**
	 * init FormCalender start jQuery datepicker;
	 */
	initCalendar : function() {

		var shortYearCutoff = parseInt(this.calenderOptions.minDate
				.getFullYear().toString().slice(2)) + 1;
		this.calenderOptions['shortYearCutoff'] = '+' + shortYearCutoff;
		jQuery.datepicker.setDefaults(this.calenderOptions);
		jQuery
				.each(
						jQuery('.cal'),
						function(index, calElement) {

							if (jQuery(calElement).hasClass('first')) {
								var depDate = '';
								if (jQuery(calElement).val() == '') {
									depDate = ibeForm.getDepDate();
								} else {
									depDate = ibeForm.formatDate(jQuery(
											calElement).val());
								}
								var arrayDate = depDate.split('.');
								minDate = new Date(arrayDate[2], arrayDate[1],
										arrayDate[0]);

								jQuery(calElement).val(depDate);
								ibeForm.setDateToInputHidden(depDate,
										calElement);
							} else {
								var retDate = '';
								if (jQuery(calElement).val() == '') {
									retDate = ibeForm.getRetDate();
								} else {
									retDate = ibeForm.formatDate(jQuery(
											calElement).val());
								}

								jQuery(calElement).val(retDate);
								ibeForm.setDateToInputHidden(retDate,
										calElement);
								ibeForm.setCalenderRetMinDate(ibeForm
										.getCurrentTripType(), calElement);
							}

							/**
							 * add Datepicker to Element
							 */
							jQuery(calElement)
									.datepicker(
											{
												onSelect : function(dateText,
														inst) {
													ibeForm.calenderOptions
															.onSelect(dateText,
																	inst,
																	calElement);
												}
											});

							/**
							 * remove background calImg
							 */
							if (jQuery('.calImg').length > 0) {
								jQuery('.calImg').css('background', 'none');
							}

							/**
							 * add Event change
							 */
							jQuery(calElement).keypress(function(event) {
								if (event.keyCode == 13) {
									calElement.blur();
									return false;
								}
							});
							jQuery(calElement)
									.change(
											function(event) {
												if (ibeForm.isDate(calElement)) {
													ibeForm
															.setDateToInputHidden(
																	jQuery(
																			calElement)
																			.val(),
																	calElement);
													if (jQuery(calElement)
															.hasClass('first')) {
														if (!calselect) {
															var parentForm = jQuery(
																	calElement)
																	.parents(
																			'form');
															ibeForm
																	.setCalenderRetMinDate(
																			calElement,
																			jQuery(
																					parentForm)
																					.find(
																							'input[type=text][name=retVal]'));
														}
													}
												} else {
													if (jQuery(calElement)
															.hasClass('first')) {
														alert('Der Abflugtermin liegt vor dem heutigen Datum oder nach dem maximalen Abflugtermin!');
														calElement.focus();
													} else {
														alert('Der Rückflugtermin liegt vor dem morgigen Datum oder nach dem maximalen Rückflugtermin!');
													}
												}
											});
						});

		jQuery(document).trigger('calender:init');
	},

	/**
	 * init object vars
	 */
	init : function() {
		this.msie = jQuery.browser.msie;

		jQuery('#divTT form')
				.submit(
						function() {
							ibeForm.setOptHotel();
							overlayLoadingBox(
									'Wir bitten Sie um einen Moment Geduld.',
									'Wir suchen für Sie nach passenden Angeboten.',
									400);
						});
		setTimeout(function() {
			jQuery('#optHotel').focus(function() {
				ibeForm.setOptHotel();
			});
		}, 500);
	},

	setOptHotel : function() {
		if (jQuery("#optHotel").length > 0
				&& jQuery("input[name$='ibeInput[village]']").length > 0) {
			jQuery("input[name$='ibeInput[village]']").attr('value', '');
		}

	},

	/**
	 * init switchForm add Events to radiobuttons if there available
	 *
	 * @param {Object}
	 *            radioButtons
	 */
	initSwitchForm : function(radioButtons) {
		ibeForm.init();

		this.defaultDestination = jQuery('#ibeInput_dest').children().clone();

		if (radioButtons.length > 0) {
			this.defaultRoomtype = jQuery("select[name$='ibeInput[optRoom]']")
					.children().clone();
			jQuery.each(radioButtons, function(key, radiobutton) {
				jQuery(radiobutton).click(function() {
					ibeForm.switchForm(this);
				});
				if (jQuery(radiobutton).attr('checked') == true) {
					ibeForm.switchForm(radiobutton);
				}
			});
		} else {
			this.hideFields();
			this.disableFields();
			this.setDestination();
		}

		this.setPortToInputHidden();

		this.fillDuration();

		if (jQuery("input[type=radio][name='sFlightInput[flightType]']").length > 0) {
			jQuery("input[type=radio][name='sFlightInput[flightType]']").click(
					function() {
						var parentForm = jQuery(this).parents('form');
						if (jQuery(this).val() == 'OW') {
							jQuery.flight.disableReturnDate(parentForm);
						} else {
							jQuery.flight.enableReturnDate(parentForm);
						}
					});
		}

		if (jQuery("select[name='sFlightInput[flightType]']").length > 0) {
			jQuery("select[name='sFlightInput[flightType]']").change(
					function() {
						var parentForm = jQuery(this).parents('form');
						if (jQuery(this).val() == 'OW') {
							jQuery.flight.disableReturnDate(parentForm);
						} else {
							jQuery.flight.enableReturnDate(parentForm);
						}
					});
		}

		if (jQuery('#sflight').length > 0) {
			jQuery('#sflight').submit(function() {
				return ibeForm.checkAirports();
			});
			jQuery('#adultSelector').change(function() {
				jQuery.flight.setNumPax();
			});
			jQuery.flight.setNumPax();
		}

		if (jQuery('#ibeAdditionalSearchFormA').length > 0) {
			jQuery('#ibeAdditionalSearchFormA')
					.click(
							function() {
								jQuery('#ibeAdditionalSearchForm').toggleClass(
										'hide');
								if (jQuery(this).text() == 'Zusätzliche Suchoption einblenden') {
									jQuery(this)
											.text(
													'Zusätzliche Suchoption ausblenden');
								} else {
									jQuery(this)
											.text(
													'Zusätzliche Suchoption einblenden');
								}
							});
		}

		this.initArea();

		this.isInit = true;
	},

	/**
	 * @param {String}
	 *            dateText
	 * @return{Boolean}
	 */
	isDate : function(calElement) {
		try {
			var insertDate = jQuery.datepicker.parseDate(
					this.calenderOptions.dateFormat, jQuery(calElement).val());
			var insertDateTime = insertDate.getTime();
			var minDateTime = jQuery(calElement)
					.datepicker('option', 'minDate').getTime();
			if (insertDateTime >= minDateTime) {
				return true;
			}
			return false;
		} catch (e) {
			return false;
		}
	},

	setArea : function(dest) {
		var port = ibeForm.getPortFromInputHidden();
		if (typeof ibeForm.regions[port] != 'undefined') {
			if (jQuery('select#area').length) {
				var area = jQuery('select#area').empty();
				if (dest != '-1') {
					if (typeof ibeForm.regions[port][dest] != 'undefined') {
						ibeForm.addOption(area, new Option('-- beliebig --',
								'-1'));

						optionsArray = [];

						for ( var destId in ibeForm.regions[port][dest]) {
							optionsArray
									.push({
										destId : ibeForm.regions[port][dest][destId].topregion,
										name : ibeForm.regions[port][dest][destId].name
									});
						}

						optionsArray.sort(this.sortWithGermanLetters);

						for ( var i = 0, len = optionsArray.length; i < len; i++) {
							var option = optionsArray[i];
							if (option.destId != dest) {
								ibeForm.addOption(area, new Option(option.name,
										option.destId), {
									'rel' : dest
								});
							}
						}

					}
				} else {
					ibeForm.addOption(area, new Option('-- beliebig --', '-1'));
					jQuery.each(ibeForm.regions[port], function(dest, datas) {
						jQuery.each(datas, function(region, data) {
							if (dest != region) {
								ibeForm.addOption(area, new Option(data.name,
										data.topregion), {
									'rel' : dest
								});
							}
						});
					});
				}
			}
			return;
		}

		if (jQuery('input#area').length) {
			if (ibeForm.area == null) {
				ibeForm.area = dest;
			}
			if (dest == ibeForm.area) {
				jQuery('input#area').val(dest);
			} else {
				jQuery('input#area').val('');
			}
		}
	},

	/**
	 * Inits the area content and events
	 */
	initArea : function() {

		if (jQuery('select#area').length || jQuery('input#area').length) {
			jQuery('#ibeInput_dest').change(function() {
				if (ibeForm.getPortFromInputHidden() == '653') {
					earthDest = jQuery(this).val();
				}
				ibeForm.setArea(jQuery(this).val());
			});
			ibeForm.setArea(jQuery('#ibeInput_dest').val());
			if (jQuery('select#area').length) {
				jQuery('select#area')
						.change(
								function() {
									var value = jQuery(
											this.options[this.selectedIndex])
											.attr('rel');
									if (value) {
										jQuery(
												'#ibeInput_dest option[value='
														+ value + ']').attr(
												'selected', 'selected');
									}
								});
				if (jQuery('#ibeInput_dest').val() != '-1') {
					jQuery('#ibeInput_dest').trigger('change');
				}
			}
		}
	},

	initLandingPage : function(baseUrl, notAction) {
		if (typeof earthDest != 'undefined') {
			var earthDefaultDest = earthDest;
		}
		var lpChangeUrl = baseUrl + 'hotelcategory/tttargetarea/id/25000/';
		var lpBaseUrl = jQuery('#bengine').attr('action');
		var inputs = jQuery('#ibeInput_dest').parent().find('input');
		var inputsValue = {};
		var hotelnameChange = false;
		jQuery.each(inputs, function(index, input) {
			inputsValue[jQuery(input).attr('name')] = jQuery(input).val();
		});

		jQuery('#ibeInput_dest')
				.change(
						function() {
							if (!hotelnameChange) {
								if (jQuery(this).val() == ibeForm.selectedDefaultDest
										|| (typeof earthDefaultDest != 'undefined' && jQuery(
												this).val() == earthDefaultDest)) {
									if (!notAction) {
										jQuery('#bengine').attr('action',
												lpBaseUrl);
									}
									jQuery.each(inputs, function(index, input) {
										jQuery(input).val(
												inputsValue[jQuery(input).attr(
														'name')]);
									});
								} else {
									if (!notAction) {
										jQuery('#bengine').attr('action',
												lpChangeUrl);
									}
									jQuery.each(inputs, function(index, input) {
										jQuery(input).val('');
									});
								}
							}
						});

		if (!notAction) {
			jQuery('#ibeInput_optHotel').change(function() {
				jQuery('#bengine').attr('action', lpChangeUrl);
				jQuery.each(inputs, function(index, input) {
					jQuery(input).val('');
				});
				hotelnameChange = true;
			});
		}
	},

	/**
	 * Set Date for Calender
	 *
	 * @param {String}
	 *            tripType
	 */
	setCalenderDate : function(tripType) {
		var depDate = ibeForm.getDepDate();

		var calFirst = jQuery('#' + ibeForm.getCurrentForm() + ' .cal.first');
		if (jQuery(calFirst).val() != depDate) {
			if (jQuery(calFirst).val() == '' || ibeForm.isInit) {
				jQuery(calFirst).val(depDate);
			}
		}
		ibeForm.setDateToInputHidden(jQuery(calFirst).val(), calFirst);

		var calLast = jQuery('#' + ibeForm.getCurrentForm()
				+ ' .cal:not(".first")');
		var retDate = ibeForm.getRetDate();
		if (jQuery(calLast).val() != retDate) {
			if (jQuery(calLast).val() == '' || ibeForm.isInit) {
				jQuery(calLast).val(retDate);
			}
		}
		ibeForm.setDateToInputHidden(jQuery(calLast).val(), calLast);
	},

	setCalenderLabel : function(triptype) {
		var labelArray = [];
		if (typeof ibeForm.switchFormParams.calendarLabel[triptype] == 'undefined') {
			labelArray = ibeForm.switchFormParams.calendarLabel['package'];
		} else {
			labelArray = this.switchFormParams.calendarLabel[triptype];
		}

		var calFirstId = jQuery('#' + ibeForm.getCurrentForm() + ' .cal.first')
				.attr('id');
		var calLastId = jQuery(
				'#' + ibeForm.getCurrentForm() + ' .cal:not(".first")').attr(
				'id');
		var calFirstLabel = jQuery('label[for="' + calFirstId + '"]');
		var calLastLabel = jQuery('label[for="' + calLastId + '"]');
		if (jQuery(calFirstLabel).html() != labelArray[0]) {
			jQuery(calFirstLabel).html(labelArray[0]);
		}
		if (jQuery(calLastLabel).html() != labelArray[1]) {
			jQuery(calLastLabel).html(labelArray[1]);
		}
	},

	/**
	 * Set min retDate by depDate
	 *
	 * @param {Mixed}
	 *            tripType
	 * @param {Object}
	 *            calElement
	 */
	setCalenderRetMinDate : function(tripType, calElement) {
		if (typeof tripType == 'object') {
			try {
				var minDate = jQuery.datepicker
						.parseDate(this.calenderOptions.dateFormat, jQuery(
								tripType).val());
			} catch (e) {
				var minDate = jQuery(tripType).val();
			}

			minDate = minDate.getTime();

			var days 	   = this.getDateDifference(this.getCurrentTripType());
			var selectDate = minDate.valueOf() + 86400000 * (days);
		} else {
			if (jQuery('#deeplinkDiv').length > 0) {
				if (jQuery("input[id$='ibeInput[depDate]']").length > 0) {
					try {
						var minDate = jQuery.datepicker.parseDate(this.calenderOptions.dateFormat, jQuery("input[id$='ibeInput[depDate]']").val());
					} catch (e) {
						var minDate    = this.getDepDate(true).getTime();
					}
				}
				
				var depDate    = ibeForm.getDepDate();
				var days 	   = this.getDateDifference(this.getCurrentTripType());
				var selectDate = minDate.valueOf() + 86400000 * (days);
			} else {
				var minDate    = this.getDepDate(true).getTime();
				var selectDate = this.getRetDate(true).getTime();
			}
		}

		minDate    = minDate + 86400000;
		minDate    = new Date(minDate);
		selectDate = new Date(selectDate);

		jQuery(calElement).datepicker(
				'setDate',
				jQuery.datepicker.formatDate(this.calenderOptions.dateFormat,
						selectDate));
		this.setDateToInputHidden(jQuery.datepicker.formatDate(
				this.calenderOptions.dateFormat, selectDate), calElement);

		jQuery(calElement).datepicker('option', 'minDate', minDate);
	},

	/**
	 * Set Date to Hidden Field from form
	 *
	 * @param {String}
	 *            dateText
	 * @param {Object}
	 *            cal
	 */
	setDateToInputHidden : function(dateText, cal) {
		if (this.getCurrentTripType() == 'hotel') {
			var hiddenDate = dateText;
		} else {
			var dateObject = jQuery.datepicker.parseDate(
					this.calenderOptions.dateFormat, dateText);
			var hiddenDate = jQuery.datepicker.formatDate(
					this.calenderOptions.dateHiddenFormat, dateObject);
		}
		/**
		 * get Form hidden input where cal in
		 */
		var currentFormHiddenElement = jQuery(cal).parents('form').find(
				"input[type=hidden][name$='" + jQuery(cal).attr('id') + "']");

		jQuery(currentFormHiddenElement).val(hiddenDate);
	},

	/**
	 * setOption for field #ibeInput_dest if no options set or no object selct
	 * option from switchFormParams
	 *
	 * @param {Object}
	 *            options [optional]
	 */
	setDestination : function(options) {
		var firstOption = null;
		var selectedOption = '-1';

		if (jQuery('#ibeInput_dest').length > 0) {
			if (jQuery('#ibeInput_dest option:first').length > 0
					&& jQuery('#ibeInput_dest option:first').attr('value') != '-1') {
				firstOption = jQuery('#ibeInput_dest option:first').clone();
			}
			if (this.selectedDefaultDest == null
					&& jQuery('#ibeInput_dest').val() != '') {
				this.selectedDefaultDest = jQuery('#ibeInput_dest').val();

			}

			if (!options && typeof options != 'object') {
				options = this.getDestinationOptions();
			}
			if (options === this.defaultDestination) {
				var dest = jQuery('#ibeInput_dest').empty();

				if (jQuery(options[0]).attr('value') == '') {
					jQuery(options[0]).attr('value', '-1');
				} else if (jQuery(options[0]).attr('value') != '-1') {
					//
				}
				jQuery(dest).append(options);

				if (this.getPortFromInputHidden() == '652') {
					return this.setDestinationSearch(dest);
				}

				if (this.selectedDefaultDest !== '') {
					jQuery('#ibeInput_dest').val(this.selectedDefaultDest);
				} else {
					jQuery('#ibeInput_dest option:first').attr('selected',
							'selected');

				}
				return;
			}
			if (this.getPortFromInputHidden() == '655') {
				return this.setDestinationVacationhome(options);
			}

			if (this.getPortFromInputHidden() == '653') {
				firstOption = jQuery('#ibeInput_dest').find(
						'option[value="' + this.selectedDefaultDest + '"]')
						.clone();
				jQuery(
						'#ibeInput_dest option[value="'
								+ this.selectedDefaultDest + '"]').attr(
						'selected', 'selected');
				var dest = jQuery('#ibeInput_dest').empty();
				return this.setDestinationEarth(options, firstOption, dest);
			}
		}

	},

	setDestinationVacationhome : function(options) {
		var dest = jQuery('#ibeInput_dest').empty();
		ibeForm.addOption(dest, new Option('-- beliebig --', '-1'));
		jQuery.each(options, function(value, option) {
			ibeForm.addOption(dest, new Option(option, value));
		});
		return;

	},
	setDestinationSearch : function(dest) {
		var searchTerm = jQuery(dest).find(
				'option[value="' + this.selectedDefaultDest + '"]').html()
				.replace('&amp;', '&');
		var options = jQuery(dest).find('option');

		jQuery.each(options, function(index, option) {

			if (jQuery(option).html().match(searchTerm) != null) {
				jQuery(dest).find(
						'option[value="' + jQuery(option).attr('value') + '"]')
						.attr('selected', 'selected');
				return;
			}
		});

	},

	setDestinationEarth : function(options, firstOption, dest) {
		if (typeof earthDest == 'undefined' || earthDest == '') {
			if (firstOption !== null && jQuery(firstOption).val() != '-1'
					&& firstOption.length) {
				if (jQuery(firstOption).html() !== '-- beliebig --') {
					ibeForm.addOption(dest, new Option(jQuery(firstOption)
							.html().replace('&amp;', '&'), jQuery(firstOption)
							.attr('value')));
					selectedOption = jQuery(firstOption).val();
				}
			}
		} else {
			selectedOption = earthDest;
		}
		ibeForm.addOption(dest, new Option('-- beliebig --', '-1'));

		optionsArray = this.sortSelected(options);

		for ( var i = 0, len = optionsArray.length; i < len; i++) {
			var option = optionsArray[i];
			ibeForm.addOption(dest, new Option(option.name, option.destId));
		}

		if (typeof selectedOption !== 'object'
				&& typeof selectedOption !== 'undefined') {
			jQuery('#ibeInput_dest option[value="' + selectedOption + '"]')
					.attr('selected', 'selected');
		}
	},

	/**
	 * Set Port to hidden input
	 *
	 * @param {string}
	 *            tripType
	 */
	setPortToInputHidden : function() {
		var tripType = this.getCurrentTripType();
		if (!isNaN(parseInt(tripType))) {

			jQuery.each(ibeForm.switchFormParams.ports, function(name, port) {
				if (tripType == port) {
					tripType = name;
					ibeForm.setTripTypeToInputHidden(tripType);
					return;
				}
			});
		}
		if (typeof this.switchFormParams.ports[tripType] == 'undefined') {
			var currentPort = this.switchFormParams.ports['standard'];
		} else {
			var currentPort = this.switchFormParams.ports[tripType];
		}
		jQuery(
				'#' + this.getCurrentForm()
						+ " input[type=hidden][name$='ibeInput[port]']").val(
				currentPort);
	},

	/**
	 * Set options for select ibeInput[optRoom] if no options set select options
	 * from switchFormParams
	 *
	 * @param {Object}
	 *            options [optional]
	 */
	setRoomType : function(options) {
		var selected = jQuery("select[name$='ibeInput[optRoom]']").val();
		jQuery("select[name$='ibeInput[optRoom]']").empty();
		if (options && typeof options == 'object') {
			jQuery.each(options, function(value, option) {
				jQuery("select[name$='ibeInput[optRoom]']").append(
						new Option(option, value));
			});
		} else if (typeof this.switchFormParams.roomtype[this
				.getCurrentTripType()] != 'undefined') {
			jQuery("select[name$='ibeInput[optRoom]']").append(
					new Option('-- beliebig --', '-1'));
			jQuery.each(this.switchFormParams.roomtype[this
					.getCurrentTripType()], function(index, option) {
				jQuery("select[name$='ibeInput[optRoom]']").append(
						new Option(option, index));
			});
		} else {
			jQuery("select[name$='ibeInput[optRoom]']").append(
					ibeForm.defaultRoomtype);
		}
		if (typeof selected != 'undefined' && selected != '-1') {
			return jQuery("select[name$='ibeInput[optRoom]']").val(selected);
		}
		jQuery("select[name$='ibeInput[optRoom]'] :first").attr('selected',
				'selected');
	},

	/**
	 * set selected triptype to input hidden
	 */
	setTripTypeToInputHidden : function(tripType) {
		if (!tripType) {
			jQuery(
					'#' + this.getCurrentForm()
							+ " input[type=hidden][name$='traveltype']").val(
					this.getCurrentTripType());
			return;
		}
		jQuery(
				'#' + this.getCurrentForm()
						+ " input[type=hidden][name$='traveltype']").val(
				tripType);
	},

	sortSelected : function(options) {
		var optionsArray = [];

		for ( var destId in options) {
			optionsArray.push({
				destId : destId,
				name : options[destId]
			});
		}
		optionsArray.sort(this.sortWithGermanLetters);

		return optionsArray;
	},

	sortWithGermanLetters : function(a, b) {
		a = a.name.replace(/^Ä/, 'A').replace(/^Ö/, 'O').replace(/^Ü/, 'U')
				.replace(/^ß/, 's');
		b = b.name.replace(/^Ä/, 'A').replace(/^Ö/, 'O').replace(/^Ü/, 'U')
				.replace(/^ß/, 's');

		if (a < b) {
			return -1;
		}

		if (a > b) {
			return 1;
		}

		return 0;
	}
};
