/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v3.1, 2010/03/19
 * COPYRIGHT 1999-2008 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/
//Production data warehouse flag
cmSetProduction();
/*===========================GLOBAL VARIABLES ===============================*/
// options for debug mode when sending tag:
// 1: only alert
// 2: only send tag
// 3: alert & send tag
var G_PS_DEBUG_MODE = 2;

var G_PS_ARR_DOMAIN = new Array("identitydirect.com.au","identitydirect.co.nz","identitydirect.ca","identitydirect.co.uk","identitydirect.com","mislibrosdeaventuras.com");

// 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_PRE_CATID = "PS_PRE_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_SHOP5 = "PS_SHOP5";
var G_PS_COOKIE_ORDER = "PS_ORDER";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";
var G_PS_COOKIE_PREFIX = "PS_PREFIX";
var G_PS_COOKIE_FAVOURITE = "PS_FAVOURITE";
var G_PS_CUR_CATID = null;
/*========================= END GLOBAL VARIABLES =============================*/

// Set prefix for pageview based on domain
/* If variable "cm_CookieDomain" is not a dynamic definition in cmdatatagutils.js
   we can enable values for it here
*/
var G_PS_PREFIX = "";
var G_PS_DOMAIN = psGetDomain(G_PS_URL_PATH);

if (G_PS_DOMAIN != null)
{
	if(G_PS_DOMAIN.search(/identitydirect\.com\.au/i) >= 0){
		G_PS_PREFIX = "";
		//cm_CookieDomain = "identitydirect.com.au";
	}else if(G_PS_DOMAIN.search(/identitydirect\.co\.nz/i) >= 0){
		G_PS_PREFIX = "NZ:";
		//cm_CookieDomain = "identitydirect.co.nz";
	}else if(G_PS_DOMAIN.search(/identitydirect\.ca/i) >= 0){
		G_PS_PREFIX = "CA:";
		//cm_CookieDomain = "identitydirect.ca";
	}else if(G_PS_DOMAIN.search(/identitydirect\.co\.uk/i) >= 0){
		G_PS_PREFIX = "UK:";
		//cm_CookieDomain = "identitydirect.co.uk";
	}else if(G_PS_DOMAIN.search(/identitydirect\.com$/i) >= 0){
		G_PS_PREFIX = "US:";
		//cm_CookieDomain = "identitydirect.com";
	}else if(G_PS_DOMAIN.search(/mislibrosdeaventuras\.com/i) >= 0){
		G_PS_PREFIX = "SP:";
		//cm_CookieDomain = "mislibrosdeaventuras.com";
	}
}

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!

if (G_PS_URL_PATH.search(/identitydirect\./i) >= 0 || G_PS_URL_PATH.search(/mislibrosdeaventuras\.com/i) >= 0){
	
	if (psIsSearchView())
	{	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		if(psPostSearchView() == false){
			psTryPostSearchView();
		}
	}
	else if (psIsProductView())
	{
		psPostProductView();
	}
	else if (psIsCartView())
	{
		psPostCartView();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else if(psPostPageView() == false)
	{	
		if(psIsSkipPage() == false){
			psCreatePageviewTag(G_PS_PATHNAME, "ADD URL");
		}		
	}
	if (psIsProductView() == false){
		psHijackAddToBasket_FromCateogry();
	}	
}

function psTryPostSearchView(){
	// wait for loading elements, post search result after 2s, 4s, 8s
	window.setTimeout("psPostSearchView()",2000);
	window.setTimeout("psPostSearchView()",4000);
	window.setTimeout("psPostSearchView()",8000);
}

function psPostPageView(){
	var pPageId = null;
	var pCatId = null;
	
	var pIsSubscribePage = false;
	
	if(G_PS_PATHNAME.search(/contents\/en\-(uk|us|ca)\/d11\.html/i) >= 0 ||
	   G_PS_PATHNAME.search(/contents\/en\-uk\/d126\.html/i) >= 0 ||
	   G_PS_PATHNAME.search(/contents\/es\/d14\.html/i) >= 0 ){
	   /* The title is "Contact Us", but it will navigate to "Subscribe" page: http://enews.identitydirect.com/rp//372/ContestForm.clsp
	      So we handle in http://enews.identitydirect.com/rp//372/ContestForm.clsp */
	   return true;
	}
	
	if(G_PS_PATHNAME.search(/contents\/en\-uk\/d14\.html/i) >= 0){
		pCatId = pPageId = "Fundraising Registration";		
	}else if(G_PS_PATHNAME.indexOf("372/form.clsp") >= 0){
		pPageId = "Thank you for subscribing";
		pCatId = "Subscribe";
		pIsSubscribePage = true;
		// This page have the same domain with Subscribe page, so we can retrieve prefix from cookie
		var prefix = psGetCookie(G_PS_COOKIE_PREFIX);
		if(prefix != null && prefix != ""){
			prefix = prefix.toUpperCase();
			pPageId = prefix + pPageId;
			pCatId = prefix + pCatId;
		}
	}else if(psIsSubscribe()){
		// Tagging code should be included into http://enews.identitydirect.com/rp//372/ContestForm.clsp
		pPageId = pCatId = "Subscribe";		
		psHijackSubscribe();
		pIsSubscribePage = true;
		var prefix = "";
		var FormId = psTrim(psGetValueFromUrl(G_PS_URL_PATH,"FormId"));
		if(FormId == "5428") prefix = ""; // Australia
		if(FormId == "5514") prefix = "CA:"; // Canada
		if(FormId == "5511") prefix = "NZ:"; // New Zealand
		if(FormId == "5512") prefix = "UK:"; // United Kingdom
		if(FormId == "5513") prefix = "US:"; // United State
		if(FormId == "8292") prefix = "SP:"; // Spanish
		if(FormId == "5589" || FormId == "7856"){
			// Write review form or Fundraising Registration
			return true;
		}
		psSetCookie(G_PS_COOKIE_PREFIX,prefix);
		pPageId = prefix + pPageId;
		pCatId = prefix + pCatId;		
	}else if(G_PS_PATHNAME.indexOf("/checkout.php") >= 0){
		pPageId = pCatId = "Checkout";
		if(G_PS_PREFIX == "SP:") pPageId = pCatId = "Caja";
		psSaveOrderInfo();
		psHijackBillingAddress();
	}else if(psIsHomePage()){
		pPageId = pCatId = "Home";
	}else{
		// Get from <DIV class="GC17 PageTitle"
		var pageTitles = psGetElementsByClassName(document,"div","GC17 PageTitle");
		if(psCheckArrayExist(pageTitles)){
			pPageId = pCatId = psTrim(psGetInnerText(pageTitles[0]));
		}else{		
			/* Get from page description, exception for "Clock", "Placemat" and "Poems"
				Australia(en-uk): d61,62,63
				NewZealand(en-uk): d58,59,60
				Canada(en-ca): d3,39,40
				United Kingdom (en-uk): d58,75,60
				United State (en-us): d46, d65, d47 */
			var pDes = psGetPageDescription();
			if( (G_PS_PATHNAME.search(/contents\/en\-uk\/d(61|62|63|58|59|60|75)\.html/i) >= 0 ||
			    G_PS_PATHNAME.search(/contents\/en\-ca\/d(3|39|40)\.html/i) >= 0 ||
				G_PS_PATHNAME.search(/contents\/en\-us\/d(46|65|47)\.html/i) >= 0 )
			   && pDes != null){
				if(pDes.search(/personalised\s+wall\s+clocks/i) >= 0){							
					pDes = "Personalised Clocks";
				}else if(pDes.search(/personalized\s+wall\s+clocks/i) >= 0){							
					pDes = "Personalized Clocks";
				}
					
				pPageId = pCatId = pDes;
			}else{
				// Get from title
				var titles = document.getElementsByTagName("title");
				if(psCheckArrayExist(titles)){
					var title = psTrim(psGetInnerText(titles[0]));
					if(title != null && title != ""){
						if(title.indexOf("-") >= 0){
							pPageId = pCatId = psTrim(title.split("-")[0]);
						}else{
							pPageId = pCatId = title;
						}
					}
				}
			}
		}
	}

	if(pPageId == null || pCatId == null){
		return false;
	}

	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));
	
	pPageId = pPageId.toUpperCase();
	pCatId = pCatId.toUpperCase();
	
	pPageId = pPageId.replace(/\,/g,"");
	pCatId = pCatId.replace(/\,/g,""); 	
	
	if(pPageId == "FAVOURITES" || pPageId == "FAVORITES" || 
	   G_PS_PATHNAME.indexOf("/favorites.htm") >= 0 || G_PS_PATHNAME.indexOf("/favourites.htm") >= 0){		
		psHijackAddToBasket_FromFavourite();
	}
	
	if(pIsSubscribePage == false){
		pPageId = G_PS_PREFIX + pPageId;
		pCatId = G_PS_PREFIX + pCatId;
	}
	
	var preClick = psGetCookie(G_PS_COOKIE_PRE_CATID);
	var prePage = psGetCookie(G_PS_COOKIE_CATID);
	var searchPageId = G_PS_PREFIX + "SEARCH";
	if(preClick != null && preClick.toLowerCase() == searchPageId.toLowerCase() &&
	   prePage != null && prePage.toLowerCase() == searchPageId.toLowerCase()){
		// the previous page is search
		pCatId = searchPageId;		
	}else{
		psSetCookie(G_PS_COOKIE_PRE_CATID,"","delete");		
	}
	
	psCreatePageviewTag(pPageId, pCatId, null, null);	
	psSetCookie(G_PS_COOKIE_CATID,pPageId);
	
	return true;
}

function psHijackAddToBasket_FromFavourite(){
	var fTables = psGetElementsByClassName(document,"table","ViewbasketMaster");
	if(psCheckArrayExist(fTables)){
		var rows = fTables[0].rows;
		for(var i=0; i<rows.length; i++){
			if(rows[i].innerHTML != null && rows[i].innerHTML.search(/add2basket\d*\.png/i) >= 0){
				if(rows[i].cells.length < 3) continue;
				var prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(rows[i].cells[1])))));
				if(prdName == null || prdName == "") continue;
				var aTags = rows[i].getElementsByTagName("a");
				if(psCheckArrayExist(aTags)){
					for(var j=0; j<aTags.length; j++){
						var aTag = aTags[j];
						if(aTag.innerHTML != null && aTag.innerHTML.search(/add2basket\d*\.png/i) >= 0){				
							if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJAddToBasket") < 0){								
								aTag.prdName = prdName;								
								aTag.OldFunction = (aTag._c_onclick != null) ?  aTag._c_onclick: aTag.onclick;
								aTag.onclick = function psHJAddToBasket_FromFavourite(){									
									var prdId = psGetValueFromCookie(G_PS_COOKIE_FAVOURITE,this.prdName);
									var curPage = psGetCookie(G_PS_COOKIE_CATID);
									if(prdId != null && prdId != ""){
										psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prdId,curPage);
										psSetValueToCookie(G_PS_COOKIE_PROD_NAME,this.prdName,prdId);
									}									
									if(this.OldFunction != null)
											return this.OldFunction();
								}
							}
						}
					}
				}				
			}
		}
	}
}

function psHijackAddFavourite(prdId,prdName){
	if(prdId == null || prdName == null)
		return;
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags)){
		for(var j=0; j<aTags.length; j++){
			var aTag = aTags[j];
			if(aTag.innerHTML != null && aTag.innerHTML.search(/favourites\.png/i) >= 0){				
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJAddFavourite") < 0){					
					aTag.prdId = prdId;
					aTag.prdName = prdName;					
					aTag.OldFunction = (aTag._c_onclick != null) ?  aTag._c_onclick: aTag.onclick;
					aTag.onclick = function psHJAddFavourite(){						
						psSetValueToCookie(G_PS_COOKIE_FAVOURITE,this.prdName,this.prdId);						
						if(this.OldFunction != null)
								return this.OldFunction();
					}
				}
			}
		}
	}	
}

function psConvertCurrency(pCurrency){
	// Convert currency to Australia currency
	if(G_PS_PREFIX == ""){
		// Australia site, not change
		return pCurrency;
	}
	pCurrency = parseFloat(pCurrency);
	var currentCurrency = 1;
	if(isFinite(pCurrency)){	
		if(G_PS_PREFIX == "NZ:" && psCheckElementExist(CURRENCY_NZD)){
			currentCurrency = parseFloat(CURRENCY_NZD);			
		}else if(G_PS_PREFIX == "CA:" && psCheckElementExist(CURRENCY_CAD)){
			currentCurrency = parseFloat(CURRENCY_CAD);			
		}else if(G_PS_PREFIX == "UK:" && psCheckElementExist(CURRENCY_GBP)){
			currentCurrency = parseFloat(CURRENCY_GBP);			
		}else if(G_PS_PREFIX == "US:" && psCheckElementExist(CURRENCY_USD)){
			currentCurrency = parseFloat(CURRENCY_USD);	
		}else if(G_PS_PREFIX == "SP:" && psCheckElementExist(CURRENCY_USD)){
			currentCurrency = parseFloat(CURRENCY_USD);	
		}
		if(isFinite(currentCurrency)){			
			pCurrency = pCurrency*currentCurrency;
			pCurrency = pCurrency.toFixed(2);
		}		
	}	
	return pCurrency;
}

function psSaveOrderInfo(){
	// Save subtotal and shipping cost
	var disTable = document.getElementById("disTable");
	if(psCheckElementExist(disTable)){
		var rows = disTable.rows;
		for(var i=0; i<rows.length; i++){
			if(psGetInnerText(rows[i]) != null && psGetInnerText(rows[i]).search(/(Total\s+Products|Total\s+Productos)/i) >= 0){
				var subtotal = psConvertCurrency(psCleanPrice(psGetInnerText(rows[i].cells[1])));
				psSetValueToCookie(G_PS_COOKIE_ORDER,"subtotal",subtotal);
			}else if(psGetInnerText(rows[i]) != null && psGetInnerText(rows[i]).search(/(Postage\s+and\s+Handling|Shipping|Env.*o)/i) >= 0){
				var shipping = psConvertCurrency(psCleanPrice(psGetInnerText(rows[i].cells[1])));
				psSetValueToCookie(G_PS_COOKIE_ORDER,"shipping",shipping);
			}

		}
	}
}

function psHijackBillingAddress(){
	// Save Billing Email for registration
	var processBtn = psGetElementByName("input","process");
	if(psCheckElementExist(processBtn)){		
		if(processBtn.onclick == null || processBtn.onclick.toString().indexOf("psHJBillingAddress") < 0){			
			processBtn.OldFunction = processBtn.onclick;
			processBtn.onclick = function psHJBillingAddress(){				
				var emailTag = psGetElementByName("input","email");
				if(psCheckElementExist(emailTag)){					
					var email = emailTag.value;					
					if(psCheckEmail(email)){						
						var city = psGetElementByName("input","suburb");
						var state = psGetElementByName("select","state");
						var zipcode = psGetElementByName("input","pcode");						
						var uP = new psProfile();
						uP.cusId = uP.email = psTrim(email);
						if(psCheckElementExist(city)) uP.city = psTrim(city.value);
						if(psCheckElementExist(state)) uP.state = state.options[state.selectedIndex].value;
						if(psCheckElementExist(zipcode)) uP.zipcode = psTrim(zipcode.value);
						uP.writeProfile();						
					}					
				}
				if(this.OldFunction != null) 
					return this.OldFunction();
			}
		}
	}	
}

function psHijackAddToBasket_FromCateogry(){
	var prd4Tds = psGetElementsByClassName(document,"td","GC4 Product");
	var prd14Tds = psGetElementsByClassName(document,"td","GC14 Product");
	if(psCheckArrayExist(prd14Tds)){
		if(psCheckArrayExist(prd4Tds)){
			prd4Tds = prd4Tds.concat(prd14Tds);
		}else{
			prd4Tds = prd14Tds;
		}
	}
	// Exception for Labels
	var pTables = psGetElementsByClassName(document,"table","Product");
	if(psCheckArrayExist(pTables)){
		if(psCheckArrayExist(prd4Tds)){
			prd4Tds = prd4Tds.concat(pTables);
		}else{
			prd4Tds = pTables;
		}
	}
	
	if(psCheckArrayExist(prd4Tds) == false) return;
	for(var i=0; i<prd4Tds.length; i++){
		var prdTd = prd4Tds[i];
		var prdId = null;
		var prdName = null;
		if(prdTd.id != null)
			prdId = psTrim(prdTd.id);
		var h2Tags = prdTd.getElementsByTagName("h2");
		if(psCheckArrayExist(h2Tags)){
			prdName = psTrim(psCleanProductName(psHtmlDecode(unescape(psGetInnerText(h2Tags[0])))));
		}
		var aTags = prdTd.getElementsByTagName("a");
		if(psCheckArrayExist(aTags) && prdId != null && prdName != null){
			for(var j=0; j<aTags.length; j++){
				var aTag = aTags[j];
				if(aTag.innerHTML != null && aTag.innerHTML.search(/add2basket\d*\.png/i) >= 0){
					if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJAddToBasket") < 0){
						aTag.prdId = prdId;
						aTag.prdName = prdName;
						/*It worked incorrect if using local variable "OldFunction", 
						when clicking on the hyper link, OldFunction contained the last aTag instead of the clicked aTag
						so bought item is different from clicked item */						
						//var OldFunction = (aTag._c_onclick != null) ?  aTag._c_onclick: aTag.onclick;
						aTag.OldFunction = (aTag._c_onclick != null) ?  aTag._c_onclick: aTag.onclick;
						aTag.onclick = function psHJAddToBasket_FromCategory(){
							var curCatId = psGetCookie(G_PS_COOKIE_PRE_CATID);
							if(curCatId == null || curCatId == ""){
								curCatId = psGetCookie(G_PS_COOKIE_CATID);
							}							
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdId,curCatId);
							psSetValueToCookie(G_PS_COOKIE_PROD_NAME,this.prdName,this.prdId);							
							if(this.OldFunction != null)
								return this.OldFunction();
						}
					}
				}
				// For Favourite
				if(aTag.innerHTML != null && aTag.innerHTML.search(/favourites\.png/i) >= 0){
					if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJAddFavourite_FromCat") < 0){
						aTag.prdId = prdId;
						aTag.prdName = prdName;
						aTag.OldFunction = (aTag._c_onclick != null) ?  aTag._c_onclick: aTag.onclick;
						aTag.onclick = function psHJAddFavourite_FromCat(){
							psSetValueToCookie(G_PS_COOKIE_FAVOURITE,this.prdName,this.prdId);							
							if(this.OldFunction != null)
								return this.OldFunction();
						}
					}
				}				
			}
		}		
	}	
}

function psHijackAddToBasket_FromProduct(prdId, prdName, prdCat){
	if(prdId == null || prdName == null)
		return;
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags)){
		for(var j=0; j<aTags.length; j++){
			var aTag = aTags[j];
			if(aTag.innerHTML != null && aTag.innerHTML.search(/add2basket\d*\.png/i) >= 0){				
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJAddToBasket") < 0){					
					aTag.prdId = prdId;
					aTag.prdName = prdName;
					aTag.prdCat = prdCat;
					aTag.OldFunction = (aTag._c_onclick != null) ?  aTag._c_onclick: aTag.onclick;
					aTag.onclick = function psHJAddToBasket_FromProduct(){						
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdId,this.prdCat);
						psSetValueToCookie(G_PS_COOKIE_PROD_NAME,this.prdName,this.prdId);						
						if(this.OldFunction != null)
								return this.OldFunction();
					}
				}
			}
		}
	}
}

function psGetPageDescription(){
	// Exception for "Placemat" and "Poems"
	var pIntro = psGetElementsByClassName(document,"div","GC18 PageIntroduction");
	if(psCheckArrayExist(pIntro)){
		var pId = psTrim(psGetInnerText(pIntro[0]));
		if(pId != null && pId != ""){
			return pId;
		}
	}
	// Exception for "Wall Clocks"
	var PageDescription = psGetElementsByClassName(document,"div","GC19 PageDescription");
	if(psCheckArrayExist(PageDescription)){		
		var strTags = PageDescription[0].getElementsByTagName("strong");
		if(psCheckArrayExist(strTags) && PageDescription[0].innerHTML != null && PageDescription[0].innerHTML.search(/FONT\-SIZE\:\s*19\.5pt/i) >= 0){			
			var pageId = psTrim(psGetInnerText(strTags[0]));			
			if(pageId != null && pageId != "") return pageId;
		}
	}
	return null;
}

function psIsSubscribe(){
	if(G_PS_PATHNAME.search(/372\/ContestForm\.clsp/i) >= 0){		
		return true;
	}
	var strTags = document.getElementsByTagName("strong");
	if(psCheckArrayExist(strTags)){
		if(psGetInnerText(strTags[0]) != null && psGetInnerText(strTags[0]).search(/Sign\s+up\s+for\s+special\s+offers\s+and\s+product\s+updates/i) >= 0){			
			return true;
		}
	}	
	return false;
}

function psHijackSubscribe(){
	var frm = document.getElementById("Process");
	if(psCheckElementExist(frm)){
		if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJSubscribe") < 0){
			frm.OldFunction = frm.onsubmit;
			frm.onsubmit = function psHJSubscribe(){
				var emailTag = document.getElementById("EmailAddress");
				if(psCheckElementExist(emailTag)){
					var email = psTrim(emailTag.value);
					if(psCheckEmail(email)){
						var uP = new psProfile();
						uP.cusId = uP.email = email;						
						uP.writeProfile();
						psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
					}
				}
				if(this.OldFunction != null) 
					return this.OldFunction();
			}
		}
	}	
}

function psIsHomePage(){
	var shipTables = psGetElementsByClassName(document,"table","TOCB1");
	if(psCheckArrayExist(shipTables)){
		for(var i=0; i<shipTables.length; i++){
			if(psGetInnerText(shipTables[i]) != null && psGetInnerText(shipTables[i]).search(/shipping\s+to\s*\:/i) >= 0)
				return true;
		}	
	}	
	// Spanish site
	if(G_PS_PATHNAME.indexOf("/contents/es/front.htm") >= 0 || ( (G_PS_PATHNAME == "/" || G_PS_PATHNAME == "/index.html") && G_PS_PREFIX == "SP:"))
		return true;
	var titles = document.getElementsByTagName("title");
	if(psCheckArrayExist(titles)){
		var title = psTrim(psGetInnerText(titles[0]));
		if(title != null && title.search(/Mis\s+Libros\s+de\s+Aventuras\s+\-\s+Identity\s+Direct/i) >= 0){
			return true;
		}
	}

	return false;
}

function psIsSkipPage(){
	if(G_PS_PATHNAME.indexOf("/contents/extra.html") >= 0 ||
	   G_PS_PATHNAME.indexOf("/contents/grey.html") >= 0 ||
	   G_PS_PATHNAME.indexOf("/contents/dynamic.html") >= 0 ||
	   G_PS_PATHNAME.indexOf("/contents/en-uk/conf.html") >= 0 ||
	   G_PS_PATHNAME.indexOf("/contents/load_minicart.html") >= 0 ||
	   G_PS_PATHNAME.indexOf("/contents/en-uk/load_index1.html") >= 0 ||
	   G_PS_PATHNAME.indexOf("/contents/en-uk/load_index2.html") >= 0 ||
	   G_PS_PATHNAME.indexOf("/contents/en-uk/load_search.html") >= 0 ){
		return true;
	}
	return false;
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	var advSearch = document.getElementById("advancedSearchForm");
	if(psCheckElementExist(advSearch)){
		// send pageview for advance search
		return false;
	}	
	if(G_PS_PATHNAME.search(/contents\/en\-(uk|ca|us)\/search\.html/i) >= 0 ||
	   G_PS_PATHNAME.search(/contents\/es\/search\.html/i) >= 0 ){
		var searchurl = psGetValueFromUrl(G_PS_URL_PATH,"searchurl");
		if(searchurl != null && searchurl.indexOf("/searchform.php") >= 0){			
			return false;
		}
		return true;
	}
	var sInput = document.getElementById("searchFormContentString");
	var sFor = document.getElementById("LD.LD_SEARCH_YOUSEARCHEDFOR_PRE");
	if(psCheckElementExist(sInput) || psCheckElementExist(sFor)){		
		return true;
	}
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	var pTables = psGetElementsByClassName(document,"table","Product");	
	if(psCheckArrayExist(pTables)){
		var pH2 = psGetElementsByClassName(pTables[0],"h2","GC37 ProductTitle");
		if(psCheckArrayExist(pH2)){
			return true;
		}		
	}
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_PATHNAME.search(/contents\/en\-(uk|us|ca)\/basket\.html/i) >= 0 ||
	   G_PS_PATHNAME.search(/contents\/es\/basket\.html/i) >= 0)
		return true;
	var pageTitles = psGetElementsByClassName(document,"div","GC17 PageTitle");
	if(psCheckArrayExist(pageTitles)){
		var pageId = psTrim(psGetInnerText(pageTitles[0]));
		if(pageId.search(/(basket|Shopping\s+Cart|Canasta)$/i) >= 0)
			return true;
	}
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_PATHNAME.search(/contents\/en\-(uk|us|ca)\/thankyou\d*\.htm/i) >= 0 ||
	   G_PS_PATHNAME.search(/contents\/es\/thankyou\d*\.htm/i) >= 0){
		return true;
	}
	var pageTitles = psGetElementsByClassName(document,"div","GC17 PageTitle");
	if(psCheckArrayExist(pageTitles)){
		var pageId = psTrim(psGetInnerText(pageTitles[0]));
		if(pageId.search(/Thank\s+you$/i) >= 0)
			return true;
	}	
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	if(psGetCookie(G_PS_COOKIE_FLAG) == "search_success"){
		return;
	}
	G_PS_CUR_CATID = G_PS_PREFIX + "SEARCH";
	var pageId = "Search Unsuccessful";
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(sResult != "0"){
		pageId = "Search Successful" + psGetSearchPageNumber();
	}	
	if(sTerm != null && sTerm != ""){
		pageId = G_PS_PREFIX + pageId;		
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);
		psSetCookie(G_PS_COOKIE_CATID,G_PS_CUR_CATID);
		psSetCookie(G_PS_COOKIE_FLAG,"search_success");
		// wait 1s for loading span "More Details"
		window.setTimeout("psHijackViewSearchDetails()",1000);
		return true;
	}
	return false;
}

function psHijackViewSearchDetails(){	
	var spanDetails = document.getElementsByTagName("span");
	if(psCheckArrayExist(spanDetails)){
		for(var i=0; i<spanDetails.length; i++){
			var spanDetail = spanDetails[i];			
			var innerText = psGetInnerText(spanDetail);
			if(innerText != null && innerText.search(/(More\s+Details|Mas\s+Detalles)/i) >= 0){				
				if(spanDetail.onclick == null || spanDetail.onclick.toString().indexOf("psHJSearchDetail") < 0){					
					spanDetail.OldFunction = spanDetail.onclick;
					spanDetail.onclick = function psHJSearchDetail(){						
						var searchPageId = G_PS_PREFIX + "SEARCH";
						psSetCookie(G_PS_COOKIE_PRE_CATID,searchPageId);
						if(this.OldFunction != null) 
							return this.OldFunction();
					}
				}
			}
		}
	}
}

function psGetSearchPageNumber(){
	var pageForm = psGetElementByName("form","nav1");
	if(psCheckElementExist(pageForm)){
		var bTags = pageForm.getElementsByTagName("b");
		if(psCheckArrayExist(bTags)){
			return " Page[" + psTrim(psGetInnerText(bTags[0])) + "]";
		}
	}
	return "";
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	var sInput = document.getElementById("searchFormContentString");
	if(psCheckElementExist(sInput)){		
		term = psTrim(sInput.value);
	}else{
		var sFor = document.getElementById("LD.LD_SEARCH_YOUSEARCHEDFOR_PRE");
		if(psCheckElementExist(sFor)){
			var bTags = sFor.getElementsByTagName("b");
			if(psCheckArrayExist(bTags)){				
				term = psTrim(psGetInnerText(bTags[0]));
			}
		}
	}	
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	var sTotal = document.getElementById("LD.LD_SEARCH_TOTALRESULTS");
	if(psCheckElementExist(sTotal)){
		var res = psGetInnerText(sTotal.parentNode);		
		result = psTrim(psHtmlDecode(unescape(res)).replace(/Total\s+Results/i,""));
		result = result.replace(/Total\s+de\s+Resultados/i,"");
	}
	return result;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()){
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
		psHijackAddToBasket_FromProduct(prd.id, prd.name, prd.catId);
		// Save product id for favourite list
		psHijackAddFavourite(prd.id,prd.name);
	}
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	psSetCookie(G_PS_COOKIE_PRE_CATID,"","delete");
	psSetCookie(G_PS_COOKIE_SHOP5,"","delete");	
	G_PS_CUR_CATID = (G_PS_PREFIX == "SP:")? G_PS_PREFIX + "CANASTA" : G_PS_PREFIX + "BASKET";
	psCreatePageviewTag(G_PS_CUR_CATID, G_PS_CUR_CATID, null, null);

	var cartTbl = null;
	
	var tables = psGetElementsByClassName(document,"table","ViewbasketMaster");
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){
			var firstRow = psGetInnerText(tables[i].rows[0]);
			if(firstRow != null && firstRow.search(/(Title\s*Price\s*Quantity|Nombre\s+Precio\s+Cantidad)/i) >= 0){
				cartTbl = tables[i];
			}
		}
		if(cartTbl == null) cartTbl = tables[0]; //in case keyword changed or other language
	}
	
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	var prdSep = "_-_";
	var itemSep = "|";
	var shop5Str = "";
	var sentShop5 = false;
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		var lastCell = rows[r].cells[rows[r].cells.length -1];
		if(psGetInnerText(lastCell) == null || psGetInnerText(lastCell).search(/\[(Delete|Elimine)\]/i) < 0){
			continue;
		}
		if(rows[r].cells.length < 6)
			continue;
		if (prd.getItem5(rows[r])){
			sentShop5 = true;
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
			// Save shop5 to cookie for shop9
			shop5Str = shop5Str + prdSep + prd.id + itemSep + prd.name + itemSep + prd.quantity + itemSep + prd.price + itemSep + prd.catId;

		}
	}
	if(sentShop5 == true){
		// Make sure to have actual postings
		psDisplayShop5s();
		psSetCookie(G_PS_COOKIE_SHOP5,shop5Str);
	}
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{	
	G_PS_CUR_CATID = "CHECKOUT";	
	psCreatePageviewTag("ORDER RECEIPT", G_PS_CUR_CATID, null);

	var ord = new psOrder();
	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile())
		{	
			//modified by Khanh Trinh for Paypal checkout
			if(psCheckElementExist(document.getElementById("cmCustomerID"))) 
			{
				this.cusId = this.email = psGetElementValueById("cmCustomerID",true);
			}
			
			// Read shop9 from cookie
			var prdSep = "_-_";
			var itemSep = "|";
			var shop5Str = psGetCookie(G_PS_COOKIE_SHOP5);
			if(shop5Str != null && shop5Str.indexOf(prdSep) >= 0){
				var products = shop5Str.split(prdSep);
				for(var p=0; p<products.length; p++){
					if(products[p].indexOf(itemSep) >= 0){
						var pItems = products[p].split(itemSep);
						if(pItems.length > 4){
							//psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
							psCreateShopAction9Tag(pItems[0], pItems[1], pItems[2], pItems[3], uP.cusId, ord.id, ord.subtotal, pItems[4]);
						}						
					}
				}				
				// 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_PROD_NAME, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
			psSetCookie(G_PS_COOKIE_SHOP5,"","delete");
			psSetCookie(G_PS_COOKIE_ORDER,"","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 pTables = psGetElementsByClassName(document,"table","Product");
			if(psCheckArrayExist(pTables)){
				var pId = pTables[0].getAttribute("id");
				if(pId != null && pId != ""){
					this.id = psTrim(pId);
				}
				var h2Tags = psGetElementsByClassName(pTables[0],"h2","GC37 ProductTitle");
				if(psCheckArrayExist(h2Tags)){
					this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(h2Tags[0])))));
				}
			}
			
			if(G_PS_URL_REFERRER != null && G_PS_URL_REFERRER.indexOf("identitydirect.") < 0 && G_PS_URL_REFERRER.indexOf("mislibrosdeaventuras.") < 0){
				this.catId = "Bookmarks";
			}else{
				var fromSearch = psGetCookie(G_PS_COOKIE_PRE_CATID);
				if(fromSearch != null && fromSearch.indexOf("search") >= 0){
					this.catId = fromSearch.toUpperCase();
				}else{
					this.catId = psGetCookie(G_PS_COOKIE_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.name = psTrim(psCleanProductName(psHtmlDecode(unescape(psGetInnerText(itemRow.cells[1])))));
			 //this.price = psCleanPrice(psGetInnerText(itemRow.cells[2]));			 
			 var quanInputs = itemRow.cells[3].getElementsByTagName("input");
			 if(psCheckArrayExist(quanInputs)){
				this.quantity = psTrim(quanInputs[0].value);
			 }
			 var subtotal = psCleanPrice(psGetInnerText(itemRow.cells[5]));
			 if(this.quantity != null && subtotal != null){				
				var quantity = parseInt(this.quantity);
				subtotal = parseFloat(subtotal);
				if(isFinite(quantity) && isFinite(subtotal)){
					this.price = subtotal/quantity;
					this.price = psConvertCurrency(this.price.toFixed(2));
				}
			 }
			 
			 if(this.name != null && this.name != ""){
				this.id = psGetValueFromCookie(G_PS_COOKIE_PROD_NAME,this.name);
			 }
			 if(this.id != null && this.id != ""){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			 }
			 
			 // Bask restored from the previous session, some products maybe not existed in cookie
			 // Use productId = productName, productCategory = DomainPrefix + "ReturnCart"
			 if(this.id == null && this.id == "")
				this.id = this.name;
			 if(this.catId == null && this.catId == ""){				
				this.catId = G_PS_PREFIX + "RETURNCART";
			 }
			 
			 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];
				
				//modified by Khanh Trinh for Paypal checkout
				if(!this.cusId && psCheckElementExist(document.getElementById("cmCustomerID")))
				{
					this.cusId = this.email = psGetElementValueById("cmCustomerID",true);
				}
				else
				{
					this.email = buf[1];
				}
				
				if (!this.cusId)
					this.cusId = psGenerateRandomValue();
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			else if(psCheckElementExist(document.getElementById("cmCustomerID"))) //modified by Khanh Trinh for Paypal checkout
			{
				this.cusId = this.email = psGetElementValueById("cmCustomerID",true);
			}
			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.subtotal = psGetValueFromCookie(G_PS_COOKIE_ORDER,"subtotal");
			this.shipping = psGetValueFromCookie(G_PS_COOKIE_ORDER,"shipping");
			if(typeof(orderID) != "undefined" && orderID != null && orderID != ""){
				// Get order number from /contents/en-uk/thankyou8.html
				this.id = orderID;
				
			}else{
				this.id = psGenerateRandomValue();
			}
			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 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 psGetElementByName(tagName,elementName){	
	// return the first element
	var tags = document.getElementsByTagName(tagName);
	if(psCheckArrayExist(tags)){
		for(var i=0; i<tags.length; i++){
			if(tags[i].name != null && tags[i].name.toLowerCase() == elementName.toLowerCase()){
				return tags[i];
			}
		}
	}
	return null;
}

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 ==================*/