/************************************************************************************/
/* $Revision: 1.1.2.8 $
 * $Id: cmtaggingservices.js,v 1.1.2.8 2010/08/16 04:35:55 chaib Exp $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.3, 2009/03/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 = ["fragrancedirect.test.venda.com","fragrancedirect.co.uk","fragrancedirect.live.venda.com"];//value must be one array of domains or null

// 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_PAGEID = "PS_PAGEID";
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";		// 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!

if(psGetDomain(G_PS_URL_PATH) != null)
{
var INTERVAL_ID = new Array();
var INTERVAL_ID_SearchByImage = new Array();
psClearInterval(INTERVAL_ID);
psHijackMyShoppingBag();
psClearRegistration();
psHijackLogout();
if(psGetDomain(G_PS_URL_PATH)!=null && psGetDomain(G_PS_URL_PATH).indexOf("blog")>-1)
{
	var pageId = psGetPageName();
	var catId = "Blog";
	psCreatePageviewTag(pageId,catId,null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if( G_PS_PATHNAME.toLowerCase() == "/"
	|| G_PS_PATHNAME.toLowerCase() == "/page/home"
	|| psHtmlDecode(G_PS_PATHNAME.toLowerCase()) == "/page/home&log=4")
{
	psCreatePageviewTag("home","home",null,null);
	INTERVAL_ID.push(window.setInterval("psHijackSpecialProduct()", 5000));
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_PATHNAME.toLowerCase() == "/page/footer_help")
{
	psCreatePageviewTag("Footer Help","Footer",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_PATHNAME.toLowerCase() == "/page/quickshop")
{
	psCreatePageviewTag("QUICK SHOP","Home",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_QUERYSTRING.toLowerCase().indexOf("param1=survey")>-1)
{
	psCreatePageviewTag("Survey","My Account",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(psIsMonthlyPrizeDrawPage())
{
	psCreatePageviewTag("Monthly Prize Draw","Monthly Prize Draw",null,null);
	psSetCookie(G_PS_COOKIE_CATID,"Monthly Prize Draw");
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(psIsSignUpEmailsPage())
{
	psCreatePageviewTag("SIGN UP FOR EMAILS","Monthly Prize Draw",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(psIsThanksMPDPage())
{
	psCreatePageviewTag("Thank you","Monthly Prize Draw",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(psIsEditCommunicationPage())
{
	psCreatePageviewTag("Edit Communication Options","My Account",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_PATHNAME.toLowerCase().indexOf("/invt/")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("temp=submitpowerreview")>-1)
{
	psCreatePageviewTag("Review","Review",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_PATHNAME.toLowerCase().indexOf("/invt/")>-1
		&& G_PS_QUERYSTRING.toLowerCase().indexOf("temp=enlarged")>-1)
{
	psCreatePageviewTag("Enlarged Image","Enlarged Image",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(psIsProductView())
{
	var prd = new psProduct();
	if (prd.getProduct())
	{
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
		psHijackAddToBagForProductView(prd.catId);
	}
	INTERVAL_ID.push(window.setInterval("psHijackAlsoLike()", 5000));
	INTERVAL_ID.push(window.setInterval("psHijackRecentView()", 5000));
	INTERVAL_ID.push(window.setInterval("psHijackRelated()", 5000));
}
else if(psIsAccountPage())
{
	psCreatePageviewTag("My Account","My Account",null,null);
	psSendRegistration();
	psSetCookie(G_PS_COOKIE_CATID,"Related Products");
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(psIsErrorAddingPage())
{
	psCreatePageviewTag("Error Adding New User","My Account",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-shopcart")>-1
		&& G_PS_QUERYSTRING.toLowerCase().indexOf("type=quickshop")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
{
	psCreatePageviewTag("QUICK SHOP","QUICK SHOP",null,null);
	psHijackAddToBagForQuickShop();
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-giftlist")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
{
	var pageId = "Wish List";
	var h1Item = document.getElementsByTagName("h1")[0];
	if(h1Item!=null)
	{
		pageId = psGetInnerText(h1Item);
	}
	psCreatePageviewTag(pageId,"Wish List",null,null);
	psHijackAddToBagForWishList();
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	psSetCookie(G_PS_COOKIE_CATID,"Wish List");
}
else if(G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-ordlookup")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
{
	var pageId = null;
	var divItem = document.getElementById("orderhistory");
	if(divItem != null)
	{
		var h1Item = divItem.getElementsByTagName("h1")[0];
		if(h1Item!=null)
		{
			pageId = psGetInnerText(h1Item);
		}
	}
	psCreatePageviewTag(pageId,"My Account",null,null);
}
else if(psIsUpdateEmailPage())
{
	var pageId = null;
	var divItem = document.getElementById("tlusermyform");
	if(divItem != null)
	{
		var h1Item = divItem.getElementsByTagName("h1")[0];
		if(h1Item!=null)
		{
			pageId = psGetInnerText(h1Item);
		}
	}
	psCreatePageviewTag(pageId,"My Account",null,null);
	psHijackUpdateEmail();
}
else if(G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-manageaddresses")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
{
	var pageId = null;
	var divItem = document.getElementById("checkout");
	if(divItem != null)
	{
		var h1Item = divItem.getElementsByTagName("h1")[0];
		if(h1Item!=null)
		{
			pageId = psGetInnerText(h1Item);
		}
	}
	psCreatePageviewTag(pageId,"My Account",null,null);
}
else if(psIsGiftWrapping())
{
	psCreatePageviewTag("Gift wrapping","checkout",null,null);
}
else if(psIsAddressBook())
{
	psCreatePageviewTag("Address Book","My Account",null,null);
}
else if(psIsAddDADetailPage())
{
	psCreatePageviewTag("Add Delivery Address Detail","My Account",null,null);
}
else if(psIsAddDAPage())
{
	psCreatePageviewTag("Add Delivery Address","My Account",null,null);
	psSendRegistration();
}
else if(psIsZipPage())
{
	psCreatePageviewTag("co_wizr-register:zipcode","My Account",null,null);
	psHijackRegister_Zipcode();
}
else if(psIsBillPage())
{
	psCreatePageviewTag("co_wizr-register:billto","My Account",null,null);
	psHijackRegister_Bill();
}
else if(psIsLoginPage())
{
	psCreatePageviewTag("co_wizr-register","My Account",null,null);
	psHijackForLogin();
}
else if(psIsConfirmPage())
{
	psSendRegistration();
	psCreatePageviewTag("co_wizr-shopcart:confirm","checkout",null,null);
}
else if(psIsRedeemGCPage())
{
	psCreatePageviewTag("Redeem a Gift Certificate","checkout",null,null);
}
else if(psIsRedeemPCPage())
{
	psCreatePageviewTag("Redeem a Promotion Code","checkout",null,null);
}
else if (psIsCheckoutFinish())
{
	psPostOrderView();
}
else if(psIsCartView())
{
	psCreatePageviewTag("co_wizr-shopcart","basket",null,null);
	psPostCartView();
	psSetCookie(G_PS_COOKIE_CATID,"Shopcart");
	psHijackShopCart();
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-giftcertificates")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
{
	psCreatePageviewTag("Gift Certificates","Home",null,null);
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_PATHNAME.toLowerCase() == "/page/monthlyofferspage")
{
	psCreatePageviewTag("monthlyofferspage","Home",null,null);
	psSetCookie(G_PS_COOKIE_CATID,"monthlyofferspage");
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
}
else if(G_PS_PATHNAME.toLowerCase() == "/page/wishlist")
{
	psCreatePageviewTag("Wish List Home Page","My Account",null,null);
}
else if (G_PS_PATHNAME.search(/^\/page\/[\w\d\_\-\~]+/gi)>-1)
{
	var pageId = null;
	var catId = null;
	var h1Item = document.getElementsByTagName("h1")[0];
	if(h1Item != null)
	{
		pageId = psHtmlDecode(psGetInnerText(h1Item));
		catId = "Footer";
		psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	}
	else
	{
		pageId = psHtmlDecode(psGetPageName());
		catId = "Home";
		psSetCookie(G_PS_COOKIE_CATID,catId);
		psSetCookie(G_PS_COOKIE_PAGEID,pageId);
		psSetCookie(G_PS_COOKIE_FLAG,"From Special");
		psHijackAddToBag(pageId);
	}
	psCreatePageviewTag(pageId,catId,null,null);
}
else if (G_PS_PATHNAME.toLowerCase().indexOf("/browse/")>-1)
{
	if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Image"))
	{
		INTERVAL_ID_SearchByImage.push(window.setInterval("psPostSearchByImage()", 5000));
		psSetCookie(G_PS_COOKIE_FLAG,"From Image");
	}
	else if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Special"))
	{
		var catId = psGetCookie(G_PS_COOKIE_CATID);
		var pageId = psGetCookie(G_PS_COOKIE_PAGEID);
		psCreatePageviewTag(pageId,catId,null,null);
		
		psSetCookie(G_PS_COOKIE_CATID,catId);
		psSetCookie(G_PS_COOKIE_PAGEID,pageId);
		psSetCookie(G_PS_COOKIE_FLAG,"From special");
		psHijackAddToBag(pageId);
	}
	else
	{
		psPostSearchView(psGetCookie(G_PS_COOKIE_CATID));
		psSetCookie(G_PS_COOKIE_FLAG,"From Browse");
		psHijackAddToBagForBrowsePage();
	}
}
else if (psIsSpecialPage())
{
	var pageId = null;
	var catId = null;
	var se = /(\/[\w\-\_\~]*)*\/(bestsellers|whatsnew|musthaves|promotions)([\w\-\_\~]*)&/gi;
	if(psHtmlDecode(G_PS_PATHNAME).search(se)>-1)
	{
		pageId = RegExp.$2;
		catId = RegExp.$3;
		psSetCookie(G_PS_COOKIE_CATID,catId);
		psSetCookie(G_PS_COOKIE_PAGEID,pageId);
		psSetCookie(G_PS_COOKIE_FLAG,"From special");
		psHijackAddToBag(pageId);
	}
	psCreatePageviewTag(pageId,catId,null,null);
}
else if(G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
{
	psPostPageView();
}
else
{
	if(psIsFromBrand_1())
	{
		var pageId = null;
		var catId = "Brand";
		var pList = document.getElementsByTagName("p");
		for (var i = 0; i < pList.length; i++)
		{
			if(psIsEqual(pList[i].className,"Lcattree categorytree"))
			{
				var breadcrumb = psHtmlDecode(psGetInnerText(pList[i]));
				breadcrumb = breadcrumb.split(">");
				if(breadcrumb.length>1)
				{
					pageId = breadcrumb[breadcrumb.length -1];
				}
				break;
			}
		}
		psCreatePageviewTag(pageId,catId,null,null);
		psSetCookie(G_PS_COOKIE_FLAG,"From Brand");
		psHijackHotpicks();
	}
	else if(psIsFromBrand_2())
	{
		psSetCookie(G_PS_COOKIE_FLAG,"From Brand");
		psSetCookie(G_PS_COOKIE_CATID,"Brand");
		psPostPageView();
	}
	else
	{
		var pageId = null;
		var catId = null;
		var pList = document.getElementsByTagName("p");
		for (var i = 0; i < pList.length; i++)
		{
			if(psIsEqual(pList[i].className,"Lcattree categorytree"))
			{
				var breadcrumb = psHtmlDecode(psGetInnerText(pList[i]));
				breadcrumb = breadcrumb.split(">");
				if(breadcrumb.length>1)
				{
					pageId = breadcrumb[breadcrumb.length -1];
					catId = breadcrumb[breadcrumb.length -2];
					psSetCookie(G_PS_COOKIE_CATID,pageId);
					psSetCookie(G_PS_COOKIE_FLAG,"","delete");
					INTERVAL_ID.push(window.setInterval("psHijackSpecialProduct()", 5000));
				}
				break;
			}
		}
		psCreatePageviewTag(pageId,catId,null,null);
		psHijackSearchByImage();
		psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	}
}
}


/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if (G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-shopcart")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
	{
		return true;
	}
	else if(G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-giftcertificates")>-1
			&& G_PS_QUERYSTRING.toLowerCase().indexOf("step=shopcart")>-1
			&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
	{
		return true;
	}
	else
	{
		var h1List = document.getElementsByTagName("h1");
		for(var i=0;i<h1List.length ;i++)
		{
			if(psIsEqual(psGetInnerText(h1List[i]),"Shopping Basket")
				|| psIsEqual(psGetInnerText(h1List[i]),"Shopping Bag"))
			{
				return true;
			}
		}
	}
	return false;
}

function psIsAddressBook()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Address Book"))
	{
		return true;
	}
	return false;
}

/*
 * Determine if the page is the product view page
 */
function psIsProductView()
{
	if (G_PS_PATHNAME.toLowerCase().indexOf("/invt/")>-1)
	{
		return true;
	}
	else if (document.getElementById("productdetail")!=null)
	{
		return true;
	}
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	//
	// TO-Do: Your logic to determine the receipt page goes here
	//
	return false;
}

function psIsSpecialPage()
{
	var se = /(\/[\w\-\_\~]*)*\/(bestsellers|whatsnew|musthaves|promotions)([\w\-\_\~]*)&/gi;
	if (psHtmlDecode(G_PS_PATHNAME).search(se)>-1)
	{
		return true;
	}
	return false;
}

function psIsAccountPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"MY ACCOUNT"))
	{
		return true;
	}
	return false;
}

function psIsZipPage()
{
	var aList = document.getElementsByTagName("a");
	for (var i = 0; i < aList.length; i++)
	{ 
		if(psIsEqual(psGetInnerText(aList[i]),"Don't know postcode?"))
		{
			return true;
		}
	}
	return false;
}

function psIsBillPage()
{
	var pList = document.getElementsByTagName("p");
	for (var i = 0; i < pList.length; i++)
	{
		if(psIsEqual(psGetInnerText(pList[i]),"Your address must match the billing address on your credit/debit card."))
		{
			return true;
		}
	}
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Edit Contact Details"))
	{
		return true;
	}
	return false;
}

function psIsLoginPage()
{
	if(G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-register")>-1
		&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1)
	{
		return true;
	}
	else if (G_PS_QUERYSTRING.toLowerCase().indexOf("ex=co_wizr-shopcart")>-1
				&& G_PS_PATHNAME.toLowerCase().indexOf("/bin/venda")>-1
				&& G_PS_QUERYSTRING.toLowerCase().indexOf("param1=login")>-1)
	{
		return true;
	}
	else
	{
		var h1Item = document.getElementsByTagName("h1")[0];
		if(psIsEqual(psGetInnerText(h1Item),"LOG IN"))
		{
			return true;
		}
	}
	return false;
}

function psIsGiftWrapping()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Gift Wrap"))
	{
		return true;
	}
	return false;
}

function psIsConfirmPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"ORDER SUMMARY"))
	{
		return true;
	}
	return false;
}

function psIsRedeemGCPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Redeem a Gift Certificate"))
	{
		return true;
	}
	return false;
}

function psIsRedeemPCPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Redeem a Promotion Code"))
	{
		return true;
	}
	return false;
}

function psIsAddDAPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Add Delivery Address"))
	{
		return true;
	}
	return false;
}

function psIsAddDADetailPage()
{
	var pList = document.getElementsByTagName("p");
	for (var i = 0; i < pList.length; i++)
	{
		if(psIsEqual(psGetInnerText(pList[i]),"Please enter your delivery details."))
		{
			return true;
		}
	}
	return false;
}

function psIsUpdateEmailPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Edit Email Address/Password"))
	{
		return true;
	}
	return false;
}

function psIsErrorAddingPage()
{
	var divItem = document.getElementById("myacc-col-two");
	if(divItem != null)
	{
		if(psGetInnerText(divItem).indexOf("Error adding new user")>-1)
		{
			return true;
		}
	}
	return false;
}

function psIsMonthlyPrizeDrawPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"MONTHLY PRIZE DRAW"))
	{
		return true;
	}
	return false;
}

function psIsSignUpEmailsPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"SIGN UP FOR EMAILS"))
	{
		return true;
	}
	return false;
}

function psIsThanksMPDPage()
{
	var divItem = document.getElementById("col-two");
	if(divItem != null)
	{
		if(psGetInnerText(divItem).toLowerCase().indexOf("thanks for your interest")>-1)
		{
			return true;
		}
	}
	return false;
}

function psIsFromBrand_1()
{
	var divItem = document.getElementById("hotpick");
	if(divItem != null)
	{
		return true;
	}
	return false;
}

function psIsFromBrand_2()
{
	var divItem = document.getElementById("searchresults");
	if(divItem != null)
	{
		return true;
	}
	return false;
}

function psIsEditCommunicationPage()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Edit Communication Options"))
	{
		return true;
	}
	return false;
}

function psIsCheckoutFinish()
{
	var h1Item = document.getElementsByTagName("h1")[0];
	if(psIsEqual(psGetInnerText(h1Item),"Order Receipt")
		|| psIsEqual(psGetInnerText(h1Item),"Your Receipt"))
	{
		return true;
	}
	return false;
}

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


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/

function psHijackHotpicks()
{
	var divItem = document.getElementById("productlist_toggle");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			aList[i].oldCMFunc = aList[i].onclick;
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,"Hot picks");
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				if(this.oldCMFunc != null)
				{
					return this.oldCMFunc();
				}
			}
		}
		
	}
}

function psHijackRegister_Bill()
{
	var divItem = document.getElementById("buttons");
	if(divItem != null)
	{
		var inputItem = divItem.getElementsByTagName("input")[0];
		if(inputItem!=null)
		{
			inputItem.oldCMFunc = inputItem.onclick;
			inputItem.onclick = function()
			{
				var profile = new psProfile();
				profile.readProfile();
				profile.cusId = profile.email = (psGetElementValueById("usemail",false)==null)? profile.cusId:psGetElementValueById("usemail",false);
				profile.city = (psGetElementValueById("city",false)==null)? profile.city:psGetElementValueById("city",false);
				var country = psGetElementValueById("cntrylist",false);
				if(psIsEqual(country,"United States"))
				{
					profile.state = (psGetElementValueById("state",false)==null)? profile.state:psGetElementValueById("state",false);
				}
				else
				{
					profile.state = null;
				}
				profile.zipcode = (psGetElementValueById("zipc",false)==null)? profile.zipcode:psGetElementValueById("zipc",false);
				var objTemp = document.getElementById("blkemail");
				if(objTemp != null)
				{
					if(objTemp.checked)
					{
						profile.subscribe = "Y";
						profile.newsletter = "latest bargains";
					}
					else
					{
						profile.subscribe = "N";
					}
				}
				objTemp = document.getElementsByName("blktrdcomm")[0];
				if(objTemp != null)
				{
					if(objTemp.checked)
					{
						profile.subscribe = "Y";
						profile.newsletter = (profile.newsletter == null)? "3rd party":(profile.newsletter + " and 3rd party");
					}
					else
					{
						profile.subscribe = psIsEqual(profile.subscribe,"Y")? "Y":"N";
					}
				}
				if(psIsEqual(profile.subscribe,"N"))
				{
					profile.newsletter = "latest bargains and 3rd party"
				}
				profile.writeProfile();
				psSetCookie(G_PS_COOKIE_FLAG,"Login");
				if(this.oldCMFunc)
				{
					return this.oldCMFunc();
				}
			}
		}
		
		var aItem = divItem.getElementsByTagName("a")[0];
		if(aItem != null)
		{
			aItem.onclick = function()
			{
				psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				if(document.getElementById("tlusermyform")){
					/* edit from my account - register workflow */
					return;
				}
				else {
						var objDiv = document.getElementsByTagName("div");
						for (var i = 0; i<objDiv.length;i++){
							if(objDiv[i].className == "container editcontactaddress"){
								/* edit from order summary - shopcart workflow */
								Step2(document.wizform,"confirm","display","","","_self","","","",""); 
								return false;
							}
							if(objDiv[i].className == "container addcontactaddress"){
								/* add new user */
								Step2(document.wizform,"zipcode","display","","","_self","","","",""); 
								return false;
							}
						}
				}
			}
		}
	}
}

function psHijackRegister_Zipcode()
{
	var divItem = document.getElementById("buttons");
	if(divItem != null)
	{
		var inputItem = divItem.getElementsByTagName("input")[0];
		if(inputItem!=null)
		{
			inputItem.oldCMFunc = inputItem.onclick;
			inputItem.onclick = function()
			{
				var profile = new psProfile();
				profile.cusId = profile.email = psGetElementValueById("usemail",false);
				profile.zipcode = psGetElementValueById("zipc",false);
				profile.writeProfile();
				if(doContinue!=null)
				{
					doContinue();
					return false;
				}
			}
		}
	}
}

function psCheckUpdateEmail()
{
	var email = psGetElementValueById("usemail",false);
	var pass = psGetElementValueById("uspswd",false);
	var confpass = psGetElementValueById("uspswd2",false);
	if(email!=null && email!="" && psCheckEmail(email))
	{
		if((confpass=="" && pass=="")
			|| (pass==null && confpass==null))
		{
			return true;
		}
		else if(pass==confpass && pass.length>=5)
		{
			return true;
		}
	}
	return false;
}

function psHijackUpdateEmail()
{
	var divItem = document.getElementById("buttons");
	if(divItem != null)
	{
		var inputItem = divItem.getElementsByTagName("input")[0];
		if(inputItem != null)
		{
			inputItem.oldCMFunc = inputItem.onclick;
			inputItem.onclick = function()
			{
				if(psCheckUpdateEmail())
				{
					var profile = new psProfile();
					profile.readProfile();
					profile.cusId = profile.email = psGetElementValueById("usemail",false);
					profile.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"Login");
				}
				if(this.oldCMFunc)
				{
					return this.oldCMFunc();
				}
			}
		}
	}
}

function psHijackLogout()
{
	var divItem = document.getElementById("header");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			if(psIsEqual(psGetInnerText(aList[i]),"Log Out"))
			{
				aList[i].oldCMFunc = aList[i].onclick;
				aList[i].onclick = function()
				{
					psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
					psSetCookie(G_PS_COOKIE_FLAG,"","delete");
					if(this.oldCMFunc != null)
					{
						return this.oldCMFunc();
					}
				}
				break;
			}
		}
	}
}

function psClearRegistration()
{
	var divItem = document.getElementById("checkout");
	if(divItem != null)
	{
		var h2List = divItem.getElementsByTagName("h2");
		for (var i = 0; i < h2List.length; i++)
		{
			if(psIsEqual(h2List[i].className,"error"))
			{
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				break;
			}
		}
	}
	
	var divItem = document.getElementById("myacc-col-two");
	if(divItem != null)
	{
		if(psGetInnerText(divItem).indexOf("Error adding new user")>-1)
		{
			psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		}
	}
}

function psSendRegistration()
{
	var divItem = document.getElementById("checkout");
	if(divItem != null)
	{
		var h2List = divItem.getElementsByTagName("h2");
		for (var i = 0; i < h2List.length; i++)
		{
			if(psIsEqual(h2List[i].className,"error"))
			{
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				break;
			}
		}
	}
	
	var divItem = document.getElementById("myacc-col-two");
	if(divItem != null)
	{
		if(psGetInnerText(divItem).indexOf("Error adding new user")>-1)
		{
			psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		}
	}
	
	if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"Login"))
	{
		var profile = new psProfile();
		profile.readProfile();
		psCreateRegistrationTag(profile.cusId, profile.email, profile.city, profile.state, profile.zipcode, profile.newsletter, profile.subscribe);
		psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	}
}

function psHrefShopcart(pHref)
{
	psSetCookie(G_PS_COOKIE_CATID,"Shopcart");
	window.location = pHref;
}

function psHijackMyShoppingBag()
{
	var ulItem = document.getElementById("minicart_products");
	if(ulItem != null)
	{
		var aList = ulItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			aList[i].oldHref = aList[i].href;
			aList[i].href = "javascript:psHrefShopcart('"+ aList[i].oldHref + "');";
		}
	}
}

function psHijackSearchByImage()
{
	var divList = document.getElementsByTagName("div");
	for (var i = 0; i < divList.length; i++)
	{
		if(psIsEqual(divList[i].className,"searchbyimage"))
		{
			var aItem = divList[i].getElementsByTagName("a")[0];
			if(aItem != null)
			{
				aItem.oldCMFunc = aItem.onclick;
				aItem.onclick = function()
				{
					psSetCookie(G_PS_COOKIE_CATID,"Search By Image");
					psSetCookie(G_PS_COOKIE_FLAG,"From Image");
					if(this.oldCMFunc)
					{
						return this.oldCMFunc();
					}
				}
			}
			break;
		}
	}
}

function psHijackShopCart()
{
	var divItem = document.getElementById("relatedbasket");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			aList[i].oldCMFunc = aList.onclick;
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,"Related Products");
				if(this.oldCMFunc)
				{
					return this.oldCMFunc();
				}
			}
		}
	}
}

function psHijackAddToBagForProductView(pCatId)
{
	if(document.getElementById("grid")!=null)
	{
		var divList = document.getElementsByTagName("div");
		for(var j = 0; j < divList.length; j++)
		{
			if(psIsEqual(divList[j].className,"sku"))
			{
				var prodId = psGetInnerText(divList[j]);
				prodId = prodId.replace("SKU","");
				prodId = prodId.replace(":","");
				prodId = psTrim(prodId);
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,pCatId);
				break;
			}
		}
	}
	else
	{
		var inputList = document.getElementsByTagName("input");
		for(var i = 0; i < inputList.length; i++)
		{
			if(psIsEqual(inputList[i].type,"image")
				&& psIsEqual(inputList[i].className,"add")
				&& inputList[i].src.indexOf("bt_addtobasket.gif")>-1)
			{
				inputList[i].oldCMFunc = inputList[i].onclick;
				inputList[i].onclick = function()
				{
					var divList = document.getElementsByTagName("div");
					for(var j = 0; j < divList.length; j++)
					{
						if(psIsEqual(divList[j].className,"sku"))
						{
							var prodId = psGetInnerText(divList[j]);
							prodId = prodId.replace("SKU","");
							prodId = prodId.replace(":","");
							prodId = psTrim(prodId);
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,pCatId);
							break;
						}
					}
					if(this.oldCMFunc != null)
					{
						return this.oldCMFunc();
					}
				}
				break;
			}
		}
	}
}

function psHijackAddToBagForWishList()
{
	var tblItem = document.getElementById("listItems");
	if(tblItem != null)
	{
		for (var i = 0; i < tblItem.rows.length; i++)
		{
			for(var j=0; j<tblItem.rows[i].cells.length; j++)
			{
				if(psIsEqual(tblItem.rows[i].cells[j].className,"buy"))
				{
					var aItem = tblItem.rows[i].cells[j].getElementsByTagName("a")[0];
					if(aItem != null)
					{
						aItem.oldCMFunc = aItem.onclick;
						aItem.onclick = function()
						{
							var parentNode = this.parentNode;
							while(!psIsEqual(parentNode.tagName,"td") && !psIsEqual(parentNode.className,"buy"))
							{
								parentNode = parentNode.parentNode;
							}
							var qty = parentNode.getElementsByTagName("input")[0];
							qty = psGetElementValue(qty,false);
							if(parseInt(qty)>0)
							{
								while(!psIsEqual(parentNode.tagName,"tr"))
								{
									parentNode = parentNode.parentNode;
								}
								var aItem_1 = parentNode.getElementsByTagName("a")[0];
								if(aItem_1 != null)
								{
									var prodId = aItem_1.href;
									var se = /\/(\d*)$/gi;
									prodId = (prodId.search(se)>-1)? RegExp.$1:prodId;
									psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,"Wish List");
								}
							}
							if(this.oldCMFunc != null)
							{
								return this.oldCMFunc();
							}
						}
					}
					break;
				}
			}
		}
	}
}

function psHijackAddToBagForQuickShop()
{
	var divItem = document.getElementById("buttons");
	if(divItem != null)
	{
		var aItem = divItem.getElementsByTagName("a")[0];
		if(aItem != null)
		{
			aItem.oldCMFunc = aItem.onclick;
			aItem.onclick = function()
			{
				if(this.oldCMFunc != null)
				{
					var tblList = document.getElementsByTagName("table");
					for (var i = 0; i < tblList.length; i++)
					{
						if(psIsEqual(tblList[i].className,"wizrtable"))
						{
							for (var j = 1; j < tblList[i].rows.length; j++)
							{
								var qty = tblList[i].rows[j].getElementsByTagName("input")[0];
								if(qty != null)
								{
									qty = psGetElementValue(qty,false);
									if(parseInt(qty)>0)
									{
										var prodId = psGetInnerText(tblList[i].rows[j].cells[0]);
										psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,"quickshop");
									}
								}
							}
						}
					}
					this.oldCMFunc();
				}
			}
		}
	}
}

function psPostPageView()
{
	if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Browse"))
	{
		var catId = psGetCookie(G_PS_COOKIE_CATID);
		psPostSearchView(catId);
		psSetCookie(G_PS_COOKIE_FLAG,"From Browse");
		psHijackAddToBagForBrowsePage();
	}
	else if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Brand"))
	{
		var catId = psGetCookie(G_PS_COOKIE_CATID);
		psPostSearchView(catId);
		psSetCookie(G_PS_COOKIE_FLAG,"From Brand");
		psHijackAddToBagForBrowsePage();
	}
	else if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From special"))
	{
		var catId = psGetCookie(G_PS_COOKIE_CATID);
		var pageId = psGetCookie(G_PS_COOKIE_PAGEID);
		psCreatePageviewTag(pageId,catId,null,null);
		
		psSetCookie(G_PS_COOKIE_CATID,catId);
		psSetCookie(G_PS_COOKIE_PAGEID,pageId);
		psSetCookie(G_PS_COOKIE_FLAG,"From special");
		psHijackAddToBag(pageId);
	}
	else if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Image"))
	{
		INTERVAL_ID_SearchByImage.push(window.setInterval("psPostSearchByImage()", 5000));
		psSetCookie(G_PS_COOKIE_FLAG,"From Image");
	}
	else
	{
		var divItem = document.getElementById("searchresults");
		if(divItem!=null)
		{
			psPostSearchView();
			psHijackAddToBag("SEARCH");
		}
		else
		{
			var pageId = "Error";
			var divItem = document.getElementById("checkout");
			if(divItem != null)
			{
				var h1Item = divItem.getElementsByTagName("h1")[0];
				if(h1Item!=null)
				{
					pageId = psGetInnerText(h1Item);
				}
			}
			psCreatePageviewTag(pageId,"My Account",null,null);
		}
	}
}

function psHijackAddToBagForBrowsePage()
{
	var divList = document.getElementsByTagName("div");
	for (var i = 0; i < divList.length; i++)
	{
		if(psIsEqual(divList[i].className,"toggle_clickbutton"))
		{
			var inputList = divList[i].getElementsByTagName("input");
			for (var j = 0; j < inputList.length; j++)
			{
				if(psIsEqual(inputList[j].type,"image") && psIsEqual(inputList[j].className,"add"))
				{
					inputList[j].oldCMFunc = inputList[j].onclick;
					inputList[j].onclick = function()
					{
						var parentNode = this.parentNode;
						while(!psIsEqual(parentNode.className,"toggle_clickbutton")
								&& !psIsEqual(parentNode.tagName,"body"))
						{
							parentNode = parentNode.parentNode;
						}
						var prodId = null;
						var inputList_1 = parentNode.getElementsByTagName("input");
						for (var k = 0; k < inputList_1.length; k++)
						{
							if(psIsEqual(inputList_1[k].name,"buy"))
							{
								prodId = inputList_1[k];
								break;
							}
						}
						if(prodId != null)
						{
							prodId = psGetElementValue(prodId,false);
							while(!psIsEqual(parentNode.className,"details")
									&& !psIsEqual(parentNode.tagName,"body"))
							{
								parentNode = parentNode.parentNode;
							}
							var aItem = parentNode.getElementsByTagName("a")[0];
							if(aItem != null)
							{
								var catId = aItem.href;
								var se = /^https*\:\/\/[^\/]+\/([^\/]+)\//gi;
								catId = (catId.search(se)>-1)? RegExp.$1:catId;
								psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,catId);
							}
						}
						if(this.oldCMFunc != null)
						{
							return this.oldCMFunc();
						}
					}
					break;
				}
			}
		}
	}
}

function psHijackAddToBag(catId)
{
	var divList = document.getElementsByTagName("div");
	for (var i = 0; i < divList.length; i++)
	{
		if(psIsEqual(divList[i].className,"toggle_clickbutton"))
		{
			var inputList = divList[i].getElementsByTagName("input");
			for (var j = 0; j < inputList.length; j++)
			{
				if(psIsEqual(inputList[j].type,"image") && psIsEqual(inputList[j].className,"add"))
				{
					inputList[j].oldCMFunc = inputList[j].onclick;
					inputList[j].onclick = function()
					{
						var parentNode = this.parentNode;
						while(!psIsEqual(parentNode.className,"toggle_clickbutton")
								&& !psIsEqual(parentNode.tagName,"body"))
						{
							parentNode = parentNode.parentNode;
						}
						var prodId = null;
						var inputList_1 = parentNode.getElementsByTagName("input");
						for (var k = 0; k < inputList_1.length; k++)
						{
							if(psIsEqual(inputList_1[k].name,"buy"))
							{
								prodId = inputList_1[k];
								break;
							}
						}
						if(prodId != null)
						{
							prodId = psGetElementValue(prodId,false);
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,catId);
						}
						
						if(this.oldCMFunc != null)
						{
							return this.oldCMFunc();
						}
					}
					break;
				}
			}
		}
	}
}

function psHijackSpecialProduct()
{
	var catId = null;
	var imgItem = document.getElementById("homeDiv3img");
	if(imgItem != null && imgItem.src.indexOf("bt_bestseller2.gif")>-1)
	{
		catId = "bestseller";
	}
	imgItem = document.getElementById("homeDiv2img");
	if(imgItem != null && imgItem.src.indexOf("bt_whatsnew2.gif")>-1)
	{
		catId = "whatsnew";
	}
	imgItem = document.getElementById("homeDiv4img");
	if(imgItem != null && imgItem.src.indexOf("bt_musthaves2.gif")>-1)
	{
		catId = "musthaves";
	}
	imgItem = document.getElementById("homeDiv5img");
	if(imgItem != null && imgItem.src.indexOf("bt_promotions2.gif")>-1)
	{
		catId = "promotions";
	}
	if(catId == null)
	{
		imgItem = document.getElementById("mensDiv3img");
		if(imgItem != null && imgItem.src.indexOf("bt_bestsellermens2.gif")>-1)
		{
			catId = "bestseller";
		}
		imgItem = document.getElementById("mensDiv2img");
		if(imgItem != null && imgItem.src.indexOf("bt_whatsnewmens2.gif")>-1)
		{
			catId = "whatsnew";
		}
		imgItem = document.getElementById("mensDiv4img");
		if(imgItem != null && imgItem.src.indexOf("bt_musthavesmens2.gif")>-1)
		{
			catId = "musthaves";
		}
		imgItem = document.getElementById("mensDiv5img");
		if(imgItem != null && imgItem.src.indexOf("bt_promotionsmens2.gif")>-1)
		{
			catId = "promotions";
		}
	}
	
	var divItem = document.getElementById("showAjaxDetail");
	if(divItem == null)
	{
		divItem = document.getElementById("showAjaxDetailMen");
	}
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,catId);
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				window.location = this.href;
			}
		}
	}
}

function psClearInterval(pIds)
{
    for (var i=0; i<pIds.length; i++)
    {
        window.clearInterval(pIds[i]);
    }
    pIds = new Array();
}

function psHijackAlsoLike()
{
	var divItem = document.getElementById("substitute");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,"Also Like");
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				window.location = this.href;
			}
		}
	}
}

function psHijackRelated()
{
	var divItem = document.getElementById("relatedbasket");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,"Related Products");
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				window.location = this.href;
			}
		}
	}
}

function psHijackRecentView()
{
	var ulItem = document.getElementById("rvilist");
	if(ulItem != null)
	{
		var aList = ulItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,"Recently Viewed");
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				window.location = this.href;
			}
		}
	}
}

function psHijackForLogin()
{
	var divItem = document.getElementById("buttons");
	if(divItem != null)
	{
		var btnCont = divItem.getElementsByTagName("input")[0];
		if(btnCont != null)
		{
			btnCont.oldCMFunc = btnCont.onclick;
			btnCont.onclick = function()
			{
				var profile = new psProfile();
				profile.cusId = profile.email = psGetElementValueById("email",false);
				profile.writeProfile();
				psSetCookie(G_PS_COOKIE_FLAG,"Login");
				if(this.oldCMFunc != null)
				{
					return this.oldCMFunc();
				}
			}
		}
	}
	
	var txtPass = document.getElementById("password");
	if(txtPass!=null)
	{
		txtPass.oldCMFunc = txtPass.onblur;
		txtPass.onblur = function()
		{
			var profile = new psProfile();
			profile.cusId = profile.email = psGetElementValueById("email",false);
			profile.writeProfile();
			psSetCookie(G_PS_COOKIE_FLAG,"Login");
			if(this.oldCMFunc != null)
			{
				return this.oldCMFunc();
			}
		}
	}
	
	var txtEmail = document.getElementById("email");
	if(txtEmail!=null)
	{
		txtEmail.oldCMFunc = txtEmail.onblur;
		txtEmail.onblur = function()
		{
			var profile = new psProfile();
			profile.cusId = profile.email = psGetElementValueById("email",false);
			profile.writeProfile();
			psSetCookie(G_PS_COOKIE_FLAG,"Login");
			if(this.oldCMFunc != null)
			{
				return this.oldCMFunc();
			}
		}
	}
}

function psGetFirstFolder()
{
	var se = /^\/([^\/]*)/gi;
	var firstFolder = (G_PS_PATHNAME.search(se)>-1)? RegExp.$1:null;
	return firstFolder;
}

function psGetPageName()
{
	var se = /(\/[\w\-\_\~]*)*\/([\w\-\_\~]*)\.?[\w\-\_\~]*/gi;
	var pageName = (G_PS_PATHNAME.search(se)>-1)? RegExp.$2:null;
	return pageName;
}

function psPostSearchByImage()
{
	G_PS_CUR_CATID = "Search By Image";
	psSetCookie(G_PS_COOKIE_CATID,G_PS_CUR_CATID);
	var pageId = "SEARCH SUCCESSFUL";
	var sTerm = null;
	var sResult = null;
	var divItem = document.getElementById("searchresults_image");
	if(divItem != null)
	{
		var spanList = divItem.getElementsByTagName("span");
		for (var i = 0; i < spanList.length; i++)
		{
			if(psIsEqual(spanList[i].className,"totalresults"))
			{
				sResult = psGetInnerText(spanList[i]);
				break;
			}
		}
		for (var i = 0; i < spanList.length; i++)
		{
			if(psIsEqual(spanList[i].className,"currentpage"))
			{
				pageId += " PAGE:[" + psGetInnerText(spanList[i]) + "]";
				break;
			}
		}
	}
	divItem = document.getElementById("term");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			if(psIsEqual(aList[i].className,"refine-link"))
			{
				sTerm = (sTerm==null)? psGetInnerText(aList[i]):(sTerm + ":" + psGetInnerText(aList[i]));
			}
		}
		if(sTerm==null)
		{
			sTerm = "All";
		}
	}
	
	if (pageId != null)
	{
		while(sTerm.indexOf("£")>-1)
		{
			sTerm = sTerm.replace("£","");
		}
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);
		psClearInterval(INTERVAL_ID_SearchByImage);
	}
}

function psPostSearchView(sType)
{
	sType = psTrim(sType);
     G_PS_CUR_CATID = "SEARCH" + ((sType!=null && sType!="")? (" : " + sType):"");
	var pageId = null;
	var sTerm = null;
	var sResult = null;
	var divItem = document.getElementById("searchresults");
	if(divItem != null)
	{
		if(psGetInnerText(divItem).toLowerCase().indexOf("the closest match was")>-1
			|| !(psGetInnerText(divItem).indexOf("returned no results")>-1))
		{
			pageId = "SEARCH SUCCESSFUL";
			if(sType!=null && sType!="")
			{
				psSetCookie(G_PS_COOKIE_CATID,sType);
			}
			else
			{
				psSetCookie(G_PS_COOKIE_CATID,"SEARCH");
			}
			psSetCookie(G_PS_COOKIE_FLAG,"","delete");
			var spanList = divItem.getElementsByTagName("span");
			for (var i = 0; i < spanList.length; i++)
			{
				if(psIsEqual(spanList[i].className,"totalresults"))
				{
					sResult = psGetInnerText(spanList[i]);
					break;
				}
			}
			for (var i = 0; i < spanList.length; i++)
			{
				if(psIsEqual(spanList[i].className,"currentpage"))
				{
					pageId += " PAGE:[" + psGetInnerText(spanList[i]) + "]";
					break;
				}
			}
		
		}
		else if(psGetInnerText(divItem).indexOf("returned no results")>-1)
		{
			pageId = "SEARCH UNSUCCESSFUL";
			sResult = 0;
		}
	}
	
	divItem = document.getElementById("term");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for (var i = 0; i < aList.length; i++)
		{
			if(psIsEqual(aList[i].className,"refine-link"))
			{
				sTerm = (sTerm==null)? psGetInnerText(aList[i]):(sTerm + ":" + psGetInnerText(aList[i]));
			}
		}
		if(sTerm==null)
		{
			sTerm = "All";
		}
	}
	
	if (pageId != null)
	{
		while(sTerm.indexOf("£")>-1)
		{
			sTerm = sTerm.replace("£","");
		}
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);
	}
}



/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	var cartTbl = null;
	var tblList = document.getElementsByTagName("table");
	for(var i= 0; i < tblList.length; i++)
	{
		if(psIsEqual(tblList[i].className,"wizrtable"))
		{
			cartTbl = tblList[i];
			break;
		}
	}
	
	if (cartTbl == null)
		return;
	var rows = cartTbl.rows;
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		if(psIsEqual(rows[r].className,"bundleitem defaultbundle")
			|| psIsEqual(rows[r].className,"standarditem"))
		{
			if (prd.getItem5(rows[r]))
				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()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("co_wizr-shopcart:finish", G_PS_CUR_CATID, null);

	var cartTbl = null;
	var tblList = document.getElementsByTagName("table");
	for (var i = 0; i < tblList.length; i++)
	{
		if(psIsEqual(tblList[i].className,"wizrtable"))
		{
			cartTbl = tblList[i];
			break;
		}
	}
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var ord = new psOrder();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var r = 0; r < rows.length; r++) // item for each row
			{
				var isProduct = false;
				for (var i = 0; i < rows[r].cells.length; i++) 
				{
					if(psIsEqual(rows[r].cells[i].className,"price"))
					{
						isProduct = true;
						break;
					}
				}
				if(isProduct)
				{
					if (prd.getItem9(rows[r]))
						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, uP.newsletter, uP.subscribe);
			psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "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;

	this.reset = function()
	{
		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.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var divItem = document.getElementById("rightside");
			if(divItem != null)
			{
				var divList = divItem.getElementsByTagName("div");
				for(var i = 0; i < divList.length; i++)
				{
					if(psIsEqual(divList[i].className,"sku"))
					{
						this.id = psGetInnerText(divList[i]);
						var se = /sku\s*:\s*(\w*)/gi;
						this.id = (this.id.search(se)>-1)? RegExp.$1:this.id;
						break;
					}
				}
				var h1Item = divItem.getElementsByTagName("h1")[0];
				if(h1Item != null)
				{
					this.name = psHtmlDecode(psGetInnerText(h1Item));
				}
				if(psGetDomain(G_PS_URL_REFERRER)!= null
					&& psGetDomain(G_PS_URL_REFERRER).indexOf("live.venda")>-1)
				{
					this.catId = "From Review";
					psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				}
				else if(psGetDomain(G_PS_URL_REFERRER)!= null
					&& psGetDomain(G_PS_URL_REFERRER).indexOf("powerreviews")>-1
					&& G_PS_URL_REFERRER.indexOf("submitreview.do")>-1)
				{
					this.catId = "From Review";
					psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				}
				else if(psGetCookie(G_PS_COOKIE_FLAG)==null
						|| psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Image"))
				{
					this.catId = psGetCookie(G_PS_COOKIE_CATID);
					if(psIsEqual(this.catId,"shopcart"))
					{
						this.catId = (psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id)==null)? this.catId:psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
					}
				}
				else if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Browse")
						|| psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Brand"))
				{
					var pList = document.getElementsByTagName("p");
					for (var i = 0; i < pList.length; i++)
					{
						if(psIsEqual(pList[i].className,"Lcattree categorytree"))
						{
							var breadcrumb = psHtmlDecode(psGetInnerText(pList[i]));
							breadcrumb = breadcrumb.split(">");
							if(breadcrumb.length>1)
							{
								this.catId = breadcrumb[breadcrumb.length -2];
							}
							break;
						}
					}
				}
				else if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"From Special"))
				{
					this.catId = psGetCookie(G_PS_COOKIE_PAGEID);
				}
				this.catId = (this.catId==null)? "BOOKMARKS":this.catId;
				psSetCookie(G_PS_COOKIE_CATID,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
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			for (var i=0; i<itemRow.cells.length; i++)
			{
				if(psIsEqual(itemRow.cells[i].className,"name"))
				{
					var aItem = itemRow.cells[i].getElementsByTagName("a")[0];
					if(aItem!=null)
					{
						this.name = psGetInnerText(aItem);
						var se = /\(([^\(\)]*)\)/gi;
						this.name = (psGetInnerText(itemRow.cells[i]).search(se)>-1)? (this.name + "(" + RegExp.$1 + ")"):this.name;
						if(psIsEqual(this.name,"Gift Certificate"))
						{
							this.catId = "Gift Certificate";
						}
						else
						{
							this.id = aItem.href;
							var questionMarkIndex = this.id.indexOf('?');
							if (questionMarkIndex != -1) {
								this.id = this.id.substring(0, questionMarkIndex);
							}
							if (this.id.substring(this.id.length-1,this.id.length) == '/') {
								this.id = this.id.substring(0,this.id.length-1);
							}
							
							var se = /\/(\d*)$/gi;
							if (this.id.search(se)>-1) {
								var splitBySlash = this.id.split('/');
								this.id = splitBySlash[splitBySlash.length-1];
							}
							this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
							this.catId = (this.catId==null)? "Shopcart":this.catId;
						}
					}
				}
				else if(psIsEqual(itemRow.cells[i].className,"priceeach"))
				{
					this.price = psGetInnerText(itemRow.cells[i]);
					if(psIsEqual(this.name,"Gift Certificate"))
					{
						this.id = "GC_" + psCleanPrice(this.price);
					}
				}
				else if(psIsEqual(itemRow.cells[i].className,"quantity"))
				{
					var inputItem = itemRow.cells[i].getElementsByTagName("input")[0];
					if(inputItem != null)
					{
						this.quantity = psGetElementValue(inputItem,false);
					}
					else
					{
						this.quantity = psGetInnerText(itemRow.cells[i]);
					}
				}
			}
			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
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			for (var i=0; i<itemRow.cells.length; i++)
			{
				if(psIsEqual(itemRow.cells[i].className,"thumb"))
				{
					var imgItem = itemRow.cells[i].getElementsByTagName("img")[0];
					if(imgItem != null)
					{
						this.id = imgItem.src;
						se = /\/invt\/(\d*)\//gi;
						this.id = (this.id.search(se)>-1)? RegExp.$1:this.id;
					}
				}
				else if(psIsEqual(itemRow.cells[i].className,"name"))
				{
					this.name = psGetInnerText(itemRow.cells[i]);
					var se = /([\w\(\)\s]*)\s*INFORMATION!/gi;
					this.name = (this.name.search(se)>-1)? RegExp.$1:this.name;
				}
				else if(psIsEqual(itemRow.cells[i].className,"price"))
				{
					this.price = psGetInnerText(itemRow.cells[i]);
				}
				else if(psIsEqual(itemRow.cells[i].className,"qty"))
				{
					this.quantity = psGetInnerText(itemRow.cells[i]);
				}
			}
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			
			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.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;
	/*
	 * Get user profile from cookie
	 */
	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];
					// when NULL is written to cookie, it becomes string, not literal constant
					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; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		try
		{
			if (this.cusId == null)
				return;
			// make sure that the data contains 4 parts separated by 3 '|'
			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);
			//
			// NOTE: To persist profile as persistent cookie, pass G_PS_COOKIE_LIFETIME as the third param instead of null
			// psSetCookie(G_PS_COOKIE_PROFILE, data, G_PS_COOKIE_LIFETIME);
			//
			return true;
		}
		catch (ex) { return false; }
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			var pList = document.getElementsByTagName("p");
			for (var i=0; i<pList.length; i++)
			{
				if(psIsEqual(pList[i].className,"ordernumber"))
				{
					this.id = psGetInnerText(pList[i].getElementsByTagName("strong")[0]);
					break;
				}
			}
			
			var divList = document.getElementsByTagName("div");
			var discount = 0;
			for (var i=0; i<divList.length; i++)
			{
				if(psIsEqual(divList[i].className,"discount"))
				{
					discount = psGetInnerText(divList[i]);
					var se = /\-\£([\d\.\,]*)/gi;
					discount = (discount.search(se)>-1)? RegExp.$1:discount;
					break;
				}
			}
			
			for (var i=0; i<divList.length; i++)
			{
				if(psIsEqual(divList[i].className,"subtotal"))
				{
					this.subtotal = psGetInnerText(divList[i]);
					this.subtotal = psCleanPrice(this.subtotal) - psCleanPrice(discount);
					break;
				}
			}
			
			for (var i=0; i<divList.length; i++)
			{
				if(psIsEqual(divList[i].className,"delivery"))
				{
					this.shipping = psGetInnerText(divList[i]);
					break;
				}
			}
			
			if (!this.id)
				this.id = psGenerateRandomValue();
			/*
			 * Extract user profile from source code
			 */
			var uP = new psProfile();
			uP.readProfile();  // Ensure to get the customer Id & email persisted at login stage
			if(uP.city == null || uP.state == null || uP.zipcode == null)
			{
				var divItem = document.getElementById("contactdetails");
				if(divItem != null)
				{
					var pItem = divItem.getElementsByTagName("p")[0];
					if(pItem != null)
					{
						var arrTemp = pItem.innerHTML;
						arrTemp = arrTemp.toLowerCase().split("<br>");
						for (var i=arrTemp.length-1 ; i>-1; i--)
						{
							if(arrTemp[i].indexOf(",")>-1)
							{
								var arrTemp_1 = psTrim(arrTemp[i]);
								arrTemp_1 = psGetInnerText(arrTemp_1);
								//arrTemp_1 = arrTemp_1.substring(arrTemp_1.indexOf(">")+1,arrTemp_1.length);
								arrTemp_1 = arrTemp_1.split(",");
								if(arrTemp_1.length>1)
								{
									uP.city = arrTemp_1[0];
									arrTemp_1 = psTrim(arrTemp_1[1]).split(" ");
									if(arrTemp_1.length>1)
									{
										uP.state = arrTemp_1[0];
										uP.zipcode = arrTemp_1[1];
									}
									else if(arrTemp_1.length>0)
									{
										uP.zipcode = arrTemp_1[0];
									}
								}
								break;
							}
						}
						if(uP.city == null || uP.state == null || uP.zipcode == null)
						{
							if(arrTemp.length > 4)
							{
								uP.city = psGetInnerText(arrTemp[arrTemp.length - 5]);
								var arrTemp_1 = psTrim(arrTemp[arrTemp.length - 4]);
								arrTemp_1 = arrTemp_1.split(" ");
								if(arrTemp_1.length>1)
								{
									uP.zipcode = arrTemp_1[1];
								}
								else if(arrTemp_1.length>0)
								{
									uP.zipcode = arrTemp_1[0];
								}
							}
						}
					}
				}
			}
			if (!uP.cusId)
				uP.cusId = psGenerateRandomValue();
			return uP.writeProfile(); // Persist profile for later use at Receipt stage
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
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;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	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;
}

/* 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 != null) ? 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
 * or key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
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;
}

/* 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, ">");
		pValue = pValue.replace(/%26/gi, "&");
    }

    return pValue;
}

/* PURPOSE: extract main domain from the URL
 * RETURN: main domain
 */
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;
	
}

/* 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)
{
    if (!pCookieName)
		return false;

	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	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;
}

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

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(pId);
	pCatId = psCleanCatId(pCatId);
	// Remove any trailing spaces
	pCatId = psTrim(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);
	// Remove any trailing spaces
	pCatId = psTrim(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);
	// Remove any trailing spaces
	pCatId = psTrim(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);
	// Remove any trailing spaces
	pCatId = psTrim(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);
	// Remove any trailing spaces
	pCatId = psTrim(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);
	// Remove any trailing spaces
	pCatId = psTrim(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 ==================*/
