/************************************************************************************/
/* $Revision: 121973 $
 * $Id: cmtaggingservices 90223154 - 20090612.txt 121973 2009-06-12 19:34:41Z croberts $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v7.0, 2009/06/11 
 * 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 ===============================*/
// 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_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
var G_PS_COOKIE_PRODID		 	= "PS_PRODID";
var G_PS_COOKIE_SHOP9		 	= "PS_SHOP9";
var G_PS_COOKIE_ORDER		 	= "PS_ORDER";
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;

// options for debug mode when sending tag:
// 1: only alert
// 2: only send tag
// 3: alert & send tag
var G_PS_DEBUG_MODE = 2;
/*========================= END GLOBAL VARIABLES =============================*/


/*========================== BEGIN NAVIGATION ===============================*/
if(G_PS_PATHNAME == "/index.aspx"
	|| G_PS_PATHNAME == "/")
{
	psCreatePageviewTag("Homepage", "0", null, null);
	psSetCookie(G_PS_COOKIE_CATID,"0");
}
else if(G_PS_URL_PATH.indexOf("category.aspx?catid") > -1)
{
	var pPageId = psGetValueFromBreadCrumb("ctl00_ColCenter_Categorycontent1_BreadCrumb1_lblTrail");
	var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"catid");
	psCreatePageviewTag(pPageId,pCatId, null, null);
}
else if(G_PS_URL_PATH.indexOf("productlist.aspx?catid") > -1)
{
	var pPageId = psGetValueFromBreadCrumb("ctl00_ColCenter_Productlisttop1_BreadCrumb1_lblTrail");
	var pCatId = psGetValueFromUrl(G_PS_URL_PATH,"catid");
	pCatId = (pCatId != null) ? pCatId.replace("#", "") : null;
	psCreatePageviewTag(pPageId,pCatId, null, null);
	psSetCookie(G_PS_COOKIE_CATID,psCleanCatId(pCatId));
}
else if(G_PS_PATHNAME == "/buildyourownring_diamondsnew.aspx")
{
	var pPageId = psGetValueFromBreadCrumb("BreadCrumb1_lblTrail");
	psCreatePageviewTag(pPageId,"Diamond", null, null);
	psSetCookie(G_PS_COOKIE_CATID,"Diamond");
}

else if(G_PS_PATHNAME.indexOf("productdetails.aspx") > -1)
{
	psPostProductView();
	psHijackRelatedItems();
	psHijackAddToWishList("ctl00_ColCenter_productDetail_btnAddToWishList","jewelry");
}
else if (G_PS_PATHNAME.indexOf("diamonddetails.aspx") > -1)
{
	psPostProductViewForDiamond();
	psHijackAddToWishList("ctl00_ColCenter_btnWishList","diamond");
	psHijackRecentlyDiamonds();
}
else if (G_PS_PATHNAME.indexOf("productdetailsstuds.aspx") > -1)
{
	psPostProductViewForStuds();
	psHijackAddToWishList("ctl00_ColCenter_productDetailStuds_btnAddToWishList","stud");
}
else if(G_PS_PATHNAME == "/buildyourownring_diamonddetails.aspx")
{
	var pPageId = psGetValueFromUrl(G_PS_URL_PATH,"diamondid");
	psCreatePageviewTag(pPageId,"Diamond", null, null);
}
else if(G_PS_PATHNAME.indexOf("staticpage.aspx") > -1)
{
	var pageId = psGetValueFromUrl(G_PS_URL_PATH,"page");
	pageId = pageId.replace(/\%20/gi, " ");
	if( pageId.toLowerCase() == "the factory" ||pageId.toLowerCase() == "diamond sorting" ||pageId.toLowerCase() == "wax molding"
		||pageId.toLowerCase()== "casting and oven" ||pageId.toLowerCase() == "gold casting" ||pageId.toLowerCase() == "tumbling"
		||pageId.toLowerCase() == "diamond setting" ||pageId.toLowerCase() == "polishing" ||pageId.toLowerCase() == "repair and sizing"
		||pageId.toLowerCase() == "Cleaning")
	{
		psCreatePageviewTag(pageId, "Factory", null, null);
	}
	else if(pageId.toLowerCase() == "diamondstudsearrings")
	{
		psCreatePageviewTag(pageId, "DiamondStuds", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"DiamondStuds")
	}
	
	else
	{
		psCreatePageviewTag(pageId, "Content", null, null);
	}
}
else if(G_PS_PATHNAME == "/email_friend.aspx")
{
	psCreatePageviewTag("Email Friend", "Content", null, null);
}
else if(G_PS_PATHNAME == "/laborcharges.aspx")
{
	psCreatePageviewTag("Labor Charges", "Content", null, null);
}
else if(G_PS_PATHNAME == "/contactus.aspx")
{
	psCreatePageviewTag("Contact Us", "Content", null, null);
}
else if(G_PS_PATHNAME == "/faq.aspx")
{
	psCreatePageviewTag("Faq", "Content", null, null);
}
else if(G_PS_PATHNAME == "/store.aspx")
{
	psCreatePageviewTag(psGetStoreLocation(), "Store Locations", null, null);
}
else if(G_PS_PATHNAME.indexOf("diamondresults.aspx") > -1)
{
	psCreatePageviewTag("Diamond", "Diamond", null, null);
	psSetCookie(G_PS_COOKIE_CATID,"Diamond");
}
else if(G_PS_PATHNAME == "/diamondsearch.aspx")
{
	psCreatePageviewTag("Diamond Search", "Diamond", null, null);
}
else if(G_PS_PATHNAME == "/searchresult.aspx")
{
	psGetPostSearchTag();
	psSetCookie(G_PS_COOKIE_CATID,"SEARCH");
}
else if(G_PS_PATHNAME == "/advancesearch.aspx")
{
	psCreatePageviewTag("Advance Search", "Search", null, null);
}
else if(G_PS_PATHNAME == "/customerregister.aspx")
{
	cmCreatePageviewTag("New Customer", "Account");
	psHijackCustomerRegister();
}
else if(G_PS_PATHNAME == "/customerlogin.aspx")
{
	psCreatePageviewTag("Customer Login", "Account", null, null);
	if(G_PS_URL_REFERRER.indexOf("customerregister.aspx") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psHijackOrgerIdLogin();
}
else if(G_PS_PATHNAME == "/wishlistlogin.aspx")
{
	cmCreatePageviewTag("WishList Login", "Account");
	psHijackWishListLogin();
}

else if(G_PS_PATHNAME == "/showwishlist.aspx")
{
	psSetCookie(G_PS_COOKIE_CATID,"Wish List");
	psCreatePageviewTag("WishList", "WishList", null, null);
	if(G_PS_URL_REFERRER.indexOf("wishlistlogin.aspx") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
}
else if(G_PS_PATHNAME == "/wishlist.aspx")
{
	psCreatePageviewTag("WishList", "WishList", null, null);
}
else if(G_PS_PATHNAME == "/editprofile.aspx")
{
	psCreatePageviewTag("Edit Profile", "Account", null, null);
	psHijackUpdateProfile();
	lstTable = psGetElementsByClassName(document, "div", "colcenter")[0].getElementsByTagName("table")[5];
	lstTable = psCleanHtmlTag(lstTable.innerHTML);
	if(lstTable.toLowerCase().indexOf("your profile has been updated successfully") > -1 )
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
}
else if(G_PS_PATHNAME == "/checkout.aspx")
{
	psCreatePageviewTag("Shopping Cart", "Checkout", null, null);
	psPostCartView();
	psHijackSpecialOffers();
	psHijackUpdateCart();
	psHijackCheckOut();
}
else if(G_PS_PATHNAME == "/checkoutlogin.aspx")
{
	psCreatePageviewTag("Checkout Login", "Account", null, null);
	psHijackCustomerCheckout();
	psHijackRegisterCheckout();
}
else if(G_PS_PATHNAME == "/billing_shipping.aspx")
{
	if(G_PS_URL_REFERRER.indexOf("checkoutlogin.aspx") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psCreatePageviewTag("Billing", "Checkout", null, null);
	psHijackBilllingButton("ctl00_ContentPlaceHolder1_btnCheckout1");
	psHijackBilllingButton("ctl00_ContentPlaceHolder1_btnCheckout2");
}
else if(G_PS_PATHNAME == "/finalizeorder.aspx")
{
	psCreatePageviewTag("Finalize Order", "Checkout", null, null);
	if(G_PS_URL_REFERRER.indexOf("billing_shipping.aspx") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psSetOrderTagToCookie();
}
else if(G_PS_PATHNAME == "/ordercomplete.aspx")
{	
	psCreatePageviewTag("Order complete", "Checkout", null, null)
	psPostOrderView();
	psSetCookie(G_PS_COOKIE_PROFILE, '', "delete"); 
}
else if(G_PS_PATHNAME == "/orderdetails.aspx")
{
	psCreatePageviewTag("Order Details", "Content", null, null);
	if(G_PS_URL_REFERRER.indexOf("customerlogin.aspx") > -1)
	{
		var uP = new psProfile();
		uP.readProfile(); // get user profile from cookie
		// post registration tag for update profile page
		if(uP.email != null)
			psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
}
else 
{
	psCreatePageviewTag(G_PS_PATHNAME, "ADD URL");
}

/*============================ END NAVIGATION ================================*/

/* 
 * Get pageId from the top menu
 */
function psGetPageIdTopMenu()
{
	var sResult = null;
	var arrTdLinkg = psGetElementsByClassName(document, "td", "linkg");
	if(psCheckArrayExist(arrTdLinkg) && arrTdLinkg.length > 0)
		sResult = psTrim(psCleanHtmlTag(arrTdLinkg[0].innerHTML));
	return sResult;
}
/* 
 * Get value from the BreadCrumb
 */
function psGetValueFromBreadCrumb(tagName)
{
	var breadCrumb =  psTrim(psGetElementValueById(tagName));
	if(breadCrumb.toLowerCase().indexOf("<sup") >-1 )
	{
		breadCrumb = breadCrumb.search(/(.*)\<sup/gi) > -1 ? RegExp.$1 : null;
	}
	var arrBreadCrumb = breadCrumb.toLowerCase().split("a>");
	var result = psCleanHtmlTag(arrBreadCrumb[arrBreadCrumb.length -1]).replace('>','');
	return psTrim(result);
}
/* 
 * Get product name
 */
function psGetProductName()
{
	var objName = psGetElementsByClassName(document,"td","s10");
	
	if(psCheckArrayExist(objName) && objName.length > 0)
	{
		var proName = objName[0].innerHTML;
		proName = psTrim(psHtmlDecode(psCleanHtmlTag(proName)));
	}
	return psCleanProductName(proName);
}

function psGetProductNameForDiamond()
{
	var proName  = null;
	var frmItem = document.getElementById("aspnetForm");
	if(psCheckElementExist(frmItem))
	{
		var lstPro = psGetElementsByClassName(frmItem,"td","s1");
		if(psCheckArrayExist(lstPro) && lstPro.length > 0)
		{
			proName = lstPro[0].innerHTML;
			proName = psTrim(psHtmlDecode(psCleanHtmlTag(proName)));
			proName = psCleanProductName(proName);
		}
	}
	return proName;
}

/* 
 * Find element by name
 */

function psGetStoreLocation()
{
	var lstTd = psGetElementsByClassName(document,"td","s3");
	if(psCheckArrayExist(lstTd) && lstTd.length > 3)
	{
		var proName = lstTd[3].innerHTML;
		var lstPro = proName.toLowerCase().split("<br>");
		proName = (psCheckArrayExist(lstPro) == true)?lstPro[0]:"";
		proName = psHtmlDecode(psCleanHtmlTag(proName));
		return psTrim(proName);
	}
}
/* 
 * Find element by name
 */
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)
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}
/* 
 * Hijack all products in Related Items block and set to cookie category value for them.
 */
function psHijackRelatedItems()
{
	var oRelated = document.getElementById("ctl00_ColCenter_productDetail_tblRelatedData");
	if(oRelated != null)
	{
		var pLinks = oRelated.getElementsByTagName("a");
		for (var i = 0; i < pLinks.length; i++)	
		{
			if (pLinks[i].href.search(/productDetails\.aspx\?jewelryID/gi) > -1)
			{
				var oldCMFunc = pLinks[i].onclick; //backup the existing onclick function
				pLinks[i].onclick = function()
				{
					psSetCookie(G_PS_COOKIE_CATID,"Related Items");
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,psGetValueFromUrl(this.href,"jewelryID"),"Related Items");
					if (oldCMFunc != null)
						return oldCMFunc();
				}
			}
		}
	}
}
function psHijackRecentlyDiamonds()
{
	var frmItem = document.getElementById("aspnetForm");
	if(frmItem != null)
	{
		var pLinks = frmItem.getElementsByTagName("a");
		for (var i = 0; i < pLinks.length; i++)	
		{
			if (pLinks[i].href.search(/diamonddetails\.aspx\?diamondID/gi) > -1)
			{
				var oldCMFunc = pLinks[i].onclick; //backup the existing onclick function
				pLinks[i].onclick = function()
				{
					psSetCookie(G_PS_COOKIE_CATID,"Recently Viewed Diamonds");
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,psGetValueFromUrl(this.href,"diamondID"),"Recently Viewed Diamonds");
					if (oldCMFunc != null)
						return oldCMFunc();
				}
			}
		}
	}
}
/* 
 * Hijack all products in Special Offers block and set to cookie category value for them.
 */
function psHijackSpecialOffers()
{
	var hrefs  = document.links;
	for (var i = 0; i < hrefs.length; i++)	
    {
        if (hrefs[i].href.toLowerCase().indexOf("productdetails.aspx") > -1 && hrefs[i].id == "")
        {
			var oldCMFunc = hrefs[i].onclick; //backup the existing onclick function
			hrefs[i].onclick = function()
            {	
				var proId =  psGetValueFromUrl(this.href.toLowerCase(),"jewelryid");
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID,proId,"Special Offers");
				psSetCookie(G_PS_COOKIE_CATID,"Special Offers");
				if (oldCMFunc != null)
					return oldCMFunc();
            }			
        }
    }
}
/* 
 * post a search tag.
 */
function psGetPostSearchTag()
{
	var strSearch = psGetElementsByClassName(document,"td","bar")[0].innerHTML;
	strSearch = psTrim(psHtmlDecode(psCleanHtmlTag(strSearch)));
	strSearch = strSearch.search(/(\d*)\s.*\"(.*)\"/gi) > -1 ? RegExp.$2 : null;
	var searhResult = RegExp.$1;
	if(parseInt(searhResult) == 0)
		psCreatePageviewTag("SEARCH UNSUCCESSFUL", "SEARCH", strSearch,searhResult);
	else
	{
		var page = psGetValueFromUrl(G_PS_URL_PATH,"pageindex") == null? 0 : parseInt(psGetValueFromUrl(G_PS_URL_PATH,"pageindex"));
		page = page + 1;
		psCreatePageviewTag("SEARCH SUCCESSFUL PAGE " + page, "SEARCH", strSearch,searhResult);
	}
}
/* 
 * Hijack submit button when new customer login.
 */
function psHijackCustomerRegister()
{
	var btnSubmit = document.getElementById("ctl00_ColCenter_btnSubmit");
	if (btnSubmit != null)
	{
		var oldCMFunc = btnSubmit.onclick; //backup the existing onclick function	
		btnSubmit.onclick = function()
		{
			var uP = new psProfile();
			uP.email = psTrim(psGetElementValueById("ctl00_ColCenter_newuser_txtEmail"));
			uP.city = null;
			uP.state = null;
			uP.zipcode = null;
			// store on cookie
			uP.writeProfile();
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}
/* 
 * Hijack submit button when new customer login from wishlist login.
 */
function psHijackWishListLogin()
{
	var btnLogin = document.getElementById("ctl00_ColCenter_btnLogIn");
	if (btnLogin != null)
	{
		var oldCMFunc = btnLogin.onclick; //backup the existing onclick function	
		btnLogin.onclick = function()
		{
			var uP = new psProfile();
			uP.email = psTrim(psGetElementValueById("ctl00_ColCenter_txtEmail"));
			uP.city = null;
			uP.state = null;
			uP.zipcode = null;
			// store on cookie
			uP.writeProfile();
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}
/* 
 * Hijack sigin button when new customer login after checkout step 1 if user doesn't login.
 */
function psHijackRegisterCheckout()
{
	var btnSubmit = document.getElementById("ctl00_ContentPlaceHolder1_newuser_btnSignIn");
	if (btnSubmit != null)
	{
		var oldCMFunc = btnSubmit.onclick; //backup the existing onclick function	
		btnSubmit.onclick = function()
		{
			var uP = new psProfile();
			uP.email = psTrim(psGetElementValueById("ctl00_ContentPlaceHolder1_newuser_txtEmail"));
			uP.city = null;
			uP.state = null;
			uP.zipcode = null;
			// store on cookie
			uP.writeProfile();			
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}

function psHijackCustomerCheckout()
{
	var btnLogin = document.getElementById("ctl00_ContentPlaceHolder1_btnSignIn");
	
	if (btnLogin != null)
	{
		var oldCMFunc = btnLogin.onclick; //backup the existing onclick function	
		btnLogin.onclick = function()
		{
			var uP = new psProfile();
			uP.email = psTrim(psGetElementValueById("ctl00_ContentPlaceHolder1_txtEmail"));
			uP.city = null;
			uP.state = null;
			uP.zipcode = null;
			// store on cookie
			uP.writeProfile();	
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}

function psHijackBilllingButton(btnBilling)
{
	var btnLogin = document.getElementById(btnBilling);
	if (btnLogin != null)
	{
		var oldCMFunc = btnLogin.onclick; //backup the existing onclick function
		btnLogin.onclick = function()
		{
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			uP.email = psTrim(psGetElementValueById("ctl00_ContentPlaceHolder1_txtCustomerEmail"));
			uP.city = psTrim(psGetElementValueById("ctl00_ContentPlaceHolder1_txtCustomerCity"));
			uP.state = psTrim(psGetElementValueById("ctl00_ContentPlaceHolder1_drpCustomerState"));
			uP.zipcode = psTrim(psGetElementValueById("ctl00_ContentPlaceHolder1_txtCustomerZip"));
			// store on cookie
			uP.writeProfile();
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}
/* 
 * Hijack submit button when customer update profile.
 */
function psHijackUpdateProfile()
{
	var btnSubmit = document.getElementById("ctl00_ContentPlaceHolder1_btnSubmit");
	if (btnSubmit != null)
	{
		var oldCMFunc = btnSubmit.onclick; //backup the existing onclick function	
		btnSubmit.onclick = function()
		{
			var uP = new psProfile();
			uP.email = psTrim(psGetElementValueById("ctl00_ContentPlaceHolder1_newuser_txtEmail"));
			uP.city = null;
			uP.state = null;
			uP.zipcode = null;
			// store on cookie
			uP.writeProfile();
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}
/* 
 * Hijack submit button when customer login to checked order.
 */
function psHijackOrgerIdLogin()
{
	var btnSubmit = document.getElementById("ctl00_ColCenter_btnLogIn");
	if (btnSubmit != null)
	{
		var oldCMFunc = btnSubmit.onclick; //backup the existing onclick function
		btnSubmit.onclick = function()
		{
			var uP = new psProfile();
			uP.email = psTrim(psGetElementValueById("ctl00_ColCenter_txtEmail"));
			uP.city = null;
			uP.state = null;
			uP.zipcode = null;
			// store on cookie
			uP.writeProfile();
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}

function psHijackAddToWishList(sBtnName,sTyle)
{
	var sProId = 0;
	switch (sTyle.toLowerCase())
	{
		case "jewelry": 
			sProId = psGetValueFromUrl(G_PS_URL_PATH,"jewelryid");	
			break;
		case "diamond":
			sProId = psGetValueFromUrl(G_PS_URL_PATH,"diamondid");	
			break;
		case "stud":
			sProId = psGetElementValueById("ctl00_ColCenter_productDetailStuds_ddlDiamondSize",true);
			break;
	  default: sProId = 0;
	}
	
	var btnAdd = document.getElementById(sBtnName);
	if (btnAdd != null)
	{
		var oldCMFunc = btnAdd.onclick; //backup the existing onclick function
		btnAdd.onclick = function()
		{
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID,sProId,"Wish List");
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}
function psHijackUpdateCart()
{
	var btnUpdate = document.getElementById("ctl00_ContentPlaceHolder1_btnUpdate");
	if (btnUpdate != null)
	{
		var oldCMFunc = btnUpdate.onclick; //backup the existing onclick function
		btnUpdate.onclick = function()
		{
			psSetShop9ToCookie();
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}
function psHijackCheckOut()
{
	var btnCheckout = document.getElementById("ctl00_ContentPlaceHolder1_btnCheckOut");
	if (btnCheckout != null)
	{
		var oldCMFunc = btnCheckout.onclick; //backup the existing onclick function
		btnCheckout.onclick = function()
		{
			psPostCartView();
			psSetShop9ToCookie();
			if (oldCMFunc != null)
				return oldCMFunc();
		}
	}
}

function psSetShop9ToCookie()
{
	var cartTbl = null;
	var pProId_tr=""; 
	var index=0;
	psSetCookie(G_PS_COOKIE_SHOP9," ", "delete");
    psSetCookie(G_PS_COOKIE_ORDER," ", "delete");
	
	/*
	 * Codes for locating the table containing items (each row for an item)
	 */
	var objCart = document.getElementById("ctl00_ContentPlaceHolder1_dvCart");
	if(psCheckElementExist(objCart))
	{
		var lstTable = objCart.getElementsByTagName("table");
		if(psCheckArrayExist(lstTable) && lstTable.length > 1)
		{
			cartTbl = lstTable[1];
		}
	}
	cartTbl =  (cartTbl== null) ? null : cartTbl;
	
	/*
	 * Codes for locating the table containing items (each row for an item)
	 */
	if(cartTbl)
	{
		var rows = cartTbl.rows; // use rows variable for optimization
		var prd = new psProduct();
		if(document.getElementById("ctl00_ContentPlaceHolder1_trPromocode")==null)
		{
		for (var r = 1; r < rows.length-1; r++) // item for each row
		{
			if(rows[r].cells[0].getElementsByTagName("input")[0].checked == false)
			{
				prd.getItem5(rows[r]);
				var pValueShop9 =prd.id + "|" +  prd.name + "|" + prd.quantity +"|"+ prd.price.replace("$","")+"|"+prd.catId;				
				var pProdId = prd.id + "_" + index;
				index+= 1;
				pProId_tr+= pProdId + "--";
				psSetValueToCookie(G_PS_COOKIE_SHOP9,pProdId,pValueShop9); 	
			}
		}
		}
		else
		{
			for (var r = 1; r < rows.length-3; r++) // item for each row
			{
				if(rows[r].cells[0].getElementsByTagName("input")[0].checked == false)
				{
					prd.getItem5(rows[r]);
					var pValueShop9 =prd.id + "|" +  prd.name + "|" + prd.quantity +"|"+ prd.price.replace("$","")+"|"+prd.catId;				
					var pProdId = prd.id + "_" + index;
					index+= 1;
					pProId_tr+= pProdId + "--";
					psSetValueToCookie(G_PS_COOKIE_SHOP9,pProdId,pValueShop9); 	
				}
			}
		}
	}
	psSetCookie(G_PS_COOKIE_PRODID,pProId_tr);
}

function psSetOrderTagToCookie()
{	
	var trTag=document.getElementById("title");	
	if(trTag != null)
	{
		var cusZip = null;
		var cusState = null;
		var cusCity = null;
		var cusId = null;
		var tblOrder = psGetTableFromCell("Sub Total");
		//var tblOrder = trTag.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName("table")[0];
		if(psCheckElementExist(tblOrder))
		{
			var tblLength = tblOrder.rows.length;
			if(tblOrder.rows[tblLength-4].cells[0].innerHTML.toLowerCase().indexOf("sub total") > -1)
			{
				var pSubtotal = psTrim(tblOrder.rows[tblLength-4].cells[1].innerHTML);
				var pShipping  = psTrim(tblOrder.rows[tblLength-3].cells[1].innerHTML);
			}
			else if(tblOrder.rows[tblLength-5].cells[0].innerHTML.toLowerCase().indexOf("sub total") > -1)
			{
				var pSubtotal = psTrim(tblOrder.rows[tblLength-5].cells[1].innerHTML);
				var pShipping  = psTrim(tblOrder.rows[tblLength-4].cells[1].innerHTML);
			}
			var uP = new psProfile();
			uP.readProfile(); // get user profile from cookie
			if(uP.email != null)
			{
				cusId = uP.email;
				cusZip = uP.zipcode;
				cusState = uP.state;
				cusCity = uP.city;
			}
			var pValueOrder =  pSubtotal.replace("$","") + ":" + pShipping.replace("$","") + ":" + cusCity + ":" + cusState + ":" + cusZip + ":" + cusId;					
			psSetCookie(G_PS_COOKIE_ORDER,pValueOrder);	
			
		}
	}
}

function psGetPostOfCellByName(pTable,pCellName)
{
	if(psCheckElementExist(pTable))
	{
		pRow = pTable.rows[0];
		if(pRow!=null && pRow.cells.length > 0)
		{
			for(var j =0 ; j < pRow.cells.length ; j++)
			{
				if(psTrim(pRow.cells[j].innerHTML.toLowerCase()) == psTrim(pCellName.toLowerCase()))
					return j;
			}
		}
	}
	return 0;
}

function psGetTableFromCell(pCellName)
{
	var sTblRe = null;
	var lstTable = document.getElementsByTagName("table");
	if(psCheckArrayExist(lstTable))
	{
		for (var j=0; j<lstTable.length; j++)	
		{
			var sRows = lstTable[j].rows; // use rows variable for optimization
			for(var i=0; i< sRows.length; i++)
			{
				for(var t=0; t<sRows[i].cells.length; t++)
				{
					var sHeader = psCleanHtmlTag(sRows[i].cells[t].innerHTML);
					if (sHeader.toLowerCase().indexOf(pCellName.toLowerCase()) > -1)
					{
						//we need catch the lastest of table so can't put a break 
						sTblRe = lstTable[j];			
					}
				}
			}
		}
	}
	return sTblRe;
}
/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	prd.getProduct();
	// Post product view tag
	psCreateProductviewTag(prd.id, prd.name, prd.catId);
	// Store productId along with catId to cookie for use later in shop5 and shop9 views
	psSetValueToCookie(G_PS_COOKIE_PROD_CATID, prd.id, prd.catId);
}

function psPostProductViewForDiamond()
{
	var prd = new psProduct();
	prd.getProductForDiamond();
	// Post product view tag
	psCreateProductviewTag(prd.id, prd.name, prd.catId);
	// Store productId along with catId to cookie for use later in shop5 and shop9 views
	psSetValueToCookie(G_PS_COOKIE_PROD_CATID, prd.id, prd.catId);
}
function psPostProductViewForStuds()
{
	var prd = new psProduct();
	prd.getProductForStuds();
	// Post product view tag
	psCreateProductviewTag(prd.id, prd.name, prd.catId);
	// Store productId along with catId to cookie for use later in shop5 and shop9 views
	psSetValueToCookie(G_PS_COOKIE_PROD_CATID, prd.id, prd.catId);
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	/*
	 * Codes for posting pageview
	 */
	var cartTbl = null;
	/*
	 * Codes for locating the table containing items (each row for an item)
	 */
	var objCart = document.getElementById("ctl00_ContentPlaceHolder1_dvCart");
	if(psCheckElementExist(objCart))
	{
		var lstTable = objCart.getElementsByTagName("table");
		if(psCheckArrayExist(lstTable) && lstTable.length > 1)
		{
			cartTbl = lstTable[1];
		}
	}
	cartTbl =  (cartTbl== null) ? null : cartTbl;
	if(cartTbl)
	{
		var rows = cartTbl.rows; // use rows variable for optimization
		var prd = new psProduct();
		if(document.getElementById("ctl00_ContentPlaceHolder1_trPromocode")==null)
		{
			for (var r = 1; r < rows.length-1; r++) // item for each row
			{
				/*
				 * Codes for skipping exceptional rows (rows don't contain items)
				 */
				var lstInput = rows[r].cells[0].getElementsByTagName("input");
				if(psCheckArrayExist(lstInput))
				{
					if(lstInput[0].checked == false)
					{
						prd.getItem5(rows[r]);
					// Post shop5tag
						psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
					}
				}
			}
		}
		else
		{
			for (var r = 1; r < rows.length-3; r++) // item for each row
			{
				/*
				 * Codes for skipping exceptional rows (rows don't contain items)
				 */
				var lstInput = rows[r].cells[0].getElementsByTagName("input");
				if(psCheckArrayExist(lstInput))
				{
					if(lstInput[0].checked == false)
					{
						prd.getItem5(rows[r]);
					// Post shop5tag
						psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
					}
				}
			}		
		}
	}
	
	// Make sure to have actual postings
	psDisplayShop5s();
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	var ord = new psOrder();
	var prd = new psProduct();

	ord.getOrder(); // Get order info from source code
	// Post Pageviewtag as cartview
	var strProductId = psGetCookie(G_PS_COOKIE_PRODID);
	if(strProductId != null)
	{
		var arrProduct = strProductId.split("--");	

		for(var i=0; i<=arrProduct.length;i++)
		{
			if (arrProduct[i] != null && arrProduct[i] != "")
			{
				prd.getItem9(arrProduct[i]);
		
				// Post shop9tag
				psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, ord.cusId, ord.id, ord.subtotal, prd.catId);
			}
		}
		// Make sure to have actual postings
		psDisplayShop9s();
		// Post order tag finally
		psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, ord.cusId, ord.cusCity, ord.cusState, ord.cusZIP);
	}
	// Delete cookie after checking successfully
	psSetCookie(G_PS_COOKIE_CATID,"", "delete");
	psSetCookie(G_PS_COOKIE_PROD_CATID,"", "delete");	
	psSetCookie(G_PS_COOKIE_PRODID,"", "delete"); 
	psSetCookie(G_PS_COOKIE_SHOP9,"", "delete");	
	psSetCookie(G_PS_COOKIE_ORDER,"", "delete");	
}
// 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;
}
/*====================== 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(pId, pName, pCatId, pPrice, pQuantity)
{
    this.id = pId;
    this.name = pName;
    this.catId = pCatId;
    this.price = pPrice;
    this.quantity = pQuantity;
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.id = psGetValueFromUrl(G_PS_URL_PATH,"jewelryid");
			this.name = psGetProductName();
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
			if(G_PS_URL_REFERRER.indexOf("checkout.aspx") > -1 && psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id) != null)
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
			else 
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
			this.catId = (this.catId != null) ? this.catId : "BOOKMARK";
			this.catId = (this.catId != null) ? this.catId.replace("#", "") : null;
			return true;
		}
		catch (ex) { return false; }
	}
	
	this.getProductForDiamond = function()
	{
		try
		{
			this.id = psGetValueFromUrl(G_PS_URL_PATH,"diamondid");
			this.name = psGetProductNameForDiamond();
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
			if(G_PS_URL_REFERRER.indexOf("checkout.aspx") > -1 && psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id) != null)
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
			else 
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
			this.catId = (this.catId != null) ? this.catId : "BOOKMARK";
			this.catId = (this.catId != null) ? this.catId.replace("#", "") : null;
			return true;
		}
		catch (ex) { return false; }
	}
	this.getProductForStuds = function()
	{
		try
		{
			this.id = psGetElementValueById("ctl00_ColCenter_productDetailStuds_ddlDiamondSize",true);
			this.name = psGetProductName();
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
			if(G_PS_URL_REFERRER.indexOf("checkout.aspx") > -1 && psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id) != null)
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
			else 
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
			this.catId = (this.catId != null) ? this.catId : "BOOKMARK";
			this.catId = (this.catId != null) ? this.catId.replace("#", "") : null;
			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
		{
			var proName = psTrim(psCleanHtmlTag(itemRow.cells[2].innerHTML))
			proName = proName.search(/(.*)\(\D*(\d*)\,/gi) > -1 ? RegExp.$1 : null;
			this.id = RegExp.$2;
			this.name = psTrim(psCleanProductName(proName));
			var price =psTrim(psCleanHtmlTag(itemRow.cells[5].innerHTML));
			var retailPrice  = price.search(/Retail Price\s\:\s\$\s(\d*)/gi) > -1 ? RegExp.$1 : null;
			var factoryPrice  = price.search(/Factory Direct Price\s\:\s\$\s(\d*)/gi) > -1 ? RegExp.$1 : null;
			this.price = retailPrice == factoryPrice?retailPrice : factoryPrice;
			this.quantity =  psGetElementValue(itemRow.cells[4].getElementsByTagName("select")[0],"true");
			// 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) : "0";
			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
		{
			var strValue = psGetValueFromCookie(G_PS_COOKIE_SHOP9,itemRow);	
			var arrValue = 	strValue.split("|");		
			this.id = arrValue[0]; 
			this.name = arrValue[1]; 
			this.quantity =  arrValue[2]; 
			this.price =  arrValue[3]; 
			this.catId = arrValue[4];
		}
		catch (ex) { return false; }
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */

function psProfile()
{
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.email = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.email != null)
			{
				var buf = this.email.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				this.email = buf[0];
				this.city = buf[1];
				this.state = buf[2];
				this.zipcode = buf[3];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		if (this.email == null)
			return;
		// make sure that the data contains 4 parts separated by 3 '|'
		var data = this.email + '|' + this.city + '|' + this.state + '|' + this.zipcode;
		// store on cookie
		psSetCookie(G_PS_COOKIE_PROFILE, data);
	}
}
/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder(pOrderId, pSubtotal, pShipping, pCusId, pcusCity, pcusState, pcusZIP){
	this.id = pOrderId;
	this.subtotal = pSubtotal;
	this.shipping = pShipping;
	this.cusId = pCusId;
	this.cusCity = pcusCity;
	this.cusState = pcusState;
	this.cusZIP = pcusZIP;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			this.id = psGetValueFromUrl(G_PS_URL_PATH,"oid");
			var pValue = psGetCookie(G_PS_COOKIE_ORDER);
			if(pValue != null)
			{
				var arrValue = 	pValue.split(":");
				this.subtotal = arrValue[0] == "null"?null:arrValue[0].replace("$","");
				this.shipping = arrValue[1] == "null"?null:arrValue[1].replace("$","");
				this.cusCity = arrValue[2] == "null"?null:arrValue[2];
				this.cusState = arrValue[3]== "null"?null:arrValue[3];
				this.cusZIP = arrValue[4] == "null"?null:arrValue[4];		
				this.cusId =  arrValue[5] == "null"?null:arrValue[5];
			}
			if (!this.id)
			{
				this.id = psGenerateRandomValue();
			}
			
			if (!this.cusId)
			{
				this.cusId = this.id;
			}
			
			 return true;
		}catch (ex) {return false;}
	}
}
/* 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 HTML tags in a string
 * RETURN: string
 */
function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : null;
}

/* PURPOSE: Remove all leading & trailing spaces of a string
 * Note: [&nbsp;] is also considered as a space
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;
	return (pStr != null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

/* PURPOSE: extract value from the URL
 * in format of http://xxx.com/page.ext?key1=value1&key2=value2
 * or key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
function psGetValueFromUrl(pUrl, pKey)
{
	pUrl = (pUrl != null) ? "?" + psTrim(pUrl.toLowerCase()) : null;
	pKey = (pKey != null) ? psTrim(pKey.toLowerCase()) : null;

	if (pUrl == null || pKey == null || pUrl.indexOf(pKey) == -1) 
		return null;
	
	var start = pUrl.indexOf('&' + pKey + '=');
	start = (start == -1) ? pUrl.indexOf('?' + pKey + '=') : start;
	if (start >= 0)
	{
		start = start + pKey.length;
		var end = pUrl.indexOf("&", start);
		if(end == -1) 
			end = pUrl.length;
		var middle = pUrl.indexOf("=", start);
		return pUrl.substring(middle + 1, end);
	}
	return null;
}

/* PURPOSE: returns the value of an element based on element_id
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 */
function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}

/* PURPOSE: returns the value of an element based on element object
 * Note: this function returns decoded text
 * to avoid "double" decode, don't invoke psHtmlDecode on returned value again
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 *  NULL: if element not exist
 */
function psGetElementValue(pTagObj, pValueFlag)
{
    var tagValue = null;
    if (pTagObj != null)
    {
        if (pTagObj.tagName.search(/^INPUT$/i) > -1)
            tagValue = pTagObj.value;
        else if (pTagObj.tagName.search(/^SELECT$/i) > -1)
        {
            if (pValueFlag == true)
                tagValue = pTagObj.options[pTagObj.selectedIndex].value;
            else
                tagValue = psHtmlDecode(pTagObj.options[pTagObj.selectedIndex].innerHTML);// return label instead of value
        }
        else
            tagValue = psHtmlDecode(pTagObj.innerHTML);
    }

    return tagValue;
}

/* PURPOSE: validate email format
 * RETURN: boolean
 */
function psCheckEmail(pEmail) 
{
    if (pEmail)
    {
        var i = pEmail.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
        return (i > -1);
    }

    return false;
}

/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
function psHtmlDecode(pValue)
{
    if (pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
    }

    return pValue;
}

/* PURPOSE: 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,pDomain)
{
	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)
	{
		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;
}
/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dtDate = new Date();
	var cusRandom = (dtDate.getTime()%10000000) + (Math.floor(Math.random()*10000));
	return cusRandom;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pageID, categoryID, searchString, searchResults) 
{
	pageID=psCleanPageId(pageID);
	categoryID=psCleanCatId(categoryID);
    if (searchResults != null)
        searchResults += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pageID + ", " + categoryID + ", " + searchString + ", " + searchResults + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pageID, categoryID, searchString, searchResults);
}

function psCreateProductviewTag(productID, productName, categoryID) 
{
	productName = psCleanProductName(productName);
	categoryID=psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + productID + ", " + productName + ", " + categoryID + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(productID, productName, categoryID);
}

function psCreateShopAction5Tag(productID, productName, productQuantity, productPrice, categoryID) 
{
	productName = psCleanProductName(productName);
	categoryID=psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + productID + ", " + productName + ", " + productQuantity + ", " + productPrice + ", " + categoryID + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(productID, productName, productQuantity, productPrice, categoryID);
    
}

function psCreateShopAction9Tag(productID, productName, productQuantity, productPrice, customerID, orderID, orderTotal, categoryID) 
{
	productName = psCleanProductName(productName);
	categoryID=psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + productID + ", " + productName + ", " + productQuantity + ", " + productPrice + ", " + customerID + ", " + orderID + ", " + orderTotal + ", " + categoryID + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(productID, productName, productQuantity, productPrice, customerID, orderID, orderTotal, categoryID);
}

function psCreateOrderTag(orderID, orderTotal, orderShipping, customerID, customerCity, customerState, customerZIP) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + orderID + ", " + orderTotal + ", " + orderShipping + ", " + customerID + ", " + customerCity + ", " + customerState + ", " + customerZIP + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(orderID, orderTotal, orderShipping, customerID, customerCity, customerState, customerZIP);
}

function psCreateConversionEventTag(eventID, actionType, categoryID, points) 
{
	categoryID=psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + eventID + ", " + actionType + ", " + categoryID + ", " + points + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(eventID, actionType, categoryID, points);
}

function psCreateRegistrationTag(customerID, customerEmail, customerCity,
				customerState, customerZIP, newsletterName, 
				subscribe) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + customerID + ", " + customerEmail + ", " + customerCity + ", " + customerState + ", " + customerZIP + ", " + newsletterName + ", " + subscribe + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(customerID, customerEmail, customerCity, customerState, customerZIP, newsletterName, subscribe);
}

function psCreateErrorTag(pageID, categoryID) 
{
	pageID=psCleanPageId(pageID);
	categoryID=psCleanCatId(categoryID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateErrorTag(" + pageID + ", " + categoryID + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateErrorTag(pageID, categoryID);
}

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 ==================*/
