﻿(function (d) {

	var b = $.telerik;

	jQuery.telerik.cultureInfo = { "shortDate": "dd.MM.yyyy", "longDate": "d MMMM yyyy 'г.'", "longTime": "H:mm:ss", "shortTime": "H:mm", "fullDateTime": "d MMMM yyyy 'г.' H:mm:ss", "sortableDateTime": "yyyy'-'MM'-'dd'T'HH':'mm':'ss", "universalSortableDateTime": "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "generalDateShortTime": "dd.MM.yyyy H:mm", "generalDateTime": "dd.MM.yyyy H:mm:ss", "monthDay": "MMMM dd", "monthYear": "MMMM yyyy", "days": ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"], "abbrDays": ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"], "shortestDays": ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"], "abbrMonths": ["янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек", ""], "months": ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь", ""], "am": "", "pm": "", "dateSeparator": ".", "timeSeparator": ":", "firstDayOfWeek": 1, "currencydecimaldigits": 2, "currencydecimalseparator": ",", "currencygroupseparator": " ", "currencygroupsize": 3, "currencynegative": 5, "currencypositive": 1, "currencysymbol": "р.", "numericdecimaldigits": 2, "numericdecimalseparator": ",", "numericgroupseparator": " ", "numericgroupsize": 3, "numericnegative": 1, "percentdecimaldigits": 2, "percentdecimalseparator": ",", "percentgroupseparator": " ", "percentgroupsize": 3, "percentnegative": 1, "percentpositive": 1, "percentsymbol": "%" };

	//	$.extend(b.cultureInfo,
	//	{
	//		abbrDays: ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
	//		abbrMonths: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
	//		months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
	//		days: ["Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресение"]
	//	});

	var a = null;
	b.datetime.parseByToken = function (g, i) {

		if (g === null || g === "") {
			return null;
		}

		i = i || new b.datetime();
		var e = null;
		var m = null;
		var k = null;
		var n = 0;

		var f = function (o) {
			var p = null;
			if (o && g.substring(n, n + o.length).toLowerCase() == o.toLowerCase()) {
				p = o
			}
			return p;
		};

		var j = function () {

			var o = null;
			$.each(["days", "abbrDays", "months", "abbrMonths"], function (q, p) {
				if (o !== null) {
					return;
				}
				$.each(b.cultureInfo[p], function (s, r) {
					if (o !== null) {
						return
					}
					o = f(r);
				});
				k = p;
			});
			return o;
		};

		var h = function () {

			var o; var p = function (r, s) {

				i[s ? "date" : "month"](i[s ? "date" : "month"]() + (o != 0 ? ((o + ((o > 0 ? 1 : -1) * r)) % r) : 0) + (m ? (e == b.cultureInfo.next ? 1 : -1) * r : 0))
			};

			var q = $.inArray(m || e, b.cultureInfo[k]);

			if (k.toLowerCase().indexOf("day") > -1) {
				o = (q == 0 ? 7 : q) - i.day();
				p(7, true)
			}
			else {
				o = q - i.month();
				p(12, false)
			}
		};

		var l = function () {

			var p = function (q) {

				var r; switch (m) {

					case "year": r = q == 1 ? 1 : 0; break; case "month": r = q == 2 ? 1 : 0; break; case "week": r = q == 3 ? 7 : 0; break; case "day": r = q == 3 ? 1 : 0; break
				} return r
			}; var o = (e == b.cultureInfo.next ? 1 : -1); i.year(i.year() + p(1) * o, i.month() + p(2) * o, i.date() + p(3) * o)
		}; $.each(["today", "tomorrow", "yesterday", "next", "last"], function (p, o) {
			if (e !== null) {
				return
			} e = f(b.cultureInfo[o])
		});
		if (e !== null) {
			n += e.length;
			if (/[^\s\d]\s+[^\s\d]/i.test(g)) {
				n++; $.each(["year", "month", "week", "day"], function (p, o) {
					if (m !== null) {
						return;
					} m = f(b.cultureInfo[o])
				});
				k = null;
				if (m === null) {
					m = j();
				}
				if (m === null) {
					return null;
				}
			}
			else {
				switch (e) {
					case b.cultureInfo.today: break; case b.cultureInfo.tomorrow: i.date(i.date() + 1); break; case b.cultureInfo.yesterday: i.date(i.date() - 1); break; default: i = null; break
				}
				return i;
			}
		}
		else {
			e = j(); if (e != null) {
				h(); return i
			}
			else {
				return null
			}
		}

		if (k !== null) {
			h();
		}
		else {
			l();
		}
		return i;

	};

	function c(nowDateTime, currentDate, minDate, maxDate) {

		if (currentDate) {
			nowDateTime = new Date(currentDate);
		}

		if (minDate > nowDateTime) {
			nowDateTime = new Date(minDate);
		}
		else {
			if (maxDate < nowDateTime) {
				nowDateTime = new Date(maxDate);
			}
		} return nowDateTime;
	}

	b.dateView = function (settings) {
		$.extend(this, settings);
		this.isValueChanged = false;
		this.focusedValue = c(new Date(), this.selectedValue, this.minValue, this.maxValue);
		this.$calendar = this._createSharedCalendar()
	};

	b.dateView.prototype = {

		_createSharedCalendar: function () {
			if (!a) {
				a = d(b.calendar.html(new b.datetime(this.focusedValue), this.selectedValue ? new b.datetime(this.selectedValue) : null, new b.datetime(this.minValue), new b.datetime(this.maxValue))).hide().addClass("t-popup t-datepicker-calendar").appendTo(document.body).tCalendar({
					selectedValue: this.selectedValue, minDate: this.minValue, maxDate: this.maxValue
				}); b.fx._wrap(a).css("display", "none"); if ($.browser.msie && $.browser.version <= 6) {
					d('<iframe class="t-iframe-overlay" src="javascript:false;"></iframe>').prependTo(a).height(a.height())
				}
			} return a;
		},

		_getCalendar: function () {
			return a.data("tCalendar")
		},

		_reassignSharedCalendar: function () {
			var e = this._getCalendar(); if (a.data("associatedDateView") != this) {
				a.stop(true, true); this.focusedValue = c(this.focusedValue, this.selectedValue, this.minValue, this.maxValue); e.minDate = this.minValue; e.maxDate = this.maxValue; e.selectedValue = this.selectedValue; e.goToView(0, this.focusedValue); a.unbind("change").bind("change", $.proxy(function (h) {
					var g = this.selectedValue; var f = new b.datetime(h.date); if (g !== null) {
						f.hours(g.getHours()).minutes(g.getMinutes()).seconds(g.getSeconds()).milliseconds(g.getMilliseconds())
					} this.onChange(f.toDate())
				}, this)).unbind("navigate").bind("navigate", $.proxy(function (i) {
					var h = this.focusedValue; var f = e.viewedMonth; var g = e.currentView.index; h.setFullYear(f.year(), f.month(), h.getDate()); b.calendar.focusDate(h, g, a, i.direction)
				}, this)).data("associatedDateView", this); if (this.selectedValue) {
					e.value(this.selectedValue)
				} b.calendar.focusDate(this.focusedValue, e.currentView.index, a)
			}
		},

		open: function (e) {
			if (this.isOpened()) {
				return;
			}

			this._reassignSharedCalendar();
			var i = this.isRtl;
			var h = this.$calendar;
			elementPosition = e.offset;
			elementPosition.top += e.outerHeight; if (i) {
				elementPosition.left -= (a.outerWidth() || a.parent().outerWidth()) - e.outerWidth
			}
			b.fx._wrap(a).css($.extend({
				position: "absolute", direction: i ? "rtl" : "", display: a.is(":visible") ? "" : "none"
			},
			elementPosition)); var f = this._getCalendar(); var g = f.currentView.index; if (!a.is(":visible") && f.viewedMonth.value - this.focusedValue != 0) {
				f.goToView(g, this.focusedValue).value(this.selectedValue)
			} b.calendar.focusDate(this.focusedValue, f.currentView.index, a); b.fx._wrap(h).css("zIndex", e.zIndex).show(); b.fx.play(this.effects, h, {
				direction: "bottom"
			})
		},

		close: function () {
			if (this.isOpened()) {
				b.fx.rewind(this.effects, this.$calendar, {
					direction: "bottom"
				},

				function () {
					if (a) {
						b.fx._wrap(a).hide()
					}
				})
			}
		},

		isOpened: function () {
			return a && a.data("associatedDateView") == this && a.is(":visible")
		},

		value: function (e) {
			if (e === undefined) {
				return this.selectedValue
			} var g = e === null; var f = this._getCalendar(); if (!g) {
				e = e.value ? new Date(e.value) : e
			} f.value(e); this.selectedValue = e; if (g) {
				e = new Date()
			} this.focusedValue = new Date(e); b.calendar.focusDate(e, f.currentView.index, a)
		},

		navigate: function (p) {
			if (this.isOpened() && d(".t-overlay", a).length > 0) {
				return
			} var m; var k = false; var o = this.$calendar; var l = this._getCalendar(); var n = l.viewedMonth; var h = l.currentView; var f = h.index; var q = new b.datetime(this.focusedValue); var r = function (e, t, s) {
				if (!d(e, o).hasClass("t-state-disabled")) {
					if ("navigateUp" == t) {
						f += 1
					} m = s || false; l[t](); return true
				} else {
					return false
				}
			};
			var g = function () {
				var e = b.calendar.findTarget(q, f, o, false)[0]; l.navigateDown(p, e, f); f = f == 0 ? 0 : f - 1; m = true
			}; var i = function (e, u, s) {
				var t = !s ? -1 : 1; if (!r(e, u, s)) {
					return false
				} if (f == 0) {
					q.addMonth(t)
				} else {
					q.addYear(t * (f == 1 ? 1 : f == 2 ? 10 : 100))
				} return true
			}; var j = b.datepicker.adjustDate; if (o.is(":visible") && !p.shiftKey) {
				k = true; switch (p.keyCode) {
					case 37: if (p.ctrlKey) {
							if (!i(".t-nav-prev", "navigateToPast")) {
								return
							}
						} else {
							j(f, q, -1, -1); if (h.navCheck(q, n, false)) {
								if (!r(".t-nav-prev", "navigateToPast")) {
									return
								}
							}
						} break; case 38: if (p.ctrlKey) {
							r(".t-nav-fast", "navigateUp")
						} else {
							j(f, q, -7, -4); if (h.navCheck(q, n, false)) {
								if (!r(".t-nav-prev", "navigateToPast")) {
									return
								}
							}
						} break; case 39: if (p.ctrlKey) {
							if (!i(".t-nav-next", "navigateToFuture", true)) {
								return
							}
						} else {
							j(f, q, 1, 1); if (h.navCheck(q, n, true)) {
								if (!r(".t-nav-next", "navigateToFuture", true)) {
									return
								}
							}
						} break; case 40: if (p.ctrlKey) {
							g()
						} else {
							j(f, q, 7, 4); if (h.navCheck(q, n, true)) {
								if (!r(".t-nav-next", "navigateToFuture", true)) {
									return
								}
							}
						} break; case 33: if (!i(".t-nav-prev", "navigateToPast")) {
							return
						} break; case 34: if (!i(".t-nav-next", "navigateToFuture", true)) {
							return
						} break; case 35: q = b.calendar.views[f].firstLastDay(q, false, l); break; case 36: q = b.calendar.views[f].firstLastDay(q, true, l); break; case 13: p.stopPropagation(); if (f == 0) {
							this.onChange(this.focusedValue)
						} else {
							g()
						} break; default: k = false; break
				}
			} if (k) {
				p.preventDefault(); q = b.calendar.fitDateToRange(q, new b.datetime(this.minValue), new b.datetime(this.maxValue)); b.calendar.focusDate(q.toDate(), f, o, m); this.focusedValue = q.toDate()
			}
		}
	}; $.each(["min", "max"], $.proxy(function (f, e) {
		b.dateView.prototype[e] = function (h) {
			var g = e + "Value"; if (h === undefined) {
				return this[g]
			} this[g] = new Date(h.value ? h.value : h); a.data("associatedDateView", null); this._reassignSharedCalendar()
		}
	}, this)); b.datepicker = function (f, g) {
		$.extend(this, g); if (f.nodeName.toLowerCase() !== "input" && f.type.toLowerCase() !== "text") {
			throw "Target element is not a INPUT"
		} this.element = f; var h = this.$element = d(f).addClass("t-input").attr("autocomplete", "off").bind({
			keydown: $.proxy(this._keydown, this), focus: $.proxy(function (l) {
				if (this.openOnFocus) {
					this._open()
				} this.$element.removeClass("t-state-error")
			}, this)
		}); if (!h.parent().hasClass("t-picker-wrap")) {
			h.wrap('<div class="t-widget t-datepicker"><div class="t-picker-wrap"></div></div>'); if (g.showButton) {
				var k = new b.stringBuilder(), i = g.buttonTitle; d(k.cat('<span class="t-select">').cat('<span class="t-icon t-icon-calendar" ').catIf('title="', i).catIf(i, i).cat('"></span></span>').string()).insertAfter(h)
			}
		} this.dateView = new b.dateView({
			selectedValue: this.selectedValue, minValue: this.minValue, maxValue: this.maxValue, effects: this.effects, isRtl: h.closest(".t-rtl").length, onChange: $.proxy(function (l) {
				this._update(l); this._close()
			}, this)
		}); this.dateView.$calendar.bind("click", $.proxy(function (l) {
			l.stopPropagation(); if (l.target.parentNode.className.indexOf("t-state-selected") != -1) {
				this._close()
			}
		}, this)); this.inputValue = h.val(); var e = this.selectedValue || this.inputValue; if (e) {
			this._value(this.parse(e))
		} var j = this.enabled ? $.proxy(this._togglePopup, this) : b.preventDefault; this.$wrapper = h.closest(".t-datepicker").find(".t-icon").bind("click", j).end(); d(document.documentElement).bind("mousedown", $.proxy(function (n) {
			var l = this.$element.val(); if (l != this.inputValue) {
				this._update(l)
			} if (!a) {
				return
			} var m = a.data("associatedDateView"); if (!m || m != this.dateView) {
				return
			} if (!$.contains(this.$wrapper[0], n.target) && !$.contains(a[0], n.target)) {
				this._close()
			}
		}, this)); b.bind(this, {
			open: this.onOpen, close: this.onClose, valueChange: this.onChange, load: this.onLoad
		})
	}; b.datepicker.prototype = {
		_togglePopup: function () {
			if (this.dateView.isOpened()) {
				this._close()
			} else {
				this.element.focus(); this._open()
			}
		}, _close: function () {
			if (!a.is(":animated") && this.dateView.isOpened()) {
				this._trigger("close")
			}
		}, _open: function () {
			if (!this.dateView.isOpened()) {
				this._trigger("open")
			}
		}, _trigger: function (e) {
			if (!b.trigger(this.element, e)) {
				this[e]()
			}
		}, _update: function (f) {
			f = this.parse(f); if (f != null) {
				if (f - this.minValue <= 0) {
					f = this.minValue
				} else {
					if (f - this.maxValue >= 0) {
						f = this.maxValue
					}
				}
			} var e = this.selectedValue, i = e ? b.datetime.format(e, this.format) : "", h = f ? b.datetime.format(f, this.format) : ""; this._value(f); if (h != i) {
				var g = {
					previousValue: e, value: f, previousDate: e, date: f
				}; if (b.trigger(this.element, "valueChange", g)) {
					this._value(e)
				}
			}
		}, _keydown: function (g) {
			var f = g.keyCode; if (f == 9 || (f == 13 && this.inputValue != this.$element.val())) {
				this._update(this.$element.val()); this._close()
			} else {
				if (f == 27) {
					this._close()
				} else {
					if (g.altKey) {
						if (f == 40) {
							this._open()
						} else {
							if (f == 38) {
								this._close()
							}
						}
					} else {
						this.dateView.navigate(g)
					}
				}
			}
		}, enable: function () {
			this.$element.attr("disabled", false); this.$wrapper.removeClass("t-state-disabled").find(".t-icon").unbind("click").bind("click", $.proxy(this._togglePopup, this))
		}, disable: function (f) {
			this.$element.attr("disabled", true); this.$wrapper.addClass("t-state-disabled").find(".t-icon").unbind("click").bind("click", b.preventDefault)
		}, _value: function (e) {
			var g = this.$element.val(); var f = e === null; this.selectedValue = e; this.dateView.value(e); if (!f) {
				g = b.datetime.format(e, this.format)
			} this.inputValue = g; this.$element.toggleClass("t-state-error", f && g != "").val(g)
		}, value: function (e) {
			if (e === undefined) {
				return this.selectedValue
			} var f = this.parse(e); f = b.datepicker.isInRange(f, this.minValue, this.maxValue) ? f : null; if (f === null) {
				this.$element.removeClass("t-state-error").val("")
			} this._value(f); return this
		}, showPopup: function () {
			this.open()
		}, hidePopup: function () {
			this.close()
		}, open: function () {
			var e = this.$element; this.dateView.open({
				offset: e.offset(), outerHeight: e.outerHeight(), outerWidth: e.outerWidth(), zIndex: b.getElementZIndex(e[0])
			})
		}, close: function () {
			this.dateView.close()
		}, parse: function (e, g) {
			if (e === null || e.getDate) {
				return e
			} var f = b.datetime.parse({
				value: e, format: g || this.format, shortYearCutOff: this.shortYearCutOff
			}); return f != null ? f.toDate() : null
		}
	}; $.each(["min", "max"], $.proxy(function (f, e) {
		b.datepicker.prototype[e] = function (g) {
			var i = e + "Value"; if (g === undefined) {
				return this[i]
			} var j = this.parse(g); if (j !== null) {
				var h = this[i]; this[i] = j; if (this.minValue > this.maxValue) {
					this[i] = h; return
				} this.dateView[e](j); if (!b.datepicker.isInRange(this.selectedValue, this.minValue, this.maxValue)) {
					this.value(j)
				}
			}
		}
	}, this)); $.extend(b.datepicker, {
		adjustDate: function (e, h, g, f) {
			if (e == 0) {
				b.datetime.modify(h, b.datetime.msPerDay * g)
			} else {
				if (e == 1) {
					h.addMonth(f)
				} else {
					h.addYear((e == 2 ? f : 10 * f))
				}
			}
		}, isInRange: function (g, e, f) {
			if (!g) {
				return false
			} return e - g <= 0 && f - g >= 0
		}
	}); $.fn.tDatePicker = function (e) {
		return b.create(this, {
			name: "tDatePicker", init: function (f, g) {
				return new b.datepicker(f, g)
			}, options: e
		})
	}; $.fn.tDatePicker.defaults = {
		effects: b.fx.slide.defaults(), selectedValue: null, format: b.cultureInfo.shortDate, minValue: new Date(1899, 11, 31), maxValue: new Date(2100, 0, 1), shortYearCutOff: 30, showButton: true, buttonTitle: "Open the calendar", enabled: true, openOnFocus: false
	}
})(jQuery);
