/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.2, 2009/11/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("oo.com.au");//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_DYNAMIC_CATID = "PS_DYNAMIC_CATID";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var G_PS_COOKIE_SHOP5_RESTORE = "PS_SHOP5_RESTORE";
var G_PS_COOKIE_GIFTCARD = "PS_GIFTCARD";

/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/

if (G_PS_URL_PATH.search(/oo\.com\.au/i) >= 0 || G_PS_URL_PATH.search(/oo1\.izilla\.com\.au/i) >= 0){
	if(psIsErrorPage()){
		psCreateErrorTag("Error", "Error");
	}else if (psIsSearchView())
	{	
		psPostSearchView();
	}
	else if (psIsProductView())
	{		
		psPostProductView();
		psHijackRelatedProduct();
	}
	else if (psIsCartView())
	{
		psPostCartView();
		psHijackOnSuggestions();
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else if(psPostPageView()== false)
	{	
		psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
	}
	psHijackRegistration();
	
	if(G_PS_PATHNAME.indexOf("/paymeth.cfm") >= 0){
		var preShop5 = psGetCookie(G_PS_COOKIE_SHOP5_RESTORE);
		if(preShop5 == "restore_all"){
			psResendShop5();			
		}
	}	
}

function psPostPageView(){
	var pPageId = null;
	var pCatId = null;
	
	if(G_PS_PATHNAME.indexOf("/billinfo.cfm") >= 0){
		pCatId = "Checkout";
		pPageId = "Billing";		
		// Hijack billing address
		psHijackBillingAddress();
		psHijackEmailSubmit("frmLogin1","txtEmail");		
		if(G_PS_URL_REFERRER.indexOf("/billinfo.cfm") >= 0 && psGetCookie(G_PS_COOKIE_FLAG) == "login" && psGetElementByName("form","frmLogin1") == false){
			// Just login successful
			psPostRegistration();
		}
	}else if(G_PS_PATHNAME.indexOf("/paymeth.cfm") >= 0){
		pCatId = "Checkout";
		pPageId = "Payment";
		if(psGetCookie(G_PS_COOKIE_FLAG) == "login"){
			psPostRegistration();
		}
	}else if(G_PS_PATHNAME.indexOf("/addressbook.cfm") >= 0){
		pCatId = "my-account";
		pPageId = "Address book";
		var addressType = psGetValueFromUrl(G_PS_URL_PATH,"addressType");
		if(addressType != null && addressType.toLowerCase() == "bill"){
			// Hijack to update billing address
			psHijackAddressBook();
		}
	}else if(G_PS_PATHNAME == "/"){
		pPageId = "HomePage";
		pCatId = "Home";		
		psSetCookie(G_PS_COOKIE_CATID,pCatId);
		psHijackWhatHot_NewArrivals_StaffPick();
	}else if(G_PS_PATHNAME == "/register/"){
		pCatId = "my-account";
		pPageId = "New customer account";		
	}else if(G_PS_PATHNAME.indexOf("/basketrestore.cfm") >= 0){
		pCatId = "Checkout";
		pPageId = "Basket Restore";
		if(psGetCookie(G_PS_COOKIE_FLAG) == "login"){
			psPostRegistration();
		}
		psHijackRestoreAll();
		
	}else if(G_PS_PATHNAME.indexOf("/helptopicpopup.cfm") >= 0){
		pCatId = "help-centre";
		var tdTitle = psGetElementsByClassName(document,"td","title");
		if(psCheckArrayExist(tdTitle)){
			pPageId = psTrim(psGetInnerText(tdTitle[0]));
		}		
	}else if(G_PS_PATHNAME == "/login/" || G_PS_PATHNAME == "/my-account/" ||
	         G_PS_PATHNAME == "/change-login/" || G_PS_PATHNAME == "/previous-orders/" ){
		pCatId = "my-account";
		pPageId = G_PS_PATHNAME.replace(/\//g,"");
	}else if(G_PS_PATHNAME.search(/_C.+\.cfm/i) >= 0){
		// Is cateogry page, get pageId and catId from bread crumbs		
		var bc = document.getElementById("breadcrumbs");
		if(psCheckElementExist(bc)){			
			var aTags = bc.getElementsByTagName("a");
			if(psCheckArrayExist(aTags) && aTags.length > 1){
				pPageId = psGetInnerText(aTags[aTags.length -1]);
				pCatId = psGetInnerText(aTags[aTags.length -2]);
			}
		}
		if(pPageId != null && pCatId != null){
			// Handle duplicate categories by using a dash '-' in the category ID value.
			// For 1. of Notes_for_PSD_on_duplicate_CDF_categories.txt
			if(G_PS_PATHNAME.search(/\/HDMI_Cables_Accessories_C1083\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Electric\-Blankets_C1573\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Memory_Foam_C836\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Air\-Conditioners\-and\-Fans_C1404\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Sewing_Machines_C913\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Outdoor\-Furniture_C1396\.cfm/i) >= 0){
				pPageId = pPageId.replace(/\s+/,"-");
			}
			// Handle duplicate categories by using prefix in the category ID value.
			// For 2. -> 6., 8., 10. and 11. of Notes_for_PSD_on_duplicate_CDF_categories.txt
			if(G_PS_PATHNAME.search(/\/Backpacks_C1376\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Pool\-Beach_C1449\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Sports_Equipment_Accessories_C920\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Accessories_C265\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Sports_Outdoors_C977\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Home\-Garden\-Books_C1426\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Car\-Speakers_C1327\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Heart\-Rate\-Monitors_C1416\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Art\-Supplies_C1217\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/Lighters_C992\.cfm/i) >= 0 ||
			   G_PS_PATHNAME.search(/\/jigsaw\-puzzles_C769\.cfm/i) >= 0 ){
				pPageId = pCatId + ":" + psTrim(pPageId);
			}
			// Handle duplicate categories by using prefix in the category ID value.
			// For 7. "Sunglasses"
			var cat = psTrim(psHtmlDecode(unescape(pCatId))).toLowerCase();			
			if(cat == "sunglasses"){
				var pageId = psTrim(psHtmlDecode(unescape(pPageId)));
				if(pageId.search(/(Christian\s+Dior|Dolce\s+\&\s+Gabbana|Emporio\sArmani|Giorgio\s+Armani|Gucci|Hugo\s+Boss|Marc\s+Jacobs|Ralph\s+Lauren|Valentino|Versace|Optical\s+Frames)/i) >= 0){
					pPageId = cat + ":" + psTrim(pPageId);
				}
			}
			if(G_PS_PATHNAME.search(/\/Optical_Frames_C787\.cfm/i) >= 0){
				pPageId = "Sunglasses:Optical Frames";
			}
			// Handle duplicate categories by using prefix in the category ID value.
			// For 9. "Mens Watches"
			if(cat == "mens watches"){
				var pageId = psTrim(psHtmlDecode(unescape(pPageId)));
				if(pageId.search(/(Digital\s+Photo\s+Frame\s+Watch|D\&G\s+Watches|Diesel\s+Watches|DKNY\s+Watches|Dunlop\s+Watches|Fila\s+Watches|Fossil\s+Watches|Guess\s+Watches|o\.d\.m\.\s+Watches|Pierre\s+Cardin\s+Watches|Playboy\s+Watches|Polar\s+Watches|Pulsar\s+Watches|Speedo\s+Watches|Timex\s+Watches|Tommy\s+Hilfiger\s+Watches)/i) >= 0){
					pPageId = cat + ":" + psTrim(pPageId);
				}
				
			}
			// Handle duplicate categories by using prefix in the category ID value.
			// For 12. "Mens Fragrances"
			if(cat == "mens fragrances" && pPageId.toLowerCase() != "adidas"){				
				pPageId = "Men:" + psTrim(pPageId);
			}			
		}
		psHijackWhatHot_NewArrivals_StaffPick();

	}else if(G_PS_URL_PATH.indexOf("search.oo.com.au/nav/") >= 0){	
		var lastRefine = psGetLastRefinement();
		if(lastRefine != null){
			var refineGroup = psGetRefineGroup(lastRefine);
			pPageId = "REFINEMENT:" + refineGroup + ":" + lastRefine;
			pCatId = "REFINEMENT:" + refineGroup;
		}else{
			pPageId = "REFINEMENT:Search Unsuccessful";
			pCatId = "REFINEMENT:Brand";
			if(G_PS_PATHNAME.indexOf("/nav/cat") >= 0) 	pCatId = "REFINEMENT:Category";
			if(G_PS_PATHNAME.indexOf("/nav/pb_aud") >= 0) 	pCatId = "REFINEMENT:Price Range";
			if(G_PS_PATHNAME.indexOf("/nav/ship") >= 0) 	pCatId = "REFINEMENT:Delivery";
		}	
	}else {		
		// pageId and catId from URL
		var pUrl = G_PS_PATHNAME.replace(/\/$/,"");
		pUrl = pUrl.replace(/^\//,"");
		if(pUrl.indexOf("/") >= 0){
			var pItems = pUrl.split("/");
			pPageId = pItems[pItems.length-1];
			pCatId = pItems[pItems.length-2];
		}else{
			pPageId = pCatId = pUrl;
			if(G_PS_PATHNAME == "rss-feeds"){
				pCatId = "Home";
			}
		}
		
	}
	
	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));
	
	pPageId = pPageId.toUpperCase();
	pCatId = pCatId.toUpperCase();
	
	psCreatePageviewTag(pPageId, pCatId, null, null);
	
	psSetCookie(G_PS_COOKIE_CATID,pPageId);
	psHijackAddToCart_CategoryView(pPageId);

	if(pCatId == "BRAND"){
		psHijackTopSellers_LastestArrivals();
	}
	if(pPageId == null || pCatId == null){
		return false;
	}
	return true;
}

function psResendShop5(){
	var cartTbl = null;	
	var tables = document.getElementsByTagName("table");
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){			
			if(tables[i].rows[0] != null && psGetInnerText(tables[i].rows[0]).search(/SKU\s*Item\s*Price/i) >= 0 ){
				cartTbl = tables[i];
			}
		}
	}	
	if (cartTbl == null)
		return;
	
	var rows = cartTbl.rows;	
	for (var r = 0; r < rows.length; r++) 
	{
		if(rows[r].cells.length < 5 || psGetInnerText(rows[r]).search(/SKU\s*Item\s*Price/i) >= 0){
			continue;
		}		
		var prdId = psTrim(psGetInnerText(rows[r].cells[1]));
		var prdName = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(rows[r].cells[2])))));
		var prdPrice = psCleanPriceNZ(psTrim(psGetInnerText(rows[r].cells[3])));
		var prdQuantity = psTrim(psGetInnerText(rows[r].cells[4]));		
		var prdCatId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, prdId);
		if(prdCatId == null || prdCatId == ""){
			prdCatId = "Unknown";
		}
		if(prdId != null && prdId.indexOf("COUPON") >= 0){
				prdQuantity = "1";
				prdCatId = "COUPON";
				prdPrice = "0";
		}
		if (prdId != null && prdName != null){
			psCreateShopAction5Tag(prdId, prdName, prdQuantity, prdPrice, prdCatId);	
		}		
	}
	// Send GiftCard from cookie
	var pGift = psGetCookie(G_PS_COOKIE_GIFTCARD);
	if(pGift != null && pGift != "" && pGift.indexOf("|") >= 0){
		var pItems = pGift.split("|");
		if(pItems.length > 4){						
			psCreateShopAction5Tag(pItems[0], pItems[1], pItems[2], pItems[3], pItems[4]);						
		}
	}
	psDisplayShop5s();	
}

function psHijackRestoreAll(){
	var restoreAll = psGetElementByName("input","all");
	if(psCheckElementExist(restoreAll)){
		if(restoreAll.onclick == null || restoreAll.onclick.toString().indexOf("psHJRestoreAll") < 0){
			restoreAll.OldFunction = restoreAll.onclick;
			restoreAll.onclick = function psHJRestoreAll(){				
				psSetCookie(G_PS_COOKIE_SHOP5_RESTORE,"restore_all");
				if(this.OldFunction != null)
					return this.OldFunction();
			}
		}
	}
}

function psHijackWhatHot_NewArrivals_StaffPick(){
	// For products at "What's hot", "new arrivals", "Staff pick"
	var prod_features = psGetElementsByClassName(document,"div","prod_feature");
	// For products at the bottom of "Staff pick"
	var staff_carousel = psGetElementsByClassName(document,"div","staff_carousel");	
	if(psCheckArrayExist(staff_carousel)){
		prod_features = prod_features.concat(staff_carousel);
	}
	// For products at "clearance"
	var carousel_feature = psGetElementsByClassName(document,"div","carousel_feature clearance");
	if(psCheckArrayExist(carousel_feature)){
		prod_features = prod_features.concat(carousel_feature);
	}
	if(psCheckArrayExist(prod_features)){
		for(var i=0; i<prod_features.length; i++){
			var prod_feature = prod_features[i];
			var secName = null;
			var h3Tags = prod_feature.parentNode.getElementsByTagName("h3");
			if(prod_feature.className.search(/clearance/i) >= 0){
				// clearance
				h3Tags = prod_feature.getElementsByTagName("h3");				
			}
			if(psCheckArrayExist(h3Tags)){
				secName = psTrim(psGetInnerText(h3Tags[0]));
			}
			if(secName == null || secName == ""){
				continue;
			}
			secName = secName.replace("'","");			
			// Hijack view product
			var aTags = prod_feature.getElementsByTagName("a");
			if(psCheckArrayExist(aTags)){
				for(var j=0; j<aTags.length; j++){
					var aTag = aTags[j];
					if(aTag.href != null && aTag.href.search(/_P.+\.cfm/i) >= 0){						
						if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHijackWhatHot") < 0){
							aTag.secName = secName;
							aTag.OldFunction = aTag.onclick;
							aTag.onclick = function psHijackWhatHot(){
								psSetCookie(G_PS_COOKIE_DYNAMIC_CATID,this.secName);
								if(this.OldFunction != null) 
									return this.OldFunction();									
							}
						}
					}
				}
			}
			// Hijack "Buy now"
			var forms = prod_feature.getElementsByTagName("form");
			if(psCheckArrayExist(forms)){
				for(var f=0; f<forms.length; f++){
					var prdId = null;
					var images = forms[f].getElementsByTagName("img");
					if(psCheckArrayExist(images)){
						if(images[0].src != null && images[0].src.search(/\/prod\/(\w+)\/(\w+)\.jpg/i) >= 0){
							prdId = RegExp.$1;
						}
					}
					var buys = psGetElementsByClassName(forms[f],"input","buy_now");
					if(psCheckArrayExist(buys) && prdId != null){
						var buy = buys[0];
						if(buy.onclick == null || buy.onclick.toString().indexOf("psHJBuyNow") < 0){
							buy.prdId = prdId;
							buy.prdCatId = secName;							
							buy.OldFunction = buy.onclick;
							buy.onclick = function psHJBuyNow(){								
								psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdId,this.prdCatId);
								if(this.OldFunction != null)
									return this.OldFunction();
							}
						}
					}
				}
			}				
		}
	}	
}

function psHijackTopSellers_LastestArrivals(){
	var prod_feature = document.getElementById("prod_feature");
	if(psCheckElementExist(prod_feature)){
		var divTags = psGetElementsByClassName(prod_feature,"div","brands_feature prod_feature");
		if(psCheckArrayExist(divTags)){
			for(var i=0; i<divTags.length; i++){
				var divTag = divTags[i];
				var h3Tags = divTag.parentNode.getElementsByTagName("h3");
				if(psCheckArrayExist(h3Tags)){
					var secName = psTrim(psGetInnerText(h3Tags[0]));					
					var aTags = divTag.getElementsByTagName("a");
					if(psCheckArrayExist(aTags)){
						for(var j=0; j<aTags.length; j++){
							var aTag = aTags[j];
							if(aTag.href != null && aTag.href.search(/_P.+\.cfm/i) >= 0){								
								if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJTopSellers_LatestArrivals") < 0){
									aTag.secName = secName;
									aTag.OldFunction = aTag.onclick;
									aTag.onclick = function psHJTopSellers_LatestArrivals(){
										psSetCookie(G_PS_COOKIE_DYNAMIC_CATID,this.secName);
										if(this.OldFunction != null) 
											return this.OldFunction();									
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

function psHijackRelatedProduct(){
	// Hijack "we recommend" and "others bought"
	var relatedDivs = psGetElementsByClassName(document,"div","p_related");
	if(psCheckArrayExist(relatedDivs)){
		for(var i=0; i<relatedDivs.length; i++){
			var secName = "Cross Sell";
			var h4Tags = relatedDivs[i].getElementsByTagName("h4");
			if(psCheckArrayExist(h4Tags)){
				secName = psGetInnerText(h4Tags[0]);
			}
			var pTags = relatedDivs[i].getElementsByTagName("a");
			if(psCheckArrayExist(pTags)){
				for(var j=0; j<pTags.length; j++){
					var pTag = pTags[j];
					if(pTag.href != null && pTag.href.search(/_P.+\.cfm/i) >= 0){
						if(pTag.onclick == null || pTag.onclick.toString().indexOf("psHJRelatedProduct") < 0){
							pTag.secName = secName;
							pTag.OldFunction = pTag.onclick;							
							pTag.onclick = function psHJRelatedProduct(){								
								psSetCookie(G_PS_COOKIE_DYNAMIC_CATID,this.secName);
								if(this.OldFunction != null) 
									return this.OldFunction();
							}
						}
					}
				}
			}			
		}
	}
}

function psHijackRegistration(){	
	if(G_PS_PATHNAME == "/register/"){
		psHijackEmailSubmit("frmCreateAccount","txtEmail");		
	}else if(G_PS_PATHNAME == "/login/"){
		psHijackEmailSubmit("frmLogin1","txtEmail");
	}else if(G_PS_PATHNAME == "/change-login/"){
		psHijackEmailOnSubmit("changeUsername","txtUserName");
	}else if(G_PS_PATHNAME == "/my-account/"){
		if(psGetCookie(G_PS_COOKIE_FLAG) == "login"){
			psPostRegistration();
		}
	}	
}

function psPostRegistration()
{
	var uP = new psProfile();
	uP.readProfile();
	if(uP.email != null)
	{
		psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
}

function psHijackEmailSubmit(frm,email){	
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	var f = psGetElementByName("form",frm);	
	if(psCheckElementExist(f)){		
		f.OldFunction = f.submit;		
		f.submit = function psHijackLogin(){			
			var mail = psGetElementByName("input",email);
			if(psCheckElementExist(mail)){
				var uP = new psProfile();
				uP.email = psTrim(mail.value);				
				uP.cusId = uP.email;
				// User can login by user name instead of email
				if(uP.email != null && uP.email != ""){
					uP.writeProfile();
					psSetCookie(G_PS_COOKIE_FLAG,"login");
				}
			}				
			if(this.OldFunction != null) return this.OldFunction();
		}		
	}	
}

function psHijackEmailOnSubmit(frm,email){	
	psSetCookie(G_PS_COOKIE_FLAG,"","delete");
	var f = psGetElementByName("form",frm);	
	if(psCheckElementExist(f)){		
		f.OldFunction = f.onsubmit;
		f.onsubmit = function psHijackLogin(){			
			var mail = psGetElementByName("input",email);
			if(psCheckElementExist(mail)){
				var uP = new psProfile();
				uP.email = psTrim(mail.value);				
				uP.cusId = uP.email;
				if(uP.email != null && uP.email != ""){
					uP.writeProfile();					
					psCreateRegistrationTag(uP.email, uP.email, uP.city, uP.state, uP.zipcode);
				}
			}				
			if(this.OldFunction != null) return this.OldFunction();
		}
	}	
}

function psHijackAddressBook(){	
	var billForm = document.getElementById("frmAddressBook");	
	if(psCheckElementExist(billForm)){
		billForm.OldFunction = billForm.onsubmit;
		billForm.onsubmit = function (){		
			var uP = new psProfile();
			if(psCheckElementExist(billForm.txtEmail)){
				uP.cusId = uP.email = psTrim(billForm.txtEmail.value);
			}
			var city = psGetElementByName("input","txtCity");
			if(psCheckElementExist(city)){
				uP.city = psTrim(city.value);
			}
			var state = psGetElementByName("select","txtProvince");
			if(psCheckElementExist(state)){
				uP.state = state.options[state.selectedIndex].value;
			}
			var zipcode = psGetElementByName("input","txtPostalCode");
			if(psCheckElementExist(zipcode)){
				uP.zipcode = psTrim(zipcode.value);
			}
			if(psCheckEmail(uP.email)){
				uP.writeProfile();
				psSetCookie(G_PS_COOKIE_FLAG,"login");
			}			
			if(this.OldFunction != null)
				return this.OldFunction();
				
		}
	}	
}

function psHijackBillingAddress(){
	var billForm = document.getElementById("frmBilling");	
	if(psCheckElementExist(billForm)){
		billForm.OldFunction = billForm.submit;
		billForm.submit = function (){		
			var uP = new psProfile();
			if(psCheckElementExist(billForm.txtEmail)){
				uP.cusId = uP.email = psTrim(billForm.txtEmail.value);
			}
			var city = psGetElementByName("input","txtCity");
			if(psCheckElementExist(city)){
				uP.city = psTrim(city.value);
			}
			var state = psGetElementByName("select","txtProvince");
			if(psCheckElementExist(state)){
				uP.state = state.options[state.selectedIndex].value;
			}
			var zipcode = psGetElementByName("input","txtPostalCode");
			if(psCheckElementExist(zipcode)){
				uP.zipcode = psTrim(zipcode.value);
			}
			if(psCheckEmail(uP.email)){
				uP.writeProfile();
				psSetCookie(G_PS_COOKIE_FLAG,"login");
			}			
			if(this.OldFunction != null)
				return this.OldFunction();
				
		}
	}	
}

function psHijackOnSuggestions(){	
	var tables = document.getElementsByTagName("table");
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){
			if(tables[i].rows[0].innerHTML.search(/images\/suggestions\-02\.jpg/i) >= 0 &&
			   psGetInnerText(tables[i].rows[0]) != null &&
			   psGetInnerText(tables[i].rows[0]).search(/SKU\s*Item\s*Price/i) < 0 ){
				var aTags = tables[i].getElementsByTagName("a");
				if(psCheckArrayExist(aTags)){
					for(var j=0; j<aTags.length; j++){
						var aTag = aTags[j];
						if(aTag.onclick == null || aTag.onclick.toString().indexOf("psHJSuggestion") < 0){							
							aTag.OldFunction = aTag.onclick;
							aTag.onclick = function psHJSuggestion(){
								psSetCookie(G_PS_COOKIE_DYNAMIC_CATID,"suggestions");
								if(this.OldFunction != null)
									return this.OldFunction();
							}
						}
					}
				}
			}
		}
	}
}

function psIsErrorPage(){
	var header = document.getElementById("gen_header");
	if(psCheckElementExist(header) && psGetInnerText(header).search(/Page\s+Not\s+Found/i) >= 0)
		return true;
	return false;
}

function psIsSearchView()
{
	if(G_PS_PATHNAME == "/search")
		return true;
	return false;
}

function psIsProductView()
{
	if(G_PS_PATHNAME.search(/_P.+\.cfm/i) >= 0){
		var productDiv = document.getElementById("product");
		if(psCheckElementExist(productDiv)){			
			return true;
		}
	}	
	return false;
}

function psIsCartView()
{
	if(G_PS_PATHNAME == "/basket/")
		return true;
	return false;
}

function psIsOrderView()
{
	if(G_PS_PATHNAME.indexOf("/vieworder.cfm") >= 0)
		return true;
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
function psPostSearchView()
{
	var pageId = "Search Unsuccessful";
	var catId = pageId;
	var sTerm = psGetSearchTerm();	
	var sResult = psGetSearchResult();
	if(sResult != "0"){
		pageId = "Search Successful Page[" + psGetPageNumber() + "]";
		catId = "Search Successful";
	}
	var prefix = sTerm.split(":")[0];
	catId += ":" + prefix;
	pageId = prefix + ":" + pageId;
	
	var lastRefine = psGetLastRefinement();
	if(lastRefine != null){
		var refineGroup = psGetRefineGroup(lastRefine);
		pageId = "REFINEMENT:" + refineGroup + ":" + lastRefine;
		catId = "REFINEMENT:" + refineGroup;		
	}	
	psCreatePageviewTag(pageId, catId, sTerm, sResult);
	psSetCookie(G_PS_COOKIE_CATID,catId);
}

function psGetRefineGroup(refineItem){
	var fGroup = null;
	var pLists = psGetElementsByClassName(document,"ul","sli_facetlist");
	if(psCheckArrayExist(pLists)){
		for(var i=0; i<pLists.length; i++){
			var temp = psHtmlDecode(unescape(psGetInnerText(pLists[i])));			
			if(temp != null && temp.toLowerCase().indexOf(refineItem.toLowerCase()) >= 0){				
				if(temp.indexOf(":") >= 0){
					fGroup = psTrim(temp.split(":")[0]);
				}					
			}
		}
	}
	return fGroup;
}

function psGetLastRefinement(){
	var lastRefine = null;
	var divRefines = psGetElementsByClassName(document,"div","sli_displayopt facetbct ");
	if(psCheckArrayExist(divRefines)==false){
		divRefines = psGetElementsByClassName(document,"div","sli_displayopt facetbct");
	}
	if(psCheckArrayExist(divRefines)){
		var refines = psHtmlDecode(unescape(psGetInnerText(divRefines[0])));		
		if(refines.indexOf(">") >= 0){
			var pItems = refines.split(">");
			lastRefine = psTrim(pItems[pItems.length -1]);
		}		
	}
	return lastRefine;
}

function psGetPageNumber(){
	var pageNumber = "1";
	var pageSpans = psGetElementsByClassName(document,"span","sli_pagination");
	if(psCheckArrayExist(pageSpans)){
		var activeLinks = psGetElementsByClassName(pageSpans[0],"a"," active");
		if(psCheckArrayExist(activeLinks) == false){
			activeLinks = psGetElementsByClassName(pageSpans[0],"a","active");
		}
		if(psCheckArrayExist(activeLinks)){
			pageNumber = psGetInnerText(activeLinks[0]);
		}
	}
	return pageNumber;
}

function psGetSearchTerm()
{
	var term = "";
	var sInputs = psGetElementsByClassName(document,"input","slisearch_box");
	if(psCheckArrayExist(sInputs)){
		term = psTrim(sInputs[0].value);
		var filter = psGetValueFromUrl(G_PS_URL_PATH,"filter");
		
		if(filter == null || filter.indexOf("prod") >= 0){
			term = "Products:" + term;
		}else if(filter != null && filter.indexOf("help") >= 0){
			term = "Help:" + term;
		}else if(filter != null && filter.indexOf("blog") >= 0){
			term = "Blog:" + term;
		}
	}
	return term;
}

function psGetSearchResult()
{
	var result = "0";
	var filter = psGetValueFromUrl(G_PS_URL_PATH,"filter");
	var h3Results = psGetElementsByClassName(document,"h3","sli_tabs");
	if(psCheckArrayExist(h3Results)){
		for(var i=0; i<h3Results.length; i++){
			if(psGetInnerText(h3Results[i]).search(/Results\:/i) >= 0){
				if(psGetInnerText(h3Results[i]).search(/Products\s+\((\d+)\)/i) >= 0){
					result = RegExp.$1;
				}
				if(filter != null && filter.indexOf("help") >= 0){
					if(psGetInnerText(h3Results[i]).search(/Help\s+\((\d+)\)/i) >= 0){
						result = RegExp.$1;
					}else{
						result = "0";
					}
				}else if(filter != null && filter.indexOf("blog") >= 0){
					if(psGetInnerText(h3Results[i]).search(/Blog\s+\((\d+)\)/i) >= 0){
						result = RegExp.$1;
					}else{
						result = "0";
					}
				}
			}
		}
	}
	return result;
}

function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()){
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
		psHijackAddToCart_ProductView(prd.id,prd.catId);
	}
}

function psHijackAddToCart_ProductView(prdId, prdCatId){
	var buys = psGetElementsByClassName(document,"input","submit buy_now");
	if(psCheckArrayExist(buys)){
		for(var i=0; i<buys.length; i++){
			if(buys[i].value == "Buy Now"){
				var buy = buys[i];
				if(buy.onclick == null || buy.onclick.toString().indexOf("psAddToCart") < 0){
					buy.prdId = prdId;
					buy.prdCatId = prdCatId;
					buy.OldFunction = buy.onclick;
					buy.onclick = function psAddToCart(){						
						psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdId,this.prdCatId);
						if(this.OldFunction != null)
							return this.OldFunction();
					}
				}
			}
		}
	}
}

function psHijackAddToCart_CategoryView(prdCatId){
	var prdDivs = psGetElementsByClassName(document,"div","prod_feature");
	if(psCheckArrayExist(prdDivs)){
		for(var i=0; i<prdDivs.length; i++){
			var prdId = null;
			var aTags = prdDivs[i].getElementsByTagName("a");
			if(psCheckArrayExist(aTags)){
				if(aTags[0].innerHTML.search(/\/prod\/(\w+)\/(\w+)\.jpg/i) >= 0){
					prdId = RegExp.$1;					
				}
			}
			var buys = psGetElementsByClassName(prdDivs[i],"input","submit");
			if(psCheckArrayExist(buys)){
				for(var j=0; j<buys.length; j++){					
					if(buys[j].value == "Buy" && prdId != null){						
						var buy = buys[j];						
						if(buy.onclick == null || buy.onclick.toString().indexOf("psAddToCart") < 0){
							buy.prdId = prdId;
							buy.prdCatId = prdCatId;
							buy.OldFunction = buy.onclick;
							buy.onclick = function psAddToCart(){								
								psSetValueToCookie(G_PS_COOKIE_PROD_CATID,this.prdId,this.prdCatId);
								if(this.OldFunction != null)
									return this.OldFunction();
							}
						}						
					}
				}
			}
		}
	}
}

function psPostCartView()
{
	psSetCookie(G_PS_COOKIE_SHOP5_RESTORE, "", "delete");
	psSetCookie(G_PS_COOKIE_GIFTCARD, "", "delete");
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("BASKET", G_PS_CUR_CATID, null, null);

	var cartTbl = null;
	
	var tables = document.getElementsByTagName("table");
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){			
			if(tables[i].rows.length > 1 && tables[i].rows[0] != null && tables[i].rows[1] != null){
				if(psGetInnerText(tables[i].rows[0]).search(/(SKU\s*Item\s*Price|Gift\s+Information\s+Updated)/i) >= 0 ||
				   psGetInnerText(tables[i].rows[1]).search(/(SKU\s*Item\s*Price|Gift\s+Information\s+Updated)/i) >= 0){
					cartTbl = tables[i];
				}
			}
		}
	}
	
	if (cartTbl == null)
		return;

	var sentShop5 = false;
	var rows = cartTbl.rows; 
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) 
	{
		if(rows[r].cells.length < 7){
			continue;
		} 
		if(rows[r].cells[1].innerHTML.indexOf("chkRemove") < 0 && psGetInnerText(rows[r]).search(/(GIFTOPTIONS|Gift\s+Cards)/i) < 0 ){
			continue;
		}		
		if (prd.getItem5(rows[r])){
			sentShop5 = true;
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
		}
	}
	if(sentShop5 == true){
		// Make sure to have actual postings
		psDisplayShop5s();
	}
}

function psPostOrderView()
{
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("View Order", G_PS_CUR_CATID, null, null);

	var cartTbl = null;

	var tables = document.getElementsByTagName("table");
	if(psCheckArrayExist(tables)){
		for(var i=0; i<tables.length; i++){
			if(psGetInnerText(tables[i].rows[0]) != null && psGetInnerText(tables[i].rows[0]).search(/SKU\s*Item\s*Price/i) >= 0){
				cartTbl = tables[i];
			}
		}
	}
	if (cartTbl == null)
		return;

	var rows = cartTbl.rows;
	var ord = new psOrder();

	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile()) // Read profile from cookie persisted earlier
		{
			var arrProductId = new Array();
			var arrProductName = new Array();
			var arrProductQuantity = new Array();
			var arrProductPrice = new Array();
			var arrProductCat = new Array();
			var prdIndex = 0;
			
			var prd = new psProduct();
			for (var r = 0; r < rows.length; r++) // item for each row
			{
				if(psGetInnerText(rows[r].cells[0]) == null || rows[r].cells.length < 5){
					continue;
				}
				var firstCol = psHtmlDecode(unescape(psGetInnerText(rows[r].cells[0])));
				if(firstCol.search(/^\s*SKU\s*$/i) >= 0){
					continue;
				}
				
				if (prd.getItem9(rows[r])){
					arrProductId[prdIndex] = prd.id;
					arrProductName[prdIndex] = prd.name;
					arrProductQuantity[prdIndex] = prd.quantity;
					arrProductPrice[prdIndex] = prd.price;
					arrProductCat[prdIndex] = prd.catId;
					prdIndex++;					
					//psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
				}
			}
			/*
			var preShop5 = psGetCookie(G_PS_COOKIE_SHOP5_RESTORE);
			if(preShop5 == "restore_all"){
				// resend shop5 if user restores the previous shop5
				for(var i=0; i<prdIndex; i++){					
					psCreateShopAction5Tag(arrProductId[i], arrProductName[i], arrProductQuantity[i], arrProductPrice[i], arrProductCat[i]);
				}				
				// Send GiftCard from cookie
				var pGift = psGetCookie(G_PS_COOKIE_GIFTCARD);
				if(pGift != null && pGift != "" && pGift.indexOf("|") >= 0){
					var pItems = pGift.split("|");
					if(pItems.length > 4){						
						psCreateShopAction5Tag(pItems[0], pItems[1], pItems[2], pItems[3], pItems[4]);						
					}
				}				
				psDisplayShop5s();
			}
			*/
			for(var i=0; i<prdIndex; i++){
				psCreateShopAction9Tag(arrProductId[i], arrProductName[i], arrProductQuantity[i], arrProductPrice[i], uP.cusId, ord.id, ord.subtotal, arrProductCat[i]);
			}
			// Send GiftCard from cookie
			var pGift = psGetCookie(G_PS_COOKIE_GIFTCARD);
			if(pGift != null && pGift != "" && pGift.indexOf("|") >= 0){
				var pItems = pGift.split("|");
				if(pItems.length > 4){
					psCreateShopAction9Tag(pItems[0], pItems[1], pItems[2], pItems[3], uP.cusId, ord.id, ord.subtotal, pItems[4]);
					//var temp = this.id + "|" + this.name + "|" + this.quantity + "|" + this.price + "|" + this.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_SHOP5_RESTORE, "", "delete");
			psSetCookie(G_PS_COOKIE_GIFTCARD, "", "delete");
		}
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
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;
	}
	
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var h3Tags = document.getElementsByTagName("h3");
			if(psCheckArrayExist(h3Tags)){
				for(var i=0; i<h3Tags.length; i++){
					if(psGetInnerText(h3Tags[i]).search(/Product\s+Code\:/i) >= 0){
						this.id = psTrim(psGetInnerText(h3Tags[i]).replace(/Product\s+Code\:/i,""));
					}
				}
			}
			var pHeader = document.getElementById("p_header");
			if(psCheckElementExist(pHeader)){
				var h1Tags = pHeader.getElementsByTagName("h1");
				if(psCheckArrayExist(h1Tags)){
					this.name = psTrim(psHtmlDecode(unescape(psGetInnerText(h1Tags[0]))));
					this.name = psCleanProductName(this.name);
				}
			}			
			if(G_PS_URL_REFERRER != null && G_PS_URL_REFERRER != "" && G_PS_URL_REFERRER.indexOf("oo.com.au") < 0){
				this.catId = "BOOKMARKS";
			}else if(G_PS_URL_REFERRER.indexOf("/basket") >= 0 || 
			         G_PS_URL_REFERRER.search(/_P.+\.cfm/i) >= 0 ||
			         G_PS_URL_REFERRER.search(/\/brand\//i) >= 0){				
				var dynamicCatId = psGetCookie(G_PS_COOKIE_DYNAMIC_CATID);
				if(dynamicCatId != null){
					// Click on Suggestions of basket page
					this.catId = dynamicCatId;
					psSetCookie(G_PS_COOKIE_DYNAMIC_CATID,"","delete");
					psSetCookie(G_PS_COOKIE_CATID,this.catId);
				}else{
					// View product in basket
					this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
					if(this.catId == null){
						//change currency on productview
						this.catId = psGetCookie(G_PS_COOKIE_CATID);
					}
				}
			}else{
				var dynamicCatId = psGetCookie(G_PS_COOKIE_DYNAMIC_CATID);
				if(dynamicCatId != null){
					// Click on What's hot, new arrivals, staff pick
					this.catId = dynamicCatId;
					psSetCookie(G_PS_COOKIE_DYNAMIC_CATID,"","delete");
					psSetCookie(G_PS_COOKIE_CATID,this.catId);
				}else{
					this.catId = psGetCookie(G_PS_COOKIE_CATID);
				}					

				if(this.catId != null && this.catId.search(/search\s+successful/i) >= 0){
					this.catId = "Search";
				}
			}
			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(psHtmlDecode(unescape(psGetInnerText(itemRow.cells[2]))));
			 this.name = psTrim(psHtmlDecode(unescape(psGetInnerText(itemRow.cells[3]))));
			 this.name = psCleanProductName(this.name);			 
			 if(this.id != null && this.id.search(/GIFTOPTIONS/i) >= 0){
				var extIndex = itemRow.cells.length-1;
				this.price = psCleanPriceNZ(psGetInnerText(itemRow.cells[extIndex]));				
				this.quantity = "1";
				this.catId = this.name;
				var temp = this.id + "|" + this.name + "|" + this.quantity + "|" + this.price + "|" + this.catId;
				psSetCookie(G_PS_COOKIE_GIFTCARD,temp);
			 }else{
				 var price = psGetInnerText(itemRow.cells[4]);			 
				 this.price = psCleanPriceNZ(price);
				 
				 var inputs = itemRow.getElementsByTagName("input");
				 if(psCheckArrayExist(inputs)){
					for(var q=0; q<inputs.length; q++){
						if(inputs[q].name != null && inputs[q].name.indexOf("QTY") >= 0){
							this.quantity = psTrim(inputs[q].value);
						}
					}
				 }
				 this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				 if(this.catId == null || this.catId == ""){
					this.catId = psGetCookie(G_PS_COOKIE_CATID);					
					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 receipt page
	 */
	this.getItem9 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!			
			this.id = psTrim(psGetInnerText(itemRow.cells[0]));
			this.name = psCleanProductName(psTrim(psGetInnerText(itemRow.cells[1])));
			if(this.id != null && this.id.indexOf("COUPON") >= 0){
				this.quantity = "1";
				this.catId = "COUPON";
				this.price = "0";
			}else{
				this.price = psCleanPriceNZ(psTrim(psGetInnerText(itemRow.cells[2])));
				this.quantity = psTrim(psGetInnerText(itemRow.cells[3]));
				this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
				if(this.catId == null){
					this.catId = "Unknown";
				}
			}
			 return true;
		}
		catch (ex) { return false; }
	}
}

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; }
	}
	
	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);
			return true;
		}
		catch (ex) { return false; }
	}
}

function psOrder()
{
	this.id = null;
	this.subtotal = null;
	this.shipping = null;
	/*
	 * get order info from source code
	 */
	this.getOrder = function()
	{
		try
		{
			var totalTable = null;
			var tables = document.getElementsByTagName("table");
			if(psCheckArrayExist(tables)){
				for(var i=0; i<tables.length; i++){
					if(psGetInnerText(tables[i].rows[0]) != null && psGetInnerText(tables[i].rows[0]).search(/Subtotal/i) >= 0){
						totalTable = tables[i];
					}
				}
			}
			if(totalTable == null) return false;
			var rows = totalTable.rows;
			for(var i=0; i<rows.length; i++){
				if(psGetInnerText(rows[i]) != null && psGetInnerText(rows[i]).search(/Subtotal/i) >= 0){
					this.subtotal = psCleanPriceNZ(psGetInnerText(rows[i].cells[1]));
				}
				if(psGetInnerText(rows[i]) != null && psGetInnerText(rows[i]).search(/Delivery/i) >= 0){
					this.shipping = psCleanPriceNZ(psGetInnerText(rows[i].cells[1]));
				}

			}
			var orderTags = psGetElementsByClassName(document,"td","title");
			if(psCheckArrayExist(orderTags)){
				for(var i=0; i<orderTags.length; i++){
					if(psGetInnerText(orderTags[i]).search(/Order\s+\#/i) >= 0){
						this.id = psTrim(psGetInnerText(orderTags[i]).replace(/Order\s+\#/i,""));
					}
				}
			}			
			var uP = new psProfile();
			uP.readProfile();  // Ensure to get the customer Id & email persisted at login stage
			
			// get billing address
			var billTable = null;
			var tbls = document.getElementsByTagName("table");
			if(psCheckArrayExist(tbls)){
				for(var i=0; i<tbls.length; i++){
					if(psGetInnerText(tbls[i].rows[0]) != null && psGetInnerText(tbls[i].rows[0]).search(/Bill\s+To\:/i) >= 0){
						billTable = tbls[i];						
					}
				}
			}
			if(billTable != null && billTable.rows.length >= 2 && billTable.rows[1].cells.length >= 2){
				
				var bAddress = billTable.rows[1].cells[0].innerHTML;
				if(bAddress.search(/<BR\s*\/*>/i) >= 0){
					var pItems = bAddress.split(/<BR\s*\/*>/gi);
					if(pItems.length > 2){						
						var addIndex = 2;
						if(psTrim(pItems[pItems.length-1]) == ""){
							addIndex = 3;
						}						
						bAddress = pItems[pItems.length - addIndex];						
						if(bAddress.search(/(.+)\,\s+(.+)\s+(\d+)/i) >= 0){
							uP.city = psTrim(RegExp.$1);
							uP.state = psTrim(RegExp.$2);
							uP.zipcode = psTrim(RegExp.$3);
						}
					}
				}
				var bEmail = billTable.rows[1].cells[1].innerHTML;				
				if( bEmail.search(/<BR\s*\/*>/i) >= 0){					
					var pItems =  bEmail.split(/<BR\s*\/*>/gi);
					bEmail = psTrim(pItems[pItems.length-1]);
					uP.cusId = uP.email = bEmail;					
				}
				
			}			
			return uP.writeProfile();
		}
		catch (ex) {return false;}
	}
}

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;
}

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;
}

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)
{
	//pProductName = pProductName.replace("°","");
	pProductName = pProductName.replace(String.fromCharCode(176),"");	
	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null; 
}

function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) != "string")
		return pStr;
	return (pStr != null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

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;
}

function psGetElementValueById(pTagId, pValueFlag)
{
    var tag = document.getElementById(pTagId);
    return psGetElementValue(tag, pValueFlag);
}
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;
}

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;
}

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;
}

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;
	
}

function psGetDomain(pUrl){
    var se = /^https*\:\/\/([^\/\:]+)/gi;
    return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}

function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

function psCleanPriceNZ(pPrice){
	var price = pPrice;
	if(pPrice.search(/\(AU(.+)\s*\)/i) >= 0){
		price = RegExp.$1;		
	}else if(pPrice.indexOf("(") >= 0){
		pPrice = pPrice.replace(/\(.+\)/,"");
		price = pPrice.replace("NZ","");
	}
	price = psCleanPrice(price);	
	return price;
}

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;
}

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);
}

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);
}

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 ==================*/