/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v2.1, 2009/06/23
 * 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("ecohaus.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 = "CUR_CATID";

var G_PS_SEARCH_TERM = "SEARCH_TERM";
var G_PS_SEARCH_PAGE = "SEARCH_PAGE";

var G_PS_COOKIE_PRE_CATID = "G_PS_PRE_CATID";

/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
if (G_PS_URL_PATH.search(/ecohaus\.com/i) >= 0 && G_PS_URL_PATH.search(/\/staticheader\.aspx$/i) == -1 && G_PS_URL_PATH.search(/\/footer\.html$/i) == -1)
{
	var objPageNumberInfo = new pageNumberInfo();
	var objShowAllInfo = new showAllInfo();
	
	if (psIsSearchView())
	{
		psPostSearchView();
	}
	else if (psIsProductView())
	{
		psPostProductView();
		psHijackPeopleAlsoBought();
		psHijackRelatedItems();
	}
	else if (psIsCartView())
	{
		psPostCartView();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else if (G_PS_URL_PATH.search(/google\.com\//i) >= 0)
	{
		try
		{
			psParseGooglePage(G_PS_URL_PATH);
		}
		catch(e) {}
	}
	else
	{
		var objPageInfo = new pageInfo();		
		
		if (objShowAllInfo.isExist && objShowAllInfo.checked) objPageInfo.pageId += " Show All";
		else if (objPageNumberInfo.value != null) objPageInfo.pageId += " Page " + objPageNumberInfo.value;

		psPostAccountView();
		psPostCheckoutView();
		
		if(G_PS_PATHNAME.indexOf("/checkoutaddress.aspx") >= 0 || 
			G_PS_PATHNAME.indexOf("/checkoutshipping.aspx") >= 0 || 
			G_PS_PATHNAME.indexOf("/checkoutpayment.aspx") >= 0 || 
			G_PS_PATHNAME.indexOf("/thank_you.aspx") >= 0	){
			
			objPageInfo.catId = "CHECKOUT";
		}		

		if(objPageInfo.pageId != null){			
			psCreatePageviewTag(objPageInfo.pageId, objPageInfo.catId, null, null);			
		}else{
			psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
		}		
	}
}

function psPostAccountView(){
	if(G_PS_PATHNAME.indexOf("/login.aspx") >= 0){
		psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
		psHijackLogin();
	}else if(G_PS_PATHNAME.indexOf("/register.aspx") >=0 ){
		psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		psSetCookie(G_PS_COOKIE_PROFILE,"","delete");
		psHijackRegistration();
	}else if(G_PS_PATHNAME.indexOf("/register_complete.aspx") >= 0 || 
			 G_PS_PATHNAME == "/" || 
			 G_PS_PATHNAME == "/default.htm"){	
		psPostRegistration();
	}
}

function psHijackLogin(){
	var pLoginBtn = document.getElementById("ctl00_MainContent_LoginControl1_btnLogin_btnImage");
	if(psCheckElementExist(pLoginBtn)){
		if(pLoginBtn.onclick == null || pLoginBtn.onclick.toString().indexOf("HijackLogin") < 0){
			pLoginBtn.OldFunction = pLoginBtn.onclick;
			pLoginBtn.onclick = function HijackLogin(){
				var pLoginNameInput = document.getElementById("ctl00_MainContent_LoginControl1_ctlLoginName");
				if(psCheckElementExist(pLoginNameInput)){
					var pLoginName = psTrim(pLoginNameInput.value);
					var uP = new psProfile();
					uP.email = uP.cusId = pLoginName;					
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"LOGIN");
				}
				if(this.OldFunction != null) 
					return this.OldFunction();
			}
		}
	}
	var pPassword = document.getElementById("ctl00_MainContent_LoginControl1_ctlPassword");
	if(psCheckElementExist(pPassword)){
		pPassword.OldFunction = pPassword.onkeypress;
		pPassword.onkeypress = function (e){
			try
			{
				var key = window.event ? event.keyCode : e.keyCode;
				if(key == 13){
					var pLoginNameInput = document.getElementById("ctl00_MainContent_LoginControl1_ctlLoginName");
					if(psCheckElementExist(pLoginNameInput)){
						var pLoginName = psTrim(pLoginNameInput.value);
						var uP = new psProfile();
						uP.email = uP.cusId = pLoginName;					
						uP.writeProfile();
						psSetCookie(G_PS_COOKIE_FLAG,"LOGIN");
					}
					if(this.OldFunction != null) 
						return this.OldFunction();	
				}
			}
			catch (ex) {}
		}		
	}
}

function psPostRegistration(){
	if(psGetCookie(G_PS_COOKIE_FLAG) != null && psGetCookie(G_PS_COOKIE_FLAG).toUpperCase() == "LOGIN"){
		var uP = new psProfile();
		if(uP.readProfile()){
			psCreateRegistrationTag(uP.cusId, uP.email,uP.city, uP.state,uP.zipcode,uP.newsletter,uP.subscribe);
			psSetCookie(G_PS_COOKIE_FLAG,"","delete");
		}
	}
}

function psHijackRegistration(){
	var pSubmitBtn = document.getElementById("ctl00_MainContent_btnSubmit_LinkButton1");
	if(psCheckElementExist(pSubmitBtn)){
		if(pSubmitBtn.onclick == null || pSubmitBtn.onclick.toString().indexOf("HijackRegistration") < 0){
			pSubmitBtn.OldFunction = pSubmitBtn.onclick;
			pSubmitBtn.onclick = function HijackRegistration(){
				var uP = new psProfile();				
				var pEmail = document.getElementById("ctl00_MainContent_ContactInformation1_ctlEmail");
				if(psCheckElementExist(pEmail)){
					uP.cusId = uP.email = psTrim(pEmail.value);
				}
				var pCity = document.getElementById("ctl00_MainContent_ContactInformation1_ctlCity");
				if(psCheckElementExist(pCity)){
					uP.city = psTrim(pCity.value);				
				}
				var pState = document.getElementById("ctl00_MainContent_ContactInformation1_ctlStateList");
				if(psCheckElementExist(pState)){
					uP.state = pState.options[pState.selectedIndex].value;
				}
				var pZipcode = document.getElementById("ctl00_MainContent_ContactInformation1_ctlPostalCode");
				if(psCheckElementExist(pZipcode)){
					uP.zipcode = psTrim(pZipcode.value);
				}
				if(uP.email != null){					
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"LOGIN");
				}
				if(this.OldFunction != null) 
					return this.OldFunction();
			}
		}
	}
}

function psPostCheckoutView(){
	if(G_PS_PATHNAME.indexOf("/checkoutaddress.aspx") >= 0 ){		
		if(psGetCookie(G_PS_COOKIE_FLAG) != null && (psGetCookie(G_PS_COOKIE_FLAG).toUpperCase() == "UPDATE_BILLING" || psGetCookie(G_PS_COOKIE_FLAG).toUpperCase() == "LOGIN")){
			if(G_PS_URL_REFERRER.indexOf("/register.aspx") >= 0){
				var uP = new psProfile();
				if(uP.readProfile()){
					psCreateRegistrationTag(uP.cusId, uP.email,uP.city, uP.state,uP.zipcode,uP.newsletter,uP.subscribe);
					psSetCookie(G_PS_COOKIE_FLAG,"","delete");
				}
			}
		}
		psHijackGetBillingAddress();
	}else if(G_PS_PATHNAME.indexOf("/checkoutshipping.aspx") >= 0){
		if(psGetCookie(G_PS_COOKIE_FLAG) != null && (psGetCookie(G_PS_COOKIE_FLAG).toUpperCase() == "UPDATE_BILLING" || psGetCookie(G_PS_COOKIE_FLAG).toUpperCase() == "LOGIN")){
			var uP = new psProfile();
			if(uP.readProfile()){
				psCreateRegistrationTag(uP.cusId, uP.email,uP.city, uP.state,uP.zipcode,uP.newsletter,uP.subscribe);
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
			}
		}	
	}
}

function psHijackGetBillingAddress(){
	var pContinueBtn = document.getElementById("ctl00_MainContent_ThemeButton1_btnImage");
	if(psCheckElementExist(pContinueBtn)){
		if(pContinueBtn.onclick == null || pContinueBtn.onclick.toString().indexOf("HijackBillingAddress") < 0){
			pContinueBtn.OldFunction = pContinueBtn.onclick;
			pContinueBtn.onclick = function HijackBillingAddress(){
				var uP = new psProfile();
				uP.readProfile();
				var pCity = document.getElementById("ctl00_MainContent_billingAddress_ctlCity");
				if(psCheckElementExist(pCity)) 
					uP.city = psTrim(pCity.value);
				var pState = document.getElementById("ctl00_MainContent_billingAddress_ctlStateList");
				if(psCheckElementExist(pState))
					uP.state = pState.options[pState.selectedIndex].value;
				var pZipcode = document.getElementById("ctl00_MainContent_billingAddress_ctlPostalCode");
				if(psCheckElementExist(pZipcode))
					uP.zipcode = psTrim(pZipcode.value);
				var pEmail = document.getElementById("ctl00_MainContent_billingAddress_ctlEmail");
				if(psCheckElementExist(pEmail))
					uP.email = uP.cusId = psTrim(pEmail.value);
				
				if(uP.email != null){
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"UPDATE_BILLING");
				}
				if(this.OldFunction != null)
					return this.OldFunction();
				
			}
		}
	}
}

/*
 * Determine if the page is the search result page
 */
function psIsSearchView()
{
	psSetCookie(G_PS_SEARCH_TERM, "", "delete");
	psSetCookie(G_PS_SEARCH_PAGE, "", "delete");
	
	// Search entire site (it works fine only on Firefox)
	if (G_PS_URL_PATH.search(/\/searchresults\.html\?(.+)(searchFormSelect=entireSite)?\&q=(.+)\&sa=/i) >= 0)
	{
		psSetCookie(G_PS_SEARCH_TERM, RegExp.$3.replace(/\+/g, " ").replace(/\%20/g, " "));
		psSetCookie(G_PS_SEARCH_PAGE, "Entire Site Search ");
	}
	
	// Search entire site (make sure it can work on IE)
	else if (navigator.userAgent.search(/firefox/i) <= 0 && G_PS_URL_PATH.search(/\/searchresults\.html\?(.+)(searchFormSelect=entireSite)?\&q=(.+)\#(\d+)$/i) >= 0)
	{
		psSetCookie(G_PS_SEARCH_TERM, RegExp.$3.replace(/\+/g, " ").replace(/\%20/g, " "));
		psSetCookie(G_PS_SEARCH_PAGE, "Entire Site Search ");
	}
	
	// Search Catalog from not search result page
	else if (G_PS_URL_PATH.search(/\/SearchByKeyword\.aspx\?searchFormSelect=catalog\&word=([^\&]+)(\&submit=)?$/i) >= 0)
	{
		psSetCookie(G_PS_SEARCH_TERM, RegExp.$1.replace(/\+/g, " ").replace(/\%20/g, " "));
		psSetCookie(G_PS_SEARCH_PAGE, "Product Catalog Search ");
	}
	
	// Search Catalog from Search result page
	else if (G_PS_URL_PATH.search(/\/SearchByKeyword\.aspx\?word=(.+)$/i) >= 0)
	{
		psSetCookie(G_PS_SEARCH_TERM, RegExp.$1.replace(/\+/g, " ").replace(/\%20/g, " "));
		psSetCookie(G_PS_SEARCH_PAGE, "Product Catalog Search ");
	}
	
	if (psGetCookie(G_PS_SEARCH_TERM) != null && psGetCookie(G_PS_SEARCH_PAGE) != null) return true;
	return false;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	if (G_PS_URL_PATH.search(/\/P\-([^\/]+)\/(.+)/i) >= 0) return true;
	if (G_PS_URL_PATH.search(/\/Item_Detail\.aspx\?ItemCode=(.+)(\&title=(.+))?/i) >= 0) return true;
	if (G_PS_URL_PATH.search(/\/item_detail\.aspx\?LineUID=(\d+)/i) >= 0) return true;
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if (G_PS_URL_PATH.search(/\/view_cart\.aspx/i) >= 0) return true;
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_PATHNAME.indexOf("/thank_you.aspx") >= 0 )	
		return true;
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	psSetCookie(G_PS_COOKIE_CATID, "SEARCH");
	
	var sPage = psGetCookie(G_PS_SEARCH_PAGE);
	var sTerm = psGetCookie(G_PS_SEARCH_TERM);
	sTerm = psHtmlDecode(unescape(sTerm));
	sPage = (sPage != null) ? sPage.toUpperCase() : sPage;
	
	var sResult = 0;
	
	if (sPage.search(/Catalog/i) >= 0)
	{
		if (objShowAllInfo.isExist)
		{
			if (objShowAllInfo.checked) sPage += "Successful Show All";
			else sPage += "Successful Page " + objPageNumberInfo.value;
		}
		else sPage += "Unsuccessful"
		
		var resultLink = document.getElementsByTagName("a");
		if(psArrayIsNotEmpty(resultLink))
		{
			for (var i = 0; i < resultLink.length; i ++)
			{
				if (resultLink[i].href.search(/http:\/\/(www\.)?ecohaus\.com\/P-([^\/]+)\/(.+)$/i) >= 0) sResult ++;
			}
		}
	}
	else if (sPage.search(/Entire/i) >= 0)
	{
		return;
	}
	else sPage = "Error in Search page";
	
	// Display search result if "Show All" is checked or only one page
	var pTotalPage = null;
	var spanTotalPage = document.getElementById("ctl00_MainContent_SearchByKeyword1_PageScroller1_ctlPageCount");
	if(psCheckElementExist(spanTotalPage)){
		pTotalPage = psGetInnerText(spanTotalPage);		
		pTotalPage = psTrim(pTotalPage.replace(/of/gi,""));
	}
	if(pTotalPage == "1" || objShowAllInfo.checked){
		psCreatePageviewTag(sPage, "SEARCH", sTerm, sResult/3);
	}else{
		if(sPage.search(/Unsuccessful/i) >= 0){
			psCreatePageviewTag(sPage, "SEARCH", sTerm, 0);
		}else{
			psCreatePageviewTag(sPage, "SEARCH", sTerm, null);
		}		
	}
}

/*
 * Get search term from URL or source code
 */
function psGetSearchTerm()
{
	var term = "";
	//
	// TO-Do: Your logic to extract search term goes here
	//
	return term;
}

/*
 * Get search result from source code
 */
function psGetSearchResult()
{
	var result = "0";
	//
	// TO-Do: Your logic to extract search result goes here
	//
	return result;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()){
		psCreateProductviewTag(prd.id, prd.name, prd.catId);		
		psSetCookie(G_PS_COOKIE_PRE_CATID,prd.catId);
	}
	psHijackAddToCart(prd);
	psSetCookie(G_PS_COOKIE_CATID, "", "delete");
}

/*
 * Hijack Add to cart for sending shop5
 */
function psHijackAddToCart(pProduct){	
	var pAddToCart = document.getElementById("ctl00_MainContent_BuyButton1_ItemOptions1_ImageButton1");
	if(!psCheckElementExist(pAddToCart)) 
		pAddToCart = document.getElementById("ctl00_MainContent_BuyButton1_BuyButton1_LinkButton1");
	if(psCheckElementExist(pAddToCart)){
		if(pAddToCart.onclick == null || pAddToCart.onclick.toString().indexOf("HijackAddToCart") < 0){
			pAddToCart.OldFunction = pAddToCart.onclick;
			pAddToCart.ProductID = pProduct.id;
			pAddToCart.ProductName = pProduct.name;
			pAddToCart.ProductCatId = pProduct.catId;
			pAddToCart.onclick = function HijackAddToCart(){				
				var ProductPrice = null;
				var divPrice = document.getElementsByTagName("div");
				if(psCheckArrayExist(divPrice)){
					for(var i=0; i<divPrice.length; i++){						
						if(divPrice[i].innerHTML.search(/<div>/gi) < 0 && psGetInnerText(divPrice[i]).search(/^\s*Price:/gi) >= 0){
							ProductPrice = psGetInnerText(divPrice[i]);							
							ProductPrice = psCleanPrice(ProductPrice.replace("Price:",""));
						}
					}
				}
				var ProductQuantity = null;
				var inputQuantity = document.getElementById("ctl00_MainContent_BuyButton1_ItemOptions1_ctlQuantity");
				if(!psCheckElementExist(inputQuantity)){
					inputQuantity = document.getElementById("ctl00_MainContent_BuyButton1_ctlQuantity");
				}
				if(psCheckElementExist(inputQuantity)){
					ProductQuantity = inputQuantity.value;					
				}				
				psCreateShopAction5Tag(this.ProductID, this.ProductName, ProductQuantity, ProductPrice, this.ProductCatId);
				psDisplayShop5s();
				// update cookie
				if(psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.ProductID) == null){
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.ProductID, this.ProductCatId);
				}
				if(this.OldFunction != null) 
					return this.OldFunction();
			}
		}
	}
}

/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Update the catId and pageId according to your specification
	psCreatePageviewTag("VIEW CART", "CHECKOUT", null, null);	
	var cartTbl = null;
	var cartTbls = psGetElementsByClassName(document,"table","AddressForm");
	if(psCheckArrayExist(cartTbls)){
		for(var i=0;i<cartTbls.length; i++){
			if(cartTbls[i].getAttribute("summary").search(/Cart\s+Items/gi) >= 0){				
				cartTbl = cartTbls[i];
			}
		}
	}
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		if(rows[r].innerHTML.search(/Remove\s+from\s+cart/gi) < 0)
			continue;
		if (prd.getItem5(rows[r]))
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
	}
	// Make sure to have actual postings
	psDisplayShop5s();
	psSetCookie(G_PS_COOKIE_CATID, "", "delete");
}

/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	// Update the catId and pageId according to your specification
	psCreatePageviewTag("THANK YOU", "CHECKOUT", null, null);

	var cartTbl = null;
	// Get cart table
	var pTables = document.getElementsByTagName("table");
	if(psCheckArrayExist(pTables)){
		for(var i=0; i<pTables.length; i++){
			if(pTables[i].getAttribute("summary") != null && pTables[i].getAttribute("summary").search(/Order\s+summary/gi) >= 0){
				cartTbl = pTables[i];
			}
		}
	}
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows; // use rows variable for optimization
	var ord = new psOrder();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var prd = new psProduct();
			for (var r = 0; r < rows.length; r++) // item for each row
			{
				if (rows[r].innerHTML.search(/<B>Price\/Unit<\/B>/gi)>=0) // Skip rows not containining the item
					continue;
				
				if (prd.getItem9(rows[r])){					
					// skip coupon Item with its price < 0
					if(prd.price.indexOf("-") < 0)
						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_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 itemNumber = psGetFirstObjectByTagNameAndId("input", "ItemNumber");
			if (itemNumber != null) this.id = itemNumber.value;
			
			var bc = document.getElementById("breadcrumb");
			if(psCheckElementExist(bc)){
				var fontTag = bc.getElementsByTagName("font");
				if(psCheckArrayExist(fontTag)){
					if (typeof(fontTag[0].className) != "undefined" && fontTag[0].className != null && psIsEqual(fontTag[0].className, "current"))
					{
						this.name = psTrim(psCleanPageId(psGetInnerText(fontTag[0])));
						this.name = psHtmlDecode(unescape(this.name));
					}
				}
			}						
			if (G_PS_URL_REFERRER != null && G_PS_URL_REFERRER != "" && G_PS_URL_REFERRER.search(/ecohaus\.com/i) < 0){ 
				/* Issue on IE 7
				G_PS_URL_REFERRER will be empty when click product on:
					http://www.ecohaus.com/C-17/electronics
				such as http://www.ecohaus.com/P-1120001/Kill-a-watt+Kwh+Monitor+Ea				
				*/
				this.catId = "BOOKMARK";
				psSetCookie(G_PS_COOKIE_CATID,this.catId);
			}else{		
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
				if(this.catId != null){
					this.catId = this.catId.toUpperCase();
				}else{
					if (G_PS_URL_REFERRER.search(/\/P\-([^\/]+)\/(.+)/i) >= 0 || 
						G_PS_URL_REFERRER.search(/\/Item_Detail\.aspx\?ItemCode=/i) >= 0 ||
						G_PS_URL_REFERRER.search(/\/item_detail\.aspx\?LineUID=/i) >= 0) {
						
						if(psGetCookie(G_PS_COOKIE_PRE_CATID) != null){
							this.catId = psGetCookie(G_PS_COOKIE_PRE_CATID).toUpperCase();
						}
					}
					if(this.catId == null) this.catId = "BOOKMARK";
				}			
			}

			if (G_PS_URL_REFERRER.search(/\/view_cart\.aspx/i) >= 0) {
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				this.catId = (this.catId == null) ? "UNKNOWN" : this.catId.toUpperCase();
			}
			psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.id, this.catId);
			
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the shopping cart
	 */
	this.getItem5 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			 this.id = psTrim(psGetInnerText(itemRow.cells[0]));
			 if(psCheckElementExist(itemRow.cells[1])){
				var paTags = itemRow.cells[1].getElementsByTagName("a");
				if(psCheckArrayExist(paTags)){
					this.name = psTrim(psGetInnerText(paTags[0]));
					this.name = psCleanProductName(psHtmlDecode(unescape(this.name)));
				}
			 }
			 if(psCheckElementExist(itemRow.cells[2])){
				var pInputTags = itemRow.cells[2].getElementsByTagName("input");
				if(psCheckArrayExist(pInputTags)){
					this.quantity = pInputTags[0].value;
				}
			 }
			 if(psCheckElementExist(itemRow.cells[3])){
				var pSelectTags = itemRow.cells[3].getElementsByTagName("select");
				if(psCheckArrayExist(pSelectTags)){
					this.price = pSelectTags[0].options[pSelectTags[0].selectedIndex].innerHTML.replace(/^.*\$/gi,"");
					this.price = psCleanPrice(this.price);
				}
			 }
			 if(this.id != null){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null){
					this.catId = psGetCookie(G_PS_COOKIE_CATID);
					if(this.catId == null){
						// in case retrieving from saved shopping cart
						this.catId = "UNKNOWN";
					}
					psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.id,this.catId);					
				}
				this.catId = this.catId.toUpperCase();
				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!
			 if(itemRow.cells.length > 4){
				this.id = psTrim(psGetInnerText(itemRow.cells[0]));
				this.quantity = psTrim(psGetInnerText(itemRow.cells[1]));
				this.name = psTrim(psGetInnerText(itemRow.cells[3]));
				this.name = psHtmlDecode(unescape(this.name));
				this.price = psTrim(psGetInnerText(itemRow.cells[4]));				
			 }
			 if(this.id != null){
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				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
		{
			var pOrderNumber = document.getElementById("ctl00_MainContent_ViewWebOrder1_ctlOrderNumber");
			if(psCheckElementExist(pOrderNumber)){
				this.id = psTrim(psGetInnerText(pOrderNumber));
			}
			var pSubtotal = document.getElementById("ctl00_MainContent_ViewWebOrder1_ctlSubtotal");
			if(psCheckElementExist(pSubtotal)){
				this.subtotal = psCleanPrice(psTrim(psGetInnerText(pSubtotal)));
			}
			var pShip = document.getElementById("ctl00_MainContent_ViewWebOrder1_ctlShipping");
			if(psCheckElementExist(pShip)){
				this.shipping = psCleanPrice(psTrim(psGetInnerText(pShip)));
			}
			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 pBillAddress = document.getElementById("ctl00_MainContent_ViewWebOrder1_ctlBillTo");
			 if(psCheckElementExist(pBillAddress)){
				if(pBillAddress.innerHTML.search(/<br\s*\/*>/gi) >= 0){
					var pItems = pBillAddress.innerHTML.split(/<br\s*\/*>/gi);					
					if(pItems.length > 5){
						var pCity = psTrim(pItems[3]);
						if(pCity.indexOf(",") >= 0){
							uP.city = psTrim(pCity.split(",")[0]);
							uP.state = psTrim(pCity.split(",")[1]);
						}
						uP.zipcode = psTrim(pItems[5]);
					}					
				}
			 }
			 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, ">");
    }

    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 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);
	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 ==================*/


function psArrayIsNotEmpty(pArray)
{
	if (typeof(pArray) != "undefined" && pArray != null && pArray.length > 0) return true;
	return false;
}

function psGetFirstObjectByTagNameAndId(pTagName, pId)
{
	var tagName_tags = document.getElementsByTagName(pTagName);
	if (tagName_tags.length > 0)
	{
		for (var i = 0; i < tagName_tags.length; i ++)
		{
			if (typeof(tagName_tags[i].id) != "undefined" && tagName_tags[i].id != null && psIsEqual(tagName_tags[i].id, pId)) return tagName_tags[i];
		}
	}
	return null;
}

function psGetObjectsByTagNameAndId(pTagName, pId)
{
	var myArray = new Array();
	var tagName_tags = document.getElementsByTagName(pTagName);
	if (tagName_tags.length > 0)
	{
		for (var i = 0; i < tagName_tags.length; i ++)
		{
			if (typeof(tagName_tags[i].id) != "undefined" && tagName_tags[i].id != null && psIsEqual(tagName_tags[i].id, pId)) myArray.push(tagName_tags[i]);
		}
	}
	if (psArrayIsNotEmpty(myArray))
	{
		return myArray;
	}
	return null;
}

function psGetFirstObjectByTagNameAndName(pTagName, pName)
{
	var tagName_tags = document.getElementsByTagName(pTagName);
	if (tagName_tags.length > 0)
	{
		for (var i = 0; i < tagName_tags.length; i ++)
		{
			if (typeof(tagName_tags[i].name) != "undefined" && tagName_tags[i].name != null && psIsEqual(tagName_tags[i].name, pName)) return tagName_tags[i];
		}
	}
	return null;
}

function psGetObjectsByTagNameAndName(pTagName, pName)
{
	var myArray = new Array();
	var tagName_tags = document.getElementsByTagName(pTagName);
	if (tagName_tags.length > 0)
	{
		for (var i = 0; i < tagName_tags.length; i ++)
		{
			if (typeof(tagName_tags[i].name) != "undefined" && tagName_tags[i].name != null && psIsEqual(tagName_tags[i].name, pName)) myArray.push(tagName_tags[i]);
		}
	}
	if (psArrayIsNotEmpty(myArray))
	{
		return myArray;
	}
	return null;
}

function psGetFirstObjectByTagNameAndClassName(pTagName, pClassName)
{
	var tagName_tags = document.getElementsByTagName(pTagName);
	if (tagName_tags.length > 0)
	{
		for (var i = 0; i < tagName_tags.length; i ++)
		{
			if (typeof(tagName_tags[i].className) != "undefined" && tagName_tags[i].className != null && psIsEqual(tagName_tags[i].className, pClassName)) return tagName_tags[i];
		}
	}
	return null;
}

function psGetObjectsByTagNameAndClassName(pTagName, pClassName)
{
	var myArray = new Array();
	var tagName_tags = document.getElementsByTagName(pTagName);
	if (tagName_tags.length > 0)
	{
		for (var i = 0; i < tagName_tags.length; i ++)
		{
			if (typeof(tagName_tags[i].className) != "undefined" && tagName_tags[i].className != null && psIsEqual(tagName_tags[i].className, pClassName)) myArray.push(tagName_tags[i]);
		}
	}
	if (psArrayIsNotEmpty(myArray))
	{
		return myArray;
	}
	return null;
}

function pageInfo()
{
	this.pageId = null;
	this.catId = null;
	this.sTerm = null;
	this.sResult = null;
	
	if (G_PS_URL_PATH.search(/\/C-(\d+)\/(.+)$/i) >= 0)
	{
		this.catId = "C-" + RegExp.$1;
		this.pageId = "Category: " + RegExp.$2.replace(/\+/g, " ");		
		this.pageId = psHtmlDecode(unescape(this.pageId));		
		psSetCookie(G_PS_COOKIE_CATID,this.catId);
		return;
	}
	
	if (G_PS_URL_PATH.search(/\/SearchByCategory\.aspx\?CategoryCode=(\d+)\&title=(.+)$$/i) >= 0)
	{
		this.catId = "C-" + RegExp.$1;
		this.pageId = "Category: " + RegExp.$2.replace(/\+/g, " ");
		psSetCookie(G_PS_COOKIE_CATID,this.catId);
		return;
	}
	
	if(G_PS_URL_PATH.search(/GetReadyForSummerSale\.html/gi) >= 0 && (G_PS_URL_REFERRER.toLowerCase() == "http://www.ecohaus.com/" || G_PS_URL_REFERRER.search(/ecohaus\.com\/default\.htm/gi) >=0) ){	
		this.catId = this.pageId = "HOME PAGE PROMOTION";
		psSetCookie(G_PS_COOKIE_CATID,this.catId);
		return;
	}
	if(G_PS_URL_PATH.search(/zoom\.aspx/gi) >= 0){
		this.catId = "SHOP";
		this.pageId = "Full Size Image";
		psSetCookie(G_PS_COOKIE_CATID, "", "delete");
		return;
	}
	var bc = psGetFirstObjectByTagNameAndId("p", "breadcrumb");
	if (bc == null)
	{
		if (psIsEqual(G_PS_PATHNAME, "/") || psIsEqual(G_PS_PATHNAME, "/default.htm"))
		{
			this.catId = "HOME";
			this.pageId = "HOME";
			psSetCookie(G_PS_COOKIE_CATID, "", "delete");
			return;
		}
	}
	else
	{
		psSetCookie(G_PS_COOKIE_CATID, "", "delete");
		var aTags = bc.getElementsByTagName("a");
		var fontTag = bc.getElementsByTagName("font");
		
		if (psArrayIsNotEmpty(fontTag) && fontTag.length == 1)
		{
			if (typeof(fontTag[0].className) != "undefined" && fontTag[0].className != null && psIsEqual(fontTag[0].className, "current"))
			{
				// code: <p id="breadcrumb"><a title="home" class="current" href="http://www.ecohaus.com">home</a> / <a title="shop" href="/shop/Default.aspx">shop</a> / <font class="current">efficiency</font></p>
				this.pageId = psTrim(psCleanPageId(psGetInnerText(fontTag[0])));
			}
		}
		
		if (psArrayIsNotEmpty(aTags) && aTags.length > 1)
		{
			var last = null;
			var beforeLast = null;
			
			var lastA = aTags[aTags.length - 1];
			var beforeLastA = aTags[aTags.length - 2];
			
			if (lastA.href.search(/\/C\-(\d+)\/(.+)/i) >= 0) last = "C-" + RegExp.$1;
			else last = psTrim(psCleanCatId(psGetInnerText(lastA))).toUpperCase();
			
			if (beforeLastA.href.search(/\/C\-(\d+)\/(.+)/i) >= 0) beforeLast = "C-" + RegExp.$1;
			else beforeLast = psTrim(psCleanCatId(psGetInnerText(beforeLastA))).toUpperCase();
			
			if (this.pageId == null)
			{
				this.pageId = last;
				
				if (aTags.length == 2) this.catId = this.pageId;
				else this.catId = beforeLast;
			}
			else this.catId = last;
			this.pageId = psHtmlDecode(unescape(this.pageId));
			this.pageId = this.pageId.toUpperCase();			
		}
		if(G_PS_PATHNAME.search(/GetReadyForSummerSale\.html/gi) >= 0){
			psSetCookie(G_PS_COOKIE_CATID,this.pageId);
		}
	}
		
	if (this.pageId == null)
	{
		if (G_PS_PATHNAME.search(/\/news\/newsletter\/(\d+)\.htm(l)?$/i) >= 0)
		{
			this.catId = "NEWS";
			this.pageId = "NEWSLETTER " + RegExp.$1;
			psSetCookie(G_PS_COOKIE_CATID,this.catId);
		}
		else
		{
			// http://www.ecohaus.com/logon_forgot_password.aspx
			var h2Tags = document.getElementsByTagName("h2");
			if (psArrayIsNotEmpty(h2Tags))
			{
				for (var i = 0; i < h2Tags.length; i ++)
				{
					if(psTrim(psGetInnerText(h2Tags[i])).search(/forgot password\?/i) >= 0)
					{
						this.pageId = "LOGON FORGOT PASSWORD";
						this.catId = "SHOP";
						break;
					}
				}
			}
			
			var h1Tags = document.getElementsByTagName("h1");
			if (psArrayIsNotEmpty(h1Tags))
			{
				for (var i = 0; i < h1Tags.length; i ++)
				{
					if(psTrim(psGetInnerText(h1Tags[i])).search(/Page not Found/i) >= 0)
					{
						this.pageId = "PAGE NOT FOUND";
						this.catId = "ERROR";
					}
				}
			}
				
			if (G_PS_PATHNAME.search(/\/error_page\.aspx/i) >= 0)
			{
				this.pageId = "ERROR PAGE";
				this.catId = "ERROR";
			}else if(G_PS_PATHNAME.search(/ProductRatings\/RateThisProduct\.aspx/gi) >= 0 ||
					 G_PS_PATHNAME.search(/ProductRatings\/ViewComments\.aspx/gi) >= 0){
				this.catId = "PRODUCT RATINGS";
				this.pageId = "Rate Product";
				if(G_PS_PATHNAME.search(/ViewComments\.aspx/gi) >= 0) this.pageId = "View Comments";
				var prdId = psGetValueFromUrl(G_PS_URL_PATH,"ItemCode");
				if(prdId != null) this.pageId += " " + prdId.toUpperCase();				
			}			
		}
	}
}

/*
 * Get status of checkbox "Show All"
 */
function showAllInfo()
{
	this.isExist = false;
	this.checked = false;
	
	var inputTags = document.getElementsByTagName("input");
	if (!psArrayIsNotEmpty(inputTags)) return;
	
	for (var i = 0; i < inputTags.length; i ++)
	{
		if (typeof(inputTags[i].type) != "undefined" && inputTags[i].type != null && psIsEqual(inputTags[i].type, "checkbox"))
		{
			if (typeof(inputTags[i].id) != "undefined" && inputTags[i].id != null && inputTags[i].id.search(/_btnShowAll/i) >= 0)
			{
				this.isExist = true;
				this.checked = inputTags[i].checked;
				return;
			}
		}
	}
}
/*
 *  Get page number
 */
function pageNumberInfo()
{
	this.isExist = false;
	this.value = null;
	
	var selectTags = document.getElementsByTagName("select");
	if (!psArrayIsNotEmpty(selectTags)) return;
	
	for (var i = 0; i < selectTags.length; i ++)
	{
		if (typeof(selectTags[i].name) != "undefined" && selectTags[i].name != null && selectTags[i].name.search(/\$PageScroller\d+\$ctlPageNumber/i) >= 0)
		{
			this.isExist = true;
			this.value = selectTags[i].options[selectTags[i].selectedIndex].value;
			return;
		}
	}
}

function psHijackPeopleAlsoBought()
{
	var tableTags = document.getElementsByTagName("table");
	if (!psArrayIsNotEmpty(tableTags)) return;
	
	for (var i = 0; i < tableTags.length; i ++)
	{
		if (typeof(tableTags[i].id) != "undefined" && tableTags[i].id != null && tableTags[i].id.search(/_MainContent_AlsoPurchased\d+_DataList\d+/i) >= 0)
		{
			var imgTags = tableTags[i].getElementsByTagName("img");
			var aTags = tableTags[i].getElementsByTagName("a");
			
			if (psArrayIsNotEmpty(imgTags))
			{
				for (var j = 0; j < imgTags.length; j ++)
				{
					
					if (imgTags[j].onclick == null || imgTags[j].onclick.toString().search(/psdHijackFunction/i) < 0)
					{
						imgTags[j].oldFunction = imgTags[j].onclick;
						imgTags[j].onclick = function psdHijackFunction()
						{
							psSetCookie(G_PS_COOKIE_CATID, "PEOPLE ALSO BOUGHT");
							if (this.oldFunction != null)
							{
								this.oldFunction();
							}
						}
					}
				}
			}
			
			if (psArrayIsNotEmpty(aTags))
			{
				for (var j = 0; j < aTags.length; j ++)
				{
					
					if (aTags[j].onclick == null || aTags[j].onclick.toString().search(/psdHijackFunction/i) < 0)
					{
						aTags[j].oldFunction = aTags[j].onclick;
						aTags[j].onclick = function psdHijackFunction()
						{
							psSetCookie(G_PS_COOKIE_CATID, "PEOPLE ALSO BOUGHT");
							if (this.oldFunction != null)
							{
								this.oldFunction();
							}
						}
					}
				}
			}
		}
	}
}

function psHijackRelatedItems()
{
	var tableTags = document.getElementsByTagName("table");
	if (!psArrayIsNotEmpty(tableTags)) return;
	
	for (var i = 0; i < tableTags.length; i ++)
	{
		if (typeof(tableTags[i].id) != "undefined" && tableTags[i].id != null && tableTags[i].id.search(/_MainContent_RelatedItems\d+_DataList\d+/i) >= 0)
		{
			var imgTags = tableTags[i].getElementsByTagName("img");
			var aTags = tableTags[i].getElementsByTagName("a");
			
			if (psArrayIsNotEmpty(imgTags))
			{
				for (var j = 0; j < imgTags.length; j ++)
				{
					
					if (imgTags[j].onclick == null || imgTags[j].onclick.toString().search(/psdHijackFunction/i) < 0)
					{
						imgTags[j].oldFunction = imgTags[j].onclick;
						imgTags[j].onclick = function psdHijackFunction()
						{
							psSetCookie(G_PS_COOKIE_CATID, "RELATED ITEMS");
							if (this.oldFunction != null)
							{
								this.oldFunction();
							}
						}
					}
				}
			}
			
			if (psArrayIsNotEmpty(aTags))
			{
				for (var j = 0; j < aTags.length; j ++)
				{
					
					if (aTags[j].onclick == null || aTags[j].onclick.toString().search(/psdHijackFunction/i) < 0)
					{
						aTags[j].oldFunction = aTags[j].onclick;
						aTags[j].onclick = function psdHijackFunction()
						{
							psSetCookie(G_PS_COOKIE_CATID, "RELATED ITEMS");
							if (this.oldFunction != null)
							{
								this.oldFunction();
							}
						}
					}
				}
			}
		}
	}
}

function psParseGooglePage(pGoogleURL)
{
	var objXMLHttpRequest;
	try
	{
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
	}
	catch(e){}
	
	if (window.XMLHttpRequest)
	{
		// IE 7, Mozilla, Opera, Safari
		objXMLHttpRequest = new XMLHttpRequest();
	}
	else{
		// assume IE6 or older
		try
		{
			objXMLHttpRequest = new ActiveXObject("Microsoft.XMLHttp");
		}
		catch(e) { }
	}
	
	if (!objXMLHttpRequest) return;
	objXMLHttpRequest.open("GET", pGoogleURL, false);
	objXMLHttpRequest.send(null);
	
	if (objXMLHttpRequest.status == 200)
	{
		var sTerm = null;
		var sResult = null;
		var pageName = null;
		var number = null;
		var catName = "SEARCH";
		
		var content = objXMLHttpRequest.responseText;
		
		if (content.search(/\<title\>(.+)-\s+Google Search\<\/title\>/i) >= 0) sTerm = psTrim(RegExp.$1);
		if (content.search(/did not match any documents/i) >= 0) sResult = 0;
		if (content.search(/Results \<b\>(\d+)\<\/b\> - \<b\>(\d+)\<\/b\> for \<b\>(.+)\<\/b\>/i) >= 0)
		{
			var one = psTrim(RegExp.$1);
			var two = psTrim(RegExp.$2);
			sResult = two - one + 1;
		}
		if (content.search(/\<span style="margin-right:\s*(0)?\.6em" class=(")?i(")?\>(\d+)/i) >= 0) number = RegExp.$4;
		
		if (sTerm != null && sResult != null)
		{
			if (sResult == 0) pageName = "Entire Site Search Unsuccessful";
			else pageName = "Entire Site Search Successful";
			
			if (number != null) pageName += " Page " + number;
			psCreatePageviewTag(pageName, catName, sTerm, sResult);
		}
	}
}










