define([
	'Global',
	'DesiredDate',
	'ApptRequestDetails',
	'Text!../html/templates/error-desired-date-popup.html'
], 
	function(Global, DesiredDate, ApptRequestDetails, template){
	'use strict';
	return Backbone.View.extend({
		id: "error-calendar-clinic-listbox",
		attributes: {
			"data-role": "popup",
			"data-theme": "a",
			"class": "ui-selectmenu"
		},
		initialize: function (event) {
			this.event = event;
			this.template = _.template(template);
            this.utilities = Global.getUtilities();
		},
		render: function(){
			var that = this,
                date = new Date();

            date.setDate(date.getDate() + 90);
			this.$el
                .empty()
                .append(this.template).popup().popup('open');

			this.$el
                .find('#correcting-date-picker-btn').mobile508datepicker({
                    onClose: that.closeDatePicker,
                    "leading-zero": true,
                    MIN: new Date(),
                    MAX: date
                });
		},
		events: {
			"keydown #correcting-desired-date:not(:disabled)": "handleDateInput",
			"blur #correcting-desired-date": "enableDisableOk",
			"tap .ok-button": "submitDesiredDate",
			"tap #close-btn": "closeDesiredDatePopup"
		},
		submitDesiredDate: function () {
			this.setDesiredDateContext();
			ApptRequestDetails.instance().fillData(this.event);
			this.closeDesiredDatePopup();
			Global.getUtilities().eventAggregator.trigger("book-appointment");
		},
		setDesiredDateContext: function () {
			DesiredDate.clearInstance();

			DesiredDate.instance({
				desiredDate: $('#correcting-desired-date').val()
			});

            Global.getUtilities().eventAggregator.trigger('updateDesiredDate');
		},
		handleDateInput: function (e) {
			var $target = $(e.currentTarget),
				code = e.which,
				value = $target.val(),
				length;

			if (code !== 9) {
				e.preventDefault();
				if (code >= 48 && code <= 57) {
					value += code - 48;

					length = value.length;

					if (length === 2 || length === 5) {
						value += "/";
					}

					if (value.length <= 10) {
						$target.val(value);
					}
				} else if (code === 8) {
					var lastChar = value.charAt(value.length - 1);

					value = value.substr(0, value.length - 1);

					length = value.length;

					if ((length === 2 || length === 5) && lastChar === "/") {
						value = value.substr(0, value.length - 1);
					}

					$target.val(value);
				} else if (code === 32 || code === 13) {
					this.enableDisableOk(e);
				}
			}
		},
		enableDisableOk: function (e) {
			var validDate = this.validateDesiredDate(),
				okBtn = $('#desired-date-ok-button button');

			if (validDate) {
				okBtn[0].disabled = false;
				if (!e){
					okBtn.focus();
				} else if (e.currentTarget.id === "correcting-desired-date") {
					okBtn.focus();
				}
			} else {
				okBtn[0].disabled = true;
			}
		},

        validateDesiredDate: function () {
            var $desiredDate = $('#correcting-desired-date'),
                $dateError = $('.date-error'),
                dateString = $desiredDate.val(),
                date = new Date(dateString),
                today = setTimeToZero(new Date()),
                maxDate = setTimeToZero(new Date());

            maxDate.setDate(today.getDate() + 90);

            if (!isValidDate(dateString) || date < today || date > maxDate) {
                if (dateString.length) {
                    $dateError.removeClass('hidden');
                    $desiredDate.focus();
                } else {
                    $dateError.addClass('hidden');
                }

                return false;
            } else {
                $dateError.addClass('hidden');

                return true;
            }
        },

		closeDatePicker: function () {
			var $this = $('#error-calendar-clinic-listbox'),
				value = $('#correcting-date-picker-btn').val(),
				$desiredDate = $('#correcting-desired-date');

			$this
				.popup()
				.popup('open');

			if (value) {
				$desiredDate
					.val(value)
					.trigger('blur');

                $desiredDate
                    .trigger('change');
			}
		},
		closeDesiredDatePopup: function(){
			this.$el.remove();
		}
	});
})