/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.4, 2009/10/07
 * 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("luggagepros.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 = 7776000; // 90*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_REFINEMENT = "PS_PROD_REF";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var G_PS_COOKIE_ORDER = "PS_ORDER";
var G_PS_COOKIE_EMAIL = "PS_EMAIL_TEMP";
var G_PS_COOKIE_COUNT_PRO = "PS_COUNT_PRO";
var INTERVAL_ID=null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
psAllHijacks();
//Page View for navigating through top menus/top categories
if(G_PS_PATHNAME == "/")
{
	psCreatePageviewTag("Home", "Home", null, null);
	psSetCookie(G_PS_COOKIE_CATID, "Home");
}
else if(G_PS_PATHNAME.search(/\/supercat_([^\/]+)(\/(index\.shtml)?)?$/gi) > -1)
{
	if(psCheckElementExist(RegExp.$1))
	{
		var pSuperCat = RegExp.$1.replace(/\--/g, " ").replace("%26","&");
		psCreatePageviewTag(pSuperCat,pSuperCat,null,null);
		psSetCookie(G_PS_COOKIE_CATID, pSuperCat);
	}
}
else if(G_PS_PATHNAME == "/luggage_brands.shtml")
{
	psCreatePageviewTag("Luggage Brands","Luggage Brands",null,null);
	psSetCookie(G_PS_COOKIE_CATID, "Luggage Brands");
}
else if(G_PS_PATHNAME == "/sales_and_closeouts.shtml")
{
	psCreatePageviewTag("Sales and Closeouts","Sales and Closeouts",null,null);
	psSetCookie(G_PS_COOKIE_CATID, "Sales and Closeouts");
}
//Page View for navigating through sub menus/sub categories
else if(G_PS_PATHNAME.search(/\/supercat_([^\/]+)\/cat_([^\/]+)(\/(index\.shtml)?)?$/gi) > -1
	|| G_PS_PATHNAME.search(/\/mfgr_([^\/]+)\/cat_([^\/]+)(\/(index\.shtml)?)?$/gi) > -1)
{
	if(psCheckElementExist(RegExp.$2))
	{
		var pSupperCat = RegExp.$1;
		var pCat = RegExp.$2;
		pCat = pCat.replace(/\--/g, " ").replace("-quote-", "").replace("%26","&");
		pSupperCat = pSupperCat.replace(/\--/g, " ").replace("-quote-", "").replace("%26","&");
		var pPageId = psGetPageIdFrombreadcrumbs();
		if(pSupperCat == "backpacks & messenger bags" && pCat == "messenger bags") 
		{
			pCat =  "cat_" + pCat;
			pPageId = "cat_" + "messenger_bags";
		}
		psCreatePageviewTag(pPageId, pCat, null, null);
		psSetCookie(G_PS_COOKIE_CATID, pCat);
	}
}
else if(G_PS_PATHNAME.search(/\/supercat_([^\/]+)\/mfgr_([^\/]+)(\/(index\.shtml)?)?$/gi) > -1)
{
	if(psCheckElementExist(RegExp.$1))
	{
		var pCat = RegExp.$1.replace(/\--/g, " ");
		pCat = pCat.replace("-quote-", "").replace("%26","&");
		psCreatePageviewTag(psGetPageIdFrombreadcrumbs(), pCat, null, null);
		psSetCookie(G_PS_COOKIE_CATID, pCat);
	}
}
//Page View for navigating the brand pages
else if(G_PS_PATHNAME.search(/\/mfgr_([^\/]+)(\/(index\.shtml)?)?$/gi) > -1)
{
	if(psCheckElementExist(RegExp.$1))
	{
		var pMfgr = RegExp.$1.replace(/\--/g, " ").replace("%26","&");
		psCreatePageviewTag(psGetPageIdFrombreadcrumbs(), pMfgr, null, null);
		psSetCookie(G_PS_COOKIE_CATID, pMfgr);
	}
}
//Page View for navigating through content pages
else if(G_PS_URL_PATH.search(/\/policies\//gi) > -1)
{
	var pCatId = "Policies";
	var pPageId = (G_PS_URL_PATH.search(/\/policies\/([^.]+).shtml/gi) > -1)?RegExp.$1:pCatId;
	psCreatePageviewTag(pPageId, pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID, pCatId);
}
else if (G_PS_PATHNAME.search(/\/mfgr_([^\/]+)\/line_([^\/]+)(\/(index\.shtml)?)?/i) > -1)
{
	if(psCheckElementExist(RegExp.$1))
	{
		var pLine = RegExp.$1.replace(/\--/g, " ");
		pLine = pLine.replace(/\-\-/gi, " ").replace("%26","&");
		psCreatePageviewTag(psGetPageIdFrombreadcrumbs(), pLine, null, null);
		psSetCookie(G_PS_COOKIE_CATID, pLine);
	}
}
else if(G_PS_URL_PATH.search(/\/travel\//gi) > -1)
{
	var pCatId = "Travel";
	var pPageId = (G_PS_URL_PATH.search(/\/travel\/([^.]+).shtml/gi) > -1)?RegExp.$1:pCatId;
	psCreatePageviewTag(pPageId, pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID, pCatId);
}
else if(G_PS_PATHNAME == "/sitemap.shtml")
{
	psCreatePageviewTag("Sitemap","Home",null,null);
}
else if(G_PS_PATHNAME == "/price_match.php")
{
	psCreatePageviewTag("Price Match","Home",null,null);
}
//For all account pages
else if(G_PS_URL_PATH.indexOf("customer/account") > -1 || G_PS_URL_PATH.indexOf("/customer/address/") > -1
		|| G_PS_URL_PATH.indexOf("/sales/order/") >-1 || G_PS_URL_PATH.indexOf("/wishlist/") >-1)
{
	var pCatId = "Account";
	psSetCookie(G_PS_COOKIE_CATID, pCatId);
	
	if(G_PS_PATHNAME == "/customer/account/login/")
	{
		psCreatePageviewTag("Login",pCatId,null,null);
		psHijackLogin("login-form","email");
	}
	else if(G_PS_PATHNAME == "/customer/account/")
	{
		psCreatePageviewTag("Account","Account",null,null);
		if(psIsSuccessfulUpdate("success-msg","account information was successfully saved") && psGetCookie(G_PS_COOKIE_FLAG) == "update account")
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			// post registration tag for update profile page
			uP.cusId = psGetCookie(G_PS_COOKIE_EMAIL);
			uP.email = psGetCookie(G_PS_COOKIE_EMAIL);
			uP.writeProfile();
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
		else if(G_PS_URL_REFERRER.indexOf("/customer/account/login/") >-1 && psGetCookie(G_PS_COOKIE_FLAG) == "login")
		{
			psPostRegistration();
		}
	}
	else if(G_PS_PATHNAME == "/customer/account/create/")
	{
		psCreatePageviewTag("Create",pCatId,null,null);
		psHijackLogin("form-validate","email_address");
	}
	else if(G_PS_PATHNAME == "/customer/account/index/")
	{
		psCreatePageviewTag("Index",pCatId,null,null);
		if(G_PS_URL_REFERRER.indexOf("/customer/account/create/") >-1 || G_PS_URL_REFERRER.indexOf("/customer/account/login/") >-1)
		{
			if(psGetCookie(G_PS_COOKIE_FLAG) == "login")
				psPostRegistration();
		}
	}
	else if(G_PS_URL_PATH.indexOf("/customer/address/edit/") > -1)
	{
		psCreatePageviewTag("address/edit",pCatId,null,null);
		psHijackUpdateAddress();
	}
	else if(G_PS_PATHNAME == "/customer/address/" || G_PS_PATHNAME == "/customer/address/index/")
	{
		psCreatePageviewTag("address",pCatId,null,null);
		if(psIsSuccessfulUpdate("success-msg","the address was successfully saved") && psGetCookie(G_PS_COOKIE_FLAG) == "updated address")
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			// post registration tag for update profile page
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
	}
	else if(G_PS_PATHNAME == "/customer/account/edit/")
	{
		psCreatePageviewTag("account/edit",pCatId,null,null);
		psHijackUpdateAcc();
	}
	else if(G_PS_PATHNAME == "/sales/order/history/")
	{
		psCreatePageviewTag("sales/order/history",pCatId,null,null);
	}
	else if(G_PS_PATHNAME == "/review/customer/")
	{
		psCreatePageviewTag("review/customer",pCatId,null,null);
	}
	else if(G_PS_PATHNAME == "/customer/account/logoutsuccess/")
	{
		psCreatePageviewTag("Logout Success",pCatId,null,null);
	}
	else if(G_PS_PATHNAME == "/wishlist/index/index/" || G_PS_PATHNAME == "/wishlist/")
	{
		psCreatePageviewTag("Wishlist",pCatId,null,null);
		if(psGetCookie(G_PS_COOKIE_FLAG) == "login")
		{
			psPostRegistration();
		}
	}
	else if(G_PS_URL_PATH.indexOf("/customer/account/edit/changepass/") > -1)
	{
		psCreatePageviewTag("edit/changepass",pCatId,null,null);
	}
	else if(G_PS_URL_PATH.indexOf("/sales/order/view/order_id/") > -1)
	{
		psCreatePageviewTag("Order View","Account",null,null);
		psHijackProductOrder();
	}

}
else if(G_PS_PATHNAME == "/review/customer/")
{
	psCreatePageviewTag("review/customer","Account",null,null);
}
else if(G_PS_URL_PATH.indexOf("/sendfriend/product/send/") > -1)
{
	psCreatePageviewTag("sendfriend/product","Home",null,null);
}
else if(G_PS_URL_PATH.indexOf("/warranty.shtml") > -1)
{
	if(psCheckElementExist(psGetValueFromUrl(G_PS_URL_PATH,"l")))
	{
		psCreatePageviewTag(psGetValueFromUrl(G_PS_URL_PATH,"l"),"Warranties",null,null);
	}
	else psCreatePageviewTag("Warranty","Home",null,null);
}

else if((G_PS_PATHNAME.indexOf("/checkout/onepage/")  > -1 && psIsOrderView() == false) || ( G_PS_PATHNAME.indexOf("/checkout/twopage/")  > -1 && psIsOrderView() == false))
{
  if(G_PS_PATHNAME.indexOf("/checkout/onepage/")  > -1)
  {
	  psCreatePageviewTag("Onepage","CHECKOUT",null,null); 
  }
  else if(G_PS_PATHNAME.indexOf("/checkout/twopage/")  > -1)
  {
//     psCreatePageviewTag("Twopage","CHECKOUT",null,null); 
  }
	var checkoutPage = psGetCheckoutPage();		
	INTERVAL_ID=window.setInterval("psStepView()", 1000);
	
	if(checkoutPage == "Checkout method")
	{
		psHijackSaveEmail();
	}
	psHijackOrderReview();
	
}
else if(psIsOrderView())
{		
	psPostOrderView();
}
else if(psIsSearchView())
{
	psHijackRefinement();
	psPostSearchView();
}
else if(psIsProductView())
{
	psPostProductView();
}
else if(psIsCartView())
{
	psPostCartView();
	psHijackProductsCart();
}
else if(G_PS_PATHNAME == "/catalog/product_compare/index/")
{	
	psCreatePageviewTag("Product Compare","Compare Products",null,null);
}
else 
{	
	psCreatePageviewTag(G_PS_PATHNAME, "ADD URL", null, null); // Other pages go to "ADD URL" category
}
function psStepView()
{
	var pBilling = document.getElementById("checkout-step-billing");
	if(psCheckElementExist(pBilling))
	{
		if(pBilling.style.display == "" && psGetCookie(G_PS_COOKIE_FLAG) == "login")	//is billing step 
		{
			psPostRegistration();
			window.clearInterval(INTERVAL_ID);
		}
	}
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	if (G_PS_URL_PATH.indexOf("/catalogsearch/result") > -1) return true;
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	//
	// TO-Do: Your logic to determine the product detail page goes here
	//
	var lstBtn = psGetElementsByClassName(document,"button","imgbutton addtocart");
	if(psCheckArrayExist(lstBtn))
	{
		return true;
	}
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	//
	// TO-Do: Your logic to determine the shopping cart page goes here
	//
	if (G_PS_URL_PATH.indexOf("/checkout/cart/") > -1) return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if((G_PS_PATHNAME.indexOf("/checkout/onepage/success/") > -1) || (G_PS_PATHNAME.indexOf("/checkout/twopage/success/") > -1)){
		return true;
	}
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
/* 
 * Hijack all products from "also recommended", "bes sellers", "my cart", "recently viewed"
 */
function psAllHijacks()
{
	psHijackProducts("div","block block-recent");
	psHijackProducts("div","block block-cart");
	psHijackProducts("div","block block-compare");
	psHijackBestSeller();
	psHijackWhatnew();
	psHijackAlsoRecommended();
	
}

/* 
 *Get productId 
 */
function psGetProId()
{
	var pProId = null;
	var tblPro = document.getElementById("product-attribute-specs-table");
	if(psCheckElementExist(tblPro))
	{
		pProId = tblPro.innerHTML.toLowerCase().search(/(pid\d+)/gi);
		pProId = psTrim(RegExp.$1);
	}
	return pProId;
}

/*
 * Get product name 
 */
function psGetProName()
{
	var pProName = null;
	var pProDiv = psGetElementsByClassName(document ,"div","product-essential");
	if(psCheckArrayExist(pProDiv))
	{
		pProName = pProDiv[0].innerHTML.toLowerCase().search(/<h2>([^<]+)<\/h2>/gi);
		pProName = psTrim(psHtmlDecode(RegExp.$1));
	}
	return pProName;
}

function psGetPageIdFrombreadcrumbs()
{
	var pPageId = "";
	var strCrumb = psGetElementsByClassName(document,"div","breadcrumbs");
	if(psCheckArrayExist(strCrumb))
	{
		var lstCrumb = strCrumb[0].innerHTML.toLowerCase().split("<li");
		if(psCheckArrayExist(lstCrumb))
		{
			pPageId = lstCrumb[lstCrumb.length -1];
			pPageId = pPageId.search(/<strong>([^<]+)<\/strong>/gi);
			pPageId = psTrim(psHtmlDecode(RegExp.$1));
		}
	}
	return pPageId;
}

/*
 * Check if array is exist or not
 */
function psCheckArrayExist(pArrElement)
{
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0)
    {
        return false;
    }

    return true;
}

/*
 * Check an element exist or not
*/
function psCheckElementExist(pElement)
{
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }

    return true;
}

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

function psPostRegistration()
{
	var uP = new psProfile();
	uP.readProfile(); // get user profile from cookie
	if(uP.email != null)
	{
		psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
}

function psPostSearchView()
{
	var sCatId = psGetCatIdForSearch();
	var pageId = "";
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(psIsRefinementSearch())
	{
		if(sCatId == "p" || sCatId == "mode" || sCatId == "order" || sCatId == "dir" || sCatId == "limit")
		{
			pageId = psGetLableRef(psGetCookie(G_PS_COOKIE_REFINEMENT));
			sCatId = pageId.search(/([^:]+):\s([^$]+)/gi);
			sCatId = "By " + RegExp.$1;
		}
		else
		{
			if(psGetCookie(G_PS_COOKIE_REFINEMENT) != "")
			{
				pageId = psTrim(sCatId.replace("By","")) + ": " + psGetCookie(G_PS_COOKIE_REFINEMENT);
			}
			else 
			{
				var temp =  psTrim(sCatId.replace("By",""));
				pageId = psGetLableRef(temp);
			}
		}
	}
	else
	{
		if(sResult == 0 || sResult == "0")
		{
			pageId = "SEARCH UNSUCCESSFUL";
		}
		else
		{
			pageId = "SEARCH SUCCESSFUL PAGE " + psGetCurrentPage();
		}
		sCatId = "SEARCH";
	}
	if (pageId != null)
		psCreatePageviewTag(pageId, sCatId, sTerm, sResult);
	psSetCookie(G_PS_COOKIE_CATID, sCatId);
}

function psGetLableRef(pRefix)
{
	var lstLabel = psGetElementsByClassName(document,"span","label");
	var sResult = null;
	if(psCheckArrayExist(lstLabel))
	{
		for(var i=0;i<lstLabel.length;i++)
		{
			var pTemp = psCleanHtmlTag(lstLabel[i].parentNode.innerHTML.toLowerCase());
			if(pTemp.indexOf(pRefix.toLowerCase()) >-1)
				sResult = psTrim(pTemp);
		}
	}
	return psHtmlDecode(sResult) ;
}

/*
 * Get search current of paging
 */
function psGetCurrentPage()
{
	var pCurrent = 1;
	var pStrCurr = psGetElementsByClassName(document, "span", "current");
	if(psCheckArrayExist(pStrCurr))
	{
		pCurrent = psTrim(psCleanHtmlTag(pStrCurr[0].innerHTML));
	}
	else 
		pCurrent = psTrim(psGetValueFromUrl(G_PS_URL_PATH,"p"));
	return (pCurrent!=null)?psTrim(pCurrent):1;
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	var strTerm = psGetElementsByClassName(document,"li","search");
	if(psCheckArrayExist(strTerm))
	{
		term = strTerm[0].innerHTML.toLowerCase();
		term = (term.search(/search for \"([^"]+)/gi) > -1)?RegExp.$1.replace('"',""):"";
		term = (psHtmlDecode(psHtmlDecode(term)));
	}
	else 
	{
		term = psHtmlDecode(psGetValueFromUrl(G_PS_URL_PATH,"q"));
		term = psTrim(term.replace(/%20+/gi, " ").replace(/[\+]/gi, " "));
	}
	return psTrim(term);
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	//
	// TO-Do: Your logic to extract search result goes here
	//
	var strResult = psGetElementsByClassName(document,"p","amount col-1");
	if(psCheckArrayExist(strResult))
	{
		result = strResult[0].innerHTML.toLowerCase();
		result = psTrim(result.replace(/[items|item]/gi," "));
	}
	
	return result;
}


function psHijackRefinement()
{
	var sContent = psGetElementsByClassName(document,"div","block-layered-nav"); 
	if(psCheckArrayExist(sContent))
	{
		var links  = sContent[0].getElementsByTagName("a");
		for (var i = 0; i < links.length; i++)	
		{
			if (psCheckElementExist(links[i].href) && links[i].href.toLowerCase().indexOf("/catalogsearch/result/index/") > -1)
			{			
				links[i].oldCMFunc  = links[i].onclick;
				links[i].onclick = function()
				{
					var sText = psTrim(psHtmlDecode(psCleanHtmlTag(this.innerHTML)));
					psSetCookie(G_PS_COOKIE_REFINEMENT,sText);
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}
			}
		}
	}		
}
/*
 * Get the last paremeter from URL
 */
function psGetLastValue()
{
	var sResult = null;
	if(G_PS_URL_PATH.search(/[\?,\&]([^=]+)=([^$,&]+)$/gi) > -1)
		sResult =  psTrim(RegExp.$1);
	return sResult;
}

/*
 * Get category for search and search refinement
 */
function psGetCatIdForSearch()
{
	var sCatId = null;
	var sRefBy = psGetLastValue();
	
	switch (sRefBy)
	{
		case "q":
			sCatId = "SEARCH";	
			break;	
		case "brand": 
			sCatId = "By Brand";	
			break;
		case "cat12":
			sCatId = "By Luggage";	
			break;
		case "cat5":
			sCatId = "By Laptop & Briefcases";	
			break;
		case "cat22":
			sCatId = "By Handbags & Wallets";	
			break;	
		case "cat26":
			sCatId = "By Backpacks & Messenger Bags";	
			break;
		case "cat47":
			sCatId = "By Travel Accessories";	
			break;	
		case "cat247":
			sCatId = "By Duffels & Sports Bags";	
			break;
		case "cat96":
			sCatId = "By Business and Personal Accessories";	
			break;	
		case "color_map":
			sCatId = "By Color";	
			break;	
		case "price":
			sCatId = "By Price";	
			break;	
		default: sCatId = sRefBy;
	}
	return sCatId;
}

function psIsRefinementSearch()
{
	if(psGetValueFromUrl(G_PS_URL_PATH, "brand") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"cat12") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"cat5") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"cat22") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"cat26") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"cat47") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"cat247") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"cat96") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"color_map") != null
		||psGetValueFromUrl(G_PS_URL_PATH,"price") != null
		)
		return true;
	return false;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()) // Get product info successfully?
	{
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
		psHiackAddToCart(prd.id,prd.catId);
	}
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("SHOPPING CART", G_PS_CUR_CATID, null);

	var cartTbl = null;
	//
	// TO-Do: Your logic to locate the items table (cartTbl) goes here
	//
	cartTbl = document.getElementById("shopping-cart-table");
	if (!psCheckElementExist(cartTbl))
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	var psCountPro = 0;
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		/*
		 * Codes for skipping exceptional rows (rows that don't contain items)
		 */
		if (rows[r].innerHTML.toLowerCase().search(/sku/gi)<0) // Skip rows not containing item (identified by the term "Item #")
			continue;
			
		if (prd.getItem5(rows[r]))
		{
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
			psCountPro+=1;
		}
	}
	//count number of product to send in shop5.
	psSetCookie(G_PS_COOKIE_COUNT_PRO,psCountPro);
	// Make sure to have actual postings
	psDisplayShop5s();
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("Success",G_PS_CUR_CATID,null,null);
	
	var cartTbl = null;
	cartTbl = document.getElementById("my-orders-table");
	if (!psCheckElementExist(cartTbl))
		return;
	/*
	 * Codes for locating the table containing items (each row for an item)
	 */
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var ord = new psOrder();
	var psCountPro = 0;
	
	if (ord.getOrder())
	{
		var psCountProShop5 = psGetCookie(G_PS_COOKIE_COUNT_PRO);
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var j = 0; j < rows.length; j++) // item for each row
			{
				/*
				 * Codes for skipping exceptional rows (rows don't contain items)
				 */
				if (rows[j].innerHTML.toLowerCase().search(/pid(\d+)/gi) < 0) // Skip rows not containing item (identified by the term "Item #")
					continue;
					
				if (prd.getItem9(rows[j]))
				{
					psCountPro+=1 ;
				}
			}
			//if exist a different between number of shop5 and shop9, the shop5 will be send again.
			if(psCountProShop5 && psCountPro != psCountProShop5)
			{
				for (var i = 0; i < rows.length; i++) // item for each row
				{		
					if (rows[i].innerHTML.toLowerCase().search(/pid(\d+)/gi) < 0) // Skip rows not containing item (identified by the term "Item #")
						continue;	
					if(prd.getItem5_Re(rows[i]))
					{
						psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
					}
				}
				psDisplayShop5s();
			}
			
			for (var r = 0; r < rows.length; r++) // item for each row
			{		
				if (rows[r].innerHTML.toLowerCase().search(/pid(\d+)/gi) < 0) // Skip rows not containing item (identified by the term "Item #")
						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");
		}
	}
}
/*
 * Get Order number from source code
 */
function psGetOrderNumber()
{
	var sNum = null;
	var pOrderNum = psGetElementsByClassName(document,"div", "order-number");
	if(psCheckArrayExist(pOrderNum))
	{
		sNum =  psTrim(psCleanHtmlTag(pOrderNum[0].innerHTML));
	}
	else
	{
		var pTags = document.getElementsByTagName("p");
		if(psCheckArrayExist(pTags))
		{
			for(var i=0; i<pTags.length; i++){
				if(psGetInnerText(pTags[i]).search(/Your\s+order\s+\#\s+is\:\s+(\d+)/) >= 0)
				{			                            
					sNum =  psTrim(RegExp.$1);
				}
			}
		}
	}
	return sNum;
}

/*
 * Determine if the page is the update account successful page
 */
function psIsSuccessfulUpdate(pClassName, pMsg)
{
	var lstMsg = psGetElementsByClassName(document,"li",pClassName);
	if(psCheckArrayExist(lstMsg))
	{
		if(lstMsg[0].innerHTML.toLowerCase().indexOf(pMsg) > -1)
			return true;
	}
	return false;
}

function psHijackOrderReview()
{	
	var buttons = psGetElementsByClassName(document,"button","button");
	if(psCheckArrayExist(buttons))
	{
		for(var i=0; i<buttons.length; i++)
		{
			var btn = buttons[i];
			if(psTrim(psGetInnerText(btn)).search(/Place\s+Order/i) >=0)
			{
				btn.OldFunction = btn.onclick;
				btn.onclick = function ()
				{
					psSaveOrderInfo();
					if(this.OldFunction != null) return this.OldFunction();
				}
			}
		}
	}
}

/*
 * Save all oder information for cookie
 */
function psSaveOrderInfo()
{
	// Save billing address
	var divContents = psGetElementsByClassName(document,"div","block-content");
	if(psCheckArrayExist(divContents))
	{
		var addressTags = divContents[0].getElementsByTagName("address");
		if(psCheckArrayExist(addressTags))
		{
			var strAddress = addressTags[0].innerHTML.toLowerCase();
			if(strAddress.search(/<br\s*\/*>/gi) >= 0)
			{
				var pItems = strAddress.split(/<br\s*\/*>/gi);
				if(pItems.length >= 3)
				{
					strAddress = pItems[pItems.length-3];
					if(strAddress.indexOf(",") > -1)
					{						
						var pTemps = strAddress.split(",");
						var uP = new psProfile();
						if(uP.readProfile() && pTemps.length > 2)
						{
							uP.city = psTrim(pTemps[0]);
							uP.state = psTrim(pTemps[1]);
							uP.zipcode = psTrim(pTemps[2]);
							uP.writeProfile();
						}
					}
				}
			}			
		}
	}
}

function psHijackLogin(formName,emailTag)
{
	var loginFrm = document.getElementById(formName);
	if(psCheckElementExist(loginFrm))
	{		
		loginFrm.OldFunction = loginFrm.onsubmit;
		loginFrm.onsubmit = function ()
		{			
			var email = document.getElementById(emailTag);
			if(psCheckElementExist(email) && psCheckEmail(psTrim(email.value)))
			{
				var uP = new psProfile();
				uP.email = uP.cusId = psTrim(email.value);
				uP.writeProfile();				
				psSetCookie(G_PS_COOKIE_FLAG,"login");
			}
			if(this.OldFunction != null) return this.OldFunction();
		}		
	}
}

function psGetCheckoutPage()
{
	var h3Tags = document.getElementsByTagName("h3");
	if(psCheckArrayExist(h3Tags))
	{
		return psTrim(psGetInnerText(h3Tags[0]));
	}
}

function psGetButtonByText(btnText)
{
	var buttons = psGetElementsByClassName(document,"button","button");
	if(psCheckArrayExist(buttons))
	{
		for(var i=0; i<buttons.length; i++)
		{
			var btn = buttons[i];
			if(psTrim(psGetInnerText(btn)) == btnText)
			{
				return btn;
			}
		}
	}
	return null;
}

function psSaveEmail(emailId)
{
	var email = document.getElementById(emailId);
	if(psCheckElementExist(email) && psCheckEmail(psTrim(email.value)))
	{
		var uP = new psProfile();
		uP.email = uP.cusId = psTrim(email.value);
		psSetCookie(G_PS_COOKIE_FLAG,"login");
		uP.writeProfile();		
	}	
}

function psHiackAddToCart(pId, pCatId)
{
	var lstBtn = psGetElementsByClassName(document,"button","imgbutton addtocart");
	if(psCheckArrayExist(lstBtn))
	{
		lstBtn[0].oldCMFunc  = lstBtn[0].onclick;
		lstBtn[0].onclick = function()
		{
			// Store productId along with catId to cookie for use later in shop5 and shop9 views
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pId, pCatId);
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}
		return true;
	}
	return false;
}

function psHijackSaveEmail()
{	
	// Hijack on Continue button
	var btnContinue = psGetButtonByText("Continue");
	if(btnContinue != null)
	{
		btnContinue.OldFunction = btnContinue.onclick;
		btnContinue.onclick = function ()
		{
			psSaveEmail("login-email");
			if(this.OldFunction != null) return this.OldFunction();
		}
	}
	// Hijack Enter Key on email
	var emailElement = document.getElementById("login-email");
	if(psCheckElementExist(emailElement))
	{
		emailElement.OldFunction = emailElement.onkeypress;
		emailElement.onkeypress = function (e)
		{
			try
			{
				var key = window.event ? event.keyCode : e.keyCode;
				if(key == 13)
				{
					psSaveEmail("login-email");
					if(this.OldFunction != null) 
						return this.OldFunction();	
				}
			}
			catch (ex) {}
		}
	}	
	// Hijack Enter Key on password
	var passwordElement = document.getElementById("login-password");
	if(psCheckElementExist(passwordElement))
	{
		passwordElement.OldFunction = passwordElement.onkeypress;
		passwordElement.onkeypress = function (e)
		{
			try
			{
				var key = window.event ? event.keyCode : e.keyCode;
				if(key == 13)
				{
					psSaveEmail("login-email");
					if(this.OldFunction != null) 
						return this.OldFunction();	
				}
			}
			catch (ex) {}
		}
	}
}

function psHijackUpdateAcc()
{
	var updateFrm = document.getElementById("form-validate");
	if(psCheckElementExist(updateFrm))
	{		
		updateFrm.OldFunction = updateFrm.onsubmit;
		updateFrm.onsubmit = function ()
		{	
			
			var pEmail = document.getElementById("email");
			if(psCheckElementExist(pEmail) && psCheckEmail(psTrim(pEmail.value)))
			{
				psSetCookie(G_PS_COOKIE_EMAIL,pEmail.value);
				psSetCookie(G_PS_COOKIE_FLAG,"update account");
			}
			if(this.OldFunction != null) return this.OldFunction();
		}		
	}
}

function psHijackUpdateAddress()
{
	var updateFrm = document.getElementById("form-validate");
	if(psCheckElementExist(updateFrm))
	{		
		updateFrm.OldFunction = updateFrm.onsubmit;
		updateFrm.onsubmit = function()
		{	
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			if(uP.email)
			{
				uP.city = psGetElementValueById("city",true);
				uP.state = psGetElementValueById("region_id",false);
				uP.zipcode = psGetElementValueById("zip",true);
				uP.writeProfile();
				psSetCookie(G_PS_COOKIE_FLAG,"updated address");
			}			
			if(this.OldFunction != null) return this.OldFunction();
		}		
	}
}

function psHijackBestSeller()
{
	var  lstPro = psGetElementsByClassName(document, "div", "products-grid");
	var pCatId = "HOME";
	if(psCheckArrayExist(lstPro))
	{
		for(var i=0;i<lstPro.length;i++)
		{
			if(lstPro[i].innerHTML.toLowerCase().indexOf("best sellers") > -1)
			{
				pCatId = "Best Sellers";
				var links = lstPro[i].getElementsByTagName("a");
				if(psCheckArrayExist(links))
				{
					for(var j=0;j<links.length;j++)
					{	
						if(links[j].className != "remove" && links[j].innerHTML.toLowerCase().indexOf("clear all items") < 0)
						{
							var oldCMFunc = (links[j]._c_onclick != null) ?  links[j]._c_onclick: links[j].onclick;
							links[j].onclick = function()
							{
								psSetCookie(G_PS_COOKIE_CATID, pCatId);			
								if (oldCMFunc != null)
									return oldCMFunc();
							}
						}
					}
				}
			}
		}
	}
}

function psHijackWhatnew()
{
	var  lstPro = psGetElementsByClassName(document, "div", "products-grid");
	var pCatId = "HOME";
	if(psCheckArrayExist(lstPro))
	{
		for(var i=0;i<lstPro.length;i++)
		{
			if(lstPro[i].innerHTML.toLowerCase().indexOf("what's new") > -1)
			{
				pCatId = "Whats new";
				var links = lstPro[i].getElementsByTagName("a");
				if(psCheckArrayExist(links))
				{
					for(var j=0;j<links.length;j++)
					{	
						if(links[j].className != "remove" && links[j].innerHTML.toLowerCase().indexOf("clear all items") < 0)
						{
							var oldCMFunc = (links[j]._c_onclick != null) ?  links[j]._c_onclick: links[j].onclick;
							links[j].onclick = function()
							{
								psSetCookie(G_PS_COOKIE_CATID, pCatId);			
								if (oldCMFunc != null)
									return oldCMFunc();
							}
						}
					}
				}
			}
		}
	}
}

function psHijackAlsoRecommended()
{
	var  lstPro = psGetElementsByClassName(document, "div", "products-grid");
	var pCatId = "HOME";
	if(psCheckArrayExist(lstPro))
	{
		for(var i=0;i<lstPro.length;i++)
		{
			if(lstPro[i].innerHTML.toLowerCase().indexOf("also recommended") > -1)
			{
				pCatId = "Also Recommended";
				var links = lstPro[i].getElementsByTagName("a");
				if(psCheckArrayExist(links))
				{
					for(var j=0;j<links.length;j++)
					{	
						if(links[j].className != "remove" && links[j].innerHTML.toLowerCase().indexOf("clear all items") < 0)
						{
							var oldCMFunc = (links[j]._c_onclick != null) ?  links[j]._c_onclick: links[j].onclick;
							links[j].onclick = function()
							{
								psSetCookie(G_PS_COOKIE_CATID, pCatId);			
								if (oldCMFunc != null)
									return oldCMFunc();
							}
						}
					}
				}
			}
		}
	}
}

function psHijackProducts(pTag,pClassName)
{
	var  lstPro = psGetElementsByClassName(document, pTag, pClassName);
	var pCatId = "HOME";
	if(psCheckArrayExist(lstPro))
	{
		for(var i=0;i<lstPro.length;i++)
		{
			if(lstPro[i].innerHTML.toLowerCase().indexOf("recently viewed products") > -1)
			{
				pCatId = "Recently Viewed";
			}
			else if(lstPro[i].innerHTML.toLowerCase().indexOf("my cart") > -1)
			{
				pCatId = "cart";
			}
			else if(lstPro[i].innerHTML.toLowerCase().indexOf("compare products") > -1)
			{
				pCatId = "Compare Products";
			}
			var links = lstPro[i].getElementsByTagName("a");
			if(psCheckArrayExist(links))
			{
				for(var j=0;j<links.length;j++)
				{	
					if(links[j].className != "remove" && links[j].innerHTML.toLowerCase().indexOf("clear all items") < 0)
					{
						var oldCMFunc = (links[j]._c_onclick != null) ?  links[j]._c_onclick: links[j].onclick;
						links[j].onclick = function()
						{
							psSetCookie(G_PS_COOKIE_CATID, pCatId);			
							if (oldCMFunc != null)
								return oldCMFunc();
						}
					}
				}
			}
		}
	}
}

function psHijackProductOrder()
{
	var pTable = document.getElementById("my-orders-table");
	if(psCheckElementExist(pTable ))
	{
		for(var j=0;j<pTable.rows.length;j++)
		{
			var itemRow = pTable.rows[j];
			for(var i=0;i<itemRow.cells.length;i++)
			{
				var pSku =  psCleanHtmlTag(itemRow.cells[i].innerHTML.toLowerCase());
				pSku = pSku.search(/(pid\d+)/gi);
				if(psCheckElementExist(RegExp.$1))
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,psTrim(RegExp.$1),"Account");
			}
		}
	}

}

function psHijackProductsCart()
{
	var cartTbl = null;
	//
	// TO-Do: Your logic to locate the items table (cartTbl) goes here
	//
	cartTbl = document.getElementById("shopping-cart-table");
	if (!psCheckElementExist(cartTbl))
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		/*
		 * Codes for skipping exceptional rows (rows that don't contain items)
		 */
		if (rows[r].innerHTML.toLowerCase().search(/sku/gi)<0) // Skip rows not containing item (identified by the term "Item #")
			continue;
		var links = rows[r].getElementsByTagName("a");
		if(psCheckArrayExist(links))
		{
			for(var j=0;j<links.length;j++)
			{				
				var oldCMFunc = links[j].onclick; //backup the existing onclick function
				links[j].onclick = function()
				{
					psSetCookie(G_PS_COOKIE_CATID, "Cart");			
					if (oldCMFunc != null)
						return oldCMFunc();
				}
			}
		}	
		
	}
}
/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	this.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
		this.price = null;
		this.quantity = null;
	}
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			this.id = psGetProId();
			this.name = psGetProName();
			//productview from shopping cart. 
			if(psGetCookie(G_PS_COOKIE_CATID) == "cart")
			{
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null || this.catId == "null"){this.catId = "HOME";}

				this.catId = psTrim(this.catId); 
			}
			
			else 
			// In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
				this.catId = (psGetCookie(G_PS_COOKIE_CATID) != null)?psGetCookie(G_PS_COOKIE_CATID):"HOME";

			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 pSku =  psCleanHtmlTag(itemRow.cells[1].innerHTML.toLowerCase());
			pSku = pSku.search(/sku:\s(pid\d+)/gi);
			this.id =  psTrim(RegExp.$1);
			var pName = psGetElementsByClassName(itemRow.cells[1],"h3","product-name");
			if(psCheckArrayExist(pName))
			{
				this.name = psHtmlDecode(psCleanHtmlTag(pName[0].innerHTML));
			}			
			this.price = psCleanHtmlTag(itemRow.cells[2].innerHTML); 
			var pQuan = psGetElementsByClassName(itemRow.cells[3],"input","input-text qty");
			if(psCheckArrayExist(pQuan))
			{
				this.quantity = psGetElementValue(pQuan[0], true);
				this.quantity = psTrim(this.quantity);
			}
			// In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			this.catId = (psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id) != null)?psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id):"UNKNOWN";
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.id,this.catId)
			return true;
		}
		catch (ex) { return false; }
	}
	this.getItem5_Re = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var pSku =  psCleanHtmlTag(itemRow.cells[1].innerHTML.toLowerCase());
			pSku = pSku.search(/(pid\d+)/gi);
			this.id =  psTrim(RegExp.$1);
			var pName = psGetElementsByClassName(itemRow.cells[0],"h4","product-name");
			if(psCheckArrayExist(pName))
			{
				this.name = psHtmlDecode(psCleanHtmlTag(pName[0].innerHTML));
				this.name = psTrim(this.name)
			}			
			this.price = psCleanHtmlTag(itemRow.cells[2].innerHTML); 
			this.price = psTrim(this.price);
			var pQuan = psCleanHtmlTag(itemRow.cells[3].innerHTML);
			pQuan = pQuan.toLowerCase().search(/ordered:\s(\d+)/gi);
			this.quantity = psTrim(RegExp.$1);
			// In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			this.catId = (psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id) != null)?psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id):"UNKNOWN";
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.id,this.catId)
			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 pSku =  psCleanHtmlTag(itemRow.cells[1].innerHTML.toLowerCase());
			pSku = pSku.search(/(pid\d+)/gi);
			this.id =  psTrim(RegExp.$1);
			var pName = psGetElementsByClassName(itemRow.cells[0],"h4","product-name");
			if(psCheckArrayExist(pName))
			{
				this.name = psHtmlDecode(psCleanHtmlTag(pName[0].innerHTML));
				this.name = psTrim(this.name)
			}			
			this.price = psCleanHtmlTag(itemRow.cells[2].innerHTML); 
			this.price = psTrim(this.price);
			var pQuan = psCleanHtmlTag(itemRow.cells[3].innerHTML);
			pQuan = pQuan.toLowerCase().search(/ordered:\s(\d+)/gi);
			this.quantity = psTrim(RegExp.$1);
			// In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			this.catId = (psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id) != null)?psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id):"UNKNOWN";
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.id,this.catId)
			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);
			return true;
		}
		catch (ex) { return false; }
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			this.id = psGetOrderNumber();
			if(this.id == null)
			{
				this.id = psGenerateRandomValue();
			}
			
			var orderTable = document.getElementById("my-orders-table");
			if(psCheckElementExist(orderTable))
			{
				var rows = orderTable.rows;
				for(var i=0; i<rows.length; i++)
				{
					if(rows[i].cells.length > 1)
					{
						var firstCol = psTrim(psGetInnerText(rows[i].cells[0]));
						firstCol = psHtmlDecode(unescape(firstCol));
						var secondCol = psTrim(psGetInnerText(rows[i].cells[1]));
						if(firstCol.toLowerCase() == "order subtotal")
						{
							this.subtotal = psCleanPrice(secondCol);
						}
						else if(firstCol.toLowerCase().search(/shipping/gi) >= 0)
						{
							this.shipping = psCleanPrice(secondCol);
						}				
					}
				}
			}
			if(this.subtotal != null && this.subtotal != "null")
			{
				return true;
			}
			return false;
		}
		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: Remove all HTML tags in a string
 * RETURN: string
 */
function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : null;
}
/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
function psHtmlDecode(pValue)
{
    if (pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
    }

    return pValue;
}

/* PURPOSE: 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;
}
/********************************************************/
/* 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 ==================*/