/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.2, 2009/09/03
 * 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("makari.com");//value must be one array of domains or null

// current page url
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_URL_REFERRER = document.referrer.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000; // 5*24*60*60 = 5 days
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if(psGetDomain(G_PS_URL_PATH).indexOf("makari.com")>-1 && psGetPageName().indexOf("subscribe.asp")<0)
{
	psCacheSearchTerm();
	psSendRegistration();
	psHijackLogout();
	if(G_PS_PATHNAME == "/" || G_PS_PATHNAME == "/default.asp")
	{
		psCreatePageviewTag("Home","Home",null,null);
		psSetCookie(G_PS_COOKIE_CATID,"Home");
	}
	else if(G_PS_PATHNAME.indexOf("contact.asp")>-1)
	{
		psCreatePageviewTag("Contact","Home",null,null);
	}
	else if(G_PS_PATHNAME.indexOf("about-us.html")>-1)
	{
		psCreatePageviewTag("About Us","Home",null,null);
	}
	else if(G_PS_PATHNAME.indexOf("makari-videos.asp")>-1 && G_PS_QUERYSTRING.indexOf("vid=")>-1)
	{
		psCreatePageviewTag("VIDEO " + psGetValueFromUrl(G_PS_QUERYSTRING,"vid"),"MAKARI VIDEOS",null,null);
	}
	else if(psIsEqual(psGetPageName(),"search.asp"))
	{
		psPostSearchView();
		psSetCookie(G_PS_COOKIE_CATID,"Search");
		psHijackSearchPage();
	}
	else if(psIsEqual(psGetPageName(),"view_order.asp"))
	{
		psCreatePageviewTag("View Order","Cart",null,null);
		psPostCartView();
		psHijackCartPage();
	}
	else if(psIsEqual(psGetPageName(),"login.asp") && G_PS_QUERYSTRING.indexOf("redirpage=billing_and_shipping.asp")>-1)
	{
		psCreatePageviewTag("Login","CHECKOUT",null,null);
		psHijackLogReg();
	}
	else if(psIsEqual(psGetPageName(),"login.asp"))
	{
		psCreatePageviewTag("My Account","Account",null,null);
		psHijackLogReg();
	}
	else if(psIsEqual(psGetPageName(),"history.asp"))
	{
		psCreatePageviewTag("History","Account",null,null);
	}
	else if(psIsEqual(psGetPageName(),"billing_and_shipping.asp"))
	{
		psCreatePageviewTag("Billing And Shipping","Account",null,null);
		psHijackBillingShiping();
	}
	else if(psIsEqual(psGetPageName(),"confirm_order.asp"))
	{
		psCreatePageviewTag("Confirm Order","CHECKOUT",null,null);
		var profile = new psProfile();
		profile.readProfile();
		psCreateRegistrationTag(profile.cusId,profile.email,profile.city,profile.state,profile.zipcode,profile.newsletter,profile.subscribe) ;
	}
	else if(psIsEqual(psGetPageName(),"purchaseorder.asp"))
	{
		psCreatePageviewTag("Confirmation","CHECKOUT",null,null);
		psPostOrderView();
	}
	else if(psIsEqual(psGetPageName(),"forgotpassword.asp"))
	{
		psCreatePageviewTag("Forgot Password","Account",null,null);
	}
	else if(psIsProductView())
	{
		var prd = new psProduct();
		if (prd.getProduct()) // Get product info successfully?
			psCreateProductviewTag(prd.id, prd.name, prd.catId);
		psHijackCrossSell();
		psHijackBuyProduct(prd.id,prd.catId);
	}
	else if(psIsCategoryPage())
	{
		var catId = psGetElementValueById("ctl00_ContentPlaceHolder1_hdrTitle",true);
		catId = psTrim(catId);
		var pageId = "";
		if(psGetValueFromUrl(G_PS_QUERYSTRING,"pg")!= null && psGetValueFromUrl(G_PS_QUERYSTRING,"pg")>1)
		{
			pageId = " Page " + psGetValueFromUrl(G_PS_QUERYSTRING,"pg");
		}
		psCreatePageviewTag("MAKARI DEPARTMENTS: " + catId + pageId,catId,null,null);
		psSetCookie(G_PS_COOKIE_CATID,catId);
		psHijackCategoryPage(catId);
	}
	else if(psIsInformationPage()
			|| G_PS_PATHNAME.indexOf("coupon")>-1
			|| psIsEqual(psGetPageName(),"SERIOUSDARKSPOTS.html")
			|| G_PS_PATHNAME.indexOf("email")>-1)
	{
		var pageId = psGetPageName();
		pageId = pageId.replace(/[-_]/gi," ");
		pageId = pageId.replace(/(.html|.asp)/gi,"");
		psCreatePageviewTag(pageId,"INFORMATION",null,null);
		psSetCookie(G_PS_COOKIE_CATID,pageId);
	}
	else
	{
		var pageId = psGetPageName();
		pageId = pageId.replace(/[-_]/gi," ");
		pageId = pageId.replace(/(.html|.asp)/gi,"");
		pageId = psTrim(pageId);
		var catId = "SEO";
		psCreatePageviewTag(pageId,catId,null,null);
		psSetCookie(G_PS_COOKIE_CATID,catId);
		psHijackCategoryPage(catId);
	}
}
psHijackSubcribe();

function psIsCategoryPage()
{
	var pageName = psGetPageName();
	pageName = pageName.replace(/-/gi," ");
	pageName = pageName.replace(/(.html|.asp)/gi,"");
	pageName = psTrim(pageName);
	var titleCate = psGetElementValueById("ctl00_ContentPlaceHolder1_hdrTitle",true);
	titleCate = psTrim(titleCate);
	var aList = document.getElementsByTagName("a");
	var se = /All\s*Products/gi;
	var aItem = null;
	for(var i = 0; i< aList.length; i++)
	{
		if(aList[i].innerHTML.search(se)>-1)
		{
			aItem = aList[i];
			break;
		}
	}
	var cellItem = null;
	if(aItem!=null)
	{
		cellItem = aItem.parentNode;
		while (!psIsEqual(cellItem.tagName,"body") && !psIsEqual(cellItem.tagName,"td"))
		{
			cellItem = cellItem.parentNode;
		}
	}
	if(cellItem!=null && psIsEqual(cellItem.tagName,"td"))
	{
		aList = cellItem.getElementsByTagName("a");
		for(var j = 0; j< aList.length; j++)
		{
			var hrefItem = aList[j].innerHTML;
			hrefItem = psTrim(hrefItem);
			if(psIsEqual(pageName,hrefItem) || psIsEqual(titleCate,hrefItem))
			{
				return true;
			}
		}
		
	}
	return false;
}

function psIsInformationPage()
{
	var pageName = psGetPageName();
	pageName = pageName.replace(/[-_]/gi," ");
	pageName = pageName.replace(/(.html|.asp)/gi,"");
	pageName = psTrim(pageName);
	var aList = document.getElementsByTagName("a");
	var se = /SiteMap/gi;
	var aItem = null;
	for(var i = 0; i< aList.length; i++)
	{
		if(aList[i].innerHTML.search(se)>-1)
		{
			aItem = aList[i];
			break;
		}
	}
	var cellItem = null;
	if(aItem!=null)
	{
		cellItem = aItem.parentNode;
		while (!psIsEqual(cellItem.tagName,"body") && !psIsEqual(cellItem.tagName,"td"))
		{
			cellItem = cellItem.parentNode;
		}
	}
	if(cellItem!=null && psIsEqual(cellItem.tagName,"td"))
	{
		aList = cellItem.getElementsByTagName("a");
		for(var j = 0; j< aList.length; j++)
		{
			var hrefItem = aList[j].innerHTML;
			hrefItem = psTrim(hrefItem);
			if(psIsEqual(pageName,hrefItem))
			{
				return true;
			}
		}
	}
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	var pageName = psGetPageName();
	if(pageName.toLowerCase().indexOf("products.asp")>-1)
	{
		return true;
	}
	else
	{
		var spanList = document.getElementsByTagName("span");
		var itemCodeCount = 0;
		var se = /item\s*code\s*#/gi;
		for(var i = 0; i< spanList.length; i++)
		{
			var spanText = psGetInnerText(spanList[i]);
			if(spanText.search(se)>-1)
			{
				itemCodeCount ++;
				if(itemCodeCount>1)
				{
					return false;
				}
			}
		}
		if(itemCodeCount==1)
		{
			var h1Item = document.getElementsByTagName("h1")[0];
			if(psCheckElementExist(h1Item))
			{
				var prodName = psTrim(psGetInnerText(h1Item));
				prodName = prodName.replace(/\s+/gi," ");
				pageName = pageName.replace(/(-+|_)/gi," ");
				pageName = pageName.replace(/(.html|.asp)/gi,"");
				pageName = psTrim(pageName);
				if(psIsEqual(pageName,prodName))
				{
					return true;
				}
			}
		}
	}
	return false;
}

/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psHijackSearchPage()
{
	var tblItem = document.getElementById("ctl00_ContentPlaceHolder1_gridAdd");
	if(psCheckElementExist(tblItem))
	{
		var inputList = document.getElementsByTagName("input");
		for(var i = 0; i< inputList.length; i++)
		{
			if(psIsEqual(inputList[i].type,"image") && inputList[i].src.indexOf("buy-now.gif")>-1)
			{
				inputList[i].oldCMF = inputList.onclick;
				inputList[i].onclick = function()
				{
					var rowItem = this.parentNode;
					while(!psIsEqual(rowItem.tagName,"body") && !psIsEqual(rowItem.tagName,"tr"))
					{
						rowItem = rowItem.parentNode;
					}
					if(psIsEqual(rowItem.tagName,"tr"))
					{
						var se = /Item\s*code\s*#\s*\:\s*([^\<]*)\s*\</gi;
						if(rowItem.innerHTML.search(se)>-1)
						{
							var prodId = RegExp.$1;
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,"Search");
						}
					}
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
		}
	}
}

function psHijackLogout()
{
	var aList = document.getElementsByTagName("a");
	for(var i = 0; i< aList.length; i++)
	{
		if(psIsEqual(psGetInnerText(aList[i]),"Logout"))
		{
			aList[i].oldCMF = aList[i].onclick;
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
				psSetValueToCookie(G_PS_COOKIE_FLAG,"Profile","Logout");
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
			break;
		}
	}
}
function psHijackBillingShiping()
{
	var frmCheckout = null;
	var frmList = document.getElementsByTagName("form");
	for(var i = 0; i< frmList.length; i++)
	{
		if(psIsEqual(psTrim(frmList[i].name),"billAndShipForm"))
		{
			frmCheckout = frmList[i];
			break;
		}
	}
	if(frmCheckout != null)
	{
		frmCheckout.oldCMF = frmCheckout.onsubmit;
		frmCheckout.onsubmit = function()
		{
			var profile = new psProfile();
			profile.readProfile();
			profile.cusId = profile.email = psGetElementValueById("email",true);
			profile.city = psGetElementValueById("bill_city",true);
			profile.state = psGetElementValueById("bill_state",true);
			profile.zipcode = psGetElementValueById("bill_zip",true);
			profile.writeProfile();
			if(psCheckElementExist(this.oldCMF))
			{
				return this.oldCMF();
			}
		}
	}
}

function psSendRegistration()
{
	var aList = document.getElementsByTagName("a");
	for(var i = 0; i< aList.length; i++)
	{
		if(psIsEqual(psGetInnerText(aList[i]),"Login"))
		{
			break;
		}
		if(psIsEqual(psGetInnerText(aList[i]),"Logout"))
		{
			if(psIsEqual(psGetValueFromCookie(G_PS_COOKIE_FLAG,"Profile"),"Login")
				||psIsEqual(psGetValueFromCookie(G_PS_COOKIE_FLAG,"Profile"),"RegGst"))
			{
				var profile = new psProfile();
				profile.readProfile();
				psCreateRegistrationTag(profile.cusId,profile.email,profile.city,profile.state,profile.zipcode,profile.newsletter,profile.subscribe);
				psSetValueToCookie(G_PS_COOKIE_FLAG,"Profile","Sent");
			}
			break;
		}
	}
}

function psHijackLogReg()
{
	var formList = document.getElementsByTagName("form");
	for(var i = 0; i< formList.length; i++)
	{
		if(formList[i].action.indexOf("login.asp")>-1 && psIsEqual(formList[i].name,"register"))
		{
			formList[i].oldCMF = formList[i].onsubmit;
			formList[i].onsubmit = function()
			{
				var profile = new psProfile();
				var inputList = this.getElementsByTagName("input");
				for(var j = 0; j< inputList.length; j++)
				{
					if(psIsEqual(inputList[j].type,"text"))
					{
						profile.cusId = psGetElementValue(inputList[j],true);
						profile.email = psGetElementValue(inputList[j],true);
						profile.writeProfile();
						psSetValueToCookie(G_PS_COOKIE_FLAG,"Profile","RegGst");
						break;
					}
				}
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
		else if(formList[i].action.indexOf("login.asp")>-1)
		{
			formList[i].oldCMF = formList[i].onsubmit;
			formList[i].onsubmit = function()
			{
				var profile = new psProfile();
				var inputList = this.getElementsByTagName("input");
				for(var j = 0; j< inputList.length; j++)
				{
					if(psIsEqual(inputList[j].type,"text"))
					{
						profile.cusId = psGetElementValue(inputList[j],true);
						profile.email = psGetElementValue(inputList[j],true);
						profile.writeProfile();
						psSetValueToCookie(G_PS_COOKIE_FLAG,"Profile","Login");
						break;
					}
				}
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
	}
}

function psHijackSubcribe()
{
	var subscribeFrame = null;
	var frameList = document.getElementsByTagName("iframe");
	if(psCheckElementExist(frameList)&& frameList.length>0)
	{
		subscribeFrame = frameList[0];
	}
	if(psCheckElementExist(subscribeFrame))
	{
		var subscribeForm = null;
		var formList = subscribeFrame.contentWindow.document.getElementsByTagName("form");
		for(var i = 0; i< formList.length; i++)
		{
			if(formList[i].action.indexOf("visitor.constantcontact.com")>-1)
			{
				subscribeForm = formList[i];
				break;
			}
		}
		if(subscribeForm != null)
		{
			subscribeForm.oldCMF = subscribeForm.onsubmit;
			subscribeForm.onsubmit = function()
			{
				var inputList = this.getElementsByTagName("input");
				for(var i = 0; i< inputList.length; i++)
				{
					if(psIsEqual(inputList[i].type,"text"))
					{
						var email = psGetElementValue(inputList[i],true);
						if(psCheckEmail(email))
						{
							psCreateRegistrationTag(email,email);
						}
						break;
					}
				}
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
		window.oldCMF = window.onload;
		window.onload = function()
		{
			var temp = this.oldCMF();
			if(subscribeForm != null)
			{
				var aList = subscribeForm.getElementsByTagName("a");
				for (var i = 0; i< aList.length; i++)
				{
					if(psIsEqual(psTrim(psGetInnerText(aList[i])),"Subscribe"))
					{
						aList[i].oldCMF = aList[i].onclick;
						aList[i].onclick = function()
						{
							var parentNode = this.parentNode;
							while(!psIsEqual(parentNode.tagName,"body") && !psIsEqual(parentNode.tagName,"table"))
							{
								parentNode = parentNode.parentNode;
							}
							if(psIsEqual(parentNode.tagName,"table"))
							{
								var inputList = parentNode.getElementsByTagName("input");
								for(var j = 0; j< inputList.length; j++)
								{
									if(psIsEqual(inputList[j].type,"text"))
									{
										var email = psGetElementValue(inputList[j],true);
										if(psCheckEmail(email))
										{
											psCreateRegistrationTag(email,email);
										}
										break;
									}
								}
							}
							if(psCheckElementExist(this.oldCMF))
							{
								return this.oldCMF();
							}
						}
						break;
					}
				}
			}
			if(psCheckElementExist(temp))
			{
				return temp;
			}
		}
		
	}
	
	
}

function psHijackCartPage()
{
	var tblItem = document.getElementById("ctl00_ContentPlaceHolder1_ShoppingCartDetails_formCart");
	if(psCheckElementExist(tblItem))
	{
		var aList = tblItem.getElementsByTagName("a");
		for(var i = 0; i< aList.length; i++)
		{
			if(aList[i].href.toLowerCase().indexOf("products.asp?product_id=")>-1)
			{
				aList[i].oldCMF = aList[i].onclick;
				aList[i].onclick = function()
				{
					psSetValueToCookie(G_PS_COOKIE_FLAG,"FromCart","true");
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
		}
	}
}

function psHijackCategoryPage(catId)
{
	var tblItem = document.getElementById("ctl00_ContentPlaceHolder1_gridAdd");
	if(psCheckElementExist(tblItem))
	{
		var formList = tblItem.getElementsByTagName("form");
		for(var i = 0; i< formList.length; i++)
		{
			formList[i].oldCMF = formList[i].onsubmit;
			formList[i].onsubmit = function()
			{
				var formIndex = null;
				var tblTemp = document.getElementById("ctl00_ContentPlaceHolder1_gridAdd");
				if(psCheckElementExist(tblTemp))
				{
					var formTemp = tblTemp.getElementsByTagName("form");
					for(var j = 0; j< formTemp.length; j++)
					{
						if(psIsEqual(formTemp[j].action,this.action))
						{
							formIndex = j;
							break;
						}
					}
				}
				var prodId = null;
				var inputList = document.getElementsByTagName("input");
				var inputCount = -1;
				for(var j = 0; j< inputList.length; j++)
				{
					if(psIsEqual(inputList[j].type,"image") && inputList[j].src.indexOf("buy-now.gif")>-1)
					{
						inputCount ++;
						if(formIndex == inputCount)
						{
							var rowItem = inputList[j].parentNode;
							while(!psIsEqual(rowItem.tagName,"body") && !psIsEqual(rowItem.tagName,"tr"))
							{
								rowItem = rowItem.parentNode;
							}
							if(psIsEqual(rowItem.tagName,"tr"))
							{
								if(rowItem.cells.length>1)
								{
									var se = /item\s*code\s*#\s*:\s*(.*)\s*Price/gi;
									if(psGetInnerText(rowItem.cells[1]).search(se)>-1)
									{
										prodId = RegExp.$1;
									}
								}
							}
						}
						
						
					}
				}
				psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,catId);
				
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
	}
}

function psHijackBuyProduct(prodId, catId)
{
	var inputList = document.getElementsByTagName("input");
	for(var i = 0; i< inputList.length; i++)
	{
		if(psIsEqual(inputList[i].type,"image") && inputList[i].src.indexOf("buy-now.gif")>-1)
		{
			var formItem = inputList[i].parentNode;
			while(!psIsEqual(formItem.tagName,"body") && !psIsEqual(formItem.tagName,"form"))
			{
				formItem = formItem.parentNode;
			}
			if(psIsEqual(formItem.tagName,"form"))
			{
				formItem.oldCMF = formItem.onsubmit;
				formItem.onsubmit = function()
				{
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prodId,catId);
					if(psCheckElementExist(this.oldCMF))
					{
						return this.oldCMF();
					}
				}
			}
			break;
		}
	}
}

function psHijackCrossSell()
{
	var divItem = document.getElementById("ctl00_ContentPlaceHolder1_formDtls_pnlDivFeatures");
	if(divItem != null)
	{
		var aList = divItem.getElementsByTagName("a");
		for(var i = 0; i< aList.length; i++)
		{
			aList[i].oldCMF = aList[i].onclick;
			aList[i].onclick = function()
			{
				psSetCookie(G_PS_COOKIE_CATID,"CROSS SELL");
				if(psCheckElementExist(this.oldCMF))
				{
					return this.oldCMF();
				}
			}
		}
	}
}

function psCacheSearchTerm()
{
	var btnSearch = document.getElementById("ctl00_FastSearch1_btnSearch");
	if(psCheckElementExist(btnSearch))
	{
		btnSearch.oldCMF = btnSearch.onclick;
		btnSearch.onclick = function()
		{
			psSetValueToCookie(G_PS_COOKIE_FLAG,"SearchTerm",psGetElementValueById("ctl00_FastSearch1_txtSearch",true));
			if(psCheckElementExist(this.oldCMF))
			{
				return this.oldCMF();
			}
		}
	}
	var txtSearch = document.getElementById("ctl00_FastSearch1_txtSearch");
	if(psCheckElementExist(txtSearch))
	{
		txtSearch.oldCMF = txtSearch.onkeypress;
		txtSearch.onkeypress = function(e)
		{
			var key;     
			if(window.event)
				key = window.event.keyCode; //IE
			else
				key = e.which; //firefox 
			if(key == 13)
			{
				psSetValueToCookie(G_PS_COOKIE_FLAG,"SearchTerm",psGetElementValueById("ctl00_FastSearch1_txtSearch",true));
			}
			if(psCheckElementExist(this.oldCMF))
			{
				return this.oldCMF();
			}
		}
	}
}

function psGetPageName()
{
	var pageName = G_PS_PATHNAME;
	var se = /\/([^\/]*)$/gi;
	if(pageName.search(se)>-1)
	{
		pageName = RegExp.$1;
		pageName = psHtmlDecode(pageName);
	}
	return pageName;
}

function psPostSearchView()
{
	var catId = "SEARCH";
	var pageId = "SEARCH SUCCESSFUL";
	var searchTerm = psGetElementValueById("ctl00_ContentPlaceHolder1_hdrTitle",true);
	var searchResult = null;
	if(searchTerm == null)
	{
		pageId = "SEARCH UNSUCCESSFUL";
		searchResult = 0;
		searchTerm = psGetValueFromCookie(G_PS_COOKIE_FLAG,"SearchTerm");
	}
	else
	{
		var tblItem = document.getElementById("ctl00_ContentPlaceHolder1_gridAdd");
		if(tblItem != null)
		{
			var aList = tblItem.getElementsByTagName("a");
			var hrefList = new Array();
			for(var i = 0; i< aList.length; i++)
			{
				var hrefItem = aList[i].href;
				var isNew = true;
				for(var j = 0; j< hrefList.length; j++)
				{
					if(psIsEqual(hrefItem,hrefList[j]))
					{
						isNew = false;
						break;
					}
				}
				if (isNew)
				{
					hrefList.push(hrefItem);
				}
			}
			searchResult = hrefList.length;
		}
	}
	psCreatePageviewTag(pageId,catId,searchTerm,searchResult);
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	var prd = new psProduct();
	var spanList = document.getElementsByTagName("span");
	for(var i = 0; i< spanList.length; i++)
	{
		if(psIsEqual(psGetInnerText(spanList[i]),"remove"))
		{
			var rowItem = spanList[i].parentNode;
			while(!psIsEqual(rowItem.tagName,"body") && !psIsEqual(rowItem.tagName,"tr"))
			{
				rowItem = rowItem.parentNode;
			}
			if(psIsEqual(rowItem.tagName,"tr"))
			{
				if (prd.getItem5(rowItem))
					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 cartTbl = psGetProdTable();
	/*
	 * Codes for locating the table containing items (each row for an item)
	 */
	if (cartTbl == null)
		return;

	var ord = new psOrder();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var r = 0; r < cartTbl.rows.length; r++) // item for each row
			{
				if(cartTbl.rows[r].cells.length>3 && cartTbl.rows[r].innerHTML.indexOf("$")>-1)
				{
					if (prd.getItem9(cartTbl.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");
		}
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	this.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
		this.price = null;
		this.quantity = null;
	}
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var h1Item = document.getElementsByTagName("h1")[0];
			if(psCheckElementExist(h1Item))
			{
				this.name = psTrim(psGetInnerText(h1Item));
			}
			
			var spanList = document.getElementsByTagName("span");
			var spanItem = null;
			var se = /item\s*code\s*#/gi;
			for(var i = 0; i< spanList.length; i++)
			{
				var spanText = psGetInnerText(spanList[i]);
				if(spanText.search(se)>-1)
				{
					spanItem = spanList[i];
					break;
				}
			}
			if(spanItem != null)
			{
				se = /item\s*code\s*#\s*(.*)$/gi;
				this.id = psGetInnerText(spanItem).search(se)>-1 ? RegExp.$1:null;
			}
			
			if(psIsEqual(psGetValueFromCookie(G_PS_COOKIE_FLAG,"FromCart"),"true"))
			{
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
				psSetValueToCookie(G_PS_COOKIE_FLAG,"FromCart","false");
				psSetCookie(G_PS_COOKIE_CATID,this.catId);
			}
			else if(G_PS_URL_REFERRER!="" && psGetDomain(G_PS_URL_REFERRER).indexOf("makari.com")>=0)
			{
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
			}
			this.catId = (!psCheckCategoryId(this.catId))? "BOOKMARK":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!
			if(itemRow.cells.length>3)
			{
				var se = /\<strong\>([^(\<\/)]*)\<\/strong\>/gi;
				if(itemRow.cells[1].innerHTML.search(se)>-1)
				{
					this.name = RegExp.$1;
				}
				se = /\<br\/*\>\s*([^\<]*)\s*\</gi;
				if(itemRow.cells[1].innerHTML.search(se)>-1)
				{
					this.id = RegExp.$1;
				}
				var inputItem = itemRow.cells[2].getElementsByTagName("input")[0];
				if(psCheckElementExist(inputItem))
				{
					this.quantity = psGetElementValue(inputItem,true);
				}
				this.price = psGetInnerText(itemRow.cells[3]);
				this.price = this.price.replace(/$/gi,"");
				
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
				this.catId = (!psCheckCategoryId(this.catId))? "UNKNOWN":this.catId;
			}
			
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the receipt page
	 */
	this.getItem9 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			this.id = psGetInnerText(itemRow.cells[0]);
			this.name = psGetInnerText(itemRow.cells[1]);
			this.price = psGetInnerText(itemRow.cells[3]).replace("$","");
			this.quantity = psGetInnerText(itemRow.cells[2]);
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
			this.catId = (!psCheckCategoryId(this.catId))? "UNKNOWN":this.catId;
			return true;
		}
		catch (ex) { return false; }
	}
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
	this.cusId = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zipcode = null;
	this.newsletter = null;
	this.subscribe = null;
	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.cusId = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.cusId != null)
			{
				var buf = this.cusId.split('|');
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					// when NULL is written to cookie, it becomes string, not literal constant
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				this.cusId = buf[0];
				if (!this.cusId)
					this.cusId = psGenerateRandomValue();
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zipcode = buf[4];
				this.newsletter = buf[5];
				this.subscribe = buf[6];
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		try
		{
			if (this.cusId == null)
				return;
			// make sure that the data contains 4 parts separated by 3 '|'
			var data = this.cusId + "|" + this.email + '|' + this.city + '|' + this.state + '|' 
				+ this.zipcode + "|" + this.newsletter + '|' + this.subscribe;
			// store on cookie
			psSetCookie(G_PS_COOKIE_PROFILE, data);
			//
			// 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; }
	}
}

function psGetProdTable()
{
	var tblItem = null;
	var bList = document.getElementsByTagName("b");
	for (var i=0; i<bList.length; i++)
	{
		var se = /Item\s*Code/gi;
		if(bList[i].innerHTML.search(se)>-1)
		{
			tblItem = bList[i].parentNode;
			while(!psIsEqual(tblItem.tagName,"body") && !psIsEqual(tblItem.tagName,"table"))
			{
				tblItem = tblItem.parentNode;
			}
			break;
		}
	}
	return tblItem;
}

/*
 * Order object encapsulates order Id, subtotal, shipping and customer Id
 * This design is aimed at code resuse and easy readability
 */
function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			var pageContent = document.getElementsByTagName("table")[0].innerHTML;
			var se = /\,\s*#([\w\d]*)\s*\,/gi;
			this.id = pageContent.search(se)>-1 ? RegExp.$1:null;
			var prodTable = psGetProdTable();
			if(prodTable != null)
			{
				for(var i=0; i<prodTable.rows.length; i++)
				{
					if(prodTable.rows[i].innerHTML.search(/Sub\s*Total:/gi)>-1)
					{
						for(var j=0; j<prodTable.rows[i].cells.length; j++)
						{
							if(prodTable.rows[i].cells[j].innerHTML.indexOf("$")>-1)
							{
								this.subtotal = psGetInnerText(prodTable.rows[i].cells[j]).replace("$","");
								break;
							}
						}
					}
					if(prodTable.rows[i].innerHTML.search(/Shippping:/gi)>-1)
					{
						for(var j=0; j<prodTable.rows[i].cells.length; j++)
						{
							if(prodTable.rows[i].cells[j].innerHTML.indexOf("$")>-1)
							{
								this.shipping = psGetInnerText(prodTable.rows[i].cells[j]).replace("$","");
								break;
							}
						}
					}
				}
			}
			if (!this.id)
				this.id = psGenerateRandomValue();
			/*
			 * Extract user profile from source code
			 */
			var uP = new psProfile();
			uP.readProfile();  // Ensure to get the customer Id & email persisted at login stage
			
			var tblItem = null;
			var bList = document.getElementsByTagName("b");
			for (var i=0; i<bList.length; i++)
			{
				var se = /Billing\s*Information:/gi;
				if(bList[i].innerHTML.search(se)>-1)
				{
					tblItem = bList[i].parentNode;
					while(!psIsEqual(tblItem.tagName,"body") && !psIsEqual(tblItem.tagName,"table"))
					{
						tblItem = tblItem.parentNode;
					}
					break;
				}
			}
			if(tblItem != null)
			{
				for(var i=0; i<tblItem.rows.length; i++)
				{
					if(tblItem.rows[i].innerHTML.indexOf("Email")>-1)
					{
						var se = /Email:\s*([^\<]*)\s*\<\/td\>/gi;
						uP.cusId = uP.email = (tblItem.rows[i].innerHTML.search(se)>-1)? RegExp.$1:null;
						se = /\<br\/*\>\s*(\w*)\s*\,*\s*(\w*)\s*(\d*)\s*\<br\/*\>/gi;
						if(tblItem.rows[i].innerHTML.search(se)>-1)
						{
							uP.city = RegExp.$1;
							uP.state = RegExp.$2;
							uP.zipcode = RegExp.$3;
						}
						break;
					}
				}
			}
			if (!uP.cusId)
				uP.cusId = psGenerateRandomValue();
			return uP.writeProfile(); // Persist profile for later use at Receipt stage
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all unaccepted characters in categoryid, including
 * [, ', ", :, comma,]
 * RETURN: string
 */
function psCleanCatId(pCatId)
{
    return (pCatId != null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

function psCleanProductName(pProductName)
{
	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

/* PURPOSE: Remove all leading & trailing spaces of a string
 * Note: [&nbsp;] is also considered as a space
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;
	return (pStr != null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

/* PURPOSE: extract value from the URL
 * in format of http://xxx.com/page.ext?key1=value1&key2=value2
 * or key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
function psGetValueFromUrl(pUrl, pKey)
{
	pUrl = (pUrl != null) ? "?" + psTrim(pUrl.toLowerCase()) : null;
	pKey = (pKey != null) ? psTrim(pKey.toLowerCase()) : null;

	if (pUrl == null || pKey == null || pUrl.indexOf(pKey) == -1) 
		return null;
	
	var start = pUrl.indexOf('&' + pKey + '=');
	start = (start == -1) ? pUrl.indexOf('?' + pKey + '=') : start;
	if (start >= 0)
	{
		start = start + pKey.length;
		var end = pUrl.indexOf("&", start);
		if(end == -1) 
			end = pUrl.length;
		var middle = pUrl.indexOf("=", start);
		return pUrl.substring(middle + 1, end);
	}
	return null;
}

/* PURPOSE: returns the value of an element based on element_id
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 */
function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}

/* PURPOSE: returns the value of an element based on element object
 * Note: this function returns decoded text
 * to avoid "double" decode, don't invoke psHtmlDecode on returned value again
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN: 
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 *  NULL: if element not exist
 */
function psGetElementValue(pTagObj, pValueFlag)
{
    var tagValue = null;
    if (pTagObj != null)
    {
        if (pTagObj.tagName.search(/^INPUT$/i) > -1)
            tagValue = pTagObj.value;
        else if (pTagObj.tagName.search(/^SELECT$/i) > -1)
        {
            if (pValueFlag == true)
                tagValue = pTagObj.options[pTagObj.selectedIndex].value;
            else
                tagValue = psHtmlDecode(pTagObj.options[pTagObj.selectedIndex].innerHTML);// return label instead of value
        }
        else
		{
            tagValue = psHtmlDecode(pTagObj.innerHTML);
		}
    }

    return tagValue;
}

/* PURPOSE: validate email format
 * RETURN: boolean
 */
function psCheckEmail(pEmail) 
{
    if (pEmail)
    {
        var i = pEmail.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
        return (i > -1);
    }

    return false;
}

/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
function psHtmlDecode(pValue)
{
    if (pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
		pValue = pValue.replace(/%27/gi, "'");
    }

    return pValue;
}

/* PURPOSE: extract main domain from the URL
 * RETURN: main domain
 */
function psGetMainDomain(pUrl){
	var se = /^https*\:\/\/([^\/\:]+)/gi;
	var domain = (pUrl.search(se) > -1) ? RegExp.$1 : null;
	if(domain != null)
	{
		if(domain.indexOf("www")==0)
		{
			domain = domain.substring(4,domain.length);
		}
		if(G_PS_ARR_DOMAIN != null)
		{
			for(var i =0; i<G_PS_ARR_DOMAIN.length; i++)
			{
				se = new RegExp("[\.]" + G_PS_ARR_DOMAIN[i] + "$","gi");
				if(("." + domain).search(se) > -1)
				{
					domain = G_PS_ARR_DOMAIN[i];
					break;
				}
			}
		}
		domain = "." + domain;
	}
	return domain;
	
}

/* PURPOSE: extract domain part in the URL
 * RETURN: domain
 */
function psGetDomain(pUrl){
    var se = /^https*\:\/\/([^\/\:]+)/gi;
    return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}

/* PURPOSE: remove unnecessary characters (dollar sign, comma, quote, minus, etc) 
 * from price to make it work properly with parseFloat/parseInt
 * RETURN: well-formed price
 */
function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

/* PURPOSE: retrieve cookie value
 * RETURN: string
 */
function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if (!pCookieName || !cookies)
		return null;

	cookies = "; " + cookies.toLowerCase();
	var key = "; " + pCookieName.toLowerCase() + "=";
	var start = cookies.lastIndexOf(key);
	if (start >= 0)
	{
		start = start + key.length;
		var end = cookies.indexOf(";", start);
		if (end == -1)
			end = cookies.length;

		return unescape(cookies.substring(start, end));
	}

    return null;
}

function psCookieBase(pCookieName, pCookieValue, pLifeTime)
{
	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
	if(pLifeTime == "delete") 
	{         
		return true;
	}
	
	// set cookie by calling coremetrics's cookie function
	var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
	
	return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

function encodeHtml(strValue)
{
	if (strValue!=null)
	{
		strValue = escape(strValue);
		strValue = strValue.replace(/\//g,"%2F");
		strValue = strValue.replace(/\?/g,"%3F");
		strValue = strValue.replace(/=/g,"%3D");
		strValue = strValue.replace(/&/g,"%26");
		strValue = strValue.replace(/@/g,"%40");
	}
	return strValue;
}

/* PURPOSE: set cookie value
 * Note: if the designated cookie is too big, the old items will be removed
 * because cookie size is limited to 4K
 * @pLifeTime in seconds
 * pDomain: don't specify if using current domain
 * RETURN: boolean
 */
function psSetCookie(pCookieName, pCookieValue, pLifeTime)
{
	if (!pCookieName)
	{
		return false;
	}
	
	pCookieValue = (pCookieValue==null)? "null":pCookieValue;
	
	if(pLifeTime != "delete")
	{
		pCookieName = psTrim(pCookieName);
		var oldCookieValue = psGetCookie(pCookieName);
		oldCookieValue = (oldCookieValue==null)? "null":oldCookieValue;
		var totalSize;
		if(document.cookie.indexOf(pCookieName)>-1)
		{
			totalSize =  document.cookie.length + encodeHtml(pCookieValue).length - encodeHtml(oldCookieValue).length;
		}
		else
		{
			totalSize =  document.cookie.length  + encodeHtml(pCookieValue).length + encodeHtml(pCookieName).length;
		}
		if(totalSize > 3500)
		{
			return false;
		}
	}
	psCookieBase(pCookieName,pCookieValue,pLifeTime);
}

/* PURPOSE: set value in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 * NOTE: Use null or '' for pValue to remove the pair specified by pKey
 */
function psSetValueToCookie(pCookieName, pKey, pValue)
{
	if (!pCookieName || !pKey)
	{
		return false;
	}

	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie == null) ? "" : catCookie;
	pValue = (pValue == null) ? "null" : pValue;
	var oldCatCookie = catCookie;
	
	var start = catCookie.indexOf(pKey);
	
	var totalsize;
	if (start >= 0) // Store before -> remove the old value
	{
		var oldValue = psGetValueFromCookie(pCookieName,pKey.replace(/[\~\#]/gi,""));
		oldValue = (oldValue == null) ? "null" : oldValue;
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1)
			end = catCookie.length;
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length - encodeHtml(oldValue).length;
	}
	else
	{
		totalsize =  document.cookie.length  + encodeHtml(pKey).length + encodeHtml(pValue).length;  
		if(document.cookie.indexOf(pCookieName)<0)
		{
			totalsize += encodeHtml(pCookieName).length;
		}
	}
	catCookie = pKey + pValue + catCookie;
	var cookieArray = null;   
	//Check existed ?
	while (totalsize > 3500)
	{
		var l1 = encodeHtml(catCookie).length;//length before pop
		cookieArray = catCookie.split("#");
		cookieArray.pop();
		catCookie = cookieArray.join("#");
		var l2 = encodeHtml(catCookie).length;//length after pop                                                        
		totalsize -=  (l1-l2);
	}   
	if(catCookie == null || catCookie == "")
	{
		catCookie = oldCatCookie;
	}
	// Save to cookie              
	psCookieBase(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

/* PURPOSE: get value stored in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 */
function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if (catCookie != null)
    {
        var start = catCookie.indexOf(pKey);
		if (start >=0 )
		{
			start = start + pKey.length;
			var end = catCookie.indexOf("#", start);
			if (end == -1)
				end = catCookie.length;
			return catCookie.substring(start, end);
		}
		return null;
    }
    return null;
}

/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dtDate = new Date();
	var cusRandom = (dtDate.getTime()%10000000) + (Math.floor(Math.random()*10000));
	return cusRandom;
}

function psShorttenPageID(pLink)
{
	var temp1 = pLink;
	if (temp1 != null)
	{
		temp1 = (temp1.length > 255) ? temp1.substr(0, 255) : temp1;
	}
	return temp1;
}

function psCheckElementExist(pElement){
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }

    return true;
}

function psCheckCategoryId(pCatId){
    if(typeof(pCatId) == "undefined" || pCatId == null || pCatId.toLowerCase() == "null")
    {
        return false;
    }

    return true;
}
/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(pId);
	pId = psShorttenPageID(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateProductviewTag(" + pId + ", " + pName + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateProductviewTag(pId, pName, pCatId);
}

function psCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction5Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction5Tag(pId, pName, pQuantity, pPrice, pCatId);    
}

function psCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId) 
{
	pName = psCleanProductName(pName);
	pCatId = psCleanCatId(pCatId);
	pQuantity = psCleanPrice(pQuantity);
	pPrice = psCleanPrice(pPrice);
	pOrderTotal = psCleanPrice(pOrderTotal);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateShopAction9Tag(" + pId + ", " + pName + ", " + pQuantity + ", " + pPrice + ", " + pCusID + ", " + pOrderID + ", " + pOrderTotal + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateShopAction9Tag(pId, pName, pQuantity, pPrice, pCusID, pOrderID, pOrderTotal, pCatId);
}

function psCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip) 
{
	pOrderTotal = psCleanPrice(pOrderTotal);
	pOrderShipping = psCleanPrice(pOrderShipping);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateOrderTag(" + pId + ", " + pOrderTotal + ", " + pOrderShipping + ", " + pCusID + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateOrderTag(pId, pOrderTotal, pOrderShipping, pCusID, pCusCity, pCusState, pCusZip);
}

function psCreateConversionEventTag(pId, pActionType, pCatID, pPoints) 
{
	pCatID = psCleanCatId(pCatID);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateConversionEventTag(" + pId + ", " + pActionType + ", " + pCatID + ", " + pPoints + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateConversionEventTag(pId, pActionType, pCatID, pPoints);
}

function psCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe) 
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateRegistrationTag(" + pCusID + ", " + pCustEmail + ", " + pCusCity + ", " + pCusState + ", " + pCusZip + ", " + pNewsletter + ", " + pSubscribe + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateRegistrationTag(pCusID, pCustEmail, pCusCity, pCusState, pCusZip, pNewsletter, pSubscribe);
}

function psCreateErrorTag(pPageID, pCatId) 
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreateErrorTag(" + pPageID + ", " + pCatId + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreateErrorTag(pPageID, pCatId);
}

function psDisplayShop5s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop5s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop5s();
}

function psDisplayShop9s()
{
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmDisplayShop9s()");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmDisplayShop9s();
}
/*===========================END GENERAL UTILITY FUNCTION ==================*/