﻿/*** IE9 hat kein "createContextualFragment" ***/
/*### http://www.sencha.com/forum/showthread.php?125869-Menu-shadow-probolem-in-IE9&p=579336 ###*/
if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment) {
	Range.prototype.createContextualFragment = function (html) {
		var frag = document.createDocumentFragment(),
		div = document.createElement("div");
		frag.appendChild(div);
		div.outerHTML = html;
		return frag;
	};
}

/*########################################################################*/
/*### zwei Popup-Kalender für Auswahl der Ankunft- und Abfahrtszeit ######*/
/*########################################################################*/
var _sas_isEN = ("string" === typeof _sas_language) && (_sas_language === "en");
var _sas_date_format = _sas_isEN ? "d/m/Y" /* englisches Datum in UK-Schreibweise */ : "d.m.Y";

function toggle_dpx2(obj) { // {{{
	var vis = obj.isVisible();
	if (vis) {
		obj.hide();
	} else {
		obj.setPosition(obj.x, obj.y);
		obj.show();
	}
} // }}} toggle_dpx2



if ("undefined" != typeof Ext) DatePickerX2 = Ext.extend(Ext.Panel, { // {{{
	DATECHANGE: "datechange",
	LeftDatePicker: null,
	RightDatePicker: null,
	VacationCombo: null,
	BundesCombo: null,
	AcceptButton: null,
	CloseButton: null,

	fire_datechange: function (newValue, oldValue, side) { // {{{
		if (newValue != oldValue) {
			this.fireEvent(this.DATECHANGE, newValue, oldValue, side);
		}
	}, // }}} fire_datechange

	setLeftDate: function (newValue, oldValue) { // {{{
		if (Ext.isDate(newValue)) {
			oldValue = oldValue || this.LeftDatePicker.getValue();
			this.LeftDatePicker.setValue(newValue);
			this.fire_datechange(newValue, oldValue, "left");
			this.setRightDate(newValue.add(Date.DAY, 7));
			this.LeftDatePicker.focus();
		}
	}, // }}} setLeftDate

	setRightDate: function (newValue, oldValue) { // {{{
		if (Ext.isDate(newValue)) {
			oldValue = oldValue || this.RightDatePicker.getValue();
			this.RightDatePicker.setValue(newValue);
			this.fire_datechange(newValue, oldValue, "right");
			var rel = newValue.getElapsed();
			var lel = this.LeftDatePicker.getValue().getElapsed();
			if (rel < lel) {
				this.setLeftDate(newValue);
				this.RightDatePicker.focus();
			}
		}
	}, // }}} setRightDate

	leftPickerSelected: function (obj, newValue, oldValue) { // {{{
		this.fire_datechange(newValue, oldValue, "left");
		this.setLeftDate(newValue, oldValue);
	}, // }}} leftPickerSelected

	rightPickerSelected: function (obj, newValue, oldValue) { // {{{
		this.fire_datechange(newValue, oldValue, "right");
		this.setRightDate(newValue, oldValue);
	}, // }}} rightPickerSelected

	onSaveSuccess: function (result, userContext, methodName) { // {{{
		if (result) {
			//Sys.WebForms.PageRequestManager.getInstance().beginAsyncPostBack();
		}
	}, // }}} onSaveSuccess

	pickerClose: function (obj, event) { // {{{
		if (typeof SAS != "undefined") {
			SAS.SetSearchDate(this.LeftDatePicker.getValue(), this.RightDatePicker.getValue(), this.onSaveSuccess, onCallbackError, this);
		}
		this.hide();
	}, // }}} pickerClose

	bundeslandGewaehlt: function (combo, record, index) { // {{{
		//this.VacationCombo.emptyText = index > 0 ? 'bitte Ferien wählen...' : '<-- kein Bundesland gewählt';
		this.VacationCombo.store.loadData(__Ferien[record.id]);
		//this.store.reset();
	}, // }}} bundeslandGewaehlt

	vacationSelected: function (combo, record, index) { // {{{
		var dur = record.get('Duration');
		var reg = /(\d+\.\d+\.\d+)-(\d+\.\d+\.\d+)/;
		var erg = reg.exec(dur);
		if (erg || erg.length < 3) {
			var fromDate = readDate(erg[1]);
			var now = new Date();
			if (now.getFullYear() > fromDate.getFullYear() || now.getFullYear() == fromDate.getFullYear() && (now.getMonth() > fromDate.getMonth() || now.getMonth() == fromDate.getMonth() && now.getDate() > fromDate.getDate())) { // kein Datum in der Vergangenheit annehmen
				fromDate = new Date(now.getFullYear, now.getMonth(), now.getDate());
			}
			var toDate = readDate(erg[2]);
			this.setLeftDate(fromDate);
			this.setRightDate(toDate);
		} else {
			//alert('falsches Datum in der Ferien-Datenbank');
		}
	}, // }}}

	constructor: function (config) { /// {{{
		Ext.apply(this, config);

		this.BundesCombo = new Ext.form.ComboBox({ // {{{
			displayField: 'landesName',
			emptyText: _sas_isEN ? 'Holidays for State' : 'Ferien für Bundesland...',
			forceSelection: true,
			lazyRender: true,
			mode: 'local',
			store: new Ext.data.ArrayStore({
				data: __Bundeslaender,
				fields: [
						{ name: 'id' },
						{ name: 'landesName' }
					],
				idIndex: 0
			}),
			triggerAction: 'all',
			typeAhead: true,
			valueField: 'id',
			height: 20,
			width: 181,
			x: 20,
			y: 250
		}); // }}} BundesCombo

		this.VacationCombo = new Ext.form.ComboBox({ // {{{
			displayField: 'Name',
			emptyText: _sas_isEN ? 'Please select vacation' : 'bitte Ferien wählen...',
			forceSelection: true,
			lazyRender: true,
			mode: 'local',
			store: new Ext.data.ArrayStore({
				data: __Ferien[0],
				fields: [
						{ name: 'Name' },
						{ name: 'Duration' }
					],
				idIndex: 1
			}),
			triggerAction: 'all',
			typeAhead: true,
			valueField: 'Duration',

			height: 20,
			width: 181,
			x: 215,
			y: 250
		}); // }}} VacationCombo

		this.AcceptButton = new Ext.Button({ // {{{
			cls: 'dpx2_accept_btn',
			icon: '/Sites/SAS/gfx/Pfeil_einzeln_weiß.gif',
			iconAlign: 'left',
			text: _sas_isEN ? 'Accept data' : 'Daten &uuml;bernehmen'
		}); // }}} AcceptButton

		this.CloseButton = new Ext.Button({ // {{{
			icon: '/Sites/SAS/gfx/close.gif',
			iconAlign: 'right',
			text: _sas_isEN ? 'Close window&nbsp;&nbsp;' : 'Fenster schlie&szlig;en&nbsp;&nbsp;'
		}); // }}} CloseButton

		this.HeaderPanel = new Ext.Container({ // {{{
			cls: 'dpx2_title_panel',
			height: 21,
			items: [this.CloseButton],
			width: 420,
			x: 0,
			y: 0
		}); // }}}

		this.FooterPanel = new Ext.Container({ // {{{
			cls: 'dpx2_footer_panel',
			height: 21,
			items: [this.AcceptButton],
			width: 420,
			x: 0,
			y: 300
		}); // }}}

		var now = new Date();
		var next_year = new Date();
		var now_year = now.getFullYear();
		next_year.setFullYear(now_year + 1);

		this.LeftDatePicker = new Ext.DatePicker({ // {{{
			minDate: now,
			maxDate: next_year,
			listeners: {
				'select': {
					fn: this.leftPickerSelected,
					scope: this
				}
			},
			showToday: false,
			x: 20,
			y: 60,
			style: 'border: solid 1px #b9cfe4;'
		}); // }}} LeftDatePicker

		this.RightDatePicker = new Ext.DatePicker({ // {{{
			minDate: now,
			maxDate: next_year,
			listeners: {
				'select': {
					fn: this.rightPickerSelected,
					scope: this
				}
			},
			showToday: false,
			x: 215,
			y: 60,
			style: 'border: solid 1px #b9cfe4;'
		}); // }}} RightDatePicker

		this.BundesCombo.addListener("select", this.bundeslandGewaehlt, this);
		this.VacationCombo.addListener("select", this.vacationSelected, this);
		this.AcceptButton.addListener("click", this.pickerClose, this);
		this.CloseButton.addListener("click", this.pickerClose, this);

		this.addEvents(this.DATECHANGE);

		DatePickerX2.superclass.constructor.call(this, { // {{{
			width: 420,
			height: 340,
			layout: 'absolute',
			renderTo: Ext.get('_calenderContainer'),
			floating: true,
			draggable: { // {{{
				// Config option of Ext.Panel.DD class.
				// It's a floating Panel, so do not show a placeholder proxy in the original position.
				insertProxy: false,
				// Called for each mousemove event while dragging the DD object.
				onDrag: function (e) {
					// Record the x,y position of the drag proxy so that we can
					// position the Panel at end of drag.
					var pel = this.proxy.getEl();
					this.x = pel.getLeft(true);
					this.y = pel.getTop(true);

					// Keep the Shadow aligned if there is one.
					var s = this.panel.getEl().shadow;
					if (s) {
						s.realign(this.x, this.y, pel.getWidth(), pel.getHeight());
					}
				},
				// Called on the mouseup event.
				endDrag: function (e) {
					this.panel.setPosition(this.x, this.y);
				}
			}, // }}} draggeble
			items: [ // {{{
			//new Ext.BoxComponent({ html: "<div style='background: url(/Sites/SAS/gfx/fensterSchliessen_verlauf.gif); background-repeat: repeat:x; height: 100%; width: 100%;'></div>", height: 21, width: 420, x: 0, y: 0 }),
			// this.CloseButton, // new Ext.BoxComponent({ html: "Fenster schließen", x: 302, y: 5 }),
				this.HeaderPanel,
				new Ext.BoxComponent({ html: _sas_isEN ? "Arrival" : "Anreisetag", x: 20, y: 40 }),
				new Ext.BoxComponent({ html: _sas_isEN ? "Departure" : "Abreisetag", x: 215, y: 40 }),
				this.LeftDatePicker,
				this.RightDatePicker,
				new Ext.BoxComponent({ html: _sas_isEN ? "School holidays:" : "Schulferien anzeigen:", x: 20, y: 230 }),
				this.BundesCombo,
				this.VacationCombo,
				this.FooterPanel
			//this.AcceptButton
			]/*, // }}} items
			tools: [{ // {{{
				id: 'close',
				handler: this.pickerClose,
				scope: this
			}], // }}} tools
			title: ''*/
		}); // }}} superclass.constructor

	} // }}} constructor

}); // }}} DatePickerX2



/*########################################################################*/
/*### Routinen für ExtJS-Componenten, die im ASP eingebunden werden ######*/
/*########################################################################*/
function readDate(dateStr) { // {{{
	var day, month, year, result, regex, matches;
	result = null;
	regEx = /0?(\d+)\.0?(\d+)\.(\d\d+)/; // deutsche Schreibweise parsen
	matches = regEx.exec(dateStr);
	if (matches && matches.length == 4) {
		day = parseInt(matches[1]);
		month = parseInt(matches[2]);
		year = parseInt(matches[3]);
		result = new Date(year, month - 1, day);
	} else {
		regEx = /0?(\d+)\/0?(\d+)\/(\d\d+)/; // englische (UK) Schreibweise parsen
		matches = regEx.exec(dateStr);
		if (matches && matches.length == 4) {
			day = parseInt(matches[1]);
			month = parseInt(matches[2]);
			year = parseInt(matches[3]);
			result = new Date(year, month - 1, day);
		} else { // andere
		}
	}
	return result;
} // }}} readDate


function asDate(dateStr) { // {{{
	if ("string" === typeof dateStr && 0 === dateStr.length) return new Date();
	var d = dateStr;
	if (Ext.isDate(d)) return d;
	d = readDate(dateStr);
	if (Ext.isDate(d)) return d;
	d = new Date(dateStr);
	if (Ext.isDate(d)) return d;
	return new Date();
} // }}}



/*------------------------------------------------------------------------*/
/*--- Event-Routinen -----------------------------------------------------*/
/*------------------------------------------------------------------------*/
function EDTB_DPx2_Changed(newValue, oldValue, edtb) { // {{{
	var o = edtb.dateBox.getValue();
	var n = newValue.dateFormat(_sas_date_format);
	if (n != o) {
		EDTB_setDate(edtb, newValue);
		edtb.dateBox.setValue(n);
		edtb.dateBox.fireEvent("change", edtb.dateBox, n, o);
	}
} // }}}


function EDTB_Left_DPx2_Changed(newValue, oldValue, side) { // {{{
	if (side == "left") {
		EDTB_DPx2_Changed(newValue, oldValue, this);
	}
} // }}}


function EDTB_Right_DPx2_Changed(newValue, oldValue, side) { // {{{
	if (side == "right") {
		EDTB_DPx2_Changed(newValue, oldValue, this);
	}
} // }}}


function DPx2_From_Change(obj, newValue, oldValue) { // {{{
	var n = asDate(newValue);
	var o = asDate(oldValue);
	this.leftPickerSelected(obj, n, o);
	this.setLeftDate(n);
} // }}}


function DPx2_To_Change(obj, newValue, oldValue) { // {{{
	this.rightPickerSelected(obj, readDate(newValue), readDate(oldValue));
	this.setRightDate(readDate(newValue));
} // }}}


function updateDoW(obj, newValue, oldValue) { // {{{
	if (newValue != oldValue || true) {
		var d = asDate(obj.getValue());
		if (!d) d = new Date(d);
		var s = d.dateFormat("l");
		this.dom.innerHTML = s;
	}
} // }}}


function getNights(fromDate, toDate) { // {{{
	var result = 0;
	var f = asDate(fromDate);
	var t = asDate(toDate);
	if (f && t) {
		var ms = f.getElapsed(t);
		result = Math.round(ms / 86400000);
	}
	return result;
} // }}}


function xftOnFromDateChanged(obj, newValue, oldValue) { // {{{ // this: XTF
	if (newValue != oldValue) {
		xtf_setValue(this, getNights(newValue, this.toEDTB.dateBox.getValue()));
	}
} // }}}


function xftOnToDateChanged(obj, newValue, oldValue) { // {{{ // this: XTF
	if (newValue != oldValue) {
		xtf_setValue(this, getNights(this.fromEDTB.dateBox.getValue(), newValue));
	}
} // }}}



/*------------------------------------------------------------------------*/
/*--- Initialisierungs-Routinen ------------------------------------------*/
/*------------------------------------------------------------------------*/
function EDTB_UpdateHiddenValue(evt, el, o) { // {{{
	if (this && this.dateVal) {
		var d = readDate(el);
		if (d) this.dateVal.dom.value = el;
	}
} // }}}

function registerEDTB(edtb) { // {{{
	var d = Ext.get(edtb);
	if (d) {
		if ("undefined" == typeof d.dateBox) {
			d.dateVal = d.first();
			var txt = Ext.get(edtb + "_date");
			var btn = Ext.get(edtb + "_icon");
			d.dateBox = new Ext.form.TextField({ renderTo: txt, height: 17, cls: 'inputTabSearch edtb_text' });
			d.dateBox.addListener("change", EDTB_UpdateHiddenValue, d);
			d.dateBut = new Ext.Button({ renderTo: btn, icon: '/Sites/SAS/gfx/Kalender.gif' });
		}
	} else {
		alert("registerEDTB(): unbekanntes Objekt(" + edtb + ")");
	}
	return d;
} // }}}


function LinkDPx2ToEDTBs(dpx2, fromEDTB, toEDTB) { // {{{
	if (dpx2 == null) {
		dpx2 = new DatePickerX2({ hidden: true });
	}
	var f = registerEDTB(fromEDTB);
	var t = registerEDTB(toEDTB);
	if (dpx2) {
		if (f) {
			dpx2.addListener(dpx2.DATECHANGE, EDTB_Left_DPx2_Changed, f);
			f.dateBox.addListener("change", DPx2_From_Change, dpx2);
			f.dateBut.addListener("click", toggle_dpx2.createCallback(dpx2), dpx2);
		}
		if (t) {
			dpx2.addListener(dpx2.DATECHANGE, EDTB_Right_DPx2_Changed, t);
			t.dateBox.addListener("change", DPx2_To_Change, dpx2);
			t.dateBut.addListener("click", toggle_dpx2.createCallback(dpx2), dpx2);
		}
	}
} // }}}


/// Textbox für die Anzeige des Wochentages
function LinkTextBox2DateBox(tb, db) { // {{{
	var t = Ext.get(tb);
	var d = registerEDTB(db);
	if (t && d) {
		d.dateBox.addListener("change", updateDoW, t);
	}
} // }}}


function onNightsChanged(obj, newValue, oldValue) { // {{{
	this.valueField.dom.value = newValue;
} // }}}


function reg_xtf(xtf, width) { // {{{
	var d = Ext.get(xtf);
	if (d) {
		if ("undefined" == typeof d.valueField) {
			d.valueField = d.first();
		}
		if ("undefined" == typeof d.textField) {
			var config = { renderTo: d, height: 17, cls: 'inputTabSearch edtb_date' };
			if ("number" == typeof width && width > 0) config.width = width;
			d.textField = new Ext.form.TextField(config);
			d.textField.addListener("change", onNightsChanged, d);
		}
	}
	return d;
} // }}}


function xtf_setValue(xft, value) { // {{{
	var d = Ext.get(xft);
	var o = d.textField.getValue();
	if (o != value) {
		d.textField.setValue(value);
		d.valueField.dom.value = value;
		d.textField.fireEvent("change", d.textField, value, o);
	}
} // }}}


function LinkXFT2EDTBs(xft, edtb_from, edtb_to) { // {{{
	var x = reg_xtf(xft);
	if ("object" == typeof x && "undefined" == typeof x.fromEDTB) {
		x.fromEDTB = registerEDTB(edtb_from);
		x.toEDTB = registerEDTB(edtb_to)
		x.fromEDTB.dateBox.addListener("change", xftOnFromDateChanged, x);
		x.toEDTB.dateBox.addListener("change", xftOnToDateChanged, x);
	}
} // }}}


function EDTB_getDate(edtb) { // {{{
	var v = edtb.dateVal.dom.value;
	return asDate(v);
} // }}}


function EDTB_setDate(edtb, date) { // {{{
	var d = asDate(date).dateFormat(_sas_date_format);
	edtb.dateVal.dom.value = d;
} // }}}


//--- SAS spezifisch ---
function triggerUpdate(edtb_from, edtb_to, xtf_nights) { // {{{
	var f = registerEDTB(edtb_from);
	var t = registerEDTB(edtb_to);
	var n = reg_xtf(xtf_nights);
	if (f && t && n) {
		var toDate = EDTB_getDate(t);
		var nights = n.valueField.dom.value;
		EDTB_DPx2_Changed(EDTB_getDate(f), null, f)
		EDTB_DPx2_Changed(toDate, null, t)
		xtf_setValue(xtf_nights, nights);
	}
} // }}}

