/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v3.0, 2010/01/20
 * 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("cricketmag.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_PROFILE_TEMP = "PS_PROFILE_TEMP";
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_SEARCH = "PS_SEARCH";
var G_PS_COOKIE_BUY_FROM_CAT = "PS_BUY_FROM_CAT";

/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if(G_PS_URL_PATH.search(/cricketmag\.com/i) >= 0){	

//	if (psIsSearchView())
//	{
//		psPostSearchView();
//	}

	if (psIsProductView())
	{
		psPostProductView();
		psHijackAlsoSuggest();
	}
	else if (psIsCartView())
	{
		psPostCartView();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else if (psPostPageView() == false){
		if(G_PS_PATHNAME.search(/\/MyDashboard2*\.aspx/i) < 0){
			psCreatePageviewTag(G_PS_PATHNAME, "ADD URL");
		}
	}
//	psHijackSearchForm();
	psCheckLogin();
}

function psPostPageView(){	
	var pPageId = null;
	var pCatId = null;
    var pSea = null;
	var pResult = null;

	
	if(G_PS_PATHNAME.search(/\/GuestUser\.asp/i) >= 0){
		pCatId = "Cart";
		pPageId = "Billing Address";
		psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
		psHijackNewUserStep1(); // reuse the function
	}else if(G_PS_PATHNAME.search(/\/Checkout0\.asp/i) >= 0){
		pCatId = "Cart";
		pPageId = "Checkout - Shipping Details";
		var flagCookie = psGetCookie(G_PS_COOKIE_FLAG);
		if(flagCookie == "login_step1" || flagCookie == "login"){
			psPostRegistration();
		}
	}else if(G_PS_PATHNAME.search(/\/Checkout2\.asp/i) >= 0){
		pCatId = "Cart";
		pPageId = "Checkout - Payment Information";
	}else if(G_PS_PATHNAME.search(/\/Checkout3\.asp/i) >= 0){
		pCatId = "Cart";
		pPageId = "Checkout - Verification";
	}
	else if(G_PS_PATHNAME.search(/\/GetSource\.asp/i) >= 0){
		pCatId = "Cart";
		pPageId = "Promotion Code";
	}
	else if(G_PS_PATHNAME.search(/\/dspQuickorder\.asp/i) >= 0)
	{
		pPageId = pCatId = "Catalog Quick Order";	
		psHijackQuickOrder();
	}
	else if(G_PS_PATHNAME.search(/\/magazinehelp\.asp/i) >= 0){
		pPageId = "Magazine help";	
		pCatId = "Magazines";	
		
	}else if(G_PS_PATHNAME.search(/\/kids_home\.asp/i) >= 0){
		pPageId = pCatId = "For Kids";	
	}else if(G_PS_PATHNAME.search(/\/home\.asp/i) >= 0){
		pPageId = pCatId = "Home";	
	}else if(G_PS_PATHNAME == "/"){
		pPageId = pCatId = "Home";	
	}else if(G_PS_PATHNAME.search(/\/about_us\.asp/i) >= 0){
		pCatId = "Content";
		pPageId = "About Cricket";		
	}else if(G_PS_PATHNAME.search(/\/pages_content\.asp/i) >= 0){
		pCatId = "Content";
		var heading = psGetHeadingValue();
		var page_id = psGetValueFromUrl(G_PS_URL_PATH,"page_id");
		if(page_id != null){
			page_id = psTrim(psHtmlDecode(unescape(page_id)));
		}
		if(heading != null){			
			pPageId = heading;			
		}else {			
			var titleValue = document.title;			
			if(titleValue != null){
				if(titleValue.indexOf(";") >= 0){
					// http://www.cricketmag.com/pages_content.asp?page_id=990
					titleValue = titleValue.split(";")[0];
				}
				if(titleValue.indexOf(":") >= 0){
					// http://www.cricketmag.com/pages_content.asp?page_id=938
					// http://www.cricketmag.com/pages_content.asp?page_id=934
					// http://www.cricketmag.com/pages_content.asp?page_id=991
					titleValue = titleValue.split(":")[0];
				}
				pPageId = psTrim(titleValue);				
			}
		}
		if(page_id == "1"){
			pPageId = pCatId = "Home";
		}else if(page_id == "523"){
			pPageId = pCatId = "Sale";
		}else if(page_id == "3"){			
			pPageId = "Cricket history";
		}else if(page_id == "1136"){			
			pPageId = "Win Subscription";
		}else if(page_id == "1138"){			
			pPageId = "Official rules";
		}else if(page_id == "5"){			
			pPageId = "Cricket Employment Opportunities";
		}else if(page_id == "6"){			
			pPageId = "Submission Guidelines";
		}else if(page_id == "124"){			
			pPageId = "Links from other great sites";
		}else if(page_id == "11"){			
			pPageId = "Site Map";
		}else if(page_id == "1214"){			
			pPageId = "Cricket Magazine Short Story Wins Coveted Reading Award";
		}else if(page_id == "1215"){			
			pPageId = "Dr. Paul A. Witty";
		}else if(page_id == "983"){			
			pCatId = pPageId;
		}else if(page_id == "1096"){			
			pPageId = "Top picks from Customers";
		}else if(page_id == "1067"){
			pCatId = pPageId = "Christmas";			
		}else if(page_id == "534"){
			pPageId = "Online Interactive Samples";
		}else if(page_id == "1224"){
			pPageId = "Our Best-Selling Animal Gifts for Kids";
		}else if(page_id == "1220"){
			pPageId = "Magazines for Preschoolers";
		}else if(page_id == "935"){
			pPageId = "Test Questions";
		}else if(page_id == "980"){
			pPageId = "Magazines hold treasures for kids";
		}else if(page_id == "1137"){
			pPageId = "Thank you for signing up";
		}
		
	}else if(G_PS_PATHNAME.search(/\/faq_(category_)*display\.asp/i) >= 0){		
		pCatId = "FAQ";
		pPageId = psGetHeadingValue();





// Enhanced: 4/27/10 - Dave Howard

	}else if(G_PS_PATHNAME.search(/\/ProductList\.asp/i) >= 0){

        // Set defaults
		pPageId = psGetHeadingValue();
		pCatId = "SEARCH";
		pSea = null;
		pResult = null;

        // Get type (BOOKS, MAGAZINES, etc.)
		var pType = psGetValueFromUrl(G_PS_URL_PATH,"type");
		if(pType != null){
			pType = psTrim(psHtmlDecode(unescape(pType))).toUpperCase();
			if(pType == "M") pCatId = "MAGAZINES";
			if(pType == "B") pCatId = "BOOKS";
			if(pType == "P") pCatId = "CONTENT";
			if(pType == "A"){
				pCatId = "MEDIA/GIFTS";
				pPageId = "SHOP FOR CHILDRENS GIFT";
			}
		}

        // Get type (BOOKS, MAGAZINES, etc.)
		var pCat = psGetValueFromUrl(G_PS_URL_PATH,"cat");
		if(pCat != null){
			pCat = psTrim(psHtmlDecode(unescape(pCat))).toUpperCase();
			pCatId = "ALL";
			if(pCat == "1") pCatId = "6MTHTO3YRS";
			if(pCat == "2") pCatId = "3TO6YRS";
			if(pCat == "3") pCatId = "6TO9YRS";
			if(pCat == "4") pCatId = "9TO14YRS";
			if(pCat == "5") pCatId = "TEENS";
			pPageId = "SHOP BY AGE CATEGORY";
		}

        // get search 
		pSea = psGetValueFromUrl(G_PS_URL_PATH,"sea");
		if(pSea != null){
			pPageId = "SEARCH SUCCESSFUL";
			pSea = psTrim(psHtmlDecode(unescape(pSea))).toUpperCase();
            pResult = "1";
			if(psCheckElementExist(coremetricsRESULTS))
				pResult = coremetricsRESULTS;
		}


	}else if(G_PS_PATHNAME.search(/\/contact_us\.asp/i) >= 0 || 
	         G_PS_PATHNAME.search(/\/sharepage\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/\/customer_service\.asp/i) >= 0
			 ){
		pPageId = pCatId = psGetHeadingValue();
	}else if(G_PS_PATHNAME.search(/\/customer_service_eCard\.asp/i) >= 0){
		pCatId = "Customer Service";
		pPageId = "Customer Service eCard";
	}else if(G_PS_PATHNAME.search(/\/customer_service_eCard_send\.asp/i) >= 0){
		pCatId = "Customer Service";
		pPageId = "Send eCard";
	}
	else if(G_PS_PATHNAME.search(/\/form\/index\.asp/i) >= 0){
		pCatId = "Customer Service";
		pPageId = psGetHeadingValue();
	}else if(G_PS_PATHNAME.search(/CustomerMessage\.asp/i) >= 0){
		pPageId = pCatId = "Customer Message";		
	}else if(G_PS_PATHNAME.search(/\/NewUser\.asp/i) >= 0){
		pCatId = "Login";
		pPageId = "New User Step 1";
		psHijackNewUserStep1();
		psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
	}else if(G_PS_PATHNAME.search(/\/NewUser2\.asp/i) >= 0){
		pCatId = "Login";
		pPageId = "New User Step 2";		
		psHijackLogin("aspnetForm","_ctl0_ContentPlaceHolder1_Login");
	}else if(G_PS_PATHNAME.search(/\/Login\.asp/i) >= 0){
		pCatId = pPageId = "Login";
		psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
		psHijackLogin("aspnetForm","_ctl0_ContentPlaceHolder1_LoginControl_UserName");
	}else if(G_PS_PATHNAME.search(/\/MyAccount\.asp/i) >= 0 ||
	         G_PS_PATHNAME.search(/\/EditAddress\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/\/AddAddress\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/\/ManageAddresses\.asp/i) >= 0 || 
	         G_PS_PATHNAME.search(/\/ManageSubscriptions\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/\/ManagePurchases\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/\/ManageOrder\.asp/i) >= 0 ||
			 G_PS_PATHNAME.search(/\/ManageShipping\.asp/i) >= 0){
		//pCatId = "My Account";
		pCatId = "Login";
		pPageId = psGetHeadingValue();
	}
	
	if(G_PS_PATHNAME.search(/\/EditAddress\.asp/i) >= 0){
		psHijackUpdateAccount();
	}
	
	if(G_PS_PATHNAME.search(/\/MyAccount\.asp/i) >= 0 && psGetCookie(G_PS_COOKIE_FLAG) == "login"){		
		psPostRegistration();
	}
	
	if( (G_PS_URL_REFERRER.search(/\/EditAddress\.asp/i) >= 0 || G_PS_URL_REFERRER.search(/\/ManageUser\.asp/i) >= 0) && G_PS_PATHNAME.search(/\/MyAccount\.asp/i) >= 0 && psGetCookie(G_PS_COOKIE_FLAG) == "update_account"){
		// Update registration to cookie
		var uP = new psProfile();
		uP.cusId = psGetCookie(G_PS_COOKIE_PROFILE_TEMP);
		if (uP.cusId != null)
		{
			var buf = uP.cusId.split('|');
			for (var i=0; i<buf.length; i++)
			{
				var tempVal = buf[i];				
				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 = buf[5];
			uP.subscribe = buf[6];
			if(uP.email != null || uP.cusId != null){
				uP.writeProfile();
				psPostRegistration();
			}
		}
		psSetCookie(G_PS_COOKIE_PROFILE_TEMP,"","delete");
	}	
	
	if(G_PS_PATHNAME.search(/\/ManageUser\.asp/i) >= 0 ){
		//pCatId = "My Account";
		pCatId = "Login";
		pPageId = "Manage User";		
		psHijackChangeLogin();
		psCheckError();
	}
	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, pSea, pResult);	

	if(pPageId.toUpperCase() != "SHIPPING TABLE"){		
		psSetCookie(G_PS_COOKIE_CATID,pCatId);	
	}
	
	if(pCatId != null){
		// Hijack on "Buy" button, Example url: http://www.cricketmag.com//ProductList.aspx?type=B
		psHijackBuyFromCategory(pCatId);
		/* Hijack on "Buy Now", Example url: 
		http://www.cricketmag.com//pages_content.asp?page_id=523
		http://www.cricketmag.com/pages_content.asp?page_id=1224&s=PIG
		*/
		if(G_PS_PATHNAME.search(/\/magazinehelp\.asp/i) >= 0){
			psHijackBuyNow("Best Sellers");
			psHijackViewProductBestSellers();
		}else{
			//psHijackBuyNow(pCatId);			
		}		
	}	
	return true;
}

function psHijackViewProductBestSellers(){
	var tables = document.getElementsByTagName("table");
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){
			var tb = tables[i];
			if(tb.rows[0] != null && psTrim(psGetInnerText(tb.rows[0])) == "Best Sellers"){
				var aTags = tb.getElementsByTagName("a");
				if(psCheckArrayExist(aTags)){
					for(var j=0; j<aTags.length; j++){
						var aTag = aTags[j];
						if(aTag.href != null && aTag.href.search(/ProductDetail\.asp/i) >= 0){
							aTag.OldFunction = aTag.onclick;
							aTag.onclick = function (){
								psSetCookie(G_PS_COOKIE_CATID,"Best Sellers");								
								if(this.OldFunction != null) return this.OldFunction();
							}
						}
					}
				}
			}
		}
	}
}

function psCheckLogin(){	
	if(G_PS_URL_REFERRER.search(/\/Login\.asp/i) >= 0){
		var dashboard2Frame = document.getElementById("dashboard2");
		if(psCheckElementExist(dashboard2Frame)){
			var logout = dashboard2Frame.contentWindow.document.getElementById("buttonLogout");
			if(psCheckElementExist(logout)){
				if(psGetCookie(G_PS_COOKIE_FLAG) == "login"){					
					psPostRegistration();
				}
			}				
		}
	}
}

function psHijackBuyNow(pCatId){	
	var buyNows = document.getElementsByTagName("input");	
	if(psCheckArrayExist(buyNows)){
		for(var j=0; j<buyNows.length; j++){					
			if(buyNows[j].value != null && psTrim(buyNows[j].value).search(/Buy.+Now/i) >= 0){
				var buyNow = buyNows[j];
				if(buyNow.onclick == null || buyNow.onclick.toString().indexOf("psHJBuyNow") < 0){					
					buyNow.pCatId = pCatId;
					buyNow.OldFunction = (buyNow._c_onclick != null) ?  buyNow._c_onclick: buyNow.onclick;
					buyNow.onclick = function psHJBuyNow(){	
						psSetCookie(G_PS_COOKIE_BUY_FROM_CAT,this.pCatId);
						if(this.OldFunction != null) 
							return this.OldFunction();
					}
				}						
			}
		}
	}
}


function psHijackUpdateAccount(){
	// Update button
	var updateBtn = document.getElementById("_ctl0_ContentPlaceHolder1_UpdateAddrBtn");
	if(psCheckElementExist(updateBtn)){
		updateBtn.OldFunction = updateBtn.onclick;
		updateBtn.onclick = function (){
			var uP = new psProfile();
			uP.readProfile();
			var email = document.getElementById("_ctl0_ContentPlaceHolder1_ShipAddrEditCtrl_Email");
			if(psCheckElementExist(email)){
				uP.email = psTrim(email.value);
				if(uP.cusId == null && uP.cusId == ""){
					uP.cusId = uP.email;
				}
			}
			var city = document.getElementById("_ctl0_ContentPlaceHolder1_ShipAddrEditCtrl_City");
			if(psCheckElementExist(city))
				uP.city = psTrim(city.value);
			
			var state = document.getElementById("_ctl0_ContentPlaceHolder1_ShipAddrEditCtrl_State");
			if(psCheckElementExist(state))
				uP.state = psTrim(state.options[state.selectedIndex].value);				
			
			var zipcode = document.getElementById("_ctl0_ContentPlaceHolder1_ShipAddrEditCtrl_Zip");
			if(psCheckElementExist(zipcode))
				uP.zipcode = psTrim(zipcode.value);
			if(uP.email != null && psCheckEmail(uP.email)){
				//uP.writeProfile();
				var data = uP.cusId + "|" + uP.email + '|' + uP.city + '|' + uP.state + '|' + uP.zipcode + "|" + uP.newsletter + '|' + uP.subscribe;
				psSetCookie(G_PS_COOKIE_PROFILE_TEMP, data);				
				psSetCookie(G_PS_COOKIE_FLAG,"update_account");
			}				
			if(this.OldFunction != null) 
				return this.OldFunction();
	
		}
	}
	
	// Cancel button
	var cancelBtn = document.getElementById("_ctl0_ContentPlaceHolder1_Cancel2Btn");
	if(psCheckElementExist(cancelBtn)){
		cancelBtn.OldFunction = cancelBtn.onclick;
		cancelBtn.onclick = function (){
			psSetCookie(G_PS_COOKIE_PROFILE_TEMP,"","delete");
			if(this.OldFunction != null) return this.OldFunction();
		}
	}
}

function psHijackNewUserStep1(){
	var frm = document.getElementById("aspnetForm");
	if(psCheckElementExist(frm)){
		if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJNewUser") < 0){			
			frm.OldFunction = frm.onsubmit;
			frm.onsubmit = function psHJNewUser(){
				var uP = new psProfile();
				var email = document.getElementById("_ctl0_ContentPlaceHolder1_AddressControl_Email");
				if(psCheckElementExist(email)){
					uP.email = psTrim(email.value);
					uP.cusId = uP.email;
				}
				var city = document.getElementById("_ctl0_ContentPlaceHolder1_AddressControl_City");
				if(psCheckElementExist(city))
					uP.city = psTrim(city.value);
				
				var state = document.getElementById("_ctl0_ContentPlaceHolder1_AddressControl_State");
				if(psCheckElementExist(state))
					uP.state = psTrim(state.options[state.selectedIndex].value);				
				
				var zipcode = document.getElementById("_ctl0_ContentPlaceHolder1_AddressControl_Zip");
				if(psCheckElementExist(zipcode))
					uP.zipcode = psTrim(zipcode.value);
				if(uP.email != null && psCheckEmail(uP.email)){
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"login_step1");
				}				
				if(this.OldFunction != null) 
					return this.OldFunction();
			}
		}
	}
}

function psHijackChangeLogin(){
	// Hijack on submit button
	var submitBtn = document.getElementById("_ctl0_ContentPlaceHolder1_SubmitButton");
	if(psCheckElementExist(submitBtn)){
		submitBtn.OldFunction = submitBtn.onclick;
		submitBtn.onclick = function (){
			psUpdateNewLogin();
			if(this.OldFunction != null) return this.OldFunction();
		}
	}
	// Hijack on key press
	var password2 = document.getElementById("_ctl0_ContentPlaceHolder1_Password2");
	if(psCheckElementExist(password2)){		
		password2.OldFunction = password2.onkeypress;
		password2.onkeypress = function (e){
			try
			{
				var key = window.event ? event.keyCode : e.keyCode;
				if(key == 13){
					psUpdateNewLogin();
					if(this.OldFunction != null) return this.OldFunction();	
				}
			}
			catch (ex) {}
		}		
	}	
}

function psUpdateNewLogin(){
	var loginName = document.getElementById("_ctl0_ContentPlaceHolder1_Login");
	if(psCheckElementExist(loginName)){
		var uP = new psProfile();
		uP.readProfile();
		uP.cusId = psTrim(loginName.value);		
		//uP.writeProfile();
		var data = uP.cusId + "|" + uP.email + '|' + uP.city + '|' + uP.state + '|' + uP.zipcode + "|" + uP.newsletter + '|' + uP.subscribe;
		psSetCookie(G_PS_COOKIE_PROFILE_TEMP, data);		
		//psSetCookie(G_PS_COOKIE_FLAG,"login");
		psSetCookie(G_PS_COOKIE_FLAG,"update_account");
	}	
}

function psCheckError(){
	var error = document.getElementById("_ctl0_ContentPlaceHolder1_ErrorMessage");
	if(psCheckElementExist(error) && psGetInnerText(error) != ""){		
		psSetCookie(G_PS_COOKIE_PROFILE_TEMP,"","delete");
	}
}

function psHijackLogin(formId,loginId){
	var loginForm = document.getElementById(formId);	
	if(psCheckElementExist(loginForm)){
		if(loginForm.onsubmit == null || loginForm.onsubmit.toString().indexOf("psHJLogin") < 0){			
			loginForm.pLoginId = loginId;
			loginForm.OldFunction = loginForm.onsubmit;
			loginForm.onsubmit = function psHJLogin(){
				var loginName = document.getElementById(this.pLoginId);
				if(psCheckElementExist(loginName)){
					var uP = new psProfile();
					uP.readProfile();
					uP.cusId = psTrim(loginName.value);					
					if(uP.cusId != null && uP.cusId != ""){
						uP.writeProfile();
						psSetCookie(G_PS_COOKIE_FLAG,"login");
					}
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psPostRegistration()
{
	var uP = new psProfile();
	uP.readProfile();
	if(uP.cusId != null || uP.email != null){
		psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
}

function psGetHeadingValue(){
	var tdHeads = psGetElementsByClassName(document,"td","heading");
	if(psCheckArrayExist(tdHeads) == false){
		tdHeads = psGetElementsByClassName(document,"p","heading");
	}
	if(psCheckArrayExist(tdHeads)){
		var headValue = psGetInnerText(tdHeads[0]);
		if(headValue != null){
			headValue = psTrim(psHtmlDecode(unescape(headValue)));
			if(headValue != "")				
				return headValue;
		}
	}
	var h3Tags = document.getElementsByTagName("h3");
	if(psCheckArrayExist(h3Tags)){
		var h3Value = psTrim(psHtmlDecode(unescape(psGetInnerText(h3Tags[0]))));
		if(h3Value != null)
			h3Value = h3Value.replace(/\:$/,"");
		return h3Value;
		
	}
	// http://www.cricketmag.com/pages_content.asp?page_id=1176
	var fonts = document.getElementsByTagName("font");
	if(psCheckArrayExist(fonts)){
		for(var i=0; i<fonts.length; i++){
			if(fonts[i].getAttribute("size") != null && psTrim(fonts[i].getAttribute("size")) == "5"){
				return psGetInnerText(fonts[i]);
			}
		}
	}
	return null;
}

function psHijackBuyFromCategory(pCat){
	var cartLines = psGetElementsByClassName(document,"tr","cartLines");
	if(psCheckArrayExist(cartLines)){
		for(var r=0; r<cartLines.length; r++){
			var prdId = null;
			var tables = cartLines[r].getElementsByTagName("table");
			if(psCheckArrayExist(tables)){
				var aTags = tables[0].getElementsByTagName("a");				
				if(psCheckArrayExist(aTags)){
					prdId = psTrim(psGetInnerText(aTags[aTags.length-1]));
				}
			}			
			var buys = psGetElementsByClassName(cartLines[r],"a","pageButton");
			if(psCheckArrayExist(buys) && prdId != null){
				for(var i=0; i<buys.length; i++){
					var buy = buys[i];
					if(psGetInnerText(buy) != null && psGetInnerText(buy).search(/buy/i) >= 0){
						if(buy.onclick == null || buy.onclick.toString().indexOf("psHJBuyFromCategory") < 0){
							buy.pCat = pCat;
							buy.prdId = prdId;
							buy.OldFunction = buy.onclick;
							buy.onclick = function psHJBuyFromCategory(){
								if(this.prdId != null && this.prdId.indexOf(",") >= 0){
									var prdIds = this.prdId.split(",");
									for(var j=0; j<prdIds.length; j++){
										psSetValueToCookie(G_PS_COOKIE_PROD_CATID, prdIds[j], this.pCat);
									}
								}
								psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.prdId, this.pCat);								
								if(this.OldFunction != null)
									return this.OldFunction();
							}
						}
					}
				}
			}			
		}
	}
}

function psHijackBuyFromProductView(pId,pCat){
	var inputTags = document.getElementsByTagName("input");
	if (psCheckArrayExist(inputTags)){
		for(var i=0; i<inputTags.length; i++){
			var inputTag = inputTags[i];
			if (psCheckElementExist(inputTag.src)){
				if ((inputTag.src != null && inputTag.src.toLowerCase().search(/addtobasket\.gif/gi) >= 0) || (inputTag.value != null && inputTag.value.search(/^Add\s+to\s+Cart$/i) >= 0) ){
					if(inputTag.onclick == null || inputTag.onclick.toString().indexOf("psHJBuyFromProductView") < 0){
						inputTag.pId = pId;
						inputTag.pCat = pCat;
						inputTag.OldFunction = inputTag.onclick; 
						inputTag.onclick = function psHJBuyFromProductView(){
							if(this.pId != null && this.pId.indexOf(",") >= 0){
								var prdIds = this.pId.split(",");
								for(var j=0; j<prdIds.length; j++){
									psSetValueToCookie(G_PS_COOKIE_PROD_CATID, prdIds[j], this.pCat);
								}
							}
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.pId, this.pCat);							
							if (this.OldFunction != null){return this.OldFunction();}
						}
					}
				}
			}
		}
	}	
}

/*
 * Modify: NhungDao-2009/12/30
*/
function psHijackQuickOrder()
{
	
		var inputTags = document.getElementsByTagName("input");
		if (psCheckArrayExist(inputTags))
		{
			for(var i=0; i<inputTags.length; i++)
			{
				var inputTag = inputTags[i];
				if (psCheckElementExist(inputTag.src))
				{
					if (inputTag.src.toLowerCase().search(/addtobasket\.gif/gi) >= 0)
					{	
						inputTag.OldFunction = inputTag.onclick; 
						inputTag.onclick = function()
						{							
							var pName = document.getElementsByName("text1");
							if(psCheckArrayExist(pName))
							{
								if(pName[0].value!=null && typeof(pName[0].value)!="undefined")
								{
									var proId = pName[0].value;
									psSetValueToCookie(G_PS_COOKIE_PROD_CATID, proId, "CATALOG QUICK ORDER");							
								}
							}
							if(psCheckElementExist(this.OldFunction)==true)
								return this.OldFunction();
						}
					}
				}
			}
		}
		
}

function psHijackAlsoSuggest(){
	var pf= document.getElementsByTagName("font");
	if (psCheckArrayExist(pf)==true){
		for(var i=0;i<pf.length;i++){
			var ptStr = psGetInnerText(pf[i]);
			if (ptStr.toLowerCase().indexOf("may we also suggest")>=0){
				var pNote = pf[i].parentNode.parentNode.parentNode.parentNode; // for tagName is TABLE
				if (pNote.tagName.toUpperCase()=="TABLE"){
					var atag = pNote.getElementsByTagName("a");
					if (psCheckArrayExist(atag)==true){
						for(var j=0;j<atag.length;j++){
							if(atag[j].onclick == null || atag[j].onclick.toString().indexOf("HijackAlsoSuggest") < 0){
								atag[j].OldFunc = atag[j].onclick; 
								atag[j].onclick = function HijackAlsoSuggest(){									
									psSetCookie(G_PS_COOKIE_CATID,"also suggest");
									if (this.OldFunc != null)
										return this.OldFunc();
								}
							}
						}
					}
					break;
				}
			}
		}
	}	
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	if(G_PS_PATHNAME.indexOf("/searchresult.asp") >= 0 || psIsSearchViewUnsuccessful() ) 
		return true;	
	return false;
}

function psIsSearchViewUnsuccessful(){
	if(G_PS_PATHNAME.indexOf("/pages_content.asp") >= 0){
		var phead = psGetElementsByClassName(document,"p","heading");
		if(psCheckArrayExist(phead)){
			if(psGetInnerText(phead[0]).search(/No\s+Search\s+Results\s+Page/i) >= 0) 
				return true;
		}
	}	
	return false;
}

function psHijackSearchForm(){
	// Hijack search form to get search term if search unsuccessful
	var sForms = document.getElementsByTagName("form");
	if(psCheckArrayExist(sForms)){
		for(var i=0; i<sForms.length; i++){
			var f = sForms[i];
			if(f.action != null && f.action.search(/searchresult\.asp/i) >= 0){
				if(f.onsubmit == null || f.onsubmit.toString().indexOf("HijackSearchForm") < 0){
					f.OldFunc = f.onsubmit; 
					f.onsubmit = function HijackSearchForm(){
						var sTags = document.getElementsByName("search");						
						if (psCheckArrayExist(sTags)){							
							psSetCookie(G_PS_COOKIE_SEARCH,psTrim(sTags[0].value));
						}
						if (this.OldFunc != null){return this.OldFunc();}
					}
				}
			}			
		}
	}
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	if (G_PS_PATHNAME.indexOf("/productdetail.asp")>=0)
		return true;
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_PATHNAME.search(/\/ViewCart\.asp/i) >= 0)
		return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_PATHNAME.search(/\/CheckoutConf\.asp/i) >= 0)
		return true;
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	G_PS_CUR_CATID = "SEARCH";
	var pageId = "SEARCH UNSUCCESSFUL";
	var sResult = "0";
	var sTerm = null;
	if(psIsSearchViewUnsuccessful() == false){
		pageId = "SEARCH SUCCESSFUL";
		sTerm = psGetSearchTerm();
		sResult = "1";
		psSetCookie(G_PS_COOKIE_CATID,G_PS_CUR_CATID);
	}else{
		sTerm = psGetCookie(G_PS_COOKIE_SEARCH);		
		psSetCookie(G_PS_COOKIE_CATID,"Best Sellers");
	}
	psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);	
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = psGetValueFromUrl(G_PS_URL_PATH,"search");
	if(term != null)
		return psTrim(psHtmlDecode(unescape(term)));
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	return result;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()){
		if(prd.id != null && prd.id.indexOf(",") >= 0){
			var prdIds = prd.id.split(",");
			for(var i=0; i<prdIds.length; i++){
				psCreateProductviewTag(prdIds[i], prd.name, prd.catId);
			}
		}else{
			psCreateProductviewTag(prd.id, prd.name, prd.catId);
		}
		psHijackBuyFromProductView(prd.id,prd.catId);
	}
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	G_PS_CUR_CATID = "CART";
	psCreatePageviewTag("SHOPPING CART", G_PS_CUR_CATID, null, null);

	var rows = psGetElementsByClassName(document,"tr","cartLines");
	if(psCheckArrayExist(rows) == false){
		return;
	}
	
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		if (prd.getItem5(rows[r])){
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);			
		}
	}
	// Make sure to have actual postings
	psDisplayShop5s();	
	psSetCookie(G_PS_COOKIE_BUY_FROM_CAT,"","delete");
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	G_PS_CUR_CATID = "CART";
	psCreatePageviewTag("Checkout - Confirmation", G_PS_CUR_CATID, null, null);	

	var rows = psGetElementsByClassName(document,"tr","cartLines");
	if(psCheckArrayExist(rows) == false){
		return;
	}
	var ord = new psOrder();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var r = 0; r < rows.length; r++) // item for each row
			{
				if(rows[r].cells.length < 5)
					continue;
				if (prd.getItem9(rows[r]))
					psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
			}
			// Make sure to have actual postings
			psDisplayShop9s();
			psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.cusId, uP.city, uP.state, uP.zipcode);
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
			psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");			
		}
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	this.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
		this.price = null;
		this.quantity = null;
	}
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var fTags = document.getElementsByTagName("font");
			if(psCheckArrayExist(fTags)){
				for(var i=0; i<fTags.length; i++){
					if(fTags[i].getAttribute("color") != null && fTags[i].getAttribute("color").search(/fd6d0d/i) >= 0 &&
					   fTags[i].getAttribute("size") != null && fTags[i].getAttribute("size").indexOf("3") >= 0){
						this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(fTags[i])))));
						break;
					   }
				}
			}			
			/*
			 * Modify: NhungDao-2009/12/30
			*/
			if(psCheckElementExist(coremetricsSKU))
				this.id = coremetricsSKU;
			if(G_PS_URL_REFERRER != null && G_PS_URL_REFERRER.indexOf("cricketmag.com") < 0){
				this.catId = "Bookmarks";
			}else if(G_PS_URL_REFERRER != null && G_PS_URL_REFERRER.indexOf("checkout0.asp") >= 0 && this.id != null && this.id != ""){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			}else if(G_PS_URL_REFERRER != null && G_PS_URL_REFERRER.indexOf("viewcart.asp") >= 0 && this.id != null && this.id != ""){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			}else{
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
			}

			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the shopping cart
	 */
	this.getItem5 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var aTags = itemRow.getElementsByTagName("a");
			if(psCheckArrayExist(aTags)){
				/*
				 * Modify: NhungDao-2009/12/30
				*/
				for(var i= aTags.length -1; i>-1; i--)
				{
					if(aTags[i].href != null && aTags[i].href.search(/ProductDetail\.asp/gi) >= 0)
					{
						this.id = psTrim(aTags[i].innerHTML);						
						break;
					}
				}
			}
			var bTags = itemRow.cells[1].getElementsByTagName("b");
			if(psCheckArrayExist(bTags)){			
				this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(bTags[0])))));
			}
			
			var qTags = itemRow.cells[2].getElementsByTagName("input");
			if(psCheckArrayExist(qTags)){
				for(var i=0; i<qTags.length; i++){
					if(qTags[i].name != null && qTags[i].name.search(/Qty/i) >= 0){
						this.quantity = psTrim(qTags[i].value);
						break;
					}
				}
			}
			this.price = psCleanPrice(psGetInnerText(itemRow.cells[3]));			
			if(this.id != null && this.id != ""){				
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);				
			}
			if(this.catId == null || this.catId == ""){				
				this.catId = psGetCookie(G_PS_COOKIE_BUY_FROM_CAT);
				if(this.catId == null || this.catId == ""){
					this.catId = psGetCookie(G_PS_COOKIE_CATID);					
				}				
				if(this.catId != null && this.catId != ""){
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.id,this.catId);
				}else{
					this.catId = "Unknown";
				}
			}
			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!
			 var temp = itemRow.cells[1].innerHTML;
			 var items = temp.split(/\<BR\s*\/*\>/i);
			 this.id = psTrim(psHtmlDecode(unescape(psGetInnerText(items[0]))));			 
			 
			 var bTags = itemRow.cells[1].getElementsByTagName("b");
			 if(psCheckArrayExist(bTags)){
				this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(bTags[0])))));				
			 }
			 this.quantity = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[3])));
			 this.price = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[4])));
			 
			 if(this.id != null && this.id != ""){
				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
		{
			var orderSpan = document.getElementById("_ctl0_ContentPlaceHolder1_OrderHdrId");
			if(psCheckElementExist(orderSpan)){
				this.id = psTrim(psHtmlDecode(unescape(psGetInnerText(orderSpan))));
			}			
			if (!this.id)
				this.id = psGenerateRandomValue();
			
			var sumRows = psGetElementsByClassName(document,"tr","cartSummary");
			if(psCheckArrayExist(sumRows)){
				for(var i=0; i<sumRows.length; i++){
					var innerText = psGetInnerText(sumRows[i]);
					if(innerText.search(/Bill\s+To\:/i) >= 0){
						// parse billing address
						var billAddress = sumRows[i].cells[0].innerHTML;						
						var pItems = billAddress.split(/<br\s*\/*>/i);						
						if(pItems.length > 3){
							billAddress = psTrim(pItems[3]);							
							if(billAddress.indexOf(",") >= 0){
								var temp = billAddress.split(",");
								var uP = new psProfile();
								uP.readProfile();
								uP.city = psTrim(temp[0]);
								if(psTrim(temp[1]).search(/\s+/) >= 0){
									temp = psTrim(temp[1]).split(/\s+/);
									uP.state = psTrim(temp[0]);
									uP.zipcode = psTrim(temp[1]);									
									uP.writeProfile();
								}
							}
						}
						if(sumRows[i].cells.length > 2){
							this.subtotal = psCleanPrice(psGetInnerText(sumRows[i].cells[2]));
						}
					}else if(innerText.search(/SHIPPING/i) >= 0 && sumRows[i].cells.length > 1){
						this.shipping = psCleanPrice(psGetInnerText(sumRows[i].cells[1]));
					}
				}
			}			
			return true;
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all unaccepted characters in categoryid, including
 * [, ', ", :, comma,]
 * RETURN: string
 */
function psCleanCatId(pCatId)
{
    return (pCatId != null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

function psCleanProductName(pProductName)
{
	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 psCleanNumber(pNumber){
	var pattern = /[^0-9]/gi;
    return (pNumber != null ? pNumber.toString().replace(pattern, "") : null);
}
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 ==================*/