define([
	'Global',
    'PatientContext',
    'PatientDemographics',
	'Text!../html/templates/patient-details-popup.html'
],
	function (Global, PatientContext, PatientDemographics, template) {
		'use strict';

		return Backbone.View.extend({
			tagName: "div",
			id: "patient-details",
			attributes: {
				"data-role": "popup",
				"data-dismissible": "false",
				"class": "ui-corner-all patient-details"
			},

			initialize: function () {
                this.template = _.template(template);
			},

			render: function () {
                var error = "",
                    patientDemographics = new PatientDemographics(),
                    that = this;

				patientDemographics.fetch({
					cache: false,
                    url: PatientContext.instance().getPatient().get('patient-demographics-operational').href,
                    success: function (data) {
                        that.drawPopup($.extend({error: error}, data.toJSON()));
                    },
                    error: function () {
                        error = "Error retrieving patient contact details.  Please try again or contact your administrator.";

	                    if (!$('#patient-details').length) {
		                    that.drawPopup({error: error});
	                    }
                    }
                });

				return this;
			},

			events: {
				"click #patient-details-done-btn": "closePopup"
			},

            drawPopup: function (model) {
                var $container = getMainContent();

                this.$el
                    .empty()
                    .append(this.template(model))
                    .trigger('create');

                $container
                    .append(this.$el);

                this.$el
                    .trigger('create')
                    .popup()
                    .popup('open');

	            $('#patient-details-done-btn').focus();
            },

			closePopup: function () {
				this.$el
					.popup('close')
					.remove();

                $('#patient-contact').focus();
			}
		});
	}
);