/*jslint node: true, nomen: true, unparam: true */
/*global jquery, $, _, define, Marionette, jqm, describe, it, expect, beforeEach, spyOn */

define(['Global',
	'Text!patient-search/templates/appletLayout.html',
	'patient-search/views/ModalDialogMixin',
	'patient-search/views/_utils',
	'patient-search/models/Model',
	'patient-search/views/AppletTitleView',
	'patient-search/views/AppletNavBarView',
	'patient-search/views/LoadingView',
	'patient-search/views/PatientListView',
	'patient-search/views/ConfirmationView' ],
	function (Global, template, modalDialogMixin, Utils, model, TitleView, NavBarView, LoadingView, PatientListView, ConfirmationView) {
		'use strict';

		return Backbone.Marionette.Layout.extend( Utils.mixinToView({
			model: model,
			id: "search",
			template: _.template(template),
			regions: {
				titleRegion: 'div[data-role=header] h2',
				//navBarRegion: '#search-type-menu',
				primaryFilterRegion: '#primary-search-filter',
				secondaryFilterRegion: '#secondary-search-filter'
			},
			events: {
				'pageshow': '_onPageShow',
				'focus #secondary-search-filter input': 'hidePrimarySearchList'
			},
			initialize: function (options) {
				var self = this;
				this.vent = options.vent || new Backbone.Wreqr.EventAggregator();
				// this.searchViews contains functions for creating views
				this.initializeSearchViews(this.model.get('configTypes'));

				this.confirmationPopup = new ConfirmationView({ model: model.get('patient'), vent: this.vent });

				this.listenTo(self.model, 'change:searchType', function () {
					if (typeof self.primaryFilterRegion !== "undefined" && typeof self.primaryFilterRegion.currentView !== "undefined") {
						self.updateView();
					}
				});
			},
			onRender: function () {
				var fragment = model.get('searchType');

				this.updateView();
				//this.navBarRegion.show( new SearchApplet.NavBarView() );
				this.titleRegion.show(new TitleView());

				fragment = (fragment === 'myList') ? 'my-list' : fragment;
				this.$el.find('a[href=#search-' + fragment + ']').addClass('ui-btn-active');
			},
			_onPageShow: function () {
				this.primaryFilterRegion.$el.find('.ui-input-search input').focus();
			},
			onClose: function () {
				var config = this.model.get('configTypes'),
					confirmationEl = '#' + this.confirmationPopup.id;
				this.stopListening();
				this.off();
				if (config.clinics) {
					this.stopListening(this.model.searches.get('clinics'));
				}
				if (config.wards) {
					this.stopListening(this.model.searches.get('wards'));
				}
				// used for confirmation
				$(confirmationEl).popup('destroy');
				$(confirmationEl).remove();
			},
			updateView: function () {
				var type = this.model.get('searchType'),
					config = this.model.get('configTypes');

				if (typeof config[type] !== 'undefined' && config[type]) {
					switch (type) {
						case 'clinics':
						case 'wards':
							this.primaryFilterRegion.show(this.searchViews[type].locationList());
							this.toggleSecondaryFilter(type);
							// set focus
							if (typeof this.model.searches.get(type) !== "undefined" && this.model.searches.get(type).get('location') !== '') {
								this.secondaryFilterRegion.$el.find('.ui-input-search input').focus();
							} else {
								this.primaryFilterRegion.$el.find('.ui-input-search input').focus();
							}
							break;
						case 'recent':
						//case 'myList':
						//    break;
						case 'patients':
							this.primaryFilterRegion.show(this.searchViews[type].patientList());
							this.hideSecondaryFilter();
							// set focus
							this.primaryFilterRegion.$el.find('.ui-input-search input').focus();
							break;
					}
				} else {
					console.log("Search Applet error: '" + type + "' is not a valid search type; check if '" + type + "' was passed in option.types");
				}
			},
			toggleSecondaryFilter: function (type) {
				var search = this.model.searches.get(type);

				if (typeof search !== 'undefined' && search.get('location') !== '') {
					this.showSecondaryFilter();
				} else {
					this.hideSecondaryFilter();
				}
			},
			showSecondaryFilter: function () {
				var type = this.model.get('searchType');

				this.secondaryFilterRegion.show(this.searchViews[type].patientList());
			},
			hideSecondaryFilter: function () {
				this.secondaryFilterRegion.close();
			},
			hidePrimarySearchList: function () {
				$("#primary-search-filter .ui-accessible-autocomplete").trigger("hide");
			},
			initializeSearchViews: function (config) {
				this.searchViews = {};

				this._addPatientSearchView(config.patients);
			},
			_addPatientSearchView: function (isConfigured) {
				var self = this,
					getPatientListView = function () {
						return new PatientListView({
							model: self.model.searches.get('patients'),
							collection: self.model.searches.get('patients').get('patientCollection'),
							vent: self.vent
						});
					};

				if (isConfigured) {
					this.searchViews.patients = { patientList: getPatientListView };
				}
			}
		}, modalDialogMixin, "initialize", "onRender", "onShow", "onClose", "_onPageShow"));
	});