define([
	'Global',
	'jquery',
	'CalendarData',
	'DesiredDate',
	'AppointmentRequest',
	'jquery.mobile-datepicker',
	'Text!../html/templates/clinics-menu.html'
],
	function (Global, $, CalendarData, DesiredDate, AppointmentRequest, jQMdatePicker, template) {
		'use strict';

		return Backbone.View.extend({
			tagName: "div",
			id: "calendar-clinic-listbox",
			attributes: {
				"data-role": "popup",
				"data-theme": "a",
				"class": "ui-selectmenu"
			},

			initialize: function (options) {
                this.options = options || {};
				this.$callElement = $(options ? options.callElement : {});
				this.clinics = options ? options.clinics : [];

				this.template = _.template(template);
			},

			render: function () {
				var $container = getMainContent(),
					that = this,
					$thisInDOM = $("#" + this.id),
					desiredDate = this.populateDesiredDate();

				if ($thisInDOM.length) {
					$thisInDOM.popup('open', {positionTo: that.$callElement});

					var $desiredDate = $('#desired-date'),
						$datePickerBtn = $('#date-picker-btn');

					$desiredDate.val(desiredDate);

					if (desiredDate === "") {
						$desiredDate.textinput("enable");

						$datePickerBtn.removeAttr('disabled');
					} else {
						$desiredDate.textinput("disable");

						$datePickerBtn.attr('disabled', 'disabled');
					}

					this.handleClinicMenu();
				} else {
					var date = new Date();
					date.setDate(date.getDate() + 90);
					this.$el
						.empty()
						.append(this.template({clinics: this.clinics, desiredDate: desiredDate}))
						.jqmData('callElement', that.$callElement);

					$container
						.append(this.$el);

					this.$el
						.trigger('create')
						.popup()
						.popup('open', {positionTo: that.$callElement});

					if (this.clinics && this.clinics.length) {
						this.reSelectClinics();
					}

					this.delegateEvents();

					this.$el.find('#date-picker-btn').mobile508datepicker({
						onClose: that.closeDatePicker,
						"leading-zero": true,
						MIN: new Date(),
						MAX: date
					});
				}

				this.setFirstFocus();

				return this;
			},

			events: {
				"change #clinics-form input": "handleClinicMenu",
				"tap .ok-button": "submitClinicsMenu",
				"keydown .ok-button": "handleOkKeyDown",
				"keydown #clinics-form .ui-checkbox": "handleCheckBoxKeyDown",
				"tap #close-btn": "closeMenu",
				"keydown #close-btn": "handleKeyDown",
				"click #clear-btn": "clearClinicSelections",
				"keydown #desired-date:not(:disabled)": "handleDateInput",
				"blur #desired-date": "enableDisableOk",
				"click #date-picker-btn": "stopDefault",
				"keydown #date-picker-btn": "handleDatePickerBtnKeyDown"
			},

			populateDesiredDate: function () {
				var desiredDateContext = DesiredDate.instance().get('desiredDate'),
					apptRequestDate = AppointmentRequest.instance().get('optionDate1'),
//					waitListEntry = WaitListEntry.instance(),
//					EWLRequestDate = waitListEntry.get('desiredDate'),
//					RecallRequestDate = waitListEntry.get('recallDate'),
//					NEARRequestDate = waitListEntry.get('requestDate'),
					desiredDate = desiredDateContext || apptRequestDate || /*EWLRequestDate || RecallRequestDate || NEARRequestDate ||*/ null;

				return desiredDate ? formatDate(desiredDate) : "";
			},

			handleDatePickerBtnKeyDown: function (e) {
				if (e.which === 9 && !e.shiftKey && this.el.querySelector('.ok-button').disabled) {
					e.preventDefault();
					$('#clear-btn').focus();
				}
			},

			stopDefault: function (e) {
				e.preventDefault();
			},

			validateDesiredDate: function () {
				var $desiredDate = $('#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;
				}
			},

			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);
					}
				}
			},

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

				$this
					.popup()
					.popup('open', {positionTo: $($this.jqmData('callElement'))});

				if (value) {
					$desiredDate
						.val(value)
						.trigger('change');
				}
			},

			clearClinicSelections: function () {
				var $checked = $('#clinics-form').find('.ui-icon-checkbox-on').parent().parent().next('input'),
					$desiredDate = $('#desired-date');

				$checked.prop('checked', false).checkboxradio('refresh');

				if ($desiredDate.attr('disabled') !== "disabled") {
					$('#desired-date').val('');
				}

				this.handleClinicMenu();
			},

			closeMenu: function (e) {
				e.preventDefault();

				this.$el
					.popup('close');

				this.$callElement.focus();
			},

			setFirstFocus: function () {
				var $firstCheckBox = $('#calendar-clinic-menu input').eq(0);

				if ($firstCheckBox.length) {
					$firstCheckBox.focus();
				} else {
					$('#close-btn').focus();
				}
			},

			submitClinicsMenu: function () {
				this.setDesiredDateContext();
				this.getClinicSlots();
			},

			setDesiredDateContext: function () {
				var appointmentRequest = AppointmentRequest.instance();

				DesiredDate.clearInstance();

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

				if (appointmentRequest.isValid() && appointmentRequest.get('optionDate1') === "No Date Selected") {
					appointmentRequest.set({
						"optionDate1": $('#desired-date').val()
					});
				}
			},

			getClinicSlots: function () {
				if (this.clinicsUrls.length) {
					this.$el
						.popup('close')
						.remove();

					this.updateClinicSlots();
				}
			},

			updateClinicSlots: function(){
				CalendarData.instance()
                    .setClinicNames(this.clinicNames)
					.setClinicUrls(this.clinicsUrls)
					.getClinicSlots();
			},

			reSelectClinics: function () {
				var calendarData = CalendarData.instance(),
					ids = calendarData.getClinicIds();

				$.each(ids, function (key) {
					$('[clinic-id="' + ids[key] + '"]').prop('checked', true).checkboxradio('refresh');
				});

				this.handleClinicMenu();
			},

			handleClinicMenu: function (e) {
				var max = 5,
					$target = $(e ? e.currentTarget : ""),
					clinicsFormData = $('#clinics-form').serializeArray(),
					that = this,
					$unchecked = $('#clinics-form').find('.ui-icon-checkbox-off').parent().parent().next('input').not($target),
					$selectCountDown = $('.select-countdown'),
					$clinicButtonText = $('#calendar-clinic-button .ui-btn-text'),
					$clinicCount = $('#calendar-clinic-button .ui-li-count'),
					$desiredDate = $('#desired-date'),
					numSelected;

				this.clinicsUrls = [];
                this.clinicNames = [];

				_.each(clinicsFormData, function (clinicData) {
					if (clinicData.name !== "desired-date") {
						that.clinicsUrls.push(clinicData.value);
						that.clinicNames.push(" " + clinicData.name);
					}
				});

				numSelected = this.clinicsUrls.length;

				if (numSelected >= max) {
					$unchecked.checkboxradio('disable');
					$selectCountDown.html('YOU HAVE SELECTED THE MAX');
				} else {
					$unchecked.checkboxradio('enable');
					$selectCountDown.html('SELECT UP TO: ' + (max - numSelected));
				}

				if (numSelected > 0) {
					$clinicCount.html(numSelected);

					if (numSelected > 1) {
						$clinicCount.removeClass('hidden');
					} else {
						$clinicCount.addClass('hidden');
					}

					$clinicButtonText.html(that.clinicNames.toString());
				} else {
					$clinicCount.addClass('hidden');
					$clinicButtonText.html("Clinics");
				}
				if ($desiredDate.val() !== '' && $desiredDate.is(':disabled')){
					this.enableDisableOk(e, true);
				} else {
					this.enableDisableOk(e);
				}
				
			},

			enableDisableOk: function (e, dateAlreadySet) {
				var validDate = dateAlreadySet ? dateAlreadySet : this.validateDesiredDate(),
					$okBtn = $('.ok-button');

				if (this.clinicsUrls.length > 0 && validDate) {
					$okBtn[0].disabled = false;
					if (!e){
						$okBtn.focus();
					} else if ($(e.currentTarget).attr('id') === "desired-date") {
						$okBtn.focus();
					}
				} else {
					$okBtn[0].disabled = true;
				}
			},

			handleKeyDown: function (e) {
				if (e.which === 13) {
					e.preventDefault();

					$(e.currentTarget).trigger('tap');
				}
			},

			handleOkKeyDown: function (e) {
				if (e.which === 13) {
					e.preventDefault();

					$(e.currentTarget).trigger('tap');
				} else if (e.which === 9 && !e.shiftKey) {
					e.preventDefault();

					$('#clear-btn').focus();
				}
			},

			handleCheckBoxKeyDown: function (e) {
				e.preventDefault();

				var $target = $(e.currentTarget);

				switch (e.which) {
					case 32:
					case 13:
						$target.find('label').trigger('click');
						break;
					case 9:
						var $clearBtn = $('#clear-btn'),
							$okBtn = $('.ok-button'),
							$desiredDate = $('#desired-date');

						if (e.shiftKey) {
							$clearBtn.focus();
						} else if ($desiredDate.attr('disabled') !== "disabled") {
							$desiredDate.focus();
						} else if (!$okBtn.attr('disabled')) {
							$okBtn.focus();
						} else {
							$clearBtn.focus();
						}
						break;
					case 38:
						var $prev = $target.prevAll('.ui-checkbox:not(.ui-disabled)').eq(0).find('input');

						if ($prev.length) {
							$prev.focus();
						}

						break;
					case 40:
						var $next = $target.nextAll('.ui-checkbox:not(.ui-disabled)').eq(0).find('input');

						if ($next.length) {
							$next.focus();
						}

						break;
				}
			}
		});
	}
);