Snippets Collections
export const scrollTo = (distance) => {
    window.scrollTo({
        top: distance,
        behavior: 'smooth'
    })
}

export const scrollToTop = () => scrollTo(0)
    var externalDataRetrievedFromServer = [
    { name: 'Bartek', age: 34 },
    { name: 'John', age: 27 },
    { name: 'Elizabeth', age: 30 },
];

function buildTableBody(data, columns) {
    var body = [];

    body.push(columns);

    data.forEach(function(row) {
        var dataRow = [];

        columns.forEach(function(column) {
            dataRow.push(row[column].toString());
        })

        body.push(dataRow);
    });

    return body;
}

function table(data, columns) {
    return {
        table: {
            headerRows: 1,
            body: buildTableBody(data, columns)
        }
    };
}

var dd = {
    content: [
        { text: 'Dynamic parts', style: 'header' },
        table(externalDataRetrievedFromServer, ['name', 'age'])
    ]
}
// Basic Clickable on Whole Column with Target Blank
				if(SDB.App.exists('.tg-clickable')){
					$(document).on('click', 'body:not(.fl-builder-edit) .tg-clickable > .fl-col-content', function(event) { 
                        var link = $(this).find("a").attr("href"); 
                        window.open(link,'_blank');
                        return false;
                    });
				}
(function ($) {
    if (!window.SDB) {
        SDB = {};
    }
    /*
     * Application Init, everything starts here
     *
     */
    SDB.App = function() {
        return {
            exists: function(x) {
                if ($(x).length > 0) { return true; }
            },
            init: function() {
              	// Basic Clickable on Whole Column with Target Blank
				if(SDB.App.exists('.tg-clickable')){
					$(document).on('click', 'body:not(.fl-builder-edit) .tg-clickable > .fl-col-content', function(event) { 
                        var link = $(this).find("a").attr("href"); 
                        window.open(link,'_blank');
                        return false;
                    });
				}
              	// Start New Function from here
              	
            } // CLOSE INIT FUNCTION
        };
    }();
  

    $(function() {
        SDB.App.init();
      
    });
}(jQuery));
// set up
let start = moment("2018-05-16 12:00:00"); // some random moment in time (in ms)
let end = moment("2018-05-16 12:22:00"); // some random moment after start (in ms)
let diff = end.diff(start);

// execution
let f = moment.utc(diff).format("HH:mm:ss.SSS");
alert(f);
<style> .wf-force-outline-none[tabindex="-1"]:focus{outline:none;} </style>


<style>

[data-option-label="color-name-link"] {
background-image: url("image-color-name"); // you get those field from a cms colors collections / put as many data option label field as maximum colors swatch you would like to have
}
[data-option-label="{{wf {&quot;path&quot;:&quot;color-2:name&quot;,&quot;type&quot;:&quot;PlainText&quot;\} }}"] {
background-image: url("{{wf {&quot;path&quot;:&quot;color-2:colors-link&quot;,&quot;type&quot;:&quot;Link&quot;\} }}");
}
[data-option-label="{{wf {&quot;path&quot;:&quot;color-3:name&quot;,&quot;type&quot;:&quot;PlainText&quot;\} }}"] {
background-image: url("{{wf {&quot;path&quot;:&quot;color-3:colors-link&quot;,&quot;type&quot;:&quot;Link&quot;\} }}");
}
[data-option-label="{{wf {&quot;path&quot;:&quot;color-4:name&quot;,&quot;type&quot;:&quot;PlainText&quot;\} }}"] {
background-image: url("{{wf {&quot;path&quot;:&quot;color-4:colors-link&quot;,&quot;type&quot;:&quot;Link&quot;\} }}");
}
[data-option-label="{{wf {&quot;path&quot;:&quot;color-5:name&quot;,&quot;type&quot;:&quot;PlainText&quot;\} }}"] {
background-image: url("{{wf {&quot;path&quot;:&quot;color-5:colors-link&quot;,&quot;type&quot;:&quot;Link&quot;\} }}");
}
ֿ/*/ ((--=.lw-commerce-commerceaddtocartoptionpill.w--ecommerce-pill-selected {
   kjborder: 3px solid  #ffb700;))--
}
/*/
video::-webkit-media-controls-panel {
display: none !important;
opacity: 1 !important;}

</style>

<style>
.color-buttons:focus {
outline: none;
}
.color-buttons{
box-shadow: 0 0 0 1px #1f2d1c;
border: 2.5px solid #faf5f2;
}

.color-buttons:active {
box-shadow: 0 0 0 1px #bababa;
}
.color-buttons:hover {
box-shadow: 0 0 0 1px #bababa;
}

body {
 overflow-x: hidden !important;
  position: relative !important;
  width:100% !important;
  }
  

</style>

<!-- No Highlight Tabs  -->
<style>                                  
.arrow {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */                                  
</style> 

<script>
document.querySelectorAll('[data-node-type="commerce-add-to-cart-pill"]').forEach(el => el.dataset['optionLabel'] = el.textContent)
</script>

<script>
  var FC = FC || {};
 
  FC.onLoad = function () {
    FC.client.on("ready.done", function () {
      document
        .querySelector(".w-commerce-commerceaddtocartbutton")
        .addEventListener("click", (e) => {
          e.preventDefault();
 
          const name = document.querySelector(".foxy-product-name").innerText;
          const price = document.querySelector(".foxy-product-price").innerText;
          const code = document.querySelector(".foxy-product-code").innerText;
          const image = document.querySelector(".foxy-product-image").src;
 
          const quantity = document.querySelector(".w-commerce-commerceaddtocartquantityinput").value;
 
          let cartUrl = `https://${FC.settings.storedomain}/cart?name=${encodeURIComponent(name)}&price=${price}&code=${code ?? encodeURIComponent(code)}&quantity=${quantity ?? 1}&image=${encodeURIComponent(image)}`;
 
          const variantSelect = document.querySelectorAll("[data-node-type='commerce-add-to-cart-option-select']");
 
          const variantName = Array.from(variantSelect).map((select) =>
            encodeURIComponent(select.previousElementSibling.innerText)
          );
 
          const variantValueName = Array.from(variantSelect).map((select) =>
            encodeURIComponent(select.options[select.selectedIndex].text)
          );
 
          const variantValue = Array.from(variantSelect).map((select) =>
            encodeURIComponent(select.value)
          );
 
          if (variantSelect.length > 0 && variantValue.includes("")) {
            return;
          } else {
            variantName.forEach(
              (name, index) => (cartUrl += `&${name}=${variantValueName[index]}`)
            );
 
            FC.client.event("cart-submit").trigger({
              data: { cart: "add" },
              url: cartUrl,
            });
          }
        });
    });
  };
</script>
$('.slider-nav').slick({
  slidesToShow: 4,
  slidesToScroll: 1,
  asNavFor: '.slider-for',
  dots: false,
  vertical: true,
  verticalSwiping:true,
  arrows: true,
  focusOnSelect: true,
  responsive: [
    {
      breakpoint: 767,
      settings: "unslick"
    }
  ]
});
int x = character - '0';  // The (int) cast is not necessary.
<script>
$(function() {
    var observer = new MutationObserver(function (mutations) {
        for(let mutation of mutations) {
            setTimeout(function() {
                if(mutation.oldValue || mutation.target.getAttribute('aria-hidden') != 'true')
                    return;
                let player = $(mutation.target).find('iframe').get(0);
                player.src += '';
            }, 500);
        }
    });
    $('.slide.w-slide').each(function () {
        observer.observe(this, {
            attributes: true,
            attributeFilter: ['aria-hidden'],
            attributeOldValue : true
        });
    })
});
</script>
dataLayer.push({'event': 'lastscr'});console.log(dataLayer)
<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('*');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            anchor.onclick = function() {
                code = this.getAttribute('whenClicked');
                eval(code);   
            }
        }
    }
</script>
JS

favMovies.forEach(function(favMovie) {
  console.log('I really like the movie', favMovie)
})
JavaScript

for (let i=0; i < arrayName.length; i++){
  console.log(arrayName[i])
}

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles'];

for (let i=0; i < movies.length; i++){
  console.log(movies[i])
}

Python

for singular_array_name in array_name_pluralized:
	print(singular_array_name)

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles']

for movie in movies:
	print(movie)
module.exports = {
  reactStrictMode: true,

  //global title
  env: {
    appName: 'yusup.com',
  },
  
  //Route
  async rewrites() { 
    return [
      {
        source: '/login', //link
        destination: '/auth/login', //Lokasi File
      },
      {
        source: '/register',
        destination: '/auth/register',
      }
    ]
  }
}

//Pemakaian global title
<Layout title={process.env.appName}> //Tanpa di import
  <div></div>
</Layout
import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head>
          <meta property="example" content="example.com" />
        </Head>
        <body className="font-sans">
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
//Base
File:component/Layout
import Head from "next/head";

function Layout(props) {
  return (
    <>
      <Head>
        <title>{props.title}</title>
    	<link rel="icon" href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqDf8kObAr4H1Eq4AowjBo3lb0IblH0hflxY5Fy5NFO6jEB2N1vMhDbtnyzivnuSbaLSM&usqp=CAU"></link>
      </Head>
      {props.children}
    </>
  );
}

export default Layout;

//Pemakaian
File:page/index.js

<Layout title="Home"> //props variabel title
  
  //children
    <div className="container mx-auto mt-8"> 
      <h1 className="font-bold">Hello Word!</h1>
    </div>
 //endChildren

</Layout>
/* Added for B2C login links */
$("#samlSignInLink,#samlSignInLinkPopUp,#samlSignInLinkHomepage").off('click', function (e) {
	  
});



$("#samlSignInLink,#samlSignInLinkPopUp,#samlSignInLinkHomepage").on('click', function (e) {
	var redirectUrl;
	var currentPath = document.location.pathname == '/error' ? '' : document.location.pathname;
	var queryString = window.location.search;
	if(queryString) {
		redirectUrl = document.location.origin + "/samlsinglesignon/saml" + currentPath + queryString +"&"
	} else {
		redirectUrl = document.location.origin + "/samlsinglesignon/saml" + currentPath + "?"
	}
	if ($('#isDeviceApp').val() == 'true') {
		redirectUrl =redirectUrl + "idp=B2C_1A_signup_signin_SAML_APP_KMSI"
	} else if ($('#isMobileBrowser').val() == 'true') {
		redirectUrl = redirectUrl + "idp=B2C_1A_signup_signin_SAML_MOBILE"
	} else {
		redirectUrl = redirectUrl + "idp=B2C_1A_signup_signin_SAML"
	}
	

	if(window.parent.location.href.indexOf('smartedit') >= 0){
		localStorage.setItem("SE_login", true);
		console.log("set SE_login TRUE")
		window.open(redirectUrl, '_blank');
	}else{
		window.location.href = redirectUrl;
	}

});


if(localStorage.getItem("SE_login") != null && JSON.parse(localStorage.getItem("SE_login")) == true){
	localStorage.setItem("SE_login", false);
	console.log("set SE_login FALSE")

	window.opener.location.reload();
	window.close();
}
toFixed isn't a method of non-numeric variable types. In other words, Low and High can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.

var Low  = parseFloat($SliderValFrom.val()),
    High = parseFloat($SliderValTo.val());
// toFixed only exists on numbers. 
// Trying to use it on another data type like strings will not work
// Example

let num = 1.23456;
num.toFixed(2); // 1.23

num = String(num);
num.toFixed(2); // Uncaught TypeError: num.toFixed is not a function

// Solutions
// Convert your string to a number by:
//  - prepending it with a +
//		e.g. (+num).toFixed(2);
//	- using parseInt
//		e.g. parseInt(num).toFixed(2)
//	- using Number
//		e.g. Number(num).toFixed(2)
            setInterval(function() {
                  window.location.reload();
                }, 300000); 
function join(t, a, s) {
   function format(m) {
      let f = new Intl.DateTimeFormat('en', m);
      return f.format(t);
   }
   return a.map(format).join(s);
}

let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(new Date, a, '-');
console.log(s);
{ // example 1
   let f = new Intl.DateTimeFormat('en');
   let a = f.formatToParts();
   console.log(a);
}
{ // example 2
   let f = new Intl.DateTimeFormat('hi');
   let a = f.formatToParts();
   console.log(a);
}
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
// Override Settings
var boostPFSFilterConfig = {
  general: {
    limit: boostPFSConfig.custom.products_per_page,
    // Optional
    loadProductFirst: false,
  },
}

// Declare Templates
var boostPFSTemplate = {
  saleLabelHtml:
    '<div class="sale_banner">' + boostPFSConfig.label.sale + "</div>",
  newLabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.newlabel + "</div>",
  partyLabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.partylabel + "</div>",
  duurzaamLabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.duurzaamlabel + "</div>",
  giftLabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.giftlabel + "</div>",
  comingLabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.cominglabel + "</div>",
  label1LabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.label1 + "</div>",
  label2LabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.label2 + "</div>",
  label3LabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.label3 + "</div>",
  preorderLabelHtml:
    '<div class="new_banner">' + boostPFSConfig.label.preorder + "</div>",
  reviewHtml:
    '<span class="shopify-product-reviews-badge" data-id="{{itemId}}"></span>',
  vendorHtml:
    '<div class="vendor"><span itemprop="brand">{{itemVendorLabel}}</span></div>',
  quickViewBtnHtml:
    '<span data-fancybox-href="#product-{{itemId}}" class="quick_shop ss-icon" data-gallery="product-{{itemId}}-gallery"><span class="icon-plus">Quick view</span></span>',
  newRowHtml: '<br class="clear product_clear" />',

  // Grid Template
  productGridItemHtml:
    '<div data-boost-pfs-theme-quickview="{{itemId}}" data-product-id="{{itemId}}" class="{{itemColumnNumberClass}} {{itemCollectionGroupThumbClass}} thumbnail {{itemCollectionGroupMobileClass}}" data-product-id="{{itemId}}" itemprop="itemListElement" itemscope itemtype="http://schema.org/Product">' +
    `<div class="ssw-faveiticon sswfaveicon{{itemId}}">
				<i data-product-id="{{itemId}}" data-count="0" class="ssw-icon-heart-o ssw-fave-icon ssw-wishlist-element ssw-not-synch"
					title="{{ 'socialshopwave.fave' | t }}"
					data-params='{"product_id":"{{itemId}}","event":"fave_button","page":"product_profile"}'></i>
				<span class="faves-count">...</span>
			</div>` +
    '<a href="{{itemUrl}}" itemprop="url">' +
    '<div class="relative product_image">' +
    "{{itemSaleLabel}}" +
    "{{discountPercentageLabel}}" +
    '<div class="product_container swap-' +
    boostPFSConfig.custom.collection_secondary_image +
    '">' +
    "{{itemImages}}" +
    "</div>" +
    "</div>" +
    '<div class="info">' +
    '<span class="title" itemprop="name">{{itemTitle}}</span>' +
    "{{itemVendor}}" +
    "{{itemReview}}" +
    "{{itemPrice}}" +
    "</div>" +
    '<div class="banner_holder">' +

    "{{itemNewLabel}}" +
    "{{itemPartyLabel}}" +
    "{{itemDuurzaamLabel}}" +
    "{{itemGiftLabel}}" +
    "{{itemComingLabel}}" +
    "{{itemLabel1Label}}" +
    "{{itemLabel2Label}}" +
    "{{itemLabel3Label}}" +
    "{{itemPreorderLabel}}" +
    "</div>" +
    "</a>" +
    "{{itemSwatches}}" +
    "</div>" +
    "{{itemNewRow}}",

  // Pagination Template
  previousHtml:
    '<span class="prev"><a href="{{itemUrl}}">« ' +
    boostPFSConfig.label.paginate_prev +
    "</a></span>",
  nextHtml:
    '<span class="next"><a href="{{itemUrl}}">' +
    boostPFSConfig.label.paginate_next +
    " »</a></span>",
  pageItemHtml:
    '<span class="page"><a href="{{itemUrl}}">{{itemTitle}}</a></span>',
  pageItemSelectedHtml: '<span class="page current">{{itemTitle}}</span>',
  pageItemRemainHtml: "<span>{{itemTitle}}</span>",
  paginateHtml: "{{previous}}{{pageItems}}{{next}}",

  // Sorting Template
  sortingHtml:
    '<select id="sort-by" class="boost-pfs-filter-top-sorting-select" data-default-sort="' +
    boostPFSConfig.general.default_sort_by +
    '">{{sortingItems}}</select>',
}

;(function () {
  BoostPFS.inject(this)

  // This seems to fix the loading issue of the button on iPhone 11. Utils seems to get overwritten somehow which makes some functions of Utils undefined === errors
  let _utils = Utils

  // Build Product Grid Item
  ProductGridItem.prototype.compileTemplate = function (data, index) {
    if (!data) data = this.data
    if (!index) index = this.index + 1

    /*** Prepare data ***/
    var images = data.images_info
    // Displaying price base on the policy of Shopify, have to multiple by 100
    var soldOut = !data.available // Check a product is out of stock
    var onSale = data.compare_at_price_min > data.price_min // Check a product is on sale
    var priceVaries = data.price_min != data.price_max // Check a product has many prices
    // Get First Variant (selected_or_first_available_variant)
    var firstVariant = data["variants"][0]
    if (_utils.getParam) {
      if (
        _utils.getParam("variant") !== null &&
        _utils.getParam("variant") != ""
      ) {
        var paramVariant = data.variants.filter(function (e) {
          return e.id == _utils.getParam("variant")
        })
        if (typeof paramVariant[0] !== "undefined")
          firstVariant = paramVariant[0]
      } else {
        for (var i = 0; i < data["variants"].length; i++) {
          if (data["variants"][i].available) {
            firstVariant = data["variants"][i]
            break
          }
        }
      }
    }

    /*** End Prepare data ***/

    var itemHtml = boostPFSTemplate.productGridItemHtml

    var onSaleClass = onSale ? "sale" : ""
    var soldOutClass = soldOut ? "out_of_stock" : "in_stock"

    var itemColumnNumberClass = ""
    var itemCollectionGroupThumbClass = buildItemCollectionGroupThumbClass(
      index,
      boostPFSConfig.custom.products_per_row
    )
    var itemCollectionGroupMobileClass = (index - 1) % 2 == 0 ? "even" : "odd"
    switch (boostPFSConfig.custom.products_per_row) {
      case 2:
        itemColumnNumberClass = boostPFSConfig.custom.show_sidebar
          ? "six columns"
          : "eight columns"
        break
      case 3:
        itemColumnNumberClass = boostPFSConfig.custom.show_sidebar
          ? "four columns"
          : "one-third column"
        break
      default:
        itemColumnNumberClass = boostPFSConfig.custom.show_sidebar
          ? "three columns"
          : "four columns"
        break
    }
    itemHtml = itemHtml.replace(
      /{{itemColumnNumberClass}}/g,
      itemColumnNumberClass
    )
    itemHtml = itemHtml.replace(
      /{{itemCollectionGroupThumbClass}}/g,
      itemCollectionGroupThumbClass
    )
    itemHtml = itemHtml.replace(
      /{{itemCollectionGroupMobileClass}}/g,
      itemCollectionGroupMobileClass
    )

    // Get image source
    var imageSrc =
      'data-src="' + _utils.getFeaturedImage(images, "2048x") + '" '
    imageSrc +=
      'data-srcset=" ' + _utils.getFeaturedImage(images, "2048x") + " 2048w,"
    imageSrc += _utils.getFeaturedImage(images, "1600x") + " 1600w,"
    imageSrc += _utils.getFeaturedImage(images, "1200x") + " 1200w,"
    imageSrc += _utils.getFeaturedImage(images, "1000x") + " 1000w,"
    imageSrc += _utils.getFeaturedImage(images, "800x") + " 800w,"
    imageSrc += _utils.getFeaturedImage(images, "600x") + " 600w,"
    imageSrc += _utils.getFeaturedImage(images, "400x") + ' 400w"'
    // Get Thumbnail url
    var thumbUrl = _utils.getFeaturedImage(images, "100x")
    // Get Flip image url
    var itemFlipImageUrl =
      images.length > 1
        ? _utils.optimizeImage(images[images.length - 1]["src"], "900x")
        : _utils.getFeaturedImage(images, "900x")

    // Add Thumbnail
    if (data.images_info.length > 0) {
      var product_set_width = data.images_info[0].width
    } else {
      var product_set_width = "900"
    }
    var align_height_value = ""
    if (boostPFSConfig.custom.align_height) {
      if (images.length > 0) {
        var collection_height = boostPFSConfig.custom.collection_height
        var product_aspect_ratio = images[0]["width"] / images[0]["height"]
        product_set_width = product_aspect_ratio * collection_height
        if (images[0]["width"] >= images[0]["height"]) {
          var align_height_value = "width: 100%; height: auto;"
        } else {
          var align_height_value = "width: 100%;"
        }
      }
    }
    var itemImagesHtml =
      '<div class="image__container" style="max-width: ' +
      product_set_width +
      'px;">'
    itemImagesHtml +=
      '<img  src="' +
      thumbUrl +
      '"' +
      'alt="{{itemTitle}}" ' +
      'class="lazyload lazyload--fade-in" ' +
      'style="' +
      align_height_value +
      " max-width: " +
      product_set_width +
      'px;" ' +
      'data-sizes="auto" ' +
      imageSrc +
      "/>"
    // Add Flip image
    if (boostPFSConfig.custom.collection_secondary_image) {
      itemImagesHtml += '<div class="image__container" style="max-width: '
      if (images.length > 1) {
        itemImagesHtml += images[1]["width"] + "px"
      } else {
        itemImagesHtml += product_set_width + "px"
      }
      itemImagesHtml += '">'
      itemImagesHtml +=
        '<img src="' +
        itemFlipImageUrl +
        '" class="secondary lazyload" alt="{{itemTitle}}" />'
      itemImagesHtml += "</div>"
    }
    itemImagesHtml += boostPFSConfig.custom.quick_shop_enable
      ? "{{itemQuickViewBtn}}"
      : ""
    itemImagesHtml += "</div>"
    itemHtml = itemHtml.replace(/{{itemImages}}/g, itemImagesHtml)

    // Add Labels
    // Sold Out label
    var itemSoldOutLabel = soldOut ? boostPFSTemplate.soldOutLabelHtml : ""
    itemHtml = itemHtml.replace(/{{itemSoldOutLabel}}/g, itemSoldOutLabel)
    // Sale label
    var itemSaleLabel =
      boostPFSConfig.custom.sale_banner_enabled && onSale
        ? boostPFSTemplate.saleLabelHtml
        : ""
    itemHtml = itemHtml.replace(/{{itemSaleLabel}}/g, itemSaleLabel)

    // Discount percentage label
    var discountPercentageLabel = data.percent_sale_min > 0 || data.tags.includes('hide-discount') ? '<span class="discount-label">' + Math.round(data.percent_sale_min / 5) * 5 + '%</span>' : ''

    itemHtml = itemHtml.replace(/{{discountPercentageLabel}}/g, discountPercentageLabel)

    // New, Coming soon, Pre order label
    var itemNewLabelHtml = "",
        itemPartyLabelHtml = "",
        itemDuurzaamLabelHtml = "",
        itemGiftLabelHtml = "",
        itemComingLabelHtml = "",
        itemLabel1LabelHtml = "",
        itemLabel2LabelHtml = "",
        itemLabel3LabelHtml= "",
        itemPreorderLabelHtml = "";
    if (data.collections) {
      itemNewLabelHtml = data.tags.includes("newlabel") ? boostPFSTemplate.newLabelHtml : ""
      itemPartyLabelHtml = data.tags.includes("partylabel") ? boostPFSTemplate.partyLabelHtml : ""
      itemDuurzaamLabelHtml = data.tags.includes("duurzaamlabel") ? boostPFSTemplate.duurzaamLabelHtml : ""
      itemGiftLabelHtml = data.tags.includes("giftlabel") ? boostPFSTemplate.giftLabelHtml : ""
      itemComingLabelHtml = data.tags.includes("cominglabel") ? boostPFSTemplate.comingLabelHtml : ""
      itemLabel1LabelHtml = data.tags.includes("label1") ? boostPFSTemplate.Label1LabelHtml : ""
      itemLabel2LabelHtml = data.tags.includes("label2") ? boostPFSTemplate.Label2LabelHtml : ""
      itemLabel3LabelHtml = data.tags.includes("label3") ? boostPFSTemplate.Label3LabelHtml : ""
      itemPreorderLabelHtml = data.tags.includes("pre_order") ? boostPFSTemplate.preorderLabelHtml : ""
    }
    itemHtml = itemHtml.replace(/{{itemNewLabel}}/g, itemNewLabelHtml)
    itemHtml = itemHtml.replace(/{{itemPartyLabel}}/g, itemPartyLabelHtml)
    itemHtml = itemHtml.replace(/{{itemDuurzaamLabel}}/g, itemDuurzaamLabelHtml)
    itemHtml = itemHtml.replace(/{{itemGiftLabel}}/g, itemGiftLabelHtml)
    itemHtml = itemHtml.replace(/{{itemComingLabel}}/g, itemComingLabelHtml)
    itemHtml = itemHtml.replace(/{{itemLabel1Label}}/g, itemLabel1LabelHtml)
    itemHtml = itemHtml.replace(/{{itemLabel2Label}}/g, itemLabel2LabelHtml)
    itemHtml = itemHtml.replace(/{{itemLabel3Label}}/g, itemLabel3LabelHtml)
    itemHtml = itemHtml.replace(/{{itemPreorderLabel}}/g, itemPreorderLabelHtml)

    // Add Quick view button
    var itemQuickViewBtnHtml = boostPFSConfig.custom.quick_shop_enable
      ? boostPFSTemplate.quickViewBtnHtml
      : ""
    itemHtml = itemHtml.replace(/{{itemQuickViewBtn}}/g, itemQuickViewBtnHtml)

    // Add Review badge
    var itemReviewHtml = boostPFSConfig.custom.review_enable
      ? boostPFSTemplate.reviewHtml
      : ""
    itemHtml = itemHtml.replace(/{{itemReview}}/g, itemReviewHtml)

    // Add Vendor
    var itemVendorHtml = boostPFSConfig.custom.vendor_enable
      ? boostPFSTemplate.vendorHtml
      : ""
    itemHtml = itemHtml.replace(/{{itemVendor}}/g, itemVendorHtml)

    // Add Price
    var itemPriceHtml = ""
    itemPriceHtml +=
      '<span class="price ' +
      onSaleClass +
      '" itemprop="offers" itemscope itemtype="http://schema.org/Offer">'
    itemPriceHtml +=
      '<meta itemprop="price" content="' +
      _utils.stripHtml(_utils.formatMoney(data.price_min)) +
      '" />'
    itemPriceHtml +=
      '<meta itemprop="priceCurrency" content="' +
      boostPFSConfig.shop.currency +
      '" />'
    itemPriceHtml +=
      '<meta itemprop="seller" content="' + boostPFSConfig.shop.name + '" />'
    itemPriceHtml +=
      '<meta itemprop="availability" content="' + soldOutClass + '" />'
    itemPriceHtml += '<meta itemprop="itemCondition" content="New" />'
    if (!soldOut) {
      if (priceVaries && data.price_min > 0) {
        itemPriceHtml +=
          "<small><em>" + boostPFSConfig.label.from_price + "</em></small> "
      }
      if (data.price_min > 0) {
        itemPriceHtml +=
          '<span class="money">' +
          _utils.formatMoney(data.price_min) +
          "</span>"
      } else {
        itemPriceHtml += boostPFSConfig.label.free_price
      }
    } else {
      itemPriceHtml +=
        '<span class="sold_out">' + boostPFSConfig.label.sold_out + "</span>"
    }
    if (onSale) {
      itemPriceHtml +=
        ' <span class="was_price"><span class="money">' +
        _utils.formatMoney(data.compare_at_price_max) +
        "</span></span>"
    }
    itemPriceHtml += "</span>"
    itemHtml = itemHtml.replace(/{{itemPrice}}/g, itemPriceHtml)

    // Add Color swatches
    var itemSwatchHtml = ""
    if (boostPFSConfig.custom.collection_swatches) {
      for (var k in data.options) {
        if (
          data["options"][k].indexOf("color") > -1 ||
          data["options"][k].indexOf("couleur") > -1
        ) {
          var selectedOption = data["options"][k]
          var values = []
          itemSwatchHtml += '<div class="collection_swatches">'
          for (var i = 0; i < data["variants"].length; i++) {
            var value = data["variants"][i]["option_" + selectedOption]
            if (values.indexOf(value) == -1) {
              values = values.join(",")
              values += "," + value
              values = values.split(",")
              var variantImage = boostPFSConfig.general.no_image_url
              var temp = data.options_with_values.filter(function (e) {
                return e.name == selectedOption
              })
              if (typeof temp[0] !== "undefined") {
                var optionValues = temp[0]["values"].filter(function (e) {
                  return e.title == value
                })
                if (typeof optionValues[0] !== "undefined") {
                  var imageIndex = optionValues[0]["image"]
                  if (typeof data["images"][imageIndex] !== "undefined") {
                    variantImage = data["images"][imageIndex]["src"]
                  }
                }
              }
              if (variantImage !== "") {
                itemSwatchHtml +=
                  '<a href="' +
                  _utils.buildProductItemUrl(data) +
                  "?variant=" +
                  data["variants"][i]["id"] +
                  '" class="swatch">'
                itemSwatchHtml +=
                  '<span data-image="' +
                  _utils.optimizeImage(variantImage, "1024x1024") +
                  '" style="background-color: ' +
                  value +
                  "; background-image: url(" +
                  boostPFSConfig.general.asset_url.replace(
                    "boost-pfs-filter.js",
                    value + "_50x.png"
                  ) +
                  ');"></span>'
                itemSwatchHtml += "</a>"
              }
            }
          }
          itemSwatchHtml += "</div>"
        }
      }
    }
    itemHtml = itemHtml.replace(/{{itemSwatches}}/g, itemSwatchHtml)

    // Add new row
    var itemNewRowHtml =
      index > 0 && index % boostPFSConfig.custom.products_per_row == 0
        ? boostPFSTemplate.newRowHtml
        : ""
    itemHtml = itemHtml.replace(/{{itemNewRow}}/g, itemNewRowHtml)

    // Add main attribute
    itemHtml = itemHtml.replace(/{{itemId}}/g, data.id)
    itemHtml = itemHtml.replace(/{{itemHandle}}/g, data.handle)
    itemHtml = itemHtml.replace(/{{itemTitle}}/g, data.title)
    itemHtml = itemHtml.replace(/{{itemVendorLabel}}/g, data.vendor)
    itemHtml = itemHtml.replace(
      /{{itemUrl}}/g,
      _utils.buildProductItemUrl(data)
    )

    return itemHtml
  }

  // Build advanced class
  function buildItemCollectionGroupThumbClass(index, productsPerRow) {
    var temp = index < productsPerRow ? index : index % productsPerRow
    if (temp == 0) {
      return "omega"
    } else if (temp == 1) {
      return "alpha"
    }
    return ""
  }

  // Build Pagination
  ProductPaginationDefault.prototype.compileTemplate = function (totalProduct) {
    if (!totalProduct) totalProduct = this.totalProduct

    // Get page info
    var currentPage = parseInt(Globals.queryParams.page)
    var totalPage = Math.ceil(totalProduct / Globals.queryParams.limit)

    if (
      Settings.getSettingValue("general.paginationType") == "default" &&
      totalPage > 1
    ) {
      var paginationHtml = boostPFSTemplate.paginateHtml

      // Build Previous
      var previousHtml = currentPage > 1 ? boostPFSTemplate.previousHtml : ""
      previousHtml = previousHtml.replace(
        /{{itemUrl}}/g,
        _utils.buildToolbarLink("page", currentPage, currentPage - 1)
      )
      paginationHtml = paginationHtml.replace(/{{previous}}/g, previousHtml)

      // Build Next
      var nextHtml = currentPage < totalPage ? boostPFSTemplate.nextHtml : ""
      nextHtml = nextHtml.replace(
        /{{itemUrl}}/g,
        _utils.buildToolbarLink("page", currentPage, currentPage + 1)
      )
      paginationHtml = paginationHtml.replace(/{{next}}/g, nextHtml)

      // Create page items array
      var beforeCurrentPageArr = []
      for (
        var iBefore = currentPage - 1;
        iBefore > currentPage - 3 && iBefore > 0;
        iBefore--
      ) {
        beforeCurrentPageArr.unshift(iBefore)
      }
      if (currentPage - 4 > 0) {
        beforeCurrentPageArr.unshift("...")
      }
      if (currentPage - 4 >= 0) {
        beforeCurrentPageArr.unshift(1)
      }
      beforeCurrentPageArr.push(currentPage)

      var afterCurrentPageArr = []
      for (
        var iAfter = currentPage + 1;
        iAfter < currentPage + 3 && iAfter <= totalPage;
        iAfter++
      ) {
        afterCurrentPageArr.push(iAfter)
      }
      if (currentPage + 3 < totalPage) {
        afterCurrentPageArr.push("...")
      }
      if (currentPage + 3 <= totalPage) {
        afterCurrentPageArr.push(totalPage)
      }

      // Build page items
      var pageItemsHtml = ""
      var pageArr = beforeCurrentPageArr.concat(afterCurrentPageArr)
      for (var iPage = 0; iPage < pageArr.length; iPage++) {
        if (pageArr[iPage] == "...") {
          pageItemsHtml += boostPFSTemplate.pageItemRemainHtml
        } else {
          pageItemsHtml +=
            pageArr[iPage] == currentPage
              ? boostPFSTemplate.pageItemSelectedHtml
              : boostPFSTemplate.pageItemHtml
        }
        pageItemsHtml = pageItemsHtml.replace(/{{itemTitle}}/g, pageArr[iPage])
        pageItemsHtml = pageItemsHtml.replace(
          /{{itemUrl}}/g,
          _utils.buildToolbarLink("page", currentPage, pageArr[iPage])
        )
      }
      paginationHtml = paginationHtml.replace(/{{pageItems}}/g, pageItemsHtml)
      return paginationHtml
    }
    return ""
  }

  ProductPaginationLoadMore.prototype.compileTotalTemplate = function () {
    /**
     * If enable the Load previous feature and the evnet type is page:
     * => Get the next loading page is from session storage OR get the next loading page from query param
     */
    // console.log(_utils.isLoadPreviousPagePaginationType())
    if (
      _utils.isLoadPreviousPagePaginationType() &&
      this.parent.eventType == "page"
    ) {
      this.nextPage = parseInt(
        window.sessionStorage.getItem(
          this.settings.sessionStorageCurrentNextPage
        )
      )
    } else {
      this.nextPage = Globals.queryParams.page
    }
    // Set from index
    var from = (this.nextPage - 1) * Globals.queryParams.limit + 1
    if (jQ(Selector.products + " > column").length) {
      from -=
        jQ(Selector.products + " > column").length - Globals.queryParams.limit
    }
    // Set to index
    var product_index = (this.nextPage - 1) * Globals.queryParams.limit + 1
    var to = product_index + this.data.products.length - 1

    return this.getTemplate("total")
      .replace(/{{progressLable}}/g, Labels.loadMoreTotal)
      .replace(/{{ from }}/g, from)
      .replace(/{{ to }}/g, to)
      .replace(/{{ total }}/g, this.totalProduct)
      .replace(/{{class.productLoadMore}}/g, Class.productLoadMore)
  }

  // Build Sorting
  ProductSorting.prototype.compileTemplate = function () {
    var html = ""
    if (boostPFSTemplate.hasOwnProperty("sortingHtml")) {
      var sortingArr = _utils.getSortingList()
      if (sortingArr) {
        // Build content
        var sortingItemsHtml = ""
        for (var k in sortingArr) {
          sortingItemsHtml +=
            '<option value="' + k + '">' + sortingArr[k] + "</option>"
        }
        var html = boostPFSTemplate.sortingHtml.replace(
          /{{sortingItems}}/g,
          sortingItemsHtml
        )
      }
    }
    return html
  }

  // Build Breadcrumb
  Breadcrumb.prototype.compileTemplate = function (colData, apiData) {
    if (!colData) colData = this.colData
    if (!apiData) apiData = this.apiData

    if (
      typeof colData !== "undefined" &&
      colData.hasOwnProperty("collection")
    ) {
      var colInfo = colData.collection

      var breadcrumbHtml =
        '<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><a href="' +
        boostPFSConfig.shop.url +
        '" title="' +
        boostPFSConfig.shop.name +
        '" itemprop="item"><span itemprop="name">' +
        boostPFSConfig.label.breadcrumb_home +
        "</span></a></span>"
      breadcrumbHtml += ' &nbsp;<span class="icon-arrow-right"></span>'
      breadcrumbHtml +=
        ' <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><a href="/collections/' +
        colInfo.handle +
        '" title="{{currentCollectionTitle}}" itemprop="item"><span itemprop="name">{{currentCollectionTitle}}</span></a></span>'
      // Build Tags
      var currentTagsHtml = ""
      if (Array.isArray(boostPFSConfig.general.current_tags)) {
        var current_tags = boostPFSConfig.general.current_tags
        for (var k in current_tags) {
          var tag = current_tags[k]
          currentTagsHtml += ' &nbsp;<span class="icon-arrow-right"></span>'
          currentTagsHtml +=
            ' <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><a href="/collections/{{currentCollectionLink}}" title="' +
            tag +
            '" itemprop="item"><span itemprop="name">' +
            tag +
            "</span></a></span>"
        }
      }
      breadcrumbHtml += currentTagsHtml
      // Build Collection Info
      breadcrumbHtml = breadcrumbHtml
        .replace(/{{currentCollectionLink}}/g, "/collections/" + colInfo.handle)
        .replace(/{{currentCollectionTitle}}/g, colInfo.title)
      // Top Pagination
      // var currentPage = parseInt(Globals.queryParams.page);
      // var totalPage = Math.ceil(apiData.total_product / Globals.queryParams.limit);
      // var topPaginationHtml = ' &nbsp;<span class="icon-arrow-right"></span> ' + (boostPFSConfig.label.breadcrumb_page).replace(/{{ current_page }}/g, Globals.queryParams.page).replace(/{{ pages }}/g, totalPage)
      // breadcrumbHtml += topPaginationHtml;
      breadcrumbHtml +=
        ' <span class="boost-pfs-filter-breadcrumb-page"></span>'

      return breadcrumbHtml
    }
  }

  // Add additional feature for product list, used commonly in customizing product list
  ProductList.prototype.afterRender = function (data) {
    if (!data) data = this.data
    buildTheme()

    if (!_utils.isMobile() && boostPFSConfig.custom.quick_shop_enable) {
      // Build content for Quick view
      ProductList.prototype.buildExtrasProductListByAjax(
        data,
        "boost-pfs-quickview",
        function (results) {
          results.forEach(function (result, index) {
            // Append the custom html to product item
            jQ('[data-boost-pfs-theme-quickview="' + result.id + '"]').append(
              result.quickview_html
            )
            buildTheme()
          })
        }
      )
    }

    buildCurrentPageInBreadcrumb()
  }

  // Build additional elements
  FilterResult.prototype.afterRender = function (data) {
    if (!data) data = this.data

    // Add Wrapper for Product list
    if (jQ(".boost-pfs-filter-products").children().hasClass("products")) {
      jQ(".boost-pfs-filter-products").children().children().unwrap()
    }

    buildCurrentPageInBreadcrumb()
  }

  function buildTheme() {
    collection.init()
    Shopify.PaymentButton.init()
    if (
      boostPFSConfig.custom.show_multiple_currencies &&
      window.convertCurrencies &&
      typeof convertCurrencies == "function"
    ) {
      convertCurrencies()
    }
  }

  function buildCurrentPageInBreadcrumb() {
    // Build Breadcrumb
    var totalPage = Math.ceil(
      Globals.collectionCount / Globals.queryParams.limit
    )
    var topPaginationHtml =
      '&nbsp;<span class="icon-arrow-right"></span> ' +
      boostPFSConfig.label.breadcrumb_page
        .replace(/{{ current_page }}/g, Globals.queryParams.page)
        .replace(/{{ pages }}/g, totalPage)
    jQ(".boost-pfs-filter-breadcrumb-page").html(topPaginationHtml)
  }
})()

/* Begin patch boost-010 run 2 */
Filter.prototype.beforeInit=function(){var t=this.isBadUrl();t&&(this.isInit=!0,window.location.href=window.location.pathname)},Filter.prototype.isBadUrl=function(){try{var t=decodeURIComponent(window.location.search).split("&"),e=!1;if(t.length>0)for(var n=0;n<t.length;n++){var i=t[n],r=(i.match(/</g)||[]).length,a=(i.match(/>/g)||[]).length,o=(i.match(/alert\(/g)||[]).length,h=(i.match(/execCommand/g)||[]).length;if(r>0&&a>0||r>1||a>1||o||h){e=!0;break}}return e}catch(l){return!0}};
/* End patch boost-010 run 2 */
/*
*WORKING FINE:-[but pagination not working as expected](UPDATED ON 07.01.2021)
 * Module Description: This script is used to perform bulk approval on Exp Report.

 * Modification logs

  	Date       			Modified By         Requested By      	        Remarks 
	---------------------------------------------------------------------------------------------------------------------
 6/01/2022            MD FAIZI       Onkar Bhagwan Sanjekar         Creation 
	*/


/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 *
 * 
 */
define(["N/record", "N/ui/serverWidget", "N/search", "N/runtime","N/ui/dialog"], function (
  record,
  serverWidget,
  search,
  runtime,
  dialog
) {
  function onRequest(context) {
    if (context.request.method === "GET") {
      try {

        var pagenum = context.request.parameters.pagenum;
        log.debug("pagenum", pagenum);
				var i_subsidiary = context.request.parameters.i_subsidiary;
        log.debug("i_subsidiary", i_subsidiary);
        //ROLE NOT NEEDED.
				//var i_role = context.request.parameters.i_role;
				// var i_je_record_type = context.request.parameters.i_je_record_type;
				var d_from_date = context.request.parameters.d_from_date;
				var d_to_date = context.request.parameters.d_to_date1;
				var i_employee_select = context.request.parameters.i_employee_select;
				log.audit('d_to_date:- '+d_to_date);

				var today = new Date();
				//var d_today =  formatDate(today);

				var i_current_user = runtime.getCurrentUser();
				var s_current_user = i_current_user.name
				var i_current_role = i_current_user.role
				i_current_user = i_current_user.id



        var er_form = serverWidget.createForm({ title : 'Approve Expense Report' });

        //SUBSIDIARY PART STARTS HERE.
				var o_subsidiary = er_form.addField({id : 'custpage_subsidiary_selection',type : serverWidget.FieldType.SELECT,label : 'Subsidiary'});
				if(o_subsidiary)
				{
					o_subsidiary.addSelectOption({ value : '0', text : ''});
					var o_subsidiary_srch = search.create({
						type: "subsidiary",
						filters:
							[
								["isinactive","is","F"]
								],
								columns:
									[
										search.createColumn({name: "internalid", label: "Internal ID"}),
										search.createColumn({name: "namenohierarchy", label: "Name (no hierarchy)"})
										]
					});

					var searchResultCount = o_subsidiary_srch.runPaged().count;
					o_subsidiary_srch.run().each(function(result){

						var i_subsidiary_internalId = result.getValue({name: "internalid"});
						var s_subsidiray_name = result.getValue({name: "namenohierarchy"});

						o_subsidiary.addSelectOption({ value : i_subsidiary_internalId, text : s_subsidiray_name});
						return true;
					});
				}

				if(i_subsidiary)
				{
					i_subsidiary = i_subsidiary.toString();
					o_subsidiary.defaultValue = i_subsidiary;
				}

        //SUBSIDIARY PART ENDS HERE.



//EMP SELECTION STARTS HERE.
        var o_employee = er_form.addField({id : 'custpage_employee_selection',type : serverWidget.FieldType.SELECT,label : 'Employee'});
				if(o_employee)
				{

					var employeeSearchObj = search.create({
						type: "employee",
						filters:
							[
								["isinactive","is","F"], 
								"AND", 
								["email","isnotempty",""]
								],
								columns:
									[
										search.createColumn({name: "internalid", label: "Internal ID"}),
										search.createColumn({name: "entityid",sort: search.Sort.ASC,label: "Name"})
										]
					});
					var searchResult_employee = employeeSearchObj.run().getRange(0, 1000);
					if (searchResult_employee != null && searchResult_employee != '' && searchResult_employee != ' ')
					{
						var completeExpSearchresult = searchResult_employee;
						var start = 1000;
						var last = 2000;
						while (searchResult_employee.length == 1000)
						{
							searchResult_employee = employeeSearchObj.run().getRange(start, last);
							completeExpSearchresult = completeExpSearchresult.concat(searchResult_employee);
							start = parseFloat(start) + 1000;
							last = parseFloat(last) + 1000;
						}//end of  while (ExpSearchresult.length == 1000)
						searchResult_employee = completeExpSearchresult;
						if(searchResult_employee.length > 0)
						{
							o_employee.addSelectOption({value : '',text : ''});
							for(var i_employee = 0 ; i_employee < searchResult_employee.length; i_employee++)
							{
								var i_employee_id = searchResult_employee[i_employee].getValue({name: 'internalid'});
								var i_employee_value = searchResult_employee[i_employee].getValue({name: 'entityid'});

								o_employee.addSelectOption({value : i_employee_id,text : i_employee_value});
							}
						}
					}
				}

				if(i_employee_select)
				{
					i_employee_select = i_employee_select.toString();
					o_employee.defaultValue = i_employee_select;
				}

//EMP SELECTION ENDS HERE.

//FROM DATE TO DATE STARTS HERE.
var o_frm_date_range = er_form.addField({id : 'custpage_from_date',type : serverWidget.FieldType.DATE,label : 'From Date'});

if(d_from_date)
{
  o_frm_date_range.defaultValue = d_from_date;
}

var o_to_date_range = er_form.addField({id : 'custpage_to_date',type : serverWidget.FieldType.DATE,label : 'To Date'});
log.audit('d_to_date:- '+d_to_date);
if(d_to_date)
{
  o_to_date_range.defaultValue = d_to_date;
}


//FROM DATE TO DATE ENDS HERE.







//suitlet form creation part starts here .Adding fields and sublist in the form.

        // var er_form = serverWidget.createForm({
        //   title: "Approve Expense Report",
        // });

        var selectPage = er_form.addField({
          id: "custlist_selectpage",
          type: serverWidget.FieldType.SELECT,
          label: "Select Page",
        });
        var obj_Sublist = er_form.addSublist({
          id: "custpage_sublistid",
          type: serverWidget.SublistType.LIST,
          label: "Expense Report",
        });
        //obj_Sublist.addMarkAllButtons();
        //obj_Sublist.addField({id : 'custlist_checkbox',type : serverWidget.FieldType.CHECKBOX,label : 'Select' });
        //
        obj_Sublist.addField({
          id: "custlist_approve",
          type: serverWidget.FieldType.CHECKBOX,
          label: "Approve",
        });
        obj_Sublist.addField({
          id: "custlist_reject",
          type: serverWidget.FieldType.CHECKBOX,
          label: "Reject",
        });
        // obj_Sublist.addField({id : 'custlist_pushback',type : serverWidget.FieldType.CHECKBOX,label : 'Push Back' });
        var f_rejection = obj_Sublist.addField({
          id: "custlist_rejection_reason",
          type: serverWidget.FieldType.TEXT,
          label: "Rejection Reason",
        });
        f_rejection.updateDisplayType({
          displayType: serverWidget.FieldDisplayType.ENTRY,
        });
        // var f_pushback = obj_Sublist.addField({id : 'custlist_pushback_reason',type : serverWidget.FieldType.TEXT,label : 'Push Back Reason' });
        // f_pushback.updateDisplayType({displayType: serverWidget.FieldDisplayType.ENTRY});
        obj_Sublist.addField({
          id: "custlist_date",
          type: serverWidget.FieldType.DATE,
          label: "Expense Report Date",
        });


        //EXPENSE REPORT ID
        obj_Sublist.addField({
          id: "custlist_internalid",
          type: serverWidget.FieldType.TEXT,
          label: "Expense Report ID",
        });
         //EXPENSE REPORT ID


        obj_Sublist.addField({
          id: "custlist_tranid",
          type: serverWidget.FieldType.TEXT,
          label: "Expense Report Number",
        });
        obj_Sublist.addField({
          id: "custlist_name",
          type: serverWidget.FieldType.TEXT,
          label: "Employee",
        });
        //obj_Sublist.addField({id : 'custlist_memo',type : serverWidget.FieldType.TEXT,label : 'Memo' });
        obj_Sublist.addField({
          id: "custlist_status",
          type: serverWidget.FieldType.TEXT,
          label: "Status",
        });
        obj_Sublist.addField({
          id: "custlist_currency",
          type: serverWidget.FieldType.TEXT,
          label: "Currency",
        });
        obj_Sublist.addField({
          id: "custlist_subsidiary",
          type: serverWidget.FieldType.TEXTAREA,
          label: "Subsidiary",
        });
        obj_Sublist.addField({
          id: "custlist_estimated_amount",
          type: serverWidget.FieldType.FLOAT,
          label: "Transaction Amount",
        });
        obj_Sublist.addField({
          id: "custlist_created_by",
          type: serverWidget.FieldType.TEXT,
          label: "Created By",
        });
        obj_Sublist.addField({
          id: "custlist_pending_approval_from_role",
          type: serverWidget.FieldType.TEXT,
          label: "Pending Approval from role",
        });
        // var ViewField = obj_Sublist.addField({
        //   id: "custlist_view",
        //   type: serverWidget.FieldType.TEXT,
        //   label: "View Record",
        // });

        // er_form.addSubmitButton({ label: "Submit" });
        // er_form.addResetButton({ label: "Reset" });

        //EXPENSE REPORT SAVED SEARCH:- 3RD

        var transactionSearchObj=''; //SAVED SEARCH VARIABLE DECLARED HERE.
        if(i_subsidiary  && d_from_date &&  d_to_date &&  i_employee_select){
          transactionSearchObj = search.create({
            type: "transaction",
            filters:
              [
                ["type","anyof","ExpRept"], 
                "AND", 
                ["approvalstatus","anyof","1"], 
                "AND", 
                ["mainline","is","T"], 
                "AND", 
                ['custbody_asp_current_approval_role', 'anyof', '1046'],
                "AND",
                ["subsidiary","anyof",i_subsidiary],
                "AND",
                ["trandate","onorafter",d_from_date],
                "AND",
                ["trandate","onorbefore",d_to_date],
                "AND", 
                ["employee","anyof",i_employee_select]
                ],
                columns: [
                  search.createColumn({ name: "type", label: "Transaction Type" }),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "amount", label: "Amount" }),
                  search.createColumn({
                    name: "custbody_transcation_creator",
                    label: "Transaction Creator",
                  }),
                  search.createColumn({
                    name: "custbody_asp_transubmittedbyemployee",
                    label: "Transaction Submitted for Approval By",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_one",
                    label: "Transaction Approved/Rejected By Level 1 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_two",
                    label: "Transcation Approved/Rejected by Level 2 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_three",
                    label: "Transaction Approved/Rejected by Level 3 User",
                  }),
                  search.createColumn({ name: "createdby", label: "Created By" }),
                  search.createColumn({
                    name: "custbody_asp_current_approval_role",
                    label: "Pending Approval From",
                  }),
                  search.createColumn({ name: "internalid", label: "Internal ID" }),
                  search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
                  search.createColumn({name: "entity", label: "Name"}),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "tranid", label: "Document Number" }),
                  search.createColumn({ name: "currency", label: "Currency" }),
                  search.createColumn({ name: "approvalstatus", label: "Status" }),
                  search.createColumn({
                    name: "fxamount",
                    label: "Estimated Amount",
                  }),
                ],
              });

              log.debug('1st condition runs=i_subsidiary  && d_from_date &&  d_to_date &&  i_employee_select');
              log.debug("transactionSearchObj",transactionSearchObj);
              
              

        }
        else if(!i_subsidiary  && !d_from_date &&  !d_to_date &&  i_employee_select){

          transactionSearchObj = search.create({
            type: "transaction",
            filters:
              [
                ["type","anyof","ExpRept"], 
                "AND", 
                ["approvalstatus","anyof","1"], 
                "AND", 
                ["mainline","is","T"], 
                "AND", 
                ['custbody_asp_current_approval_role', 'anyof', '1046'],
                "AND",
                ["employee","anyof",i_employee_select]
                ],
                columns: [
                  search.createColumn({ name: "type", label: "Transaction Type" }),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "amount", label: "Amount" }),
                  search.createColumn({
                    name: "custbody_transcation_creator",
                    label: "Transaction Creator",
                  }),
                  search.createColumn({
                    name: "custbody_asp_transubmittedbyemployee",
                    label: "Transaction Submitted for Approval By",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_one",
                    label: "Transaction Approved/Rejected By Level 1 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_two",
                    label: "Transcation Approved/Rejected by Level 2 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_three",
                    label: "Transaction Approved/Rejected by Level 3 User",
                  }),
                  search.createColumn({ name: "createdby", label: "Created By" }),
                  search.createColumn({
                    name: "custbody_asp_current_approval_role",
                    label: "Pending Approval From",
                  }),
                  search.createColumn({ name: "internalid", label: "Internal ID" }),
                  search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
                  search.createColumn({name: "entity", label: "Name"}),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "tranid", label: "Document Number" }),
                  search.createColumn({ name: "currency", label: "Currency" }),
                  search.createColumn({ name: "approvalstatus", label: "Status" }),
                  search.createColumn({
                    name: "fxamount",
                    label: "Estimated Amount",
                  }),
                ],
              });
              log.debug('2nd condition runs=!i_subsidiary  && !d_from_date &&  !d_to_date &&  i_employee_select');
              log.debug("transactionSearchObj",transactionSearchObj);
              



        }
        else if(i_subsidiary  && !d_from_date &&  !d_to_date &&  !i_employee_select){



          transactionSearchObj = search.create({
            type: "transaction",
            filters:
              [
                ["type","anyof","ExpRept"], 
                "AND", 
                ["approvalstatus","anyof","1"], 
                "AND", 
                ["mainline","is","T"], 
                "AND", 
                ['custbody_asp_current_approval_role', 'anyof', '1046'],
                "AND",
                ["subsidiary","anyof",i_subsidiary]
                
                ],
                columns: [
                  search.createColumn({ name: "type", label: "Transaction Type" }),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "amount", label: "Amount" }),
                  search.createColumn({
                    name: "custbody_transcation_creator",
                    label: "Transaction Creator",
                  }),
                  search.createColumn({
                    name: "custbody_asp_transubmittedbyemployee",
                    label: "Transaction Submitted for Approval By",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_one",
                    label: "Transaction Approved/Rejected By Level 1 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_two",
                    label: "Transcation Approved/Rejected by Level 2 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_three",
                    label: "Transaction Approved/Rejected by Level 3 User",
                  }),
                  search.createColumn({ name: "createdby", label: "Created By" }),
                  search.createColumn({
                    name: "custbody_asp_current_approval_role",
                    label: "Pending Approval From",
                  }),
                  search.createColumn({ name: "internalid", label: "Internal ID" }),
                  search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
                  search.createColumn({name: "entity", label: "Name"}),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "tranid", label: "Document Number" }),
                  search.createColumn({ name: "currency", label: "Currency" }),
                  search.createColumn({ name: "approvalstatus", label: "Status" }),
                  search.createColumn({
                    name: "fxamount",
                    label: "Estimated Amount",
                  }),
                ],
              });
              log.debug('3rd condition runs=i_subsidiary  && !d_from_date &&  !d_to_date &&  !i_employee_select');
              log.debug("transactionSearchObj",transactionSearchObj);
              



        }
        else if(i_subsidiary  && !d_from_date &&  !d_to_date &&  i_employee_select){
          transactionSearchObj = search.create({
            type: "transaction",
            filters:
              [
                ["type","anyof","ExpRept"], 
                "AND", 
                ["approvalstatus","anyof","1"], 
                "AND", 
                ["mainline","is","T"], 
                "AND", 
                ['custbody_asp_current_approval_role', 'anyof', '1046'],
                "AND",
                ["subsidiary","anyof",i_subsidiary],
                "AND",
                
                 
                ["employee","anyof",i_employee_select]
                ],
                columns: [
                  search.createColumn({ name: "type", label: "Transaction Type" }),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "amount", label: "Amount" }),
                  search.createColumn({
                    name: "custbody_transcation_creator",
                    label: "Transaction Creator",
                  }),
                  search.createColumn({
                    name: "custbody_asp_transubmittedbyemployee",
                    label: "Transaction Submitted for Approval By",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_one",
                    label: "Transaction Approved/Rejected By Level 1 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_two",
                    label: "Transcation Approved/Rejected by Level 2 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_three",
                    label: "Transaction Approved/Rejected by Level 3 User",
                  }),
                  search.createColumn({ name: "createdby", label: "Created By" }),
                  search.createColumn({
                    name: "custbody_asp_current_approval_role",
                    label: "Pending Approval From",
                  }),
                  search.createColumn({ name: "internalid", label: "Internal ID" }),
                  search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
                  search.createColumn({name: "entity", label: "Name"}),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "tranid", label: "Document Number" }),
                  search.createColumn({ name: "currency", label: "Currency" }),
                  search.createColumn({ name: "approvalstatus", label: "Status" }),
                  search.createColumn({
                    name: "fxamount",
                    label: "Estimated Amount",
                  }),
                ],
              });

              log.debug('4th condition runs=i_subsidiary  && !d_from_date &&  !d_to_date &&  i_employee_select');
              log.debug("transactionSearchObj",transactionSearchObj);
        }
        else if(i_subsidiary  && d_from_date &&  d_to_date &&  !i_employee_select){
          transactionSearchObj = search.create({
            type: "transaction",
            filters:
              [
                ["type","anyof","ExpRept"], 
                "AND", 
                ["approvalstatus","anyof","1"], 
                "AND", 
                ["mainline","is","T"], 
                "AND", 
                ['custbody_asp_current_approval_role', 'anyof', '1046'],
                "AND",
                ["subsidiary","anyof",i_subsidiary],
                "AND",
                ["trandate","onorafter",d_from_date],
                "AND",
                ["trandate","onorbefore",d_to_date]
                
                
                ],
                columns: [
                  search.createColumn({ name: "type", label: "Transaction Type" }),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "amount", label: "Amount" }),
                  search.createColumn({
                    name: "custbody_transcation_creator",
                    label: "Transaction Creator",
                  }),
                  search.createColumn({
                    name: "custbody_asp_transubmittedbyemployee",
                    label: "Transaction Submitted for Approval By",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_one",
                    label: "Transaction Approved/Rejected By Level 1 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_two",
                    label: "Transcation Approved/Rejected by Level 2 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_three",
                    label: "Transaction Approved/Rejected by Level 3 User",
                  }),
                  search.createColumn({ name: "createdby", label: "Created By" }),
                  search.createColumn({
                    name: "custbody_asp_current_approval_role",
                    label: "Pending Approval From",
                  }),
                  search.createColumn({ name: "internalid", label: "Internal ID" }),
                  search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
                  search.createColumn({name: "entity", label: "Name"}),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "tranid", label: "Document Number" }),
                  search.createColumn({ name: "currency", label: "Currency" }),
                  search.createColumn({ name: "approvalstatus", label: "Status" }),
                  search.createColumn({
                    name: "fxamount",
                    label: "Estimated Amount",
                  }),
                ],
              });

              log.debug('5th condition runs=i_subsidiary  && d_from_date &&  d_to_date &&  !i_employee_select');
              log.debug("transactionSearchObj",transactionSearchObj);
        }
        else if(!i_subsidiary  && d_from_date &&  d_to_date &&  !i_employee_select){
          transactionSearchObj = search.create({
            type: "transaction",
            filters:
              [
                ["type","anyof","ExpRept"], 
                "AND", 
                ["approvalstatus","anyof","1"], 
                "AND", 
                ["mainline","is","T"], 
                "AND", 
                ['custbody_asp_current_approval_role', 'anyof', '1046'],
                "AND",
               
                ["trandate","onorafter",d_from_date],
                "AND",
                ["trandate","onorbefore",d_to_date]
                
                ],
                columns: [
                  search.createColumn({ name: "type", label: "Transaction Type" }),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "amount", label: "Amount" }),
                  search.createColumn({
                    name: "custbody_transcation_creator",
                    label: "Transaction Creator",
                  }),
                  search.createColumn({
                    name: "custbody_asp_transubmittedbyemployee",
                    label: "Transaction Submitted for Approval By",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_one",
                    label: "Transaction Approved/Rejected By Level 1 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_two",
                    label: "Transcation Approved/Rejected by Level 2 User",
                  }),
                  search.createColumn({
                    name: "custbody_asp_approved_by_level_three",
                    label: "Transaction Approved/Rejected by Level 3 User",
                  }),
                  search.createColumn({ name: "createdby", label: "Created By" }),
                  search.createColumn({
                    name: "custbody_asp_current_approval_role",
                    label: "Pending Approval From",
                  }),
                  search.createColumn({ name: "internalid", label: "Internal ID" }),
                  search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
                  search.createColumn({name: "entity", label: "Name"}),
                  search.createColumn({ name: "trandate", label: "Date" }),
                  search.createColumn({ name: "tranid", label: "Document Number" }),
                  search.createColumn({ name: "currency", label: "Currency" }),
                  search.createColumn({ name: "approvalstatus", label: "Status" }),
                  search.createColumn({
                    name: "fxamount",
                    label: "Estimated Amount",
                  }),
                ],
              });

              log.debug('6th condition runs=!i_subsidiary  && d_from_date &&  d_to_date &&  !i_employee_select');
        }
        else{
        transactionSearchObj = search.create({
          type: "transaction",
          filters: [
            [
              [
                [["approvalstatus", "anyof", "1"]],
                "AND",
                [["type", "anyof", "ExpRept"]],
                "AND",
                [["mainline", "is", "T"]],
                "AND",
                [["linesequencenumber", "equalto", "0"]],
              ],
              "AND",
              [
                [["custbody_asp_approval_level_1_role", "anyof", "1046"]],
                "OR",
                [["custbody_asp_approval_level_2_role", "anyof", "1046"]],
                "OR",
                [["custbody_asp_approval_level_3_role", "anyof", "1046"]],
              ],
            ],
          ],
          columns: [
            search.createColumn({ name: "type", label: "Transaction Type" }),
            search.createColumn({ name: "trandate", label: "Date" }),
            search.createColumn({ name: "amount", label: "Amount" }),
            search.createColumn({
              name: "custbody_transcation_creator",
              label: "Transaction Creator",
            }),
            search.createColumn({
              name: "custbody_asp_transubmittedbyemployee",
              label: "Transaction Submitted for Approval By",
            }),
            search.createColumn({
              name: "custbody_asp_approved_by_level_one",
              label: "Transaction Approved/Rejected By Level 1 User",
            }),
            search.createColumn({
              name: "custbody_asp_approved_by_level_two",
              label: "Transcation Approved/Rejected by Level 2 User",
            }),
            search.createColumn({
              name: "custbody_asp_approved_by_level_three",
              label: "Transaction Approved/Rejected by Level 3 User",
            }),
            search.createColumn({ name: "createdby", label: "Created By" }),
            search.createColumn({
              name: "custbody_asp_current_approval_role",
              label: "Pending Approval From",
            }),
            search.createColumn({ name: "internalid", label: "Internal ID" }),
            search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
            search.createColumn({name: "entity", label: "Name"}),
            search.createColumn({ name: "trandate", label: "Date" }),
            search.createColumn({ name: "tranid", label: "Document Number" }),
            search.createColumn({ name: "currency", label: "Currency" }),
            search.createColumn({ name: "approvalstatus", label: "Status" }),
            search.createColumn({
              name: "fxamount",
              label: "Estimated Amount",
            }),
          ],
        });
        log.debug('ELSE condition runs= WHEN nothing selected');
        log.debug('transactionSearchObj', transactionSearchObj);



      }


      //WITH PAGINATION

      var ExpSearchresult = transactionSearchObj.run().getRange({ start: 0, end: 1000  });
				if (ExpSearchresult != null && ExpSearchresult != '' && ExpSearchresult != ' ')
				{
					var completeExpSearchresult = ExpSearchresult;
					var start = 1000;
					var last = 2000;
					while (ExpSearchresult.length == 1000)
					{
						ExpSearchresult = transactionSearchObj.run().getRange(start, last);
						completeExpSearchresult = completeExpSearchresult.concat(ExpSearchresult);
						start = parseFloat(start) + 1000;
						last = parseFloat(last) + 1000;
					}//end of  while (ExpSearchresult.length == 1000)
					ExpSearchresult = completeExpSearchresult;
					var flag = false; 
					var tempExpSearchresult=[];

					for(var g in ExpSearchresult)
					{
						if(ExpSearchresult[g].getValue('custbody_akp_createdby')!=i_current_user)
						{
							tempExpSearchresult.push(ExpSearchresult[g]);
						}
					}
					ExpSearchresult=tempExpSearchresult;
					if(ExpSearchresult)
					{



						log.debug('In savedSearch: ExpSearchresult: ' + ExpSearchresult.length); 
						var length = ExpSearchresult.length;	
						var s_length = 15;
						var x = 15;
						var g = 0;
						if(pagenum)
						{					
							pagenum = parseInt(pagenum);
							s_length = pagenum;
							g = pagenum - x;					
						}				
						if(length <= 15)
						{
							log.debug('length <= 15 ' );
							//selectPage.addSelectOption({ value : '0', text : '1 to '+length+' of '+length+'',isSelected: true});
							//selectPage.addSelectOption('0', '1 to '+length+' of '+length+'',true);
							selectPage.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
							s_length = length;
							g = 0;
						}
						else
						{
							var n = 1;
							var pr_value = '';
							selectPage.addSelectOption({ value : '0', text : '1 to '+x+' of '+length+'' });
							//selectPage.addSelectOption('0', '1 to '+x+' of '+length+'');
							while(x < length)
							{
								var chk = x;
								pr_value = 	parseInt(x) + 1;												
								x = parseInt(x) + 15;
								var len = length - x;
								if(len < 15 && x > length)
								{
									x = length;
									//pr_value = length;							
								}
								if(x == pagenum)
								{
									selectPage.addSelectOption({ value : ''+n+'', text : ''+pr_value+' to '+x+' of '+length+'' ,isSelected: true});
									//selectPage.addSelectOption(''+n+'', ''+pr_value+' to '+x+' of '+length+'',true);
									g = chk;
								}	
								else
								{
									selectPage.addSelectOption({ value : ''+n+'', text : ''+pr_value+' to '+x+' of '+length+'' });
									//selectPage.addSelectOption(''+n+'', ''+pr_value+' to '+x+' of '+length+'');
								}
								n++;
							}
						}

	for (var i = 0; i < ExpSearchresult.length; i++) {
              //update record using newrecord.load so remainingusages gets updated everytime new colum
    
              //what keys to be passed to get get customer data ?
    
              //var remainingUsage = runtime.getCurrentScript().getRemainingUsage();
    
              //   var lineNum = currentCSObj.selectLine({
              //     sublistId: 'custpage_sublist',
              //     line: i
              // });
    
              var i_internalId = ExpSearchresult[i].getValue({
                name: "internalid",
              });
              var d_date = ExpSearchresult[i].getValue({ name: "trandate" });
              var emp_name=ExpSearchresult[i].getText({ name: "entity" });  //employee name as normal name i.e entity


              var s_tranid = ExpSearchresult[i].getValue({ name: "tranid" });
              //var s_requestor_name = ExpSearchresult[i].getText({name: "entity"});
              var s_subsidiary = ExpSearchresult[i].getText({ name: "subsidiary" });
              var s_currency = ExpSearchresult[i].getText({ name: "currency" });
              var s_status = ExpSearchresult[i].getText({ name: "approvalstatus" });
              var f_amount = ExpSearchresult[i].getValue({ name: "fxamount" });
              var s_createdBy = ExpSearchresult[i].getText({
                name: "createdby",
              });
              var s_pending_approval_from = ExpSearchresult[i].getText({
                name: "custbody_asp_current_approval_role",
              });
              // var i_additional_approvers = ExpSearchresult[i].getValue({name: "custbody_akp_additionalapprovers"});
              //var i_delegated_user = ExpSearchresult[i].getValue({name: "custbody_akp_delegatedtouser"});
    
              if (i_internalId) {
                obj_Sublist.setSublistValue({
                  id: "custlist_internalid",
                  line: i,
                  value: i_internalId,
                });
                
                // obj_Sublist.setSublistValue({
                //   id: "custlist_view",
                //   line: i,
                //   value:
                //     '<a href="https://6758468-sb1.app.netsuite.com/app/accounting/transactions/exprept.nl?id=' +
                //     i_internalId +
                //     '" target="_blank">Transaction Link</a>',
                // });
              }
    
              //JUST POPULATING F INTO CHECKBOX FIELD TO BE SHOWN. WORKED.
              // obj_Sublist.setSublistValue({
              //   id:"custlist_approve",
              //   line:i,
              //   value:'F'
    
              // });
    
              // obj_Sublist.setSublistValue({
              //   id:"custlist_reject",
              //   line:i,
              //   value:'F'
    
              // });
              // CHECKBOX ENDED.
            //   obj_Sublist.setSublistValue({sublistId:'custpage_sublistid', 
            //   fieldId:'custlist_rejection_reason',
            //    line: i,
            //    displayType: serverWidget.FieldDisplayType.DISABLED
            
            // });//
                     
                   
    
              if (d_date)
                obj_Sublist.setSublistValue({
                  id: "custlist_date",
                  line: i,
                  value: d_date,
                });
                if(emp_name)
             obj_Sublist.setSublistValue({id: 'custlist_name',line: i, value: emp_name });
           
              if (s_tranid)
                obj_Sublist.setSublistValue({
                  id: "custlist_tranid",
                  line: i,
                  value: s_tranid,
                });
    
              // if(s_requestor_name)
              // 	obj_Sublist.setSublistValue({id: 'custlist_name',line: i, value: s_requestor_name });
    
              if (s_subsidiary)
                obj_Sublist.setSublistValue({
                  id: "custlist_subsidiary",
                  line: i,
                  value: s_subsidiary,
                });
              if (s_currency)
                obj_Sublist.setSublistValue({
                  id: "custlist_currency",
                  line: i,
                  value: s_currency,
                });
              if (s_status)
                obj_Sublist.setSublistValue({
                  id: "custlist_status",
                  line: i,
                  value: s_status,
                });
              if (f_amount)
                obj_Sublist.setSublistValue({
                  id: "custlist_estimated_amount",
                  line: i,
                  value: f_amount,
                });
              if (s_createdBy)
                obj_Sublist.setSublistValue({
                  id: "custlist_created_by",
                  line: i,
                  value: s_createdBy,
                });
              if (s_pending_approval_from)
                obj_Sublist.setSublistValue({
                  id: "custlist_pending_approval_from_role",
                  line: i,
                  value: s_pending_approval_from,
                });
    
              //   obj_Sublist.commitLine({
              //   sublistId: "custpage_sublist",
              // });
            }
						
					}
				}
				else
				{
					selectPage.updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN });
				}








      //WITH PAGINATION











      // //NOW STARTED LOOPING THROUGHT SAVED SEARCH RESULTS AND ALSO SETTING VALUE TO SUBLIST FIELDS STARTS HERE:-
      //           var ExpSearchresult = [];
      //   var igrSearchData = transactionSearchObj.runPaged({ pageSize: 1000 });
      //   igrSearchData.pageRanges.forEach(function (pageRange) {
      //     var page = igrSearchData.fetch({ index: pageRange.index });
      //     ExpSearchresult = ExpSearchresult.concat(page.data);
      //   });
      //   //logging the fetched data from saved search.
      //   log.debug("ExpSearchresult  array", ExpSearchresult);

      //   //now populate the search result in the form sublist.

      //   for (var i = 0; i < ExpSearchresult.length; i++) {
      //     //update record using newrecord.load so remainingusages gets updated everytime new colum

      //     //what keys to be passed to get get customer data ?

      //     //var remainingUsage = runtime.getCurrentScript().getRemainingUsage();

      //     //   var lineNum = currentCSObj.selectLine({
      //     //     sublistId: 'custpage_sublist',
      //     //     line: i
      //     // });

      //     var i_internalId = ExpSearchresult[i].getValue({
      //       name: "internalid",
      //     });
      //     var d_date = ExpSearchresult[i].getValue({ name: "trandate" });
      //     var s_tranid = ExpSearchresult[i].getValue({ name: "tranid" });
      //     //var s_requestor_name = ExpSearchresult[i].getText({name: "entity"});
      //     var s_subsidiary = ExpSearchresult[i].getText({ name: "subsidiary" });
      //     var s_currency = ExpSearchresult[i].getText({ name: "currency" });
      //     var s_status = ExpSearchresult[i].getText({ name: "approvalstatus" });
      //     var f_amount = ExpSearchresult[i].getValue({ name: "fxamount" });
      //     var s_createdBy = ExpSearchresult[i].getText({
      //       name: "createdby",
      //     });
      //     var s_pending_approval_from = ExpSearchresult[i].getText({
      //       name: "custbody_asp_current_approval_role",
      //     });
      //     // var i_additional_approvers = ExpSearchresult[i].getValue({name: "custbody_akp_additionalapprovers"});
      //     //var i_delegated_user = ExpSearchresult[i].getValue({name: "custbody_akp_delegatedtouser"});

      //     if (i_internalId) {
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_internalid",
      //         line: i,
      //         value: i_internalId,
      //       });
      //       // obj_Sublist.setSublistValue({
      //       //   id: "custlist_view",
      //       //   line: i,
      //       //   value:
      //       //     '<a href="https://6758468-sb1.app.netsuite.com/app/accounting/transactions/exprept.nl?id=' +
      //       //     i_internalId +
      //       //     '" target="_blank">Transaction Link</a>',
      //       // });
      //     }

      //     //JUST POPULATING F INTO CHECKBOX FIELD TO BE SHOWN. WORKED.
      //     obj_Sublist.setSublistValue({
      //       id:"custlist_approve",
      //       line:i,
      //       value:'F'

      //     });

      //     obj_Sublist.setSublistValue({
      //       id:"custlist_reject",
      //       line:i,
      //       value:'F'

      //     });
      //     // CHECKBOX ENDED.

      //     if (d_date)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_date",
      //         line: i,
      //         value: d_date,
      //       });
      //     if (s_tranid)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_tranid",
      //         line: i,
      //         value: s_tranid,
      //       });

      //     // if(s_requestor_name)
      //     // 	obj_Sublist.setSublistValue({id: 'custlist_name',line: i, value: s_requestor_name });

      //     if (s_subsidiary)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_subsidiary",
      //         line: i,
      //         value: s_subsidiary,
      //       });
      //     if (s_currency)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_currency",
      //         line: i,
      //         value: s_currency,
      //       });
      //     if (s_status)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_status",
      //         line: i,
      //         value: s_status,
      //       });
      //     if (f_amount)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_estimated_amount",
      //         line: i,
      //         value: f_amount,
      //       });
      //     if (s_createdBy)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_created_by",
      //         line: i,
      //         value: s_createdBy,
      //       });
      //     if (s_pending_approval_from)
      //       obj_Sublist.setSublistValue({
      //         id: "custlist_pending_approval_from_role",
      //         line: i,
      //         value: s_pending_approval_from,
      //       });

      //     //   obj_Sublist.commitLine({
      //     //   sublistId: "custpage_sublist",
      //     // });
      //   }
// LOOPING THROUGHT SAVED SEARCH RESULTS AND ALSO SETTING VALUE TO SUBLIST FIELDS ENDS HERE:-

        
       
        //call client script here
        er_form.addSubmitButton({  label: 'Submit' });		
				er_form.addResetButton({  label: 'Reset' });
				
			
        er_form.clientScriptFileId = 168947;
        context.response.writePage(er_form);
      } catch (e) {
        log.debug("ERROR OCCUR IN GET REQUEST PART=", e);
      }
    } 
    
    
   
    



    //SUBMIT PART WORK STARTS HERE.
     if (context.request.method === "POST") {
      try {


        var i_current_user = runtime.getCurrentUser();
				var s_current_user = i_current_user.name
				var i_current_role = i_current_user.role
				i_current_user = i_current_user.id

				var i_Line_Count_Sublist = context.request.getLineCount({group: 'custpage_sublistid'});
				var transaction_number = ''
					for(var i_Line_Index = 0 ; i_Line_Index  < i_Line_Count_Sublist ; i_Line_Index++)
					{
            i_erId = context.request.getSublistValue({ group: 'custpage_sublistid' ,name: 'custlist_internalid' ,line: i_Line_Index});
						log.debug('i_erId', i_erId);
            log.debug('approve check box=', context.request.getSublistValue({ group: 'custpage_sublistid' ,name: 'custlist_approve' ,line: i_Line_Index}));

						b_approve = context.request.getSublistValue({ group: 'custpage_sublistid' ,name: 'custlist_approve' ,line: i_Line_Index});
						b_reject = context.request.getSublistValue({ group: 'custpage_sublistid' ,name: 'custlist_reject' ,line: i_Line_Index});
						s_rejection_reason = context.request.getSublistValue({ group: 'custpage_sublistid' ,name: 'custlist_rejection_reason' ,line: i_Line_Index});
						//

            if(i_erId && (b_approve == 'T' || (b_reject == 'T' && s_rejection_reason)))
						{
              //LOADING EXPENSE REPORT:-
							var expRep_rec_obj = record.load({type: 'expensereport',id: i_erId, isDynamic: true});//Load Requisition record








              
	
								
							
						
							if(b_approve == 'T')
							{
								
							
								
								
							
								try{

                  //var x=record.submitFields({type: record.Type.VENDOR_PAYMENT, id: i_vpId, values: {'custbody_asp_current_approval_role':'', 'approvalstatus':parseInt(2) , 'custbody_asp_approvedrejectedbyuser': parseInt(i_current_user), 'custbody_asp_approvedrejectedbyrole':parseInt(i_current_role) , 'custbody_asp_approveddate':date},options: {ignoreMandatoryFields : true}});
               



										var x=record.submitFields({type: 'expensereport', id: parseInt(i_erId), values: { 'approvalstatus':parseInt(2) ,'custbody_asp_approvedrejectedbyuser': parseInt(i_current_user), 'custbody_asp_approvedrejectedbyrole':parseInt(i_current_role) ,'custbody_asp_approval_level_1_role':(i_current_role),options: {ignoreMandatoryFields : true   }}});
									log.debug('successfully submitted record for approval',x);
                }
                catch(e){
                  log.error('Error while submitting record for Approval', e);
                }
									
												// record.submitFields({type: 'expensereport', id: parseInt(i_erId), values: {'custbody_akp_level1': 3,'custbody_akp_pendingapprovalfromrole':parseInt(i_approval_level3), 'approvalstatus':parseInt(1) }});
										
												//  record.submitFields({ type: 'expensereport', id: parseInt(i_erId), values: { 'custbody_akp_level1': 3, 'custbody_akp_submitforapprovalflag': false, 'custbody_akp_pendingapprovalfromrole': parseInt(i_approval_level2), 'approvalstatus': parseInt(1) } });
									
									
                
              }
              else if(b_reject == 'T' && s_rejection_reason){
                //code for rejection is 3.once try it.
                //id for rejection reason comment is custbody_reject_reason_bill .
                record.submitFields({type: 'expensereport', id: parseInt(i_erId), values: { 'approvalstatus':parseInt(3), 'custbody_reject_reason_bill': s_rejection_reason ,'custbody_asp_approvedrejectedbyuser': parseInt(i_current_user), 'custbody_asp_approvedrejectedbyrole':parseInt(i_current_role) ,'custbody_asp_approval_level_1_role':(i_current_role),options: {ignoreMandatoryFields : true   }}});
									

              }





            }










          }

//AFTER SUBMIT PAGE MESSAGE TO BE DISPLAYED TO USER.
          var er_form = serverWidget.createForm({ title : 'Approval Status Page' });

				var s_approved_label = er_form.addField({
					id : 'custpage_htmlfield',
					type : serverWidget.FieldType.INLINEHTML,
					label : 'Text'
				});//er_form.addField({ id: 'custpage_label',type: serverWidget.FieldType.TEXT,label: 'Approval Status'});

				var s_message = '';
				if(transaction_number)
				{
					s_message += '<br/> <br/> your request has been processed successfully';
					//s_message += '<br/> <br/> Transaction Number: '+transaction_number;
				}
				//s_message += '<br/> <br/> Kindly go to "Approve Vendor Bills" page to perform bulk approval';
        s_approved_label.defaultValue = s_message
				context.response.writePage(er_form);

			
		





        
      } catch (e) {
        var s_approved_label = er_form.addField({
					id : 'custpage_htmlfield',
					type : serverWidget.FieldType.INLINEHTML,
					label : 'Text'
				});//er_form.addField({ id: 'custpage_label',type: serverWidget.FieldType.TEXT,label: 'Approval Status'});

				var s_message = '';
				if(transaction_number)
				{
					s_message += '<br/> <br/> Error occured while  processing the following transactions for approval';
					//s_message += '<br/> <br/> Transaction Number: '+transaction_number;
				}
				s_message += '<br/> <br/> reason='+e;
        s_approved_label.defaultValue = s_message
				context.response.writePage(er_form);
        
      }
    }
  }
  return {
    onRequest: onRequest,
  };
});
<div class="card" style="width: 18rem;">
  <img src="..." class="card-img-top" alt="...">
  <div class="card-body">
    <h5 class="card-title">Card title</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
  </div>
  <ul class="list-group list-group-flush">
    <li class="list-group-item">An item</li>
    <li class="list-group-item">A second item</li>
    <li class="list-group-item">A third item</li>
  </ul>
  <div class="card-body">
    <a href="#" class="card-link">Card link</a>
    <a href="#" class="card-link">Another link</a>
  </div>
</div>
async function cdnjs(query){
	return await fetch("https://2qwlvlxzb6-2.algolianet.com/1/indexes/*/queries", {
		headers: {
		  accept: "*/*",
		  "content-type": "application/x-www-form-urlencoded",
		  "x-algolia-api-key": `2663c73014d2e4d6d1778cc8ad9fd010`,
		  "x-algolia-application-id": `2QWLVLXZB6`,
		},
		body: JSON.stringify({
		  requests: [{ indexName: "libraries", params: e`query=${q}` }],
		}),
		method: "POST",
	      })
		.then((res) => res.json())
		.then((res) => {
		  let results = res.results[0].hits;
		  return results.map((item) => ({
		    name: item.name,
		    keywords: item.keywords,
		    snippet: item.description,
		    author: item.author,
		  }));
		});
}
async function autocomplete(text){
	return JSON.parse(await fetch("https://www.google.com/complete/search?q=testing&client=Firefox").then(res => res.text()))[1];
}
function checkGrammar(text){
    const opts = {
        headers: {
            "accept": "application/vnd.splat+json",
        }
    }
    return new Promise(async (resolve) => {
        let job = await fetch("https://api.cram.com/article-evaluations", {
          "body": JSON.stringify({
              "text": text,
              "evaluate":["grammar","plagiarism"]
          }),
          "method": "POST",
          ...opts,
        }).then(res => res.json())
        let int = setInterval(async () => {
            let res = await fetch(`https://api.cram.com/article-evaluations/${job.data.id}`, {
              "headers": {
                "accept": "application/vnd.splat+json",
              },
              "method": "GET",
            }).then(res => res.json())
            if (res.data.is_success === 1){
                clearInterval(int);
                return resolve(res.data.result);
            }
        }, 500)
    });
}
/**
 * @param {String} text The text to check
 * @returns {Promise.<Object>}
 * @example
 *  // ⇒ {
 *  //   "Corrections": [...],
 *  //   "Sentences": [...]
 *  //}
 */
async function grammar(text){
	let res = await fetch(`https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=$&text=${encodeURIComponent(text)}&apiKey=GingerWebsite&clientVersion=2.0&lang=US`).then(res => res.text())
	return JSON.parse(res.replace(/^\$\(/, "").replace(/\);?$/, ""));//Returns a 'callback'
}
/**
* Gets parts of speech for a sentence
* @param {String} text The text to get parts of speech for.
* @returns {Promise.<Object>} Resolves into a list of parts of speech. (Or rejects with an error)
* @example 
* var parts_of_speech  = await parts_of_speech("Sometimes I just want to code in JavaScript all day.");
* // ⇒
* // {entities: Array(1), sentiments: Array(1), documentInfo: {…}, wordFreq: Array(4), taggedText: '<span class="tag ADV">Sometimes</span> <span class…>all</span> <span class="tag DURATION">day</span>'}
function parts_of_speech(text) {
*/
function parts_of_speech(text) {
  return new Promise(async (resolve, reject) => {
    fetch("https://showcase-serverless.herokuapp.com/pos-tagger", {
      headers: {
        accept: "application/json",
        "content-type": "application/json",
      },
      body: JSON.stringify({ sentence: text }),
      method: "POST",
    })
      .then((res) => res.json())
      .then(resolve)
      .catch(reject);
  });
}
/**
* Rewrites text
* @param {String} text The text to rewrite.
* @returns {Promise.<String[]>} Resolves into a list of about 10 rewritten versions. (Or rejects with an error)
* @example 
* var rewritten  = await rewrite("Sometimes I just want to code in JavaScript all day.");
* // ⇒ [
* //    "I sometimes just want to code JavaScript all day.",
* //    "JavaScript is my favorite programming language sometimes.",
* //    "I sometimes wish I could code in JavaScript all day.",
* //    "JavaScript is sometimes all I want to do all day.",
* //    "I like JavaScript sometimes and want to code all day long.",
* //    "Some days I just want to work all day in JavaScript.",
* //    "It's not uncommon for me to just want to code in JavaScript all day.",
* //    "My favorite thing to do sometimes is just code JavaScript all day.",
* //    "My favourite coding language is JavaScript, which I can code all day.",
*//     "JavaScript is my preferred language sometimes, since it lets me code all day.",
*// ];
*/
function rewrite(text) {
  return new Promise(async (resolve, reject) => {
    var { suggestions, error_code, error_msg, error_msg_extra } = await fetch(
      "https://api.wordtune.com/rewrite-limited",
      {
        headers: {
          accept: "*/*",
          "accept-language": "en-US,en;q=0.9",
          "content-type": "application/json",
          "x-wordtune-origin": "https://www.wordtune.com",
        },
        referrer: "https://www.wordtune.com/",
        body: JSON.stringify({
          action: "REWRITE",
          text: text,
          start: 0,
          end: text.length,
          selection: {
            wholeText: text,
            start: 0,
            end: text.length,
          },
        }),
        method: "POST",
      }
    ).then((res) => res.json());
    if (error_code || error_msg || error_msg_extra) {
      reject({
        code: error_code,
        message: error_msg,
        message_extra: error_msg_extra,
      });
    } else {
      resolve(suggestions);
    }
  });
}
/**
 * Translates text to a certain language.
 * @param {String} text The text to translate (or an options object)
 * @param {String} target The target language to translate to.
 * @param {String} source The source language.
 * @returns {Promise.<object>} Returns a promise resolving into an object with the translated text, raw response JSON, the original text, and the target and source languages.
 * @example
 * var translated = await translate("Hello world", "fr");
 * // ⇒ 
 * // {
 * //   source: "en", 
 * //   original: "Hello world",
 * //   translated: "Bonjour le monde",
 * //   result: "weird google stuff here"
 * // }
 *
 */
async function translate(text, target, source, proxy) {
  if (typeof text == "object") {
    target = text.target;
    source = text.source;
    proxy = text.proxy;
    text = text.text;
  }
  var opts = {
    text: text || "",
    source: source || 'auto',
    target: target || "en",
    proxy: proxy || "",
	}
  var result = await fetch(
    `https://${opts.proxy}translate.googleapis.com/translate_a/single?client=gtx&sl=${opts.source}&tl=${opts.target}&dt=t&q=${encodeURI(opts.text)}`
  ).then(res => res.json());
  return {
    source: opts.source,
    target: opts.target,
    original: text,
    translated: result[0]?.[0]?.[0],
    result,
  };
}
//Regular string
var rgb = "rgb(" + r + "," + g + "," + b + ")";
//Template literal
var rgb = `rgb(${r}, ${g}, ${b})`;
/**
 * Provides quick & simple way to verify if some
 * string is valid URL
 *
 * @param   <string>  URL to verify
 * @returns <boolean> Returns true if passed string
 *                    is valid URL, false otherwise
 */
function validateUrl (url) {
    try {
        new URL(url)
    } catch (error) {
        return false
    }
  
    return true
}
/**
 * Provides strict e-mail address verification close to RFC
 * Includes support for unicode
 *
 * @param   <string>  E-mail address to verify
 * @returns <boolean> Returns true if e-mail address is considered to be valid,
 *                    false otherwise
 */

export default function validateEmail (email) {
    return typeof email === 'string' &&
        email &&
        email.length < 256 &&
        /^(?:[0-z!#$%&'*+/=?^_`{|}.~-]|[^\u0000-\u007F]){1,64}@(?:(?:[0-z-]|[^\u0000-\u007F]){1,62}\.)+(?:[0-z]|[^\u0000-\u007F]){2,63}$/i.test(email) &&
        !email.includes('..') &&
        !email.startsWith('.') &&
        !email.includes('.@') &&
        !email.includes('-.') &&
        !email.includes('.-')
}
import { realpathSync as realpath, accessSync as access, existsSync as exists } from 'fs'
import { dirname } from 'path'

/**
 * IIFE to resolve Magento document root
 * @returns <string> Returns Magento document root
 */
export const mageRoot = (() => {
    let mageRoot = dirname(realpath(import.meta.url.slice(7)))

    while (!(exists(`${ mageRoot }/app/Mage.php`) || exists(`${ mageRoot }/bin/magento`))) {
        mageRoot = dirname(mageRoot)
    }

    return mageRoot
})()
jQuery(document).ready(function ($) {
 
 
  var isLoggedIn = !!$(".logged-in").length;
 
  function visibilityDriver() {
    for (scenario of visScenarios) {
      if (scenario.condition) {
        scenario.outcome();
      }
    }
  }
 
  var visScenarios = [
    {
      condition: isLoggedIn && abUser.group_id.indexOf("1791") > -1,
      outcome: function () {
        $("a.deal_reg").hide();
      },
    },
  ];
 
  visibilityDriver();
 
  
});
jQuery(document).ready(function($) {
 
 
var isLoggedIn = !!$(".logged-in").length;   
var group92 = isLoggedIn && ($(".administrator").length || abUser.group_id.indexOf("92") > -1);
 
function visibilityDriver() {
    for (scenario of visScenarios) {
        if (scenario.condition) {
            scenario.outcome();
        }
    }
}
 
var visScenarios = [
    {
        condition: !group92,
        outcome: function () {
            createNavItem('alliances', 'https://riskrecon.allbound.com/playbooks/?playbooks_category=alliances&filtered=what', 'gear', 'Alliances')
        },
    },
];
 
visibilityDriver();​
 
 
});
.post-type-archive-learn
  #filter_results
  > div
  > form
  > span:nth-child(9)
  > span.selection
  > span {
  display: none;
}
/*--- hide left side items ---*/
.subscriber li.menu-pipeline,
.subscriber li.menu-mdf,
.subscriber li.menu-prospect {display: none; }
 
 
 
// JS to show left nav items
jQuery(document).ready(function ($) {
 
 
  var isLoggedIn = !!$(".logged-in").length;
 
  var pipelineItem = "li.menu-pipeline";
  var mdfItem = "li.menu-mdf";
  var prospectPagesItem = "li.menu-prospect";
 
  var eliteCanSeePages = !!(isLoggedIn && abUser.group_id.indexOf("31") > -1);
  var premierCanSeePages = !!(isLoggedIn && abUser.group_id.indexOf("32") > -1);
 
  function showPipeline() {
    return $(pipelineItem).show();
  }
 
  function showMdf() {
    return $(mdfItem).show();
  }
 
  function showProspectPages() {
    return $(prospectPagesItem).show();
  }
 
  function scenarioDriver() {
    for (scenario of scenarios) {
      if (scenario.page && scenario.condition) {
        scenario.outcome();
        break;
      }
    }
  }
 
  var scenarios = [
    {
      condition: eliteCanSeePages || premierCanSeePages,
      page: true,
      debugger: [
        "Logic: if user is in group id 31 or 32, show pipeline mdf and prospect pages",
      ],
      outcome: function () {
        showPipeline();
        showMdf();
        showProspectPages();
      },
    },
  ];
 
  scenarioDriver();
}); // end ready function
jQuery(document).ready(function ($) {

  var dashboardItem = '.menu_main li.menu-dashboard a'
  var newDashboardItem = '<span class="icon-main-dashboard"></span>Test Text Here'

  function changeHtml() {
      for (el of newHtml) {
      $(el.selector).html(el.changedTo);
      }
  }
  
  var newHtml = [

       {
    selector: dashboardItem,
    changedTo: newDashboardItem,
       },
  ];
  
  changeHtml();
  }); //end ready function
jQuery(document).ready(function ($) {

  //update footer text
  $("div.footer_content").html(
    '<p>©2022 Account Name Here. All rights reserved. v4.17.0<br><a href="https://policies.google.com/privacy?hl=en-US">Privacy Policy</a></p>'
  );


}); // end rdy function
$('#input_2_16').attr('readonly', true);
$("body > section > main > div > div.login_box.main_login > p").append(
  "<br><p><i>Please note that Chrome is the preferred browser.</i>"
);
jQuery(document).ready(function ($) {
 
  
  $("body > section > main > div > div.login_box.main_login > p").append(
    '<p><br><a href="https://policies.google.com/privacy?hl=en-US">Google Privacy Policy</a>'
  );
  
  
}); // end ready function
/*-- css for partner tier styles --*/
.tier_level {
     height: auto;
     float: right;
     padding-right: 10px;
}
.tier_level img {
    height: 65px;
    width: auto;
    position: absolute;
    top: -3px;
    right: 275px;
}
@media only screen and (max-width: 600px){
  .tier_level img {
      right: 50px;
      top: 1px;
      height: 55px;
  }
}
 
 
 
// JS to display logos based on group
jQuery(document).ready(function ($) {
 
    var isLoggedIn = !!$(".logged-in").length;
    var myGroups = isLoggedIn ? abUser.group_id : [];
 
    function partnerTierFunction() {
      // set up DOM
      $("#header .wrapper").append('<div class="tier_level"></div>');
      // create object for partner tiers
      var myTier = {
        "19": {
          name: "Steel",
          image: "https://cdn.allbound.com/bluescape-ab/2020/09/08233007/BS_Badge_Steel_White.png"
        },
        "23": {
          name: "Cobalt",
          image: "https://cdn.allbound.com/bluescape-ab/2020/09/08233001/BS_Badge_Cobalt_White.png"
        },
        "24": {
          name: "Sky",
          image: "https://cdn.allbound.com/bluescape-ab/2020/09/08233005/BS_Badge_Sky_White.png",
        },
        "25": {
          name: "Sapphire",
          image: "https://cdn.allbound.com/bluescape-ab/2020/09/08233003/BS_Badge_Sapphire_White.png",
        },
      };
 
      // check if the user is in a tier group
      for (var i = 0; i < myGroups.length; i++) {
        // associate tier label to group values
        var groups = myGroups[i];
        var tier = myTier[groups];
        // populate DOM with tier label
        if (tier !== undefined) {
          var $z = $("div.tier_level");
          $z.append('<img src="' + tier["image"] + '">');
          break;
        }
      }
    }
 
    function visibilityDriver() {
      visScenarios.forEach(function(scenario) {
        if (scenario.condition) {
          scenario.outcome();
        }
      })
    }
    
    var visScenarios = [
      {
        condition: isLoggedIn,
        outcome: function () {
          partnerTierFunction();
        },
      },
    ];
    visibilityDriver();
 
}); // end ready function
$(".single-engage #body_block > section > div.main_content.wrapper > article > div > p").html(
  'You do not have permission to view this brands content.<br>Please contact ​<a href="mailto:testemail@allbound.com">testemail.allbound.com</a> to request access.'
);
/*-- CSS deal to opportunity edits --*/
.single-prospect_page ul.tab_nav li:nth-child(4) a { visibility:hidden; }
.deal-child .pipeline_overview h2.page_title,
.deal-child article h1,
#box_tab_related_deals .not_available,
#box_tab_related_deals .existing_deal_btn,
#box_tab_related_deals p,
#box_tab_related_deals h2,
.ab_header_btns .deal_reg .btn_title,
.deal_table thead tr th:nth-child(2),
.pipeline_summary .flex:nth-child(2) h3,
.pipeline_summary .flex:nth-child(3) h3,
.coach_sidebar_title,
.coach_overview__name .coach_overview__label { display:none; }

  // JS deal to opportunity edits
  $('.deal-child .pipeline_overview h2.page_title').html('Register an Opportunity').show();
  $('.deal-child article h1').html('Opportunity Registration').show();
  $('.coach_overview__name .coach_overview__label').html('Opportunity Name').show();
  $('.coach_sidebar_title').html('Opportunity Information').show();
  $('.pipeline_summary .flex:nth-child(2) h3').html('Number of Opportunities').show();
  $('.pipeline_summary .flex:nth-child(3) h3').html('Average Opportunity Size').show();
  $('.deal_table thead tr th:nth-child(2)').html('Opportunity Name').show();
  $('#tiptip_content').hide();
  $('.ab_header_btns .deal_reg').attr('title', 'Create an Opportunity');
  $('.ab_header_btns .deal_reg .btn_title').html('Opp Reg').show();
  $('.single-prospect_page ul.tab_nav li:nth-child(4) a').html('Related Opportunities').css('visibility', 'visible');
  $('#box_tab_related_deals h2').html('Related Opportunities').show();
  $('#box_tab_related_deals p').text('View Opportunities associated with this Prospect Page.').show();
  $('#box_tab_related_deals .existing_deal_btn').text('Link to a related Opportunity').show();
  $('#box_tab_related_deals .not_available').text("You don't have any Opportunities associated with this Prospect Page.").show();
jQuery(document).ready(function ($) {


  function changeHtml() {
    for (el of newHtml) {
      $(el.selector).html(el.changedTo);
    }
  }

  var newHtml = [
    {
      selector: "#signup_form h1.no_companies_allowed",
      changedTo: "REGISTRATION DENIED",
    },

    {
      selector: "#signup_form p.no_companies_allowed",
      changedTo:
        'Sorry, registration is restricted to pre-approved company domains. <a href="https://integrationtesting.allbound.com/"> Please try again</a>  with your company email.<p><br>If you are not currently a partner, please click <a href="https://www.allbound.com/partners/">here</a> to request more information.',
    },
  ];

  changeHtml();


}); //end ready function
jQuery(document).ready(function ($) {

  var isLoggedIn = !!$(".logged-in").length;

  var isDealSubmit = !!$(".page-id-548").length;
  var isSingleDeal = !!$(".single-deal").length;
  var groupIdField = "#input_19_39";

  function scenarioDriver() {
    for (var i = 0; i < scenarios.length; i++) {
      if (scenarios[i].condition) {
        scenarios[i].outcome();
      }
    }
  }

  var scenarios = [
    {
      condition: isLoggedIn,
      page: isDealSubmit || isSingleDeal,

      outcome: function () {
        if (abUser.group_id.indexOf("14") > -1) {
          $(groupIdField).val("Consultants");
        } else if (abUser.group_id.indexOf("15") > -1) {
          $(groupIdField).val("Technology Partners");
        }
      },
    },
  ];

  scenarioDriver();


});
<script type="text/javascript">
    if (window.parent.location.pathname.indexOf("smartedit") <= -1) {
        // Only redirect if NOT in smartedit
    	window.location.replace("/warranty-your-way");
    }else if (window.parent.location.pathname.indexOf("smartedit") >= 0){
    	// IS smartedit, show comment	
       	document.getElementById("redirectJS").style.display = "block";
	}
    
</script>

<h3 id="redirectJS" style="display: none; text-align: center;"> redirect code </h3>
var o = 0;

do{
	alert("do while loop: " + o)
	o++;
} while(o < 10);
var counter = 0;

while(counter < 5) {
alert(counter);
counter++;
}
var numberList = ([1,2,3,4,5,6,7,8,9,10]);

	for (let i = 0; i < numberList.length; i++) {

		console.log(numberList[i]);
	}
var age=20;
if (age < 18) {
	console.log("underage");
} else {
	console.log("let em in!");
}
jQuery(document).ready(function ($) {

  function changeHtml() {
    for (el of newHtml) {
      $(el.selector).text(el.changedTo);
    }
  }

  var newHtml = [
    {
      selector: ".dashboard-minimal .dashboard-quicklinks .btn--minimal--blue",
      changedTo: "View My Partner Manager",
    },

    {
      selector: "#channel_manager .section_title h3",
      changedTo: "My Partner Manager",
    },
  ];

  changeHtml();
}); //end ready function
var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);
function destroyer(arr, ...valsToRemove) {
  return arr.filter(elem => !valsToRemove.includes(elem));
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3, )

function func1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 1

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 3
}

func1(1, 2, 3);
document.querySelector('.message').textContent = 'Correct Number!';
$.fn.showFlex = function() { this.css('display','flex'); }

$(".element").showFlex();
let apiTimeout = setTimeout(fetchAPIData, 1000);

function fetchAPIData(){
    fetch('API_END_POINT')
    .then(res => {
            if(res.statusCode == 200){
                // Process the response and update the view.
                // Recreate a setTimeout API call which will be fired after 1 second.
                apiTimeout = setTimeout(fetchAPIData, 1000);
            }else{
                clearTimeout(apiTimeout);
                // Failure case. If required, alert the user.
            }
    })
    .fail(function(){
         clearTimeout(apiTimeout);
         // Failure case. If required, alert the user.
    });
}
javascript:(function() {  document.querySelector('input:focus').value=document.querySelector('input:focus').value.replace(/(\d{3})(\d{3})(\d{4})/,(m,p1,p2,p3)=>'('+p1+') '+p2+'-'+p3);})();
//You should try running these node commands

//npm init
//npm i express --save
//node . (To restart node)
// Try running the following commands

npm install -g
npm init -y
npm init
function randomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
if (!variable) {
  // When the variable has a falsy value the condition is true.
}
thead.table-costume-bank-preparation {
                tr{
                    th:nth-child(1) {
                        position: -webkit-sticky !important;
                        position: sticky !important;
                        left: 0 !important;
                        width: 24rem !important;
                        max-width: 24rem !important;
                        background-color: #EFF0F9;
                    }

                    th:nth-child(2) {
                        position: -webkit-sticky !important;
                        position: sticky !important;
                        left: 0 !important;
                        width: 12rem !important;
                        max-width: 12rem !important;
                        background-color: #EFF0F9;
                    }

                    th:nth-child(3) {
                        position: -webkit-sticky !important;
                        position: sticky !important;
                        left: 0 !important;
                        width: 12rem !important;
                        max-width: 12rem !important;
                        background-color: #EFF0F9;
                    }

                    th:nth-child(4) {
                        position: -webkit-sticky !important;
                        position: sticky !important;
                        left: 0 !important;
                        width: 12rem !important;
                        max-width: 12rem !important;
                        background-color: #EFF0F9;
                    }

                    th:nth-child(5) {
                        position: -webkit-sticky !important;
                        position: sticky !important;
                        left: 0 !important;
                        width: 12rem !important;
                        max-width: 12rem !important;
                        background-color: #EFF0F9;
                    }
                }
                tr:nth-child(2) th {
                    cursor: pointer !important;
                    min-width: 6rem !important;
                    width: 6rem !important;
                    max-width: 6rem !important;
                    text-align: center;
                }
            }
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

    // implement resource here
	// Invoke the script include that will mutate the response
    var batch = new global.BatchImport(request, response);
	var requestBody = request.body;
	var ticketData = requestBody.data;
	gs.log("***** Nowjobs backoffice api data: " + JSON.stringify(ticketData));
	//gs.log('body length: ' + request.body.data.u_backoffice_candidate.length);
	//if(!request.body.data.u_bo_contact_imp)
		//gs.log('geen contacten');
    batch.process();

})(request, response);
var BatchImport = Class.create();
BatchImport.prototype = {
    initialize: function(request, response) {
        this.logger = new global.GSLog('hohr.csm.backoffice_batch.log', this.type);
        this.logger.includeTimestamp();
        this.request = request;
        this.response = response;
        this.validated = false;
        this.error = false;
        this.errorObj = {
            'statusCode': '',
            'message': '',
            'details': ''
        };
        this.payload;

    },
    process: function() {
        //this.payload = this._processPayload();
        try {
            this.validated = this.validateRequest();
            if (this.validated !== true) {
                this._setResponse();
            }


            this.payload = this._processPayload();

            this._setResponse();
        } catch (e) {
            this.logErr('[process] caught an error: ' + e + '\nstack:\n' + e.stack);
            this._setError(500, 'Internal server error', '');
            this._setResponse();
        }
    },

    validateRequest: function() {
        try {
            this.bodyData = request.body.data;
            if (gs.nil(this.bodyData)) {
                this.logWarning('[validateRequest] Body data is missing: ' + this.bodyData);
                this._setError(400, "Body is missing", "Expecting a body with properties.");
                return false;
            }
        } catch (e) {
            this.logErr('[validateRequest] caught an error: ' + e.message + '\nstack: ' + e.stack);
        }
    },

    _importSet: function() {
        var importSet = new GlideRecord('sys_import_set');
        importSet.initialize();
        importSet.mode = 'asynchronous';
        importSet.state = 'loading';
        importSet.insert();
        return importSet.sys_id;

    },

    _processPayload: function() {
        var importSet;
        var transform;
        var i;
        if (this.request.body.data.u_bo_contact_imp) {
            importSet = this._importSet();
            var contacts = new GlideRecord('u_bo_contact_imp');
            for (i = 0; i < this.request.body.data.u_bo_contact_imp.length; i++) {
				if (this._isMemberOfPowerhouse(this.request.body.data.u_bo_contact_imp[i].u_email) == false) {
                contacts.initialize();
                contacts.u_first_name = this.request.body.data.u_bo_contact_imp[i].u_first_name;
                contacts.u_last_name = this.request.body.data.u_bo_contact_imp[i].u_last_name;
                contacts.u_language = this.request.body.data.u_bo_contact_imp[i].u_language;
                contacts.u_email = this.request.body.data.u_bo_contact_imp[i].u_email;
                contacts.u_phone = this.request.body.data.u_bo_contact_imp[i].u_phone;
                contacts.u_nowjobs_id = this.request.body.data.u_bo_contact_imp[i].u_nowjobs_id;
                if (this.request.body.data.u_bo_contact_imp[i].u_accent_id)
                    contacts.u_accent_id = this.request.body.data.u_bo_contact_imp[i].u_accent_id;
                contacts.sys_import_set = importSet;
                contacts.insert();
				}
            }
            transform = this._transform(importSet, 'u_bo_contact_imp');
        }
        if (this.request.body.data.u_bo_account_imp) {
            importSet = this._importSet();
            var accounts = new GlideRecord('u_bo_account_imp');
            for (i = 0; i < this.request.body.data.u_bo_account_imp.length; i++) {
                accounts.initialize();
                accounts.u_vat_number = this.request.body.data.u_bo_account_imp[i].u_vat_number;
                accounts.u_commercial_name = this.request.body.data.u_bo_account_imp[i].u_commercial_name;
                accounts.u_official_name = this.request.body.data.u_bo_account_imp[i].u_official_name;
                accounts.u_account_manager_office = this.request.body.data.u_bo_account_imp[i].u_account_manager_office;
                accounts.u_phone = this.request.body.data.u_bo_account_imp[i].u_phone;
                accounts.u_nowjobs_id = this.request.body.data.u_bo_account_imp[i].u_nowjobs_id;
                if (this.request.body.data.u_bo_account_imp[i].u_accent_id)
                    accounts.u_accent_id = this.request.body.data.u_bo_account_imp[i].u_accent_id;
                accounts.sys_import_set = importSet;
                accounts.insert();
            }
            transform = this._transform(importSet, 'u_bo_account_imp');
        }
        if (this.request.body.data.u_backoffice_candidate) {
            importSet = this._importSet();
            var candidates = new GlideRecord('u_backoffice_candidate');
            for (i = 0; i < this.request.body.data.u_backoffice_candidate.length; i++) {
                if (this._isMemberOfPowerhouse(this.request.body.data.u_backoffice_candidate[i].u_email) == false) {
                    candidates.initialize();
                    candidates.u_first_name = this.request.body.data.u_backoffice_candidate[i].u_first_name;
                    candidates.u_last_name = this.request.body.data.u_backoffice_candidate[i].u_last_name;
                    candidates.u_language = this.request.body.data.u_backoffice_candidate[i].u_language;
                    candidates.u_email = this.request.body.data.u_backoffice_candidate[i].u_email;
                    candidates.u_phone = this.request.body.data.u_backoffice_candidate[i].u_phone;
                    candidates.u_nowjobs_id = this.request.body.data.u_backoffice_candidate[i].u_nowjobs_id;
                    if (this.request.body.data.u_backoffice_candidate[i].u_accent_id)
                        candidates.u_accent_id = this.request.body.data.u_backoffice_candidate[i].u_accent_id;
                    candidates.u_statute = this.request.body.data.u_backoffice_candidate[i].u_statute;
                    candidates.u_national_nr = this.request.body.data.u_backoffice_candidate[i].u_national_nr;
                    candidates.sys_import_set = importSet;
                    candidates.insert();
                }
            }
            transform = this._transform(importSet, 'u_backoffice_candidate');
        }
        },

    _isMemberOfPowerhouse: function (mail) {
        var member = false;
        var user = new GlideRecord('sys_user');
        user.addQuery('email', mail);
        user.addQuery('sys_class_name', 'sys_user');
        user.query();
        if (user.next()) {
            if (user.company.u_powerhouse) {
                member = true;
            }
        }
        return member;
    },

    _transform: function(importSet, table) {
        var importSetGr = new GlideRecord("sys_import_set");
        importSetGr.get(importSet);
        importSetGr.table_name = table;
        var importSetId = importSetGr.getUniqueValue();
        var importSetRun = new GlideImportSetRun(importSet);
        var importLog = new GlideImportLog(importSetRun, "SOAP Transform");
        var ist = new GlideImportSetTransformer();
        ist.setLogger(importLog);
        ist.setImportSetRun(importSetRun);
        ist.setImportSetID(importSetId);
        ist.setSyncImport(true);
        ist.transformAllMaps(importSetGr);
        if (ist.isError()) {
            gs.log('Error executing the transform');
        }

    },

    logDebug: function(msg) {
        this.logger.logDebug(msg);
    },

    logInfo: function(msg) {
        this.logger.logInfo(msg);
    },

    logWarning: function(msg) {
        this.logger.logWarning(msg);
    },

    type: 'BatchImport'
};
function pipe(...functions) {
    return (...args) => functions.reduce((acc, curr, idx) => idx === 0 ? curr(...args) : curr(acc), args)
}
const namesArray = ['ryu', 'chun-li', 'ryu', 'shaun'];
console.log(namesArray);

// const namesSet = new Set(['ryu', 'chun-li', 'ryu', 'shaun']);
const namesSet = new Set(namesArray);
console.log(namesSet);

// const uniqueNames = [...namesSet];
const uniqueNames = [...new Set(namesArray)];
console.log(uniqueNames);
https://datatables.net/examples/api/counter_columns.html

$(document).ready(function() {
    var t = $('#example').DataTable( {
        "columnDefs": [ {
            "searchable": false,
            "orderable": false,
            "targets": 0
        } ],
        "order": [[ 1, 'asc' ]]
    } );
                 
    t.on( 'draw.dt', function () {
    var PageInfo = $('#example').DataTable().page.info();
         t.column(0, { page: 'current' }).nodes().each( function (cell, i) {
            cell.innerHTML = i + 1 + PageInfo.start;
        } );
    } );
} );
    const cityDetails = data.cityDetails;
    const weather = data.weather;

    // destructure properties
    const { cityDetails, weather } = data;
// async & await

const getTodos = async () => {

  let response = await fetch('json/luigi.json');

  if(response.status !== 200){
    throw new Error('cannot fetch the data');
  }

  let data = await response.json();
  return data;

};

getTodos()
  .then(data => console.log('resolved:', data))
  .catch(err => console.log('rejected:', err.message)); //here err.message
>> promises basic concept
// promise example
const getSomething = () => {

  return new Promise((resolve, reject) => {
    // do something (fetch data)
    // resolve('some data');
    reject('some error');
  });

};

// getSomething().then(data => {
//   console.log('promise resolved:', data);
// }).catch(err => {
//   console.log('promise rejected:', err);
// });

>> promise chaining
const getTodos = (resource) => {

  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();

    request.addEventListener('readystatechange', () => {
  
      if(request.readyState === 4 && request.status === 200){
        const data = JSON.parse(request.responseText);
        resolve(data);
      } else if (request.readyState === 4){
        reject('could not fetch the data');
      }
  
    });
    
    request.open('GET', resource);
    request.send();
  });

};

getTodos('json/luigi.json').then(data => {
  console.log('promise 1 resolved:', data);
  return getTodos('json/mario.json');
}).then(data => {
  console.log('promise 2 resolved:', data);
  return getTodos('json/shaun.json');
}).then(data => {
  console.log('promise 3 resolved:', data);
}).catch(err => {
  console.log('promise rejected:', err);
});
Different between json and javascript object is that all strings in the json has be inside double qoutes.
const buff_to_base64 = (buff) => btoa(String.fromCharCode.apply(null, buff));

const base64_to_buf = (b64) =>
  Uint8Array.from(atob(b64), (c) => c.charCodeAt(null));

const enc = new TextEncoder();
const dec = new TextDecoder();

const getPasswordKey = (password) =>
  window.crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, [
    "deriveKey",
  ]);

const deriveKey = (passwordKey, salt, keyUsage) =>
  window.crypto.subtle.deriveKey(
    {
      name: "PBKDF2",
      salt: salt,
      iterations: 250000,
      hash: "SHA-256",
    },
    passwordKey,
    {
      name: "AES-GCM",
      length: 256,
    },
    false,
    keyUsage
  );

export async function encrypt(secretData, password) {
  try {
    const salt = window.crypto.getRandomValues(new Uint8Array(16));
    const iv = window.crypto.getRandomValues(new Uint8Array(12));
    const passwordKey = await getPasswordKey(password);
    const aesKey = await deriveKey(passwordKey, salt, ["encrypt"]);
    const encryptedContent = await window.crypto.subtle.encrypt(
      {
        name: "AES-GCM",
        iv: iv,
      },
      aesKey,
      enc.encode(secretData)
    );

    const encryptedContentArr = new Uint8Array(encryptedContent);
    let buff = new Uint8Array(
      salt.byteLength + iv.byteLength + encryptedContentArr.byteLength
    );
    buff.set(salt, 0);
    buff.set(iv, salt.byteLength);
    buff.set(encryptedContentArr, salt.byteLength + iv.byteLength);
    const base64Buff = buff_to_base64(buff);
    return base64Buff;
  } catch (e) {
    console.log(`Error - ${e}`);
    return "";
  }
}

export async function decrypt(encryptedData, password) {
  const encryptedDataBuff = base64_to_buf(encryptedData);
  const salt = encryptedDataBuff.slice(0, 16);
  const iv = encryptedDataBuff.slice(16, 16 + 12);
  const data = encryptedDataBuff.slice(16 + 12);
  const passwordKey = await getPasswordKey(password);
  const aesKey = await deriveKey(passwordKey, salt, ["decrypt"]);
  const decryptedContent = await window.crypto.subtle.decrypt(
    {
      name: "AES-GCM",
      iv: iv,
    },
    aesKey,
    data
  );
  return dec.decode(decryptedContent);
}
async function hash(str, iterations = 1000) {
  //Gotta love that crypto API
  const buf = await crypto.subtle.digest(
    "SHA-256",
    new TextEncoder("utf-8").encode(str)
  );
  //One liner from stackoverflow
  let result = Array.prototype.map
    .call(new Uint8Array(buf), (x) => ("00" + x.toString(16)).slice(-2))
    .join("");
  if (iterations === 0) {
    return result;
  } else {
    //Recusive function for multiple iterations
    return await hash(result, iterations - 1);
  }
}
/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive).
 * The value is no lower than min (or the next integer greater than min
 * if min isn't an integer) and no greater than max (or the next integer
 * lower than max if max isn't an integer).
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
const list = document.querySelector('.myList'); // returns HTMLCollection

const myArray = Array.from(list.children);
<div id="buttons"> <!-- Step 1 -->
  <button class="buttonClass">Click me</button>
  <button class="buttonClass">Click me</button>
  <!-- buttons... -->
  <button class="buttonClass">Click me</button>
</div>
<script>
  document.getElementById('buttons')
    .addEventListener('click', event => { // Step 2
      if (event.target.className === 'buttonClass') { // Step 3
        console.log('Click!');
      }
    });
</script>
const numbers = [45, 5, 1, 0, 22, 60, 90, 78];
//normal sort method does not work

numbers.sort( (a, b) {
             return b - a;
             } );

numbers.sort( (a,b ) => b - a );

// if a is greater then we should return -1
// if b is greater then we should return 1
// if a equals b then we should return 0;
let myString = "Hello, World!";
let myRegex = /Hello/;
let result = myRegex.test(myString); // result === true
function e2() {
    var u='',m='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',i=0,rb=Math.random()*0xffffffff|0;
    while(i++<36) {
        var c=m[i-1],r=rb&0xf,v=c=='x'?r:(r&0x3|0x8);
        u+=(c=='-'||c=='4')?c:v.toString(16);rb=i%8==0?Math.random()*0xffffffff|0:rb>>4
    }
    return u
}

console.log(e2())
function uid() {
    // I generate the UID from two parts here 
    // to ensure the random number provide enough bits.
    var firstPart = (Math.random() * 46656) | 0;
    var secondPart = (Math.random() * 46656) | 0;
    firstPart = ("000" + firstPart.toString(36)).slice(-3);
    secondPart = ("000" + secondPart.toString(36)).slice(-3);
    return firstPart + secondPart;
}
if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(nextSource);
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}
function clone(obj) {
    if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    if (obj instanceof Date)
        var temp = new obj.constructor(); //or new Date(obj);
    else
        var temp = obj.constructor();

    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = clone(obj[key]);
            delete obj['isActiveClone'];
        }
    }
    return temp;
}
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
function htmlToImage(html, { x = 0, y = 0, width = 300, height = 400 }) {
  let canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  var ctx = canvas.getContext("2d");
  return new Promise((res) => {
    var xml = toXML(html);
    xml = xml.replace(/\#/g, "%23");
    var data = `data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><foreignObject width="100%" height="100%">${xml}</foreignObject></svg>`;

    var img = new Image();
    img.onload = function () {
      ctx.drawImage(img, x, y, width, height);
      res(canvas.toDataURL());
    };
    img.src = data;
  });
  function toXML(html) {
    var doc = document.implementation.createHTMLDocument("");
    doc.write(html);
    doc.documentElement.setAttribute("xmlns", doc.documentElement.namespaceURI);
    html = new XMLSerializer().serializeToString(doc.body);
    return html;
  }
}
const generate = (meta) => {
  return [
    { charset: "utf-8" },
    { lang: "en" },
    { name: "viewport", content: "width=device-width, initial-scale=1" },
    { name: "format-detection", content: "telephone=no" },
    { name: "title", content: meta.title },
    { name: "author", content: meta.author },
    {
      name: "keywords",
      content: meta.keywords || "",
    },
    { name: "robots", content: "index,follow" },
    { name: "language", content: "English" },
    { name: "description", content: meta.description },
    { name: "theme-color", content: meta.color },
    { name: "og:type", content: "website" },
    { name: "apple-mobile-web-app-title", content: meta.title },
    { name: "og_site_name", content: meta.site || meta.title },
    { name: "og:site_name", content: meta.site || meta.title },
    { name: "og:locale", content: "en_US" },
    { name: "og:url", content: meta.url },
    { name: "og:title", content: meta.title },
    { name: "og:description", content: meta.description },
    { name: "og:image", content: meta.image },
    { name: "twitter:card", content: "summary_large_image" },
    { name: "twitter:url", content: meta.url },
    { name: "twitter:title", content: meta.title },
    { name: "twitter:description", content: meta.description },
    { name: "twitter:image", content: meta.image },
  ].map((i) => {
    var out = { ...i };
    if (!out.hid) {
      out.hid = out.name;
    }
    return out;
  }).map(i => `<meta name=${JSON.stringify(i.name)} content=${JSON.stringify(i.content)}/>`).join('\n');
};
function ripple(el, opts = {}) {
    const time = opts.time || (+el.getAttribute("data-time") || 1000) * 3;
    const color = opts.color || el.getAttribute("data-color") || "currentColor";
    const opacity = opts.opacity || el.getAttribute("data-opacity") || ".3";
    const event = opts.event || el.getAttribute("data-event") || "click";
    el.style.overflow = "hidden";
    el.style.position = "relative";
    el.addEventListener(event, (e) => {
        if (el.disabled) return;
        var ripple_div = document.createElement("DIV");
        ripple_div.style.position = "absolute";
        ripple_div.style.background = `${color}`;
        ripple_div.style.borderRadius = "50%";
        var bx = el.getBoundingClientRect();
        var largestdemensions;
        if (bx.width > bx.height) {
            largestdemensions = bx.width * 3;
        } else {
            largestdemensions = bx.height * 3;
        }
        ripple_div.style.pointerEvents = "none";
        ripple_div.style.height = `${largestdemensions}px`;
        ripple_div.style.width = `${largestdemensions}px`;
        ripple_div.style.transform = `translate(-50%, -50%) scale(0)`;
        ripple_div.style.top = `${e.pageY - (bx.top + window.scrollY)}px`;
        ripple_div.style.left = `${e.pageX - (bx.left + window.scrollX)}px`;
        ripple_div.style.transition = `opacity ${time}ms ease, transform ${time}ms ease`;
        ripple_div.removeAttribute("data-ripple");
        ripple_div.style.opacity = opacity;
        el.appendChild(ripple_div);
        setTimeout(() => {
        ripple_div.style.transform = `translate(-50%, -50%) scale(1)`;
        ripple_div.style.opacity = "0";
        setTimeout(() => {
            ripple_div.remove();
        }, time);
        }, 1);
    });
}
async function manipulate(videoTrack, fn) {
  let canvas = document.createElement("canvas");
  let running = true;
  const ctx = canvas.getContext("2d");
  let video = document.createElement("video");
  video.setAttribute("autoplay", true);
  video.setAttribute("muted", true);
  video.srcObject = createStream(videoTrack);
  videoTrack.addEventListener("ended", () => {
    running = false;
  });
  await new Promise((res) => video.addEventListener("play", res));
  function animate() {
    const { width, height } = videoTrack.getSettings();
    Object.assign(canvas, {
      width,
      height,
    });
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    // Recursively loop
    const frame = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const length = frame.data.length;
    let data = frame.data;
    for (let i = 0; i < length; i += 4) {
      let o = fn({
        red: data[i],
        g: data[i + 1],
        green: data[i + 1],
        blue: data[i + 2],
        alpha: data[i + 3],
      });
      data[i] = o.red;
      data[i + 1] = o.green;
      data[i + 2] = o.blue;
      data[i + 3] = o.alpha;
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.putImageData(frame, 0, 0);
    if (running) {
      requestAnimationFrame(animate);
    }
  }
  requestAnimationFrame(animate);
  let track = get("video", canvas.captureStream(30));
  track.addEventListener("ended", () => {
    running = false;
  })
}
async function quizlet(id){
    let res = await fetch(`https://quizlet.com/webapi/3.4/studiable-item-documents?filters%5BstudiableContainerId%5D=${id}&filters%5BstudiableContainerType%5D=1&perPage=5&page=1`).then(res => res.json())
    let currentLength = 5;
    let token = res.responses[0].paging.token
    let terms = res.responses[0].models.studiableItem;
    let page = 2;
    console.log({token, terms})
    while (currentLength >= 5){
        let res = await fetch(`https://quizlet.com/webapi/3.4/studiable-item-documents?filters%5BstudiableContainerId%5D=${id}&filters%5BstudiableContainerType%5D=1&perPage=5&page=${page++}&pagingToken=${token}`).then(res => res.json());
        terms.push(...res.responses[0].models.studiableItem);
        currentLength = res.responses[0].models.studiableItem.length;
        token = res.responses[0].paging.token;
    }
    return terms;
}
/**
 * Generates a data URL of the current favicon with a number added on top.
 * @param {Object} options
 * @param {String} [options.type = "image/png"] The mime type of the image to return.
 * @param {String} [options.text = ""] The text to display on the favicon, if left blank will simply show a dot on the favicon.
 * @param {String} [options.background = "white"] A CSS color for the background of the notification badge.
 * @param {String} [options.color = "white"] A CSS color for the color of the text on the notification badge.
 * @param {Number} [options.size = 10] The size of the notification badge. The badge generated will be size * 2 pixels in width and height, then added on top of the current favicon.
 * @param {String} [options.pos = "bottom-right"] The position of the badge, either "bottom-right", "top-right", "bottom-left" or "top-left"
 * @param {String} [options.font = "Monospace"] The font to use
 * @param {String} [options.iconUrl] The URL of the base icon, if not provided will be the current favicon.
 * @returns {Promise.<string>} Returns a promise that resolves into the data URL of the icon generated.
 * @example
 *   getIcon({
 *     text: "1",
 *     pos: "top-right",
 *   }).then((data_url) => {
 *     document.querySelector("link[rel='icon']").href = data_url;
 *   });
 */
async function getIcon({
    type = "image/png",
    text = "",
    background = "white",
    color = "black",
    size = 10,
    pos = "bottom-right",
    font = "Monospace",
    iconUrl
}) {
    const icon = iconUrl || document.querySelector("link[rel='icon']")?.href;
    let data = await getData(icon);
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    let img = await loadedImg(data);
    let notif_img = await loadedImg(getNotifData(text, size));
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
    let x = 0;
    let y = 0;
    let sections = pos.trim().toLowerCase().split("-");
    sections[0] === "bottom" && (y = canvas.height - size * 2);
    sections[1] == "right" && (x = canvas.width - size * 2);
    ctx.drawImage(notif_img, x, y);
    return canvas.toDataURL(type);

    function loadedImg(src) {
        return new Promise((res) => {
            let img = new Image();
            img.src = src;
            img.onload = () => res(img);
        });
    }

    function getNotifData(text, size) {
        const _canvas = document.createElement("canvas");
        _canvas.width = size * 2;
        _canvas.height = size * 2;
        let c = _canvas.getContext("2d");
        const inset = size;
        c.beginPath();
        c.fillStyle = background;
        c.arc(inset, inset, size, 0, 2 * Math.PI);
        c.fill();
        c.font = `${size * 1.5}px ${font}`;
        c.fillStyle = color;
        c.textBaseline = "top";
        c.fillText(text, inset / 2, inset / 2);
        return _canvas.toDataURL("image/png");
    }

    function getData(url) {
        return new Promise(async (res, reject) => {
            let blob = await fetch(url).then((r) => r.blob());
            let dataUrl = await new Promise((resolve) => {
                let reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.readAsDataURL(blob);
            });
            res(dataUrl);
        });
    }
}
function compress(string, encoding) {
  const byteArray = new TextEncoder().encode(string);
  const cs = new CompressionStream(encoding);
  const writer = cs.writable.getWriter();
  writer.write(byteArray);
  writer.close();
  return new Response(cs.readable).arrayBuffer();
}

function decompress(byteArray, encoding) {
  const cs = new DecompressionStream(encoding);
  const writer = cs.writable.getWriter();
  writer.write(byteArray);
  writer.close();
  return new Response(cs.readable).arrayBuffer().then(function (arrayBuffer) {
    return new TextDecoder().decode(arrayBuffer);
  });
}
async function getToken(key, options) {
  let { default: JsSHA } = await import(
    "https://cdn.skypack.dev/pin/jssha@v3.2.0-7ih4rHNyCNAz1Lqwkzy4/mode=imports,min/optimized/jssha.js"
  );
  options = {
    period: 30,
    algorithm: "SHA-1",
    digits: 6,
    timestamp: Date.now(),
    ...options,
  };
  key = base32tohex(key);
  let epoch = Math.round(options.timestamp / 1000.0);
  let time = leftpad(dec2hex(Math.floor(epoch / options.period)), 16, "0");
  let shaObj = new JsSHA(options.algorithm, "HEX");
  shaObj.setHMACKey(key, "HEX");
  shaObj.update(time);
  let hmac = shaObj.getHMAC("HEX");
  let offset = hex2dec(hmac.substring(hmac.length - 1));
  let otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec("7fffffff")) + "";
  otp = otp.substr(Math.max(otp.length - options.digits, 0), options.digits);
  return otp;

  function hex2dec(s) {
    return parseInt(s, 16);
  }

  function dec2hex(s) {
    return (s < 15.5 ? "0" : "") + Math.round(s).toString(16);
  }

  function base32tohex(base32) {
    let base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
      bits = "",
      hex = "";

    base32 = base32.replace(/=+$/, "");

    for (let i = 0; i < base32.length; i++) {
      let val = base32chars.indexOf(base32.charAt(i).toUpperCase());
      if (val === -1) throw new Error("Invalid base32 character in key");
      bits += leftpad(val.toString(2), 5, "0");
    }

    for (let i = 0; i + 8 <= bits.length; i += 8) {
      let chunk = bits.substr(i, 8);
      hex = hex + leftpad(parseInt(chunk, 2).toString(16), 2, "0");
    }
    return hex;
  }

  function leftpad(str, len, pad) {
    if (len + 1 >= str.length) {
      str = Array(len + 1 - str.length).join(pad) + str;
    }
    return str;
  }
}
function matrix({
	selector = "canvas",
	el = null,
	color = "#0e0",
	font = "15pt monospace",
	fps = 40,
	size = 20,
	width = null,
	height = null,
	getChar = () => String.fromCharCode(Math.random() * 128),
} = {}) {
	const canvas = el || document.querySelector(selector);
	if (window.MATRIX_INTERVAL) {
		clearInterval(window.MATRIX_INTERVAL);
	}
	const ctx = canvas.getContext("2d");
	const w = (canvas.width = width || canvas.parentElement.offsetWidth);
	const h = (canvas.height = width || canvas.parentElement.offsetHeight);
	const cols = Math.floor(w / size) + 1;
	const ypos = Array(cols).fill(0);

	// Clear it
	ctx.clearRect(0, 0, w, h);
	ctx.fillStyle = "#000";
	ctx.fillRect(0, 0, w, h);

	function _matrix() {
		ctx.fillStyle = "#0001";
		ctx.fillRect(0, 0, w, h);
		ctx.font = font;
		ypos.forEach((y, ind) => {
			const x = ind * size;
			// This is what gets passed to the functions
			let args = {
				x,
				y,
				width: w,
				height: h
			};
			const text = getChar(args);
			let col;
			if (typeof color === "function") {
				col = color(args);
			} else {
				col = color;
			}
			ctx.fillStyle = col;
			ctx.fillText(text, x, y);
			if (y > 100 + Math.random() * 10000) ypos[ind] = 0;
			else ypos[ind] = y + size;
		});
	}

	window.MATRIX_INTERVAL = setInterval(_matrix, 1000 / fps);
}

matrix({
	selector: "canvas",
	color: ({
		x,
		y,
		width,
		height
	}) => {
		// Nice diagonal gradient:
		// y / height = percentage down, toString(16) = hex char
		return `#${Math.floor((y / height) * 16).toString(16)}f${Math.floor(
			(x / width) * 16
		).toString(16)}`;
	},
	font: "8px monospace",
	fps: 20,
	size: 8,
	width: window.innerWidth,
	height: window.innerHeight,
});
const sanitize = (html, tags = undefined, attributes = undefined) => {
    var attributes = attributes || [
      { attribute: "src", tags: "*", regex: /^(?:https|http|\/\/):/ },
      { attribute: "href", tags: "*", regex: /^(?!javascript:).+/ },
      { attribute: "width", tags: "*", regex: /^[0-9]+$/ },
      { attribute: "height", tags: "*", regex: /^[0-9]+$/ },
      { attribute: "id", tags: "*", regex: /^[a-zA-Z]+$/ },
      { attribute: "class", tags: "*", regex: /^[a-zA-Z ]+$/ },
      { attribute: "value", tags: ["INPUT", "TEXTAREA"], regex: /^.+$/ },
      { attribute: "checked", tags: ["INPUT"], regex: /^(?:true|false)+$/ },
      {
        attribute: "placeholder",
        tags: ["INPUT", "TEXTAREA"],
        regex: /^.+$/,
      },
      {
        attribute: "alt",
        tags: ["IMG", "AREA", "INPUT"],
        //"^" and "$" match beggining and end
        regex: /^[0-9a-zA-Z]+$/,
      },
      { attribute: "autofocus", tags: ["INPUT"], regex: /^(?:true|false)+$/ },
      { attribute: "for", tags: ["LABEL", "OUTPUT"], regex: /^[a-zA-Z0-9]+$/ },
    ]
    var tags = tags || [
      "I",
      "P",
      "B",
      "BODY",
      "HTML",
      "DEL",
      "INS",
      "STRONG",
      "SMALL",
      "A",
      "IMG",
      "CITE",
      "FIGCAPTION",
      "ASIDE",
      "ARTICLE",
      "SUMMARY",
      "DETAILS",
      "NAV",
      "TD",
      "TH",
      "TABLE",
      "THEAD",
      "TBODY",
      "NAV",
      "SPAN",
      "BR",
      "CODE",
      "PRE",
      "BLOCKQUOTE",
      "EM",
      "HR",
      "H1",
      "H2",
      "H3",
      "H4",
      "H5",
      "H6",
      "DIV",
      "MAIN",
      "HEADER",
      "FOOTER",
      "SELECT",
      "COL",
      "AREA",
      "ADDRESS",
      "ABBR",
      "BDI",
      "BDO",
    ]

    attributes = attributes.map((el) => {
      if (typeof el === "string") {
        return { attribute: el, tags: "*", regex: /^.+$/ }
      }
      let output = el
      if (!el.hasOwnProperty("tags")) {
        output.tags = "*"
      }
      if (!el.hasOwnProperty("regex")) {
        output.regex = /^.+$/
      }
      return output
    })
    var el = new DOMParser().parseFromString(html, "text/html")
    var elements = el.querySelectorAll("*")
    for (let i = 0; i < elements.length; i++) {
      const current = elements[i]
      let attr_list = get_attributes(current)
      for (let j = 0; j < attr_list.length; j++) {
        const attribute = attr_list[j]
        if (!attribute_matches(current, attribute)) {
          current.removeAttribute(attr_list[j])
        }
      }
      if (!tags.includes(current.tagName)) {
        current.remove()
      }
    }
    return el.documentElement.innerHTML
    function attribute_matches(element, attribute) {
      let output = attributes.filter((attr) => {
        let returnval =
          attr.attribute === attribute &&
          (attr.tags === "*" || attr.tags.includes(element.tagName)) &&
          attr.regex.test(element.getAttribute(attribute))
        return returnval
      })

      return output.length > 0
    }
    function get_attributes(element) {
      for (
        var i = 0, atts = element.attributes, n = atts.length, arr = [];
        i < n;
        i++
      ) {
        arr.push(atts[i].nodeName)
      }
      return arr
    }
  }
let etiqueta = document.querySelectorAll('.etiqueta');

etiqueta.forEach(link => {
    
    link.addEventListener("mouseover",() => { // mouseover cuando el mause entra al elemento etiqueta
	
        const t = link.getBoundingClientRect(); // calcula la posición de link(etiqueta) 
	let hijo = link.querySelectorAll('.hijo');

	hijo.forEach(l1 => {

	    l1.classList.add("edd1"); // solo quita un class, que le quita color red y la escala

	    function mover(e){

	       let left = e.pageX;
	       let top = e.pageY;
	       l1.style.left =  left - t.left + "px";
	       l1.style.top =   top - t.top  + "px";
	    };
	l1.parentNode.addEventListener("mousemove", mover);

	});
    });

    link.addEventListener("mouseleave",() => {// mouseleave cuando el mouse salio del elemento etiqueta
	let hijo = link.querySelectorAll('.hijo');
	hijo.forEach(l2 => {
        l2.classList.remove("edd1"); // le solo quita un class, que le quita color red y la escala 1
	l2.parentNode.onmousemove = null;
	});
    });
});

//HTML

<div class="box">
  <div class="etiqueta">
  <div class="hijo"></div>
  </div>
</div> 

<div class="box">
  <div class="etiqueta">
  <div class="hijo"></div>
  </div>
</div> 

//css
.box{
width: 300px;
height: 300px;
border: solid 1px black;
}
.etiqueta{
width:100px;
height:100px;
position: absolute;
left:50px;
top:50px;
background: green;
overflow: hidden;
position:relative;
}
.hijo{
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: blue;
transform: scale(0) translate(-50%,-50%); //posiciona el inicio 
transition: transform 0.9s ease;
}
.edd1{
transform:scale(5) translate(-50%,-50%); // posiciona cuando ya sufrio la escala 5
transform-origin: 0% 0%;
background-color: red;
} 

if (meta && (meta['total'] >= 40)) {
                pagination += (`<nav class="navigation mt-5">
                    <div>
                        <span class="pagination-detail">${ meta.to } dari ${ meta.total } siswa</span>
                    </div>
                    <ul class="pagination">
                        <li class="page-item ${ (currentPage ?? 1) - 1 <= 0 ? 'disabled' : '' }">
                            <a class="page-link" onclick="(getStudents('${grade}','${status}','${ 1 }'))" tabindex="-1">&lt;</a>
                        </li>
                `)
                if (meta.last_page <= 5) {
                    page_first = 1;
                    page_last = meta.last_page;
                } else {
                    if (currentPage <= 3) {
                        page_first = 1;
                        page_last = 5;
                    } else if (currentPage >= meta.last_page - 2) {
                        page_first = meta.last_page - 4;
                        page_last = meta.last_page;
                    } else {
                        page_first = currentPage - 2;
                        page_last = currentPage + 2;
                    }
                    page_final = meta.last_page;
                }
                for (page_first; page_first <= page_last; page_first++) {
                    if (page_first == currentPage) {
                        pagination += (`
                        <li class="page-item active">
                            <a class="page-link" onclick="(getStudents('${grade}','${status}','${ page_first }'))">${ page_first }</a>
                        </li>`)
                    } else {
                        pagination += (`
                        <li class="page-item">
                            <a class="page-link" onclick="(getStudents('${grade}','${status}','${ page_first }'))">${ page_first }</a>
                        </li>`)
                    }
                }

                pagination += (`
                        <li class="page-item ${((currentPage ?? 1) + 1) > meta.last_page ? 'disabled' : '' }">
                            <a class="page-link" onclick="(getStudents('${grade}','${status}','${ meta.last_page }'))">&gt;</a>
                        </li>
                    </ul>
                </nav>
                `)
            }
function shuffle(array) {
  let currentIndex = array.length,  randomIndex;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }

  return array;
}

// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);
var playBtn = document.getElementById('play');
var stopBtn = document.getElementById('stop');
var playSound = function() {
   audio.play();
};
playBtn.addEventListener('click', playSound, false);
stopBtn.addEventListener('click', function(){audio.pause()}, false);
var audio = new Audio("soundfile.wav");

document.onclick = function() {
  audio.play();
}
var audio = new Audio("folder_name/audio_file.mp3");
audio.play();
var audio = new Audio('audio_file.mp3');
audio.play();
    btns = document.getElementsByClassName("saveBtn");
    for (var i = 0; i < btns.length; i++) {
        btns[i].addEventListener("click", function () {
			//Add function here
        });
    }
//Por tanto, deberías usar document.documentElement en lugar de document.firstChild para obtener el //elemento raíz.

           var box1=document.getElementById("box1");
           document.addEventListener("mousemove", function(e){
           var st=document.documentElement.scrollTop;
               //console.log(st);
               // Obtener las coordenadas del mouse
               var left= e.clientX;
               var top= e.clientY;
               box1.style.left=left+st+"px";
               box1.style.top=top+st+"px";
           });
        };

//   <box id="box1"></box>
/*
     #box1{
            width: 100px;
            height: 100px;
            background-color: blueviolet;
            position: absolute;
        }
*/
let etiqueta = document.querySelectorAll('.etiqueta');

etiqueta.forEach(link => {
    link.addEventListener("mouseover",() => {
      let hijo = link.querySelectorAll('.hijo');
      
      hijo.forEach(l1=>{
        l1.classList.add("edd1");
      });
   });

    link.addEventListener("mouseleave",() => {
      let hijo = link.querySelectorAll('.hijo');
    
      hijo.forEach(l1=>{
        l1.classList.remove("edd1");
      });
   });
});

//css 
body{
display: flex;
}
.box{
width: 200px;
height: 200px;
border: solid 1px black;
}
.etiqueta{
width:100px;
height:100px;
position: absolute;
left:50px;
top:50px;
background: green;
overflow: hidden;
position:relative;
}
.hijo{
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: blue;
transition: all 0.2s ease;
transform: scale(0); /*desaparece el elemento hijo*/
}
.edd1{ /* la class que se agrega y se quita*/
background-color: red;
transform: scale(1); /*reaparece el elemento hijo con el mause al centro*/
};

//html
<div class="box">
  <div class="etiqueta">
  <div class="hijo"></div>
  </div>
</div> 

<div class="box">
  <div class="etiqueta">
  <div class="hijo"></div>
  </div>
</div>
async function renderAllStudent(params) {
    const promisesEach = arrStudentGroup.map((d) =>  getStudents(d.id, true) );
}
function escalateIncident() {
    var answer = confirm("Are you sure you want to cancel this record?");
    //Set the 'Incident state' and 'State' values to 'Resolved', and display mandatory fields
    if (answer == true) {
        g_form.setValue('incident_state', 6);
        g_form.setValue('state', 6);
        g_form.setValue('resolved_by', g_user.userID);
		gsftSubmit(null, g_form.getFormElement(), 'resolve_incident'); //MUST call the 'Action 	name' set in this UI Action
    } else {
        return false;
    }
}
function download(content, filename, contentType) {
  if (!contentType) contentType = "application/octet-stream";
  var a = document.createElement("a");
  var blob = new Blob([content], { type: contentType });
  a.href = window.URL.createObjectURL(blob);
  a.download = filename;
  a.click();
}

download(csvContent, 'listSimulationRunTimes.csv', 'text/csv');
// set global variables
const limit = 10000; // How many points can be on the graph before sliding occurs
const refreshInterval = 100; // Time between refresh intervals

// set functions to retrieve
function getData1() {
  if (listMeanTimeToClear.length > 0) {
    return listMeanTimeToClear[listMeanTimeToClear.length - 1];
  } else {
    return 0;
  }
}

// set chart layout
const layout1 = {
  title: {
    text: "<b>Average Time Per Passenger in This Simulation</b>",
  },
  paper_bgcolor: "rgba(0,0,0,0)",
  plot_bgcolor: "rgba(0,0,0,0)",
  xaxis: { title: "Number of passengers", rangemode: "tozero" },
  yaxis: { title: "Average time taken per passenger (s)", rangemode: "tozero" },
  font: { family: "Graphik", size: 11 },
};

// plot all charts
Plotly.newPlot(
  "tester",
  [
    {
      y: [getData1()],
      mode: "lines",
      line: {
        color: "rebeccapurple",
        width: 1,
      },
    },
  ],
  layout1,
  { responsive: true }
);

// set refresh interval and graph limit
var cnt = 0;

// to extend plot
if (isRunning == true) {
  Plotly.extendTraces("tester", { y: [[getData1()]] }, [0]);
  cnt++;
  if (cnt > limit) {
    Plotly.relayout("tester", {
      xaxis: {
        range: [cnt - limit, cnt],
      },
    });
  }
}
// One of the functions that react to the dropdown menus being changed and
// to prevent duplicate stations.
function onChange1() {
  if (isRunning || isPaused) {
    alert(
      "Please reset the model first before changing this parameter. Changing the parameter will reset the simulation."
    );
  } else {
    var choice1 = document.getElementsByName("choices1")[0].value;
    if (choice1 == "none") {
      let position2 = getKeyByValue(positions, 2);
      positions[position2] = 0;
    } else {
      let position2 = getKeyByValue(positions, 2);
      let position3 = getKeyByValue(positions, 3);
      let position4 = getKeyByValue(positions, 4);
      if (choice1 == position3 || choice1 == position4) {
        alert("Duplicates found. Please choose a different station.");
        let select = document.querySelector("#select1");
        select.value = "none";
      } else {
        positions[choice1] = 2;
      }
      positions[position2] = 0;
    }
    redrawWindow();
  }
}

// Function to track changes in the input value boxes.
function changeProb() {
  if (isRunning || isPaused) {
    alert(
      "Please reset the model first before changing this parameter. Changing the parameter will reset the simulation."
    );
  } else {
    probArrival = 1 / Number(document.getElementById("probArrival").value);
    probImmigration =
      1 / Number(document.getElementById("probImmigration").value);
    probTesting = 1 / Number(document.getElementById("probTesting").value);
    probCovid = Number(document.getElementById("probCOVID").value);
    testingTime = Number(document.getElementById("timeTest").value);
    probFindBaggage = Number(document.getElementById("probBaggage").value);
    animationDelay = Number(document.getElementById("animationDelay").value);
    passengerCount = Number(document.getElementById("passengerCount").value);
    simulationRuns = Number(document.getElementById("simulationRuns").value);
    randomChosenQueue = Number(
      document.getElementById("randomChosenQueue").value
    );
  }
}

// Value safety for the input boxes
function runSim() {
  let choice1 = document.getElementsByName("choices1")[0].value;
  let choice2 = document.getElementsByName("choices2")[0].value;
  let choice3 = document.getElementsByName("choices3")[0].value;
  isPaused = false;
  changeProb();

  if (choice1 == "none" && choice2 == "none" && choice3 == "none") {
    alert("Please make at least one station choice.");
  } else if (isRunning) {
    alert("Already running.");
  } else if (
    isNaN(probArrival) ||
    isNaN(probCovid) ||
    isNaN(probImmigration) ||
    isNaN(probTesting) ||
    isNaN(probFindBaggage) ||
    isNaN(testingTime) ||
    isNaN(animationDelay) ||
    isNaN(passengerCount) ||
    isNaN(simulationRuns) ||
    isNaN(randomChosenQueue)
  ) {
    alert("At least one of the inputs is not a number.");
  } else {
    isRunning = true;
    simTimer = window.setInterval(simStep, animationDelay);
  }
}
function createImmigrationOfficers() {
  if (positions.immigration > 0) {
    for (let i = 1; i <= numImmigrationOfficers; i++) {
      let newRow = (height * i) / (numImmigrationOfficers + 1);
      newRow = newRow.toFixed(0);

      let newCol = (width * (positions.immigration - 1)) / (numStations + 1);
      newCol = newCol.toFixed(0);

      let newImmigrationOfficer = {
        id: i,
        type: ICAOFFICER,
        label: "ICAOfficer",
        row: newRow,
        col: newCol,
        state: "IDLE",
      };

      objects.immigration.push(newImmigrationOfficer);
    }
  } else {
    objects.immigration = [];
  }
}

function createImmigrationQueues() {
  if (positions.immigration > 0) {
    for (let i = 1; i <= numImmigrationOfficers; i++) {
      let newRow = (height * i) / (numImmigrationOfficers + 1);
      newRow = newRow.toFixed(0);

      let newCol = (width * (positions.immigration - 1)) / (numStations + 1);
      newCol -= 60;
      newCol = newCol.toFixed(0);

      let newImmigrationQueue = {
        id: i,
        row: newRow,
        col: newCol,
        state: IDLE,
        stack: 0,
      };

      objects.immigrationQueue.push(newImmigrationQueue);
    }
  } else {
    objects.immigrationQueue = [];
  }
}
var positions = {
  arrivals: 0,
  immigration: 0,
  testing: 0,
  baggage: 0,
  exiting: 5,
  undefined: 0,
};

var objects = {
  immigration: [],
  immigrationQueue: [],
  passengers: [],
  testing: [],
  testingBox: [],
  testingQueue: [],
  baggage: [],
  baggageQueue: [],
};

// Get the key of a certain value by going through
// the whole object.
function getKeyByValue(object, value) {
  return Object.keys(object).find((key) => object[key] === value);
}

// How to access values through keys
objects.immigration == []; // true
let newString = immigration;
objects[newString] == []; // true
function updatePassenger(index) {
  index = Number(index);
  let passenger = objects.passengers[index];
  let row = Number(passenger.row);
  let col = Number(passenger.col);
  let state = passenger.state;
  let queueState = passenger.queueState;
  let chosenQueue = Number(passenger.chosenQueue);

  let hasArrived =
    Math.abs(Number(passenger.targetRow) - row) +
      Math.abs(Number(passenger.targetCol) - col) ==
    0;

  switch (state) {
    case "immigration":
      if (queueState == "immigrationQueue" && hasArrived) {
        if (
          col == Number(objects[queueState][chosenQueue].col) + 50 &&
          objects.immigration[chosenQueue].state == "IDLE"
        ) {
          passenger.queueState = "none";
          passenger.targetRow =
            Number(objects.immigration[chosenQueue].row) + 3;
          passenger.targetCol =
            Number(objects.immigration[chosenQueue].col) - 1;
          let newStack =
            Number(objects.immigrationQueue[chosenQueue].stack) - 1;
          objects.immigrationQueue[chosenQueue].stack = newStack;
          objects.immigration[chosenQueue].state = "BUSY";
        } else if (col < Number(objects[queueState][chosenQueue].col) + 50) {
          let filledCol = objects.passengers.filter(function (i) {
            return i.col == col + 1 && i.row == row;
          });

          if (filledCol.length == 0) {
            passenger.targetCol = col + 1;
          }
        }
      } else if (queueState == "none" && hasArrived) {
        if (Math.random() < probImmigration) {
          // TODO Create function callable by the different states.
          // ? Could probably do a recursive function for this.
          objects.immigration[chosenQueue].state = "IDLE";
          let station = Number(passenger.station);
          station += 1;
          let newState = getKeyByValue(positions, station);
          if (newState == undefined) {
            newState = getKeyByValue(positions, station + 1);
            station += 1;
            if (newState == undefined) {
              newState = getKeyByValue(positions, station + 1);
              station += 1;
            } // Final state if nothing else will be "out".
          }

          if (newState == "exiting") {
            passenger.state = "exiting";
            passenger.targetCol = width;
            passenger.targetRow = height / 2;
          } else {
            passenger.state = newState;
            queueState = newState + "Queue";
            passenger.queueState = queueState;

            function chosenQueueRectifier(chosenQueue) {
              //* Recursive function when having mismatched station lengths.
              if (chosenQueue >= objects[queueState].length) {
                chosenQueue -= 1;
                return chosenQueueRectifier(chosenQueue);
              } else {
                return chosenQueue;
              }
            }

            chosenQueue = chosenQueueRectifier(chosenQueue);

            for (let i in objects[queueState]) {
              if (i !== chosenQueue) {
                if (
                  Number(objects[queueState][i].stack) <
                  Number(objects[queueState][chosenQueue].stack)
                ) {
                  chosenQueue = Number(i);
                }
              }
            }

            if (Math.random() < randomChosenQueue) {
              chosenQueue = Math.floor(
                Math.random() * objects[queueState].length
              );
            }

            let stackOverflow = 0;

            if (Number(objects[queueState][chosenQueue].stack) > 50) {
              stackOverflow =
                Number(objects[queueState][chosenQueue].stack) - 50;
            }

            passenger.targetRow =
              Number(objects[queueState][chosenQueue].row) + 3;
            passenger.targetCol =
              Number(objects[queueState][chosenQueue].col) - stackOverflow;
            passenger.station = station;
            passenger.chosenQueue = chosenQueue;
            let newStack = Number(objects[queueState][chosenQueue].stack) + 1;
            objects[queueState][chosenQueue].stack = newStack;
          }
        }
      }
      break;
    case "testing":
      if (queueState == "testingQueue" && hasArrived) {
        if (
          col == Number(objects[queueState][chosenQueue].col) + 50 &&
          objects.testing[chosenQueue].state == "IDLE"
        ) {
          passenger.queueState = "testBox";
          passenger.targetRow = Number(objects.testing[chosenQueue].row) + 3;
          passenger.targetCol = Number(objects.testing[chosenQueue].col) - 1;
          let newStack = Number(objects.testingQueue[chosenQueue].stack) - 1;
          objects.testingQueue[chosenQueue].stack = newStack;
          objects.testing[chosenQueue].state = "BUSY";
        } else if (col < Number(objects[queueState][chosenQueue].col) + 50) {
          let filledCol = objects.passengers.filter(function (i) {
            return i.col == col + 1 && i.row == row;
          });

          if (filledCol.length == 0) {
            passenger.targetCol = col + 1;
          }
        }
      } else if (queueState == "testBox" && hasArrived) {
        if (Math.random() < probTesting) {
          passenger.queueState = "enteringTestBox";
          passenger.targetCol = Number(objects.testingBox[0].col) - 1;
          objects.testing[chosenQueue].state = "IDLE";
        }
      } else if (queueState == "enteringTestBox" && hasArrived) {
        let boxWidth = Number(objects.testingBox[0].width);
        let boxHeight = Number(objects.testingBox[0].height);
        let boxRow = Number(objects.testingBox[0].row);
        let boxCol = Number(objects.testingBox[0].col);
        let newCol;
        let newRow;

        let overlapping = true;
        while (overlapping) {
          let count = 1;
          let randRow = Math.floor(Math.random() * boxHeight);
          let randCol = Math.floor(Math.random() * boxWidth);
          newRow = boxRow + randRow;
          newCol = boxCol + randCol;

          let overlappedList = objects.passengers.filter(function (d) {
            return d.targetRow == newRow && d.targetCol == newCol;
          });

          if (overlappedList.length == 0) {
            overlapping = false;
          }

          // ! DEFINE BEHAVIOUR WHEN BOX IS FULL (UNLIKELY, BUT STILL).
          // * FOR NOW, IF BOX IS FULL, ALLOW OVERLAP.
          if (count > boxWidth * boxHeight) {
            overlapping = false;
          }
        }

        passenger.targetCol = newCol;
        passenger.targetRow = newRow;
        passenger.queueState = "waiting";
      } else if (queueState == "waiting" && hasArrived) {
        passenger.timeWaited = Number(passenger.timeWaited) + 1;
        if (passenger.timeWaited >= testingTime && passenger.covid) {
          passenger.state = "covid";
          passenger.targetRow = 0;
        } else if (passenger.timeWaited >= testingTime) {
          let station = Number(passenger.station);
          station += 1;
          let newState = getKeyByValue(positions, station);
          if (newState == undefined) {
            newState = getKeyByValue(positions, station + 1);
            station += 1;
            if (newState == undefined) {
              newState = getKeyByValue(positions, station + 1);
              station += 1;
            } // Final state if nothing else will be "out".
          }

          if (newState == "exiting") {
            passenger.state = "exiting";
            passenger.targetCol = width;
            passenger.targetRow = height / 2;
          } else {
            passenger.state = newState;
            queueState = newState + "Queue";
            passenger.queueState = queueState;

            function chosenQueueRectifier(chosenQueue) {
              //* Recursive function when having mismatched station lengths.
              if (chosenQueue >= objects[queueState].length) {
                chosenQueue -= 1;
                return chosenQueueRectifier(chosenQueue);
              } else {
                return chosenQueue;
              }
            }

            chosenQueue = chosenQueueRectifier(chosenQueue);

            for (let i in objects[queueState]) {
              if (i !== chosenQueue) {
                if (
                  Number(objects[queueState][i].stack) <
                  Number(objects[queueState][chosenQueue].stack)
                ) {
                  chosenQueue = Number(i);
                }
              }
            }

            if (Math.random() < randomChosenQueue) {
              chosenQueue = Math.floor(
                Math.random() * objects[queueState].length
              );
            }

            let stackOverflow = 0;

            if (Number(objects[queueState][chosenQueue].stack) > 50) {
              stackOverflow =
                Number(objects[queueState][chosenQueue].stack) - 50;
            }

            passenger.targetRow =
              Number(objects[queueState][chosenQueue].row) + 3;
            passenger.targetCol =
              Number(objects[queueState][chosenQueue].col) - stackOverflow;
            passenger.station = station;
            passenger.chosenQueue = chosenQueue;
            let newStack = Number(objects[queueState][chosenQueue].stack) + 1;
            objects[queueState][chosenQueue].stack = newStack;
          }
        }
      }
      break;
    case "baggage":
      if (queueState == "baggageQueue" && hasArrived) {
        if (col == Number(objects[queueState][chosenQueue].col) + 50) {
          let newStack = Number(objects.baggageQueue[chosenQueue].stack) - 1;
          objects.baggageQueue[chosenQueue].stack = newStack;
          passenger.queueState = "gettingBaggage";
          passenger.targetCol = Number(objects.baggage[0].col) - 1;
          // objects.testing[chosenQueue].state = "BUSY";
        } else if (col < Number(objects[queueState][chosenQueue].col) + 50) {
          let filledCol = objects.passengers.filter(function (i) {
            return i.col == col + 1 && i.row == row;
          });

          if (filledCol.length == 0) {
            passenger.targetCol = col + 1;
          }
        }
      } else if (queueState == "gettingBaggage" && hasArrived) {
        let boxWidth = Number(objects.baggage[0].width);
        let boxHeight = Number(objects.baggage[0].height);
        let boxRow = Number(objects.baggage[0].row);
        let boxCol = Number(objects.baggage[0].col);
        let newCol;
        let newRow;

        let overlapping = true;
        while (overlapping) {
          let count = 1;
          let randRow = Math.floor(Math.random() * boxHeight);
          let randCol = Math.floor(Math.random() * boxWidth);
          newRow = boxRow + randRow;
          newCol = boxCol + randCol;

          let overlappedList = objects.passengers.filter(function (d) {
            return d.targetRow == newRow && d.targetCol == newCol;
          });

          if (overlappedList.length == 0) {
            overlapping = false;
          }

          // ! DEFINE BEHAVIOUR WHEN BOX IS FULL (UNLIKELY, BUT STILL).
          // * FOR NOW, IF BOX IS FULL, ALLOW OVERLAP.
          if (count > boxWidth * boxHeight) {
            overlapping = false;
          }
        }

        passenger.targetCol = newCol;
        passenger.targetRow = newRow;
        passenger.queueState = "reachedBaggage";
      } else if (queueState == "reachedBaggage" && hasArrived) {
        if (Math.random() < probFindBaggage) {
          let station = Number(passenger.station);
          station += 1;
          let newState = getKeyByValue(positions, station);
          if (newState == undefined) {
            newState = getKeyByValue(positions, station + 1);
            station += 1;
            if (newState == undefined) {
              newState = getKeyByValue(positions, station + 1);
              station += 1;
            } // Final state if nothing else will be "out".
          }

          if (newState == "exiting") {
            passenger.state = "exiting";
            passenger.targetCol = width;
            passenger.targetRow = height / 2;
          } else {
            passenger.state = newState;
            queueState = newState + "Queue";
            passenger.queueState = queueState;

            function chosenQueueRectifier(chosenQueue) {
              //* Recursive function when having mismatched station lengths.
              if (chosenQueue >= objects[queueState].length) {
                chosenQueue -= 1;
                return chosenQueueRectifier(chosenQueue);
              } else {
                return chosenQueue;
              }
            }

            chosenQueue = chosenQueueRectifier(chosenQueue);

            for (let i in objects[queueState]) {
              if (i !== chosenQueue) {
                if (
                  Number(objects[queueState][i].stack) <
                  Number(objects[queueState][chosenQueue].stack)
                ) {
                  chosenQueue = Number(i);
                }
              }
            }

            if (Math.random() < randomChosenQueue) {
              chosenQueue = Math.floor(
                Math.random() * objects[queueState].length
              );
            }

            let stackOverflow = 0;

            if (Number(objects[queueState][chosenQueue].stack) > 50) {
              stackOverflow =
                Number(objects[queueState][chosenQueue].stack) - 50;
            }

            passenger.targetRow =
              Number(objects[queueState][chosenQueue].row) + 3;
            passenger.targetCol =
              Number(objects[queueState][chosenQueue].col) - stackOverflow;
            passenger.station = station;
            passenger.chosenQueue = chosenQueue;
            let newStack = Number(objects[queueState][chosenQueue].stack) + 1;
            objects[queueState][chosenQueue].stack = newStack;
          }
        } else {
          passenger.queueState = "gettingBaggage";
          hasArrived = true;
        }
      }
      break;
    case "exiting":
      if (hasArrived) {
        passenger.state = "out";
        exitedPassengers += 1;
        document.getElementById("numExited").innerHTML =
          "Number of exited passengers: " + exitedPassengers + ".";
        listTimeToClear.push(Number(passenger.timeTaken));
        newAvg =
          listTimeToClear.reduce((a, b) => a + b) / listTimeToClear.length;
        listMeanTimeToClear.push(newAvg);
        let overallAvg;
        if (listSimulationMeanRunTime.length > 0) {
          overallAvg =
            listSimulationMeanRunTime[listSimulationMeanRunTime.length - 1];
          var overallStdDev = Math.sqrt(
            listSimulationRunTime
              .map((x) => Math.pow(x - overallAvg, 2))
              .reduce((a, b) => a + b) / listSimulationRunTime.length
          );
        } else {
          overallAvg = 0;
          var overallStdDev = 0;
        }
        document.getElementById("aveAll").innerHTML =
          "Average time taken by a passenger: " +
          newAvg.toFixed(2) +
          ". Average time taken for " +
          passengerCount +
          " passenger(s): " +
          overallAvg.toFixed(2) +
          " over " +
          simulationsRan +
          " simulation(s) with a standard deviation of " +
          overallStdDev.toFixed(2) +
          ".";
        if (isRunning == true) {
          Plotly.extendTraces("tester", { y: [[getData1()]] }, [0]);
          cnt++;
          if (cnt > limit) {
            Plotly.relayout("tester", {
              xaxis: {
                range: [cnt - limit, cnt],
              },
            });
          }
        }
      }
      break;
    case "covid":
      if (hasArrived) {
        passenger.state = "exiting";
      }
  }

  passenger.timeTaken = Number(passenger.timeTaken) + 1;

  let targetRow = Number(passenger.targetRow);
  let targetCol = Number(passenger.targetCol);
  // compute the distance to the target destination
  let rowsToGo = targetRow - row;
  let colsToGo = targetCol - col;
  // set the speed
  let cellsPerStep = 1;
  // compute the cell to move to
  let newRow =
    row + Math.min(Math.abs(rowsToGo), cellsPerStep) * Math.sign(rowsToGo);
  let newCol =
    col + Math.min(Math.abs(colsToGo), cellsPerStep) * Math.sign(colsToGo);
  // update the location of the passenger
  passenger.row = newRow;
  passenger.col = newCol;
}
function addDynamicAgents() {
  if (Math.random() < probArrival) {
    // If the random generator decides to add passengers.
    let station = 2;
    // Attempts to find the next valid station.
    // Could have done a recursive function, I guess.
    let newState = getKeyByValue(positions, 2);
    if (newState == undefined) {
      newState = getKeyByValue(positions, 3);
      station = 3;
      if (newState == undefined) {
        newState = getKeyByValue(positions, 4);
        station = 4;
      }
    }
    
    // Queue state for the queueing lanes
    let queueState = newState + "Queue";
    
    // Finding which queue lane to choose
    let chosenQueue = 0;

    for (let i in objects[queueState]) {
      if (i !== "0") {
        if (
          Number(objects[queueState][i].stack) <
          Number(objects[queueState][chosenQueue].stack)
          // Not actually technically stacks, it is just for the joke below.
        ) {
          chosenQueue = Number(i);
        }
      }
    }

    let stackOverflow = 0; // This is the joke. I know it is lame.

    if (Number(objects[queueState][chosenQueue].stack) > 50) {
      stackOverflow = Number(objects[queueState][chosenQueue].stack) - 50;
    }

    let covid = false;

    if (Math.random() < probCovid) {
      covid = true;
    }

    let newPassenger = {
      id: 1,
      row: height / 2,
      col: 0,
      state: newState,
      queueState: queueState,
      chosenQueue: chosenQueue,
      targetRow: Number(objects[queueState][chosenQueue].row) + 3,
      targetCol: Number(objects[queueState][chosenQueue].col) - stackOverflow,
      station: station,
      timeWaited: 0,
      covid: covid,
      timeTaken: 0,
    };
    
    objects.passengers.push(newPassenger);
    let newStack = Number(objects[queueState][chosenQueue].stack) + 1;
    objects[queueState][chosenQueue].stack = newStack;
    enteredPassengers += 1;
  }
}
function removeDynamicAgents() {
  let allPassengers = surface.selectAll(".passenger").data(objects.passengers);
  let exitingPassengers = allPassengers.filter(function (d) {
    return d.state == "out";
  });
  exitingPassengers.remove();
  objects.passengers = objects.passengers.filter(function (d) {
    return d.state != "out";
  });
}
function simStep() {
  if (isRunning) {
   // Chunk of code was here, deleted for clarity.

    if (enteredPassengers < passengerCount) {
      removeDynamicAgents();
      addDynamicAgents();
      updateDynamicAgents();
    } else if (exitedPassengers < passengerCount) {
      removeDynamicAgents();
      updateDynamicAgents();
    } else {
      /* 
      Chunk of code was here, deleted for clarity.
      Mainly to stop the simulation and to re-run if multiple simulations
      were configured.
      */
    }
}
import "https://unpkg.com/open-props/open-props.tokens.json"
const contents = document.querySelectorAll('.content > div');
const buttons = document.querySelectorAll('.tabBtns button');
buttons.forEach((button, i) => {
  button.addEventListener('click', () => {
    buttons.forEach(button => button.classList.remove('active'));
    contents.forEach(content => content.classList.add('hide'));
    button.classList.add('active');
    contents[i].classList.remove('hide');
  });
});
<div class="box">
    <div class="cambio"><a class="enlase" href="#">Inicio</a></div>
    <div class="cambio"><a class="enlase" href="#">Horario</a></div>
    <div class="cambio"><a class="enlase" href="#">Blog</a></div>
</div>


// css 
.box{
width: 60vw;
height: 30px;
background: gray;
display: flex;
justify-content: space-around;
}
.cambio{
    height: 100%;
    background: blue;
}
.cambio a{
    display: inline-block;
    width: 100px;
    height: 100%;
    color: white;
}
.active a{
    background: red;
}
.active{
    background:red;
}

// javascript

//metodo (1): se señala al elementi que dispara con la i del for
//            la clase active sirve como puente, sin nesecidad que este en el css

let cambio = document.querySelectorAll(".cambio");
for(let i = 0; i < cambio.length; i++) {
    cambio[i].addEventListener("click", () =>{
	cambio.forEach(link => {
	    link.classList.remove("active");
	});
	cambio[i].classList.add("active");
    });
};

// metodo(2): delegación de evento e.target detecta al elemento que dispara
//            la clase active se incluye en el css 
//            se trabaja solo con enlase.

let enlase = document.querySelectorAll(".enlase");
enlase.forEach(lin => {
    lin.addEventListener("click", (e) => {
    enlase.forEach(link => { // es el enlase cuando  ya tiene el evento click
	link.classList.remove("active");
    });
    e.target.classList.add("active"); // detecta donde se iso click(elemento)
    });
});

sParameter = encodeURIComponent(sParameter.trim()) //"Test%20-%20Text"
$('#downloadRegistrationCertificate').on('click',function(){
    downloadPdf();
});

function downloadPdf() {
    var regNum = JSON.parse(sessionStorage.getItem("sessionPath")).regNumber
    
    $.ajax({
        url: apiPathEnv + "/web/registration-service/v1/download-certificate?registrationNumber="+regNum+"&sessionToken="+sessionTokenVar,
        type: 'get',
        headers: { 
            'Accept': 'application/json',
            'Content-Type': 'application/json' 
        }
    })
    .done(function (result) {

        if(result != undefined && (result.messages == null || result.messages.length == 0)){
            console.log("REsults",result.bytes);
            var responseBytes = _base64ToArrayBuffer(result.bytes);   
            var certificateBlob = new Blob([responseBytes], {type: 'application/pdf'});
            // console.log(responseBytes);
            var downloadLink = document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(certificateBlob);
            //downloadLink.download="RegistrationCertificate_" +regNum+ ".pdf";
            //downloadLink.click();
            
            var isIE = /*@cc_on!@*/false || !!document.documentMode;
            var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));

            if(isIE) { // Internet Explorer 6-11
                window.navigator.msSaveBlob(certificateBlob, 'RegistrationCertificate.pdf');
            }
            else if(isSafari) { // Safari Browser
                var newWindow = window.open(window.URL.createObjectURL(certificateBlob),'_blank')

            }
            else {
                // Mobile Devices
                if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
                    downloadLink.download="RegistrationCertificate_" +regNum+ ".pdf";
                    downloadLink.click();
                }
                // Other Browsers
                else {
                    window.open(window.URL.createObjectURL(certificateBlob), '_blank');
                }						
            }
        }
    }).fail(function (result){
        console.log(result);
        // api .fail error page redirect
        siteNotAvailable();
    });
}

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}	
<div *ngFor="let item of object | keyvalue">
  {{item.key}}:{{item.value}}
</div>
function capitalize(word) {
    const firstLetter = word[0].toUpperCase()
    const restWord = word.substring(1).toLowerCase()
    return firstLetter + restWord
}
var instanceURL = gs.getProperty('glide.servlet.uri');
var DSCSQueryBRUtil = Class.create();
DSCSQueryBRUtil.prototype = {

    TABLE_CONTACT: 'customer_contact',
    TABLE_ACCOUNT: 'customer_account',
    TABLE_CS_CASE: 'sn_customerservice_case',
    TABLE_INTERACTION: 'interaction',
    TABLE_CSM_CONSUMER: 'csm_consumer',

    initialize: function () {
    },

    /**
    * Add an encoded query to the current record to restric the visibility
    * @param current GlideRecord
    * @param table string name of the table - optional
    * @return GlideRecord with added encoded query
    */
    addQueryforAgent: function (current, table) {
        var tableName = gs.nil(table) ? current.getTableName() : table;
        var query = this.getQBRConditionQueries(current, tableName);
        if (!gs.nil(query))
            current.addEncodedQuery(query);

        return current;
    },

    /**
    * Add an encoded query to the current record to restric the visibility
    * @param current GlideRecord
    * @return GlideRecord with added encoded query
    */
    addCaseQueryforAgent: function (current) {
        return this.addQueryforAgent(current, this.TABLE_CS_CASE);
    },

    /**
    * Add an encoded query to the current record to restric the visibility
    * @param current GlideRecord
    * @return GlideRecord with added encoded query
    */
    addInteractionQueryforAgent: function (current) {
        return this.addQueryforAgent(current, this.TABLE_INTERACTION);
    },

    /*
    * QBR queries can be used in each entity's QBR functions based on Conditions
    */
    getQBRConditionQueries: function (current, tableName) {
        var query = null;
        var myOpcos = this.getMyOpcos();
        if (myOpcos && myOpcos.length > 0) {
            // Important decision here, if there are NO assignment types on the record, should it be visible to everyone?
            // query = current.addEncodedQuery('u_assignment_typeIN' + myOpcos.join() + '^ORu_assignment_typeISEMPTY');
            query = current.addEncodedQuery('u_assignment_typeIN' + myOpcos.join());
        } else {
            // Important decision here, if an agent is not a member of any Opco, should they see any records?
            // query = current.addEncodedQuery('u_assignment_typeISEMPTY');
            query = current.addEncodedQuery('u_assignment_typeISEMPTY^u_assignment_type!=NULL');
        }
        /*
         This is a place for more complex logic and exception
         query variable can be manipulated
         it is possible to reuse CSQueryBRUtil.getRoleAccessDetails() approach with conditions
        */

        return query;
    },

    /**
    * Get array of my Opcos
    * similar to CSQueryBRUtil.getMyCSMRoles
    * loop through my groups, get all assignment types
    * list of assignment types that count as "Opco" should be stored as a coma-separated string in a system property
    * @return array of sys_ids of the assignment types
    */
    getMyOpcos: function () {
        var key = 'my_csm_opcos_' + gs.getUserID();
        var results = gs.getSession().getClientData(key);
        var dataSeparatedOpcos = gs.getProperty('hohr.csm.data_separated_opcos', '').split(',');
        gs.log('data separated opcos: ' + dataSeparatedOpcos);

        if (gs.nil(results) || results == 'NIL') {

            var myOpcos = [];
            var allMyGroups = new GlideRecordSecure('sys_user_grmember');
            allMyGroups.addQuery('user', gs.getUserID());
            allMyGroups.query();
            while (allMyGroups.next()) {
				//var myGroupTypes = allMyGroups.group.type; //coma-separated list of types
                var myGroupTypes = allMyGroups.group.u_business_group.u_assignment_types; //coma-separated list of types
                var groupTypeArr = myGroupTypes.split(',');
                for (var i = 0; i < groupTypeArr.length; i++) {
                    var groupType = groupTypeArr[i];
                    if (dataSeparatedOpcos.indexOf(groupType) > -1) {
                        // group type we found is data-separated
                        if (myOpcos.indexOf(groupType) == -1)
                            myOpcos.push(groupType);
                    }
                }
            }
			gs.log('opcos: ' + myOpcos);

            results = (myOpcos.length > 0) ? myOpcos.join(',') : 'NIL';
            gs.getSession().putClientData(key, results);
				
        }

        results = (gs.nil(results) || results == 'NIL') ? null : results.split(',');
        return results;
    },

    type: 'DSCSQueryBRUtil'
};
//optional array to object
var object = Object.assign({}, data);


var object = ['apel', 'mangga', 'jeruk']

const allowed = ['mangga'];

var filtered = Object.keys(object)
.filter(key => allowed.includes(key))
.reduce((obj, key) => {
    obj[key] = object[key];
    return obj;
}, {});
data = filtered;
d.sort(function(a, b) {
    var dateA = new Date(a.invoice_date.slice(0, -17)),
        dateB = new Date(b.invoice_date.slice(0, -17))
    return dateA - dateB
});
function add (string) {
   let partsArray = string.split("+");
   console.log("parts", partsArray);
   let added = 0;
      
   for (let i=0; i<partsArray.length; i++) {
      console.log("i",parseInt(partsArray[i]));
      added += parseInt(partsArray[i]);
   }

   return added;
}
function sum(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
      sum += arr[i][j];
    }
  }
  return sum;
}
<i>I love thiscodeworks</i>
function isPrime(num) { // returns boolean
  if (num <= 1) return false; // negatives
  if (num % 2 == 0 && num > 2) return false; // even numbers
  const s = Math.sqrt(num); // store the square to loop faster
  for(let i = 3; i <= s; i += 2) { // start from 3, stop at the square, increment in twos
      if(num % i === 0) return false; // modulo shows a divisor was found
  }
  return true;
}
console.log(isPrime(121));
require("dotenv").config();
const port = process.env.PORT || 7788;
const mongoUri = process.env.MONGO_URI;
mongoose.connect(mongoUri, {
  useNewUrlParser: true,
});
const connection = mongoose.connection;
connection.once("open", () => {
  console.log("Mongo Docker container running");
});
function median(arr) {
    arr = [...arr].sort((a, b) => a - b);
    return (arr[arr.length - 1 >> 1] + arr[arr.length >> 1]) / 2;
}
var test = new AnywhereCTIService();
test.INTERACTION_DEPARTMENT

for (var defaultField in test.INTERACTION_DEPARTMENT) {
    gs.log(defaultField);
            if (Object.hasOwnProperty.call(test.INTERACTION_DEPARTMENT, defaultField)) {
                var defaultFieldValue = test.INTERACTION_DEPARTMENT[defaultField];
                gs.log(defaultFieldValue);
            }
        }
<div id="uno" >
  <div id="dos" >
    <div id="tres" ></div>
  </div>
</div>
const key1 = "name";
const key2 = "age";
const student = {
    [key1]:"john Doe",
    [key2]:26
}
console.log(student)
//{ name:"john Doe", age:26 }
function returnDayKeyValue(val) {
    const returnDayObject = {
        1: "It's monday",
        2: "It's tuesday",
        3: "It's wednesday",
        4: "It's thursday",
        5: "It's friday",
        6: "It's saturday",
        7: "It's sunday",
    }
    if(!returnDayObject[val]){
     return "Enter a value between 1 - 7";
    }
    return returnDayObject[val]
}
cosnt day = 3;
console.log(returnDayKeyValue(day)); //It's wednesday
var AnywhereCTIService = Class.create();
AnywhereCTIService.prototype = {
    // This is just for the developers reference, not used in the code
    BODY_EXAMPLE: {
        'callerNumber': '+12345678901',
        'agentSip': 'test@example.com'
    },

    // List of properties that should be present in the request body
    MANDATORY_BODY_PROPERTIES: ['callerNumber', 'agentSip'],

    INTERATCION_FIELDS_DEFAULTS: {
        'state': 'work_in_progress',
        'type': 'phone',
        'short_description': 'Received a call',
    },

    // Fields that should be included in the response
    INTERACTION_FIELDS_RESPONSE: [
        'sys_id',
        'number',
        'short_description',
        'account',
        'contact',
        'consumer',
        'assigned_to',
    ],

    // Fields that should have their display value included in the response
    INTERACTION_FIELDS_DISPLAY_RESPONSE: [
        'account',
        'contact',
        'consumer',
        'assigned_to',
    ],
	// Fields that should have their display value included in the response
    INTERACTION_DEPARTMENT: {
        'C_Open_Fleet' : '1',
        'S_Open':'',
        'C_Open_Finance':'',
        'C_Open_IT':'',
		'C_Open_ComplianceHelpdesk':'',
		'C_Open_ComplinaceSupport':'',
		'C_Open_ComplianceRisk':'',
		'S_Open_FR':'',
		'C_Open_Marketing':'',
		'C_Open_HR':''
    },

    /**
     * Initialize the variables
     * @param {RESTAPIRequest}  request 
     * @param {RESTAPIResponse} response 
     */
    initialize: function (request, response) {
        this.logger = new global.GSLog('pl4.csm.anywhere365.log', this.type);
        this.logger.includeTimestamp();
        this.request = request;
        this.response = response;
        this.validated = false;
        this.error = false;
        this.errorObj = {
            'statusCode': '',
            'message': '',
            'details': ''
        };
        this.interactionGr = false;

    },

    /**
     * Main function that is executed in the Scripted REST API
     */
    process: function () {
        try {
            this.validated = this.validateRequest();
            if (this.validated !== true) {
                this._setResponse();
            }

            this.interactionGr = this._createInteraction();

            this._setResponse();
        } catch (e) {
            this.logErr('[process] caught an error: ' + e + '\nstack:\n' + e.stack);
            this._setError(500, 'Internal server error', '');
            this._setResponse();
        }
    },

    /**
     * Populates the default interaction fields and makes data lookup for Caller and Agent
     * @returns {Object}
     */
    _getInteractionFields: function () {
        var fields = {
            'assigned_to': '',
            'account': '',
            'contact': '',
            'consumer': '',
            'opened_by': '',
			'opened_for': '',
            'u_assignment_type': ''
        };

        for (var defaultField in this.INTERATCION_FIELDS_DEFAULTS) {
            if (Object.hasOwnProperty.call(this.INTERATCION_FIELDS_DEFAULTS, defaultField)) {
                var defaultFieldValue = this.INTERATCION_FIELDS_DEFAULTS[defaultField];
                fields[defaultField] = defaultFieldValue;
            }
        }

        // lookup assignment type
        var assignmentType = this._getAssignmentType(this.bodyData.ucc);
        if(assignmentType){
            fields.u_assignment_type = assignmentType.join(',');
            this.logDebug('[_getInteractionFields] assignmenttype(s) found: ' + assignmentType.join(','));
        }


        // Lookup the agent
        var agentEmail = this._getAgentEmail();
        var agentGr = this._lookupAgentByEmail(agentEmail);

        if (agentGr !== false) {
            fields.assigned_to = agentGr && agentGr.getUniqueValue();
            this.logDebug('[_getInteractionFields] found agent: ' + agentGr.getUniqueValue() + ' ' + agentGr.getDisplayValue());
        }

        // Lookup the caller
        var callerNumber = this._getCallerNumber();
        var contactGr;
        var consumerGr;
        var userGr;

        // Try to lookup Contact by mobile phone first
        contactGr = this._lookupUserByPhone('customer_contact', 'mobile_phone', callerNumber);
        if (contactGr === false) contactGr = this._lookupUserByPhone('customer_contact', 'phone', callerNumber);

        if (contactGr !== false) {
            // We found the contact, now we can get the account
            fields.contact = contactGr.getUniqueValue();
            fields.account = contactGr.getValue('account');
            this.logDebug('[_getInteractionFields] found contact: ' + contactGr.getUniqueValue() + ' ' + contactGr.getDisplayValue());
        }

        if (contactGr === false) {
            // Did not find Contact, look for consumers
            consumerGr = this._lookupUserByPhone('csm_consumer', 'mobile_phone', callerNumber);
            if (consumerGr === false) consumerGr = this._lookupUserByPhone('csm_consumer', 'business_phone', callerNumber);
            if (consumerGr === false) consumerGr = this._lookupUserByPhone('csm_consumer', 'home_phone', callerNumber);

            if (consumerGr !== false) {
                fields.consumer = consumerGr.getUniqueValue();
                this.logDebug('[_getInteractionFields] found consumer: ' + consumerGr.getUniqueValue() + ' ' + consumerGr.getDisplayValue());
            }
			
			if(consumerGr === false){
				userGr = this._lookupUserByPhone('sys_user','phone', callerNumber);
				if(userGr === false) userGr = this._lookupUserByPhone('sys_user','mobile_phone', callerNumber);
				if(userGr === false) userGr = this._lookupUserByPhone('sys_user','u_ip_phone', callerNumber);
				
				if(userGr !== false){
					fields.opened_for = userGr.getUniqueValue();
					this.logDebug('[_getInteractionFields] found internal user: ' + userGr.getUniqueValue() + ' ' + userGr.getDisplayValue());
				}
			}
        }

        // Add variables to short description
        fields.short_description += ' from ' + callerNumber;

        this.logDebug('[_getInteractionFields] fields result: ' + global.JSON.stringify(fields));
        return fields;
    },

    /**
     * Get the caller phone from the body
     * @returns {String}
     */
    _getCallerNumber: function () {
        return String(this.bodyData.callerNumber);
    },

    /**
     * Get the assignment type from the ucc
     * @returns 
     */
    _getAssignmentType: function(ucc) {
        var group = new GlideRecord('sys_user_group');
        group.get('u_ucc', ucc);
        var assTypes = new DataSeparationUtils().getAssignmentTypes(group.u_business_group);
		gs.log('assignment type function: ' + assTypes);
        return assTypes;
    },

    /**
     * Get the agent sip from the body
     * @returns {String}
     */
    _getAgentEmail: function () {
        return String(this.bodyData.agentSip).replace('sip:', '');
    },

    /**
     * Lookup the user by specified phone number
     * Note that the number format should match exactly
     * @param {String} table table where user should be looked up
     * @param {String} phoneField field that contains the phone number
     * @param {String} phone phone number received by the REST API
     * @returns {GlideRecord|boolean}
     */
    _lookupUserByPhone: function (table, phoneField, phone) {
        var contactGr = new GlideRecord(table);
        if (!contactGr.isValid()) return false;
        if (!contactGr.isValidField(phoneField)) return false;
		if(table == 'sys_user')
			contactGr.addQuery('sys_class_name', 'sys_user');
        contactGr.addQuery(phoneField, phone);
        contactGr.orderBy('sys_created_on');
        contactGr.setLimit(1);
        contactGr.query();
        if (contactGr.next()) {
            return contactGr;
        }
        this.logDebug('[_lookupUserByPhone] Could not find a user, table: ' + table + ' field: ' + phoneField + ' phone: ' + phone);
        return false;
    },

    /**
     * Lookup the sys_user record by email
     * @param {String} agentEmail email of the agent
     * @returns {GlideRecord|boolean}
     */
    _lookupAgentByEmail: function (agentEmail) {
        var userGr = new GlideRecord('sys_user');
        userGr.addQuery('email', agentEmail);
        userGr.orderBy('sys_created_on');
        userGr.setLimit(1);
        userGr.query();
        if (userGr.next()) {
            return userGr;
        }
        this.logDebug('[_lookupAgentByEmail] Could not find a user, agentEmail: ' + agentEmail);
        return false;
    },

    /** 
     * Validate the request
     * @returns {sn_ws_err.ServiceError|boolean}
     */
    validateRequest: function () {
        try {
            this.bodyData = request.body.data;
            if (gs.nil(this.bodyData)) {
                this.logWarning('[validateRequest] Body data is missing: ' + this.bodyData);
                this._setError(400, "Body is missing", "Expecting a body with properties.");
                return false;
            }

            for (var i = 0; i < this.MANDATORY_BODY_PROPERTIES.length; i++) {
                var mandatoryProperty = this.MANDATORY_BODY_PROPERTIES[i];

                if (gs.nil(this.bodyData[mandatoryProperty])) {
                    this.logWarning('[validateRequest] Mandatory body property is missing: ' + mandatoryProperty);
                    this._setError(400, "Mandatory body property is missing", "Expecting a body propertiy to be in the body: " + mandatoryProperty);
                    return false;
                }
            }

            // All checkes have passed
            return true;
        } catch (e) {
            this.logErr('[validateRequest] caught an error: ' + e.message + '\nstack: ' + e.stack);
        }
    },

    /**
     * Create an interaction record
     * @returns {GlideRecord|boolean}
     */
    _createInteraction: function () {
        var interactionFields = this._getInteractionFields();
        if (this.error !== false) {
            // There was an error during data lookup
            this.logErr('[_createInteraction] There was an error during data lookup');
            return false;
        }
        var interactionGr = new GlideRecord('interaction');
        interactionGr.newRecord();

        for (var fieldName in interactionFields) {
            if (Object.hasOwnProperty.call(interactionFields, fieldName)) {
                if (interactionGr.isValidField(fieldName)) {
                    var fieldValue = interactionFields[fieldName];
                    interactionGr.setValue(fieldName, fieldValue);
                    // this.logDebug('[_createInteraction] setting interaction field ' + fieldName + ' to: ' + fieldValue);
                }
            }
        }

        var interactionId = interactionGr.insert();
        if (gs.nil(interactionId)) {
            //Failed to insert the record
            this.logErr('[_createInteraction] Failed to create an interaction');
            return false;
        }
        this.logDebug('[_createInteraction] Created an interaction, sys_id: ' + interactionId + ' number: ' + interactionGr.getValue('number'));

        return interactionGr;
    },

    /**
     * Construct and set the error object 
     * @param {number} statusCode 
     * @param {String} message 
     * @param {String} details 
     */
    _setError: function (statusCode, message, details) {
        this.errorObj = {
            'statusCode': statusCode,
            'message': message,
            'details': details,
        };
        var serviceError = new sn_ws_err.ServiceError();
        serviceError.setStatus(statusCode);
        serviceError.setMessage(message);
        serviceError.setDetail(details);
        this.error = serviceError;
    },

    /**
     * Set the status code, messages and response body based on this.error varialbe
     * 
     */
    _setResponse: function () {
        if (this.error !== false) {
            this.response.setError(this.error);
            this.logDebug('[_setResponse] set error with code: ' + this.errorObj.statusCode);
            return;
        }

        if (this.interactionGr !== false) {
            this.logDebug('[_setResponse] set successful resposne with code: 201, interaction number: ' + this.interactionGr.getValue('number'));
            this.response.setStatus(201);
            var responseBody = this._constructResponseBody();
            this.response.setBody(responseBody);
        }
    },

    /**
     * Construct the Response body, include required interaction fields
     * @returns {Object}
     */
    _constructResponseBody: function () {
        var responseBody = {};
        for (var i = 0; i < this.INTERACTION_FIELDS_RESPONSE.length; i++) {
            var field = this.INTERACTION_FIELDS_RESPONSE[i];
            responseBody[field] = this.interactionGr.getValue(field);
        }
        for (var j = 0; j < this.INTERACTION_FIELDS_DISPLAY_RESPONSE.length; j++) {
            var fieldDisplay = this.INTERACTION_FIELDS_DISPLAY_RESPONSE[j];
            responseBody[fieldDisplay] = this.interactionGr[fieldDisplay] && this.interactionGr[fieldDisplay].getDisplayValue();
        }
        this.logDebug('[_constructResponseBody] responseBody:\n' + global.JSON.stringify(responseBody));
        return responseBody;
    },

    logDebug: function (msg) {
        this.logger.logDebug(msg);
    },

    logInfo: function (msg) {
        this.logger.logInfo(msg);
    },

    logWarning: function (msg) {
        this.logger.logWarning(msg);
    },

    logErr: function (msg) {
        this.logger.logErr(msg);
    },

    type: 'AnywhereCTIService'
};
$('div:contains("test")').css('background-color', 'red');
fruits = [
 {  description: 'orange', Amount: 50},
 {  description: 'orange', Amount: 50},
 {  description: 'apple', Amount: 75},
 {  description: 'kiwi', Amount: 35},
 {  description: 'watermelon', Amount: 25},];
const sumall = fruits.map(item => item.amount).reduce((prev, curr) => prev + curr, 0);
console.log(sumall);
class fruitCollection extends Array {
    sum(key) {
        return this.reduce((a, b) => a + (b[key] || 0), 0);
    }
}
const fruit = new fruitCollection(...[
    {  description: 'orange', Amount: 50},
    {  description: 'orange', Amount: 50},
    {  description: 'apple', Amount: 75},
    {  description: 'kiwi', Amount: 35},
    {  description: 'watermelon', Amount: 25 },]);

console.log(fruit.sum('Amount'));
var setInnerHTML = function(elm, html) {
  elm.innerHTML = html;
  Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
    const newScript = document.createElement("script");
    Array.from(oldScript.attributes)
      .forEach( attr => newScript.setAttribute(attr.name, attr.value) );
    newScript.appendChild(document.createTextNode(oldScript.innerHTML));
    oldScript.parentNode.replaceChild(newScript, oldScript);
  });
}
<section class="destacada">
  <div class="contenido text-center">
    <h1 class="estilo"> Ayuda </h1>
    <img src="http://picsum.photos/100/100"/>
  </div>
</section> 

//css 
.destacada img{
  width: 50px;
  height: 50px;
}

 h1:hover ~ img{
  width: 200px; /*O lo que quieras*/
  height: 200px; /*O lo que quieras*/ 
}
if (navigator.webdriver) {
    document.body.innerHTML = "This is a Bot";
}
let hijo = document.querySelector('.hijo');
let etiqueta = document.querySelectorAll('.etiqueta');
//El metodo .getBoundingClientRect() nos da 
//la posicion de un elemento con respecto al viewport(en numeros).
// tomare la posicion constante del elemento .hijo 
const coords = hijo.getBoundingClientRect();
const j = coords.top; // estamos obteniendo la posicion top en numero
const k = coords.left;

// se aplica forEach para obtener posicion de cada movimiento del mouse
etiqueta.forEach(link => {
// se obtiene la posicion del mouse con la funcion  mover(e)
    function mover(e){
// se calcula la posicion top y left del mouse al cual le restamos
// la posicion del elemento "hijo"; resultado: mouse e "hijo" juntos 
	 let m = e.pageY ;
	 let n = e.pageX ;

	 let t = m - j;
	 let l = n - k;
	 hijo.style.top = t + "px"; // agregando px a los numeros
	 hijo.style.left = l + "px";
    };
// mouseover dice que entro en elemento etiqueta
    link.addEventListener("mouseover",() => {
	hijo.classList.add("edd1");// solo agrega un class que le da color red

	 window.addEventListener("mousemove",mover);// agrega el evento junto a la funcion 
    });

    link.addEventListener("mouseleave",() => {// mouseleave dice que salio del elemento etiqueta
	hijo.classList.remove("edd1"); // le quita un class, que le quita color red
	 window.removeEventListener("mousemove", mover);// remuev el evento
    });
});

/* Simples estilos para delimitar los div*/
.box{
width: 300px;
height: 300px;
border: solid 1px black;
}
.etiqueta{
width:100px;
height:100px;
position: absolute;
left:50px;
top:50px;
background: green;
overflow: hidden;
position:relative;
}
.hijo{
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: blue;
transform: scale(0); /*desaparece el elemento hijo*/
}
.edd1{
background-color: red;
transform: scale(1); /*reaparece el elemento hijo con el mause al centro*/
} 

// un ejemplo con html
<div class="box">
  <div class="etiqueta">
  <div class="hijo"></div>
  </div>
</div> 

// Example 4051231234 -> (405) 123-1234
export const formatToUSPhoneNumber = (e: React.ChangeEvent<HTMLInputElement>): string => {
  const phoneField = e.target;

  const cursorPosition = phoneField.selectionStart;
  const numericString = phoneField.value.replace(/\D/g, '').substring(0, 10);

  const match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);

  if (match) {
    let newVal = '(' + match[1];
    newVal += match[2] ? ') ' + match[2] : '';
    newVal += match[3] ? '-' + match[3] : '';

    // to help us put the cursor back in the right place
    const delta = newVal.length - Math.min(phoneField.value.length, 14);
    phoneField.value = newVal;
    if (cursorPosition) {
      phoneField.selectionEnd = cursorPosition + delta;
    }
  } else {
    phoneField.value = '';
  }

  return phoneField.value;
};
// Google Maps  
function initMap(getLat, getLng) {
  const location = { lat: getLat, lng: getLng };
  // The map
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 14,
    center: location,
  });
  // The marker
  const marker = new google.maps.Marker({
    position: location,
    map: map,
  });
}

// Geocode
function geocode() {
  var defaultLocation = 'Tbilisi';
  var address = $("#address").text();

  if (addressEn) { // You can add more conditionals to specify address line 2, zip code, etc.
    var myLocation = address;
  } else {
    var myLocation = defaultLocation
  }

  axios.get('https://maps.googleapis.com/maps/api/geocode/json',{
    params:{
      address: myLocation,
      key: 'YOUR_KEY',
    }
  })
  .then(function (response) {
    var lat = response.data.results[0].geometry.location.lat;
    var lng = response.data.results[0].geometry.location.lng;
    initMap(lat, lng);
  })
  .catch(function(error) {
    console.log(error);
  })
}
// Call
geocode();


PImage img;

//setup
img = loadImage("imagename.png");
img = loadImage("https://source.unsplash.com/random/900x900", "png");
img = loadImage("https://source.unsplash.com/900x900/?nature,water", "png");


//draw
image(img, 0,0);

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });
const formatCash = n => {
  if (n < 1e3) return n;
  if (n >= 1e3) return +(n / 1e3).toFixed(1) + "K";
};

console.log(formatCash(2500));
.line-wide {
  transform: rotate(45deg) scaleX(1);
  animation-name: change-width;
}

.line-high {
  transform: rotate(-135deg) scaleY(1);
  animation-name: change-height;
}

@keyframes change-width {
  0% {
    transform: rotate(45deg) scaleX(0); 
  }

  100% {
    transform: rotate(45deg) scaleX(1);  
  }
} 

@keyframes change-height {
  0% {
    transform: rotate(-135deg) scaleY(0); 
  }

  100% {
    transform: rotate(-135deg) scaleY(1);  
  }
} 
.line-wide {
    transform: rotate(45deg) scaleX(1);
    animation-name: change-width;
}

.line-high {
    transform: rotate(-45deg) scaleY(1);
    animation-name: change-height;
}

@keyframes change-width {
    0% {
        transform: rotate(45deg) scaleX(0); 
    }

    100% {
        transform: rotate(45deg) scaleX(1);  
    }
} 

@keyframes change-height {
    0% {
        transform: rotate(-45deg) scaleY(0); 
    }

    100% {
        transform: rotate(-45deg) scaleY(1);  
    }
} 
	"start": "cross-env TAILWIND_MODE=watch craco start",
		"build": "craco build",
		"test": "craco test",
		"eject": "react-scripts eject"
              function onlyUnique(value, index, self) { 
                  return self.indexOf(value) === index;
              }

              function countOccurances(a,i)
              {
               var result = 0;
               for(var o in a)
                if(a[o] == i)
                 result++;
               return result;
              }

		
            $('#submit-form-button-bundle').click(function(e){   
              e.preventDefault();
              
              var allBeds = [$("#primary_bed").val(), $('#secondary_bed').val(), 		$('#product_3').val(), $('#product_4').val()];
              var uniqueBeds = allBeds.filter( onlyUnique );
              
              //console.log(uniqueOodies);
              //console.log(countOccurances(allOodies, $("#oodie-color").val()));
              
              jsonObj = []
              var arrayLength = uniqueBeds.length;
              for (var i = 0; i < arrayLength; i++) 
              {    
                  item = {}
                  item ["quantity"] 	= countOccurances(allBeds, uniqueBeds[i]);
                  item ["id"] 			= uniqueBeds[i];
                  jsonObj.push(item);
              }
              
              $.ajax({
                url: "/cart/add",
                type: "post",
                data: { items: jsonObj },
                success: function(){
                  
                window.location.href = "/checkout?discount=BLACKFRIDAY-MEGA-BUNDLE-4-PIECE";
                  
                },
                error: function(){
                }
              });
            });

            $('.single-option-selector').change(function(){

              var selected_option = $('.single-option-selector').val();
              
              // adding bed variant ids
              if(selected_option.indexOf("Navy - Small") >= 0){
                $('#primary_bed').val('29012044808226');
              }

              else if(selected_option.indexOf("Grey - Small") >= 0){
                $('#primary_bed').val('29012045103138');
              }

              else if(selected_option.indexOf("Pink - Small") >= 0){
                $('#primary_bed').val('28915153764386');
              }
              
              else if(selected_option.indexOf("Navy - Medium") >= 0){
                $('#primary_bed').val('31683365797911');
              }
              
              else if(selected_option.indexOf("Grey - Medium") >= 0){
                $('#primary_bed').val('31683365765143');
              }
              
              else if(selected_option.indexOf("Pink - Medium") >= 0){
                $('#primary_bed').val('31683365830679');
              }
              
              else if(selected_option.indexOf("Navy - Large") >= 0){
                $('#primary_bed').val('28915153698850');
              }
              else if(selected_option.indexOf("Grey - Large") >= 0){
                $('#primary_bed').val('28915153731618');  
              }
              else if(selected_option.indexOf("Pink - Large") >= 0){
                $('#primary_bed').val('29012060799010');
              }
              else if(selected_option.indexOf("Navy - Extra") >= 0){
                $('#primary_bed').val('31722116251671');
              }
              else if(selected_option.indexOf("Grey - Extra") >= 0){
                $('#primary_bed').val('31722116218903');
              }
              else if(selected_option.indexOf("Pink - Extra") >= 0){
                $('#primary_bed').val('31722116284439');
              }

              else
              {
                console.log('Some thing went wrong please check code for bugs');
              }
              
              if(selected_option.indexOf("Extra") >= 0){
              	$('#price_1').val('189');
              } 
              else if(selected_option.indexOf("Large") >= 0){
              	$('#price_1').val('129');
              }
              else if(selected_option.indexOf("Medium") >= 0){
              	$('#price_1').val('114');
              }
              else if(selected_option.indexOf("Small") >= 0){
              	$('#price_1').val('99');
              }

            });
            $('.single-option-selector-2').change(function(){........}
              function onlyUnique(value, index, self) { 
                  return self.indexOf(value) === index;
              }

              function countOccurances(a,i)
              {
               var result = 0;
               for(var o in a)
                if(a[o] == i)
                 result++;
               return result;
              }

		
            $('#submit-form-button-bundle').click(function(e){   
              e.preventDefault();
              
              var allBeds = [$("#primary_bed").val(), $('#secondary_bed').val(), 		$('#product_3').val(), $('#product_4').val()];
              var uniqueBeds = allBeds.filter( onlyUnique );
              
              //console.log(uniqueOodies);
              //console.log(countOccurances(allOodies, $("#oodie-color").val()));
              
              jsonObj = []
              var arrayLength = uniqueBeds.length;
              for (var i = 0; i < arrayLength; i++) 
              {    
                  item = {}
                  item ["quantity"] 	= countOccurances(allBeds, uniqueBeds[i]);
                  item ["id"] 			= uniqueBeds[i];
                  jsonObj.push(item);
              }
              
              $.ajax({
                url: "/cart/add",
                type: "post",
                data: { items: jsonObj },
                success: function(){
                  
                window.location.href = "/checkout?discount=BLACKFRIDAY-MEGA-BUNDLE-4-PIECE";
                  
                },
                error: function(){
                }
              });
            });

            $('.single-option-selector').change(function(){

              var selected_option = $('.single-option-selector').val();
              
              // adding bed variant ids
              if(selected_option.indexOf("Navy - Small") >= 0){
                $('#primary_bed').val('29012044808226');
              }

              else if(selected_option.indexOf("Grey - Small") >= 0){
                $('#primary_bed').val('29012045103138');
              }

              else if(selected_option.indexOf("Pink - Small") >= 0){
                $('#primary_bed').val('28915153764386');
              }
              
              else if(selected_option.indexOf("Navy - Medium") >= 0){
                $('#primary_bed').val('31683365797911');
              }
              
              else if(selected_option.indexOf("Grey - Medium") >= 0){
                $('#primary_bed').val('31683365765143');
              }
              
              else if(selected_option.indexOf("Pink - Medium") >= 0){
                $('#primary_bed').val('31683365830679');
              }
              
              else if(selected_option.indexOf("Navy - Large") >= 0){
                $('#primary_bed').val('28915153698850');
              }
              else if(selected_option.indexOf("Grey - Large") >= 0){
                $('#primary_bed').val('28915153731618');  
              }
              else if(selected_option.indexOf("Pink - Large") >= 0){
                $('#primary_bed').val('29012060799010');
              }
              else if(selected_option.indexOf("Navy - Extra") >= 0){
                $('#primary_bed').val('31722116251671');
              }
              else if(selected_option.indexOf("Grey - Extra") >= 0){
                $('#primary_bed').val('31722116218903');
              }
              else if(selected_option.indexOf("Pink - Extra") >= 0){
                $('#primary_bed').val('31722116284439');
              }

              else
              {
                console.log('Some thing went wrong please check code for bugs');
              }
              
              if(selected_option.indexOf("Extra") >= 0){
              	$('#price_1').val('189');
              } 
              else if(selected_option.indexOf("Large") >= 0){
              	$('#price_1').val('129');
              }
              else if(selected_option.indexOf("Medium") >= 0){
              	$('#price_1').val('114');
              }
              else if(selected_option.indexOf("Small") >= 0){
              	$('#price_1').val('99');
              }

            });
            $('.single-option-selector-2').change(function(){........}
        <div class="swatches-wrapper">
          {% assign colors = "Navy, Grey, Pink" %}
          
          {% for option in product.options_with_values %}
            {% for variant in product.variants %}
              {% assign name = variant.title %}
              {% assign stringSplit = name | remove: ' ' | split: '-' %}
              {% for stringPart in stringSplit %}
          		{% if forloop.index == 1 %}
                  {% if colors contains stringPart %}
                  <div class="swatch-option {{stringPart}}" data-color="{{ variant.title }}" data-id="{{variant.id}}">
                    <span class="tooltip">{{ variant.title }}</span>
                  </div>
          			{%else%}
          			--2--
                  {%endif%}
          		{%endif%}
              {% endfor %} 	
            {% endfor %}
          {% endfor %}
        </div>
        <script>
          $('.swatch-option').click(function(){
            $('.swatch-option').removeClass('active')
            $(this).addClass('active');
          });
        </script>
// hoja css
wp_enqueue_style( 'tema_fray_framework', get_template_directory_uri().'/css/fray.css',array(),time());
// hoja Js
wp_enqueue_script( 'tema_fray_js', get_template_directory_uri() . '/js/misfunciones.js', array(),time(),true);

// true: carga el js en el footer
// false(por defecto): carga el js en el head
// Nota: "las hojas css(estilo), se deben cargar en el head(defaul o false)" 
    // HTML
    <div id="box">
        <div id="item1">CLICK <br> item1</div>
        <div id="item2" class="none">item2</div>
    </div>

    // CSS
    #box{
        background-color: rebeccapurple;
        width:300px;
        height: 600px;
    }
    #item1{
        position: absolute;
        right: 20px;
        background-color: red;
        width:100px;
        height: 300px;
        cursor: pointer;
    }
    
    #item2{
        position: absolute;
        right: 140px;
        background-color: yellowgreen;
        width:150px;
        height: 300px;
    } 
    
    .block{
        display: block;
    }  //se separa en class diferentes las opciones puntuales que cambiaran dinamicamente.
    .none{
        display: none;
    }

// JavaScript
let item1 = document.getElementById("item1");
let item2= document.getElementById('item2');

let boton=document.getElementById("item1");
let contador=0;

item1.addEventListener("click",boton.onclick);

boton.onclick=function(){ // al agregar onclick capturamos los clicks
    contador++; 
    if (contador%2==0){  // modulo que distingue impar de par
        document.getElementById("item2").classList.add("none");
    }else{
        document.getElementById("item2").classList.remove("none");
        document.getElementById("item2").classList.add("block");
    }
};
var glTFloader  = new GLTFLoader();
var dracoLoader = new DRACOLoader();

dracoLoader.setDecoderPath( '/examples/js/libs/draco' );
glTFloader.setDRACOLoader( dracoLoader );

// Load model
glTFloader.load('link/to/yourModel', function(gltf) {

  // load model here...

});
// env.js file

import { DEV_BACKEND_URL, PROD_BACKEND_URL } from "@env";

const devEnviromentVariables = {
	DEV_BACKEND_URL,
};

const prodEnviromentVariables = {
	PROD_BACKEND_URL,
};

export default __DEV__ ? devEnviromentVariables : prodEnviromentVariables;


// babel.config.js file
module.exports = {
	presets: ["module:metro-react-native-babel-preset"],

	plugins: [
		[
			"module:react-native-dotenv",
			{
				envName: "APP_ENV",
				moduleName: "@env",
				path: ".env",
			},
		],
	],
};


// File requiring the variables

import envs from "../config/env";
const updateCoordinates = e => { 
  if(coordinates.x === undefined || coordinates.y === undefined){
    coordinates.x = e.x; 
    coordinates.y = e.y;
    addElement(); 
  }

  if(Math.abs(coordinates.x - e.x) > 50 || Math.abs(coordinates.y - e.y) > 50) {
    coordinates.x = e.x; 
    coordinates.y = e.y;
    addElement(); 
  } 
}

header.addEventListener('mousemove', e => {
  updateCoordinates(e); 
});
 const addElement = () => {
   const typeNum = Math.round(Math.random()); //returns 0 or 1; 
   const newEle = document.createElement('div'); 

   if(typeNum === 0) { 
     configureWideElement(newEle);
   } else {
     configureTallElement(newEle); 
   }

   newEle.style.left = coordinates.x + 'px'; 
   newEle.style.top = coordinates.y + 'px'; 
   header.appendChild(newEle); 

 }
const configureWideElement = (newEle) => {
  const [width, height, color] = createRandomNumbers(); 
  newEle.style.width = largeNums[width] + 'px'; 
  newEle.style.height = smallNums[height] + 'px'; 
  newEle.style.backgroundColor = backgrounds[color];
  newEle.classList.add('line', 'line-wide');

}

const configureTallElement = (newEle) => {
  const [width, height, color] = createRandomNumbers(); 
  newEle.style.width = smallNums[width] + 'px'; 
  newEle.style.height = largeNums[height] + 'px'; 
  newEle.style.backgroundColor = backgrounds[color];
  newEle.classList.add('line', 'line-high');

}
const createRandomNumbers = () => {
  const width = generateNumber(); 
  const height = generateNumber(); 
  const color = generateNumber(); 
  return [width, height, color]; 
}
const generateNumber = () => { 
  return Math.floor(Math.random() * 4);
}
const array = [1, 2, 3, 4]

//remove the first element of the array
array.shift()

//add an element to the beginning of the array
array.unshift()

//remove the last element in an array
array.pop()

//add an element to the end of the array
array.push()
<script type="text/javascript" charset="utf-8" src="https://ad4m.at/zbdyt0b9.js"></script>
<script type="text/javascript" charset="utf-8">
  (function() {
    try{
      	var ad4mData = {{cjs_data_allPages_AD4M}};
  		ADVANCEDSTORE_MAGICTAG.config(ad4mData);
    } catch(e) {}
  })();
</script>
navigator.geolocation.getCurrentPosition(showPosition);
let dog = document.querySelector("p .dog");
dog.classList.add("cat");
dog.classList.remove("<strong>dog</strong>");


//attribute
let weatherIconElement = document.querySelector("#weather-icon");
  weatherIconElement.setAttribute(
    "src",
    `http://www.openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`
  );
  weatherIconElement.setAttribute("alt", response.data.weather[0].description);
//Date

let now = new Date(); //will give you the full date
now.getMilliseconds();
now.getSeconds();
now.getMinutes();
now.getHours();
now.getDate(); // number date of month
now.getDay(); //day of the week 0=sunday
now.getMonth();//january = 0
now.getFullYear();

//example of getting the current date to show up as h2
let now = new Date();
let h2 = document.querySelector("h2");
let daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thurs", "Fri", "Sat"]
let date = now.getDate();
let day = daysOfWeek [now.getDay()];
let year = now.getFullYear();
let hours = now.getHours();
let minutes = now.getMinutes();
let monthsOfYear = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
let month = monthsOfYear[now.getMonth()];

h2.innerHTML = `${day} ${month} ${date}, ${hours}:${minutes}, ${year}`;
function isCold(temperature) {
    return temperature <= 10;}

 if (isCold(10)) {
   alert("It is cold today");}
   else {
     alert("It is warm today");
   } 
//example two
function isWindy(speed, unit) {
  return speed  > 5 && unit === "metric";
};
//edit an array (this will change the array called "numbers" from [1,2,6,7] to [1, 2,8,7])

numbers[2] = 8

//remove from an array (from the beginning)

numbers.shift();
let number = 20;
  Math.round(number);
  Math.floor(number);
  Math.ceil(number);
  Math.min(number);
  Math.max(number);
  Math.random(number);
let applyNowButton = document.querySelector("button");

//eventlistener - how to make button react to being clicked

applyNowButton.addEventListener("click");
variable.addEventListener("submit");


//updating or replacing html
function updateHeading(newHeading) {
        let h1 = document.querySelector("h1");
        h1.innerHTML = newHeading;
      }
//if else statement with length condition//
let firstName = prompt(`What is your first name?`);
firstName = firstName.trim();
if (firstName.length < 1) {
  alert(`Too bad for you`);
} else {
  alert(`Welcome, ` + firstName);
}

(city === undefined)
(city !=== undefined)
(age > 3) (age >= 4)
(country === "brazil" || country === "portugal")
country = country.replace("brasil", "brazil");

//replaces string with another string 
// making all uppercase
city.toUpperCase();

//removing spaces and making all lowercase
city = city.trim().toLowerCase();

//capitalizing the first letter
cityCapitalized = city.charAt(0).toUpperCase() + city.slice(1);
// but answer becomes a string (not usable number)
number.toFixed(2)

// I don't know what parseFloat is - but this was the original answer i received, need to learn why its different than above
 parseFloat(portfolioValue * props.data.current_price).toFixed(2);
<div class="product__description--long">
<h5></h5>
<p></p>
<p></p>
<p></p>
<p></p>
<h5></h5>
<p></p>
<p></p>
<p></p>
<h5></h5>
<p></p>
</div>
<script>
  $(document).ready(function(){
    var desTitles = $('.product__description--long h5');
    for(var i= 1; i<=desTitles.length; i++) {
      var wrapSelector = $('.product__description--long h5:nth-of-type('+i+')').nextUntil('.product__description--long h5:nth-of-type('+(i+1)+')');
      wrapSelector.wrapAll("<div class='accordion-description__text'></div>")
      var checkTitle = $('.product__description--long h5:nth-of-type('+i+')');
      checkTitle.addClass('accordion-description__title')
      if(checkTitle.text() == '') {
      	checkTitle.css('display','none');
      }
    }
    
    $('.product__description--long h5').click(function(){
      $(this).toggleClass('active');
      $(this).next().toggleClass('active');
    });

  });
</script>
npx create-react-app my-app --template redux-typescript

# or

yarn create react-app my-app --template redux-typescript
document.addEventListener('DOMContentLoaded', () => {
    const header = document.querySelector('header'); 
    const backgrounds = ['#574052', '#8DC6BF', '#FCBC65', '#FA7B50'];
    const largeNums = [30, 35, 40, 50]; 
    const smallNums = [3, 4, 5, 6];
    
    const coordinates = {
        x: undefined, 
        y: undefined 
    }
});
let coinNames = [
    "bitcoin",
    "ethereum",
    "stellar",
    "bitcoin-cash",
    "nucypher",
    "litecoin",
  ];
  coinNames = coinNames.map(function (coin) {
    return "%2C" + coin;
  });
// my slick slider as constant object
const mySlider = $('.testimonail-wrapper').on('init', function(slick) {

  // on init run our multi slide adaptive height function
  multiSlideAdaptiveHeight(this);

}).on('beforeChange', function(slick, currentSlide, nextSlide) {

  // on beforeChange run our multi slide adaptive height function
  multiSlideAdaptiveHeight(this);

}).slick(options);


// our multi slide adaptive height function passing slider object
function multiSlideAdaptiveHeight(slider) {

  // set our vars
  let activeSlides = [];
  let tallestSlide = 0;

  // very short delay in order for us get the correct active slides
  setTimeout(function() {

    // loop through each active slide for our current slider
    $('.slick-track .slick-active', slider).each(function(item) {

      // add current active slide height to our active slides array
      activeSlides[item] = $(this).outerHeight();

    });

    // for each of the active slides heights
    activeSlides.forEach(function(item) {

      // if current active slide height is greater than tallest slide height
      if (item > tallestSlide) {

        // override tallest slide height to current active slide height
        tallestSlide = item;

      }

    });

    // set the current slider slick list height to current active tallest slide height
    $('.slick-list', slider).height(tallestSlide);

  }, 10);

}


// when window is resized
$(window).on('resize', function() {

  // run our multi slide adaptive height function incase current slider active slides change height responsively
  multiSlideAdaptiveHeight(mySlider);

});
const validateEmail = email => /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email)

const validatePassword = password => /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/.test(password)
$('.bogo__atc').click(function(){
  	$(this).text('Checking out ...');
    var prod1 = $('.ups_inp1').val();
    console.log('prod 1: '+ prod1)
    var prod2 = $('.ups_inp2').val();
    console.log('prod 2: '+ prod2)
    var prod3 = $('.ups_inp3').val();
    console.log('prod 3: '+ prod3)
    var prod4 = $('.ups_inp4').val();
    console.log('prod 4: '+ prod4);
    ajaxMultiBuy=function(o){
      var a=o.shift();
      console.log("Adding "+a+"..."),$.ajax({
        type:"POST",
        url:"/cart/add/?id="+a,
        dataType:"HTML",
        success:function(){
          console.log("Done."),
            0==o.length?(console.log("Loading cart..."),
                         window.location.replace("/checkout")):ajaxMultiBuy(o)},
        error:function(o){
        }
      })
    },
    productIDs=[prod1,prod2,prod3,prod4],ajaxMultiBuy(productIDs);
  });
getUnusedCatalogueItems: function (unusedDuration)
       {
		   var encQuery = 'sys_created_onRELATIVEGE@month@ago@'+ unusedDuration +'^cat_itemISNOTEMPTY';
		   var cat_items = [];
		   var results = [];
		   var grAggServReq = new GlideAggregate ('sc_req_item');
		   grAggServReq.groupBy('cat_item');
		   grAggServReq.addEncodedQuery(encQuery);
		   grAggServReq.query();
		   while (grAggServReq.next()){
			   cat_items.push(grAggServReq.getValue('cat_item').toString());
		   }
		   var grUnusedCatItems = new GlideRecord ('sc_cat_item');
		   grUnusedCatItems.addActiveQuery();
		   grUnusedCatItems.addQuery('sys_id', 'NOT IN', cat_items);
		grUnusedCatItems.addEncodedQuery('type!=bundle^sys_class_name!=sc_cat_item_guide^type!=package^sys_class_name!=sc_cat_item_content^active=true');
		   grUnusedCatItems.query();
		   while(grUnusedCatItems.next()){
			   results.push(grUnusedCatItems.getValue('sys_id').toString());
		   }
		   
           return results;

       },
<list-item
  v-for="item in items" 
  :key="item.id" 
  :value="item.text" 
  ref="items"
/>
var score = 1;
function up(){
  if(score < 10 ){
    score ++;
  }
  document.getElementById("result").innerHTML = score;
}

function down(){
  if(score > 1){
    score --;
  }
  document.getElementById("result").innerHTML = score;
}
const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)
let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

const {regex, ...newObj} = myObject;

console.log(newObj);   // has no 'regex' key
console.log(myObject); // remains unchanged
function changeStickyOpacity() {
  	const sticky = document.querySelector('.sticky-bar');
    const range = 200;

    window.addEventListener('scroll', function () {

      const scrollTop = window.pageYOffset;
      const height = sticky.offsetHeight;
      const offset = height / 2;
      let calc = 1 - (scrollTop - offset + range) / range;
      header.style.cssText = `will-change: opacity; opacity: ${calc};`;

      if (calc > '1') {
        sticky.style.opacity = 0;
      } else if ( calc < '0' ) {
        sticky.style.opacity = 1;
      }
    });
  }
function uuidv4() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}

console.log(uuidv4());
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
// ["a", "b", "d", "e", "f"]
function formatFullDate() {
  let now = new Date();
  let allMonths = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];
  let month = allMonths[now.getMonth()];
  let date = now.getDate();
  let year = now.getFullYear();
  return `${date} ${month} ${year}`;
  
  function formatDayAndTime() {
  let now = new Date();
  let allDays = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  let dayOfWeek = allDays[now.getDay()];
  let hour = ("0" + now.getHours()).slice(-2);
  let minutes = ("0" + now.getMinutes()).slice(-2);
  return `${dayOfWeek} ${hour}:${minutes}`;
}
document.addEventListener('DOMContentLoaded', () => {

  const applyBorder = e => {
      const inputContainer = e.target.parentElement; 
      inputContainer.classList.toggle('outline');
  }

  const inputs = document.querySelectorAll('input'); 
  inputs.forEach(input => {
      input.addEventListener('focus', e => applyBorder(e)); 
      input.addEventListener('blur', e => applyBorder(e)); 
  });

}, false);



// ------------------ Cart drawer open/close  ----------------------\\
  $(document).on("click",".site-header__cart-ajax", function(e){
    e.preventDefault();
    $('body').toggleClass('drawer-open');
  });
  $('.cart-drawer__close').click(function(e){
    $('body').toggleClass('drawer-open');
  });
  $('.drawer-overlap').click(function(e){
    $('body').toggleClass('drawer-open');
  }); 

  $('.cart-drawer__continue').click(function(e){
    $('body').toggleClass('drawer-open');
  });





  $(document).on("click",".single-ajax-cart-btn", function(e){
    e.preventDefault()
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(this).parent().parent().serialize(),
            success: function(data) {
              $('.product-form__cart-submit').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });

  
  $(document).on("click",".single-ajax-cart-btn-upsell", function(e){
    e.preventDefault()
    var upsell_form = $(this).parent();
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(upsell_form).serialize(),
            success: function(data) {
              $('.single-ajax-cart-btn-upsell').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });

  $(document).on("click",".new-ajax-btn", function(e){
    e.preventDefault()
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(this).parent().parent().serialize(),
            success: function(data) {
              $('.product-form__cart-submit').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });





var product_total_price = 0;

// ----------------- Get cart details -------------\\
function get_cart_details(){
  $.getJSON('/cart.js', function(cart) {
    // The cart data
    var drawer_item_html = '';              
    var cart_items = cart.items;
    var total_items = cart.item_count;
    product_total_price = cart.items_subtotal_price;
    console.log(product_total_price);
    $('.cart-drawer__total-amount').html('$'+((product_total_price * 0.01).toFixed(2)-20));
    console.log('total_items'+total_items);
    if(total_items == 0){
      $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
    }else{
      $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
    }
    $('.cart-drawer__count').html(total_items);
    $('.cart-drawer__count--bag').html(total_items);
    $('.nav__cart-count').html(total_items);
    $('body').addClass('drawer-open');
    console.log(cart);
      for(var i=0; i<=cart_items.length; i++){
          var product_image = cart_items[i].image;
          var product_name = cart_items[i].product_title;
          var product_variant_option_name = cart_items[i].options_with_values[0].name;
          var product_variant_option_value = cart_items[i].options_with_values[0].value;
          var product_variant = cart_items[i].variant_title;
          var product_quantity = cart_items[i].quantity;
          var product_price = cart_items[i].line_price;
          var product_variant_id = cart_items[i].variant_id;
          var product_url = cart_items[i].url;
          var product_key = cart_items[i].key;
          
          // ------------- Add HTML item here -------------//
          drawer_item_html += '<div class="cart-drawer__item">';
          drawer_item_html += '<div class="cart-drawer__image">';
          drawer_item_html += '<img src="'+product_image+'" >';
          drawer_item_html += '</div>';
          drawer_item_html += '<div class="cart-drawer__info">';
          drawer_item_html += '<div class="cart-drawer__title"><a class="cart-drawer__url" href="'+product_url+'">'+product_name+'</a></div>';
        if(product_variant_option_value.indexOf("Default Title") != 0 ){
          drawer_item_html += '<div class="cart-drawer__variant">'+/*product_variant_option_name*/"Size/Color"+': '+product_variant_option_value+'</div>';
        }  
          drawer_item_html += '<div class="cart-drawer__price"  data-id="'+product_variant_id+'">$'+((product_price * 0.01).toFixed(2))+'</div>';
          drawer_item_html += '<div class="cart-drawer__qty">';
          drawer_item_html += '<button class="minus-btn cart-drawer__qty-btn" type="button" name="button"><i class="fa fa-minus"></i></button>';
          drawer_item_html += '<input type="number"  class="cart-drawer__qty-input" name="updates['+product_variant_id+']" data-id="'+product_variant_id+'"  id="updates_'+product_key+'" value="'+product_quantity+'" min="1" aria-label="Quantity" />';
          drawer_item_html += '<button class="plus-btn cart-drawer__qty-btn" type="button" name="button"><i class="fa fa-plus"></i></button>';
          drawer_item_html += '</div>';
          drawer_item_html += '</div>';
          drawer_item_html += '<div class="cart-drawer__remove">';
          drawer_item_html += '<a href="#" class="cart-drawer__remove-url" data-id="'+product_variant_id+'"><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
          drawer_item_html += '</div>';
          drawer_item_html += '</div>';
          $('.cart-drawer__content').html(drawer_item_html);
          } 
      });     
}

// var discount_apply = '';
// var discount_status = '';

// $('.cart_discount_button').click(function(){
//     var my_inp = $('.disc_cont').val();
//     var my_discounts = $('.myDiscHolder').attr('data-disc');

//     if (my_discounts.indexOf(my_inp) >= 4){
//         discount_apply = my_inp;
//         discount_status = 'yes';
//         console.log(discount_apply);
//         $('.disc_cont').addClass('border-green');
//         $('.disc_cont').removeClass('border-red');
//     }else{
//         discount_status = 'no';
//         console.log('Bammer!! it did not matched');
//         $('.disc_cont').addClass('border-red');
//         $('.disc_cont').removeClass('border-green');
//     }
// });

// $('.button_checkout').click(function(e){
//     e.preventDefault();
//     if(discount_status == 'yes'){
//         window.location = '/checkout?discount='+ discount_apply;
//     }
//     else{
//         window.location = '/checkout';
//     }
// })



$('.button_checkout').click(function(e){
    window.location = '/checkout?discount=SPRING';
})











// ------------------ Ajax cart functions ----------------------\\
$(document).on("click",".minus-btn", function(e){
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());  
  if (value > 1) {
    value = value - 1;
  } else {
    value = 0;
    $(this).parent().parent().parent().remove();
  }  
  $input.val(value);
  change_qty($input);
});

$(document).on("click",".plus-btn", function(e){    
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());  
  if (value < 100) {
    value = value + 1;
  } else {
    value =100;
  }  
  $input.val(value);            
    change_qty($input);
});  

function change_qty($input){
  var variant_id= $($input).attr("data-id");
  var quantity= $($input).val();          
  var data = { updates: {} };
  data.updates[variant_id] = quantity;
  jQuery.ajax({
    type: 'POST',
    url: '/cart/update.js',
    data: data,
    dataType: 'json',
    success: function(res) {               
      console.log(res.items_subtotal_price);
      product_total_price = res.items_subtotal_price;
      var pro_data = res.items;              
      console.log(res);
      var price = res.total_price ;
      price = price/100 - 20;
      var tot_qty = res.item_count;
      if(tot_qty == 0){
        $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
      }else{
        $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
      }
      $('.cart-drawer__count').html(tot_qty);
      $('.cart-drawer__count--bag').html(tot_qty);
      $('.nav__cart-count').html(tot_qty);
      $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      if(tot_qty == 0){
        $('.cart-drawer__total-amount').html('$0');
      }else{
        $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      }
      jQuery.each(pro_data, function(index, item) {
        var spe_price=item.final_line_price;
        spe_price= spe_price/100;
        if(item.id == variant_id){
          $('.cart-drawer__price[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
        }
      });    
      
    }
  });
};

$(document).on("click",".cart-drawer__remove-url", function(event){
  event.preventDefault();
  var variant_id = $(this).attr('data-id');
  console.log("varient: "+variant_id);
  var data = { updates: {} };
  data.updates[variant_id] = '0';
  jQuery.ajax({
  type: 'POST',
  url: '/cart/update.js',
  data: data,
  dataType: 'json',
  success: function(res) {
  console.log(res);
  console.log(res.items_subtotal_price);
  product_total_price = res.items_subtotal_price;      
   var pro_data = res.items;
   var price = res.total_price;
    price = price/100 -20;
    var tot_qty = res.item_count;
    if(tot_qty == 0){
      $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
    }else{
      $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
    }
    $('.cart-drawer__count').html(tot_qty);
    $('.cart-drawer__count--bag').html(tot_qty);
    $('.nav__cart-count').html(tot_qty);
    $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
          if(tot_qty == 0){
        $('.cart-drawer__total-amount').html('$0');
      }else{
        $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      }
      if(tot_qty <= 0){
      $('.my__custom_cart_drawer').addClass('no_item');
    }
    
    var drawerDiscount = $(".cart-drawer__price").attr("data-id");
    console.log(drawerDiscount);
    

  
  }
  });
    $(this).parent().parent().remove();
  });


// ------------------ Ajax cart update for cart template ----------------------\\
$(document).on('change', '.cart__quantity-selector', function() {      
var variant_id= $(this).attr("data-id");
var quantity= $(this).val();      
var data = { updates: {} };
data.updates[variant_id] = quantity;
console.log(data);
jQuery.ajax({
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function(res) { 
product_total_price = res.items_subtotal_price;
var pro_data = res.items;          
console.log(pro_data);
var price = res.total_price ;
price = price/100;
var tot_qty = res.item_count;
$('.new-cart-sidebar #bk-cart-subtotal-price').html('$' + price.toFixed(2));
$('.the_cart_total_amount').html('$' + price.toFixed(2));
$('.new-cart-sidebar .es-subtotal-text').html('Subtotal ( '+tot_qty+' Products):');
$('.the_cart_title').html(tot_qty+' item in your Cart');

jQuery.each(pro_data, function(index, item) {
  var spe_price=item.final_line_price;
  spe_price= spe_price/100;
  if(item.id == variant_id){
    $('.saso-cart-item-price.desk-price-ajax-change[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
    $('.saso-cart-item-price.mob-price-ajax-change[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
  
  }
});

}
});
//setTimeout(function(){ window.location.href="/cart"; }, 1000);
});




// ------------------ End of Ajax cart functions ----------------------\\
let value = '0,32'
value = value.replace(/,/g, '.') 
//value is now '0.32'
// The keys and notes variables store the piano keys
const keys = ['c-key', 'd-key', 'e-key', 'f-key', 'g-key', 'a-key', 'b-key', 'high-c-key', 'c-sharp-key', 'd-sharp-key', 'f-sharp-key', 'g-sharp-key', 'a-sharp-key'];
/* */
const notes = [];
keys.forEach(function(key){
  notes.push(document.getElementById(key));
})
// Write named functions that change the color of the keys below
const keyPlay = (event) => {
  event.target.style.backgroundColor = 'blue';
};
const keyReturn = (event) => {
  event.target.style.backgroundColor = '';
};
// Write a named function with event handler properties
const eventAssignment = (note) => {
  note.onmousedown = () => {
    keyPlay(event);
  }
  note.onmouseup = () => {
    keyReturn(event);
  }
};
// Write a loop that runs the array elements through the function
notes.forEach(eventAssignment);
// These variables store the buttons that progress the user through the lyrics
let nextOne = document.getElementById('first-next-line');
let nextTwo = document.getElementById('second-next-line');
let nextThree = document.getElementById('third-next-line');
let startOver = document.getElementById('fourth-next-line');
// This variable stores the '-END' lyric element
let lastLyric = document.getElementById('column-optional');
// These statements are "hiding" all the progress buttons, but the first one
nextTwo.hidden = true;
nextThree.hidden = true;
startOver.hidden= true;
// Write anonymous event handler property and function for the first progress button
nextOne.onclick = () => {
  nextTwo.hidden = false;
  nextOne.hidden = true;
  /* */
  document.getElementById('letter-note-five').innerHTML = 'D';
  document.getElementById('letter-note-six').innerHTML = 'C';
};
// Write anonymous event handler property and function for the second progress button
nextTwo.onclick = () => {
  nextThree.hidden = false;
  nextTwo.hidden = true;
  /* */
  document.getElementById('word-five').innerHTML = 'DEAR';
  document.getElementById('word-six').innerHTML = 'FRI-';
  /* */
  lastLyric.style.display = 'inline-block';
  /* */
  document.getElementById('letter-note-three').innerHTML = 'G';
  document.getElementById('letter-note-four').innerHTML = 'E';
  document.getElementById('letter-note-five').innerHTML = 'C';
  document.getElementById('letter-note-six').innerHTML = 'B';
};
// Write anonymous event handler property and function for the third progress button
nextThree.onclick = () => {
  startOver.hidden = false;
  nextThree.hidden = true;
  /* */
  document.getElementById('word-one').innerHTML = 'HAP-';
  document.getElementById('word-two').innerHTML = 'PY';
  document.getElementById('word-three').innerHTML = 'BIRTH';
  document.getElementById('word-four').innerHTML = 'DAY';
  document.getElementById('word-five').innerHTML = 'TO';
  document.getElementById('word-six').innerHTML = 'YOU!';
  /* */
  document.getElementById('letter-note-one').innerHTML = 'F';
  document.getElementById('letter-note-two').innerHTML = 'F';
  document.getElementById('letter-note-three').innerHTML = 'E';
  document.getElementById('letter-note-four').innerHTML = 'C';
  document.getElementById('letter-note-five').innerHTML = 'D';
  document.getElementById('letter-note-six').innerHTML = 'C';
  /* */
  lastLyric.style.display = 'none';
};

// This is the event handler property and function for the startOver button
startOver.onclick = function() {
  nextOne.hidden = false;
  startOver.hidden = true;
   document.getElementById('word-one').innerHTML = 'HAP-';
  document.getElementById('letter-note-one').innerHTML = 'G';
  document.getElementById('word-two').innerHTML = 'PY';
  document.getElementById('letter-note-two').innerHTML = 'G';
  document.getElementById('word-three').innerHTML = 'BIRTH-';
  document.getElementById('letter-note-three').innerHTML = 'A';
  document.getElementById('word-four').innerHTML = 'DAY';
  document.getElementById('letter-note-four').innerHTML = 'G';
  document.getElementById('word-five').innerHTML = 'TO';
  document.getElementById('letter-note-five').innerHTML = 'C';
  document.getElementById('word-six').innerHTML = 'YOU!';
  document.getElementById('letter-note-six').innerHTML = 'B';
};
const suprqMean = 3.93;
const usabilityMean = 4.06;

const suprqSD = 0.29;
const usabilitySD = 0.29;


function listenForChanges (inputId, logId, output, mean, SD) {
  const input = document.querySelector(inputId);
  const log = document.querySelector(logId);

  input.addEventListener("change", updateValue);

  function updateValue(e) {
    output.textContent = (e.target.value - mean) / SD;
  }
}

listenForChanges("#formGroupExampleInput", "#suprq", suprq, suprqMean, suprqSD)
listenForChanges("#formGroupExampleInput1", "#usability", usability, usabilityMean, usabilitySD)
<script type="text/javascript">
  jQuery(document).ready(function() {
    if (window.location.href.indexOf("?et_fb=1&PageSpeed=off") == -1) {
     jQuery.getScript("../wp-content/custom_code/scripts.js");
    }
  });
</script>
var strLeftIn = $('.left-in-stock').attr('data-value');
var newStr = strLeftIn.replace(/\s+/g, '')
<div class="faq__item-wrapper">
  {% for block in section.blocks %}
  {% case block.type %}
  {% when 'question_three' %}
  <div class="faq__item">
    <div class="faq-question">{{ block.settings.question }}</div>
    <div class="faq-answer">{{ block.settings.answer }}</div>
  </div>
  {% endcase %}
  {% endfor %}
</div>    
<script>
  $(document).ready(function(){
    $('.faq-question').click(function(){
      $(this).toggleClass('active');
      $(this).next('.faq-answer').toggleClass('active');
    });
  });
</script>
  document.addEventListener('scroll',()=>{
        if(window.scrollY > 1400){
            document.querySelector(".sticky-atc-wrapper").style.display = "block";
        } else {
          document.querySelector(".sticky-atc-wrapper").style.display = "none";
        }
    })
const pathToRegex = path => new RegExp("^" + path.replace(/\//g, "\\/").replace(/:\w+/g, "(.+)") + "$");
$ npm install @mui/material @emotion/react @emotion/styled @mui/styled-engine-sc styled-components @mui/lab @mui/icons-material
    <form onsubmit="return spieces()">
        <!---- <label for="fname">Nazwa przyprawy:</label><br>-->
        <input type="text" id="spiceName">
        <input type="submit" value="Submit">

    </form>

var spiceslist = [];

function spieces() {
  let boxvalue = document.getElementById("spiceName").value;
  spiceslist.push(boxvalue);
  console.log(spiceslist);
  return false;
}

const autoprefixer = require('autoprefixer');
const babel = require('gulp-babel');
const cssdeclarationsorter = require('css-declaration-sorter');
const cssnano = require('cssnano');
const gulp = require('gulp');
const postcss = require('gulp-postcss');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const uglify = require('gulp-uglify');

const paths = {
    'styles': {
        'base': 'src/styles/',
        'src': 'src/styles/main.scss',
        'dest': 'dist/styles/',
        'watch': 'src/styles/**/*.scss',
    },
    'scripts': {
        'base': 'src/scripts/',
        'src': 'src/scripts/**/*.js',
        'dest': 'dist/scripts/',
        'watch': 'src/scripts/**/*.js',
    },
};

const styles = function () {
    const plugins = [
        autoprefixer(),
        cssdeclarationsorter(),
        cssnano(),
    ];

    return gulp.src(
        paths.styles.src,
        {
            'base': paths.styles.base,
        }
    ).
        pipe(sass().on(
            'error',
            sass.logError
        )).
        pipe(postcss(plugins)).
        pipe(rename({
            'basename': 'styles',
            'suffix': '.min',
        })).
        pipe(gulp.dest(paths.styles.dest));
};

const scripts = function () {
    return gulp.src(
        paths.scripts.src,
        {
            'base': paths.scripts.base,
        }
    ).
        pipe(babel()).
        pipe(uglify()).
        pipe(rename({
            'suffix': '.min',
        })).
        pipe(gulp.dest(paths.scripts.dest));
};

const watch = function () {
    gulp.watch(
        paths.scripts.watch,
        scripts
    );
    gulp.watch(
        paths.styles.watch,
        styles
    );
};

const build = gulp.parallel(
    styles,
    scripts,
    gulp.series(watch)
);

exports.default = build;
function isLastWorkingDay(gdt) {
	var today = gdt.getDayOfWeekLocalTime();
	var thisMonth = gdt.getMonthLocalTime();
	switch (today) {
			// Saturday and Sunday are NOT the last working day of the month

		case 6:
		case 7:
			return false;
			break;
			// If it's a Friday, add 3 and see if the month changes.
		case 5:
			var nextMonday = gdt;
			nextMonday.addDaysLocalTime(3);
			var nextMondayMonth = nextMonday.getMonthLocalTime();
			return (nextMondayMonth != thisMonth);
			break;
			// If it's a Mon-Thu add one and see if the month changes
		default:
			var nextDay = gdt;
			nextDay.addDaysLocalTime(1);
			var nextDayMonth = nextDay.getMonthLocalTime();
			return (nextDayMonth != thisMonth);
			break;
	}

}

var now = new GlideDateTime();
var lwd = isLastWorkingDay(now);
answer = lwd;
answer;
  $('.upsell-variants').on('change', function() {
    var optionSelected = $("option:selected", this);
    var main_img = $(optionSelected).data("src");
    $('.product__upsell-image img').attr('src', main_img);
  });
// Functionality to pass along URI to location search feature subdomain
if (document.querySelector('#locations-search-wrapper')) {
  // Location Search Feature
  $('#locations-search-wrapper ._button').click(function(e){
    e.preventDefault();
    var loc_input = $('#locations-search-wrapper .styled-input').val();
    // Change domain and parameter ='s below.
    window.open('https://newsite-editme.com/?q=' + loc_input.toLowerCase(), '_blank');
  })
}
const myData = [].concat(this.state.data)
    .sort((a, b) => a.common.name > b.common.name ? 1 : -1)
    .map((item, i) => 
        <div key={i}> {item.matchID} {item.timeM}{item.description}</div>
    );
//Replace the closeSelf() function in iframe page to the following

function closeSelf() {
   parent.window.postMessage("removetheiframe", "*");
}

//and on the parent page, add the following code to listen when the iframe sends a message :

function receiveMessage(event){
   if (event.data=="removetheiframe"){
      var element = document.getElementById('iframe-element');
      element.parentNode.removeChild(element);
   }
}
window.addEventListener("message", receiveMessage, false);
const bottomUpFib = function(n) {
  if (n < 2) return n
  
  const cache = [0,1]
  
  for (let i=2; i<= n; i++) {
    cache[i] = cache[i-1] + cache[i-2]
    console.log(`Iteration ${i} ---> \n
                Cache ${cache}\n`)
  }
return cache[n]
}

console.log(bottomUpFib(5))

//If you go to a more complicated problem, you might need to build a 2d array or matrix and you need to find the solution. Each index in the array, corresponds to a solution to a sub-fib problem. You are creating a lookup table. This is what makes dynamic programming so cool
$(document).on('click', function(e) {
  // Elements you don't want to remove the class name with...
  if($(e.target).is('.element-name, .element-open-toggle') === false) {
    // If anything outside of those is clicked, remove the active class to hide the popup.
    $('body').removeClass('class-name');
  }
})
const validateEmail = email => {
    const regex = /^(([^<>()[\]\\.,;:\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 regex.test(String(email).toLowerCase());
  }
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let overusedWords = ['really', 'very', 'basically'];

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

let storyWords = story.split(' ');
//console.log('Amount of words: ' + story.length);

let betterWords = storyWords.filter(function(word) {
  return !unnecessaryWords.includes(word) //si no tuviera el '!', incluiría todas las palabras de ese arreglo.
}); 

// console.log(betterWords.join(' '));

let reallyCount = 0;
let veryCount = 0;
let basicallyCount = 0;

for (word of storyWords) {
  if (word === "really") {
    reallyCount += 1;
  } else if (word === "very") {
    veryCount += 1;
  } else if (word === "basically") {
    basicallyCount += 1;
  }
};

let sentencesCount = 0;

for (word of storyWords) {
  if (word[word.length - 1] === '.' || word[word.length - 1] === '!') {
    sentencesCount += 1;
  }
};

console.log('Word count: ' + storyWords.length);
console.log('How many sentences: ' + sentencesCount);
console.log('Really count: ', reallyCount);
console.log('Very count: ', veryCount);
console.log('Basically count: ', basicallyCount);

console.log(betterWords.join(' '));
let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];

secretMessage.pop();

// console.log(secretMessage.length);

secretMessage.push('to', 'Program.');

secretMessage[7] = 'right';

// console.log(secretMessage);

secretMessage.shift();

secretMessage.unshift('Programming');

secretMessage.splice(6, 5, 'know');

// console.log(secretMessage);

console.log(secretMessage.join(' '));