$(function() {
    var htmlElement = $('html');
    var mainCanvasElement = $('.l-canvas');
    var offCanvasElement = $('.l-off-canvas');
    var toggleButtonElement = $('#toggle-off-canvas-left');
    var offCanvasActiveClass = 's-active';
    var offCanvasActiveHtmlClass = 's-off-canvas-active';

    /**
     * @description Shows the off canvas nav.
     */
    function showNav() {
        offCanvasElement.show();
        htmlElement.addClass(offCanvasActiveHtmlClass);
        mainCanvasElement.on('click', hideNav);
        mainCanvasElement.css({ 'cursor': 'pointer' });
        toggleButtonElement.addClass(offCanvasActiveClass);
        $(window).scrollTop(0);
    }

    /**
     * @description Hides the off canvas nav.
     */
    function hideNav() {
        offCanvasElement.hide();
        htmlElement.removeClass(offCanvasActiveHtmlClass);
        mainCanvasElement.off('click', hideNav);
        mainCanvasElement.css({ 'cursor': 'default' });
        toggleButtonElement.removeClass(offCanvasActiveClass);
    }

    /**
     * @description Initializes the off canvas nav toggle.
     *              All the "handled" logic below prevents ghost clicks on touch devices. references:
     *              http://ariatemplates.com/blog/2014/05/ghost-clicks-in-mobile-browsers/
     *              http://stackoverflow.com/questions/7018919
     */
    toggleButtonElement.on('touchstart click', function(e) {
        e.stopPropagation();
        e.preventDefault();

        if(e.handled !== true) {
            if (toggleButtonElement.hasClass(offCanvasActiveClass)) {
                hideNav();
            } else {
                showNav();
            }

            // Handle the event.
            e.handled = true;
        } else {
            return false;
        }
    });
});