/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.1, 2009/08/21
 * 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("alamode.com");//value must be one array of domains or null

// current page url
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_URL_REFERRER = document.referrer.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000; // 5*24*60*60 = 5 days
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_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
/*
 * Flag to turn sending shop5 on/off, at order page
 * G_PS_SHOP5_FLAG = true: shop5 will be sent
 * G_PS_SHOP5_FLAG = false: shop5 will not be sent
 */
var G_PS_SHOP5_FLAG = false;
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var INTERVAL_ID=null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if(G_PS_URL_PATH.search(/alamode\.com/i) >= 0)
{
	psHijackAddToCart();
	if(G_PS_PATHNAME == "/default.aspx"
		|| G_PS_PATHNAME == "/"
		|| G_PS_PATHNAME == "/defaultin.aspx")
	{
		psCreatePageviewTag("HOME","HOME",null,null);
	}
	else if(G_PS_PATHNAME == "/common/termsofuse.aspx" 
			||G_PS_PATHNAME == "/sitemap.aspx" 
			||G_PS_PATHNAME == "/company/contact.aspx")
	{
		psCreatePageviewTag(psGetFileNameAsPageId(),"HOME",null,null);
	}
	else if(G_PS_PATHNAME == "/common/search.aspx")
	{
		psCreatePageviewTag("SEARCH","SEARCH",null,null);
	}
	
	else if(G_PS_PATHNAME == "/news/default.aspx")
	{
		psCreatePageviewTag("News","HOME",null,null);
	}
	else if(G_PS_PATHNAME == "/notifmngr/default.aspx")
	{
		psCreatePageviewTag("Subscribe","HOME",null,null);
	}
	else if(G_PS_PATHNAME == "/directorygenerator/default.htm")
	{
		psCreatePageviewTag("Find a Real Estate Professional","HOME",null,null);
	}
	else if(G_PS_PATHNAME == "/support/training.aspx")
	{
		psCreatePageviewTag("Training" + " " + psGetFirstItemTitle(),psGetCatIdFromPath(),null,null);
	}

	else if(G_PS_PATHNAME == "/company/corporate.aspx")
	{
		psCreatePageviewTag("About us","HOME",null,null);
	}
	else if(psIsLabsPages())
	{
		psCreatePageviewTag(psGetPageIdForLabs(),psGetCatIdFromPath(),null,null);
	}
	else if(G_PS_PATHNAME == "/alashopping/shopevent/topics.aspx")
	{
		var pageId = psGetFirstItemTitle() + " " + "topic" + " "  + psGetValueFromUrl(G_PS_URL_PATH,"market") ;	
		psCreatePageviewTag(pageId,psGetCatIdFromPath(),null,null);
	}
	
	else if(G_PS_PATHNAME == "/search/find.aspx"
		|| G_PS_PATHNAME == "/search/search.aspx")
	{
		INTERVAL_ID=window.setInterval("psPostSearchView()", 5000);
	}
	else if(G_PS_PATHNAME == "/alashopping/shoppingcart/addtocart.aspx")
	{
		psCreatePageviewTag("Add Product To Shopping Cart",psGetCatIdFromPath() ,null,null);
		if(G_PS_URL_REFERRER.indexOf("/alashopping/shoppingcart/addtocart.aspx") > -1)
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		psHijackSignInAddPro();
	}
	else if(G_PS_PATHNAME == "/myaccount/downloads.aspx"
			|| G_PS_PATHNAME == "/myaccount/training.aspx" 
			|| G_PS_PATHNAME == "/myaccount/support.aspx" 
			|| G_PS_PATHNAME == "/myaccount/orderhistory.aspx" 
			|| G_PS_PATHNAME == "/myaccount/payments.aspx" 
			|| G_PS_PATHNAME == "/reseller/getpassword.aspx")
	{
		psCreatePageviewTag(psGetFileNameAsPageId(),"My Account",null,null);
	}
	else if(G_PS_PATHNAME == "/myaccount/profile.aspx")
	{
		psCreatePageviewTag(psGetFileNameAsPageId(),"My Account",null,null);
		if(G_PS_URL_REFERRER.indexOf("/myaccount/profile.aspx") > -1)
		{
			psPostRegChangePro();
		}
	}
	/*
	 * Is the login page.
	*/
	else if(G_PS_PATHNAME == "/myaccount/"
			|| G_PS_PATHNAME == "/myaccount/default.aspx")
	{
		psCreatePageviewTag("Login","My Account",null,null);
		psHijackCustomerSignIn();
	}
	else if(G_PS_PATHNAME == "/myaccount/accounthome.aspx")
	{
		psCreatePageviewTag("Account Home","My Account",null,null);
		if(G_PS_URL_REFERRER.indexOf("/myaccount/") > -1)
		{
			psPostRegChangePro();
		}
	}
	/*
	 * Create new account page.
	*/
	else if(G_PS_PATHNAME == "/alashopping/shoppingcart/createaccount.aspx")
	{
		psCreatePageviewTag("Create Account","My Account",null,null);
		psHijackCreatNewAccount();
	}
	else if(psIsStorePages())
	{
		if(psIsOldArch())
		{
			psCreatePageviewTag(psGetFirstItemTitle(),psGetCatIdFromPath(),null,null);
		}
		else 
		{	
			psCreatePageviewTag(psGetPageIdFromPath(),psGetCatIdFromPath(),null,null); // Other pages go to "ADD URL" category
		}
	}
	else if(psIsProductView())
	{
		if(psIsOldArch())
		{
			psCreatePageviewTag(psGetFirstItemTitle(),psGetCatIdFromPath(),null,null);
		}
		else 
		{	
			psCreatePageviewTag(psGetPageIdFromPath(),psGetCatIdFromPath(),null,null); // Other pages go to "ADD URL" category
		}
		psPostProductView();
	}
	else if(psIsProViewOldArch())
	{
		psPostProViewOldArch();
	}
	else if(G_PS_PATHNAME == "/alashopping/shopevent/schedules.aspx")
	{
		psPostSchedulePro();
	}
	else if(G_PS_PATHNAME == "/alashopping/shoppingcart/shoppingcart.aspx")
	{
		/*
		 * Post a registration tag when uses login or create account successful.
		*/
		if(G_PS_URL_REFERRER.indexOf("/alashopping/shoppingcart/createaccount.aspx") > -1 || psGetCookie(G_PS_COOKIE_FLAG) == "global sign" 
			|| psGetCookie(G_PS_COOKIE_FLAG) == "customer sign")
		{
			psPostRegistration();
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
		psCreatePageviewTag("SHOPPING CART", "CHECKOUT", null);
		//psPostCartView();
	}
	else if(G_PS_PATHNAME == "/alashopping/checkout/receipt.aspx")
	{
		psPostOrderView();
	}
	else if(psIsHelpAlamode())
	{	
		var pPageId = psGetFirstItemTitle();
		if(psCheckElementExist(pPageId))
			psCreatePageviewTag(pPageId,"A la mode Help",null,null);
	}
	else if(psIsLiveChatAlamode())
	{	
		var pPageId = psGetFirstItemTitle();
		if(psCheckElementExist(pPageId))
			psCreatePageviewTag(pPageId,"A la mode Live Chat",null,null);
	}
	else if(psIsOldArch())
	{
		psCreatePageviewTag(psGetFirstItemTitle(),psGetCatIdFromPath(),null,null);
	}
	else 
	{	
		psCreatePageviewTag(psGetPageIdFromPath(),psGetCatIdFromPath(),null,null);
	}
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	var pCat = document.getElementById("ctabuttons");
	if(psCheckElementExist(pCat))
	{
		var links = pCat.getElementsByTagName("a");
		if (psCheckArrayExist(links))
		{	
			for (var i = 0; i < links.length; i++)
			{
				if (links[i].href.search(/\/alashopping\/shoppingcart\/addtocart\.aspx/gi) >= 0)
				{
					return true;
				}
			}
		}
	}
	return false;
}
/*
 * Determine if the page is the product detail page belong the old architecture.
 */
function psIsProViewOldArch()
{
	var pImage = document.getElementsByTagName("img");
	for (var i = 0; i < pImage.length; i++)	
	{
		var items = pImage[i];
		if (items.getAttribute("src").search(/products\/images\/rail_shared\/buy_now\.gif/gi) > -1)
		{
			return true;
		}
	}    
}

/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
/*
 * Determine if the page is belong old architecture
 */
function psIsOldArch()
{
	return (G_PS_URL_PATH.search(/\.aspx|\.htm/gi) > 0)?true:false;
}

function psIsLabsPages()
{
	var sPath = G_PS_URL_PATH;
	if(sPath.search(/^http(s)?\:\/\/(www\.)?alamode\.com\/labs/gi) >=0)
		return true;
	return false;
}

function psIsStorePages()
{
	var sPath = G_PS_URL_PATH;
	if(sPath.search(/^http(s)?\:\/\/(www\.)?alamode\.com\/common\/store/gi) >=0)
		return true;
	return false;
}

function psIsHelpAlamode()
{
	var sPath = G_PS_URL_PATH;
	if(sPath.search(/^http(s)?\:\/\/(www\.)?help\.alamode\.com/gi) >=0)
	{
		return true;
	}
	return false;

}

function psIsLiveChatAlamode()
{
	var sPath = G_PS_URL_PATH;
	if(sPath.search(/^http(s)?\:\/\/(www\.)?livechat\.alamode\.com/gi) >=0)
	{
		return true;
	}
	return false;

}

function psGetPageIdForLabs()
{
	var objCont = document.getElementById("content");
	if(psCheckElementExist(objCont))
	{
		var lstH1 = objCont.getElementsByTagName("h1");
		var lstSpan = objCont.getElementsByTagName("span");
		if(psCheckArrayExist(lstH1))
		{
			pageId = psHtmlDecode(psCleanHtmlTag(lstH1[0].innerHTML));
		}	
		else if(psCheckArrayExist(lstSpan))
		{
			pageId = psHtmlDecode(psCleanHtmlTag(lstSpan[0].innerHTML));
		}	
	}
	return psTrim(pageId);
}

function psGetPageIdFromPath()
{
	sPath = psMoveLastSlash(G_PS_URL_PATH); 
	if(sPath.search(/^http(s)?\:\/\/(www\.)?alamode\.com\/(.*\/)?(.*$)/gi) >=0)
	{
		if(RegExp.$4 == "" || RegExp.$4 == null)
			sPath = RegExp.$3.replace(/\/+/gi, "");
		else 
			sPath = RegExp.$4.replace(/\/+/gi, "");
	}
	
	if(sPath.search(/(.*)\?.*/gi) >=0)
		sPath = RegExp.$1;
	return sPath;
}

function psMoveLastSlash(sText)
{
	var last_char = sText.charAt(sText.length - 1);
	if(last_char == "/")
		sText = sText.substring(0,sText.length - 1); 
	return sText;

}

function psGetCatIdFromPath()
{		
	sPath = psMoveLastSlash(G_PS_URL_PATH); 
	if(sPath.search(/^http(s)?\:\/\/(www\.)?alamode\.com\/(.*\/)?([^$]*)/gi) >=0)
	{
		if(RegExp.$3 == "")
			sPath = psMoveLastSlash(RegExp.$4).replace(/\/+/gi, " | ");
		else 
			sPath = psMoveLastSlash(RegExp.$3).replace(/\/+/gi, " | ");
	}
	return sPath;
}

function psGetFirstItemTitle()
{
	var sTitle = "";
	var pTitle = document.getElementsByTagName("title");
	if(psCheckArrayExist(pTitle))
	{
		sTitle = psHtmlDecode(unescape(pTitle[0].innerHTML));
		if(sTitle.search(/([^\|]*)/gi) >=0)
		{
			return psTrim(RegExp.$1);
		}
	}
	return sTitle;
}

function psGetFileNameAsPageId()
{
	return G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf("."));
}

/* 
 * Hijack "sign in" button when customer login.
 */
function psHijackCustomerSignIn()
{
	window.oldFunc = window.onload;
	window.onload = function()
	{
		var myTemp =null;
		try
		{
			if(psCheckElementExist(this.oldFunc)==true)
			{
				myTemp = this.oldFunc();
				
			}
			var pSignBtn = document.getElementById("btnLogin");
			if(psCheckElementExist(pSignBtn))
			{
				
				pSignBtn.oF = pSignBtn.onclick; //backup the existing onclick function
				pSignBtn.onclick = function()
				{
					var pEmail = psGetElementValueById("txtUserName");
					if(pEmail && pEmail != "")
					{
						var uP = new psProfile();
						uP.email = psTrim(pEmail);
						uP.cusId = psTrim(pEmail);
						uP.city = null;
						uP.state = null;
						uP.zipcode = null
						uP.writeProfile();
					}
					if(psCheckElementExist(this.oF)==true)
					{
						return this.oF();
					}
				}
			}

		}		
		catch(err){
		}
		if(psCheckElementExist(myTemp)==true)
		{
			return myTemp;
		}
	}
	return;
}

/* 
 * Hijack "sign in" button when customer login when add product to cart.
 */
function psHijackSignInAddPro()
{
	window.oldFunc = window.onload;
	window.onload = function()
	{
		var myTemp =null;
		try
		{
			if(psCheckElementExist(this.oldFunc)==true)
			{
				myTemp = this.oldFunc();
			}
			var pSignBtn = document.getElementById("PBMain_btnContinue");
			if(psCheckElementExist(pSignBtn))
			{
				pSignBtn.oF = pSignBtn.onclick; //backup the existing onclick function
				pSignBtn.onclick = function()
				{
					var rdo = document.getElementById("PBMain_rbYes");
					if(psCheckElementExist(rdo) && rdo.checked == true)
					{
						var rdo2 = document.getElementById("PBMain_rbGlobal");
						if(psCheckElementExist(rdo2) && rdo2.checked == true)
						{
							var pEmail = psGetElementValueById("PBMain_txtEmail");
							if(pEmail && pEmail != "")
							{
								var uP = new psProfile();
								uP.email = psTrim(pEmail);
								uP.cusId = psTrim(pEmail);
								uP.city = null;
								uP.state = null;
								uP.zipcode = null
								uP.writeProfile();
							}
							psSetCookie(G_PS_COOKIE_FLAG, "global sign");							
						}
						else
						{
							rdo2 = document.getElementById("PBMain_rbCustomer");
							if(psCheckElementExist(rdo2) && rdo2.checked == true)
							{
								var pEmail = psGetElementValueById("PBMain_txtCustNum");
								if(pEmail && pEmail != "")
								{
									var uP = new psProfile();
									uP.email = psTrim(pEmail);
									uP.cusId = psTrim(pEmail);
									uP.city = null;
									uP.state = null;
									uP.zipcode = psTrim(psGetElementValueById("PBMain_txtZipCode"));
									uP.writeProfile();
								}
								psSetCookie(G_PS_COOKIE_FLAG, "customer sign");
								
							}
						}
					}
					if(psCheckElementExist(this.oF)==true)
					{
						return this.oF();
					}
				}
			}
		}		
		catch(err){
		}
		if(psCheckElementExist(myTemp)==true)
		{
			return myTemp;
		}
	}
}

/* 
 * Hijack create a new account.
 */
function psHijackCreatNewAccount()
{
	window.oldFunc = window.onload;
	window.onload = function()
	{
		var myTemp =null;
		try
		{
			if(psCheckElementExist(this.oldFunc)==true)
			{
				myTemp = this.oldFunc();
			}
			var btnContinue = document.getElementById("PBMain_btnContinue");
			if(psCheckElementExist(btnContinue))
			{
				btnContinue.oF = btnContinue.onclick;
				btnContinue.onclick = function()
				{
					var rdo = document.getElementById("PBMain_rbExisting");
					if(psCheckElementExist(rdo) && rdo.checked == true)
					{
						var pCustNum = psGetElementValueById("PBMain_txtCustNum");
						if(pCustNum && pCustNum != "")
						{
							var uP = new psProfile();
							uP.cusId = psTrim(pCustNum);
							uP.email = uP.cusId;
							uP.city = null;
							uP.state = null;
							uP.zipcode = psGetElementValueById("PBMain_txtZipCod");
							uP.writeProfile();
						}						
					}
					else 
					{
						rdo = document.getElementById("PBMain_rbNew");
						if(psCheckElementExist(rdo) && rdo.checked == true)
						{
							var pEmail = psGetElementValueById("PBMain_txtNewEmail");		
							if(pEmail && pEmail != "")
							{
								var uP = new psProfile();
								uP.email = psTrim(pEmail);
								uP.cusId = psTrim(pEmail);
								uP.city = psTrim(psGetElementValueById("PBMain_txtCity"));
								uP.state = psTrim(psGetElementValueById("PBMain_ddlState"));
								uP.zipcode = psTrim(psGetElementValueById("PBMain_txtZip"));
								uP.writeProfile();
							}
						}
					}
					if(psCheckElementExist(this.oF)==true)
					{
						return this.oF();
					}
				}
			}

		}		
		catch(err){
		}
		if(psCheckElementExist(myTemp)==true)
		{
			return myTemp;
		}
	}
}

/* 
 * Send a registration when user updated profile
 */
function psPostRegChangePro()
{
	var pEmail = psGetElementValueById("ctl00_ContentPlaceHolder1_lblEmail");
	if(pEmail && pEmail != "")
	{
		var uP = new psProfile();
		uP.email = psTrim(pEmail);
		uP.cusId = psTrim(pEmail);
		var oAdd = psGetElementValueById("ctl00_ContentPlaceHolder1_lblAddress");
		if(psCheckElementExist(oAdd))
		{
			var lstText = oAdd.toLowerCase().split("<br>");
			if(psCheckArrayExist(lstText))
			{
				var strAdd = psTrim(lstText[1]);
				if(strAdd.search(/(.*)\,\s(.*)\s(\d*)/gi) >=0)
				{
					uP.city = psCheckElementExist(RegExp.$1)?psTrim(RegExp.$1):null;
					uP.state = psCheckElementExist(RegExp.$2)?psTrim(RegExp.$2):null;
					uP.zipcode = psCheckElementExist(RegExp.$3)?psTrim(RegExp.$3):null;
					psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
					uP.writeProfile();
				}
			}
		}		
	}
}

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);
	}
}

/* 
 * Find element by class name
 */
function psGetElementsByClassName(psDocument, psElementTagName, psClassName)
{
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null)
    {
        return null;
    }
    for(var i = 0; i < arrInputs.length; i ++ )
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

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 psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	G_PS_CUR_CATID = "SEARCH";
	var pageId = null;
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(sResult != 0)
	{
		var pPageNo = psGetElementValueById("OurSiteCurrent");
		pPageNo = psCheckElementExist(pPageNo)?pPageNo:psGetElementValueById("ManualsCurrent");
		if(psCheckElementExist(pPageNo))
			pageId = "SEARCH SUCCESSFUL " + "PAGE " + pPageNo;
		else 
			pageId = "SEARCH SUCCESSFUL";
	}
	else 
	{
		pageId = "SEARCH UNSUCCESSFUL"
	}
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);
	window.clearInterval(INTERVAL_ID);
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	term = psGetValueFromUrl(G_PS_URL_PATH, "q");
	term =  psDecodeSearchTerm(term);
	return psTrim(psHtmlDecode(term));
}

function psDecodeSearchTerm(strValue)
{
	if (strValue!=null)
	{
		strValue = strValue.toLowerCase();
		strValue = strValue.replace(/\+/gi,"");
		strValue = strValue.replace(/\%2f/gi,"\/");
		strValue = strValue.replace(/\%3f/gi,"\?");
		strValue = strValue.replace(/\%3d/gi,"=");
		strValue = strValue.replace(/\%26/gi,"&");
		strValue = strValue.replace(/\%40/gi,"@");
		strValue = strValue.replace(/\%2b/gi,"+");
	}
	return strValue;
}
/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	var sText = psGetElementValueById("SliderCount");
	result = (sText.search(/(\d*)\sResults/gi) >= 0)?RegExp.$1:result;
	return result;
}
/*
 * Hijack add to cart button
 */ 
function psHijackAddToCart()
{	
	var proCatId = psGetCatIdFromPath();
	var sProId = null;
	var links = document.links;
	if (psCheckArrayExist(links))
	{	
		for (var i = 0; i < links.length; i++)
		{
			if (links[i].href.search(/\/alashopping\/shoppingcart\/addtocart\.aspx/gi) >= 0)
			{
				var oldCMFunc = links[i].onclick; //backup the existing onclick function
				links[i].onclick = function()
				{
					sProId =  psGetValueFromUrl(this.href,"code");
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,psTrim(sProId),proCatId);
					
					if (oldCMFunc != null)
						return oldCMFunc();
				}
			}
		}
	}
}

function psGetProductName(objUl)
{
	var rResult = "";
	var oLi = psGetElementsByClassName(objUl, "li", "prod");
	if(psCheckArrayExist(oLi))		
	{
		rResult = psCleanHtmlTag(psGetInnerText(oLi[0]));
		rResult = psTrim(psHtmlDecode(rResult));
	}
	else 
	{
		rResult = psGetFileNameAsPageId();
		rResult = rResult.replace(/\_/gi, " ");	
	}
	return rResult;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var proId = null;
    var proName = null;
    var proCatId = psGetCatIdFromPath();
    
	var oDiv = psGetElementsByClassName(document, "div", "box-inner");
	if(psCheckArrayExist(oDiv))		
	{
		var pUl = psGetElementsByClassName(oDiv[0], "ul", "clearfix");
		if(psCheckArrayExist(pUl))		
		{
			for(var i = 0; i < pUl.length; i++)
			{
				proName = psGetProductName(pUl[i]);
				var links = pUl[i].getElementsByTagName("a");
				if (psCheckArrayExist(links))
				{	
					proId = psGetValueFromUrl(links[0].href,"code");
					psCreateProductviewTag(proId, proName, proCatId);
				}
			}
		}
	}
	else 
	{
		proName = psGetPageIdFromPath();
		proName = proName.replace(/\_/gi, " ");	
		proId = psGetProIdFromBuyNowBtn();
		psCreateProductviewTag(proId, proName, proCatId);	
	}
	
}

function psGetProIdFromBuyNowBtn()
{
	var links = document.getElementsByTagName("a");
	var sProId = null;
	if (psCheckArrayExist(links))
	{	
		for (var i = 0; i < links.length; i++)
		{
			if (links[i].href.search(/\/alashopping\/shoppingcart\/addtocart\.aspx/gi) >= 0)
			{
				sProId =  psGetValueFromUrl(links[i].href,"code");
			}
		}
	}
	return sProId;
}
function psPostSchedulePro()
{
	var lstTable = psGetElementsByClassName(document, "table", "bodystyleMED");	
	var proCatId = psGetCatIdFromPath();
	if(psCheckArrayExist(lstTable))		
	{
		var links = lstTable[0].getElementsByTagName("a");
		var sProId = null;
		if (psCheckArrayExist(links))
		{	
			for (var i = 0; i < links.length; i++)
			{
				if (links[i].href.search(/\/alashopping\/shoppingcart\/addtocart\.aspx/gi) >= 0)
				{
					sProId =  psGetValueFromUrl(links[i].href,"code");
					var pProName = psGetElementValueById("lblTitle");
					pProName = (psCheckElementExist(pProName))?psTrim(psCleanHtmlTag(psHtmlDecode(pProName))):null;
					psCreateProductviewTag(sProId, pProName, proCatId);
				}			
			}
		}
	}
}

function psPostProViewOldArch()
{
	var lstTable = psGetElementsByClassName(document, "table", "bodystyleMED");	
	if(psCheckArrayExist(lstTable))		
	{
		for(var i=0;i<lstTable.length;i++)
		{
			if(lstTable[i].innerHTML.toLowerCase().indexOf("/alashopping/shoppingcart/addtocart.aspx") > -1)
			{
				psPostProInTable(lstTable[i]);
			}
			else 
			{
				proId = psGetProIdFromBuyNowBtn();
				proName = psGetFirstItemTitle();
				proCatId = psGetCatIdFromPath();
				psCreateProductviewTag(proId, proName, proCatId);
			}	
		}
	}
}

function psPostProInTable(pTable)
{
	var pRows = pTable.rows; // use rows variable for optimization
	var proId = null;
    var proName = null;
    var proCatId = psGetCatIdFromPath();
	
	for(var r=0;r<pRows.length;r++)
	{
		var pSpan = psGetElementsByClassName(pRows[r],"span","subLinkTRIAL");
		if(psCheckArrayExist(pSpan))
		{
			proName =  psCleanHtmlTag(psGetInnerText(pSpan[0]));
			proName = psTrim(psHtmlDecode(proName));
			proName = proName.replace(/\s\s+/gi, " ");
			
			var links = pRows[r].getElementsByTagName("a");
			if (psCheckArrayExist(links))
			{	
				for (var i = 0; i < links.length; i++)
				{
					if (links[i].href.search(/\/alashopping\/shoppingcart\/addtocart\.aspx/gi) >= 0)
					{
						proId =  psGetValueFromUrl(links[i].href,"code");
					}
				}
			}
			psCreateProductviewTag(proId, proName, proCatId);
		}
		else 
		{
			pSpan = psGetElementsByClassName(pRows[r],"span","bodystyleBLK1");
			if(psCheckArrayExist(pSpan))
			{
				proName =  psCleanHtmlTag(psGetInnerText(pSpan[0]));
				proName = psTrim(psHtmlDecode(proName));
				if(pRows[r].cells.length > 0 && psCheckElementExist(pRows[r].cells[0]))
				{
					var pSpanAdd =  psGetElementsByClassName(pRows[r].cells[0],"span","bodystyleSM");
					if(psCheckArrayExist(pSpanAdd))
					{
						var proNameAdd = psCleanHtmlTag(psGetInnerText(pSpanAdd[0]));
						proNameAdd = psTrim(psHtmlDecode(proNameAdd));
						proName = proName + " " + proNameAdd;
					}
					else 
					{
						pSpanAdd =  psGetElementsByClassName(pRows[r].cells[0],"span","bodystyleXSM");
						if(psCheckArrayExist(pSpanAdd))
						{
							var proNameAdd = psCleanHtmlTag(psGetInnerText(pSpanAdd[0]));
							proNameAdd = psTrim(psHtmlDecode(proNameAdd));
							proName = proName + " " + proNameAdd;
						}
					}
					pSpanAdd =  psGetElementsByClassName(pRows[r].cells[0],"span","bodystyleBLK2");
					if(psCheckArrayExist(pSpanAdd))
					{
						var proNameAdd = psCleanHtmlTag(psGetInnerText(pSpanAdd[0]));
						proNameAdd = psTrim(psHtmlDecode(proNameAdd));
						proName = proName + " " + proNameAdd;
					}
				}
				proName = proName.replace(/\s\s+/gi, " ");
				var links = pRows[r].getElementsByTagName("a");
				if (psCheckArrayExist(links))
				{	
					for (var i = 0; i < links.length; i++)
					{
						if (links[i].href.search(/\/alashopping\/shoppingcart\/addtocart\.aspx/gi) >= 0)
						{
							proId =  psGetValueFromUrl(links[i].href,"code");
						}
					}
				}
				psCreateProductviewTag(proId, proName, proCatId);
			}
		}
		
	}
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("SHOPPING CART", G_PS_CUR_CATID, null);

	var cartTbl = null;
	cartTbl = document.getElementById("PBCart_dgContents");
	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.toLowerCase().search(/pbcart_dgcontents__ctl(\d*)_txtqty/gi) < 0) 
		{
			continue;
		}
		if (prd.getItem5(rows[r]))
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
			
	}
	// Make sure to have actual postings
	psDisplayShop5s();
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("THANK YOU", G_PS_CUR_CATID, null);

	var cartTbl = null;
	/*
	 * Codes for locating the table containing items (each row for an item)
	 */
	cartTbl = document.getElementById("PBCart_dgContents");
	
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var ord = new psOrder();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var r = 0; r < rows.length; r++) // item for each row
			{
				 //Codes for skipping exceptional rows (rows don't contain items)
				if(rows[r].cells.length > 2)
				{
					if (psIsNumber(psTrim(rows[r].cells[2].innerHTML)) == false) // Skip rows not containining the item
						continue;
				}
				if (prd.getItem9(rows[r]))
				{
					if(G_PS_SHOP5_FLAG == true)
					{
						psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
					}
					psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
					
				}
			}
			// Make sure to have actual postings
			if(G_PS_SHOP5_FLAG == true)
			{
				psDisplayShop5s();
			}
			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");
		}
	}
}

function psGetOrderId()
{
	var pBodyText = document.getElementsByTagName("body")[0].innerHTML;
	var pId = pBodyText.toLowerCase().search(/receipt for invoice\s#:\s([^<]*)/gi) > -1 ?RegExp.$1: null;
	if(pId == null)
	{
		var lstForm = document.getElementsByName("Form1");
		if(psCheckArrayExist(lstForm))
		{
			var pAction = psCheckElementExist(lstForm[0].action)?lstForm[0].action:null;
			if(pAction)
				pId = psGetValueFromUrl(pAction,"on");
		}
	 
	}
	return (pId!=null)?psTrim(psCleanHtmlTag(pId)):null;
}
function psIsNumber(val)
{
	if(val != null && val != "")
		return (isNaN(val) == true)?false:true;
	return false;
}
/*====================== 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 = <from URL or source code>
			 * this.name = <from source code>
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
			 * this.catId = psGetCookie(G_PS_COOKIE_CATID);
			 */
			// Store productId along with catId to cookie for use later in shop5 and shop9 views
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);

			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the shopping cart
	 */
	this.getItem5 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			//this.id = psGetValueFromUrl(itemRow.cells[1].getElementsByTagName("a")[0].href,"cid");
			var pName = itemRow.cells[0].innerHTML;
			var lstEm = pName.split("<em>");
			if(psCheckArrayExist(lstEm))
			{
				this.name = psTrim(psCleanHtmlTag(lstEm[0]));
			}	
			this.price = psTrim(psCleanHtmlTag(itemRow.cells[2].innerHTML));
			var pQuantity = itemRow.getElementsByTagName("input");
			this.quantity = psCheckElementExist(pQuantity)?psTrim(pQuantity[0].value):0;
			// In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			//this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);

			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!
			this.id = psTrim(psCleanHtmlTag(itemRow.cells[0].innerHTML));
			this.name = psTrim(psCleanHtmlTag(itemRow.cells[1].innerHTML));
			this.price = psTrim(psCleanHtmlTag(itemRow.cells[3].innerHTML));
			this.quantity = psTrim(psCleanHtmlTag(itemRow.cells[2].innerHTML));
			// In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			this.catId = (this.catId == null)?"HOME":this.catId;
			return true;
		}
		catch (ex) { return false; }
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
	this.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.cusId = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.cusId != null)
			{
				var buf = this.cusId.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				this.cusId = buf[0];
				if (!this.cusId)
					this.cusId = psGenerateRandomValue();
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		try
		{
			if (this.cusId == null)
				return;
			// make sure that the data contains 4 parts separated by 3 '|'
			var data = this.cusId + "|" + this.email + '|' + this.city + '|' + this.state + '|' 
				+ this.zipcode + "|" + this.newsletter + '|' + this.subscribe;
			// store on cookie
			psSetCookie(G_PS_COOKIE_PROFILE, data);
			//
			// NOTE: To persist profile as persistent cookie, pass G_PS_COOKIE_LIFETIME as the third param instead of null
			// psSetCookie(G_PS_COOKIE_PROFILE, data, G_PS_COOKIE_LIFETIME);
			//
			return true;
		}
		catch (ex) { return false; }
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			this.id = psGetOrderId();
			this.subtotal = psGetElementValueById("PBCart_lblSubtotal");
			this.subtotal = psTrim(this.subtotal);
			this.shipping = psGetElementValueById("PBCart_lblShipping");
			this.shipping = psTrim(this.shipping);
			if (!this.id)
				this.id = psGenerateRandomValue();
			/*
			 * Extract user profile from source code
			 */
			var uP = new psProfile();
			uP.readProfile();  // Ensure to get the customer Id & email persisted at login stage
			/*
			 * uP.city = <from source code>
			 * uP.state = <from source code>
			 * uP.zipcode = <from source code>
			 * uP.newsletter = <from source code>
			 * uP.subscribe = <from source code>
			 */
			 if (!uP.cusId)
				uP.cusId = psGenerateRandomValue();
			return uP.writeProfile(); // Persist profile for later use at Receipt stage
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all HTML tags in a string
 * RETURN: string
 */
function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : 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: 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 ==================*/