/************************************************************************************/
/* $Revision: 134031 $
 * $Id: cmtaggingservices-112409.js 134031 2009-11-24 19:48:50Z yhunt $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v2.1, 2009/11/24
 * 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("inspiredfaith.com","nexternal.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_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var G_PS_COOKIE_CLICKED_MENU = "PS_CLICKED_MENU";
var G_PS_COOKIE_ORDER = "PS_ORDER";
var G_PS_COOKIE_SHOP9 = "G_PS_COOKIE_SHOP9";
var G_PS_COOKIE_EMAIL = "PS_EMAIL_TEMP";
var G_PS_COOKIE_TERM = "PS_SEARCH_TERM";
var INTERVAL_ID=null;

/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if(G_PS_URL_PATH.indexOf("twitter.com/inspired_faith") >= 0){	
	psCreatePageviewTag("TWITTER", "COMMUNITY", null, null);
}
if(G_PS_URL_PATH.indexOf("facebook.com/pages/inspired-faith/105471527226") >= 0){	
	psCreatePageviewTag("FACEBOOK", "COMMUNITY", null, null);	
}

if (G_PS_URL_PATH.search(/inspiredfaith\.com/i) >= 0 || G_PS_URL_PATH.indexOf("store.nexternal.com") >= 0){	
	// Content pages on www.inspiredfaith.com, and http://store.inspiredfaith.com
	// Shop5, shop9 and order on https://store.nexternal.com	
	if (psIsSearchView())
	{
		psPostSearchView();
	}
	else if (psIsProductView())
	{
		psPostProductView();
	}	
	else if (psIsCartView() && psIsOrderView() == false)
	{		
		psPostCartView();
		psHijackShippingChange();
		psGetUserInfo();		
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}	
	else if(psPostPageView() == false)
	{	if(psIsNoPage() == false){
			psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
		}
	}
	psHijackClickedMenu();
	psHijackSiteSearch();
	psHijackSearchTable();
	if(G_PS_URL_PATH.indexOf("/shared/storefront/search.asp")  > -1){
		psHijackAdvanceSearch();
	}
	psHijackAddToCart();

}
// End navigation

function psIsNoPage(){
	// Don't send pageview
	if(G_PS_PATHNAME.indexOf("shared/storefront/persistant_category.asp") >= 0 ||
	   G_PS_PATHNAME.indexOf("shared/storefront/products.asp") >= 0 ||
	   G_PS_PATHNAME.indexOf("shared/storefront/user_reg.asp") >= 0 ||
	   G_PS_PATHNAME.indexOf("shared/storefront/redirect.asp") >= 0 ||
	   //G_PS_PATHNAME.indexOf("shared/storefront/category_detail.asp") >= 0 ||
	   G_PS_PATHNAME.indexOf("shared/storefront/default.asp") >= 0 ){
		return true;
	}
	return false;
}

function psPostPageView(){
	var pPageId = null;
	var pCatId = null;
	
	if(G_PS_PATHNAME.search(/order_confirm\.asp/i) >= 0){
		pCatId = "Checkout";
		pPageId = "Thank you for your order";		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/search\.asp/i) >= 0){
		pCatId = "Store";
		pPageId = "Advanced Search";		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/tellafriend\.asp/i) >= 0 ||
	   G_PS_PATHNAME.search(/shared\/StoreFront\/tellafriend_send\.asp/i) >= 0 ||
	   G_PS_PATHNAME.search(/shared\/StoreFront\/enter_ship_to\.asp/i) >= 0){
		pCatId = "Store";
		var bannerText = document.getElementById("bannerText");
		if(psCheckElementExist(bannerText)){
			pPageId = psGetInnerText(bannerText);
		}
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/common_policy\.asp/i) >= 0 ||
	         G_PS_PATHNAME.search(/shared\/StoreFront\/ship_policy\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/shared\/StoreFront\/edit_address\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/shared\/StoreFront\/edit_cc\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/shared\/StoreFront\/verify_login\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/shared\/StoreFront\/account\.asp/i) >= 0 ){
		pCatId = "Store";
		pPageId = psGetInnerTextFirstElement("title").split("--")[0];		
	}else if(G_PS_PATHNAME.search(/safesender\.asp/i) >= 0){
		pCatId = "Store";
		pPageId = "Safe Sender";
	}else if(G_PS_PATHNAME == "/index.asp" || G_PS_PATHNAME == "/"){
		pCatId = "Home";
		pPageId = psGetInnerTextFirstElement("title");
		psSetCookie(G_PS_COOKIE_CLICKED_MENU,"","delete");
	}else if(G_PS_PATHNAME == "/partners.asp" || G_PS_PATHNAME == "/about.asp" ||
	         G_PS_PATHNAME == "/contact.asp" || G_PS_PATHNAME == "/movies.asp" ){
		
		pCatId = G_PS_PATHNAME.replace("/","").replace(".asp","");
		if(G_PS_PATHNAME == "/about.asp"){
			pPageId = psGetMainH2Value("last");
		}else{
			pPageId = psGetMainH2Value();
		}		
	}else if(G_PS_PATHNAME == "/newsletter.asp" || G_PS_PATHNAME == "/blog.asp" || G_PS_PATHNAME == "/devotions.asp"){
		pCatId = "Community";
		pPageId = psGetMainH2Value();
	}else if(G_PS_PATHNAME == "/authors.asp" || G_PS_PATHNAME == "/affiliates.asp" ||	
	         G_PS_PATHNAME == "/returns.asp" || G_PS_PATHNAME == "/shipping.asp" ||
			 G_PS_PATHNAME == "/privacy.asp" || G_PS_PATHNAME == "/sitemap.asp" ){
			 
		pCatId = "Footer";
		pPageId = psGetMainH2Value();
		
	}else if(psIsCategoryPage()){		
		var bannerText = document.getElementById("bannerText");
		if(psCheckElementExist(bannerText)){
			pPageId = psTrim(psHtmlDecode(unescape(psGetInnerText(bannerText))));
		}else{
			pPageId = psGetInnerTextFirstElement("title").split("--")[0];			
		}		
		var temp = psGetValueFromUrl(G_PS_URL_PATH,"CategoryID");
		if(temp != null && temp != ""){
			// Click on the left menu
			pCatId = "Categories";
		}else{
			// Click on top menu, footer or from home page
			var clickedMenu = psGetCookie(G_PS_COOKIE_CLICKED_MENU);
			if(clickedMenu != null && clickedMenu != ""){
				pCatId = clickedMenu;				
			}else{
				var prePage = psGetCookie(G_PS_COOKIE_CATID);				
				if(prePage != null && prePage.search(/our\s+partners/i) >= 0){
					pCatId = "Categories";
				}else{
					pCatId = "Store";
				}				
			}
		}
		psSetCookie(G_PS_COOKIE_CLICKED_MENU,"","delete");
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/(categories|category_detail)\.asp/i) >= 0){		
		pCatId = "Store";
		pPageId = "Select a Category";		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/cart_calculator1\.asp/i) >= 0){
		pCatId = "Store";
		pPageId = "Ship To";		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/cart_calculator2\.asp/i) >= 0){
		pCatId = "Store";
		pPageId = "Ship Via";		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/gift_adder\.asp/i) >= 0){
		pCatId = "Store";
		pPageId = "Packing Slip Message";		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/enter_giftcard\.asp/i) >= 0){
		pCatId = "Store";
		pPageId = "Gift Message";		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/(login|register)\.asp/i) >= 0 ||	         
			 G_PS_PATHNAME.search(/shared\/StoreFront\/password_reminder\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/shared\/StoreFront\/enter_coupon\.asp/i) >= 0 ){

		pCatId = "Store";
		var banners = psGetElementsByClassName(document,"tr","banner1");
		if(psCheckArrayExist(banners)){
			pPageId = psGetInnerText(banners[0]);
		}
		// Hijack for registration
		if(G_PS_PATHNAME.search(/shared\/StoreFront\/register\.asp/i) >= 0){
			pCatId = "New Customer";
			pPageId = "Register";
			var from = psGetValueFromUrl(G_PS_URL_PATH,"from");
			if(from == "account"){
				pCatId = "Store";
				pPageId = "Edit Contact Information";
			}
			psHijackUpdateAcc();
		}		
		if(G_PS_URL_PATH.indexOf("/shared/storefront/login.asp") > -1){
			psHijackLogin();
		}
		// Checkout on domain store.nexternal.com
//		if(G_PS_PATHNAME.search(/shared\/StoreFront\/(login|register)\.asp/i) >= 0 &&
//		   G_PS_URL_PATH.indexOf("store.nexternal.com") >= 0){
//		   pCatId = "Checkout";
//		}
		
	}else if(G_PS_PATHNAME.search(/shared\/StoreFront\/orderinfo\.asp/i) >= 0){
		pCatId = "Checkout";
		pPageId = "Ship To/Bill To";
		psSaveBillInfo();
	}else if(G_PS_URL_PATH.indexOf("/shared/storefront/cart.asp") > -1){		
		psHijackViewProductFromCart();
		psPostLoginSuccess();
		return true;
	}	
	// Check registration if it navigates to the following page
	if(G_PS_PATHNAME.search(/shared\/StoreFront\/(user_reg|categories|category_detail|account|orderinfo)\.asp/i) >= 0){       
		var cookieFlag = psGetCookie(G_PS_COOKIE_FLAG);
		if(cookieFlag == "login"){			
			//psPostLoginSuccess();
			psPostRegistration();
		}else if(cookieFlag == "update account" && psCheckUpdateSucc()){
			psUpdateAccount();
		}
	}
	
	if(pPageId == null || pCatId == null){
		return false;
	}
	
	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));
	
	pPageId = pPageId.toUpperCase();
	pCatId = pCatId.toUpperCase();
	
	psCreatePageviewTag(pPageId, pCatId, null, null);
	if(G_PS_PATHNAME == "/index.asp" || G_PS_PATHNAME == "/" || psIsCategoryPage()){
		psSetCookie(G_PS_COOKIE_CATID,pPageId);
	}
	return true;
}

function psGetUserInfo(){
	/* If user has already logined on domain inspiredfaith.com, 
	   we could not get the email on domain nexternal.com.
	   Get customer name from Billing address for CustomerID, CustomerEmail
	*/
	var uP = new psProfile();
	uP.readProfile();
	if(uP.email == null || uP.email == ""){		
		var pTags = document.getElementsByTagName("p");
		if(psCheckArrayExist(pTags)){
			for(var i=0; i<pTags.length; i++){
				if(psGetInnerText(pTags[i]).search(/This\s+is\s+a\s+(residential|business)\s+address/i) >= 0){					
					var items = pTags[i].innerHTML.split(/<br\s*\/*>/gi);
					if(items.length > 3){
						var uName = psTrim(items[0]);
						if(uName.search(/\s+/) >= 0){
							uP.cusId = uName.split(/\s+/)[0];
							uP.email = uP.cusId;
						}
						var addr = psTrim(items[2]);
						if(addr.indexOf(",") >= 0){
							var temp = addr.split(",");
							uP.city = psTrim(temp[0]);
							temp[1] = psTrim(temp[1]);
							if(temp[1].search(/\s+/) >= 0){
								var temp2 = temp[1].split(/\s+/);
								uP.state = temp2[0];
								uP.zipcode = temp2[1];
							}
						}
					}
				}
			}
		}		
		uP.writeProfile();
	}
}

function psHijackShippingChange(){
	// Update shipping cost when it changes
	var shippingOption = document.getElementById("ShippingOption0_0");
	if(psCheckElementExist(shippingOption)){		
		if(shippingOption.onchange == null || shippingOption.onchange.toString().indexOf("HijackShipping") < 0){			
			shippingOption.OldFunction = shippingOption.onchange;
			shippingOption.onchange = function HijackShipping(){				
				var str = shippingOption.options[shippingOption.selectedIndex].innerHTML;				
				if(str.search(/\(\$(.+)\)/) >= 0){
					var shipping = RegExp.$1;					
					psSetValueToCookie(G_PS_COOKIE_ORDER,"shipping",shipping);
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackViewProductFromCart(){		
	// To avoid error Stack overflow, infinitive loop caused by conflict with link click of coremetric
	// this function just inserts new code in the current Hijack function.
	var cartTable = document.getElementById("nextCartData");
	if(psCheckElementExist(cartTable)){		
		var a_Tags = cartTable.getElementsByTagName("a");		
		if(psCheckArrayExist(a_Tags)){
			for(var i=0; i<a_Tags.length; i++){				
				if(a_Tags[i].href != null && a_Tags[i].href.search(/products\.asp\?RowID=/i) >= 0){
					//var prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(a_Tags[i])))));					
					if(a_Tags[i].onclick == null){
						a_Tags[i].onclick = function(){
							psSetCookie(G_PS_COOKIE_CLICKED_MENU,"from_cart");
						}
					}else if(a_Tags[i].onclick.toString().indexOf("HijackViewFromCart") < 0){											
						var strFunction = a_Tags[i].onclick.toString();						
						// split current function into header and body section
						var begin_function=strFunction.indexOf("{");
						var part1=strFunction.substring(0,begin_function);	
						var part2=strFunction.substring(begin_function,strFunction.length);	
						// Get the argument in the current Hijack
						var arg_pattern=/\((.*)\)/;
						var fArg="";
						if(arg_pattern.test(part1)){
							fArg=RegExp.$1;
						}
						// Insert Hijack2 code at the beginning of current Hijack
						part2=part2.replace(/\{/,"{ psClickProductFromCat();");	
						// Create new function for event
						if(fArg.length>0){
							a_Tags[i].onclick=new Function(fArg,part2);
						}else{
							a_Tags[i].onclick=new Function(part2);
						}						
					}					
				}
			}
		}
	}
}

function psClickProductFromCat(){
	psSetCookie(G_PS_COOKIE_CLICKED_MENU,"from_cart");
}

function psHijackAddToCart(){
	// Hijack on Category page & search page
	var prdTable = document.getElementById("nextProductListTable");
	if(psCheckElementExist(prdTable) && psIsProductView() == false){
		var Rows = prdTable.rows;
		for(var r=0; r < Rows.length; r++){			
			var prdName = null;
			var aTags = Rows[r].getElementsByTagName("a");
			for(var i=0; i<aTags.length; i++){
				// get product name
				if(aTags[i].className != null && aTags[i].className.toLowerCase() == "nextprodname"){
					prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[i])))));
				}
				// Hijack Add to cart
				if(aTags[i].innerHTML.search(/(Add\s+to\s+Cart|inspiredfa\/if_addtocart\.jpg)/i) >= 0){
					if(aTags[i].onclick == null || aTags[i].onclick.toString().indexOf("HijackAddToCart1") < 0){
						aTags[i].OldFunction = aTags[i].onclick;
						aTags[i].prdName = prdName;
						aTags[i].onclick = function HijackAddToCart1(){
							var pCat = null;
							if(G_PS_URL_REFERRER == null){
								pCat = "BOOKMARK";
							}else{
								pCat = psGetCookie(G_PS_COOKIE_CATID) != null? psGetCookie(G_PS_COOKIE_CATID):"Home Page";
							}
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdName,pCat);
							if(this.OldFunction != null) return this.OldFunction();
						}
					}
				}
			}			
		}
	}
	// Hijack on product page
	if (psIsProductView()){
		var prdName = null;
		var prdTag = document.getElementById("nextProductName");
		if(psCheckElementExist(prdTag)){
			prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(prdTag)))));
		}
		var aTags = document.getElementsByTagName("a");
		for(var i=0; i<aTags.length; i++){
			// Hijack Add to cart
			if(aTags[i].innerHTML.search(/(Add\s+to\s+Cart|inspiredfa\/if_addtocart\.jpg)/i) >= 0){
				if(aTags[i].onclick == null || aTags[i].onclick.toString().indexOf("HijackAddToCart2") < 0){
					aTags[i].OldFunction = aTags[i].onclick;
					aTags[i].prdName = prdName;
					aTags[i].onclick = function HijackAddToCart2(){
						var pCat = null;
						if(G_PS_URL_REFERRER == null){
							pCat = "BOOKMARK";
						}else{
							pCat = psGetCookie(G_PS_COOKIE_CATID) != null? psGetCookie(G_PS_COOKIE_CATID):"Home Page";
						}
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdName,pCat);
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}			
	}	
}

function psHijackClickedMenu(){	
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags)){
		for(var i=0; i < aTags.length; i++){
			// Hijack Gifts Image on home page and "List of Our Titles" at the footer
			if(aTags[i].innerHTML.search(/images\/(homeButton_gifts\.jpg|side_gifts\.png)/i) >= 0 || 
			   psGetInnerText(aTags[i]).indexOf("List of Our Titles") >= 0){				
				if(aTags[i].onclick == null || aTags[i].onclick.toString().indexOf("HijackClickedMenu") < 0){					
					aTags[i].ClickedMenu = "Footer";
					if(aTags[i].innerHTML.search(/images\/homeButton_gifts\.jpg/i) >= 0){
						aTags[i].ClickedMenu = "Gifts";
					}					
					aTags[i].OldFunction = aTags[i].onclick;
					aTags[i].onclick = function HijackClickedMenu(){
						psSetCookie(G_PS_COOKIE_CLICKED_MENU,this.ClickedMenu);
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}	
}

function psIsCategoryPage(){
	if(G_PS_PATHNAME.search(/shared\/StoreFront\/product_detail\.asp/i) >= 0){		
		var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"CategoryID");		
		if(pCatId != null && pCatId != ""){
			return true;
		}else{
			var bannerText = document.getElementById("bannerText");
			if(psCheckElementExist(bannerText)){
				return true;
			}
		}
	}
	return false;
}

function psGetMainH2Value(pIndex){
	var res = null;
	var divTags = psGetElementsByClassName(document,"div","interiorcontentwrapper");
	if(psCheckArrayExist(divTags)){
		var h2Tags = divTags[0].getElementsByTagName("h2");
		if(psCheckArrayExist(h2Tags)){
			if(pIndex != null && pIndex != ""){				
				if(pIndex.toLowerCase() == "last"){
					res = psGetInnerText(h2Tags[h2Tags.length -1]);
				}else if(pIndex >= 0 && pIndex < h2Tags.length){
					res = psGetInnerText(h2Tags[pIndex]);
				}
			}else{
				res = psGetInnerText(h2Tags[0]);
			}
		}
	}
	return psTrim(res);
}

function psGetInnerTextFirstElement(pTag){
	if(pTag == null || pTag == "") return null;
	var pItems = document.getElementsByTagName(pTag);
	if(psCheckArrayExist(pItems)){
		return psTrim(psGetInnerText(pItems[0]));
	}
	return null;
}

/*
 * Start: Define functions for search and registration
*/

function psHijackSiteSearch()
{
	var sForms = document.getElementsByTagName("form");
	if (psCheckArrayExist(sForms) == false)
		return;	
	for(var i=0;i<sForms.length;i++)
	{
		var sbmForms = sForms[i];
		if(sbmForms.action!=null && sbmForms.action.toLowerCase().indexOf("http://store.inspiredfaith.com/") > -1)
		{
			sbmForms.OldFunc = sbmForms.onsubmit; // Back up original pointer
			sbmForms.onsubmit = function()
			{
				var sTerm = "";
				var sInputs = this.getElementsByTagName("input");
				if(psCheckArrayExist(sInputs))
				{
					for(var j=0;j<sInputs.length;j++)
					{
						if(sInputs[j].name != null && psTrim(sInputs[j].name.toLowerCase()) == "keyword")
						{
							sTerm = psTrim(sInputs[j].value);				
						}
					}
				}
				if(sTerm != "")
					psSetCookie(G_PS_COOKIE_TERM,sTerm);						
				if (this.OldFunc != null)
					return this.OldFunc();
			}			
			break;
		}
	}	
}
function psHijackSearchTable()
{

	var searchForm = document.getElementById("nextSearchForm");
	if(psCheckElementExist(searchForm) == false){
		return;
	}

	searchForm.OldFunc = searchForm.onsubmit; // Back up original pointer		
	searchForm.onsubmit = function()
	{		
		var sTerm = psGetElementValueById("nextSearchField");		
		if(sTerm != "")
			psSetCookie(G_PS_COOKIE_TERM,psTrim(sTerm));	
		if (this.OldFunc != null)
			return this.OldFunc();
	}
}

function psHijackAdvanceSearch()
{
	var sForms = document.getElementsByTagName("form");
	if (psCheckArrayExist(sForms) == false)
		return;		
	for(var i=0;i<sForms.length;i++)
	{
		var sSearchForm = sForms[i];
		if(sSearchForm.action!=null && sSearchForm.action.toLowerCase().indexOf("products.asp") > -1)
		{
			sSearchForm[i].OldFunc = sSearchForm[i].onsubmit; // Back up original pointer
			sSearchForm.onsubmit = function()
			{
				var sTerm = psGetElementValueById("Keyword");
				if(sTerm != "")
					psSetCookie(G_PS_COOKIE_TERM,psTrim(sTerm));						
				psSetCookie(G_PS_COOKIE_FLAG, "search");											
				if (this.OldFunc != null)
					return this.OldFunc();
			}				
			break;
		
		}
	}
}

function psSaveBillInfo()
{
	var btnContinue = document.getElementById("nextButtonContinueToSecurePaymentPage");
	if(psCheckElementExist(btnContinue))
	{
		btnContinue.oF = btnContinue.onclick;
		btnContinue.onclick = function()
		{
			var uP = new psProfile();
			var sText = psCleanHtmlTag(document.getElementsByTagName("body")[0].innerHTML.toLowerCase());
			sText = sText.search(/e-mail address:\s([^:]+:)/gi);
			var email = RegExp.$1;
			email = psTrim(email.replace("password:",""));
			uP.email = (uP.readProfile()== true)?uP.email:email;
			uP.city = psTrim(psGetElementValueById("BILL_CITY"));
			uP.state = psTrim(psGetElementValueById("BILL_STATE",false));
			uP.zipcode = psTrim(psGetElementValueById("BILL_ZIP"));
			uP.writeProfile();
			if(psCheckElementExist(this.oF)==true)
			{
				return this.oF();
			}
		}	
	}
}
function psUpdateAccount()
{
	var uP = new psProfile();
	var cusId = psGetCookie(G_PS_COOKIE_EMAIL);
	if (cusId!= null)
	{
		var buf = 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); 
		}
		uP.cusId = buf[0];
		if (!uP.cusId)
			uP.cusId = psGenerateRandomValue();
		uP.email = buf[1];
		uP.city = buf[2];
		uP.state = buf[3];
		uP.zipcode = buf[4];
		uP.newsletter = null;
		uP.subscribe = null;
	}
	uP.writeProfile(); // get user profile from cookie
	if(uP.email != null)
	{
		psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
	psSetCookie(G_PS_COOKIE_EMAIL,"","delete");
}
function psPostLoginSuccess()
{
	var linkLogout = document.getElementById("nextCartLogout");
	if(psCheckElementExist(linkLogout) == false){		
		var cartFrame = document.getElementById("NexternalCart");
		if(psCheckElementExist(cartFrame)){
			linkLogout = cartFrame.contentWindow.document.getElementById("nextCartLogout");
		}
	}
	if(psCheckElementExist(linkLogout) && psGetCookie(G_PS_COOKIE_FLAG) == "login")
	{
		psPostRegistration();
	}
}

function psPostRegistration()
{
	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_COOKIE_FLAG,"delete");
}

function psHijackLogin()
{
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	var btnLogin = document.getElementById("nextButtonLogInSecurely");
	if(psCheckElementExist(btnLogin))
	{
		btnLogin.oF = btnLogin.onclick;
		btnLogin.onclick = function()
		{
			var email = document.getElementById("EMAIL");
			if(psCheckElementExist(email) && psCheckEmail(psTrim(email.value)))
			{
				var uP = new psProfile();
				uP.email = uP.cusId = psTrim(email.value);				
				uP.writeProfile();				
				psSetCookie(G_PS_COOKIE_FLAG,"login");
			}
			if(psCheckElementExist(this.oF)==true)
			{
				return this.oF();
			}
		}						
	}	
}
function psCheckUpdateSucc()
{
	if(document.getElementsByTagName("body")[0].innerHTML.toLowerCase().indexOf("address validation error") > -1)
	{
		return false;
	}
	return true;
		
}
function psHijackUpdateAcc()
{
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	psSetCookie(G_PS_COOKIE_EMAIL,"","delete");
	var btnUpdate = document.getElementById("nextButtonReg");
	if(psCheckElementExist(btnUpdate))
	{
		btnUpdate.oF = btnUpdate.onclick;
		btnUpdate.onclick = function()
		{
			var pEmail = psGetElementValueById("EMAIL");
			if(psCheckElementExist(pEmail))
			{
				var city = psGetElementValueById("CITY");
				var state = psGetElementValueById("STATE",false);
				var zipcode = psGetElementValueById("ZIP");
				
				var data = psTrim(pEmail) + "|" +psTrim(pEmail) + '|' + psTrim(city) + '|' + psTrim(state) + '|' + psTrim(zipcode);
						// store on cookie
				psSetCookie(G_PS_COOKIE_EMAIL, data);
				psSetCookie(G_PS_COOKIE_FLAG,"update account");
				
				if(psCheckElementExist(this.oF)==true)
				{
					return this.oF();
				}
			}	
		}	
	}	
}

function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : null;
}

/*
 * End: Define functions for search and registration
*/

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	if(document.title !=null && document.title.toLowerCase().indexOf("search results") > -1)
		return true;
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	var bFlag = false;
	if (G_PS_PATHNAME.indexOf("shared/storefront/product_detail.asp")>=0){
		var rowid = psGetValueFromUrl(G_PS_URL_PATH,"rowid");
		if (rowid!=null && rowid!="")
			bFlag=true;	
		else
			bFlag=false;	
	}		
	return bFlag;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_PATHNAME.search(/shared\/StoreFront\/invoice\.asp/i) >= 0) return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_PATHNAME.search(/shared\/StoreFront\/invoice/i) >= 0 || G_PS_PATHNAME.search(/(order_confirm\.asp|order\.asp)/i) >= 0){
		var pTags = document.getElementsByTagName("p");
		if(psCheckArrayExist(pTags)){
			for(var i=0; i < pTags.length; i++){
				if(psGetInnerText(pTags[i]).search(/Your\s+order\s+number\s+is/i) >= 0){
					return true;
				}
			}
		}
	}
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	if(G_PS_PATHNAME.indexOf("product_detail.asp")<0)
		return;	
	// Your logic of throwing pageview tag for search functionalities goes here
	G_PS_CUR_CATID = "SEARCH";
	var pageId = null;
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(sResult == 0 || sResult == "0")
	{
		pageId = "SEARCH UNSUCCESSFUL";
	}
	else
	{
		pageId = "SEARCH SUCCESSFUL";
	}
	if (pageId != null)
	{
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);
	}	
	psSetCookie(G_PS_COOKIE_FLAG, "","delete");	
	psSetCookie(G_PS_COOKIE_CATID,"Search");
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var sTerm = psGetCookie(G_PS_COOKIE_TERM);
	return sTerm;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	var sBody = document.getElementsByTagName("body");
	if(psCheckArrayExist(sBody))
	{
		var sText = psCleanHtmlTag(sBody[0].innerHTML.toLowerCase());
		if(sText.indexOf("there are no products") > -1)
		{
			result = "0";
		}
		else
		{
			result = 0; 
			sTblProduct =  document.getElementById("nextProductListTable");
			if(psCheckElementExist(sTblProduct))
			{
				var sProLink = sTblProduct.getElementsByTagName("a");
				if(psCheckArrayExist(sProLink))
				{
					for(var i=0;i<sProLink.length;i++)
					{
						if(sProLink[i].className && sProLink[i].className.toLowerCase().indexOf("nextprodname") >-1 )
						{
							result+= 1;
						}
					}
				}
			}         
		
		}
	}
	return result;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()) // Get product info successfully?
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("INVOICE", G_PS_CUR_CATID, null,null);

	var cartTbl = null;
	var tables = document.getElementsByTagName("table");
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){			
			if(psHtmlDecode(unescape(psGetInnerText(tables[i]))).search(/Qty\s*Book\s+title\s*Unit\s+Price\s*Ext\s+Price/i) >= 0){				
				cartTbl = tables[i];
			}
		}
	}
	
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	var productIndex = 0;
	var pIndexShop="prd_";
	psSetCookie(G_PS_COOKIE_SHOP9, "", "delete");
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		var rowContent = psHtmlDecode(unescape(psGetInnerText(rows[r])));
		if(rowContent.search(/\$\d+/) < 0) continue;
		if(rowContent.search(/Subtotal\s*\$\d+/i) >= 0){			
			var subtotal = rowContent.replace(/Subtotal/i,"");
			subtotal = psCleanPrice(psTrim(subtotal));
			psSetValueToCookie(G_PS_COOKIE_ORDER,"subtotal",subtotal);			
		}
		if(rowContent.search(/Shipping\s+Policy/i) >= 0){			
			var shipping = rowContent.replace(/.+Shipping\s+Policy/i,"");
			shipping = psCleanPrice(psTrim(shipping));
			psSetValueToCookie(G_PS_COOKIE_ORDER,"shipping",shipping);			
		}
		if(rows[r].cells.length < 7) continue;		
		if (prd.getItem5(rows[r])){
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
			var keyF = pIndexShop + productIndex;
			var temp = prd.name + "-_-" + prd.quantity + "-_-" + prd.price + "-_-" + prd.catId;
			psSetValueToCookie(G_PS_COOKIE_SHOP9,keyF,temp);
			productIndex++;
		}
	}
	// Make sure to have actual postings
	psDisplayShop5s();
}

function psCleanNumber(pNumber){
	var pattern = /[^0-9]/gi;
    return (pNumber != null ? pNumber.toString().replace(pattern, "") : null);
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("Submit Order", G_PS_CUR_CATID, null);

	// Get order number
	var orderNumber = null;
	var tagP = document.getElementsByTagName("P")
	if (psCheckArrayExist(tagP)==true){
		for(var i =0; i< tagP.length; i++){
			var temp = tagP[i].innerHTML;
			if (temp.toLowerCase().indexOf("your order number is")>=0){				
				var arrInfo = temp.toLowerCase().split("<br>");				
				if (arrInfo[4]!=null){
					orderNumber = psCleanNumber(arrInfo[4]);
				}
			}
		}
	}
	
	var subtotal = psGetValueFromCookie(G_PS_COOKIE_ORDER,"subtotal");
	var shipping = psGetValueFromCookie(G_PS_COOKIE_ORDER,"shipping");

	var uP = new psProfile();
	uP.readProfile();
	
	var pIndexShop="prd_";
	for(var i=0; i < 300; i++){
		var keyIndex  = pIndexShop+i;
		var temp = psGetValueFromCookie(G_PS_COOKIE_SHOP9,keyIndex);		
		if (temp==null){break;}
		//Order in cookie: name	quantity	price	category
		var arrInfo = temp.toLowerCase().split("-_-");		
		psCreateShopAction9Tag(arrInfo[0], arrInfo[0],arrInfo[1], arrInfo[2], uP.cusId, orderNumber, subtotal, arrInfo[3]);		
	}
	psDisplayShop9s();
	psCreateOrderTag(orderNumber,subtotal, 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_SHOP9, "", "delete");
	psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
	psSetCookie(G_PS_COOKIE_ORDER, "", "delete");
	psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");

}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	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 pName=document.getElementById("nextProductName");
			this.name = (pName != null ? psTrim(psHtmlDecode(unescape(psGetInnerText(pName)))) : null);
			this.name = psCleanProductName(this.name);
			this.id = this.name;
			// handle view product from cart			
			var pClickArea = psGetCookie(G_PS_COOKIE_CLICKED_MENU);			
			if(pClickArea != null && pClickArea.toLowerCase() == "from_cart"){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
				if(this.catId == null || this.catId == "") this.catId = "All Gift Books";
			}else{			
				if(G_PS_URL_REFERRER == null){
					this.catId = "BOOKMARK";				
				}else{
					this.catId = psGetCookie(G_PS_COOKIE_CATID) != null? psGetCookie(G_PS_COOKIE_CATID):"Home Page";					
				}
				//psSetValueToCookie(G_PS_COOKIE_PROD_CATID, psTrim(this.id.toLowerCase()), 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!
			var temp = itemRow.innerHTML;
			temp = temp.replace(/<TD>\s*<\/TD>/gi,"");			
			var items = temp.split(/<\/TD>/i);
			if(items.length > 3){
				var basePrice_index = 2;
				if(psGetInnerText(items[items.length-1]).indexOf("$") < 0){
					// on FF
					basePrice_index = 3;
				}				
				this.price = psCleanPrice(psTrim(psGetInnerText(items[items.length-basePrice_index])));
				basePrice_index++;
				this.id = this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(items[items.length-basePrice_index])))));
				basePrice_index++;
				this.quantity = psTrim(psGetInnerText(items[items.length-basePrice_index]));
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null) this.catId = "All Gift Books";				
			} 
  		    return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the receipt page
	 */
	this.getItem9 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			/*
			 * this.id = <from itemRow>
			 * this.name = <from itemRow>
			 * this.price = <from itemRow>
			 * this.quantity = <from itemRow>
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			 * this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			 */
			 return true;
		}
		catch (ex) { return false; }
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
	this.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.cusId = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.cusId != null)
			{
				var buf = this.cusId.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				this.cusId = buf[0];
				if (!this.cusId)
					this.cusId = psGenerateRandomValue();
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		try
		{
			if (this.cusId == null)
				return;
			// make sure that the data contains 4 parts separated by 3 '|'
			var data = this.cusId + "|" + this.email + '|' + this.city + '|' + this.state + '|' 
				+ this.zipcode + "|" + this.newsletter + '|' + this.subscribe;
			// store on cookie
			psSetCookie(G_PS_COOKIE_PROFILE, data);
			//
			// NOTE: To persist profile as persistent cookie, pass G_PS_COOKIE_LIFETIME as the third param instead of null
			// psSetCookie(G_PS_COOKIE_PROFILE, data, G_PS_COOKIE_LIFETIME);
			//
			return true;
		}
		catch (ex) { return false; }
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			/*
			 * this.id = <from source code>
			 * this.subtotal = <from source code>
			 * this.shipping = <from source code>
			 */
			if (!this.id)
				this.id = psGenerateRandomValue();
			/*
			 * Extract user profile from source code
			 */
			var uP = new psProfile();
			uP.readProfile();  // Ensure to get the customer Id & email persisted at login stage
			/*
			 * uP.city = <from source code>
			 * uP.state = <from source code>
			 * uP.zipcode = <from source code>
			 * uP.newsletter = <from source code>
			 * uP.subscribe = <from source code>
			 */
			 if (!uP.cusId)
				uP.cusId = psGenerateRandomValue();
			return uP.writeProfile(); // Persist profile for later use at Receipt stage
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all unaccepted characters in categoryid, including
 * [, ', ", :, comma,]
 * RETURN: string
 */
function psCleanCatId(pCatId)
{
    return (pCatId != null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

function psCleanProductName(pProductName)
{
	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

/* PURPOSE: Remove all leading & trailing spaces of a string
 * Note: [&nbsp;] is also considered as a space
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;
	return (pStr != null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

/* PURPOSE: extract value from the URL
 * in format of http://xxx.com/page.ext?key1=value1&key2=value2
 * or key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
function psGetValueFromUrl(pUrl, pKey)
{
	pUrl = (pUrl != null) ? "?" + psTrim(pUrl.toLowerCase()) : null;
	pKey = (pKey != null) ? psTrim(pKey.toLowerCase()) : null;

	if (pUrl == null || pKey == null || pUrl.indexOf(pKey) == -1) 
		return null;
	
	var start = pUrl.indexOf('&' + pKey + '=');
	start = (start == -1) ? pUrl.indexOf('?' + pKey + '=') : start;
	if (start >= 0)
	{
		start = start + pKey.length;
		var end = pUrl.indexOf("&", start);
		if(end == -1) 
			end = pUrl.length;
		var middle = pUrl.indexOf("=", start);
		return pUrl.substring(middle + 1, end);
	}
	return null;
}

/* PURPOSE: returns the value of an element based on element_id
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 */
function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}

/* PURPOSE: returns the value of an element based on element object
 * Note: this function returns decoded text
 * to avoid "double" decode, don't invoke psHtmlDecode on returned value again
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 *  NULL: if element not exist
 */
function psGetElementValue(pTagObj, pValueFlag)
{
    var tagValue = null;
    if (pTagObj != null)
    {
        if (pTagObj.tagName.search(/^INPUT$/i) > -1)
            tagValue = pTagObj.value;
        else if (pTagObj.tagName.search(/^SELECT$/i) > -1)
        {
            if (pValueFlag == true)
                tagValue = pTagObj.options[pTagObj.selectedIndex].value;
            else
                tagValue = psHtmlDecode(pTagObj.options[pTagObj.selectedIndex].innerHTML);// return label instead of value
        }
        else
            tagValue = psHtmlDecode(pTagObj.innerHTML);
    }

    return tagValue;
}

/* PURPOSE: validate email format
 * RETURN: boolean
 */
function psCheckEmail(pEmail) 
{
    if (pEmail)
    {
        var i = pEmail.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
        return (i > -1);
    }

    return false;
}

/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
function psHtmlDecode(pValue)
{
    if (pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
    }

    return pValue;
}

/* PURPOSE: extract main domain from the URL
 * RETURN: main domain
 */
function psGetMainDomain(pUrl){
	var se = /^https*\:\/\/([^\/\:]+)/gi;
	var domain = (pUrl.search(se) > -1) ? RegExp.$1 : null;
	if(domain != null)
	{
		if(domain.indexOf("www")==0)
		{
			domain = domain.substring(4,domain.length);
		}
		if(G_PS_ARR_DOMAIN != null)
		{
			for(var i =0; i<G_PS_ARR_DOMAIN.length; i++)
			{
				se = new RegExp("[\.]" + G_PS_ARR_DOMAIN[i] + "$","gi");
				if(("." + domain).search(se) > -1)
				{
					domain = G_PS_ARR_DOMAIN[i];
					break;
				}
			}
		}
		domain = "." + domain;
	}
	return domain;
	
}

/* PURPOSE: extract domain part in the URL
 * RETURN: domain
 */
function psGetDomain(pUrl){
    var se = /^https*\:\/\/([^\/\:]+)/gi;
    return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}

/* PURPOSE: remove unnecessary characters (dollar sign, comma, quote, minus, etc) 
 * from price to make it work properly with parseFloat/parseInt
 * RETURN: well-formed price
 */
function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

/* PURPOSE: retrieve cookie value
 * RETURN: string
 */
function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if (!pCookieName || !cookies)
		return null;

	cookies = "; " + cookies.toLowerCase();
	var key = "; " + pCookieName.toLowerCase() + "=";
	var start = cookies.lastIndexOf(key);
	if (start >= 0)
	{
		start = start + key.length;
		var end = cookies.indexOf(";", start);
		if (end == -1)
			end = cookies.length;

		return unescape(cookies.substring(start, end));
	}

    return null;
}

function psCookieBase(pCookieName, pCookieValue, pLifeTime)
{
	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
	if(pLifeTime == "delete") 
	{         
		return true;
	}
	
	// set cookie by calling coremetrics's cookie function
	var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
	
	return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

function encodeHtml(strValue)
{
	if (strValue!=null)
	{
		strValue = escape(strValue);
		strValue = strValue.replace(/\//g,"%2F");
		strValue = strValue.replace(/\?/g,"%3F");
		strValue = strValue.replace(/=/g,"%3D");
		strValue = strValue.replace(/&/g,"%26");
		strValue = strValue.replace(/@/g,"%40");
	}
	return strValue;
}

/* PURPOSE: set cookie value
 * Note: if the designated cookie is too big, the old items will be removed
 * because cookie size is limited to 4K
 * @pLifeTime in seconds
 * pDomain: don't specify if using current domain
 * RETURN: boolean
 */
function psSetCookie(pCookieName, pCookieValue, pLifeTime)
{
	if (!pCookieName)
	{
		return false;
	}
	
	pCookieValue = (pCookieValue==null)? "null":pCookieValue;
	
	if(pLifeTime != "delete")
	{
		pCookieName = psTrim(pCookieName);
		var oldCookieValue = psGetCookie(pCookieName);
		oldCookieValue = (oldCookieValue==null)? "null":oldCookieValue;
		var totalSize;
		if(document.cookie.indexOf(pCookieName)>-1)
		{
			totalSize =  document.cookie.length + encodeHtml(pCookieValue).length - encodeHtml(oldCookieValue).length;
		}
		else
		{
			totalSize =  document.cookie.length  + encodeHtml(pCookieValue).length + encodeHtml(pCookieName).length;
		}
		if(totalSize > 3500)
		{
			return false;
		}
	}
	psCookieBase(pCookieName,pCookieValue,pLifeTime);
}

/* PURPOSE: set value in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 * NOTE: Use null or '' for pValue to remove the pair specified by pKey
 */
function psSetValueToCookie(pCookieName, pKey, pValue)
{
	if (!pCookieName || !pKey)
	{
		return false;
	}

	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;
	pValue = (pValue == null) ? "null" : pValue;
	var oldCatCookie = catCookie;
	
	var start = catCookie.indexOf(pKey);
	
	var totalsize;
	if (start >= 0) // Store before -> remove the old value
	{
		var oldValue = psGetValueFromCookie(pCookieName,pKey.replace(/[\~\#]/gi,""));
		oldValue = (oldValue == null) ? "null" : oldValue;
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1)
			end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length - encodeHtml(oldValue).length;
	}
	else
	{
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length;  
		if(document.cookie.indexOf(pCookieName)<0)
		{
			totalsize += encodeHtml(pCookieName).length;
		}
	}
	catCookie = pKey + pValue + catCookie;
	var cookieArray = null;   
	//Check existed ?
	while (totalsize > 3500)
	{
		var l1 = encodeHtml(catCookie).length;//length before pop
		cookieArray = catCookie.split("#");
		cookieArray.pop();
		catCookie = cookieArray.join("#");
		var l2 = encodeHtml(catCookie).length;//length after pop                                                        
		totalsize -=  (l1-l2);
	}   
	if(catCookie == null || catCookie == "")
	{
		catCookie = oldCatCookie;
	}
	// Save to cookie              
	psCookieBase(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

/* PURPOSE: get value stored in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 */
function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if (catCookie != null)
    {
        var start = catCookie.indexOf(pKey);
		if (start >=0 )
		{
			start = start + pKey.length;
			var end = catCookie.indexOf("#", start);
			if (end == -1)
				end = catCookie.length;
			return catCookie.substring(start, end);
		}
		return null;
    }
    return null;
}

/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dtDate = new Date();
	var cusRandom = (dtDate.getTime()%10000000) + (Math.floor(Math.random()*10000));
	return cusRandom;
}

function psShorttenPageID(pLink)
{
	var temp1 = pLink;
	if (temp1 != null)
	{
		temp1 = (temp1.length > 255) ? temp1.substr(0, 255) : temp1;
	}
	return temp1;
}

function psCheckArrayExist(pArrElement){
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0)
    {
        return false;
    }

    return true;
}
function psCheckElementExist(pElement){
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }

    return true;
}

function psGetElementsByClassName(psDocument, psElementTagName, psClassName){
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null)
    {
        return null;
    }
    for(var i = 0; i < arrInputs.length; i ++ )
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(pId);
	pId = psShorttenPageID(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + pId + ", " + pName + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(pId, pName, pCatId);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId);    
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
	pOrderTotal = psCleanPrice(pOrderTotal);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCusID + ", " + pOrderID + ", " + pOrderTotal + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId);
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip) 
{
	pOrderTotal = psCleanPrice(pOrderTotal);
	pOrderShipping = psCleanPrice(pOrderShipping);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + pId + ", " + pOrderTotal + ", " + pOrderShipping + ", " + pCusID + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip);
}

function psCreateConversionEventTag(pId, pActionType, pCatID, pPoints) 
{
	pCatID = psCleanCatId(pCatID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + pId + ", " + pActionType + ", " + pCatID + ", " + pPoints + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(pId, pActionType, pCatID, pPoints);
}

function psCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pNewsletter + ", " + pSubscribe + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe);
}

function psCreateErrorTag(pPageID, pCatId) 
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateErrorTag(" + pPageID + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateErrorTag(pPageID, pCatId);
}

function psDisplayShop5s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop5s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop5s();
}

function psDisplayShop9s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop9s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop9s();
}
/*===========================END GENERAL UTILITY FUNCTION ==================*/