/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.3, 2010/03/24
 * 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("mycatwalk.com.au");//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
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var G_PS_COOKIE_ORDER	= "PS_ORDER";
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if(G_PS_URL_PATH.search(/mycatwalk\.com\.au/i) > -1)
{	
	window.setInterval("psHijackPrdInQuickBasket()","1000");
	window.setInterval("psHijackPrdInQuickWishList()","1000");
	if(psIsEqual(G_PS_PATHNAME,"/") || psIsEqual(G_PS_PATHNAME,"/index.html"))
	{
		psCreatePageviewTag("Home","Home");
	}
	else if(psIsWishListLogin())
	{
		psCreatePageviewTag("WISHLIST LOGIN","WISHLIST",null,null);
		psHijackLoginBtn();
		psHijackNewCus();
	}
	else if(G_PS_PATHNAME == "/products/customers/wishlist.php")
	{
		if(psGetCookie(G_PS_COOKIE_FLAG) == "login" || psGetCookie(G_PS_COOKIE_FLAG) == "register")
		{
			psPostRegistration();
		}
		psCreatePageviewTag("WISHLIST","WISHLIST");
		psHijackWishList();
	}
	else if(G_PS_PATHNAME.search(/\/products\/shop\/checkout\.php/gi) > -1)
	{
		var sCatId = "CHECKOUT"
		var sCheckStep = psGetCheckoutSteps();
		sCheckStep = sCheckStep.toLowerCase();
		if(psCheckElementExist(sCheckStep))
		{
			switch (sCheckStep)
			{
				case "welcome":
				{
					psCreatePageviewTag("CHECKOUT:EMAIL",sCatId,null,null);
					psHijackWelcomeCheckout();
				}
				break;
				case "delivery details":
				{
					if(psGetCookie(G_PS_COOKIE_FLAG) && psGetCookie(G_PS_COOKIE_FLAG) == "checkout signin")
					{
						psPostRegistration();
					}
					var pageTitle = psGetTypeOfAddressPages(); 
					if(pageTitle == "delivery")
					{
						psCreatePageviewTag("CHECKOUT:SHIPPING",sCatId,null,null);
						if(psIsAlsoTheBilling())
						{
							psHijackDeliveryAddress();
						}
					}
					else if(pageTitle == "billing")
					{
						psCreatePageviewTag("CHECKOUT:BILLING",sCatId,null,null);
						psHijackBillingAddress();
					}
				}
				break;
				case "delivery options":
				{
					psCreatePageviewTag("CHECKOUT:Delivery Options",sCatId,null,null);
					if(psGetCookie(G_PS_COOKIE_FLAG) == "user address"
						||psGetCookie(G_PS_COOKIE_FLAG) == "address")
					{
						psPostRegistration();
					}
				}
				break;
				case "order summary":
				{
					psCreatePageviewTag("CHECKOUT:REVIEW",sCatId,null,null);
					if(psGetCookie(G_PS_COOKIE_FLAG) == "user address"
						||psGetCookie(G_PS_COOKIE_FLAG) == "address")
					{
						psPostRegistration();
					}
					psHijackReviewCheckOut();
				}
				break;
				case "payment":
				{
					psSetOrderToCookie();
					psCreatePageviewTag("CHECKOUT:PAYMENT",sCatId,null,null);
					psHijackPaymentCheckout();
				}
				break;
			}
		}
	}
	else if(G_PS_PATHNAME == "/pages/fashion-newsletter.html")
	{
		var pageId = psGetPageName();
		var catId = psGetPageName();
		psCreatePageviewTag(pageId,catId,null,null);
		psHijackRegNewsletter();
	}
	else if(G_PS_PATHNAME == "/pages/thankyou-cat.html")
	{	
		var pageId = psGetPageName();
		var catId = psGetPageName();
		psCreatePageviewTag(pageId,catId,null,null);
		if(psGetCookie(G_PS_COOKIE_FLAG) && psGetCookie(G_PS_COOKIE_FLAG) == "reg newsletter" && G_PS_URL_REFERRER.search(/\/pages\/fashion\-newsletter\.html/gi) >-1)
		{
			psPostRegistration();
		}
	}
	else if (psIsSearchView())
	{
		psPostSearchView();
	}
	else if (psIsProductView())
	{
		var prd = new psProduct();
		if (prd.getProduct()) // Get product info successfully?
		{
			psCreateProductviewTag(prd.id, prd.name, prd.catId);
		}
		psHijackAddToBasket(psGetCookie(G_PS_COOKIE_CATID));
		psHijackSuggestedPrd();
	}
	else if (psIsCartView())
	{
		psCreatePageviewTag("BASKET", "BASKET", null);
		psPostCartView();
		psHijackPrdInBasket();
		psHijackCheckOut();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else 
	{	
		psPostPageView();
	}
}

function psIsWishListLogin()
{
	var divItem = document.getElementById("myContent");
	if(psCheckElementExist(divItem))
	{
		var imgList = divItem.getElementsByTagName("img");
		for(var i =0; i<imgList.length; i++)
		{
			var imgItem = imgList[i];
			if(typeof(imgItem.alt)!="undefined" && imgItem.alt!=null)
			{
				var se = /May\s*All\s*Your\s*Wihes\s*Come\s*True/gi;
				if(imgItem.alt.search(se)>-1)
				{
					return true;
				}
			}
		}
	}
	return false;
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	if(G_PS_PATHNAME == "/products/pages/search.php")
	{
		return true;
	}
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	if(psCheckElementExist(document.getElementById("myproducts")))
	{
		return true;
	}
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_PATHNAME == "/products/shop/basket.php")
	{
		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
	//
	if(G_PS_PATHNAME == "/products/shop/thanks_order.php")
	{
		return true;
	}
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psHijackPrdInQuickWishList()
{
	var divList = psGetElementsByClassName(document,"div","aCol1");
	for(var i =0; i<divList.length; i++)
	{
		var imgList = divList[i].getElementsByTagName("img");
		for(var j =0; j<imgList.length; j++)
		{
			if(psCheckElementExist(imgList[j].onclick)==false || imgList[j].onclick.toString().indexOf("psSetCookie")==-1)
			{
				imgList[j].oldCMF = imgList[j].onclick;
				imgList[j].onclick = function ()
				{
					psSetCookie(G_PS_COOKIE_CATID,"WISHLIST");
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
		}
	}
	divList = psGetElementsByClassName(document,"div","aCol2");
	for(var i =0; i<divList.length; i++)
	{
		var aList = divList[i].getElementsByTagName("a");
		for(var j =0; j<aList.length; j++)
		{
			if(psCheckElementExist(aList[j].onclick)==false || aList[j].onclick.toString().indexOf("psSetCookie")==-1)
			{
				aList[j].oldCMF = aList[j].onclick;
				aList[j].onclick = function ()
				{
					psSetCookie(G_PS_COOKIE_CATID,"WISHLIST");
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
		}
	}
	
	divList = psGetElementsByClassName(document,"div","aCol3");
	for(var i =0; i<divList.length; i++)
	{
		var aList = divList[i].getElementsByTagName("a");
		for(var j =0; j<aList.length; j++)
		{
			if(psCheckElementExist(aList[j].onclick)==false || aList[j].onclick.toString().indexOf("this.parentNode")==-1)
			{
				aList[j].oldCMF = aList[j].onclick;
				aList[j].onclick = function ()
				{
					var divItem = this.parentNode;
					var cont = true;
					while (!psIsEqual(divItem.tagName,"body") && cont)
					{
						divItem = divItem.parentNode;
						if(psIsEqual(divItem.tagName,"div"))
						{
							if(typeof(divItem.className)!="undefined" && divItem.className!=null && psIsEqual(divItem.className,"aList"))
							{
								cont = false;
							}
						}
					}
					divItem = psGetElementsByClassName(divItem,"div","aCol2");
					if(psCheckArrayExist(divItem))
					{
						divItem = divItem[0];
						var aItem = divItem.getElementsByTagName("a");
						if(psCheckArrayExist(aItem))
						{
							aItem = aItem[0];
							var prdId = psGetInnerText(aItem);
							if(prdId!=null)
							{
								psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prdId,"WISHLIST");
							}
						}
					}
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
		}
	}
}

function psHijackWishList()
{
	var imgList = document.getElementsByTagName("img");
	var imgItem = null;
	for(var i =0; i<imgList.length; i++)
	{
		imgItem = imgList[i];
		if(imgItem.src.toLowerCase().indexOf("buynow3.gif")>-1)
		{
			imgItem.oldCMF = imgItem.onclick;
			imgItem.onclick = function ()
			{
				var prdId = null;
				var frmItem = this.parentNode;
				while (!psIsEqual(frmItem.tagName,"body") && !psIsEqual(frmItem.tagName,"form"))
				{
					frmItem = frmItem.parentNode;
				}
				if(psIsEqual(frmItem.tagName,"form"))
				{
					var spanList = psGetElementsByClassName(document,"span","Helv12");
					if(psCheckArrayExist(spanList))
					{
						prdId = psGetInnerText(spanList[0]);
					}
				}
				if(prdId != null)
				{
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prdId,"WISHLIST");
				}
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
	}
}

function psHijackPrdInQuickBasket()
{
	var divList = psGetElementsByClassName(document,"div","bCol1");
	for(var i =0; i<divList.length; i++)
	{
		var imgList = divList[i].getElementsByTagName("img");
		for(var j =0; j<imgList.length; j++)
		{
			if(psCheckElementExist(imgList[j].onclick)==false || imgList[j].onclick.toString().indexOf("psSetCookie")==-1)
			{
				imgList[j].oldCMF = imgList[j].onclick;
				imgList[j].onclick = function ()
				{
					psSetCookie(G_PS_COOKIE_FLAG,"FromShopCart");
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
		}
	}
	
	divList = psGetElementsByClassName(document,"div","bCol2");
	for(var i =0; i<divList.length; i++)
	{
		var aList = divList[i].getElementsByTagName("a");
		for(var j =0; j<aList.length; j++)
		{
			if(psCheckElementExist(aList[j].onclick)==false || aList[j].onclick.toString().indexOf("psSetCookie")==-1)
			{
				aList[j].oldCMF = aList[j].onclick;
				aList[j].onclick = function ()
				{
					psSetCookie(G_PS_COOKIE_FLAG,"FromShopCart");
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
		}
	}
}

function psHijackPaymentCheckout()
{
	var aItem = psGetElementsByClassName(document,"a","continueCheckout");
	if(psCheckArrayExist(aItem))
	{
		aItem = aItem[0];
		aItem.oldCMF = aItem.onclick;
		aItem.onclick = function()
		{
			psPostCartViewAtReview();
			if(psCheckElementExist(this.oldCMF))
			{
				return this.oldCMF();
			}
		}
	}
}

function psPostCartViewAtReview()
{
	var divItem = document.getElementById("reviewBasket");
	if(psCheckElementExist(divItem))
	{
		var prdIdList = new Array();
		var priceList = new Array();
		var quantityList = new Array();
		var aList = psGetElementsByClassName(divItem,"a","productLink");
		for(var i =0; i<aList.length; i++)
		{
			prdIdList.push(psGetInnerText(aList[i]));
		}
		var inputList = psGetElementsByClassName(divItem,"input","bQty");
		for(var i =0; i<inputList.length; i++)
		{
			quantityList.push(psGetElementValue(inputList[i],true));
		}
		var cellList = psGetElementsByClassName(divItem,"td","h11dark");
		for(var i =0; i<cellList.length; i++)
		{
			var price = psTrim(psCleanHtmlTag(psHtmlDecode(cellList[i].innerHTML)));
			price = psCurrencyEx(price);
			priceList.push(price);
		}
		if(prdIdList.length == quantityList.length
			&& priceList.length > prdIdList.length
			&& prdIdList.length>0)
		{
			for(var i =0; i<prdIdList.length; i++)
			{
				psCreateShopAction5Tag(prdIdList[i],prdIdList[i],quantityList[i],priceList[i]/quantityList[i],psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,prdIdList[i]));
			}
			psDisplayShop5s();
		}
	}
}

function psHijackReviewCheckOut()
{
	var aList = psGetElementsByClassName(document,"a","continueCheckout");
	for(var i =0; i<aList.length; i++)
	{
		aList[i].oldCMF = aList[i].onclick;
		aList[i].onclick = function()
		{
			psPostCartViewAtReview();
			if(psCheckElementExist(this.oldCMF))
			{
				return this.oldCMF();
			}
		}
	}
	var aList = psGetElementsByClassName(document,"a","continueCheckoutWhite");
	for(var i =0; i<aList.length; i++)
	{
		aList[i].oldCMF = aList[i].onclick;
		aList[i].onclick = function()
		{
			psPostCartViewAtReview();
			if(psCheckElementExist(this.oldCMF))
			{
				return this.oldCMF();
			}
		}
	}
}

function psHijackCheckOut()
{
	var divItem = document.getElementById("myContent");
	if(psCheckElementExist(divItem))
	{
		var imgList = divItem.getElementsByTagName("img");
		for(var i =0; i<imgList.length; i++)
		{
			if(imgList[i].src.toLowerCase().indexOf("checkoutnow.gif")>-1)
			{
				imgList[i].oldCMF = imgList[i].onclick;
				imgList[i].onclick = function()
				{
					psPostCartView();
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
				break;
			}
		}
	}
}

function psHijackSuggestedPrd()
{
	var divItem = document.getElementById("suggestionlisting");
	if(psCheckElementExist(divItem))
	{
		var aList = divItem.getElementsByTagName("a");
		var aItem = null;
		for(var i =0; i<aList.length; i++)
		{
			aItem = aList[i];
			aItem.oldCMF = aItem.onclick;
			aItem.onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,"Recently Viewed");
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
	}
}

function psHijackPrdInWishList()
{
	var frmList = document.getElementsByTagName("form");
	var frmItem = null;
	for(var i =0; i<frmList.length; i++)
	{
		frmItem = frmList[i];
		if(frmItem.action.search(/products\/includes\/add_product\.php/gi)>-1)
		{}
	}
}

function psHijackPrdInBasket()
{
	var divItem = document.getElementById("myBasket");
	if(psCheckElementExist(divItem))
	{
		var aList = divItem.getElementsByTagName("a");
		for(var i =0; i<aList.length; i++)
		{
			var aItem = aList[i];
			aItem.oldCMF = aItem.onclick;
			aItem.onclick = function()
			{
				psSetCookie(G_PS_COOKIE_FLAG,"FromShopCart");
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
	}
}

function psHijackAddToBasket(catId)
{
	var imgItem = document.getElementById("img17");
	if(psCheckElementExist(imgItem))
	{
		var aItem = imgItem.parentNode;
		while (!psIsEqual(aItem.tagName,"body") && !psIsEqual(aItem.tagName,"a"))
		{
			aItem = aItem.parentNode;
		}
		if(psIsEqual(aItem.tagName,"a"))
		{
			aItem.oldCMF = aItem.onclick;
			aItem.onclick = function()
			{
				var divItem = document.getElementById("breadcrumb");
				if(psCheckElementExist(divItem))
				{
					var h1List = divItem.getElementsByTagName("h1");
					if(psCheckArrayExist(h1List))
					{
						var prdId = psGetInnerText(h1List[0]);
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prdId,catId);
					}
				}
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
	}
}

function psGetPageName()
{
	var pageName = G_PS_PATHNAME;
	var se = /\/([^\/]*)$/gi;
	if(pageName.search(se)>-1)
	{
		pageName = RegExp.$1;
		pageName = psHtmlDecode(pageName);
		pageName = pageName.replace(/(\.html|\.php)/gi,"");
	}
	return pageName;
}

function psPostPageView()
{
	var pageId = null;
	var catId = null;
	pageId = catId = psGetPageName();
	if(psIsEqual(pageId,"about_mycatwalk"))
	{
		pageId = catId = "FASHION_NEWSLETTER";
	}
	else if(psIsEqual(pageId,"help_main"))
	{
		pageId = catId = "HELP_CENTRE";
	}
	else if(psIsEqual(pageId,"contact_new"))
	{
		pageId = catId = "CONTACT_FRAMESET";
	}
	else if(G_PS_QUERYSTRING.indexOf("mypage")>-1)
	{
		pageId = pageId + ":mypage=" + psGetValueFromUrl(G_PS_QUERYSTRING,"mypage")
	}
	if(catId == null || catId == "")
	{
		catId = "ADD URL";// Other pages go to "ADD URL" category
	}
	if(pageId == null || pageId == "")
	{
		pageId = G_PS_PATHNAME;
	}
	psCreatePageviewTag(pageId,catId);
	psSetCookie(G_PS_COOKIE_CATID,catId);
}

function psTestPostOrderView()
{
	var uP = new psProfile();
	uP.email = uP.cusId = "test@yahoo.com";
	uP.writeProfile();
	psSetCookie(G_PS_COOKIE_ORDER,"120-_-36");
	psPostOrderView();
}

function psHijackLoginBtn()
{
	var frmItem = document.getElementsByName("login");
	if(psCheckArrayExist(frmItem))
	{
		frmItem = frmItem[0];
		frmItem.oldCMF = frmItem.onsubmit;
		frmItem.onsubmit = function()
		{
			var lstInputs = this.getElementsByTagName("input");
			if(psCheckArrayExist(lstInputs))
			{
				for(var i=0;i<lstInputs.length;i++)
				{
					if(lstInputs[i].name && lstInputs[i].name == "email")
					{
						var email = lstInputs[i].value;
						var uP = new psProfile();
						if(psCheckEmail(email)) //login with email
							uP.email = uP.cusId = email;
						uP.writeProfile();				
						psSetCookie(G_PS_COOKIE_FLAG,"login");				
					}
				}
			}
			if (this.oldCMF != null)
			{
				return this.oldCMF();
			}
		}
	}
	

	var btnLogin = document.getElementById("send1");
	if(psCheckElementExist(btnLogin))
	{
		btnLogin.oldCMFunc = btnLogin.onclick; //backup the existing onclick function
		btnLogin.onclick = function()
		{
			var frmLogin = document.getElementsByName("login");
			if(psCheckArrayExist(frmLogin))
			{
				var lstInputs = frmLogin[0].getElementsByTagName("input");
				if(psCheckArrayExist(lstInputs))
				{
					for(var i=0;i<lstInputs.length;i++)
					{
						if(lstInputs[i].name && lstInputs[i].name == "email")
						{
							var email = lstInputs[i].value;
							var uP = new psProfile();
							if(psCheckEmail(email)) //login with email
								uP.email = uP.cusId = email;
							uP.writeProfile();				
							psSetCookie(G_PS_COOKIE_FLAG,"login");				
						}
					}
				}
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}
	}
}

function psHijackNewCus()
{
	var btnSend = document.getElementById("imgsend2");
	if(psCheckElementExist(btnSend))
	{
		btnSend.oldCMFunc = btnSend.onclick; //backup the existing onclick function
		btnSend.onclick = function()
		{
			var frmLogin = document.getElementsByName("login_new");
			if(psCheckArrayExist(frmLogin))
			{
				var lstInputs = frmLogin[0].getElementsByTagName("input");
				if(psCheckArrayExist(lstInputs))
				{
					for(var i=0;i<lstInputs.length;i++)
					{
						if(lstInputs[i].name && lstInputs[i].name == "email")
						{
							var email = lstInputs[i].value;
							var uP = new psProfile();
							if(psCheckEmail(email)) //login with email
								uP.email = uP.cusId = email;
							uP.writeProfile();				
							psSetCookie(G_PS_COOKIE_FLAG,"register");						
						}
					}
				}
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}
	}
}

function psHijackWelcomeCheckout()
{
	var btnContinue= psGetElementsByClassName(document,"a","continueCheckout");
	if(psCheckArrayExist(btnContinue))
	{
		btnContinue[0].oldCMFunc = btnContinue[0].onclick; //backup the existing onclick function
		btnContinue[0].onclick = function()
		{
			var email = document.getElementById("email");
			if(psCheckElementExist(email))
			{
				var uP = new psProfile();
				if(psCheckEmail(email.value)) //login with email
					uP.email = uP.cusId = email.value;
				uP.writeProfile();				
				psSetCookie(G_PS_COOKIE_FLAG,"checkout signin");
			}			
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}
	}
	
	var frmItem = document.getElementsByName("login");
	if(psCheckArrayExist(frmItem))
	{
		frmItem = frmItem[0];
		frmItem.oldCMF = frmItem.onsubmit;
		frmItem.onsubmit = function()
		{
			var temp = psGetElementValueById("email");
			if(temp!=null && temp!="")
			{
				var uP = new psProfile();
				uP.email = uP.cusId = temp;
				uP.writeProfile();				
				psSetCookie(G_PS_COOKIE_FLAG,"checkout signin");
			}
			if (this.oldCMF != null)
			{
				return this.oldCMF();
			}
		}
	}
}

function psGetCheckoutSteps()
{
	var sStep = null;
	var divStep = document.getElementById("checkoutSteps");
	if(psCheckElementExist(divStep))
	{
		var navOver = psGetElementsByClassName(divStep,"a","checkoutNavOver");
		if(psCheckArrayExist(navOver))
		{
			sStep = psTrim(psHtmlDecode(psCleanHtmlTag(navOver[0].innerHTML)));
		}
	}
	return sStep;
}

function psHijackDeliveryAddress()
{
	var btnContinue= psGetElementsByClassName(document,"a","continueCheckout");
	if(psCheckArrayExist(btnContinue))
	{
		btnContinue[0].oldCMFunc = btnContinue[0].onclick; //backup the existing onclick function
		btnContinue[0].onclick = function()
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			if(uP.cusId != null)
			{
				uP.city = psGetElementValueById("DlyCity",true);
				uP.state =  psGetElementValueById("DlyRegion",true);
				uP.zipcode = psGetElementValueById("DlyZip",true);	
				uP.country = psGetElementValueById("DlyCountry",false);
				uP.writeProfile();				
				psSetCookie(G_PS_COOKIE_FLAG,"user address");
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}
	}
}

function psHijackBillingAddress()
{
	var btnContinue= psGetElementsByClassName(document,"a","continueCheckout");
	if(psCheckArrayExist(btnContinue))
	{
		btnContinue[0].oldCMFunc = btnContinue[0].onclick; //backup the existing onclick function
		btnContinue[0].onclick = function()
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			if(uP.cusId != null)
			{
				uP.city = psGetElementValueById("DlyCity",true);
				uP.state =  psGetElementValueById("DlyRegion",true);
				uP.zipcode = psGetElementValueById("DlyZip",true);	
				uP.country = psGetElementValueById("DlyCountry",false);
				if(psIsEqual(uP.country,"Other"))
				{
					uP.country = psGetElementValueById("Dlyother",true);
				}
				uP.writeProfile();		
				psSetCookie(G_PS_COOKIE_FLAG,"address");
			}			
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}
	}
}


function psIsAlsoTheBilling()
{
	var sResult = null;
	var lstChecks = document.getElementsByName("billingChk");
	if(psCheckArrayExist(lstChecks))
	{
		for(var i= 0;i< lstChecks.length;i++)
		{
			if(lstChecks[i].checked == true)
			{
				sResult = lstChecks[i].value;
			}
		}
	}
	return (sResult == 1)?true:false;
}

function psGetTypeOfAddressPages()
{
	var divCheckout = document.getElementById("checkoutContent");
	if(psCheckElementExist(divCheckout))
	{
		var sTitle = divCheckout.getElementsByTagName("h3");
		if(psCheckArrayExist(sTitle))
		{
			var sText =  psTrim(psCleanHtmlTag(psHtmlDecode(sTitle[0].innerHTML)));
			if(sText.search(/Delivery\s*Details/gi) >-1)
				return "delivery";
			else if(sText.search(/Billing\s*Details/gi) >-1)
				return "billing";
			
		}
	}
	return null;
}

function psHijackRegNewsletter()
{
	var lstInput = document.getElementsByTagName("input");
	if(psCheckArrayExist(lstInput))
	{
		for(var j=0;j<lstInput.length;j++)
		{
			if(lstInput[j].type &&  lstInput[j].type == "image" && lstInput[j].src.search(/Resources\/sendro\.gif/gi) > -1)
			{
				lstInput[j].oldCMFunc = lstInput[j].onclick;
				lstInput[j].onclick = function()
				{
					var email = psGetElementsByClassName(document,"input","register");
					if(psCheckArrayExist(email))
					var uP = new psProfile();
					if(psCheckEmail(email[0].value)) //login with email
						uP.email = uP.cusId = email[0].value;
					uP.writeProfile();				
					psSetCookie(G_PS_COOKIE_FLAG,"reg newsletter");
				}	
			}
		}
	}
}

function psGetValueByName(pName,pValueFlag)
{
	var lstNames = document.getElementsByName(pName);
	var sText = psGetElementValue(lstNames[0],pValueFlag);
	return (lstNames && lstNames.length >0)?psTrim(sText):"";
}

function psPostRegistration()
{
	var uP = new psProfile();
	uP.readProfile(); // get user profile from cookie
	if(uP.cusId != null)
	{
		psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, uP.country);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
}

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

    return true;
}

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

    return true;
}

function 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;
}
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";
	}
	if (pageId != null)
		psCreatePageviewTag(pageId, sCatId, sTerm, sResult);
	psSetCookie(G_PS_COOKIE_CATID, sCatId);
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = psGetValueFromUrl(G_PS_URL_PATH,"part");
	if(psCheckElementExist(term))
	{
		term = unescape(term);
	}
	else
	{
		var divItem = document.getElementById("Results");
		if(psCheckElementExist(divItem))
		{
			var se = /Sorry,\s*we\s*have\s*no\s*matches\s*with\s*([^\:\<]*)/gi;
			if(divItem.innerHTML.search(se)>-1)
			{
				term = RegExp.$1;
				term = unescape(term);
			}
			else
			{
				divItem = document.getElementById("breadcrumb");
				if(psCheckElementExist(divItem))
				{
					se = /searching:\s*([^\<]*)/gi;
					term = (divItem.innerHTML.search(se)>-1)? RegExp.$1:"";
					term = unescape(term);
				}
			}
		}
	}
	if(term=="")
	{
		term = "All";
	}
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	//
	// TO-Do: Your logic to extract search result goes here
	//
	var divResult = document.getElementById("Results");
	if(psCheckElementExist(divResult))
	{
		if(divResult.innerHTML.search(/Sorry\,\swe\shave\sno\smatches\swith/gi) < 0)
			result = 1;
	}
	
	return result;
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	var cartTbl = null;
	var frmBasket = document.getElementById("basket_update");
	if(psCheckElementExist(frmBasket))
	{
		var lstTable = frmBasket.getElementsByTagName("table");
		if(psCheckArrayExist(lstTable))
			cartTbl = lstTable[0];
	}
	if (cartTbl == null)
		return;
	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		/*
		 * Codes for skipping exceptional rows (rows that don't contain items)
		 */
		if (rows[r].innerHTML.search(/bPrice/gi)<0) // Skip rows not containing item (identified by the term "Item #")
			 continue;
		
		if (prd.getItem5(rows[r]))
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
	}
	// Make sure to have actual postings
	psDisplayShop5s();
}

function psSetOrderToCookie()
{              
	var pSubtotal = 0;
	var pShipping = 0;
	var cartTbl = null;
	var frmBasket = document.getElementById("basket_update");
	if(psCheckElementExist(frmBasket))
	{
		var lstTable = frmBasket.getElementsByTagName("table");
		if(psCheckArrayExist(lstTable))
			cartTbl = lstTable[0];
	}
	if(psCheckArrayExist(cartTbl))
	{
		for(var i=0; i<cartTbl.rows.length; i++)
		{
			var sRows = cartTbl.rows[i];
			for(var j=0;j<sRows.cells.length; j++)
			{
				if(sRows.cells[j].innerHTML.search(/Total/gi) > -1)
				{
					pSubtotal = psTrim(psCleanHtmlTag(psHtmlDecode(sRows.cells[j+1].innerHTML)));
					pSubtotal = psCleanPrice(pSubtotal);
				}
				else if(sRows.cells[j].innerHTML.search(/Includes Delivery/gi) > -1)
				{
					pShipping = psTrim(psCleanHtmlTag(psHtmlDecode(sRows.cells[j+1].innerHTML))) ;
					pShipping  = psCleanPrice(pShipping );
					break;
				}
			}
		}
	}
	var pValueOrder =  pSubtotal + "-_-" + pShipping;  
	psSetCookie(G_PS_COOKIE_ORDER, pValueOrder);                                                        
}

function psGetPostOfCellExist(sTable,sText)
{
	for(var i=0; i<sTable.rows.length; i++)
	{
		var sRows = sTable.rows[i];
		for(var j=0;j<sRows.cells.length; j++)
		{
			if(sRows.cells[j].innerHTML.toLowerCase().indexOf(sText.toLowerCase()) > -1)
			{
				return j;
			}
			
		}
	}
	return -1;
}

function psCurrencyEx(price)
{
	var newPrice = psCleanPrice(price);
	if(price.toLowerCase().indexOf("aud")>-1 && psCheckElementExist(CURRENCY_AUD))
	{
		return newPrice*CURRENCY_AUD;
	}
	else if(price.toLowerCase().indexOf("usd")>-1 && psCheckElementExist(CURRENCY_USD))
	{
		return newPrice*CURRENCY_USD;
	}
	else if(price.toLowerCase().indexOf("gbp")>-1 && psCheckElementExist(CURRENCY_GBP))
	{
		return newPrice*CURRENCY_GBP;
	}
	else if(price.toLowerCase().indexOf("cad")>-1 && psCheckElementExist(CURRENCY_CAD))
	{
		return newPrice*CURRENCY_CAD;
	}
	else if(price.toLowerCase().indexOf("nzd")>-1 && psCheckElementExist(CURRENCY_NZD))
	{
		return newPrice*CURRENCY_NZD;
	}
	return newPrice;
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("THANK YOU", G_PS_CUR_CATID, null);

	var cartTbl = null;
	var divBasket = document.getElementById("reviewBasket");
	if(psCheckElementExist(divBasket))
	{
		var lstTable = divBasket.getElementsByTagName("table");
		if(psCheckArrayExist(lstTable))
			cartTbl = lstTable[0];
	}
	if (cartTbl == null)
		return;
	var postProLink = psGetPostOfCellExist(cartTbl,"productLink")
	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
			{
				/*
				 * Codes for skipping exceptional rows (rows don't contain items)
				 */
				if (rows[r].innerHTML.search(/productLink/gi) < 0) // Skip rows not containing item (identified by the term "Item #")
					continue;
				if (prd.getItem9(rows[r],postProLink))
					psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
			}
			// Make sure to have actual postings
			psDisplayShop9s();
			psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.cusId, uP.city, uP.state, uP.zipcode);
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
			psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
	}
}


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


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* 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("breadcrumb");
			if(psCheckElementExist(divItem))
			{
				var h1List = divItem.getElementsByTagName("h1");
				if(psCheckArrayExist(h1List))
				{
					this.id = this.name = psGetInnerText(h1List[0]);
				}
			}
			if(psIsEqual(psGetCookie(G_PS_COOKIE_FLAG),"FromShopCart"))
			{
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
				psSetCookie(G_PS_COOKIE_CATID,this.catId)
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
			}
			else
			{
				this.catId = psGetCookie(G_PS_COOKIE_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!
			var pLinks = psGetElementsByClassName(itemRow,"a","bName");
			if(psCheckArrayExist(pLinks))
				this.id = psTrim(psCleanHtmlTag(psHtmlDecode(pLinks[0].innerHTML)));
			this.name = this.id;
			var pPrices = psGetElementsByClassName(itemRow,"td","bPrice1");
			if(psCheckArrayExist(pPrices))
			{
				this.price = psTrim(psCleanHtmlTag(psHtmlDecode(pPrices[0].innerHTML)));
				this.price = psCurrencyEx(this.price);
			}
			var pQuantity = psGetElementsByClassName(itemRow,"input","bQty");
			if(psCheckArrayExist(pQuantity))
				this.quantity = pQuantity[0].value;
			var idTemp = this.id.replace(/&/gi,"&amp;");
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, idTemp);
			if(this.catId == null)
				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,postProLink)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var pLinks = psGetElementsByClassName(itemRow,"a","productLink");
			if(psCheckArrayExist(pLinks))
				this.id = psTrim(psCleanHtmlTag(psHtmlDecode(pLinks[0].innerHTML)));
			this.name = this.id;
			var pQuantity = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[postProLink+1].innerHTML)));
			if(pQuantity.search(/(\d+)/gi) > -1) 
				pQuantity = RegExp.$1;
			this.quantity = pQuantity;
			if(psCheckElementExist(itemRow.cells[postProLink+2]))
			{
				this.price = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[postProLink+2].innerHTML)));
				this.price = psCurrencyEx(this.price);
			}
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			if(this.catId == null)
				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.country = 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.country = buf[5];
			}
			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.country;
			// 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
		{
			this.id = psGetValueFromUrl(G_PS_URL_PATH,"oid");
			var pValue = psGetCookie(G_PS_COOKIE_ORDER);
			if(pValue != null)
			{
				var arrValue = 	pValue.split("-_-");
				this.subtotal = arrValue[0] == "null"?null:arrValue[0];
				if(this.subtotal!=null)
				{
					this.subtotal = psCurrencyEx(this.subtotal);
				}
				this.shipping = arrValue[1] == "null"?null:arrValue[1];
				if(this.shipping!=null)
				{
					this.shipping = psCurrencyEx(this.shipping);
				}
			} 
			if(!this.id)
			{
				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;
}

function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/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: 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, pCountry, pAttributes) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pCountry + ", " + pAttributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pAttributes, pAttributes);
}

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 ==================*/
