define([
		'Global',
		'HeaderView',
		'AppointmentRequest',
		'DesiredDate',
		'PatientContext',
		'User',
		'patient-search/models/Model',
		'patient-search/models/Patients',
        'patient-search/views/AppletLayout'
	],
	function (Global, HeaderView, AppointmentRequest, DesiredDate, PatientContext, user,
	          SearchModel, Patients, AppletLayout) {
		'use strict';
		return Backbone.View.extend({
			id: "portal-modal",
			initialize: function (options) {
                this.options = options || {};

				var self = this;

				this.vent = this.options.vent || new Backbone.Wreqr.EventAggregator();
				this.router = this.options.router;

				this.vent.on('set:patient-context', function(){
					self.updatePatientContext();
					self.search.trigger('close-modal-dialog');
				});
                this.render();
			},
			render: function () {
				this.$el.remove();

				$('body').append(this.$el);

				this.updateSearchModel();

				this.openDialog();
			},
			updateSearchModel: function () {
				SearchModel.set({
					configTypes: {
						clinics: false,
						myList: false,
						patients: true,
						recent: false,
						wards: false
					},
					searchType: 'patients',
					title: 'Patient Search'
				});
				SearchModel.searches.add({
					id: 'patients',
					patientCollection: new Patients({url:user.get('patients-operational').href})
				});
			},
			openDialog: function () {
                var region = new Backbone.Marionette.Region({el: this.$el});

                this.search = new AppletLayout( {
                    model: SearchModel,
                    scrollableContent: true,
                    vent: this.vent,
                    modalRegion: region,
                    router: this.router,
                    fragment: "#booking"
                });
                this.search.trigger("open-modal-dialog");
			},
			updatePatientContext: function () {
				PatientContext.instance().createContext({
					patient: SearchModel.get('patient').toJSON(),
					success: function () {
						new HeaderView().render();

//						WaitListEntry.clearInstance();

						AppointmentRequest.clearInstance();

						DesiredDate.clearInstance();

						Global.getUtilities().eventAggregator.trigger('refreshPatientAppts');
					}
				});
			}
		});
	}
);
