define([
    'Global',
    'FooterView',
    'PrimaryView',
    'SecondaryView',
    'RightSubHeaderView',
    'DefaultView',
	'CalendarData',
    'LeftPanelNavigationView',
    'PatientSimpleDetailsView',
    'Text!../html/templates/main-double-column.html'
],
    function (Global, FooterView, primaryView, secondaryView, RightSubHeaderView,
              DefaultView, CalendarData, LeftPanelNavigationView, PatientSimpleDetailsView, mainTemplate) {
        'use strict';

        var singleInstance,
            MainView = Backbone.View.extend({
            id: "main",
            tagName: 'div',
            className: 'ui-page',
            attributes: {
                'data-role': 'page'
            },
            initialize: function () {
                var that = this;

				this.utilities = Global.getUtilities();
                this.mainTemplate = _.template(mainTemplate);
				CalendarData.instance();

                this.listenTo(that.utilities.eventAggregator, "closePanel", function() {
					$('#left-navigation-panel').panel("close");
                });

                this.listenTo(that.utilities.eventAggregator, "openPanel", function() {
					$('#left-navigation-panel').panel("open");
                });
            },
            render: function () {
                var $el = this.$el,
					footerView = new FooterView(),
                    leftPanelNavigationView = new LeftPanelNavigationView({parent:this});

            	$el.append(this.mainTemplate()).find("#footer")
					.append(
						footerView.render()
					);

                this.polyFills();

				$('body')
                    .prepend($el);

                leftPanelNavigationView.render();
                DefaultView.instance();

                //issue with subheader not being rendered in time.
                this.waitForSubHeader();

                $(window).resize();
            },

            polyFills: function () {
                var ie = this.ie();
                if (ie && ie === 9) {
                    this.$el
                        .find('#content').addClass('no-placeholder');
                }
            },

            ie: function(){
                    var isUndefined,
                        v = 3,
                        div = document.createElement('div'),
                        all = div.getElementsByTagName('i');

                    while (
                        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
                            all[0]
                        );

                    return v > 4 ? v : isUndefined;

            },
            events: {
                "keyup .no-placeholder .input [placeholder]": "ie9placeholder",
                "keyup .no-placeholder .textarea [placeholder]": "ie9placeholder",
                "click #slide-btn": "slidePrimary",
                "swipe #slide-btn, #sub-header .ui-header": "slidePrimary",
                "click #left-navigation": "toggleLeftNavigationPanel",
	            "keydown #left-navigation": "handlePanelTab"
            },
	        handlePanelTab: function (e) {
		        var $openPanel = $('#left-navigation-panel.ui-panel-open'),
			        $panelBtns = $openPanel.find('button');

		        if ($openPanel.length) {
			        if (e.which === 9) {
				        e.preventDefault();

				        if (e.shiftKey) {
					        $panelBtns.eq($panelBtns.length - 1).focus();
				        } else {
					        $panelBtns.eq(0).focus();
				        }
			        }
		        }
	        },
            toggleLeftNavigationPanel: function () {
                $('#left-navigation-panel').panel("toggle");               
            },
            ie9placeholder: function (e) {
                var $this = $(e.currentTarget),
                    $parent = $this.parents('.input, .textarea');

                if ($this.val() !== "" &&  !$parent.hasClass('typed')) {
                    return $parent.addClass('typed');
                }

                if ($this.val() === "" && $parent.hasClass('typed')) {
                    return $parent.removeClass('typed');
                }
            },

			createUI: function () {
				this.ui = {
					calendarTabs: this.$el.find('#calendar-tabs'),
					primaryPane: this.$el.find('.ctn-grey'),
					secondaryPane: this.$el.find('.ui-block-content').eq(1)
				}
			},

			toggleVisibility: function () {
				this.ui.calendarTabs.add(this.ui.primaryPane)[this.ui.secondaryPane.hasClass('closed') ? 'hide' : 'show']();
			},

            slidePrimary: function () {
				var timeoutID, view = this;

				_.once(this.createUI());
                this.utilities.slidePrimary('.ui-block-content');

				var fix508Tabbing = function () {
					timeoutID = window.setTimeout(function () {
						view.ui.calendarTabs.add(view.ui.primaryPane).css({visibility: [view.ui.secondaryPane.hasClass('closed') ? 'hidden' : '']});
					}, 400);
				};

				fix508Tabbing();

            },

            waitForSubHeader: function(){
                var interval = setInterval(function(){
                    if( getSubHeaderRight().is(":visible") ){
                        PatientSimpleDetailsView.instance().render();
                        clearInterval(interval);
                    }
                }, 500 );
            },

            clearView: function (options) {
                this.options = options || {};

                var $content = getContent(),
                    $mainContent = getMainContent(),
                    $sidebarContent = getSidebarContent(),
                    $subHeaderLeft = getSubHeaderLeft(),
	                $subHeaderRight = getSubHeaderRight(),
	                classesForLeftCol = this.options.classesForLeftCol || "",
	                classesForRightCol = this.options.classesForRightCol || "";

                if (!$mainContent.length) {
                    $content.empty();
                    getSubHeader().empty();

                    secondaryView.render({"classes": classesForLeftCol});
                    primaryView.render({"classes": classesForRightCol});
                } else {
	                var $leftColumn = getContent().find('.ui-block-sidebar'),
		                $rightColumn = getContent().find('.ui-block-content');

                    $mainContent.empty();
                    $sidebarContent.empty();
                    $subHeaderLeft.empty();
	                $subHeaderRight.empty();

	                $subHeaderLeft[0].className = "ui-block-sidebar " + classesForLeftCol;
	                $leftColumn[0].className = "ui-block-sidebar ctn-grey bdr-right scrollable " + classesForLeftCol;
	                getSubHeaderRight()[0].className = "ui-block-content " + classesForRightCol;
	                $rightColumn[0].className = "ui-block-content " + classesForRightCol;
                }

	            new RightSubHeaderView().render();
                this.clearPopups();
            },

            clearPopups: function () {
                var $page = getPage();

                $.each($page.find('.ui-popup'), function (key, value) {
                    var $value = $(value);

                    if (!($value[0].id === "footer-menu-popup")) {
                        $value.remove();
                    }
                });
            }
        });

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

        return MainView;
    }
);
