/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.4, 12/19/2008
 * 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;

// current page url
var G_PS_URL_PATH = "" + document.location;
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_FLAG_LOGIN = "PS_FLAG_LOGIN";		// used as a "session" variable to handle events between pages
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
/*========================= END GLOBAL VARIABLES =============================*/


/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
/*
 * Page view for navigating through top menu.
*/
if(psIsHomePageView())
{
	psCreatePageviewTag("Cutter and Buck Men's and Women's clothing", "Home", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("cutterbuck.igreentree.com/css_external/csspage_welcome.asp") > -1)
{
	psCreatePageviewTag("Cutter and Buck Employment Center", "Careers", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("surveymonkey.com") > -1)
{
	psCreatePageviewTag("Tell us what you think", "Surveymonkey", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/mens_apparel/cid=9/shop.axd/menscategory") > -1
	|| G_PS_URL_PATH.toLowerCase().indexOf("/womens_apparel/cid=19/shop.axd/womenscategory") > -1
	|| G_PS_URL_PATH.toLowerCase().indexOf("/sportswear/cid=28/shop.axd/collections") > -1
	|| G_PS_URL_PATH.toLowerCase().indexOf("/gift_ideas_sportswear/cid=53/shop.axd/great_gifts") > -1)
{
	var pLst = G_PS_URL_PATH.split("/");
	psCreatePageviewTag(pLst[pLst.length-1], psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
/*
 * Exceptions for top menu.
*/
else if(G_PS_URL_PATH.toLowerCase().search(/\/accessories\/cid=\d+(\/page_no=\d+)*\/shop\.axd\/category/gi) > -1)
{
	//var pPageNo = psGetValueFromUrl(G_PS_URL_PATH.toLowerCase(),"page_no");
	//pPageNo = pPageNo != null? pPageNo:1;
	//psCreatePageviewTag("Accessories " + " Page " + pPageNo, psGetValueFromUrl(G_PS_URL_PATH, "cid"), null, null);
	psCreatePageviewTag("Accessories", psGetValueFromUrl(G_PS_URL_PATH, "cid"), null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/teamshop/shop.axd/teamshop_home") > -1)
{
	psCreatePageviewTag("Teamshop_home", "Teamshop", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/sale_clearance/cid=54/shop.axd/category") > -1)
{
	psCreatePageviewTag("Sale", psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
/*
 * Exceptions to content pages for assigning categoryid. 
*/
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/affiliates.aspx") > -1
		|| G_PS_URL_PATH.toLowerCase().indexOf("/help/privacy.aspx") > -1
		|| G_PS_URL_PATH.toLowerCase().indexOf("/help/shipping.aspx") > -1
		|| G_PS_URL_PATH.toLowerCase().indexOf("/help/corporate.aspx") > -1
		|| G_PS_URL_PATH.toLowerCase().indexOf("/help/international.aspx") > -1
		|| G_PS_URL_PATH.toLowerCase().indexOf("/help/investors.aspx") > -1)
{
 	psCreatePageviewTag(psGetPageIdNonePageNo(), psGetFileNameAsCatId(), null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("secure.cutterbuck.com/catalogrequest.aspx") > -1)
{
 	psCreatePageviewTag("Request a Cutter and Buck Direct Catalog", "Catalog", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/browsecatalog.aspx") > -1)
{
 	psCreatePageviewTag("Browse Our Latest Catalog", "Catalog", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/cutter_buck_emails/shop.axd/subscribe") > -1)
{
 	psCreatePageviewTag("Receive Cutter and Buck Emails", "Newsletter", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/contact_cutter_and_buck/shop.axd/contactus") > -1)
{
 	psCreatePageviewTag("Contact Cutter and Buck", "Contact Us", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/sizinginfo.aspx") > -1
		|| G_PS_URL_PATH.toLowerCase().indexOf("/size_chart.aspx") > -1)
{
 	psCreatePageviewTag("Cutter and Buck Size Charts", "Sizes", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/storelocator.aspx") > -1)
{
 	psCreatePageviewTag("Store Locator", "Store Locator", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/aboutus.aspx") > -1)
{
 	psCreatePageviewTag("About Cutter and Buck Direct", "About Us", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/aboutheritage.aspx") > -1)
{
 	psCreatePageviewTag("Cutter and Buck Direct Golf Heritage", "Golf", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/abouttour.aspx") > -1)
{
 	psCreatePageviewTag("Cutter and Buck Direct on Tour", "On Tour", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/aboutannika.aspx") > -1)
{
 	psCreatePageviewTag("Annika", "About Annika", null, null);
}	
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/aboutpartners.aspx") > -1)
{
 	psCreatePageviewTag("Premier Partners", "Partners", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/aboutadvertising.aspx") > -1)
{
 	psCreatePageviewTag("Recent Advertising", "Advertising", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/abouthistory.aspx") > -1)
{
 	psCreatePageviewTag("Our History", "History", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/aboutpress.aspx") > -1)
{
 	psCreatePageviewTag("Press Room", "Press", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/help/aboutfaq.aspx") > -1)
{
 	psCreatePageviewTag("Frequently Asked Questions", "FAQ", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/zoom/zoom2.jsp") > -1)
{
	var pPageId = psGetValueFromUrl(G_PS_URL_PATH.toLowerCase(),"zf") != null?psGetValueFromUrl(G_PS_URL_PATH.toLowerCase(),"zf"):"Closer view";
	var pLst = pPageId.split("_");
	if(pLst)
		pPageId = pLst.length >0?pLst[0]:pPageId;
 	psCreatePageviewTag("Zoom:" + pPageId, "Closer view", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/tell_a_friend.aspx") > -1)
{
	psCreatePageviewTag("Tell a Friend", "Home", null, null);
}

/*
 * Exceptions to content pages for assigning pageID. 
*/
else if(G_PS_URL_PATH.toLowerCase().search(/\/annika_collection\/cid=\d+\/mro=\d+\/shop\.axd\/annika/gi) > -1)
{
	psCreatePageviewTag("Annika Collection", psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
else if(G_PS_URL_PATH.toLowerCase().search(/\/sportswear_protec\/cid=\d+\/shop\.axd\/protec/gi) > -1)
{
	psCreatePageviewTag("CB ProTec Collection", psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
else if(G_PS_URL_PATH.toLowerCase().search(/\/signature_collection\/cid=\d+\/mro=\d+\/shop\.axd\/signature/gi) > -1)
{
	psCreatePageviewTag("Signature collection", psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
else if(G_PS_URL_PATH.toLowerCase().search(/\/cid=\d+\/shop\.axd\/crystalgifts/gi) > -1)
{
	psCreatePageviewTag("Crystal Gifts", psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
else if(G_PS_URL_PATH.toLowerCase().search(/\/cbuk_apparel\/cid=\d+\/shop\.axd\/cbukcategory/gi) > -1)
{
	psCreatePageviewTag("CBUK", psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
else if(G_PS_URL_PATH.toLowerCase().search(/\/big_and_tall\/cid=\d+\/shop\.axd\/bigandtall/gi) > -1)
{
	psCreatePageviewTag("Big and tall", psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
/*
 * Page view for navigating through left menu.
*/
else if(psIsLMPages())
{
	psCreatePageviewTag(psGetPageIdForLM(), psGetValueFromUrl(G_PS_URL_PATH,"cid"), null, null);
}
/* 
 *The page is the product detail page
*/
else if(psIsProductView())
{
	psPostProductView();
}
else if(psIsSearchView(G_PS_URL_PATH))
{
	psPostSearchView();
}
/*
 * customer login.
*/
else if(G_PS_URL_PATH.toLowerCase().indexOf("/shop.axd/myaccount_login") > -1)
{
	psCreatePageviewTag(psGetPageIdNonePageNo(), "My Account",null, null);
	psHijackCustomerSignIn();
}
/*
 * neu customer login.
*/
else if(G_PS_URL_PATH.toLowerCase().indexOf("/shop.axd/myaccount_new") > -1)
{
	psCreatePageviewTag(psGetPageIdNonePageNo(), "My Account",null, null);
	psHijackNewCustomerSignIn();
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/order_history/shop.axd/myaccount_history") > -1)
{
	psCreatePageviewTag(psGetPageIdNonePageNo(), "Order History",null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/shop.axd/myaccount_orderdetail") > -1)
{
	var pPageId = psGetPageIdNonePageNo();
	psCreatePageviewTag(pPageId.replace("#",""), "Order History",null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/shop.axd/myaccount_home") > -1)
{
	psSignInSuccess();
	psCreatePageviewTag(psGetPageIdNonePageNo(), "My Account",null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/shop.axd/checkout_createpw") > -1)
{
	psCreatePageviewTag("Create Account Password", "My Account",null, null);
}

else if(G_PS_URL_PATH.toLowerCase().indexOf("shop.axd/myaccount_email") > -1)
{
	psCreatePageviewTag(psGetPageIdNonePageNo(), "My Account",null, null);
	if(document.getElementsByTagName("body")[0].innerHTML.toLowerCase().indexOf("your email has been updated") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
		{
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_FLAG_LOGIN, '', "delete"); // turn off flag
		}
	}
	psHijackUpdateEmail();
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/my_account/shop.axd/myaccount_pw") > -1)
{
	psCreatePageviewTag(psGetPageIdNonePageNo(), "My Account",null, null);
}

else if(psIsCartView(G_PS_URL_PATH))
{
	psPostCartView();
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/request=checkout/shop.axd/login") > -1)
{
	psCreatePageviewTag("Checkout Login", "Checkout", null, null);
	psHijackNewCustomerCheckout();
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/shop.axd/checkout_billing") > -1)
{
	psCreatePageviewTag("Payment Info", "Checkout", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/shop.axd/checkout_shipmethod") > -1)
{
	psCreatePageviewTag("Shipping Info", "Checkout", null, null);
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/cutter_and_buck/shop.axd/checkout_recap") > -1)
{
	// Is thank you page.
	if(document.getElementsByTagName("body")[0].innerHTML.toLowerCase().indexOf("your order number is") > -1)
	{
		psPostOrderView();
		psPostPaymentRegistration();
	}
	else
	{
		psCreatePageviewTag("Order Confirmation", "Checkout", null, null);
		psPostPaymentRegistration();
	}
}
else if(psIsExceptionContentPage())
{
	psCreatePageviewTag(psGetPageIdNonePageNo(),psGetValueFromUrl(G_PS_URL_PATH,"cid"),null,null );
}
else if(psGetPageIdNonePageNo() && psGetValueFromUrl(G_PS_URL_PATH,"cid") == null)
{
	psCreatePageviewTag(psGetPageIdNonePageNo(),psGetFileNameAsCatId(),null,null );
}
else if(G_PS_URL_PATH.toLowerCase().indexOf("/ucm/ucmcontroller") < 0 ) 
{	
	
	psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
}
/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView(pPath)
{
	if (pPath.toLowerCase().indexOf("/cart_display.aspx") > -1
		|| pPath.toLowerCase().indexOf("/cutter_and_buck/shop.axd/cart_display") > -1
		|| document.title.toLowerCase().indexOf("your cutter & buck shopping cart") > -1)
		return true;
	return false;
}
/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	return G_PS_URL_PATH.toLowerCase().search(/\/shop\.axd\/productdetails/gi) > -1?true:false;
}
/*
 * Determine if the page is the search result page
 */
function psIsSearchView(pPath)
{
	return pPath.toLowerCase().indexOf("search.cutterbuck.com") > -1?true:false;
}
function psIsExceptionContentPage()
{
	if(psGetPageIdNonePageNo() && psGetValueFromUrl(G_PS_URL_PATH,"cid"))
		return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsHomePageView()
{
	if(G_PS_URL_PATH.toLowerCase().indexOf("search.cutterbuck.com") < 0)
	{
		if(G_PS_PATHNAME == "/shop.axd" || G_PS_PATHNAME == "/")
			return true;
	}
	return false;
}


/*
 * Check is left menu page. 
 * Return true if the page has url format "/cid=.../shop.axd/".
 * Else return false.
*/
function psIsLMPages()
{
	var pResult = false;
	if(G_PS_URL_PATH.toLowerCase().search(/\/cid=\d+(\/page_no=\d+)*\/shop\.axd\/([^$]+)/gi) > -1)
	{
		if(RegExp.$2 != "productdetails")
			pResult = true;
	}
	return pResult;
}
/*
 * Get pageId for Left menu pages.
*/
function psGetPageIdForLM()
{
	var pHeader = psGetElementsByClassName(document,"h1","headertext");
	if(pHeader)
		var pPageId = pHeader.length > 0 ? psHtmlDecode(pHeader[0].innerHTML).replace(/&+/gi, "and"):null;
	var pPageNo = psGetValueFromUrl(G_PS_URL_PATH,"page_no");
	pPageNo = pPageNo == null? 1: pPageNo;
	return "Catalog: " + psTrim(psCleanHtmlTag(pPageId)) + " Page " + pPageNo;
}
/*
 * Get pageId for Left menu pages.
*/
function psGetPageIdNonePageNo()
{
	var pHeader = psGetElementsByClassName(document,"h1","headertext");
	if(pHeader)
		var pPageId = pHeader.length > 0 ? psHtmlDecode(pHeader[0].innerHTML).replace(/&+/gi, "and"):null;
	return psTrim(psCleanHtmlTag(pPageId));
}

/* 
 * Find element by name
 */
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)
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}
/* 
 * Get file name of url as catid
*/
function psGetFileNameAsCatId()
{
	return G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf("."));
}
/*
 * Get productId from meta name is "PRODUCT_SKU"
*/
function psGetProductId()
{
	var pProId = null;
	if(document.getElementsByName("PRODUCT_SKU").length > 0)
		pProId = document.getElementsByName("PRODUCT_SKU")[0].content;
	return pProId;
}
/*
 * Get productId from the url pathname.
*/
function psGetProductIdFromUrl(pPath)
{
	var pItem_No = psGetValueFromUrl(pPath,"item_no");
	if(pItem_No)
	{
		var pLst = pItem_No.split("+");
		if(pLst.length == 3)
		{
			pItem_No = pItem_No.toLowerCase().indexOf("membership") > -1? pItem_No:pLst[0];
		}
	}
	return pItem_No.replace(/[\+]+/gi, " ");
}
/*
 * Get productId from the string in shop9.
*/

function psGetProductIdForShop9(pItem_No)
{
	var pLst = pItem_No.split(" ");
		if(pLst.length == 3)
			pItem_No = pLst[0];
	return pItem_No;
}
/*
 * Hijack "Add to cart" button.
*/
function psHijackAddToCart()
{
	var pAddCart = document.getElementsByName("AddToCart");
	if(pAddCart.length > 0)
	{
		pAddCart[0].oldCMFunc = pAddCart[0].onclick; //backup the existing onclick function
		pAddCart[0].onclick = function()
		{
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID,psGetProductIdFromUrl(G_PS_URL_PATH),psGetCookie(G_PS_COOKIE_CATID));
			if (this.oldCMFunc != null)
			return this.oldCMFunc();
		}
	}
}

/* 
 * Hijack "sign in" button when customer login.
 */
function psHijackCustomerSignIn()
{
	var pInputs = document.getElementsByName("imageField");
	for (var i = 0; i < pInputs.length; i++)	
    {
        if (pInputs[i].getAttribute("src") && pInputs[i].getAttribute("src").toLowerCase().search(/images\/btn\_signin\.gif/gi) > -1)
        {
			pInputs[i].oldCMFunc = pInputs[i].onclick; //backup the existing onclick function
			pInputs[i].onclick = function()
			{
				var uP = new psProfile();
				uP.email = psTrim(document.getElementsByName("email")[0].value);
				uP.city = null;
				uP.state = null;
				uP.zipcode = null
				uP.writeProfile();
				// store on cookie
				psSetCookie(G_PS_FLAG_LOGIN, "signed in");
				if (this.oldCMFunc != null)
					return this.oldCMFunc();
			}
		}
	}
}
/* 
 * Hijack "sign in" button when new customer login.
 */
function psHijackNewCustomerSignIn()
{
	var pInputs = document.getElementsByTagName("input");
	for (var i = 0; i < pInputs.length; i++)	
    {
        if (pInputs[i].getAttribute("src") && pInputs[i].getAttribute("src").toLowerCase().search(/images\/submit\.gif/gi) > -1)
        {
			pInputs[i].oldCMFunc = pInputs[i].onclick; //backup the existing onclick function
			pInputs[i].onclick = function()
			{
				var uP = new psProfile();
				uP.email = psTrim(document.getElementsByName("email")[0].value);
				uP.city = psTrim(document.getElementsByName("city")[0].value);
				var pState = document.getElementsByName("state")[0];
				uP.state = pState.options[pState.selectedIndex].value; 
				uP.zipcode = psTrim(document.getElementsByName("zip_code")[0].value);
				uP.writeProfile();
				// store on cookie
				psSetCookie(G_PS_FLAG_LOGIN, "signed in");
				if (this.oldCMFunc != null)
					return this.oldCMFunc();
			}
		}
	}    
}
function psHijackNewCustomerCheckout()
{
	var pInputs = document.getElementsByTagName("input");
	for (var i = 0; i < pInputs.length; i++)	
    {
        if (pInputs[i].getAttribute("src") && pInputs[i].getAttribute("src").toLowerCase().search(/images\/btn\_nextpage\.gif/gi) > -1)
        {
			pInputs[i].oldCMFunc = pInputs[i].onclick; //backup the existing onclick function
			pInputs[i].onclick = function()
			{
				var uP = new psProfile();
				uP.email = psTrim(document.getElementsByName("email")[0].value);
				uP.city = psTrim(document.getElementsByName("city")[0].value);
				var pState = document.getElementsByName("state")[0];
				uP.state = pState.options[pState.selectedIndex].value; 
				uP.zipcode = psTrim(document.getElementsByName("zip_code")[0].value);
				uP.writeProfile();
				// store on cookie
				psSetCookie(G_PS_FLAG_LOGIN, "signed checkout");
				if (this.oldCMFunc != null)
					return this.oldCMFunc();
			}
		}
	}    
}


/* 
 * Hijack "sign in" button when customer update email.
 */
function psHijackUpdateEmail()
{
	var pInputs = document.getElementsByTagName("input");
	for (var i = 0; i < pInputs.length; i++)	
    {
        if (pInputs[i].getAttribute("src") && pInputs[i].getAttribute("src").toLowerCase().search(/assets\/submit\.gif/gi) > -1)
        {
			pInputs[i].oldCMFunc = pInputs[i].onclick; //backup the existing onclick function
			pInputs[i].onclick = function()
			{
				var uP = new psProfile();
				uP.email = psTrim(document.getElementsByName("email")[0].value);
				uP.city = null;
				uP.state = null;
				uP.zipcode = null
				uP.writeProfile();
				// store on cookie
				psSetCookie(G_PS_FLAG_LOGIN, "updated");
				if (this.oldCMFunc != null)
					return this.oldCMFunc();
			}
		}
	}
}
/*
 * Check user sign in successful
 * post registration tag if user login successful.
*/
function psSignInSuccess()
{
	if(document.getElementsByTagName("body")[0].innerHTML.toLowerCase().indexOf("(sign out)") > -1 )
	{
		if(psGetCookie(G_PS_FLAG_LOGIN) && psGetCookie(G_PS_FLAG_LOGIN)== "signed in")
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			// post registration tag for update profile page
			if(uP.email != null)
			{
				psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
				psSetCookie(G_PS_FLAG_LOGIN, '', "delete"); // turn off flag
			}
		}
	}
}

/* 
 * Post registration tag again when user changed billing address.
*/
function psPostPaymentRegistration()
{
	var uP = new psProfile();
	if(psGetCookie(G_PS_FLAG_LOGIN))
	{
		if(psGetCookie(G_PS_FLAG_LOGIN)== "signed checkout")
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			// post registration tag for update profile page
			if(uP.email != null)
			{
				psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
				psSetCookie(G_PS_FLAG_LOGIN, '', "delete"); // turn off flag
			}
		}
	}
	else
	{
		var pTdTag = psGetElementsByClassName(document,"td","co_box");
		if(pTdTag && pTdTag.length > 0)
		{
			var pTable = pTdTag[0].getElementsByTagName("table")[0];
		}
		if(pTable)
		{
			var pAddress = pTable.rows[0].cells[0].innerHTML;
			var lstBr = pAddress.toLowerCase().split("<br");
			uP.email = psTrim(lstBr[lstBr.length-1]).replace(">","");
			pAddress = psTrim(lstBr[lstBr.length-3]);
			uP.city = pAddress.search(/>(.*)\,(\D*)(\d*)/gi) > -1 ? psTrim(RegExp.$1) : null;
			uP.city = psCleanHtmlTag(uP.city);
			uP.state = pAddress.search(/>(.*)\,(\D*)(\d*)/gi) > -1 ? psTrim(RegExp.$2) : null;
			uP.state = psCleanHtmlTag(uP.state);
			uP.zipcode = pAddress.search(/>(.*)\,(\D*)(\d*)/gi) > -1 ? psTrim(RegExp.$3) : null;
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			// store on cookie
			uP.writeProfile();
		}
	
	}
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	G_PS_CUR_CATID = "SEARCH";
	var searchTerm = psGetSearchTerm();
	var searchResult = 0;
	var pPageNo = psGetValueFromUrl(G_PS_URL_PATH,"page");
	pPageNo = pPageNo == null? 1: pPageNo;
	var pTd = psGetElementsByClassName(document,"td", "content");
	if(pTd && pTd.length > 0)
	{
		if(pTd[0].parentNode.parentNode.parentNode.innerHTML.toLowerCase().indexOf("unfortunately, no items were found with the keyword") > -1)
		{
			psSetCookie(G_PS_COOKIE_CATID,"UNSUCCESSFUL");
			psCreatePageviewTag("SEARCH UNSUCCESSFUL",G_PS_CUR_CATID,searchTerm,searchResult);
		}
		else
		{
			searchResult = psGetSearchResult();
			psCreatePageviewTag("SEARCH SUCCESSFUL " + "PAGE " + pPageNo, G_PS_CUR_CATID, searchTerm, searchResult);
		}
	}
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	if(psGetValueFromUrl(G_PS_URL_PATH,"u4"))
	{
		term = psGetValueFromUrl(G_PS_URL_PATH,psGetValueFromUrl(G_PS_URL_PATH,"u4"));
		term = term.replace(/[+]/gi, " ");
		psSetCookie(G_PS_COOKIE_CATID,term);
	}
	else if(psGetValueFromUrl(G_PS_URL_PATH,"u3"))
	{
		term = psGetValueFromUrl(G_PS_URL_PATH,psGetValueFromUrl(G_PS_URL_PATH,"u3"));
		term = term.replace(/[+]/gi, " ");
		psSetCookie(G_PS_COOKIE_CATID,term);
	}
	else if(psGetValueFromUrl(G_PS_URL_PATH,"u2"))
	{
		term = psGetValueFromUrl(G_PS_URL_PATH,psGetValueFromUrl(G_PS_URL_PATH,"u2"));
		term = term.replace(/[+]/gi, " ");
		psSetCookie(G_PS_COOKIE_CATID,term);
	}
	else
	{
		term = psGetValueFromUrl(G_PS_URL_PATH,"q");
		psSetCookie(G_PS_COOKIE_CATID,"SEARCH");
	}
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	var pTd = psGetElementsByClassName(document,"td", "content")[0];
	var pTable = pTd.getElementsByTagName("table")[0];
	var pTemp = psTrim(pTable.rows[0].cells[0].innerHTML);
	pTemp = pTemp.replace(/[,]/gi, "");
	result = pTemp.search(/Results[^of]+\sof\s(\d*)/gi) > -1? RegExp.$1 : null;
	return result;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()) // Get product info successfully?
	{
		psSetCookie(G_PS_COOKIE_CATID,prd.catId);
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
	}
}
/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Throw page view tag
	psCreatePageviewTag("SHOPPING CART", "CART", null, null);
	var cartTbl = null;
	var pTd = psGetElementsByClassName(document, "td", "content");
	if(pTd  && pTd.length > 0)
	{
		cartTbl = pTd[0].getElementsByTagName("table").length > 0?pTd[0].getElementsByTagName("table")[0]:null;
	}
	if (cartTbl == null)
		return;
	
	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		/*
		 * Codes for skipping exceptional rows (rows that don't contain items)
		 */
		
		if (rows[r].innerHTML.search(/Item:/gi)<0) // Skip rows not containing item (identified by the term "Item:")
		 	 continue;
		if (prd.getItem5(rows[r])) // Get shop5 item successfully?
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
	}
	// Make sure to have actual postings
	psDisplayShop5s();
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	// Throw page view tag
	G_PS_CUR_CATID = "Checkout";
	psCreatePageviewTag("Order Thank You", G_PS_CUR_CATID, null);

	var cartTbl = null;
	var pTemp = psGetElementsByClassName(document.getElementById("tdContent"),"td","co_box");
	
	if(pTemp && pTemp.length > 3)
	{
		cartTbl = pTemp[3].getElementsByTagName("table")[0];
	}
	
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var ord = new psOrder();
	var prd = new psProduct();

	if (ord.getOrder()) // Get order info from source code successfully?
	{
		// Post Pageviewtag as cartview
		for (var r = 1; r < rows.length; r++) // item for each row
		{
			/*
			 * Codes for skipping exceptional rows (rows don't contain items)
			 */
			if (rows[r].innerHTML.indexOf("colspan") > -1) // Skip rows not containining the item
			{
				
				continue;
			}
			if (prd.getItem9(rows[r])) // Get shop9 item successfully?
			{
				psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, ord.cusId, ord.id, ord.subtotal, prd.catId);
			}
		}
		
		// Make sure to have actual postings
		psDisplayShop9s();
		// Post order tag finally
		psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, ord.cusId, ord.city, ord.state, ord.zipCode);
		// Delete cookie after checking successfully
		psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.id = psGetProductIdFromUrl(G_PS_URL_PATH);
			this.name = psGetPageIdNonePageNo();
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
			if(psIsSearchView(G_PS_URL_REFERRER))
			{
				var pTemp = psGetCookie(G_PS_COOKIE_CATID);
				if(psGetCookie(G_PS_COOKIE_CATID) != null && psGetCookie(G_PS_COOKIE_CATID) != "unsuccessful")
				{
					this.catId = psGetCookie(G_PS_COOKIE_CATID);
				}
				else 
				{
					this.catId = psGetValueFromUrl(G_PS_URL_PATH, "cid");
				}
			}
			else if(psIsCartView(G_PS_URL_REFERRER) || G_PS_URL_REFERRER.indexOf("cart_add.aspx") > -1)
			{
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
			}
			else if(G_PS_URL_REFERRER == "" || G_PS_URL_REFERRER == null)
			{
				this.catId = psGetValueFromUrl(G_PS_URL_PATH, "cid") != null?psGetValueFromUrl(G_PS_URL_PATH, "cid"):"BOOKMARTS";
			}
			else 
			{
				this.catId = psGetValueFromUrl(G_PS_URL_PATH, "cid");
			}
			if(this.catId == "")
			{
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
			}
			this.catId = this.catId != null?this.catId: "HOME";
			 // Store productId along with catId to cookie for use later in shop5 and shop9 views
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the shopping cart
	 */
	this.getItem5 = function(itemRow)
	{
		try
		{
			 var pLink = itemRow.cells[1].getElementsByTagName("a")[0];
			 this.id = psGetProductIdFromUrl(pLink.href);
			  var pName = psTrim(psHtmlDecode(psCleanHtmlTag(pLink.innerHTML)));
			 this.name = pName.toLowerCase().indexOf("discount membership") > -1 ? pName: null;
			 this.price = psTrim(psCleanHtmlTag(itemRow.cells[2].innerHTML));
			 this.price = psCleanPrice(this.price);
			 if(itemRow.cells[3].getElementsByTagName("input").length > 0)
				this.quantity = itemRow.cells[3].getElementsByTagName("input")[0].value;
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			 this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			 if(this.catId == null)
			 {
				this.catId = psGetValueFromUrl(pLink.href,"cid") != null?psGetValueFromUrl(pLink.href,"cid"):"Home"
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
			 }
			 return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the receipt page
	 */
	this.getItem9 = function(itemRow)
	{
		try
		{
			// get product Id
			var pProText = psTrim(psCleanHtmlTag(itemRow.cells[1].innerHTML));
			this.id = psGetProductIdForShop9(pProText);
			this.name = null;
			// get quantity
			this.quantity = psTrim(psCleanHtmlTag(itemRow.cells[0].innerHTML));
			// get price
			this.price = psTrim(psCleanHtmlTag(itemRow.cells[3].innerHTML));
			this.price = psCleanPrice(this.price);
			// get catId from cookie
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id) != null?psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id):"HOME";
			return true;
		}
		catch (ex) { return false; }
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.email = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.email != null)
			{
				var buf = this.email.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				this.email = buf[0];
				this.city = buf[1];
				this.state = buf[2];
				this.zipcode = buf[3];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		if (this.email == null)
		{
			return;
		}
		// make sure that the data contains 4 parts separated by 3 '|'
		var data = this.email + '|' + this.city + '|' + this.state + '|' + this.zipcode;
		// store on cookie
		psSetCookie(G_PS_COOKIE_PROFILE, data);
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder(pOrderId, pSubtotal, pShipping, pCusId, pCity, pState, pZipCode)
{
	this.id = pOrderId;
	this.subtotal = pSubtotal;
	this.shipping = pShipping;
	this.cusId = pCusId;
	this.city = pCity;
	this.state = pState;
	this.zipCode = pZipCode;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{				
			var pBody = psCleanHtmlTag(document.body.innerHTML).toLowerCase();
			this.id = pBody.search(/your order number is\s+([^.]+)/gi) > -1? RegExp.$1 : null;
			this.subtotal = psGetElementValueById("csCCPT");
			this.subtotal = psCleanPrice(this.subtotal);
			this.shipping = document.body.innerHTML.toLowerCase().split("shipping:")[1];
			var start = this.shipping.indexOf("$")+1;
			var end = this.shipping.indexOf("<", start);
			this.shipping = psTrim(this.shipping.substring(start, end));
			this.shipping = psCleanPrice(this.shipping);
			var pTdTag = psGetElementsByClassName(document,"td","co_box");
			if(pTdTag && pTdTag.length > 2)
			{
				var pAddress = pTdTag[2].innerHTML;
				var lstBr = pAddress.toLowerCase().split("<br");
				this.cusId = psTrim(lstBr[lstBr.length-2]).replace(">","");
				pAddress = psTrim(lstBr[lstBr.length-4]);
				this.city = pAddress.search(/>(.*)\,(\D*)(\d*)/gi) > -1 ? psTrim(RegExp.$1) : null;
				this.city = psCleanHtmlTag(this.city);
				this.state = pAddress.search(/>(.*)\,(\D*)(\d*)/gi) > -1 ? psTrim(RegExp.$2) : null;
				this.state = psCleanHtmlTag(this.state);
				this.zipCode = pAddress.search(/>(.*)\,(\D*)(\d*)/gi) > -1 ? psTrim(RegExp.$3) : null;
			}
			return true;
		}
		catch (ex) {return false;}
	}
}
/* PURPOSE: Remove all HTML tags in a string
 * RETURN: string
 */
function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : null;
}
/* PURPOSE: Get inner text of an object or clean remove html tags of a particular string
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb)
{
	if (pTagOjb != null)
	{
		if (typeof(pTagOjb) == "object")
			return pTagOjb.innerHTML.replace(/\<+.+?\>+/g, "");
		else
			return pTagOjb.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all unaccepted characters in categoryid, including
 * [, ', ", :, comma,]
 * RETURN: string
 */
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)
{
	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"]/gi, "") : null; 
}

/* PURPOSE: Remove all leading & trailing spaces of a string
 * Note: [&nbsp;] is also considered as a space
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;
	return (pStr) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}
/* PURPOSE: extract value from the URL
 * in format of http://xxx.com/page.ext?key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
 /*
 * This function have been modified for this site:"/cid=9/" 
 * http://www.cutterbuck.com/mens_apparel/cid=9/shop.axd/menscategory
 */
function psGetValueFromUrl(pUrl, pKey)
{
    var re = new RegExp("[?&\/]" + pKey + "=([^&$\/]*)", "i");
    if (pUrl.search(re) == -1)
		return null;
    return unescape(RegExp.$1);
}

/* PURPOSE: returns the value of an element based on element_id
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 */
function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}

/* PURPOSE: returns the value of an element based on element object
 * Note: this function returns decoded text
 * to avoid "double" decode, don't invoke psHtmlDecode on returned value again
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 *  NULL: if element not exist
 */
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 == true)
                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;
}

/* PURPOSE: validate email format
 * RETURN: boolean
 */
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;
}

/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
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;
}

/* PURPOSE: extract domain part in the URL
 * RETURN: domain
 */
function psGetDomain(pUrl){
    var se = /^https*\:\/\/([^\/]+)/gi;
    return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}
/* PURPOSE: remove unnecessary characters (dollar sign, comma, quote, minus, etc) 
 * from price to make it work properly with parseFloat/parseInt
 * RETURN: well-formed price
 */
function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

/* PURPOSE: retrieve cookie value
 * RETURN: string
 */
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;
}

/* PURPOSE: set cookie value
 * Note: if the designated cookie is too big, the old items will be removed
 * because cookie size is limited to 4K
 * @pLifeTime in seconds
 * pDomain: don't specify if using current domain
 * RETURN: boolean
 */
function psSetCookie(pCookieName, pCookieValue, pLifeTime, pDomain)
{
    if (!pCookieName)
		return false;
	pDomain = ".cutterbuck.com";
	if(pLifeTime == "delete") 
    {         
        CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
        return true;
    }
    // set cookie by calling coremetrics's cookie function
    var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
    
    return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

/* PURPOSE: set value in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 * NOTE: Use null or '' for pValue to remove the pair specified by pKey
 */
function psSetValueToCookie(pCookieName, pKey, pValue)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// 
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;

	var start = catCookie.indexOf(pKey);
	if (start >= 0) // Store before -> remove the old value
	{
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1)
			end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
	}
	
	// remove the last items (eldest items) until cookie size < 3500	
	if (pValue != null && pValue != '')
	{
		catCookie = pKey + pValue + catCookie;
		var cookieArray = null;
		while (catCookie.length > 3500)
		{
			cookieArray = catCookie.split("#");
			cookieArray.pop();
			catCookie = cookieArray.join("#");
		}
	}
	// Save to cookie
	psSetCookie(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

/* PURPOSE: get value stored in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 */
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;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(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) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + pId + ", " + pName + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(pId, pName, pCatId);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    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);
    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) 
{
    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 ==================*/