define([
    'Global',
    'AppointmentRequests',
    'AppointmentRequestDetailsView',
	'DatatableView',
    'Text!../html/templates/datatable.html'
],
    function (Global, AppointmentRequests, AppointmentRequestDetailsView, DatatableView, template) {
        'use strict';
        var thisView;
        return Backbone.View.extend({
	        id: 'appointment-requests',
            className: 'var-view',
            initialize: function () {
                thisView = this;
                this.datatableTemplate = _.template(template);
                this.initialLoad = true;
            },
            render: function () {
	            var $container = getSidebarContent();

                $container
                    .empty()
                    .append(
                        this.$el.append(
                            this.datatableTemplate()
                        )
                    )
                    .trigger('create');

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

                this.refreshAppointmentList();
                return this;
            },

            events: {
                'keydown a.ui-input-clear': 'handleKeyDown',
                'tap .ui-input-clear': 'clearFilter',
                'keyup #vaac-request-filter': 'getVAACRequestList',
	            'click #restore-sort-btn': 'restoreDefaultSortOrder',
                'click #list-refresh-btn': 'refreshAppointmentListFromButton'
            },

	        handleKeyDown: function (e) {
		        if (e.which === 13 || e.which === 32) {
			        $(e.currentTarget).trigger('tap');
		        }
	        },

	        refreshAppointmentListFromButton: function (e) {
                e.preventDefault();

                this.requestsDataTable.refreshTable();
            },

	        restoreDefaultSortOrder: function (e) {
		        e.preventDefault();

		        this.refreshAppointmentList();
	        },

            refreshAppointmentList: function () {
                $.extend($.fn.dataTableExt.oStdClasses, {
                    sFilter: "ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield ui-body-c",
                    sSortable: "ui-bar ui-bar-d",
                    sSortDesc: "ui-bar ui-bar-d",
                    sSortAsc: "ui-bar ui-bar-d",
                    sStripeOdd: "ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-btn-up-c",
                    sStripeEven: "ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-btn-up-c"
                });

	            if (thisView.initialLoad !== undefined) {
		            if (thisView.initialLoad) {
			            thisView.initialLoad = false;
		            } else {
			            thisView.requestsDataTable.fnDestroy();
		            }

		            thisView.initializeDatatable();
	            }

                return this;
            },
            initializeDatatable: function () {
	            thisView.requestsDataTable = new DatatableView({
	                rowSelected: this.tapAppointmentRequestRow,
	                tableDataURL: AppointmentRequests.instance().url,
	                dataCollection: AppointmentRequests.instance(),
	                rowCallback: this.rowCallback,
	                drawCallback: this.drawCallback,
	                tableConfiguration: {
		                "id": "appointment-requests",
		                "columns": [
			                {
				                //set custom sort order
				                "mDataProp": function (source) {
					                return source.hasProviderNewMessage || source.secondRequest;
				                },
				                "sTitle": "Alerts",
				                "sortProp": "alerts"
			                },
			                {
				                "mDataProp": "patient.displayName",
				                "sTitle": "Patient Name"
			                },
			                {
				                "mDataProp": "facility.name",
				                "sTitle": "Facility"
			                },
			                {
				                "mDataProp": "appointmentType",
				                "sTitle": "Type"
			                },
			                {
				                "mDataProp": "status",
				                "sTitle": "Status"
			                },
			                {
				                "mDataProp": "lastUpdatedDate",
				                "sTitle": "Last Activity"
			                }
		                ],
		                "container": "#appointment-requests .VAAC-requests",
		                "defaultSort": "defaultVAACSort",
		                "destroy": true,
		                "dom": "<'top'<'clear'>>r<'varTable't><'bottom'<'clear'>>",
		                "paginate": false,
		                "serverPaginate": true,
		                "scroll": true
	                }
                }).render().getDataTable();
            },
	        rowCallback: function (nRow, aData) {
		        var $nRow = $(nRow),
			        $alerts = $nRow.find('td:eq(0)').empty();

		        if (aData.secondRequest === true) {
			        $alerts.append('<span class="ui-icon ui-icon-refresh ui-icon-shadow">&nbsp;</span>');
		        }

		        if (aData.hasProviderNewMessage === true) {
			        $alerts.append('<i class="fonticon chat new-message" title="New Unread Message(s)"></i>');
		        }

		        $nRow
			        .data({
				        'requestHref': aData.link[0].href,
				        'theme': 'c',
				        'role': 'button'
			        });

		        //highlight row if currently viewed appointment.
		        //if not current let screen readers know tap/click triggers appointment request details
		        if (aData.link[0].href === $(document).jqmData('requestId-for-detail-viewing')) {
			        $nRow
				        .prop({'title': 'Currently viewed appointment request.'})
				        .addClass('selected-active');
		        } else {
			        $nRow.prop({'title': 'Tap to see appointment request details.'});
		        }
	        },
	        drawCallback: function () {
		        $('tbody tr td:nth-child(2)').each(function () {
			        var $this = $(this), text = $this.text();
			        if ($this.find('a').length === 0) { $this.empty().append('<a href="#">'+ text +'</a>') }
		        });

		        $('#appointment-requests-table_paginate')
			        .data('role', 'controlgroup')
			        .find('a')
			        .data({
				        'theme': 'c',
				        'role': 'button',
				        'icon': 'delete'
			        });
		        //retriggers the datatable paging select && refresh buttons
		        $('#appointment-requests-table_wrapper, .nav-container')
			        .trigger('create');
	        },
            tapAppointmentRequestRow: function (e) {
                var that = this,
                    requestHref =
                    $(e.currentTarget)
                        .addClass('selected-active')
                        .prop({'title': 'Currently viewed appointment request.'})
                        .siblings()
                        .removeClass('selected-active')
                        .prop({'title': 'Tap to see appointment request details'})
                        .end()
                        .find(".new-message")
                        .remove()
                        .end()
                        .jqmData('requestHref');

                if (requestHref !== undefined) {
                    $(document).jqmData('requestId-for-detail-viewing', requestHref);
                    new AppointmentRequestDetailsView({afterCancelRequest: that.refreshAppointmentList}).render();
                }
            },
            getVAACRequestList: function(e){
                var filterString = $('#vaac-request-filter').val();

                if (e.which === 13) {
                    e.preventDefault();
                    this.requestsDataTable.filterTable(filterString);
                } else if (e.which === 8) {
                    e.preventDefault();
                    if (filterString.length < 1){
                        this.clearFilter();
                    }
                }

            },
            clearFilter: function(){
                this.requestsDataTable.clearFilter();
            }

        });
    }
);
