/************************************************************************************/
/* $Revision: 146762 $
 * $Id: cmtaggingservices.js.txt 146762 2010-05-18 10:54:42Z cmichael $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v2.5, 2010/05/18
 * COPYRIGHT 1999-2008 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/
//Production data warehouse flag
cmSetProduction();
/*===========================GLOBAL VARIABLES ===============================*/
// options for debug mode when sending tag:
// 1: only alert
// 2: only send tag
// 3: alert & send tag
var G_PS_DEBUG_MODE = 2;

var G_PS_ARR_DOMAIN = new Array("cathkidston.co.uk");//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_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
var G_PS_COOKIE_EMAIL = "PS_EMAIL_TEMP";
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var G_PS_COOKIE_SHOP9		 	= "PS_SHOP9";
var G_PS_COOKIE_PRODID		 	= "PS_PRODID";
var G_PS_COOKIE_ORDER		 	= "PS_ORDER";
var G_PS_COOKIE_BILLING		 	= "PS_BILLING";
var G_PS_COOKIE_SKU 			= "PS_SKU";
var G_PS_COOKIE_FLAG_BILLING    = "PS_FLAG_BILLING";		// used as a "session" variable to handle events between pages
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if(G_PS_URL_PATH.indexOf("cathkidston.co.uk") >-1 )
{
	if(psIsLoginSuccessful())
	{
		if(psCheckElementExist(psGetCookie(G_PS_COOKIE_FLAG)))
		{
			if(psGetCookie(G_PS_COOKIE_FLAG) == "new cus" || psGetCookie(G_PS_COOKIE_FLAG) == "login")
				psPostRegistration();
		}
	}
	if(G_PS_PATHNAME == "/default.aspx"
		||G_PS_PATHNAME == "/")
	{
		var CatId = "HOME";
		psCreatePageviewTag(psGetDocTitle(), CatId, null, null);
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(G_PS_PATHNAME == "/e-maginus.shops.storedetails.aspx")
	{
		var CatId = "STORES";
		if(psIsStoreDetailPage())
		{
			psCreatePageviewTag(psGetPageIdForStore(), CatId, null, null);
		}
		else 
			psCreatePageviewTag("STORES", CatId, null, null);
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(psIsCategoriesPage())
	{
		var CatId = psGetCatIdForCategories(G_PS_URL_PATH);
		psCreatePageviewTag(psGetDocTitle(), CatId,null,null);
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(psIsOtherPage())
	{
		var CatId = "OTHER";
		psCreatePageviewTag(psGetDocTitle(), CatId,null,null);
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}

	else if(psIsFooterPage())
	{
		var CatId = "FOOTER LINKS";
		psCreatePageviewTag(psGetDocTitle(), CatId,null,null);
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}

	else if(G_PS_PATHNAME == "/signin.aspx")
	{
		var CatId = "ACCOUNT";
		psHijackLogin("existingLoginButton")
		psCreatePageviewTag("Login", CatId, null, null);
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(G_PS_PATHNAME == "/createaccount.aspx")
	{
		var CatId = "ACCOUNT";
		psCreatePageviewTag("CREATE ACCOUNT", CatId, null, null);
		psHijackNewCustomer();
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(G_PS_PATHNAME == "/account.aspx")
	{
		var CatId = "ACCOUNT";
		psCreatePageviewTag("MY ACCOUNT", CatId, null, null);
		
		psHijackUpdateAcc();
		if(psIsUpdatedSuccessful() && psGetCookie(G_PS_COOKIE_FLAG) == "update account")
		{
			var uP = new psProfile();
			uP.readProfile(); 
			uP.cusId = psGetCookie(G_PS_COOKIE_EMAIL);
			uP.email = psGetCookie(G_PS_COOKIE_EMAIL);
			uP.writeProfile();
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(G_PS_PATHNAME == "findus.aspx"){
		var pStore = psTrim(psHtmlDecode(unescape(psGetValueFromUrl(G_PS_URL_PATH, "store"))));
		if(pStore != null && pStore != "null" && pStore != ""){
			pStore = "Store:" + pStore;
		}
		else {
			pStore = "Store: home";
		}
		psCreatePageviewTag(pStore, "store finder", null, null);	
	}
	else if(psIsSearchView())
	{
		psPostSearchView();
	}
	else if(psIsProductView())
	{
		psPostProductView();
		psHijackRecommendPro();
	}
	else if(G_PS_PATHNAME == "/emailproduct.aspx")
	{
		psCreatePageviewTag(psGetPageIdForEmailPro(),"EMAIL PRODUCT",null,null);
	}
	else if(psIsCartView())
	{
		var CatId = "ACCOUNT";
		psCreatePageviewTag("SHOPPING CART", CatId, null);
	
		psPostCartView();
	}
	else if(G_PS_PATHNAME == "/checkoutanon.aspx")
	{
		var CatId = "CHECKOUT";
		psCreatePageviewTag("ANONYMOUS CHECKOUT", CatId, null, null);
		psHijackLogin("btnSignInAndCheckoutx");
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(G_PS_PATHNAME == "/checkoutshipping.aspx")
	{
		var CatId = "CHECKOUT";
		psCreatePageviewTag("SHIPPING", CatId, null, null);
	}
	else if(G_PS_PATHNAME == "/checkoutpayment.aspx")
	{
		var CatId = "CHECKOUT";
		psCreatePageviewTag("PAYMENT", CatId, null, null);
	}
	else if(G_PS_PATHNAME == "/checkoutreview.aspx")
	{
		var CatId = "CHECKOUT";
		psCreatePageviewTag("REVIEW ORDER", CatId, null, null);
		psPostCartView();
		psSetOrderToCookie();
		psUpdateBillingAddress();
		psSetSKUToCookie();
	}
	else if(G_PS_PATHNAME == "/giftregistry.aspx")
	{
		var CatId = "gift list";
		psCreatePageviewTag("Gift List", CatId, null, null);
		psSetCookie(G_PS_COOKIE_CATID, CatId);
		
	}
	else if(psIsOrderView())
	{
		var CatId = "CHECKOUT";
		psCreatePageviewTag("ORDER COMPLETED", CatId, null, null);
		psPostOrderView();
	}
	else if(G_PS_PATHNAME == "/error.htm")
	{
		psCreatePageviewTag("Error Page", "Home", null, null);
	}
	else if(G_PS_PATHNAME == "/showsection.aspx")
	{
		psCreatePageviewTag(psGetDocTitle(), "OTHER", null, null);
	}
	else if(G_PS_PATHNAME.search(/\quickaddress\/([^.]+)\.aspx/gi) >-1)
	{
		psCreatePageviewTag("QuickAddress:" + RegExp.$1, "OTHER", null, null);
	}
	else if(G_PS_PATHNAME == "/orderhistoryheader.aspx")
	{
		psCreatePageviewTag("Order History", "ACCOUNT", null, null);
	}
	else if(G_PS_PATHNAME == "/mailinglist.aspx")
	{
		psCreatePageviewTag("Mailing List", "OTHER", null, null);
	}
	else if(G_PS_PATHNAME == "/selectaddress.aspx")
	{
		psCreatePageviewTag("Change the primary billing address", "ACCOUNT", null, null);
		psHijackSetPrimaryBilling();
		psHijackChangePrimaryBilling();
		if(psGetCookie(G_PS_COOKIE_FLAG) == "update address" && psGetCookie(G_PS_COOKIE_FLAG_BILLING) == "primary")
		{
			var pAdd = psGetCookie(G_PS_COOKIE_BILLING);
			if(psCheckElementExist(pAdd))
			{
				psGetBillingAddFromCookie();
			}
			psSetCookie(G_PS_COOKIE_FLAG_BILLING,"","delete");
		}
		else
			psGetBillingAddFromSite();
	}
	else if(G_PS_PATHNAME == "/editaddress.aspx")
	{
		psCreatePageviewTag("Edit address", "ACCOUNT", null, null);
		var msgError = document.getElementById("ErrorMsgLabel");
		if(psCheckElementExist(msgError))
		{
			psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		}
		psHijackDeleteAdd();
		psHijackUpdateBillingAdd();
		psSetCookie(G_PS_COOKIE_CATID, CatId);
	}
	else if(G_PS_PATHNAME == "/giftregistrysearch.aspx")
	{
		psCreatePageviewTag("Gift List Finder", "OTHER", null, null);
	}
	else 
	{	
		psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
	}
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	if(G_PS_PATHNAME == "/searchadv.aspx")
		return true;
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	if(G_PS_URL_PATH.search(/cathkidston\.co\.uk\/p-([^\.]+)\.aspx/gi) > -1)
	{
		var lstInputs = psGetElementsByClassName(document,"input","AddToCartButton");
		if(psCheckArrayExist(lstInputs))
		{
			for (var i=0; i<lstInputs.length; i++)	
			{
				var items = lstInputs[i];
				if (items.type && items.value && items.type == "button" && items.value.toLowerCase() == "add to bag")
				{
					return true;
				}
			}
		}
		else 
		{
			var btnCart = document.getElementById("AddToCartButton");
			if(psCheckElementExist(btnCart))
			{
				if (btnCart.value && btnCart.value.toLowerCase() == "add to bag")
				{
					return true;
				}
			}
		}
	}
	else if(G_PS_PATHNAME == "/showproduct.aspx")
	{
		return true;
	}
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_PATHNAME == "/shoppingcart.aspx")
		return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_PATHNAME == "/orderconfirmation.aspx")
		return true;
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psGetCusId()
{
	var cusId = psGenerateRandomValue();
	var se = /\>\s*([^\>\@\.]*\@[^\.]*\.[^\<]*)\s*\</gi;
	var contentDiv = document.getElementById("content");
	if(psCheckElementExist(contentDiv))
	{
		cusId = (contentDiv.innerHTML.search(se)>-1)? RegExp.$1:cusId;
	}
	return cusId;
}

function psSetSKUToCookie(){
	var proID = null;
	var proSKU = null;
	var proCatID = null;
	var proQt = null;
	var pTable = document.getElementById("pnlOrderSummary");
	if(psCheckElementExist(pTable)){
		pTable = pTable.getElementsByTagName("table");
		for(var i=0; i< pTable.length; i++){
			if(pTable[i].innerHTML.search(/product/gi) >= 0){
				if(psCheckArrayExist(pTable[i].getElementsByTagName("table")) == false){
					var pItemRow = pTable[i].getElementsByTagName("tr");
					if(psCheckArrayExist(pItemRow)){
						for(var j=0; j< pItemRow.length; j++){
							var pTD = pItemRow[j].getElementsByTagName("td");
							if(psCheckArrayExist(pTD)){
								if(psCheckArrayExist(pTD[0].getElementsByTagName("a"))){
									proID = pTD[0].getElementsByTagName("a")[0];
									proID = proID.href;
									proID = psGetProductId(proID);
									
									proSKU = pTD[1].innerHTML.split(/\<br\>/gi)[1]; 
																										
									proCatID = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, proID);
									
									proQt = pTD[3].getElementsByTagName("input")[0];
									proQt = proQt.value; 
									
									psSetValueToCookie(G_PS_COOKIE_SKU, proSKU, proCatID + "-_-" + proQt);
								}
							}
						}
					}
					break;
				}
			}
		}
	}
}

function psGetValueFromGooGleAnalys(){
	var pText = null;
	var pScript = document.getElementsByTagName("script");
	if(psCheckArrayExist(pScript)){
		for(var i=0; i< pScript.length; i++){
			if(pScript[i].innerHTML.search(/\_addItem/) >= 0){
				pText = psTrim(psHtmlDecode(unescape(pScript[i].innerHTML)));
				break;
			}
		}
	}
	if(pText != null){
		pText = pText.split(/pageTracker\.\_trackTrans/gi)[0];
		pText = pText.split(/pageTracker\.\_addTrans/gi);
		for(var i= pText.length -1; i >= 0; i--){
			if(pText[i] != null && pText[i] != ""){
				pText = pText[i];
				break;
			}
			else {
				return false;
			}
		}
		pText = pText.split(/pageTracker\.\_addItem/gi);
	}
	return pText;
}

function psReplaceCommon(pText){
	pText = pText.replace(/^\"/,"");
	pText = pText.replace(/\"$/,"");
	return pText;
}

function psUpdateBillingAddress(){
	var pContent = document.getElementById("TopPanel");
	var pText = null;
	var uP = new psProfile();
	uP.readProfile();
	if(uP.city == null ||uP.city == "" || uP.zipcode == null 
	|| uP.zipcode == "" ||uP.state == null ||uP.state == ""){
		if(psCheckElementExist(pContent)){
			var pTable = pContent.getElementsByTagName("table");
			if(psCheckArrayExist(pTable)){
				for(var i=0; i<pTable.length; i++){
					if((psHtmlDecode(unescape(pTable[i].innerHTML)).search(/Invoice\s+Address/gi) >= 0)
					&&(psHtmlDecode(unescape(pTable[i].innerHTML)).search(/Payment\s+Method/gi) >= 0)){
						pText = pTable[i].innerHTML.split(/\<\/span\>/gi)[1];
						pText = pText.split(/\<span/gi)[0];
						break;
					}
				}
			}
		}
		if(pText!= null && pText!= "null" && pText!= ""){
			pText = pText.split(/\<br\>/gi);
			for(var j= pText.length; j>=0; j--){
				if(psTrim(pText[j])!= null && psTrim(pText[j])!= "null" && psTrim(pText[j])!= ""){
					uP.zipcode = psHtmlDecode(psTrim(pText[j-2]));
					uP.state = psHtmlDecode(psTrim(pText[j-3]));
					uP.city = psHtmlDecode(psTrim(pText[j-4]));
					uP.writeProfile();
					break;
				}
			}
		}
	}
}

function psIsNumber(val)
{
	if(val != null && val != "")
		return (isNaN(val) == true)?false:true;
	return false;
}
function psGetDocTitle()
{
	var sTitle = null;
	var lstTitle = document.getElementsByTagName("title");
	if(psCheckArrayExist(lstTitle))
	{
		sTitle = lstTitle[0].innerHTML;
		sTitle = psTrim(psCleanCatId(psHtmlDecode(sTitle)));
	}
	return sTitle;
}
function psIsLoginSuccessful()
{
	var oUserName = document.getElementById("userName")
	if(psCheckElementExist(oUserName))
	{
		var sText = oUserName.innerHTML.toLowerCase();
		sText = psHtmlDecode(psCleanHtmlTag(sText))
		if(sText.indexOf("welcome back") > -1)
			return true;
	}
	return false;
}

function psIsUpdatedSuccessful()
{
	var oMsg = document.getElementById("lblAcctUpdateMsg")
	if(psCheckElementExist(oMsg))
	{
		var sText = oMsg.innerHTML.toLowerCase();
		sText = psHtmlDecode(psCleanHtmlTag(sText))
		if(sText.indexOf("your account has been updated") > -1)
			return true;
	}
	return false;
}
function psPostRegistration()
{
	var uP = new psProfile();
	uP.readProfile(); // get user profile from cookie
	if(uP.email != null)
	{
		psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
}

function psHijackNewCustomer()
{
	var btnCreateAcc = document.getElementById("btnContinueCheckout");
	if (psCheckElementExist(btnCreateAcc))
	{
		btnCreateAcc.oldCMFunc = btnCreateAcc.onclick;
		btnCreateAcc.onclick = function()
		{
			var pEmail = psGetElementValueById("EMail");
			if(psCheckArrayExist(pEmail))
			{
				var uP = new psProfile();
				uP.email = psTrim(pEmail);
				uP.cusId = psTrim(pEmail);
				uP.city = psGetElementValueById("BillingCity",true);
				uP.state =  psGetElementValueById("BillingStateNew",true);
				uP.zipcode = psGetElementValueById("BillingZip",true);	
				uP.writeProfile();				
				psSetCookie(G_PS_COOKIE_FLAG,"new cus");
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}		
	}
}

function psHijackUpdateAcc()
{
	var btnUpdeteAcc = document.getElementById("btnUpdateAccount");
	if (psCheckElementExist(btnUpdeteAcc))
	{
		btnUpdeteAcc.oldCMFunc = btnUpdeteAcc.onclick;
		btnUpdeteAcc.onclick = function()
		{
			var pEmail = psGetElementValueById("EMail");
			if(psCheckArrayExist(pEmail))
			{
				psSetCookie(G_PS_COOKIE_EMAIL,pEmail);
				psSetCookie(G_PS_COOKIE_FLAG,"update account");
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}		
	}
}

function psHijackLogin(btnId)
{
	var btnLogin = document.getElementById(btnId);
	if (psCheckElementExist(btnLogin))
	{
		btnLogin.oldCMFunc = btnLogin.onclick;
		btnLogin.onclick = function()
		{
			var pEmail = psGetElementValueById("EMail");
			if(psCheckArrayExist(pEmail))
			{
				var uP = new psProfile();
				uP.email = psTrim(pEmail);
				uP.cusId = psTrim(pEmail);
				uP.writeProfile();				
				psSetCookie(G_PS_COOKIE_FLAG,"login");
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}		
	}
}

function psGetPageIdForStore()
{
	var pageId = null;
	var sContent = document.getElementById("contentLHN");
	if(psCheckElementExist(sContent))
	{
		var lstH2 = sContent.getElementsByTagName("h2");
		if(psCheckArrayExist(lstH2))
		{
			pageId = psHtmlDecode(psCleanHtmlTag(lstH2[0].innerHTML));
			pageId = psTrim(pageId);
		}
	}
	return pageId;
}

function psIsStoreDetailPage()
{
	var sShop = psGetValueFromUrl(G_PS_URL_PATH,"shopid");
	if(psCheckElementExist(sShop))
		return true;
	return false;
}

function psIsCategoriesPage()
{
	if(G_PS_URL_PATH.search(/cathkidston\.co\.uk\/c-(\d+)-([^\.]+)\.aspx/gi) > -1)
		return true;
	return false;
}

function psGetCatIdForCategories(sPath)
{
	if(sPath.search(/cathkidston\.co\.uk\/c-(\d+)-([^\.]+)\.aspx/gi) > -1)
		return RegExp.$1;
	return  null;
}

function psIsOtherPage()
{
	if(G_PS_URL_PATH.search(/cathkidston\.co\.uk\/s-([^\.]+)\.aspx/gi) > -1
		|| G_PS_PATHNAME == "/t-emailerror.aspx"
		|| G_PS_PATHNAME == "/404b.htm")
		return true;
	return false;
}

function psIsFooterPage()
{
	if(G_PS_URL_PATH.search(/cathkidston\.co\.uk\/t-([^\.]+)\.aspx/gi) > -1)
		return true;
	return false;
}

function psGetProductId(sPath)
{
	var proId = null;
	if(sPath.search(/p-(\d+)-([^\.]+)\.aspx/gi) > -1)
	{
		proId = RegExp.$1;
	}
	if(proId == null)
	{
		proId = psGetValueFromUrl(sPath,"ProductID");
	}
	return proId;
}

function psGetPageIdForEmailPro()
{
	var pPageId = null;
	var proName = psGetLastedFromCrumb();
	var proId = psGetProductId(G_PS_URL_PATH);
	if(proName && proId)
		pPageId = "Email :" + proName + "("+ proId + ")";
	return pPageId;
}

function psGetLastedFromCrumb()
{
	var sLasted = null;
	var oCrumb = document.getElementById("breadcrumb2");
	oCrumb = (oCrumb==null)?document.getElementById("breadcrumb"):oCrumb
	if(psCheckElementExist(oCrumb))
	{
		var sSpan = oCrumb.getElementsByTagName("span")
		if(psCheckArrayExist(sSpan))
		{
			sLasted = psTrim(psCleanCatId(psHtmlDecode(sSpan[0].innerHTML)));
		}
		else 
		{
			var lstLink = oCrumb.innerHTML.toLowerCase().split("</a>");
			if(psCheckArrayExist(lstLink))
			{
				sLasted = psTrim(psCleanCatId(psHtmlDecode(lstLink[lstLink.length-1])));
				sLasted = psTrim(sLasted.replace(/-/gi,""));
			}
		}			
	}
	
	return sLasted;
}

function psGetProCatFromCrumb()
{
	var oCrumb = document.getElementById("breadcrumb2");
	var sCatId = null;
	if(psCheckElementExist(oCrumb))
	{
		var sLink = oCrumb.getElementsByTagName("a");	
		if(psCheckArrayExist(sLink))
		{
			var sPath = sLink[sLink.length-1].href;
			if(psCheckElementExist(sPath))
			{
				sCatId = psGetCatIdForCategories(sPath);
			}
		}
	}
	return sCatId;
}

function psGetProductName()
{
	var proName = null;
	var proDetail = psGetElementsByClassName(document,"div", "productDetailColumn");
	if(psCheckArrayExist(proDetail))
	{
		var lstH3 = proDetail[0].getElementsByTagName("h3");
		if(psCheckArrayExist(lstH3))
		{
			proName = psTrim(psCleanHtmlTag(psHtmlDecode(lstH3[0].innerHTML)));
		}
	}
	if(proName == "null")
	{
		proName = psGetLastedFromCrumb();
	}
	return proName;
}

function psHiackAddToCart(pProId, pCatId)
{
	var lstInputs = psGetElementsByClassName(document,"input","AddToCartButton");
	if(psCheckArrayExist(lstInputs))
	{
		for (var i=0; i<lstInputs.length; i++)	
		{
			var items = lstInputs[i];
			if (items.type && items.value && items.type == "button" && items.value.toLowerCase() == "add to bag")
			{
				items.oldCMFunc = items.onclick;
				items.onclick = function()
				{
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pProId, pCatId);
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}	
			}
		}
	}
	else 
	{
		var btnCart = document.getElementById("AddToCartButton");
		if(psCheckElementExist(btnCart))
		{
			if (btnCart.value && btnCart.value.toLowerCase() == "add to bag")
			{
				btnCart.oldCMFunc = btnCart.onclick;
				btnCart.onclick = function()
				{
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pProId, pCatId);
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}	
			}
		}
	}
}

function psHijackRecommendPro()
{
	var lstDivs = psGetElementsByClassName(document,"div","upsellContainer");
	if(psCheckArrayExist(lstDivs))
	{
		var sLinks = lstDivs[0].getElementsByTagName("a");
		if(psCheckArrayExist(sLinks))
		{
			for (var i=0; i<sLinks.length; i++)	
			{
				if(sLinks[i].href.search(/p-(\d+)-([^\.]+)\.aspx/gi) > -1)
				{
					sLinks[i].oldCMFunc = sLinks[i].onclick;
					sLinks[i].onclick = function()
					{
						var pProId = psGetProductId(this.href);
						psSetCookie(G_PS_COOKIE_CATID,"Recommend Products");
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pProId, "Recommend Products");
						if (this.oldCMFunc != null)
							return this.oldCMFunc();
					}	
				}
			}
		}
	}	
}

function psGetTableByCellName(pCellName)
{
	var sTblRe = null;
	var lstTable = document.getElementsByTagName("table");
	if(psCheckArrayExist(lstTable))
	{
		for (var j=0; j<lstTable.length; j++)	
		{
			var sRows = lstTable[j].rows; // use rows variable for optimization
			var sStop = (sRows.length > 3)? 4:sRows.length;
			for(var i=0; i< sStop; i++)
			{
				for(var t=0; t<sRows[i].cells.length; t++)
				{
					var sHeader = psCleanHtmlTag(sRows[i].cells[t].innerHTML);
					if (sHeader.toLowerCase().indexOf(pCellName.toLowerCase()) > -1)
					{
						//we need catch the lastest of table so can't put a break 
						sTblRe = lstTable[j];			
					}
				}
			}
		}
	}
	return sTblRe;
}

function psGetElementsByClassName(psDocument, psElementTagName, psClassName)
{
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null)
    {
        return null;
    }
    for(var i = 0; i < arrInputs.length; i ++ )
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

/*
 * Check if array is exist or not
 */
function psCheckArrayExist(pArrElement)
{
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0)
    {
        return false;
    }

    return true;
}

/*
 * Check an element exist or not
*/
function psCheckElementExist(pElement)
{
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }

    return true;
}
function psPostSearchView()
{
	var sCatId = "search";
	var pageId = null;
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(sResult == 0 || sResult == "0")
	{
		pageId = "SEARCH UNSUCCESSFUL";
	}
	else
	{
		pageId = "SEARCH SUCCESSFUL PAGE " + psGetCurrentPage();
	}
	if (pageId != null)
		psCreatePageviewTag(pageId, sCatId, sTerm, sResult);
	psSetCookie(G_PS_COOKIE_CATID, sCatId);
}

function psGetCurrentPage()
{
	var sPageNum = psGetValueFromUrl(G_PS_URL_PATH,"pagenum");
	return psCheckElementExist(sPageNum)?sPageNum:1;
}
/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = psGetValueFromUrl(G_PS_URL_PATH,"SearchTerm");
	term = psHtmlDecode(unescape(term));
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	var sNum = document.getElementById("paging-info");
	if(psCheckElementExist(sNum))
	{
		var sText = psHtmlDecode(psCleanHtmlTag(sNum.innerHTML));
		if(sText.search(/of\s(\d*)/gi) > -1)
			result = RegExp.$1;
	}
	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?
	{
		psHiackAddToCart(prd.id,prd.catId);
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
		psSetCookie(G_PS_COOKIE_CATID,prd.catId);
	}
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	var index=0;
	var pProId_tr="";
	
	psSetCookie(G_PS_COOKIE_SHOP9, "", "delete");
    psSetCookie(G_PS_COOKIE_ORDER, "", "delete");
	
	var cartTbl = null;
	cartTbl = psGetTableByCellName("Quantity");
	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++) 
	{
		if (rows[r].innerHTML.search(/Quantity_/gi)<0) 
			continue;
		if (prd.getItem5(rows[r]))
		{
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
			var pValueShop9 = prd.id + "|" +  prd.name + "|" + prd.quantity +"|" + prd.price.replace("$","") + "|" + prd.catId;				
			var pProdId = prd.id + "_" + index;
			pProId_tr+=pProdId + "--";
			index+=1;
			
			psSetValueToCookie(G_PS_COOKIE_SHOP9,pProdId,pValueShop9); 
		}
	}
	psSetValueToCookie(G_PS_COOKIE_PRODID,"ProLst",pProId_tr);
	// Make sure to have actual postings
	psDisplayShop5s();
}

function psSetOrderToCookie()
{	
	var pSubtotal = 0;
	var pShipping = 0;
	
	var oderPanel = document.getElementById("pnlOrderSummary");
	if(psCheckElementExist(oderPanel))
	{
		var lstTable = oderPanel.getElementsByTagName("table");
		if(psCheckArrayExist(lstTable))
		{
			for(var t =0 ;t < lstTable.length; t++)
			{
				if((psHtmlDecode(unescape(lstTable[t].innerHTML)).search(/Sub\s+Total/gi) >= 0)
				&& (psHtmlDecode(unescape(lstTable[t].innerHTML)).search(/Delivery/gi) >= 0)
				&& (psHtmlDecode(unescape(lstTable[t].innerHTML)).search(/Product/gi) < 0)
				&& (psCheckArrayExist(lstTable[t].getElementsByTagName("table")) == false))
				{
					var pRows = lstTable[t].rows;
					for(var i =0 ;i < pRows.length; i++)
					{
						if(pRows[i].innerHTML.toLowerCase().indexOf("sub total") >-1)
						{
							pSubtotal = psTrim(psHtmlDecode(psCleanHtmlTag(pRows[i].innerHTML)));
							if(pSubtotal.search(/(\d+[.,]?\d+)/gi) >-1)
								pSubtotal = RegExp.$1;
						}
						if(pRows[i].innerHTML.toLowerCase().indexOf("delivery") >-1)
						{
							var sText = psTrim(psHtmlDecode(psCleanHtmlTag(pRows[i].innerHTML)));
							if(sText.search(/(\d+[.,]?\d+)/gi) >-1)
								pShipping = RegExp.$1;
						}						
					}
				}
			}
		}
	}
	var pValueOrder =  pSubtotal+ ":" + pShipping;	
	psSetCookie(G_PS_COOKIE_ORDER,pValueOrder);				
}

/*
 * Process to post shop9tags for items purchased
 */

function psPostOrderView()
{
	var ord = new psOrder();
	var prd = new psProduct();
	ord.getOrder();
	var uP = new psProfile();
	uP.readProfile();
	uP.cusId = uP.email = psGetCusId();
	var strProductId = psGetValueFromCookie(G_PS_COOKIE_PRODID,"ProLst");
    var flg_order_tag = false;
	
	if(strProductId != "" && strProductId != null)
	{
		var arrProduct = strProductId.split("--");
		for(var i=0; i<arrProduct.length;i++)
		{
			if (arrProduct[i]!=null && arrProduct[i]!="")
			{
				prd.getItem9(arrProduct[i]);
				prd.price = psCleanPrice(prd.price);
				if(parseFloat(prd.price)> 0)
				{	
					flg_order_tag = true;
					psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
				}				
			}
		}
	}
	else
	{
		var pTextGoogle = psGetValueFromGooGleAnalys();
		if(pTextGoogle != null && pTextGoogle != ""){
			for(var k=1; k< pTextGoogle.length; k++){
				prd.getItem9(pTextGoogle[k]);
				prd.price = psCleanPrice(prd.price);				
				if(parseFloat(prd.price) > 0)
				{	
					flg_order_tag = true;
					psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
				}
			}
		}
	}
	
	psDisplayShop9s();	
	if(!(parseFloat(ord.subtotal) == 0 && flg_order_tag == false))
	{	
		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_FLAG, "", "delete");
	psSetCookie(G_PS_COOKIE_SKU, "", "delete");
}

function psHijackSetPrimaryBilling()
{
	var pnlAdd = document.getElementById("pnlAddressListBottom");
	if(psCheckElementExist(pnlAdd))
	{
		var lstLi = pnlAdd.getElementsByTagName("li");
		if(psCheckArrayExist(lstLi))
		{
			for(var i=0;i< lstLi.length;i++)
			{
				if(lstLi[i].innerHTML.toLowerCase().indexOf("btnmakeprimary") < 0 && lstLi[i].innerHTML.toLowerCase().indexOf("lnkaddaddress") < 0)
				{
					var lstInput = lstLi[i].getElementsByTagName("input");
					if(psCheckArrayExist(lstInput))
					{
				
						for(var j=0;j<lstInput.length;j++)
						{
							if(lstInput[j].src && lstInput[j].src.search(/\/images\/edit2\.gif/gi) > -1)
							{
								lstInput[j].oldCMFunc = lstInput[j].onclick;
								lstInput[j].onclick = function()
								{
									psSetCookie(G_PS_COOKIE_FLAG_BILLING,"primary");
									if (this.oldCMFunc != null)
										return this.oldCMFunc();
								}	
							}
						}
					}
				}
			}
		}
	}
}

function psHijackChangePrimaryBilling()
{
	var pnlAdd = document.getElementById("pnlAddressListBottom");
	if(psCheckElementExist(pnlAdd))
	{
		var lstLi = pnlAdd.getElementsByTagName("li");
		if(psCheckArrayExist(lstLi))
		{
			for(var i=0;i< lstLi.length;i++)
			{
				if(lstLi[i].innerHTML.toLowerCase().indexOf("btnmakeprimary") > -1 && lstLi[i].innerHTML.toLowerCase().indexOf("lnkaddaddress") < 0)
				{
					var lstInput = lstLi[i].getElementsByTagName("input");
					if(psCheckArrayExist(lstInput))
					{
				
						for(var j=0;j<lstInput.length;j++)
						{
							if(lstInput[j].src && lstInput[j].src.search(/\/images\/usethisbillingaddress\.gif/gi) > -1)
							{
								lstInput[j].oldCMFunc = lstInput[j].onclick;
								lstInput[j].onclick = function()
								{
									psSetCookie(G_PS_COOKIE_FLAG_BILLING,"change primary");
									if (this.oldCMFunc != null)
										return this.oldCMFunc();
								}	
							}
						}
					}
				}
				
			}
		}
		
	}
}


function psHijackDeleteAdd()
{
	var btnDelete = document.getElementById("btnDeleteAddress");
	if(psCheckElementExist(btnDelete))
	{
		if (btnDelete.value && btnDelete.value.toLowerCase() == "delete this address")
		{
			btnDelete.oldCMFunc = btnDelete.onclick;
			btnDelete.onclick = function()
			{
				psSetCookie(G_PS_COOKIE_BILLING,"","delete");
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				if (this.oldCMFunc != null)
					return this.oldCMFunc();
			}	
		}
	}
}

function psHijackUpdateBillingAdd()
{
	var city = null;
	var state = null;
	var zipcode = null;
	var add = null;
	var frmEditAdd = document.getElementById("Form1");
	if(psCheckElementExist(frmEditAdd))
	{
		if (frmEditAdd.name && frmEditAdd.name.toLowerCase() == "form1")
		{
			frmEditAdd.oldCMFunc = frmEditAdd.onsubmit;
			frmEditAdd.onsubmit = function()
			{
				city = psGetElementValueById("txtCity");
				state = psGetElementValueById("txtState");
				zipcode = psGetElementValueById("txtZip");
				add = city + "-_-" + state + "-_-" + zipcode;
				psSetCookie(G_PS_COOKIE_BILLING,add);
				psSetCookie(G_PS_COOKIE_FLAG,"update address");
				if (this.oldCMFunc != null)
					return this.oldCMFunc();
			}	
		}
	}

}

function psGetBillingAddFromCookie()
{
	try
	{
		var sAddress = psGetCookie(G_PS_COOKIE_BILLING);
		if (psCheckElementExist(sAddress))
		{
			var uP = new psProfile();
			if(uP.readProfile())
			{
				var buf = sAddress.split("-_-");
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				uP.city = buf[0];
				uP.state = buf[1];
				uP.zipcode = buf[2];
				psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
				uP.writeProfile();
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
			}
		}
		return true;
	}
		catch (ex) { return false; }
}

function psGetBillingAddFromSite()
{
	var pnlAdd = document.getElementById("pnlAddressListBottom");
	if(psCheckElementExist(pnlAdd))
	{
		var lstLi = pnlAdd.getElementsByTagName("li");
		if(psCheckArrayExist(lstLi))
		{
			for(var i=0;i< lstLi.length;i++)
			{
				if(lstLi[i].innerHTML.toLowerCase().indexOf("btnmakeprimary") < 0 && lstLi[i].innerHTML.toLowerCase().indexOf("lnkaddaddress") < 0)
				{
					var lstBr = lstLi[i].innerHTML.toLowerCase().split("<br");
					if(psCheckArrayExist(lstBr))
					{
						var uP = new psProfile();
						if(uP.readProfile())
						{
							if(uP.city == null || uP.city == "null" || uP.city == "" || psGetCookie(G_PS_COOKIE_FLAG_BILLING) == "change primary")
							{
								var sPos = -1;
								for(var j=lstBr.length -1;j>=0;j--)
								{
									var sTemp = psCleanHtmlTag(lstBr[j]);
									sTemp = sTemp.replace(/[<>]/gi,"")
									if(psTrim(sTemp) != "")
									{
										sPos = 	j;	
										break;
									}
									
								}
								if(sPos != -1 && sPos > 2)
								{
									uP.city = lstBr[sPos - 2].replace(/>/gi,"");
									uP.city = psTrim(uP.city);
									uP.zipcode =  lstBr[sPos - 3].replace(/>/gi,"");
									uP.zipcode = psTrim(uP.zipcode);
									uP.state = null;
									uP.writeProfile();
									psGetCookie(G_PS_COOKIE_FLAG_BILLING,"","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!
			
			this.id = psGetProductId(G_PS_URL_PATH);
			this.name = psGetProductName();
			var sCatId = psGetCookie(G_PS_COOKIE_CATID);
			if(G_PS_URL_REFERRER == "" && psCheckElementExist(sCatId) == false) 
			{
				this.catId = "BOOKMARK";
			}
			else if(G_PS_URL_REFERRER.indexOf("shoppingcart.asp") > -1
					|| G_PS_URL_REFERRER.indexOf("/checkoutreview.aspx") > -1)
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id.toLowerCase());
			else if(sCatId.toLowerCase() == "search" || sCatId.toLowerCase() == "recommend products" || sCatId.toLowerCase() == "gift list")
				this.catId = sCatId;
			else 
				this.catId = psGetProCatFromCrumb();
			if(this.catId == null)
				this.catId = sCatId;
			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!
			var proLink = itemRow.cells[0].getElementsByTagName("a");
			if(psCheckArrayExist(proLink))
			{
				this.id = psGetProductId(proLink[0].href)
			}
			proLink = itemRow.cells[1].getElementsByTagName("a");
			if(psCheckArrayExist(proLink))
			{
				this.name = psTrim(psCleanHtmlTag(psHtmlDecode(proLink[0].innerHTML)));
			}
			this.price = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[2].innerHTML)));
			var oSelect = itemRow.cells[3].getElementsByTagName("select");
			if(psCheckArrayExist(oSelect))
			{
				this.quantity = psGetElementValue(oSelect[0]);
				this.quantity = psTrim(psCleanHtmlTag(psHtmlDecode(this.quantity )));
			}
			else 
			{
				var oInput = itemRow.cells[3].getElementsByTagName("input");
				if(psCheckArrayExist(oInput))
				{
					this.quantity = psTrim(psCleanHtmlTag(psHtmlDecode(oInput[0].value)));
					
				}
			}
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			var price = psCleanPrice(this.price);
			if(psIsNumber(this.price))
			{
				price = parseFloat(price);
			}
			if(this.name.toLowerCase().indexOf("magazine") > -1 && price == 0)
			{
				this.catId = this.name;	
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId );
			}
			if(this.catId == null || this.catId == "")
			{
				this.catId = "Unknown";
			}
			
			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!
			if(itemRow.search(",") >= 0){
				itemRow = itemRow.split(",");
				this.id = psTrim(unescape(itemRow[1]));
				this.id = psReplaceCommon(this.id);
					
				this.name = psTrim(unescape(itemRow[2]));
				this.name = psReplaceCommon(this.name);
				
				var pSKU = psTrim(psHtmlDecode(this.id.toLowerCase()));
				var pCAT_QUANT = psGetValueFromCookie(G_PS_COOKIE_SKU, pSKU);
				
				if(pCAT_QUANT != null && pCAT_QUANT != ""){
					this.catId = pCAT_QUANT.split("-_-")[0];
					this.quantity = pCAT_QUANT.split("-_-")[1];
				}
				else{
					this.catId = psTrim(unescape(itemRow[3]));
					this.catId = psReplaceCommon(this.catId);
				}
				if(this.catId == null || this.catId == ""){
					this.catId = psGetValueFromCookie(G_PS_COOKIE_SHOP9,itemRow);
					if(this.catId != null && this.catId!= ""){
						this.catId = this.catId.split("|")[4];
					}
				}
							
				if(this.quantity == null || this.quantity == ""){
					this.quantity = psTrim(itemRow[5]);
					this.quantity = itemRow[5].replace(/\;/,"");
					this.quantity = this.quantity.replace(/\)/,"")
					this.quantity = psReplaceCommon(psTrim(unescape(this.quantity)));
				}
				
				this.price = psTrim(unescape(itemRow[4]));
				this.price = psReplaceCommon(this.price);
				if(parseFloat(this.quantity) >= 2){
					this.price = Math.round(parseFloat(this.price)/parseFloat(this.quantity));
				}
			}
			if(this.id == null ||this.name == null ||this.quantity == null
			|| this.price == null || this.catId == null){
				var strValue = psGetValueFromCookie(G_PS_COOKIE_SHOP9,itemRow);	
				if(strValue)
				{
					var arrValue = 	strValue.split("|");
					this.id = arrValue[0]; 	
					this.name = arrValue[1]; 
					this.quantity =  arrValue[2]; 
					this.price =  arrValue[3]; 
					this.catId = arrValue[4];
				}
			}
			if(this.catId == null || this.catId == "")
			{
				this.catId = "Unknown";
			}
			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];
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			if(this.cusId == "" || this.cusId == null)
			{
				this.cusId = psGenerateRandomValue();
			}
			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 pValue = psGetCookie(G_PS_COOKIE_ORDER);
			if(pValue != null && pValue != "")
			{
				this.id = psGetValueFromUrl(G_PS_URL_PATH,"ordernumber");
				var arrValue = 	pValue.split(":");
				this.subtotal = arrValue[0] == "null"?null:arrValue[0];
				this.shipping = arrValue[1] == "null"?null:arrValue[1];
			} 
			else
			{
				var pTextGoogle = psGetValueFromGooGleAnalys();
				var pOrder = pTextGoogle[0]; 
				if(pOrder != null){
					pOrder = pOrder.split(",");
					this.id = psTrim(psHtmlDecode(unescape(pOrder[0].replace(/^\(/, ""))));
					this.id = psReplaceCommon(this.id);
					
					this.subtotal = psTrim(psHtmlDecode(unescape(pOrder[2])));
					this.subtotal = psReplaceCommon(this.subtotal);
					
					this.shipping = psTrim(psHtmlDecode(unescape(pOrder[4])));
					this.shipping = psReplaceCommon(this.shipping);
					
					this.subtotal = Math.round(parseFloat(this.subtotal) - parseFloat(this.shipping));
				}
			}
			if(this.id == "" || this.id == null)
			{
				this.id = psGenerateRandomValue();
			}
			return true;
		}
		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, ">");
    }

    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: Remove all HTML tags in a string
 * RETURN: string
 */
function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : 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;
}

function psCookieBase(pCookieName, pCookieValue, pLifeTime)
{
	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
	if(pLifeTime == "delete") 
	{         
		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);
}

function encodeHtml(strValue)
{
	if (strValue!=null)
	{
		strValue = escape(strValue);
		strValue = strValue.replace(/\//g,"%2F");
		strValue = strValue.replace(/\?/g,"%3F");
		strValue = strValue.replace(/=/g,"%3D");
		strValue = strValue.replace(/&/g,"%26");
		strValue = strValue.replace(/@/g,"%40");
	}
	return strValue;
}

/* 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;
	}
	
	pCookieValue = (pCookieValue==null)? "null":pCookieValue;
	
	if(pLifeTime != "delete")
	{
		pCookieName = psTrim(pCookieName);
		var oldCookieValue = psGetCookie(pCookieName);
		oldCookieValue = (oldCookieValue==null)? "null":oldCookieValue;
		var totalSize;
		if(document.cookie.indexOf(pCookieName)>-1)
		{
			totalSize =  document.cookie.length + encodeHtml(pCookieValue).length - encodeHtml(oldCookieValue).length;
		}
		else
		{
			totalSize =  document.cookie.length  + encodeHtml(pCookieValue).length + encodeHtml(pCookieName).length;
		}
		if(totalSize > 3500)
		{
			return false;
		}
	}
	psCookieBase(pCookieName,pCookieValue,pLifeTime);
}

/* 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)
{
	if (!pCookieName || !pKey)
	{
		return false;
	}

	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;
	pValue = (pValue == null) ? "null" : pValue;
	var oldCatCookie = catCookie;
	
	var start = catCookie.indexOf(pKey);
	
	var totalsize;
	if (start >= 0) // Store before -> remove the old value
	{
		var oldValue = psGetValueFromCookie(pCookieName,pKey.replace(/[\~\#]/gi,""));
		oldValue = (oldValue == null) ? "null" : oldValue;
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1)
			end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length - encodeHtml(oldValue).length;
	}
	else
	{
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length;  
		if(document.cookie.indexOf(pCookieName)<0)
		{
			totalsize += encodeHtml(pCookieName).length;
		}
	}
	catCookie = pKey + pValue + catCookie;
	var cookieArray = null;   
	//Check existed ?
	while (totalsize > 3500)
	{
		var l1 = encodeHtml(catCookie).length;//length before pop
		cookieArray = catCookie.split("#");
		cookieArray.pop();
		catCookie = cookieArray.join("#");
		var l2 = encodeHtml(catCookie).length;//length after pop                                                        
		totalsize -=  (l1-l2);
	}   
	if(catCookie == null || catCookie == "")
	{
		catCookie = oldCatCookie;
	}
	// Save to cookie              
	psCookieBase(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

/* 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;
}

function psShorttenPageID(pLink)
{
	var temp1 = pLink;
	if (temp1 != null)
	{
		temp1 = (temp1.length > 255) ? temp1.substr(0, 255) : temp1;
	}
	return temp1;
}
/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(pId);
	pId = psShorttenPageID(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId) 
{
	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);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId);    
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
	pOrderTotal = psCleanPrice(pOrderTotal);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCusID + ", " + pOrderID + ", " + pOrderTotal + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId);
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip) 
{
	pOrderTotal = psCleanPrice(pOrderTotal);
	pOrderShipping = psCleanPrice(pOrderShipping);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + pId + ", " + pOrderTotal + ", " + pOrderShipping + ", " + pCusID + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip);
}

function psCreateConversionEventTag(pId, pActionType, pCatID, pPoints) 
{
	pCatID = psCleanCatId(pCatID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + pId + ", " + pActionType + ", " + pCatID + ", " + pPoints + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(pId, pActionType, pCatID, pPoints);
}

function psCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pNewsletter + ", " + pSubscribe + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe);
}

function psCreateErrorTag(pPageID, pCatId) 
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateErrorTag(" + pPageID + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateErrorTag(pPageID, pCatId);
}

function psDisplayShop5s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop5s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop5s();
}

function psDisplayShop9s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop9s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop9s();
}
/*===========================END GENERAL UTILITY FUNCTION ==================*/
