/************************************************************************************/
/* $Revision: 123083 $
 * $Id: cmtaggingservices.js.txt 123083 2009-06-29 20:01:37Z lhibbard $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.3, 2009/06/29
 * COPYRIGHT 1999-2008 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/
// Set domain and prefix for each site
var G_PS_KMART = false;
var G_PS_KTAS = false;
var G_PS_PREFIX = null;
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();

var pDomain = psGetDomain(G_PS_URL_PATH);

if(pDomain.search(/kmart\.com\.au/i) >= 0){
	cm_CookieDomain = "kmart.com.au";
	G_PS_KMART = true;
	G_PS_PREFIX = "AU:";
}else if(pDomain.search(/kmart\.co\.nz/i) >= 0){
	cm_CookieDomain = "kmart.co.nz";
	G_PS_KMART = true;
	G_PS_PREFIX = "NZ:";
}else if(pDomain.search(/ktas\.com\.au/i) >= 0){
	cm_CookieDomain = "ktas.com.au";
	G_PS_KTAS = true;
	G_PS_PREFIX = "KTAS:";
}

//Production data warehouse flag
cmSetProduction();
/*===========================GLOBAL VARIABLES ===============================*/
// options for debug mode when sending tag:
// 1: only alert
// 2: only send tag
// 3: alert & send tag
var G_PS_DEBUG_MODE = 2;

var G_PS_ARR_DOMAIN = ["kmart.com.au","kmart.co.nz","ktas.com.au"]; //value must be one array of domains or null

// current page url
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;

/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!

if(G_PS_KMART || G_PS_KTAS){
	if (psIsSearchView())
	{
		psPostSearchView();
	}
	else if(psIsProductView())
	{
		//psPostProductView();
	}
	else 
	{	if(psPostPageview() == false)
			psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
	}
}

/*
 * Handle all page view
 */
function psPostPageview(){
	var pPageId = null;
	var pCatId = null;
	
	if(G_PS_PATHNAME == "/" || G_PS_PATHNAME.search(/^\/default\.asp\x*$/i) >= 0){
		pPageId = "HOME";
		pCatId = G_PS_PREFIX + pPageId;
	}else if(G_PS_PATHNAME.indexOf("/about/privacypolicy/default.asp") >= 0 ||
			G_PS_PATHNAME.indexOf("/about/privacypolicy/") >= 0 ||
			G_PS_PATHNAME.indexOf("/privacy-policy.aspx") >= 0 ){
		pPageId = "Privacy Policy";
		pCatId = G_PS_PREFIX + "HOME";
	}else if(G_PS_KMART){		
		if(G_PS_PATHNAME.indexOf("/onlineshop/order_step4.asp") >= 0){
			if(G_PS_URL_REFERRER.indexOf("onlineshop/order_step3.asp") >= 0)
				psPostRegistration();
		}
		var pTitle = document.getElementsByTagName("title");
		if(G_PS_PATHNAME.indexOf("/toysale/competition.asp") >= 0){
			// http://www.kmart.com.au/toysale/competition.asp
			pCatId = G_PS_PREFIX + "Toy Sale";
			pPageId = "Competition";			
		}else if(G_PS_PATHNAME.indexOf("/toysale/layby.asp") >= 0){
			// http://www.kmart.com.au/toysale/layby.asp
			pCatId = G_PS_PREFIX + "Toy Sale";
			pPageId = "Layby";		
		}else if(G_PS_PATHNAME.indexOf("/toysale/toysaleterms.asp") >= 0){
			// http://www.kmart.com.au/toysale/toysaleterms.asp
			pCatId = G_PS_PREFIX + "Toy Sale";
			pPageId = "Terms & Conditions";		
		}else if(unescape(G_PS_PATHNAME).search(/\/Gift\s+Cards\/html\/default\.asp/i) >= 0){
			// http://www.kmart.co.nz/Gift%20Cards/html/default.asp
			pCatId = G_PS_PREFIX + "Gift Cards";
			pPageId = "Gift Cards";
		}		
		else if(G_PS_URL_PATH.indexOf("/onlineshop/default.asp?item=no") >= 0){
			// Handle exception http://www.kmart.com.au/onlineshop/default.asp?item=no
			// After removing all products from cart
			pCatId = G_PS_PREFIX + "Shop from Home";
			pPageId = "Online";			
		}else if(G_PS_URL_PATH.search(/\/careers[\/\.]/i) >= 0 && G_PS_URL_PATH.indexOf("/about/careers/default.asp") < 0 ){
			// handle career page
			pPageId = null;
			pCatId = G_PS_PREFIX + "Careers";
			var h1Tags = psGetElementsByClassName(document,"h1","pageTitle");
			if(psCheckArrayExist(h1Tags)){
				pPageId = psTrim(psHtmlDecode(unescape(psGetInnerText(h1Tags[0]))));
			}else{
				// handle exception in NZ
				pPageId = psGetLastTitleItem();
			}
			if( (pPageId == null || pPageId == "") && psCheckArrayExist(pTitle)){				
				pPageId = psTrim(psHtmlDecode(unescape(psGetInnerText(pTitle[0]))));
			}
		}else if(G_PS_PATHNAME.indexOf("/catalogue/") >= 0){
			var pCatId = G_PS_PREFIX + "Catalogue";
			// http://www.kmart.com.au/catalogue/Catalogue.aspx?CatalogueID=134&WT.mc_id=cat|Super_Toy_&amp;_Entertainment_Sale|20090625
			var cat = null;
			var uPath = psHtmlDecode(unescape(G_PS_URL_PATH));
			if(uPath.search(/WT\.mc_id\=cat\|/i) >= 0){
				cat = uPath.replace(/^.+WT\.mc_id\=cat\|/gi,"");
				if(cat.search(/rendermode\=BASIC/i) >= 0)
					cat = cat.replace(/\&rendermode\=BASIC/i,"");
			}
			if(cat != null){
				pPageId = cat;
			}else if(psCheckArrayExist(pTitle)){
				pPageId = psTrim(psHtmlDecode(unescape(psGetInnerText(pTitle[0]))));
			}
		}else if(psCheckArrayExist(pTitle)){
			// Get pCatId and pPageId from title by default
			var sTitle = psHtmlDecode(unescape(pTitle[0].innerHTML));			
			if(sTitle.search(/\s+\>\s+/) >= 0){				
				var pItems = sTitle.split(/\s+\>\s+/);				
				if(pItems.length >= 4){					
					pCatId = G_PS_PREFIX + psTrim(pItems[pItems.length -2]);
					if(G_PS_PATHNAME.indexOf("/stores/storedetails.asp") >= 0){
						var divContainer = document.getElementById("storeDetailContainer");
						if(psCheckElementExist(divContainer)){
							var h3Tags = divContainer.getElementsByTagName("h3");
							if(psCheckArrayExist(h3Tags)){
								pPageId = psTrim(psHtmlDecode(unescape(psGetInnerText(h3Tags[0]))));
							}
						}
					}
					if(pPageId == null)
						pPageId = pItems[pItems.length -1];
				}else if(pItems.length >= 3){					
					if(G_PS_PREFIX.indexOf("NZ") >= 0 && G_PS_PATHNAME.indexOf("/stores/default.asp") >= 0 && psGetValueFromUrl(G_PS_URL_PATH,"storeid") != null ){
						// Handle exception http://www.kmart.co.nz/stores/default.asp?location=north&storeid=Albany
						pCatId = G_PS_PREFIX + psTrim(pItems[2]);
						var divContainer = document.getElementById("storesContainer");
						if(psCheckElementExist(divContainer)){
							var h1Tags = divContainer.getElementsByTagName("h1");
							if(psCheckArrayExist(h1Tags)){
								pPageId = psTrim(psGetInnerText(h1Tags[0]));
								pPageId = psTrim(psHtmlDecode(unescape(psGetInnerText(h1Tags[0]))));
							}
						}
					}else{
						pCatId = G_PS_PREFIX + psTrim(pItems[1]);
						pPageId = pItems[2];
					}
				}else if(pItems.length >= 2){
					pCatId = G_PS_PREFIX + psTrim(pItems[1]);
					pPageId = pItems[1];					
				}
			}else{				
				pPageId = sTitle;
				pCatId = G_PS_PREFIX + pPageId;
				//Handle exception: https://www.kmart.com.au/membership/registration1.asp
				if(G_PS_PATHNAME.indexOf("/membership/registration1.asp") >= 0 || G_PS_PATHNAME.indexOf("/membership_nz/registration1.asp") >= 0){
					pCatId = G_PS_PREFIX + "Subscribe to KMail";
				}
			}
		}

	}else if(G_PS_KTAS){
		var pTitle = document.getElementsByTagName("title");
		if(G_PS_PATHNAME.search(/\/service\-centres\/trading\-hours\//i) >= 0){
			pCatId = G_PS_PREFIX + "TRADING HOURS";
			var err = "";
			var h1Tags = document.getElementsByTagName("h1");
			if(psCheckArrayExist(h1Tags)){
				err = psGetInnerText(h1Tags[0]);
			}
			if(err.search(/Directory\s+Listing\s+Denied/i) < 0 && err.search(/Server\s+Application\s+Unavailable/i) < 0){
				var items = G_PS_PATHNAME.split("/");
				var lc = items[items.length - 1];
				lc = psTrim(lc.replace(/\.asp\x*/i,"")).toUpperCase();
				pPageId = lc.replace(/\-+/," ");
				pPageId = pPageId.replace(/\-+/," ");
				pPageId = pPageId.replace(/\-+/," ");
			}
		}else if(G_PS_PATHNAME.indexOf("/catalogue/catalogue.asp") >= 0){
			var pCatId = G_PS_PREFIX + "Catalogue";
			var cat = null;
			var uPath = psHtmlDecode(unescape(G_PS_URL_PATH));
			if(uPath.search(/WT\.mc_id\=cat\|/i) >= 0){
				cat = uPath.replace(/^.+WT\.mc_id\=cat\|/gi,"");
				if(cat.search(/rendermode\=BASIC/i) >= 0)
					cat = cat.replace(/\&rendermode\=BASIC/i,"");
			}
			if(cat != null){
				pPageId = cat;
			}else if(psCheckArrayExist(pTitle)){
				pPageId = psTrim(psHtmlDecode(unescape(psGetInnerText(pTitle[0]))));
			}	
		}else if(psCheckArrayExist(pTitle)){
			var sTitle = psHtmlDecode(unescape(pTitle[0].innerHTML));
			if(sTitle.search(/\s+\-\s+/) >= 0){				
				var pItems = sTitle.split(/\s+\-\s+/);
				if(pItems.length >= 4){
					pPageId = psTrim(pItems[0]) + " - " + psTrim(pItems[1]);
					pCatId = G_PS_PREFIX + psTrim(pItems[2]);
				}else if(pItems.length >= 3){					
					pPageId = pItems[0];
					pCatId = G_PS_PREFIX + psTrim(pItems[1]);
				}else if(pItems.length >= 2){
					pPageId = pItems[0];
					pCatId = G_PS_PREFIX + psTrim(pItems[0]);
				}
			}else{
				pPageId = sTitle;
				pCatId = G_PS_PREFIX + pPageId;
			}
		}		
	}
	
	if(pPageId == null)
		return false;
	
	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));
	if(pPageId.search(/The\s+page\s+cannot\s+be\s+found/i) < 0)
		psCreatePageviewTag(pPageId, pCatId, null, null);
	return true;
}

function psGetLastTitleItem(){
	var pTitle = document.getElementsByTagName("title");
	if(psCheckArrayExist(pTitle)){
		var sTitle = psHtmlDecode(unescape(pTitle[0].innerHTML));
		if(sTitle.search(/\s+\>\s+/) >= 0){
			var pItems = sTitle.split(/\s+\>\s+/);
			return psTrim(psHtmlDecode(unescape(pItems[pItems.length -1])));
		}
	}
	return null;
}

function psPostRegistration(){
	var frmTags = document.getElementsByName("frmProduct");
	if(psCheckArrayExist(frmTags)){
		var uP = new psProfile();
		//uP.city = psGetItem(frmTags[0],"Suburb");
		uP.state = psGetItem(frmTags[0],"State");
		uP.zipcode = psGetItem(frmTags[0],"Postcode");
		uP.email = psGetItem(frmTags[0],"Email");
		if(uP.email == null) 
			uP.email = psGenerateRandomValue();
		uP.cusId = uP.email;		
		psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, G_PS_PREFIX.replace(":",""));
	}
}

function psGetItem(frm, item){
	var div1 = psGetElementsByClassName(frm,"div","column1");
	var div2 = psGetElementsByClassName(frm,"div","column2");
	if(psCheckArrayExist(div1)){
		for(var i=0; i<div1.length; i++){
			var itemStr =  psTrim(psGetInnerText(div1[i]));
			if(itemStr != null && itemStr.toLowerCase() == item.toLowerCase() ){
				if(psCheckElementExist(div2[i])){
					return psTrim(psGetInnerText(div2[i]));
				}
			}
		}
	}
	return null;
}
/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	if(G_PS_KTAS && G_PS_PATHNAME.indexOf("/service-centres/location-search-results.aspx") >= 0)
		return true;
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	if(G_PS_KMART && G_PS_URL_PATH.search(/\/onlineshop\/default\.asp\?showimage\=/i) >= 0)
		return true;
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	//
	// TO-Do: Your logic to determine the shopping cart page goes here
	//
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	//
	// TO-Do: Your logic to determine the receipt page goes here
	//
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	G_PS_CUR_CATID = G_PS_PREFIX + "SEARCH";	
	var sTerm = psGetSearchTerm();	
	/* Search results are included in iframe with different domain, so we can't get them
	<iframe id="ctl00_ContentPlaceHolder1_ifrm_Map" width="690" height="800" frameborder="0" scrolling="no" noresize="noresize"
	src="http://www.nowwhere.com.au/colesgroup/kmarttyreandauto/default.aspx?postcode=&amp;suburb=sa 5000&amp;state=&amp;address="></iframe>
	*/
//	var pageId = "SEARCH SUCCESSFUL";
//	var sResult = psGetSearchResult();
//	if(sResult == "0")
//		pageId = "SEARCH UNSUCCESSFUL";

	var sResult = null;
	pageId = "LOCATION SEARCH RESULTS";
	if (pageId != null){
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);		
	}
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	var postcode = psGetValueFromUrl(G_PS_URL_PATH,"postcode");
	if(psCheckElementExist(postcode)){
		postcode = psTrim(psHtmlDecode(unescape(postcode)));
		if(postcode != "") 
			term += " " + postcode;
	}
	var suburb = psGetValueFromUrl(G_PS_URL_PATH,"suburb");
	if(psCheckElementExist(suburb)){
		suburb = psTrim(psHtmlDecode(unescape(suburb)));
		if(suburb != "") 
			term += " " + suburb;
	}
	var state = psGetValueFromUrl(G_PS_URL_PATH,"state");
	if(psCheckElementExist(state)){
		state = psTrim(psHtmlDecode(unescape(state)));
		if(state != "") 
			term += " " + state;
	}
	var addr = psGetValueFromUrl(G_PS_URL_PATH,"address");
	if(psCheckElementExist(addr)){
		addr = psTrim(psHtmlDecode(unescape(addr)));
		if(addr != "") 
			term += " " + addr;
	}	
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";	
	var mapFrame = psGetMapFrame();	
	if(psCheckElementExist(mapFrame)){
		var h1Tags = mapFrame.getElementsByTagName("h1");		
		if(psCheckArrayExist(h1Tags) && h1Tags[0].innerHTML.search(/The\s+page\s+cannot\s+be\s+found/i) >= 0){			
			alert(h1Tags[0].innerHTML);
			return "0";
		}
		// Count results from combox
		//var cbResults = mapFrame.getElementsByName("cmbMultiple");		
		var cbResults = mapFrame.getElementsByTagName("select");
		if(psCheckArrayExist(cbResults)){
			for(var i=0 ; i<cbResults.length; i++){
				alert(cbResults[i].getAttribute("name"));
				if(cbResults[i].getAttribute("name") == "cmbMultiple"){					
					result = cbResults[0].options.length - 1;
				}
			}
		}else{			
			if(mapFrame.innerHTML.search(/nearest\s+stores\s+to/i) >= 0) 
				return 1;
		}		
	}
	return result;
}

function psGetMapFrame(){
	var mapFrames = document.getElementsByTagName("iframe");
	if(psCheckArrayExist(mapFrames)){
		for(var i=0; i<mapFrames.length; i++){			
			if(mapFrames[i].getAttribute("src") != null && mapFrames[i].getAttribute("src").search(/www\.nowwhere\.com\.au/i) >= 0)				
				return mapFrames[i];
		}
	}
	return null;
}
/*
 * 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()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("SHOPPING CART", G_PS_CUR_CATID, null);

	var cartTbl = null;
	//
	// 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]))
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
	}
	// Make sure to have actual postings
	psDisplayShop5s();
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("THANK YOU", G_PS_CUR_CATID, null);

	var cartTbl = null;
	/*
	 * Codes for locating the table containing items (each row for an item)
	 */
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var ord = new psOrder();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var r = 0; r < rows.length; r++) // item for each row
			{
				/*
				 * Codes for skipping exceptional rows (rows don't contain items)
				 */
				/* 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]))
					psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
			}
			// Make sure to have actual postings
			psDisplayShop9s();
			psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.cusId, uP.city, uP.state, uP.zipcode);
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
			psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	this.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
		this.price = null;
		this.quantity = null;
	}
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!			
			var prdId = psGetValueFromUrl(G_PS_URL_PATH,"showimage");
			if(prdId != null)
				this.id = prdId.replace(/\#\d*$/,"").toUpperCase();
			var preDiv = psGetElementsByClassName(document,"div","largePreview");
			if(psCheckArrayExist(preDiv)){
				var div2 = psGetElementsByClassName(preDiv[0],"div","description2");
				if(psCheckArrayExist(div2)){
					this.name = psTrim(psHtmlDecode(unescape(psGetInnerText(div2[0]))));
				}
			}
			this.catId = "Online Shop";
			//psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);

			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the shopping cart
	 */
	this.getItem5 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			/*
			 * this.id = <from itemRow>
			 * this.name = <from itemRow>
			 * this.price = <from itemRow>
			 * this.quantity = <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.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			/*
			 * this.id = <from itemRow>
			 * this.name = <from itemRow>
			 * this.price = <from itemRow>
			 * this.quantity = <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.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.cusId = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.cusId != null)
			{
				var buf = this.cusId.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				this.cusId = buf[0];
				if (!this.cusId)
					this.cusId = psGenerateRandomValue();
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		try
		{
			if (this.cusId == null)
				return;
			// make sure that the data contains 4 parts separated by 3 '|'
			var data = this.cusId + "|" + this.email + '|' + this.city + '|' + this.state + '|' 
				+ this.zipcode + "|" + this.newsletter + '|' + this.subscribe;
			// store on cookie
			psSetCookie(G_PS_COOKIE_PROFILE, data);
			//
			// NOTE: To persist profile as persistent cookie, pass G_PS_COOKIE_LIFETIME as the third param instead of null
			// psSetCookie(G_PS_COOKIE_PROFILE, data, G_PS_COOKIE_LIFETIME);
			//
			return true;
		}
		catch (ex) { return false; }
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			/*
			 * this.id = <from source code>
			 * this.subtotal = <from source code>
			 * this.shipping = <from source code>
			 */
			if (!this.id)
				this.id = psGenerateRandomValue();
			/*
			 * Extract user profile from source code
			 */
			var uP = new psProfile();
			uP.readProfile();  // Ensure to get the customer Id & email persisted at login stage
			/*
			 * uP.city = <from source code>
			 * uP.state = <from source code>
			 * uP.zipcode = <from source code>
			 * uP.newsletter = <from source code>
			 * uP.subscribe = <from source code>
			 */
			 if (!uP.cusId)
				uP.cusId = psGenerateRandomValue();
			return uP.writeProfile(); // Persist profile for later use at Receipt stage
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all unaccepted characters in categoryid, including
 * [, ', ", :, comma,]
 * RETURN: string
 */
function psCleanCatId(pCatId)
{
    //return (pCatId != null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
	return (pCatId != null) ? pCatId.replace(/[\'\",\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

function psCleanProductName(pProductName)
{
	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

/* PURPOSE: Remove all leading & trailing spaces of a string
 * Note: [&nbsp;] is also considered as a space
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;
	return (pStr != null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

/* PURPOSE: extract value from the URL
 * in format of http://xxx.com/page.ext?key1=value1&key2=value2
 * or key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
function psGetValueFromUrl(pUrl, pKey)
{
	pUrl = (pUrl != null) ? "?" + psTrim(pUrl.toLowerCase()) : null;
	pKey = (pKey != null) ? psTrim(pKey.toLowerCase()) : null;

	if (pUrl == null || pKey == null || pUrl.indexOf(pKey) == -1) 
		return null;
	
	var start = pUrl.indexOf('&' + pKey + '=');
	start = (start == -1) ? pUrl.indexOf('?' + pKey + '=') : start;
	if (start >= 0)
	{
		start = start + pKey.length;
		var end = pUrl.indexOf("&", start);
		if(end == -1) 
			end = pUrl.length;
		var middle = pUrl.indexOf("=", start);
		return pUrl.substring(middle + 1, end);
	}
	return null;
}

/* PURPOSE: returns the value of an element based on element_id
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 */
function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}

/* PURPOSE: returns the value of an element based on element object
 * Note: this function returns decoded text
 * to avoid "double" decode, don't invoke psHtmlDecode on returned value again
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 *  NULL: if element not exist
 */
function psGetElementValue(pTagObj, pValueFlag)
{
    var tagValue = null;
    if (pTagObj != null)
    {
        if (pTagObj.tagName.search(/^INPUT$/i) > -1)
            tagValue = pTagObj.value;
        else if (pTagObj.tagName.search(/^SELECT$/i) > -1)
        {
            if (pValueFlag == true)
                tagValue = pTagObj.options[pTagObj.selectedIndex].value;
            else
                tagValue = psHtmlDecode(pTagObj.options[pTagObj.selectedIndex].innerHTML);// return label instead of value
        }
        else
            tagValue = psHtmlDecode(pTagObj.innerHTML);
    }

    return tagValue;
}

/* PURPOSE: validate email format
 * RETURN: boolean
 */
function psCheckEmail(pEmail) 
{
    if (pEmail)
    {
        var i = pEmail.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
        return (i > -1);
    }

    return false;
}

/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
function psHtmlDecode(pValue)
{
    if (pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
    }

    return pValue;
}

/* PURPOSE: extract main domain from the URL
 * RETURN: main domain
 */
function psGetMainDomain(pUrl){
	var se = /^https*\:\/\/([^\/\:]+)/gi;
	var domain = (pUrl.search(se) > -1) ? RegExp.$1 : null;
	if(domain != null)
	{
		if(domain.indexOf("www")==0)
		{
			domain = domain.substring(4,domain.length);
		}
		if(G_PS_ARR_DOMAIN != null)
		{
			for(var i =0; i<G_PS_ARR_DOMAIN.length; i++)
			{
				se = new RegExp("[\.]" + G_PS_ARR_DOMAIN[i] + "$","gi");
				if(("." + domain).search(se) > -1)
				{
					domain = G_PS_ARR_DOMAIN[i];
					break;
				}
			}
		}
		domain = "." + domain;
	}
	return domain;
	
}

/* PURPOSE: extract domain part in the URL
 * RETURN: domain
 */
function psGetDomain(pUrl){
    var se = /^https*\:\/\/([^\/\:]+)/gi;
    return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}

/* PURPOSE: remove unnecessary characters (dollar sign, comma, quote, minus, etc) 
 * from price to make it work properly with parseFloat/parseInt
 * RETURN: well-formed price
 */
function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

/* PURPOSE: retrieve cookie value
 * RETURN: string
 */
function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if (!pCookieName || !cookies)
		return null;

	cookies = "; " + cookies.toLowerCase();
	var key = "; " + pCookieName.toLowerCase() + "=";
	var start = cookies.lastIndexOf(key);
	if (start >= 0)
	{
		start = start + key.length;
		var end = cookies.indexOf(";", start);
		if (end == -1)
			end = cookies.length;

		return unescape(cookies.substring(start, end));
	}

    return null;
}

function psCookieBase(pCookieName, pCookieValue, pLifeTime)
{
	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
	if(pLifeTime == "delete") 
	{         
		return true;
	}
	
	// set cookie by calling coremetrics's cookie function
	var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
	
	return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

function encodeHtml(strValue)
{
	if (strValue!=null)
	{
		strValue = escape(strValue);
		strValue = strValue.replace(/\//g,"%2F");
		strValue = strValue.replace(/\?/g,"%3F");
		strValue = strValue.replace(/=/g,"%3D");
		strValue = strValue.replace(/&/g,"%26");
		strValue = strValue.replace(/@/g,"%40");
	}
	return strValue;
}

/* PURPOSE: set cookie value
 * Note: if the designated cookie is too big, the old items will be removed
 * because cookie size is limited to 4K
 * @pLifeTime in seconds
 * pDomain: don't specify if using current domain
 * RETURN: boolean
 */
function psSetCookie(pCookieName, pCookieValue, pLifeTime)
{
	if (!pCookieName)
	{
		return false;
	}
	
	pCookieValue = (pCookieValue==null)? "null":pCookieValue;
	
	if(pLifeTime != "delete")
	{
		pCookieName = psTrim(pCookieName);
		var oldCookieValue = psGetCookie(pCookieName);
		oldCookieValue = (oldCookieValue==null)? "null":oldCookieValue;
		var totalSize;
		if(document.cookie.indexOf(pCookieName)>-1)
		{
			totalSize =  document.cookie.length + encodeHtml(pCookieValue).length - encodeHtml(oldCookieValue).length;
		}
		else
		{
			totalSize =  document.cookie.length  + encodeHtml(pCookieValue).length + encodeHtml(pCookieName).length;
		}
		if(totalSize > 3500)
		{
			return false;
		}
	}
	psCookieBase(pCookieName,pCookieValue,pLifeTime);
}

/* PURPOSE: set value in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 * NOTE: Use null or '' for pValue to remove the pair specified by pKey
 */
function psSetValueToCookie(pCookieName, pKey, pValue)
{
	if (!pCookieName || !pKey)
	{
		return false;
	}

	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;
	pValue = (pValue == null) ? "null" : pValue;
	var oldCatCookie = catCookie;
	
	var start = catCookie.indexOf(pKey);
	
	var totalsize;
	if (start >= 0) // Store before -> remove the old value
	{
		var oldValue = psGetValueFromCookie(pCookieName,pKey.replace(/[\~\#]/gi,""));
		oldValue = (oldValue == null) ? "null" : oldValue;
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1)
			end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length - encodeHtml(oldValue).length;
	}
	else
	{
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length;  
		if(document.cookie.indexOf(pCookieName)<0)
		{
			totalsize += encodeHtml(pCookieName).length;
		}
	}
	catCookie = pKey + pValue + catCookie;
	var cookieArray = null;   
	//Check existed ?
	while (totalsize > 3500)
	{
		var l1 = encodeHtml(catCookie).length;//length before pop
		cookieArray = catCookie.split("#");
		cookieArray.pop();
		catCookie = cookieArray.join("#");
		var l2 = encodeHtml(catCookie).length;//length after pop                                                        
		totalsize -=  (l1-l2);
	}   
	if(catCookie == null || catCookie == "")
	{
		catCookie = oldCatCookie;
	}
	// Save to cookie              
	psCookieBase(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

/* PURPOSE: get value stored in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 */
function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if (catCookie != null)
    {
        var start = catCookie.indexOf(pKey);
		if (start >=0 )
		{
			start = start + pKey.length;
			var end = catCookie.indexOf("#", start);
			if (end == -1)
				end = catCookie.length;
			return catCookie.substring(start, end);
		}
		return null;
    }
    return null;
}

/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dtDate = new Date();
	var cusRandom = (dtDate.getTime()%10000000) + (Math.floor(Math.random()*10000));
	return cusRandom;
}

function psShorttenPageID(pLink)
{
	var temp1 = pLink;
	if (temp1 != null)
	{
		temp1 = (temp1.length > 255) ? temp1.substr(0, 255) : temp1;
	}
	return temp1;
}

function psCheckArrayExist(pArrElement){
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0)
    {
        return false;
    }

    return true;
}
function psCheckElementExist(pElement){
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }

    return true;
}

function psGetElementsByClassName(psDocument, psElementTagName, psClassName){
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null)
    {
        return null;
    }
    for(var i = 0; i < arrInputs.length; i ++ )
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(pId);
	pId = psShorttenPageID(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + pId + ", " + pName + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(pId, pName, pCatId);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId);    
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
	pOrderTotal = psCleanPrice(pOrderTotal);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCusID + ", " + pOrderID + ", " + pOrderTotal + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId);
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip) 
{
	pOrderTotal = psCleanPrice(pOrderTotal);
	pOrderShipping = psCleanPrice(pOrderShipping);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + pId + ", " + pOrderTotal + ", " + pOrderShipping + ", " + pCusID + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip);
}

function psCreateConversionEventTag(pId, pActionType, pCatID, pPoints) 
{
	pCatID = psCleanCatId(pCatID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + pId + ", " + pActionType + ", " + pCatID + ", " + pPoints + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(pId, pActionType, pCatID, pPoints);
}

function psCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pNewsletter + ", " + pSubscribe + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe);
}

function psCreateErrorTag(pPageID, pCatId) 
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateErrorTag(" + pPageID + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateErrorTag(pPageID, pCatId);
}

function psDisplayShop5s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop5s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop5s();
}

function psDisplayShop9s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop9s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop9s();
}
/*===========================END GENERAL UTILITY FUNCTION ==================*/
