﻿Sys.Application.add_init (function(){
(function($){
// In the context of this anonymous function $ is a reference to $telerik.$

window.SchedulerAdvancedTemplate = function SchedulerAdvancedTemplate(schedulerId)
{
	this._schedulerId = schedulerId;
	
	// We need to obtain the ID of the naming container that
	// contains the advanced template. We can find it from
	// the ID of a known element hosted in the form,
	// such as BasicControlsPanel.
	var basicControlsPanel = $("#" + schedulerId + " .rsAdvBasicControls");
	if (basicControlsPanel.length == 0)
		return;
		
	var basicControlsPanelId = basicControlsPanel[0].id;
	this._templateId = basicControlsPanelId.substring(0, basicControlsPanelId.lastIndexOf("_"));
}

window.SchedulerAdvancedTemplate._adjustHeight = function(schedulerId)
{
	// Stretches the rsAdvOptions div to the available height.
	var scheduler = $("#" + schedulerId);

	var advancedEditDiv = scheduler.find(".rsAdvancedEdit");
	var advancedEditDivBorder = advancedEditDiv.outerHeight() - advancedEditDiv.height();

	var buttonsDiv = scheduler.find(".rsAdvancedSubmitArea");
	var buttonsHeight = buttonsDiv.outerHeight({ margin: true });

	var targetHeight = scheduler.height() - buttonsHeight - advancedEditDivBorder;
	
	scheduler.find(".rsAdvOptionsScroll").height(targetHeight + "px");
	
	// IE fix
	if (buttonsDiv[0])
		buttonsDiv[0].style.cssText = buttonsDiv[0].style.cssText;
}

window.SchedulerAdvancedTemplate.prototype =
{
	initialize: function()
	{
		// Is the advanced template rendered?
		if ($("#" + this._schedulerId + " .rsAdvancedEdit").length == 0)
			return;
	
		$find(this._schedulerId).add_disposing(Function.createDelegate(this, this.dispose));
		
		// Enable the buttons in the advanced form
		$("#" + this._schedulerId + " .rsAdvancedSubmitArea a").attr("onclick", "");
		
		window.SchedulerAdvancedTemplate._adjustHeight(this._schedulerId);
		this._initializePickers();
		this._initializeAdvancedFormValidators();
		this._initializeAllDayCheckbox();
		
		var recurrenceSupport = $("#" + this._templateId + "_RecurrencePanel").length > 0;
		if (recurrenceSupport)
		{
			this._initializeRecurrenceCheckbox();
			this._initializeResetExceptions();
			this._initializeRecurrenceRadioButtons();
			this._initializeLinkedRecurrenceControls();
		}
		
		if ($telerik.isIE)
		{
			var textarea = $("#" + this._schedulerId + " .textareaWrapper textarea")[0];
			
			//textarea.style.cssText = textarea.style.cssText;
		}
	},
	
	dispose: function()
	{	
		$("#" + this._schedulerId + " *").unbind();
				
		this._pickers = null;
	},

	_initializePickers: function()
	{
		// Show picker pop-ups when the inputs are focused

		var showPopupDelegate = Function.createDelegate(this, this._showPopup);

		var templateId = this._templateId;
		this._pickers =
		{
			"startDate": $find(templateId + "_StartDate"),
			"endDate": $find(templateId + "_EndDate"),
			"rangeEndDate": $find(templateId + "_RangeEndDate"),
			"startTime": $find(templateId + "_StartTime"),
			"endTime": $find(templateId + "_EndTime")
		};

		$.each(
			this._pickers,
			function()
			{
				if (this && this.get_dateInput)
					this.get_dateInput().add_focus(showPopupDelegate);
			});


		var pickerControls = [
					$get(this._pickers.startDate.get_element().id + "_wrapper"),
					$get(this._pickers.startTime.get_element().id + "_wrapper"),
					$get(this._pickers.startTime.get_element().id + "_timeView_wrapper"),
					$get(this._pickers.endDate.get_element().id + "_wrapper"),
					$get(this._pickers.endTime.get_element().id + "_wrapper"),
					$get(this._pickers.endTime.get_element().id + "_timeView_wrapper"),
					$get(this._templateId + "_SharedCalendar")
				];
				
		// Might be null if recurrences are disabled
		if (this._pickers.rangeEndDate)
			Array.add(pickerControls, $get(this._pickers.rangeEndDate.get_element().id + "_wrapper"));


		// Hide the pickers when the focus moves to another element in the template
		var advancedTemplate = this;
		var eventName = "focusin";

		$("#" + this._schedulerId + " .rsAdvancedEdit").bind(eventName,
			function(e)
			{
				var inPickerControls = false;
				for (var i = 0, len = pickerControls.length; i < len; i++)
				{
					var control = pickerControls[i];
					if ($telerik.isDescendantOrSelf(control, e.target))
					{
						inPickerControls = true;
						break;
					}
				}

				if (!inPickerControls)
					advancedTemplate._hidePickerPopups();
			});
	},

	_initializeAdvancedFormValidators: function()
	{
		var toolTip = this._createValidatorToolTip();

		for (var validatorIndex in Page_Validators)
		{
			var validator = Page_Validators[validatorIndex];
			if (this._validatorIsInTemplate(validator))
			{
				var control = $("#" + validator.controltovalidate);
				if (control.length == 0)
					break;

				if (control.parent().is(".rsAdvDatePicker") ||
					control.parent().is(".rsAdvTimePicker"))
				{
					$("#" + validator.controltovalidate + "_dateInput_text")
						.bind("focus", { "toolTip": toolTip }, this._showToolTip)
						.bind("blur", { "toolTip": toolTip }, this._hideToolTip)
						[0].errorMessage = validator.errormessage;
				}
				else
				{
					control.addClass("rsValidatedInput");
				}

				control[0].errorMessage = validator.errormessage;
				this._updateValidator(validator, control);
			}
		}

		var advancedTemplate = this;
		var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;

		ValidatorUpdateDisplay = function(validator)
		{
			if (advancedTemplate._validatorIsInTemplate(validator))
			{
				advancedTemplate._updateValidator(validator);
			}
			else
			{
				originalValidatorUpdateDisplay(validator);
			}
		}

		$("#" + this._schedulerId + " .rsValidatedInput")
			.bind("focus", { "toolTip": toolTip }, this._showToolTip)
			.bind("blur", { "toolTip": toolTip }, this._hideToolTip);
	},

	_initializeAllDayCheckbox: function()
	{
		var initialPickersWidth = $("#" + this._schedulerId + " .rsTimePick").eq(0).outerWidth();
		var allDayPickersWidth = initialPickersWidth - $("#" + this._templateId + "_StartTime_wrapper").outerWidth();

		var startTimeValidator = $get(this._templateId + "_StartTimeValidator");
		var endTimeValidator = $get(this._templateId + "_StartTimeValidator");

		var allDayCheckbox = $("#" + this._templateId + "_AllDayEvent");
		var controlList = $(allDayCheckbox[0].parentNode.parentNode.parentNode);

		var advancedTemplate = this;

		// IE fix - the hidden input pushes down the other TimePicker elements during animation
		controlList.find('.rsAdvTimePicker > input').css("display", "none");

		var clickHandler = function(checked, animate)
		{
			var timePickers = controlList.find('.rsAdvTimePicker');
			if (animate)
			{
				timePickers.animate(
					{ opacity: checked ? "hide" : "show" }, "slow");
			}
			else
			{
				if (checked)
					timePickers.hide();
				else
					timePickers.show();
			}

			controlList.find('.rsTimePick').each(function(i)
			{
				if (animate)
				{
					$(this).animate({
						width: checked ? allDayPickersWidth : initialPickersWidth
					}, "slow");
				}
				else
				{
					if (checked)
					{
						$(this).width(allDayPickersWidth);
					}
				}
			});

			ValidatorEnable(startTimeValidator, !checked);
			ValidatorEnable(endTimeValidator, !checked);

			var startTimePicker = advancedTemplate._pickers.startTime;
			startTimePicker.set_enabled(!checked);
			startTimePicker.get_element().parentNode.disabled = checked ? "disabled" : "";

			var endTimePicker = advancedTemplate._pickers.endTime;
			endTimePicker.set_enabled(!checked);
			endTimePicker.get_element().parentNode.disabled = checked ? "disabled" : "";
		}

		clickHandler(allDayCheckbox[0].checked, false);
		allDayCheckbox.click(function(e) { clickHandler(this.checked, true); });
	},

	_initializeRecurrenceCheckbox: function()
	{
		var recurrencePanel = $("#" + this._templateId + "_RecurrencePanel");
		var recurrentAppointment = $("#" + this._templateId + "_RecurrentAppointment");
		if (recurrentAppointment[0].checked)
		{
			recurrencePanel.show();
		}

		recurrentAppointment
			.click(function(e)
			{
				recurrencePanel
					.animate({
						opacity: "toggle",
						height: "toggle"
					}, "slow");
			});
	},

	_initializeResetExceptions: function()
	{
		var resetExceptions = $("#" + this._templateId + "_ResetExceptions");
		if (resetExceptions.length == 1)
		{
			var scheduler = $find(this._schedulerId);
			var doneMessage = scheduler.get_localization().AdvancedDone;
			if (resetExceptions[0].innerHTML.indexOf(doneMessage) > -1)
			{
				// Hide "Done" after 2 seconds
				resetExceptions.click(function(e) { return false; });
				window.setTimeout(function() { resetExceptions.fadeOut("slow"); }, 2000);
			}
			else
			{
				var advancedForm = this;
				
				resetExceptions.click(
					function(e)
					{
						// Display confirmation dialog
						var dialog = $telerik.$.modal('#' + scheduler.get_element().id + '>.rsAdvancedEdit');
						
						localization = scheduler.get_localization();
						
						dialog
							.initialize()
							.set_content ({
								title: localization.ConfirmResetExceptionsTitle,
								content: localization.ConfirmResetExceptionsText,
								ok: localization.ConfirmOK,
								cancel: localization.ConfirmCancel
							})
							.set_onActionConfirm(function(content) {
								// The user has confirmed - proceed with postback
								var workingMessage = localization.AdvancedWorking;
								resetExceptions[0].innerHTML = workingMessage;
								window.location.href = resetExceptions[0].href;
								
								dialog.dispose();
							})
							.show();
							
						return false;
					});
			}
		}
	},

	_initializeRecurrenceRadioButtons: function()
	{
		var radioButtons = [
			$get(this._templateId + "_RepeatFrequencyHourly"),
			$get(this._templateId + "_RepeatFrequencyDaily"),
			$get(this._templateId + "_RepeatFrequencyWeekly"),
			$get(this._templateId + "_RepeatFrequencyMonthly"),
			$get(this._templateId + "_RepeatFrequencyYearly")];

		var recurrencePatternPanels = $("#" + this._templateId + "_RecurrencePatternPanel .rsAdvPatternPanel");

		var getCorrespondingPanel = function(button)
		{
			var targetId = button.value.replace("RepeatFrequency", "RecurrencePattern") + "Panel";
			return recurrencePatternPanels.filter("[id$='" + targetId + "']");
		}

		for (var i = 0, len = radioButtons.length; i < len; i++)
		{
			var button = radioButtons[i];

			if (button.checked)
			{
				// Show initially selected options panel without animation
				getCorrespondingPanel(button).show();
			}

			$(button)
				.click(function()
				{
					var panel = $(getCorrespondingPanel(this));

					if (panel.css("display") == "none")
					{
						// Show the corresponding panel with animation
						recurrencePatternPanels.hide();
						panel.fadeIn("slow");
					}
				});
		}
	},

	_initializeLinkedRecurrenceControls: function()
	{
		// Each radio button is listed with all of it's linked controls
		var controls = {};

		var id = this._templateId;
		var hid = "#" + id;

		controls[id + "_RepeatEveryNthDay"] = [
				$(hid + "_DailyRepeatInterval")];

		controls[id + "_RepeatEveryNthMonthOnDate"] = [
				$(hid + "_MonthlyRepeatDate"),
				$(hid + "_MonthlyRepeatIntervalForDate")];

		controls[id + "_RepeatEveryNthMonthOnGivenDay"] = [
				$(hid + "_MonthlyDayOrdinalDropDown"),
				$(hid + "_MonthlyDayMaskDropDown"),
				$(hid + "_MonthlyRepeatIntervalForGivenDay")];

		controls[id + "_RepeatEveryYearOnDate"] = [
				$(hid + "_YearlyRepeatMonthForDate"),
				$(hid + "_YearlyRepeatDate")];

		controls[id + "_RepeatEveryYearOnGivenDay"] = [
				$(hid + "_YearlyDayOrdinalDropDown"),
				$(hid + "_YearlyDayMaskDropDown"),
				$(hid + "_YearlyRepeatMonthForGivenDay")];

		controls[id + "_RepeatGivenOccurrences"] = [
				$(hid + "_RangeOccurrences")];

		controls[id + "_RepeatUntilGivenDate"] = [
				$(hid + "_RangeEndDate_dateInput_text")];


		// Attach event handlers, so:
		// 1. When a radio-button is clicked, the first of the linked controls will be focused.
		// 2. When a linked control is clicked, the radio-button will be checked.
		$.each(controls, function(radioId)
		{
			var radio = $("#" + radioId);
			var firstControl = controls[radioId][0];

			radio.click(function()
			{
				if (firstControl.css("visibility") == "hidden")
				{
					var inputControl = $("#" + firstControl[0].id + "_text");
					if (inputControl)
						inputControl.focus();
				}
				else
				{
					firstControl.focus();
				}
			});

			$.each(controls[radioId], function()
			{
				$(this).focus(function()
				{
					radio[0].checked = true;
				});
			});
		});
	},

	_updateValidator: function(validator)
	{
		var control = $("#" + validator.controltovalidate);

		if (control.is("textarea"))
			control = control.parent();

		if (!validator.isvalid)
			control.addClass("rsInvalid");
		else
			control.removeClass("rsInvalid");
	},

	_validatorIsInTemplate: function(validator)
	{
		return $(validator).parents().is("#" + this._schedulerId);
	},

	_createValidatorToolTip: function()
	{
		return $('<div class="rsValidatorTooltip">Test</div>').hide().appendTo("#" + this._schedulerId);
	},

	_showToolTip: function(e)
	{
		var toolTip = e.data.toolTip;
		var _control = $(this);
		var isTextArea = false;

		if (_control.is("textarea"))
		{
			isTextArea = true;
			_control = _control.parent();
		}

		var isInvalid = _control.is(".rsInvalid");
		// Date and time pickers are validated against a hidden input located one level up in the DOM
		isInvalid = isInvalid || _control.parent().parent().children().is(".rsInvalid");

		if (isInvalid)
		{
			toolTip
				.css("visibility", "hidden")
				.text(this.errorMessage);

			var schedulerOffset = $(_control).parents(".RadScheduler").offset();
			var pos = _control.offset();
			pos.left -= schedulerOffset.left;
			pos.top -= schedulerOffset.top;
			
			var toolTipLeft = pos.left + "px";

			if (isTextArea)
			{
				toolTipLeft = (pos.left + _control.outerWidth() - toolTip.outerWidth()) + "px";
			}

			var toolTipTop = (pos.top - toolTip.outerHeight()) + "px";
			toolTip
				.css({
					top: toolTipTop,
					left: toolTipLeft,
					visibility: "visible"
				})
				.fadeIn("fast");
		}
	},

	_hideToolTip: function(e)
	{
		var toolTip = e.data.toolTip;
		toolTip.hide();
	},

	_hidePickerPopups: function()
	{
		if (!this._pickers)
			return;
			
		for (var pickerId in this._pickers)
		{
			var picker = this._pickers[pickerId];
			
			if (!picker)
				continue;
			
			if (picker.hideTimePopup)
				picker.hideTimePopup();
			else
				picker.hidePopup();
		}
	},

	_showPopup: function(sender, eventArgs)
	{
		this._hidePickerPopups();

		if (sender.Owner.showTimePopup)
			sender.Owner.showTimePopup();
		else
			sender.Owner.showPopup();
	}
}
})($telerik.$)
});
