/***********/
/*POLYFILL*/
/**********/
if (!Array.prototype.indexOf)  Array.prototype.indexOf = (function(Object, max, min){
	"use strict";
	return function indexOf(member, fromIndex) {
	if(this===null||this===undefined)throw TypeError("Array.prototype.indexOf called on null or undefined");

	var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len);
	if (i < 0) i = max(0, Len+i); else if (i >= Len) return -1;

	if(member===void 0){ for(; i !== Len; ++i) if(that[i]===void 0 && i in that) return i; // undefined
	}else if(member !== member){   for(; i !== Len; ++i) if(that[i] !== that[i]) return i; // NaN
	}else                           for(; i !== Len; ++i) if(that[i] === member) return i; // all else

	return -1; // if the value was not found, then return -1
	};
})(Object, Math.max, Math.min);

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: https://es5.github.io/#x15.4.4.18

if (!Array.prototype['forEach']) {

  Array.prototype.forEach = function(callback, thisArg) {

	if (this == null) { throw new TypeError('Array.prototype.forEach called on null or undefined'); }

	var T, k;
	// 1. Let O be the result of calling toObject() passing the
	// |this| value as the argument.
	var O = Object(this);

	// 2. Let lenValue be the result of calling the Get() internal
	// method of O with the argument "length".
	// 3. Let len be toUint32(lenValue).
	var len = O.length >>> 0;

	// 4. If isCallable(callback) is false, throw a TypeError exception.
	// See: https://es5.github.com/#x9.11
	if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); }

	// 5. If thisArg was supplied, let T be thisArg; else let
	// T be undefined.
	if (arguments.length > 1) { T = thisArg; }

	// 6. Let k be 0
	k = 0;

	// 7. Repeat, while k < len
	while (k < len) {

	  var kValue;

	  // a. Let Pk be ToString(k).
	  //    This is implicit for LHS operands of the in operator
	  // b. Let kPresent be the result of calling the HasProperty
	  //    internal method of O with argument Pk.
	  //    This step can be combined with c
	  // c. If kPresent is true, then
	  if (k in O) {

		// i. Let kValue be the result of calling the Get internal
		// method of O with argument Pk.
		kValue = O[k];

		// ii. Call the Call internal method of callback with T as
		// the this value and argument list containing kValue, k, and O.
		callback.call(T, kValue, k, O);
	  }
	  // d. Increase k by 1.
	  k++;
	}
	// 8. return undefined
  };
}

/********/
/* GETS */
/********/
function getParameterByName(name) {
	name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
	var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
		results = regex.exec(location.search);
	return results == null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

function getCleanURL(url){
	let s1 = url.split('?');
	let s2 = s1[1].split('&');

	let ss1 = /compid/;
	let ss2 = /formid/;
	let ss3 = /h=/;

	let i;

	let fin = s1[0] + '?';

	for(i=0;i<s2.length;i++){
		if(ss1.test(s2[i])){
			fin = fin + s2[i] + '&';
		}else if(ss2.test(s2[i])){
			fin = fin + s2[i] + '&';
		}else if(ss3.test(s2[i])){
			fin = fin +s2[i];
		}
	}

	return fin;
}

function getLPIDdl(){
	let uTemp = document.getElementsByTagName('img');
	let substr2 = /LandingPageID/;
	let lpid;
	let split1, split2;
	let str;

	for(i=0;i<uTemp.length;i++){
		if(substr2.test(uTemp[i].src)){
			str = uTemp[i].src;
		}
	}

	split1 = str.split('&');

	for(i=0;i<split1.length;i++){
		if(substr2.test(split1[i])){
			split2 = split1[i].split('=');
			lpid = split2[1];
		}
	}

	return lpid;
}

function getTimeMetrices(type){ //1=time in pst, 2=day, 3=weekend/weekday
	let year = new Date().getFullYear();
	let currDate = new Date(); //local Date/Time
	let utcHours = currDate.getUTCHours(); //UTC hours (24-hr format)
	// console.log(currDate);
	// console.log(currDate.getUTCHours());
	let dummy = "";

	let dstUS = function(){
		//start of dst
			dummy = new Date(year, 2, 7);
			let secondSunday = 7 + (7 - dummy.getDay()); 	
			let dstStart = new Date(year, 2, secondSunday); //second sunday of march
			// console.log(dstStart);
		//end of dst
			dummy = "";
			dummy = new Date(year, 10, 7);	
			let firstSunday = 7 - dummy.getDay();
			let dstEnd = new Date(year, 10, firstSunday); //first sunday of november
			// console.log(dstEnd);

		//return unsigned offset
		if(currDate >= dstStart && currDate <= dstEnd){
			return(7);
		}else{
			return(8);
		}
	};

	let offset = dstUS();
	let pstHour = (utcHours - offset) + 24;
	let pstDay = "";
	let pstDayType = "";
	let pstTime = "";

	if((pstHour <= 23) && (currDate.getMinutes() <= 59) && (currDate.getSeconds() <= 59)){
		dummy = currDate.getDate() - 1;
	}else{
		dummy = currDate.getDate();
	}

	if(pstHour == 24){
		pstHour = 0;
	}

	let pstDayTime = new Date(year,currDate.getMonth(),dummy,pstHour,currDate.getMinutes(),currDate.getSeconds());
	//console.log(pstDayTime);
	if(type == 1){
		if(pstDayTime.getHours() > 12){
			dummy = (pstDayTime.getHours() - 12) + ":" + pstDayTime.getMinutes() + "PM";
		}else{
			dummy = pstDayTime.getHours() + ":" + pstDayTime.getMinutes() + "AM";
		}

		return dummy;
	}else if(type == 2){
		dummy = pstDayTime.getDay();

		switch(dummy){ //Day in PST
			case 0:
				pstDay = "Sunday";
				break;
			case 1:
				pstDay = "Monday";
				break;
			case 2:
				 pstDay = "Tuesday";
				break;
			case 3:
				pstDay = "Wednesday";
				break;
			case 4:
				pstDay = "Thursday";
				break;
			case 5:
				pstDay = "Friday";
				break;
			case 6:
				pstDay = "Saturday";
		}
		//console.log(pstDay);
		return pstDay;
	}else if(type == 3){
		dummy = pstDayTime.getDay();
		if((dummy == 0) || (dummy == 6)){ //Weekend/Weekday in PST
			pstDayType = "Weekend";
		}else{
			pstDayType = "Weekday";
		}
		//console.log(pstDayType);
		return pstDayType;
	}
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function getDLIndex(name){ //returns -1 if not found
	const find = (element) => element.name == name;

	return nlDataLayer.findIndex(find);
}

/********/
/* SETS */
/********/
function setCookie(name,value,days,domain) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/; domain="+domain+";";
    //console.log("cookie set");
}

/********/
/* MISC */
/********/
function searchArray(arr, key) {
	let isFound = false;
	let i;

	for (i = 0; i < arr.length; i++) {
	  if (arr[i] == key) {
		isFound = true;
	  }
	}

	return isFound;
}

function nlDataLayerPush(name,attributes){ 
	if(Array.isArray(attributes)){
		let attr = {};
		let key, i;
		for(i=0;i<attributes.length;i++){
			for(key in attributes[i]){
				attr[key] = attributes[i][key];
			}
		}

		attributes = attr;
	}

	let node = { 
					"name" : name
					,"attributes" : attributes //parse to plain json
					,"read" : false
					,"timestamp" : new Date().toUTCString() //timestamp in UTC; convert timestamp to PST in format that Infinity requires
				};
	nlDataLayer.push(node);
	//console.log(JSON.stringify(nlDataLayer));
	// console.log(JSON.stringify(attr));
	// console.log(attributes);
}

function utagPush(name,value){
	utag_data[name] = value.toString;
}

/***************/
/* GLOBAL VARS */
/***************/
window.nlDataLayer = window.nlDataLayer || [];
/*{ 
	"name" : 
	,"attributes" : 
	,"read" : true/false
}*/
var nsFormDomains = ['nlcorp.extforms.netsuite.com', '6262239.extforms.netsuite.com', 'nlcorp-sb2.extforms.netsuite.com', '6262239-rp.app.netsuite.com'];
var elqFormDomains = ['go.netsuite.com', 'grow.netsuite.com', 'go-netsuite-com-796203850.p04.elqsandbox.com'];

var nsSB = [];
var crumb = [];

var domain = document.domain;

var separator = ':';

var pageName = "";

/**********/
/* EVENTS */
/**********/

//BEFORE LOAD
	let attributes = [];
	let previousReferrer;

	if(getCookie("previousReferrer")){
		previousReferrer = getCookie("previousReferrer");
	}else{
		previousReferrer = document.referrer;
	}
	//console.log("pr: " + getCookie("previousReferrer"));
	nlDataLayerPush("nsformReferrer",previousReferrer); //for ns form use
	setCookie("previousReferrer",window.location,7,"netsuite.com"); 

	attributes.push({"currentURL" : (window.location.toString())}); //prop11, evar24
	attributes.push({"pathName" : window.location.pathname}); //prop13, evar25
	attributes.push({"fullQueryString" : window.location.search}); //prop12, evar27
	
	//attributes.push({"timePST" : getTimeMetrices(1)}); //prop4, evar5
	//attributes.push({"dayPST" : getTimeMetrices(2)}); //prop5, evar6
	//attributes.push({"dayTypePST" : getTimeMetrices(3)}); //prop6, evar7
	attributes.push({"browserLanguage" : navigator.language}); //prop9

	attributes.push({"domain" : domain}); //evar23
	//attributes.push({"entryURL" : document.location.href}); //evar38

	if(getParameterByName("eid")){
		attributes.push({"eid" : getParameterByName("eid")}); //evar8
	}
	if(getParameterByName("inid")){
		attributes.push({"inid" : getParameterByName("inid")}); //evar9
	}

	if(getParameterByName("gclid")){
		attributes.push({"gclid" : getParameterByName("gclid")}); //evar33
	}

	nlDataLayerPush("beforeLoad",attributes);
//END OF BEFORE LOAD

//ON LOAD
var onLoad = function(){
		attributes = [];

		/*ON LOAD ATTRIBUTES*/
			//FOR LATER
			/*if(getParameterByName("cid")){
				nlDataLayerPush("cid", getParameterByName("cid"));
			}
			if(getParameterByName("fbclid")){
				nlDataLayerPush("fbclid", getParameterByName("fbclid"));
			}
			if(getParameterByName("utm")){
				nlDataLayerPush("utm", getParameterByName("utm"));
			}*/
			if(searchArray(nsFormDomains,domain) ||searchArray(elqFormDomains,domain) ){
				let leadsource = "";

				if(searchArray(nsFormDomains,domain)){ //is form
					pageName = "Form" + separator + getParameterByName("formid");

					if(getParameterByName("leadsource")){
						leadsource = getParameterByName("leadsource");
					}else if(getParameterByName("source")){
						leadsource = getParameterByName("source");
					}

				}else if(searchArray(elqFormDomains,domain)){
					pageName = "Form" + separator + getLPIDdl();

					if(getParameterByName("leadsource")){
						leadsource = getParameterByName("leadsource");
					}else if(getParameterByName("source")){
						leadsource = getParameterByName("source");
					}else if(getParameterByName("nsCampaignCode")){
						leadsource = getParameterByName("nsCampaignCode");
					}
				}

				if(leadsource == ""){
					leadsource = "Website_Forms";
				}

				attributes.push({"leadsource" : leadsource});
				attributes.push({"pageType"	: "forms"}); //eVar26
				attributes.push({"pageName"	: pageName}); //eVar13, eVar15, eVar18, eVar3, prop8

			}else{
				let pageType = "";

				//page name --> s.getPageName
				//page type --> s.getPageType , s.isThankYouPage
				//form type --> s.getFormType
				//form title (?) --> s.getFormTitle

				let loc = window.location.pathname.toLowerCase();
				let p = loc.substring(loc.lastIndexOf("/") + 1);

				let breadcrumbs = document.querySelectorAll(".breadcrumb li");
				if(breadcrumbs.length > 0){
					let k;
					breadcrumbs.forEach((breadcrumb) => {
						crumb.push(breadcrumb.innerText.trim()); 
					});
					pageName = crumb.join(separator);
				}

				if((loc.indexOf('/resource/') != -1 && p.indexOf('thank') != -1) 
					|| (loc.indexOf('/confirmation/') != -1 && p.indexOf('thank') != -1) 
					|| (loc.indexOf('/resource/') != -1 && p.indexOf('freetrial-ensighten-update-test.shtml') != -1)
					){ //TY Page
					pageName = "Form" + separator + "Confirmaiton" + separator + p.replace('.shtml', '');
					pageType = "thank-you";
				}else{
					if(breadcrumbs.length > 0){
						pageName = crumb.join(separator);
					}else{
						if((loc.indexOf('/home.shtml') != -1) || (loc.indexOf('/home-ensighten-update-test.shtml') != -1)){
							pageName = 'Home';
						}else if((loc == '/' || loc == '/home.shtml') && location.href.indexOf('netsuite.co.jp') > -1){
							pageName = 'Page:jp/home.shtml';
						}else{
							pageName = loc.substring(loc.lastIndexOf("/portal/") + 8).split('/').join(':');
						}
					}

					if(pageName.toLowerCase() == 'home') {
						pageType = 'home'
					}else if (pageName.toLowerCase().indexOf('overview') > -1) {
						pageType = 'overview';
					}else if (pageName.toLowerCase().indexOf('products') > -1) {
						pageType = 'product-detail';
					}else if (pageName.toLowerCase().indexOf('why') > -1) {
					  	pageType = 'product-information';
					}else if ((pageName.toLowerCase().indexOf('customer-testimonials') > -1) || (pageName.toLowerCase().indexOf('customer testimonials') > -1)) {
						pageType = 'customer-testimonials';
					}else if (pageName.toLowerCase().indexOf('educational resources') > -1) {
					  	pageType = 'educational-resources'
					}else if (pageName.toLowerCase().indexOf('landing') > -1) {
					  	pageType = 'landing';
					}else if ((pageName.toLowerCase().indexOf('services') > -1)) {
					  	pageType = 'services';
					}else if ((pageName.toLowerCase().indexOf('partners') > -1)) {
					  	pageType = 'partners';
					}else if ((pageName.toLowerCase().indexOf('contactus') > -1)) {
					  	pageType = 'contact-us';
					}else if ((pageName.toLowerCase().indexOf('contact us') > -1)) {
					  	pageType = 'company';
					}else{
						pageType = 'default';
					}
				}

				attributes.push({"pageName"	: pageName}); //eVar13, eVar15, eVar18
				attributes.push({"pageType"	: pageType}); //eVar26
				attributes.push({"breadcrumbs" : crumb.join(separator)}); //prop10
				//attributes.push({"referringURL" :document.referrer}); //prop20
		
			}
			attributes.push({"referringURL" : previousReferrer}); //prop20
			nlDataLayerPush("onLoad",attributes);

		/*END OF ON LOAD ATTRIBUTES*/
		/*CLICK TRACKING*/
		/*if(!searchArray(nsFormDomains,domain) && !searchArray(elqFormDomains,domain)){ 

			attributes = [];
			
			let links = document.querySelectorAll("a[data-tracklinktext]");

			let i;
			
			for(i=0; i<links.length; i++){
				links[i].addEventListener('click', function(e){
					e.stopPropagation();
					//console.log(e.type);
						
					let location = '';
					let region = false;
					let section = false;
					let regionName = ''

					let container = document.querySelectorAll("*[data-linkcontainer=\"lt_region\"]"); //list all regions
					let j,k;
					for(j=0;j<container.length;j++){
						if(container[j].querySelectorAll("*[data-tracklinktext=\""+e.currentTarget.dataset.tracklinktext+"\"]").length && !region){
							location = container[j].dataset.tracklinktext;
							regionName = container[j].dataset.tracklinktext;
							region = true;

							let s = container[j].querySelectorAll("*[data-linkcontainer=\"lt_section\"]"); //list all sections in the region
							if((s.length > 0) && !section){
								for(k=0;k<s.length;k++){
									if(s[k].querySelectorAll("*[data-tracklinktext=\""+e.currentTarget.dataset.tracklinktext+"\"]").length && !section){
										location = location + "|" + s[k].dataset.tracklinktext;
										section = true;
									}
								}
							}
						}
					}

					attributes.push({"linkName" : regionName.toLowerCase() + separator + e.currentTarget.dataset.tracklinktext.toLowerCase()}); //eVar12
					attributes.push({"linkTarget" : e.currentTarget.href}); //eVar10
					attributes.push({"linkLocation" : location.toLowerCase()}); //eVar11
					attributes.push({"linkPageName" : pageName}); //eVar13
					attributes.push({"linkURL" : window.location.toString()}); //eVar14 

					if(e.currentTarget.href.indexOf(".pdf") > -1){ //.pdf download
						attributes.push({"download" : e.currentTarget.href.split('/').pop()}); //prop3, evar4
					}

					nlDataLayerPush("click", attributes);
					//console.log(nlDataLayer);
					//console.log(e.currentTarget.href.split('/').pop());
					//console.log("end");
					//}
				} ,true);
				// links[i].addEventListener('contextmenu', function(e){
				// 	e.stopPropagation();
				// 	console.log(e.currentTarget.attributes);
				// 	console.log(e.target.attributes);
				// 	console.log(e);
				// });
			}
		}*/
		/*END OF CLICK TRACKING*/
	};

if(!searchArray(nsFormDomains,domain)){
	document.addEventListener('load',onLoad);

	var setC = false;

	document.addEventListener('scscomponentrendercomplete',(e) =>{
		let componentEvent = e.detail;
		
		if((componentEvent.componentId == 'dc04dd87-3760-4cf3-a67b-e278951f5ce8') && componentEvent.timestamp && !setC){
			let container = document.querySelector("[data-articleorigin]");
			
			if(container){
				attributes.push({"articleOrigin" : container.dataset.articleorigin});
				nlDataLayerPush("afterLoad",attributes);

				setC = true;
				
				let evt = new Event("articleoriginready");

				window.addEventListener("articleoriginready",(e)=>{/*console.log("custom" + s.eVar39);*/});
				window.dispatchEvent(evt);
			}
		}
	});
}
