/*jslint node: true, nomen: true, unparam: true */
/*global jquery, $, _, define, Marionette, jqm, describe, it, expect, beforeEach, spyOn */

define([ 'Global', 'moment',
	'loadingSpinner',
	'Text!patient-search/templates/confirmation.html'],
	function (Global, moment, loadingSpinner, template) {
		'use strict';

		return Backbone.Marionette.ItemView.extend({
			tagName: 'div',
			id: 'confirmation',
			attributes: {
				'data-role': 'popup',
				'data-theme': 'b',
				'data-transition': 'fade',
				'data-tolerance': '130,0,0,0',
				'data-dismissible': 'true',
				'data-shadow': 'true',
				'data-overlay-theme': 'a'
			},
			className: 'ui-content',
			template: _.template(template),
            templateHelpers: {
                formatDate: function (date, format) {
                    if (date) {
                        if (moment(date, 'MMM YYYY', true).isValid()) {
                            return date;
                        } else if (moment(date, 'YYYY', true).isValid()) {
                            return date;
                        } else {
                            return moment(date).format(format);
                        }
                    } else {
                        return '';
                    }
                },
                formatGender: function (gender, format) {
                    if (!gender) {
                        return '';
                    }

                    var genderFormats = {
                        single: gender.charAt(0),
                        lowercase: gender.toLowerCase(),
                        titlecase: (function(str) {
                            return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
                        })(gender),
                        uppercase: gender.toUpperCase()
                    };
                    return genderFormats[format];
                }
            },
			events: {
				'tap #confirm-button': 'confirm',
				'keyup #confirm-button': 'keyupList'
			},
			initialize: function (options) {
				var self = this;
                this.options = options || {};
				this.vent = this.options.vent || new Backbone.Wreqr.EventAggregator();

				this.vent.on('open:popup:confirmation', self.openConfirmation, self);

				this.vent.on('close:popups', self.closeConfirmation, self);
			},
			onRender: function () {
				this.$el.popup();
				this.$el.trigger('create');
			},
			onClose: function () {
				this.vent.off('open:popup:confirmation');
				this.vent.off('close:popups');
				this.stopListening();
				this.off();
			},
			openConfirmation: function (options) {
				var self = this,
					deferred = this.loadPatientData($.Deferred());
				deferred.then(function () {
					var centerY;
					self.render();
					if (typeof options !== 'undefined' && $('#patient-list').find(options.positionTo).length > 0) {
						self.$el.css({ 'margin-top': "-" + (self.$el.outerHeight() / 2 + 20) + "px" });
						self.$el.popup('option', options);
						self.$el.popup('open');
					}
				});
			},
			closeConfirmation: function () {
				$('#' + this.id).popup('close');
			},
			loadPatientData: function (deferred) {
				var firstLink = this.model.get('link')[0],
					url = (firstLink.rel === "self") ? firstLink.href : null;

				if (url !== null) {
					this.model.fetch({ url: url })
						.success(function () {
							deferred.resolve();
						})
						.fail(function () {
							deferred.fail();
						});
					return deferred.promise();
				}

				return deferred.fail();
			},
			confirm: function () {
				var self = this;
				loadingSpinner.show();
				window.setTimeout(function () { //let the loading spinner show, otherwise vent call blocks dom update
					self.vent.trigger('set:patient-context');
					self.closeConfirmation();
					self.close();
					loadingSpinner.hide();
				}, 100);
			},
			keyupList: function (e) {
				if (e.which === 13 || e.which === 32 || e.which === 39) {
					// Enter || Space Bar || Right Arrow
					this.confirm();
				}
			}
		});
	});