/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v2.2, 2009/05/12
 * COPYRIGHT 1999-2008 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 * 13MAR09 - ABrink - Split, Space Ad, Magazine and Transcript logic
 */
/************************************************************************************/
//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("teach12.com","thegreatcourses.com","ttcstageweb.teachco.com");//value must be one array of domains or null

// 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_ORDER = "PS_ORDER";
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
var G_PS_FLAG_LOGIN = "PS_FLAG_LOGIN";		// used as a "session" variable to handle events between pages
var G_PS_COOKIE_EMAIL = "PS_EMAIL_TEMP";
var G_PS_COOKIE_SHOP9 = "PS_SHOP9";
var G_PS_COOKIE_PRODID = "PS_PRODID";
var G_PS_COOKIE_COUNT_PRO = "PS_COUNT_PRO";
var G_PS_COOKIE_ORDER_GIFT = "PS_ORDER_GIFT";
var G_PS_COOKIE_PROFILE_GIFT = "PS_PROFILE_GIFT";

// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = "";
var pCatId = null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
psDeleteCookie();
if(G_PS_PATHNAME == "/teach12.aspx"
	|| G_PS_PATHNAME == "/")
{
	pCatId = "HOME";
	psCreatePageviewTag("HOME","HOME", null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if(psIsCoursesPages()
		|| G_PS_PATHNAME == "/storex/professors.aspx")
{
	pCatId = psGetCatId();
	psCreatePageviewTag(pCatId + " " + psGetLetterStart(),pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if(G_PS_PATHNAME == "/storex/coursesdetail.aspx" )
{
	pCatId = psGetValueFromUrl(G_PS_URL_PATH,"s");
	var qSubjectArea =  psGetValueFromUrl(G_PS_URL_PATH,"sn");
	
	if (qSubjectArea != null)
	{
	var pSubjectArea = document.getElementById("hfParentSubjectAreaID").value + " - " + psGetValueFromUrl(G_PS_URL_PATH,"sn");
	}
	else 
	{
	var pSubjectArea = document.getElementById("hfParentSubjectAreaID").value + " courses";
	}
	
	if (pCatId == null)
		{
			pCatId = psGetValueFromUrl(G_PS_URL_PATH,"ps");			
		}	
	
	psCreatePageviewTag(pSubjectArea,pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if(G_PS_PATHNAME == "/storex/coursesonsale.aspx")
{
	pCatId = psGetCatIdOnSale();
	psCreatePageviewTag(psGetPageIdOnSale(), pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if(G_PS_PATHNAME == "/ttcx/ourguarantee.aspx")
{
	psCreatePageviewTag("OUR LIFETIME SATISFACTION", "GUARANTEE", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/ourhistory.aspx")
{
	psCreatePageviewTag("ABOUT US","ABOUT US", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/faqs.aspx")
{
	psCreatePageviewTag("FAQ","FAQ", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/faqs.aspx")
{
	psCreatePageviewTag("FAQ","FAQ", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/help.aspx")
{
	psCreatePageviewTag("HELP","HELP", null, null);
}
else if(G_PS_PATHNAME == "/storex/giftcerthome.aspx")
{
	psCreatePageviewTag("GIFT CERTIFICATES","GIFT CERTIFICATES", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/privacy.aspx")
{
	psCreatePageviewTag("OUR PRIVACY POLICY","OUR PRIVACY POLICY", null, null);
}
else if(G_PS_PATHNAME ==  "/ttcx/coursequotes.aspx")
{
	psCreatePageviewTag("TESTIMONIALS","TESTIMONIALS", null, null);
}
else if(G_PS_PATHNAME ==  "/ttcinq/great_courses.aspx"
		|| G_PS_PATHNAME ==  "/ttcinq/our_guarantee.aspx"
		|| G_PS_PATHNAME ==  "/ttcinq/great_professors.aspx"
		|| G_PS_PATHNAME ==  "/co/basketdetails.aspx"
		|| G_PS_PATHNAME ==  "/ttcx/PrivacyInfo.aspx"
		|| G_PS_PATHNAME ==  "/ttcinq/lifelong_learning.aspx" 
		|| G_PS_PATHNAME == "/co/prioritycode.aspx")
{
	psCreatePageviewTag(psGetFileNameAsPageId(),psGetFileNameAsPageId(), null, null);
}
else if(G_PS_PATHNAME ==  "/ttcinq/what_people_say.aspx")
{
	psCreatePageviewTag("WHAT PEOPLE SAY","TESTIMONIALS", null, null);
}
else if(G_PS_PATHNAME ==  "/common/courselecturetitles.aspx")
{
	var pPageId = psTrim(psHtmlDecode(document.getElementsByTagName("TITLE")[0].innerHTML));
	psCreatePageviewTag(pPageId,"COURSE LECTURE TITLES", null, null);
}
else if(G_PS_PATHNAME ==  "/ttcx/events.aspx")
{
	var pPageId = psTrim(psHtmlDecode(document.getElementsByTagName("TITLE")[0].innerHTML));
	psCreatePageviewTag(pPageId,"EVENTS LISTING", null, null);
}
else if(G_PS_PATHNAME ==  "/ttcx/transcripttips.aspx")
{
	psCreatePageviewTag("What are Transcript Books","TranscriptTips", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/downloaddetails.aspx")
{
	psCreatePageviewTag("FAQ ON DOWNLOAD","FAQ ON DOWNLOAD", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/download_faq_pc.aspx"
		|| G_PS_PATHNAME == "/ttcx/download_faq_pc.aspx" 
		|| G_PS_PATHNAME == "/ttcx/download_faq_mac.aspx")
{
	psCreatePageviewTag(psGetFileNameAsPageId() ,"FAQ ON DOWNLOAD", null, null);
}
else if(G_PS_PATHNAME ==  "/accounts/salenotifierhelp.aspx")
{
	psCreatePageviewTag("SALE NOTIFIER HELP","YOUR ACCOUNT", null, null);
}
else if(G_PS_PATHNAME ==  "/ttcx/aboutsaleprices.aspx")
{
	psCreatePageviewTag("ABOUT OUR SALE PRICES","ABOUT OUR SALE PRICES", null, null);
}
else if(G_PS_PATHNAME ==  "/ttcinq/courseformats.aspx")
{
	psCreatePageviewTag("COURSE FORMATS","LIFELONG LEARNING", null, null);
}
else if(G_PS_PATHNAME == "/ttcx/siteindex.aspx")
{
	pCatId = "SITE INDEX";
	psCreatePageviewTag(pCatId,pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if(psIsLeftMenuPages())
{
	pCatId = psGetValueFromUrl(G_PS_URL_PATH,"s");
	psCreatePageviewTag(psGetPageIdLeftMenu(),pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if (G_PS_PATHNAME == "/searchv2/searchttc.aspx")
{
	psPostSearchView();
	psSetCookie(G_PS_COOKIE_CATID,"SEARCH");
}
else if(G_PS_PATHNAME == "/ttcx/magazine.aspx" && psIsProductDetails() == false)
{ 
	pCatId = "MAGAZINE";
	var pLid = psGetValueFromUrl(G_PS_URL_PATH,"lid");
	
	psCreatePageviewTag("MAGAZINE: " + pLid,pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if (psIsProductDetails())
{	
	psPostProductView();
}
else if(psIsProfessorDetails())
{
	pCatId = "PROFESSORS";
	psCreatePageviewTag(psGetPageIdProfessor(),pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,pCatId);
}
else if(G_PS_PATHNAME == "/accounts/custlogin.aspx")
{
	pCatId = "YOUR ACCOUNT";
	psCreatePageviewTag("YOUR ACCOUNT",pCatId,null, null);
	psHijackCustomerSignIn();
	psHijackCreatNewAccount();
	
	psSetCookie(G_PS_COOKIE_CATID,pCatId);	
	if(G_PS_URL_REFERRER.indexOf("/co/confirmpurchasedinfo.aspx") > -1 && psGetCookie(G_PS_FLAG_LOGIN)== "newusercheckout")
	{
		if(psGetCookie(G_PS_COOKIE_EMAIL))
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			// post registration tag for update profile page
			uP.cusId = psGetCookie(G_PS_COOKIE_EMAIL);
			uP.email = psGetCookie(G_PS_COOKIE_EMAIL);
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
			uP.writeProfile();
		}
	}
}
else if(G_PS_PATHNAME == "/accounts/accthome.aspx")
{
	pCatId = "YOUR ACCOUNT";
	psCreatePageviewTag("YOUR ACCOUNT OVERVIEW", pCatId, null, null);
	psPostRegisterSuccessful();
	psSetCookie(G_PS_COOKIE_CATID,pCatId);	
}
else if(G_PS_PATHNAME == "/accounts/acctbillinfo.aspx" && psGetValueFromUrl(G_PS_URL_PATH,"Action") == null)
{
	psCreatePageviewTag("BILLING INFORMATION","YOUR ACCOUNT",null, null);
	if(psGetCookie(G_PS_FLAG_LOGIN)== "updated billing")
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, uP.newsletter, uP.subscribe);
		psSetCookie(G_PS_FLAG_LOGIN, "", "delete");
	}
}
else if(G_PS_PATHNAME == "/accounts/trackorder.aspx")
{
	var pPageId = psTrim(psCleanHtmlTag(psHtmlDecode(document.getElementsByTagName("TITLE")[0].innerHTML)));
	psCreatePageviewTag(pPageId,"YOUR ACCOUNT", null, null);
}
else if(G_PS_PATHNAME == "/accounts/rcmdreading.aspx"
		|| G_PS_PATHNAME == "/accounts/profsummary.aspx")
{
	var pArr = psGetElementsByClassName(document,"td","myAccountPopupTitle");
	if(pArr && pArr.length > 0)
	{
		var pageId = psTrim(psCleanHtmlTag(psHtmlDecode(pArr[0].innerHTML)));
		psCreatePageviewTag(pPageId,"YOUR ACCOUNT", null, null);
	}
}
else if(G_PS_PATHNAME == "/accounts/acctvieworder.aspx")
{
	psCreatePageviewTag("View Order " + psGetValueFromUrl(G_PS_URL_PATH,"o") ,"YOUR ACCOUNT", null, null);
}
else if(G_PS_PATHNAME == "/accounts/custloginpwd.aspx")
{
	psCreatePageviewTag("FORGOT YOUR PASSWORD","YOUR ACCOUNT",null, null);
}
else if(G_PS_PATHNAME == "/accounts/acctaddressmgmt.aspx")
{
	psCreatePageviewTag("VIEW & EDIT SHIPPING ADDRESSES","YOUR ACCOUNT",null, null);
}
else if(G_PS_PATHNAME == "/accounts/acctshipinfo.aspx")
{
	psCreatePageviewTag("ADD A NEW SHIPPING ADDRESS","YOUR ACCOUNT",null, null);
}
else if(psIsBillingUpdate())
{
	psCreatePageviewTag("ADD BILLING INFORMATION","YOUR ACCOUNT",null, null);
	psHijackUpdateBilling();
}
else if(G_PS_PATHNAME == "/accounts/acctuserinfo.aspx")
{
	psCreatePageviewTag("UPDATE E-MAIL OR PASSWORD","YOUR ACCOUNT",null, null);
	psSetCookie(G_PS_COOKIE_EMAIL, '',"delete");
	psHijackUpdatedEmail();
}
else if(G_PS_PATHNAME == "/accounts/createaccount.aspx")
{
	psCreatePageviewTag("CREATE A NEW ACCOUNT","YOUR ACCOUNT",null, null);
	psHijackCreatNewAccount();
}
else if(G_PS_PATHNAME == "/accounts/acctnotificationpreferences.aspx"
		|| G_PS_PATHNAME == "/accounts/acctdownloads.aspx"
		|| G_PS_PATHNAME == "/accounts/acctsalenotifier.aspx"
		|| G_PS_PATHNAME == "/accounts/culturalevents.aspx"
		)
{
	var objTitle = psGetElementsByClassName(document,"span","title");
	if(psCheckArrayExist(objTitle))
	{
		var pPageId = psHtmlDecode(objTitle[0].innerHTML);
		psCreatePageviewTag(psTrim(pPageId) ,"YOUR ACCOUNT",null, null);
	}
}
else if(G_PS_PATHNAME == "/ttcx/august2008lecture.aspx")
{
	psCreatePageviewTag("FREE LECTURES IN HONOR OF THE 2008 OLYMPICS IN BEIJING","YOUR ACCOUNT",null, null);
}
else if(G_PS_PATHNAME == "/ttcx/figs.aspx")
{
	psCreatePageviewTag("FIG0002","YOUR ACCOUNT",null, null);
}
else if(G_PS_PATHNAME == "/ttcx/may2008lecture.aspx")
{
	psCreatePageviewTag("FREE LECTURE IN HONOR OF MEMORIAL DAY","YOUR ACCOUNT",null, null);
}
else if(G_PS_PATHNAME == "/co/whyrecommended.aspx")
{
	psCreatePageviewTag("Why are these recommended?","RECOMMENDED",null, null);
}

else if(G_PS_PATHNAME == "/co/courseformatadd.aspx")
{
	var psCatId = "RECOMMENDED";
	var objTitle = psGetElementsByClassName(document,"span","courseTitle");
	if(psCheckArrayExist( objTitle))
	{
		var pPageId = psCleanHtmlTag(psHtmlDecode(objTitle[0].innerHTML));
		pPageId = psCleanProductName(pPageId);
		psCreatePageviewTag(psTrim(pPageId), psCatId ,null, null);
		
		var pId = psGetValueFromUrl(document.getElementById("AddFormats").action,"id");
		// Store productId along with catId to cookie for use later in shop5 and shop9 views
		psCatId  = psGetDCSext(psCatId); 
		psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pId, psCatId);
	}
}
else if(G_PS_PATHNAME ==  "/co/basket.aspx")
{
	psPostCartView();
}
else if(G_PS_PATHNAME == "/ttcx/shiptable.aspx")
{
	psCreatePageviewTag("SHIPPING RATES","CHECKOUT",null, null);
}

else if(G_PS_PATHNAME == "/co/checkoutwelcome.aspx")
{
	psCreatePageviewTag("CHECKOUT WELCOME","CHECKOUT",null, null);
	psHijackCheckOutWelcome();
}

else if(G_PS_PATHNAME == "/co/shipinfo.aspx")
{
	psCreatePageviewTag("SHIPPING","CHECKOUT",null, null);
	if(psGetCookie(G_PS_FLAG_LOGIN) == "checkoutwelcome" || G_PS_URL_REFERRER.indexOf("/co/checkoutwelcome.aspx") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		if(uP.email != null)
		{
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_FLAG_LOGIN, '', "delete"); // turn off flag
		}
		
	}
}
else if(G_PS_PATHNAME == "/co/checkoutlegal.aspx")
{
	psCreatePageviewTag("Download Terms and Conditions of Use","CHECKOUT",null, null);
	if(G_PS_URL_REFERRER.indexOf("/co/checkoutwelcome.aspx") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		if(uP.email != null)
		{
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_FLAG_LOGIN, '', "delete"); // turn off flag
		}
	}
}
else if(G_PS_PATHNAME == "/co/billinfo.aspx")
{
	psCreatePageviewTag("BILLING","CHECKOUT",null, null);
	psHijackUpdateBillingCheckout();
	if(psGetCookie(G_PS_FLAG_LOGIN) == "updated billing checkout")
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		if(uP.email != null)
		{
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
		}
		psSetCookie(G_PS_FLAG_LOGIN, '', "delete"); // turn off flag
	}
}
else if(G_PS_PATHNAME == "/co/confirminfo.aspx")
{
	psCreatePageviewTag("PLACE YOUR ORDER","CHECKOUT",null, null);
	if(psGetCookie(G_PS_FLAG_LOGIN) == "updated billing checkout")
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		if(uP.email != null)
		{
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
		}
		psSetCookie(G_PS_FLAG_LOGIN, '', "delete"); // turn off flag
	}
	else
		psPostPlaceOrderReg()
	psSetOrderToCookie();
}
else if (G_PS_PATHNAME == "/co/confirmpurchasedinfo.aspx")
{
	psCreatePageviewTag("THANK YOU","CHECKOUT",null, null);
	psPostOrderView();
	psHijackNewUserCheckout();
}
else if (G_PS_PATHNAME == "/co/checkoutlegalnotaccepted.aspx")
{
	psCreatePageviewTag("Checkout: Legal Not Accepted","CHECKOUT",null, null);
}
else if(G_PS_PATHNAME == "/storex/giftcertpurchaseupd.aspx"
		|| G_PS_PATHNAME == "/storex/giftcertpersonalization.aspx"
		||  G_PS_PATHNAME == "/storex/giftcertredeem.aspx")
{
	psCreatePageviewTag(G_PS_PATHNAME,"GIFT CERTIFICATE",null, null);
}
else if(G_PS_PATHNAME == "/storex/giftcertrecipinfo.aspx")
{
	psCreatePageviewTag(G_PS_PATHNAME,"GIFT CERTIFICATE",null, null);
	psCreateProductviewTag("2395","Gift Certificate","GIFT CERTIFICATE");
}
else if(G_PS_PATHNAME == "/storex/giftcertpreview.aspx")
{
	psCreatePageviewTag(G_PS_PATHNAME,"GIFT CERTIFICATE",null, null);
	var psPrice = 0;
	var objPrice = psGetElementsByClassName(document,"h2","styleText");
	if(psCheckArrayExist(objPrice))
		psPrice = psCleanPrice(psCleanHtmlTag(objPrice[0].innerHTML));
	
	psCreateShopAction5Tag("2395","Gift Certificate","1",psPrice,"GIFT CERTIFICATE");
	cmDisplayShop5s();
}
else if(G_PS_PATHNAME == "/storex/giftcertorderpreview.aspx")
{
	psCreatePageviewTag(G_PS_PATHNAME,"GIFT CERTIFICATE",null, null);
	var psGiftTable = psGetTableFromCell("Price");
	if(psCheckElementExist(psGiftTable))
	{
		if( psGiftTable.rows.length > 1 && psGiftTable.rows[0].cells.length > 3)
		{
			var pTotal = psCleanHtmlTag(psGiftTable.rows[1].cells[3].innerHTML); 
			var pQty = psCleanHtmlTag(psGiftTable.rows[1].cells[2].innerHTML); 
			var pUnit = psCleanHtmlTag(psGiftTable.rows[1].cells[1].innerHTML); 
			var pValueOrder =  pTotal + ":" + pQty + ":" + pUnit;		
			psSetCookie(G_PS_COOKIE_ORDER_GIFT,pValueOrder);
		}
	}
}
else if(G_PS_PATHNAME == "/storex/giftcertsenderinfo.aspx")
{
	psCreatePageviewTag(G_PS_PATHNAME,"GIFT CERTIFICATE",null, null);
	psSetCusGiftToCookie();
}
else if(G_PS_PATHNAME == "/storex/giftcertpurchaseconfirm.aspx")
{
	psCreatePageviewTag(G_PS_PATHNAME,"GIFT CERTIFICATE",null, null);
	var subtotal = 0;
	var qty = 0;
	var unitprice = 0;
	var pOrderId = psGetValueFromUrl(G_PS_URL_PATH,"order") != null?psGetValueFromUrl(G_PS_URL_PATH,"order"):psGenerateRandomValue();
	var cusId = psGetCookie(G_PS_COOKIE_PROFILE_GIFT);
	if (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); 
		}
		cusId = buf[0];
		if (!cusId)
			cusId = psGenerateRandomValue();
		var city = buf[2];
		var state = buf[3] != ""?buf[3]:null;
		var zipcode = buf[4];
	}
	var pValue = psGetCookie(G_PS_COOKIE_ORDER_GIFT);
	
	if(psCheckElementExist(pValue))
	{
		var arrValue = 	pValue.split(":");				
		subtotal = arrValue[0] == "null"?subtotal:psCleanPrice(arrValue[0]);
		qty = arrValue[1] == "null"?qty:psCleanPrice(arrValue[1]);
		unitprice = arrValue[2] == "null"?unitprice:psCleanPrice(arrValue[2]);
		psCreateShopAction9Tag("2395", "Gift Certificate", qty, unitprice, cusId, pOrderId , subtotal, "GIFT CERTIFICATE");
		psDisplayShop9s();
	}
	psCreateOrderTag(pOrderId, subtotal,"0", cusId, city, state, zipcode);
	psCreateRegistrationTag(cusId, cusId, city, state, zipcode, null, null);
}

else 
{	
	psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
}

/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psDeleteCookie()
{
	var oldCookie = psGetCookie(G_PS_COOKIE_SHOP9);
	if(psCheckElementExist(oldCookie))
	{
		psSetCookie(G_PS_COOKIE_PROD_CATID, '',"delete");
		psSetCookie(G_PS_COOKIE_SHOP9, '',"delete");
		psSetCookie(G_PS_COOKIE_PRODID, '',"delete");
	}
}
function psGetDCSext(CatId)
{
	var dcsSplit = document.getElementsByName("DCSext.split");
	var psRe = CatId;
	if(psCheckArrayExist(dcsSplit))
	{
		psRe = psCheckElementExist(dcsSplit[0].content) == true?dcsSplit[0].content + CatId:CatId;	
	}
	return psRe;
}
function psIsProductDetails()
{
	if(G_PS_PATHNAME == "/ttcx/coursedesclong2.aspx"
		|| G_PS_PATHNAME == "/ttcx/lp_general.aspx")
		return true;
	else if(G_PS_PATHNAME == "/ttcx/magazine.aspx")
	{
		var pCid = psGetValueFromUrl(G_PS_URL_PATH,"cid");
		if(pCid != null && pCid != "")
		{
			return true;
		}
	}
	return false;
}

/*
 * Determine if the page is the update billing address page.
*/
function psIsBillingUpdate()
{
	if(G_PS_PATHNAME == "/accounts/acctbillinfo.aspx")
	{
		var pAction = psGetValueFromUrl(G_PS_URL_PATH,"Action");
		if(pAction && pAction == "upd")
		{
			return true;
		}
	}
	return false;
}
function psGetFileNameAsPageId()
{
	return G_PS_PATHNAME.substring(G_PS_PATHNAME.lastIndexOf("/")+1, G_PS_PATHNAME.lastIndexOf(".")).replace(/\_+/gi, " ");
}
function psGetPageNumber()
{
	var pPageNo = 1;
	var pagesize = psGetValueFromUrl(G_PS_URL_PATH,"pagesize");
	var startNo = psGetValueFromUrl(G_PS_URL_PATH,"ps");
	if(pagesize != null && startNo != null)
	{
		pagesize = parseInt(pagesize);
		startNo = parseInt(startNo);
		if(startNo != 0)
			pPageNo += parseInt(startNo/pagesize);
	}
	return pPageNo;
}
function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	var sTerm = document.getElementById("hfSearchPhrase").value;
	var sResult = document.getElementById("hfTotalNumberofResults").value;;
	
	var pArrTd = psGetElementsByClassName(document,"td", "PortalTitleA");
	if(psCheckArrayExist(pArrTd))
	{
		var pValue = psTrim(psCleanHtmlTag(pArrTd[0].innerHTML));
		if(pValue.toLowerCase().indexOf("no matches found for") > -1)
		{
			psCreatePageviewTag("SEARCH UNSUCCESSFUL","SEARCH",sTerm,"0");
		}
		else
		{
			var pPageNo = psGetPageNumber();
			psCreatePageviewTag("SEARCH SUCCESSFUL " + "PAGE " + pPageNo, "SEARCH", sTerm, sResult);
		}
	}
}
/*
 *Get the start letter.
*/
function psGetLetterStart()
{
	var pArr = psGetElementsByClassName(document,"div","indexHeader");
	if(!pArr || pArr.length < 1)
		pArr = psGetElementsByClassName(document,"td","indexHeader");
	if(pArr && pArr.length > 0)
	{
		var pResult = psHtmlDecode(pArr[0].innerHTML);
		return pResult.replace(/[\s-]*/gi, "");
	}
	return "";
}

/*
 * Get pageId for left menu pages
*/
function psGetPageIdLeftMenu()
{
	var pPageTitle = "";
	var pArrTitle = psGetElementsByClassName(document,"p","indexPageTitle");
	if(psCheckArrayExist(pArrTitle))
	{
		var pText = pArrTitle[0].innerHTML;
		/*	Quick-fix for Opera browser, the innerHTML will not return correct value if tag format is not well-formed. 
        For example: the below span tag has no closing tag </span>
        <p class="indexPageTitle">Religion Courses <span class='indexPageTitleAlt'><!-- Error Message Display --></p>                                          
		*/
		var pLstText = (pText.toLowerCase().indexOf("<span") >-1)?pText.toLowerCase().split("<span"):null;
		pPageTitle = psCheckArrayExist(pLstText)== true?psHtmlDecode(psCleanHtmlTag(pLstText[0])): psHtmlDecode(psCleanHtmlTag(pText));
		pPageTitle = psTrim(pPageTitle.replace(/\s\s+/gi, " "));
	}
	else
		{
			var pArrTitle = psGetElementsByClassName(document,"a","SubjectAreaTitle");
			
			var pText = pArrTitle[0].innerHTML;
		/*	Quick-fix for Opera browser, the innerHTML will not return correct value if tag format is not well-formed. 
        For example: the below span tag has no closing tag </span>
        <p class="indexPageTitle">Religion Courses <span class='indexPageTitleAlt'><!-- Error Message Display --></p>                                          
		*/
		var pLstText = (pText.toLowerCase().indexOf("<span") >-1)?pText.toLowerCase().split("<span"):null;
		pPageTitle = psCheckArrayExist(pLstText)== true?psHtmlDecode(psCleanHtmlTag(pLstText[0])): psHtmlDecode(psCleanHtmlTag(pText));
		pPageTitle = psTrim(pPageTitle.replace(/\s\s+/gi, " "));
		pPageTitle = pPageTitle.toLowerCase() + " courses";
		}
	return pPageTitle;
}

/*
 * Get pageId for professor pages
*/
function psGetPageIdProfessor()
{
	var pPageTitle = "";
	var pArrTitle = psGetElementsByClassName(document,"td","profNameTitle");
	if(psCheckArrayExist(pArrTitle))
	{
		var pPageTitle = psHtmlDecode(psCleanHtmlTag(pArrTitle[0].innerHTML));
		pPageTitle = "PROFESSORS:" + psTrim(pPageTitle.replace(/\s\s+/gi, " "));
	}
	return pPageTitle;
}

/*
 * Is "Courses By Title" or "Courses  On Sale By Title" page.
*/
function psIsCoursesPages()
{
	if(G_PS_PATHNAME == "/storex/courses.aspx")
	{
		var pTDet = psGetValueFromUrl(G_PS_URL_PATH,"TDet");
		if(psCheckElementExist(pTDet))
		{
			pTDet = psTrim(pTDet.replace(/[\+\s]+/gi, " ").replace(/\%20/gi, " "));
			if(pTDet.toLowerCase() == "on sale by title" || pTDet.toLowerCase() == "by title")
				return true;
		}
	}
	return false;
}
/*
 * Get pageid for on sale pages
*/
function psGetPageIdOnSale()
{
	var pSbjArea = psGetValueFromUrl(G_PS_URL_PATH,"sbjArea");
	if(psCheckElementExist(pSbjArea))
	{
		 pSbjArea =  pSbjArea.replace(/\%2d/gi, "-");	
		 pSbjArea =  psTrim(pSbjArea.replace(/[\+\s]+/gi, " ").replace(/\%20/gi, " "));
	}
	return "ON SALE:" + pSbjArea;
}
/*
 * Get category id for on sale pages
*/
function psGetCatIdOnSale()
{
	var pCatId = "";
	var pFirst = psGetValueFromUrl(G_PS_URL_PATH,"sl");
	var pEnd = psGetValueFromUrl(G_PS_URL_PATH,"s");
	if(psCheckElementExist(pFirst) && psCheckElementExist(pEnd))
	{
		 pCatId =  "" + pFirst + pEnd;			
	}
	return pCatId;
}
/*
 * checked left menu pages.
*/
function psIsLeftMenuPages()
{
	if(G_PS_PATHNAME == "/storex/courses.aspx")
	{
		var pSbj = psGetValueFromUrl(G_PS_URL_PATH,"sbj");
		if(psCheckElementExist(pSbj))
			return true;
	}
	return false;
}
/*
 * is professor pages.
*/
function psIsProfessorDetails()
{
	if(G_PS_PATHNAME == "/storex/professor.aspx" )
	{
		var pId = psGetValueFromUrl(G_PS_URL_PATH,"id");
		if(psCheckElementExist(pId))
			return true;
	}
	if(G_PS_PATHNAME == "/co/professor.aspx")
		return true;
	return false;
}

function psGetCatId()
{
	switch (G_PS_PATHNAME)
	{
		case "/storex/courses.aspx":
		{
			var pTDet = psGetValueFromUrl(G_PS_URL_PATH,"TDet")
			if(psCheckElementExist(pTDet))
			{
				pTDet = pTDet.replace(/[\+\s]+/gi, " ").replace(/\%20/gi, " ");
				pTDet = psTrim(pTDet);
				if(pTDet.toLowerCase() == "on sale by title")
				{
					return "ON SALE: BY TITLE";
				}
				else if(pTDet.toLowerCase() == "by title")
				{
					return "COURSES BY TITLE";
				}
			}
			break;
		}
		case "/storex/professors.aspx":
			return "PROFESSORS"
			break;
		default:
			return "HOME";
	}
}

/* 
 * Find element by name
 */
function psGetElementsByClassName(psDocument, psElementTagName, psClassName)
{
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null)
    {
        return null;
    }
    for(var i = 0; i < arrInputs.length; i ++ )
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

/* 
 * Hijack "sign in" button when customer login.
 */
function psHijackCustomerSignIn()
{
	var pSignBtn = document.getElementById("LogIn");
	if(psCheckElementExist(pSignBtn))
	{
		pSignBtn.oldCMFunc = pSignBtn.onclick; //backup the existing onclick function
		pSignBtn.onclick = function()
		{
			var pEmail = psGetElementValueById("UserName");
			if(pEmail && pEmail != "")
			{
				var uP = new psProfile();
				uP.email = psTrim(pEmail);
				uP.cusId = psTrim(pEmail);
				uP.city = null;
				uP.state = null;
				uP.zipcode = null
				uP.writeProfile();
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}
	}
}
/* 
 * Hijack update email or password
 */
function psHijackUpdatedEmail()
{
	var allInputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if (items.getAttribute("type") == "image" && items.getAttribute("src").search(/images\/btn\_SaveChanges\_o\.gif/gi) > -1)
			{
				items.oldCMFunc = items.onclick; //backup the existing onclick function
				items.onclick = function()
				{
					var pEmail = psGetElementValueById("NewEmail");		
					if(pEmail && pEmail != "" && psCheckUpdateMailSucc())
					{
						psSetCookie(G_PS_COOKIE_EMAIL,pEmail);
					}
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}
			}
		}
	}
}
/* 
 * Hijack create 1 new user when checkout successful as a customer.
 */
function psHijackNewUserCheckout()
{
	var allInputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if (items.getAttribute("type") == "image" && items.getAttribute("src").search(/images\/btn\_createNewAcct\_o\.gif/gi) > -1)
			{
				items.oldCMFunc = items.onclick; //backup the existing onclick function
				items.onclick = function()
				{
					var pEmail = psGetElementValueById("UserName");		
					if(pEmail && pEmail != "")
					{
						psSetCookie(G_PS_COOKIE_EMAIL,pEmail);
						psSetCookie(G_PS_FLAG_LOGIN,"newusercheckout");
					}
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}
			}
		}
	}
}

/*
 * check save email or password successfully.
*/
function psCheckUpdateMailSucc()
{
	var objClassError = psGetElementsByClassName(document,"span","formError");
	if(psCheckArrayExist(objClassError))
	{
		for (var i=0; i< objClassError.length; i++)	
		{
			var pErrorText = psHtmlDecode(psCleanHtmlTag(objClassError[i].innerHTML.toLowerCase()));
			if(pErrorText.indexOf("please enter your password") > -1
				||pErrorText.indexOf("the new e-mail address and the re-entered address do not match") > -1
				|| pErrorText.indexOf("please provide a valid e-mail address") > -1)
			{
				return false;
			}
		}
	}
	return true;
}

/*
 * Post a registration tag when:
 * User login successful
 * user updated emai successful
*/
function psPostRegisterSuccessful()
{
	if(G_PS_URL_REFERRER.indexOf("/accounts/custlogin.aspx") > -1
		|| G_PS_URL_REFERRER.indexOf("/accounts/createaccount.aspx") >-1 )
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
		{
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
		}
	}

	else if(G_PS_URL_REFERRER.indexOf("/accounts/acctuserinfo") > -1)
	{
		var pEmail = psGetCookie(G_PS_COOKIE_EMAIL);
		if(pEmail && pEmail != "")
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			// post registration tag for update profile page
			if(uP.email != null)
			{
				uP.email = pEmail;
				uP.cusId = pEmail;
				uP.writeProfile();
				psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
				psSetCookie(G_PS_COOKIE_EMAIL, '',"delete");
			}
		}
	}
}	
/* 
 * delete profile cookie when user checkout as a customer.
 */
function psCheckOutOption()
{
	var allInputs = document.getElementsByName("loginType");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if (items.getAttribute("type") == "radio")
			{
				if(items.checked && items.getAttribute("value") != "existingUser")
					psSetCookie(G_PS_COOKIE_PROFILE,'',"delete");
			}
		}
	}
}
/* 
 * Hijack create a new account.
 */
function psHijackCreatNewAccount()
{
	var allInputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if (items.getAttribute("type") == "image" && items.getAttribute("src").search(/images\/btn\_createNewAcct\.gif/gi) > -1)
			{
				items.oldCMFunc = items.onclick; //backup the existing onclick function
				items.onclick = function()
				{
					var pEmail = psGetElementValueById("UserNameNew");		
					if(psCheckElementExist(pEmail) == false)
						 pEmail = psGetElementValueById("UserName");	
					if(pEmail && pEmail != "")
					{
						var uP = new psProfile();
						uP.email = psTrim(pEmail);
						uP.cusId = psTrim(pEmail);
						uP.city = null;
						uP.state = null;
						uP.zipcode = null
						uP.writeProfile();
					}
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}
			}
		}
	}
}
/* 
 * Hijack checkout welcome process.
 */
function psHijackCheckOutWelcome()
{
	var allInputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if (items.getAttribute("type") == "image" && items.getAttribute("src").search(/images\/cartContinue\.gif/gi) > -1)
			{
				items.oldCMFunc = items.onclick; //backup the existing onclick function
				items.onclick = function()
				{
					psCheckOutOption();
					var pEmail = psGetElementValueById("Text1");					
					if(pEmail == null || pEmail == "")
					{
						if(document.getElementsByName("loginType"))
						{
							var pText = document.getElementsByName("loginType")[0].parentNode.innerHTML;
							pEmail = pText.toLowerCase().split("<span")[0];
							pEmail = psTrim(psCleanHtmlTag(pEmail));
						}
					}
					if(pEmail && pEmail != "")
					{
						var uP = new psProfile();
						uP.email = pEmail;
						uP.cusId = psTrim(pEmail);
						uP.city = null;
						uP.state = null;
						uP.zipcode = null
						uP.writeProfile();
						psSetCookie(G_PS_FLAG_LOGIN,"checkoutwelcome");
					}
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}
			}
		}
	}
}

function psHijackUpdateBillingCheckout()
{
	var allImgs = document.getElementsByTagName("img");
	if(psCheckArrayExist(allImgs))
	{
		for (var i=0; i<allImgs.length; i++)	
		{
			var items = allImgs[i];
			if (items.getAttribute("src") && items.getAttribute("src").toLowerCase().search(/images\/cartcontinue\.gif/gi) > -1 
			|| items.getAttribute("src").search(/images\/btn\_Save\.gif/gi) > -1)
			{
				var aSubmit = items.parentNode;
				if(psCheckElementExist(aSubmit) && aSubmit.tagName.toLowerCase() == "a")
				{
					aSubmit.oldCMFunc = aSubmit.onclick; //backup the existing onclick function
					aSubmit.onclick = function()
					{
						var uP = new psProfile();
						uP.readProfile(); // get user profile from cookie
						if(uP.email && psGetValueByTagName("billCity",true) != null && psGetValueByTagName("billCity",true) != "")
						{
							uP.city = psGetValueByTagName("billCity",true);
							uP.state = psGetValueByTagName("BillRegion",true);
							uP.zipcode = psGetValueByTagName("billPostalCode",true);
							uP.writeProfile();
							psSetCookie(G_PS_FLAG_LOGIN,"updated billing checkout");
						}
						if (this.oldCMFunc != null)
							return this.oldCMFunc();
					}
				}
			}
		}
	}
}

/* 
 * Hijack update billing address.
 */
function psHijackUpdateBilling()
{
	var allInputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if (items.getAttribute("type") == "image" && items.getAttribute("src").search(/images\/btn\_SaveChanges\_o\.gif/gi) > -1)
			{
				items.oldCMFunc = items.onclick; //backup the existing onclick function
				items.onclick = function()
				{
					var uP = new psProfile();
					uP.readProfile(); // get user profile from cookie
					if(uP.email)
					{
						uP.city = psGetElementValueById("City") != null?psTrim(psGetElementValueById("City")):uP.city ;
						var sState = document.getElementsByName("State");
						if(sState && sState.length >0)
						{
							uP.state = psGetElementValue(sState[0],true);
						}
						uP.zipcode = psGetElementValueById("PostalCode")!= null?psTrim(psGetElementValueById("PostalCode")):uP.zipcode;				
						uP.writeProfile();
						psSetCookie(G_PS_FLAG_LOGIN,"updated billing");
					}
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}
			}
		}
	}
}
/*
 * Post a registration tag at place order step
*/
function psPostPlaceOrderReg()
{
	var pForm = document.getElementById("ConfirmInfo");
	var pAddress = "";
	if(psCheckElementExist(pForm))
	{
		var lstTable = pForm.getElementsByTagName("table");
		pTable = psCheckArrayExist(lstTable) == true?lstTable[0]:null;
		if(pTable && pTable.rows.length >3)
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			var psPostBillingAdd =  psGetPostOfCellByName(pTable,"Edit Billing Information");
			if(psPostBillingAdd != -1)
			{
				pAddress = pTable.rows[3].cells[psPostBillingAdd].innerHTML;
			}
			if(uP.email != null && psCheckEmail(uP.email))
			{
				if(psCheckElementExist(pAddress) && pAddress != "")
				{
					var lstBr = pAddress.toLowerCase().split("<br");
					if(psCheckArrayExist(lstBr)&&lstBr.length > 3)
					{
						//no address 2
						var pCountry  = psTrim(psCleanHtmlTag(lstBr[lstBr.length -2]).replace(">",""));
						pAddress = psTrim(psCleanHtmlTag(lstBr[lstBr.length -3]));
						if(pCountry.toLowerCase().indexOf("united states") > -1 || pCountry.toLowerCase().indexOf("canada")>-1)
						{
							pAddress = pAddress.replace(/\s+/gi," ");
							uP.city = pAddress.search(/>(.*)\,\s(\D*)\s(\d*)/gi) > -1 ? psTrim(RegExp.$1) : uP.city;
							uP.state = pAddress.search(/>(.*)\,\s(\D*)\s(\d*)/gi) > -1 ? psTrim(RegExp.$2) : uP.state;
							uP.zipcode = pAddress.search(/>(.*)\,\s(\D*)\s(\d*)/gi) > -1 ? psTrim(RegExp.$3) : uP.zipcode;
						}
						else 
						{
							pAddress = pAddress.replace(/\s+/gi," ");
							uP.city = pAddress.search(/>(.*)\,\s(\d*)/gi) > -1 ? psTrim(RegExp.$1) : uP.city;
							uP.zipcode = pAddress.search(/>(.*)\,\s(\d*)/gi) > -1 ? psTrim(RegExp.$2) : uP.zipcode;
						}
						// store on cookie
						uP.writeProfile();
					}
				}
			}
			else
			{
				var uP_Re = new psProfile();
				uP_Re.cusId = psGenerateRandomValue();
				uP_Re.email = uP_Re.cusId;
				if(psCheckElementExist(pAddress) && pAddress != "")
				{
					var lstBr = pAddress.toLowerCase().split("<br");
					if(psCheckArrayExist(lstBr)&&lstBr.length > 3)
					{
						var pCountry  = psTrim(psCleanHtmlTag(lstBr[lstBr.length -2]).replace(">",""));
						pAddress = psTrim(psCleanHtmlTag(lstBr[lstBr.length -3]));
						if(pCountry.toLowerCase() == "usa" || pCountry.toLowerCase() == "ca")
						{
							pAddress = pAddress.replace(/\s+/gi," ");
							uP.city = pAddress.search(/>(.*)\,\s(\D*)\s(\d*)/gi) > -1 ? psTrim(RegExp.$1) : null;
							uP.state = pAddress.search(/>(.*)\,\s(\D*)\s(\d*)/gi) > -1 ? psTrim(RegExp.$2) : null;
							uP.zipcode = pAddress.search(/>(.*)\,\s(\D*)\s(\d*)/gi) > -1 ? psTrim(RegExp.$3) : null;
						}
						else 
						{
							pAddress = pAddress.replace(/\s+/gi," ");
							uP.city = pAddress.search(/>(.*)\,\s(\d*)/gi) > -1 ? psTrim(RegExp.$1) : null;
							uP.zipcode = pAddress.search(/>(.*)\,\s(\d*)/gi) > -1 ? psTrim(RegExp.$2) : null;
							uP.state = null;
						}
					}
				}
				
				// store on cookie
				uP_Re.writeProfile();
				
			}
		}
	}
}
/*
 * 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("YOUR SHOPPING CART", G_PS_CUR_CATID, null,null);
	
	var cartTbl = null;
	
	// Iterate to throw shop5 tags
	cartTbl = document.getElementById("shoppingCartItems");
	
	//
	// 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();
	var psCountPro = 0;
	for (var r = 1; r < rows.length; r++) // item for each row
	{
		if(prd.getItem5(rows[r]))
		{
			// Post shop5tag
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
			psCountPro+=1;
		}
	}
	//count number of product to send in shop5.
	psSetCookie(G_PS_COOKIE_COUNT_PRO,psCountPro);
	// 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 FOR YOUR PURCHASE","CHECKOUT",null, null);

	var ord = new psOrder();
	var prd = new psProduct();
	var psCountPro = 0;
	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var sTableOrder = document.getElementById("OrderItems");	
			if(psCheckElementExist(sTableOrder) == false)
				return;
			var psCountProShop5 = psGetCookie(G_PS_COOKIE_COUNT_PRO);
			
			var rows = sTableOrder.rows; // use rows variable for optimization			
			for (var j = 0; j < rows.length; j++) // item for each row
			{				
				if(prd.getItem9(rows[j]))
				{
					if(psIsProducts(prd.name, prd.price) == true)
					psCountPro+=1 ;
				}
			}
			//if exist a different between number of shop5 and shop9, the shop5 will be send again.
			if(psCountProShop5 && psCountPro != psCountProShop5)
			{
				for (var i = 0; i < rows.length; i++) // item for each row
				{				
					if(prd.getItem5_Re(rows[i]))
					{
						psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
					}
				}
				psDisplayShop5s();
			}
			
			for (var r = 0; r < rows.length; r++) // item for each row
			{		
				if(prd.getItem9(rows[r]))
				{
					if(psIsProducts(prd.name, prd.price) == true)
						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);
			if(psCheckEmail(uP.email) == false)
				uP.email = null;
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
		}
	}
}
function psIsProducts(pName, pPrice)
{
	var psResult = true;
	if(pName.toLowerCase().indexOf("coupon") > -1
		|| pName.toLowerCase().indexOf("gift certificate") > -1 
		|| pName.toLowerCase().indexOf("not applicable") > -1 
		|| pPrice < 0)
		psResult = false;
	return psResult;
}
/*
 * Set all informations of order tag to cookie.
*/
function psSetOrderToCookie()
{		
	var pCartTable = document.getElementById("shoppingCartItems");
	var pSubtotal = 0;
	var pShipping = 0;
	var pShippMethod = 0;
	if(psCheckElementExist(pCartTable) && pCartTable.rows.length > 1)
	{
		for(var i = pCartTable.rows.length -1; i >0; i--)
		{
			if(pCartTable.rows[i].cells.length > 1)
			{
				if(pCartTable.rows[i].cells[1].innerHTML.toLowerCase().indexOf("subtotal:") > -1 && pCartTable.rows[i].cells.length > 4)
				{
					pSubtotal = pCartTable.rows[i].cells[4].innerHTML.replace("$","");		
					pSubtotal = psTrim(pSubtotal);
				}
				if(pCartTable.rows[i].cells[1].innerHTML.toLowerCase().indexOf("shipping and handling:") > -1&& pCartTable.rows[i].cells.length > 4)
				{
					pShipping = pCartTable.rows[i].cells[4].innerHTML.replace("$","");		
					pShipping = psTrim(pShipping);
				}
				if(pCartTable.rows[i].cells[1].innerHTML.toLowerCase().indexOf("shipping method") > -1 && pCartTable.rows[i].cells.length > 4)
				{
					for(var j = 0; j< pCartTable.rows[i].cells.length; j++)
					{
						if(psCheckPriceValue(pCartTable.rows[i].cells[j].innerHTML))
						{
							pShippMethod = pCartTable.rows[i].cells[j].innerHTML.replace("$","");		
							pShippMethod = psTrim(pShippMethod);
						}
					}
					
				}
			}
		}	
		if(psIsNumber(pShipping) && psIsNumber(pShippMethod))
		{
			pShipping = parseFloat(pShipping) + parseFloat(pShippMethod);
		}
	}
	var pValueOrder =  pSubtotal+ ":" + pShipping;		
	psSetCookie(G_PS_COOKIE_ORDER,pValueOrder);	
}

function psHijackUpsellSet(pCatId)
{
	var pFlag = true;
	var hrefs  = document.links;
	for (var i = 0; i < hrefs.length; i++)	
    {
        if (hrefs[i].href.toLowerCase().indexOf("/co/basket.aspx?wtqty") > -1)
        {
			var pProId = psTrim(psGetElementValueById("hfSetCourseID"));
			var pProSetId = psTrim(psGetElementValueById("hfUpsellSetTitle"));
			if(pFlag)
			{
				psCreateProductviewTag(pProId,pProSetId,pCatId);
				pFlag = false;
			}
			var oldCMFunc = hrefs[i].onclick; //backup the existing onclick function
			hrefs[i].onclick = function()
            {	
				// Store productId along with catId to cookie for use later in shop5 and shop9 views
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pProId , pCatId);
				if (oldCMFunc != null)
					return oldCMFunc();
            }			
        }
    }
}
// Check if array is exist or not
function psCheckArrayExist(pArrElement)
{
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0)
    {
        return false;
    }
    return true;
}

// Check an element exist or not
function psCheckElementExist(pElement)
{
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }
    return true;
}
function psGetValueByTagName(pName,pValueFlag)
{
	var lstNames = document.getElementsByName(pName);
	if(psCheckArrayExist(lstNames))
	{
		var sText = psGetElementValue(lstNames[0],pValueFlag);
		return psTrim(sText);
	}
	return null;
}
function psGetPostOfCellByName(pTable,pCellName)
{
	if(psCheckElementExist(pTable))
	{
		for(var i =0; i < pTable.rows.length ; i++)
		{
			pRow = pTable.rows[i];
			for(var j =0 ; j < pRow.cells.length ; j++)
			{
				if(pRow.cells[j].innerHTML.toLowerCase().indexOf(pCellName.toLowerCase()) > -1)
					return j;
			}
		}		
	}
	return -1;
}
function psGetTableFromCell(pCellName)
{
	var sTblRe = null;
	var lstTable = document.getElementsByTagName("table");
	if(psCheckArrayExist(lstTable))
	{
		for (var j=0; j<lstTable.length; j++)	
		{
			var sRows = lstTable[j].rows; // use rows variable for optimization
			var sStop = (sRows.length > 1)? 2:sRows.length;
			for(var i=0; i< sStop; i++)
			{
				for(var t=0; t<sRows[i].cells.length; t++)
				{
					var sHeader = psCleanHtmlTag(sRows[i].cells[t].innerHTML);
					if (sHeader.toLowerCase().indexOf(pCellName.toLowerCase()) > -1)
					{
						//we need catch the lastest of table so can't put a break 
						sTblRe = lstTable[j];			
					}
				}
			}
		}
	}
	return sTblRe;
}
function psGetValueByTagName(pName,pValueFlag)
{
	var lstNames = document.getElementsByName(pName);
	var sText = psGetElementValue(lstNames[0],pValueFlag);
	return (lstNames && lstNames.length >0)?psTrim(sText):"";
}
function psSetCusGiftToCookie()
{
	var lstNames = document.getElementsByName("SubmitInfo");
	if(psCheckArrayExist(lstNames))
	{
		var pSignBtn = lstNames[0];
		if(psCheckElementExist(pSignBtn))
		{
			pSignBtn.oldCMFunc = pSignBtn.onclick; //backup the existing onclick function
			pSignBtn.onclick = function()
			{
				var pEmail = psGetElementValueById("EmailAddress");
				if(pEmail && pEmail != "")
				{
					var email = psTrim(pEmail);
					var cusId = psTrim(pEmail);
					var city = psGetElementValueById("City");
					var state = psGetValueByTagName("Region",true);
					var zipcode = psGetElementValueById("PostalCode");
					var data = cusId + "|" + email + '|' + city + '|' + state + '|' + zipcode;
					// store on cookie
					psSetCookie(G_PS_COOKIE_PROFILE_GIFT, data);
				}
				if (this.oldCMFunc != null)
					return this.oldCMFunc();
			}
		}
	}
}
function psCheckPriceValue(pText)
{
	return pText.search(/\$\d*\.*\d*/gi) > -1? true:false;
}
function psIsNumber(val)
{
	if(val != null && val != "")
		return (isNaN(val) == true)?false:true;
	return false;
}
function psIsTranscriptProduct(pProId)
{
	return pProId.search(/t\d*/gi) > -1? true:false;
}
/*====================== 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!
			
			this.id = psGetValueFromUrl(G_PS_URL_PATH,"cid");
			this.id = psTrim(this.id);
			var psCourse = psGetElementsByClassName(document,"span","courseTitle");
			if(psCheckArrayExist(psCourse))
			{
				this.name = psCleanProductName(psHtmlDecode(psCourse[0].innerHTML));
				this.name = psTrim(psCleanHtmlTag(this.name.toLowerCase()));
			}
			else 
			{
				var objTitle = psGetElementsByClassName(document,"p","dek");
				if(psCheckArrayExist(objTitle))
				{
					var pTagPText = objTitle[0].innerHTML.toLowerCase().split("p>");
					if(psCheckArrayExist(pTagPText))
					{
						var pText = pTagPText[0].split("<strong>");
						if(psCheckArrayExist(pText))
						{
							var pName =  pText[1].split("<");
							if(psCheckArrayExist(pName))
								this.name = psCleanProductName(psCleanHtmlTag(psHtmlDecode(pName[0])));
						}
					}	
				}
				else
				{
					objTitle = psGetElementsByClassName(document,"p","headline");
					if(psCheckArrayExist(objTitle))
						this.name = psCleanProductName(psCleanHtmlTag(psHtmlDecode(objTitle[0].innerHTML)));				
				}
			}
			//Look for CatID SPLIT prefix; apply later if present

			//productview from search result page. 
			if(G_PS_URL_REFERRER.indexOf("/searchv2/searchttc.aspx") >-1)
			{
				this.catId = "SEARCH";
				this.catId = psGetDCSext(this.catId); 
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
			}
			//productview from shopping cart. 
			else if(G_PS_URL_REFERRER.indexOf("/co/basket.aspx") >-1)
			{
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null || this.catId == "null"){this.catId = "HOME"; this.catId = psGetDCSext(this.catId); }

				this.catId = psCleanCatId(this.catId); 
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id,this.catId);
			}
			else if(G_PS_PATHNAME == "/ttcx/magazine.aspx")
			{
				this.catId = "MAGAZINE";
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
			}
			// In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
			//productview from email campaign
			else if (G_PS_URL_REFERRER.indexOf("cm_mmc=email") > -1) {

			    this.catId = "EMAIL";

			    psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);

			}
			else if(G_PS_PATHNAME == "/ttcx/lp_general.aspx")
			{
				this.catId = "SPACE AD";
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
			}
			else
			{
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
				if(this.catId == null && G_PS_URL_REFERRER == "") 
				{
					this.catId = "BOOKMARK";
				}
				else if(this.catId == null) 
				{
					this.catId = "HOME";
				}
				this.catId = psGetDCSext(this.catId); 
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
			}
			psHijackUpsellSet(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!
			if(itemRow.cells.length > 3 && itemRow.cells[3].getElementsByTagName("select").length > 0)
			{
				
				this.id = psGetValueFromUrl(itemRow.cells[1].getElementsByTagName("a")[0].href,"cid");
				this.name =  psCleanProductName(psHtmlDecode(itemRow.cells[1].getElementsByTagName("a")[0].innerHTML));
				this.name = psTrim(psCleanHtmlTag(this.name.toLowerCase()));
				this.price = psTrim(psCleanHtmlTag(itemRow.cells[2].innerHTML.replace('$','')));
				
				if(itemRow.cells[3].getElementsByTagName("select").length > 0)
				{
					var pTagObj = itemRow.cells[3].getElementsByTagName("select")[0];
					this.quantity = psTrim(pTagObj.options[pTagObj.selectedIndex].value);
				}
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null || this.catId == "null")
				{
					this.catId = "NO CATEGORY";
				}

				// MAKE TRANSCRIPT SEP ITEM, SAME CAT ID
				var lstTemp =  itemRow.cells[1].innerHTML.toLowerCase().split("<br");
				if(psCheckArrayExist(lstTemp) && lstTemp.length > 1)
				{
					var temp = psHtmlDecode(lstTemp[1]);
					if(temp.indexOf("transcript")>-1)
					{ 
						this.id = "T" + this.id;   
						this.name = this.name + " transcript";  
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
					}
				}
				return true;
			}
		}
		catch (ex) { return false; }
	}
	this.getItem5_Re = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			if(itemRow.cells.length > 3)
			{
				this.id = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[0].innerHTML))); 
				this.name = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[1].innerHTML))); 	
				if(psIsTranscriptProduct(this.id.toLowerCase()))
					this.name = this.name + " transcript"; 
				this.quantity =  psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[2].innerHTML))); 	
				this.price =  psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[3].innerHTML))); 	
				this.price =  psCleanPrice(this.price);
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null || this.catId == "null")
				{
					this.catId = "NO CATEGORY";
				}
			}
			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!
			
			if(itemRow.cells.length > 3)
			{
				this.id = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[0].innerHTML))); 	
				this.name = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[1].innerHTML))); 	
				if(psIsTranscriptProduct(this.id.toLowerCase()))
					this.name = this.name + " transcript"; 
				this.quantity =  psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[2].innerHTML))); 	
				this.price =  psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[3].innerHTML))); 	
				this.price =  psCleanPrice(this.price);
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null || this.catId == "null")
				{
					this.catId = "NO CATEGORY";
				}
			}
			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] != ""?buf[3]:null;
				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.email == 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);
			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
		{
			//get order id.
			var objOrder = psGetElementsByClassName(document, "span", "textConfirmationNumber");
			var pValue = psGetCookie(G_PS_COOKIE_ORDER);
			if(objOrder && objOrder.length >0)
			{
				this.id = psTrim(psCleanHtmlTag(objOrder[0].innerHTML));		
			}
			if(pValue != null)
			{
				var arrValue = 	pValue.split(":");				
				this.subtotal = arrValue[0] == "null"?null:arrValue[0].replace("$","");
				this.shipping = arrValue[1] == "null"?null:arrValue[1].replace("$","");
			}
			if (!this.id)
				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;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

function psCleanProductName(pProductName)
{
	pProductName = pProductName.replace(String.fromCharCode(8212),"-");
	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}
/* PURPOSE: Remove all HTML tags in a string
 * RETURN: string
 */
function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : null;
}
/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
function psHtmlDecode(pValue)
{
    if (pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
    }

    return pValue;
}

/* PURPOSE: 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;
}

/* 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;

	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	if(pLifeTime == "delete") 
    {         
        CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
        return true;
    }
    // set cookie by calling coremetrics's cookie function
    var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
    
    return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

/* PURPOSE: set value in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 * NOTE: Use null or '' for pValue to remove the pair specified by pKey
 */
function psSetValueToCookie(pCookieName, pKey, pValue)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;

	var start = catCookie.indexOf(pKey);
	if (start >= 0) // Store before -> remove the old value
	{
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1)
			end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
	}
	// remove the last items (eldest items) until cookie size < 3500	
	if (pValue != null && pValue != '')
	{
		catCookie = pKey + pValue + catCookie;
		var cookieArray = null;
		while (catCookie.length > 3500)
		{
			cookieArray = catCookie.split("#");
			cookieArray.pop();
			catCookie = cookieArray.join("#");
		}
	}
	// Save to cookie
	psSetCookie(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

/* PURPOSE: get value stored in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 */
function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if (catCookie != null)
    {
        var start = catCookie.indexOf(pKey);
		if (start >=0 )
		{
			start = start + pKey.length;
			var end = catCookie.indexOf("#", start);
			if (end == -1)
				end = catCookie.length;
			return catCookie.substring(start, end);
		}
		return null;
    }
    return null;
}

/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dtDate = new Date();
	var cusRandom = (dtDate.getTime()%10000000) + (Math.floor(Math.random()*10000));
	return cusRandom;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);

    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + pId + ", " + pName + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(pId, pName, pCatId);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId);    
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
	pOrderTotal = psCleanPrice(pOrderTotal);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCusID + ", " + pOrderID + ", " + pOrderTotal + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId);
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip) 
{
	pOrderTotal = psCleanPrice(pOrderTotal);
	pOrderShipping = psCleanPrice(pOrderShipping);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + pId + ", " + pOrderTotal + ", " + pOrderShipping + ", " + pCusID + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip);
}

function psCreateConversionEventTag(pId, pActionType, pCatID, pPoints) 
{
	pCatID = psCleanCatId(pCatID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + pId + ", " + pActionType + ", " + pCatID + ", " + pPoints + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(pId, pActionType, pCatID, pPoints);
}

function psCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pNewsletter + ", " + pSubscribe + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe);
}

function psCreateErrorTag(pPageID, pCatId) 
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateErrorTag(" + pPageID + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateErrorTag(pPageID, pCatId);
}

function psDisplayShop5s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop5s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop5s();
}

function psDisplayShop9s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop9s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop9s();
}
/*===========================END GENERAL UTILITY FUNCTION ==================*/