//////////////////////////////////////////////////
/////          Name: DefaultJS
/////       Wrapper: KUDER-LT
/////            ID: 4226
//////////////////////////////////////////////////

$.ajaxSetup({
  // Disable caching of AJAX responses
  cache: false
});

//navtojouupgrade any wrapper
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Helpful Functions
// Description: Helpful prototype functions for handling animations, events etc.
//				More info on jQuery prototypes can be found on https://api.jquery.com/jquery.fn.extend
// 		Author: Alen S / Kuder Inc



// --------------------------------------------------------------------------------- //
// ------ Showing and hiding with customized animations and optional callback ------ //
// --------------------------------------------------------------------------------- //

$.fn.fadeNicely = function(speed, easing, callback) {
  return this.animate({opacity: 'toggle'}, speed ? speed : 700, easing, callback);
};

$.fn.showHideNicely = function(speed, easing, callback) {
  return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};

$.fn.hideNicely = function(speed, easing, callback) {
  return this.animate({opacity: 'hide', height: 'hide'}, speed, easing, callback);
};

$.fn.showNicely = function(speed, easing, callback) {
  return this.animate({opacity: 'show', height: 'show'}, speed, easing, callback);
};

$.fn.extend({
  animateCss: function(animationName, callback) {
    var animationEnd = (function(el) {
      var animations = {
        animation: 'animationend',
        OAnimation: 'oAnimationEnd',
        MozAnimation: 'mozAnimationEnd',
        WebkitAnimation: 'webkitAnimationEnd',
      };

      for (var t in animations) {
        if (el.style[t] !== undefined) {
          return animations[t];
        }
      }
    })(document.createElement('div'));

    this.addClass('animated ' + animationName).one(animationEnd, function() {
      $(this).removeClass('animated ' + animationName);

      if (typeof callback === 'function') callback();
    });

    return this;
  },
});

// --------------------------------------------------------------------------------- //
// ---------------------------- END Animation_Functions ---------------------------- //
// --------------------------------------------------------------------------------- //





// --------------------------------------------------------------------------------- //
// ------------------- Universal Favoriting Accross The Web App -------------------- //
// --------------------------------------------------------------------------------- //
// NEW CLEANER MINIFIED WAY
var fav={set:function(e,a){if(null==e.favlink||void 0==e.favlink)return console.warning("favlink is null or undefined."),!1;if(null==e.favtitle||void 0==e.favtitle)return console.warning("favtitle is null or undefined."),!1;if(null==e.favtype||void 0==e.favtype)return console.warning("favtype is null or undefined."),!1;var n=e.favlink,i=e.favtitle,r=e.favtype,t="."+a+"[data-favlink='"+n+"']";this.update(userFavorites[r],existsInArray(n,userFavorites[r]),n,i,r,t)},update:function(e,a,n,i,r,t){a?(WRM$.favRem(n,r),$(t+" .fa-star").animateCss("rubberBand"),$(t).removeClass("selected"),$(t).attr("aria-checked", "false"),userFavorites[r]=arrayRemove(e,n)):(WRM$.favAdd(n,i,r),$(t+" .fa-star").animateCss("rubberBand"),$(t).addClass("selected"),$(t).attr("aria-checked", "true"),userFavorites[r].push(n))}};

// Favorition Expression Function
var favorites = {
  checkFavInfo: function(data, elementClass) {
    if (data == undefined || data == null) {
      return false;
    }

    var id = data.favlink;
    var title = data.favtitle;
    var favtype = data.favtype;
    var element = "." + elementClass + "[data-favlink='" + id + "']";
	this.set(userFavorites[favtype], existsInArray(id, userFavorites[favtype]), id, title, favtype, element);
  },
  set: function(currentFavorites, alreadyFavorited, id, title, favtype, element) {
    if (alreadyFavorited) { // rem
      WRM$.favRem(id, favtype);      
      $(element + " .fa-star").animateCss('rubberBand');
      $(element).removeClass('selected');
      $(element).attr('aria-checked', 'false');
      userFavorites[favtype] = arrayRemove(currentFavorites, id);
    } else {
      WRM$.favAdd(id, title, favtype); // add
      $(element + " .fa-star").animateCss('rubberBand');
      $(element).addClass('selected');
      $(element).attr('aria-checked', 'true');
      userFavorites[favtype].push(id);
    }
  },// faveType=12
  pathway: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=10
  cluster: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=3
  occupation: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=11
  militaryOcc: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=5
  major: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=30
  customMajor: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=66
  holland: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=7
  values: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  },// faveType=101
  pathwayLink: function(data, elementClass) {
    this.checkFavInfo(data, elementClass);
  }
};
// --------------------------------------------------------------------------------- //
// ----------------- END Universal Favoriting Accross The Web App ------------------ //
// --------------------------------------------------------------------------------- //





// --------------------------------------------------------------------------------- //
// ------------------- Convert C2B Model date to Javascript date ------------------- //
// --------------------------------------------------------------------------------- //

Date.prototype.formatMMDDYYYY = function(symbol) {
  symbol == undefined ? symbol = '/' : symbol = symbol;
  return (this.getMonth() + 1) + 
    symbol +  this.getDate() +
    symbol +  this.getFullYear();
}

function convertToJSDate(date, localize) {
  cleanDate = date.replace("/Date(", "").replace(")/","");
  convertedDate = new Date(parseInt(cleanDate, 10));
  if (localize) {
    var convertedDate = convertedDate.toLocaleDateString();
  }

  return convertedDate;
};

function convertToJSDateObject(date){
  cleanDate = date.replace("/Date(", "").replace(")/","");
  return new Date(parseInt(cleanDate, 10));
};

// --------------------------------------------------------------------------------- //
// ----------------- END Convert C2B Model date to Javascript date ----------------- //
// --------------------------------------------------------------------------------- //



// --------------------------------------------------------------------------------- //
// ---------------------------- Fixing Bootstrap JS Bugs --------------------------- //
// --------------------------------------------------------------------------------- //

// Toggling radio btn-group buttons with just .button('toggle') is broken as of Bootstrap 3.3.7 and this function fixes that
$.fn.toggleRadio = function() {
  return this.closest('.btn').button('toggle');
};

// --------------------------------------------------------------------------------- //
// ------------------------- END Fixing Bootstrap JS Bugs -------------------------- //
// --------------------------------------------------------------------------------- //



// --------------------------------------------------------------------------------- //
// -------------------------------- String Checkers -------------------------------- //
// --------------------------------------------------------------------------------- //

var is = {
  Number: function(n) {
    'use strict';
    n = n.replace(/\./g, '').replace(',', '.');
    return !isNaN(parseFloat(n)) && isFinite(n);
  },
  Float: function(n) {
    var number = (/[\d]+(\.[\d]+)?/).exec(n);
    if (number) {
      // Check if there is a decimal place
      if (number[1]) { return true; }
      else { return 'integer'; }          
    }
    return 'string';
  },
  dateBeforeToday: function(date) {
    var today = new Date(); //get todays date
    return date < today; //return if date passed is before todays date
  },
  dateAfterToday: function(date) {
    var today = new Date(); //get todays date
    return date > today; //return if date passed is before todays date
  }
};

// Check if a string exists in an array
function existsInArray(string, array) {
  if ( string !== undefined && array !== undefined ) {
    return array.indexOf(string) > -1;
  } else {
    return console.error('You forgot to pass in the string or array for existsInArray(string, array) function.');
  }
};

// Parses out duplicates from an array
function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}


// --------------------------------------------------------------------------------- //
// ----------------------------------- API Helpers --------------------------------- //
// --------------------------------------------------------------------------------- //

const validAPIResponse = (res) => {
  const valid = res.ResponseCode === 200 && 
    res.ResponseMessage === "SUCCESS" &&
    res.Status === "OK" &&
    res.ErrorMessage === null;
  
  return valid ? res.ReturnItem : res;
}

// --------------------------------------------------------------------------------- //
// --------------------------------- END API Helpers ------------------------------- //
// --------------------------------------------------------------------------------- //



// Sorts Array of Objects based on the property you pass in
function dynamicSort(property) {
  var sortOrder = 1;
  if(property[0] === "-") {
    sortOrder = -1;
    property = property.substr(1);
  }
  return function (a,b) {
    var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
    return result * sortOrder;
  }
}

function isObjEmpty(obj) {
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop))
      return false;
  }

  return JSON.stringify(obj) === JSON.stringify({});
}

// Get the text from all the selected bootstrap multiselect options
// and store in an array separated by "|"
$.fn.getSelectedOptionsTextForSearch = function(options) {
  return this.map(function(a, item){return item.text;}).toArray().join(options);
}

// Get the value from all the selected bootstrap multiselect options
// and store in an array separated by "|"
$.fn.getSelectedOptionsValueForSearch = function(options) {
  return this.map(function(a, item){return item.value;}).toArray().join(options);
}

// Generates the holland code paragraph found on the assessment results page
////////////////////////////////////////////////////////////////////////////////
// ID: 1446
// NAME: buildHollandTypeParagraphJS
function buildHollandTypeParagraph(data, type, paragraphSelector) {
  var html = "";
  var slashIndex;
  var codes = data.split('');
  var thereIsATie = (codes.indexOf('/') > -1);
  var assessmentName = type;
  var determiner = 'Your';
  var forYou = ' for you';
  // Is there a slash/tie?
  if (thereIsATie) {
    //loop through codes to find the slash 
    //so that we know what the paragraph will look like
    for (var i = 0; i < codes.length; i++) {
      if (codes[i].indexOf('/') > -1) { //find index of slash
        slashIndex = i;
      }
    }

    if (slashIndex === 1) { //eg S/CE = index 0/2 3
      html += determiner + ' profile of results from the ' + assessmentName + ' shows that '+
        '<strong>' + getHollandTypeFullName(codes[0]) + ' (' + codes[0] + ')</strong> and '+
        '<strong>' + getHollandTypeFullName(codes[2]) + ' (' + codes[2] + ')</strong> '+
        'interests are tied as highest' + forYou + '. Third highest are '+
        '<strong>' + getHollandTypeFullName(codes[3]) + ' (' + codes[3] + ')</strong> interests.';
    } else if (slashIndex === 2) { //eg SC/E = index 0 1/3
      html += determiner + ' profile of results from the ' + assessmentName + ' shows that '+
        '<strong>' + getHollandTypeFullName(codes[0]) + ' (' + codes[0] + ')</strong> '+
        'interests are highest' + forYou + '. Tied for next highest are '+
        '<strong>' + getHollandTypeFullName(codes[1]) + ' (' + codes[1] + ')</strong> and <strong>' + getHollandTypeFullName(codes[3]) + ' (' + codes[3] + ')</strong> interests.';
    } else if (slashIndex === 3) { //eg S/C/E = index 0/2/4
      html += determiner + ' profile of results from the ' + assessmentName + ' shows that '+
        '<strong>' + getHollandTypeFullName(codes[0]) + ' (' + codes[0] + ')</strong>, '+
        '<strong>' + getHollandTypeFullName(codes[2]) + ' (' + codes[2] + ')</strong>, '+
        '<strong>' + getHollandTypeFullName(codes[4]) + ' (' + codes[4] + ')</strong> '+
        'interests are tied as highest' + forYou + '.';
    }
  } else { //eg SCE = index 012
    html += determiner + ' profile of results from the ' + assessmentName + ' shows that '+
      '<strong>' + getHollandTypeFullName(codes[0]) + ' (' + codes[0] + ')</strong> '+
      'interests are highest' + forYou + '. Second highest is '+
      '<strong>' + getHollandTypeFullName(codes[1]) + ' (' + codes[1] + ')</strong>'+
      ' interests, and third highest is <strong>' + getHollandTypeFullName(codes[2]) + ' (' + codes[2] + ')</strong> interests.'
  }
  
  $(paragraphSelector).html(html);
}

function getHollandTypeFullName(code) {
  var fullName;
  switch (code) {
    case 'R':
      fullName = 'Realistic';
      break;
    case 'I':
      fullName = 'Investigative';
      break;
    case 'A':
      fullName = 'Artistic';
      break;
    case 'S':
      fullName = 'Social';
      break;
    case 'E':
      fullName = 'Enterprising';
      break;
    case 'C':
      fullName = 'Conventional';
  }
  return fullName;
}

// Reads holland code and returns icons for the Holland Code Column 
function convertHollandCodeToIcons(code) {
  var hollandCode = "";
  for (var i = 0; i < code.length; i++) {
    if (code[i] == 'R') {
      hollandCode += '<span class="fa-stack fa-sm hex-r">  <i class="fa fa-square fa-stack-2x"></i>  <i class="fa fa-stack-1x fa-inverse holland-icon-text">R</i> </span>'
    };
    if (code[i] == 'I') {
      hollandCode += '<span class="fa-stack fa-sm hex-i">  <i class="fa fa-square fa-stack-2x"></i>  <i class="fa fa-stack-1x fa-inverse holland-icon-text">I</i> </span>'
    };
    if (code[i] == 'A') {
      hollandCode += '<span class="fa-stack fa-sm hex-a">  <i class="fa fa-square fa-stack-2x"></i>  <i class="fa fa-stack-1x fa-inverse holland-icon-text">A</i> </span>'
    };
    if (code[i] == 'S') {
      hollandCode += '<span class="fa-stack fa-sm hex-s">  <i class="fa fa-square fa-stack-2x"></i>  <i class="fa fa-stack-1x fa-inverse holland-icon-text">S</i> </span>'
    };
    if (code[i] == 'E') {
      hollandCode += '<span class="fa-stack fa-sm hex-e">  <i class="fa fa-square fa-stack-2x"></i>  <i class="fa fa-stack-1x fa-inverse holland-icon-text">E</i> </span>'
    };
    if (code[i] == 'C') {
      hollandCode += '<span class="fa-stack fa-sm hex-c">  <i class="fa fa-square fa-stack-2x"></i>  <i class="fa fa-stack-1x fa-inverse holland-icon-text">C</i> </span>'
    };
  };
  return hollandCode;
};

// Initializes the Bootstrap Multiselect Plugin
function initializeMultiSelects(width) {
  $multiselects.multiselect({
    templates: {
      filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search" aria-hidden="true"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
      filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default multiselect-clear-filter" type="button"><i class="fa fa-times-circle" aria-hidden="true"></i></button></span>',
      li: '<li><div class="checkbox"><label></label></div></li>',
    },
    enableFiltering: true,//Turns on filtering
    enableCaseInsensitiveFiltering: true,//Turns off case sensitivity
    allSelectedText: 'All selected',
    buttonWidth: width === undefined ? '100%' : width,
    numberDisplayed: 1,
    includeSelectAllOption: true,
    nSelectedText: ' selected',
    nonSelectedText: 'None selected',
    selectAllText: 'Select all'
  });
  $multiselects.multiselect('selectAll', false);
  $multiselects.multiselect('updateButtonText');
}

// Initializes the Bootstrap Multiselect Plugin
function initializeMultiSelect(options) {
  if (options !== undefined) {
    if (options.element !== undefined) {
      options.element.multiselect({
        templates: {
          filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search" aria-hidden="true"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
          filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default multiselect-clear-filter" type="button"><i class="fa fa-times-circle" aria-hidden="true"></i></button></span>',
          li: '<li><div class="checkbox"><label></label></div></li>',
        },
        enableFiltering: options.filtering === undefined ? false : options.filtering,//Turns on filtering
        enableCaseInsensitiveFiltering: options.filtering === undefined ? false : options.filtering,//Turns off case sensitivity
        buttonWidth: options.width === undefined ? '100%' : options.width,
        numberDisplayed: options.numberDisplayed === undefined ? 1 : options.numberDisplayed,
        includeSelectAllOption: true,
        allSelectedText: 'All selected',
        nSelectedText: ' selected',
        nonSelectedText: 'None selected',
        selectAllText: 'Select all'
      });
    } else {
      console.error('initializeMultiSelect: You forgot to pass in the element!');
      return;
    }
    // Load saved options
    if (options.selectedOptions !== undefined) {
      options.element.multiselect('select', options.selectedOptions);
    }
    // Fix checkboxes
    if (options.fixCheckboxes !== undefined && options.fixCheckboxes) {
      fixMultiSelectCheckboxes()
    }
  } else {
    console.warn(`initializeMultiSelect: You forgot to pass in the options object!
ex: {
  element: '#id',
  filtering: true,
  width: 'auto',
  numberDisplayed: 1,
  selectedOptions: ['1', '2', '3'],
  fixCheckboxes: fixMultiSelectCheckboxes()
}`);
  }
}

//Manipulates the multiselect dropdowns to work with awesome-checkbox plugin
function fixMultiSelectCheckboxes() {
  $('.multiselect-container div.checkbox').each(function (index) {
    var id = 'multiselect-' + index,
        $input = $(this).find('input');

    // Associate the label and the input
    $(this).find('label').attr('for', id).removeClass('checkbox');  
    $input.attr('id', id);

    // Remove the input from the label wrapper
    $input.detach();

    // Place the input back in before the label
    $input.prependTo($(this));

    $(this).click(function (e) {
      // Prevents the click from bubbling up and hiding the dropdown
      //e.stopPropagation();
      //e.trigger('click');
      console.log("Clicking");
    });
  });
}

// Filters out HTML for Occupations
function filterHTML(string) {
  if (string.indexOf('<') >= 0) {
    return string.substr(0, string.indexOf('<'));
  } else {
    return string;
  }
};

const decodeHTMLEntities = html => {
  var txt = document.createElement("textarea");
  txt.innerHTML = html;
  return txt.value;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Helpful API List Functions
// Description: Helpful prototype functions for handling API list calls
//				More info on jQuery prototypes can be found on https://api.jquery.com/jquery.fn.extend
// 		Author: Alen S / Kuder Inc

// Sorts Array of Objects based on the property you pass in
function dynamicSort(property) {
  var sortOrder = 1;
  if(property[0] === "-") {
    sortOrder = -1;
    property = property.substr(1);
  }
  return function (a,b) {
    var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
    return result * sortOrder;
  }
}

// --------------------------------------------------------------------------------- //
// --------------------------- Building out select lists --------------------------- //
// --------------------------------------------------------------------------------- //
var isRegionsActive;
var regionsList = 'regionsList';
var servicesList = 'servicesList';
var oppTypesList = 'oppTypesList';
var clustersList = 'clustersList';

// Clearing sessionStorage on logout
$("a[href='/account/logout']").on('click', function() {
  sessionStorage.clear();
})

function apiResponseValid(res) {
  var valid = false;
  if (res.responseStatus == "success" && res.error.length === 0) valid = true;
  return valid;
}

function isListInSession(listName) {
  var listInSession = JSON.parse(sessionStorage.getItem(listName));

  if ((!listInSession) || listInSession.length==0) {
    // Lists were not found in sessionStorage so we call the api to load them
    if (listName == clustersList) {
      getClustersList();
    } else if (listName == regionsList || listName == servicesList || listName == oppTypesList) {
      getC2bLists();
    }
    listInSession = JSON.parse(sessionStorage.getItem(listName));
  }

  return listInSession;
}

function getC2bLists(callback) {
  var data = $.ajax({
    url: '/Ajax/BusinessProfile/GetC2BList',
    type: 'GET',
    async: false,
    contentType: 'application/json',
    data: {
      filterGroupKey: ''
    },
    error: function() {
      console.log("Major error");
    },
    success : function(res) {
      if (apiResponseValid(res)) {
        // Parse the json to that we can target each individual object
        var lists = JSON.parse(res.c2bLists)
        // Save lists to sessionStorage so that we don't keep loading them every page load
        sessionStorage.setItem(regionsList, JSON.stringify(lists.RegionList));
        sessionStorage.setItem(servicesList, JSON.stringify(lists.ServiceList));
        sessionStorage.setItem(oppTypesList, JSON.stringify(lists.OpportunityTypeList));
      } else {
        //ToDo: APIValidation Here
        console.log("Error: " + res.error);
      }
    }
  })

  return callback;
}

function getClustersList() {
  var data = WRM$.getData('K03~zRIk5ftw79F-jmTGdvpaBsBtbePg64bWBA1k0p13y69UW47B17RTJ-_IQSI4UDU6SmmXrEHLzs8bvPRRka_fn0u30DfrytZbvCTU3DyvYiJ8Wm4jSyIK0tMJLYmXcQF8-8Li1gM7YMIFPup_0THdfLaC8w-ALingduoo2dq4lEk', {
    '@language': 'en-US',
    '@portal': 'AFL',
    '@clusters_only': 1
  });

  if (data !== undefined && data.tables !== undefined && data.tables.length > 0 && data.tables[0].row_count > 0) {
    sessionStorage.setItem(clustersList, JSON.stringify(data.tables[0].rows));
  }
}

// Build region select
$.fn.buildRegionList = function() {
  // Select selector
  var select = this;
  // Check to see if we need to load the lists from api if they are not in sessionStorage
  var list = isListInSession(regionsList);
  // Sort alphabetically
  list.sort(dynamicSort("RegionName"));
  // Build out selection options
  list.forEach(function(item, index) {
    select.append('<option value="' + item.RegionID + '">' + item.RegionName + '</option>');
  });
  // Mark region select as finished loading
  checkPageState('regionListLoaded');
};

// Build Services List
$.fn.buildServicesList = function() {
  // Select selector
  var select = this;
  // Check to see if we need to load the lists from api if they are not in sessionStorage
  var list = isListInSession(servicesList);
  // Adding a "No Serviced Offered" for filtering to work properly
  list.push({ ServiceID: 0, ServiceName: "No Services Offered", IsSelected: false, CultureCode: "en-US" })
  // Sort alphabetically
  list.sort(dynamicSort("ServiceName"));
  // Build out selection options
  list.forEach(function(item, index) {
    select.append('<option value="' + item.ServiceID + '">' + item.ServiceName + '</option>');
  });  

  //select.append('<option value="0">No Services Offered</option>');
  // Mark region select as finished loading
  checkPageState('servicesListLoaded');
};

// Build Services List
$.fn.buildOppTypeList = function() {
  // Select selector
  var select = this;
  // Check to see if we need to load the lists from api if they are not in sessionStorage
  var list = isListInSession(oppTypesList);
  // Sort alphabetically
  list.sort(dynamicSort("OpportunityType"));
  // Build out selection options
  list.forEach(function(item, index) {
    select.append('<option value="' + item.OpportunityTypeID + '">' + item.OpportunityType + '</option>');
  });
  // Mark region select as finished loading
  checkPageState('oppTypeListLoaded');
};

// Build Services List
$.fn.buildClusterList = function() {
  // Select selector
  var select = this;
  // Check to see if we need to load the lists from api if they are not in sessionStorage
  var list = isListInSession(clustersList);
  // Build out selection options
  list.sort().forEach(function(item, index) {
    select.append('<option value="' + item[1] + '">' + item[0] + '</option>');
  });
  // Mark region select as finished loading
  checkPageState('clustersListLoaded');
};

$.fn.getSelectedOptionsTextForSearch = function(options) {
  return this.map(function(a, item){return item.text;}).toArray().join(options);
}

$.fn.getSelectedOptionsValueForSearch = function(options) {
  return this.map(function(a, item){return item.value;}).toArray().join(options);
}

// --------------------------------------------------------------------------------- //
// ------------------------- END Building out select lists ------------------------- //
// --------------------------------------------------------------------------------- //
//--------------------------------------------------------------------------
//VALIDATE AN EMAIL ADDRESS
function validateEmail(email){
  // old regex
  //var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  // new regex that accounts for international emails 
  var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return email != '' && emailReg.test(email);
}

//--------------------------------------------------------------------------
//VALIDATE A URL
function validateURL(weburl) {
  var RegExp = /(http|https|ftp|smtp|mail):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
  return weburl != '' && RegExp.test(weburl);
}

//--------------------------------------------------------------------------
//VALIDATE A US PHONE
function validateUSPhone(phone, allowExt){
  if (allowExt) phone = phone.left(12);
  var phReg = /[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
  return phReg.test(phone);
}

//----------------------------------------------------------------------
//FORMATT PHONE IN US FORMAT
function formatPhone(numbersToFormat){
  return numbersToFormat.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
}

//----------------------------------------------------------------------
//VALIDATE US ZIP + 4
function validateUSZipcode(zipcode) {
  return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipcode);
}

//----------------------------------------------------------------------
//VALIDATE TAS 4 Digit ZIP
function validateTASZipcode(zipcode) {
  return /^\d{4}$/.test(zipcode);
}

//----------------------------------------------------------------------
//VALIDATE ILP 6 Digit ZIP
function validateILPZipcode(zipcode) {
  return /^\d{6}$/.test(zipcode);
}

//VALIDATE Custom Course Title (no special characters)
function validateCustomCourseTitle(title)
{
  ///(^[^a-zA-Z0-9 ]$)/
  return (/^[a-zA-Z0-9 ]{0,100}$/.test(title.replace('"', '\"')));
}

//----------------------------------------------------------------------------
//CHECK IF USERNAME ALREADY EXISTS
function userNameExists(username) {
  var settings = jQuery.extend({}, WRM$.ajaxDefaults);
  settings.url = wrmUrl('~/PostBack/_/UserNameExists/_');
  settings.data = JSON.stringify({ name: username.trim() });
  //settings.success = function(dat){
  //  if (dat === true){
  //    return true;
  //  }
  //  else {
  //    return false;
  //  }
  //};
  settings.async = false;
  var ret = $.ajax(settings).responseText;
  if (ret.toLowerCase() === "false") {
    return false;
  } else {
    return true;  //this is the else so we don't attempt to submit dups in the case of an error (which will fail on the server side)
  }
}

//------------------------------------------------------------------------------

//CHECK IF ACTIVATION CODE IS VALID
function validateActivationCode(val) {
  var blnRet = false;
  if (val.substring(0,1).toLowerCase() == 'j') {
    var settings = jQuery.extend({}, WRM$.ajaxDefaults);
    settings.url = wrmUrl('~/PostBack/_/ValidateBatch/_');
    settings.data = JSON.stringify({
      Code: val
    });
    settings.async = false;
    settings.success = function (dat) {
      if (dat === "OK" || dat === true || dat === 'true') {
        blnRet = true;
      } else {
        blnRet = false;
      }
      //return blnRet;
    };
    $.ajax(settings);
    return blnRet;
  }
}
function getGradeText(level, addGrade) {
  switch (level) {
    case "13":
      level = 'Freshman';
      break;
    case "14":
      level = 'Sophomore';
      break;
    case "15":
      level = 'Junior';
      break;
    case "16":
      level = 'Senior';
      break;
    case "17":
      level = 'Graduate Student';
      break;
    default:
      level += '<sup>th</sup>';
      if (addGrade) {
        level += ' Grade';
      }
      break;
  }
  return level;
}
/**
 * DefaultJS jQuery Prototype Functions
 * Extension functions in the $().wrm() namespace 
 * Author: Addison B
 */

var NAMESPACE = "wrm";
$.wrm = function(callbacksConstructor) {
  if (typeof(window[NAMESPACE]) === "undefined") {
    window[NAMESPACE] = {};
  }
  if (typeof(window[NAMESPACE].callbacks) === "undefined") {
    window[NAMESPACE].callbacks = callbacksConstructor;        
  } else if (typeof(window[NAMESPACE].callbacks) === "object") {
    window[NAMESPACE].callbackName = $.extend(window[NAMESPACE].callbackName, 
                                          callbacksConstructor);
  } else {
    window[NAMESPACE].callbackName = callbacksConstructor;
  }
}

$.fn.wrm = function (callbackName, params) {
  // logger object to handle errors 
  var logger = {};
  logger.missingCallback = function() {
    console.log("%cError: parameter callbackName cannot be empty for $()." + NAMESPACE + "(callbackName)", "color:red");
    return; 
  };
  logger.callbackNotFound = function(callbackName) {
    console.log("%cError: callback function " + callbackName + " not found in $()." + NAMESPACE + "(callbackName)", "color:red");
    return;
  };
  logger.invalidParams = function(callbackName, numParams) {
    var msg = "Error: " + callbackName + " function requires at least " + numParams + " parameter";
    if (numParams > 1) 
      msg += "s";
    console.log("%c" + msg, "color:red");
    return;
  };
  logger.jqueryNotFound = function() {
    console.log("%cError: jquery parameter in $(this).fn not found", "color:red");
    return;
  };

  // validate parameters 
  var isValid = true;
  if (callbackName === undefined) {
    logger.missingCallback(); 
    isValid = false;
  }
  if ($(this).length === 0) {
    logger.jqueryNotFound();
    isValid = false;
  }
  // return early if base parameters invalid
  if (!isValid) {
  	return;
  }
  // initialize params if empty (some functions may not have parameters)
  if (params === undefined)
    params = [];
  // add "this" scope to params so callback functions can manipulate 
  // "this" of parent function 
  params.push($(this));
  // callbacks object for callback functions
  var callbacks = {};
  // if constructor used merge with callbacks object 
  if (typeof(window[NAMESPACE]) != undefined && typeof(window[NAMESPACE]) === "object") {
    callbacks = $.extend({}, window[NAMESPACE].callbacks)
  } 

  // @params[0] = array of objects { display : "" : value: ""} for Select List 
  // @params[1] = string of "display" or "value" to sort on (optional)
  // @params[2] = string type to sort on (string for display. string, float, or 
  //              integer for values) (optional)
  // @return status object of DOM manipulatin 
  callbacks.setListOptions = function(params) {
    if (params.length  < 2) {
      return { msg : "invalid params", numParams: 1};
    }
    // handle overloading the function 
    var arrayList= params[0]; 
    var jquery = params[1];
    if (params.length > 2) {
      var sortOn = params[1];
      jquery = params[2];
    } 
    if (params.length > 3) {
      var sortType = params[2];
      jquery = params[3];
    }
    // validate params 
    if (sortOn === undefined) 
      sortOn = false; 
    if (sortType === undefined)
      sortType = false;
    // sort arrayList according to display / value or sort type  
    if (typeof(sortOn) === "string" && sortOn != false) {
      if (sortOn === "display" && sortType === "string") { 
      arrayList.sort(function(a, b) {
          // set two items to compare case insensitive 
          var nameA = a.display.toUpperCase(); 
          var nameB = b.display.toUpperCase(); 
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          // names must be equal
          return 0;
        });
    } else if (sortOn === "values") { // sort by values
      switch (sortType) {
        case "float": 
        arrayList.sort(function(a, b) {
            // set two items to compare
            var nameA = parseFloat(a.value);
            var nameB = parseFloat(b.value);
            if (isNaN(nameA) || isNaN(nameB)) {
              return 0; 
            }
            if (nameA < nameB) {
              return -1;
            }
            if (nameA > nameB) {
              return 1;
            }
            // names must be equal
            return 0;
          });
          break;
      case "integer": 
        arrayList.sort(function(a, b) {
            // set two items to compare
            var nameA = parseInt(a.value, 10);
            var nameB = parseInt(b.value, 10);
            if (isNaN(nameA) || isNaN(nameB))
              return 0; 
            if (nameA < nameB)
              return -1;
            if (nameA > nameB) 
              return 1;
            // names must be equal
            return 0;
        });
        break;
      case "string": 
      default:
          arrayList.sort(function(a, b) {
            // set two items to compare case insensitive 
            var nameA = a.display.toUpperCase(); 
            var nameB = b.display.toUpperCase(); 
            if (nameA < nameB) {
              return -1;
            }
            if (nameA > nameB) {
              return 1;
            }
            // names must be equal
            return 0;
        });
        break;
      } // end switch sortType
     } // end sortType === "values"
    } // end typeof sortOn
    // build out html for select list input   
    var listHtml = [];
    $(arrayList).each(function(i, listItem) {
      listHtml.push("<option value=\""+ listItem.value + "\">" + listItem.display + "</option>");
    });
    // clear html of select input 
    jquery.html("");
    // bind html to $(this) of jquery function call 
    jquery.append("<option value=\"-1\">Any</option>");        
    jquery.append(listHtml.join(""));
    return { msg : "OK" };
  };
  // @params[0] = string error message 
  // @returns void DOM manipulation 
  callbacks.addError = function(params) {
      if (params.length  != 2) {
        return { msg : "invalid params", numParams: 1};
      }
      // set params
      var errorMsg = params[0];
      var jquery = params[1];
      // add error classes and message
      jquery.find('.error-message').remove();
      jquery.after("<div class=\"error-message text-danger\">" + errorMsg + "</div>");
      jquery.addClass("input-error");
      return { msg : "OK" };
  };
     // clears all error messages on a page. If a form id is
    // passed the form fields will also be cleared
    // @param formid = id of form (optional)
    // @return status object of DOM manipulation 
    callbacks.clearErrors = function (params) {
        var jquery = params[0];
      	var resetForm = false; 
      	if (params.length > 1) {
          resetForm = String(params[0]).toLowerCase() === "true"; 
          jquery = params[1]; 
        }
      	var formId = $(jquery).attr("id"); 
        $(".input-error").removeClass("input-error");
        $(".error-message").remove();
        if (formId != undefined && resetForm) {
            var form = document.getElementById(jquery.attr("id"));
            form.reset();
        }
        return { msg: "OK" };
    };
    // clears input errors and values in a modal form
    // @params[0] $(this) of $.fn.SimpleCMS (default/always set)
    // @return status object of DOM manipulation 
    callbacks.clearModalErrors = function (params) {
        var jquery = params[0];
        jquery.on('hidden.bs.modal', function () {
            var id = jquery.find('form').attr('id');
            $("#" + id).SimpleCMS("clearErrors"); 
        });
        return { msg : "OK" };
    };
    // Clears input errors on change
    // @params[0] $(this) of $.fn.SimpleCMS (default/always set)
    // @return status object of DOM manipulation 
    callbacks.updateInputField = function (params) {
        var jquery = params[0];
        jquery.change(function () {
            if (this.value != "") {
                $(this).removeClass("input-error");
                $("." + field.substring(1) + ".error-message").remove();
            }
        });
        return { msg : "OK" };
    };
    // adds a dismissable alert to an element
    // @params[0] type = name of what is being updated
    // @params[1] action = update or delete
    // @return status object of DOM manipulation 
    callbacks.alertMsg = function (params) {
        if (params.length != 3) {
            return { msg : "invalid params", numParams: 2 };
        }
        var type = params[0];
        var action = params[1];
        var jquery = params[2];
        var deleteMsg = [
            '<div class="alert alert-success alert-dismissible" role="alert">',
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">',
            '<span aria-hidden="true">×</span></button>',
            '<strong>Success!</strong> ' + type + ' has been deleted.',
            '</div>'
        ];
        var updateMsg = [ 
            '<div class="alert alert-success alert-dismissible" role="alert">',
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">',
            '<span aria-hidden="true">×</span></button>',
            '<strong>Success!</strong> ' + type + ' has been updated.',
            '</div>'
        ];
        if (action === 'delete') jquery.html(deleteMsg.join(""));
        if (action === 'update') jquery.html(updateMsg.join(""));
        return { msg : "OK" };
    };
    
  // @params[0] = jquery (default always added) 
  // @returns void DOM scroll to selector 
  callbacks.scrollView = function (params) {
	var jquery = params[0];
    return { msg : "OK", data : WRM$.scrollTo(jquery.selector) };
  };
  
  // @params[0] = jquery (default always added) 
  // @returns trimed value of field 
  callbacks.getField = function(params) {
    var jquery = params[0];
    return { msg : "OK", data : $.trim(jquery.val()) } ;
  }
  // call callback function and log errors 
  if (callbacks.hasOwnProperty(callbackName)) {
    var status = callbacks[callbackName](params);
    if (typeof (status) === "object" && status.msg === "invalid params") 
      logger.invalidParams(callbackName, status.numParams);
    if (status.msg === "OK" && status.hasOwnProperty("data")) {
    	return status.data; 
    }
  } else { 
      logger.callbackNotFound(callbackName);
  }
  return;
}; // end $.fn.wrm
/**
 * DefaultJS Vanilla Prototype Functions
 * Extension functions in the string.wrm() / array.wrm() / object.wrm() namespace 
 * Author: Addison B
 */

// define prototype extensions using Object.defineProperty and enumerable set to false
// to prevent prototypes from showing up in for in loops 
Object.defineProperty(String.prototype, 'wrm', {
  enumerable: false,
  value: function (callbackName, params) {
    if (typeof(params) != "object") {
      params = [];  
    }
    params.push(this);
    var callbacks = {};
    callbacks.trim = function(params) {
      var scopedString = params[0]; 
      return scopedString.replace(/^\s+|\s+$/g, "");
    };
    callbacks.startsWith = function(params) {
      var needle = params[0];
      var scopedString = params[1]; 
      return scopedString.indexOf(needle) === 0; 
    };
    callbacks.endsWith =  function(params) {
      var searchString = params[0]; 
      var scopedString = params[1];
      var  position = scopedString.length;
      position -= searchString.length;
      var lastIndex = scopedString.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
    };
    callbacks.formatMoney = function(params){
      if (params.length == 1) {
        var n = params[0];
      } else if (params.length == 2) {
        var fixedLength = params[0]
        var n = params[1];
      } else {
        var fixedLength = params[0]
        var d = params[1];
        var t = params[2];
        var n = params[3];
      }
      var fixedLength = fixedLength == undefined ? 0 : fixedLength,
      	  d = d == undefined ? "." : d, 
          t = t == undefined ? "," : t, 
          s = n < 0 ? "-" : "", 
          i = parseInt(n = Math.abs(+n || 0).toFixed(fixedLength)) + "", 
          j = (j = i.length) > 3 ? j % 3 : 0;
      return "$" + s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (fixedLength ? d + Math.abs(n - i).toFixed(fixedLength).slice(2) : "");
    };
    callbacks.numberWithCommas = function (params) {
      var x = params[0];
      var parts = x.toString().split(".");
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      return parts.join(".");
    };
    callbacks.formatPercent = function(params) {
      var num = parseFloat(params[0]);
      var percent;
      if (isNaN(num)) {
        return params[0];    
      }
      if (num < 1) {
      	percent = (num * 100).toFixed(1); 
      } else {
        percent = num.toFixed(1);  
      }
      return percent + "%";
    };
    callbacks.contains = function(params) {
      var needle = params[0];
      var scopedString = params[1];
      return scopedString.indexOf(needle) > 0; 
    };
    if (callbacks.hasOwnProperty(callbackName)) {
      return callbacks[callbackName](params);  
    }
    return;
  } // end String.prototype.wrm
}); // end Object.defineProperty 

Object.defineProperty(Array.prototype, 'wrm', {
  enumerable: false,
  value: function (callbackName, params) {
    if (typeof(params) != "object") {
      params = [];  
    }
    params.push(this);
    var callbacks = {};
    callbacks.contains = function (params) {
      var needle = params[0];
      var scopedArray = params[1];
      var i = scopedArray.length; 
      while (i--) { 
        if (scopedArray[i] === needle) { return true; } 
      } 
      return false;
    }
    if (callbacks.hasOwnProperty(callbackName)) {
      return callbacks[callbackName](params);  
    }
    return;
  } // end Array.prototype.wrm
}); // end Object.defineProperty


Object.defineProperty(Object.prototype, 'wrm', {
  enumerable: false,
  value: function (callbackName, params) {
    if (typeof(params) != "object") {
      params = [];  
    }
    params.push(this);
    var callbacks = {};
    callbacks.getKey = function (params) {
      var value, scopedObject; 
      var caseInsensitive = false; 
      if (params.length === 2) {
        value = params[0];
        scopedObject = params[1];
      } else if (params.length === 3) {
        value = params[0];
        caseInsensitive = params[1];
        scopedObject = params[2]; 
      }

      if (caseInsensitive) {
        return Object.keys(scopedObject).filter(function(key) { return scopedObject[key].toLowerCase() === value.toLowerCase() })[0]; 
      } else { // case sensitive 
        return Object.keys(scopedObject).filter(function(key) { return scopedObject[key] === value })[0];     
      }
    };
    callbacks.contains = function (prams) {
      var needle = params[0];
      var scopedObject = params[1];
      var objectKeys = Object.keys(scopedObject); 
      for (var i = 0, key; key = objectKeys[i++];) {
        if (scopedObject[key] === needle) {
          return true; 
        }
      }
      return false; 
    };
    if (callbacks.hasOwnProperty(callbackName)) {
      return callbacks[callbackName](params);  
    }
    return;
  } // end Object.prototype.wrm
}); // end Object.defineProperty
/**
 * languageToggleJS
 * Functions used for toggling language 
 * Author: Addison B 
**/

// used for google tag manager for collecting analytics around language 
if (typeof(dataLayer) === "undefined") {
  dataLayer = [];
}

// object to store language toggle functions 
var LanguageHelper = {};

// property to store userCulture 
LanguageHelper.userCulture = "en-US"; 

// sets userCulture and calls setCultureCSS 
LanguageHelper.init = function() {
  if (this.userCulture == undefined || this.userCulture === "") {
    this.userCulture = $(".language-select").attr("data-currentuserlanguage");
  } 
  // if we could not get culture from the data attribute get it form the language cookie 
  if (this.userCulture == undefined || this.userCulture === "") {
    this.userCulture = this.getCultureFromCookie();
  } 
  if (this.userCulture.length === 2) {
    this.userCulture = this.addCountryCode(this.userCulture);  
  }
  this.userCulture = this.userCulture.toLowerCase();
  this.setCultureCSS();  
  dataLayer.push({"userLanguage" : this.userCulture}); 
}

// adds the country code if it is missing from the culture 
LanguageHelper.addCountryCode = function(langOrCultureCode) {
  var rtnCode = "";
  if (langOrCultureCode === undefined) {
    rtnCode = "en-us" 
  }
  if (langOrCultureCode.length == 2) {
    //rtnCode = langOrCultureCode + "-" + this.getCurrentCountry();
    rtnCode = langOrCultureCode + "-us";
  } else {
    rtnCode = langOrCultureCode;  
  }
  return rtnCode; 
}

// sets culture navigation css for active culture 
LanguageHelper.setCultureCSS = function () {
  // remove any previous styles 
  $(".language-select a").removeClass('active-language'); 
  var language = "";
  if (this.userCulture !== undefined && this.userCulture !== "" && this.userCulture.length > 1) {
    language = this.userCulture.substr(0, 2); 
  }

  // clear current active 
  $(".languageToggle").removeClass('active-language');
  switch (language) {
    case "es": 
      $("#es").addClass('active-language');
      $(".current-language").text('Español');
      break; 
    default: 
      $("#en").addClass('active-language');
      $(".current-language").text('English (US)');
  }
  return false;
}
// gets the current country from the browser settings 
LanguageHelper.getCurrentCountry = function () {
  var culture = navigator.languages || navigator.language;
  var country = "us";
  if (typeof (culture) === "object" && culture != null) {
    country = culture[0].split('-').length > 0 ? culture[0].split('-')[1].toLowerCase() : country;  
  } else if (typeof (culture) === "string") {
    country = culture.split('-').length > 0 ? culture.split('-')[1].toLowerCase() : country;  
  }
  return country;
}
// updates the culture associated with a user and any language/culture cookies 
LanguageHelper.updateCulture = function (language) {
  if (language == undefined) {
    language = "en";  
  }
  var culture = this.addCountryCode(language); 
  if (culture != this.userCulture.toLowerCase()) {
    var settings = $.extend({}, WRM$.ajaxDefaults); 
    settings.url = "/Ajax/Postback/UpdateUserCulture";
    settings.data = JSON.stringify({ 'culture' : culture }); 
    settings.success = function(data) {
      if (data.status === "OK") {
        this.userCulture = culture; 
        //setCultureCSS(); 
        window.location.reload();
      }
    }
    $.ajax(settings);  
  } // end if culture != userCulture 
  return false;
}

LanguageHelper.getCultureFromCookie = function(){
  var pairs = document.cookie.split(";");
  var cookies = {};
  for (var i=0; i<pairs.length; i++){
    var pair = pairs[i].split("=");
    cookies[pair[0].trim()] = unescape(pair[1]);
  }
  var culture = this.addCountryCode(cookies["_language"]);
  return culture;
}

LanguageHelper.init();
// jquery events / onload function calls
$(function() {
  $(".language-select a").click(function(e) {
    e.preventDefault(); 
    $(".language-select a").removeClass(".active-language");
    //$(".language-select a").addClass('active-language'); //.css("font-weight", "normal"); 
    var language = $(this).attr("data-userlanguage"); 
    dataLayer.push({"toggleLanguageValue" : language}); 
    LanguageHelper.updateCulture(language);
  });

});

function moveLanguageToggle() {
  if (wrm_section == "landing-page") {
    //do nothing
  } else { 
    // move toggle to specified location
    if ($('.profile-account').is(':hidden')) {
      $('.dropdown.language-toggle').insertAfter('.navbar-brand');
    }
    if ($('.profile-account').is(':visible')) {
      $('.dropdown.language-toggle').prependTo('.nav.navbar-nav');
    }
    if ($('.navbar-collapse').is(':hidden')) {
      $('.dropdown.language-toggle').insertAfter('.navbar-brand');
    }
  }
}

moveLanguageToggle();

$(window).resize(function() {
  moveLanguageToggle();
});
$(function() {
  // check if language is spanish
  if (LanguageHelper.userCulture === "es-us") {
    // find .english-only class and add class .no-translated-content to hide elements
    $('body').find('.english-only').addClass('no-translated-content');
    // hide and show message why its hidden
    $('body').find('.english-only-with-message').hide().before('<p class="no-spanish-video-para"><i class="fa fa-language fa-fw fa-lg" aria-hidden="true"></i> Please switch to English (US) to see the English content.</p>');
    // hide and show message why its hidden with larger text and icon
    $('body').find('.english-only-with-message-large').hide().before('<div class="english-only-message-large"><i class="fa fa-language fa-fw fa-5x" aria-hidden="true"></i><h3>Please switch to English (US) to see the English content. </h3></div>');
    // hide youtube videos with .english-only class
    $(".embed-responsive.english-only, .help-block.english-only").hide();
    // and replace videos with message to turn on english to view content
    $(".embed-responsive.english-only").before('<div class="no-english-content"><i class="fa fa-language fa-5x" aria-hidden="true"></i><h3 id="no-spanish-video">No AP Spanish content to show here.</h3><p class="no-spanish-video-para">please change to english to view english content.</p></div>');
  }
});
//Any Wrapper
/*=== ratingsJS-dataTables ===*/

// Set to false before checking if it is turned on
var stateflag = false;

// Check to see if turned on
if ('False' == 'True') {
  stateflag = true;
}

// Create table and add rating column with ratingHTML content
function showRatings(isHollandorCluster) {
  var table = $('#occs_table').DataTable();

  if (isHollandorCluster) { // A check for holland/cluster pages
    var demandcolindex = table.columns().count()-1;
    table.column(demandcolindex).visible(stateflag, stateflag);
    table.columns.adjust().draw( stateflag );
  } else { // All other pages
    var col = table.columns("demand:name");
    col.visible(stateflag, stateflag);
  }
};

// Get rating value in tables and insert rating span
function ratingCell(td, cellData, rowData, row, col) {
  $(td).html(GetRatingIcons(rowData[ratingColumn]));
};

// Get rating value in divs and insert rating span
function ratingDiv(divID) {
  var divName = "#" + divID + "";
  var val = $(divName).html();
  if ( val == '' ) {
    val = 0
  }
  if(val == 0)
  {
    $('.demand').css('display','none');
  }
  if(val != undefined){
    $(divName).html(GetRatingIcons(val));
  }
};

function GetRatingIcons(val) {
  var retVal = val;
  // If wrapper.hasStateData = 'True'
  if(stateflag) {
    if ( val == '' ) {
      val = 0;
    }
    if ( val >= -2 ) {
      // Check if val is a number
      if ( $.isNumeric( val ) ) {
        // Create array for the 5 levels of ratings
        var activeRating = ['', '', '', '', ''];
        // Set rating level based on val parameter
        for (var r = 0; r < val; r++) {
          activeRating[r] = 'active'; 
        };
      };
    };
    // Create array to hold html that will go into table column
    var ratingHTML = [];
    ratingHTML.push('<span class="ratingSpanWrap" style="position:relative" data-tooltip="true" data-toggle="tooltip" data-placement="top" title="'+GetRatingToolTipText(val)+'">'+
                    '<span class="rating '+ activeRating[0] +'"></span>'+
                    '<span class="rating '+ activeRating[1] +'"></span>'+
                    '<span class="rating '+ activeRating[2] +'"></span>'+
                    '<span class="rating '+ activeRating[3] +'"></span>'+
                    '<span class="rating '+ activeRating[4] +'"></span>');
    if (val < 0) {
      ratingHTML.push('<label class="lblOverFlames">Data Not Available</label>');
    }
    ratingHTML.push("</span>");
    retVal = ratingHTML.join('');
  }
  else {
    retVal = '';
  }
  return retVal;
};

function GetRatingToolTipText(rating){
  var tooltip = '';
  
  // Switch case to enable different tooltips based on the rating levels
  switch(rating) {
  case '1':
    tooltip = "Minimal Future Outlook";
    break;
  case '2':
    tooltip = "Low Future Outlook";
    break;
  case '3':
    tooltip = "Fair Future Outlook";
    break;
  case '4':
    tooltip = "Good Future Outlook";
    break;
  case '5':
    tooltip = "Best Future Outlook";
    break;
  default:
    tooltip = "";
}

  return tooltip;
}

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

// Fix for dataTable sortint
var sortasc = true;
$('#occs_table').on( 'order.dt', function () {
  var occtable = $('#occs_table').DataTable();
  var demandindex = occtable.columns().count()-2;
  var actualindex = occtable.columns().count()-1;

  if ( occtable != undefined ) {

    if ( occtable.order()[0] == demandindex + ',asc' ){
      if (sortasc)
        occtable.order([actualindex,'desc']).draw();
      else
        occtable.order([actualindex,'asc']).draw();
      sortasc =! sortasc;
    }
  }
});

/*=== END ratingsJS-dataTables ===*/
//////////////////////////////////////////////////////////////////////////
// C2B_EmailVerification
// Description: Object for validating email addresses using Kickbox: Email
//				Address Verification Service
// URL: https://docs.kickbox.io
var email = {
  //Pass email to verify
  //Return true or false
  verify : function (email) {
    var answer = '';
    $.ajax({
      url	  : "/Ajax/KickBox/EmailVerify",   
      data 	  : {Email: email},
      async	  : false,
      success : function(res) {
        //Set some vars to keep code dry
        var returnedItem = res.ReturnItem;
        var returnMsg 	 = res.ResponseMessage;
        //Check if response code and message are success and that validation is turned on
        if (res.ResponseCode == 200 && returnMsg == "SUCCESS") {
          var validateOFF  = returnedItem.do_not_validate;
          if (validateOFF == false) {
            answer = returnedItem;
          } else if (validateOFF == true && returnMsg == "Validation is OFF") {//If validation is turned off just let user register
            answer = false;
          }
        } else {//if kickbox is unreachable
          answer = false;
          
        }
      }//success
    });//ajax
    return answer;
  }//verify function
}//C2B_Email
// KCPS_Notify include //

// Object for managing notify plugin 
var BASE_Notify = {
  notify : {},
  
  sessionEnd : function (showTitle, showMsg, callback) {
    // Show notify progress
    this.notify = $.notify({
      title: showTitle ? '<strong>'+showTitle+'</strong>' : "Processing",
      message: showMsg ? showMsg : "Do not close or navigate away from this page.",
    }, {
      //additional options go here
      type: 'warning',
      onClosed: callback,
            customClasses: 'session-expired',
    });
  }, 
  validating : function (showTitle, showMsg, callback) {
    // Show notify progress
    this.notify = $.notify({
      title: showTitle ? '<strong>'+showTitle+'</strong>' : "Processing",
      message: showMsg ? showMsg : "Do not close or navigate away from this page."
    }, {
      //additional options go here
      onClosed: callback
    });
  },

  info : function (infoTitle, infoMsg, callback) {
    this.notify = $.notify({
      title: infoTitle,
      message: infoMsg
    },{
      //additional options go here
      onClose: callback
    });
  },

  // Show notify success
  successful : function (successTitle, successMsg, timeoutMs, closedFunction) {
    this.notify = $.notify({
      title: successTitle,
      message: successMsg
    },{
      type: 'success',
      delay: 5000,
      onClosed: closedFunction
    });
    if (timeoutMs > 0) {
      this.close(timeoutMs);
    }
  },

  // Show notify success
  unsuccessful : function (unsuccessTitle, unsuccessMsg, UStimeoutMs) {
    this.notify = $.notify({
      title: unsuccessTitle,
      message: unsuccessMsg
    },{
      type: 'danger',
      delay: 5000,
    });
  },

  // Show notify success
  success : function (successMsg, callback) {
    this.notify = $.notify({
      title: 'Success',
      message: successMsg
    },{
      type: 'success',
      delay: 3000,
      onClosed: callback
    });
  },

  warning : function (warningTitle, warningMsg, closeTime, closedFunction) {
    this.notify = $.notify({
      title: warningTitle,
      message: warningMsg
    },{
      'type': 'warning',
      delay: closeTime,
      customClasses: 'outage-notification',
      onClosed: closedFunction
    });
  },

  error : function (errorTitle, errorMsg) {
    this.notify = $.notify({
      title: errorTitle,
      message: errorMsg
    },{
      type: 'danger',
      allow_duplicates: true,
      newest_on_top: false
    });
  },

  apiError : function (errorTitle, errorMsg, isForm) {
    this.notify = $.notify({
      title: errorTitle,
      message: errorMsg
    },{
      type: 'danger',
      allow_duplicates: true,
      newest_on_top: false
    });
  },

  outage : function (warningTitle, warningMsg) {
    this.notify = $.notify({
      title: warningTitle,
      message: warningMsg
    },{
      'type': 'warning',
      customClasses: 'outage-notification',
    });
  },
  // Show notify success
  survey : function (surveyTitle, surveyMsg, closedFunction) {
    this.notify = $.notify({
      title: surveyTitle,
      message: surveyMsg
    },{
      type: 'success',
      onClosed: closedFunction
    });
  },

  close : function (inMiliSeconds) {
    var thisNotify = this;
    window.setTimeout(function() {
      thisNotify.notify.close();
    }, inMiliSeconds);
  },

  closeAll : function() {
    $.notifyClose(); 
  }
};
// END KCPS_Notify include //
function displayWarning() {
  var content = '';
  //content += '<div class="right-sidebar-alert alert alert-warning" role="alert">';
  try {
    var content = '';
    WRM$.missingInformation(function(listData){
      if (listData !== undefined && typeof listData == "object") {
        $.each(listData.List, function(index, item){
          var label = item.Label;
          var url = item.URL;
          if (item.ShowAsIncomplete == 1) {
            if (label.toLowerCase() == 'expected education level') {
              content += '<div class="missings-info missing-ed-level">Your education goals are incomplete. Please visit <a href="/account-settings?highestedlevel=1" class="capture" id="edGoalLink">account settings</a> to update your information.</div>';
              //replace link with db link
              var scriptToExec = "$('#edGoalLink').attr('href','javascript:handleWarningLinkClick(\"" + item.URL + "\",\"" + item.Label + "\");');";
              scriptToExec += "$('#edGoalLink').attr('area','" + item.Label + "');";
              $("head").append($("<script> function swapEdGoal(){" + scriptToExec + "}<\/script>"));
            }
            else if(label.toLowerCase() == 'needs and barriers') {
              if (window.userType < 256) {
                content += '<div class="missing-info missing-needs-and-barriers">Your needs and barriers are incomplete. Please visit <a href="/account-settings?needsbarriers=1" class="capture" id="needsLink">account settings</a> to update your information.</div>';
                var scriptToExec = "$('#needsLink').attr('href','javascript:handleWarningLinkClick(\"" + item.URL + "\",\"" + item.Label + "\");');";
                scriptToExec += "$('#needsLink').attr('area','" + item.Label + "');";
                $("head").append($("<script> function swapNeeds(){" + scriptToExec + "}<\/script>"));
              }

            }
          }
          else {
            if (window.userType < 256 && label.toLowerCase() == 'needs and barriers') {
              $('.needs-and-barriers').attr('style','display:block');
            }
          }

        });
      }
      if (content.length === 0) {
        $('#alertBox').attr('style','display:none;');
      }
      else {
        content = '<h3><i class="fa fa-warning"></i> Information Missing</h3>' + content;
        $('#alertBox').attr('style','');
        $('#alertBox').html(content);
        if (typeof swapEdGoal == 'function') { swapEdGoal(); }
        if (typeof swapNeeds == 'function') { swapNeeds(); }  
      }
    });
  }
  catch(e) {}
  //content += '</div><!-- /.right sidebar alert -->';
  $('#alertBox').attr('style','display:none;');
}//content

//DataDog include 

  (function(h,o,u,n,d) {
    h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
    d=o.createElement(u);d.async=1;d.src=n
    n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
  })(window,document,'script','https://www.datadoghq-browser-agent.com/us1/v4/datadog-rum.js','DD_RUM')

  window.DD_RUM.onReady(function() {
    window.DD_RUM.init({
      clientToken: 'pub92ff30812f7c5a9a63b5c8602d13c8cd',
      applicationId: '47c65162-c912-46c7-a93c-e56926c762d7',
      site: 'datadoghq.com',
      service: 'navigator-journey',
    
      env: 'prod',
      sessionReplaySampleRate: 100,
      sessionSampleRate: 100,
    
    
    
      // Specify a version number to identify the deployed version of your application in Datadog 
      // version: '1.0.0',
      trackUserInteractions: true,
      trackResources: true,
      trackLongTasks: true,
      defaultPrivacyLevel: 'mask-user-input',
    });

    window.DD_RUM.startSessionReplayRecording();

	datadogSetUser();
  })
  
  function datadogSetUser() {
    
  }
  
  function datadogClearUserSession() {
    window.DD_RUM.stopSession();
    window.DD_RUM.stopSessionReplayRecording();
  }

//////////////////////////////////////////////////////////////////////////
// Datatable functions
// Description: Object for creating common datatable functionality
// Use: Make sure to add the following JS to any files you use this in
//      <script type="text/javascript" src="https://cdn.datatables.net/v/bs/dt-1.10.18/r-2.2.2/datatables.min.js"></script>
//      The link for the CSS is in the include - DefaultHTMLHead. Update the version there if you change the script version
/////////////////////////////////////////////////////////////////////////

/**
 * Creates a basic table using the dataTables API
 * @param tableId The id of this table
 * @param tableData The data to display in this table
 * @param tableColumns The columns in this table
 */
function createTable(tableId, tableData, tableColumns) {
  $(tableId).DataTable({
    destroy: true,
    ordering: false,
    paging: false,
    searching: false,
    info: false,
    fnDrawCallback:function(o) { // Table Drawn
      // Common to all tables in the app
      $(this)
        .addClass('table table-bordered table-striped table-hover table-responsive')
      	.css({'width' : '100%'});
      // Needed for accessibilty
      $('th').attr('scope', 'col').attr('tabindex', 0);
      $('td').attr('tabindex', 0);
    },
    createdRow: function( row, data, dataIndex ) {
      // Needed for accessibilty
      $(row).children('td:first-child').attr('role', 'rowheader').attr('scope', 'row');
    },
    data: tableData,
    columns: tableColumns
  });
}

/**
 * Creates a data table using the dataTables API
 * @param tableId - The id of this table
 * @param userTableSettings - Settings for this dataTable
 * @param options - Used to toggle options within this table.
 *					Accepted parameters:
 *						* srLabel (string): A screen reader only label describing the content of the table.
 *                      * srOnly (boolean): Makes the table visiable only to screen readers.
 * 						* tableType (string): The type of table you want to create.
 *                       	- basic: A standard table w/o ordering, paging, searching, or info. A basic table.
 */
function createDataTable(tableId, userTableSettings, options) {
  if ($.fn.DataTable.isDataTable(tableId)) {
    $(tableId).DataTable().destroy();    
  }
  
  let userSettings = {
   	...userTableSettings,
  }
  delete userSettings.fnDrawCallback;
  delete userSettings.language;
  delete userSettings.createdRow;
  
  if (options.tableType === "basic") {
   userSettings = {
     ...userSettings,
     info: false,
     ordering: false,
     paging: false,
     searching: false
   }
  }
  
  let defaultSettings = {
    ordering: true,
    order: [], // Needed for if first column is not orderable.
    paging: true,
    searching: true,
    fnDrawCallback: function(settings) {
      let tableClasses = 'table table-striped table-hover table-responsive table-bordered';
      let tableCss = {'width': '100%'}
      if (options.srOnly) {
       tableClasses = tableClasses + ' sr-only'; 
      }
      if (options.srLabel) {
       $(tableId).attr('aria-label', options.srLabel) 
      }
      if (options.removeTablePadding) {
        tableCss = {
          ...tableCss,
          'padding': '0px'
        }
      }
      if (userTableSettings.fnDrawCallback) {
      	userTableSettings.fnDrawCallback(settings);
      }
      
      // Common to all tables in the app
      $(this).addClass(tableClasses).css({...tableCss}).attr('role', 'table');
  
      // Hide info display manually, otherwise screen reader will not read table properly
      if (settings.aoData.length < 10) {
        $(tableId + "_info").hide();
        $(tableId + "_paginate").hide();
        $(tableId + "_length").hide();
      } else if (settings.oInit.paging) {
        $(tableId + "_info").show();
        $(tableId + "_paginate").show();
        $(tableId + "_length").show();
      }
      
      // Needed for accessibility
      $('thead').attr('role', 'rowgroup');
      $('tbody').attr('role', 'rowgroup');
      
      $('tr').attr('role', 'row');
      
      $('th').attr('scope', 'col').attr('tabindex', 0).attr('aria-sort', 'none').attr('role', 'columnheader');
      $('th.sorting_asc').attr('aria-sort', 'ascending');
      $('th.sorting_desc').attr('aria-sort', 'descending');
      
      $('td').attr('tabindex', 0).attr('role', 'cell');
      $('tr').children('td:first-child').attr('role', 'rowheader').attr('scope', 'row');
      
      $('td > button').parent().removeAttr('tabindex');
      $('td > a').parent().removeAttr('tabindex');
      //$('td > i').parent().removeAttr('tabindex');
      $('td > .dropdown').parent().removeAttr('tabindex');
      $('td input[type="checkbox"]').parent().parent().removeAttr('tabindex');
      
      $('ul.pagination').attr('role', 'region').attr('aria-label', 'pagination');
      $('ul.pagination li.disabled a').attr('aria-disabled', true);
      $('ul.pagination li.active a').attr('aria-current', 'page');
      
      if (!options.srOnly) {
        $(tableId + '_wrapper').find('.help-block').remove();
        $(tableId + '_wrapper').append('<p class="help-block"><i class="fa fa-arrows-h" aria-hidden="true"></i>Table may scroll horizontally depending on device and screen size.</p>')
      }
    },
    createdRow: function(row, data) {
      if (userTableSettings.createdRow) {
      	userTableSettings.createdRow(row);
      }
      
      // Needed for accessibility
      $(row).children('td:first-child').attr('role', 'rowheader').attr('scope', 'row');
    },
    language: {
      //Loaded from datatables-language-options include (1205)
    emptyTable: "No data available in table",
    zeroRecords: "No matching records found",
    info: "Showing _START_ - _END_ of _TOTAL_ entries",
    infoEmpty: "Showing 0 - 0 of 0 entries",
    infoPostFix: "",
    thousands: ",",
    lengthMenu: "Show _MENU_ entries",
    infoFiltered: "(filtered from _MAX_ total entries)",
    loadingRecords: "Loading......",
    processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i><span class="sr-only">Processing...</span>',
    search: "Search",
    paginate: {
      first: "First",
      last: "Last",
      next: "Next",
      previous: "Previous"
    },
      ...userTableSettings.language
    },
	dom: // DataTables DOM positioning https://datatables.net/examples/basic_init/dom.html
"<'row table-top-row'" + // opening top row
"<'col-xs-6 show-entries'l>" + // show entries dropdown
"<'col-xs-6 holland-key-wrapper text-right'B>" +
">" + // closing top row
"<'row' <'col-sm-12'tr> >" + // table row
"<'row' <'col-xs-12' <'text-right compare-favorites'> > >" + // compare div
"<'row table-bottom-row'" + // opening bottom row
"<'col-sm-5'i>" + // showing entries information
"<'col-sm-7'p>" + // pagination buttons
">",
    ...userSettings
  };
 
  let table = $(tableId).DataTable({...defaultSettings})
  return table;
}

$(document).on('click', 'ul.pagination li a', function(e) {
  $('ul.pagination li.disabled a').attr('aria-disabled', true);
  $('ul.pagination li:not(li.disabled) a').attr('aria-disabled', false);
  $('li.active a').attr('aria-current', 'page');
  $('li:not(li.active) a').removeAttr('aria-current', 'page');
})

/**
 * Creates an accessible table in the event that a table cannot be converted into a data table with createDataTable
 * @param tableId - The id of this table
 */
function createAccessibleTable(tableId) {
  $(tableId).attr('role', 'table');
  $(tableId + ' thead').attr('role', 'rowgroup');
  $(tableId + ' tbody').attr('role', 'rowgroup');

  $(tableId + ' tr').attr('role', 'row')

  $(tableId + ' th').attr('scope', 'col').attr('tabindex', 0).attr('aria-sort', 'none').attr('role', 'columnheader');

  $(tableId + ' td').attr('tabindex', 0).attr('role', 'cell');
  $(tableId + ' td > button').parent().removeAttr('tabindex');
  $(tableId + ' td > a').parent().removeAttr('tabindex');
  //$(tableId + ' td > i').parent().removeAttr('tabindex');
  $(tableId + ' td > .dropdown').parent().removeAttr('tabindex');
  $(tableId + ' td input[type="checkbox"]').parent().parent().removeAttr('tabindex');
  $(tableId + ' td input[type="text"]').parent().removeAttr('tabindex');
  $(tableId + ' th input[type="text"]').parent().removeAttr('tabindex');
  $(tableId + ' tr td:first-child').attr('role', 'rowheader').attr('scope', 'row');
}
//////////////////////////////////////////////////////////////////////////
// Datatable functions
// Description: Object for creating common datatable functionality
// Use: Make sure to add the following JS to any files you use this in
//      <script type="text/javascript" src="https://cdn.datatables.net/v/bs/dt-1.10.18/r-2.2.2/datatables.min.js"></script>
//      The link for the CSS is in the include - DefaultHTMLHead. Update the version there if you change the script version
/////////////////////////////////////////////////////////////////////////

/**
 * Creates a basic table using the dataTables API
 * @param tableId The id of this table
 * @param tableData The data to display in this table
 * @param tableColumns The columns in this table
 */

function createTableWBL(tableId, tableData, tableColumns) {
  $(tableId).DataTable({
    destroy: true,
    ordering: false,
    paging: false,
    searching: false,
    info: false,
    fnDrawCallback:function(o) { // Table Drawn
      // Common to all tables in the app
      $(this)
        .addClass('table table-bordered table-striped table-hover table-responsive')
      	.css({'width' : '100%'});
      // Needed for accessibilty
      $('th').attr('scope', 'col').attr('tabindex', 0);
      $('td').attr('tabindex', 0);
    },
    createdRow: function( row, data, dataIndex ) {
      // Needed for accessibilty
      $(row).children('td:first-child').attr('role', 'rowheader').attr('scope', 'row');
    },
    data: tableData,
    columns: tableColumns
  });
}

/**
 * Creates a data table using the dataTables API
 * @param tableId - The id of this table
 * @param userTableSettings - Settings for this dataTable
 * @param options - Used to toggle options within this table.
 *					Accepted parameters:
 *						* srLabel (string): A screen reader only label describing the content of the table.
 *                      * srOnly (boolean): Makes the table visiable only to screen readers.
 * 						* tableType (string): The type of table you want to create.
 *                       	- basic: A standard table w/o ordering, paging, searching, or info. A basic table.
 */
function createDataTableWBL(tableId, userTableSettings, options) {
  if ($.fn.DataTable.isDataTable(tableId)) {
    $(tableId).DataTable().destroy();    
  }
  
  let userSettings = {
   	...userTableSettings,
  }
  delete userSettings.fnDrawCallback;
  delete userSettings.language;
  delete userSettings.createdRow;
  
  if (options.tableType === "basic") {
   userSettings = {
     ...userSettings,
     info: false,
     ordering: false,
     paging: false,
     searching: false
   }
  }
  
  let defaultSettings = {
    ordering: true,
    order: [], // Needed for if first column is not orderable.
    paging: true,
    searching: true,
    fnDrawCallback: function(settings) {
      let tableClasses = 'table table-striped table-hover table-responsive table-bordered';
      let tableCss = {'width': '100%'}
      if (options.srOnly) {
       tableClasses = tableClasses + ' sr-only'; 
      }
      if (options.srLabel) {
       $(tableId).attr('aria-label', options.srLabel) 
      }
      if (options.removeTablePadding) {
        tableCss = {
          ...tableCss,
          'padding': '0px'
        }
      }
      if (userTableSettings.fnDrawCallback) {
      	userTableSettings.fnDrawCallback(settings);
      }
      
      // Common to all tables in the app
      $(this).addClass(tableClasses).css({...tableCss}).attr('role', 'table');
  
      // Hide info display manually, otherwise screen reader will not read table properly
      if (settings.aoData.length < 10) {
        $(tableId + "_info").hide();
        $(tableId + "_paginate").hide();
        $(tableId + "_length").hide();
      } else if (settings.oInit.paging) {
        $(tableId + "_info").show();
        $(tableId + "_paginate").show();
        $(tableId + "_length").show();
      }
      
      // Needed for accessibility
      $('thead').attr('role', 'rowgroup');
      $('tbody').attr('role', 'rowgroup');
      
      $('tr').attr('role', 'row');
      
      $('th').attr('scope', 'col').attr('tabindex', 0).attr('aria-sort', 'none').attr('role', 'columnheader');
      $('th.sorting_asc').attr('aria-sort', 'ascending');
      $('th.sorting_desc').attr('aria-sort', 'descending');
      
      $('td').attr('tabindex', 0).attr('role', 'cell');
      $('tr').children('td:first-child').attr('role', 'rowheader').attr('scope', 'row');
      
      $('td > button').parent().removeAttr('tabindex');
      $('td > a').parent().removeAttr('tabindex');
      //$('td > i').parent().removeAttr('tabindex');
      $('td > .dropdown').parent().removeAttr('tabindex');
      $('td input[type="checkbox"]').parent().parent().removeAttr('tabindex');
      
      $('ul.pagination').attr('role', 'region').attr('aria-label', 'pagination');
      $('ul.pagination li.disabled a').attr('aria-disabled', true);
      $('ul.pagination li.active a').attr('aria-current', 'page');
      
      if (!options.srOnly) {
        $(tableId + '_wrapper').find('.help-block').remove();
        $(tableId + '_wrapper').append('<p class="help-block"><i class="fa fa-arrows-h" aria-hidden="true"></i>Table may scroll horizontally depending on device and screen size.</p>')
      }
    },
    createdRow: function(row, data) {
      if (userTableSettings.createdRow) {
      	userTableSettings.createdRow(row);
      }
      
      // Needed for accessibility
      $(row).children('td:first-child').attr('role', 'rowheader').attr('scope', 'row');
    },
    language: {
      //Loaded from datatables-language-options include (1205)
    emptyTable: "No data available in table",
    zeroRecords: "No matching records found",
    info: "Showing _START_ - _END_ of _TOTAL_ entries",
    infoEmpty: "Showing 0 - 0 of 0 entries",
    infoPostFix: "",
    thousands: ",",
    lengthMenu: "Show _MENU_ entries",
    infoFiltered: "(filtered from _MAX_ total entries)",
    loadingRecords: "Loading......",
    processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i><span class="sr-only">Processing...</span>',
    search: "Search",
    paginate: {
      first: "First",
      last: "Last",
      next: "Next",
      previous: "Previous"
    },
      ...userTableSettings.language
    },
	dom: // DataTables DOM positioning https://datatables.net/examples/basic_init/dom.html
"<'row table-top-row'" + // opening top row
"<'col-xs-6 show-entries'l>" + // show entries dropdown
"<'col-xs-6 holland-key-wrapper text-right'B>" +
">" + // closing top row
"<'row' <'col-sm-12'tr> >" + // table row
"<'row' <'col-xs-12' <'text-right compare-favorites'> > >" + // compare div
"<'row table-bottom-row'" + // opening bottom row
"<'col-sm-5'i>" + // showing entries information
"<'col-sm-7'p>" + // pagination buttons
">",
    ...userSettings
  };
 
  let table = $(tableId).DataTable({...defaultSettings})
  return table;
}

$(document).on('click', 'ul.pagination li a', function(e) {
  $('ul.pagination li.disabled a').attr('aria-disabled', true);
  $('ul.pagination li:not(li.disabled) a').attr('aria-disabled', false);
  $('li.active a').attr('aria-current', 'page');
  $('li:not(li.active) a').removeAttr('aria-current', 'page');
})

/**
 * Creates an accessible table in the event that a table cannot be converted into a data table with createDataTable
 * @param tableId - The id of this table
 */
function createAccessibleTableWBL(tableId) {
  $(tableId).attr('role', 'table');
  $(tableId + ' thead').attr('role', 'rowgroup');
  $(tableId + ' tbody').attr('role', 'rowgroup');

  $(tableId + ' tr').attr('role', 'row')

  $(tableId + ' th').attr('scope', 'col').attr('tabindex', 0).attr('aria-sort', 'none').attr('role', 'columnheader');

  $(tableId + ' td').attr('tabindex', 0).attr('role', 'cell');
  $(tableId + ' td > button').parent().removeAttr('tabindex');
  $(tableId + ' td > a').parent().removeAttr('tabindex');
  //$(tableId + ' td > i').parent().removeAttr('tabindex');
  $(tableId + ' td > .dropdown').parent().removeAttr('tabindex');
  $(tableId + ' td input[type="checkbox"]').parent().parent().removeAttr('tabindex');
  $(tableId + ' td input[type="text"]').parent().removeAttr('tabindex');
  $(tableId + ' th input[type="text"]').parent().removeAttr('tabindex');
  $(tableId + ' tr td:first-child').attr('role', 'rowheader').attr('scope', 'row');
}
//////////////////////////////////////////////////////////////////////////
/* Checkbox dropdown functions
   Description: Functions for creating accessible dropdowns with checkboxes
   Use: Add the following CSS to the top of any page that will be using this
		functionality.
        
    	.checkbox-input {
          margin-top: 4px;
        }
        .checkbox-input-label {
    	  display: inline;
          margin-left: 1rem;
          pointer-events: none;
        }
        .dropdown-menu {
          padding: 1rem;
          width: 100%;
        }
        .dropdown-menu-button {
          background-color: white;
          border: 1px solid #ccc;
          border-radius: 4px;
          padding: 6px 12px;
          text-align: left;
          width: 100%;
        }
        .dropdown-menu-button-caret {
          font-weight: 900;
        }
        .float-right {
          float: right;
          vertical-align: middle;
        }
*/
/////////////////////////////////////////////////////////////////////////

function createCheckboxDropdownMenu(selectMenuWrapper, selectMenuId) {
    let arrayOptions = $('#'+selectMenuId)[0];
    let optionCount = 0;
    let dropDownMenuId = selectMenuId + 'DropDownMenu';
    let dropDownMenuButtonId = selectMenuId + 'DropDownMenuButton';

  	$('#'+selectMenuId).css('display', 'none');
    $('#'+selectMenuWrapper)
      .append('<div id="'+dropDownMenuId+'" class="dropdown">' +
            	'<button type="button" id="'+dropDownMenuButtonId+'" class="dropdown-menu-button" aria-haspopup="true" aria-expanded="false">' +
            		'selected (<span class="selected-options-count">0</span>) <span class="float-right dropdown-menu-button-caret fa fa-angle-down" aria-hidden="true"></span>' +
  				'</button>' +
            	'<div class="dropdown-menu" aria-labelledby="#'+dropDownMenuButtonId+'"></div>' +
              '</div>')
    
 	$('#'+selectMenuWrapper+' label').attr('for', dropDownMenuButtonId);

    Array.from(arrayOptions).forEach(function (opt) {
      $('#'+dropDownMenuId+' .dropdown-menu').append('<div class="checkbox-input"><input type="checkbox" id="checkbox-input-'+opt.value+'" value="'+opt.value+'" checked="'+opt.selected+'" aria-label="'+opt.text+'" /><label for="checkbox-input-'+opt.value+'" class="checkbox-input-label">'+opt.text+'</label></div>');
      
      if (opt.selected) {
        optionCount++;
      }
    });
  	
  	$('#'+dropDownMenuButtonId).attr('aria-label', $('#'+selectMenuWrapper+' label').html() + ' selected ' + optionCount);
    $('.selected-options-count').html(optionCount);

    $('.dropdown-menu input').click(function (e) {
      let count = parseInt($('.selected-options-count').html())

      Array.from(arrayOptions).forEach(function (opt) {
        if (opt.value == e.target.value) {
          opt.selected = !opt.selected;
          count = opt.selected ? count + 1 : count - 1;
        }
      });

      $('.selected-options-count').html(count)
      $('#'+dropDownMenuButtonId).attr('aria-label', $('#'+selectMenuWrapper+' label').html() + ' selected ' + count);
    });

    $('#'+dropDownMenuButtonId).click(function () {
      if ($(this).parent().hasClass('open')) {
        $(this).parent().removeClass('open');
        $(this).attr('aria-expanded', false);
      } else { 
        $(this).parent().addClass('open');
        $(this).attr('aria-expanded', true);
      }
    });

    let dropDownMenu = $('#'+dropDownMenuId)
      .keydown(function (e) {
        let key = e.key.toLowerCase();

        if (key === 'escape' && dropDownMenu.hasClass('open')) {
          $('#'+dropDownMenuButtonId).trigger('click');
          $('#'+dropDownMenuButtonId).focus();
        }

        if (key !== 'tab') {
          return;
        }

        let tabbable = $()
          // All form elements can receive focus.
          .add( dropDownMenu.find("input") )
        let target = $(e.target);  

        // Reverse tabbing (Key: Shift+Tab).
        if (e.shiftKey) {
          if (target.is(dropDownMenu) || target.is(tabbable.first())) {
            // Force focus to last element in container.
            e.preventDefault();
            tabbable.last().focus();
          }
          // Forward tabbing (Key: Tab).
        } else {
          if (target.is(tabbable.last())) {
            // Force focus to first element in container.
            e.preventDefault();
            tabbable.first().focus();
          }
        }
    });

    $(document).on('click', function(event) {
      if (!$(event.target).closest('#'+dropDownMenuId).length && $('#'+dropDownMenuId).hasClass('open')) {
        // Hide the menus.
        $('#'+dropDownMenuButtonId).trigger('click');
      }
    });
  }
//////////////////////////////////////////////////////////////////////////
// Datatable functions
// Description: Object for creating common datatable functionality
// Use: Make sure to add the following JS to any files you use this in
//      <script type="text/javascript" src="https://cdn.datatables.net/v/bs/dt-1.10.18/r-2.2.2/datatables.min.js"></script>
//      The link for the CSS is in the include - DefaultHTMLHead. Update the version there if you change the script version
/////////////////////////////////////////////////////////////////////////



function createChartDataAccordion(widgetID, tableID, title) {
  const collaspableID = widgetID + '-collaspable'
  const groupID = widgetID + '-group'
  const collaspableHeading = widgetID + '-heading'
  let found = document.getElementById(widgetID)
  if(!document.getElementById(groupID)){
    if(!tableID){
     
          //$('#'+widgetID).css({  "width": "100%","border": "1px solid #dddddd", "padding": "0 20px 0 20px","margin": "60px auto"})
    } else{
    $('#'+widgetID).css({  "width": "100%","border": "1px solid #dddddd", "padding": "0 20px 0 20px","margin": "60px auto"})
  $('#'+widgetID).append('<div class="panel-group" id="'+groupID+'" aria-multiselectable="true">'+'<div class="panel panel-default">'
              			+'<div class="panel-heading" id="'+collaspableHeading+'">'
                			+'<h4 class="panel-title">'
                              +  '<a class="js-tabcollapse-panel-heading accordion-toggle  collapsed" role="button" data-toggle="collapse" data-parent="#'+groupID+'"  href="#'+collaspableID+'" aria-expanded="false" aria-controls="'+collaspableID+'">'
                            +  title
                            +    '</a>'
               				+ '</h4>'
              			+'</div>'
              			+'<div id="'+collaspableID+'" class="panel-collapse collapse" aria-labelledby="'+collaspableHeading+'">'
                        +  '<div class="panel-body">'
                		
                        +   ' <table id="'+ tableID +'"></table>'

                      +   ' </div>'
              		+	'</div>'
                   +' </div></div>') 
    }

  }
  
 
  setTimeout(function(){
  let selector = '#'+widgetID + ' svg'
       $(selector).each(function() {
    $(this).attr('aria-hidden','true');
	});    
  }, 500)

  
  window.onload = function()
{ 
    let selector = '#'+widgetID + ' svg'
       $(selector).each(function() {
    $(this).attr('aria-hidden','true');
});
  }
}

//------------------------------------------------------------

//This is used to handle updating the Warning Message items
function handleWarningLinkClick(link,area) {
  var settings = jQuery.extend({}, WRM$.ajaxDefaults);
  settings.url = wrmUrl('~/PostBack/_/MarkWarningComplete/_');
  settings.data = JSON.stringify({ label: area});
  $.ajax(settings);
  window.open(link,"_self");
}

function userLogout() {
  //This is to remove the zustand state so navui knows it's logged out
  localStorage.removeItem('navigatorPreferences');

  datadogClearUserSession();
  
  window.location.href="/account/logout"
}

// The manageSessionTimeOut function was created for accessability reasons. The following code basically checks for activity.
// If there has been no activity 20 minutes they will be given a notification to either continue their session for another 20 minutes.
// If there is no response to the notification for 30 seconds they will be logged out.
// This function considers time away from the site as inactivity. 
// For example if a student leaves the site and comes back more than 20 minutes later they will be logged out.


function manageSessionTimeOut(){
//Check to see if the user is authenticated, if not then remove the session stamp from local storage.
if (!wrm_userauth) {
   localStorage.removeItem('session_stamp')
  return;
}
// Check if the session stamp exists
  if(localStorage.getItem('session_stamp')){
  let getStamp = new Date(localStorage.getItem('session_stamp'));
// Calculate the time difference from the initial session stamp vs the current time.
  let currentTime = new Date()
  let checkDiff = currentTime - getStamp
// Set the total time of allowed inactivity.
  let totalTimeOutMin = 20
  let diffMins = Math.floor(((checkDiff % 86400000) % 3600000) / 60000); // minutes
  let limit = Math.floor(60000 * totalTimeOutMin)
  let remaining = limit - checkDiff
  if(diffMins > totalTimeOutMin + 1) {
 	// If more than 21 minutes has passed with inactivity, log off the user. 
 	// This accounts of scenarios where the user left the site, and more than 21 minutes has passed.
    logoutAndResetSession()
    return;
     }
    //This starts the timer counting down 20 minutes
    let sessionTimer = window.setTimeout(timerCallBack, limit)
    function timerCallBack(){
      //The Logout timer is what starts after the notification has popuped up saying their session will end unless they click continue. 
     const logoutTimer = setTimeout(function(){logoutAndResetSession()}, 30000);
  		BASE_Notify.sessionEnd('Your session has expired due to inactivity.', 'To continue your session for 20 more minutes click continue. Otherwise you will be logged out in 30 seconds.')
			$(".session-expired").append( "<hr/> <button class='btn btn-primary' id='continue-session'>Continue</button>" )
    		$("#continue-session").click(function(){ 
              //Clears the logout timer and prevents the user from automatically being logged out.
        	clearTimeout(logoutTimer);
              //Updates the session stamp to start over
  			localStorage.setItem('session_stamp', new Date());
      		$(".session-expired").remove()
    		 resetTimer()
   		 });
    }
    function resetTimer(updateSessionStamp){
      // The Scroll Event Listener gets called incredibly frequently, so to avoid updating the session stamp 25+ times in a second the session stamp is only updated on clicks and keydowns. However scrolls will still reset the timer.
      	updateSessionStamp ? localStorage.setItem('session_stamp', new Date()) : ''
      	//This clears the timer and restarts back to 20 minutes
        clearTimeout(sessionTimer)
        sessionTimer = window.setTimeout(timerCallBack, limit)
    }
    window.addEventListener("keydown", function myKeyStroke() {
		resetTimer(true)
    })
      window.addEventListener("click", function myClick() {
		resetTimer(true)
    });
        window.addEventListener("scroll", function myScroll() {
		resetTimer(false)
    });
  }
  else{
	//Start a New Session if no session stamp was found and a user has been authenticated.
  	localStorage.setItem('session_stamp', new Date());
    manageSessionTimeOut()
  }
}

function logoutAndResetSession() {
  localStorage.removeItem('session_stamp');
  //This is to remove the zustand state so navui knows it's logged out
localStorage.removeItem('navigatorPreferences');

  datadogClearUserSession();


  window.location.href="/account/logout"
}
function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.getElementsByClassName(selector)) {
            return resolve(document.getElementsByClassName(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.getElementsByClassName(selector)) {
                resolve(document.getElementsByClassName(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

$(function() {
	manageSessionTimeOut()
})

$(function() {

  // Needed for accessibility //
  $(window).resize(function (e) {
    if (e.target.outerWidth > 1024 && $('#sidebar').css('display') !== 'table-cell') {
      $('#sidebar').css('display', 'table-cell');
    }
  });
  
  //////////////////////////////

  $("#menu-bar").show();

  $('a.btn').keydown(function(event){    
    if(event.keyCode==13){
      $(this).trigger('click');
    }
  });

  $('input[type=checkbox]').keydown(function(event){
    if(event.keyCode==13){
      $(this).trigger('click');
    }
  });

  //$('.modal').on('shown.bs.modal', function () {
  //setTimeout(function (){
  //$('.modal input:first').focus();
  //}, 1000);
  //});

  $('.modal').on('shown.bs.modal', function () {
    //$('.modal input:not(input[type=button], input[type=radio],.modal input[type=submit],.modal button):visible:first').focus()
    $('.modal .modal-title').focus();
  });

  // Change input to date format if mobile 
  //if (isMobile()){
  //$("#dateBirth").attr("type", "date");
  //}

  // Hides the jquery datepicker on touch devices
  if (!isMobile()) {


    // Date Picker for Journey Birth Date - Account Settings 
    var userTypeId = "0";
    if(userTypeId <= 256){    
      $('#dateBirth').datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: "-75:-16",
        maxDate: "-16y",
        //minDate: "-25y",
        beforeShow : function() { 
          var dt = new Date();
          var year = dt.getFullYear() - 25;
          dt.setFullYear(year);
          $(this).datepicker('option', 'defaultDate', dt);
        },
        dateFormat: wrm_datepickerformat
      });   
    }

    //Journey Registration
    $('.adultUserBirthdate').datepicker({
      changeMonth: true,
      changeYear:true,
      yearRange: "-75:-16",
      maxDate: "-16y",
      //minDate: "-25y",
      beforeShow : function() { 
        var dt = new Date();
        var year = dt.getFullYear() - 25;
        dt.setFullYear(year);
        $(this).datepicker('option', 'defaultDate', dt);
      },
      dateFormat: wrm_datepickerformat
    });   

    //Navigator 
    $('#userBirthDate, input[id^=parentStudentBirthdate], #personalform, #dateBirth').datepicker({
      changeMonth: true,
      changeYear:true,
      yearRange: "-20:-8",
      maxDate: "-8y",
      //minDate: "-25y",
      beforeShow : function() { 
        var dt = new Date();
        var year = dt.getFullYear() - 15;
        dt.setFullYear(year);
        $(this).datepicker('option', 'defaultDate', dt);
      },
      dateFormat: wrm_datepickerformat
    }); 

    //Parent only on focus of element
    $('body').on('focus', '.parentDatepicker', function() {
      $(this).datepicker({
        changeMonth: true,
        changeYear:true,
        yearRange: "-20:-8",
        maxDate: "-8y",
        //minDate: "-25y",
        beforeShow : function() { 
          var dt = new Date();
          var year = dt.getFullYear() - 15;
          dt.setFullYear(year);
          $(this).datepicker('option', 'defaultDate', dt);
        },
        dateFormat: wrm_datepickerformat
      });    
    });

    // Create a resume datepicker
    $('.resume-page .datepicker').datepicker({
      dateFormat: "mm/yy",
      changeMonth: true,
      changeYear: true,
      yearRange: "-75:+1",
      showButtonPanel: true,
      //maxDate: '0y',
      onClose: function(dateText, inst) {
        function isDonePressed(){
          return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
        }

        if (isDonePressed()){
          var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
          var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
          $(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');

          $('.date-picker').focusout()//Added to remove focus from datepicker input box on selecting date
        }
      },
      beforeShow : function(input, inst) {

        inst.dpDiv.addClass('month_year_datepicker')

        if ((datestr = $(this).val()).length > 0) {
          year = datestr.substring(datestr.length-4, datestr.length);
          month = datestr.substring(0, 2);
          $(input).after($(input).datepicker('option', 'defaultDate', new Date(year, month-1, 1)));
          $(input).after($(input).datepicker('setDate', new Date(year, month-1, 1)));
          $(".ui-datepicker-calendar").hide();
        }
      }
    });

    $('.datepicker').datepicker({
      changeMonth: true,
      changeYear: true, 
      maxDate: '0',
      dateFormat: wrm_datepickerformat
    });


  }


  $('[data-toggle="tooltip"]').tooltip()

  //Favorites
  /*
  $(".favorite").click(function() {
    $(this).toggleClass( "selected" );
  });
	*/


  //set usertype dropdowns
  handleUserTypeInteraction();
  //New Message Count
  getMsgCount();

  //Display Any Warning/Infos
  displayWarning();

  //--------------------------------------------------


  //Left Menu Navigation
  $('#menu > ul > li > a').click(function() {
    $('#menu li').removeClass('active');

    $(this).closest('li').addClass('active'); 

    var checkElement = $(this).next();

    if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
      $(this).closest('li').removeClass('active');
      checkElement.slideUp('normal');
      $(this).attr("aria-expanded", "false");
    }

    if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
      $('#menu ul ul:visible').slideUp('normal');
      checkElement.slideDown('normal');
      $(this).closest('li').addClass('active');
      $(this).attr("aria-expanded", "true");
    }

    return ($(this).closest('li').find('ul').children().length == 0);
  });

  //Match Height
  
  // turned off by Alen because it is affecting scrollTop plugin
  //$('#right-hand-div').matchHeight({
  //  target: $('#sidebar'),
  //  remove: false
  //});
    

      

  //Sticky Footer

  if ( $('#footer').length ) {
    var docHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var footerTop = $('#footer').position().top + footerHeight;
  }

  if (footerTop < docHeight) {
    $('#footer').css('padding-bottom', 0+ (docHeight - footerTop) + 'px');
  }

  if("0" != "8192") {
    //Select Correct Left Menu Items for class .active
    $('.left-menu li').removeClass('active');
    $('.left-menu li' + '.' + wrm_section).addClass('active');
    $('.left-menu li' + '.' + wrm_page).addClass('active');
  }
  //Sidebar
  var s = 0;
  $('.menu-toggle').click(function() {
    if (s === 0) {
      s = 1;
      $( "#sidebar" ).animate({left: "-210px"}, 100 );
      $('.dashboard-wrapper').animate({'margin-left': "0px"}, 100);
    } else {
      s = 0;
      $('#sidebar').animate({left: "0px"}, 100);
      $('.dashboard-wrapper').animate({'margin-left': "210px"}, 100);
    }
  });
  $('[data-toggle=offcanvas]').click(function () {
    let menuExpanded =  $('.row-offcanvas').hasClass('active');
    console.log("Tabindex: ", $('.row-offcanvas').hasClass('active'));
    let displayProp = menuExpanded ? 'none' : 'block';
    $('#sidebar').css('display', displayProp);
    $('#nav-control-button').attr('aria-expanded', !menuExpanded);
    $('.row-offcanvas').toggleClass('active');
  });


  //Change Photo Settings
  $('.user-avatar')
    .mouseover(function() {				
    $('.camera-icon').css( 'display', 'block' );
  })
    .mouseout(function() {
    $('.camera-icon').css( 'display', 'none' );
  });

  //Assessments complete animate results - home	 
  $('.result-bar .progress-bar').css('width',  function(){ return ($(this).attr('aria-valuenow')+'%')});

  //Tasks Progress Bar
  var totalCheckBoxes = $('.current.tasks input.tasks-list-cb').length;
  var checkedBoxes = $('.current.tasks input.tasks-list-cb:checked').length;
  var checkBoxValue = (checkedBoxes / totalCheckBoxes) * 100;

  $('.current.tasks input.tasks-list-cb').attr('value', checkBoxValue);
  $('#tasks-progress-bar').css('width', checkBoxValue + '%').attr('aria-valuenow', checkBoxValue);
  $('#percentage-done-number').html(checkBoxValue.toFixed());

  if (checkBoxValue==0) {
    $('#tasks-progress-bar').css('visibility', 'hidden');
  } 

  $('.current.tasks input.tasks-list-cb').on('click', function() {
    var checkedBoxes = $('.current.tasks input.tasks-list-cb:checked').length;
    checkBoxValue = (checkedBoxes / totalCheckBoxes) * 100;

    if (checkBoxValue==0) {
      $('#tasks-progress-bar').css('visibility', 'hidden');
    } else {
      $('#tasks-progress-bar').css('visibility', 'visible');
      $('#tasks-progress-bar').css('width', checkBoxValue + '%').attr('aria-valuenow', checkBoxValue);
      $('#percentage-done-number').html(checkBoxValue.toFixed());
    }
  });

  //DateStamp 
  //var now = new Date();
  //var nowYear = now.getFullYear();
  //var nowMonth = now.getMonth() + 1;
  //var nowDate = now.getDate();
  //var DateStamp = WRM$.formatDateShort(nowMonth);
  //$(".datestamp").html(DateStamp);

  //Tab Change
  $('.nav-tabs a').click(function (e) {
    e.preventDefault()
    $(this).tab('show')
  });

  if( $('#view-by-pathways').hasClass('active') ) { 
    $('#view-by-pathways-link').css('display', 'none');
    $('#view-by-clusters-link').css('display', 'block');
  } else if ($('#view-by-clusters').hasClass('active')) {
    $('#view-by-pathways-link').css('display', 'block');
    $('#view-by-clusters-link').css('display', 'none');
  }
  $('#view-by-pathways-link a').click(function (e) {
    $('#view-by-pathways-link').css('display', 'none');
    $('#view-by-clusters-link').css('display', 'block');
  });
  $('#view-by-clusters-link a').click(function (e) {
    $('#view-by-pathways-link').css('display', 'block');
    $('#view-by-clusters-link').css('display', 'none');
  });

  //================================================================================================================================
  //Accordion
  /*$('.panel-collapse').prev().addClass('active').find('a').addClass('collapsed').prepend('<i class="fa fa-plus-square"></i>');

  $('.panel-collapse').on('show.bs.collapse', function (e) {
    e.stopPropagation();
    $(this).prev().find('.fa-plus-square').first().removeClass('fa-plus-square').addClass('fa-minus-square');
  });

  $('.panel-collapse').on('hide.bs.collapse', function (e) {
    e.stopPropagation();
    $(this).prev().find('.fa-minus-square').first().removeClass('fa-minus-square').addClass('fa-plus-square');
  });

  //$('.panel-heading a').on('click', function (e) {
  //e.preventDefault();
  //$('.fa-minus-square').not($(this)).toggleClass('fa-plus-square fa-minus-square');
  //if ($(this).hasClass('collapsed')) {
  //$(this).find('.fa-plus-square').addClass('fa-minus-square').removeClass('fa-plus-square');       
  //} else {
  //$(this).find('.fa-minus-square').addClass('fa-plus-square').removeClass('fa-minus-square');
  //}
  //});

  $.fn.accordionPrep = function() {
    var $active = $('.panel-collapse').prev().addClass('active');
    $active.find('a').prepend('<i class="fa fa-plus-square"></i>');
  };*/

  //if (isMobile()) {
  //$('.panel-group').on('shown.bs.collapse', function (e) {
  //var offset = $('.panel.panel-default > .panel-collapse.in').offset();
  //if(offset) {
  //$('html,body').animate({
  //scrollTop: $('.panel-collapse.in').siblings('.panel-heading').offset().top -70
  //}, 500); 
  //}
  //});
  //}

  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  //Cluster Icons
  $.fn.clusterIcons = function() {
    $('.cluster-name').find('span.fa-stack').remove();
    $('.cluster-name').prepend('<span class="fa-stack fa-lg"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-stack-1x fa-inverse"></i></span> ');

    $('.manufacturing > .cluster-name').find('.fa-inverse').addClass('fa-wrench');
    $('.transportation-distribution-and-logistics > .cluster-name').find('.fa-inverse').addClass('fa-bus');
    $('.science-technology-engineering-and-mathematics > .cluster-name').removeClass('fa-flask');
    $('.science-technology-engineering-and-mathematics > .cluster-name').find('.fa-inverse').addClass('fa-flask');
    $('.architecture-and-construction > .cluster-name').find('.fa-inverse').addClass('fa-building');
    $('.marketing > .cluster-name').find('.fa-inverse').addClass('fa-lightbulb-o');
    $('.finance > .cluster-name').find('.fa-inverse').addClass('fa-calculator');
    $('.business-management-and-administration > .cluster-name').find('.fa-inverse').addClass('fa-bar-chart');
    $('.hospitality-and-tourism > .cluster-name').find('.fa-inverse').addClass('fa-suitcase');
    $('.human-services > .cluster-name').find('.fa-inverse').addClass('fa-users');
    $('.law-public-safety-corrections-and-security > .cluster-name').find('.fa-inverse').addClass('fa-lock');
    $('.government-and-public-administration > .cluster-name').find('.fa-inverse').addClass('fa-gavel');
    $('.education-and-training > .cluster-name').find('.fa-inverse').addClass('fa-book');
    $('.arts-audio-video-technology-and-communications > .cluster-name').find('.fa-inverse').addClass('fa-paint-brush');
    $('.information-technology > .cluster-name').find('.fa-inverse').addClass('fa-laptop');
    $('.health-science > .cluster-name').find('.fa-inverse').addClass('fa-stethoscope');
    $('.agriculture-food-and-natural-resources > .cluster-name').find('.fa-inverse').addClass('fa-tint');
  };	


  //Cluster Icons
  $.fn.careerFieldIcons = function() {
    $('.career-field-name').prepend('<span class="fa-stack fa-lg"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-stack-1x fa-inverse"></i></span> ');

    $('.industrial-manufacturing-and-engineering-systems .career-field-name').find('.fa-inverse').addClass('fa-cogs');
    $('.business-marketing-and-management .career-field-name').find('.fa-inverse').addClass('fa-briefcase');
    $('.human-services-and-resources .career-field-name').find('.fa-inverse').addClass('fa-users');
    $('.communication-and-information-systems .career-field-name').find('.fa-inverse').addClass('fa-rss');
    $('.health-sciences .career-field-name').find('.fa-inverse').addClass('fa-medkit');
    $('.environmental-and-agricultural-systems .career-field-name').find('.fa-inverse').addClass('fa-leaf');
  };

  //Pathway H1 Icons
  $.fn.pathwayIconsH1 = function() {
    $('h1.pathway-name').prepend('<span class="fa-stack fa-lg"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-stack-1x fa-inverse"></i></span> ');

    $('h1.pathway-name.manufacturing').find('.fa-inverse').addClass('fa-wrench');
    $('h1.pathway-name.transportation-distribution-and-logistics').find('.fa-inverse').addClass('fa-bus');
    $('h1.pathway-name.science-technology-engineering-and-mathematics').find('.fa-inverse').addClass('fa-flask');
    $('h1.pathway-name.architecture-and-construction').find('.fa-inverse').addClass('fa-building');
    $('h1.pathway-name.marketing').find('.fa-inverse').addClass('fa-lightbulb-o');
    $('h1.pathway-name.finance').find('.fa-inverse').addClass('fa-calculator');
    $('h1.pathway-name.business-management-and-administration ').find('.fa-inverse').addClass('fa-bar-chart');
    $('h1.pathway-name.hospitality-and-tourism').find('.fa-inverse').addClass('fa-suitcase');
    $('h1.pathway-name.human-services').find('.fa-inverse').addClass('fa-users');
    $('h1.pathway-name.law-public-safety-corrections-and-security').find('.fa-inverse').addClass('fa-lock');
    $('h1.pathway-name.government-and-public-administration').find('.fa-inverse').addClass('fa-gavel');
    $('h1.pathway-name.education-and-training').find('.fa-inverse').addClass('fa-book');
    $('h1.pathway-name.arts-audio-video-technology-and-communications').find('.fa-inverse').addClass('fa-paint-brush');
    $('h1.pathway-name.information-technology').find('.fa-inverse').addClass('fa-laptop');
    $('h1.pathway-name.health-science').find('.fa-inverse').addClass('fa-stethoscope');
    $('h1.pathway-name.agriculture-food-and-natural-resources').find('.fa-inverse').addClass('fa-tint');
  };


  //Work Value Icons
  $.fn.workValueIcons = function() {
    $('a.value-name').prepend('<span class="fa-stack fa-lg"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-stack-1x fa-inverse"></i></span> ');

    $('.achievement a.value-name').find('.fa-inverse').addClass('fa-trophy');
    $('.challenge a.value-name').find('.fa-inverse').addClass('fa-cubes');
    $('.co-workers a.value-name').find('.fa-inverse').addClass('fa-users');
    $('.creativity a.value-name').find('.fa-inverse').addClass('fa-lightbulb-o');
    $('.income a.value-name').find('.fa-inverse').addClass('fa-usd');
    $('.independence a.value-name').find('.fa-inverse').addClass('fa-globe');
    $('.lifestyle a.value-name').find('.fa-inverse').addClass('fa-clock-o');
    $('.prestige a.value-name').find('.fa-inverse').addClass('fa-certificate');
    $('.security a.value-name').find('.fa-inverse').addClass('fa-lock');
    $('.supervision a.value-name').find('.fa-inverse').addClass('fa-sitemap');
    $('.variety a.value-name').find('.fa-inverse').addClass('fa-exchange');
    $('.workplace a.value-name').find('.fa-inverse').addClass('fa-briefcase');
  };


  //Work Value H1 Icons
  $.fn.workValueIconsH1 = function() {
    $('h1.value-name').prepend('<span class="fa-stack fa-lg"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-stack-1x fa-inverse"></i></span> ');

    $('h1.value-name.achievement').find('.fa-inverse').addClass('fa-trophy');
    $('h1.value-name.challenge').find('.fa-inverse').addClass('fa-cubes');
    $('h1.value-name.co-workers').find('.fa-inverse').addClass('fa-users');
    $('h1.value-name.creativity').find('.fa-inverse').addClass('fa-lightbulb-o');
    $('h1.value-name.income').find('.fa-inverse').addClass('fa-usd');
    $('h1.value-name.independence').find('.fa-inverse').addClass('fa-globe');
    $('h1.value-name.lifestyle').find('.fa-inverse').addClass('fa-clock-o');
    $('h1.value-name.prestige').find('.fa-inverse').addClass('fa-certificate');
    $('h1.value-name.security').find('.fa-inverse').addClass('fa-lock');
    $('h1.value-name.supervision').find('.fa-inverse').addClass('fa-sitemap');
    $('h1.value-name.variety').find('.fa-inverse').addClass('fa-exchange');
    $('h1.value-name.workplace').find('.fa-inverse').addClass('fa-briefcase');
  };

  //Back to Top Button - Mobile Only	
  var offset = 300;
  var duration = 300;
  $(window).scroll(function() {
    if ($(this).scrollTop() > offset) {
      $('.back-to-top').fadeIn(duration);
    } else {
      $('.back-to-top').fadeOut(duration);
    }
  });

  $('.back-to-top').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop: 0}, duration);
    return false;
  });

  //Breadcrumb remove dashes
  $("#breadcrumb-section").html(wrm_sectiontitle.replace(/-/g,' '));
  $("#breadcrumb-page").html(wrm_pagetitle.replace(/-/g,' '));
  //$("#breadcrumb-section").html(wrm_section.replace(/-/g,' '));
  //$("#breadcrumb-page").html(wrm_page.replace(/-/g,' '));


  //Breadcrumb remove default
  $('li#breadcrumb-page').filter(function () {
    return $(this).text() == '';
  }).css('display','none');


  //open account setting modal based on URL string
  var parts = window.location.search.substr(1).split('&');
  var url_params = {};
  for (; parts.length ;) {
    var curr = parts.shift().split('=');
    if (curr.length > 1) {
      url_params[curr.shift()] = curr.join('=');
    }
  }
  if( url_params.needsbarriers ) {
    // if "needsbarriers" was passed in the URL, then open the login
    $('#needsbarriersModal').modal();
  }
  if( url_params.highestedlevel ) {
    // if "highestedlevel" was passed in the URL, then open the registration
    $('#schoolInformation').modal();
  }
  if( url_params.contactinfo ) {
    // if "contactinfo" was passed in the URL, then open the registration
    $('#contactInformation').modal();
  }
  if( url_params.myaddress ) {
    // if "myaddress" was passed in the URL, then open the registration
    $('#addressInformation').modal();
  }
});

function toggleDropdownEnabled(dd, state)
{
  if(dd != null && dd != undefined)
  {
    if(state === 0 || state === "0")
    {   
      dd.attr("disabled","disabled");
      dd.addClass("disabled");
    }
    else
    {
      dd.removeAttr("disabled");
      dd.removeClass("disabled");
    }    
  }
}
//KSK -1.11.2017 - PROVIDED A PARAMETER FROM A QUERY STRING AND THE URL AND GET THE VALUE
function getParameterByName(name, url) {
  if (!url) {
    url = window.location.href;
  }
  name = name.replace(/[\[\]]/g, "\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function findPos(obj) {
  var curtop = 0;
  if (obj.offsetParent) {
    do {
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
    return [curtop];
  }
}

// Get Messages
function getMsgCount(clear) {

  if (!wrm_userauth) return; // skip everything if thery're not logged-in

  ///////////////////////////////////////////////////////////////////////////////////////////  

  function set(sel, C, clear){ // Set the 'msg count' call-out
    clear = init(clear, true)
    $(sel).each(
      function () {
        if (clear||$(this).html().trim() == "") $(this).html(C);
        else if (wrm_rightleftlang) $(this).prepend(C);
        else $(this).append(': ' + C);
      });
  }
  function hide() { // Hide Dropdown
    $('.badge.wrmNewMsg').css('display','none');
    $('.navbar-default .messages a').removeAttr('data-toggle'); 
  }
  function show() { // Show Droprdown
    $('.badge.wrmNewMsg').css('display','inline-block');
    $('.navbar-default .messages a').attr('data-toggle', 'dropdown'); 
  }

  ///////////////////////////////////////////////////////////////////////////////////////////

  WRM$.msgCount(function(d) {
    var c = d.newCount, htm = "", div = '<li class="divider"></li>';
    if (c) { // if msg_count > 0 populate menu
      show(c);
      set('.badge.wrmNewMsg',c,clear);
      htm += "<li><a href=\"javascript:wrmGo('~/my-messages');\" class=\"wrmNewMsg\">" + d.menuMsg + "</a></li>" + div;
      for (var m in d.newMessages)
        htm += "<li><a href=\"javascript:wrmGo('~/message-view/default/" + m.left(1) + "/" + m.right(-2) + "');\"><i class=\"fa fa-envelope-o\"></i> " + d.newMessages[m] + "</a></li>";
      htm += div + "<li><a href=\"javascript:wrmGo('~/my-messages');\"><i class=\"fa fa-list\"></i> View All</a></li>";
      $("#messages_menu").html(htm);      
    } else {
      hide(); // if msg_count = 0, hide drop-down
    }
  });
}

//------------------------------------------------------------------------------
window.userGrade = 0;
window.userType = 0;

function setGradeData() {
  if ( window.userType < 512 ) {
    $("#outOfSchoolCurrentAccountTypeSelect option").prop("selected", "");
    $("#postsecondaryCurrentGradeLevelSelect option").prop("selected", "");
    switch (String(window.userType)) {
      case '256':
        var ctl = $("#outOfSchoolCurrentAccountTypeSelect option[value='-1']");
        $(ctl).attr('selected','selected');
        $(ctl).prop("selected", true);
        var ctl2 = $("#postsecondaryCurrentGradeLevelSelect option[value='" + window.userGrade + "']");
        $(ctl2).attr('selected','selected');
        $(ctl2).prop("selected", true);
        break;
      default:
        var ctl = $("#postsecondaryCurrentGradeLevelSelect option[value='-2']");
        $(ctl).attr('selected','selected');
        $(ctl).prop("selected", true);
        var ctl2 = $("#outOfSchoolCurrentAccountTypeSelect option[value='" + window.userType + "']");
        $(ctl2).attr('selected','selected');
        $(ctl2).prop("selected", true);
        break;
    }
  } 
  else {
    var ctl = $(".active input[value='" + window.userGrade + "']");
    $('label[id^=gr]').removeClass('active');
    $('label[id^=gr]').attr('checked', 'false');
    $(ctl).attr('checked','true');
    $('#gr' + window.userGrade).addClass('active');
  }
}

function SaveGradeChange() {
  var newLevel; 
  var userTp = window.userType;
  if ($('#postsecondaryCurrentGradeLevelSelect').length > 0) {
    newLevel = $('#postsecondaryCurrentGradeLevelSelect').val();
  }
  else {
    newLevel = $("label.active input[name='grade-level']").val();
    //added label before the .active in order to make the newLevel more speicifc 
  }
  window.userGrade = newLevel;
  if (newLevel >= 13 && newLevel <= 17) {
    userTp = 256;  //postsecondary
    $("#school_info").show(); // show school info row if change to postsecondary user 
    $("#school_summary").show(); 
    $("#edu_info").hide()
    $("#ed_summary").hide();
    $("#needsandbarriers").hide();
  } else if (userTp < 256) {
    $("#school_info").hide()
    $("#school_summary").hide(); 
    $("#edu_info").show()
    $("#ed_summary").show();
    $("#needsandbarriers").show();
  }
  if ($("#outOfSchoolCurrentAccountTypeSelect").is(":visible") && newLevel < 1) {
    userTp = $('#outOfSchoolCurrentAccountTypeSelect').val();
    newLevel = 0;
  }
  window.userType = userTp;
  if (newLevel < 6 || newLevel > 17) {
    $.get(wrmUrl('~/PostBack/_/ChangeAdultUserType/_'), {userType: userTp}, function(){  
    });
  }
  else {
    $.get(wrmUrl('~/PostBack/_/ChangeUserGradeLevel/_'), {gradeLevel: newLevel}, function(){  
    });
  }
  
  if (newLevel < 1) {
    switch (userTp) {
      case '1':
        newLevel = 'a graduate, just out of school looking for my first full-time job';
        break;
      case '4':
        newLevel = 'a laid off worker and/or a worker seeking a job within the same occupation';
        break;
      case '8':
        newLevel = 'a worker exploring a change to an entirely different occupation';
        break;
      case '16':
        newLevel = 'a veteran or active member in the military';
        break;
      case '32':
        newLevel = 'a person with a disability';
        break;
      case '64':
        newLevel = 'an ex-offender';
        break;
      case '128':
        newLevel = 'a retired person seeking another job or volunteer work';
        break;
    }    
  }
  if ($.isNumeric(newLevel)) {
    //getGradeText is in the GetGradeTextJs include
    newLevel = getGradeText(newLevel,true);
  }
  if($.isNumeric(newLevel)) {  
    $('#grade').html(newLevel + '<sup>th</sup> Grade'); // user account page
    if ($('#userGrade2').length > 0) {
      $('#userGrade2').html( newLevel + '<sup>th</sup> Grade' );
    }
  } else {
    $('#grade').html(newLevel); // user account page
    if ($('#userGrade2').length > 0) {
      $('#userGrade2').html(newLevel);
      setTimeout(function(){
        location.reload();
      }, 1000);
    }
  }


  $('#change-grade-modal').modal('hide');
  //COMMENT THIS LINE vvvv TO FORCE A POSTBACK AFTER GRADE CHANGE (BASE83)
  //window.location.reload(true);
}

$(function() {
  // $('.adult-out-of-school-selection').css('display','none');
  // $('.adult-back-to-school-selection').css('display','none');

  $('#postsecondaryCurrentGradeLevelSelect').change(function() {
    postsecondaryLevelChange();
  });
  $('#outOfSchoolCurrentAccountTypeSelect').change(function() {
    adultTypeChange();
  });
  //$('#adultCurrentAccountTypeSelect').change(function() {
  //    if ($('#adultCurrentAcountTypeSelect').val()=='-1') {
  //        $('.adult-back-to-school-selection').fadeIn(400);
  //        }
  //    else {
  //        $('.adult-back-to-school-selection').css('display','none');
  //        }
  //});
});

function adultTypeChange(){
  if ($('#outOfSchoolCurrentAccountTypeSelect').val()=='-1') {
    $('.postsecondary-selection').css('display','');
    //$('.adult-out-of-school-selection').css('display','none');
    $('#postsecondaryCurrentGradeLevelSelect').val('13'); //freshman
    $('.postsecondary-selection').fadeIn(400);
  }
  else {
    $('#postsecondaryCurrentGradeLevelSelect').val('-2');
  }
}

function postsecondaryLevelChange() {
  if ($('#postsecondaryCurrentGradeLevelSelect').val()=='-2') {
    $('.adult-out-of-school-selection').css('display','');
    $('#outOfSchoolCurrentAccountTypeSelect').val('1');
    $('.adult-out-of-school-selection').fadeIn(400);
  }
  else {
    $('#outOfSchoolCurrentAccountTypeSelect').val('-1');
  }
}
function handleUserTypeInteraction() {
  if ($('#postsecondaryCurrentGradeLevelSelect').val()=='-2') {
    $('.adult-out-of-school-selection').css('display','');
    $('.postsecondary-selection').css('display','none');
  }
  else {
    $('.postsecondary-selection').css('display','');
    $('.adult-out-of-school-selection').css('display','none');
  }
}

//TASK LIST


function fillTasks(userID, usertypeid, userGrade, userOrg) {
    return new Promise((resolve, reject) => {
        if (userID == undefined) userID = 0;
        if (usertypeid == undefined) usertypeid = 0;
        if (userGrade == undefined) userGrade = 0;
        if (userOrg == undefined) userOrg = 0;
        if (!wrm_userauth) return reject("User not authenticated");
        if (userID == 0) userID =0;
        if (userGrade == 0) userGrade =0;
        if (userOrg == 0) userOrg =0;
        if (usertypeid == 0) usertypeid =0;
        var strContents = "";

        if (usertypeid > 256 && usertypeid < 131072) {
            $.get(wrmUrl('~/PostBack/_/TaskList/_'), {
                userID: userID,
                gradeLevel: userGrade,
                orgID: userOrg,
                culture: 'en-US'
            }, function (listData) {
                if (listData !== undefined && typeof listData == "object") {
                    resolve(listData);
                } else {
                    reject("Invalid list data");
                }
            }).fail(function (jqXHR, textStatus, errorThrown) {
                reject(errorThrown);
            });
        } else if (usertypeid < 512) {
			try{
            WRM$.userToDoList(function (listData) {
       
                if (listData !== undefined && typeof listData == "object") {
                    resolve(listData);
                } else {
                    reject("Invalid list data");
                }
            })
            } catch(error){
              reject(error);
              }

        }
    });
}

function fillTasksOld(taskListID, userID, usertypeid, userGrade, userOrg) {
  if (userID == undefined) userID = 0; // IE and Safari do not support functions with default values 
  if (usertypeid == undefined) usertypeid = 0; // IE and Safari do not support functions with default values 
  if (userGrade == undefined) userGrade = 0; // IE and Safari do not support functions with default values 
  if (userOrg == undefined) userOrg = 0; // IE and Safari do not support functions with default values 
  if (!wrm_userauth) return; // skip everything if they're not logged-in
  if (userID==0) {
    userID=0;
  }
  if (userGrade==0) {
    userGrade=0;
  }
  if (userOrg==0) {
    userOrg=0;
  }
  if (usertypeid==0) {
    usertypeid=0;
  }
  $(taskListID).html("");
  var strContents = "";

  //navigator and adults
  if (usertypeid > 256 && usertypeid < 131072 ) {

    $.get(wrmUrl('~/PostBack/_/TaskList/_'), {userID: userID,gradeLevel: userGrade,orgID: userOrg,culture:'en-US'}, function(listData){  
      strContents = '<fieldset class="tasks-list"><legend class="sr-only">Tasks List</legend>';

      if (listData !== undefined && typeof listData == "object"){
        $.each(listData.List, function(index, item){
          var dt = '';
          var label = item.TaskName;
          var chkVal = '';
          if (item.Completed !== null) {
            dt = item.Completed;
            dt = dt.replace("/Date(","");
            dt = dt.replace(")/","");
            dt = new Date(Number(dt)).toLocaleDateString();
            chkVal = 'Checked="true"';
          }
          label = label.replace("<%KCIA%>",listData.InterestLabel);
          label = label.replace("<%KWVA%>",listData.ValuesLabel);
          label = label.replace("<%KSCA%>",listData.SkillsLabel);
          var link = true;
          var idx = "'" + index + "'" ;
          if (window.userType === 8192) {
            strContents += '<label for="Guid_' + index + '" class="tasks-list-item"><input type="checkbox" class="tasks-list-cb" id="Guid_' + index + '" ' + chkVal + ' disabled><span class="tasks-list-mark"></span><span class="tasks-list-desc">' + label + '</span><span class="datestamp" id="dts_' + index + '">' + dt + '</span></label>';
          } else {
            strContents += '<label for="Guid_' + index + '" class="tasks-list-item"><input type="checkbox" class="tasks-list-cb" id="Guid_' + index + '" onclick="javascript:toggleTaskCompletion(this.checked,' + idx + ')" ' + chkVal + '><span class="tasks-list-mark" style="border-color: #8c8c8c"></span> <span class="tasks-list-desc"><a href="' + item.URL + '">' + label + '</a><span class="sr-only is-completed">This step is not completed</span></span><span class="datestamp" id="dts_' + index + '">' + dt + '</span></label>';
          }
        });
        strContents += '</fieldset>'; 

        $(taskListID).html(strContents); 

        // Making external links in tasklist open in new tab
        $('.tasks-list-desc a').each( function() {
          if ( location.hostname === this.hostname || !this.hostname.length ) { // If local link
            // Ignore local links
          } else { // If external link
            $(this).attr("target","_blank").append('<i class="fa fa-external-link"></i><span class="sr-only">(Opens in a new window.)</span>');
          }
        });

        var totalCheckBoxes = $('.current.tasks input.tasks-list-cb').length;
        checkedBoxes = $('.current.tasks input.tasks-list-cb:checked').length;
        checkBoxValue = (checkedBoxes / totalCheckBoxes) * 100;

        $('.current.tasks input.tasks-list-cb').attr('value', checkBoxValue);

        if (checkBoxValue==0) {
          $('#tasks-progress-bar').css('visibility', 'hidden');
        } else {
          $('#tasks-progress-bar').css('width', checkBoxValue + '%').attr('aria-valuenow', checkBoxValue);
        }

        $('#percentage-done-number').html(checkBoxValue.toFixed());
      }
    });
  } else if(usertypeid < 512) {
    //adults/journey
    WRM$.userToDoList(function(listData) {
      var strContents = '<fieldset class="tasks-list"><legend class="sr-only">Tasks List</legend>';

      if (listData !== undefined && typeof listData == "object"){
        //jsdump(listData);
        $.each(listData.List, function(index, item){
          var dt = '';
          var label = item.Label;
          var chkVal = '';
          if (item.ShowAsIncomplete == 1) {
            //chkVal = 'Checked="false"';
          }
          else {
            chkVal = 'Checked="true"';
            if (item.Visited !== null) {
              dt = item.Visited;
              dt = dt.replace("/Date(","");
              dt = dt.replace(")/","");
              dt = WRM$.formatDateShort(new Date(Number(dt)));
              //dt = 'Last visited: ' + dt;
            }
          }
          var link = true;
          var idx = "'" + index + "'" ;
          var re = / /g;
          var lbl = label.replace(re, "_");
          if('' == 'True'){
            if(item.URL != '/plan-for-education/find-schools'){
              strContents += '<label for="label__' + lbl + '" class="tasks-list-item"><input type="checkbox" class="tasks-list-cb" id="label__' + lbl + '" onclick="javascript:toggleToDoVisited(this.checked,\'' + label + '\')" ' + chkVal + '><span class="tasks-list-mark"></span> <span class="tasks-list-desc"><a href="' + item.URL + '">' + label + '</a></span><span class="datestamp" id="dts_' + lbl + '">' + dt + '</span></label>';
            }
          }
          else{
            strContents += '<label for="label__' + lbl + '" class="tasks-list-item"><input type="checkbox" class="tasks-list-cb" id="label__' + lbl + '" onclick="javascript:toggleToDoVisited(this.checked,\'' + label + '\')" ' + chkVal + '><span class="tasks-list-mark"></span> <span class="tasks-list-desc"><a href="' + item.URL + '">' + label + '</a></span><span class="datestamp" id="dts_' + lbl + '">' + dt + '</span></label>';
          }
        });
        strContents += '</fieldset>'; 

        $('#taskList-journey').html(strContents); 

        var totalCheckBoxes = $('.current.tasks input.tasks-list-cb').length;
        checkedBoxes = $('.current.tasks input.tasks-list-cb:checked').length;
        checkBoxValue = (checkedBoxes / totalCheckBoxes) * 100;

        $('.current.tasks input.tasks-list-cb').attr('value', checkBoxValue);

        if (checkBoxValue==0) {
          $('#tasks-progress-bar').css('visibility', 'hidden');
        } else {
          $('#tasks-progress-bar').css('width', checkBoxValue + '%').attr('aria-valuenow', checkBoxValue);
        }

        $('#percentage-done-number').html(checkBoxValue.toFixed());
      }
    });
  }
}



//Mark Task Complete Or Incomplete
function toggleTaskCompletion(complete, taskID){
    var settings = jQuery.extend({}, WRM$.ajaxDefaults);
    if (complete){
        settings.url = wrmUrl('~/PostBack/_/MarkTaskComplete/_');
    } else {
        settings.url = wrmUrl('~/PostBack/_/MarkTaskIncomplete/_');
    }
    settings.data = JSON.stringify({ taskID: taskID});
    settings.success = function(dat){
        if (complete) {
            var finalDt = new Date();
            var dt = WRM$.formatDateShort(finalDt);
            $('#dts_' + taskID).html(dt);
        } else {
            $('#dts_' + taskID).html('');
        }
        var totalCheckBoxes = $('.current.tasks input.tasks-list-cb').length;
        var checkedBoxes = $('.current.tasks input.tasks-list-cb:checked').length;
        checkBoxValue = (checkedBoxes / totalCheckBoxes) * 100;

        if (checkBoxValue===0) {
            $('#tasks-progress-bar').css('visibility', 'hidden');
        } else {
            $('#tasks-progress-bar').css('visibility', 'visible');
            $('#tasks-progress-bar').css('width', checkBoxValue + '%').attr('aria-valuenow', checkBoxValue);
            $('#percentage-done-number').html(checkBoxValue.toFixed());
        }
    };
    $.ajax(settings);
}

//Mark To Do visited or not
function toggleToDoVisited(complete, label){
    var settings = jQuery.extend({}, WRM$.ajaxDefaults);
    if (complete){
        settings.url = wrmUrl('~/PostBack/_/MarkToDoComplete/_');
    } else {
        settings.url = wrmUrl('~/PostBack/_/MarkToDoIncomplete/_');
    }
    settings.data = JSON.stringify({ label: label});
    settings.success = function(dat){
        var re = / /g;
        var lbl = label.replace(re, "_");
        if (complete) {
            var finalDt = new Date();
            var dt = WRM$.formatDateShort(finalDt);
            $('#dts_' + lbl).html(dt);
        } else {
            $('#dts_' + lbl).html('');
        }
        var totalCheckBoxes = $('.current.tasks input.tasks-list-cb').length;
        var checkedBoxes = $('.current.tasks input.tasks-list-cb:checked').length;
        checkBoxValue = (checkedBoxes / totalCheckBoxes) * 100;

        if (checkBoxValue===0) {
            $('#tasks-progress-bar').css('visibility', 'hidden');
        } else {
            $('#tasks-progress-bar').css('visibility', 'visible');
            $('#tasks-progress-bar').css('width', checkBoxValue + '%').attr('aria-valuenow', checkBoxValue);
            $('#percentage-done-number').html(checkBoxValue.toFixed());
        }
    };
    $.ajax(settings);
}

function getCompletedDate() {
    var finalDt = new Date();
    var dt = WRM$.formatDateShort(finalDt);
    return dt.toString(); 
}

function doOtherStuff() {
    // Making external links in tasklist open in new tab
    $('.tasks-list-desc a').each( function() {
        if ( location.hostname === this.hostname || !this.hostname.length ) { // If local link
            // Ignore local links
        } else { // If external link
            $(this).attr("target","_blank").append('<i class="fa fa-external-link"></i><span class="sr-only">(Opens in a new window.)</span>');
        }
    });

    var totalCheckBoxes = $('.current.tasks input.tasks-list-cb').length;
    checkedBoxes = $('.current.tasks input.tasks-list-cb:checked').length;
    checkBoxValue = (checkedBoxes / totalCheckBoxes) * 100;

    $('.current.tasks input.tasks-list-cb').attr('value', checkBoxValue);

    if (checkBoxValue == 0) {
        $('#tasks-progress-bar').css('visibility', 'hidden');
    } else {
        $('#tasks-progress-bar').css('width', checkBoxValue + '%').attr('aria-valuenow', checkBoxValue);
    }

    $('#percentage-done-number').html(checkBoxValue.toFixed());
    toggleToDoVisited();
    toggleTaskCompletion();
}

//------------------------------------------------------------------------------
//NOTES PANEL	

//open the notes panel
if (wrm_userauth) { // skip if they're not logged-in
  var noteTitleFix = wrm_pagetitle == '' ? wrm_sectiontitle : wrm_pagetitle;
  $('.note-btn').on('click', function(event){
    event.preventDefault();
    $('.note-panel').addClass('is-visible');
    var s = document.getElementById('take-notes-select');

    if(s && s.options.length == 0) {
      //show different note dropdown
      $('.edit-different-note').on('click', function(event){
        $('.previous-note-select').css('display','block');
        $('.edit-different-note').hide();
        $('#take-notes-select').focus();
      });

      // bind to the change event on the dropdown 
      var isOpen = 1;
      $(s).on('blur keypress', function(e){
        if(e.type == 'keypress' && e.which == 13 && isOpen > 0){
          isOpen--;
        } else if(e.type == 'keypress' && e.which == 13 && isOpen == 0){
   	      e.preventDefault();
          isOpen++; 
        }
        if(e.type == 'blur' || (e.type == 'keypress' && e.which == 13 && isOpen > 0)){
          var id = $(this).val();
          if (id=="[NEW]"){
            $('#take-note-title').html(noteTitleFix);   
            $('#take-note-content').val(''); 
            $('#take-note-id').val(id);
          } else {
            $('#take-note-id').val(id);
          }
          WRM$.getNotes(function(dat){ 
            var dropdownTitleFix = dat.ContentTitle == 'Note Not Found' ? noteTitleFix : dat.ContentTitle; 
            var dropdownIdFix = dat.ContentID == "" ? "[NEW]" : dat.ContentID; 
            $('#take-note-title').html(dropdownTitleFix); 
            $('#take-note-content').val(dat.Content); 
            $('#take-note-id').val(dropdownIdFix);
          },'ID', id);
          $('.edit-different-note').show();      
          $('.previous-note-select').hide();      
          $('.note-saved-on').hide();
          $('#take-note-content').focus();
        }
      });

      //bind to save button click - close the notes panel on save
      $('#btn-save-note').on('click', function(event){
        var content = $('#take-note-content').val();
        var title = $('#take-note-title').html();
        var id = $('#take-note-id').val();
        var d = new Date();
        var cd = (d.getMonth() + 1) + "," + d.getDate() + "," + d.getFullYear() + "," + d.getHours() + "," + d.getMinutes();

        var settings = jQuery.extend({}, WRM$.ajaxDefaults);
        settings.url = wrmUrl('~/PostBack/_/SaveNote/_');
        settings.data = JSON.stringify({ Content: content, ID: id, Title: title, Type: wrm_page, ClientDate: cd, Language: wrm_userlang });
        settings.success = function(dat){
          $('#take-note-id').val(dat.ContentID);
          if (dat.New) {
            $('#take-notes-select option[value="[NEW]"]').val(dat.ContentID);
          }
          $('.note-saved-on').show().html(dat.ConfirmText);
        };
        $.ajax(settings);
        wrmResetSessionTimer();
      });
      // populate drop-down
      WRM$.getNotes(function(dat){ 
        WRM$.bindSelect(dat.ExistingNotes, '#take-notes-select', false, null, dat.ContentID); 
        $('#take-note-title').html(dat.ContentTitle); 
        $('#take-note-content').val(dat.Content); 
        $('#take-note-id').val(dat.ContentID);
        if (Object.keys(dat.ExistingNotes).length <= 1) {
          $('.edit-different-note').hide();      
        }
        var existingObjectKeys = Object.keys(dat.ExistingNotes); 
        var isPageInNotes = false; 
        for(var i = 0; i < existingObjectKeys.length; i++) {
          if(dat.ExistingNotes[existingObjectKeys[i]] == noteTitleFix) {
            isPageInNotes = true; 
          }
        }
        if(!isPageInNotes) {
          $("#take-notes-select").prepend("<option value='[NEW]'></option>");
        }

        if ($('#' + s.id + ' option:nth-of-type(1)').val() =="[NEW]"){
          $('#take-note-title').html(noteTitleFix)
          $('#' + s.id + ' option:nth-of-type(1)').html(noteTitleFix);
          $('#take-note-content').val(''); 
          $('#take-note-id').val('[NEW]');
        }
      });
    }
  });

  //close the notes panel
  $('.note-panel').on('click', function(event){
    if( $(event.target).is('.note-panel') || $(event.target).is('.note-panel-close, .note-panel-close > .fa-close') || $(event.target).is('#btn-save-note') ) {
      $('.note-panel').removeClass('is-visible');
      $('.take-notes-open').focus();
      event.preventDefault();
    }
  });

  $('#take-note-content').change(function(){$('.note-saved-on').hide();});
}

function getNotes(callback) {
    WRM$.getNotes(function(dat){
       callback(dat);
    });
}

  function saveNote(note) {
        var content = note.content;
        var title = note.title;
        var id = note.id;
        var d = new Date();
        var cd = (d.getMonth() + 1) + "," + d.getDate() + "," + d.getFullYear() + "," + d.getHours() + "," + d.getMinutes();

        var settings = jQuery.extend({}, WRM$.ajaxDefaults);
        settings.url = wrmUrl('~/PostBack/_/SaveNote/_');
        settings.data = JSON.stringify({ Content: content, ID: id, Title: title, Type: wrm_page, ClientDate: cd, Language: wrm_userlang });
        settings.success = function(dat){
            $('#note-saved').removeClass('is-invisible');
            $('#note-saved').addClass('is-visible');
        };
        $.ajax(settings);
        wrmResetSessionTimer();
      };
//---------------------------------------------------------------------------------------------

function assessmentBackButtonCheck() {
  WRM$.userLastPage(function(r){
    var l = r.LastPage.toLowerCase();
    if (l!='home/dashboard'&&l!='my-assessments/activation-code-needed'&&l!='take-an-assessment/default') {
      wrmGo('~/my-assessments/my-assessment-results/js'); 
    }
  });
}

/*var cropperHeader;
function changePhoto() {
  var m = document.getElementById('cropContainerModal');
  if (m) {
    $(m).modal('show');
  } else {
    //$.getScript(wrmUrl('~/Resources/HTML/ChangePhotoModal.html'));
    $.get(wrmUrl('~/Resources/HTML/ChangePhotoModal.html'), function(html) { // , {"_":$.now()}
      wrmResetSessionTimer();
      $('body').append(html);
      $('#cropContainerModal').modal('show');

      //$.getScript(wrmUrl('~/Scripts/croppic/jquery.mousewheel.min.js'));
      $.getScript(wrmUrl('~/Scripts/croppic/croppic.min.js'), function(){

        var cropperOptions = {
          uploadUrl:'/Ajax/CropPic/Save',
          cropUrl:'/Ajax/CropPic/Crop',
          imgEyecandy:false,
          doubleZoomControls:false,
          rotateControls: false,
          loaderHtml:'<div class="photo-loader"><i class="fa fa-spinner fa-pulse"></i></div>',
          loadPicture:false,
          onError: function(err){ alert(err); cropperHeader.reset(); }
        };

        cropperHeader = new Croppic('upload-photo-area',cropperOptions);
      });
    }, 'html');
  }
} */

//created by ksk - 11.17.2016
//inserts a user attribute
function InsertUserAdultAttribute(userID, username, attributeID, attributeValue, rewrite)
{
  var blnRet = false;
  var settings = jQuery.extend({}, WRM$.ajaxDefaults);
  settings.url = wrmUrl('~/PostBack/_/CreateUserAttribute/_');
  settings.data = JSON.stringify({
    attributeID: attributeID,
    attributeValue: attributeValue,
    userID: userID,
    userName: username,
    replaceExisting: rewrite
  });
  settings.success = function (dat) {
    if (dat === "OK" || dat === true) {
      blnRet = true;
      //login now
    } else {
      //eat the error and return false (don't add the attribute)     
    }
  };
  $.ajax(settings); 

  return blnRet;
}

// accepts an object from WRM$.getData and converts the response  
// from { tables : [{ columns: [arrayOfCols], rows: [array of rows] }, { columns: [arrayOfCols], rows: [array of rows] } ] }
// to   { table1 : [ { columnName, ... }, { columnName, ... } ], table2: [ ... ] }
// Example: to access a value in table 1 row 1 column 1 it would be response.table1[0].ColumnOneName
// NOTE: if there is only one table the response is just table1 in an array 
function formatWRMData(wrmResponse) {
  var tables = [];
  if (typeof (wrmResponse) === "object") {
    tables = wrmResponse.tables;
  }
  // zip function created to format data in WRM response tables 
  // returns array of objects that are { columnName : rowValue, ... } 
  var zipColumnsAndRows = function (columns, rows) {
    if (rows.length == 0 ) {
      return {}; 
    }
    // helper used to get object key from value 
    var getObjectKey = function(object, value) {
      var res = Object.keys(object).filter(function(key) {return object[key] === value})[0];
      return res;
    };
    var formatedData = [];
    for (var i = 0, row; row = rows[i++];) {
      var newRow = {};
      for (var j = 0; j < Object.keys(columns).length; j++) {
        newRow[getObjectKey(columns, j)] = row[j];
      }
      formatedData.push(newRow);
    }
    return formatedData;
  };

  if (tables?.length > 0) {
    var formatedResponse = {};
    for (var k = 0, table; table = tables[k++];) {
      formatedResponse["table" + k] = zipColumnsAndRows(table.columns, table.rows);
    }
  }
  // if only run table return an array of row objects 
  if (Object.keys(formatedResponse)?.length == 1) {
    return formatedResponse.table1;
  } else { // return array of tables for multiple tables 
    return formatedResponse;  
  }
}


$(document).ready(function() { 
  // Print Button Tooltip //
  /* $(".printTooltip").tooltip({
    title : wrm_print_msg
  }); */
  
  // Bright Outlook Tooltip //
  $(".iconKey .fa-sun-o").tooltip({
    title : "National Bright Outlook occupations are expected to grow rapidly in the next several years, will have large numbers of job openings or are new and emerging occupations."
  });

  // Green Economy Tooltip //
  $(".iconKey .fa-leaf").tooltip({
    title : "The National Green Economy will cause a change in employment demand or work and worker requirements such as tasks, skills, knowledge and credentials."
  });
});

// Detect browser and show browser specific print instructions after clicking Print Instructions in the footer.
var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "Other";
    this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
  },
  searchString: function (data) {
    for (var i = 0; i < data.length; i++) {
      var dataString = data[i].string;
      this.versionSearchString = data[i].subString;

      if (dataString.indexOf(data[i].subString) !== -1) {
        return data[i].identity;
      }
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index === -1) {
      return;
    }

    var rv = dataString.indexOf("rv:");
    if (this.versionSearchString === "Trident" && rv !== -1) {
      return parseFloat(dataString.substring(rv + 3));
    } else {
      return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    }
  },

  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Edge",
      identity: "MS Edge"
    },
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer"
    },
    {
      string: navigator.userAgent,
      subString: "Trident",
      identity: "Explorer"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {
      string: navigator.userAgent,
      subString: "Safari",
      identity: "Safari"
    },
    {
      string: navigator.userAgent,
      subString: "Opera",
      identity: "Opera"
    }
  ]

};

BrowserDetect.init();
//document.write("You are using <b>" + BrowserDetect.browser + "</b> with version <b>" + BrowserDetect.version + "</b>");

$( "#printInstructions" ).click(function(e) {
  e.preventDefault();
  if (BrowserDetect.browser === "Explorer") {
    $('#ieModal').modal('show');
  } else if (BrowserDetect.browser === "Chrome") {
    $('#chromeModal').modal('show');
  } else if (BrowserDetect.browser === "Firefox") {
    $('#ffModal').modal('show');
  } else if (BrowserDetect.browser === "Safari") {
    $('#safariModal').modal('show');
  } else if (BrowserDetect.browser === "Edge") {
    $('#edgeModal').modal('show');
  } else {
    $('#defaultPrintInstructionsModal').modal('show');
  }
});

// Add external link icon and a screen reader only span to tell user that this is opens in a new window
$(window).load(function() {
  $('#center-div a[target="_blank"]:not(.not-external-link), #center-div a[target="_new"]:not(.not-external-link), #center-div-parent a[target="_blank"]:not(.not-external-link), #center-div-parent a[target="_new"]:not(.not-external-link)').each(function () {
    if ($(this).text() == 0) {
      //$(this).append('');
    } else {
      if($(this).find("[class*=fa-external-link]").length==0){
        $(this).append('<i class="fa fa-external-link"></i><span class="sr-only">(Opens in a new window.)</span>');
      }
    }
  });
});

// Show or hide upgrade to journey link
$('#change-grade-modal').on('shown.bs.modal', function () {
  $('#gr6, #gr7, #gr8').on( "click", function() {
    $('.upgradeToJourney').hide();
  });
  $('#gr9, #gr10, #gr11, #gr12').on( "click", function() {
    $('.upgradeToJourney').show();
  });
});

"use strict";

  // $(function() {
  //   $('.preview-crop').matchHeight({ property: 'min-height' });
  // });
  var selected_avatar = '';
  var profileImage = {}; 

  profileImage.init = function() {
    this.orignal = null;
    this.cropped = null; 
  };


  function avSel(e, pic) {
    e.preventDefault();
    $('.avatar-selector').removeClass( 'active' );    
    $(pic).addClass( 'active' );
    selected_avatar = pic.id;
    profileImage.init();
    $("#saveProfileImage").removeAttr("disabled");

    // var imageURL = $('#'+selected_avatar).find('img').prop('src');
  }

  //sets the avatars provided for navigator users
  function avSet() {
    if (selected_avatar != null && selected_avatar.length != 0) { // prevent exception if selected_avatar is empty 
      $.get(wrmUrl('~/pb/' + selected_avatar + '/SetAvatar/K64~MA'), function(r){
        wrmResetSessionTimer();
        $("#UserAvatarImg").attr('src', wrmUrl(r.Link));
        $("#UserAvatarImgSm").attr('src', wrmUrl(r.Link));
        $("#UserAvatarImgProfile").attr('src', wrmUrl(r.Link));
        $("#current-profile-img").attr('src', wrmUrl(r.Link));     
        $("#current-profile-img").show();
        $("#result").hide();
        $(".MuiAvatar-img").attr("src", wrmUrl(r.Link));
      });
    }
  }

  profileImage.upload = function() {
    if (this.cropped != null) {
      var settings = $.extend({}, WRM$.ajaxDefaults); 
      settings.url = "/Ajax/Postback/UploadProfileBase64";
      settings.async = true;
      settings.data = JSON.stringify({ "ImageDataURI" : this.cropped });
      settings.success = function(data) {
        if (data.status) {
          var imageUrl = wrmUrl(data.link);
          $("#UserAvatarImg").attr("src", imageUrl);
          $("#UserAvatarImgSm").attr("src", imageUrl);
          $("#UserAvatarImgProfile").attr('src', imageUrl);
          $("#current-profile-img").attr('src', imageUrl);   
          $("#current-profile-img").show();
          $(".MuiAvatar-img").attr("src", imageUrl);
        }
      }
      $.ajax(settings); 
    }
  };

  profileImage.getRoundedCanvas = function (sourceCanvas) {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var width = sourceCanvas.width;
    var height = sourceCanvas.height;
    canvas.width = width;
    canvas.height = height;
    context.beginPath();
    context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI);
    context.strokeStyle = 'rgba(0,0,0,0)';
    context.stroke();
    context.clip();
    context.drawImage(sourceCanvas, 0, 0, width, height);
    return canvas;
  };

  $('.camera-icon').on('click', function () {
    profileImage.init(); 
   // $("#saveProfileImage").attr("disabled", "true");
   // $("#crop-button").attr("disabled", "true");
   // $("#current-profile-img").show(); 
   // $("#image").hide();
   // $("#result").hide(); 
   // $(".cropper-container").hide();
  });


  $(function () {
    $('#avatarSelect').show();
    profileImage.init(); 

    $("#saveProfileImage").attr("disabled", "true");
    $("#crop-button").attr("disabled", "true");

    $("#saveProfileImage").click(function(e) {
      e.preventDefault(); 
      avSet();
      //if(profileImage != {}){
      profileImage.upload(); 
      // }
      $('#cropperModal').modal('hide')
      $("#saveProfileImage").attr("disabled", "true");
      $("#crop-button").attr("disabled", "true");
    });

    $('#photoUploadPanelImg').click(function(e){
      $('#'+selected_avatar).removeClass('active');
      selected_avatar = '';
      $("#saveProfileImage").attr("disabled", "true");
    });
    $('#cropperModal').on('hidden.bs.modal', function (e) {
  //  $('#cancel-change-photo').click(function(e){
      $('#'+selected_avatar).removeClass('active');
      selected_avatar = '';
      profileImage.init(); 
      profileImage.getRoundedCanvas = function (sourceCanvas) {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var width = sourceCanvas.width;
        var height = sourceCanvas.height;
        canvas.width = width;
        canvas.height = height;
        context.beginPath();
        context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI);
        context.strokeStyle = 'rgba(0,0,0,0)';
        context.stroke();
        context.clip();
        context.drawImage(sourceCanvas, 0, 0, width, height);
        return canvas;
      };
      profileImage.upload = function() {
        if (this.cropped != null) {
          var settings = $.extend({}, WRM$.ajaxDefaults); 
          settings.url = "/Ajax/Postback/UploadProfileBase64";
          settings.async = true;
          settings.data = JSON.stringify({ "ImageDataURI" : this.cropped });
          settings.success = function(data) {
            if (data.status) {
              var imageUrl = wrmUrl(data.link);
              $("#UserAvatarImg").attr("src", imageUrl);
              $("#UserAvatarImgSm").attr("src", imageUrl);
              $("#UserAvatarImgProfile").attr('src', imageUrl);
              $("#current-profile-img").attr('src', imageUrl);   
              $("#current-profile-img").show();
              $(".MuiAvatar-img").attr("src", imageUrl);

             //  $("#current-profile-img").attr('src', wrmUrl(r.Link));   
            }
          }
          $.ajax(settings); 
        }
      };

      $("#saveProfileImage").attr("disabled", "true");
      $("#crop-button").attr("disabled", "true");
      $("#current-profile-img").show(); 
      $("#image").hide();
      $("#result").hide(); 
      $(".cropper-container").hide();
    });

    // Import image
    var $inputImage = $('#uploadImage');
    //$("#current-profile-img").attr('src', $inputImage);
    var URL = window.URL || window.webkitURL;
    var blobURL;

    var $image = $('#image');
    var $button = $('#crop-button');
    var $result = $('#result');
    var croppable = false;

    $image.cropper({
      aspectRatio: 1,
      viewMode: 2,
      zoomable: false,
      setDragMode: 'move',
      built: function () {
        croppable = true;
        // Hid cropping feature on the UI. This will force the click to happen and 'auto' crop the photo. 
        $button.trigger('click');
      }
    });

    $button.on('click', function () {
      var croppedCanvas;
      var roundedCanvas;
      if (!croppable) {
        return;
      }
      // Crop
      croppedCanvas = $image.cropper('getCroppedCanvas',{
        width: 400,
        height: 400
      });
      // Round
      roundedCanvas = profileImage.getRoundedCanvas(croppedCanvas);
      profileImage.cropped = roundedCanvas.toDataURL();
      // Show
      if (profileImage.cropped != null && profileImage.cropped.length > 0) {
        $result.html('<img class="cropped-result-img" src="' + profileImage.cropped + '" alt="Your profile image">');
        $("#saveProfileImage").removeAttr("disabled");
        $("#current-profile-img").hide();
        $("#image").hide();
        $(".preview-crop").show();
        $("#result").show();
        $(".cropper-container").hide();

      }
    });

    // Uploading image
    if (URL) {
      $inputImage.change(function () {
        var files = this.files;
        var file;

        if (!$image.data('cropper')) {
          return;
        }

        if (files && files.length) {
          file = files[0];
          profileImage.original = file; 

          if (/^image\/\w+$/.test(file.type)) {
            blobURL = URL.createObjectURL(file);
            $image.one('built.cropper', function () {

              // Revoke when load complete
              URL.revokeObjectURL(blobURL);
            }).cropper('reset').cropper('replace', blobURL);
            $inputImage.val('');
          } else {
            window.alert('Please choose an image file.');
          }
          $("#crop-button").removeAttr("disabled");
          $("#current-profile-img").hide();
          $("#image").show();
          $(".preview-crop-edit").show();
          $(".preview-crop").hide();
        }
      });
    } else {
      $inputImage.prop('disabled', true).parent().addClass('disabled');
    }
  });






//===============================================//
//============= Outage Notification =============//
// Description: Displaying a notification when
//				scheduled maintenance is set to 
//				occur withing 48 hours.
// Author: Alen S / Kuder Inc
var getOutageData = formatWRMData(WRM$.getData('K03~JX1STVC7WS4NKhl398mOBKui_HipI7h1HNFY8bqXijqq-gOOP1FnpY6gtkQyOnvhQJjXTXvXcTPtH4GCwJtb0udytg6ZtQnZEQdzR4FvZLttR6Q75nzo3Me2gZHu3yAUnloUKeSFgg_C4k2rDo5PIowq8NkFriYWYZRhkswkMLTgty9MzPFunFeYlSlDoMH8', {'@Culture':'en-US'}));

var outageInfo 	   = getOutageData[0];
var firstTimeLogin = ('True' == 'True');
var showOutageMsg  = (outageInfo.IsUnderMaintenance == "True");


function displayOutageNotification() {
  if(sessionStorage.getItem("notified")!=="yes"){
    //Build out needed variables
    var duration	  = parseInt(outageInfo.DurationHours);
    var hours;
    if ( duration > 1 ) {
      hours = 'hours'
    } else {
      hours = 'hour'
    };
    var date 	      = new Date(outageInfo.EndDate + " UTC");
    //Getting end date minuse duration hours
    date.setHours(date.getHours() - duration);
    //Building out notify variables
    var dateOptions = {day: 'numeric', weekday: 'long', month: 'long', year: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'short'};
    var lang 		  = 'en-US';
    //var startDate   = sDate.toLocaleDateString(lang, dateOptions);
    
    //This might seem confusing but we use the end date because we subtract duration from the end date not the start date.
    var endDate     = date.toLocaleDateString(lang, dateOptions);
    //Display notification
    BASE_Notify.outage(
      "Monthly Scheduled Maintenance<br>" + endDate, 
      "A planned outage for system maintenance is scheduled and is expected to last less than {duration} {hours}. During this outage period the system may be unavailable.".replace("{duration}", duration).replace("{hours}", hours)
    ); 
    sessionStorage.setItem("notified", "yes");
  }
}

if ((!firstTimeLogin) && showOutageMsg) {
  displayOutageNotification();
}

$('#firstTimeLoginModal').on('hidden.bs.modal', function(e) {
  if (firstTimeLogin && showOutageMsg) {
    displayOutageNotification();
  }
});


//this is a test comment// 

/////////////////////////////////////////////////
// === Handle avatar modal swap
$(document).on('click', '#choose-avatar-btn', function(){
  $('#avatarImages').show().addClass('in active');
  $('#photoUploadPanel').removeClass('in active').hide();
});
$(document).on('click', '#upload-photo-btn', function(){
  $('#photoUploadPanel').show().addClass('in active');
  $('#avatarImages').removeClass('in active').hide();
  setTimeout(function(){
    $('.upload-button').focus();
  }, 200);
});

/////////////////////////////////////////////////
// === Focus on upload when modal shows
$(document).on('click', '.btn-link', function(){
  setTimeout(function(){
    $('.upload-button').focus();
  }, 500);
});

// Trap focus in CropperModal
$(document).ready(function(){
  var firstAnchor = $(".upload-button");
  var lastAnchor = $('#cancel-change-photo');
  
  $('#crop-button').click(function(){
    lastAnchor = $('#saveProfileImage');
  });
  $('#upload-photo-btn').click(function(){
    firstAnchor = $(".upload-button");
  });
  $('#choose-avatar-btn').click(function(){
    firstAnchor = $("#BoyAvatar1");
    setTimeout(function(){
      $(".avatar-selector").first().focus();
    }, 200);
  });
  $('.avatar-selector').click(function(){
    lastAnchor = $('#saveProfileImage');
  });
  
  $(document).on('keydown', function(e){
    let isTabPressed = e.key === 'Tab' || e.keyCode == 9;
    if (!isTabPressed) {
      return;
    }
    if(e.shiftKey){
      if(firstAnchor.is(":focus")){
        lastAnchor.focus();
        e.preventDefault();
      }
    }else{
      if(lastAnchor.is(":focus")){
        firstAnchor.focus();
        e.preventDefault();
      }
    }
  });
  firstAnchor.focus();
});


//////////////////////////////////////////////////
// === Note Taker
$('#edit-different-note').click(function(e){
  e.preventDefault();
  $(this).hide();
  $('#take-notes-select').show();
  $('#take-notes-select').focus();
});

$('.take-notes-open').click(function(){
  setTimeout(function(){
  	$(".note-panel-close").focus();
  }, 200);
  
  var firstAnchor = $('.note-panel-close');
  var lastAnchor = $('#btn-save-note');

  $(document).on('keydown', function(e){
    let isTabPressed = e.key === 'Tab' || e.keyCode == 9;
    if (!isTabPressed) {
      return;
    }
    if(e.shiftKey){
      if(firstAnchor.is(":focus")){
        lastAnchor.focus();
        e.preventDefault();
      }
    }else{
      if(lastAnchor.is(":focus")){
        firstAnchor.focus();
        e.preventDefault();
      }
    }
  });
});


///////////////////////////////////////////////////
// === Task list
$(document).on('focus', '.tasks-list-cb', function(){
  $(this).siblings('.tasks-list-mark').css('border-color','#339966');
});
$(document).on('focusout', '.tasks-list-cb', function(){
  $(this).siblings('.tasks-list-mark').css('border-color','#dddddd');
});
setTimeout(function(){
  $('.tasks-list-cb').each(function() {
    if($(this).attr('checked')){
      $(this).siblings('.tasks-list-desc').find('.is-completed').text(' This step was completed ');
    }
  });
}, 2000);
$(document).on('change', '.tasks-list-cb', function(){
  if($(this).is(':checked')){
    $(this).siblings('.tasks-list-desc').find('.is-completed').text(' This step was completed ');
  }else{
    $(this).siblings('.tasks-list-desc').find('.is-completed').text(' This step is not completed ');
  }
})

/* $('button.nav-toggle').click(function () {
	console.log("Clicked: ", $('.sidebar-offcanvas').css('display'));
  let displayType = $('.sidebar-offcanvas').css('display') === 'none' ? 'table-cell' : 'none';
  $('.sidebar-offcanvas').css('display', displayType);
}); */
//===============================================//