/************************************************************************************/
/* $Revision: 99361 $
 * $Id: cmtaggingservices.js.txt 99361 2008-09-24 15:44:19Z abrink $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.5, 09/16/2008
 * COPYRIGHT 1999-2008 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/
//Production data warehouse flag
//cmSetProduction();
/*===========================GLOBAL VARIABLES ===============================*/
// current page url
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000;	// 5*24*60*60 = 5 days
var G_PS_CUR_CATID = null;			// current category ID while browsing/searching/refining, etc
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
// function pointers
var loginPtr = null;
var signUpPtr = null;
var savePtr = null;

// options for debug mode when sending tag:
// 1: only alert
// 2: only send tag
// 3: alert & send tag
var G_PS_DEBUG_MODE = 2;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
var h2 = document.getElementsByTagName("h2");
h2 = ((h2.length < 2 || h2[1] == null) ? "" : psGetInnerText(h2[1]).toUpperCase());

// Page views for Online Classifieds
if (h2 == "SEARCH CLASSIFIEDS ONLINE")
{
	psPostOnlineClassifiedsPageViews();
}
else
{
	// Page views for Forum
	if (G_PS_PATHNAME.search(/\/forum\//gi)>=0)
	{
		psPostFORUMPageViews();
	}
	// Page views for Search
	else if (G_PS_PATHNAME.search(/\/mapsearch.aspx/gi)>=0)
	{
		psPostMAPSEARCHPageViews();
	}
	// Page views for WOW checkout (DEAL)
	else if (document.location.hostname.search(/wowu.com/gi)>=0)
	{
		psPostWOWUPageViews();
	}
	// Page views for ADVERTISE
	else if (G_PS_PATHNAME.search(/\/advertise\//gi)>=0)
	{
		psPostADVERTISEPageViews();
	}
	// Page views for DEALS
	else if (G_PS_PATHNAME.search(/\/deals/gi)>=0)
	{
		psPostDEALSPageViews();
	}
	// Page views for COUPONS
	else if (G_PS_PATHNAME.search(/\/coupons/gi)>=0)
	{
		psPostCOUPONSPageViews();
	}
	// Page views for CONTESTS
	else if (G_PS_PATHNAME.search(/\/contests/gi)>=0)
	{
		psPostCONTESTSPageViews();
	}
	// Page views for AFF
	else if (G_PS_PATHNAME.search(/\/aff\//gi)>=0)
	{
		psPostAFFPageViews();
	}
	// Registration views for LOGIN
	else if (G_PS_PATHNAME.search(/\/user\//gi)>=0)
	{
		psPostUSERPageViews();
	}
	// Post other page views
	else
	{
		psPostOtherPageViews();
	}
}
//
// Persist current catId to cookie for use later
psSetCookie(G_PS_COOKIE_CATID, G_PS_CUR_CATID);
//
// check to send registration tags as user logged in or created/updateds ucessfully
// (use G_PS_COOKIE_FLAG cookie to track instead of referer URL)
psPostSignInView();
psPostUpdateProfileView();
/*============================ END NAVIGATION ================================*/

function psPostUSERPageViews()
{
	G_PS_CUR_CATID = "LOGIN";
	var pageId = "USER " + G_PS_PATHNAME.substr(G_PS_PATHNAME.lastIndexOf("/") + 1).replace(".aspx", "").toUpperCase();
	
	if (G_PS_PATHNAME == "/user/login.aspx")			// login
		psSubscribeSignInPages();
	else if (G_PS_PATHNAME == "/user/register.aspx")	// registration
		psSubscribeProfilePages();
	else if (G_PS_PATHNAME == "/user/details.aspx")	// profile detail
	{
		// capture email & username to update cookie
		var email = document.getElementById("lblEmail");
		var usename = document.getElementById("lblUsername");
		if (email != null && usename != null)
		{
			var uP = new psProfile();
			uP.readProfile();
			uP.customerId = psGetInnerText(usename);
			uP.email = psGetInnerText(email);
			uP.writeProfile(); // Persist to cookie for use later
		}
		psSubscribeProfilePages();
	}
	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, null, null, psGetSubdomain());
}

/*
 * Subscribe login form to capture user profile
 */
function psSubscribeSignInPages()
{
	// subscribe submit function in order to capture user profile information as the user submits
	var btnLogin = document.getElementById("btnLogin");
	if (btnLogin != null)
	{
		loginPtr = btnLogin.onclick; // backup original function
		btnLogin.onclick = function()
		{
			var uP = new psProfile();
			uP.customerId = document.getElementById("txtLoginUsername").value;
			// store profile on cookie
			uP.writeProfile();
			// mark as signed in successfully for the next step to post registration
			psSetCookie(G_PS_COOKIE_FLAG, "signed in");
			//
			// invoke the original function
			if (loginPtr != null)
				return loginPtr();
		}
	}
}

/*
 * Process to post registration tags as user signs in
 */
function psPostSignInView()
{
	if ((psGetCookie(G_PS_COOKIE_FLAG) == "signed in")
		&& (document.body.innerHTML.search(/Logout<\/a>/gi) >= 0))
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for login page
		psCreateRegistrationTag(uP.customerId, uP.email);
		psSetCookie(G_PS_COOKIE_FLAG, "", "delete"); // turn off flag
	}	
}

/*
 * Subscribe updating profile form to capture user profile
 */
function psSubscribeProfilePages()
{
	if (G_PS_PATHNAME == "/user/register.aspx")	// register new profile
	{
		var btnSignUp = document.getElementById("btnRegister");
		if (btnSignUp != null)
		{
			signUpPtr = btnSignUp.onclick; // back up original function
			btnSignUp.onclick = function()
			{
				// extract email
				var uP = new psProfile();
				uP.customerId = document.getElementById("txtUsername").value;
				uP.email = document.getElementById("txtEmail").value;
				uP.city = document.getElementById("txtCity").value;
				uP.state = document.getElementById("ddlState");
				uP.state = uP.state.options[uP.state.selectedIndex].innerHTML;
				uP.zipcode = document.getElementById("txtZip").value;
				uP.newsletterName = "NEWS AND OFFERS";
				uP.subscribe = document.getElementById("chkMayMail").checked;
				uP.referral = document.getElementById("ddlHear");
				uP.referral = uP.referral.options[uP.referral.selectedIndex].innerHTML;
				if (uP.referral.search(/please choose one/gi)>=0)
					uP.referral = "";
				// store on cookie
				uP.writeProfile();
				// set cookie to mark the status of creating user profile
				psSetCookie(G_PS_COOKIE_FLAG, "updated");
				//
				// invoke the original function
				if (signUpPtr != null)
					return signUpPtr();
			}
		}
	}
	else if (G_PS_PATHNAME == "/user/details.aspx")	// update profile detail
	{
		var type = null;
		var btnSave = document.getElementById("btnDetails");
		if (btnSave != null)
			type = "edit detail";
		else
		{
			btnSave = document.getElementById("btnEmailSet");
			if (btnSave != null)
				type = "edit email";
		}
		if (type != null)
		{
			savePtr = btnSave.onclick; // back up original function
			btnSave.onclick = function()
			{
				var uP = new psProfile();
				uP.readProfile(); // Read user ID and email from cookie
				if (type == "edit detail")
				{
					uP.city = document.getElementById("txtCity").value;
					uP.state = document.getElementById("ddlState");
					uP.state = uP.state.options[uP.state.selectedIndex].innerHTML;
					uP.zipcode = document.getElementById("txtZip").value;
					uP.newsletterName = "NEWS AND OFFERS";
					uP.subscribe = document.getElementById("chkMayMail").checked;
					uP.referral = "";
				}
				else
				{
					uP.email = document.getElementById("txtEmail").value;
				}
				// store on cookie
				uP.writeProfile();
				// set cookie to mark the status of creating user profile
				psSetCookie(G_PS_COOKIE_FLAG, "updated");
				//
				// invoke the original function
				if (savePtr != null)
					return savePtr();
			}
		}
	}
}

/*
 * Process to post registration tag as user updated profile successfully
 */
function psPostUpdateProfileView()
{
	if ((psGetCookie(G_PS_COOKIE_FLAG) == "updated") 
		&& (document.body.innerHTML.search(/Thank you for registering/gi)>=0
			|| document.body.innerHTML.search(/Your details have been updated!/gi)>=0
			|| document.body.innerHTML.search(/You have requested to change your e-mail address/gi)>=0)
		) // register account successfully?
	{
		// Only send when user successfully updated profile. By this we avoid posting registration tag
		// as the user cancel update
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		psCreateRegistrationTag(uP.customerId, uP.email, uP.city, uP.state, uP.zipcode, 
			uP.newsletterName, uP.subscribe, uP.subscribe, uP.referral);
		psSetCookie(G_PS_COOKIE_FLAG, "", "delete"); // turn off flag
	}
}

/*
 * Extract subdomain from hostname
 */
function psGetSubdomain()
{
	return document.location.hostname.toLowerCase().replace(".pennysaverusa.com", "");
}

/*
 * Post page view tags for Online Classifieds pages
 */
function psPostOnlineClassifiedsPageViews()
{
	var searchTerm = "";
	var searchResult = psGetONLINESearchResult();
	var subDomain = psGetSubdomain();
	var region = psGetInnerText(document.getElementById("clCatList_lblUserRegion"));
	region = (region != null ? region.replace(",", "") : "");
	region = (region != null ? region.replace("METRO:", "") : "");
	region = (region != null ? region.replace("Area", "") : "");
	var topLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl0_lblDimName"));
	topLevel = (topLevel != null ? topLevel.replace(",", "") : "");
	var secondLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl0_lblDimValName"));
	secondLevel = (secondLevel != null ? secondLevel.replace(",", "") : "");
	var thirdLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl1_lblDimValName"));
	thirdLevel = (thirdLevel != null ? thirdLevel.replace(",", "") : "");
	var fourthLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl2_lblDimValName"));
	fourthLevel = (fourthLevel != null ? fourthLevel.replace(",", "") : "");
	var fifthLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl3_lblDimValName"));
	fifthLevel = (fifthLevel != null ? fifthLevel.replace(",", "") : "");
	var sixthLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl4_lblDimValName"));
	sixthLevel = (sixthLevel != null ? sixthLevel.replace(",", "") : "");
	var seventhLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl5_lblDimValName"));
	seventhLevel = (seventhLevel != null ? seventhLevel.replace(",", "") : "");
	var attrs = subDomain + "-_-" + region + "-_-" + topLevel + "-_-" + secondLevel + "-_-" + thirdLevel + 
		"-_-" + fourthLevel + "-_-" + fifthLevel + "-_-" + sixthLevel + "-_-" + seventhLevel;

	// build search term
	searchTerm = region;
	if (secondLevel != "")
		searchTerm  = searchTerm  + "|" + secondLevel;
	if (thirdLevel != "")
		searchTerm  = searchTerm  + "|" + thirdLevel;
	var keyword = psGetInnerText(document.getElementById("clCatList_lblSearchTerms"));
	keyword = (keyword != null ? keyword.replace(",", "") : "");
	if (keyword != "")
		searchTerm  = searchTerm  + "|" + keyword;
	if (searchTerm.indexOf("|") == 0)
		searchTerm = searchTerm.substr(1);
	// catId
	G_PS_CUR_CATID = topLevel + ":" + secondLevel;			
	G_PS_CUR_CATID = (G_PS_CUR_CATID != null ? G_PS_CUR_CATID.replace("Metro Area:", "") : "");
	G_PS_CUR_CATID = (G_PS_CUR_CATID != null ? G_PS_CUR_CATID.replace("State:", "") : "");
	G_PS_CUR_CATID = (G_PS_CUR_CATID != null ? G_PS_CUR_CATID.replace("Area", "") : "");
	if (G_PS_CUR_CATID == ":" || G_PS_CUR_CATID == "")
		G_PS_CUR_CATID = (region != null ? region : "NORTH AMERICA");
	// pageId
	var pageId = "";
	if (document.title.indexOf(":")>=0)
		pageId = "SEARCH ADS:" + document.title.substr(document.title.indexOf(":") + 1);
	else
		pageId = "SEARCH ADS";
	//
	// Post page view	
	psCreatePageviewTag(pageId, G_PS_CUR_CATID, searchTerm, searchResult, attrs);
}

/*
 * Extract online search result
 */
function psGetONLINESearchResult()
{
	var result = document.getElementById("srResults_lblPagination");
	if (result != null)
	{
		if (result.innerHTML.search(/No Ads/gi)>=0)
			result = "0";
		else
		{
			result = result.innerHTML.toUpperCase();
			result = result.substring(0, result.indexOf("ADS FOUND"));
			result = psHtmlDecode(result.substr(result.lastIndexOf(">") + 1)).replace("OF", "");
		}
	}
	else
		result = "0";

	return result;
}

/*
 * Post page view tags for Forum pages
 */
function psPostFORUMPageViews()
{
	var pageId = null;
	var searchTerm = null;
	var searchResult = null;
	G_PS_CUR_CATID = "FORUM";

	if (G_PS_PATHNAME == "/forum/" || G_PS_PATHNAME == "/forum/default.aspx")
		pageId = "FORUM";
	else if (G_PS_PATHNAME.search(/Inappropriate.aspx/gi)>=0) 
		pageId = "INAPPROPRIATE";
	else if (G_PS_PATHNAME == "/forum/forumrules.aspx")
		pageId = "FORUM RULES";
	else if (G_PS_PATHNAME.search(/replies.aspx/gi)>=0 || G_PS_PATHNAME.search(/NewThread.aspx/gi)>=0)
	{
		pageId = "NEWTHREAD";
		var pageNumber = psGetValueFromUrl(G_PS_QUERYSTRING, "pageNum");
		if (pageNumber != null)
			pageId = pageId + " PAGE " + pageNumber;
	}
	else if (G_PS_PATHNAME.search(/subcat.aspx/gi)>=0)
	{
		pageId = "FORUM SUBCATEGORIES";
		var pageNumber = psGetValueFromUrl(G_PS_QUERYSTRING, "pageNum");
		if (pageNumber != null)
			pageId = pageId + " PAGE " + pageNumber;
		G_PS_CUR_CATID = psdHtmlDecode(psGetValueFromUrl(G_PS_QUERYSTRING, "parentId"));
	}
	else if (G_PS_PATHNAME.search(/topics.aspx/gi)>=0)
	{
		pageId = "FORUM SUBCATEGORIES";
		var pageNumber = psGetValueFromUrl(G_PS_QUERYSTRING, "pageNum");
		if (pageNumber != null)
			pageId = pageId + " PAGE " + pageNumber;
		G_PS_CUR_CATID = psdHtmlDecode(psGetValueFromUrl(G_PS_QUERYSTRING, "catid"));
	}	
	else if (G_PS_PATHNAME.search(/search.aspx/gi)>=0)
	{
		pageId = "FORUM SEARCH";
		var pageNumber = psGetValueFromUrl(G_PS_QUERYSTRING, "pageNum");
		if (pageNumber != null)
			pageId = pageId + " PAGE " + pageNumber;
		G_PS_CUR_CATID = psdHtmlDecode(psGetValueFromUrl(G_PS_QUERYSTRING, "cId"));
		searchTerm = psGetValueFromUrl(G_PS_QUERYSTRING, "kw");
	}
	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, searchTerm, searchResult, psGetSubdomain());
}

/*
 * Post page view tags for Search pages
 */
function psPostMAPSEARCHPageViews()
{
	G_PS_CUR_CATID = "GARAGESALES";
	var searchTerm = null;
	var subDomain = psGetSubdomain();
	var region = document.getElementById("txtArea").value;
	region = (region != null ? region.toUpperCase() : "");
	var keyword = document.getElementById("txtKeywords").value;
	keyword = (keyword != null ? keyword.toUpperCase() : "");
	var attrs = subDomain + "-_-" + region + "-_-GARAGESALES";

	if (region != "")
		searchTerm = region;
	if (keyword != "")
		searchTerm = searchTerm + "|" + region;
	
	psCreatePageviewTag("MAP SEARCH", G_PS_CUR_CATID, searchTerm, null, attrs);
}

/*
 * Post page views for www.WOWU.com checkout pages
 */
function psPostWOWUPageViews()
{
	G_PS_CUR_CATID = "WOWU";
	var pageId = null;
	if (G_PS_PATHNAME == "/checkout")
	{
		pageId = "DEAL OF THE DAY - CHECKOUT";
		// post product view
		psPostCardView_WOWU();
	}
	else if (G_PS_PATHNAME == "/checkout/confirm")
	{
		pageId = "DEAL OF THE DAY - CONFIRM";
	}
	else if (G_PS_PATHNAME == "/checkout/complete")
	{
		pageId = "DEAL OF THE DAY - COMPLETE";
		// post product view
		psPostOrderView_WOWU();
	}
	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, null, null, psGetSubdomain().toUpperCase());
}

/*
 * Post page view tags for ADVERTISE pages
 */
function psPostADVERTISEPageViews()
{
	var pageId = null;
	var searchTerm = null;
	var searchResult = null;

	if (G_PS_PATHNAME.search(/\/mediakit\//gi)>=0)
	{
		G_PS_CUR_CATID = "MEDIAKIT";
		if (G_PS_PATHNAME == "/advertise/mediakit/")
			pageId = "MEDIAKIT";
		else
			pageId = G_PS_PATHNAME.substr(G_PS_PATHNAME.lastIndexOf("/") + 1).replace(".aspx", "").toUpperCase();
	}
	else
	{
		G_PS_CUR_CATID = "ADVERTISE";
		if (G_PS_PATHNAME == "/advertise/" || G_PS_PATHNAME == "/advertise/index.aspx")
			pageId = "ADVERTISE";
		else if (G_PS_PATHNAME == "/advertise/myads.aspx")
			pageId = "MY ADS";
		else if (G_PS_PATHNAME == "/advertise/details.aspx")
			pageId = "AD DETAILS";
		else if (G_PS_PATHNAME.search(/\/advertise\/banners\//gi)>=0)
			pageId = "BANNER ADS";
		else if (G_PS_PATHNAME == "/advertise/editions.aspx")
			pageId = "LOCAL EDITION";
		else if (G_PS_PATHNAME == "/advertise/edit.aspx")
			pageId = "EDIT AD";
		else if (G_PS_PATHNAME == "/advertise/adcopy_en.aspx")
		{
			pageId = "EDIT AD STYLE";
			// Post productview
			psPostProductView_ADVERTISE();
		}
		else if (G_PS_PATHNAME == "/advertise/adcopy_internetenhancements.aspx")
			pageId = "FREE ENHANCEMENT FOR YOUR INTERNET AD";
		else if (G_PS_PATHNAME == "/advertise/area.aspx")
			pageId = "WHERE WOULD YOU LIKE TO ADVERTISE";			
		else if (G_PS_PATHNAME == "/advertise/availablepackages.aspx")
			pageId = "ZIP CODE HAS THE FOLLOWING OPTIONS";			
		else if (G_PS_PATHNAME == "/advertise/section.aspx")
			pageId = "CHOOSE AD CATEGORY";			
		else if (G_PS_PATHNAME == "/advertise/misc.aspx")
			pageId = "PLEASE ENTER DETAILS";			
		else if (G_PS_PATHNAME == "/advertise/adtype.aspx")
			pageId = "SELECT PRIVATE PARTY / BUSINESS";			
		else if (G_PS_PATHNAME == "/advertise/review.aspx")
			pageId = "REVIEW AD";
		else if (G_PS_PATHNAME == "/advertise/payment.aspx")
		{
			pageId = "BILLING INFORMATION";
			// Post shop5 tags
			psPostCartView_ADVERTISE();
		}
		else if (G_PS_PATHNAME == "/advertise/payment_review.aspx")
			pageId = "PAYMENT REVIEW";
		else if (G_PS_PATHNAME == "/advertise/finished.aspx")
		{
			pageId = "CONFIRMATION";
			// Post shop9 tags
			psPostOrderView_ADVERTISE();
		}
		else // Default page logic
		{
			pageId = G_PS_PATHNAME;
			G_PS_CU = "ADD URL";
		}
	}
	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, searchTerm, searchResult, psGetSubdomain());
}

/*
 * Extract info to throw productview tag for ADS item
 */
function psPostProductView_ADVERTISE()
{
	var lanOpt = document.getElementById("rblLanguage_0");
	if (lanOpt != null && lanOpt.checked)
		lanOpt = "English";
	else
	{
		lanOpt = document.getElementById("rblLanguage_1");
		if (lanOpt != null && lanOpt.checked)
			lanOpt = "Spain";
		else
			lanOpt = "Other";
	}

	var attrs = psGetSubdomain().toUpperCase() + "-_-" + lanOpt;
	var prd = new psProduct();
	prd.getProduct_ADVERTISE();
	// Throw product view tag
	psCreateProductviewTag(prd.id, prd.name, prd.catId, attrs);
}

/*
 * Process to post page view tag & shop5 tag for the purchasing item
 */
function psPostCartView_ADVERTISE()
{
	var prd = new psProduct();
	if (prd.getItem5_ADVERTISE()) // get shop5 item successfully
	{
		psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId, psGetSubdomain());
		psDisplayShop5s();
	}
}

/*
 * Process to post shop9 tag for the purchased item
 */
function psPostOrderView_ADVERTISE()
{
	var ord = new psOrder();
	var prd = new psProduct();
	
	// Post shop9 tag
	if (ord.getOrder_ADVERTISE() && prd.getItem9_ADVERTISE()) // Extract info from source code
	{
		psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, 
			ord.customerId, ord.id, ord.subtotal, prd.catId, psGetSubdomain().toUpperCase());
		psDisplayShop9s();
		// Post order tag finally
		psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, ord.customerId); 
	}
}

/*
 * Post page view tags for DEALS pages
 */
function psPostDEALSPageViews()
{
	G_PS_CUR_CATID = "DEALS";
	var pageId = null;
	var searchTerm = psGetValueFromUrl(G_PS_QUERYSTRING, "Ntt");
	var searchResult = null;

	var ns = psGetValueFromUrl(G_PS_QUERYSTRING, "Ns");
	ns = (ns == null ? "" : ns);

	// categorized by Ns parameter
	if (ns.search(/Import/gi)>=0)
		pageId = "NEWLY ADDED";
	else if (ns.search(/Expire/gi)>=0)
		pageId = "EXPIRING SOON";
	else if (ns.search(/FreeShipping/gi)>=0)
		pageId = "FREE SHIPPING";
	else if (searchTerm != null)
	{
		pageId = "DEALS SEARCH ";
		searchResult = psGetDEALSearchResult();
		if (searchResult == "0")
			pageId += " UNSUCCESSFULL";
		else
			pageId += " SUCCESSFULL";
	}
	else
		pageId = G_PS_PATHNAME.substr(G_PS_PATHNAME.lastIndexOf("/")+1).replace(".aspx", "").toUpperCase();
	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, searchTerm, searchResult, psGetSubdomain());
}

/*
 * Extract online search result
 */
function psGetDEALSearchResult()
{
	var result = document.getElementById("srResults_lblPagination");
	if (result != null)
	{
		if (result.innerHTML.search(/No Deals/gi)>=0)
			result = "0";
		else
		{
			result = result.innerHTML.toUpperCase();
			result = result.split("DEALS FOUND")[0];
			var start = result.lastIndexOf("OF")+2;
			if (start <= 2)
				start = result.indexOf(">")+1;
			result = psHtmlDecode(result.substr(start));
		}
	}
	else
		result = "0";

	return result;
}

/*
 * Post page view tags for COUPONS pages
 */
function psPostCOUPONSPageViews()
{
	G_PS_CUR_CATID = "COUPONS";

	var searchTerm = "";
	var searchResult = psGetCOUPONSSearchResult();
	var subDomain = psGetSubdomain();
	var region = psGetInnerText(document.getElementById("clCatList_lblUserRegion"));
	region = (region != null ? region.replace(",", "") : "");
	var topLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl0_lblDimName"));
	topLevel = (topLevel != null ? topLevel.replace(",", "") : "");
	var secondLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl0_lblDimValName"));
	secondLevel = (secondLevel != null ? secondLevel.replace(",", "") : "");
	var thirdLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl1_lblDimValName"));
	thirdLevel = (thirdLevel != null ? thirdLevel.replace(",", "") : "");
	var fourthLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl2_lblDimValName"));
	fourthLevel = (fourthLevel != null ? fourthLevel.replace(",", "") : "");
	var fifthLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl3_lblDimValName"));
	fifthLevel = (fifthLevel != null ? fifthLevel.replace(",", "") : "");
	var sixthLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl4_lblDimValName"));
	sixthLevel = (sixthLevel != null ? sixthLevel.replace(",", "") : "");
	var seventhLevel = psGetInnerText(document.getElementById("clCatList_rptBreadcrumbs__ctl5_lblDimValName"));
	seventhLevel = (seventhLevel != null ? seventhLevel.replace(",", "") : "");
	var attrs = subDomain + "-_-" + region + "-_-" + topLevel + "-_-" + secondLevel + "-_-" + thirdLevel + 
		"-_-" + fourthLevel + "-_-" + fifthLevel + "-_-" + sixthLevel + "-_-" + seventhLevel;

	// build search term
	searchTerm = region;
	if (secondLevel != "")
		searchTerm  = searchTerm  + "|" + secondLevel;
	if (thirdLevel != "")
		searchTerm  = searchTerm  + "|" + thirdLevel;
	var keyword = psGetInnerText(document.getElementById("clCatList_lblSearchTerms"));
	keyword = (keyword != null ? keyword.replace(",", "") : "");
	if (keyword != "")
		searchTerm  = searchTerm  + "|" + keyword;
	if (searchTerm.indexOf("|") == 0)
		searchTerm = searchTerm.substr(1);
	// pageId
	var pageId = "COUPON SEARCH";
	if (secondLevel != "")
		pageId += ":" + secondLevel;
	//
	// Post page view
	psCreatePageviewTag(pageId, G_PS_CUR_CATID, searchTerm, searchResult, attrs);
}

/*
 * Extract coupons search result
 */
function psGetCOUPONSSearchResult()
{
	var result = document.getElementById("searchresultsCpn_lblPagination");
	if (result != null)
	{
		if (result.innerHTML.search(/No Coupons/gi)>=0)
			result = "0";
		else
		{
			result = result.innerHTML.toUpperCase();
			result = result.split("COUPONS FOUND")[0];
			var start = result.lastIndexOf("OF")+2;
			if (start <= 2)
				start = result.indexOf(">")+1;
			result = psHtmlDecode(result.substr(start));
		}
	}
	else
		result = "0";

	return result;
}

/*
 * Post page view tags for CONTESTS pages
 */
function psPostCONTESTSPageViews()
{
	G_PS_CUR_CATID = "CONTESTS";
	var pageId = null;

	if (G_PS_PATHNAME == "/contests/")
		pageId = "CONTESTS";
	else
	{
		pageId = G_PS_PATHNAME.substr(G_PS_PATHNAME.lastIndexOf("/")+1).replace(".aspx", "").toUpperCase();
		var id = psGetValueFromUrl(G_PS_QUERYSTRING, "Id");
		if (id != null)
			pageId = pageId + " " + id;
	}
	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, null, null, psGetSubdomain());
}

/*
 * Post page view tags for AFF pages
 */
function psPostAFFPageViews()
{
	var pageId = null;
	G_PS_CUR_CATID = "AFF";
	if (G_PS_PATHNAME == "/aff/index.aspx")
		pageId = "AFFILIATE PROGRAM";
	else if (G_PS_PATHNAME == "/aff/freepower.aspx")
		pageId = "FREE POWER";
	else if (G_PS_PATHNAME == "/aff/newacct.aspx")
		pageId = "NEW ACCOUNT";
	else if (G_PS_PATHNAME == "/aff/newacct.aspx")
		pageId = "NEW ACCOUNT";
	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, null, null, psGetSubdomain());
}

/*
 * Post page view tags for other pages
 */
function psPostOtherPageViews()
{
	var pageId = null;
	// Home links
	if ((G_PS_PATHNAME == "/" || G_PS_PATHNAME == "/index.aspx"))
	{
		pageId = "HOME";
		G_PS_CUR_CATID = "HOME";
	}
	else if (G_PS_PATHNAME == "/error/404.aspx")
	{
		pageId = "ERROR: PAGE NOT FOUND";
		G_PS_CUR_CATID = "HOME";
	}
	else if (G_PS_PATHNAME.search(/\/sitemap\//gi)>=0)
	{
		pageId = "SITEMAP";
		G_PS_CUR_CATID = "HOME";
	}	
	else if (G_PS_PATHNAME == "/feedback.aspx")
	{
		G_PS_CUR_CATID = "FEEDBACK";
		psCreatePageviewTag("FEEDBACK", G_PS_CUR_CATID, null, null, psGetSubdomain());			
	}
	else if (G_PS_PATHNAME.search(/\/info\/show/gi)>=0)
	{
		pageId = "AD:" + document.title + " (" + G_PS_QUERYSTRING.substring(4,25) + ")";
		G_PS_CUR_CATID = psGetCookie(G_PS_COOKIE_CATID);
		if (G_PS_CUR_CATID == null)
			G_PS_CUR_CATID = "DIRECT LOAD";
		psSetCookie(G_PS_COOKIE_CATID, "", "delete"); // clear		
	}
	// New Features links
	else if (G_PS_PATHNAME == "/horoscope.aspx")
	{
		pageId = "HOROSCOPES";
		G_PS_CUR_CATID = "NEW FEATURES";
	}
	else if (G_PS_PATHNAME == "/weather.aspx")
	{
		pageId = "WEATHER FORECAST";
		G_PS_CUR_CATID = "NEW FEATURES";
	}
	else if (G_PS_PATHNAME == "/gas_prices.aspx")
	{
		pageId = "GAS PRICES";
		G_PS_CUR_CATID = "NEW FEATURES";
	}
	else if (G_PS_PATHNAME == "/mpg.aspx")
	{
		pageId = "MPG";
		G_PS_CUR_CATID = "NEW FEATURES";
	}
	else if (G_PS_PATHNAME == "/lottery.aspx")
	{
		pageId = "LOTTERY";
		G_PS_CUR_CATID = "NEW FEATURES";
	}
	else if (G_PS_PATHNAME == "/region.aspx")
	{
		pageId = "ADVERTISING REGIONS";
		G_PS_CUR_CATID = "REGIONS";
	}
	else if (G_PS_PATHNAME == "/hr/")
	{
		pageId = "EMPLOYMENT OPPORTUNITES";
		G_PS_CUR_CATID = "HOME";
	}
	else if (G_PS_PATHNAME.search(/\/contactus\//gi)>=0)
	{
		pageId = "CONTACT US";
		G_PS_CUR_CATID = "HOME";
	}
	else if (G_PS_PATHNAME == "/privacy.aspx")
	{
		pageId = "PRIVACY POLICY";
		G_PS_CUR_CATID = "HOME";
	}
	else if (G_PS_PATHNAME == "/tandc.aspx")
	{
		pageId = "TERMS AND CONDITIONS";
		G_PS_CUR_CATID = "HOME";
	}
	else if (G_PS_PATHNAME == "/scam.aspx")
	{
		pageId = "SCAM";
		G_PS_CUR_CATID = "HOME";
	}
	// Home Online Classifieds pages
	else if (G_PS_PATHNAME.search(/\/restaurants\//gi)>=0)
	{
		G_PS_CUR_CATID = "RESTAURANTS";
		if (G_PS_PATHNAME.search(/.aspx/gi)>=0)
			pageId = G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf(".")).toUpperCase();
		else
			pageId = G_PS_CUR_CATID;
	}
	else if (G_PS_PATHNAME.search(/\/merchandise\//gi)>=0)
	{
		G_PS_CUR_CATID = "MERCHANDISE";
		if (G_PS_PATHNAME.search(/.aspx/gi)>=0)
			pageId = G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf(".")).toUpperCase();
		else
			pageId = G_PS_CUR_CATID;
	}
	else if (G_PS_PATHNAME.search(/\/garagesales\//gi)>=0)
	{
		G_PS_CUR_CATID = "GARAGE SALES";
		if (G_PS_PATHNAME.search(/.aspx/gi)>=0)
			pageId = G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf(".")).toUpperCase();
		else
			pageId = G_PS_CUR_CATID;
	}
	else if (G_PS_PATHNAME.search(/\/cars\//gi)>=0)
	{
		G_PS_CUR_CATID = "CARS & VEHICLES";
		pageId = document.title.substring(46,150);
	}
	else if (G_PS_PATHNAME.search(/\/realestate\//gi)>=0)
	{
		G_PS_CUR_CATID = "REAL ESTATE";
		if (G_PS_PATHNAME.search(/.aspx/gi)>=0)
			pageId = G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf(".")).toUpperCase();
		else
			pageId = G_PS_CUR_CATID;
	}
	else if (G_PS_PATHNAME.search(/\/jobs\//gi)>=0)
	{
		G_PS_CUR_CATID = "CAREERS";
		if (G_PS_PATHNAME.search(/.aspx/gi)>=0)
			pageId = G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf(".")).toUpperCase();
		else
			pageId = G_PS_CUR_CATID;
	}
	else if (G_PS_PATHNAME.search(/\/services\//gi)>=0)
	{
		G_PS_CUR_CATID = "SERVICES";
		if (G_PS_PATHNAME.search(/.aspx/gi)>=0)
			pageId = G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf(".")).toUpperCase();
		else
			pageId = G_PS_CUR_CATID;
	}
	else if (G_PS_PATHNAME == "/info/email.aspx")
	{
		pageId = "EMAIL A FRIEND";
		G_PS_CUR_CATID = "DEALS";
	}
	else // Default page logic
	{
		pageId = G_PS_PATHNAME;
		G_PS_CUR_CATID = "ADD URL";
	}

	// post page view tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, null, null, psGetSubdomain());
}


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
/*
 * Process to post productview tag & shop5 tag for the purchasing item
 */
function psPostCardView_WOWU()
{
	var prd = new psProduct();
	// Post product view tag
	if (prd.getProduct_WOWU())
		psCreateProductviewTag(prd.id, prd.name, prd.catId, psGetSubdomain().toUpperCase());
	// Post shop5 tag
	if (prd.getItem5_WOWU())
	{
		psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
		psDisplayShop5s();
	}
}

/*
 * Process to post shop9 tag for the purchased item
 */
function psPostOrderView_WOWU()
{
	var ord = new psOrder();
	var prd = new psProduct();
	
	// Post shop9 tag
	if (ord.getOrder_WOWU() && prd.getItem9_WOWU()) // Extract info from source code
	{
		psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, 
			ord.customerId, ord.id, ord.subtotal, prd.catId, psGetSubdomain().toUpperCase());
		psDisplayShop9s();
		// Post order tag finally
		psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, ord.customerId, 
			ord.city, ord.state, ord.zipCode, psGetSubdomain().toUpperCase()); 
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct_WOWU = function()
	{
		try
		{
			this.id = "DEAL OF THE DAY";
			this.name = psGetInnerText(document.getElementsByTagName("h3")[0]);
			this.catId = "WOWU";

			return true;
		}
		catch (err) { return false;	}
	}
	/*
	 * Extracting product info from source code in www.WOWU.com/checkout
	 */
	this.getItem5_WOWU = function()
	{
		try
		{
			this.id = "DEAL OF THE DAY";
			this.name = psGetInnerText(document.getElementsByTagName("h3")[0]);
			this.quantity = document.getElementById("quantity").selectedIndex + 1;
			this.price = document.body.innerHTML.toUpperCase().split("COST OF EACH</TD>")[1];
			this.price = this.price.substr(this.price.indexOf(">")+1);
			this.price = this.price.substring(0, this.price.indexOf("<")).replace("$", "");
			this.catId = "WOWU";

			return true;
		}
		catch (err) { return false;	}
	}
	/*
	 * Extracting product info from source code on www.WOWU.com/checkout/complete
	 */
	this.getItem9_WOWU = function()
	{
		try
		{
			this.id = "DEAL OF THE DAY";
			this.name = psGetInnerText(document.getElementsByTagName("h3")[0]);
			this.quantity = document.getElementById("quantity").selectedIndex + 1;
			this.price = document.body.innerHTML.toUpperCase().split("COST OF EACH</TD>")[1];
			this.price = this.price.substr(this.price.indexOf(">")+1);
			this.price = this.price.substring(0, this.price.indexOf("<")).replace("$", "");
			this.catId = "WOWU";

			return true;
		}
		catch (err) { return false;	}
	}

	/*
	 * Extract ADVERTISE product info
	 */
	this.getProduct_ADVERTISE = function()
	{
		this.id = "CLASSIFIED AD";
		this.name = "CLASSIFIED AD - PAID OPTIONS";
		this.catId = "ADVERTISE";
	}
	/*
	 * Extracting product info from source code of page "/advertise/payment.aspx"
	 */
	this.getItem5_ADVERTISE = function()
	{
		try
		{
			this.id = "CLASSIFIED AD";
			this.name = "CLASSIFIED AD - PAID OPTIONS";
			this.quantity = 1;
			this.price = psGetInnerText(document.getElementById("lblPrice")).replace("$", "");
			this.catId = "ADVERTISE";

			return true;
		}
		catch (err) { return false;	}
	}	
	/*
	 * Extracting product info from source of page "/advertise/finished.aspx"
	 */
	this.getItem9_ADVERTISE = function()
	{
		try
		{
			this.id = "CLASSIFIED AD";
			this.name = "CLASSIFIED AD - PAID OPTIONS";
			this.quantity = 1;
			this.price = psGetInnerText(document.getElementById("lblPrice")).replace("$", "");
			this.catId = "ADVERTISE";

			return true;
		}
		catch (err) { return false;	}
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
	this.customerId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletterName = null;
    this.subscribe = null;
	this.referral = "";
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		this.customerId = psGetCookie(G_PS_COOKIE_PROFILE);
		if (this.customerId != null)
		{
			var buf = this.customerId.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.customerId = buf[0];
			this.email = buf[1];
			this.city = buf[2];
			this.state = buf[3];
			this.zipcode = buf[4];
			this.newsletterName = buf[5];
			this.subscribe = buf[6];
			this.referral = buf[7];
		}
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		// make sure that the data contains 4 parts separated by 3 '|'
		var data = this.customerId + "|" + this.email + '|' + this.city + '|' + this.state + 
			'|' + this.zipcode + '|' + this.newsletterName + '|' + this.subscribe + '|' + this.referral;
		// store on cookie
		psSetCookie(G_PS_COOKIE_PROFILE, data);
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	this.customerId = null;
	this.city = null;
	this.state = null;
	this.zipCode = null;
	/*
	 * get order info from source code
	 */
	this.getOrder_WOWU = function()
	{
		try
		{
			this.id = document.getElementById("order_email").value;
			this.customerId = this.id;
			this.subtotal = psGetInnerText(document.getElementById("cart_subtotal")).replace("$", "");
			this.shipping = document.body.innerHTML.toUpperCase().split("SHIPPING</TD>")[1];
			this.shipping = this.shipping.substr(this.shipping.indexOf(">")+1);
			this.shipping = this.shipping.substring(0, this.shipping.indexOf("<")).replace("$", "");
			this.city = document.getElementById("order_billing_city").value;
			this.state = document.getElementById("order_billing_state");
			this.state = this.state.options[this.state.selectedIndex].innerHTML;
			this.zipCode = document.getElementById("order_billing_zipcode").value;

			return true;
		}
		catch (err) { return false; }
	}
	/*
	 * get order info from source code
	 */
	this.getOrder_ADVERTISE = function()
	{
		try
		{
			this.id = psGetInnerText(document.getElementById("lblOrderID"));
			this.customerId = this.id;
			this.subtotal = psGetInnerText(document.getElementById("lblPrice")).replace("$", "");
			this.shipping = 0;

			return true;
		}
		catch (err) { return false; }
	}
}

/* PURPOSE: Get inner text of an _object or clean remove html tags of a particular string
 * RETURN: resultant string or null _object
 */
function psGetInnerText(node, ignorewhitespace)
{
	if (node == null || typeof(node) == "undefined")
		return "";

	var text = "";
	if (typeof(node) == "object")
	{
		if (node.hasChildNodes())
		{
			var children = node.childNodes;
			for(var i=0; i<children.length; i++)
			{
				if(children[i].nodeName == "#text")
				{
					if(ignorewhitespace)
					{
						if(!/^\s+$/.test(children[i].nodeValue))
						{
							text = text.concat(children[i].nodeValue);
						}
					}
					else
					{
						text = text.concat(children[i].nodeValue);
					}
				}
				else if(children[i].nodeName.search(/BR/i)>=0)
				{
					text = text.concat("\n"); // a break line for a <br> tag
				}
				else
				{
					text = text.concat(psGetInnerText(children[i]));
				}
			}
		}
		else
		{
			if(node.nodeName == "#text")
			{
				text = text.concat(node.nodeValue);
			}
			else if(node.nodeName.search(/BR/i)>=0)
			{
				text = text.concat("\n"); // a break line for a <br> tag
			}
		}
	}
	else
		text =  node.replace(/\<+.+?\>+/g, "");

	return text;
}

/* PURPOSE: Remove all leading & trailing spaces of a string
 * Note: [&nbsp;] is also considered as a space
 * Two ways to call: as a string's built-in method or as an independent function
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;

	return (pStr) ? pStr.replace(/&nbsp;/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

/* PURPOSE: extract value from the URL
 * in format of http://xxx.com/page.ext?key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
function psGetValueFromUrl(pUrl, pKey)
{
    var re = new RegExp("[?&]" + pKey + "=([^&$]*)", "i");
    if (pUrl.search(re) == -1)
		return null;
    return unescape(RegExp.$1);
}

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: 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: retrieve cookie value
 * RETURN: string
 */
function psGetCookie(pCookieName)
{
    if (!pCookieName)
		return null;

    var start = document.cookie.indexOf(pCookieName + "=");
    if (start > -1)
    {
        start = start + pCookieName.length + 1; 
        end = document.cookie.indexOf(";", start);
        if (end == -1)
            end = document.cookie.length;
        return unescape(document.cookie.substring(start, end));
    }
    return null;
}

/* PURPOSE: set cookie value
 * Note: if the designated cookie is too big, the old items will be removed
 * because cookie size is limited to 4K
 * @pLifeTime in seconds
 * pDomain: don't specify if using current domain
 * RETURN: boolean
 */
function psSetCookie(pCookieName, pCookieValue, pLifeTime, pDomain)
{
    if (!pCookieName)
		return false;

	if(pLifeTime == "delete") 
    {         
        CC(pCookieName);//delete cookie by calling coremetrics's cookie function
        return true;
    }
    // set cookie by calling coremetrics's cookie function
    var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
    
    return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

/* PURPOSE: set value in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 * NOTE: Use null or '' for pValue to remove the pair specified by pKey
 */
function psSetValueToCookie(pCookieName, pKey, pValue)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = psTrim(pKey);
	// 
	var catCookie = psGetCookie(pCookieName);
	if (catCookie == null)
		catCookie = '';

	if (catCookie.indexOf(pKey) >=0) // Store before -> remove the old value
	{
        var reg = new RegExp("#" + pKey + "~([^#]*)", "gi");
        catCookie = catCookie.replace(reg, "");
	}
	// remove the last items (eldest items) until cookie size < 3500	
	if (pValue != null && pValue != '')
	{
		catCookie = "#" + pKey + "~" + pValue + catCookie;
		var cookieArray = null;
		while (catCookie.length > 3500)
		{
			cookieArray = catCookie.split("#");
			cookieArray.pop();
			catCookie = cookieArray.join("#");
		}
	}
	// Save to cookie
	psSetCookie(pCookieName, catCookie);
}

/* 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 = psTrim(pKey);
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if (catCookie != null)
    {
        var re = new RegExp("#" + pKey + "~([^#$]+)", "i");
		if (catCookie.search(re) == -1)
			return null;

        return RegExp.$1;
    }
    return null;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pageID, categoryID, searchString, searchResults, attributes) 
{
	pageID = psCleanPageId(pageID);
	categoryID = psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pageID + ", " + categoryID + ", " + searchString + ", " + searchResults + ", " + attributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pageID, categoryID, searchString, searchResults, attributes);
}

function psCreateProductviewTag(productID, productName, categoryID, attributes) 
{
	productName = psCleanProductName(productName);
	categoryID = psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + productID + ", " + productName + ", " + categoryID + ", " + attributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(productID, productName, categoryID, attributes);
}

function psCreateShopAction5Tag(productID, productName, productQuantity, productPrice, categoryID,attributes) 
{
	productName = psCleanProductName(productName);
	categoryID = psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + productID + ", " + productName + ", " + productQuantity + ", " + productPrice + ", " + categoryID + ", " + attributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(productID, productName, productQuantity, productPrice, categoryID,attributes);
    
}

function psCreateShopAction9Tag(productID, productName, productQuantity, productPrice, customerID, orderID, orderTotal, categoryID,attributes) 
{
	productName = psCleanProductName(productName);
	categoryID = psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + productID + ", " + productName + ", " + productQuantity + ", " + productPrice + ", " + customerID + ", " + orderID + ", " + orderTotal + ", " + categoryID + ", " + attributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(productID, productName, productQuantity, productPrice, customerID, orderID, orderTotal, categoryID,attributes);
}

function psCreateOrderTag(orderID, orderTotal, orderShipping, customerID, customerCity, customerState, customerZIP,attributes) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + orderID + ", " + orderTotal + ", " + orderShipping + ", " + customerID + ", " + customerCity + ", " + customerState + ", " + customerZIP + ", " + attributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(orderID, orderTotal, orderShipping, customerID, customerCity, customerState, customerZIP,attributes);
}

function psCreateConversionEventTag(eventID, actionType, categoryID, points,attributes) 
{
	categoryID = psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + eventID + ", " + actionType + ", " + categoryID + ", " + points + ", " + attributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(eventID, actionType, categoryID, points,attributes);
}

function psCreateRegistrationTag(customerID, customerEmail, customerCity,
				customerState, customerZIP, newsletterName, 
				subscribe, referral) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + customerID + ", " + customerEmail + ", " + customerCity + ", " + customerState + ", " + customerZIP + ", " + newsletterName + ", " + subscribe + ", " + referral + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(customerID, customerEmail, customerCity, customerState, customerZIP, newsletterName, subscribe, referral);
}

function psCreateErrorTag(pageID, categoryID) 
{
	pageID = psCleanPageId(pageID);
	categoryID = psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateErrorTag(" + pageID + ", " + categoryID + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateErrorTag(pageID, categoryID);
}

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 ==================*/