  /**
   * TaskList jQuery plugin 1.0
   * Created by Rene Theriault
   * November 2015
   * Last Modified: January 16, 2017
   **/
  /** Applies to topics in Features_standard and features_optional folder **/
  /** Requirements:

  1) This goes in <head>
       <script type="text/javascript" language="javascript1.2" src="../jquery-3.5.1.min.js" charset="utf-8"></script>


  2) This goes just before the first <h1> of topics that are in the Task List

       <div class="backToTaskList" id="taskList" style="display: none;">
        <br />
        <a href="../task_help.html" style="margin-left: 10px;">Back to Task List</a> | <a href="#" id="more" class="more" name="more">Show More</a>
         <a name="exit" onclick="toggleTaskMode();"><img class="exitBtn" title="Exit" src="../exit.png"></a>
      </div>
      <div class="spacer" style="display: none;"></div>


      Topics NOT in the list need this:

      <div class="backLink" style="display: none;">
        <br />
        <a href="#" onClick="window.history.back(-1);" style="margin-left: 10px;">Back</a></span> | <a href="" onClick="window.history.go(1)">Forward</a></span> | <a href="../task_help.html">Task List</a></span>
      </div>
      <div class="spacer" style="display: none;"></div>

  3) Put "Contents" div wrapper just before h1 element and before closing body element

      <div id="contents">
       </div>

  4) ID in h2 wrapper for Device Support section

       <h2 id="deviceSupport">Device Support</h2>

  5) Div wrapper around programming section with id = "programming" and class = "programming" h2 wrapper

       <div id="programming">
          <h2 class="programming">
            Programming
          </h2>
       </div>                               <--- Goes directly before <h2 id="deviceSupport">

  6) Functions - goes above closing </body> tag
      <script type="text/javascript" language="javascript1.2" src="../TaskList.js" charset="utf-8"></script>
       <script type="text/javascript" language="javascript1.2">
       checkContainerAndReferrer();
       </script>

       **/
  /* Unhide the "Back to main list" link when topic called from Task List in ESM */
  /* Also hides non-programming related content when topic loaded into Task List in ESM*/
  /* Stores the original text of the h2 element for reinsertion when page toggled to show more content.*/
  /* Removes ESM quick links and Lightboxlink class when Help installed locally */
  /* The class stops lightboxed images from displaying which is not good*/
  /* Removes the note about links to the PDF and Excel versions of the Feature-Phone Matrix not*/
  /* working when Help is locally hosted--i.e., on C drive. */
  switch (window.location.protocol) {
      case 'http:':
      case 'https:':
          //remote file over http or https
  		  $('#snippet').css('display','none');
          break;
      case 'file:':
          //local file
          $(".ESMlink").remove();
          $(".Lightboxlink").removeClass("Lightboxlink");
          break;
      default:
          //some other protocol
  }

  (function(window, undefined) {
      var originalh2Text = $('h2.programmingtask').text();
      window.originalh2Text = originalh2Text;
      //alert($('h2.programmingtask').text());
  })(window);



  $(document).ready(function() {
      var toggle_switch = $('#more');
      var isInIFrame = (window.name);
	  var hash = window.location.hash;
      var url = window.location.href
      option = url.search(/[?]option=/gi); // returns -1 if no match is found.
	  
	  //checks URL for hash fragment (indicating that topic was loaded by a click event on anchor link )
	  //and displays all content if the topic has a multiTask id
	  if (($("body").prop("id") == 'multiTask') && (hash !== null) && (option == -1) && (isInIFrame == "TaskListWindow")) {
	  
	   //alert("This is a multitask page");
	   $('#contents, div.spacer').css('display','block');
	  }
	  
      else if ((option != -1) && (isInIFrame == "TaskListWindow")) {
          showContent();
          changeStyle();
          hideNonProg();
          removeShowLink();
          noProgReqdTxt();
          destroyBlankPara();
		  
      } else if //hides content in programming tasks when displayed from deep link and sets ShowMore/ShowLess to ShowMore

      ((isInIFrame == "TaskListWindow") && ((option == -1) && ($('#ProgrammingTask').length > 0))) {

          //alert("This is a programming topic because it contains ProgrammingTask or allTask id");

          changeStyle();
          hideNonProg();
          removeShowLink();
          noProgReqdTxt();
          destroyBlankPara();
          toggle_switch.html('<img class="exitBtn" title="Show More" src="../tasklistmore.png">');
 		   
      } else {

          return false;
      }
  });



  function showContent() {
      $('.backToTaskList, div.spacer, span.toggleTaskList, #RelatedTopics').hide();
  }

  function removeShowLink() {
      $("body").each(function() {
          if ($(this).prop("id") == 'allTask') {
              $("a.more").remove();
          }
      });
  }

  /* Restyle h2 to match styling of h1*/

  function changeStyle() {
      $("h2.programmingtask").css({
          "color": "#199bd8",
          "font-weight": "normal",
          "font-style": "normal",
          "font-size": "14pt",
          "font-family": "Verdana",
          "margin-top": "60px" //was 45
      });
      /* Rewrite h2 by getting the id of the h1 element */
      var replaceWith = $("h2.programmingtask, h1.programmingtask").attr('id');
      //  alert($('h2.programmingtask').attr('id'));
      $("h2.programmingtask, h1.programmingtask").text(replaceWith);
  }

  /* Hide everything but the programming section when topic in Task List*/

  function hideNonProg() {
      $('#contents').hide();
      $("h1").css({
          "margin-top": "60px"
      });
      $('span.toggleTaskList').hide();
      $('#RelatedTopics').hide();
      $('#ProgrammingTask').appendTo('body');
  }
  /* Show hidden content on Show More click event when topic in Task List*/
  /* Also undoes DOM & CSS manipulations applied by preceding functions*/

  /* Removes the empty paragraph at the end of topics which is there because the search cuts off topic heading */
  function destroyBlankPara() {
      var isInIFrame = (window.name);
      if (isInIFrame == "TaskListWindow") {
          $("p.spacer").remove();
      };
  };



  var toggleMoreLess = function() {
      var collapse_content_selector = $("#contents, span.toggleTaskList, #RelatedTopics");
      var toggle_switch = $(this);
      $(collapse_content_selector).toggle(function() {
          if ($(this).css('display') == 'none') {
              toggle_switch.html('<img class="exitBtn" title="Show More" src="../tasklistmore.png">');
              //alert ("Show More link showing")
              window.location.hash = '#showMore'; //preserves nav links on nav Back
              $("h2.programmingtask").css({
                  "color": "#199bd8",
                  "font-weight": "normal",
                  "font-size": "14pt",
                  "font-family": "Verdana",
                  "margin-top": "60px" //was 50
              });

              $('#ProgrammingTask').appendTo('body');
              $("h1").css({
                  "margin-top": "60px" //was 50
              });
              /* Rewrite h2 by replacing it with its ID */
              var replaceWith = $("h2.programmingtask").attr('id');
              //  alert($('h2.programmingtask').attr('id'));
              $("h2.programmingtask").text(replaceWith);

          }
          if ($(this).css('display') == 'block') {
              toggle_switch.html('<img class="exitBtn" title="Show Less" src="../tasklistless.png">');
              //alert ("Show Less link showing")
              $("h2.programmingtask").css({
                  "color": "#000000",
                  "font-weight": "Bold",
                  "font-size": "11pt",
                  "font-family": "Verdana",
                  "margin-top": "16px" //was 14pt
              });

              if ($('#deviceSupport').length > 0) {
                  $("#ProgrammingTask").insertBefore($("#deviceSupport"));
                  $("h2.programmingtask").html("Programming");
                  //alert($('h2.programmingtask').text());
              } else if ($('#insertTaskhere').length > 0) {
                  $("#ProgrammingTask").insertBefore($("#insertTaskhere"));

                  $("h2.programmingtask").html(originalh2Text);
                  //alert("h2 content is: " + $("h2.programmingtask").text());

              }
              window.location.hash = '#showLess'; //preserves nav links on nav Back
              $("h1").css({
                  "margin-top": "50px" //was 50
              });
              $("div.spacer").remove();

          }
          if ($('#contents').css('display') == 'block') {
              $("p:contains('This feature does not require programming.')").html(
                  "This feature does not require programming.");
          }


          if ($('#contents').css('display') == 'none') {
              noProgReqdTxt();
          }

      });

  };

  /* Test for id of page container to see if it's the ESM task pane
  and whether the page in it came from clicking a link
  in the Task List. If both tests are true, it means the page
  is in the Help browser so don't show the Back | Forward links.*/
  /*********************************************/
  /* MUST BE CALLED BY ALL TOPICS IN THE HELP */
  /*********************************************/
  function checkContainerAndReferrer() {
      var isInIFrame = (window.name);
      var isFromTaskList = $(location).attr('search');
      var isDeepLinkShowVal = $("a.more span").attr("class"); // test current state of Show More | Show Less link
      var isDeepLinkContentsVal = $("#contents").attr('style'); // test whether Contents div has display attributes
      /* if isDeepLinkShowVal = Show More and isDeepLinkContentsVal = undefined (i.e., no display attributes exist) then the topic must have come from a link to a Task List topic and not the Task List nor via the Back link. In which case, the whole topic is showing and therefore needs to show the Show Less link */

      if (isInIFrame == "TaskListWindow" && isFromTaskList == "?option=taskList") {
          //alert("Page is from ESM and was referred from Task List")
          //alert($("#contents").attr("style"));
          $('.backLink').hide();
          $('.HideInTaskHelp').remove();
          $('.TaskHelpOnly').toggle();
          overrideDefaultNav();
          //preventLinkOpenInNewWin();
      } else if (isInIFrame == "TaskListWindow" && isDeepLinkShowVal == '<img class="exitBtn" title="Show More" src="../tasklistmore.png">' && isDeepLinkContentsVal === undefined) {
          //alert("Page is from ESM and came from a deep link");
          //alert($("a.more span").attr("title"));
          //alert($("#contents").attr("style"));
          $(".backLink, .backToTaskList, div.spacer").show();
          //$("a.more span").replaceWith('<span class="fa fa-chevron-circle-up fa-2x" title="Show Less"></span>');
          $("a.more span").replaceWith('<img class="exitBtn" title="Show Less" src="../tasklistless.png">');
          // $(".more").html('Show Less');
          $('.HideInTaskHelp').remove();
          $('.TaskHelpOnly').toggle();
          //preventLinkOpenInNewWin();
      } else if (isInIFrame == "TaskListWindow" && isDeepLinkContentsVal === undefined) {
          //alert("Page is in Task browser and was referred from deep link")
          //alert($("#contents").attr("style"));
          //alert($("a.more").attr("class"));
          $(".backLink, .backToTaskList, div.spacer").show();
          $('span.toggleTaskList, #RelatedTopics').toggle();
          $("a.more").replaceWith('<a id="more" class="more" href="#" name="more"><img class="exitBtn" title="Show Less" src="../tasklistless.png"></a>');

      } else {
          //alert("Page is from standalone Help")
          $(".backLink, div.spacer").hide();
          $("div#ProgrammingTask").css({
              "margin-top": "0px"
          })
      }
      //preventLinkOpenInNewWin();

  }

  checkContainerAndReferrer();
  /*Allows jQuery functions to fire when Back button used.
  Otherwise hidden divs fail to show when they should.*/
  function overrideDefaultNav() {
      history.navigationMode = 'compatible';
      $(document).ready(function() {
          //alert('overrideDefaultNav fired');
          $('.backToTaskList').show();
      });
  }
  /* Closes the Task pane */


  $(document).ready(function() {
      $("a.more , #backLink").on('click', toggleMoreLess);

      //alert("Click event fired on Show More / Show Less")
  });

  $(window).scroll(function() {
      var scroll = $(window).scrollTop();
      if (scroll >= 50) {
          $(".backToTaskList, .backLink").addClass("darkHeader");
      } else {
          $(".backToTaskList, .backLink").removeClass("darkHeader");
      }
  });


  /* Prevents links for opening in new window/tab via use of context menu and keyboard shortcuts (e.g.m ctrl+click) */
  function preventLinkOpenInNewWin() {
      var isInIFrame = (window.name);
      //var links = matches = $('#contents a'); 
      //var links = matches = $("#contents a:not('.ESMlink')");
      var links = matches = $("#contents a:not('.ESMlink, .Lightboxlink')");
      if (isInIFrame == "TaskListWindow") {
          for (var i = 0; i < links.length; i++) {
              links[i].setAttribute("data-href", links[i].getAttribute("href"));
              links[i].removeAttribute("href");
              links[i].onclick = function() {
                  window.location = this.getAttribute("data-href");
              };
          }
      } else {
          return false;
      }
  }

  //Replaces the "no programming required" string in the source with one that better fits the context.
  function noProgReqdTxt() {
      if ($('#contents').css('display') == 'none') {
          $("p:contains('This feature does not require programming.')").html(
              // "This feature does not require programming. For more information on the feature, click <span class=\"fa fa-chevron-circle-down fa-2x\" style\=\"color\: #c8c8c8\;\ font-size\: 12pt;\" title=\" Show Less\"></span> above."
              "This feature does not require programming. For more information on the feature, click the \<span style\=\"font-size\: 10pt\"\>\<b\>+\<\/b>\<\/span\> button above."
          );
      } else {
          return false;
      }
  };
  
  
 //shows the Bookmarking and PDF Comments buttons when Help hosted on the eDocs 
 //hides ESM form link images too
  $(document).ready(function() {
    var url = $(location).attr('host');

 //show Bookmarking button and ESM form link images only on edocs.mitel.com (live) site	
	if( url == "edocs.mitel.com" ) {
		//alert(window.location.host);
		$('div.favoritesbtn').css('display','block');
		$('div.commentbtn').css('display','none');
		$('#contents').css('display','inline');		
		$(".ESMlink").remove();
		}
 //show both buttons but not ESM form link images on stgedocs.mitel.com (draft review) site			
	else if( url == "stgedocs.mitel.com" ) {
		//alert(window.location.host);
		$('div.favoritesbtn').css('display','block');
		$('div.commentbtn').css('display','block');
		$('#contents').css('display','inline');		
		$(".ESMlink").remove();		
            
      } else {
         //return false;
		 //$('#btncustom4811').remove;
		 $("a.btncustom4811").remove();
      }

});
  

  //Inserts check boxes
  function addCheckboxes() {
    var isInIFrame = (window.name);
      if (isInIFrame == "TaskListWindow") {
  
      switch (window.location.protocol) {
          case 'http:':
          case 'https:':
              //remote file over http or https
              $(
                  '#ProgrammingTask > ol > li.P-List-number, #ProgrammingTask > ul > li.P-Bullet, #ProgrammingTaskMore > ol > li.P-List-number, #ProgrammingTaskMore > ul > li.P-Bullet'
              ).prepend(
                  '<input type="checkbox" value="1" /><label for="checkbox" class="css-label"></label>'
              );
              $('input[type="checkbox"]').addClass("css-checkbox");
              $('input').each(function(i) {
                  $(this).attr('id', 'checkbox_' + (i + 1));
                  $(this).attr('name', 'checkbox_' + (i + 1));
              });
              $("label[for='.css-label']")
              $('.css-label').each(function(i) {
                  $(this).attr('for', 'checkbox_' + (i + 1));
              });
              break;
          case 'file:':
              //local file
              return false;
              break;
          default:
              //some other protocol
      };
  };
};

  //Save check box state to localstorage
  var strLocalStorgage = $("title").text().replace(/\s/g, ''); //Gets title element text to append to localstorage object. Comment out for testing
  function saveCheckboxState() {
      if (window.localStorage) {
          $('input').on('click', function() {
              var fav, favs = [];
              $('input').each(function() { // run through each of the checkboxes
                  fav = {
                      id: $(this).attr('id'),
                      value: $(this).prop('checked')
                  };
                  favs.push(fav);
              });
              localStorage.setItem('ESMtasksteps' + strLocalStorgage,
                  JSON.stringify(favs)); //Comment out + strLocalStorgage for testing
          });
          $(document).ready(function() {
              if (localStorage.getItem('ESMtasksteps' +
                      strLocalStorgage)) {
                  var ESMtasksteps = JSON.parse(localStorage.getItem(
                      'ESMtasksteps' + strLocalStorgage)); //Comment out + strLocalStorgage for testing
                  if (!ESMtasksteps.length) {
                      return
                  };
                  console.debug(ESMtasksteps);
                  for (var i = 0; i < ESMtasksteps.length; i++) {
                      console.debug(ESMtasksteps[i].value == 'on');
                      $('#' + ESMtasksteps[i].id).prop('checked',
                          ESMtasksteps[i].value);
                  }
              }
          });
      };
  };

  //Adds scroll to top button 
  function scrollToTop() {
      // var isInIFrame = (window.name);
      //if (isInIFrame == "TaskListWindow") {
      $.scrollUp({
          scrollName: 'scrollUp', // Element ID
          scrollDistance: 300, // Distance from top/bottom before showing element (px)
          scrollFrom: 'top', // 'top' or 'bottom'
          scrollSpeed: 300, // Speed back to top (ms)
          easingType: 'linear', // Scroll to top easing (see http://easings.net/)
          animation: 'fade', // Fade, slide, none
          animationSpeed: 999, // Animation speed (ms)
          scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object
          scrollTarget: false, // Set a custom target element for scrolling to. Can be element or number
          scrollText: '<img title="Scroll to Top" src="../tasklistscrolltotop.png">', // Text for element, can contain HTML
          scrollTitle: false, // Set a custom <a> title if required.
          scrollImg: false, // Set true to use image
          activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF'
          zIndex: 2147483647 // Z-Index for the overlay
      });
      // } else {
      //    return false;
      // }
  };