define([
    'Global',
    'HeaderView',
    'ConsultOrders',
    'PatientContext',
    'Patient',
    'PatientSimpleDetailsView',
	'AppointmentRequest',
    'Text!../html/templates/consult-details.html'
],
    function (Global, HeaderView, ConsultOrders, PatientContext, Patient, PatientSimpleDetailsView, AppointmentRequest, consultDetailsTemplate) {
        'use strict';
        return Backbone.View.extend({
            tagName: "div",
	        className: "consults-details-facility",
            initialize: function () {
                this.template = _.template(consultDetailsTemplate); 
            },
            render: function () {
	            var url = $(document).jqmData('requestHref-for-detail-viewing'),
                    that = this;

	            this.detailsId = $(document).jqmData("details-id");

                $.ajax({
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    url: url,
                    success: function (response) {
                        var $container = getMainContent(),
	                        consult = ConsultOrders.instance().findById(that.detailsId);

                        that.$el.append(that.template(response));

                        $container
                            .empty()
                            .append(that.$el);

                        that.$el.trigger('create');

                        $(document).jqmData('requestHref-for-detail-viewing', '');

                        new Patient().fetch({
	                        cache: false,
                            url:consult.get("patientLink"),
                            success:function(data){
	                            if ($('.' + that.className).length) {
		                            that.viewpatient = data;
		                            PatientSimpleDetailsView.instance().render(data);
	                            }
                            }
                        });

	                    $('#print-consult').focus();

                        return that;
                    },
                    type: "GET"
                });
            },
            events: {
                "click #print-consult": "printConsult"
            },
            printConsult: function (e) {
                e.preventDefault();
                var consult = ConsultOrders
                        .instance()
                        .findById(this.detailsId);

                Global.getUtilities().flattenLinks(consult);

                var printUrl = consult.get('print-consult-pdf').href + "?startDate=" + consult.get('requestDate');

                window.open(printUrl);
            }
        });
    }
);



