define([
    'Global',
    'backbone',
    'underscore',
    'jquery',
    'jquery.mobile',
    'Resources',
    'UserSession',
    'PatientContext',
    'AppointmentRequest',
    'DesiredDate',
    'Text!../html/templates/exit-navigation-popup.html'
],
    function (Global, Backbone, _, $, jqm, resources, UserSession, PatientContext, AppointmentRequest, DesiredDate, exitPopupTemplate) {
        'use strict';

        var singleton,
            ExitNavigationPopupView = Backbone.View.extend({
                tagName: 'div',
                id: "exit-popup",
                attributes: {
                    'data-role': 'popup',
                    'data-corners': 'false',
                    'data-theme': 'a',
                    'data-history':'false',
                    'data-positionTo': 'window',
                    'data-overlay-theme': 'd'
                },
                events : {
                    "tap #logout-btn": "logout",
                    "tap #launchpad-btn": "launchpad",
	                "keydown a": "handleKeyDown"
                },
                initialize : function (options) {
                    this.options = options || {};
                    var loc = window.location,
                        path = loc.protocol + "//" + loc.hostname + (loc.port ? ":" + loc.port : loc.port ),
                        launchpadPath = '/launchpad';

                    _.bindAll(this);
                    this.template = _.template(exitPopupTemplate);
                    this.mhpuser = UserSession.instance().get('mhpuser');
                    
                    if (loc.hostname === 'localhost' && loc.port !== '8080'){
                        path = path + ":8080";
                    }
                    this.launchpadPath = path+launchpadPath;
                },
                render: function () {
                    var $container = getMainContent(),
                    that = this,
                    $thisInDOM = $("#" + this.id);

                    if ($thisInDOM.length) {
                        $thisInDOM.popup('open', {positionTo: "window"});
	                    this.$el.find("a#exit-close-btn").focus();
                    } else {
                        this.$el
                            .empty()
                            .append(this.template());

                        $container
                            .append(this.$el);

                        this.$el.attr({"style":"width:150px;"});

                        this.$el
                            .popup()
                            .popup('open', {positionTo: "window"});

	                    var that = this,
		                    $exitButton = this.$el.find("a#exit-close-btn");

                        this.$el.find('#launchpad-btn').get(0).setAttribute('href', this.launchpadPath);
                        $exitButton.button();

	                    $exitButton
		                    .focus()
		                    .on('tap', function () {
		                    that.$el.popup('close');

		                    if ($.isFunction(that.onCloseExit)) {
			                    that.onCloseExit();
		                    }
	                    });

	                    this.delegateEvents();
                    }

                    return this;
                },
                stage: function(){
                    this.$el.popup();
                },
                onClose: function() {
                    this.stopListening();
                    this.off();
                    this.undelegateEvents();
                },
                openExit: function (options) {
	                options = options || {};
                    this.render();
	                this.onCloseExit = options.onCloseExit;
                   // this.$el.popup('open');
                },
                logout: function(e) {
                    e.preventDefault();
                    PatientContext.instance().clearContext({
                        success: function () {
                           Global.getUtilities().eventAggregator.trigger("do:logout");
                        }
                    });
                },
                launchpad: function(e){
                    e.preventDefault();
                    Global.getUtilities().eventAggregator.trigger("do:launchpad");
                },
	            handleKeyDown: function (e) {
		            if (e.which === 13 || e.which === 32) {
			            e.preventDefault();
			            $(e.currentTarget).trigger('tap');
		            }
	            }
        });

        ExitNavigationPopupView.instance = function () {
            if (typeof singleInstance === "undefined") {
                singleInstance = new ExitNavigationPopupView();
            }
            return singleInstance;
        };
        return ExitNavigationPopupView;
    }
);
