/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.1, 2009/12/09
 * 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("bissingers.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";
var G_PS_COOKIE_ORDER_HISTORY_ITEM = "PS_ORDER_HISTORY_ITEM";
var G_PS_COOKIE_TEMP_PROFILE = "PS_TEMP_PROFILE";
var G_PS_COOKIE_ORDER = "PS_ORDER";
var G_PS_COOKIE_ITEM_IN_CART = "PS_ITEM_IN_CART";
var G_PS_CUR_CATID = null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if (G_PS_URL_PATH.search(/bissingers\.com/i) >= 0){
	if(psIsErrorPage()){
		psCreateErrorTag("Error", "Error");
	}else if (psIsSearchView())
	{
		psPostSearchView();
	}
	else if (psIsProductView())
	{
		psPostRegistration();
		psPostProductView();
		psHijackAddToOrder();
	}
	else if (psIsCartView())
	{
		psPostCartView();
		psHijackUpdateQuantity();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else 
	{	
		if(psPostPageView() == false){
			psCreatePageviewTag(G_PS_PATHNAME, "ADD URL");
		}
	}
	psHijackCrossSellTopMenu();
	psHijackSuggestedItems();	
}

function psPostPageView(){
	var pPageId = null;
	var pCatId = null;
	var updateCatIdCookie = true;
	
	if(G_PS_PATHNAME == "/"){
		pPageId = "Home Page";
		pCatId = "Home";
	}else if(G_PS_PATHNAME.indexOf("category/detail/interim.php") >= 0){		
		pPageId = pCatId = "Item Added to Cart";		
		updateCatIdCookie = false;
	}else{
		// Get PageId and CategoryID from URL for top menu, content page, account page, and category 
		var paths = psGetPathItems(G_PS_PATHNAME);
		if(paths != null){
			if(paths.length == 1){
				pPageId = paths[0];
				pCatId = "Home";
			}else if(paths.length > 1){
				pPageId = paths[paths.length -1];
				pCatId = paths[paths.length -2];
				if(pCatId == "giftfinder"){
					pCatId = "Gift Finder";
					var gf_cat = psGetValueFromUrl(G_PS_URL_PATH,"gf_cat");
					var price = psGetValueFromUrl(G_PS_URL_PATH,"price");					
					if((gf_cat != null && gf_cat != "") || (price != null && price != "")){
						var headSpans = psGetElementsByClassName(document,"span","darkHeadline");
						if(psCheckArrayExist(headSpans)){
							pPageId = psGetInnerText(headSpans[0]);
						}
					}
				}
				if(pCatId == "quickorder"){
					pCatId = "Quick Order";
					psHijackQuickOrder();
				}
				if(pCatId == "aboutus") pCatId = "About Us";
				if(pCatId == "my_account") pCatId = "Account";
				if(pCatId == "category"){
					// Category page
					pCatId = (pPageId.indexOf("-") >= 0)? pPageId.split("-")[0]: pPageId;
					var headSpans = psGetElementsByClassName(document,"span","darkHeadline");
					if(psCheckArrayExist(headSpans)){
						pPageId = (pPageId.indexOf("-") >= 0)? psTrim(psGetInnerText(headSpans[0])) + " Page " + pPageId.split("-")[1]: psGetInnerText(headSpans[0]);
					}					
				}
			}
		}
	}

	if(G_PS_PATHNAME.indexOf("my_account/order_detail.php") >= 0){
		psHijackPreviousBoughtItems();
	}
	
	// Hijack for registration
	if(G_PS_PATHNAME.indexOf("/my_account/login.php") >= 0 ||
	   G_PS_PATHNAME.indexOf("/checkout/checkout.php") >= 0){
		psHijackLogin();
		updateCatIdCookie = false;
	}else if(G_PS_PATHNAME.indexOf("/my_account/home.php") >= 0 ||			 
	         G_PS_PATHNAME.indexOf("/checkout/shipping.php") >= 0 ||
			 G_PS_PATHNAME.indexOf("/checkout/billing.php") >= 0){
		psPostRegistration();
	}
	
	if(G_PS_PATHNAME.indexOf("/my_account/create.php") >= 0 || 
	         G_PS_PATHNAME.indexOf("/checkout/billing.php") >= 0 || 
	         G_PS_PATHNAME.indexOf("/my_account/edit.php") >= 0){
		psHijackCreateOrEditAccount();
	}
	if(G_PS_PATHNAME.indexOf("/checkout/review.php") >= 0){
		psPostRegistration();
		psSaveShippingSubtotal();
	}

	if(pPageId == null || pCatId == null){
		return false;
	}
	
	if(G_PS_PATHNAME.search(/checkout\/(billing|shipping|payment|review|confirmation)\.php/i) >= 0){
		pPageId = "Checkout:" + pPageId;
	}
	
	//pPageId = pPageId.replace(/\_/g," ");
	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));
	
	pPageId = pPageId.toUpperCase();
	pCatId = pCatId.toUpperCase();

	psCreatePageviewTag(pPageId, pCatId, null, null);	
	if(updateCatIdCookie){
		if(G_PS_PATHNAME.indexOf("/sitemap.html") >= 0){
			psSetCookie(G_PS_COOKIE_CATID,pPageId);
		}else{
			psSetCookie(G_PS_COOKIE_CATID,pCatId);
		}
	}
	
	return true;
}

function psIsErrorPage(){	
	var pHead = psGetElementsByClassName(document,"span","darkHeadline");
	if(psCheckArrayExist(pHead)){
		var temp = psTrim(psGetInnerText(pHead[0]));
		if(temp != null && temp.search(/Page\s+Not\s+Found/i) >= 0){			
			return true;
		}
	}
	return false;
}

function psHijackUpdateQuantity(){
	var checkout = psGetElementByName("input","checkout");
	if(psCheckElementExist(checkout)){
		if(checkout.onclick == null || checkout.onclick.toString().indexOf("psHJUpdateQuantity") < 0){
			checkout.OldFunction = checkout.onclick;
			checkout.onclick = function psHJUpdateQuantity(){
				if(psIsUpdateQuantity() == true)
					psPostCartView();
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
		// Hijack on enter
		checkout.OldFunction2 = checkout.onkeypress;
		checkout.onkeypress = function (e){
			try
			{
				var key = window.event ? event.keyCode : e.keyCode;
				if(key == 13){					
					if(psIsUpdateQuantity() == true)
						psPostCartView();
					if(this.OldFunction2 != null) 
						return this.OldFunction2();	
				}
			}
			catch (ex) {}
		}		
	}	
}

function psIsUpdateQuantity(){	
	var itemInCart = "";
	var inputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(inputs)){
		for(var i=0; i<inputs.length; i++){
			if(inputs[i].name != null && inputs[i].name.search(/^qty/i) >= 0){
				var quantity = psTrim(inputs[i].value);
				itemInCart += quantity + " ";
			}
		}
	}
	var preItem = psGetCookie(G_PS_COOKIE_ITEM_IN_CART);
	if(preItem == null || preItem == "" || itemInCart == "")
		return false;
	
	if(psGetCookie(G_PS_COOKIE_ITEM_IN_CART) == psTrim(itemInCart))
		return false;
	return true;
}

function psSaveShippingSubtotal(){

	psSetCookie(G_PS_COOKIE_ORDER,"","delete");
	
	// If we shipping to many packages, it will contains many shipping cost
	// The shipping cost will be total of them.
	var shipping = 0;
	var tables = document.getElementsByTagName("table");	
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){
			var firstRow = psGetInnerText(tables[i].rows[0]);
			if(firstRow != null && firstRow.search(/^\s*Item\s+Description\s*Item\s*\#/i) >= 0){
				var desTable = tables[i];
				if(desTable.rows.length < 2) continue;				
				var rows = desTable.rows;
				for(var r=1; r<rows.length; r++){		
					if(psGetInnerText(rows[r]).search(/Shipping\s*\:/i) >= 0){			
						var packageShip = psCleanPrice(psGetInnerText(rows[r]).replace(/Shipping\s*\:/,""));			
						if(isFinite(packageShip)){
							shipping += parseFloat(packageShip);
						}
					}
				}							
			}
		}
	}
	psSetValueToCookie(G_PS_COOKIE_ORDER,"shipping",shipping);
	
	// Get subtotal
	var subtotal = null;
	var subTds = psGetElementsByClassName(document,"td","orderSubtotal");
	if(psCheckArrayExist(subTds)){
		for(var i=0; i<subTds.length; i++){
			var temp = psTrim(psGetInnerText(subTds[i]));
			if(temp != null && temp.search(/^ORDER\s+SUBTOTAL\:/i) >= 0){
				var subRow = subTds[i].parentNode;
				var subTd = subRow.cells[subRow.cells.length-1];
				subtotal = psCleanPrice(psTrim(psGetInnerText(subTd)));				
				if(isFinite(subtotal) && isFinite(shipping)){
					subtotal = parseFloat(subtotal) - parseFloat(shipping);
					subtotal = subtotal.toFixed(2);
				}
				psSetValueToCookie(G_PS_COOKIE_ORDER,"subtotal",subtotal);				
			}
		}
	}
}

function psHijackCreateOrEditAccount(){	
	var cookieFlag = "edit";
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	if(G_PS_PATHNAME.indexOf("/my_account/create.php") >= 0){
		psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
		cookieFlag = "create";
	}
	var frm = null;
	if(G_PS_PATHNAME.indexOf("/checkout/billing.php") >= 0){
		// for billing page
		var forms = document.getElementsByTagName("form");
		if(psCheckArrayExist(forms)){
			for(var i=0; i<forms.length; i++){
				if(forms[i].innerHTML != null && forms[i].innerHTML.search(/BILLING\s+INFORMATION/i) >= 0){
					frm = forms[i];
					break;
				}
			}
		}
	}else{
		// For create & edit account
		frm = psGetElementByName("form","form");
	}
		
	if(psCheckElementExist(frm)){
		if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJCreateEditAccount") < 0){
			frm.OldFunction = frm.onsubmit;
			frm.onsubmit = function psHJCreateEditAccount(){
				var uP = new psProfile();
				var email = psGetElementByName("input","email");
				if(psCheckElementExist(email)) uP.cusId = uP.email = psTrim(email.value);
				
				var city = psGetElementByName("input","city");
				if(psCheckElementExist(city)) uP.city = psTrim(city.value);
				
				var state = psGetElementByName("select","state");
				if(psCheckElementExist(state)) uP.state = state.options[state.selectedIndex].value;

				var zipcode = psGetElementByName("input","zip");
				if(psCheckElementExist(zipcode)) uP.zipcode = psTrim(zipcode.value);
				
				if(uP.cusId != null){
					if(cookieFlag == "create"){
						uP.writeProfile();
					}else{
						// edit can be unsuccessful, must store new information to temporary cookie
						var data = uP.cusId + "|" + uP.email + '|' + uP.city + '|' + uP.state + '|' 
							+ uP.zipcode + "|" + uP.newsletter + '|' + uP.subscribe;						
						psSetCookie(G_PS_COOKIE_TEMP_PROFILE, data);
					}
					psSetCookie(G_PS_COOKIE_FLAG,cookieFlag);
				}				
			}
			if(this.OldFunction != null) return this.OldFunction();
		}
	}
}

function psPostRegistration(){
	var cookieFlag = psGetCookie(G_PS_COOKIE_FLAG);
	if(cookieFlag == "login" || cookieFlag == "create"){
		var uP = new psProfile();
		uP.readProfile();
		if(uP.cusId != null)
		{
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
		}
	}else if(cookieFlag == "edit"){
		// Just edit account or update billing address
		// If just update billing address, copy user info from temporary profile to profile, not send registration
		var uP = new psProfile();
		uP.cusId = psGetCookie(G_PS_COOKIE_TEMP_PROFILE);
		if (uP.cusId != null)
		{
			var buf = uP.cusId.split('|');
			for (var i=0; i<buf.length; i++)
			{
				var tempVal = buf[i];				
				buf[i] = (tempVal=="null" ? null : tempVal); 
			}
			uP.cusId = buf[0];			
			uP.email = buf[1];
			uP.city = buf[2];
			uP.state = buf[3];
			uP.zipcode = buf[4];
			uP.newsletter = buf[5];
			uP.subscribe = buf[6];
			if(G_PS_PATHNAME.indexOf("/my_account/home.php") >= 0 ||
			   G_PS_PATHNAME.indexOf("/checkout/shipping.php") >= 0){
				// Just edit account
				psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
			}
			uP.writeProfile();
		}		
		psSetCookie(G_PS_COOKIE_TEMP_PROFILE,"","delete");
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
}

function psHijackLogin(){
	psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	// Find login form
	var loginForm = null;
	var forms = document.getElementsByTagName("form");
	if(psCheckArrayExist(forms)){
		for(var i=0; i<forms.length; i++){
			if(forms[i].innerHTML != null && forms[i].innerHTML.search(/(My\s+Current\s+Account|login\.gif)/i) >= 0){
				loginForm = forms[i];
				break;
			}
		}
	}
	if(loginForm == null) return;
	// Hijack
	if(loginForm.onsubmit == null || loginForm.onsubmit.toString().indexOf("psHJLogin") < 0){
		loginForm.OldFunction = loginForm.onsubmit;
		loginForm.onsubmit = function psHJLogin(){
			var emailTag = psGetElementByName("input","email");
			if(psCheckElementExist(emailTag)){
				var email = psTrim(emailTag.value);
				if(psCheckEmail(email)){					
					var uP = new psProfile();
					uP.cusId = uP.email = email;
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"login");
				}
			}
			if(this.OldFunction != null) return this.OldFunction();
		}
	}
}

function psHijackPreviousBoughtItems(){
	//Save Item# to cookie to determine the product category Id for product ordered from order history
	psSetCookie(G_PS_COOKIE_ORDER_HISTORY_ITEM,"","delete");
	
	var orderToCart = psGetElementByName("input","copy");
	if(psCheckElementExist(orderToCart)){
		if(orderToCart.onclick == null || orderToCart.onclick.toString().indexOf("psHJPreBoughtItems") < 0){
			orderToCart.OldFunction = orderToCart.onclick;
			orderToCart.onclick = function psHJPreBoughtItems(){				
				var tables = document.getElementsByTagName("table");				
				if(psCheckArrayExist(tables)){
					for(var i=0; i<tables.length; i++){
						var firstRow = psGetInnerText(tables[i].rows[0]);
						if(firstRow != null && firstRow.search(/^\s*Item\s+Description\s*Item\s*\#/i) >= 0){
							var desTable = tables[i];
							var rows = desTable.rows;
							if(rows.length < 2) continue;
							for(var r=1; r<rows.length; r++){
								if(rows[r].cells.length < 5) continue;
								var prdId = psTrim(psGetInnerText(rows[r].cells[1]));								
								psSetValueToCookie(G_PS_COOKIE_ORDER_HISTORY_ITEM,prdId,"account");						
							}									
						}
					}
				}				
			}
		}
	}	
}

function psGetItemDescriptionTable(){
	var tables = document.getElementsByTagName("table");
	var desTable = null;
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){
			var firstRow = psGetInnerText(tables[i].rows[0]);
			if(firstRow != null && firstRow.search(/^\s*Item\s+Description\s*Item\s*\#/i) >= 0){
				desTable = tables[i];				
				break;
			}
		}
	}
	return desTable;
}

function psHijackQuickOrder(){
	var frm = psGetElementByName("form","form");
	if(psCheckElementExist(frm)){
		if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJQuickOrder") < 0){
			frm.OldFunction = frm.onsubmit;
			frm.onsubmit = function psHJQuickOrder(){
				var pCatId = psGetCookie(G_PS_COOKIE_CATID);				
				var tdTags = frm.getElementsByTagName("td");
				if(psCheckArrayExist(tdTags)){
					for(var i=0; i<tdTags.length; i++){
						var temp = psTrim(psGetInnerText(tdTags[i]));
						if(temp != null && temp.search(/^catalog\s+item\s+number$/i) >= 0){
							var row = tdTags[i].parentNode;
							var items = psGetElementsByClassName(row,"input","formcell");
							if(psCheckArrayExist(items)){
								for(var j=0; j<items.length; j++){
									var prdId = psTrim(items[j].value);
									if(prdId != "" && prdId.search(/^\d+/) >= 0){
										psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prdId,pCatId);										
									}
								}
							}
						}
					}
				}				
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}	
}

function psHijackAddToOrder(){
	var frm = psGetElementByName("form","form");
	if(psCheckElementExist(frm)){		
		if(frm.onsubmit == null || frm.onsubmit.toString().indexOf("psHJAddToOrder") < 0){
			frm.OldFunction = frm.onsubmit;
			frm.onsubmit = function psHJAddToOrder(){				
				var desTable = psGetItemDescriptionTable();
				if(desTable != null){
					var pCatId = psGetCookie(G_PS_COOKIE_CATID);
					var rows = desTable.rows;
					if(rows.length > 1){
						for(var i=1; i<rows.length; i++){
							if(rows[i].cells.length > 3){
								var quanInputs = psGetElementsByClassName(rows[i],"input","formcell");
								if(psCheckArrayExist(quanInputs)){
									var quantity = psTrim(quanInputs[0].value);
									if(quantity != null && quantity.search(/^\d+/i) >= 0){
										var prdId =  psTrim(psGetInnerText(rows[i].cells[1]));
										psSetValueToCookie(G_PS_COOKIE_PROD_CATID,prdId,pCatId);
									}
								}							
							}
						}
					}					
				}
				if(this.OldFunction != null) return this.OldFunction();
			}
		}
	}
}

function psHijackSuggestedItems(){
	var spans = psGetElementsByClassName(document,"span","goldHeadline");
	if(psCheckArrayExist(spans)){
		for(var i=0; i<spans.length; i++){
			var pInnerText = psGetInnerText(spans[i]);
			if(pInnerText != null && pInnerText.search(/^\s*Suggested\s+items/i) >= 0){				
				var aTags = spans[i].parentNode.getElementsByTagName("a");
				if(psCheckArrayExist(aTags)){
					for(var j=0; j<aTags.length; j++){					
						var aTag = aTags[j];						
						if( (aTag.parentNode.innerHTML != null &&  aTag.parentNode.innerHTML.search(/buymore\d+\.gif/i) >= 0) ||
						    (aTag.className != null && aTag.className.toLowerCase()== "body"))
							continue;
						if(aTag.href != null && aTag.href.search(/category\/detail\//i) >= 0){							
							if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJSuggestedItems") < 0){
								aTag.OldFunction = aTag.onclick;
								aTag.onclick = function psHJSuggestedItems(){
									psSetCookie(G_PS_COOKIE_CATID,"Suggested Items");
									if(this.OldFunction != null) return this.OldFunction();
								}
							}
						}
					}
				}
			}
		}
	}
}

function psHijackCrossSellTopMenu(){
	var tables = document.getElementsByTagName("table");
	if(psCheckArrayExist(tables)){		
		var tdTags = tables[0].getElementsByTagName("td") ;
		if(psCheckArrayExist(tdTags)){
			for(var i=0; i<tdTags.length; i++){
				if(tdTags[i].getAttribute("background") != null && tdTags[i].getAttribute("background").search(/home_topbg\.gif/i) >= 0){
					var aTags = tdTags[i].getElementsByTagName("a");
					if(psCheckArrayExist(aTags)){
						for(var j=0; j<aTags.length; j++){
							var aTag = aTags[j];
							if(aTag.href != null && aTag.href.search(/category\/detail\//i) >= 0){								
								if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJTopMenu") < 0){
									aTag.OldFunction = aTag.onclick;
									aTag.onclick = function psHJTopMenu(){
										psSetCookie(G_PS_COOKIE_CATID,"cross sell");
										if(this.OldFunction != null) return this.OldFunction();
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

function psGetPathItems(path){
	if(path == null || psTrim(path) == "")
		return null;	
	path = path.replace(/\.(php|html|htm|asp|aspx)/i,"");
	path = path.replace(/\/$/,"");	
	if(path.indexOf("/") >= 0){
		path = path.replace("/","");
		if(path.indexOf("/") >= 0) return path.split("/");
	}
	return new Array(path);	
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	if(G_PS_PATHNAME.indexOf("/search/results.php") >= 0)
		return true;
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	if(G_PS_PATHNAME.indexOf("/category/detail/interim.php") >= 0)
		return false;
	if(G_PS_PATHNAME.search(/category\/detail\/\d+\.(htm|php|asp)/i) >= 0 || 
	   G_PS_PATHNAME.indexOf("/category/detail/detail.php") >= 0)
		return true;
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_PATHNAME.indexOf("checkout/viewcart.php") >= 0)
		return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_PATHNAME.indexOf("/checkout/confirmation.php") >= 0)
		return true;
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	G_PS_CUR_CATID = "SEARCH";
	var pageId = "SEARCH UNSUCCESSFUL";
	var sTerm = psGetSearchTerm();
	var sResult = psGetSearchResult();
	if(sResult != "0"){
		pageId = "SEARCH SUCCESSFUL";
	}
	psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult);
	psSetCookie(G_PS_COOKIE_CATID,G_PS_CUR_CATID);
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	var headSpans = psGetElementsByClassName(document,"span","darkHeadline");
	if(psCheckArrayExist(headSpans)){
		term = psTrim(psGetInnerText(headSpans[0]));
	}
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	var tdResults = document.getElementsByTagName("td");
	if(psCheckArrayExist(tdResults)){
		for(var i=0; i<tdResults.length; i++){
			var res = psGetInnerText(tdResults[i]);
			if( res != null && res.search(/Found\:\s*\d+/i) >= 0){
				result = psTrim(res.replace(/Found\:/,""));
			}
		}
	}
	return result;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	// Send page view
	var pCatId = null;
	if(G_PS_URL_REFERRER.indexOf("bissingers.com") < 0){
		pCatId = "Bookmarks";
	}else{
		pCatId = psGetCookie(G_PS_COOKIE_CATID);		
	}
	var pPageId = null;
	
	var pHeadLines = psGetElementsByClassName(document,"span","darkHeadline");
	if(psCheckArrayExist(pHeadLines)){
		var temp = pHeadLines[0].innerHTML.replace(/<BR\s*\/*>/gi,"&nbsp;");		
		temp = psTrim(psGetInnerText(temp));
		temp = psTrim(psHtmlDecode(unescape(temp)));
		if(temp != "")
			pPageId = "Product:" + temp;
	}
	if(pPageId == null){
		var cHeadLines = psGetElementsByClassName(document,"span","categoryHeadline");
		if(psCheckArrayExist(cHeadLines)){
			pPageId = psGetInnerText(cHeadLines[0]).replace(/\·\s*VIEW\s+ALL/i,"");
			pPageId = "Product:" + psTrim(psHtmlDecode(unescape(pPageId)));
		}
	}
	if(pPageId != null)	pPageId = pPageId.toUpperCase();
	if(pCatId != null) pCatId = pCatId.toUpperCase();
	psCreatePageviewTag(pPageId, pCatId, null, null);	
	
	// Send product view
	var desTable = psGetItemDescriptionTable();
	if(desTable != null){
		var rows = desTable.rows;
		if(rows.length > 1){
			for(var i=1; i<rows.length; i++){
				if(rows[i].cells.length > 3){					
					var prdName = psTrim(psCleanProductName(psHtmlDecode(unescape(psGetInnerText(rows[i].cells[0])))));
					var prdId =  psTrim(psGetInnerText(rows[i].cells[1]));
					psCreateProductviewTag(prdId, prdName, pCatId);					
				}
			}
		}
	}	
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	psSetCookie(G_PS_COOKIE_ITEM_IN_CART,"","delete");
	var itemInCart = "";
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("VIEWCART", G_PS_CUR_CATID, null,null);
	var sendShop5Flag = false;
	// there are many cart tables if we package to different shipping address
	var cartTables = document.getElementsByTagName("table");
	if(psCheckArrayExist(cartTables)){
		for(var i=0; i<cartTables.length; i++){			
			var firstRow = psTrim(psHtmlDecode(unescape(psGetInnerText(cartTables[i].rows[0]))));			
			if(firstRow != null && firstRow.search(/^\s*Item\s+Description\s*Item\s*\#/i) >= 0){				
				var rows = cartTables[i].rows;				
				var prd = new psProduct();
				for (var r = 0; r < rows.length; r++) // item for each row
				{
					if (rows[r].innerHTML.search(/images\/remove\.gif/i)<0)
					  continue;					 
					if (prd.getItem5(rows[r])){
						psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
						sendShop5Flag = true;
						itemInCart += prd.quantity + " ";
					}
				}
			}
		}
	}	
	if(itemInCart != "") psSetCookie(G_PS_COOKIE_ITEM_IN_CART,psTrim(itemInCart));
	if(sendShop5Flag == true) psDisplayShop5s();
	psSetCookie(G_PS_COOKIE_ORDER_HISTORY_ITEM,"","delete");
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("Checkout:Confirmation", G_PS_CUR_CATID, null,null);	
	
	var ord = new psOrder();
	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();			
			var tables = document.getElementsByTagName("table");
			if(psCheckArrayExist(tables)){
				for(var i=0; i<tables.length; i++){			
					var firstRow = psTrim(psHtmlDecode(unescape(psGetInnerText(tables[i].rows[0]))));			
					if(firstRow != null && firstRow.search(/^\s*Item\s+Description\s*Item\s*\#/i) >= 0){				
						var rows = tables[i].rows;
						if(rows.length < 2) continue;
						for (var r = 1; r < rows.length; r++) // item for each row
						{
							if(rows[r].cells.length < 3 || psGetInnerText(rows[r]).search(/Shipping\s*\:/i) >= 0 ) continue;
							if (prd.getItem9(rows[r]))
								psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
						}						
					}
				}
			}					
			// Make sure to have actual postings
			psDisplayShop9s();
			psCreateOrderTag(ord.id, ord.subtotal, ord.shipping, uP.cusId, uP.city, uP.state, uP.zipcode);
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode, null, null);
			psSetCookie(G_PS_COOKIE_PROD_CATID, "", "delete");
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");			
			psSetCookie(G_PS_COOKIE_ORDER, "", "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!
			/*
			 * this.id = <from URL or source code>
			 * this.name = <from source code>
			 // In most cases, catId is retrived from cookie G_PS_COOKIE_CATID as follows:
			 * this.catId = psGetCookie(G_PS_COOKIE_CATID);
			 */
			// 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();
			this.name = psTrim(psCleanProductName(psHtmlDecode(unescape(psGetInnerText(itemRow.cells[1])))));
			this.id = psTrim(psGetInnerText(itemRow.cells[2]));
			this.price = psCleanPrice(psGetInnerText(itemRow.cells[4]));
			var quanInputs = itemRow.cells[5].getElementsByTagName("input");
			if(psCheckArrayExist(quanInputs)){
				this.quantity = psTrim(quanInputs[0].value);
			}
			if(this.id != null && this.id != ""){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null){
					// Bought from order history
					this.catId = psGetValueFromCookie(G_PS_COOKIE_ORDER_HISTORY_ITEM,this.id);
					if(this.catId != null && this.catId != ""){
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.id,this.catId);
					}
				}
			}
			if(this.id != "" && this.quantity != null && this.quantity != "0" && this.quantity.search(/^\d+/) >= 0 )
				return true;
			return false;
		}
		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.name = psTrim(psCleanProductName(psHtmlDecode(unescape(psGetInnerText(itemRow.cells[0])))));
			this.id =  psTrim(psGetInnerText(itemRow.cells[1]));
			this.price = psCleanPrice(psTrim(psGetInnerText(itemRow.cells[3])));
			this.quantity = psTrim(psGetInnerText(itemRow.cells[4]));
			this.catId = "unknown";
			if(this.id != null && this.id != "") this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID,this.id);
			if(this.catId == null){
				if(this.id == "9999" || this.price == "0.00"){
					this.catId = "Gift";
				}else{
					this.catId = "unknown";
				}
			}
			if(this.price == "0.00") this.price = "0";
			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 = psGetValueFromUrl(G_PS_URL_PATH,"id");
			this.subtotal = psGetValueFromCookie(G_PS_COOKIE_ORDER,"subtotal");
			this.shipping = psGetValueFromCookie(G_PS_COOKIE_ORDER,"shipping");
			if(this.id != null) 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)
{
    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, ">");
    }

    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 psCheckArrayExist(pArrElement){
    if(typeof(pArrElement) == "undefined" || pArrElement == null || pArrElement.length <= 0)
    {
        return false;
    }

    return true;
}
function psCheckElementExist(pElement){
    if(typeof(pElement) == "undefined" || pElement == null)
    {
        return false;
    }

    return true;
}

function psGetElementByName(tagName,elementName){	
	// return the first element
	var tags = document.getElementsByTagName(tagName);
	if(psCheckArrayExist(tags)){
		for(var i=0; i<tags.length; i++){
			if(tags[i].name != null && tags[i].name.toLowerCase() == elementName.toLowerCase()){
				return tags[i];
			}
		}
	}
	return null;
}

function psGetElementsByClassName(psDocument, psElementTagName, psClassName){
    var arrResult = new Array();
    var index = 0;
    var arrInputs = psDocument.getElementsByTagName(psElementTagName);
    if(arrInputs == null)
    {
        return null;
    }
    for(var i = 0; i < arrInputs.length; i ++ )
    {
        if(arrInputs[i].className.toLowerCase() == psClassName.toLowerCase())
        {
            arrResult[index ++ ] = arrInputs[i];
        }
    }
    return arrResult;
}

/********************************************************/
/* WRAPPER FOR COREMETRICS' TAG FUNCTIONS               */
/********************************************************/
function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult) 
{
	pId = psCleanPageId(pId);
	pId = psShorttenPageID(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
    if (G_PS_DEBUG_MODE == 1 || G_PS_DEBUG_MODE == 3)
        alert("cmCreatePageviewTag(" + pId + ", " + pCatId + ", " + pSrchTerm + ", " + pSrchResult + ")");
    if (G_PS_DEBUG_MODE == 2 || G_PS_DEBUG_MODE == 3)
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult);
}

function psCreateProductviewTag(pId, pName, pCatId) 
{
	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 ==================*/