/************************************************************************************/
/* $Revision: 140590 $
 * $Id: cmtaggingservices.js.txt 140590 2010-03-08 18:30:46Z lhibbard $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.3, 2010/03/12
 * 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("carsondellosa.com");//value must be one array of domains or null // change to carsondellosa.com for production

// current page url
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_URL_REFERRER = document.referrer.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000; // 5*24*60*60 = 5 days
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
var G_PS_COOKIE_PROID = "PS_LST_PROID";
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var G_PS_CM_VC_QSKEY = "CM_VC";
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!.
psCheckForSearchEnter();
if(psGetDomain(G_PS_URL_PATH).indexOf("teacher-supplies.carsondellosa.com")>-1)
{
	if(G_PS_URL_PATH == "http://teacher-supplies.carsondellosa.com/"
		|| G_PS_URL_PATH == "http://www.teacher-supplies.carsondellosa.com/")
	{
		psCreatePageviewTag("Popular Products", "10000",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_URL_PATH.indexOf("teacher-supplies.carsondellosa.com/teachingsupplies/") >-1)
	{
		var sPageId = psGetTeachingSupplies();
		var sCatId = sPageId.replace(/\s*/gi,"");
		psCreatePageviewTag(sPageId, sCatId,null,null );
		psHijackAddToCartSearch(sCatId);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_URL_PATH.indexOf("teacher-supplies.carsondellosa.com/search") > -1)
	{
		var sCatId = "10001";
		if (psIsSearchView() && psGetCookie(G_PS_COOKIE_CATID) == "10001")
		{
			psPostSearchView();
			psSetCookie(G_PS_COOKIE_CATID,sCatId);
			psHijackAddToCartSearch(sCatId);
		}
		else 
		{
			sCatId = psGetCatIdForCatalogSearch();
			if(psCheckElementExist(sCatId))
			{
				sCatId = sCatId.replace(/\s*/gi,"");
				psCreatePageviewTag(psGetPageIdForCatalogSearch(), sCatId, null, null);
			}
			else 
			{
				var sPageID  = psGetSearchTerm();
				if(psCheckElementExist(sPageID))
				{
					var lstTerm = sPageID.split(",");
					if(psCheckArrayExist(lstTerm))
					{
						sCatId = lstTerm[0];
						sCatId = sCatId.replace(/\s*/gi,"");
						psCreatePageviewTag(sPageID,psTrim(sCatId), null, null);
					}
				}
			}
			psHijackAddToCartSearch(sCatId);
			psSetCookie(G_PS_COOKIE_CATID,"","delete");
		}
	}
}
else if(psGetDomain(G_PS_URL_PATH).indexOf("carsondellosa.com")>-1)  // change to carsondellosa.com for production
{
	if(psIsLoginSuccess())
	{
		psPostRegistration();
	}	
	if(G_PS_URL_PATH == "http://www.carsondellosa.com/cd2/default.aspx"
		||G_PS_URL_PATH == "http://carsondellosa.com/cd2/default.aspx"
		||G_PS_URL_PATH == "https://www.carsondellosa.com/cd2/default.aspx"
		||G_PS_URL_PATH == "https://carsondellosa.com/cd2/default.aspx"
     	||G_PS_URL_PATH == "https://commerce-webdev:8050/cd2/default.aspx"
		||G_PS_URL_PATH == "http://commerce-webdev/cd2/default.aspx")

	{
		psCreatePageviewTag("Home", "10000", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/teacherquickorderpad.aspx")
	{
		psCreatePageviewTag(psGetDocTitle(), "QuickOrderPad", null, null);
		psHijackQuickOrder("ctl00_ctl00_LeftNavMainContent_MainContent_btnAddToCart");
		psHijackQuickOrder("ctl00_ctl00_LeftNavMainContent_MainContent_btnToCart");
		if(psIsQuickOrderSucc())
		{
			var lstProId = psGetCookie(G_PS_COOKIE_PROID);
			if(psCheckElementExist(lstProId))
			{
				lstId = lstProId.split("-_-");
				if(psCheckArrayExist(lstId))
				{
					for(var i=0; i< lstId.length ; i++)
					{
						if(lstId[i] != "" && lstId[i] != "null" && lstId[i] != null)
						{
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID, lstId[i], "QuickOrderPad");
						}
					}
				}
			}
		}
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cdsignup/welcomenewteachers.aspx")
	{
		psCreatePageviewTag("welcome new teachers", "10000", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cdsignup/thankyouforsigningup.aspx")
	{
		psPostRegistrationNew();
		psCreatePageviewTag("thank you for signing up", "10000", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/correlations/teachercorrelationproductsearch.aspx")
	{
		psCreatePageviewTag("teacher correlation product search", "10000", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/correlations/correlationssearchproducts.aspx")
	{
		psCreatePageviewTag("correlations search products", "10000", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/correlations/teachercorrelationproductview.aspx"
			|| G_PS_PATHNAME == "/cd2/correlations/teachercorrelationproductviewlearnunit.aspx")
	{
		psSendCorrelatedPros();
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/posignup/poregister.aspx")	
	{
		psCreatePageviewTag("poregister", "10000",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(psIsContentPage())
	{
		psCreatePageviewTag(psGetPageIdForContent(), "10000", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/forms/catalog_main.aspx"
			|| G_PS_PATHNAME == "/cd2/locator/main.aspx"
			|| G_PS_PATHNAME == "/cdsignup/quickjoin.aspx")
	{
		psCreatePageviewTag(psGetDocTitle(), "10000", null, null);
		psPostRegistrationNew();        //DCADDED 06102010
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/siteerror.aspx")
	{
		psCreatePageviewTag("Error", "10000", null, null);
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/searchresults.aspx")
	{
		var sMsg = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_lblResultMessage");
		if(psCheckElementExist(sMsg))
		{
			var sText = psCleanHtmlTag(psHtmlDecode(sMsg.innerHTML.toLowerCase()));
			if(sText.search(/search\sfound\s(\d*)\sresults/gi) > -1)
			{
				if(RegExp.$1 == 0 || RegExp.$1 == "0")
					psCreatePageviewTag("SEARCH UNSUCCESSFUL", "10001", psGetValueFromUrl(G_PS_URL_PATH,"KeyWords"),"0");
				else if(psCheckElementExist(RegExp.$1) && RegExp.$1 != "")
					psCreatePageviewTag("SEARCH SUCCESSFUL", "10001", psGetValueFromUrl(G_PS_URL_PATH,"KeyWords"),unescape(RegExp.$1));
				psSetCookie(G_PS_COOKIE_CATID,"","delete");
			}
		}
	}
	else if(psIsProductView(G_PS_URL_PATH))
	{
		psPostProductView();
		psHijackCoordinatingPros();
	}
	else if(psIsCartView())
	{
		psPostCartView();
		psHijackCartAndWishListPro("cart");
	}
	//added by Khanh Trinh for Checkout by Guest User
	else if(G_PS_URL_PATH.indexOf("carsondellosa.com/cd2/user/login.aspx?referrer=shoppingcart")>-1
			&& psCheckElementExist(document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_CheckoutHeader")))
	{
		psCreatePageviewTag("Billing Information", "10005",null,null )
		psHijackGuestCheckoutEmail();
	}
	else if(G_PS_PATHNAME == "/cd2/checkout/default.aspx"
			|| G_PS_PATHNAME == "/cd2/anoncheckout/default.aspx")
	{
		var checkoutStep = psGetCheckoutStep();	
		if(checkoutStep != null && checkoutStep.toLowerCase() == "confirmation")
		{		
			psCreatePageviewTag("Confirmation", "10005",null,null )
			psGetBillingAddress();
		}
		else if(checkoutStep != null && checkoutStep.toLowerCase() == "billing")
		{		
			psCreatePageviewTag("Billing Information", "10005",null,null )
			psHijackGuestCheckoutEmail();
		}
		else if(checkoutStep != null && checkoutStep.toLowerCase() == "payment")
		{		
			psCreatePageviewTag("Payment Info", "10005",null,null )
		}
		else if(checkoutStep != null && checkoutStep.toLowerCase() == "shipping")
		{		
			psCreatePageviewTag("Shipping", "10005",null,null )
		}
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/default.aspx")	
	{
		psCreatePageviewTag("My Account", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/addressbook.aspx")	
	{
		psCreatePageviewTag("Address Book", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/general.aspx")	
	{
		psCreatePageviewTag("Change General", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/changelogin.aspx")	
	{
		psCreatePageviewTag("Change Login", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/payment.aspx")	
	{
		psCreatePageviewTag("Payment Methods", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/changepassword.aspx")	
	{
		psCreatePageviewTag("Change Password", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/changequestion.aspx")	
	{
		psCreatePageviewTag("Change Question", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/orderhistory.aspx")	
	{
		psCreatePageviewTag("order history", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/orderdetail.aspx")	
	{
		psCreatePageviewTag("order detail", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/saveforlater.aspx")	
	{
		psCreatePageviewTag("save for later", "10007",null,null );
		psHijackCartAndWishListPro("wishlist");
		psHijackWishListPro();
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/manageebooks.aspx")	
	{
		psCreatePageviewTag("manage ebooks", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd2/profile/options.aspx")	
	{
		psCreatePageviewTag("Express Checkout Option", "10007",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME == "/cd_dealer/user/newdealer.aspx")	
	{
		psCreatePageviewTag("New Dealer", "10000",null,null );
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	
	else if(psIsOrderView())
	{
		psPostOrderView();
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(G_PS_PATHNAME.search(/\/cd2\/user\/(login|register)\.asp/i) >= 0)
	{
		// For both login and register pages
		psCreatePageviewTag("Log In", "10007",null,null );
		psHijackRegistration();
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
	else if(psIsTopMenuPage()
		|| G_PS_PATHNAME ==  "/cd2/browse.aspx")
	{
		var catId = psGetLastedFromCrumb();
		if(psCheckElementExist(catId))
		{
			catId = catId.replace(/\s+/gi,"");
			if(psCheckElementExist(catId))
			{
			//	psCreatePageviewTag("CATEGORY:" + psGetLastedFromCrumb(), catId, null, null); //DC07202010 commented this line and added below
			    psCreatePageviewTag("CATEGORY:" + psGetLastedFromCrumb(), psGetCatFromElement(), null, null);
			}
			psHijackAddToCartCatelog(catId);
		}
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
    }
    else if (G_PS_PATHNAME == "/cd2/searchcatalog.aspx") {
        var catId = getQuerystringValue(G_PS_CM_VC_QSKEY);
        if (catId) {
            if (psCheckElementExist(catId)) {
                catId = catId.replace(/\s+/gi, "");
                if (psCheckElementExist(catId)) {
                    //	psCreatePageviewTag("CATEGORY:" + psGetLastedFromCrumb(), catId, null, null); //DC07202010 commented this line and added below
                    psCreatePageviewTag("CATEGORY:" + catId, catId, null, null);
                }
                psHijackAddToCartCatelog(catId);
            }
            psSetCookie(G_PS_COOKIE_CATID, "", "delete");
        }
    }
	else if(G_PS_PATHNAME == "/cd2/search.aspx")
	{
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
		psCreatePageviewTag("Advanced search","10000",null,null);
		psHijackAdvancedSearch();
	}
	
	else if(G_PS_PATHNAME == "/cd2/locator/international.aspx"
			||G_PS_PATHNAME == "/cd2/forms/psuggest.aspx" )
	{
		psCreatePageviewTag(psGetPageIdFromUrl(G_PS_URL_PATH),"10000",null,null);
	}
	
	else if(G_PS_PATHNAME == "/cd2/contest/cdscotchcontest.aspx")
	{
		psCreatePageviewTag(psGetPageIdFromUrl(G_PS_URL_PATH),"10000",null,null);
	}
	
	else if(G_PS_PATHNAME == "/cd2/User/RecoverPassword.aspx")
	{
		psCreatePageviewTag(psGetPageIdFromUrl(G_PS_URL_PATH),"10007",null,null);
	}
	
	else if(G_PS_PATHNAME == "/cd2/Forms/custservicemail.aspx")
	{
		psCreatePageviewTag(psGetPageIdFromUrl(G_PS_URL_PATH),"10000",null,null);
	}

    else if(G_PS_PATHNAME == "/cd2/ebooks/downloadtemplate.aspx")
	{
		psCreatePageviewTag("Download My eBooks","eBooks",null,null);
	}

   else if(G_PS_PATHNAME == "/cd2/posignup/poreview.aspx")
	{
		psCreatePageviewTag("PO Review","10000",null,null);
	}

 else if(G_PS_PATHNAME == "/cd2/posignup/poinstselect.aspx")
	{
		psCreatePageviewTag("PO Institution Select","10000",null,null);
	}

 else if(G_PS_PATHNAME == "/cd2/posignup/poconfirmation.aspx")
	{
		psCreatePageviewTag("PO Confirmation","10000",null,null);
	}

else if(G_PS_PATHNAME == "/cd2/posignup/profileinfo.aspx")
	{
		psCreatePageviewTag("Please tell us more","10000",null,null);
	}

else if(G_PS_PATHNAME == "/cd2/forms/custservicemail.aspx")
	{
		psCreatePageviewTag("Email Customer Service","10000",null,null);
	}

else if(G_PS_PATHNAME == "/cd2/wallofhonor/honorlistingpage.aspx")
	{
		psCreatePageviewTag("Wall of Honor","10000",null,null);
	}

else if(G_PS_PATHNAME == "/cd2/pagenotfound.aspx")
	{
		psCreatePageviewTag("Page not found","10000",null,null);
	}

else if(G_PS_PATHNAME == "/cdsignup/unsubscribe.aspx")
	{
		psCreatePageviewTag("Unsubscribe","10000",null,null);
	}

else if(G_PS_PATHNAME == "/cdsignup/profileinfo.aspx")
	{
		psCreatePageviewTag("Profile Info","10000",null,null);
	}

else if(G_PS_PATHNAME == "/cd2/wallofhonor/honorentryform.aspx")
	{
		psCreatePageviewTag("Wall of Honor Entry Form","10000",null,null);
	}

else if(G_PS_PATHNAME == "cd2/contest/sweepsvideo.html")
	{
		psCreatePageviewTag("Scotch Video","10000",null,null);
	}



	
	else 
	{	
		psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
		psSetCookie(G_PS_COOKIE_CATID,"","delete");
	}
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	var tblSearch = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ResultsPanel");
	if(psCheckElementExist(tblSearch))
	{
		var sText = psCleanHtmlTag(tblSearch.innerHTML);
		if(sText.search(/(\d+)\sSearch\sResults\sfor/gi) > -1)
		{
			return true;
		}
	}
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView(sPath)
{
	if(sPath.search(/\/Products\/[^\/]+\/PID-/gi) > -1
		||sPath.search(/\/cd2\/Products\.aspx/gi) > -1
		||sPath.search(/ProductView.aspx/gi) > -1) // DCAdded 06232010
		return true;
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_PATHNAME == "/cd2/cart.aspx")
		return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_PATHNAME == "/cd2/checkout/receipttemplate.aspx" || G_PS_PATHNAME == "/cd2/anoncheckout/receipttemplate.aspx")
		return true;
	return false;
}


/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/

function getQuerystringValue(key, default_) 
{
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(document.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

function psGetLastedFromCrumb()
{
	var oCrumb = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_Breadcrumbs");
	if(psCheckElementExist(oCrumb))
	{
		var sSpan = oCrumb.getElementsByTagName("span")
		if(psCheckArrayExist(sSpan))
		{
			for(var i = sSpan.length-1; i >= 0; i--)
			{
				var sLasted = psTrim(psCleanHtmlTag(psHtmlDecode(sSpan[i].innerHTML)));
				if(sLasted != "")
				{
					return  sLasted;
				}
			}
			
		}
	}
	return null;
}

function psGetProCatFromCrumb()
{
	var sResult = null;
	var oCrumb = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_Breadcrumbs");
	if(psCheckElementExist(oCrumb))
	{
		var sSpan = oCrumb.getElementsByTagName("span")
		if(psCheckArrayExist(sSpan))
		{
			for(var i = sSpan.length-1; i >= 0; i--)
			{
				if(psTrim(psHtmlDecode(sSpan[i].innerHTML)) != "")
				{
					var j = i-1;
					while(psTrim(psCleanHtmlTag(psHtmlDecode(sSpan[j].innerHTML))) == "" || psTrim(psCleanHtmlTag(psHtmlDecode(sSpan[j].innerHTML))) == ">")
					{
						j--;
					}

					sResult = psTrim(psCleanHtmlTag(psHtmlDecode(sSpan[j].innerHTML)));
					sResult = sResult.replace(/[\s\-\,]/gi,"") ;
					return sResult;
				}
			}
			
		}
	}
	return sResult;
}

function psGetCatIdForTopMenu()
{
	var result = null;
	sPath = psMoveLastSlash(G_PS_PATHNAME); 
	var lstPath = sPath.split("/");
	if(psCheckArrayExist(lstPath))
	{
		result = (lstPath.length>1)?psTrim(lstPath[lstPath.length-2]):null;		
	}
	return (result!=null)?unescape(result):null;
}

function psMoveLastSlash(sText)
{
	var result = sText;
	var last_char = sText.charAt(sText.length - 1);
	if(last_char == "/")
		result = sText.substring(0,sText.length - 1); 
	return result;

}

function psIsTopMenuPage()
{
	var fileName = psGetPageIdFromUrl(G_PS_PATHNAME);
	if(psCheckElementExist(fileName) && fileName.toLowerCase() == "default")
	{
		var holderName = psGetValueFromUrl(G_PS_URL_PATH,"HolderName");
		if(psCheckElementExist(holderName) == false)
			return true;
	}
	return false;
}

function psIsContentPage()
{
	var holderName = psGetValueFromUrl(G_PS_URL_PATH,"HolderName");
	if(psCheckElementExist(holderName))
		return true;
	return false;
}

function psGetPageIdForContent()
{
	var holderName = psGetValueFromUrl(G_PS_URL_PATH,"HolderName");
	if(psCheckElementExist(holderName))
	{
		if(holderName.search(/([^\#\?]+)/gi)>-1 )
		{
			return RegExp.$1;
		}
	}
	return null;
}

function psGetDocTitle()
{
	var sTitle = null;
	var lstTitle = document.getElementsByTagName("title");
	if(psCheckArrayExist(lstTitle))
	{
		sTitle = lstTitle[0].innerHTML;
		sTitle = psTrim(psCleanHtmlTag(psHtmlDecode(sTitle)));
	}
	return sTitle;
}
/*
 * Get pageId 
*/
function psGetPageIdFromUrl(sPath)
{
	var sPageId = sPath.substring(sPath.lastIndexOf("/")+1, sPath.lastIndexOf("."));
	return sPageId;
}	
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;
}

/*
 * 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 psPostSearchView()
{
	psGetCurrentPage()	;
	// Your logic of throwing pageview tag for search functionalities goes here
	G_PS_CUR_CATID = "10001";
	var pageId = null;
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(sResult!= 0 || sResult!= "0")
	{
		var pPageNo = psGetCurrentPage();
		pageId = "SEARCH SUCCESSFUL " + "PAGE " + pPageNo;
		
	}
	else 
	{
		pageId = "SEARCH UNSUCCESSFUL"
	}
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	var tblSearch = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ResultsPanel");
	if(psCheckElementExist(tblSearch))
	{
		var sText = psCleanHtmlTag(psHtmlDecode(tblSearch.innerHTML));
		if(sText.search(/(\d+)\sSearch\sResults\sfor(.*)[\n]?/gi) > -1)
		{
			term = RegExp.$2;
			term = term.replace(/\s>/gi,",");
		}
	}
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	var tblSearch = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ResultsPanel");
	if(psCheckElementExist(tblSearch))
	{
		var sText = psCleanHtmlTag(psHtmlDecode(tblSearch.innerHTML));
		if(sText.search(/of\s(\d+)\sSearch\sResults\sfor/gi) > -1)
		{
			result = RegExp.$1;
		}
	}
	return result;
}

function psHijackAdvancedSearch()
{
	var btnSearch = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_SearchButton");
	if(psCheckElementExist(btnSearch))
	{
		btnSearch.oldCMFunc = btnSearch.onclick;
		btnSearch.onclick = function()
		{
			psSetCookie(G_PS_COOKIE_CATID,"10001");
			if(psCheckElementExist(this.oldCMFunc))
				return this.oldCMFunc();
		}		
	}		
}

function psCheckForSearchEnter()
{
	var searchBox = document.getElementById("ctl00_SearchTextBox");
	var searchFrm = document.getElementById("aspnetForm");
	searchBox = psCheckElementExist(searchBox)?searchBox:document.getElementById("sli_search_1");
	if(psCheckElementExist(searchFrm))
	{
		searchFrm.oldCMFunc = searchFrm.onkeydown;
		searchFrm.onkeydown = function (e)
		{
			try
			{
				var key = window.event ? event.keyCode : e.keyCode;
				if(key == 13)
				{
					if(searchBox.value != "")
					{
						psSetCookie(G_PS_COOKIE_CATID,"10001");
					}
				}
				if(this.oldCMFunc != null) 
					return this.oldCMFunc(); 
			}
			catch (ex) {}
			 
		}
	}
}

function psGetCurrentPage()
{
	var curPage = 1;
	var lstPage = psGetElementsByClassName(document,"span", "pageselectoractive");
	if(psCheckArrayExist(lstPage))
	{
		curPage = psTrim(psCleanHtmlTag(psHtmlDecode(lstPage[0].innerHTML)));
	}
	return curPage;
}

function psGetPageIdForCatalogSearch()
{
	var sTitle = psGetDocTitle();
	sTitle = sTitle.replace(/on Carson Dellosa/gi,"");
	sTitle = psTrim(sTitle);
	return sTitle;
}

function psGetCatIdForCatalogSearch()
{
	var term = null;
	var tblSearch = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ResultsPanel");
	if(psCheckElementExist(tblSearch))
	{
		var sText = psCleanHtmlTag(psHtmlDecode(tblSearch.innerHTML));
		if(sText.search(/All\sProducts\s>\s(.*)/gi) > -1)
		{
			term = RegExp.$1;
			var lstTerm = term.split(">");
			if(psCheckArrayExist(lstTerm))
			{
				term = lstTerm[0];
			}
		}
	}
	return term;
}
/*
 * 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);
		psHijackIndividualPros(prd.catId);
	}
}

function psHiackAddToCart(pProId, pCatId)
{
	var oProPanel = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ProductDisplayPanel");
	if(psCheckElementExist(oProPanel))
	{
		var allInputs = oProPanel.getElementsByTagName("input");
		if(psCheckArrayExist(allInputs))
		{
			for (var i=0; i<allInputs.length; i++)	
			{
				var items = allInputs[i];
				if (items.type && items.src && items.id && items.type == "image" && items.src.search(/Images\/nav\/a2cPlaceholder\.png/gi) > -1 && items.id.toLowerCase() != "ctl00_ctl00_LeftNavMainContent_MainContent_ctl00_addtocartbutton")
				{
					items.oldCMFunc = items.onclick;
					items.onclick = function()
					{
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pProId, pCatId);
						if (this.oldCMFunc != null)
							return this.oldCMFunc();
					}		
				}
			}
		}
	}
}

function psHijackAddToCartCatelog(pCatId)
{
	var tblProduct = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ctl00_Products");
	if(psCheckElementExist(tblProduct))
	{
		var lstTable = tblProduct.getElementsByTagName("table");
		if(psCheckArrayExist(lstTable))
		{
			for (var i=0; i<lstTable.length; i++)	
			{
				if(lstTable[i].id && lstTable[i].id.toLowerCase() == "product_table")
				{
					psHijackDetail(lstTable[i],pCatId);
				}
			}
		}
	}
}

function psHijackDetail(pTable,pCatId)
{
	var lstPro = psGetElementsByClassName(pTable,"span","item_id");
	if(psCheckArrayExist(lstPro))
	{
		var proId = psTrim(psCleanHtmlTag(psHtmlDecode(lstPro[0].innerHTML)));
		var lstInput = pTable.getElementsByTagName("input");
		if(psCheckArrayExist(lstInput))
		{
			for(var n = 0; n < lstInput.length; n++ )
			{
				var items = lstInput[n];
				if(items.type && items.src && items.type == "image" && items.src.search(/Images\/Cart_Btn\.jpg/gi) > -1)
				{
					items.oldCMFunc = items.onclick;
					items.onclick = function()
					{
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID, proId, pCatId);
						if (this.oldCMFunc != null)
							return this.oldCMFunc();
					}		
				}
			}
		}
	}
}

function psHijackCoordinatingPros()
{	
	var divRelated = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_RelatedItems_RelatedItemsContent");
	if(psCheckElementExist(divRelated))
	{
		var relatedItems = psGetElementsByClassName(divRelated,"td","Related_Items")
		if(psCheckArrayExist(relatedItems))
		{
			for(var  j=0; j < relatedItems.length; j++)
			{
				psHijackCoordinatingProsDettail(relatedItems[j]);
			}
		}
	}
}

function psHijackCoordinatingProsDettail(relatedItems)
{
	var lstInput = relatedItems.getElementsByTagName("input");
	if(psCheckArrayExist(lstInput))
	{
		for(var n = 0; n < lstInput.length; n++ )
		{
			var items = lstInput[n];
			if(items.type && items.src && items.type == "image" && items.src.search(/cd2\/catalog\/tn-([^\.]+).gif/gi) > -1)
			{
				var sProId = RegExp.$1;	
			}
			if(items.type && items.src && items.type == "image" && items.src.search(/Images\/Cart_Btn\.jpg/gi) > -1)
			{
				items.oldCMFunc = items.onclick;
				items.onclick = function()
				{
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID, sProId, "10002");
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}		
			}
		}
	}
}

function psHijackAddToCartSearch(catId)
{
	var tblProduct = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ResultsPanel");
	if(psCheckElementExist(tblProduct))
	{
		var links = tblProduct.getElementsByTagName("a");
		if(psCheckArrayExist(links))
		{
			for (var i=0; i<links.length; i++)
			{
				if(links[i].href && links[i].href.search(/\/cd2\/cart\.aspx\?Action=AddProduct/gi) > -1)
				{
					links[i].oldCMFunc = links[i].onclick;
					links[i].onclick = function()
					{
						var proId = psGetValueFromUrl(this.href,"ProductID");
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID, proId, catId);
						if (this.oldCMFunc != null)
							return this.oldCMFunc();
					}				
				}
			}
		}
	}
}

function psIsQuickOrderSucc()
{
	var sMsg = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_lblItemsQty");
	if(psCheckElementExist(sMsg))
	{
		var sText = psTrim(psCleanHtmlTag(psHtmlDecode(sMsg.innerHTML.toLowerCase())));
		if( sText.indexOf("items added to the cart") > -1)
			return true;
	}
	return false;
}

function psHijackQuickOrder(oAddCartId)
{
	var lstPro = "";
	var btnAddToCart = document.getElementById(oAddCartId);
	if(psCheckElementExist(btnAddToCart))
	{
		btnAddToCart.oF = btnAddToCart.onclick;
		btnAddToCart.onclick = function()
		{
			var sTable = psGetTableByCellName("Quantity");
			if(psCheckElementExist(sTable))
			{
				var sRows = sTable.rows;
				for(var i=0; i< sRows.length ; i++)
				{
					var pIsvalid = psHtmlDecode(sRows[i].cells[4].innerHTML.toLowerCase());				
					if(sRows[i].cells.length > 3 && pIsvalid.search(/\/cd2\/Buttons\/invalidProduct\.gif/gi) <0)
					{
						var lstInput = sRows[i].cells[0].getElementsByTagName("input");
						if(psCheckArrayExist(lstInput))
						{
							var sProId = lstInput[0].value;
							if(sProId != null && sProId != "")
							{
								lstPro+= sProId;
								lstPro+="-_-"; 
							}
						}
					}
					
				}
			}
			psSetCookie(G_PS_COOKIE_PROID,lstPro);
			if(psCheckElementExist(this.oF)==true)
			{
				return this.oF();
			}
		}						
	}
}

function psHijackCartAndWishListPro(sCatId)
{
	var lstLinks = document.getElementsByTagName("a");
	if(psCheckArrayExist(lstLinks))
	{
		for (var i=0; i<lstLinks.length; i++)	
		{
			var items = lstLinks[i];
			if(items.href && items.href.search(/\/Products\/[^\/]+\/PID-/gi) > -1)
			{
				items.oldCMFunc = items.onclick;
				items.onclick = function()
				{
					psSetCookie(G_PS_COOKIE_CATID,sCatId);
					if (this.oldCMFunc != null)
					return this.oldCMFunc();
				}		
			}
		}
	}
}

function psGetTeachingSupplies()
{
	var result = null;
	sPath = psMoveLastSlash(G_PS_PATHNAME); 
	var lstPath = sPath.split("/");
	if(psCheckArrayExist(lstPath))
	{
		result = (lstPath.length>0)?psTrim(lstPath[lstPath.length-1]):null;		
	}
	return (result!=null)?unescape(result):null;
}

function psHijackAddSuppliesCart(sCatId)
{
	var proPanel = null;
	proPanel = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ResultsPanel");
	if(psCheckElementExist(proPanel))
	{
		var lstLinks = proPanel.getElementsByTagName("a");
		if(psCheckArrayExist(lstLinks))
		{
			for (var i=0; i<lstLinks.length; i++)	
			{
				var items = lstLinks[i];
				if(items.href && items.href.search(/\/cd2\/cart\.aspx/gi) > -1)
				{
					items.oldCMFunc = items.onclick;
					items.onclick = function()
					{
						
						if (this.oldCMFunc != null)
						return this.oldCMFunc();
					}		
				}
			}
		}
	}
}
function psHijackGuestCheckoutEmail()
{
	var emailTag = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_Billing_AddressManager_EmailTextBox");
	if(psCheckElementExist(emailTag))
	{		
		var btnNext = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_NextButton");
		if(psCheckElementExist(btnNext))
		{
			if(btnNext.onclick == null || btnNext.onclick.toString().indexOf("psHJCheckoutEmail") < 0)
			{
				btnNext.OldFunction = btnNext.onclick;
				btnNext.onclick = function psHJCheckoutEmail()
				{
					var email = psTrim(emailTag.value);					
					if(psCheckEmail(email))
					{
						var uP = new psProfile();
						uP.readProfile();
						if(uP.email == null || uP.email == "")
						{
							uP.email = uP.cusId = email;
							uP.writeProfile();
						}
					}
					if(this.OldFunction != null) 
						return this.OldFunction();
				}
			}
		}
	}
}

function psGetCheckoutStep()
{
	var checkoutHeader = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_CheckoutHeader");
	if(psCheckElementExist(checkoutHeader))
	{
		var selectedSpans = psGetElementsByClassName(checkoutHeader,"span","selected");
		if(psCheckArrayExist(selectedSpans))
		{
			var temp = psTrim(psGetInnerText(selectedSpans[0]));			
			return temp;
		}
	}
	return null;	
}

function psGetBillingAddress()
{
	var billAddress = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_BasketBillingAddress");
	if(psCheckElementExist(billAddress))
	{
		var temp = billAddress.innerHTML;
		if(temp != null && temp.search(/\<BR\s*\/*\s*\>/i) >= 0){			
			temp = temp.replace(/(\s*\<BR\s*\/*\s*\>\s*)*$/gi,"");
			var items = temp.split(/\<BR\s*\/*\s*\>/gi);
			if(items.length > 3)
			{
				// The address can be one or two lines, so must parse from the end
				var zipcode = psTrim(items[items.length-2]);
				var city = psTrim(items[items.length-3]);
				var state = null;
				if(city.search(/\s+/) >= 0){
					// The city can include space in its name, such as "New York", so must parse from the end.					
					var pItems = city.split(/\s+/);
					state = pItems[pItems.length-1];
					city = psTrim(city.replace(state,""));
				}				
				var uP = new psProfile();
				uP.readProfile();
				if(zipcode != null && zipcode != "") uP.zipcode = zipcode;
				if(city != null && city != "") uP.city = city;
				if(state != null && state != "") uP.state = state;
				uP.writeProfile();
			}
		}
	}
}

function psIsLoginSuccess()
{
	var btnLogout = document.getElementById("ctl00_LoginStatusControl");
	if(psCheckElementExist(btnLogout))
	{
		var temp = psTrim(psGetInnerText(btnLogout));
		if(temp != null && temp.toLowerCase() == "logout")
			return true;
	}
	return false;
}

function psPostRegistration()
{
	var cookieFlag = psGetCookie(G_PS_COOKIE_FLAG);
	if(cookieFlag == "login")
	{
		var uP = new psProfile();
		uP.readProfile();
		if(uP.cusId != null && uP.cusId != "")
		{
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode,uP.newsletter,uP.subscribe);
		}
		psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	}	
}

function psPostRegistrationNew()
{
	var uR = new psReg();
	uR.readReg();
		if(uR.cusId != null && uR.cusId != "")
		{
			psCreateRegistrationTagNew(uR.cusId, uR.email, uR.city, uR.state, uR.zipcode,uR.attributes);
		}
}


function psHijackRegistration()
{
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");	
	
	var btnLogin = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_LoginForm_LoginButton"); // login page
	if(psCheckElementExist(btnLogin) == false)
	{
		btnLogin = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_NewUserForm___CustomNav0_CreateButton"); // register page
	}
	if(psCheckElementExist(btnLogin))
	{
		if(btnLogin.onclick == null || btnLogin.onclick.toString().indexOf("psHJLogin") < 0)
		{
			btnLogin.OldFunction = btnLogin.onclick;
			btnLogin.onclick = function psHJLogin()
			{
				var emailTag = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_LoginForm_UserName"); // login
				if(psCheckElementExist(emailTag) == false)
				{
					emailTag = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_NewUserForm_CreateUserStepContainer_UserName"); // register
				}
				if(psCheckElementExist(emailTag))
				{
					var email = psTrim(emailTag.value);
					// school/PP account used ID instead of email
					//if(psCheckEmail(email)){
						var uP = new psProfile();						
						uP.cusId = email;
						if(psCheckEmail(email))
							uP.email = email
						uP.writeProfile();
						psSetCookie(G_PS_COOKIE_FLAG,"login");						
					//}					
				}
				if(this.OldFunction != null) 
					return this.OldFunction();
			}
		}
	}
}

function psGetTableByCellName(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
			var sStop = (sRows.length > 2)? 3:sRows.length;
			for(var i=0; i< sStop; 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;
}
function psSendCorrelatedPros()
{
	var proId = psGetElementValueById("ctl00_ContentPlaceHolder1_ProductLabel");
	var proName = psGetElementValueById("ctl00_ContentPlaceHolder1_TitleLabel");
	if(psCheckElementExist(proId) && psCheckElementExist(proName))
	{
		proId = psTrim(psCleanHtmlTag(proId));
		proName = psTrim(psCleanHtmlTag(proName));
		psCreateProductviewTag(proId,proName,"CorrelationsRelated");
		psHiackCorrelatedPros(proId, "CorrelationsRelated");
	}
}

function psHiackCorrelatedPros(pProId, pCatId)
{
	var allInputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if(items.type && items.src && items.type == "image" && items.src.search(/Images\/Cart_Btn\.jpg/gi) > -1)
			{
				items.oldCMFunc = items.onclick;
				items.onclick = function()
				{
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID, pProId, pCatId);
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}		
			}
		}
	}
}

function psHijackWishListPro()
{
	var tblProduct = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_BasketDetail");
	if(psCheckElementExist(tblProduct))
	{
		var sRows = tblProduct.rows;
		for(var  j=0; j < sRows.length; j++)
		{
			psHijackWishListDetail(sRows[j]);
		}
	}
}

function psHijackWishListDetail(pRows)
{
	var links = pRows.getElementsByTagName("a");
	var proId = null;
	if(psCheckArrayExist(links))
	{
		for(var l = 0; l < links.length; l++ )
		{
			if(links[l].href.search(/\/Products\/[^\/]+\/PID-([^\(\.]+)/gi) > -1)
			{
				proId = RegExp.$1;
			}
		}
	
		var lstInput = pRows.getElementsByTagName("input");
		if(psCheckArrayExist(lstInput))
		{
			for(var n = 0; n < lstInput.length; n++ )
			{
				var items = lstInput[n];
				if(items.type && items.value && items.type == "submit" && items.value.toLowerCase()=="add to cart")
				{
					items.oldCMFunc = items.onclick;
					items.onclick = function()
					{
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID, proId, "10007");
						if (this.oldCMFunc != null)
							return this.oldCMFunc();
					}		
				}
			}
		}
	}
}

function psIsNumber(val)
{
	if(val != null && val != "")
		return (isNaN(val) == true)?false:true;
	return false;
}

function psHijackIndividualPros(sCatId)
{
	var btnAddToCart = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ctl00_AddToCartButton");
	if(psCheckElementExist(btnAddToCart))
	{
		btnAddToCart.oldCMFunc = btnAddToCart.onclick;
		btnAddToCart.onclick = function()
		{
			var tblProduct = psGetTableByCellName("You can also purchase individual items or add multiple items");
			if(psCheckElementExist(tblProduct))
			{
				var sRows = tblProduct.rows
				for(var r =0 ;r<sRows.length;r++)
				{
					var lstInput = sRows[r].getElementsByTagName("input");
					if(psCheckArrayExist(lstInput))
					{	
						for(var n = 0; n < lstInput.length; n++ )
						{
							var items = lstInput[n];
							if(items.type && items.name && items.type == "text" && items.name.search(/QuantityBox/gi) >-1)
							{
								if(items.value && items.value != "" && psIsNumber(items.value) && items.value > 0)
								{
									var links =  sRows[r].getElementsByTagName("a");
									if(psCheckArrayExist(links))
									{
										for(var j=0; j< links.length ; j++)
										{
											if(links[j].href.search(/\/Products\/[^\/]+\/PID-([^\(\.]+)/gi) > -1)
											{
												proId = RegExp.$1;
												psSetValueToCookie(G_PS_COOKIE_PROD_CATID, proId, sCatId);
												
											}
										}
									}
								}
							}
						}
					}	
			
				}
			}
					
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}	
	}
}

function psHijackIndividualProsDetail(oRow)
{
	var btnAddToCart = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_ctl00_AddToCartButton");
	if(psCheckElementExist(btnAddToCart))
	{
		btnAddToCart.oldCMFunc = btnAddToCart.onclick;
		btnAddToCart.onclick = function()
		{
			
			var lstInput = oRow.getElementsByTagName("input");
			if(psCheckArrayExist(lstInput))
			{	
				for(var n = 0; n < lstInput.length; n++ )
				{
					var items = lstInput[n];
					if(items.type && items.name && items.type == "text" && items.name.search(/QuantityBox/gi) >-1)
					{
						if(items.value && items.value != "")
						{
							var links =  oRow.getElementsByTagName("a");
							if(psCheckArrayExist(links))
							{
								for(var j=0; j< links.length ; j++)
								{
									if(links[j].href.search(/\/Products\/[^\/]+\/PID-([^\(\.]+)/gi) > -1)
									{
										proId = RegExp.$1;
										psSetValueToCookie(G_PS_COOKIE_PROD_CATID, proId, "10007");
										
									}
								}
							}
						}
					}
				}
			}				
			
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}	
	}
}
/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "10004";
	psCreatePageviewTag("CART", G_PS_CUR_CATID, null);

	var cartTbl = null;
	cartTbl = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_BasketDetail");
	//
	// TO-Do: Your logic to locate the items table (cartTbl) goes here
	//
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	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.search(/\/cd2\/Products\/[^\/]+\/PID/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);
	}
	// Make sure to have actual postings
	psDisplayShop5s();
}

function psGetOrderId()
{
	var pOrderID = psGetValueFromUrl(G_PS_URL_PATH,"OrderNumber");
	if(psCheckElementExist(pOrderID) == false)
	{
		var oMsg = document.getElementById("ctl00_ctl00_LeftNavMainContent_MainContent_orderNumberLabel");
		if(psCheckElementExist(oMsg))
		{
			var sText = psTrim(psCleanHtmlTag(psHtmlDecode(oMsg.innerHTML)));
			if(sText.search(/Your\sorder\sconfirmation\snumber\sis\s([^$\.]+)/gi) > -1)
			{
				pOrderID = RegExp.$1;
				pOrderID.replace(/\./gi,"");
			}
		}
	}
	return pOrderID;
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	psCreatePageviewTag("Receipt" , "10005", null, null);
	var cartTbl = psGetTableByCellName("Unit Price");
	/*
	 * 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();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var r = 0; r < rows.length; r++) // item for each row
			{
				/*
				 * Codes for skipping exceptional rows (rows don't contain items)
				 */
				
				if(rows[r].innerHTML.toLowerCase().indexOf("quantity") >- 1 && rows[r].innerHTML.indexOf("$") >-1)
				{
					if (prd.getItem9(rows[r]))
					{
						psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
					}
				}
			}
			// Make sure to have actual postings
			psDisplayShop9s();
			psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.cusId, uP.city, uP.state, uP.zipcode);
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
			psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	this.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
		this.price = null;
		this.quantity = null;
	}
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			if(unescape(G_PS_PATHNAME).search(/PID-([^\(\.]+)/gi) >-1)
				this.id = RegExp.$1;
			if(psCheckElementExist(this.id) == false)
			{
				this.id  = psGetValueFromUrl(G_PS_URL_PATH,"ProductID");
			}
			var clsProName = psGetElementsByClassName(document,"td","Product_Name");
			if(psCheckArrayExist(clsProName))
			{
				this.name = psTrim(psCleanHtmlTag(psHtmlDecode(clsProName[0].innerHTML)))
			}
			if(psCheckElementExist(this.name) == false)
			{
				this.name = psGetLastedFromCrumb();
			}

			sCatId = psGetCookie(G_PS_COOKIE_CATID);
			if(sCatId && sCatId.toLowerCase() == "cart")
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id.toLowerCase());
			else if(sCatId && sCatId.toLowerCase() == "wishlist")
				this.catId = "10007";
			else if(sCatId && sCatId.toLowerCase() == "10001")
				this.catId = sCatId;
			else
			//	this.catId = psGetProCatFromCrumb(); //DC07202010 commented this line and added next
			    this.catId = getQuerystringValue(G_PS_CM_VC_QSKEY); //psGetCatFromElement();
			
			if(this.catId == null)
			{
				if(G_PS_URL_REFERRER == "") 
				{
					this.catId = "BOOKMARK";
				}
				else 
					this.catId = "Unknown";
			}
			// Store productId along with catId to cookie for use later in shop5 and shop9 views
			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 shopping cart
	 */
	this.getItem5 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var lstLinks = itemRow.cells[1].getElementsByTagName("a");
			if(psCheckArrayExist(lstLinks))
			{
				for (var i = 0; i < lstLinks.length; i++) // item for each row
				{
					if(lstLinks[i].href && lstLinks[i].href.search(/\/cd2\/Products\/[^\/]+\/PID/gi) > -1)
					{
						var pName = psTrim(psCleanHtmlTag(psHtmlDecode(lstLinks[i].innerHTML)));
						if(pName.search(/(\d+)(-EB)?(.*)/gi) > -1)
						{
							this.id = psTrim(unescape(RegExp.$1));
							var ebook = RegExp.$2;
							this.name = psTrim(unescape(RegExp.$3));
							this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
							if(psTrim(ebook) != "") //ebook product
							{
								this.id = this.id + ebook;
								psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
							}
							this.name = psTrim(this.name.replace(/-/gi, ""));
						}
					}
				}
			}
			this.price = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[2].innerHTML)));
			var lstInput = itemRow.cells[0].getElementsByTagName("input");
			if(psCheckArrayExist(lstLinks))
			{
				this.quantity = lstInput[0].value;
			}
			if(this.catId == null || this.catId == "")
			{
				this.catId = "Unknown";
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the receipt page
	 */
	this.getItem9 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var pName = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[1].innerHTML)));
			
			if(pName.search(/(\d+)(-EB)?(.*)/gi) > -1)
			{
				this.id = psTrim(unescape(RegExp.$1));
				var ebook = RegExp.$2;
				this.name = psTrim(unescape(RegExp.$3));
				if(psTrim(ebook) != "") //ebook product
				{
					this.id = this.id + ebook;
				}
				this.name = psTrim(this.name.replace(/-/gi, ""));
			}	
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);			
			this.price = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[2].innerHTML)));
			this.quantity = psTrim(psCleanHtmlTag(psHtmlDecode(itemRow.cells[0].innerHTML)));
			if(this.catId == null || this.catId == "")
			{
				this.catId = "Unknown";
			}
			
			return true;
		}
		catch (ex) { return false; }
	}
}

/* PURPOSE: constructor for Reg (Registrations)  DC Added 06072010
 * Note: you can add more methods to psReg in its prototype
 * RETURN: none
 */

function psReg()
{
	this.cusId = null;
    this.email = null;
	this.city = null;
	this.state = null;
	this.zipcode = null;
	
    this.conversionstatus = null;
    this.source = null;
    this.contest = null;
    this.position = null;
	this.parentorteacher = null;
	this.howlongteacher = null;
    this.campainid = null;
	this.campdes = null;
	this.unsubreason = null;
	this.attributes = null;
	
	this.readReg = function()
	{
		try
		{
	       this.cusId = psGetElementValueById("ctl00_Customer_ID_CT", true);
           this.email = psGetElementValueById("ctl00_Email_CT", true);
		   this.city = psGetElementValueById("ctl00_City_CT", true) ;
		   this.state = psGetElementValueById("ctl00_State_CT", true);
		   this.zipcode = psGetElementValueById("ctl00_ZipCode_CT", true);
		 
		   this.conversionstatus =  psGetElementValueById("ctl00_CONVERSION_STATUS_CT",true);
		   this.source = psGetElementValueById("ctl00_SOURCE_CT",true);
		   this.contest = psGetElementValueById("ctl00_CONTEST_CT",true);
		   this.position = psGetElementValueById("ctl00_POSITION_CT",true);
		   this.parentorteacher = psGetElementValueById("ctl00_PARENT_OR_TEACHER_CT",true);
		   this.howlongteacher = psGetElementValueById("ctl00_HOW_LONG_A_TEACHER_CT", true);
		   this.campainid = psGetElementValueById("ctl00_CAMPAIGN_ID_CT", true);
		   this.campdes = psGetElementValueById("ctl00_RECEIVE_TYPE_DESC_CT", true);
		   this.unsubreason = psGetElementValueById("ct100_UNSUBSCRIBE_REASON_CT", true);

		   this.attributes = this.conversionstatus+"-_-"+this.source+"-_-"+this.contest+"-_-"+this.position+"-_-"+this.parentorteacher+"-_-"+this.howlongteacher+"-_-"+this.campainid+"-_-"+this.campdes+"-_-"+this.unsubreason ;
			return true;
		}
		catch (ex) { return false; }
	}
	
	
}




/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
	this.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;
	
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.cusId = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.cusId != null)
			{
				var buf = this.cusId.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				this.cusId = buf[0];
				if (!this.cusId)
					this.cusId = psGenerateRandomValue();
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		try
		{
			if (this.cusId == null)
				return;
			// make sure that the data contains 4 parts separated by 3 '|'
			var data = this.cusId + "|" + this.email + '|' + this.city + '|' + this.state + '|' 
				+ this.zipcode + "|" + this.newsletter + '|' + this.subscribe;
			// store on cookie
			psSetCookie(G_PS_COOKIE_PROFILE, data);
			//
			// NOTE: To persist profile as persistent cookie, pass G_PS_COOKIE_LIFETIME as the third param instead of null
			// psSetCookie(G_PS_COOKIE_PROFILE, data, G_PS_COOKIE_LIFETIME);
			//
			return true;
		}
		catch (ex) { return false; }
	}
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			this.id = psGetOrderId();
			var cartTbl = psGetTableByCellName("Unit Price");
			if(psCheckElementExist(cartTbl))
			{
				var rows = cartTbl.rows; 
				for (var t = 0; t < rows.length; t++) // item for each row
				{
					if(rows[t].innerHTML.toLowerCase().indexOf("footeritemlabel displayname") <0)
					{
						continue;
					}
					for (var c = 0; c < rows[t].cells.length; c++)
					{
						var sText = psTrim(psCleanHtmlTag(psHtmlDecode(rows[t].cells[c].innerHTML.toLowerCase())));
						if (sText == "subtotal")
						{
							var lstValue = psGetElementsByClassName(rows[t],"td","FooterItem FooterItemValue currency");
							if(psCheckArrayExist(lstValue))
							{
								this.subtotal = psTrim(psCleanHtmlTag(psHtmlDecode(lstValue[0].innerHTML)));
							}
						}
						else if(sText == "shipping")
						{
							var lstValue = psGetElementsByClassName(rows[t],"td","FooterItem FooterItemValue currency");
							if(psCheckArrayExist(lstValue))
							{
								this.shipping = psTrim(psCleanHtmlTag(psHtmlDecode(lstValue[0].innerHTML)));
							}
						
						}
					}
					
						
				}	
			}
			if (!this.id)
				this.id = psGenerateRandomValue();
			return true;
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all unaccepted characters in categoryid, including
 * [, ', ", :, comma,]
 * RETURN: string
 */
function psCleanCatId(pCatId)
{
	var j=0;
	while(j<pCatId.length)
	{
		if(pCatId.charCodeAt(j)== 8482 || pCatId.charCodeAt(j)== 174 || pCatId.charCodeAt(j)== 8217)
		{
			pCatId = pCatId.replace(String.fromCharCode(8482),"");
			pCatId = pCatId.replace(String.fromCharCode(174),"");
			pCatId = pCatId.replace(String.fromCharCode(8217),""); //DCAdded 06152010
		}
		j++;
	}	
    return (pCatId != null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	var j=0;
	while(j<pPageId.length)
	{
		if(pPageId.charCodeAt(j)== 8482 || pPageId.charCodeAt(j)== 174 || pPageId.charCodeAt(j)== 8217)
		{
			pPageId = pPageId.replace(String.fromCharCode(8482),"");
			pPageId = pPageId.replace(String.fromCharCode(174),"");
			pPageId = pPageId.replace(String.fromCharCode(8217),""); //DCAdded 06152010
		}
		j++;
	}	
		
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

function psCleanProductName(pProductName)
{
	var j=0;
	while(j<pProductName.length)
	{
		if(pProductName.charCodeAt(j)== 8482 || pProductName.charCodeAt(j)== 174 || pProductName.charCodeAt(j)== 8217 || pProductName.charCodeAt(j)== 8216)
		{
			pProductName = pProductName.replace(String.fromCharCode(8482),"");
			pProductName = pProductName.replace(String.fromCharCode(174),"");
			pProductName = pProductName.replace(String.fromCharCode(8217),""); //DCAdded 06152010
			pProductName = pProductName.replace(String.fromCharCode(8216),""); //DCAdded 06152010
		}
		j++;
	}
	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 unescape(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)
{
	var sResult = pValue;
	sResult  = sResult.replace(/<script(.*)>(.*)<\/script>/gi,"");
    sResult =  (sResult != null) ? sResult.replace(/\<+.+?\>+/g, "") : null;
	return sResult;
	
}
/* 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 psCreateRegistrationTagNew(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pAttributes) 
{
    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, pAttributes);
}


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();
}


//DC07202010 get the category from the hidden field that was added
function psGetCatFromElement()
{
	var term = psGetElementValueById("ctl00_CS_CategoryID_Tag", false);
	if(psCheckElementExist(term))
	{
		return term;
	}
}

/*===========================END GENERAL UTILITY FUNCTION ==================*/
