/*
 * app.shell.js
 * Shell module for SPA
 */

/*jslint         browser : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/
/*global $, app */

app.shell = (function () {
    'use strict';
    //---------------- BEGIN MODULE SCOPE VARIABLES --------------

    var

        stateMap = {
            $container: undefined,
            anchor_map: {},
            user: {
                authenticated: false,
                token: '',
                name: ''
            },
            apiUrl: '',
            search_cache: {
                has_cache: false
            }
        },
        activateMenuItem,
        onLogin, onLogout,
        initModule;
    //----------------- END MODULE SCOPE VARIABLES ---------------

    //------------------- BEGIN UTILITY METHODS ------------------

    //hide menu item by class specified or show it
    //depending on it's current state
    activateMenuItem = function (menuClass) {
        $("." + menuClass).removeClass("app-mnu-inactive");
        $("." + menuClass).addClass("app-mnu-active");
    }

    //-------------------- END UTILITY METHODS -------------------



    //------------------- BEGIN EVENT HANDLERS -------------------

    onLogin = function (event, login_user) {
        //store creds
        store.set('rockfish.usercreds', stateMap.user);
        //Go to the dashboard
        page('#!/dashboard/');
        return false;
    };

    onLogout = function (event) {
        store.clear();
        stateMap.user.authenticated = false;
        stateMap.user.name = '';
        stateMap.user.token = '';
        page('#!/authenticate/');
        return false;
    };
    //-------------------- END EVENT HANDLERS --------------------



    //------------------- BEGIN PUBLIC METHODS -------------------   
    initModule = function ($container) {

        document.title = 'Rockfish ' + app.api.rockFishVersion;
        //PRE FLIGHT CHECK
        //local storage required
        if (!store.enabled) {
            alert('Local storage is not supported by your browser. Please disable "Private Mode", or upgrade to a modern browser.');
            return;
        }

        //wait indicator for ajax functions
        $(document).ajaxStart(function () {

            //disable all buttons
            $('.app-frm-buttons button').prop('disabled', true).addClass('disabled');
            //$('.app-frm-buttons button').attr('disabled', 'disabled');
            $("body").css("cursor", "progress");
            //add app-ajax-busy style to buttons div where user clicked          
            $('.app-frm-buttons').addClass('app-ajax-busy');

        }).ajaxStop(function () {

            //with delay in case it's too fast to see
            setTimeout(function () {
                $('.app-frm-buttons button').prop('disabled', false).removeClass('disabled');
                //$('.app-frm-buttons button').removeAttr('disabled');              
                $("body").css("cursor", "default");
                $('.app-frm-buttons').removeClass('app-ajax-busy');
            }, 250);

        });

        // load HTML and map jQuery collections
        stateMap.$container = $container;
        $container.html(Handlebars.templates['app.shell']({}));

        //determine API url and save it
        stateMap.apiUrl = app.util_b.getApiUrl();


        //fetch stored creds if available
        var creds = store.get('rockfish.usercreds');
        if (creds) {

            //Show the logout item in the menu
            $(".app-mnu-logout").removeClass("app-hidden");

            stateMap.user.authenticated = true;
            stateMap.user.name = creds.name;
            stateMap.user.token = creds.token;
        }


        $.gevent.subscribe($container, 'app-login', onLogin);
        $.gevent.subscribe($container, 'app-logout', onLogout);


        //ROUTES
        //
        page.base('/app.html');
        page('*', beforeUrlChange);
        page('/authenticate', authenticate);
        page('/', dashboard);
        page('/dashboard', dashboard);
        page('/search', search);
        page('/logout', function () {
            $.gevent.publish('app-logout');
        });

        page('/customers', customers);
        page('/customer_edit/:id', customer_edit);
        page('/customer_contact_edit/:id/:cust_id', customer_contact_edit);
        page('/customer_contacts/:id', customer_contacts);
        page('/customer_notifications/:id', customer_notifications);
        page('/customer_notification_edit/:id/:cust_id', customer_notification_edit);
        page('/customer_sites/:id', customer_sites);
        page('/customer_site_edit/:id/:cust_id', customer_site_edit);

        page('/purchases/:id', purchases);
        page('/purchase_edit/:id/:site_id', purchase_edit);

        page('/incidents/:id', incidents);
        page('/incident_edit/:id/:site_id', incident_edit);

        page('/trials/:id', trials);
        page('/trial_edit/:id/:site_id', trial_edit);

        page('/license', license);
        page('/license_templates', license_templates);
        page('/license_requests', license_requests);
        page('/license_request_edit/:id', license_request_edit);

        page('*', notFound);
        page({
            hashbang: true
        });
        // /ROUTES




    };
    // End PUBLIC method /initModule/

    var beforeUrlChange = function (ctx, next) {
        //bypass stuff below if about to logout
        if (ctx.path == '/logout') {
            return next();
        }
        stateMap.mediaSize = app.util_b.getMediaSize();
        if (stateMap.mediaSize == "app-large-mode") {
            stateMap.$menu = $('#app-shell-nav-side');
        } else {
            stateMap.$menu = $('#app-shell-nav-bottom');
        }


        //Not logged in and trying to go somewhere but authenticate?
        if (!stateMap.user.authenticated) {
            //hide nav
            stateMap.$menu.hide({
                duration: 500
            });
            //page nav to authenticate
            if (ctx.path != '/authenticate/')
                return page('#!/authenticate/');

        } else {
            stateMap.$menu.show({
                duration: 500
            });
            menuShowAll();
        }


        next();
    }

    var authenticate = function (ctx) {
        // activateMenuItem('app-mnu-dashboard');

        app.authenticate.configModule({
            context: ctx
        });
        app.authenticate.initModule();
    }

    var dashboard = function (ctx) {
        activateMenuItem('app-mnu-dashboard');
        app.dashboard.configModule({
            context: ctx
        });
        app.dashboard.initModule();
    }

    var search = function (ctx) {
        activateMenuItem('app-mnu-search');
        app.search.configModule({
            context: ctx
        });
        app.search.initModule();
    }

    var customers = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customers.configModule({
            context: ctx
        });
        app.customers.initModule();
    }

    var customer_edit = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customer_edit.configModule({
            context: ctx
        });
        app.customer_edit.initModule();
    }

    var customer_contacts = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customer_contacts.configModule({
            context: ctx
        });
        app.customer_contacts.initModule();
    }

    var customer_contact_edit = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customer_contact_edit.configModule({
            context: ctx
        });
        app.customer_contact_edit.initModule();
    }


    var customer_notifications = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customer_notifications.configModule({
            context: ctx
        });
        app.customer_notifications.initModule();
    }

    var customer_notification_edit = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customer_notification_edit.configModule({
            context: ctx
        });
        app.customer_notification_edit.initModule();
    }

    var customer_sites = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customer_sites.configModule({
            context: ctx
        });
        app.customer_sites.initModule();
    }

    var customer_site_edit = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.customer_site_edit.configModule({
            context: ctx
        });
        app.customer_site_edit.initModule();
    }



    var purchases = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.purchases.configModule({
            context: ctx
        });
        app.purchases.initModule();
    }

    var purchase_edit = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.purchase_edit.configModule({
            context: ctx
        });
        app.purchase_edit.initModule();
    }



    var incidents = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.incidents.configModule({
            context: ctx
        });
        app.incidents.initModule();
    }

    var incident_edit = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.incident_edit.configModule({
            context: ctx
        });
        app.incident_edit.initModule();
    }



    var trials = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.trials.configModule({
            context: ctx
        });
        app.trials.initModule();
    }

    var trial_edit = function (ctx) {
        activateMenuItem('app-mnu-customers');
        app.trial_edit.configModule({
            context: ctx
        });
        app.trial_edit.initModule();
    }


    var license = function (ctx) {
        activateMenuItem('app-mnu-license');
        app.license.configModule({
            context: ctx
        });
        app.license.initModule();
    }

    var license_templates = function (ctx) {
        activateMenuItem('app-mnu-license');
        app.license_templates.configModule({
            context: ctx
        });
        app.license_templates.initModule();
    }

    var license_requests = function (ctx) {
        activateMenuItem('app-mnu-license');
        app.license_requests.configModule({
            context: ctx
        });
        app.license_requests.initModule();
    }

    var license_request_edit = function (ctx) {
        activateMenuItem('app-mnu-license');
        app.license_request_edit.configModule({
            context: ctx
        });
        app.license_request_edit.initModule();
    }

    var notFound = function (ctx) {
        console.log("404 - Context variable is:");
        console.log(ctx);
        dashboard(ctx);

    }

    //called before every route change
    var menuShowAll = function (ctx) {


        //show all menu items even if hidden
        $("#app-shell-nav-side li").addClass("app-mnu-inactive");
        $("#app-shell-nav-bottom li").addClass("app-mnu-inactive");

        $("#app-shell-nav-side li").removeClass("app-mnu-active");
        $("#app-shell-nav-bottom li").removeClass("app-mnu-active");
    }



    return {
        initModule: initModule,
        stateMap: stateMap
    };
    //------------------- END PUBLIC METHODS ---------------------
}());