﻿/*** 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;
	};
}


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], 10);
		month = parseInt(matches[2], 10);
		year = parseInt(matches[3], 10);
		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], 10);
			month = parseInt(matches[2], 10);
			year = parseInt(matches[3], 10);
			result = new Date(year, month - 1, day);
//		} else { // andere
		}
	}
	return result;
}





///*########################################################################*/
///*### 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();
	}
}

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);
			}
		},

		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();
			}
		},

		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();
				}
			}
		},

		leftPickerSelected: function (obj, newValue, oldValue) {
			this.fire_datechange(newValue, oldValue, "left");
			this.setLeftDate(newValue, oldValue);
		},

		rightPickerSelected: function (obj, newValue, oldValue) {
			this.fire_datechange(newValue, oldValue, "right");
			this.setRightDate(newValue, oldValue);
		},

		onSaveSuccess: function (result, userContext, methodName) {
			if (result) {
				//Sys.WebForms.PageRequestManager.getInstance().beginAsyncPostBack();
			}
		},

		pickerClose: function (obj, event) {
			if (typeof SAS !== "undefined") {
				SAS.SetSearchDate(this.LeftDatePicker.getValue(), this.RightDatePicker.getValue(), this.onSaveSuccess, onCallbackError, this);
			}
			this.hide();
		},

		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();
		},

		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
			});

			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
			});

			this.AcceptButton = new Ext.Button({
				cls: 'dpx2_accept_btn',
				icon: '/Sites/Usedom/img/btn_daten_uebernehmen.gif',
				iconAlign: 'left',
				text: '<div style="width: 119px; height: 19px;"></div>'
			});

			this.CloseButton = new Ext.Button({
				icon: '/Sites/Usedom/img/dp-fenster-zu.png',
				iconAlign: 'right',
				text: '<div style="width: 127px; height: 23px;"></div>'
			});

			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;'
			});

			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;'
			});

			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);
					}
				},
				// tools: [ { id: 'close', handler: this.pickerClose, scope: this }],
				// title: '',
				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: "Anreisetag", x: 20, y: 40 }),
					new Ext.BoxComponent({ html: "Abreisetag", x: 215, y: 40 }),
					this.LeftDatePicker,
					this.RightDatePicker,
					new Ext.BoxComponent({ html: "Schulferien anzeigen:", x: 20, y: 230 }),
					this.BundesCombo,
					this.VacationCombo,
					this.FooterPanel
				]
			});

		}

	});

}



/*########################################################################*/
/*### Routinen für ExtJS-Componenten, die im ASP eingebunden werden ######*/
/*########################################################################*/
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_setDate(edtb, date) {
	var d = asDate(date).dateFormat(_sas_date_format);
	edtb.dateVal.dom.value = d;
}


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 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 xftOnFromDateChanged(obj, newValue, oldValue) {
	if (newValue !== oldValue) {
		xtf_setValue(this, getNights(newValue, this.toEDTB.dateBox.getValue()));
	}
}


function xftOnToDateChanged(obj, newValue, oldValue) {
	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/Usedom/img/Kalender.gif' });
		}
	} else {
		alert("registerEDTB(): unbekanntes Objekt(" + edtb + ")");
	}
	return d;
}


function LinkDPx2ToEDTBs(dpx2, fromEDTB, toEDTB) {
	if (dpx2 === null) {
		alert("kein dpx2");
		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 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);
}


//--- Usedom spezifisch ---
function triggerUpdate(edtb_from, edtb_to) {
	var f = registerEDTB(edtb_from);
	var t = registerEDTB(edtb_to);
	if (f && t) {
		var oldTo = EDTB_getDate(t);
		EDTB_DPx2_Changed(EDTB_getDate(f), null, f);
		EDTB_DPx2_Changed(oldTo, null, t);
	}
}

function buildSelect(sel, days, selIdx) {
	if (sel && "number" === typeof days) {
		var opt, txt, idx, i;
		idx = "number" === typeof (selIdx) && !isNaN(selIdx) ? selIdx : sel.options.selectedIndex;
		idx = Math.max(0, Math.min(idx, days - 1));
		sel.innerHTML = "";
		opt = document.createElement("option");
		txt = document.createTextNode("bitte wählen");
		opt.appendChild(txt);
		if (0 === idx) {
			opt.setAttribute("selected", "selected");
		}
		sel.appendChild(opt);

		for (i = 2; i <= days; ++i) {
			opt = document.createElement("option");
			txt = document.createTextNode(i.toString() + " Tage");
			opt.appendChild(txt);
			if (i - 1 === idx) {
				opt.setAttribute("selected", "selected");
			}
			sel.appendChild(opt);
		}
	}
}

function onDatechange() {
	var n = getNights(this.LeftDatePicker.getValue(), this.RightDatePicker.getValue());
	var s = Ext.get('select_container');
	if (s) {
		s = s.first();
		v = s.next();
		buildSelect(s.dom, n, parseInt(v.dom.value));
	}
}

/*-- "Dauer des Aufenthalts" in HiddenField speichern --*/
function updateDuration(sel) {
	var o = Ext.get(sel);
//	var p = o.parent();
//	var l = p.last();
	var n = o.next();
	n.dom.value = sel.options.selectedIndex;
}

