define([
        //Paths from config.js, each passed into the following anonymous function
        'Global',
        'App',
        'PatientContext',
        'MainView',
        'HeaderView',
        'FooterView',
        'BookingMainView',
        'VaacMainView',
        'BookingDialogView',
        'AboutDialogView',
        'PatientSimpleDetailsView',
        'LoadSearchView',
        'SessionWarning',
        'SessionExpired',
        'SplashDialogView',
        'User',
        'UserSession',
        'ApptRequestDetails',
        'AppointmentRequest',
        'Resources'
    ],
    function (Global, App, PatientContext, MainView, HeaderView, FooterView, BookingMainView, VaacMainView,
              BookingDialogView, AboutDialogView, PatientSimpleDetailsView, LoadSearchView, SessionWarning, SessionExpired, SplashDialogView, user, UserSession, ApptRequestDetails, AppointmentRequest, resources) {
        // http://documentcloud.github.com/backbone/#Router

        var AppRouter = Backbone.Router.extend({
            initialize: function (options) {
                var utilities = Global.getUtilities();
                this.options = options || {};
                this.vent = (options && options.vent) || new Backbone.Wreqr.EventAggregator();
                this.title = App.defineResourceTitles().title;
                this.location = window.location.hash;
                utilities.globalInit({
                    user: user,
                    customHeight: 102,
                    spinnerOptions: App.getSpinnerOptions()
                });

                var locationArray = window.location.href.split('?token='),
                    location = locationArray[0],
                    token = locationArray[1];

                if (token && token.length) {
                    var base = document.getElementsByTagName('head')[0].getElementsByTagName('base')[0];
                    base.setAttribute('href',base.getAttribute('href').split('?token')[0]);
                    if (history.replaceState) {
                        history.replaceState({}, '', '/scheduling-manager/');
                    } else {
                        window.location.href = location;
                    }
                }

                window.onbeforeunload = function(){
                    AppointmentRequest.clearInstance();

                    return void 0;
                };

                $(window).on('unload', function(){
                    AppointmentRequest.clearInstance();

                    return void 0;
                });
            },
            routes: {
                '': 'defaultAction',
                'booking': 'showBooking',
//                'consults': 'showConsults',
                'veteran-requests': 'showVaac',
//                'waitlist': 'showWaitList',
                'book-appointment': 'showBookingDialog',
                'cancel-appointment': 'showCancelDialog',
                'about': 'showAboutDialog',
                'splash': 'showSplashDialog',
//	            'search': 'showSearch',
                //Default
                '*actions': 'defaultAction'
            },

            showBooking: function () {
                if(getCookie("accept") !== "true")
                    this.openPage(new SplashDialogView());
                else
                    this.openPage(new BookingMainView());



            },

            /*showConsults: function () {
             if(getCookie("accept") !== "true")
             this.openPage(new SplashDialogView());
             else
             this.openPage(new ConsultsMainView());
             },*/

            showVaac: function () {
                if(getCookie("accept") !== "true")
                    this.openPage(new SplashDialogView());
                else
                    this.openPage(new VaacMainView());
            },

            /*showWaitList: function () {
             if (getCookie("accept") !== "true")
             this.openPage(new SplashDialogView());
             else
             this.openPage(new WaitListMainView());
             },*/

            showBookingDialog: function () {
                if(getCookie("accept") !== "true")
                    this.openPage(new SplashDialogView());
                else {
                    if (ApptRequestDetails.instance().isValid()) {
                        this.openPage(new BookingDialogView({"notesMax": 160}));
                    } else {
                        history.back();
                    }
                }
            },
            showCancelDialog: function(){
                if(getCookie("accept") !== "true")
                    this.openPage(new SplashDialogView());
                else {
                    if (ApptRequestDetails.instance().isValid()){
                        this.openPage(new BookingDialogView({"notesMax": 200, "cancel": true}));
                    } else {
                        history.back();
                    }
                }
            },

            showAboutDialog: function (){
                if(getCookie("accept") !== "true")
                    this.openPage(new SplashDialogView());
                else
                    this.openPage(new AboutDialogView());
            },

            showSplashDialog: function (){
                this.openPage(new SplashDialogView());
            },

            /*showSearch: function () {
             if(getCookie("accept") !== "true")
             this.openPage(new SplashDialogView());
             else {
             new LoadSearchView({
             router: this,
             vent: this.vent
             });
             }
             },*/

            defaultAction: function () {
                appRouter.navigate('#splash', {trigger: true});
            },
            //route
            openPage: function (page) {
                var pageType = $(page.el).eq(0).attr('data-role'),
                    that = this;

                PatientSimpleDetailsView.remove();
                PatientContext.instance().resume(function() {
                    if (pageType === 'dialog') {
                        page.render();
                        $.mobile.changePage("#" + page.id, {transition: 'pop'});
                    } else {
                        that.buildMain.call(this, page);
                        that.activateFooter(Backbone.history.fragment);

                        $('#main').animationComplete(function () {
                            new HeaderView().render();
                            page.render();
                            if ($('#content-primary').hasClass("closed")) {
                                Global.getUtilities().slidePrimary();
                            }
                        });
                        $.mobile.changePage("#main", {allowSamePageTransition: true});
                    }
                })
            },
            activateFooter: function (page) {
                if (!page) {
                    page = "veteran-requests";
                }
                $('#footer a, #footer-menu-popup li, #footer-menu-popup a').removeClass('ui-btn-active');
                $('#footer a[href="#' + page + '"]').addClass('ui-btn-active');
                $('#footer-menu-popup a[href="#' + page + '"]').parents('li').addClass('ui-btn-active');
            },
            buildMain: (_.once(function () {
                MainView.instance().render();
            }))
        });

        var appRouter = new AppRouter(),
            eventAggregator = Global.getUtilities().eventAggregator;

        _.map(appRouter.routes, function (method, key) {
            eventAggregator.on(key, function () {
                appRouter.navigate('#' + key, {trigger: true});
            });
        });

        eventAggregator.on("do:login", function(){
            Global.getUtilities().login();
        });

        eventAggregator.on("do:logout", function(){
            Global.getUtilities().logout();
        });

        eventAggregator.on("do:launchpad", function(){
            Global.getUtilities().launchpad();
        });

        eventAggregator.on("show:session:expired", function(){
            appRouter.navigate("#session-expired", {trigger:false});
            appRouter.openPage(new SessionExpired());
        });

        eventAggregator.on("show:session:warning", function(){
            appRouter.sessionWarning = appRouter.sessionWarning || new SessionWarning({model:UserSession.instance()});
            appRouter.navigate("#session-warning", {trigger:false});
            if(!appRouter.sessionWarning.current){
                appRouter.openPage(appRouter.sessionWarning);
            }
        });

        eventAggregator.on("disable:patient:tab", function () {
            var $patientButton = $('#patient-button'),
                $calendarButton = $('#calendar-button');

            $patientButton.addClass('ui-disabled');
            $patientButton.data().disabled = true;

            if ($patientButton.data().active) {
                $patientButton.removeClass('ui-btn-active');

                $calendarButton.addClass('ui-btn-active');
                $calendarButton.trigger('tap');
            }
        });

        eventAggregator.on("do:session:refresh", function(fromWarning){
            $.ajax({
                url: user.url,
                success: function(){
                    if(fromWarning){
                        history.back();
                    }
                }
            });
        });

        eventAggregator.on("refresh:patient:incontext", function(){
            PatientContext.instance().reloadPatient();
        });

        eventAggregator.on("footer", function () {
            $('#footer-menu-popup').remove();

            var footerView = new FooterView();

            var $generatedFooter = footerView.render(),
                $footer = $('#footer');
            $footer.empty().append($generatedFooter);

            if (!$footer.find('div[data-role="navbar"]').hasClass('ui-navbar')) {
                try {
                    $footer.trigger('create');
                } catch (err) {
                    // JUSTIFICATION: Ignore error on trigger.  If the footer event is called around the same time, the trigger causes an error
                }
            }

            $('#footer-menu-popup').removeAttr('style');
            appRouter.activateFooter(Backbone.history.fragment);
        });

        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for(var i=0; i<ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1);
                if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
            }
            return "";
        }

        Backbone.history.start();
    });