/************************************************************************************/
/* $Revision: 110359 $
 * $Id: cmtaggingservices - 5986923 - 90223936 - 082808.txt 110359 2009-02-13 17:12:04Z rnaik $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v2.5, 2009/02/13
 * 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
if ( document.domain.indexOf('californiapsychics.com') >=0 ) {
    cmSetProduction();
} else {
    //no-op 
}
/*===========================GLOBAL VARIABLES ===============================*/
// current page url
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
// cookie name
var G_PS_COOKIE_CUR_CATID = "PS_CUR_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
var G_PS_PRD = "PS_PRD";		// used to persist product info
var G_PS_ITEM = "PS_ITEM";		// used to persist product info
var G_PS_ORDER = "PS_ORDER";		// used to persist product info
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;

// options for debug mode when sending tag:
// 1: only alert
// 2: only send tag
// 3: alert & send tag
var G_PS_DEBUG_MODE = 2;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Error page views
if (psGetInnerText(psGetFirstElementByClassName("articletitle")).search(/An error has occurred.../gi)>=0)
{
	psPostErrorView();
}
else if(G_PS_PATHNAME.toLowerCase() == "/search/search_results.aspx")
{
	psPostSearchView();
}
else if(G_PS_PATHNAME.toLowerCase() == "/psychics/allpsychics.aspx")
{
	psPostPsychicsSearchView();
}
// Product views
else if (psIsProductView())
{
	psPostProductView();
}
// Shop5 views
else if (G_PS_PATHNAME == "/ms/mbuyminutes.aspx")
{
	psHijackShoppingSubmit(); // Hijack to capture item (5 & 9) info
}
// Confirm step
else if (G_PS_PATHNAME == "/ms/mbuyminutessorry.aspx")
{
	G_PS_CUR_CATID = "CHECKOUT:MEMBER";	
	psCreatePageviewTag("BUY MINUTES SORRY", G_PS_CUR_CATID);
	// Clear cache from cookie
	psSetCookie(G_PS_PRD, "", "delete");
	psSetCookie(G_PS_ORDER, "", "delete");
}
// Confirm step
else if (G_PS_PATHNAME == "/ms/mbuyminutesconfirm.aspx")
{
	// Throw registration tag to confirm
	var uP = new psProfile();
	if (uP.readProfile()) // read from cookie
		psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipCode, uP.country);
	psPostCartView(); // Throw shop5 tags
	psHijackOrderSubmit(); // Hijack to capture order info
}
// Shop9 views
else if (G_PS_PATHNAME == "/ms/mbuyminutesreceipt.aspx")
{
	psPostOrderView();
	// Clear cache from cookie
	psSetCookie(G_PS_PRD, "", "delete");
	psSetCookie(G_PS_ORDER, "", "delete");
}
// Login pages
else if (G_PS_PATHNAME.search(/\/login.aspx/gi)>=0)
{
	G_PS_CUR_CATID = "MEMBER ACCOUNT";	
	psCreatePageviewTag("MEMBER LOGIN", G_PS_CUR_CATID);
	psHijackMemberLogin(); // Hijack login pages
}
// Search other page views
else
{
	psPostPageView();
}

//
// Persist status of entering search page
psPersistSearchStatus();
psThrowRegTag_MemberLogin(); // throw registration tag as member signs in
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
/*
 * Process to post error tag as user encounters error pages
 */
function psPostErrorView()
{
	G_PS_CUR_CATID = "HOME";
	// Throw error tag
	psCreateErrorTag("AN ERROR HAS OCCURRED", G_PS_CUR_CATID);
}

function psPostPsychicsSearchView()
{
	G_PS_CUR_CATID = "PSYCHICS SEARCH";
	var pageId = "SEARCH SUCCESSFUL";
	var sTerm = psGetElementValueById("ctl00_ctl00_cphCenter_cphCenter_msmPsychicList_ListHeader_TxtKeyword",false)
				+ ":" + psGetElementValueById("ctl00_ctl00_cphCenter_cphCenter_msmPsychicList_ListHeader_DdlFilter",false);
	var sResult = null;
	var divItem = document.getElementById("ctl00_ctl00_cphCenter_cphCenter_msmPsychicList_PnlNoMatch");
	if(psGetInnerText(divItem).toLowerCase().indexOf("no results found")>-1)
	{
		pageId = "SEARCH UNSUCCESSFUL";
		sResult = "0";
	}
	else
	{
		sResult = 0;
		var liList = document.getElementsByTagName("li");
		for (var i = 0; i < liList.length; i++)
		{
			var se = /ctl00_ctl00_cphCenter_cphCenter_msmPsychicList_RptPsychics_(ctl\d+)_ListItem/gi;
			if(liList[i].id.search(se)>-1)
			{
				sResult++;
			}
		}
		if(sResult.toString() == "0")
		{
			pageId = "ALLPSYCHICS";
			catId = "PSYCHICS SEARCH";
			sResult = null;
			sTerm = null;
		}
	}
	psCreatePageviewTag(pageId,G_PS_CUR_CATID,sTerm,sResult);
}

/*
 * Process to post page tags as user makes search
 */
function psPostSearchView()
{
	G_PS_CUR_CATID = "SEARCH";
	var pageId = "SEARCH SUCCESSFUL";
	var sTerm = psGetElementValueById("ctl00_ctl00_cphCenter_cphCenter_ucSearch_txtSearch",false);
	var sResult = null;
	var spanList = document.getElementsByTagName("span");
	for (var i = 0; i < spanList.length; i++)
	{
		if(psGetInnerText(spanList[i]).toLowerCase().indexOf("did not match any documents")>-1)
		{
			pageId = "SEARCH UNSUCCESSFUL";
			sResult = "0";
			break;
		}
	}
	if(sResult == null)
	{
		var divItem = document.getElementById("ctl00_ctl00_cphCenter_cphCenter_ucSearch_divGoogle");
		if (divItem != null && divItem != "undefined") {
		    var fontList = divItem.getElementsByTagName("font");
		    for (var i = 0; i < fontList.length; i++)
		    {
			    var se = /Results\s*\d*\s*\-\s*\d*\s*of\s*about\s*(\d*)\s*for\s*/gi;
			    if(psGetInnerText(fontList[i]).search(se)>-1)
			    {
				    sResult = RegExp.$1;
				    break;
			    }
		    }
		}
	}
	
	psCreatePageviewTag(pageId,G_PS_CUR_CATID,sTerm,sResult);
}
/*
 * Extract search result from source code: 
 */
function psGetSearchResult()
{
	var result = "0";

	if (document.body.innerHTML.search(/No pages were found containing/gi)>=0)
		result = "0";
	else
	{
		if (document.body != null && document.body.innerHTML.search(/of about <b>/gi)>=0)
		{
			result = document.body.innerHTML.toLowerCase().split("of about <b>")[1];
			result = result.substring(0, result.indexOf("<"));
		}
	}

	return result;
}

/*
 * Hijack to throw registration tag as user successfully logs in
 */
function psHijackMemberLogin()
{
	// Hijack email textbox
	var txtEmail = document.getElementById("ctl00_cphCenter_VipMemberLoginBox1_txtEmail");
	txtEmail = (txtEmail != null ? txtEmail : document.getElementById("ctl00_cphLeftSide_Viplogin1_txtEmail"));
	txtEmail = (txtEmail != null ? txtEmail : document.getElementById("ctl00_cphCenter_txtEmail"));
	if (txtEmail != null)
	{
		txtEmail.onkeypress = function()
		{
			if (event.keyCode == 13)
			{
				var uP = new psProfile();
				uP.writeMemberProfile();
			}
		}
	}
	// Hijack PIN textbox
	var txtPIN = document.getElementById("ctl00_cphCenter_VipMemberLoginBox1_txtPIN");
	txtPIN = (txtPIN != null ? txtPIN : document.getElementById("ctl00_cphLeftSide_Viplogin1_txtPIN"));
	txtPIN = (txtPIN != null ? txtPIN : document.getElementById("ctl00_cphCenter_txtPIN"));
	if (txtPIN != null)
	{
		txtPIN.onkeypress = function()
		{
			if (event.keyCode == 13)
			{
				var uP = new psProfile();
				uP.writeMemberProfile();
			}
		}
	}
	// Hijack LOGIN button
	var btnLogin = document.getElementById("ctl00_cphCenter_VipMemberLoginBox1_imgbLogin");
	btnLogin = (btnLogin != null ? btnLogin : document.getElementById("ctl00_cphLeftSide_Viplogin1_imgbLogin"));
	btnLogin = (btnLogin != null ? btnLogin : document.getElementById("ctl00_cphCenter_btnLogin"));
	if (btnLogin != null)
	{
		btnLogin.oldOnClick = btnLogin.onclick; // back up original onclick function
		btnLogin.onclick = function()
		{
			var uP = new psProfile();
			uP.writeMemberProfile();
			//
			// Invoke original function
			if (this.oldOnClick != null)
				return this.oldOnClick();
		}
	}	
}

/*
 * Throw registration tag
 */
function psThrowRegTag_MemberLogin()
{
	var flag = psGetCookie(G_PS_FLAG);
	if (flag != null)
	{
		if ((flag.toLowerCase() == "member-signin")
			&& (document.body != null && document.body.innerHTML.search(/Could not process login/gi)<0))
		{
			var uP = new psProfile();
			if (uP.readProfile())
				psCreateRegistrationTag(uP.email, uP.email); // Throw registration tag as user logins successfully
			psSetCookie(G_PS_FLAG, ""); // Clear flag
		}
	}
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	prd.getProduct();
	// Post product view tag
	psCreateProductviewTag(prd.id, prd.name, prd.catId);
	// Store productId along with catId to cookie for use later in shop5 and shop9 views
	psSetValueToCookie(G_PS_COOKIE_PROD_CATID, prd.id, prd.catId);
	// Hijack login form
	psHijackMemberLogin();
	// Hijack Add to cart button
	psHijackAddToCart();
}

/*
 * Hijack "AddToCart" button in order to persist product info to cookie for use later
 */
function psHijackAddToCart()
{
	var btnAddToCart = document.getElementById("ctl00_cphLeftSide_Navigation1_ctl05_btnAccount");
	if (btnAddToCart != null)
	{
		btnAddToCart.oldOnClick = btnAddToCart.onclick; // back up original function
		btnAddToCart.onclick = function()
		{
			var prd = new psProduct();
			prd.writeItem5_Member(); // Persist product info including prdId, prdName, and catId to cookie
			// Invoke original function
			if (this.oldOnClick != null)
				return this.oldOnClick();
		}
	}
}

/*
 * Hijack the "Buy now with credit card" button to persist item5 to cookie
 */
function psHijackShoppingSubmit()
{
	G_PS_CUR_CATID = "CHECKOUT:MEMBER";	
	// Throw page view tag
	psCreatePageviewTag("BUY MINUTES", G_PS_CUR_CATID);
	// Hijack submit button to throw shop5 tag
	var btnSubmit = document.getElementById("ctl00_cphCenter_ctl00_btnCreditCard");
	if (btnSubmit != null)
	{
		btnSubmit.oldOnClick = btnSubmit.onclick; // backup original function
		btnSubmit.onclick = function()
		{
			var prd = new psProduct();
			prd.writeItem(); // Persist item (item5 as well as item9) to cookie for use in the next 2 steps
			// Invoke original function
			if (this.oldOnClick != null)
				return this.oldOnClick();
		}
	}
}

/*
 * Process to throw shop5 tags as user purchase product
 */
function psPostCartView()
{
	G_PS_CUR_CATID = "CHECKOUT:MEMBER";	
	// Throw page view tag
	psCreatePageviewTag("BUY MINUTES CONFIRM", G_PS_CUR_CATID);
	// Get shop9 items from cookie
	var prd = new psProduct();

	if (prd.readItem(G_PS_ITEM)) // Read item5 from cookie
	{
		// Throw shop5 tag for PhoneCard item
		psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
		// Flush shop5 tags
		psDisplayShop5s();
	}
}

/*
 * Hijack the "Confirm" button to persist order info to cookie for use in the next step
 */
function psHijackOrderSubmit()
{
	G_PS_CUR_CATID = "CHECKOUT:MEMBER";	
	// Throw page view tag
	psCreatePageviewTag("BUY MINUTES CONFIRM", G_PS_CUR_CATID);
	// Hijack submit button to throw shop5 tag
	var frm = document.getElementById("aspnetForm");
	if (frm != null)
	{
		frm.oldSubmit = frm.submit; // backup original function
		frm.submit = function()
		{
			var ord = new psOrder();		
			ord.writeOrder(); // Capture order info to persist to cookie for use in the next step
			// Invoke original function
			if (this.oldSubmit != null)
				return this.oldSubmit();
		}
	}
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	G_PS_CUR_CATID = "CHECKOUT:MEMBER";	
	// Throw page view tag
	psCreatePageviewTag("BUY MINUTES RECEIPT", G_PS_CUR_CATID);
	// Get shop9 items from cookie
	var ord = new psOrder();
	var prd = new psProduct();

	if (ord.readOrder() && prd.readItem(G_PS_ITEM)) // inputs are enterred and we got them?
	{
		// Throw shop9 tag for PhoneCard item
		psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, ord.cusId, ord.id, ord.subtotal, prd.catId);
		var psychicPrd = new psProduct();
		// Throw shop9 tag for Pshychic item
		if (psychicPrd.readItem(G_PS_PRD)) // Read psychic product from cookie
			psCreateShopAction9Tag(psychicPrd.id, psychicPrd.name, prd.quantity, prd.price, ord.cusId, ord.id, ord.subtotal, psychicPrd.catId);
		// Flush shop9 tags
		psDisplayShop9s();
		// Post order tag finally
		psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, ord.cusId, 
			ord.city, ord.state, ord.zipCode);
	}
}

/*
 * Process to post page tags as user visit pages other than "transaction" pages
 */
function psPostPageView()
{
	var pageId = null;
	var pageType = null;
	G_PS_CUR_CATID = psGetCatId();

	// Horoscope pages
	pageType = document.getElementById("ctl00_cphBody_ucHoroContent_lblSignName");
	if (pageType != null)
	{
		pageId = psGetInnerText(pageType).toUpperCase();
		var submit = document.getElementById("ctl00_cphBody_ctl51_btnSubmit");
		submit = (submit == null ? document.getElementById("ctl00_cphBody_ctl38_btnSubmit") : submit);
		if (submit != null) // found newsletter sign-up
		{
			// Hijack Daily newsletter sign=up
			psHijackDailyNewsletterSignUp_v();
		}
	}
	else
	{
		// Article pages
		pageType = document.getElementById("ctl00_cphCenter_BreadCrumbs1_hlArticleTitle");
		if (pageType != null)
		{
			// For Red Responds pages, pageId is extracted from subtitle
			if (G_PS_PATHNAME.search(/\/Red_Responds.aspx/gi) >= 0)
				pageId = psGetInnerText(psGetFirstElementByClassName("articlesubtitle"));
			else
				pageId = psGetInnerText(pageType).toUpperCase();
			G_PS_CUR_CATID = G_PS_PATHNAME.replace("/articles/", "").toUpperCase();
			G_PS_CUR_CATID = G_PS_CUR_CATID.substring(0, G_PS_CUR_CATID.indexOf("/"));
		}
		// Member account links
		else if (G_PS_PATHNAME.search(/\/ms\//gi)>=0)
		{
			G_PS_CUR_CATID = "MEMBER ACCOUNT";
			if (G_PS_PATHNAME == "/ms/maccount.aspx")
				pageId = "YOUR ACCOUNT";
			else if (G_PS_PATHNAME == "/ms/mcallhistory.aspx")
				pageId = "CALL HISTORY";
			else if (G_PS_PATHNAME == "/ms/mpurchasehistory.aspx")
				pageId = "PURCHASE HISTORY";
			else if (G_PS_PATHNAME == "/ms/mrankings.aspx")
				pageId = "YOUR RANKINGS";
			else if (G_PS_PATHNAME == "/ms/mfavoritepsychics.aspx")
				pageId = "OTHER CUSTOMERS' FAVORITE PSYCHICS";
			else if (G_PS_PATHNAME == "/ms/mfeedback.aspx")
				pageId = "FEEDBACK FORM";
		}
		// Top menu links
		else if (G_PS_PATHNAME == "/" || G_PS_PATHNAME == "/index.aspx")
		{
			pageId = "HOME";
			G_PS_CUR_CATID = "HOME";
		}
		else if (G_PS_PATHNAME == "/love/index.aspx")
		{
			pageId = document.title.substring(0, document.title.lastIndexOf(" - "));
			G_PS_CUR_CATID = "HOME";
		}
		else if (G_PS_PATHNAME == "/about/krfaq.aspx")
		{
			pageId = psGetPageId();
			G_PS_CUR_CATID = "FAQ";
		}
		else if (G_PS_PATHNAME == "/5free/v2/index.aspx" || G_PS_PATHNAME == "/5free/v1/index.aspx")
		{
			pageId = document.title.substring(0, document.title.lastIndexOf(" - "));
			G_PS_CUR_CATID = "HOME";
			// Hijack Daily newsletter sign=up
			psHijackDailyNewsletterSignUp_v();
		}
		// New customers
		else if (G_PS_PATHNAME == "/newcustomer/special_offer.aspx" || G_PS_PATHNAME == "/newcustomer2/special_offer.aspx") // step 1 of Checkout
		{			
			psHijackNewCustomerReg();// Hijack creating new customer account
			// Throw conversation even tag (begin)
			psCreateConversionEventTag("NEW CUSTOMER SIGN-UP", 1, "CHECKOUT:NEW MEMBER");
		}
		else if (G_PS_PATHNAME == "/newcustomer/confirm.aspx" || G_PS_PATHNAME == "/newcustomer2/confirm.aspx") // step 2.1 of Checkout
		{
			pageId = "PURCHASE CONFIRMATION";
			G_PS_CUR_CATID = "CHECKOUT:NEW MEMBER";
			// Throw conversation even tag (finish)
			psCreateConversionEventTag("NEW CUSTOMER SIGN-UP", 2, G_PS_CUR_CATID);
			// Throw tags as new customer successfully register service
			psThrowTags_NewCustomerSignUp();
		}
		else if (G_PS_PATHNAME == "/newcustomer/sorry.aspx" || G_PS_PATHNAME == "/newcustomer2/sorry.aspx") // step 2.2 of Checkout
		{
			var error = psGetValueFromUrl(G_PS_QUERYSTRING, "error");
			error = (error != null ? error.toUpperCase() : "");
			if (error != "APPOINTMENTTIMEOUT")
				pageId = "ERROR: " + error.toUpperCase();
			else
				pageId = "APPOINTMENT TIMEOUT"
			G_PS_CUR_CATID = "CHECKOUT:NEW MEMBER";
			// Clear cache cookie
			psSetCookie(G_PS_PRD, "", "delete");
			psSetCookie(G_PS_FLAG, ""); // Clear flag in cookie
		}
		//
		else if (G_PS_PATHNAME == "/horoscope/horoscopeyourway.aspx")
		{
			pageId = "YOUR HOROSCOPE: SIX WAYS!";
			G_PS_CUR_CATID = "HOROSCOPE";
			// Hijack Daily newsletter sign-up
			psHijackDailyNewsletterSignUp_v1();
			window.setInterval("psHijackDailyNewsletterSignUp_v1()", 5000);
		}
		else if ((G_PS_PATHNAME == "/horoscope/index.aspx") || (G_PS_PATHNAME == "/horoscope/index_new.aspx"))
		{
			pageId = psGetPageId();
			G_PS_CUR_CATID = "HOROSCOPE";
			// Hijack Daily newsletter sign-up
			psHijackDailyNewsletterSignUp_v();
		}		
		else if (G_PS_PATHNAME.search(/\/KarmaRewards\/KarmaRewardsConfirmation.aspx/gi) >= 0)
		{
			pageId = psGetPageId();
			// Hijack Karma sign-up
			psHijackKarmaSignUp();
		}
		else if (G_PS_PATHNAME == "/appointment/search.aspx")
			pageId = "MAKE AN APPOINTMENT";
		else
			pageId = psGetPageId();
	}
	// Throw page tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID);
}

/*
 * Hijack daily newsletter sign up to throw registration
 * http://www.californiapsychics.com/horoscope/index.aspx
 * http://www.californiapsychics.com/horoscope/index_new.aspx
 * http://www.californiapsychics.com/5free/v1/index.aspx
 * http://www.californiapsychics.com/5free/v2/index.aspx
 * http://www.californiapsychics.com/horoscope/aries+Horoscope/daily/today.aspx
 */
function psHijackDailyNewsletterSignUp_v()
{
	var btnSubmit = document.getElementById("ctl00_cphBody_ctl00_btnSubmit");
	btnSubmit = (btnSubmit == null ? document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_btnStep2") : btnSubmit);
	btnSubmit = (btnSubmit == null ? document.getElementById("ctl00_cphMain_LandingPage1_btnStep2") : btnSubmit);
	btnSubmit = (btnSubmit == null ? document.getElementById("ctl00_cphCenter_HoroscopeSignupForm1_btnSubmit") : btnSubmit);
	btnSubmit = (btnSubmit == null ? document.getElementById("ctl00_cphBody_ctl51_btnSubmit") : btnSubmit);
	btnSubmit = (btnSubmit == null ? document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_btnSubmit") : btnSubmit);	
	btnSubmit = (btnSubmit == null ? document.getElementById("ctl00_cphBody_ctl38_btnSubmit") : btnSubmit);
	if (btnSubmit != null)
	{
		// Hijack onmouseup event
		btnSubmit.oldOnClick = btnSubmit.onclick; //back up pointer
		btnSubmit.onclick = function()
		{
			var newsLetterName = "Daily Newsletter";
			if ((G_PS_PATHNAME == "/horoscope/index.aspx") || (G_PS_PATHNAME.search(/\/daily\/today.aspx/gi) >=0))
				newsLetterName = "Free Horoscope Newsletter";

			var email = document.getElementById("ctl00_cphBody_ctl00_txtEmail");
			email = (email == null ? document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_txtEmail") : email);
			email = (email == null ? document.getElementById("ctl00_cphMain_LandingPage1_txtEmail") : email);
			email = (email == null ? document.getElementById("ctl00_cphCenter_HoroscopeSignupForm1_txtEmail") : email);
			email = (email == null ? document.getElementById("ctl00_cphBody_ctl51_txtEmail") : email);
			email = (email == null ? document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_txtEmail") : email);
			email = (email == null ? document.getElementById("ctl00_cphBody_ctl38_txtEmail") : email);
			email = (email != null ? email.value : null);
			var subscribe = document.getElementById("ctl00_cphBody_ctl00_chkEmail");
			subscribe = (subscribe == null ? document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_cbHoroscope") : subscribe);
			subscribe = (subscribe == null ? document.getElementById("ctl00_cphMain_LandingPage1_cbHoroscope") : subscribe);
			subscribe = (subscribe == null ? document.getElementById("ctl00_cphCenter_HoroscopeSignupForm1_chkEmailings") : subscribe);
			subscribe = (subscribe == null ? document.getElementById("ctl00_cphBody_ctl51_chkEmail") : subscribe);
			subscribe = (subscribe == null ? document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_chkEmailings") : subscribe);
			subscribe = (subscribe == null ? document.getElementById("ctl00_cphBody_ctl38_chkEmail") : subscribe);
			subscribe = (subscribe != null ? subscribe.checked : "N");
			subscribe = (subscribe == true ? "Y" : "N");
			if (psIsValidSignUp_v())
			{
				// Throw registration tag
				psCreateRegistrationTag(email, email, null, null, null, null, newsLetterName, subscribe);
				// Throw conversion tag
				psCreateConversionEventTag(psGetPageId() + ":Email Signup", "2", "Newsletter Signup", "10");
			}
			// Invoke original function
			if (this.oldOnClick != null)
				return this.oldOnClick();
		}
	}
}

/*
 * Check if valid sign up information enterred
 */
function psIsValidSignUp_v()
{
	var firstName = document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_txtName");
	firstName = (firstName == null ? document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_txtFirstName") : firstName);
	firstName = (firstName == null ? document.getElementById("ctl00_cphMain_LandingPage1_txtFirstName") : firstName);
	firstName = (firstName == null ? document.getElementById("ctl00_cphBody_ctl00_txtFName") : firstName);
	firstName = (firstName == null ? document.getElementById("ctl00_cphBody_ctl38_txtFName") : firstName);	
	
	if (firstName != null && psTrim(firstName.value) != "")
	{
		var email = document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_txtEmail");
		email = (email == null ? document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_txtEmail") : email);
		email = (email == null ? document.getElementById("ctl00_cphMain_LandingPage1_txtEmail") : email);
		email = (email == null ? document.getElementById("ctl00_cphBody_ctl00_txtEmail") : email);
		email = (email == null ? document.getElementById("ctl00_cphBody_ctl38_txtEmail") : email);
		email = (email != null ? email.value.toLowerCase() : "");
		var emailConfirm = document.getElementById("ctl00_cphBody_ctl00_txtEmailConfirm");
		emailConfirm = (emailConfirm == null ? document.getElementById("ctl00_cphBody_ctl38_txtEmailConfirm") : emailConfirm);
		emailConfirm = (emailConfirm != null ? emailConfirm.value.toLowerCase() : "");
		if (G_PS_PATHNAME == "/horoscope/index_new.aspx" || G_PS_PATHNAME.search(/\/daily\/today.aspx/gi)>=0)
		{
			if (!psCheckEmail(email) || !psCheckEmail(emailConfirm) || (email != emailConfirm))
				return false;
		}
		if (psCheckEmail(email))
		{
			var month = document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_ddMonth");
			month = (month == null ? document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_ddMonth") : month);
			month = (month == null ? document.getElementById("ctl00_cphMain_LandingPage1_ddMonth") : month);
			month = (month == null ? document.getElementById("ctl00_cphBody_ctl00_ddlBDateM") : month);			
			month = (month == null ? document.getElementById("ctl00_cphBody_ctl38_ddlBDateM") : month);			
			month = (month != null ? month.options[month.selectedIndex].innerHTML : null);
			if (month != null && month.toLowerCase() != "month")
			{
				var day = document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_ddDay");
				day = (day == null ? document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_ddDay") : day);
				day = (day == null ? document.getElementById("ctl00_cphMain_LandingPage1_ddDay") : day);
				day = (day == null ? document.getElementById("ctl00_cphBody_ctl00_ddlBDateD") : day);
				day = (day == null ? document.getElementById("ctl00_cphBody_ctl38_ddlBDateD") : day);
				day = (day != null ? day.options[day.selectedIndex].innerHTML : null);
				if (day != null && day.toLowerCase() != "day")
				{
					if (G_PS_PATHNAME == "/5free/v1/index.aspx" || G_PS_PATHNAME == "/5free/v2/index.aspx"
						|| G_PS_PATHNAME == "/horoscope/index.aspx" || G_PS_PATHNAME == "/horoscope/index_new.aspx" 
						|| G_PS_PATHNAME.search(/\/daily\/today.aspx/gi)>=0)
					{
						var year = document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_ddYear");
						year = (year == null ? document.getElementById("ctl00_ctl00_cphCenter_cphCenter_HoroscopeSignupForm1_ddYear") : year);						
						year = (year == null ? document.getElementById("ctl00_cphMain_LandingPage1_ddYear") : year);						
						year = (year == null ? document.getElementById("ctl00_cphBody_ctl00_ddlBDateY") : year);						
						year = (year == null ? document.getElementById("ctl00_cphBody_ctl38_ddlBDateY") : year);						
						year = (year != null ? year.options[year.selectedIndex].innerHTML : null);
						if (year != null && year.toLowerCase() != "year")
						{
							if (G_PS_PATHNAME == "/5free/v1/index.aspx")
							{
								var extraText = document.getElementById("ctl00_ContentPlaceHolder1_LandingPage1_txtQuestion");
								if (extraText != null && psTrim(extraText.value) != "")
									return true;
							}
							else if (G_PS_PATHNAME == "/5free/v2/index.aspx")
							{
								var extraText = document.getElementById("ctl00_cphMain_LandingPage1_txtQuestion");
								if (extraText != null && psTrim(extraText.value) != "")
									return true;
							}
							else if (G_PS_PATHNAME == "/horoscope/index_new.aspx")
							{
								var subscribe = document.getElementById("ctl00_cphBody_ctl00_chkEmail");
								subscribe = (subscribe == null ? document.getElementById("ctl00_cphBody_ctl38_chkEmail") : subscribe);
								subscribe = (subscribe != null ? subscribe.checked : false);
								return subscribe;
							}
							else if (G_PS_PATHNAME.search(/\/daily\/today.aspx/gi)>=0)
							{
								var subscribe = document.getElementById("ctl00_cphBody_ctl38_chkEmail");
								subscribe = (subscribe != null ? subscribe.checked : false);
								return subscribe;
							}
							else
								return true;
						}
					}
					else
						return true;
				}
			}
		}
	}
	return false;
}

/*
 * Hijack Karma sign up to throw registration
 * http://www.californiapsychics.com/KarmaRewards/KarmaRewardsConfirmation.aspx
 */
function psHijackKarmaSignUp()
{
	var frm = document.getElementById("aspnetForm");
	if (frm != null)
	{
		// Hijack onmouseup event
		frm.oldSubmit = frm.submit; //back up pointer
		frm.onsubmit = function()
		{
			var result = this.oldSubmit(); // Invoke original function
			if (result) // Only throw registration tag as the user successfully register
			{
				var email = document.getElementById("ctl00_cphCenter_KRsignup_txtEmail");
				email = (email != null ? email.value : null);
				// Throw registration tag
				psCreateRegistrationTag(email, email);
				// Throw conversion tag
				psCreateConversionEventTag(psGetPageId() + ":Rewards Signup", "2", "Karma Rewards Signup", "10");
			}
			return result;
		}
	}
}

/*
 * Hijack daily newsletter sign up to throw registration
 * http://www.californiapsychics.com/horoscope/horoscopeyourway.aspx
 */
function psHijackDailyNewsletterSignUp_v1()
{
	var btnSubmit = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_btnStep2");
	if (btnSubmit != null)
	{
		// Hijack onclick event
		if (btnSubmit.onclick.toString().search(/psIsValidSignUp_v1/gi)<0)
		{
			btnSubmit.oldOnClick = btnSubmit.onclick; //back up pointer
			btnSubmit.onclick = function()
			{
				if (psIsValidSignUp_v1())
					psThrowRegTag_DailyNewsletter_v1();
				if (this.oldOnClick != null)
					return this.oldOnClick();
			}
			// Hijack onkeypress event
			btnSubmit.onkeypress = function()
			{
				if (event.keyCode == 13)
				{
					if (psIsValidSignUp_v1())
						psThrowRegTag_DailyNewsletter_v1();
				}
			}
		}
	}
}

/*
 * Check to see if registration input is valid or not
 */
function psIsValidSignUp_v1()
{
	var firstName = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_txtFirstName");
	if (firstName != null && psTrim(firstName.value) != "")
	{
		var email = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_txtEmail");
		email = (email != null ? email.value.toLowerCase() : "");
		var emailConfirm = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_txtConfirmEmail");
		emailConfirm = (emailConfirm != null ? emailConfirm.value.toLowerCase() : "");
		if (psCheckEmail(email) && psCheckEmail(emailConfirm) && (email == emailConfirm))
		{
			var month = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_ddMonth");
			month = (month != null ? month.options[month.selectedIndex].innerHTML : null);
			if (month != null && month.toLowerCase() != "month")
			{
				var day = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_ddDay");
				day = (day != null ? day.options[day.selectedIndex].innerHTML : null);
				if (day != null && day.toLowerCase() != "day")
				{
					var subscribe = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_chkEmailings");
					subscribe = (subscribe != null ? subscribe.checked : false);
					return subscribe;
				}
			}
		}
	}
	return false;
}

/*
 * Throw registration tag
 */
function psThrowRegTag_DailyNewsletter_v1()
{
	var newsLetterName = "Daily Newsletter";
	var email = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_txtEmail");
	email = (email != null ? email.value : null);
	var subscribe = document.getElementById("ctl00_cphCenter_SignupWithEmailConfirm1_chkEmailings");
	subscribe = (subscribe != null ? subscribe.checked : "N");
	subscribe = (subscribe == true ? "Y" : "N");
	// Throw registration tag
	psCreateRegistrationTag(email, email, null, null, null, null, newsLetterName, subscribe);
	// Throw conversion tag
	psCreateConversionEventTag(psGetPageId() + ":Email Signup", "2", "Newsletter Signup", "10");
}

/*
 * Hijack new customer registration form to throw registration tag & shop5 tag
 * as user submits successfully
 */
function psHijackNewCustomerReg()
{
	// Throw page view tag
	var txtFirstName = document.getElementById("ctl00_cphMain_txtFirstName");
	if (txtFirstName == null) // DEBUG ONLY
		return;

	var pageId = (txtFirstName.disabled ? "NEWCUSTOMER:SHOPPING CART" : "CREATE AN ACCOUNT");
	G_PS_CUR_CATID = (txtFirstName.disabled ? "CHECKOUT:NEW MEMBER" : "MEMBER ACCOUNT");
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID);
	//
	// Hijack submit button
	if (txtFirstName.disabled) // last step?
	{
		var frm = document.getElementById("aspnetForm");
		if (frm != null)
		{
			frm.oldSubmit = frm.submit; // backup original submit function
			frm.submit = function()
			{
				// Get user profile
				var uP = new psProfile();
				uP.writeNewCustomerProfile();
				// Get product info from source code
				var prd = new psProduct();
				prd.writeItem5_NewCustomer();
				// Flag cookie to throw tags in the next step
				psSetCookie(G_PS_FLAG, "new customer sign-up");
				//
				// Invoke original function
				if (this.oldSubmit != null)
					return this.oldSubmit();
			}
		}
	}
	else
	{
		var subscribe = document.getElementById("ctl00_cphMain_chkEmailings");
		psSetCookie(G_PS_FLAG, (subscribe.checked ? "Y" : "N"));// Save status
	}
}

/*
 * Throw registration tag as new user successfully registers service
 */
function psThrowTags_NewCustomerSignUp()
{
	if (psGetCookie(G_PS_FLAG) == "new customer sign-up")
	{
		// Throw registration tag as new customer sign up successfully
		var uP = new psProfile();
		if (uP.readProfile()) // read from cookie
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipCode, uP.country, uP.newsletter, uP.subscribe);
		var prd = new psProduct();
		if (prd.readItem(G_PS_PRD)) // read product info from cookie
		{
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);		
			psDisplayShop5s(); // Flush shop5 tags
		}
		// Clear cache cookie
		psSetCookie(G_PS_PRD, "", "delete");
		psSetCookie(G_PS_FLAG, ""); // Clear flag in cookie
	}
}

/*
 * Throw shop5 tag as new user successfully registers service
 */
function psThrowShop5Tag_NewCustomer()
{
	var prd = new psProduct();
	if (prd.writeItem5_NewCustomer()) // inputs are enterred and we got them?
	{
		// Throw shop5 tag
		psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
		// Flush shop5 tags
		psDisplayShop5s();
	}
}

/*
 * Determine whether the current page is search page or not
 */
//function psIsSearchView()
//{
//	var sTerm = document.getElementById("ctl00_cphCenter_ctl00_txtSearch");	
//	sTerm = (sTerm == null ? document.getElementById("ctl00_cphCenter_Search_new1_txtSearch") : sTerm);
//	
//	return (sTerm != null);
//}

/*
 * Determine whether the current page is product page or not
 */
function psIsProductView()
{
	var se = /^\?extid\=\d+$/gi;
	var se_1 = /^\/psychics\/\d+\/\w+.aspx/gi;
	if((G_PS_PATHNAME.toLowerCase()=="/psychics/psychicpage.aspx" && G_PS_QUERYSTRING.search(se)>-1)
		|| (G_PS_PATHNAME.search(se_1)>-1))
	{
		return true;
	}
	return false;
}

/*
 * Manage cookie flag in order to get catId for product correctly
 */
function psPersistSearchStatus()
{
	if(G_PS_PATHNAME.toLowerCase() == "/search/search_results.aspx"
		|| G_PS_PATHNAME.toLowerCase() == "/psychics/allpsychics.aspx") // search view? -> Mark as a search made
	{
		psSetCookie(G_PS_FLAG, "SEARCH");
		psSetCookie(G_PS_COOKIE_CUR_CATID, G_PS_CUR_CATID); // Persist search catId
	}
}

/*
 * Extract pageId from source code following the rule:
 * - Inner text of <class="overviewSignName">
 * - Inner text of <class="articletitle">
 * - Or else html page name will be the page Id
 */
function psGetPageId()
{
	var pageId = null;
	var spans = null;
		
	if (document.body != null && document.body.innerHTML.search(/overviewSignName/gi)>=0) // overviewSignName rule?
		pageId = psGetInnerText(psGetFirstElementByClassName("overviewSignName"));
	else if (document.body != null && document.body.innerHTML.search(/articletitle/gi)>=0) // articletitle rule?
		pageId = psGetInnerText(psGetFirstElementByClassName("articletitle"));
	else
	{
		pageId = G_PS_PATHNAME.substr(G_PS_PATHNAME.lastIndexOf("/")+1).replace(".aspx", "").replace(".htm", "");
		pageId = pageId.replace(/_/g, " ");
	}
	if (pageId != null)
		pageId = pageId.toUpperCase();

	return pageId;
}

/*
 * Return the first element encountered by the class name
 */
function psGetFirstElementByClassName(pClassName)
{
	var allPageTags = document.getElementsByTagName("*");	
	for (var i = 0; i < allPageTags.length; i++)
	{
		if (allPageTags[i].className.toLowerCase() == pClassName.toLowerCase())
			return  allPageTags[i];
	}
	return null;
}

/*
 * Return general categoryId from URL
 */
function psGetCatId()
{
	var catId = G_PS_PATHNAME.substr(1);	
	catId = catId.substring(0, catId.indexOf("/")).toUpperCase();
	if (catId == null || catId == "")
		catId = "HOME";

	return catId;
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.id = document.getElementById("ctl00_cphCenter_PsychicView1_msmPsychicView_PSSummaryMain_LblName");
			if (this.id != null)
			{
				this.id = psGetInnerText(this.id);
				this.name = this.id;
			}
			//
			// catId would be:
			// - "PHYSICS" if user navigates to product detail page from other pages than search page
			// - "SEARCH" if user navigates to product detail page from search page
			if (psGetCookie(G_PS_FLAG) == "SEARCH")
			{
				this.catId = psGetCookie(G_PS_COOKIE_CUR_CATID);
				this.catId = (this.catId == null || this.catId == "" ? "SEARCH" : this.catId);
				psSetCookie(G_PS_FLAG, "");
			}
			else
			{
				// catId is the first subfolder found in the URL
				this.catId = G_PS_PATHNAME.substr(1);
				this.catId = this.catId.substring(0, this.catId.indexOf("/")).toUpperCase();	
			}
			return true;
		}
		catch (err) {return false;}
	}

	/*
	 * Extract to persist product info to cookie
	 */
	this.writeItem5_Member = function()
	{
		// Get product info
		this.getProduct();
		// Persist product info to cookie
		var data = this.id + "|" + this.name + "|1|0|" + this.catId;
		psSetCookie(G_PS_PRD, data);
	}

	/*
	 * Extract product info to persist to cookie
	 */
	this.writeItem5_NewCustomer = function()
	{
		try
		{
			var priceDiv = document.getElementById("ctl00_cphMain_pnlForm1Price");
			this.id = document.getElementById("ctl00_cphMain_rblPricePoints_0");
			if (this.id != null && this.id.checked)
			{
				this.id = "30:PHONECARD";
				this.price = priceDiv.getElementsByTagName("label")[0].innerHTML; // first label
				this.price = this.price.substr(this.price.indexOf("$")+1);
				this.price = this.price.substring(0, this.price.indexOf("<"));
			}
			else
			{
				this.id = document.getElementById("ctl00_cphMain_rblPricePoints_1");
				if (this.id != null && this.id.checked)
				{
					this.id = "20:PHONECARD";
					this.price = priceDiv.getElementsByTagName("label")[1].innerHTML; // second label
					this.price = this.price.substr(this.price.indexOf("$")+1);
					this.price = this.price.substring(0, this.price.indexOf("<"));
				}
				else
				{
					this.id = document.getElementById("ctl00_cphMain_rblPricePoints_2");
					if (this.id != null && this.id.checked)
					{
						this.id = "10:PHONECARD";
						this.price = priceDiv.getElementsByTagName("label")[2].innerHTML; // third label
						this.price = this.price.substr(this.price.indexOf("$")+1);
						this.price = this.price.substring(0, this.price.indexOf("<"));
					}
					else
						return false; // ERROR
				}
			}
			this.name = this.id;
			this.quantity = 1;
			this.catId = "PHONE CARD"; // hard coded
			// Persist product info to cookie for use in the next step
			var data = this.id + "|" + this.name + "|" + this.quantity + "|" + this.price + "|" + this.catId;
			psSetCookie(G_PS_PRD, data);

			return true;
		}
		catch (err) { return false; }
	}
	/*
	 * Read product info from cookie
	 */
	this.readItem = function(itemNameOnCookie)
	{
		try
		{
			this.id = psGetCookie(itemNameOnCookie);
			if (this.id != null)
			{
				var buf = this.id.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" || tempVal=="undefined") ? null : tempVal); 
				}
				this.id = buf[0];
				this.name = buf[1];
				this.quantity = buf[2];
				this.price = buf[3];
				this.catId = buf[4];

				return true;
			}
			return false;
		}
		catch (err) { return false; }
	}
	/*
	 * Extract product info to throw shop5 tag as member successfully chooses service
	 */
	this.writeItem = function()
	{
		var tables = document.getElementsByTagName("table");
		if (tables.length >= 5)
		{
			var selection = null;
			var rows = tables[4].rows;
			for (var i = 1; i < rows.length ; i++)
			{
				if (rows[i].innerHTML.indexOf("$")>=0 || rows[i].innerHTML.search(/minutes/gi)>=0)
				{
					selection = rows[i].cells[0].getElementsByTagName("input")[0]; // the only input
					if (selection.checked)
					{
						this.id = rows[i].cells[1].innerHTML.replace("$", "") + ":PHONECARD";
						this.name = this.id;
						this.price = this.id;
						this.quantity = 1;
						this.catId = "PHONE CARD";
						// Persist product info to cookie
						var data = this.id + "|" + this.name + "|" + this.quantity + "|" + 
							this.price + "|" + this.catId;
						psSetCookie(G_PS_ITEM, data);

						return true;
					}
				}
			}
			return false;
		}
		return false;
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
    this.email = null;
    this.city = null;
    this.state = null;
	this.country = null;
    this.zipCode = null;
	this.newsletter = null;
	this.subscribe = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.email = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.email != null)
			{
				var buf = this.email.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = ((tempVal=="null" || tempVal=="NULL"|| tempVal=="undefined") ? null : tempVal); 
				}
				this.email = buf[0];
				this.city = buf[1];
				this.state = buf[2];
				this.zipCode = buf[3];
				this.country = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];

				return true;
			}
			return false;
		}
		catch (err) { return false; }
	}
	/*
	 * Get new customer profile to persist to cookie
	 */
	this.writeNewCustomerProfile = function()
	{
		try
		{
			this.email = document.getElementById("ctl00_cphMain_txtEmail");
			this.email = (this.email == null ? "" : this.email.value);
			if (psTrim(this.email) == "")
				return false;

			this.city = document.getElementById("ctl00_cphMain_txtCity");
			this.city = (this.city == null ? "" : this.city.value);
			if (psTrim(this.city) == "")
				return false;

			this.state = document.getElementById("ctl00_cphMain_ddState");
			if (this.state != null)
				this.state = psHtmlDecode(this.state.options[this.state.selectedIndex].innerHTML);
			if (psTrim(this.state) == "")
				return false;

			this.country = document.getElementById("ctl00_cphMain_ddCountry");
			if (this.country != null)
				this.country = psHtmlDecode(this.country.options[this.country.selectedIndex].innerHTML);
			if (psTrim(this.country) == "")
				return false;

			this.zipCode = document.getElementById("ctl00_cphMain_txtZipCode");
			this.zipCode = (this.zipCode == null ? "" : this.zipCode.value);
			if (psTrim(this.zipCode) == "")
				return false;
			
			this.newsletter = "FREE HOROSCOPE NEWSLETTER";
			this.subscribe = psGetCookie(G_PS_FLAG); // get from cookie persisted in previous step
			// Persist to cookie
			var data = this.email + '|' + this.city + '|' + this.state + '|' + this.zipCode + 
				'|' + this.country + '|' + this.newsletter + '|' + this.subscribe;
			psSetCookie(G_PS_COOKIE_PROFILE, data);

			return true;
		}
		catch (err) { return false; }
	}
	/*
	 * Get new customer profile to persist to cookie
	 */
	this.writeMemberProfile = function()
	{
		this.email = document.getElementById("ctl00_cphCenter_VipMemberLoginBox1_txtEmail");
		this.email = (this.email != null ? this.email : document.getElementById("ctl00_cphLeftSide_Viplogin1_txtEmail"));
		this.email = (this.email != null ? this.email : document.getElementById("ctl00_cphCenter_txtEmail"));
		this.email = (this.email == null ? "" : this.email.value);
		if (psTrim(this.email) == "")
			return false;
		// Persist to cookie
		var data = this.email + '|' + this.city + '|' + this.state + '|' + this.zipCode + 
			'|' + this.country + '|' + this.newsletter + '|' + this.subscribe;
		psSetCookie(G_PS_COOKIE_PROFILE, data);
		// Flag
		psSetCookie(G_PS_FLAG, "member-signin");

		return true;
	}
}

/*
 * Order _object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	this.cusId = null;
	this.city = null;
	this.state = null;
	this.zipCode = null;
	/*
	 * get order info from source code to persist to cookie
	 */
	this.writeOrder = function()
	{
		try
		{
			//var dt = new Date();
			//this.id = (dt.getTime()%10000000) + (Math.floor(Math.random()*10000));
			this.subtotal = document.body.innerHTML.toUpperCase().split("YOUR PIN: <STRONG>")[1];
			this.subtotal = this.subtotal.substring(0, this.subtotal.indexOf("<")).replace("$", "");
			this.shipping = 0;
			// In most cases, cusId is retrieved from from cookie G_PS_COOKIE_PROFILE as follows:
			var uP = new psProfile();
			if (uP.readProfile())
			{
				this.cusId = uP.email;
				this.city = uP.city;
				this.state = uP.state;
				this.zipCode = uP.zipCode;
			}
			// Persist product info to cookie
			var data = this.id + "|" + this.subtotal + "|" + this.shipping;
			psSetCookie(G_PS_ORDER, data);

			return true;
		}
		catch (err) { return false; }
	}
	/*
	 * get order info from cookie
	 */
	this.readOrder = function()
	{
		try
		{
			// Persist product info to cookie
			var data = this.id + "|" + this.subtotal + "|" + this.shipping;
			var data = psGetCookie(G_PS_ORDER);
			if (data != null)
			{
				var buf = data.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" || tempVal=="undefined") ? null : tempVal); 
				}
				this.id = buf[0];
				// Use tid parameter as orderId
				this.id = psGetValueFromUrl(G_PS_QUERYSTRING, "tid");
				this.subtotal = buf[1];
				this.shipping = buf[2];
				// In most cases, cusId is retrieved from from cookie G_PS_COOKIE_PROFILE as follows:
				var uP = new psProfile();
				if (uP.readProfile())
				{
					this.cusId = uP.email;
					this.city = uP.city;
					this.state = uP.state;
					this.zipCode = uP.zipCode;
				}
				return true;
			}

			return false;
		}
		catch (err) { return false; }
	}
}

/* PURPOSE: Get inner text of a node or clean html tags of a particular string
 * RETURN: resultant string or null
 */
function psGetInnerText(node, ignorewhitespace)
{
	if (node == null)
		return "";

	var text = "";
	if (typeof(node) == "object")
	{
		if (node.hasChildNodes())
		{
			var children = node.childNodes;
			for(var i=0; i<children.length; i++)
			{
				if(children[i].nodeName == "#text")
				{
					if(ignorewhitespace)
					{
						if(!/^\s+$/.test(children[i].nodeValue))
							text = text.concat(children[i].nodeValue);
					}
					else
						text = text.concat(children[i].nodeValue);
				}
				else if(children[i].nodeName.search(/BR/i)>=0)
					text = text.concat("\n"); // a break line for a <br> tag
				else
					text = text.concat(psGetInnerText(children[i])); // recursively get text
			}
		}
		else
		{
			if(node.nodeName == "#text")
				text = text.concat(node.nodeValue);
			else if(node.nodeName.search(/BR/i)>=0)
				text = text.concat("\n"); // a break line for a <br> tag
		}
	}
	else
		text =  node.replace(/\<+.+?\>+/g, "");

	return text;
}

/* 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
 * Two ways to call: as a string's built-in method or as an independent function
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) == "undefined")
		return pStr;

	return pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '');
}

/* 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: extract value from the URL
 * RETURN: string value of the parameter
 */
function psGetValueFromUrl(pUrl, pKey)
{
    var re = new RegExp("[?&]" + pKey + "=([^&$]*)", "i");
    if (pUrl.search(re) == -1)
		return null;
    return unescape(RegExp.$1);
}

/* 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: retrieve cookie value
 * RETURN: string
 */
function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if (!pCookieName || !cookies)
		return null;

	cookies = "; " + cookies.toUpperCase();
	var key = "; " + pCookieName.toUpperCase() + "=";
	var start = cookies.lastIndexOf(key);
	if (start >= 0)
	{
		start = start + key.length;
		var end = cookies.indexOf(";", start);
		if (end == -1)
			end = cookies.length;

		return unescape(cookies.substring(start, end));
	}

    return null;
}

/* PURPOSE: set cookie value
 * Note: if the designated cookie is too big, the old items will be removed
 * because cookie size is limited to 4K
 * @pLifeTime in seconds
 * pDomain: don't specify if using current domain
 * RETURN: boolean
 */
function psSetCookie(pCookieName, pCookieValue, pLifeTime, pDomain)
{
    if (!pCookieName)
		return false;

	if(pLifeTime == "delete") 
    {         
        CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
        return true;
    }
    // set cookie by calling coremetrics's cookie function
    var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
    
    return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

/* PURPOSE: set value in cookie in format of:
 * 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 = psTrim(pKey);
	// 
	var catCookie = psGetCookie(pCookieName);
	if (catCookie == null)
		catCookie = '';

	if (catCookie.indexOf(pKey) >=0) // Store before -> remove the old value
	{
        var reg = new RegExp("#" + pKey + "~([^#]*)", "gi");
        catCookie = catCookie.replace(reg, "");
	}
	// 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);
}

/* PURPOSE: get value stored in cookie in format of:
 * RETURN: string
 */
function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = psTrim(pKey);
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if (catCookie != null)
    {
        var re = new RegExp("#" + pKey + "~([^#$]+)", "i");
		if (catCookie.search(re) == -1)
			return null;

        return RegExp.$1;
    }
    return null;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult, pAttributes) 
{
	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 + ", " + pAttributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult, pAttributes);
}

function psCreateProductviewTag(pId, pName, pCatId, pAttributes) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + pId + ", " + pName + ", " + pCatId + ", " + pAttributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(pId, pName, pCatId, pAttributes);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId, pAttributes) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCatId + ", " + pAttributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId, pAttributes);    
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId, pAttributes) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCusID + ", " + pOrderID + ", " + pOrderTotal + ", " + pCatId + ", " + pAttributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId, pAttributes);
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip, pAttributes) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + pId + ", " + pOrderTotal + ", " + pOrderShipping + ", " + pCusID + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pAttributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip, pAttributes);
}

function psCreateConversionEventTag(pId, pActionType, pCatID, pPoints, pAttributes) 
{
	pCatID = psCleanCatId(pCatID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + pId + ", " + pActionType + ", " + pCatID + ", " + pPoints + ", " + pAttributes + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(pId, pActionType, pCatID, pPoints, pAttributes);
}

function psCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pCountry, pNewsletter, pSubscribe) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pCountry + ", " + pNewsletter + ", " + pSubscribe + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pCountry, 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 ==================*/