define([
    'Global',
    'PatientDetailsPopupView',
    'PatientContext',
    'AppointmentRequest',
	'DesiredDate',
    'Text!../html/templates/header.html'
],
    function (Global, PatientDetailsPopupView, PatientContext, AppointmentRequest, DesiredDate, primaryHeader) {
        'use strict';
        return Backbone.View.extend({
            tagName: 'div',
            attributes: {
                class: "header"
            },
            events: {
                "click #clear-context": "clearPatientContext",
//	            "click #patient-search": "showPatientSearch",
                "click #patient-contact": "showPatientContactInfo"
            },
            initialize: function () {
	            var that = this;
                this.model = PatientContext.instance();
                this.template = _.template(primaryHeader);
                this.listenTo(this.model, 'change', function(){
                    this.render();
                });
            },
            render: function () {
                var patient = PatientContext.instance().getPatient(),
	                tab = window.location.hash;

                this.$el
                    .empty()
                    .append(this.template($.extend({tab: tab}, patient.toJSON())));

                $('#header')
                    .empty()
                    .append(this.$el);

                this.delegateEvents();

                return this;
            },
            clearPatientContext: function () {
                var that = this;

                PatientContext.instance().clearContext({
                    success: function () {
                        that.render();

	                    that.delegateEvents();

                        Global.getUtilities().eventAggregator.trigger('clearPatientAppts');

//                        WaitListEntry.clearInstance();

                        AppointmentRequest.clearInstance();

	                    DesiredDate.clearInstance();

	                    $('#below-filter').empty();

                        Global.getUtilities().eventAggregator.trigger('disable:patient:tab');
                    }
                });
            },
            showPatientContactInfo: function () {
	            if (PatientContext.instance().isValid()) {
		            new PatientDetailsPopupView().render();
	            }
            }
//	        showPatientSearch: function () {
//		        Global.getUtilities().eventAggregator.trigger('search');
//	        }
        });
    }
);
