define([
	'Global',
	'Resources',
	'UserSession',
	'Version',
	'FooterButtons',
	'Text!../html/templates/footer.html',
	'Text!../html/templates/userBar.html',
	'Text!../html/templates/footerMenuPopup.html'
],
	function(Global, resources, UserSession, Version, footerButtons, footerTemplate, userBarTemplate, footerMenuPopup) {
		"use strict";
        var utilities = Global.getUtilities(),
            FooterView = Backbone.View.extend({
			tagName: 'div',
			attributes: {"data-role":"navbar"},
			initialize: function() {
				this.mhpuser = UserSession.instance().get('mhpuser');
				this.template = _.template(footerTemplate);
				this.userTemplate = _.template(userBarTemplate);
				this.menuTemplate = _.template(footerMenuPopup);
				this.version = Version.instance().toJSON();
			},
			render: function(breakpoint) {
				var template = this.template,
					userBar = this.userTemplate,
					mhpuser = this.mhpuser,
					footerSize = _.filter(footerButtons.models, function(button){ return button.get("available"); }).length,//footerButtons.length,
					defaultFooterSize = breakpoint ? breakpoint : 5, //jquery Mobile sets breakpoint at 5
					menuTemplate = this.menuTemplate,
					menuSize = 0,
					menuButtons = [],
					moreBtn = {id: "footer-more-btn", url: "#", icon: "grid", active: "false", title: "More"},
					$el = this.$el;

                $el.empty().append('<ul>');

				if (footerSize > defaultFooterSize) {
					menuSize = footerSize - (defaultFooterSize - 1);
				}

				for (var i= 0, active; i<footerSize; i++) {
					if (i < footerSize - menuSize) {
						active = footerButtons.models[i].get('active') ? "ui-btn-active" : "";

						$('ul', $el)
							.append(template($.extend({}, mhpuser, footerButtons.models[i].toJSON(), {active: active})));
					} else {
						menuButtons.push(footerButtons.models[i].toJSON());
					}
				}

                $el.append(userBar($.extend({}, {user: mhpuser, version: this.version})));
				
				var $result = $el;
				
				if (menuSize > 0) {
					$('>ul', $el).append(template(moreBtn));
					$result = $el.add(menuTemplate({models: menuButtons}));
				}
				return $result;
			},
			events: {
				"tap a": "routeSelection",
				"keydown a": "handleKeyDown"
			},

            openFooterPopup: function(e) {
                var $moreMenu = $('#footer-menu-popup'),
                    scope = this,
                    $this = $(e.currentTarget);

                $moreMenu.popup();
                $moreMenu.popup('open', {positionTo: $this});
                $moreMenu.find('a').eq(0).focus();
                $moreMenu.on('tap.more-menu', 'a', function(e){
                    e.stopPropagation();
                    $moreMenu.popup('close');
                    scope.routeSelection(e);
                });
                $moreMenu.on('keydown.more-menu', 'a', function(e){
                    scope.handleKeyDown(e);
                });
                $this.removeClass('ui-btn-active');
            },

			routeSelection: function(e) {
				e.preventDefault();
				var $this = $(e.currentTarget),
					scope = this,
					//If specific to footer links, should probably pick one convention
					//Filter is requirement of isotope
					target = $this.data('filter') ?
						$this.data('filter') :
						$this.attr('id'),
					referencePath = utilities.getMhpReferencePath();

				if (target !== undefined) {
					switch (target) {
						case "footer-logout-btn":
							if (typeof this.mhpuser !== "undefined") {
								var logoutUrl = resources.get('logout').get('href');
								$.ajax({
								    url: resources.get('token').get('href'),
								    type: 'DELETE',
								    success: function(data){
										sessionStorage.clear();
										window.location = logoutUrl;
								    }	
								});
							} else {
								window.location = referencePath + "../oauthlogin?redirect_uri=" + Global.getUtilities.getReferencePathWithHash();
							}
							break;
						case "footer-launchpad-btn":
							window.location = referencePath + $this.attr('href');
							break;
						case ".app": case ".link": case "*":
							$('#container').isotope({ filter: target });
							$("#footer").jqmData('previousFooterSelectedTab', $('#footer .ui-btn-active').attr('id'));
							break;
						case "footer-more-btn":
                            scope.openFooterPopup(e);
							break;
						default:
							target = target.replace('-btn', '').replace('footer-', '');
                            utilities.eventAggregator.trigger(target);
					}
				}
			},
			handleKeyDown: function (e) {
				if (e.which === 13) {
					e.preventDefault();

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

		return FooterView;
	}
);