/************************************************************************************/
/* $Revision: 1.4 $
 * $Id: cmtaggingservices.js,v 1.4 2010/01/14 16:52:13 pyannam Exp $
 *
 * Author: Coremetrics/PSD
 * Coremetrics  v2.0, 2010/01/06
 * 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("dollartree.com", "fry.com", "localhost:8080");

// current page url
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_URL_REFERRER = document.referrer.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000; // 5*24*60*60 = 5 days
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";
var G_PS_COOKIE_TEMP_EMAIL = "PS_TEMP_EMAIL";
var G_PS_COOKIE_PRE_PRDID = "PS_PRE_PRDID";

var G_PS_INTERVAL = 1000; // 1s
//var G_PS_INTERVAL = 5000; // 5s, for debug only

var G_PS_IS_QUICKVIEW_PAGE = false;
var G_PS_QUICK_INTERVALID = null;
var G_PS_CART_INTERVALID = null;
var G_PS_UPDATE_INTERVALID = null;

// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!

if ((G_PS_URL_PATH.search(/(dollartree|dollartreeinfo|fry)\.com/i) >= 0) || (G_PS_URL_PATH.search(/localhost:8080/i) >= 0)){
	if (psIsSearchView())
	{
		psPostSearchView();
	}
	else if(psIsEnsemblePage()){
		psPostEnsembleView();
	}
	else if (psIsProductView())
	{
		psPostProductView();
	}
	else if (psIsCartView())
	{
		psPostCartView();
		psHijackResendShop5();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else if(psPostPageView() == false)
	{
		psCreatePageviewTag(G_PS_PATHNAME, "ADD URL");
	}
	psHijackRecentlyViewed();
	psHijackRelatedItems();

	psHijackRegistration();
	psHijackViewShoppingCart();
	psCleanQuickViewInterval();
	psHijackSearchForm();
}

function psIsEnsemblePage(){
	//http://www.dollartree.com/party-supplies/party-decor/party-decor/Bold-Blue-Party-Supplies-Buy-the-Ensemble-/207c217c217e14/index.ens
	//http://www.dollartree.com/catalog/ensemble.jsp?ensembleId=14
	if(G_PS_PATHNAME.indexOf("/index.ens") >= 0 || G_PS_PATHNAME.indexOf("catalog/ensemble.jsp") >= 0)
		return true;
	return false;
}

function psPostEnsembleView(){
	var prdCat = null;
	var ePrdId = null;
	var ePrdName = null;

	if(G_PS_PATHNAME.search(/\/(\d+)c(\d+)c(\d+)e(\d+)\//i) >= 0){
		prdCat = RegExp.$2;
		ePrdId = "e" + RegExp.$4;
		psSetCookie(G_PS_COOKIE_CATID,prdCat);
	}else if(G_PS_PATHNAME.search(/\/(\d+)c(\d+)e(\d+)\//i) >= 0){
		prdCat = RegExp.$2;
		ePrdId = "e" + RegExp.$3;
		psSetCookie(G_PS_COOKIE_CATID,prdCat);
	}else if(G_PS_PATHNAME.indexOf("catalog/ensemble.jsp") >= 0){
		ePrdId = "e" + psGetValueFromUrl(G_PS_URL_PATH,"ensembleId");
		prdCat = psGetCookie(G_PS_COOKIE_CATID);
	}
	var bcItems = psGetBreadCrumbItems();
	if(psCheckArrayExist(bcItems)){
		ePrdName = psCleanProductName(bcItems[bcItems.length-1]);
	}
	if(ePrdName == null || ePrdName == "" || ePrdName == "Home"){
		var h1Tags = document.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags)){
			ePrdName = psCleanProductName(psTrim(psGetInnerText(h1Tags[0])));
		}
	}
	psCreateProductviewTag(ePrdId, ePrdName, prdCat);

	var prd_str = "";
	var comDiv = document.getElementById("combo_products_wrap");
	if(psCheckElementExist(comDiv)){
		var rows = comDiv.getElementsByTagName("tr");
		if(psCheckArrayExist(rows)){
			for(var r=0; r<rows.length; r++){
				var prdName = null;
				var prdId = null;
				// Get product name
				var h3Tags = rows[r].getElementsByTagName("h3");
				if(psCheckArrayExist(h3Tags)){
					for(var i=0; i<h3Tags.length; i++){
						var aTags = h3Tags[i].getElementsByTagName("a");
						if(psCheckArrayExist(aTags)){
							prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));
						}
					}
				}
				// Get productID
				var temp = psGetInnerText(rows[r]);
				if(temp.search(/Sku\:\s*(\w+)\s+/i) >= 0){
					prdId = RegExp.$1;
					psCreateProductviewTag(prdId, prdName, prdCat);
					prd_str += prdId + ":";
				}
			}
		}
	}
	if(prd_str != ""){
		psHijackAddToCart_fromProductview(prd_str,prdCat);
	}
}

function psCleanQuickViewInterval(){
	if(G_PS_IS_QUICKVIEW_PAGE == false && G_PS_QUICK_INTERVALID != null){
		window.clearInterval(G_PS_QUICK_INTERVALID);
		G_PS_QUICK_INTERVALID = null;
	}
}

function psHijackRegistration(){
	if(G_PS_PATHNAME.search(/\/user\/(login|register)\.(jsp|cmd)/i) >= 0)
	{
		psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
		psHijackOnSubmit("loginForm","userName"); // Login
		psHijackOnSubmit("registerForm","emailAddress"); // Register
	}
	else if(G_PS_PATHNAME.search(/\/user\/(change_email_password\.jsp|updateMemberEmailAddress\.cmd)/i) >= 0)
	{
		psHijackOnSubmit("editEmailForm","newEmailAddress"); // change email
		var updatedFlag = false;
		var temp = psGetElementsByClassName(document,"p","hilite");
		if(psCheckArrayExist(temp)){
			for(var i=0; i<temp.length; i++){
				if(psGetInnerText(temp[i]).search(/You\s+have\s+successfully\s+updated\s+your\s+Email\s+Address/i) >= 0){
					updatedFlag = true;
				}
			}
		}
		if(updatedFlag == true){
			psPostRegistration();
		}else{
			psSetCookie(G_PS_COOKIE_FLAG,"","delete");
			psSetCookie(G_PS_COOKIE_TEMP_EMAIL,"","delete");
		}
	}else if(G_PS_PATHNAME.indexOf("/user/main.jsp") >= 0 ||
			 G_PS_PATHNAME.search(/checkout\/(shipping|billing)\.(jsp|cmd)/i) >= 0 ){
		psPostRegistration();
	}
	if(G_PS_PATHNAME.search(/checkout\/(billing|update_items_in_order)\.(jsp|cmd)/i) >= 0){
		psHijackBillingLogin();
		psHijackBillingAddress();
	}
	if(G_PS_PATHNAME.indexOf("user/personal_info.jsp") >= 0 || G_PS_PATHNAME.indexOf("user/updatememberinfo.cmd") >= 0){
		psHijackManageBillingAddress();
	}
	if(G_PS_PATHNAME.indexOf("user/updatememberinfo.cmd") >= 0){
		var pTags = psGetElementsByClassName(document,"p","hilite");
		if(psCheckArrayExist(pTags)){
			for(var i=0; i<pTags.length; i++){
				if(psGetInnerText(pTags[i]).search(/You\s+successfully\s+updated\s+your\s+billing\s+address/i) >= 0){
					psUpdateBillingAddress();
				}
			}
		}
	}
}

function psPostPageView(){
	var pPageId = null;
	var pCatId = null;
	var pIsQuickView = false;

	if(G_PS_PATHNAME == "/home.jsp" || G_PS_PATHNAME == "/"){
		pPageId = pCatId = "Home";
	}else if(G_PS_PATHNAME.indexOf("checkout/shipping_assignment_address.cmd") >= 0){
		pPageId = "Add New Shipping Address";
		pCatId = "My Account";
	}else if(G_PS_PATHNAME.indexOf("checkout/update_award_in_order.cmd") >= 0){
		// Payment page after apply promotion code
		pPageId = "Payment";
		pCatId = "Checkout";
	}else if(G_PS_PATHNAME.indexOf("catalog/alt_image_popup.jsp") >= 0){
		pPageId = pCatId = "Larger View";
	}else if(G_PS_PATHNAME.indexOf("/email_a_friend.jsp") >= 0 ||
			 G_PS_PATHNAME.indexOf("/catalog/product_email.cmd") >= 0 ||
			 G_PS_PATHNAME.indexOf("/user/subscribe.jsp") >= 0 ||
			 G_PS_PATHNAME.search(/checkout\/(billing|shipping|delivery|payment|update_items_in_order)\.(jsp|cmd)/i) >= 0){
		// Get pageId from url
		var temp = G_PS_PATHNAME.replace(/^.+\//g,"");
		temp = temp.replace(/\.(jsp|cmd|asp|aspx|html|htm)/i,"");
		pPageId = pCatId = temp.replace(/\_/g," ");
		if(G_PS_PATHNAME.indexOf("checkout/") >= 0)
			pCatId = "Checkout";
	}else if(G_PS_PATHNAME.indexOf("/user/subscribe.cmd") >= 0){
		pPageId = pCatId = "Thank you for subscribing";
	}else{
		var pPageName = psGetValueFromUrl(G_PS_URL_PATH,"pageName");
		if(pPageName != null && pPageName != "" && pPageName.search(/^ChristmasCorner$/i) >= 0){
			pPageId = pCatId = pPageName;
			var temp = psGetValueFromUrl(G_PS_URL_PATH,"parentName");
			if(temp != null && temp != "") pCatId = temp;
		}else{
			var bcItems = psGetBreadCrumbItems();
			if(psCheckArrayExist(bcItems)){
				// Get pageId from breadcrumb
				pPageId = bcItems[bcItems.length-1];
				var decPath = psHtmlDecode(unescape(G_PS_PATHNAME));
				if(decPath.search(/(\d+)c(\d+)c(\d+)\/index\.cat/) >= 0){
					// sub category
					// http://www.dollartree.com/health-personal-care/baby-products/211c242c242/index.cat
					pCatId = RegExp.$2;
					pIsQuickView = true;
				}else if(decPath.search(/c(\d+)\/index\.cat/) >= 0){
					//sub category, exception:
					//http://www.dollartree.com/health-personal-care/bath-products/211c243/index.cat
					pCatId = RegExp.$1;
					pIsQuickView = true;
				}else if(decPath.search(/\/(\d+)\/index\.cat/) >= 0){
					// Category at top menu
					pCatId = RegExp.$1;
				}else if(decPath.search(/catalog\/(thumbnail|section|category)\.jsp/) >= 0){
					// View category from sitemap
					//http://www.dollartree.com/catalog/thumbnail.jsp?sectionId=202&parentCategoryId=202&categoryId=204&subCategoryId=204
					//http://www.dollartree.com/catalog/section.jsp?categoryId=202
					//http://www.dollartree.com/catalog/category.jsp?sectionId=211&parentCategoryId=211&categoryId=243
					var catId = psGetValueFromUrl(G_PS_URL_PATH,"categoryId");
					if(catId != null && catId != "")
						pCatId = catId;
				}else if(bcItems.length > 1){
					pCatId = bcItems[bcItems.length-2];
				}
			}else{
				// Get pageId from div grayHead -> H1
				var headDivs = psGetElementsByClassName(document,"div","grayHead grayULine");
				if(psCheckArrayExist(headDivs)){
					var h1Tags = headDivs[0].getElementsByTagName("h1");
					if(psCheckArrayExist(h1Tags)){
						pPageId = pCatId = psGetInnerText(h1Tags[0]);
					}
				}

			}
		}
	}
	if(pPageId == null && pCatId == null){
		// Get from <h1 class="popTitle">Forgot Your Password?</h1> for popup window
		var h1Tags = psGetElementsByClassName(document,"h1","popTitle");
		if(psCheckArrayExist(h1Tags) == false)
			h1Tags = document.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags)){
			pPageId = pCatId = psGetInnerText(h1Tags[0]);
		}
	}

	if(pPageId == null || pCatId == null){
		return false;
	}

	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));

	pPageId = pPageId.toUpperCase();
	pCatId = pCatId.toUpperCase();

	psCreatePageviewTag(pPageId, pCatId, null, null);

	if(G_PS_PATHNAME.search(/catalog\/(alt_image_popup|alt_image_thumbnail|alt_image_view|email_a_friend|product_email)\.(jsp|cmd)/i) < 0 &&
	   pPageId.search(/Why\s+we\s+need\s+your\s+ZIP\s+code/i) < 0){
		psSetCookie(G_PS_COOKIE_CATID,pCatId);
	}

	if(pIsQuickView == true && G_PS_QUICK_INTERVALID == null){
		G_PS_IS_QUICKVIEW_PAGE = true;
		G_PS_QUICK_INTERVALID = window.setInterval("psCheckQuickViewProduct()",G_PS_INTERVAL);
	}else{
		if(G_PS_QUICK_INTERVALID != null){
			window.clearInterval(G_PS_QUICK_INTERVALID);
			G_PS_QUICK_INTERVALID = null;
		}
	}

	return true;

}

function psUpdateBillingAddress(){
	var uP = new psProfile();
	uP.readProfile();
	var city = psGetValueFromCookie(G_PS_COOKIE_TEMP_EMAIL,"city");
	var state = psGetValueFromCookie(G_PS_COOKIE_TEMP_EMAIL,"state");
	var zipcode = psGetValueFromCookie(G_PS_COOKIE_TEMP_EMAIL,"zipcode");

	if(psCheckElementExist(city)) uP.city = city;
	if(psCheckElementExist(state)) uP.state = state;
	if(psCheckElementExist(zipcode)) uP.zipcode = zipcode;
	uP.writeProfile();

	psPostRegistration();
	psSetCookie(G_PS_COOKIE_TEMP_EMAIL,"","delete");
}

function psHijackManageBillingAddress(){
	var bForm = psGetElementByName("form","billingForm");
	if(psCheckElementExist(bForm)){
		if(bForm.onsubmit == null || bForm.onsubmit.toString().indexOf("psHJManageBillingAddress") < 0){
			bForm.OldFunction = bForm.onsubmit;
			bForm.onsubmit = function psHJManageBillingAddress(){
				var city = psGetElementByName("input","city");
				var state = psGetElementByName("select","state");
				var zipcode = psGetElementByName("input","zipCode");
				if(psCheckElementExist(city)){
					psSetValueToCookie(G_PS_COOKIE_TEMP_EMAIL,"city",psTrim(city.value));
				}
				if(psCheckElementExist(state)){
					psSetValueToCookie(G_PS_COOKIE_TEMP_EMAIL,"state",state.options[state.selectedIndex].value);
				}
				if(psCheckElementExist(zipcode)){
					psSetValueToCookie(G_PS_COOKIE_TEMP_EMAIL,"zipcode",psTrim(zipcode.value));
				}
				psSetCookie(G_PS_COOKIE_FLAG,"login");
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackSearchForm(){
	var sForm = psGetElementByName("form","searchForm");
	if(psCheckElementExist(sForm)){
		if(sForm.onsubmit == null || sForm.onsubmit.toString().indexOf("psHJSearchForm") < 0){
			sForm.OldFunction = sForm.onsubmit;
			sForm.onsubmit = function psHJSearchForm(){
				psSetCookie(G_PS_COOKIE_FLAG,"from_search");
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackBillingAddress(){
	var buttons = document.getElementsByTagName("input");
	var btn = null;
	if(psCheckArrayExist(buttons)){
		for(var i=0; i<buttons.length; i++){
			var btnSrc = buttons[i].getAttribute("src");
			if(btnSrc != null && btnSrc.search(/btn\/big_continue\.gif/i) >= 0){
				btn = buttons[i];
				break;
			}
		}
	}
	if(btn != null){
		if(btn.onclick == null || btn.onclick.toString().indexOf("psHJBillingAddress") < 0){
			btn.OldFunction = btn.onclick;
			btn.onclick = function psHJBillingAddress(){
				var city = document.getElementById("city");
				var state = document.getElementById("state");
				var zipcode = document.getElementById("zipCode");
				var email = document.getElementById("emailAddress");
				var uP = new psProfile();
				if(psCheckElementExist(city)) uP.city = psTrim(city.value);
				if(psCheckElementExist(state)) uP.state = state.options[state.selectedIndex].value;
				if(psCheckElementExist(zipcode)) uP.zipcode = psTrim(zipcode.value);
				if(psCheckElementExist(email)) uP.cusId = uP.email = psTrim(email.value);
				if(uP.email != null && psCheckEmail(uP.email)){
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"login");
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackBillingLogin(){
	var forms = document.getElementsByTagName("form");
	var frm = null;
	if(psCheckArrayExist(forms)){
		for(var i=0; i<forms.length; i++){
			var frmAction = forms[i].getAttribute("action");
			if(frmAction != null && frmAction.search(/checkout\/login\.cmd/i) >= 0){
				frm = forms[i];
				break;
			}
		}
	}
	if(frm == null) return;
	if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJBillingLogin") < 0){
		frm.OldFunction = frm.onsubmit;
		frm.onsubmit = function psHJBillingLogin(){
			var email = document.getElementById("userName");
			if(psCheckElementExist(email)){
				var uP = new psProfile();
				uP.cusId = uP.email = psTrim(email.value);
				if(psCheckEmail(uP.email)){
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"login");
				}
			}
			if(this.OldFunction != null) return this.OldFunction();
		}
	}
}

function psHijackResendShop5(){
	// Resend shop5 when click on "Checkout" button, because the quantity can be changed
	var checkoutDivs = psGetElementsByClassName(document,"div","right basket-checkout-button-wrapper");
	if(psCheckArrayExist(checkoutDivs)){
		var temps = checkoutDivs[0].getElementsByTagName("input");
		if(psCheckArrayExist(temps)){
			var checkoutBtn = temps[0];
			if(checkoutBtn.onclick == null || checkoutBtn.onclick.toString().indexOf("psHJResendShop5") < 0){
				checkoutBtn.OldFunction = checkoutBtn.onclick;
				checkoutBtn.onclick = function psHJResendShop5(){
					psPostCartView();
					if(this.OldFunction != null)
						return this.OldFunction();
				}
			}
		}

	}
}

function psCheckQuickViewCart(){
	var cartContent = document.getElementById("glo-ucart-content");
	if(psCheckElementExist(cartContent)){
		var checkoutTables = psGetElementsByClassName(cartContent,"table","checkoutTable");
		if(psCheckArrayExist(checkoutTables)){
			var sendShop5Flag = false;
			var rows = checkoutTables[0].rows;
			for(var i=0; i<rows.length; i++){
				var prdId = null;
				var prdName = null;
				var prdQuan = null;
				var prdPrice = null;
				var prdCat = null;
				if(rows[i].innerHTML != null && rows[i].innerHTML.search(/btn\/sm_remove\.gif/i) < 0)
					continue;
				if(rows[i].cells.length < 4) continue;

				var temp = rows[i].cells[0].innerHTML;
				if(temp.search(/product_images\/styles\/small\/(\w+)\.jpg/i) >= 0){
					prdId = RegExp.$1;
				}

				var aTags = rows[i].cells[1].getElementsByTagName("a");
				if(psCheckArrayExist(aTags)){
					prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));
					//prdId = psGetValueFromUrl(aTags[0].href,"productId");
				}
				var cell2 = psGetInnerText(rows[i].cells[2]);
				if(cell2 != null && cell2.search(/(\d+)\s+Case/i) >= 0){
					prdQuan = RegExp.$1;
				}
				var strongTags = rows[i].cells[2].getElementsByTagName("strong");
				if(psCheckArrayExist(strongTags)){
					prdPrice = psCleanPrice(psGetInnerText(strongTags[0]));
					if(isFinite(prdPrice) && isFinite(prdQuan)){
						prdPrice = parseFloat(prdPrice)/parseFloat(prdQuan);
						prdPrice = prdPrice.toFixed(2);
					}
				}
				if(prdId != null) prdCat = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,prdId);
				if(prdCat == null || prdCat == "")
					prdCat = "Unknown";
				if(prdId != null && prdName != null){
					psCreateShopAction5Tag(prdId, prdName, prdQuan, prdPrice, prdCat);
					sendShop5Flag = true;
				}
			}
			if(sendShop5Flag == true){
				psDisplayShop5s();
				// clear interval
				if(G_PS_CART_INTERVALID != null){
					window.clearInterval(G_PS_CART_INTERVALID);
					G_PS_CART_INTERVALID = null;
				}
			}
			psHijackQuickEditRemoveQuantity(cartContent);
			// clear interval for hijack Update button
			if(G_PS_UPDATE_INTERVALID != null){
				window.clearInterval(G_PS_UPDATE_INTERVALID);
				G_PS_UPDATE_INTERVALID = null;
			}

		}
	}
}

function psHijackQuickEditRemoveQuantity(quickCart){
	var aTags = quickCart.getElementsByTagName("a");
	if(psCheckArrayExist(aTags)){
		for(var i=0; i<aTags.length; i++){
			var aSrc = aTags[i].innerHTML;
			if(aSrc != null && aSrc.search(/btn\/(sm_remove|sm_edit)\.gif/i) >= 0){
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJEditRemove") < 0){
					aTag.OldFunction = aTag.onclick;
					aTag.aSrc = aSrc;
					aTag.onclick = function psHJEditRemove(){
						if(this.aSrc.search(/btn\/sm_edit\.gif/i) >= 0){
							// Wait for editing quantity
							if(G_PS_UPDATE_INTERVALID == null){
								G_PS_UPDATE_INTERVALID = window.setInterval("psHijackUpdateCartButton()",G_PS_INTERVAL);
							}
						}else{
							// Click on remove
							if(G_PS_CART_INTERVALID == null){
								G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()",G_PS_INTERVAL);
							}
						}
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackUpdateCartButton(){
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags)){
		for(var i=0; i<aTags.length; i++){
			var aSrc = aTags[i].innerHTML;
			if(aSrc != null && aSrc.search(/btn\/update_cart_icon\.gif/i) >= 0){
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJEditRemove") < 0){
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJEditRemove(){
						if(G_PS_CART_INTERVALID == null){
							G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()",G_PS_INTERVAL);
						}
						// clear interval for hijack Update button
						if(G_PS_UPDATE_INTERVALID != null){
							window.clearInterval(G_PS_UPDATE_INTERVALID);
							G_PS_UPDATE_INTERVALID = null;
						}
						if(this.OldFunction != null) return this.OldFunction();
					}
				}
			}
		}
	}

}

function psHijackViewShoppingCart(){
	// Set interval to send shop5 when clicking on "Shopping cart" button
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags)){
		for(var i=0; i<aTags.length; i++){
			var aTag = aTags[i];
			if(aTag.href != null && aTag.href.search(/checkout\/basket\.jsp/i) >= 0){
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJViewCart") < 0){
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJViewCart(){
						if(G_PS_CART_INTERVALID == null){
							G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()",G_PS_INTERVAL);
						}
						if(this.OldFunction != null)
							return this.OldFunction();
					}
				}
			}
		}
	}
}

function psCheckQuickViewProduct(){
	// Send productview when ajax load QuickView
	var quickViewDiv = document.getElementById("cat-quickview-content");
	if(psCheckElementExist(quickViewDiv)){
		var prdName = null;
		var prdId = null;
		// Get productId from sku
		var priceDiv = psGetElementsByClassName(quickViewDiv,"div","pricing_group");
		if(psCheckArrayExist(priceDiv)){
			var temp = psGetInnerText(priceDiv[0]);
			if(temp.search(/Sku\:\s*(\w+)\s+/i) >= 0){
				prdId = RegExp.$1;
			}
		}

		var h1Tags = quickViewDiv.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags)){
			for(var i=0; i<h1Tags.length; i++){
				var aTags = h1Tags[i].getElementsByTagName("a");
				if(psCheckArrayExist(aTags)){
					for(var j=0; j<aTags.length; j++){
						var temp = aTags[j].href;
						if(temp != null && temp.search(/catalog\/product\.jsp\?productId\=/i) >= 0){
							prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[j])))));
							//prdId = psGetValueFromUrl(temp,"productId");
						}
						if(temp != null && temp.search(/catalog\/ensemble\.jsp\?ensembleId\=/i) >= 0){
							prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[j])))));
							prdId = "e" + psGetValueFromUrl(temp,"ensembleId");
						}
					}
				}
			}
		}

		var preProductId = psGetCookie(G_PS_COOKIE_PRE_PRDID);
		var prdCat = psGetCookie(G_PS_COOKIE_CATID);
		if(G_PS_PATHNAME.indexOf("checkout/basket.jsp") >= 0){
			prdCat = "Related Items";
		}
		if(prdId != null && prdName != null && (preProductId == null || prdId != preProductId) ){
			psCreateProductviewTag(prdId, prdName, prdCat,"Quickwiew");
			psSetCookie(G_PS_COOKIE_PRE_PRDID,prdId);
			// Hijack Add to cart
			psHijackQuickAddToCart(quickViewDiv,prdId,prdCat);

			// Send productview for each item in ensemble
			if(prdId.indexOf("e") >= 0){
				var qDivs = psGetElementsByClassName(quickViewDiv,"div","qv_combo_cell");
				if(psCheckArrayExist(qDivs)){
					for(var r=0; r<qDivs.length; r++){
						// Get product name
						var h3Tags = qDivs[r].getElementsByTagName("h3");
						if(psCheckArrayExist(h3Tags)){
							prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(h3Tags[0])))));
						}
						// Get productId
						var temp = qDivs[r].innerHTML;
						if(temp.search(/product_images\/styles\/small\/(\w+)\.jpg/i) >= 0){
							prdId = RegExp.$1;
							psCreateProductviewTag(prdId, prdName, prdCat,"Quickwiew");
						}
					}
				}
			}
		}
	}
}

function psHijackAddToCart_fromProductview(prdId,prdCat){
	var aTags = document.getElementsByTagName("a");
	if(psCheckArrayExist(aTags)){
		for(var i=0; i<aTags.length; i++){
			var aTag = aTags[i];
			if(aTag.innerHTML != null && aTag.innerHTML.search(/btn\/add_to_cart_icon\.gif/i) >= 0){
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJAddToCartPW") < 0){
					aTag.OldFunction = aTag.onclick;
					aTag.prdId = prdId;
					aTag.prdCat = prdCat;
					aTag.onclick = function psHJAddToCartPW(){
						if(this.prdId != null && this.prdId.indexOf(":") >= 0){
							// Ensemble
							var pItems = this.prdId.split(":");
							for(var t=0; t<pItems.length; t++){
								if(pItems[t] != ""){
									psSetValueToCookie(G_PS_COOKIE_PROD_CATID,pItems[t],this.prdCat);
								}
							}
						}else{
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdId,this.prdCat);
						}
						// Set interval to send shop5
						if(G_PS_CART_INTERVALID == null){
								G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()",G_PS_INTERVAL);
						}
						if(this.OldFunction != null)
							return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackQuickAddToCart(quickDiv,productId,productCat){
	var addToCartBtns = psGetElementsByClassName(quickDiv,"a","widget-quickview-but-add");
	if(psCheckArrayExist(addToCartBtns)){
		var addBtn = addToCartBtns[0];
		if(addBtn.onclick == null || addBtn.onclick.toString().indexOf("psHJQuickBuy") < 0){
			addBtn.OldFunction = addBtn.onclick;
			addBtn.prdId = productId;
			addBtn.prdCat = productCat;
			addBtn.onclick = function psHJQuickBuy(){
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdId,this.prdCat);
				// Set interval to send shop5
				if(G_PS_CART_INTERVALID == null){
						G_PS_CART_INTERVALID = window.setInterval("psCheckQuickViewCart()",G_PS_INTERVAL);
				}
				if(this.OldFunction != null)
					return this.OldFunction();
			}
		}
	}
}

function psPostRegistration(){
	var cookieFlag = psGetCookie(G_PS_COOKIE_FLAG);
	if(cookieFlag == "login"){
		var uP = new psProfile();
		uP.readProfile();
		if(uP.cusId != null)
		{
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
		}
	}else if(cookieFlag == "edit_email"){
		var uP = new psProfile();
		uP.readProfile();
		var tempEmail = psGetCookie(G_PS_COOKIE_TEMP_EMAIL);
		if(tempEmail != null && tempEmail != ""){
			uP.cusId = uP.email = tempEmail;
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
			uP.writeProfile();
			psSetCookie(G_PS_COOKIE_TEMP_EMAIL,"","delete");
		}
	}
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");

}

function psHijackOnSubmit(formName,emailId){
	var frm = psGetElementByName("form",formName);
	if(psCheckElementExist(frm)){
		if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJEmail") < 0){
			frm.emailId = emailId;
			frm.OldFunction = frm.onsubmit;
			frm.onsubmit = function psHJEmail(){
				var email = document.getElementById(this.emailId);
				if(psCheckElementExist(email)){
					if(this.emailId == "newEmailAddress"){
						// change email, write to temporary cookie
						psSetCookie(G_PS_COOKIE_TEMP_EMAIL,psTrim(email.value));
						psSetCookie(G_PS_COOKIE_FLAG,"edit_email");
					}else{
						//login or registration
						var uP = new psProfile();
						uP.cusId = uP.email = psTrim(email.value);
						if(this.emailId == "emailAddress"){
							// registration
							var zipcode = document.getElementById("zipCode");
							if(psCheckElementExist(zipcode)){
								uP.zipcode = psTrim(zipcode.value);
							}
						}

						uP.writeProfile();
						psSetCookie(G_PS_COOKIE_FLAG,"login");
					}
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackRelatedItems(){
	// At productview page
	var rightDiv = document.getElementById("right_rail");

	// At Shopping cart page
	if(G_PS_PATHNAME.indexOf("checkout/basket.jsp") >= 0 || psCheckElementExist(rightDiv) == false){
		var relatedDivs = psGetElementsByClassName(document,"div","basket-also-like-container");
		if(psCheckArrayExist(relatedDivs)){
			rightDiv = relatedDivs[0];
		}
	}

	if(psCheckElementExist(rightDiv)){
		var pSectionName = null;
		var h2Tags = rightDiv.getElementsByTagName("h2");
		if(psCheckArrayExist(h2Tags)){
			pSectionName = psTrim(psHtmlDecode(unescape(psGetInnerText(h2Tags[0]))));
		}
		if(pSectionName == null || pSectionName == "")
			return;
		var aTags = rightDiv.getElementsByTagName("a");
		if(psCheckArrayExist(aTags)){
			for(var i=0; i<aTags.length; i++){
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJRelatedItems") < 0){
					aTag.sectionName = pSectionName;
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJRelatedItems(){
						psSetCookie(G_PS_COOKIE_CATID,this.sectionName);
						if(this.OldFunction != null)
							return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackRecentlyViewed(){
	var leftDiv = document.getElementById("viewed-products");
	if(psCheckElementExist(leftDiv)){
		var pSectionName = null;
		var h6Tags = leftDiv.getElementsByTagName("h6");
		if(psCheckArrayExist(h6Tags)){
			pSectionName = psTrim(psHtmlDecode(unescape(psGetInnerText(h6Tags[0]))));
		}
		if(pSectionName == null || pSectionName == "")
			return;
		var aTags = leftDiv.getElementsByTagName("a");
		if(psCheckArrayExist(aTags)){
			for(var i=0; i<aTags.length; i++){
				var aTag = aTags[i];
				if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJRecentlyViewed") < 0){
					aTag.sectionName = pSectionName;
					aTag.OldFunction = aTag.onclick;
					aTag.onclick = function psHJRecentlyViewed(){
						psSetCookie(G_PS_COOKIE_CATID,this.sectionName);
						if(this.OldFunction != null)
							return this.OldFunction();
					}
				}
			}
		}
	}
}

function psGetBreadCrumbItems(){
	var arrResult = new Array();
	var index = 0;

	var bc = document.getElementById("breadcrumb");
	if(psCheckElementExist(bc)){
		var liTags = bc.getElementsByTagName("li");
		if(psCheckArrayExist(liTags)){
			for(var i=0; i<liTags.length; i++){
				var temp = psTrim(psHtmlDecode(unescape(psGetInnerText(liTags[i]))));
				if(temp != null && temp != ""){
					arrResult[index]= temp;
					index++;
				}
			}
		}
	}
	return arrResult;
}

function psIsSearchView()
{
	if(G_PS_PATHNAME.indexOf("catalog/search.cmd") >= 0){
		var prdDiv = psGetElementsByClassName(document,"div","prodImageWrap");
		var prdId = psGetElementByName("input","productId");
		if(psCheckArrayExist(prdDiv) || psCheckElementExist(prdId)){
			return false;
		}
		return true;
	}
	return false;
}

function psIsProductView()
{
	if(G_PS_PATHNAME.indexOf("/index.pro") >= 0 || G_PS_PATHNAME.indexOf("catalog/product.jsp") >= 0)
		return true;
	if(G_PS_PATHNAME.indexOf("catalog/search.cmd") >= 0){
		var prdDiv = psGetElementsByClassName(document,"div","prodImageWrap");
		var prdId = psGetElementByName("input","productId");
		if(psCheckArrayExist(prdDiv) || psCheckElementExist(prdId)){
			return true;
		}
	}
	return false;
}

function psIsCartView()
{
	if(G_PS_PATHNAME.indexOf("/checkout/basket.jsp") >= 0)
		return true;

	if(G_PS_PATHNAME.indexOf("checkout/update_items_in_order.cmd") >= 0){
		// It can be shopping cart page after applying promation code or billing address
		var h1Tags = document.getElementsByTagName("h1");
		if(psCheckArrayExist(h1Tags)){
			for(var i=0; i<h1Tags.length; i++){
				var temp = psGetInnerText(h1Tags[i]);
				if(temp != null && temp.search(/Shopping\s+Cart/i) >= 0){
					return true;
				}
			}
		}
	}

	return false;
}

function psIsOrderView()
{
	if(G_PS_PATHNAME.indexOf("/checkout/receipt.jsp") >= 0)
		return true;
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	G_PS_CUR_CATID = "SEARCH";
	var pPageId = "SEARCH UNSUCCESSFUL";
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(sResult != "0"){
		var viewAll = psTrim(psGetValueFromUrl(G_PS_URL_PATH,"viewall"));
		if(viewAll == "true"){
			pPageId = "SEARCH SUCCESSFUL VIEW ALL";
		}else{
			pPageId = "SEARCH SUCCESSFUL PAGE[" + psGetPageNumber() + "]";
		}
	}
	if(psGetCookie(G_PS_COOKIE_FLAG) == "from_search" || G_PS_URL_REFERRER.indexOf("catalog/search.cmd") >= 0 ){
		psCreatePageviewTag(pPageId, G_PS_CUR_CATID, sTerm, sResult);
		psSetCookie(G_PS_COOKIE_CATID,G_PS_CUR_CATID);
	}else{
		G_PS_CUR_CATID = "Defined Search";
		pPageId = "Defined Search: " + sTerm;
		psCreatePageviewTag(pPageId, G_PS_CUR_CATID);
		psSetCookie(G_PS_COOKIE_CATID,G_PS_CUR_CATID);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");

	G_PS_IS_QUICKVIEW_PAGE = true;
	if(G_PS_QUICK_INTERVALID == null){
		G_PS_QUICK_INTERVALID = window.setInterval("psCheckQuickViewProduct()",G_PS_INTERVAL);
	}

}

function psGetPageNumber(){
	var spanTags = psGetElementsByClassName(document,"span","currentPage");
	if(psCheckArrayExist(spanTags)){
		return psTrim(psHtmlDecode(unescape(psGetInnerText(spanTags[0]))));
	}
	return "1";
}

function psGetSearchTerm()
{
	var term = "";
	var searchTag = document.getElementById("searchKey");
	if(psCheckElementExist(searchTag)){
		term = psTrim(searchTag.value);
	}else{
		term = psTrim(psHtmlDecode(unescape(psGetValueFromUrl(G_PS_URL_PATH,"keyword"))));
	}
	return term;
}

function psGetSearchResult()
{
	var result = "0";
	var pTags = document.getElementsByTagName("p");
	if(psCheckArrayExist(pTags)){
		for(var i=0; i<pTags.length; i++){
			var temp = psGetInnerText(pTags[i]);
			if(temp != null && temp.search(/There\s+are\s+(\d+)\s+products\s+that\s+match\s+your\s+search/i) >= 0){
				return RegExp.$1;
			}
		}
	}
	return result;
}

function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()){
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
		psHijackAddToCart_fromProductview(prd.id,prd.catId);
	}
}

function psPostCartView()
{
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("BASKET", G_PS_CUR_CATID, null,null);
	psSetCookie(G_PS_COOKIE_CATID,"BASKET");
	var sendShop5Flag = false;

	var cartTbl = document.getElementById("shopping-cart-items");
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows;
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++)
	{

		if (rows[r].innerHTML.search(/checkout\/delete_item_from_order\.cmd/gi) < 0 || rows[r].cells.length < 5)
			continue;

		if (prd.getItem5(rows[r])){
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
			sendShop5Flag = true;
		}
	}
	if(sendShop5Flag == true)
		psDisplayShop5s();
	// Set interval for Quickview product at Related Items
	if(G_PS_QUICK_INTERVALID == null){
		G_PS_IS_QUICKVIEW_PAGE = true;
		G_PS_QUICK_INTERVALID = window.setInterval("psCheckQuickViewProduct()",G_PS_INTERVAL);
	}
}

function psPostOrderView()
{
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("ORDER COMPLETE", G_PS_CUR_CATID, null, null);
	psSetCookie(G_PS_COOKIE_CATID,"ORDER COMPLETE");

	var ord = new psOrder();
	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile())
		{
			var prd = new psProduct();

			var checkoutTables = psGetElementsByClassName(document,"table","checkoutTable");
			if(psCheckArrayExist(checkoutTables)){
				for(var i=0; i<checkoutTables.length; i++){
					var rows = checkoutTables[i].rows;
					for (var r = 0; r < rows.length; r++)
					{
						if(rows[r].innerHTML.search(/catalog\/product\.jsp/i) < 0)
							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 ===========================*/
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;
	}
	this.getProduct = function()
	{
		try
		{
			this.reset();
			var priceDiv = psGetElementsByClassName(document,"div","pricing_group");
			if(psCheckArrayExist(priceDiv)){
				var temp = psGetInnerText(priceDiv[0]);
				if(temp.search(/Sku\:\s*(\w+)\s+/i) >= 0){
					this.id = RegExp.$1;
				}
			}

			var bcItems = psGetBreadCrumbItems();
			if(psCheckArrayExist(bcItems)){
				this.name = psCleanProductName(bcItems[bcItems.length-1]);
				if(this.name != null && this.name.toUpperCase() == "HOME"){
					var h1Tags = document.getElementsByTagName("h1");
					if(psCheckArrayExist(h1Tags)){
						this.name = psTrim(psCleanProductName(psHtmlDecode(unescape(psGetInnerText(h1Tags[0])))));
					}
				}
			}
			if(G_PS_URL_REFERRER == null || G_PS_URL_REFERRER == ""){
				if(G_PS_PATHNAME.search(/\/(\d+)c(\d+)c(\d+)p.+\/index\.pro/i) >= 0){
					this.catId = RegExp.$2;
				}else{
					this.catId = "Bookmarks";
				}
			}else if(G_PS_URL_REFERRER.indexOf("dollartree.com") < 0){
				this.catId = "Bookmarks";
			}else{
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
				if(this.id != null &&
				    ((this.catId == "basket" && G_PS_URL_REFERRER.indexOf("checkout/basket.jsp") >= 0) ||
					G_PS_URL_REFERRER.search(/checkout\/(delivery|payment)\.jsp/i) >= 0)){
					this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
				}
			}
			if(G_PS_PATHNAME.indexOf("catalog/search.cmd") >= 0){
				this.catId = "Search";
			}
			if(this.id != null && this.id != "")
				return true;
		}
		catch (ex) { return false; }
	}
	this.getItem5 = function(itemRow)
	{
		try
		{
			this.reset();
			var temp = psGetInnerText(itemRow.cells[1]);
			if(temp.search(/SKU\:\s*(\w+)\s+/i) >= 0){
				this.id = RegExp.$1;
			}
			var aTags = itemRow.cells[1].getElementsByTagName("a");
			if(psCheckArrayExist(aTags)){
				this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));
				//this.id = psGetValueFromUrl(aTags[0].href,"productId");
			}
			this.price = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[3])));
			var quanInputs = itemRow.cells[4].getElementsByTagName("input");
			if(psCheckArrayExist(quanInputs)){
				this.quantity = psTrim(quanInputs[0].value);
			}
			if(this.id != null){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null || this.catId == "")
					this.catId = "Unknown";
				return true;
			}
		}
		catch (ex) { return false; }
	}
	this.getItem9 = function(itemRow)
	{
		try
		{
			this.reset();

			var temp = psGetInnerText(itemRow.cells[1]);
			if(temp.search(/SKU\:\s*(\w+)\s+/i) >= 0){
				this.id = RegExp.$1;
			}
			var aTags = itemRow.cells[1].getElementsByTagName("a");
			if(psCheckArrayExist(aTags)){
				this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(aTags[0])))));
				//this.id = psGetValueFromUrl(aTags[0].href,"productId");
			}
			this.price = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[2])));
			this.quantity = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[3])));
			if(this.id != null)
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
     		return true;
		}
		catch (ex) { return false; }
	}
}

function psProfile()
{
	this.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;

	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];
					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; }
	}

	this.writeProfile = function()
	{
		try
		{
			if (this.cusId == null)
				return;
			var data = this.cusId + "|" + this.email + '|' + this.city + '|' + this.state + '|'
				+ this.zipcode + "|" + this.newsletter + '|' + this.subscribe;
			// store on cookie
			psSetCookie(G_PS_COOKIE_PROFILE, data);
			return true;
		}
		catch (ex) { return false; }
	}
}

function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;

	this.getOrder = function()
	{
		try
		{
			var h5Tags = document.getElementsByTagName("h5");
			if(psCheckArrayExist(h5Tags)){
				for(var i=0; i<h5Tags.length; i++){
					if(psGetInnerText(h5Tags[i]).search(/Order\s+Number\:\s*(\w+)\s+placed\s+on/i) >= 0){
						this.id = RegExp.$1;
					}
				}
			}
			var orderSummaryTags = psGetElementsByClassName(document,"dl","orderSummary");
			if(psCheckArrayExist(orderSummaryTags)){
				var shipping = null;
				var handling = null;
				var discount = null;
				var dtTags = orderSummaryTags[0].getElementsByTagName("dt");
				var ddTags = orderSummaryTags[0].getElementsByTagName("dd");
				if(psCheckArrayExist(dtTags) && psCheckArrayExist(ddTags)){
					for(var i=0; i<dtTags.length; i++){
						if(psGetInnerText(dtTags[i]).search(/Merchandise\s*\:/i) >= 0){
							if(psCheckElementExist(ddTags[i])){
								this.subtotal = psCleanPrice(psGetInnerText(ddTags[i]));
							}
						}
						if(psGetInnerText(dtTags[i]).search(/Handling\s*\:/i) >= 0){
							if(psCheckElementExist(ddTags[i]) && psGetInnerText(ddTags[i]).search(/\d+/) >= 0){
								handling = psCleanPrice(psGetInnerText(ddTags[i]));
							}
						}
						if(psGetInnerText(dtTags[i]).search(/Shipping\s*\:/i) >= 0){
							if(psCheckElementExist(ddTags[i])){
								shipping = psCleanPrice(psGetInnerText(ddTags[i]));
							}
						}
						if(psGetInnerText(dtTags[i]).search(/Order\s+Discount\s*\:/i) >= 0){
							if(psCheckElementExist(ddTags[i])){
								discount = psCleanPrice(psGetInnerText(ddTags[i]));
							}
						}

					}
				}
				if(handling != null && shipping != null && isFinite(handling) && isFinite(shipping)){
					shipping = parseFloat(shipping) + parseFloat(handling);
					shipping = shipping.toFixed(2);
				}
				if(discount != null && this.subtotal != null && isFinite(discount) && isFinite(this.subtotal)){
					this.subtotal = parseFloat(this.subtotal) - parseFloat(discount);
					this.subtotal = this.subtotal.toFixed(2);
				}
				this.shipping = shipping;
			}

			if (!this.id)
				this.id = psGenerateRandomValue();
			var uP = new psProfile();
			uP.readProfile();
			 if (!uP.cusId)
				uP.cusId = psGenerateRandomValue();
			return uP.writeProfile();
		}
		catch (ex) {return false;}
	}
}

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;
}

function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi;
	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;
}

function psCleanCatId(pCatId)
{
    return (pCatId != null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null;
}

function psCleanProductName(pProductName)
{
	pProductName = pProductName.replace(String.fromCharCode(8541),"");
	pProductName = pProductName.replace(String.fromCharCode(189),""); // 1/2
	pProductName = pProductName.replace(String.fromCharCode(188),""); // 1/4

	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null;
}

function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;
	return (pStr != null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

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;
}

function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}

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;
}

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;
}

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;
}

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;

}

function psGetDomain(pUrl){
    var se = /^https*\:\/\/([^\/\:]+)/gi;
    return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}

function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

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;
}

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);
}

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);
}

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;
}

function psGenerateRandomValue()
{
	var dtDate = new Date();
	var cusRandom = (dtDate.getTime()%10000000) + (Math.floor(Math.random()*10000));
	return cusRandom;
}

function psShorttenPageID(pLink)
{
	var temp1 = pLink;
	if (temp1 != null)
	{
		temp1 = (temp1.length > 255) ? temp1.substr(0, 255) : temp1;
	}
	return temp1;
}

function psCheckArrayExist(pArrElement){
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0)
    {
        return false;
    }

    return true;
}
function psCheckElementExist(pElement){
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }

    return true;
}

function psGetElementByName(tagName,elementName){
	// return the first element
	var tags = document.getElementsByTagName(tagName);
	if(psCheckArrayExist(tags)){
		for(var i=0; i<tags.length; i++){
			if(tags[i].name != null && tags[i].name.toLowerCase() == elementName.toLowerCase()){
				return tags[i];
			}
		}
	}
	return null;
}

function psGetElementsByClassName(psDocument, psElementTagName, psClassName){
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null)
    {
        return null;
    }
    for(var i = 0; i < arrInputs.length; i ++ )
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult)
{
	pId = psCleanPageId(pId);
	pId = psShorttenPageID(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId, 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)
{
	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 ==================*/