/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics 01/29/2009
 * COPYRIGHT 1999-2009 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/

cmSetProduction();
var G_PS_URL_PATH = "" + document.location;
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 = 259200; // 3*24*60*60 = 3 days

var G_PS_COOKIE_FLAG = "PS_FLAG"; // used as a "session" variable to handle events between pages
var G_PS_CUR_PAGEID = false;
var G_PS_CUR_CATID = psGetValueFromCookie(G_PS_COOKIE_FLAG, "catId");

var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_ATTRIBUTES = "PS_ATTRS";
var G_PS_COOKIE_SHOP9 = "PS_SHOP9";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";

// Navigation
if (psIsDomainToTag() && document.body != null)
{
	if (document.body.innerHTML.search('404.png')>=0)
	{
		// Error tags
		G_PS_CUR_CATID = "HOME"; // Main page
		psCreateErrorTag("404 NOT FOUND", G_PS_CUR_CATID);
	}
	else if (psIsCartView())
	{
		psPostCartView();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else
	{
		// Content pages
		psPostPageView();
	}

	// Renew catId in cookies
	psSetValueToCookie(G_PS_COOKIE_FLAG, "catId", G_PS_CUR_CATID);
}



function psIsDomainToTag()
{
	result = false;
	var domain = document.location.hostname.replace("www.", "").toLowerCase();
	if (domain == "bigyellow.co.uk") result = true;
	if (domain == "bigyellownew.testing.bmb.uk.com") result = true;
	cm_JSFPCookieDomain = domain;
	return result;
}


// 404 error page

function psCreateErrorTag(pPageID, pCatId) 
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
	cmCreateErrorTag(pPageID, pCatId);
}


// Pageview

function psPostPageView()
{
	psGetBreadcrumb();
	psCreatePageviewTag(G_PS_CUR_PAGEID, G_PS_CUR_CATID);
}

function psPostCarePageView()
{
	psGetCareInfo();
	psCreatePageviewTag(G_PS_CUR_PAGEID, G_PS_CUR_CATID);
}

// Shop

function psIsCartView()
{
	return (G_PS_URL_PATH.search(/boxshop\/basket/gi)>=0);
}

function psPostCartView()
{
	// Attribute info
	var attributes = "-_--_--_--_-";
	G_PS_CUR_CATID = "Basket";
	psCreatePageviewTag("Basket", G_PS_CUR_CATID, null, null, attributes);

	//
	// Hijack the Proceed Secure Checkout buttons
	try
	{
		//redButton redArrow
		var checkoutBtn = psGetFirstElementByClassName("redButton redArrow");
		onclickCheckoutBtn = checkoutBtn.onclick;
		checkoutBtn.onclick = function()
		{
			psThrowShop5Tags();
			if (onclickCheckoutBtn != null && onclickCheckoutBtn != "undefined")
				return onclickCheckoutBtn();
		}
	}
	catch (ex) {}
}

function psThrowShop5Tags()
{
	// Throw page view tag
	// Throw shop5 tags
	var cartTbl = document.getElementById("items");
		if (cartTbl == null) return;

	psSetCookie(G_PS_COOKIE_SHOP9, "", "delete"); // Initialize buffer
	var rows = cartTbl.getElementsByTagName("div"); // use rows variable for optimization

	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		if (prd.getItem5(rows[r].getElementsByTagName("div")[1], r)) // Get shop5 item successfully?
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId, "-_--_--_--_-");
	}
	// Make sure to have actual postings
	psDisplayShop5s();
}


// Order

function psIsOrderView()
{
	var result = false;
	if (G_PS_URL_PATH.search(/boxshop\/paymentdetails/gi)>=0) result = true;
	if (G_PS_URL_PATH.search(/boxshop\/thankyou/gi)>=0) result = true;
	return result;
}

function psPostOrderView()
{
	var attributes = psGetCookie(G_PS_COOKIE_ATTRIBUTES); // Get attributes from cookie
	attributes = (attributes == null ? "" : attributes);
	//
	// Throw page view tag
	G_PS_CUR_CATID = "Checkout";
	
	if (G_PS_URL_PATH.search(/boxshop\/thankyou/gi)>=0) 
	{
		psCreatePageviewTag("Thank You", G_PS_CUR_CATID, null, null, psGetAttributes());
				var ord = new psOrder();
				if (ord.getThanks()) // Get order info from cookie
				{
					var uP = new psProfile();
					if (uP.readProfile()) // Read profile
					{
						
						var prd = new psProduct();
						// Get shop9 items from cookie to throw shop9 tags
						var item9 = psGetCookie(G_PS_COOKIE_SHOP9);
						item9 = (item9 != null ? item9 : "");
						item9 = item9.split("#");
						
						for (var r = 1; r < item9.length; r++) // item for each row
						{
							if (prd.getItem9(item9[r]))
								psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.id, ord.id, ord.subtotal, prd.catId, attributes);
						}
						// Make sure to have actual postings
						psDisplayShop9s();

						// Post order tag finally
						psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.id, uP.address, null, uP.zipCode, attributes);
					}
				}
	}
	else 
	{
		psCreatePageviewTag("Payment Details", G_PS_CUR_CATID, null, null, psGetAttributes());

		if (document.getElementById("paymentForm") != null)
		{
			onsubmitFormPtr = document.getElementById("paymentForm").onsubmit; // Back up original pointer
			document.getElementById("paymentForm").onsubmit = function()
			{
				var ord = new psOrder();
				if (ord.getOrder()) // Get order info from cookie
				{
					var uP = new psProfile();
					if (uP.readProfile()) // Read profile
					{
						cmCreateRegistrationTag(uP.id, uP.email, uP.address, null, uP.postcode, null, null);
						
						var prd = new psProduct();
						// Get shop9 items from cookie to throw shop9 tags
						var item9 = psGetCookie(G_PS_COOKIE_SHOP9);
						item9 = (item9 != null ? item9 : "");
						item9 = item9.split("#");
						
						for (var r = 1; r < item9.length; r++) // item for each row
						{
							if (prd.getItem9(item9[r]))
								psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.id, ord.id, ord.subtotal, prd.catId, attributes);
						}
						// Make sure to have actual postings
						psDisplayShop9s();

						// Post order tag finally
						psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.id, uP.address, null, uP.zipCode, attributes);
					}
				}
			}
		}

	}

}

// Get info

function psGetBreadcrumb() 
{
	// Get info from permalink

	if (G_PS_PATHNAME.search("boxshop") >= 0)
	{
		// Product pages
		var cl = Array("name/");
		var ch = psStrReplace(cl,"",G_PS_PATHNAME.substr(G_PS_PATHNAME.search("category")+9));
		if (ch.substr(ch.length-1,1) == "/") ch = ch.substr(0,ch.length-1);
		
		var pul = ch.split("/");
		var i = 0;
		
		G_PS_CUR_PAGEID = G_PS_CUR_CATID = decodeURIComponent(pul[0]);

		for (i = 0; i < pul.length; i++) {
			if (pul[i] != null && pul[i-1] != null) {
				G_PS_CUR_PAGEID = decodeURIComponent(pul[i]);
				G_PS_CUR_CATID = decodeURIComponent(pul[i-1]);
			}
		}
		
		if (G_PS_CUR_PAGEID != "checkout")
		{
			var prd = new psProduct();
			if (prd.getProduct()) // Get product info successfully?
			psCreateProductviewTag(prd.id, prd.name, prd.catId, psGetAttributes());
		}

	}
	else
	{
		// Content pages
		var cl = Array("index/");
	
		var ch = G_PS_PATHNAME.substr(1);
		if (ch.substr(ch.length-1,1) == "/") ch = ch.substr(0,ch.length-1);
	
		var pul = psStrReplace(cl,"",ch).split("/");

		G_PS_CUR_PAGEID = G_PS_CUR_CATID = pul[0];
	
		for (i = 0; i < pul.length; i++) {
			if (pul[i] != null && pul[i-1] != null) {
				G_PS_CUR_PAGEID = pul[i];
				G_PS_CUR_CATID = pul[i-1];
			}
		}
		
		psPrefixCat();
	}

	psHardcode();

	return true;
}

function psHardcode()
{
	var ch = G_PS_PATHNAME.substr(1);

	if (ch.substr(ch.length-1,1) == "/") ch = ch.substr(0,ch.length-1);

	switch(ch)
	{
		case "partners": setId("Partners","About Big Yellow");
		break;

		case "property": setId("Property","About Big Yellow");
		break;

		case "newstores": setId("New Stores","About Big Yellow");
		break;

		case "contactus/about": setId("Contact Us: About","About Big Yellow");
		break;

		case "contactus": setId("Contact Us","Site Help");
		break;

		case "help": setId("Help","Site Help");
		break;

		case "termsandconditions": setId("Terms and Conditions","Site Help");
		break;

		case "privacypolicy": setId("Privacy Policy","Site Help");
		break;

		case "sitemap": setId("Sitemap","Site Help");
		break;

		case "careers": setId("Careers","Opportunities");
		break;

		case "franchising": setId("Franchising","Opportunities");
		break;

		case "estimate": setId("Estimate","Price your space");
		break;

		case "estimate/searchresults": setId("Estimate: Search Results","Price your space");
		break;
		
		case "boxshop/basket": setId("Basket","Basket");
		break;
		
		case "boxshop/checkout": setId("Checkout","Checkout");
		break;
		
		case "boxshop/paymentdetails": setId("Payment Details","Checkout");
		break;

		case "boxshop/thankyou": setId("Thank You","Checkout");
		break;

		case "selfstorageblog": setId("Blog Home","Self Storage Blog");
		break;

		case "selfstorageblog/big-yellow-on-the-web": setId("Big Yellow Hub","Self Storage Blog");
		break;
	}
	
	if (G_PS_PATHNAME.substr(1).search("estimate/store") >= 0) setId("Estimate: Step2","Price your space");
	
	if (G_PS_PATHNAME.substr(1).search("estimate/yourestimate") >= 0) setId("Estimate: Your Estimate","Price your space");
}

function psPrefixCat()
{
	switch(G_PS_CUR_CATID)
	{
		case "quote": psPrefix = "quote";
			break;

		case "reserve": psPrefix = "reserve";
			break;
		
		default: psPrefix = G_PS_CUR_CATID;
	}	
	
	switch(G_PS_CUR_CATID)
	{
		case "personal": G_PS_CUR_CATID = "Personal";
			break;

		case "business": G_PS_CUR_CATID = "Business-storage";
			break;

		case "quote": G_PS_CUR_CATID = "quote-and-reserve";
			break;

		case "reserve": G_PS_CUR_CATID = "quote-and-reserve";
			break;
		
		case "": G_PS_CUR_PAGEID = G_PS_CUR_CATID = "Home"; 
			break;
	}
	
	if (G_PS_CUR_PAGEID != psPrefix) G_PS_CUR_PAGEID = psPrefix + ": " + G_PS_CUR_PAGEID;
}

function setId(psPage, psCat)
{
	if (psPage != null) G_PS_CUR_PAGEID = psPage;
	if (psCat != null) G_PS_CUR_CATID = psCat;
}

/* PURPOSE: constructors for forms
 * Note: you can add more methods to psProfile 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();

			this.id = this.name = G_PS_CUR_PAGEID;
			this.catId = G_PS_CUR_CATID;
					var priceNode = psGetFirstElementByClassName("pageHeading").getElementsByTagName("h3")[0];
			this.price = psStrReplace(" per pack","",psGetInnerText(priceNode).substr(1));

			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, rowIndex)
	{
		try
		{
			this.id = null;
			this.name = null;
			this.catId = null;
			this.price = null;
			// Extract product info
			
				prdLink = itemRow.getElementsByTagName("div")[0].getElementsByTagName("a")[0].href;
				if (prdLink != null)
				{
					this.getId(prdLink);

						pNode = itemRow.getElementsByTagName("div")[1].getElementsByTagName("h3")[0];
					this.price = psStrReplace(" per pack","",psGetInnerText(pNode).substr(1));

						pNode = psGetFirstElementByClassName("quantity", itemRow.getElementsByTagName("div")[1]);
					this.quantity = pNode.value;
				}
				else return false;

			//
			// Persist shop9 items in pair (id, "quantity|price")
			var item9 = this.quantity + "|" + this.price;
			//
			// to differentiate extended protection plan items, suffixed by "_" + price
			var itemId = this.id;
			if (this.catId == "EPP/RP")
				itemId = this.id + "_!_" + rowIndex;
			psSetValueToCookie(G_PS_COOKIE_SHOP9, itemId, item9);

			return true;
		}
		catch (ex) { return false; }
	}

	/*
	 * Extract product info from item (get back from cookie)
	 */
	this.getItem9 = function(item)
	{
		try
		{
			this.reset();
			//
			var data = item.split("~");
			if (data.length >= 2)
			{
				this.id = data[0];
				data = data[1].split("|");
				this.name = null;
				this.quantity = data[0];
				this.price = data[1];
				// clean id for EPP items
				var endIndex = this.id.indexOf("_!_");
				if (endIndex >=0)
				{
					this.id = this.id.substring(0, endIndex);
					this.catId = "EPP/RP";
				}
				else // get catId from cookie G_PS_COOKIE_PROD_CATID
					this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			}
			return true;
		}
		catch (ex) {return false;}
	}

	this.getId = function(prdLink)
	{
		var cl = Array("name/");
		var ch = psStrReplace(cl,"",prdLink.substr(prdLink.search("category")+9));
		if (ch.substr(ch.length-1,1) == "/") ch = ch.substr(0,ch.length-1);
		
		var pul = ch.split("/");
		
		this.id = this.name = this.catId = decodeURIComponent(pul[0]);

		for (i = 0; i < pul.length; i++) {
			if (pul[i] != null && pul[i-1] != null) {
				this.id = this.name = decodeURIComponent(pul[i]);
				this.catId = decodeURIComponent(pul[i-1]);
			}
		}
	}
}

function psGetAttributes()
{
	var attributes = "";
	var card = psGetFirstElementByClassName("vcard");
	if (card != null)
	{
		// organization
		var org = psGetFirstElementByClassName("org");
		org = (org != null ? psGetInnerText(org) : "");
		if (org.indexOf(",")>=0)
		{
			org = org.split(",");
			attributes = psTrim(org[0]) + "-_-"; // first attribute
			org = org[1];
		}
		else
			attributes = "-_-";
		// region
		var region = psGetFirstElementByClassName("region");
		attributes += (region != null ? psGetInnerText(region) : "") + "-_-";
		// third attribute
		if (org.indexOf("#")>=0)
		{
			org = org.split("#");
			attributes += psTrim(org[1]) + "-_-";
		}
		else
			attributes += "-_-";
		// fourth attribute (postal-code)
		var postalCode = psGetFirstElementByClassName("postal-code");
		attributes += (postalCode != null ? psGetInnerText(postalCode) : "") + "-_-";
		// fifth attribute (locality)
		var locality = psGetFirstElementByClassName("locality");
		attributes += (locality != null ? psGetInnerText(locality).replace(",", "") : "") + "-_-";
	}
	else
		attributes = "-_--_--_--_-";

	return attributes;
}

function psOrder()
{
	this.id = null;
	this.subtotal = 0;
	this.shipping = 0;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			// Get orderId from source code
			var dt = new Date();
			this.id = (dt.getTime()%10000000) + (Math.floor(Math.random()*10000));
			// subtotal
			this.subtotal = psGetFirstElementByClassName("highlightedPrice").getElementsByTagName("h3")[0].innerHTML.substr(12);
			this.shipping = 0;
			return true;
		}
		catch (ex) {return false;}
	}

	this.getThanks = function()
	{
		try
		{
			// Get orderId from source code
			var dt = new Date();
			this.id = (dt.getTime()%10000000) + (Math.floor(Math.random()*10000));
			// subtotal
			this.subtotal = document.getElementById("subTotal").innerHTML;
			this.shipping = document.getElementById("delivery").innerHTML;
			return true;
		}
		catch (ex) {return false;}
	}
}

function psProfile()
{
	this.id = null;
  this.email = null;
  this.adress = null;
  this.postcode = null;

	/*
	 * Reset all fields to null by default
	 */
	this.reset = function()
	{
		this.id = null;
  	this.email = null;
  	this.adress = null;
  	this.postcode = null;
	}

	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.reset();

				var frm = document.getElementById("paymentForm");
				if (frm != null)
				{
					this.id = this.getField(frm.emailAddress);
					this.email = this.id;
					this.address = this.getField(frm.address);
					this.postcode = this.getField(frm.postCode);
				}
			
			if (this.id == null || this.id == "") {
				this.id = psGetCookie(G_PS_COOKIE_PROFILE);
				if (this.id != null)
				{
					var buf = this.id.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" || tempVal=="NULL")? null : tempVal); 
						buf[i] = ((tempVal=="null" || tempVal=="NULL")? "" : tempVal); 
					}
					this.id = buf[0];
					this.email = buf[1];
					this.address = buf[2];
					this.postcode = buf[3];
				}
			}else{
				this.writeProfile();
			}

			// make sure that customerId never gets null
			if (!this.id)
				this.id = psGenerateRandomValue();

			return true;
		}
		catch (ex) { return false; }
	}

	this.getField = function(field)
	{
		result = null;
		if (field != null && field != "" && field.value != null)
		{
			result = psTrim(field.value);
		}
		
		return result;
	}

	this.getSelect = function(field)
	{
		result = null;
		if (field != null && field != "")
		{
			return psTrim(field.options[field.selectedIndex].text);
		}
	}

	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		if (this.id == null)
			return;

		var data = this.id + '|' + this.email + '|' + this.address + '|' + this.postcode;
		// store on cookie
		psSetCookie(G_PS_COOKIE_PROFILE, data);
	}
	
	this.postTag = function()
	{
		this.readProfile();
		cmCreateRegistrationTag(this.id, this.email, this.address, null, this.postcode, null, null);
	}
}

// Info utils

function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if (!pCookieName || !cookies)
		return null;

	cookies = "; " + cookies.toUpperCase();
	var key = "; " + pCookieName.toUpperCase() + "=";
	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 psSetCookie(pCookieName, pCookieValue, pLifeTime, pDomain)
{
    if (!pCookieName)
		return false;

	if(pLifeTime == "delete") 
    {         
        CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
        return true;
    }
    // set cookie by calling coremetrics's cookie function
    var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
    
    return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

function psSetValueToCookie(pCookieName, pKey, pValue)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null ? psTrim(pKey).toUpperCase() : 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, G_PS_COOKIE_LIFETIME);
}

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;
}

function psGetValueFromUrl(pUrl, pKey)
{
    var re = new RegExp("[?&amp;&]" + pKey + "=([^&$]*)", "i");
    if (pUrl.search(re) == -1)
		return null;
    return unescape(RegExp.$1);
}

function psGetInnerText(node, ignorewhitespace)
{
	if (node == null)
		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(" "); // a break line for a <br> tag
				else
					text = text.concat(psGetInnerText(children[i])); // recursively get text
			}
		}
		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;
}

function psGetFirstElementByClassName(pClassName, node)
{
	if (node == null)
		node = document;
	var allPageTags = node.getElementsByTagName("*");	
	for (var k = 0; k < allPageTags.length; k++)
	{
		if (allPageTags[k].className.toLowerCase() == pClassName.toLowerCase())
			return  allPageTags[k];
	}
	return null;
}

// Cleaning info

function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) == "undefined")
		return pStr;

	return pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '');
}

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;
}

function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

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; 
}

function psStrReplace ( search, replace, subject ) 
{
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
 
    return subject;
}


// Tagging functions

function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult, pAttributes)
{
	pId = psCleanPageId(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult, pAttributes);
}

function psCreateProductviewTag(pId, pName, pCatId, pAttributes)
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	cmCreateProductviewTag(pId, pName, pCatId, pAttributes);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId, pAttributes)
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
  cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId, pAttributes);
}

function psDisplayShop5s()
{
	cmDisplayShop5s();
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId, pAttributes)
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
  cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId, pAttributes);
}

function psDisplayShop9s()
{
	cmDisplayShop9s();
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip, pAttributes)
{
	cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip, pAttributes);
}

/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dt = new Date();
	return (dt.getTime()%10000000) + (Math.floor(Math.random()*10000));
}