/************************************************************************************/
/* $Revision: 1.11 $
 * $Id: cmtaggingservices.js,v 1.11 2011/10/13 03:02:29 aflesner Exp $
 *
 * Author: Coremetrics/PSD
 * Coremetrics  v2.0, 2010/01/06
 * COPYRIGHT 1999-2008 COREMETRICS, INC.
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/
//Production data warehouse flag
//cmSetProduction();
/*===========================GLOBAL VARIABLES ===============================*/
// options for debug mode when sending tag:
// 1: only alert
// 2: only send tag
// 3: alert & send tag
var G_PS_DEBUG_MODE = 2;

var G_PS_ARR_DOMAIN = new Array("dollartree.com", "fry.com", "localhost:8080");

// current page url
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_URL_REFERRER = document.referrer.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000; // 5*24*60*60 = 5 days
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";
var G_PS_COOKIE_TEMP_EMAIL = "PS_TEMP_EMAIL";
var G_PS_COOKIE_PRE_PRDID = "PS_PRE_PRDID";

var G_PS_INTERVAL = 1000; // 1s
//var G_PS_INTERVAL = 5000; // 5s, for debug only

var G_PS_IS_QUICKVIEW_PAGE = false;
var G_PS_QUICK_INTERVALID = null;
var G_PS_CART_INTERVALID = null;
var G_PS_UPDATE_INTERVALID = null;

// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
function generateCMTags(reviewsCount, avgRating, percentRec)
{
    if((G_PS_URL_PATH.search(/(dollartree|dollartreeinfo|fry)\.com/i) >= 0) || (G_PS_URL_PATH.search(/localhost:8080/i) >= 0))
    {
        if(psIsSearchView()) psPostSearchView();
	    else if(psIsEnsemblePage()) psPostEnsembleView();
        else if(psIsProductView()) psPostProductView(reviewsCount, avgRating, percentRec);
	    else if(psIsCartView())
        {
            psPostCartView();
            psHijackResendShop5();
        }
        else if(psIsOrderView()) psPostOrderView();
	    else if(!psPostPageView()) psCreatePageviewTag(G_PS_PATHNAME, "ADD URL", null, null);

        psHijackRecentlyViewed();
	    psHijackRelatedItems();
        psHijackRegistration();
        psHijackViewShoppingCart();
        psCleanQuickViewInterval();
        psHijackSearchForm();
    }
}

function psIsEnsemblePage()
{
    return G_PS_PATHNAME.indexOf("/index.ens") >= 0 || G_PS_PATHNAME.indexOf("catalog/ensemble.jsp") >= 0;
}

function psPostEnsembleView()
{
    var variantId = null;
    var prdName = null;
    var prdId = null;
    var h3Tags = null;
    var prdCat = null;
	var ePrdId = null;
	var ePrdName = null;
    var avgRating = null;
    var numReviews = null;
    var inputNodes = null;

	if(G_PS_PATHNAME.search(/\/(\d+)c(\d+)c(\d+)e(\d+)\//i) >= 0)
    {
		prdCat = RegExp.$2;
		ePrdId = "e" + RegExp.$4;
		psSetCookie(G_PS_COOKIE_CATID, prdCat, null);
	}
    else if(G_PS_PATHNAME.search(/\/(\d+)c(\d+)e(\d+)\//i) >= 0)
    {
		prdCat = RegExp.$2;
		ePrdId = "e" + RegExp.$3;
		psSetCookie(G_PS_COOKIE_CATID, prdCat, null);
	}
    else if(G_PS_PATHNAME.indexOf("catalog/ensemble.jsp") >= 0)
    {
		ePrdId = "e" + psGetValueFromUrl(G_PS_URL_PATH, "ensembleId");
		prdCat = psGetCookie(G_PS_COOKIE_CATID);
	}

    var bcItems = psGetBreadCrumbItems();
	if(psCheckArrayExist(bcItems)) ePrdName = psCleanProductName(bcItems[bcItems.length - 1]);
	if(ePrdName == null || ePrdName == "" || ePrdName == "Home")
    {
        var h1Tags = document.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags)) ePrdName = psCleanProductName(psTrim(psGetInnerText(h1Tags[0])));
	}
    
    psCreateProductviewTag(ePrdId, ePrdName, prdCat, "-_--_--_-");

    var prd_str = "";
	var comDiv = document.getElementById("combo_products_wrap");
	if(psCheckElementExist(comDiv))
    {
		var rows = comDiv.getElementsByTagName("tr");
		if(psCheckArrayExist(rows))
        {
			for(var r = 0; r < rows.length; r++)
            {
                //Get product name
				h3Tags = rows[r].getElementsByTagName("h3");
                prdName = null;
				prdId = null;
                inputNodes = rows[r].getElementsByTagName("input");

                for(var j = 0; j < inputNodes.length; j++)
                {
                    if(inputNodes[j].name == "productId") variantId = inputNodes[j].value;
                }

				if(psCheckArrayExist(h3Tags))
                {
					for(var i = 0; i < h3Tags.length; i++)
                    {
						var aTags = h3Tags[i].getElementsByTagName("a");
						if(psCheckArrayExist(aTags)) prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));
					}
				}

                // Get productID
				var temp = psGetInnerText(rows[r]);
				if(temp.search(/Sku #\:\s*(\w+)\s+/i) >= 0)
                {
					prdId = RegExp.$1;
                    avgRating = document.getElementById("BVAvgRating_" + variantId).value;
                    numReviews = document.getElementById("BVNumReviews_" + variantId).value;
					psCreateProductviewTag(prdId, prdName, prdCat, numReviews + "-_-" + avgRating + "-_--_-");
					prd_str += prdId + ":";
				}
			}
		}
	}
	if(prd_str != "") psHijackAddToCart_fromProductview(prd_str, prdCat);
}

function psCleanQuickViewInterval()
{
	if(!G_PS_IS_QUICKVIEW_PAGE && G_PS_QUICK_INTERVALID != null)
    {
		window.clearInterval(G_PS_QUICK_INTERVALID);
		G_PS_QUICK_INTERVALID = null;
	}
}

function psHijackRegistration()
{
	if(G_PS_PATHNAME.search(/\/user\/(login|register)\.(jsp|cmd)/i) >= 0)
	{
		psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		psSetCookie(G_PS_COOKIE_PROFILE, "", "delete");
		psHijackOnSubmit("loginForm", "userName"); // Login
		psHijackOnSubmit("registerForm", "emailAddress"); // Register
	}
	else if(G_PS_PATHNAME.search(/\/user\/(change_email_password\.jsp|updateMemberEmailAddress\.cmd)/i) >= 0)
	{
		psHijackOnSubmit("editEmailForm", "newEmailAddress"); // change email
		var updatedFlag = false;
		var temp = psGetElementsByClassName(document, "p", "hilite");
		if(psCheckArrayExist(temp))
        {
			for(var i = 0; i < temp.length; i++)
            {
				if(psGetInnerText(temp[i]).search(/You\s+have\s+successfully\s+updated\s+your\s+Email\s+Address/i) >= 0) updatedFlag = true;
			}
		}
		if(updatedFlag) psPostRegistration();
		else
        {
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
			psSetCookie(G_PS_COOKIE_TEMP_EMAIL, "", "delete");
		}
	}else if(G_PS_PATHNAME.indexOf("/user/main.jsp") >= 0 || G_PS_PATHNAME.search(/checkout\/(shipping|billing)\.(jsp|cmd)/i) >= 0 )
    {
		psPostRegistration();
	}

    if(G_PS_PATHNAME.search(/checkout\/(billing|update_items_in_order)\.(jsp|cmd)/i) >= 0) psHijackBillingAddress();

    if(G_PS_PATHNAME.indexOf("user/personal_info.jsp") >= 0 || G_PS_PATHNAME.indexOf("user/updatememberinfo.cmd") >= 0)
    {
		psHijackManageBillingAddress();
	}

    if(G_PS_PATHNAME.indexOf("user/updatememberinfo.cmd") >= 0)
    {
		var pTags = psGetElementsByClassName(document,"p","hilite");
		if(psCheckArrayExist(pTags))
        {
			for(var i = 0; i < pTags.length; i++)
            {
				if(psGetInnerText(pTags[i]).search(/You\s+successfully\s+updated\s+your\s+billing\s+address/i) >= 0)
                {
					psUpdateBillingAddress();
				}
			}
		}
	}
}

function psPostPageView()
{
	var pPageId = null;
	var pCatId = null;
	var pIsQuickView = false;

	if(G_PS_PATHNAME == "/home.jsp" || G_PS_PATHNAME == "/") pPageId = pCatId = "Home";
    else if(G_PS_PATHNAME.indexOf("checkout/shipping_assignment_address.cmd") >= 0)
    {
		pPageId = "Add New Shipping Address";
		pCatId = "My Account";
	}
    else if(G_PS_PATHNAME.indexOf("checkout/update_award_in_order.cmd") >= 0)
    {
		// Payment page after apply promotion code
		pPageId = "Payment";
		pCatId = "Checkout";
	}
    else if(G_PS_PATHNAME.indexOf("catalog/alt_image_popup.jsp") >= 0) pPageId = pCatId = "Larger View";
	else if(G_PS_PATHNAME.indexOf("/email_a_friend.jsp") >= 0 ||
            G_PS_PATHNAME.indexOf("/catalog/product_email.cmd") >= 0 ||
            G_PS_PATHNAME.indexOf("/user/subscribe.jsp") >= 0 ||
            G_PS_PATHNAME.search(/checkout\/(billing|shipping|delivery|payment|update_items_in_order)\.(jsp|cmd)/i) >= 0)
    {
		// Get pageId from url
		var temp = G_PS_PATHNAME.replace(/^.+\//g,"");
		temp = temp.replace(/\.(jsp|cmd|asp|aspx|html|htm)/i,"");
		pPageId = pCatId = temp.replace(/\_/g," ");
		if(G_PS_PATHNAME.indexOf("checkout/") >= 0) pCatId = "Checkout";
	}
    else if(G_PS_PATHNAME.indexOf("/user/subscribe.cmd") >= 0) pPageId = pCatId = "Thank you for subscribing";
    else
    {
		var pPageName = psGetValueFromUrl(G_PS_URL_PATH, "pageName");
		if(pPageName != null && pPageName != "" && pPageName.search(/^ChristmasCorner$/i) >= 0)
        {
			pPageId = pCatId = pPageName;
			var temp = psGetValueFromUrl(G_PS_URL_PATH, "parentName");
			if(temp != null && temp != "") pCatId = temp;
		}
        else
        {
			var bcItems = psGetBreadCrumbItems();
			if(psCheckArrayExist(bcItems))
            {
				// Get pageId from breadcrumb
				pPageId = bcItems[bcItems.length-1];
				var decPath = psHtmlDecode(unescape(G_PS_PATHNAME));
				if(decPath.search(/(\d+)c(\d+)c(\d+)\/index\.cat/) >= 0)
                {
					// sub category
					// http://www.dollartree.com/health-personal-care/baby-products/211c242c242/index.cat
					pCatId = RegExp.$2;
					pIsQuickView = true;
				}
                else if(decPath.search(/c(\d+)\/index\.cat/) >= 0)
                {
					//sub category, exception:
					//http://www.dollartree.com/health-personal-care/bath-products/211c243/index.cat
					pCatId = RegExp.$1;
					pIsQuickView = true;
				}
                else if(decPath.search(/\/(\d+)\/index\.cat/) >= 0)
                {
					// Category at top menu
					pCatId = RegExp.$1;
				}
                else if(decPath.search(/catalog\/(thumbnail|section|category)\.jsp/) >= 0)
                {
					// View category from sitemap
					//http://www.dollartree.com/catalog/thumbnail.jsp?sectionId=202&parentCategoryId=202&categoryId=204&subCategoryId=204
					//http://www.dollartree.com/catalog/section.jsp?categoryId=202
					//http://www.dollartree.com/catalog/category.jsp?sectionId=211&parentCategoryId=211&categoryId=243
					var catId = psGetValueFromUrl(G_PS_URL_PATH, "categoryId");
					if(catId != null && catId != "") pCatId = catId;
				}
                else if(bcItems.length > 1) pCatId = bcItems[bcItems.length - 2];
			}
            else
            {
				// Get pageId from div grayHead -> H1
				var headDivs = psGetElementsByClassName(document, "div", "grayHead grayULine");
				if(psCheckArrayExist(headDivs))
                {
					var h1Tags = headDivs[0].getElementsByTagName("h1");
					if(psCheckArrayExist(h1Tags)) pPageId = pCatId = psGetInnerText(h1Tags[0]);
				}
			}
		}
	}
	if(pPageId == null && pCatId == null)
    {
		// Get from <h1 class="popTitle">Forgot Your Password?</h1> for popup window
		var h1Tags = psGetElementsByClassName(document, "h1", "popTitle");
		if(!psCheckArrayExist(h1Tags)) h1Tags = document.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags)) pPageId = pCatId = psGetInnerText(h1Tags[0]);
	}

	if(pPageId == null || pCatId == null) return false;

	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));

	pPageId = pPageId.toUpperCase();
	pCatId = pCatId.toUpperCase();

	psCreatePageviewTag(pPageId, pCatId, null, null);

	if(G_PS_PATHNAME.search(/catalog\/(alt_image_popup|alt_image_thumbnail|alt_image_view|email_a_friend|product_email)\.(jsp|cmd)/i) < 0 && pPageId.search(/Why\s+we\s+need\s+your\s+ZIP\s+code/i) < 0)
    {
		psSetCookie(G_PS_COOKIE_CATID, pCatId);
	}

	if(pIsQuickView && G_PS_QUICK_INTERVALID == null)
    {
		G_PS_IS_QUICKVIEW_PAGE = true;
		G_PS_QUICK_INTERVALID = window.setInterval("psCheckQuickViewProduct()", G_PS_INTERVAL);
	}
    else
    {
		if(G_PS_QUICK_INTERVALID != null)
        {
			window.clearInterval(G_PS_QUICK_INTERVALID);
			G_PS_QUICK_INTERVALID = null;
		}
	}

	return true;
}

function psUpdateBillingAddress()
{
	var uP = new psProfile();
	uP.readProfile();
	var city = psGetValueFromCookie(G_PS_COOKIE_TEMP_EMAIL, "city");
	var state = psGetValueFromCookie(G_PS_COOKIE_TEMP_EMAIL, "state");
	var zipcode = psGetValueFromCookie(G_PS_COOKIE_TEMP_EMAIL, "zipcode");

	if(psCheckElementExist(city)) uP.city = city;
	if(psCheckElementExist(state)) uP.state = state;
	if(psCheckElementExist(zipcode)) uP.zipcode = zipcode;
	uP.writeProfile();

	psPostRegistration();
	psSetCookie(G_PS_COOKIE_TEMP_EMAIL, "", "delete");
}

function psHijackManageBillingAddress()
{
	var bForm = psGetElementByName("form", "billingForm");
	if(psCheckElementExist(bForm))
    {
		if(bForm.onsubmit == null || bForm.onsubmit.toString().indexOf("psHJManageBillingAddress") < 0)
        {
			bForm.OldFunction = bForm.onsubmit;
			bForm.onsubmit = function psHJManageBillingAddress()
            {
				var city = psGetElementByName("input", "city");
				var state = psGetElementByName("select", "state");
				var zipcode = psGetElementByName("input"," zipCode");
				if(psCheckElementExist(city)) psSetValueToCookie(G_PS_COOKIE_TEMP_EMAIL, "city", psTrim(city.value));
				if(psCheckElementExist(state)) psSetValueToCookie(G_PS_COOKIE_TEMP_EMAIL, "state", state.options[state.selectedIndex].value);
				if(psCheckElementExist(zipcode)) psSetValueToCookie(G_PS_COOKIE_TEMP_EMAIL, "zipcode", psTrim(zipcode.value));

				psSetCookie(G_PS_COOKIE_FLAG, "login", null);
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackSearchForm()
{
	var sForm = psGetElementByName("form", "searchForm");
	if(psCheckElementExist(sForm))
    {
		if(sForm.onsubmit == null || sForm.onsubmit.toString().indexOf("psHJSearchForm") < 0)
        {
			sForm.OldFunction = sForm.onsubmit;
			sForm.onsubmit = function psHJSearchForm()
            {
				psSetCookie(G_PS_COOKIE_FLAG, "from_search", null);
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackBillingAddress()
{
	var buttons = document.getElementsByTagName("input");
	var btn = null;
	if(psCheckArrayExist(buttons))
    {
		for(var i = 0; i < buttons.length; i++)
        {
			var btnSrc = buttons[i].getAttribute("src");
			if(btnSrc != null && btnSrc.search(/btn\/big_continue\.gif/i) >= 0)
            {
				btn = buttons[i];
				break;
			}
		}
	}

    if(btn != null)
    {
		if(btn.onclick == null || btn.onclick.toString().indexOf("psHJBillingAddress") < 0)
        {
			btn.OldFunction = btn.onclick;
			btn.onclick = function psHJBillingAddress()
            {
				var city = document.getElementById("city");
				var state = document.getElementById("state");
				var zipcode = document.getElementById("zipCode");
				var email = document.getElementById("emailAddress");
				var uP = new psProfile();
				if(psCheckElementExist(city)) uP.city = psTrim(city.value);
				if(psCheckElementExist(state)) uP.state = state.options[state.selectedIndex].value;
				if(psCheckElementExist(zipcode)) uP.zipcode = psTrim(zipcode.value);
				if(psCheckElementExist(email)) uP.cusId = uP.email = psTrim(email.value);
				if(uP.email != null && psCheckEmail(uP.email))
                {
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG, "login", null);
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHJBillingLogin(action)
{
    var email;
    if(/\/checkout\/login.cmd/i.test(action)) email = $('#userName').attr('value');
    else if(/\/checkout\/billing.cmd/i.test(action)) email = $('#emailAddress').attr('value');

    if(psCheckElementExist(email))
    {
        var uP = new psProfile();
        uP.cusId = uP.email = psTrim(email);
        if(psCheckEmail(uP.email))
        {
            uP.writeProfile();
            psSetCookie(G_PS_COOKIE_FLAG, "login", null);
        }
    }
}

function psHijackResendShop5()
{
    //Resend shop5 when click on "Checkout" button, because the quantity can be changed
	var checkoutDivs = psGetElementsByClassName(document, "div", "right basket-checkout-button-wrapper");
	if(psCheckArrayExist(checkoutDivs))
    {
		var temps = checkoutDivs[0].getElementsByTagName("input");
		if(psCheckArrayExist(temps))
        {
			var checkoutBtn = temps[0];
			if(checkoutBtn.onclick == null || checkoutBtn.onclick.toString().indexOf("psHJResendShop5") < 0)
            {
				checkoutBtn.OldFunction = checkoutBtn.onclick;
				checkoutBtn.onclick = function psHJResendShop5()
                {
					psPostCartView();
					if(this.OldFunction != null) return this.OldFunction();
                }
			}
		}

	}
}

function consolidateItem5(products)
{
    var consolidatedItem5s = {};
    var consolidatedItem5 = null;
    var product, id, name, catId, price, quantity;

    for(var i = 0; i < products.length; i++)
    {
        product = products[i];
        if(consolidatedItem5s[product.id])
        {
            consolidatedItem5 = new psProduct();
            consolidatedItem5.setProduct(product.id, product.name, product.catId, product.price, parseInt(product.quantity) + parseInt(consolidatedItem5s[product.id].quantity));
            consolidatedItem5s[product.id] = consolidatedItem5;
        }
        else consolidatedItem5s[product.id] = product;
    }

    return consolidatedItem5s;
}

function psCheckQuickViewCart()
{
	var cartContent = document.getElementById("glo-ucart-content");
	if(psCheckElementExist(cartContent))
    {
		var checkoutTables = psGetElementsByClassName(cartContent, "table", "checkoutTable");
		if(psCheckArrayExist(checkoutTables))
        {
			var products = new Array();
            var product = null;
            var sendShop5Flag = false;

            //for each row in the cart parse and item5 product from the row
            var rows = checkoutTables[0].rows;
			for(var i = 0; i < rows.length; i++)
            {
				//the first two ifs catch rows that are not products but are functionality items
                if(rows[i].innerHTML != null && rows[i].innerHTML.search(/btn\/sm_remove\.jpg/i) < 0) continue;
				else if(rows[i].cells.length < 4) continue;
                else
                {
                    //we have a product row parse an item5 product from it and push it into an array for consolidation
                    product = new psProduct();
                    if(product.getItem5(rows[i])) products.push(product);
                }
            }

            //consolidate the array of item5s (if there is a case and a units row for the same SKU combine them together)
            var item5s = consolidateItem5(products);
            for(var sku in item5s)
            {
                var item5 = item5s[sku];
                if(item5.id != null && item5.name != null)
                {
                    //for each consolidated item5 create an item5 tag
                    psCreateShopAction5Tag(item5.id, item5.name, item5.quantity, item5.price, item5.catId);
					sendShop5Flag = true;
                }
            }

            if(sendShop5Flag)
            {
				psDisplayShop5s();
				//clear interval
				if(G_PS_CART_INTERVALID != null)
                {
					window.clearInterval(G_PS_CART_INTERVALID);
					G_PS_CART_INTERVALID = null;
				}
			}
			psHijackQuickEditRemoveQuantity(cartContent);

            //clear interval for hijack Update button
			if(G_PS_UPDATE_INTERVALID != null)
            {
				window.clearInterval(G_PS_UPDATE_INTERVALID);
				G_PS_UPDATE_INTERVALID = null;
			}
		}
	}
}

function psHijackQuickEditRemoveQuantity(quickCart)
{
	var aTags = quickCart.getElementsByTagName("a");
	if(psCheckArrayExist(aTags))
    {
		for(var i = 0; i < aTags.length; i++)
        {
			var aSrc = aTags[i].innerHTML;
			if(aSrc != null && aSrc.search(/btn\/(sm_remove|sm_edit)\.jpg/i) >= 0)
            {
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJEditRemove") < 0)
                {
					aTag.OldFunction = aTag.onclick;
					aTag.aSrc = aSrc;
					aTag.onclick = function psHJEditRemove()
                    {
						if(this.aSrc.search(/btn\/sm_edit\.jpg/i) >= 0)
                        {
							// Wait for editing quantity
							if(G_PS_UPDATE_INTERVALID == null)
                            {
								G_PS_UPDATE_INTERVALID = window.setInterval("psHijackUpdateCartButton()", G_PS_INTERVAL);
							}
						}
                        else
                        {
							// Click on remove
							if(G_PS_CART_INTERVALID == null)
                            {
								G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()", G_PS_INTERVAL);
							}
						}
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackUpdateCartButton()
{
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags))
    {
		for(var i = 0; i < aTags.length; i++)
        {
			var aSrc = aTags[i].innerHTML;
			if(aSrc != null && aSrc.search(/btn\/add_to_cart\.gif/i) >= 0)
            {
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJEditRemove") < 0)
                {
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJEditRemove()
                    {
						if(G_PS_CART_INTERVALID == null)
                        {
							G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()", G_PS_INTERVAL);
						}
						// clear interval for hijack Update button
						if(G_PS_UPDATE_INTERVALID != null)
                        {
							window.clearInterval(G_PS_UPDATE_INTERVALID);
							G_PS_UPDATE_INTERVALID = null;
						}
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackViewShoppingCart()
{
	// Set interval to send shop5 when clicking on "Shopping cart" button
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags))
    {
		for(var i = 0; i < aTags.length; i++)
        {
			var aTag = aTags[i];
			if(aTag.href != null && aTag.href.search(/checkout\/basket\.jsp/i) >= 0)
            {
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJViewCart") < 0)
                {
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJViewCart()
                    {
						if(G_PS_CART_INTERVALID == null)
                        {
							G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()", G_PS_INTERVAL);
						}
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}
}

function psCheckQuickViewProduct()
{
    //Send productview when ajax load QuickView
	var quickViewDiv = document.getElementById("cat-quickview-content");
	if(psCheckElementExist(quickViewDiv))
    {
        var prdName = null;
        var prdId = null;
        var isEnsemble = false;

        //determine name, id and type of item
        var h1Tags = quickViewDiv.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags))
        {
			for(var i = 0; i < h1Tags.length; i++)
            {
				var aTags = h1Tags[i].getElementsByTagName("a");
				if(psCheckArrayExist(aTags))
                {
					for(var j = 0; j < aTags.length; j++)
                    {
						var url = aTags[j].href;
						if(url != null && url.search(/catalog\/product\.jsp\?productId\=/i) >= 0)
                        {
							//item is a product
                            isEnsemble = false;
                            prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[j])))));
						}
						if(url != null && url.search(/catalog\/ensemble\.jsp\?ensembleId\=/i) >= 0)
                        {
							//item is an ensemble
                            isEnsemble = true;
                            prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[j])))));
							prdId = "e" + psGetValueFromUrl(url, "ensembleId");
						}
					}
				}
			}

            if(!isEnsemble)
            {
                //get sku from page
                var skuDiv = psGetElementsByClassName(quickViewDiv, "dl", "sku");
                prdId = $(skuDiv).find("dd").text();
            }

            var preProductId = psGetCookie(G_PS_COOKIE_PRE_PRDID);
            var prdCat = psGetCookie(G_PS_COOKIE_CATID);
            if(G_PS_PATHNAME.indexOf("checkout/basket.jsp") >= 0) prdCat = "Related Items";
            if(prdId != null && prdName != null && (preProductId == null || prdId != preProductId))
            {
                psCreateProductviewTag(prdId, prdName, prdCat, "-_--_--_-Quickview");
                psSetCookie(G_PS_COOKIE_PRE_PRDID, prdId, null);
                //Hijack Add to cart
                psHijackQuickAddToCart(quickViewDiv, prdId, prdCat);

                //Send productview for each item in ensemble
                if(prdId.indexOf("e") >= 0)
                {
                    var qDivs = psGetElementsByClassName(quickViewDiv, "div", "qv_combo_cell");
                    if(psCheckArrayExist(qDivs))
                    {
                        for(var r = 0; r < qDivs.length; r++)
                        {
                            //Get product name
                            var h3Tags = qDivs[r].getElementsByTagName("h3");
                            if(psCheckArrayExist(h3Tags)) prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(h3Tags[0])))));
                            //Get productId
                            var temp = qDivs[r].innerHTML;
                            if(temp.search(/product_images\/styles\/small\/(\w+)\.jpg/i) >= 0)
                            {
                                prdId = RegExp.$1;
                                psCreateProductviewTag(prdId, prdName, prdCat, "-_--_--_-Quickview");
                            }
                        }
                    }
                }
            }
        }
	}
}

function psHijackAddToCart_fromProductview(prdId, prdCat)
{
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags))
    {
		for(var i = 0; i < aTags.length; i++)
        {
			var aTag = aTags[i];
			if(aTag.innerHTML != null && (aTag.innerHTML.search(/btn\/add_to_cart_icon\.gif/i) >= 0 || aTag.innerHTML.search(/btn\/add_to_cart\.gif/i) >=0))
            {
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJAddToCartPW") < 0)
                {
					aTag.OldFunction = aTag.onclick;
					aTag.prdId = prdId;
					aTag.prdCat = prdCat;
					aTag.onclick = function psHJAddToCartPW()
                    {
						if(this.prdId != null && this.prdId.indexOf(":") >= 0)
                        {
							// Ensemble
							var pItems = this.prdId.split(":");
							for(var t=0; t < pItems.length; t++)
                            {
								if(pItems[t] != "")
                                {
									psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pItems[t], this.prdCat);
								}
							}
						}
                        else psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.prdId, this.prdCat);

						// Set interval to send shop5
						if(G_PS_CART_INTERVALID == null)
                        {
                            G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()", G_PS_INTERVAL);
						}
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackQuickAddToCart(quickDiv, productId, productCat)
{
	var addToCartBtns = psGetElementsByClassName(quickDiv, "a", "widget-quickview-but-add");
	if(psCheckArrayExist(addToCartBtns))
    {
		var addBtn = addToCartBtns[0];
		if(addBtn.onclick == null || addBtn.onclick.toString().indexOf("psHJQuickBuy") < 0)
        {
			addBtn.OldFunction = addBtn.onclick;
			addBtn.prdId = productId;
			addBtn.prdCat = productCat;
			addBtn.onclick = function psHJQuickBuy()
            {
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.prdId, this.prdCat);
				// Set interval to send shop5
				if(G_PS_CART_INTERVALID == null)
                {
						G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()", G_PS_INTERVAL);
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psPostRegistration()
{
	var cookieFlag = psGetCookie(G_PS_COOKIE_FLAG);
	if(cookieFlag == "login")
    {
		var uP = new psProfile();
		uP.readProfile();
		if(uP.cusId != null) psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
	}
    else if(cookieFlag == "edit_email")
    {
		var uP = new psProfile();
		uP.readProfile();
		var tempEmail = psGetCookie(G_PS_COOKIE_TEMP_EMAIL);
		if(tempEmail != null && tempEmail != "")
        {
			uP.cusId = uP.email = tempEmail;
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
			uP.writeProfile();
			psSetCookie(G_PS_COOKIE_TEMP_EMAIL, "", "delete");
		}
	}
	psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
}

function psHijackOnSubmit(formName,emailId)
{
	var frm = psGetElementByName("form",formName);
	if(psCheckElementExist(frm))
    {
		if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJEmail") < 0)
        {
			frm.emailId = emailId;
			frm.OldFunction = frm.onsubmit;
			frm.onsubmit = function psHJEmail()
            {
				var email = document.getElementById(this.emailId);
				if(psCheckElementExist(email))
                {
					if(this.emailId == "newEmailAddress")
                    {
						// change email, write to temporary cookie
						psSetCookie(G_PS_COOKIE_TEMP_EMAIL, psTrim(email.value), null);
						psSetCookie(G_PS_COOKIE_FLAG, "edit_email", null);
					}
                    else
                    {
						//login or registration
						var uP = new psProfile();
						uP.cusId = uP.email = psTrim(email.value);
						if(this.emailId == "emailAddress")
                        {
							// registration
							var zipcode = document.getElementById("zipCode");
							if(psCheckElementExist(zipcode)) uP.zipcode = psTrim(zipcode.value);
						}

						uP.writeProfile();
						psSetCookie(G_PS_COOKIE_FLAG,"login");
					}
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackRelatedItems()
{
	// At productview page
	var rightDiv = document.getElementById("right_rail");

	// At Shopping cart page
	if(G_PS_PATHNAME.indexOf("checkout/basket.jsp") >= 0 || !psCheckElementExist(rightDiv))
    {
		var relatedDivs = psGetElementsByClassName(document,"div","basket-also-like-container");
		if(psCheckArrayExist(relatedDivs)) rightDiv = relatedDivs[0];
	}

	if(psCheckElementExist(rightDiv))
    {
		var pSectionName = null;
		var h2Tags = rightDiv.getElementsByTagName("h2");
		if(psCheckArrayExist(h2Tags)) pSectionName = psTrim(psHtmlDecode(unescape(psGetInnerText(h2Tags[0]))));
		if(pSectionName == null || pSectionName == "") return;
		var aTags = rightDiv.getElementsByTagName("a");
		if(psCheckArrayExist(aTags))
        {
			for(var i = 0; i < aTags.length; i++)
            {
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJRelatedItems") < 0)
                {
					aTag.sectionName = pSectionName;
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJRelatedItems()
                    {
						psSetCookie(G_PS_COOKIE_CATID, this.sectionName, null);
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackRecentlyViewed()
{
	var leftDiv = document.getElementById("viewed-products");
	if(psCheckElementExist(leftDiv))
    {
		var pSectionName = null;
		var h6Tags = leftDiv.getElementsByTagName("h6");
		if(psCheckArrayExist(h6Tags)) pSectionName = psTrim(psHtmlDecode(unescape(psGetInnerText(h6Tags[0]))));
		if(pSectionName == null || pSectionName == "") return;
		var aTags = leftDiv.getElementsByTagName("a");
		if(psCheckArrayExist(aTags))
        {
			for(var i = 0; i < aTags.length; i++)
            {
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJRecentlyViewed") < 0)
                {
					aTag.sectionName = pSectionName;
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJRecentlyViewed()
                    {
						psSetCookie(G_PS_COOKIE_CATID, this.sectionName, null);
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}
}

function psGetBreadCrumbItems()
{
	var arrResult = new Array();
	var index = 0;

	var bc = document.getElementById("breadcrumb");
	if(psCheckElementExist(bc))
    {
		var liTags = bc.getElementsByTagName("li");
		if(psCheckArrayExist(liTags))
        {
			for(var i = 0; i < liTags.length; i++)
            {
				var temp = psTrim(psHtmlDecode(unescape(psGetInnerText(liTags[i]))));
				if(temp != null && temp != "")
                {
					arrResult[index]= temp;
					index++;
				}
			}
		}
	}

    return arrResult;
}

function psIsSearchView()
{
	if(G_PS_PATHNAME.indexOf("catalog/search.cmd") >= 0)
    {
		var prdDiv = psGetElementsByClassName(document,"div","prodImageWrap");
		var prdId = psGetElementByName("input","productId");
		if(psCheckArrayExist(prdDiv) || psCheckElementExist(prdId)) return false;
		return true;
	}
	return false;
}

function psIsProductView()
{
	if(G_PS_PATHNAME.indexOf("/index.pro") >= 0 || G_PS_PATHNAME.indexOf("catalog/product.jsp") >= 0) return true;
	if(G_PS_PATHNAME.indexOf("catalog/search.cmd") >= 0)
    {
		var prdDiv = psGetElementsByClassName(document,"div","prodImageWrap");
		var prdId = psGetElementByName("input","productId");
		if(psCheckArrayExist(prdDiv) || psCheckElementExist(prdId)) return true;
	}
	return false;
}

function psIsCartView()
{
    if(G_PS_PATHNAME.indexOf("/checkout/basket.jsp") >= 0) return true;
	if(G_PS_PATHNAME.indexOf("checkout/update_items_in_order.cmd") >= 0)
    {
        //It can be shopping cart page after applying promotion code or billing address
		var h1Tags = document.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags))
        {
			for(var i = 0; i < h1Tags.length; i++)
            {
				var temp = psGetInnerText(h1Tags[i]);
				if(temp != null && temp.search(/Shopping\s+Cart/i) >= 0) return true;
			}
		}
	}

	return false;
}

function psIsOrderView()
{
	return G_PS_PATHNAME.indexOf("/checkout/receipt.jsp") >= 0;
}

function generateCMConversionEventTags(pageType, hasReviews, reviewTag)
{
    var prd = new psProduct();
    var eventID = "";
    var actionType = "";
    var categoryID = "";
    var points = "";
    var attributes = "";

    if(prd.getProduct())
    {
        //if we are on the product page and there are no reviews
        if(pageType == 'product' && !hasReviews)
        {
            eventID = "Write a Review";
            actionType = "1";
            categoryID = "User Reviews";
            points = "5";
            attributes = prd.name;
        }

        //if we are on the product page and there are reviews returned
        else if(pageType == 'product' && hasReviews)
        {
            // clicked on write review links
            if(reviewTag == 'BVCustomerRatings' || reviewTag == 'BVReviewsContainer')
            {
                eventID = "Write a Review";
                actionType = "1";
                categoryID = "User Reviews";
                points = "5";
                attributes = prd.name;
            }

            // clicked on thumbs up for yes this was helpful
            else if(reviewTag == 'BVRRReviewFeedbackLinkYes')
            {
                eventID = "Helpful Review";
                actionType = "2";
                categoryID = "User Reviews";
                points = "5";
                attributes = prd.name;
            }

            // clicked on thumbs down for no this was not helpful
            else if(reviewTag == 'BVRRReviewFeedbackLinkNo')
            {
                eventID = "Unhelpful Review";
                actionType = "2";
                categoryID = "User Reviews";
                points = "5";
                attributes = prd.name;
            }

            // clicked on inappropriate link to flag as inappropriate                
            else if(reviewTag == 'BVRRReviewFeedbackLinkInappropriate')
            {
                eventID = "Inappropriate Review";
                actionType = "1";
                categoryID = "User Reviews";
                points = "5";
                attributes = prd.name;
            }
        }

        // if we are on the reviews page
        else if(pageType == 'reviews')
        {
            // if we clicked the submit button to submit the review
            if(reviewTag == 'BVRRSubmitReviewButtonID')
            {
                eventID = "Write a Review";
                actionType = "2";
                categoryID = "User Reviews";
                points = "20";
                attributes = prd.name;
            }

            // else if we clicked on the submit button to submit inappropriate reasoning
            else if(reviewTag == 'BVRRSubmitInappropriateFeedbackButtonID')
            {
                eventID = "Inappropriate Review";
                actionType = "2";
                categoryID = "User Reviews";
                points = "20";
                attributes = prd.name;
            }
        }

    }
    cmCreateConversionEventTag(eventID, actionType, categoryID, points, attributes);
}

/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	G_PS_CUR_CATID = "SEARCH";
	var pPageId = "SEARCH UNSUCCESSFUL";
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();

    if(sResult != "0")
    {
        var viewAll = psTrim(psGetValueFromUrl(G_PS_URL_PATH, "viewall"));
        if(viewAll == "true") pPageId = "SEARCH SUCCESSFUL VIEW ALL";
		else pPageId = "SEARCH SUCCESSFUL PAGE[" + psGetPageNumber() + "]";
	}

    if(psGetCookie(G_PS_COOKIE_FLAG) == "from_search" || G_PS_URL_REFERRER.indexOf("catalog/search.cmd") >= 0)
    {
		psCreatePageviewTag(pPageId, G_PS_CUR_CATID, sTerm, sResult);
		psSetCookie(G_PS_COOKIE_CATID, G_PS_CUR_CATID, null);
	}
    else
    {
		G_PS_CUR_CATID = "Defined Search";
		pPageId = "Defined Search: " + sTerm;
		psCreatePageviewTag(pPageId, G_PS_CUR_CATID, null, null);
		psSetCookie(G_PS_COOKIE_CATID, G_PS_CUR_CATID, null);
	}

    psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
	G_PS_IS_QUICKVIEW_PAGE = true;
	if(G_PS_QUICK_INTERVALID == null) G_PS_QUICK_INTERVALID = window.setInterval("psCheckQuickViewProduct()", G_PS_INTERVAL);
}

function psGetPageNumber()
{
	var spanTags = psGetElementsByClassName(document, "span", "currentPage");
	if(psCheckArrayExist(spanTags))
    {
		return psTrim(psHtmlDecode(unescape(psGetInnerText(spanTags[0]))));
	}
	return "1";
}

function psGetSearchTerm()
{
	var term = "";
	var searchTag = document.getElementById("searchKey");
	if(psCheckElementExist(searchTag))cterm = psTrim(searchTag.value);
	else term = psTrim(psHtmlDecode(unescape(psGetValueFromUrl(G_PS_URL_PATH,"keyword"))));
	return term;
}

function psGetSearchResult()
{
	var result = "0";
	var pTags = document.getElementsByTagName("p");
	if(psCheckArrayExist(pTags))
    {
		for(var i = 0; i < pTags.length; i++)
        {
			var temp = psGetInnerText(pTags[i]);
			if(temp != null && temp.search(/There\s+are\s+(\d+)\s+products\s+that\s+match\s+your\s+search/i) >= 0)
            {
				return RegExp.$1;
			}
		}
	}
	return result;
}

function psPostProductView(reviewsCount, avgRating, percentRec)
{
    var prd = new psProduct();
    if(prd.getProduct())
    {
        psCreateProductviewTag(prd.id, prd.name, prd.catId, avgRating + "-_-" + reviewsCount + "-_-" + percentRec + "-_-");
		psHijackAddToCart_fromProductview(prd.id, prd.catId);
	}
}

function psPostCartView()
{
    G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("BASKET", G_PS_CUR_CATID, null, null);
	psSetCookie(G_PS_COOKIE_CATID, "BASKET", null);

    var products = new Array();
    var product = null;
    var sendShop5Flag = false;
	var cartTbl = document.getElementById("shopping-cart-items");
	if(cartTbl == null) return;

    //for each row in the cart parse and item5 product from the row
    var rows = cartTbl.rows;
	for(var r = 0; r < rows.length; r++)
	{
        //the first two ifs catch rows that are not products but are functionality items
        if(rows[r].innerHTML.search(/checkout\/delete_item_from_order\.cmd/gi) < 0) continue;
		else if(rows[r].cells.length < 5) continue;
        else
        {
            //we have a product row parse an item5 product from it and push it into an array for consolidation
            product = new psProduct();
            if(product.getItem5(rows[r])) products.push(product);
        }
    }

    //consolidate the array of item5s (if there is a case and a units row for the same SKU combine them together)
    var item5s = consolidateItem5(products);
    for(var sku in item5s)
    {
        var item5 = item5s[sku];
        if(item5.id != null && item5.name != null)
        {
            //for each consolidated item5 create an item5 tag
            psCreateShopAction5Tag(item5.id, item5.name, item5.quantity, item5.price, item5.catId);
            sendShop5Flag = true;
        }
    }
	if(sendShop5Flag) psDisplayShop5s();

    //Set interval for Quickview product at Related Items
	if(G_PS_QUICK_INTERVALID == null)
    {
        G_PS_IS_QUICKVIEW_PAGE = true;
		G_PS_QUICK_INTERVALID = window.setInterval("psCheckQuickViewProduct()", G_PS_INTERVAL);
	}
}

function psPostOrderView()
{
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("ORDER COMPLETE", G_PS_CUR_CATID, null, null);
	psSetCookie(G_PS_COOKIE_CATID, "ORDER COMPLETE", null);

	var ord = new psOrder();
	if(ord.setReceiptOrd(cmOrder))
	{
		var uP = new psProfile();
		if(uP.readProfile())
		{
			var prd = new psProduct();

            for(var i = 0; i < cmProducts.length; i++)
            {
                if(prd.setReceiptPrd(cmProducts[i])) psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
            }

			// Make sure to have actual postings
			psDisplayShop9s();
			psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.cusId, uP.city, uP.state, uP.zipcode);
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
			psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	this.setProduct = function(id, name, catId, price, quantity)
    {
        this.id = id;
		this.name = name;
		this.catId = catId;
		this.price = price;
		this.quantity = quantity;
    };

    this.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
		this.price = null;
		this.quantity = null;
	};

	this.getProduct = function()
	{
		try
		{
			this.reset();

            //get sku from page
            var skuDiv = psGetElementsByClassName(document, "dl", "sku");
            if(psCheckArrayExist(skuDiv)) this.id = $(skuDiv).find("dd").text();

            //get product name from page try breadcrumbs first
			var bcItems = psGetBreadCrumbItems();
			if(psCheckArrayExist(bcItems))
            {
				this.name = psCleanProductName(bcItems[bcItems.length - 1]);
				if(this.name != null && this.name.toUpperCase() == "HOME")
                {
					//if name not available in breadcrumbs, use header tag
                    var h1Tags = document.getElementsByTagName("h1");
					if(psCheckArrayExist(h1Tags)) this.name = psTrim(psCleanProductName(psHtmlDecode(unescape(psGetInnerText(h1Tags[0])))));
				}
			}

            if(G_PS_URL_REFERRER == null || G_PS_URL_REFERRER == "")
            {
				//get category id from url
                if(G_PS_PATHNAME.search(/\/(\d+)c(\d+)c(\d+)p.+\/index\.pro/i) >= 0) this.catId = RegExp.$2;
				else this.catId = "Bookmarks";
			}
            else if(G_PS_URL_REFERRER.indexOf("dollartree.com") < 0) this.catId = "Bookmarks";
			else
            {
                //if category id unavailable via url get from cookie G_PS_COOKIE_CATID
                this.catId = psGetCookie(G_PS_COOKIE_CATID);
				if(this.id != null && ((this.catId == "basket" && G_PS_URL_REFERRER.indexOf("checkout/basket.jsp") >= 0) ||
					G_PS_URL_REFERRER.search(/checkout\/(delivery|payment)\.jsp/i) >= 0))
                {
					//if category id unavailable from G_PS_COOKIE_CATID get from G_PS_COOKIE_PROD_CATID
                    this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				}
			}
			if(G_PS_PATHNAME.indexOf("catalog/search.cmd") >= 0) this.catId = "Search";
			if(this.id != null && this.id != "") return true;
		}
		catch(ex){ return false; }
	};

	this.getItem5 = function(itemRow)
	{
		try
		{
            var aTags = null;
            var casePack = null;

            this.reset();
            if($(itemRow).hasClass('glo-ucart-slider-item'))
            {
                //we are on the universal cart screen
                //populate SKU
                if(itemRow.cells[0].innerHTML.search(/product_images\/styles\/small\/(\w+)\.jpg/i) >= 0) this.id = RegExp.$1;

                //populate name
                aTags = itemRow.cells[1].getElementsByTagName("a");
                if(psCheckArrayExist(aTags)) this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));

                //populate casepack
                var pTags = itemRow.cells[1].getElementsByTagName("p");
                if(psCheckArrayExist(pTags) && psGetInnerText(pTags[0]).search(/(\d+)\s+units/i) >= 0) casePack = RegExp.$1;

                //populate quantity multiply by casepack if this a cases item
                var cell2 = psGetInnerText(itemRow.cells[2]);
                if(cell2 != null && cell2.search(/(\d+)\s+Case/i) >= 0) this.quantity = parseInt(RegExp.$1) * parseInt(casePack);
                else if(cell2 != null && cell2.search(/(\d+)\s+Unit/i) >= 0) this.quantity = RegExp.$1;

                //populate the unit price by dividing the line price by the quantity
                var strongTags = itemRow.cells[2].getElementsByTagName("strong");
                if(psCheckArrayExist(strongTags))
                {
                    this.price = psCleanPrice(psGetInnerText(strongTags[0]));
                    if(isFinite(this.price) && isFinite(this.quantity))
                    {
                        this.price = parseFloat(this.price) / parseFloat(this.quantity);
                        this.price = this.price.toFixed(2);
                    }
                }

                //populate the category id if the condition is true consider this object valid
                if(this.id != null)
                {
                    this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
                    if(this.catId == null || this.catId == "") this.catId = "Unknown";
                    return true;
                }
            }
            else
            {
                //we are on the basket screen
                //populate SKU
                if(psGetInnerText(itemRow.cells[1]).search(/SKU #\:\s*(\w+)\s+/i) >= 0) this.id = RegExp.$1;

                //populate casepack
                if(psGetInnerText(itemRow.cells[1]).search(/(\d+)\s*units/i) >= 0) casePack = RegExp.$1;

                //populate name
                aTags = itemRow.cells[1].getElementsByTagName("a");
                if(psCheckArrayExist(aTags)) this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));

                //populate quantity multiply by casepack if this a cases item
                var qtyText = psGetInnerText(itemRow.cells[2]);
                if(qtyText != null && qtyText.search(/case\(s\)/i) >= 0)
                {
                    this.quantity = parseInt($(itemRow.cells[2]).find('input').val()) * parseInt(casePack);
                }
                else if(qtyText != null && qtyText.search(/unit\(s\)/i) >= 0)
                {
                    this.quantity = $(itemRow.cells[2]).find('select option:selected').val();
                }

                var handling = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[4])));
                handling = isNaN(handling) ? 0 : handling;

                //populate the unit price by dividing the line price by the quantity
                this.price = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[5])));
                if(isFinite(this.price) && isFinite(this.quantity))
                {
                    this.price = (parseFloat(this.price) - parseFloat(handling)) / parseFloat(this.quantity);
                    this.price = this.price.toFixed(2);
                }

                //populate the category id if the condition is true consider this object valid
                if(this.id != null)
                {
                    this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
                    if(this.catId == null || this.catId == "") this.catId = "Unknown";
                    return true;
                }
            }
		}
		catch(ex) { return false; }
	};

    this.getItem9 = function(itemRow)
	{
		try
		{
			this.reset();
            var temp = psGetInnerText(itemRow.cells[1]);
			if(temp.search(/SKU #\:\s*(\w+)\s+/i) >= 0) this.id = RegExp.$1;
			var aTags = itemRow.cells[1].getElementsByTagName("a");
			if(psCheckArrayExist(aTags))
            {
				this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));
			}
			this.price = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[2])));
			this.quantity = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[3])));
			if(this.id != null) this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
     		return true;
		}
		catch(ex){ return false; }
	};

    this.setReceiptPrd = function(cmProduct)
    {
    	try
		{
			this.reset();
            this.id = cmProduct.sku;
			this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(cmProduct.name))));
			this.price = psCleanPrice(psTrim(cmProduct.price));
			this.quantity = psCleanPrice(psTrim(cmProduct.quantity));
			if(this.id != null) this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
     		return true;
		}
		catch(ex){ return false; }
	};
}

function psProfile()
{
	this.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;

	this.readProfile = function()
	{
		try
		{
			this.cusId = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.cusId != null)
			{
				var buf = this.cusId.split('|');
				for (var i = 0; i < buf.length; i++)
				{
					var tempVal = buf[i];
					buf[i] = (tempVal== "null" ? null : tempVal);
				}
				this.cusId = buf[0];
				if(!this.cusId) this.cusId = psGenerateRandomValue();
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			return true;
		}
		catch (ex) { return false; }
	};

	this.writeProfile = function()
	{
		try
		{
			if(this.cusId == null) return;
			var data = this.cusId + "|" + this.email + '|' + this.city + '|' + this.state + '|'
				+ this.zipcode + "|" + this.newsletter + '|' + this.subscribe;
			// store on cookie
			psSetCookie(G_PS_COOKIE_PROFILE, data, null);
			return true;
		}
		catch (ex) { return false; }
	};
}

function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;

	this.getOrder = function()
	{
		try
		{
			var h5Tags = document.getElementsByTagName("h5");
			if(psCheckArrayExist(h5Tags))
            {
				for(var i = 0; i < h5Tags.length; i++)
                {
					if(psGetInnerText(h5Tags[i]).search(/Order\s+Number\:\s*(\w+)\s+placed\s+on/i) >= 0)
                    {
						this.id = RegExp.$1;
					}
				}
			}

            var orderSummaryTags = psGetElementsByClassName(document, "dl", "orderSummary");
			if(psCheckArrayExist(orderSummaryTags))
            {
				var shipping = null;
				var handling = null;
				var discount = null;
				var dtTags = orderSummaryTags[0].getElementsByTagName("dt");
				var ddTags = orderSummaryTags[0].getElementsByTagName("dd");
				if(psCheckArrayExist(dtTags) && psCheckArrayExist(ddTags))
                {
					for(var i = 0; i < dtTags.length; i++)
                    {
						if(psGetInnerText(dtTags[i]).search(/Merchandise\s*\:/i) >= 0)
                        {
							if(psCheckElementExist(ddTags[i])) this.subtotal = psCleanPrice(psGetInnerText(ddTags[i]));
						}

                        if(psGetInnerText(dtTags[i]).search(/Handling\s*\:/i) >= 0)
                        {
							if(psCheckElementExist(ddTags[i]) && psGetInnerText(ddTags[i]).search(/\d+/) >= 0)
                            {
								handling = psCleanPrice(psGetInnerText(ddTags[i]));
							}
						}

                        if(psGetInnerText(dtTags[i]).search(/Shipping\s*\:/i) >= 0)
                        {
							if(psCheckElementExist(ddTags[i])) shipping = psCleanPrice(psGetInnerText(ddTags[i]));
						}

                        if(psGetInnerText(dtTags[i]).search(/Order\s+Discount\s*\:/i) >= 0)
                        {
							if(psCheckElementExist(ddTags[i])) discount = psCleanPrice(psGetInnerText(ddTags[i]));
						}
					}
				}

                if(handling != null && shipping != null && isFinite(handling) && isFinite(shipping))
                {
					shipping = parseFloat(shipping) + parseFloat(handling);
					shipping = shipping.toFixed(2);
				}

                if(discount != null && this.subtotal != null && isFinite(discount) && isFinite(this.subtotal))
                {
					this.subtotal = parseFloat(this.subtotal) - parseFloat(discount);
					this.subtotal = this.subtotal.toFixed(2);
				}
				this.shipping = shipping;
			}

			if(!this.id) this.id = psGenerateRandomValue();

            var uP = new psProfile();
			uP.readProfile();
            if(!uP.cusId) uP.cusId = psGenerateRandomValue();
			return uP.writeProfile();
		}
		catch(ex){ return false; }
	};

    this.setReceiptOrd = function(cmOrder)
    {
    	try
		{
            this.id = cmOrder.id;
			this.subtotal = cmOrder.subtotal;
            this.shipping = cmOrder.shipping;
     		return true;
		}
		catch(ex){ return false; }
	};
}

function psIsEqual()
{
	for (var i = 0; i < arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

function psGetInnerText(pTagOjb)
{
	var pattern = /<script[\s\S]*?<\/script>/gi;
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while(sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

function psCleanCatId(pCatId)
{
    return (pCatId != null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null;
}

function psCleanProductName(pProductName)
{
	pProductName = pProductName.replace(String.fromCharCode(8541),"");
	pProductName = pProductName.replace(String.fromCharCode(189),""); // 1/2
	pProductName = pProductName.replace(String.fromCharCode(188),""); // 1/4

	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null;
}

function psTrim(pStr)
{
	if(pStr == null || typeof(pStr) != "string") return pStr;
	return (pStr != null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

function psGetValueFromUrl(pUrl, pKey)
{
	pUrl = (pUrl != null) ? "?" + psTrim(pUrl.toLowerCase()) : null;
	pKey = (pKey != null) ? psTrim(pKey.toLowerCase()) : null;

	if(pUrl == null || pKey == null || pUrl.indexOf(pKey) == -1) return null;

	var start = pUrl.indexOf('&' + pKey + '=');
	start = (start == -1) ? pUrl.indexOf('?' + pKey + '=') : start;
	if(start >= 0)
	{
		start = start + pKey.length;
		var end = pUrl.indexOf("&", start);
		if(end == -1) end = pUrl.length;
		var middle = pUrl.indexOf("=", start);
		return pUrl.substring(middle + 1, end);
	}
	return null;
}

function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}

function psGetElementValue(pTagObj, pValueFlag)
{
    var tagValue = null;
    if(pTagObj != null)
    {
        if(pTagObj.tagName.search(/^INPUT$/i) > -1) tagValue = pTagObj.value;
        else if(pTagObj.tagName.search(/^SELECT$/i) > -1)
        {
            if(pValueFlag) tagValue = pTagObj.options[pTagObj.selectedIndex].value;
            else tagValue = psHtmlDecode(pTagObj.options[pTagObj.selectedIndex].innerHTML);// return label instead of value
        }
        else tagValue = psHtmlDecode(pTagObj.innerHTML);
    }

    return tagValue;
}

function psCheckEmail(pEmail)
{
    if(pEmail)
    {
        var i = pEmail.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
        return (i > -1);
    }

    return false;
}

function psHtmlDecode(pValue)
{
    if(pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
    }

    return pValue;
}

function psGetMainDomain(pUrl)
{
	var se = /^https*\:\/\/([^\/\:]+)/gi;
	var domain = (pUrl.search(se) > -1) ? RegExp.$1 : null;
	if(domain != null)
	{
		if(domain.indexOf("www") == 0)
		{
			domain = domain.substring(4, domain.length);
		}
		if(G_PS_ARR_DOMAIN != null)
		{
			for(var i = 0; i < G_PS_ARR_DOMAIN.length; i++)
			{
				se = new RegExp("[\.]" + G_PS_ARR_DOMAIN[i] + "$","gi");
				if(("." + domain).search(se) > -1)
				{
					domain = G_PS_ARR_DOMAIN[i];
					break;
				}
			}
		}
		domain = "." + domain;
	}
	return domain;
}

function psGetDomain(pUrl)
{
    var se = /^https*\:\/\/([^\/\:]+)/gi;
    return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}

function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if(!pCookieName || !cookies) return null;

	cookies = "; " + cookies.toLowerCase();
	var key = "; " + pCookieName.toLowerCase() + "=";
	var start = cookies.lastIndexOf(key);
	if(start >= 0)
	{
		start = start + key.length;
		var end = cookies.indexOf(";", start);
		if(end == -1) end = cookies.length;

		return unescape(cookies.substring(start, end));
	}

    return null;
}

function psCookieBase(pCookieName, pCookieValue, pLifeTime)
{
	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	CC(pCookieName, pDomain); //delete cookie by calling Coremetrics cookie function
	if(pLifeTime == "delete") return true;

	//set cookie by calling Coremetrics cookie function
	var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;

	return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

function encodeHtml(strValue)
{
	if (strValue!=null)
	{
		strValue = escape(strValue);
		strValue = strValue.replace(/\//g,"%2F");
		strValue = strValue.replace(/\?/g,"%3F");
		strValue = strValue.replace(/=/g,"%3D");
		strValue = strValue.replace(/&/g,"%26");
		strValue = strValue.replace(/@/g,"%40");
	}
	return strValue;
}

function psSetCookie(pCookieName, pCookieValue, pLifeTime)
{
	if(!pCookieName)
	{
		return false;
	}

	pCookieValue = (pCookieValue == null) ? "null" : pCookieValue;

	if(pLifeTime != "delete")
	{
		pCookieName = psTrim(pCookieName);
		var oldCookieValue = psGetCookie(pCookieName);
		oldCookieValue = (oldCookieValue == null) ? "null" : oldCookieValue;
		var totalSize;
		if(document.cookie.indexOf(pCookieName) > -1)
		{
			totalSize =  document.cookie.length + encodeHtml(pCookieValue).length - encodeHtml(oldCookieValue).length;
		}
		else totalSize =  document.cookie.length  + encodeHtml(pCookieValue).length + encodeHtml(pCookieName).length;
		if(totalSize > 3500) return false;
	}
	psCookieBase(pCookieName, pCookieValue, pLifeTime);
}

function psSetValueToCookie(pCookieName, pKey, pValue)
{
	if(!pCookieName || !pKey) return false;

	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;
	pValue = (pValue == null) ? "null" : pValue;
	var oldCatCookie = catCookie;

	var start = catCookie.indexOf(pKey);

	var totalsize;
	if(start >= 0) // Store before -> remove the old value
	{
		var oldValue = psGetValueFromCookie(pCookieName, pKey.replace(/[\~\#]/gi, ""));
		oldValue = (oldValue == null) ? "null" : oldValue;
		var end = catCookie.indexOf("#", start + pKey.length);
		if(end == -1) end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length - encodeHtml(oldValue).length;
	}
	else
	{
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length;
		if(document.cookie.indexOf(pCookieName) < 0) totalsize += encodeHtml(pCookieName).length;
	}
	catCookie = pKey + pValue + catCookie;
	var cookieArray = null;
	//Check existed ?
	while(totalsize > 3500)
	{
		var l1 = encodeHtml(catCookie).length;//length before pop
		cookieArray = catCookie.split("#");
		cookieArray.pop();
		catCookie = cookieArray.join("#");
		var l2 = encodeHtml(catCookie).length;//length after pop
		totalsize -=  (l1-l2);
	}
	if(catCookie == null || catCookie == "") catCookie = oldCatCookie;

	// Save to cookie
	psCookieBase(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if(catCookie != null)
    {
        var start = catCookie.indexOf(pKey);
		if(start >=0)
		{
			start = start + pKey.length;
			var end = catCookie.indexOf("#", start);
			if(end == -1) end = catCookie.length;
			return catCookie.substring(start, end);
		}
		return null;
    }
    return null;
}

function psGenerateRandomValue()
{
	var dtDate = new Date();
    return dtDate.getTime() % 10000000 + Math.floor(Math.random() * 10000);
}

function psShorttenPageID(pLink)
{
	var temp1 = pLink;
	if(temp1 != null) temp1 = (temp1.length > 255) ? temp1.substr(0, 255) : temp1;
	return temp1;
}

function psCheckArrayExist(pArrElement)
{
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0) return false;
    return true;
}

function psCheckElementExist(pElement)
{
    if(typeof(pElement) == "undefined" || pElement == null) return false;
    return true;
}

function psGetElementByName(tagName, elementName)
{
	// return the first element
	var tags = document.getElementsByTagName(tagName);
	if(psCheckArrayExist(tags))
    {
		for(var i = 0; i < tags.length; i++)
        {
			if(tags[i].name != null && tags[i].name.toLowerCase() == elementName.toLowerCase())
            {
				return tags[i];
			}
		}
	}
	return null;
}

function psGetElementsByClassName(psDocument, psElementTagName, psClassName)
{
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null) return null;
    for(var i = 0; i < arrInputs.length; i++)
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult)
{
	pId = psCleanPageId(pId);
	pId = psShorttenPageID(pId);
	pCatId = psCleanCatId(pCatId);
    if(pSrchResult != null) pSrchResult += "";
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId, pAttributes)
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreateProductviewTag(" + pId + ", " + pName + ", " + pCatId  + ", " + pAttributes + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreateProductviewTag(pId, pName, pCatId, pAttributes);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId)
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreateShopAction5Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCatId + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId);
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId)
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
	pOrderTotal = psCleanPrice(pOrderTotal);
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreateShopAction9Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCusID + ", " + pOrderID + ", " + pOrderTotal + ", " + pCatId + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId);
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip)
{
	pOrderTotal = psCleanPrice(pOrderTotal);
	pOrderShipping = psCleanPrice(pOrderShipping);
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreateOrderTag(" + pId + ", " + pOrderTotal + ", " + pOrderShipping + ", " + pCusID + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip);
}

function psCreateConversionEventTag(pId, pActionType, pCatID, pPoints)
{
	pCatID = psCleanCatId(pCatID);
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreateConversionEventTag(" + pId + ", " + pActionType + ", " + pCatID + ", " + pPoints + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreateConversionEventTag(pId, pActionType, pCatID, pPoints);
}

function psCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe)
{
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pNewsletter + ", " + pSubscribe + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe);
}

function psCreateErrorTag(pPageID, pCatId)
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmCreateErrorTag(" + pPageID + ", " + pCatId + ")");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmCreateErrorTag(pPageID, pCatId);
}

function psDisplayShop5s()
{
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmDisplayShop5s()");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmDisplayShop5s();
}

function psDisplayShop9s()
{
    if(G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3) alert("cmDisplayShop9s()");
    if(G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3) cmDisplayShop9s();
}
/*===========================END GENERAL UTILITY FUNCTION ==================*/
