/* -------------------------------------
	Salesforce Marketing Cloud Helper functions 
	Functions to classify pages by category, gather search term or get SKU
	v 1.0: MK 3/12/2015
	v 2.0: MK 3/17/2015  Added Fuze search, changed categories to use Fuze first
	v 2.1: MK 3/19/2015  Changed additional category code from trackEvent to trackPageView 
	v 2.2: MK 3/23/2015  Added code to remove ampersands and spaces from category names
	v 2.3: MK 3/24/2015  Bug fixes, collect Item attribute from Newsroom pages
	v 2.4: MK 3/25/2015  Fixed newsroom detection to work on auth site
	v 2.5: MK 4/07/2015  Added array functions for IE7/8, added locale collection code
   -------------------------------------
*/

industries = ["automotive","commercial-solutions","communications","design-construction","electronics","energy","health-care","manufacturing","mining-oil-gas","safety","transportation"]
SFMCcategories = [];
badCategories = ["all-products","united-states"];

function SFMCcallTrackingCode(){
	_etmc.push(["setOrgId", "7209862"]);
	SFMCgetTrackPageJSON();	
}

function SFMCgetTrackPageJSON(){
	// construct the JSON array for the trackPageView code
	// returns search string on search results
	// returns item sku if available
	// returns category (or category=Corporate if nothing is available)
	var path = window.location.pathname;
	path = path.toLowerCase();
	if (path.indexOf("search-results")>0){ //EWCD search results
		_etmc.push(["trackPageView", { "search" :  SFMCgetQS("q") }]);
	}else if (SFMCgetQS("Ntt").length>0){ //FUZE search results
		_etmc.push(["trackPageView", { "search" :  SFMCgetQS("Ntt")}]);
	}else if (typeof WT.pn_sku !== "undefined" && WT.pn_sku.length>0){ // product detail on ECWD
		_etmc.push(["trackPageView", { "item" :  WT.pn_sku }]);
	}else if (SFMCgetMetaContent("WT.pn_sku").length>0){ // product detail on FUZE
		_etmc.push(["trackPageView", { "item" :  SFMCgetMetaContent("WT.pn_sku") }]);
	}else if (SFMCgetMetaContent("DCSext.business")=="Newsroom"||SFMCgetQS("storyid").length>0) { // is a newsroom page or a industry specific story
		if (path.substr(path.length-19,path.length) == "/3m/en_us/newsroom/") { // main newsroom page
			_etmc.push(["trackPageView",{"category": "newsroom"}]);
		}else{  // return storyid as item
		_etmc.push(["trackPageView", { "item" : SFMCgetNewsStoryID() }]);
		}
	}else{  //get categories and return
		SFMCloadCategories();  // load category array. May be zero length
		if (SFMCcategories.length==0){ // run trackPageView with no params
			_etmc.push(["trackPageView"]);
		}else{  //run trackPageView with each category in the array
			for (var i=0;i<SFMCcategories.length;i++){
				_etmc.push(["trackPageView",{"category": SFMCcategories[i]}]);
			}
		}
	}
}

function SFMCgetNewsStoryID(){
// get news item ID (is path + storyid querystring for a news item)
	if (SFMCgetQS("storyid").length>0){
		return window.location.pathname + "?storyid=" + SFMCgetQS("storyid");
	}else{
		return window.location.pathname;
	}
}



function SFMCloadCategories(){
	//get category name depending on what info is available on the page
	SFMCloadFUZEIndustry(); // load industry category from URL if available
	SFMCloadFUZEBreadcrumb(); // load industry and or product categories from itemscope (breadcrumb)
	SFMCloadFUZEFacets(); // load facet selections from "Your Selections" area into categories array
	SFMCloadBigBDivision(); // load big b and division on ECWD pages
	SFMCloadLocale(); // load locale as category 
	SFMCcategories = uniq(SFMCcategories); // deduplicate categories array
}

function SFMCloadFUZEBreadcrumb(){
	// look for itemprop=title SPAN elements and get textContent or innerText (from breadcrumb)
	var spans=document.getElementsByTagName("span");
	var category = "";
	if (spans){
		for (var i=0;i<spans.length;i++){
			if(spans[i].getAttribute("itemprop")=="title"){
				if(spans[i].textContent) category=spans[i].textContent;
				if(spans[i].innerText) category=spans[i].innerText;
				category=SFMCcleanCategory(category);
				if(category!==""&& badCategories.indexOf(category)==-1){
					// add to category array
					SFMCcategories.push(category);
				}
			}
		}
	}
}

function SFMCloadFUZEFacets(){
	// look for classname = MMM--actionLabel wt-link (from "your selections" and get inner text
	var spans=document.getElementsByClassName("MMM--actionLabel wt-link");
	var category = "";
	if (spans){
		for (var i=0;i<spans.length;i++){
			if(spans[i].textContent) category=spans[i].textContent;
			if(spans[i].innerText) category=spans[i].innerText;
			category=SFMCcleanCategory(category);
			if(category!==""&& badCategories.indexOf(category)==-1){
				// add to category array
				SFMCcategories.push(category);
			}
		}
	}
}

function SFMCloadFUZEIndustry(){
	// if is a fuze page parse industries from URL (last bit of URL)
	if (SFMCgetMetaContent("DCSext.platform")=="FUZE"){
		var path = window.location.pathname;
		var aIndustry=path.split("/");
		for (var i=0; i<aIndustry.length;i++){
			if (industries.indexOf(aIndustry[i].toLowerCase())>-1) SFMCcategories.push(aIndustry[i].toLowerCase()); // push industry into categories if it is on the list
		}
	}
}

function SFMCloadBigBDivision(){
	//  push in Big B and Division if available (only be on legacy EWCD pages)
	if (SFMCgetMetaContent("DCSext.platform")=="EWCD"){
		var division = SFMCgetMetaContent("DCSext.division");
		if (division!="") SFMCcategories.push(division);
		var bigB = SFMCgetMetaContent("DCSext.bigB");
		if (bigB!="") SFMCcategories.push(bigB);
	}
}

function SFMCloadLocale(){
	//  push Locale from DCSext.locale
		var locale = SFMCgetMetaContent("DCSext.locale");
		if (locale!="") SFMCcategories.push(locale);
}

function SFMCgetMetaContent(tagName) { 
	//get content attribute of meta tag with name = tagName
   var metas = document.getElementsByTagName('meta'); 

   for (var i=0; i<metas.length; i++) { 
      if (metas[i].getAttribute("name") == tagName) { 
         return metas[i].getAttribute("content"); 
      } 
   } 

    return "";
}

function SFMCgetQS(name) {
	//return the value of the querstring with name = name
	name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
	var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
	results = regex.exec(location.search);
	return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function SFMCcleanCategory(category){
	category=SFMCreplaceAll(category,"3M ","").trim().toLowerCase();
	category=SFMCreplaceAll(category,"&nbsp;"," ").trim();
	category=SFMCreplaceAll(category,"remove","").trim();
	category=SFMCreplaceAll(category,",","");
	category=SFMCreplaceAll(category," & ","-");
	category=SFMCreplaceAll(category,"& ","-");
	category=SFMCreplaceAll(category," &","-");
	category=SFMCreplaceAll(category," ","-");
	return category
}

function SFMCreplaceAll(string, find, replace) {
  return string.replace(new RegExp(SFMCescapeRegExp(find), 'g'), replace);
}

function SFMCescapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function uniq(a) {
	// returns unique values from array
    var seen = {};
    var out = [];
    var len = a.length;
    var j = 0;
    for(var i = 0; i < len; i++) {
         var item = a[i];
         if(seen[item] !== 1) {
               seen[item] = 1;
               out[j++] = item;
         }
    }
    return out;
}

/*start cross browser array fixes */

// add getElementsByClassName function if not present
if(!document.getElementsByClassName) {
    document.getElementsByClassName = function(className) {
        return this.querySelectorAll("." + className);
    };
    Element.prototype.getElementsByClassName = document.getElementsByClassName;
}

// Add ECMA262-5 method binding if not supported natively
//from http://stackoverflow.com/questions/2790001/fixing-javascript-array-functions-in-internet-explorer-indexof-foreach-etc
if (!('bind' in Function.prototype)) {
    Function.prototype.bind= function(owner) {
        var that= this;
        if (arguments.length<=1) {
            return function() {
                return that.apply(owner, arguments);
            };
        } else {
            var args= Array.prototype.slice.call(arguments, 1);
            return function() {
                return that.apply(owner, arguments.length===0? args : args.concat(Array.prototype.slice.call(arguments)));
            };
        }
    };
}

// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}

// Add ECMA262-5 Array methods if not supported natively
//
if (!('indexOf' in Array.prototype)) {
    Array.prototype.indexOf= function(find, i /*opt*/) {
        if (i===undefined) i= 0;
        if (i<0) i+= this.length;
        if (i<0) i= 0;
        for (var n= this.length; i<n; i++)
            if (i in this && this[i]===find)
                return i;
        return -1;
    };
}
if (!('lastIndexOf' in Array.prototype)) {
    Array.prototype.lastIndexOf= function(find, i /*opt*/) {
        if (i===undefined) i= this.length-1;
        if (i<0) i+= this.length;
        if (i>this.length-1) i= this.length-1;
        for (i++; i-->0;) /* i++ because from-argument is sadly inclusive */
            if (i in this && this[i]===find)
                return i;
        return -1;
    };
}
if (!('forEach' in Array.prototype)) {
    Array.prototype.forEach= function(action, that /*opt*/) {
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this)
                action.call(that, this[i], i, this);
    };
}
if (!('map' in Array.prototype)) {
    Array.prototype.map= function(mapper, that /*opt*/) {
        var other= new Array(this.length);
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this)
                other[i]= mapper.call(that, this[i], i, this);
        return other;
    };
}
if (!('filter' in Array.prototype)) {
    Array.prototype.filter= function(filter, that /*opt*/) {
        var other= [], v;
        for (var i=0, n= this.length; i<n; i++)
            if (i in this && filter.call(that, v= this[i], i, this))
                other.push(v);
        return other;
    };
}
if (!('every' in Array.prototype)) {
    Array.prototype.every= function(tester, that /*opt*/) {
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this && !tester.call(that, this[i], i, this))
                return false;
        return true;
    };
}
if (!('some' in Array.prototype)) {
    Array.prototype.some= function(tester, that /*opt*/) {
        for (var i= 0, n= this.length; i<n; i++)
            if (i in this && tester.call(that, this[i], i, this))
                return true;
        return false;
    };
}
/*end cross browser array fixes */