$(document).ready( function () { 	
	calendar.setSettings();	
});



		var calendar = {
			setSettings: function () {

				var myDate = new Date();

				$.datepicker.setDefaults( {
						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: "+4d",
						defaultDate: +7,
						changeMonth: false,
						changeYear: false,
						showStatus: false,
						statusForDate: describeDate,
						initStatus: this.title,
						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);
						}
					}); 

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

			}
		}
		
		

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

	function reDefineDatePickers(v1,v2){

		var dateParts=v2.split('.');
		var mydate = dateParts[1] + '/' + dateParts[0] + '/' + dateParts[2];
		mydate = DateAdd(mydate, "D", 1);
		var curDate=new Date(mydate);

		if(v1.indexOf('von')!=-1) {
            // prepare data to compare the both dates wich are depends on each other
            var localv1 = v1;
            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;
            }

			$("#" + v1.replace(/von/gi,'nach')).datepicker("destroy")
			$("#" + v1.replace(/von/gi,'nach')).datepicker({
				 minDate: $("#"+v1).datepicker("getDate")
			})
            // used for the second return flight date field
			$("#" + v1.replace(/von/gi,'nach2')).datepicker("destroy")	
			$("#" + v1.replace(/von/gi,'nach2')).datepicker({
				 minDate: $("#"+v1).datepicker("getDate")
			})

                // update second date field only if the first date higher or equals to the second one
            if (firstDateMS >= secondDateMS) {
                $("#" + v1.replace(/von/gi,'nach')).val(twoNum(curDate.getDate()) + '.' + twoNum(eval(1+curDate.getMonth())) + '.' + curDate.getFullYear());
                    // used for the second return flight date field
                $("#" + v1.replace(/von/gi,'nach2')).val(twoNum(curDate.getDate()) + '.' + twoNum(eval(1+curDate.getMonth())) + '.' + curDate.getFullYear());
            }
		}
	}

	function setHiddenDateFields(id, val) {

		if (id.substr(0,9) == 'datefrom_') {
			var dateArray = val.split('.');
			if (dateArray.length == 3) {

                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]);
                }}}
	}


	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(){
		$('#ui-datepicker-div > div:first').html('<p>' + $("#ui-datepicker-div").attr('title') + '</p>'+'<p style="position: relative; width:370px !important; text-align:right; right: 5px; top:-3px !important;font-weight:bold;font-size:11px;white-space: nowrap;"><a style="color: #555555;text-decoration:underline;" onclick="jQuery.datepicker._hideDatepicker();">'+aoe_labels['form.close']+'</a> &#187;</p>');
		//$('#ui-datepicker-div > div:first').html('<p>' + $("#ui-datepicker-div").attr('title') + '</p><p style="position: absolute; left: 273px;_left: 266px;*left:266px;font-weight:bold;font-size:11px;white-space: nowrap;"><a style="color: #555555;text-decoration:underline;" onclick="jQuery.datepicker._hideDatepicker();">'+aoe_labels['form.close']+'</a> &#187;</p>');
	}
	function aoeRemoveBadDiv() {
		if (aoeRemoveStaticDiv != '') {
			$("#"+aoeRemoveStaticDiv).remove();
			aoeRemoveStaticDiv = '';
		}
	}
	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'));
 }
}


var aoe_labels = {
	'form.loading': 	'wird geladen',
	'form.close': 		'Kalender schließen',
	'month.full.january': 	'Januar',
	'month.full.february': 	'Februar',
	'month.full.march': 	'März',
	'month.full.april': 	'April',
	'month.full.may': 	'Mai',
	'month.full.june': 	'Juni',
	'month.full.july': 	'Juli',
	'month.full.august': 	'August',
	'month.full.september': 'September',
	'month.full.october': 	'Oktober',
	'month.full.november': 	'November',
	'month.full.december': 	'Dezember',
	
	'month.short.january': 	'Jan',
	'month.short.february': 'Feb',
	'month.short.march': 	'Mär',
	'month.short.april': 	'Apr',
	'month.short.may':	'Mai',
	'month.short.june': 	'Jun',
	'month.short.july': 	'Jul',
	'month.short.august': 	'Aug',
	'month.short.september':'Sep',
	'month.short.october': 	'Okt',
	'month.short.november': 'Nov',
	'month.short.december': 'Dez',
		
	'day.full.monday': 	'Montag',
	'day.full.tuesday': 	'Dienstag',
	'day.full.wednesday': 	'Mittwoch',
	'day.full.thursday': 	'Donnerstag',
	'day.full.friday': 	'Freitag',
	'day.full.saturday': 	'Samstag',
	'day.full.sunday': 	'Sonntag',
		
	'day.short.monday': 	'Mo',
	'day.short.tuesday': 	'Di',
	'day.short.wednesday': 	'Mi',
	'day.short.thursday': 	'Do',
	'day.short.friday': 	'Fr',
	'day.short.saturday': 	'Sa',
	'day.short.sunday': 	'So',
	
	'date.format':		'dd.mm.yy'
};
