/**
 * Redmine - project management software
 * Copyright (C) 2006-  Jean-Philippe Lang
 * This code is released under the GNU General Public License.
 */

// generic layout specific responsive stuff goes here

function openFlyout() {
  $('html').addClass('flyout-is-active');
  $('#main, #header').on('click.close-flyout', function(e){
    e.preventDefault();
    e.stopPropagation();
    closeFlyout();
  });
}

function closeFlyout() {
  $('html').removeClass('flyout-is-active');
  $('#main, #header').off('click.close-flyout');
}


function isMobile() {
  return $('.js-flyout-menu-toggle-button').is(":visible");
}

function setupFlyout() {
  var mobileInit = false,
    desktopInit = false;

  /* click handler for mobile menu toggle */
  $('.js-flyout-menu-toggle-button').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
    if($('html').hasClass('flyout-is-active')) {
      closeFlyout();
    } else {
      openFlyout();
    }
  });

  /* bind resize handler */
  $(window).resize(function() {
    initMenu();
  })

  /* menu init function for dom detaching and appending on mobile / desktop view */
  function initMenu() {

    var _initMobileMenu = function() {
      /* only init mobile menu, if it hasn't been done yet */
      if(!mobileInit) {

        $('#main-menu > ul').detach().appendTo('.js-project-menu');
        $('#top-menu .general-menu .top-menu__links > ul').detach().appendTo('.js-general-menu');
        $('#sidebar > *').detach().appendTo('.js-sidebar');
        $('#account ul').detach().appendTo('.js-profile-menu');

        mobileInit = true;
        desktopInit = false;
      }
    }

    var _initDesktopMenu = function() {
      if(!desktopInit) {

        $('.js-project-menu > ul').detach().prependTo('#main-menu');
        $('.js-general-menu > ul').detach().prependTo('#top-menu .general-menu .top-menu__links');
        $('.js-sidebar > *').detach().appendTo('#sidebar');

        var accountMenuParent = $('#account .dropdown-content');
        if (accountMenuParent.length === 0) {
          accountMenuParent = $('#account');
        }
        $('.js-profile-menu > ul').detach().appendTo(accountMenuParent);

        desktopInit = true;
        mobileInit = false;
      }
    }

    if(isMobile()) {
      _initMobileMenu();
    } else {
      _initDesktopMenu();
    }
  }

  // init menu on page load
  initMenu();
}

$(document).ready(setupFlyout);
