/************************************************************************************/
/* $Revision: 113343 $
 * $Id: cmtaggingservices - 6430704 - 90224664 - 123108.txt 113343 2009-03-26 15:58:01Z rnaik $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.1, 01/6/2009
 * 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;

// current page url
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_URL_REFERRER = document.referrer.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000; // 5*24*60*60 = 5 days
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var INTERVAL_ID=null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
/*
 * The corporate home page.
 */
if(psIsErrorPage())
{
	psCreatePageviewTag("500 internal server error","Error",null,null);	
}
else if(G_PS_PATHNAME == "/portal/page/portal/tggwebportal")
{
	psCreatePageviewTag("Corporate Home page","Home",null,null);
}

else if(G_PS_URL_PATH.indexOf("/portal/page/portal/tggwebportal/corporate/storelocator?") > -1)
{
	
	INTERVAL_ID=window.setInterval("psLocatorPageView()", 5000);
}
/* 
 * The “Store Locator” page.
 */
else if(G_PS_PATHNAME=="/portal/page/portal/tggwebportal/corporate/storelocator")
{
	psCreatePageviewTag("Corporate Home page","Store locator",null,null);
}
	//
else if(G_PS_URL_PATH.search(/\/portal\/page\/portal\/tggwebportal\/[^\/]+\/(store\d+)\/productguides\/buyersguide\//gi) > -1
	|| G_PS_URL_PATH.search(/\/portal\/page\/portal\/tggwebportal\/[^\/]+\/(store\d+)\/productguides\/shopperschecklist\//gi) > -1
	|| G_PS_URL_PATH.search(/\/portal\/page\/portal\/tggwebportal\/[^\/]+\/(store\d+)\/productguides\/jargonbuster\//gi) > -1)
{
	var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"storeId");
	var pPageId = psGetProducGuidePageId();
	psCreatePageviewTag(pPageId,"StoreID" + pCatId + ":Home",null,null);
}

else if(G_PS_URL_PATH.search(/\/portal\/page\/portal\/tggwebportal\/[^\/]+\/(store\d+)/gi) > -1)
{
	var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"storeId");
	if(psGetLastInPath() == "home")
	{
		psCreatePageviewTag(RegExp.$1 + " home",RegExp.$1,null,null);
	}
	
	//Page View for navigating through top menus
	else
	{
		var pPageId = psTrim(psHtmlDecode(document.getElementsByTagName("TITLE")[0].innerHTML));
		pPageId = pPageId.replace("The Good Guys - ","");
		psCreatePageviewTag(pPageId,"StoreID" + pCatId + ":Home",null,null);
	}	
}
else if(G_PS_URL_PATH.indexOf("/portal/page/portal/tggwebportal/corporate/products/comparison") > -1 
	&& psGetValueFromUrl(G_PS_URL_PATH,"productId") == null)
{
	var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"storeId");
	psCreatePageviewTag("StoreID" + pCatId + ":Comparison","StoreID" + pCatId + ":Comparison",null,null);	
}
else if(G_PS_URL_PATH.indexOf("/portal/page/portal/tggwebportal/corporate/products/undefined/catalogue") > -1)
{
	psCreatePageviewTag("Undefined Page","Error",null,null);	
}

else if(G_PS_URL_PATH.indexOf("/portal/tggwebportal/corporate/products/package_details") > -1)
{
	var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"storeId");
	var pPacketId = psGetValueFromUrl(G_PS_URL_PATH,"packageId") != null? psGetValueFromUrl(G_PS_URL_PATH,"packageId"):null;
	psCreatePageviewTag("PacketId"  + ":" + pPacketId,"StoreID" + pCatId + ":Package details",null,null);
}

else if(psIsSearchView())
{
	psPostSearchView();
}
else if (psIsProductView() || psIsProductSearchView() || psIsProductComparisonView())
{
	psPostProductView();
}
else if(psIsCatalogPage())
{
	var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"storeId");
	var pPageNo = psGetPageNumber();
	psCreatePageviewTag(psGetContentPageId() + " Page " + pPageNo ,"StoreID" + pCatId + ":Product details",null,null);		
}

else 
{	
	psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
}
/*
 * Send a page view tag for store locator page.
*/
function psLocatorPageView()
{
	var pPageId = psGetElementValueById("store-locator-title");
	if(pPageId.indexOf("-") > -1)
	{		
		psCreatePageviewTag(pPageId,"Store locator",null, null);
		window.clearInterval(INTERVAL_ID);
	}
}
/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	//
	// TO-Do: Your logic to determine the product detail page goes here
	if(G_PS_URL_PATH.toLowerCase().indexOf("/portal/tggwebportal/corporate/products/details") > -1
		&& psGetValueFromUrl(G_PS_URL_PATH,"productId") != null)
	{
		return true;
	}
	return false;	
}
function psIsErrorPage()
 {
	var pBodyText = document.getElementsByTagName("body")[0].innerHTML;
	if(pBodyText.toLowerCase().indexOf("error: the listener returned the following message: 500 internal server error") > -1)
		return true;
	return false;
 }

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	//
	// TO-Do: Your logic to determine the search page goes here
	//
	if(G_PS_URL_PATH.indexOf("/portal/page/portal/tggwebportal/corporate/products/search") > -1
		 && psGetValueFromUrl(G_PS_URL_PATH,"productId") == null)
		 return true;
	return false;
}

/*
 * Determine if the page is the product detail page from search.
 */
function psIsProductSearchView()
{
	//
	// TO-Do: Your logic to determine the product detail page goes here
	if(G_PS_URL_PATH.toLowerCase().indexOf("/portal/page/portal/tggwebportal/corporate/products/search") > -1
		&& psGetValueFromUrl(G_PS_URL_PATH,"productId") != null)
	{
		return true;
	}
	return false;	
}
function psIsProductComparisonView()
{
	if(G_PS_URL_PATH.toLowerCase().indexOf("/portal/page/portal/tggwebportal/corporate/products/comparison") > -1
		&& psGetValueFromUrl(G_PS_URL_PATH,"productId") != null)
	{
		return true;
	}
	return false;	
}

/*
 * Is list of products page.
*/
function psIsCatalogPage()
{//products/categorycontent
	if(G_PS_URL_PATH.toLowerCase().indexOf("/portal/tggwebportal/corporate/products/details") > -1
		|| G_PS_URL_PATH.toLowerCase().indexOf("/portal/tggwebportal/corporate/products/packages") > -1 ||
		G_PS_URL_PATH.toLowerCase().indexOf("/portal/tggwebportal/corporate/products/categorycontent") > -1)
	{
		if(psGetValueFromUrl(G_PS_URL_PATH,"productId") == null)
		{
			return true;
		}
	}
	return false;	

}
/*
 * Get page id for content pages
*/
function psGetContentPageId()
{
	var pDiv = document.getElementById("p_e21_menu");
	if(pDiv)
	{
		var pH = pDiv.parentNode.getElementsByTagName("h1");
		if(pH)
		{
			var pResult = psHtmlDecode(pH[0].innerHTML);
			if(pResult.indexOf(">") > -1)
			{
				var pArr = pResult.split(">");
				return  psTrim(pArr[pArr.length - 1]);
			}
		}
	}
	return null;
}
/*
 * Get page id for content pages
*/
function psGetProducGuidePageId()
{
	var pDiv = document.getElementById("p_e21_menu");
	if(pDiv)
	{
		var pH = pDiv.parentNode.getElementsByTagName("h1");
		if(pH)
		{
			var pResult = psHtmlDecode(pH[0].innerHTML);
			if(pResult.indexOf(">") > -1)
			{
				var pArr = pResult.split(">");
				return  psTrim(pArr[pArr.length - 2]) + ":" + psTrim(pArr[pArr.length - 1]);
			}
		}
	}
	return null;
}
/*
 * Get page id for store location pages
*/
function psGetLocationName()
{
	var pDiv = document.getElementById("c_e21_menu");
	if(pDiv)
	{
		var pSpan = pDiv.getElementsByTagName("span");
		if(pSpan)
		{
			var result = psHtmlDecode(pSpan[0].innerHTML);
			return "Store locator - " + psTrim(result.replace("/",""));
		}
	}
	return null;
}
/*
 * Get the lasted of elements in G_PS_PATHNAME after "/"
*/
function psGetLastInPath()
{
	var arr = G_PS_PATHNAME.split("/");
	if(arr)
		return arr[arr.length - 1];
}
/* 
 * Find element by 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 psClearnSpecailCharacture(temp)
{
	var copyRight =String.fromCharCode(0xae);
	while (temp.indexOf(copyRight)>=0){
					temp=temp.replace(copyRight,"");
	}
	temp=temp.replace(String.fromCharCode(185),"");        
	temp=temp.replace(String.fromCharCode(42),"");
	var mark=String.fromCharCode(34);
	while (temp.indexOf(mark)>=0){
					temp=temp.replace(mark,"");
	}
	var tradeMark=String.fromCharCode(0x2122);
	while (temp.indexOf(tradeMark)>=0){
					temp=temp.replace(tradeMark,"");
	}             
	temp=temp.replace(String.fromCharCode(194),"");	
	
	temp=temp.replace(/[\n™®&*#]/gi, ""); 
	temp=temp.replace("  ", " ");	
	temp=psTrim(temp);
	return temp;
}
function psGetPageNumber()
{
	var pPageNo = 1;
	var firstResult = psGetValueFromUrl(G_PS_URL_PATH,"firstResult");
	var maxResults = psGetValueFromUrl(G_PS_URL_PATH,"maxResults");
	if(firstResult != null && maxResults != null)
	{
		firstResult = parseInt(firstResult);
		maxResults = parseInt(maxResults);
		if(maxResults != 0)
		pPageNo += firstResult/maxResults;
	}
	return pPageNo;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	
	var pValue = psTrim(psGetElementValueById("globalMessage"));
	if(pValue.toLowerCase().indexOf("did not return any matching products") > -1)
	{
		
		psCreatePageviewTag("SEARCH UNSUCCESSFUL","SEARCH",sTerm,sResult);
	}
	else
	{
		var pPageNo = psGetPageNumber();
		psCreatePageviewTag("SEARCH SUCCESSFUL " + "PAGE " + pPageNo, "SEARCH", sTerm, sResult);
	}
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	// TO-Do: Your logic to extract search term goes here
	//Your search for 'camera' in 'Cameras & Camcorders' for 'all brands' returned 22 product(s). 
	var pValue = psTrim(psGetElementValueById("globalMessage"));
	var pArr = pValue.toLowerCase().split("<strong>");

	for(var i=1; i < pArr.length; i++)
	{
		var pTemp = pArr[i].search(/([^<]*)/gi) > -1? psTrim(RegExp.$1) : 0;
		term+= pTemp.replace("' in '","") + ":";

	}
	return term.substring(0,term.length-1).replace(/[',]+/gi, "");
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	//
	// TO-Do: Your logic to extract search result goes here
	//
	var pValue = psTrim(psCleanHtmlTag(psGetElementValueById("globalMessage")));
	result = pValue.toLowerCase().search(/returned\s+(\d*)\s+product\(s\)/gi) > -1? RegExp.$1 : 0;
	return result;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()) // Get product info successfully?
	{
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
	}
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Throw page view tag
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("SHOPPING CART", G_PS_CUR_CATID, null);

	var cartTbl = null;
	//
	// TO-Do: Your logic to locate the items table (cartTbl) goes here
	//
	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)
		 */
		/* Following statements are for demonstration purpose only:
		 * if (rows[r].innerHTML.search(/ITEM #/gi)<0) // Skip rows not containing item (identified by the term "Item #")
		 *	 continue;
		 */
		if (prd.getItem5(rows[r])) // Get shop5 item successfully?
			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()
{
	// Throw page view tag
	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)
	 */
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var ord = new psOrder();
	var prd = new psProduct();

	if (ord.getOrder()) // Get order info from source code successfully?
	{
		// Post Pageviewtag as cartview
		for (var r = 0; r < rows.length; r++) // item for each row
		{
			/*
			 * Codes for skipping exceptional rows (rows don't contain items)
			 */
			/* Following statements are for demonstration purpose only:
			 * if (rows[r].innerHTML.search(/<B>PRICE<\/B>/gi)>=0) // Skip rows not containining the item
			 *	continue;
			 */
			 
			 
			if (prd.getItem9(rows[r])) // Get shop9 item successfully?
				psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, ord.cusId, ord.id, ord.subtotal, prd.catId);
		}
		// Make sure to have actual postings
		psDisplayShop9s();
		// Post order tag finally
		psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, ord.cusId, ord.city, ord.state, ord.zipCode);
		// Delete cookie after checking successfully
		psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
		    var pId = psGetElementsByClassName(document,"p", "p_e26_modelNumber");
			pId = pId.length > 0 ? psTrim(psHtmlDecode(pId[0].innerHTML)):null;
			if(pId)
				this.id = pId.search(/Model Number:\s(.*)/gi) > -1 ?RegExp.$1: null;
			var pName = psGetElementsByClassName(document, "h4", "productheading");
			this.name = pName.length > 0 ? psTrim(psHtmlDecode(pName[0].innerHTML)):null;
			if(this.name)
				this.name = psClearnSpecailCharacture(this.name);
			if(psIsProductSearchView())
			{
				this.catId = "SEARCH";
			}
			else 
				this.catId = "StoreID" + psGetValueFromUrl(G_PS_URL_PATH,"storeId") + ":Products";
			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.id = <from itemRow>
			 * this.name = <from itemRow>
			 * this.price = <from itemRow>
			 * this.quantiy = <from itemRow>
			 // 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.id = <from itemRow>
			 * this.name = <from itemRow>
			 * this.price = <from itemRow>
			 * this.quantiy = <from itemRow>
			 // 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; }
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.email = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.email != null)
			{
				var buf = this.email.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.email = buf[0];
				this.city = buf[1];
				this.state = buf[2];
				this.zipcode = buf[3];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		if (this.email == null)
			return;
		// make sure that the data contains 4 parts separated by 3 '|'
		var data = this.email + '|' + this.city + '|' + this.state + '|' + this.zipcode;
		// 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.cusId = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			/*
			 * this.id = <from source code>
			 * this.subtotal = <from source code>
			 * this.shipping = <from source code>
			 // In most cases, cusId is retrieved from from cookie G_PS_COOKIE_PROFILE as follows:
			 * this.cusId = psGetCookie(G_PS_COOKIE_PROFILE);
			 * if (this.cusId != null)
			 *	 this.cusId = this.cusId.split('|')[0]; // email as the customer id
			 */
			if (!this.id)
			{
				this.id = psGenerateRandomValue();
			}
			
			if (!this.cusId)
			{
				this.cusId = this.id;
			}
			
			 return true;
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */

function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}
/* PURPOSE: Remove all 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 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;
}

/* 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, 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);
}

/* 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 = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// 
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;

	var start = catCookie.indexOf(pKey);
	if (start >= 0) // Store before -> remove the old value
	{
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1)
			end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
	}
	
	// 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);
}

/* 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;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(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 ==================*/