define([
    'Global',
	'App',
    'MainView',
    'DatatableView',
    'SchedulingResourceDirectory',
    'ConsultServices',
    'ConsultsDetailsFacilityView',
    'ConsultOrders',
    'Text!../html/templates/consults-filter.html',
	'Text!../data/consultsResultsTable.json'
],
    function (Global, App, MainView, DatatableView, SchedulingResourceDirectory, ConsultServices, ConsultsDetailsFacilityView, ConsultOrders, ConsultsFilterTemplate, ConsultsResultsTable){
        'use strict';

        return Backbone.View.extend({

            id: "consults-filter",
            attributes: {'class' : 'filter'},

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

            render: function(){
	            var url = SchedulingResourceDirectory.instance().get('consulting-services').href,
		            consultServices = ConsultServices.instance(),
		            that = this;

                MainView.instance().clearPopups();

	            if (!consultServices.length) {
		            $.mobile.loading('show', App.getSpinnerOptions());
		            $('.ui-loader').css('display', 'block');

		            consultServices.fetch({
			            cache: false,
			            url: url,
			            success: function () {
				            $.mobile.loading('hide');
				            $('.ui-loader').removeAttr('style');

				            that.drawSpecialtiesAutocomplete();

				            return that;
			            }
		            });
	            } else {
					that.drawSpecialtiesAutocomplete()
	            }
            },

            events: {
                'keyup #service-specialty-form input': 'showAutocompleteList',
                'tap #service-specialty-form .ui-input-clear': 'handleClear',
                'keydown #service-specialty-form .ui-input-clear': 'handleKeyDown',
                'tap #service-specialty li a': 'showConsultsResultsTable',
                'keydown #service-specialty li a': 'handleKeyDown'
            },

	        drawSpecialtiesAutocomplete: function () {
		        var $container = getSidebarContent(),
			        consultServices = ConsultServices.instance().toJSON();

		        this.$el
			        .empty()
			        .append(this.ConsultsFilterTemplate({consultServices: consultServices}));

		        this.$serviceSpecialty = this.$el.find('#service-specialty');

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

		        this.setAttributesToJQMinput(this.$serviceSpecialty);
	        },

            setAttributesToJQMinput: function ($ul) {
                var attr, key, value,
                    attributes = $ul.data('attributes').split(','),
                    props = ['autofocus', 'disabled', 'readonly', 'required', 'selected'],
                    $serviceSpecialty =
                        $ul.prev('form')
                            .attr('id', [$ul[0].id, 'form'].join('-'))
                            .find('input')
                            .attr('id', [$ul[0].id, 'input'].join('-'));

                $('.ui-input-search').prop('title', 'Search...');

                for (var i = 0; i < attributes.length; i++) {
                    attr = attributes[i].split('=');
                    key = attr[0];
                    value = attr[1] || true;

                    $serviceSpecialty[props.indexOf(key) >= 0 ? "prop" : "attr"](key, value);
                }
            },

            handleClear: function (e) {
                this.hideAutocompleteList(e);

	            Global.getUtilities().eventAggregator.trigger("default-view");

	            if (this.$consultsTable) {
		            this.$consultsTable.clearTable();
	            }
            },

            handleKeyDown: function (e) {
                if (e.which === 13) {
                    e.preventDefault();

                    $(e.currentTarget).trigger('tap');
                }
            },

            hideAutocompleteList: function (e) {
                this.$serviceSpecialty.addClass('hidden');

                $(e.currentTarget).trigger('click');
            },

            showAutocompleteList: function (e) {
                var $input = $('#service-specialty-form input');

                if ((e.which === 8 || e.which === 46) && !$input.val()) {
                    this.$serviceSpecialty.addClass('hidden');
                } else if (e.which !== 13 && e.which !== 9 && e.which !== 16) {
                    this.$serviceSpecialty.removeClass('hidden');
                }
            },

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

                var $specialtyInput = $('#service-specialty-form input'),
                    $target = $(e.currentTarget),
	                specialtyName = $target.text(),
	                specialtyId = $target.data('id'),
	                startDate = subtractFromDate(0, 0, 1, 0, 0, 0, 0, new Date()),
	                endDate = formatDate(new Date()),
	                dateFilter = "&startDate=" + startDate + "&endDate=" + endDate,
	                url = SchedulingResourceDirectory.instance().get('consult-by-service').href + "?serviceId=" + specialtyId + dateFilter,
	                that = this;

                $specialtyInput.val(specialtyName);

                this.$serviceSpecialty.addClass('hidden');

                this.$consultsTable = new DatatableView({
                    rowSelected: that.showConsultDetails,
                    tableConfiguration: JSON.parse(ConsultsResultsTable),
                    tableDataURL: url,
                    dataCollection: ConsultOrders.instance()
                }).render().getDataTable();

	            Global.getUtilities().eventAggregator.trigger("default-view");
            },

            showConsultDetails: function() {
                new ConsultsDetailsFacilityView().render();
            }
        })

    }
);