//*****************************************************************************************************//
// Coremetrics tagging throughout the site.
// Hwa Son  6/19/2009
var BillBoardCategoryName = {
    Get: function(r, setCookie)
    {
    	var CatName = "";
    	var queryStrings = $H(window.location.href.toQueryParams());
	
	    if (r.indexOf("HTTP://FOOTSMART.COM") > -1)
	    {
		    r = HomePage + r.substring(20);
	    }
    	
	    if (r == HomePage)
	    {
		    r = HomePage + "DEFAULT.ASPX";
	    }
	    if ((queryStrings.get('cm_re') != null && queryStrings.get('cm_re').toLowerCase().indexOf("-_-bill-_-") > -1) ||
		    (queryStrings.get('cm_mmc') != null && queryStrings.get('cm_mmc').toLowerCase().split("-_-")[0].indexOf("bill") > -1)
		    )
	    {
		    if (r.indexOf("DEFAULT.ASPX") > -1)
		    {
			    CatName = "HomePage-BillBoard";
		    }
		    else if (r.indexOf("CLEARANCEOUTLET.ASPX") > -1)
		    {
			    CatName = "233-BillBoard";
		    }
		    else if (r.indexOf("SMARTERBODY.ASPX") > -1)
		    {
			    CatName = "340-BillBoard";
		    }
		    else
		    {
			    var pcat = this.Prev_Url_Parse(r);
			    var rQueryStrings = $H(r.toQueryParams());
			    
			    if (pcat == "" && rQueryStrings.get('PRODUCTCATEGORYID') != null)
			    {
				    pcat = rQueryStrings.get('PRODUCTCATEGORYID');
			    }
			    if (pcat != "")
			    {
				    CatName = pcat + "-BillBoard";
			    }
		    }
	    }
    	
    	if (setCookie && CatName != null && CatName.length > 0)
    	{
	        SetCookie("CM_Category", CatName, null, null);
	    }
        
	    return CatName;
    },
    
    Prev_Url_Parse: function (r)
    { 
        var params = $H(r.toQueryParams());
    	
	    var tempArray = r.replace("?" + params.toQueryString(), "").split("/"); 
	    if (tempArray[tempArray.length-1].indexOf("C-") != 0)
	    {
		    return "";
	    }
	    
	    var arrayUrl = tempArray[tempArray.length-1].split("-");
	    var catId = arrayUrl[arrayUrl.length-1].substring(0, arrayUrl[arrayUrl.length-1].indexOf("."));
	    
	    return catId;
    },
    
    GetPageName: function (fullUrl)
    {
        fullUrl = fullUrl.toUpperCase();
        
        var tempArray = fullUrl.split("?");
        
        return tempArray[0];
    },
    
    RemoveSpecialCharacters: function (orginal)
    {
        return orginal.replace(/,/g, "").replace(/''/g, "").replace(/&/g, "").replace(/\*/g, "").replace(/\^/g, "");
    }
};

var FootSmartCoremetricsUtilities = Class.create({
	initailize: { },
	
	GetSearchReferrerByCharacterPattern: function(searchTerm) {
		var pattern = "";
		
		if (searchTerm !== "") {
			if (searchTerm.startsWith('***')) pattern = "SBC";
            else if (searchTerm.startsWith('^*^')) pattern = "HC";
// currently only using SBC and HC
//            else if (searchTerm.startsWith('*^*')) pattern = "Comfortista:Search";
//            else if (searchTerm.startsWith('^^*')) pattern = "Finder:Insole";
//            else if (searchTerm.startsWith('**^')) pattern = "Affiliate";
//            else if (searchTerm.startsWith('^^^')) pattern = "Finder:Clear";
//            else if (searchTerm.startsWith('**') && !searchTerm.startsWith("***")) pattern = "PaidSearch";
//            else if (searchTerm.startsWith('^^')) pattern = "Finder:Slip";
//            else if (searchTerm.startsWith('^') && !searchTerm.startsWith("^*^")) pattern = "Finder:Shoe";
//            else if (searchTerm.endsWith('*^^')) pattern = "Facebook";
//            else if (searchTerm.endsWith('**')) pattern = "SiteGenerated";
//            else if (searchTerm.endsWith('*')) pattern = "Email";
//            else if (searchTerm.startsWith('*') && !searchTerm.startsWith("***")) pattern = "PaidSearch";
//            else pattern = "UserSearch";
		}
		
		return pattern;
	},
	
	GetSearchReferrerByPage: function(internalUrl) {
		var referrer = "";
		var pageName = fsu.getPageName(internalUrl);
		
		switch (pageName) {
			case "shopbycondition":
				referrer = "SBC";
				break;
			case "healthcondition":
				referrer = "HC";
				break;
		}
		
		return referrer;
	},
	
	GetOriginalSearchTerm: function() {
		var originalSearchTerm = "";
	    if ($('searchResults_searchTermHidden') != null && $F('searchResults_searchTermHidden').length > 0) {
            originalSearchTerm = $F('searchResults_searchTermHidden').split('--');
        }
        return originalSearchTerm[0];
	}
});

//FootSmartUI.Coremetrics = Class.create(BillBoardCategoryName, {
var FootSmartCoremetricsOld = Class.create(BillBoardCategoryName, {
    initialize: function() {
        this.DELIMITER = "-_-";
        this.REGEXP = new RegExp(' ', 'gi');
    },

    SetProduction: function() {
        if (typeof (coremetrics) !== "undefined") {
            if (window.location.href.toUpperCase().indexOf("HTTP://WWW.FOOTSMART.COM") == 0 ||
	            window.location.href.toUpperCase().indexOf("HTTPS://WWW.FOOTSMART.COM") == 0 ||
	            window.location.href.toUpperCase().indexOf("HTTP://FOOTSMART.COM") == 0 ||
	            window.location.href.toUpperCase().indexOf("HTTPS://FOOTSMART.COM") == 0 ||
	            window.location.href.toUpperCase().indexOf("HTTP://STAGING.FOOTSMART.COM") == 0 ||
	            window.location.href.toUpperCase().indexOf("HTTPS://STAGING.FOOTSMART.COM") == 0
	            ) {
                cmSetProduction(); // execute this if only on the production.
            }
        }
    },
    
    SetSearchReferrerForSearchReturnsPage: function() {
		var cmu = new FootSmartCoremetricsUtilities();
		var pageName = fsu.getPageName();
		// get whatever value exists as the search referrer
		var searchReferrer = GetCookie("SearchRef") || "";
		
		// clear search referrer if it's a search box search or direct load and no url referrer or if it's an external url
		if ((searchReferrer !== "" && searchReferrer === "searchbox") ||
			// direct load/bookmark
			(!FootSmartGlobal.IsPostBack && document.referrer == null) ||
			// external referrer
			(document.referrer != null && !FootSmartGlobal.IsReferringUrlLocal) ||
			// these pages need to be search
			pageName === "whatsnew" ||
			pageName === "smartbuys" ||
			pageName === "clearanceshoes")
		{
			SetCookie("SearchRef", "search", null, null, null, true);
			FootSmartGlobal.SearchReferrer = "search";
		}
		// otherwise, set or replace the search referrer
		else
		{
			// if the user is refining, don't overwrite the cookie
			if (searchReferrer === "" || (searchReferrer !== "" && fsu.getQSParameter("SH") === ""))
			{
				// (1) try to get referrer by character pattern
				var referrer = cmu.GetSearchReferrerByCharacterPattern(fsu.getQSParameter("SearchTerm"));
				
				// (2) if the above search didn't yield results, try looking it up based on the url referrer
				if (referrer === "") {
					referrer = cmu.GetSearchReferrerByPage(FootSmartGlobal.ReferringInternalUrl);
				}
				
				// (3) if all else fails, set the referrer to search
				if (referrer === "") 
				{
					referrer = "search";
				}
				
				// set the search referrer in footsmart global
				FootSmartGlobal.SearchReferrer = referrer;
				
				// if the referrer is from ShopByCondition or HealthCondition, append the ailment name on those pages
				if (referrer === "SBC" || referrer === "HC") {
					var ailmentName = FootSmartGlobal.SearchTerm;
					var existingReferrerValue = searchReferrer.split("|");
					ailmentName = (ailmentName === "" || ailmentName.indexOf("@") > -1 && existingReferrerValue.length > 1 && existingReferrerValue[1] !== "") ?
						existingReferrerValue[1] : ailmentName;
					
					// this happens if the customer performs a search and hits the back button
					if (ailmentName.indexOf("@Searcher") > -1) {
						ailmentName = BillBoardCategoryName.RemoveSpecialCharacters(cmu.GetOriginalSearchTerm());
					}
					referrer = referrer + "|" + ailmentName;
					FootSmartGlobal.Page.AilmentName = ailmentName;
				}
				
				SetCookie("SearchRef", referrer, null, null, null, true);
			}
		}
    },
    
    DeterminePageAndCategoryNameForSearchReturnsPage: function() {
		switch (FootSmartGlobal.SearchReferrer) {
			case "SBC":
				FootSmartGlobal.Coremetrics.PageId = "SHOPBYCONDITION.ASPX";
				FootSmartGlobal.Coremetrics.CategoryId = "Content - Shop By Condition";
				break;
			case "HC":
				FootSmartGlobal.Coremetrics.PageId = "HEALTHCONDITION.ASPX";
				FootSmartGlobal.Coremetrics.CategoryId = "Content - Health Condition";
				break;
		}
    },

    PageViewTag: function() {
        if (typeof (coremetrics) !== "undefined") {

		    var queryStrings = location.href.toQueryParams();

		    // sets things like the SearchRef
		    if (typeof(FootSmartGlobal) !== "undefined" && FootSmartGlobal.Page.Name.toLowerCase() === "searchreturns.aspx") {
			    this.SetSearchReferrerForSearchReturnsPage();
			    this.DeterminePageAndCategoryNameForSearchReturnsPage();
		    }
    
            if (CoremetricsPageId == "ERROR.ASPX" || CoremetricsPageId == "404.ASPX") {
                cmCreateErrorTag(CoremetricsPageId);
            }
            else if
		    (
            // all of these pages either do not render a tag call or have special tag properties
			    CoremetricsPageId != "Search Box" &&
			    CoremetricsPageId != "Catalog Quick Shop" && CoremetricsPageId != "Product Brand Search" &&
			    CoremetricsPageId != "ProductZoomPopup" && CoremetricsPageId != "MULTIANGLEPRODUCTVIEWSPOPUP" &&
			    CoremetricsPageId != "DEFAULT.ASPX" && CoremetricsPageId != "NONE" &&
			    CoremetricsPageId != "STOREFRONT.ASPX" && CoremetricsPageId != "STOREFRONTBRAND.ASPX" &&
			    CoremetricsPageId != "STOREFRONTGIFT.ASPX" && CoremetricsPageId != "CLEARANCEOUTLET.ASPX" &&
			    CoremetricsPageId != "PRODUCTLIST.ASPX" && CoremetricsPageId != "PRODUCT.ASPX" &&
			    CoremetricsPageId != "SEARCHRESULTS.ASPX" && CoremetricsPageId != "SEARCHRETURNSBRANDS.ASPX" &&
			    CoremetricsPageId != "SEARCHRETURNS.ASPX" && CoremetricsPageId != "SEARCHRETURNS2.ASPX" &&
			    CoremetricsPageId != "HEALTHCONDITION.ASPX" && CoremetricsPageId != "SHOPBYCONDITION.ASPX" &&
			    CoremetricsPageId != "SMARTERBODY.ASPX" && CoremetricsPageId != "ORDERCONFIRMATION.ASPX" &&
			    CoremetricsPageId != "CATALOGREQUEST.ASPX" && CoremetricsPageId != "SUBMITREVIEW.ASPX" &&
			    CoremetricsPageId != "NEWSLETTER.ASPX" && CoremetricsPageId != "NEWSLETTERSIGNUP.ASPX" &&
			    CoremetricsPageId != "TOPSELLERS.ASPX" && CoremetricsPageId != "SMARTBUY.ASPX" &&
			    CoremetricsPageId != "TOPRATED.ASPX" && CoremetricsPageId != "OPTOUT.ASPX" &&
            //CoremetricsPageId != "PRODUCTZOOMPOPUP.ASPX" && CoremetricsPageId != "MULTIANGLEPRODUCTVIEWSPOPUP.ASPX" &&  
            //CoremetricsPageId.indexOf("P-") != 0 && 
            //CoremetricsPageId.indexOf("C-") != 0 &&
			    CoremetricsPageId.toLowerCase().indexOf("sitemap_") == -1
		    ) {
                // Carried a search term and search count from the search page.
                if (CoremetricsPageId == "No results page" && GetCookie("SearchTerm") != null && GetCookie("SearchTerm").length > 0) {
                    var spe = GetCookie("SearchTerm").split("@");
                    if (spe.length > 1) {
                        cmCreatePageviewTag(CoremetricsPageId, spe[0], CoremetricsCategoryId, spe[1]);
                    }
                    else {
                        cmCreatePageviewTag(CoremetricsPageId, null, CoremetricsCategoryId, null);
                        SetCookie("SearchTerm", "", null, null);
                    }
                }
                else if(CoremetricsPageId == "No results page" && queryStrings.searchterm !== 'undefined')
                {
                    cmCreatePageviewTag(CoremetricsPageId,   queryStrings.searchterm.replace("+"," ") , CoremetricsCategoryId, '0');
                }
                else if (CoremetricsPageId.indexOf('Shop By Condition Landing') > -1) {
                    CM_Page = CoremetricsPageId;
                    CM_Cat = CoremetricsCategoryId;
                    this.PageViewTagWithAttributes();
                }
                else {
                    cmCreatePageviewTag(CoremetricsPageId, null, CoremetricsCategoryId, null);
                    SetCookie("SearchTerm", "", null, null);
                }
            }
            else {
                if (CM_Cat.length > 0 && (CM_Cat.indexOf("-Billboard") > 0 ||
		            CM_Cat.indexOf("-TopSellers") > -1 ||
		            CM_Cat.indexOf("-TopRated") > -1 ||
		            CM_Cat.indexOf("-SmartBuy") > -1)) {
                    SetCookie("CM_Category", CM_Cat, null, null);
                }

                this.PageViewTagWithAttributes();
            }

            // Redirect to a custom page from all of the traffic builder pages.   
            // Hwa Son 11/18/2005
            if (CoremetricsPageId.toLowerCase().indexOf("sitemap_") > -1) {
                window.location.href = "/Page.aspx?PageId=901";
            }
        }
    },

    PageViewTagWithAttributes: function () {
        if (typeof (coremetrics) !== "undefined")
        {
            try
            {
                var attributes = "";
                var r = document.referrer.toUpperCase();
                var url = window.location.href;
                var originalSearchTerm = "";
                var queryStrings = $H(url.toQueryParams());
                var orgCM_Cat = "";

                var isSearchPage = FootSmartGlobal.Page.Name.toLowerCase().include('searchreturns');

                if ($('searchResults_searchTermHidden') != null && $F('searchResults_searchTermHidden').length > 0) {
                    originalSearchTerm = $F('searchResults_searchTermHidden').split('--');
                }

                // Field 1: Products per Page
                if ($('TopPageSizeSelectorContent') != null) {
                    // only for SearchReturns.aspx and SearchReturnsBrands.aspx
                    if (url.toUpperCase().indexOf("SEARCHRETURNS") > -1) {
                        orgCM_Cat = CM_Cat;
                        CM_Cat = this.DetermineCoremetricsCategoryIdForSearchReturnsPage(orgCM_Cat);
                        if (CM_Cat != orgCM_Cat) {
                            CM_Page = this.DetermineCoremetricsPageIdForSearchReturnsPage(CM_Page);
                        }
                    }

                    var productsPerPage = $('TopPageSizeSelectorContent').getElementsBySelector('select')[0];
                    attributes += $F('searchResults_searchPageSizeHidden');
                    /*
                     if (productsPerPage && productsPerPage.options.length > 0)
                     {
                     attributes += productsPerPage.options[productsPerPage.options.selectedIndex].text;
                     }
                     else if (queryStrings.get('SH') != null) // when a refinement gets selected.
                     {
                     attributes += $F('searchResults_searchPageSizeHidden');
                     }
                     else
                     {
                     // when there is no "product per page" dropdown.
                     // requested by Andrew.
                     attributes += "NA";
                     }
                     */
                }
                // product list page
                else if ($('tdProductsPerPage') != null) {
                    orgCM_Cat = $F('productListIdHidden');
                    CM_Cat = this.DetermineCoremetricsCategoryIdForProductListPage();

                    CM_Page = $F('productListNameHidden');
                    if (CM_Cat != orgCM_Cat) {
                        CM_Page = this.DetermineCoremetricsPageIdForProductListPage();
                    }

                    var productsPerPage = $('tdProductsPerPage').getElementsBySelector('select')[0];
                    if (productsPerPage && productsPerPage.options.length > 0) {
                        attributes += productsPerPage.options[productsPerPage.options.selectedIndex].text;
                    }
                    else {
                        // when there is no "product per page" dropdown.
                        // requested by Andrew.
                        attributes += "NA";
                    }
                }
                // Condition pages without search
                else if (url.toUpperCase().indexOf("SHOPBYCONDITION.ASPX") > -1 ||
                    url.toUpperCase().indexOf("HEALTHCONDITION.ASPX") > -1) {
                    SetCookie("CM_Category", CM_Cat, null, null);
                }

                attributes += this.DELIMITER;

                // Field 2: Sort by Option
                if ($('TopSortingSelectorContent')) {
                    var ddSortOptions = $('TopSortingSelectorContent').getElementsBySelector('select')[0];
                    if (ddSortOptions && ddSortOptions.options.length > 0) {
                        attributes += ddSortOptions.options[ddSortOptions.options.selectedIndex].text;
                    }
                }
                attributes += this.DELIMITER;

                // Field 3: Refinements Selected Qestion
                if ($('searchResults_spSearchPath_lblLastEntry') && $('searchResults_spSearchPath_lblLastEntry').innerHTML.indexOf(':') > 0) {
                    attributes += $('searchResults_spSearchPath_lblLastEntry').innerHTML.split(':')[0];
                }
                attributes += this.DELIMITER;

                // Field 4: Refinements Selected Answer
                if ($('searchResults_spSearchPath_lblLastEntry') && $('searchResults_spSearchPath_lblLastEntry').innerHTML.indexOf(':') > 0) {
                    attributes += $('searchResults_spSearchPath_lblLastEntry').innerHTML;
                }
                attributes += this.DELIMITER;

                // Field 5: Product Layout
                if ($('productListIdHidden') != null) {
                    // product list page.
                    if (queryStrings.get('CatViewMode') != undefined && queryStrings.get('CatViewMode').toUpperCase() == "LISTVIEW") {
                        attributes += "ShowList";
                    }
                    else {
                        attributes += "ShowGrid";
                    }
                }
                //else if ($('searchResults_searchTermHidden') != null)  // search page
                //{
                // do not pass it for now.
                //attributes += "ShowGrid";
                //}
                attributes += this.DELIMITER;

                // Field 6: Shop by Condition / Health Condition
                if (CM_Page.indexOf('Shop By Condition Landing') > -1) {
                    attributes += "SBC:LandingPg";
                }
                // when direct load of SearchReturns.aspx, we don't have the SBC PageId and CatID in FootSmartGlobal, so using originalSearchTerm here
                // would cause a mismatch of SBC/HC attributes and regular search PageID and CatID
                //
                // Shows on ShopByCondition.aspx and SearchReturns.aspx when referrer is ShopByCondition.aspx

                else if (url.toUpperCase().indexOf('SHOPBYCONDITION.ASPX') > -1 || (CM_Cat.indexOf('Shop By Condition') > -1 && typeof (FootSmartGlobal) !== 'undefined' && FootSmartGlobal.SearchReferrer == 'SBC')/* || (originalSearchTerm.length > 0 && originalSearchTerm[0].startsWith("***"))*/) {
                    attributes += "SBC:" + (FootSmartGlobal.Page.AilmentName/* || originalSearchTerm[0].replace("***", "")*/);
                }
                // Shows on HealthCondition.aspx and SearchReturns.aspx when referrer is HealthCondition.aspx
                else if (url.toUpperCase().indexOf('HEALTHCONDITION.ASPX') > -1 || (CM_Cat.indexOf('Health Condition') > -1 && typeof (FootSmartGlobal) !== 'undefined' && FootSmartGlobal.SearchReferrer == 'HC')/* || (originalSearchTerm.length > 0 && originalSearchTerm[0].startsWith("^*^"))*/) {
                    attributes += "HealthCond:" + (FootSmartGlobal.Page.AilmentName/* || originalSearchTerm[0].replace("^*^", "")*/);
                }
                else {
                }

                attributes += this.DELIMITER;


                // Field 7: Searcher
                if ($('searchResults_spSearchPath_lblLastEntry')) {
                    attributes += "Searcher";
                }
                attributes += this.DELIMITER;

                // Field 8: Search Type
                if (originalSearchTerm.length > 0) {
                    // do not change the order in this if statement.
                    if (originalSearchTerm[0].startsWith('***') && (typeof(FootSmartGlobal) !== "undefined" && FootSmartGlobal.SearchReferrer == "SBC")) attributes += "SBC:Search";
                    else if (originalSearchTerm[0].startsWith('^*^') && (typeof (FootSmartGlobal) !== "undefined" && FootSmartGlobal.SearchReferrer == "HC")) attributes += "HealthCond:Search";
                    else if (originalSearchTerm[0].startsWith('*^*')) attributes += "Comfortista:Search";
                    else if (originalSearchTerm[0].startsWith('^^*')) attributes += "Finder:Insole";
                    else if (originalSearchTerm[0].startsWith('**^')) attributes += "Affiliate";
                    else if (originalSearchTerm[0].startsWith('^^^')) attributes += "Finder:Clear";
                    else if (originalSearchTerm[0].startsWith('**') && !originalSearchTerm[0].startsWith("***")) attributes += "PaidSearch";
                    else if (originalSearchTerm[0].startsWith('^^')) attributes += "Finder:Slip";
                    else if (originalSearchTerm[0].startsWith('^') && !originalSearchTerm[0].startsWith("^*^")) attributes += "Finder:Shoe";
                    else if (originalSearchTerm[0].endsWith('*^^')) attributes += "Facebook";
                    else if (originalSearchTerm[0].endsWith('**')) attributes += "SiteGenerated";
                    else if (originalSearchTerm[0].endsWith('*')) attributes += "Email";
                    else if (originalSearchTerm[0].startsWith('*') && !originalSearchTerm[0].startsWith("***")) attributes += "PaidSearch";
                    else attributes += "UserSearch";
                }
                attributes += this.DELIMITER;

                // Field 9: Current Page Number
                // on the search page
                if ($('TopNavigationBarContent')) {

                    if ($$('#TopNavigationBarContent span.currentPageNumber')[0]) {
                        attributes += $$('#TopNavigationBarContent span.currentPageNumber')[0].innerHTML;
                    }
                    else {
                        attributes += "NA";
                    }

                }
                // ProductList.aspx
                else if (CM_Page.toUpperCase().indexOf("PRODUCTS:") > 0 || CM_Page.toUpperCase().indexOf("-_-BILL-_-") > 0) {
                    if ($$("span[id='productListCurrentPageNumber']")[0] != null) {
                        attributes += $$('span[id=\'productListCurrentPageNumber\']')[0].innerHTML;
                    }
                    else {
                        attributes += "NA";
                    }
                }
                attributes += this.DELIMITER;

                //Field10 - Endeca
                attributes += this.DELIMITER;

                //Field11 - Endeca
                attributes += this.DELIMITER;

                //Attribute 12 Celebros/Endeca
                attributes += isSearchPage ? 'Celebros' : '';
                attributes += this.DELIMITER;

                //Field13 - Endeca
                attributes += this.DELIMITER;

                //Field14 - Endeca
                attributes += this.DELIMITER;

                //Field15 - Endeca
                attributes += this.DELIMITER;

                attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

                if (CM_Page != "" && CM_Cat != "") {
                    var searchTerm = "";
                    var searchCount = "";

                    if ($('searchResults_searchTermHidden') != null) {
                        searchTerm = $F('searchResults_searchTermHidden')
                    }

                    if ($('searchResults_searchCountHidden') != null) {
                        searchCount = $F('searchResults_searchCountHidden');
                    }

                    if (CM_Cat == "Search" || CM_Cat == "Brands") {
                        SetCookie("CM_Category", CM_Cat, null, null);
                    }
                    cmCreatePageviewTag(CM_Page, searchTerm, CM_Cat, searchCount, attributes);
                }
            }
            catch (e)
            {
                var t = new Template('JS Error: FootSmartCoremetricsOld.PageViewTagWithAttribures(): Attributes: #{Attributes}');
                var result = {Attributes: attributes};
                fsu.logEntry('Error', null, e.message, t.evaluate(result));
            }
        }
    },

    //get page id for ProductList.aspx
    DetermineCoremetricsPageIdForProductListPage: function()
    {
        var r = document.referrer.toUpperCase();
        var url = window.location.href;
        var queryStrings = $H(url.toQueryParams());
        var PageName = '';

        try
        {
              PageName = $F('productListNameHidden');
              // Billboard Category, initial load with a "cm_re" parameter.
              if (r.length > 0 && queryStrings.get('cm_re') != null && queryStrings.get('cm_re').toUpperCase().indexOf("-_-BILL-_-") > -1) {
                  PageName = queryStrings.get('cm_re');
                  SetCookie("CM_Page", PageName, null, null);
              }
              // Billboard Category, when a products per page selected or a page number clicked.
              // [1] the referrer can have an external url, so in that case, try and match the categoryId (this case would happen if a customer clicked on the "show in list" link

              else if ((r.length == 0 || BillBoardCategoryName.GetPageName(url) == BillBoardCategoryName.GetPageName(r) || /*[1]*/ r.indexOf(queryStrings.get('ProductCategoryId')) > -1) &&
                  (queryStrings.get('pageSize') != null || queryStrings.get('pageIndex') != null || queryStrings.get('CatViewMode') != null) &&
                  GetCookie("CM_Page") != null && GetCookie("CM_Page").toUpperCase().indexOf("-_-BILL-_-") > -1) {
                  PageName = GetCookie("CM_Page");
              }
              // initial load without a "cm_re" parameter
              // when from the address bar or from a link
              else if (r.length == 0 || BillBoardCategoryName.GetPageName(url) != BillBoardCategoryName.GetPageName(r)) {
                  SetCookie("CM_Page", "", null, null);
              }

              if (PageName == "") PageName = $F('productListNameHidden');
        }
        catch (e)
        {
              var t = new Template('JS Error: FootSmartCoremetricsOld.DetermineCoremetricsPageIdForProductListPage(): PageName: #{PName}');
              var result = {PName: PageName};
              fsu.logEntry('Error', null, e.message, t.evaluate(result));
              return PageName;
        }

        return PageName;

    },

    // get category id for ProductList.aspx
    DetermineCoremetricsCategoryIdForProductListPage: function()
    {
        var CatName = '';
        var r = document.referrer.toUpperCase();
        var url = window.location.href;
        var queryStrings = $H(url.toQueryParams());


        try {
            CatName = $F('productListIdHidden');
            // Billboard Category, initial load with a "cm_re" parameter.
            if (r.length > 0 && queryStrings.get('cm_re') != null && queryStrings.get('cm_re').toUpperCase().indexOf("-_-BILL-_-") > -1) {
                CatName = BillBoardCategoryName.Get(r, true);
            }
            // Billboard Category, when a products per page selected or a page number clicked.
            // [1] the referrer can have an external url, so in that case, try and match the categoryId (this case would happen if a customer clicked on the "show in list" link
            else if ((r.length == 0 || BillBoardCategoryName.GetPageName(url) == BillBoardCategoryName.GetPageName(r) || /*[1]*/ r.indexOf(queryStrings.get('ProductCategoryId')) > -1) &&
                (queryStrings.get('pageSize') != null || queryStrings.get('pageIndex') != null || queryStrings.get('CatViewMode') != null) &&
                GetCookie("CM_Category") != null && GetCookie("CM_Category").toLowerCase().indexOf("-billboard") > -1) {
                CatName = GetCookie("CM_Category");
            }
            else if ($F('productListIdHidden').toLowerCase().indexOf("products") > -1) {
                SetCookie("CM_Category", $F('productListIdHidden'), null, null);
            }
            // initial load without a "cm_re" parameter
            // when from the address bar or from a link
            else if (r.length == 0 || BillBoardCategoryName.GetPageName(url) != BillBoardCategoryName.GetPageName(r)) {
                SetCookie("CM_Category", "", null, null);
            }

            if (CatName == "") CatName = $F('productListIdHidden');
        }
        catch (e) {
            var t = new Template('JS Error: FootSmartCoremetricsOld.DetermineCoremetricsCategoryIdForProductListPage(): CatName: #{CName}');
            var result = {CName:CatName};
            fsu.logEntry('Error', null, e.message, t.evaluate(result));
            return CatName;
        }

        return CatName;

    },

    //This is obsolete.  The search page now uses FootSmartCoremetrics.js
    DetermineCoremetricsPageIdForSearchReturnsPage: function(page)
    {
        return page;
    },

    //This is obsolete.  The search page now uses FootSmartCoremetrics.js
    DetermineCoremetricsCategoryIdForSearchReturnsPage: function(cat)
    {
        return cat;
    },

    RegistrationTagWithAttributes: function(customerId, emailAddress, city, state, zipcode, newsletterName, subscribe, firstName, lastName, createdAnAccount, gender, birthMonth) {
        if (typeof (coremetrics) !== "undefined") {
            var attributes = "";

            // Field 1: Customer ID
            if (customerId) attributes += customerId;
            attributes += this.DELIMITER;

            // Field 2: Newsletter Type
            if (newsletterName) attributes += newsletterName;
            attributes += this.DELIMITER;

            // Field 3: Email Address
            if (emailAddress) attributes += emailAddress;
            attributes += this.DELIMITER;

            // Field 4: State
            if (state) attributes += state;
            attributes += this.DELIMITER;

            // Field 5: First Name
            if (firstName) attributes += firstName;
            attributes += this.DELIMITER;

            // Field 6: Last Name
            if (lastName) attributes += lastName;
            attributes += this.DELIMITER;

            // Field 7: Created an Account
            if (createdAnAccount) attributes += createdAnAccount;
            attributes += this.DELIMITER;

            // Field 8: Gender
            if (gender) attributes += gender;
            attributes += this.DELIMITER;

            // Field 9: Birth Month
            if (birthMonth) attributes += birthMonth;
            attributes += this.DELIMITER;

            // remove all of spaces
            attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

            cmCreateRegistrationTag(customerId, emailAddress, city, state, zipcode, newsletterName, subscribe, attributes);
        }
    },

    EnableConversionEventForElement: function(element, eventId, eventCategoryId, eventType) {
        var eventHolderKey = eventId + "EnableConversionEventForElementCallback";
        // in case the element hasn't been "prototypized" yet
        element = $(element);

        //Throw tag with event action 1 only once
        if (typeof (EventHolder.get(eventHolderKey)) === "undefined")
        {
            //event handler function used by observe
            var handler = this.EnableConversionEventForElementCallback
                .bind(this, element, eventHolderKey, eventId, eventCategoryId, eventType);

            this.ConversionEventTagWithAttributes(eventId, 1, eventCategoryId);

            EventHolder.set(eventHolderKey, handler);
        }

        //attach eventType to element
        element.observe(eventType, EventHolder.get(eventHolderKey));
    },

    EnableConversionEventForElementCallback: function (element, eventHolderKey, eventId, eventCategoryId, eventType, e) {
        this.ConversionEventTagWithAttributes(eventId, 2, eventCategoryId);
        element.stopObserving(eventType, EventHolder.get(eventHolderKey));    
    },

    ConversionEventTagWithAttributes: function(eventId, actionType, eventCategoryId, points, attributes) {
        if (typeof (coremetrics) !== "undefined") {

            // default value of points in case it's not supplied
            if (typeof(points) === "undefined") {
                points = 10;
            }

            if (typeof(attributes) !== "undefined") {
                if (attributes instanceof(Array)) {
                    attributes = attributes.join(this.DELIMITER);
                }
                // remove all spaces
                attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));
            }

            cmCreateConversionEventTag(eventId, actionType, eventCategoryId, points, attributes);
        }
    },

    /* 2011-07-20 JChen - Obsolete: Old PDP Page
    ConversionEventTagWithAttributes: function(actionType, clickedEventId) {
        if (typeof (coremetrics) !== "undefined") {
            // Field 1: Shoe/Non-Shoe
            // Field 2: Primary Product Category

            var attributes = "";
            if ($('CoremetricsConversionTagAttributes') != null) {
                attributes = $F('CoremetricsConversionTagAttributes')
            }
            if (actionType == null) {
                actionType = 1;
            }
        
            if (clickedEventId == null)
            {
                clickedEventId = "";
            }

            // remove all of spaces
            attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

            if ((actionType == 1 || (actionType == 2 && clickedEventId == "Product Zoom")) && 
                $('enlargeIsZoomHidden') != null && $F('enlargeIsZoomHidden').toUpperCase() == "TRUE")
            {
                cmCreateConversionEventTag("Product Zoom", actionType, "Product Page", 20, attributes);
            }

            if ((actionType == 1 || (actionType == 2 && clickedEventId == "Multi-View Product Zoom")) &&
                $('enlargeIsMultiAngleZoomHidden') != null && $F('enlargeIsMultiAngleZoomHidden').toUpperCase() == "TRUE")
            {
                cmCreateConversionEventTag("Multi-View Product Zoom", actionType, "Product Page", 20, attributes);
            }

            // JLH - Support for How To Measure div.
            if ((actionType == 1 || (actionType == 2 && clickedEventId == "How To Measure")) && 
                $('productPurchaseToolHidden') != null && $F('productPurchaseToolHidden').toUpperCase() == "HOW_TO_MEASURE")
            {
                cmCreateConversionEventTag("How To Measure", actionType, "Product Page", 20, attributes);
            }            
        }
    },

    ConversionEventTagWithAttributesForReview: function(eventId, actionType) {
        if (typeof (coremetrics) !== "undefined") {
            // Field 1: Shoe/Non-Shoe
            // Field 2: Primary Product Category

            var attributes = "";
            if ($('CoremetricsConversionTagAttributes') != null) {
                attributes = $F('CoremetricsConversionTagAttributes')
            }

            // remove all of spaces
            attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

            cmCreateConversionEventTag(eventId, actionType, "Bazaar Voice", 10, attributes);
        }
    },
    */

    ShopActionTagWithAttributes: function (at, shortSku, productName, quantity, price, customerId, orderId, orderTotal, cmCategoryId, reviewRating, totReviewCount, reviewRecommendPercentage, primaryProductCategoryNameInChain, productType, isNew, inventoryPosition, longSKU, city, state, zipCode, searchResults) {
        if (typeof (coremetrics) !== "undefined") {
            var attributes = "";

            /*
            cmCategoryId will be a string delimited by the '@' character (why? b/c Hwa made it such).  These are values passed from PDP Page
                0 Product CategoryId
                1 Search Term for SBC or HC
                2 Searcher
                3 PDP Page Type
                4 Visual Look or DropDown
                5 Inventory Value
                6 Cross Sell Type from PDP
                7 Initial Search Dimension Count from Search Page
                8 Pipe Delimited list of Dimensions from Search Page
                9 Endeca or Celebros
                10 Navigator or Searcher (basically means are you from ProductList.aspx or SearchReturns.aspx)
                11 Web Category Id
             */

            var cmCategory = cmCategoryId.split('@');

            //holds session based data for search page
            var SearchResultsConfig = searchResults || {};

            // Field 1: Review Rating
            if (reviewRating) attributes += reviewRating;
            attributes += this.DELIMITER;

            // Field 2: Number of Reviews
            if (totReviewCount) attributes += totReviewCount;
            attributes += this.DELIMITER;

            // Field 3: Likelihood to Recommend
            //if (reviewRecommendPercentage) attributes += reviewRecommendPercentage;  -- remove parameter "reviewRecommendPercentage" later.
            if (cmCategory.length > 4 && cmCategory[4].length > 0) attributes += cmCategory[4];
            attributes += this.DELIMITER;

            // Field 4: Primary Merch Category
            if (primaryProductCategoryNameInChain) attributes += primaryProductCategoryNameInChain;
            attributes += this.DELIMITER;

            // Field 5: Shoe/Non-Shoe
            if (productType) attributes += productType;
            attributes += this.DELIMITER;

            // Field 6: New
            if (isNew) attributes += isNew;
            attributes += this.DELIMITER;

            // Field 7: Inventory Position
            //if (inventoryPosition) attributes += inventoryPosition;  -- remove parameter "inventoryPosition" later.
            if (cmCategory.length > 5 && cmCategory[5].length > 0) attributes += cmCategory[5];
            attributes += this.DELIMITER;

            // Field 8: Shop By Condition / Health Condition
            if (cmCategory.length > 1 && cmCategory[0].length > 4 && cmCategory[0].substring(cmCategory[0].length - 4) == "-SBC") attributes += "SBC:" + cmCategory[1];
            else if (cmCategory.length > 1 && cmCategory[0].length > 3 && cmCategory[0].substring(cmCategory[0].length - 3) == "-HC") attributes += "HealthCond:" + cmCategory[1];
            attributes += this.DELIMITER;

            // Field 9: Searcher
            if (cmCategory[0].toUpperCase().indexOf('-SEARCH') > -1 ||
                cmCategory[0].toUpperCase().indexOf('-BRANDS') > -1 ||
                cmCategory[0].toUpperCase().indexOf('SEARCH - FINDER') > -1) {
                attributes += "Searcher";
            }
            else if (cmCategory.length > 2 && cmCategory[2] == "Searcher") {
                attributes += "Searcher";
            }
            /*
            if (cmCategory.length > 3 && cmCategory[3] == "Searcher" &&
            (cmCategory[0].toUpperCase().indexOf('-SBC') > -1 || cmCategory[0].toUpperCase().indexOf('-HC') > -1)
            ) {
            attributes += "Searcher";
            }
            else if (cmCategory.length > 1 && cmCategory[1] == "Searcher") {
            attributes += "Searcher";
            }
            */
            attributes += this.DELIMITER;

            // Field 10: Cross Sell
            if (cmCategoryId.toUpperCase().indexOf("RECS_") > -1) attributes += "CrossSoldItem";
            attributes += this.DELIMITER;



            // Field 11: Initial Search Refinement Count
            attributes += SearchResultsConfig.InitialRefinementCount || '';
            attributes += this.DELIMITER;

            // Field 12: List of Refinements in order of which they appear (this is pipe delimited)
            //Attribute 11 Available Refinements
            attributes +=  Object.isArray(SearchResultsConfig.Dimensions) ? SearchResultsConfig.Dimensions.join('|') : '';
            attributes += this.DELIMITER;

            // Field 13: Came from Celebros or Endeca
            attributes += cmCategory[7] || '';
            attributes += this.DELIMITER;

            // Field 14: PDP page type
            if (cmCategory.length > 3 && cmCategory[3].length > 0) attributes += cmCategory[3];
            attributes += this.DELIMITER;

            // Field 15: CrossSell display type
            if (cmCategory.length > 6 && cmCategory[6].length > 0) attributes += cmCategory[6];
            attributes += this.DELIMITER;

            //Field 16: Long SKU
             if (longSKU) attributes += longSKU;
            attributes += this.DELIMITER;

            //Shop 9 Tag
            if(at == 9)// && typeof(FootSmartGlobal.Order) != 'undefined' && FootSmartGlobal.Order != null)
            {
                 //Field 17: Billing City
                 attributes += city;
                 attributes += this.DELIMITER;

                 //Field 18: Billing State
                 attributes += state;
                 attributes += this.DELIMITER;

                 //Field 19: Billing Zip
                 attributes += zipCode;
                 attributes += this.DELIMITER;
    //            if(FootSmartGlobal.Order.BillingCity != null)
    //            {
    //                attributes += FootSmartGlobal.Order.BillingCity;
    //                attributes += this.DELIMITER;
    //            }
    //
    //
    //            if(FootSmartGlobal.Order.BillingState != null)
    //            {
    //                attributes += FootSmartGlobal.Order.BillingState;
    //                attributes += this.DELIMITER;
    //            }
    //
    //
    //            if(FootSmartGlobal.Order.PostalCode != null)
    //            {
    //                attributes += FootSmartGlobal.Order.PostalCode;
    //                attributes += this.DELIMITER;
    //            }
            }
            //Shop 5 Tag
            else
            {
                attributes += this.DELIMITER;
                attributes += this.DELIMITER;
                attributes += this.DELIMITER;
            }

            //Attribute 20 - searcher or navigator
            attributes += cmCategory[8] || '';
            attributes += this.DELIMITER;

            //Attribute 21 - Web Category Id
            attributes += cmCategory[9] || '';
            attributes += this.DELIMITER;

            //Attribute 22 - Breadbox Refinement Count
            attributes += Object.isArray(SearchResultsConfig.RefinedDimensionValues) ? SearchResultsConfig.RefinedDimensionValues.length : '0';
            attributes += this.DELIMITER;

            //Attribute 23 - Breadbox Refinement Values (pipe delimited)
            attributes += Object.isArray(SearchResultsConfig.RefinedDimensionValues) ? SearchResultsConfig.RefinedDimensionValues.pluck('Name').join('|') : '';
            attributes += this.DELIMITER;

            //Attribute 24 - Initial Refinement Selections for finders
            attributes += SearchResultsConfig.InitialFinderRefinementValues || '';
            attributes += this.DELIMITER;

            // remove all of spaces
            attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

            if (at == 5) {
                // gets called from ShoppingCart.aspx
                cmCreateShopAction5Tag(shortSku, productName, quantity, price, cmCategory[0], attributes);
            }
            else if (at == 9) {
                // gets called from OrderConfirmation.aspx
                cmCreateShopAction9Tag(shortSku, productName, quantity, price, customerId, orderId, orderTotal, cmCategory[0], attributes);
            }
        }
    },

    OrderTagWithAttributes: function(ecometryId, subTotal, skus, shippingPrice, customerId, city, state, zipcode, paymentMethod, shippingMethod, promotionCode) {
        if (typeof (coremetrics) !== "undefined") {
            var attributes = "";

            // Field 1: Payment Methods
            //          PayPal - PayPal
            //          PayPal Express - PayPalExpress
            //          Credit Card - CreditCard
            //          Bill Me Later - BML
            //          Google - Google
            //          TeleCheck - TeleCheck
            if (paymentMethod) attributes += paymentMethod;
            attributes += this.DELIMITER;

            // Field 2: Shipping Methods
            //          Standard
            //          Rush
            //          Express
            //          Overnight
            if (shippingMethod) {
                switch (shippingMethod) {
                    case '2':
                        attributes += "Rush";
                        break;
                    case '3':
                        attributes += "Express";
                        break;
                    case '4':
                        attributes += "Overnight";
                        break;
                    case '5':
                        attributes += "Standard:Priority";
                        break;
                    case '7':
                        attributes += "Standard:Canada";
                        break;
                    default:
                        attributes += "Standard:48";
                        break;
                }
            }
            attributes += this.DELIMITER;

            // Field 3: Promo Code
            if (promotionCode) attributes += promotionCode;
            attributes += this.DELIMITER;

            // Field 4: Order Number
            if (ecometryId) attributes += ecometryId;
            attributes += this.DELIMITER;

            // remove all of spaces
            attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

            cmCreateOrderTag(ecometryId, subTotal, skus, shippingPrice, customerId, city, state, zipcode, attributes);
        }
    },

    ProductViewTagWithAttributes: function(reviewRating, totReviewCount, reviewRecommendPercentage, primaryProductCategoryNameInChain, productType, isNew, inventoryPosition) {
        if (typeof (coremetrics) !== "undefined") {
            var attributes = "";
            var r = document.referrer;
            var url = window.location.href;
            var queryStrings = $H(url.toQueryParams());
            var skuSearchTerm = "";

            if ($F('skuSearchTerm') != null && $F('skuSearchTerm') != "") {
                skuSearchTerm = $F('skuSearchTerm').split("@");
                if (skuSearchTerm.length > 1) {
                    skuSearchTerm[0] = BillBoardCategoryName.RemoveSpecialCharacters(skuSearchTerm[0]);
                }
            }

            // Field 1: Review Rating
            if (reviewRating) attributes += reviewRating;
            attributes += this.DELIMITER;

            // Field 2: Number of Reviews
            if (totReviewCount) attributes += totReviewCount;
            attributes += this.DELIMITER;

            // Field 3: Likelihood to Recommend
            //if (reviewRecommendPercentage) attributes += reviewRecommendPercentage;
            attributes += this.DELIMITER;

            // Field 4: Primary Product Category Name in Chain
            if (primaryProductCategoryNameInChain) attributes += primaryProductCategoryNameInChain;
            attributes += this.DELIMITER;

            // Field 5: Shoe/Non-Shoe
            if (productType) attributes += productType;
            attributes += this.DELIMITER;

            // Field 6: New
            if (isNew) attributes += isNew;
            attributes += this.DELIMITER;

            // Field 7: Inventory Position - TBD
            if (inventoryPosition) attributes += inventoryPosition;
            attributes += this.DELIMITER;

            // Field 8: Cross Sell
            if (queryStrings.get('cm_vc') != undefined && queryStrings.get('cm_vc').indexOf('recs_') > -1) attributes += "CrossSoldItem";
            attributes += this.DELIMITER;

            // Field 9: Shop By Condition / Health Condition
            //if (CatName.indexOf('-SBC') > -1) attributes += "SBC:"
            if ($F('CoremetricsCategoryIdHidden').indexOf('-SBC') > -1) attributes += "SBC:" + skuSearchTerm[0];
            else if ($F('CoremetricsCategoryIdHidden').indexOf('-HC') > -1) attributes += "HealthCond:" + skuSearchTerm[0];
            attributes += this.DELIMITER;

            // Field 10: Searcher
            if ($F('CoremetricsCategoryIdHidden').toUpperCase().indexOf('-SEARCH') > -1 ||
                $F('CoremetricsCategoryIdHidden').toUpperCase().indexOf('-BRANDS') > -1 ||
                $F('CoremetricsCategoryIdHidden').toUpperCase().indexOf('SEARCH - FINDER') > -1) {
                attributes += "Searcher";
            }
            else if (skuSearchTerm.length > 1 && skuSearchTerm[1] == "Searcher" &&
                    ($F('CoremetricsCategoryIdHidden').toUpperCase().indexOf('-SBC') > -1 ||
                    $F('CoremetricsCategoryIdHidden').toUpperCase().indexOf('-HC') > -1 ||
                    $F('CoremetricsCategoryIdHidden').toUpperCase().indexOf('-BILLBOARD') > -1)) {
                attributes += "Searcher";
            }
            attributes += this.DELIMITER;

            // Field 11: will use this for new search later
            attributes += this.DELIMITER;

            // Field 12: will use this for new search later
            attributes += this.DELIMITER;

            // Field 13: will use this for new search later
            attributes += this.DELIMITER;

            // Field 14: PDP page type
            attributes += "OldPDP";
            attributes += this.DELIMITER;

            //Field 15: CrossSell display type
            attributes += this.DELIMITER;

            // remove all of spaces
            attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

            // do not send after postback
            if (IsPostBack == "False") {
                var CatName = $F('CoremetricsCategoryIdHidden');

                var searchTerm = null;
                var searchCount = null;
                if (skuSearchTerm.length > 1 && skuSearchTerm[1] == "1" && $F('CoremetricsCategoryIdHidden').toUpperCase().indexOf('-SEARCH') > -1) {
                    searchTerm = skuSearchTerm[0];
                    searchCount = skuSearchTerm[1];
                    // remove "SearchTerm" cookie value.
                    SetCookie("SearchTerm", "", null, null);
                }
                cmCreateProductviewTag($F('productShortSkuHidden'), $F('productNameHidden'), CatName, 'Y', searchTerm, searchCount, attributes);

                if ($F('productShortSkuHiddenBottom') != "") {
                    cmCreateProductviewTag($F('productShortSkuHiddenBottom'), $F('productNameHiddenBottom'), CatName, 'N', attributes);
                }

                /* 2011-07-20 JChen - Obsolete: Old PDP Page
                // for Scene7 image links on Product.aspx
                this.ConversionEventTagWithAttributes(1);
                */
            }
        }
    },

    // For Product.aspx
    DetermineCoreMetricsCategoryId: function(internalUrlForCustomUrl) {
        var CM_Cat = "";
        var CatName = "";
        var pcat = "";
        var productCategoryNameHidden = $F('productCategoryNameHidden');
        var productCategoryNameHidden1 = $F('productCategoryNameHidden1');

        var url = window.location.href;
        var queryStrings = $H(url.toQueryParams());

        if (GetCookie("CM_Category") != null) CM_Cat = GetCookie("CM_Category");

        var r = "";
        if (internalUrlForCustomUrl.length > 0) {
            r = internalUrlForCustomUrl.toUpperCase();
        }
        else if (document.referrer != null && document.referrer.length > 0) {
            r = document.referrer.toUpperCase();
        }

        var rQueryStrings = $H(r.toQueryParams());

        HomePage = HomePage.toUpperCase();
        var HomePath = HomePage + "DEFAULT.ASPX";

        // from footsmart blog site
        // Search sites grab urls with "cm_sp" parameter from the blog site which causes throwing a wrong category id.
        // add blog domain names in the if statement if we have new blog sites.
        if (queryStrings.get('cm_sp') != null && queryStrings.get('cm_sp').toLowerCase().indexOf("blog-_-") > -1 &&
            document.referrer.length > 0 && document.referrer.toUpperCase().indexOf("COMFORTISTA.COM") > -1) {
            var urlArr = document.referrer.toLowerCase().split(".");
            CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-" + urlArr[1].substring(0, 1).toUpperCase() + urlArr[1].substring(1, urlArr[1].length));
        }
        // from outside of footsmart.com (-EXTERNAL)
        else if (document.referrer.length > 0 && document.referrer.toUpperCase().indexOf(HomePage) == -1) {
            CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-External");
        }
        // sku search
        else if ($F('skuSearchTerm').indexOf("@1") > -1) {
            CatName = productCategoryNameHidden;
        }
        // from home page.
        else if (r == HomePage || BillBoardCategoryName.GetPageName(r) == HomePath) {
            // from bill board
            var BillCatName = BillBoardCategoryName.Get(r, false);
            if (BillCatName != "") {
                CatName = BillCatName;
            }
            // from home page featured produts.
            else if (HomePageFeaturedProduct == "1") {
                CatName = "Home Page";
            }
        }
        // from EditionDuo
        else if (queryStrings.get('PartnerURL') != null && queryStrings.get('PartnerURL').toUpperCase().indexOf("EDITIONDUO") > -1) {
            CatName = "Interactive Catalog";
        }
        // smarterbody
        else if (r.indexOf("SMARTERBODY") > -1) {
            CatName = "340";
        }
        // from paid search
        else if (queryStrings.get('srccode') != null && queryStrings.get('srccode') != "") {
            CatName = "Natural/Paid Search";
        }
        // cross sell from product detail page.
        else if (queryStrings.get('cm_re') != null && queryStrings.get('cm_re').toLowerCase().indexOf("xsell-_-product-_-") > -1) {
            CatName = "Product Cross Sell";
        }
        // cross sell from shopping cart page.
        else if (queryStrings.get('cm_re') != null && queryStrings.get('cm_re').toLowerCase().indexOf("xsell-_-shoppingcart-_-") > -1) {
            CatName = "Shopping Cart Cross Sell";
        }
        /** commented out on 2/11/2008  requested by Melissa Sullivan
        // for Internet Only  
        else if (productCategoryNameHidden1.toUpperCase() == "INTERNET ONLY")
        {
        //CatName = "INTERNET ONLY";
        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-InternetOnly"); 
        }
        */
        // from write a review page.
        else if (r.indexOf("SUBMITREVIEW") > -1) {
            CatName = "Submit Review";
        }
        // from shop by condition. (-SBC)
        else if (r.indexOf("SHOPBYCONDITION") > -1) {
            CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-SBC");
        }
        // from health condition. (-HC)
        else if (r.indexOf("HEALTHCONDITION") > -1) {
            CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-HC");
        }
        // from on site search - finder search
        else if (r.indexOf("SEARCHRESULTS.ASPX") > -1) {
            CatName = "Search - Finder";
        }
        // from store front page.
        else if (r.indexOf("STOREFRONT.ASPX") > -1) {
            // from storefront bill board.
            var BillCatName = BillBoardCategoryName.Get(r, false);
            if (BillCatName != "") {
                CatName = BillCatName;
            }
            // from featured products
            else if (rQueryStrings.get('PRODUCTCATEGORYID') != null && rQueryStrings.get('PRODUCTCATEGORYID') != "") {
                CatName = rQueryStrings.get('PRODUCTCATEGORYID') + "-FP";
            }
            SetCookie("SearchTerm", "", null, null);
            document.forms[0].elements['skuSearchTerm'].value = "";
        }
        // from product list page.
        else if (r.indexOf("PRODUCTLIST.ASPX") > -1) {
            // through product list page from a bill board on other pages.
            if (CM_Cat.toLowerCase().indexOf("-billboard") > -1) {
                CatName = CM_Cat;
            }
            // Marketing Products, Gift Products, Style products, Brand produts, and Ailment products
            else if (CM_Cat.toLowerCase().indexOf("products") > -1) {
                CatName = CM_Cat;
            }
            // product category id
            else if (rQueryStrings.get('PRODUCTCATEGORYID') != null && rQueryStrings.get('PRODUCTCATEGORYID') != "") {
                CatName = rQueryStrings.get('PRODUCTCATEGORYID');
            }

            SetCookie("SearchTerm", "", null, null);
            document.forms[0].elements['skuSearchTerm'].value = "";
        }
        else if (r.indexOf("SEARCHRETURNS.ASPX") > -1) {
            if (CM_Cat.toLowerCase().indexOf("-billboard") > -1) {
                CatName = CM_Cat;
            }
            else {
                CatName = productCategoryNameHidden;
            }
        }
        else if (r.indexOf("SEARCHRETURNSBRANDS.ASPX") > -1) {
            if (CM_Cat.toLowerCase().indexOf("-billboard") > -1) {
                CatName = CM_Cat;
            }
            else {
                CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-BRANDS");
            }
        }
        // from dynamic top sellers page.
        else if ((r.toUpperCase().indexOf("TOPSELLERS.ASPX") > -1 || r.toUpperCase().indexOf("T-") > -1)
                    && CM_Cat.toLowerCase().indexOf("-topsellers") > 0) {
            CatName = CM_Cat;
        }
        // from dynamic top rated page
        else if ((r.toUpperCase().indexOf("TOPRATED.ASPX") > -1 || r.toUpperCase().indexOf("R-") > -1)
                    && CM_Cat.toLowerCase().indexOf("-toprated") > 0) {
            CatName = CM_Cat;
        }
        // from dynamic smart buy page.
        else if ((r.toUpperCase().indexOf("SMARTBUY.ASPX") > -1 || r.toUpperCase().indexOf("S-") > -1)
                    && CM_Cat.toLowerCase().indexOf("-smartbuy") > 0) {
            CatName = CM_Cat;
        }
        // from custom pages. (this includes page.aspx and marketingpage.aspx)
        else if (r.indexOf("PAGE.ASPX") > -1) {
            if (CM_Cat.toLowerCase().indexOf("-custom") > -1 && productCategoryNameHidden.toLowerCase().indexOf("-search") > -1)  // from customized pages (page.aspx)
            {
                switch (CM_Cat.replace("-custom", "")) {
                    case "1":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-SRCH");
                        break;

                    case "2":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-MKTG");
                        break;

                    case "3":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-FSH");
                        break;

                    case "4":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-STSRVC");
                        break;

                    case "5":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-OTH");
                        break;

                    case "6":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-SPECIAL");
                        break;

                    case "7":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-NEWS");
                        break;

                    case "8":
                        CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-SPECIALSHOPS");
                        break;
                }
            }
        }


        /*
        // to prevent to get assigned under first level categories.
        if (productCategoryNameHidden.toLowerCase().indexOf("-search") > -1)
        {
        var catNames = productCategoryNameHidden.split("-");
        if (catNames.length > 2 && CatName == catNames[0])
        {
        CatName = catNames[catNames.length-2];
        }
        }
        */
        if (CatName == "") {
            // from OrderHistory.aspx or shopping cart
            var cat = productCategoryNameHidden.split("-");
            if (r.indexOf(HomePage) > -1 && cat.length > 2 && parseInt(cat[cat.length - 2]) > 0 && parseInt(cat[cat.length - 2]) < 999999) {
                CatName = cat[cat.length - 2];
            }
            else {
                // from no idea. (-OTHER)
                CatName = productCategoryNameHidden.toLowerCase().replace("-search", "-Other");
            }
        }

        return CatName;
    },

    DisplayCoremetricsFormErrorTag: function() {
        if (typeof (coremetrics) !== "undefined") {
            var pageId = "";

            if ($('productNameHidden') != null && $('productShortSkuHidden') != null) {
                pageId = "PRODUCT: " + $F('productNameHidden') + " (" + $F('productShortSkuHidden') + ")";
            }
            else {
                pageId = CoremetricsPageId;
            }

            $$('span').each(function(e, index) {
                if (e.id.toLowerCase().indexOf('validator') > -1 &&
            	    e.innerHTML.stripTags().replace(this.REGEXP, "") != "") {
                    if ($$("input.PromotionTextBox")[0] && e.id.indexOf('lbPromotionErrorValidator') > 0) {
                        // This will be used only on pages with ShoppingCartPromotion.ascx
                        var promotionCode = GetCookie('FootSmart_Source');
                        if (promotionCode != null && promotionCode.length > 0) {
                             promotionCode = " |" + promotionCode;
                        }
                        else {
                            promotionCode = "";
                        }
                        cmCreateFormErrorTag(pageId, e.innerHTML.stripTags().strip() + promotionCode);
                    }
                    else {
                        cmCreateFormErrorTag(pageId, e.innerHTML.stripTags().strip());
                    }
                }
            });
        }
    },

    // Hwa Son 9/5/2008
    // for the OrderShippingMethod.aspx
    // updated by Hwa Son 2/18/2009
    ManualLinkClickForPayment: function() {
        if (typeof (coremetrics) !== "undefined") {
            var shippingOption = "";

            var formArray = $('frmOrderShippingMethod').getInputs('radio');
            for (i = 0; i < formArray.size(); i++) {
                el = formArray[i];

                // payment options.
                if (el.id.indexOf("payment_") > -1 && el.checked) {
                    cmCreateManualLinkClickTag("/" + el.id);
                }

                // shipping options.
                if (el.id.indexOf("shipping_shippingMethodTypes") > -1 && el.checked) {
                    cmCreateManualLinkClickTag("/" + el.id);
                    shippingOption = el.id.replace("shipping_shippingMethodTypes_", "");
                }
            }

            formArray = $('frmOrderShippingMethod').getInputs('checkbox');
            for (i = 0; i < formArray.size(); i++) {
                el = formArray[i];

                // assured delivery option.
                if (el.id.indexOf("shipping_assuredDeliveryCheckBox") > -1 && el.checked) {
                    cmCreateManualLinkClickTag("/" + el.id);
                }
            }

            // if the expedited promo image shows up on OrderShippingMethod.aspx.
            var elements = $$('div#shipping_panelExpeditedPromo');
            if (elements[0] != null) {
                this.ConversionEventTagForExpeditedShippingOffer(shippingOption, "1")
            }
        }
    },

    // throwing a ConversionEventTag for the expedited shipping offer
    // Hwa Son 2/18/2009
    ConversionEventTagForExpeditedShippingOffer: function(shippingOption, actionType) {
        if (typeof (coremetrics) !== "undefined") {
            var point = 0;
            var eventId = "";

            switch (shippingOption) {
                case '1':
                    eventId = 'Rush';
                    point = 20;
                    break;
                case '2':
                    eventId = 'Express';
                    point = 30;
                    break;
                case '3':
                    eventId = 'Overnight';
                    point = 10;
                    break;
                default:
                    eventId = 'Standard';
                    point = 10;
                    break;
            }

            cmCreateConversionEventTag(eventId, actionType, "Expedited Shipping Offer", point);

            if (actionType == "1") {
                SetGenericSessionCookie("SentConversionEventTagForExpeditedShippingOffer", shippingOption);
            }
            else if (actionType == "2") {
                RemoveGenericSessionCookie("SentConversionEventTagForExpeditedShippingOffer");
            }
        }
    },

    //Throw element tag
    ElementTagWithAttributes: function(elementId, elementCategoryId, primaryLocation, subLocation) {
        if (typeof (coremetrics) !== "undefined") {
            var attributes = "";

            if (primaryLocation) attributes += primaryLocation;
            attributes += this.DELIMITER;

            if (subLocation) attributes += subLocation;
            attributes += this.DELIMITER;

            attributes = BillBoardCategoryName.RemoveSpecialCharacters(attributes.replace(this.REGEXP, ""));

            cmCreatePageElementTag(elementId, elementCategoryId, null, null, null, attributes);
        }
    },

    SendCoremetricsShopAction5Tag: function(shortSku, productName, quatity, price, cmCategoryId, reviewRating, totReviewCount, reviewRecommendPercentage, primaryProductCategoryNameInChain, productType, isNew, inventoryPosition, searchResults) {
        if (typeof (coremetrics) !== "undefined")
        {
            this.ShopActionTagWithAttributes(5, shortSku, productName, quatity, price, null, null, null, cmCategoryId, reviewRating, totReviewCount, reviewRecommendPercentage, primaryProductCategoryNameInChain, productType, isNew, inventoryPosition, null, null, null, null, searchResults);
        }
    }

    /* 2011-07-20 JChen - Obsolete: Old PDP Page
    SendCoremetricsTagOnReadReview: function(actionType) {
        if (typeof (coremetrics) !== "undefined") {
            this.ConversionEventTagWithAttributesForReview("Read All Reviews", actionType);
        }
    },

    SendCoremetricsTagOnWriteReview: function(actionType) {
        if (typeof (coremetrics) !== "undefined") {
            this.ConversionEventTagWithAttributesForReview("Write a Review", actionType);
        }
    }
    */

});

//var coremetrics = new FootSmartUI.Coremetrics();
//coremetrics.SetProduction();
/*
coremetrics.SendCoremetricsShopAction5Tag = function(shortSku, productName, quatity, price, cmCategoryId, reviewRating, totReviewCount, reviewRecommendPercentage, primaryProductCategoryNameInChain, productType, isNew, inventoryPosition)
{
    coremetrics.ShopActionTagWithAttributes(5, shortSku, productName, quatity, price, null, null, null, cmCategoryId, reviewRating, totReviewCount, reviewRecommendPercentage, primaryProductCategoryNameInChain, productType, isNew, inventoryPosition);
}

// Do not change this function name for Bazaar Voice.
coremetrics.SendCoremetricsTagOnReadReview = function(actionType)
{
    coremetrics.ConversionEventTagWithAttributesForReview("Read All Reviews", actionType);
}

// Do not change this function name for Bazaar Voice.
function SendCoremetricsTagOnWriteReview(actionType)
{
    coremetrics.ConversionEventTagWithAttributesForReview("Write a Review", actionType);
}

*/

