/************************************************************************************/
/* $Revision: 144477 $
 * $Id: cmtaggingservices -MASTER.js.txt 144477 2010-04-21 17:44:18Z croberts $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics  v1.3, 2010/04/21
 * 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
cmSetClientID("90303267",true,"catchoftheday.com.au");
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("catchoftheday.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_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG";		// used as a "session" variable to handle events between pages
var G_PS_COOKIE_EMAIL = "PS_EMAIL_TEMP";
var G_PS_COOKIE_BILLING	= "PS_BILLING";

var G_PS_COOKIE_SHOP9		 	= "PS_SHOP9";
var G_PS_COOKIE_PRODID		 	= "PS_PRODID";
var G_PS_COOKIE_ORDER		 	= "PS_ORDER";
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
var G_PS_COOKIE_FLAG_VIEW = "PS_FLAG_VIEW";
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!

if(G_PS_URL_PATH.indexOf("catchoftheday.com") > -1)
{
	psHijackLoginOnSite()
	if(psIsLoginSuccessful())
	{
		if(psCheckElementExist(psGetCookie(G_PS_COOKIE_FLAG)))
		{
			if(psGetCookie(G_PS_COOKIE_FLAG) == "new cus" || psGetCookie(G_PS_COOKIE_FLAG) == "login")
				psPostRegistration();
		}
	}
	if(G_PS_PATHNAME == "/login.php")
	{
		psHijackLogin();
		psHijackCreatAccount();
		psCreatePageviewTag("Login", "Account", null, null);
	}
	else if(G_PS_PATHNAME == "/account_edit.php")
	{
		if(psIsUpdatedUnSuccessful("account_edit")){
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
		psCreatePageviewTag("Account Edit", "Account", null, null);
		psHijackUpdateAcc();
	}
	else if(G_PS_PATHNAME == "/account_password.php")
	{
		psCreatePageviewTag("Change Password", "Account", null, null);
	}
	else if(G_PS_PATHNAME == "/account.php")
	{
		psCreatePageviewTag("Account", "Account", null, null);
		if(psGetCookie(G_PS_COOKIE_FLAG) == "update account")
		{
			
			var uP = new psProfile();
			uP.readProfile(); 
			var accValue = psGetCookie(G_PS_COOKIE_EMAIL);
			if (psCheckElementExist(accValue))
			{
				var buf = accValue.split("-_-");
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				if (buf[0])
					uP.cusId = buf[0];
				uP.email = buf[1];
			}	
			uP.writeProfile();
			psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
	}
	else if(G_PS_PATHNAME.search(/\/create\_account\_success/gi)>= 0){
		psCreatePageviewTag("Create_account_success", "Account", null, null);
	}
	else if(G_PS_PATHNAME == "/address_book_process.php")
	{
		psCreatePageviewTag("Address Book Process", "Account", null, null);
		if(psIsUpdatedUnSuccessful("addressbook"))
		{
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
		if(psIsAddAddress())
		{
			psHijackAddAddress();
		}
		else if(psIsEditPrimaryAdd())
		{
			psHijackUpdateAdd();
		}
	}
	else if(G_PS_PATHNAME == "/address_book.php")
	{
		
		if(psGetCookie(G_PS_COOKIE_FLAG) == "update address"
			|| psGetCookie(G_PS_COOKIE_FLAG) == "add address")
		{
			var pAdd = psGetCookie(G_PS_COOKIE_BILLING);
			if(psCheckElementExist(pAdd))
			{
				psGetBillingAddFromCookie();
			}
			psSetCookie(G_PS_COOKIE_BILLING,"","delete");
		}
		psCreatePageviewTag("Address Book", "Account", null, null);
	}
	else if(G_PS_PATHNAME == "/"
		|| G_PS_PATHNAME == "/index.php")
	{
		psCreatePageviewTag("Home Page", "Home", null, null);
		psHijackCatIdFromPage("Smallfish_info");
	}
	else if(G_PS_PATHNAME ==  "/gvpurchase.php")
	{
		psCreatePageviewTag("Gift Vouchers", "Gift Vouchers", null, null);
		psHijackAddGift("col132");
		psHijackAddGift("col132 left16");	
	}
	else if(G_PS_PATHNAME ==  "/about_us.php")
	{
		psCreatePageviewTag("About Us", "Home", null, null);
	}
	else if(G_PS_PATHNAME ==  "/news.php")
	{
		if(psIsArticlePage()){
			psCreatePageviewTag(psGetArticleName(), "Blog", null, null);
		}
		else{ 
			psCreatePageviewTag("Blog news", "Home", null, null);
		}
	}
	else if(G_PS_PATHNAME == "/past_product_archive.php")
	{
		psCreatePageviewTag("Caught", "Past Product Archive", null, null);
	}
	else if(G_PS_PATHNAME.search(/\/helpcenter\//i) >= 0)
	{
		psCreatePageviewTag("Help center", "Home", null, null);
	}
	else if(G_PS_PATHNAME.search(/\/wine\/windex\.php/i) >= 0)
	{
		psCreatePageviewTag("wine", "wine", null, null);
	}
	else if(G_PS_PATHNAME.search(/\/newsletters/i) >= 0)
	{
		psCreatePageviewTag("newsletters", "newsletters", null, null);
	}
	else if(G_PS_PATHNAME.search(/shipping\_table\.php/i) >= 0)
	{
		psCreatePageviewTag("shipping", "shipping", null, null);
	}
	else if(G_PS_PATHNAME == "/privacy.php" || G_PS_PATHNAME == "/term.php")
	{
		var pTemp = G_PS_PATHNAME.replace(/\//i,"");
		pTemp = pTemp.replace(/\.php/i, "");
		psCreatePageviewTag(pTemp, pTemp, null, null);
	}
	else if(G_PS_PATHNAME == "/password_forgotten.php"){
		psCreatePageviewTag("Password_forgotten", "Account", null, null);
	}
	else if(psIsProductView())
	{
		psPostProductView();
	}
	else if (psIsCartView())
	{
		psHijackAddFromShopCart("cs_item borderright");
		psHijackAddFromShopCart("cs_item");
		psHijackViewProduct();
		psPostCartView();
	}
	else if(G_PS_PATHNAME.search(/checkout\_payment\_address\.php/gi) >= 0)
	{
		psCreatePageviewTag("Checkout Payment Address","checkout",null,null);
		var pForm = psGetElementByName("form", "checkout_address");
		if(psCheckElementExist(pForm)){
			if(pForm.innerHTML.search(/Address Book Entries/gi) >= 0 
			&& pForm.innerHTML.search(/New Billing Address/gi) >= 0){
				psHijackNewBillingOrAddressBookEntries();
			}
			else{
				if(pForm.innerHTML.search(/Address Book Entries/gi) >= 0){
					psHijackAddressBookEntries();
				}
				if(pForm.innerHTML.search(/New Billing Address/gi) >= 0){
					psHijackNewBilling();
				}
			}
		}
	}
	else if(G_PS_PATHNAME.search(/checkout\_payment\.php/gi) >= 0)
	{
		psCreatePageviewTag("Checkout Payment","checkout",null,null);
		if(psGetCookie(G_PS_COOKIE_FLAG) == "new billing" 
		|| psGetCookie(G_PS_COOKIE_FLAG) == "choose address"
		|| psGetCookie(G_PS_COOKIE_FLAG) == "one or two"){
			psGetBillingAddFromCookie();
		}
	}
	else if(G_PS_PATHNAME == "/checkout_confirmation.php")
	{
		psCreatePageviewTag("Checkout_confirmation","checkout",null,null);
		psSetOrderToCookie();
		psSaveProfileFromCheckOut();
		//psPostOrderView(); // only for test.
	}
	else if (psIsOrderView())
	{
		psPostOrderView();
	}
	else 
	{	
		var pId = G_PS_PATHNAME.replace(/^\/*/i, "");
		pId = pId.replace(/\.php/gi, "");
		if(pId.search(/\_/gi) >= 0){
			pId = pId.replace(/\_/gi, " ");
		}
		var psCat = null;
		var pHeader = document.getElementById("secheader");
		if(psCheckElementExist(pHeader)){
			var pImgs = pHeader.getElementsByTagName("img");
			if(psCheckArrayExist(pImgs)){
				var pImg = pImgs[0];
				if(pImg.src != null && pImg.src.search(/\.jpg/i) >= 0){
					var pcatId = pImg.src.replace(/\.jpg/i, "");
					if(pcatId.search(/t\_/i) >= 0){
						var pcatIds = pcatId.split(/t\_/i);
						psCat = pcatIds[pcatIds.length -1];
					}
				}
			}
		}
		psCreatePageviewTag(pId, psCat, null, null); // Other pages go to "ADD URL" category
	}
	if(G_PS_PATHNAME == "/past_product.php"){
		psHijackCatIdFromPage("Past Product Archive");
	}
	if(psDetectedCmId()){
		psPostProductView();
	}
}

function psDetectedCmId(){
	var pIns = psGetElementByName("input", "cm_id");
	if(psCheckElementExist(pIns)){
		if(pIns.value != null && pIns.value != ""){
			return true;
		}
	}
	return false;
}
/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{
	if(psIsSoldOutProduct()){
		return true;
	}
	return false;
}

function psIsSoldOutProduct()
{
	var smDetail = document.getElementById("smallfish_details");
	if(psCheckElementExist(smDetail))
	{
		var lstImg = smDetail.getElementsByTagName("img");
		if(psCheckArrayExist(lstImg))
		{
			for(var i=0;i< lstImg.length;i++)
			{
				if(lstImg[i].src && lstImg[i].src.search(/images\/img\/banner\_soldout\.jpg/gi) >= 0)				
				{
					psSetCookie(G_PS_COOKIE_CATID, "Past Product Archive");
					return true;
				}
				if(lstImg[i].src){
					if(lstImg[i].src.search(/images\/img\/bite\_me\.jpg/gi) >= 0 
					|| lstImg[i].src.search(/images\/img\/almostgone\_hover\.gif/gi) >= 0){
						if(psGetCookie(G_PS_COOKIE_FLAG_VIEW) == "view"){
							psSetCookie(G_PS_COOKIE_CATID, "Past Product Archive");
							psSetCookie(G_PS_COOKIE_FLAG_VIEW ,"", "delete");
						}
						else{
							psSetCookie(G_PS_COOKIE_CATID, "Smallfish_info");
						}
						return true;
					}
				}
			}
		}
	}
	return false;
}

/*
 * Determine if the page is the shopping cart page
 */
function psIsCartView()
{
	if(G_PS_URL_PATH.search(/\/shopping\_cart\.php/i) >= 0){
		return true;
	}
	return false;
}

/*
 * Determine if the page is the thank you page
 */
function psIsOrderView()
{
	if(G_PS_URL_PATH.search(/\/checkout\_success\.php/i) >= 0){
		return true;
	}
	return false;
}
/*============================ END NAVIGATION ================================*/


/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/

function psIsArticlePage()
{
	var sArticle = psGetValueFromUrl(G_PS_URL_PATH,"article");
	return psCheckElementExist(sArticle)?true:false;
}

function psGetArticleName()
{
	var sName = null;
	var sDivTitle = document.getElementById("pasttitle");
	if(psCheckElementExist(sDivTitle) == false)
	{
		var sDivTitles = psGetElementsByClassName(document, "div","pasttitle");
		if(psCheckArrayExist(sDivTitles)){
			sDivTitle = sDivTitles[0]; 
			var oTitle = sDivTitle.getElementsByTagName("h1");
			if(psCheckArrayExist(oTitle))
			{
				sName = psTrim(psCleanHtmlTag(psHtmlDecode(oTitle[0].innerHTML)));			
			}
		}
	}
	return sName;
}

function psSaveProfileFromCheckOut(){
	var pTemp = "";
	var uP = new psProfile();
	uP.readProfile();
	var pTables = psGetElementsByClassName(document, "table", "gridtable");
	if(psCheckArrayExist(pTables)){
		for(var i=0; i< pTables.length; i++){
			var pH3s = pTables[i].getElementsByTagName("h3");
			if(psCheckArrayExist(pH3s)){
				if(pH3s[0].innerHTML.search(/Billing\s+Details/i) >= 0){
					var pTds = pTables[i].getElementsByTagName("td");
					if(psCheckArrayExist(pTds)){
						var pText = pTds[0].innerHTML;
						if(pText.search(/\<\s*BR\s*\/*\s*\>/gi) >= 0){
							var pProf = pText.split(/\<\s*BR\s*\/*\s*\>/gi);
							for(var j=0; j< pProf.length; j++){
								if(pProf[j].search(/\,/i) >= 0){
									pTemp = pTemp + "," + pProf[j];
								}
							}
						}
					}
				}
			}
		}
	}
	var pTemps = pTemp.split(",");
	for(var j=0; j<pTemps.length; j++){
		if(pTemps[j] != null && pTemps[j] != "" && isFinite(psTrim(pTemps[j]))){
			uP.city = psTrim(psHtmlDecode(unescape(pTemps[j -1])));
			uP.zipcode = psTrim(psHtmlDecode(unescape(pTemps[j])));
			uP.state = psTrim(psHtmlDecode(unescape(pTemps[j + 1])));
		}
	}
	uP.writeProfile();
}



function psHijackCatIdFromPage(PageId){
	var pPbs = psGetElementsByClassName(document, "div", "pb");
	var pTemp = null;
	if(psCheckArrayExist(pPbs)){
		for(var i=0; i< pPbs.length; i++){
			var pLinks = pPbs[i].getElementsByTagName("a");
			if(psCheckArrayExist(pLinks)){
				for(var j=0; j< pLinks.length; j++){
					if(pLinks[j].href!= null && pLinks[j].href.search(/smallfish\_info\.php\?/i) >= 0){
						pTemp = psGetValueFromUrl(pLinks[j].href, "products_id");
						break;
					}
				}
			}
			var pInputs = pPbs[i].getElementsByTagName("input");
			if(psCheckArrayExist(pInputs)){
				for(var j=0; j< pInputs.length; j++){
					if(pInputs[j].title == "Add to cart"){
						pInputs[j].prodId = pTemp;
						pInputs[j].Oldf = pInputs[j].onclick;
						pInputs[j].onclick = function HijackCaIdFromHome(){
							this.prodId = psTrim(psHtmlDecode(unescape(this.prodId)));
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.prodId, PageId);
							if(this.Oldf != null){
								return this.Oldf();
							}
						}
					}
				}
			}
		}
	}
}


function psHijackAddGift(ClassName){
	var pTemp = null;
	var pGifts = psGetElementsByClassName(document, "div", ClassName);
	if(psCheckArrayExist(pGifts)){
		for(var i=0; i< pGifts.length; i++){
			
			var pNames = pGifts[i].getElementsByTagName("p");
			if(psCheckArrayExist(pNames)){
				var psName = pNames[0].innerHTML;
				if(psName.indexOf(" ") >= 0){
					var psNames = psName.split(" ");
					pTemp = psTrim(psHtmlDecode(unescape(psNames[0]))) + " Gift Voucher";
				}
			}
			
			var pAddbtns = pGifts[i].getElementsByTagName("input");
			if(psCheckArrayExist(pAddbtns)){
				for(var j=0; j< pAddbtns.length; j++){
					if(pAddbtns[j].title == "Add Gift Voucher to Cart"){
						pAddbtns[j].pName = pTemp;
						pAddbtns[j].Oldf = pAddbtns[j].onclick;
						pAddbtns[j].onclick = function HijackAddGift(){
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.pName, "Gift Vouchers");
							if(this.Oldf != null){
								return this.Oldf();
							}
						}
					}
				}
			}
		}
	}
}

function psHijackNewBilling(){
	var city = null;
	var state = null;
	var zipcode = null;
	var add = null;
	var pForms = document.getElementsByTagName("form");
	if(psCheckArrayExist(pForms)){
		for(var i=0; i< pForms.length; i++){
			if(pForms[i].innerHTML.search(/New\s+Billing\s+Address/i) >= 0){
				pForms[i].Oldf = pForms[i].onsubmit;
				pForms[i].onsubmit = function HijackNewBilling(){
					var pCode = psGetElementByName("input", "postcode");
					zipcode = pCode.value;
					var pCities = psGetElementByName("select", "city");
					city = pCities.options[pCities.selectedIndex].innerHTML;
					var pStates = psGetElementByName("select", "state");
					state = pStates.options[pStates.selectedIndex].innerHTML;
					add = city + "-_-" + state + "-_-" + zipcode;
					psSetCookie(G_PS_COOKIE_BILLING, add);
					psSetCookie(G_PS_COOKIE_FLAG, "new billing");
					if(this.Oldf != null){
						return this.Oldf();
					}
				}
			} 
		} 
	}
}

function psHijackAddressBookEntries(){
	var city = null;
	var state = null;
	var zipcode = null;
	var add = null;
	var pForms = psGetElementByName("form", "checkout_address");
	if(psCheckElementExist(pForms)){
		pForms.Oldf = pForms.onsubmit;
		pForms.onsubmit = function HijackAddressBookEntries(){
			pTables = psGetElementsByClassName(this, "table", "gridtable");
			if(psCheckArrayExist(pTables)){
				for(var i=0; i< pTables.length; i++){
					var pIns = pTables[i].getElementsByTagName("input");
					if(psCheckArrayExist(pIns)){
						for(var j=0; j< pIns.length; j++){
							if(pIns[j].checked){
								var pText = psGetInnerText(pTables[i]);
								if(pText.search(/\,/gi) >= 0){
									var pTexts = pText.split(/\,/gi);
									for(var t=0; t< pTexts.length; t++){
										if(pTexts[t]!= null && isFinite(pTexts[t]) == true){
											city = psTrim(pTexts[t-1]);
											zipcode = psTrim(pTexts[t]);
											state = psTrim(pTexts[t +1]);
											add = city + "-_-" + state + "-_-" + zipcode;
										}
									}
								}
							}
						}
					}
				}
			}
			psSetCookie(G_PS_COOKIE_BILLING,add);
			psSetCookie(G_PS_COOKIE_FLAG, "choose address");
			if(this.Oldf != null){
				return this.Oldf();
			}
		}
	}
}

function psHijackNewBillingOrAddressBookEntries(){
	var pForms = psGetElementByName("form", "checkout_address");
	var city = null;
	var state = null;
	var zipcode = null;
	var add = null;
	if(psCheckElementExist(pForms)){
		pForms.Oldf = pForms.onsubmit;
		pForms.onsubmit = function HijackNewBillingOrAddressBookEntries(){
			
			var pCode = psGetElementByName("input", "postcode");
			zipcode = pCode.value;
			var pCities = psGetElementByName("input", "city");
			city = pCities.value;
			var pSts = psGetElementByName("input", "street_address");
			var pStreet = pSts.value;
			var pStates = psGetElementByName("select", "state");
			state = pStates.options[pStates.selectedIndex].innerHTML;
			if(zipcode != null && city!= null && zipcode != "" && city!= "" && pSts != null && pSts!= null){
				add = city + "-_-" + state + "-_-" + zipcode;
			}
			else{
				pTables = psGetElementsByClassName(this, "table", "gridtable");
				if(psCheckArrayExist(pTables)){
					for(var i=0; i< pTables.length; i++){
						var pIns = pTables[i].getElementsByTagName("input");
						if(psCheckArrayExist(pIns)){
							for(var j=0; j< pIns.length; j++){
								if(pIns[j].checked){
									var pText = psGetInnerText(pTables[i]);
									if(pText.search(/\,/gi) >= 0){
										var pTexts = pText.split(/\,/gi);
										for(var t=0; t< pTexts.length; t++){
											if(pTexts[t]!= null && isFinite(pTexts[t]) == true){
												city = psTrim(pTexts[t-1]);
												zipcode = psTrim(pTexts[t]);
												state = psTrim(pTexts[t +1]);
												add = city + "-_-" + state + "-_-" + zipcode;
											}
										}
									}
								}
							}
						}
					}
				}
			}
			psSetCookie(G_PS_COOKIE_BILLING,add);
			psSetCookie(G_PS_COOKIE_FLAG, "one or two");
			if(this.Oldf != null){
				return this.Oldf();
			}
		}
	}
}

function psHijackViewProduct(){
	var psCross = psGetElementsByClassName(document, "div", "cross_sell");
	if(psCheckArrayExist(psCross)){
		var pCross = psCross[0];
		var pViewbtn = pCross.getElementsByTagName("img");
		if(psCheckArrayExist(pViewbtn)){
			for(var i=0; i< pViewbtn.length; i++){
				if(pViewbtn[i].src.search(/images\/img\/b\_view\.jpg/gi) >= 0){
					var pView = pViewbtn[i];
					pView.Oldf = pView.onclick;
					pView.onclick = function HijackViewProduct(){
						psSetCookie(G_PS_COOKIE_FLAG_VIEW, "view");
						if(this.Oldf != null){
							return this.Oldf();
						}
					}
				}
			}
		}
	}
}

function psHijackAddFromShopCart(ClassName){
	var pTemp = null;
	var pDivs = psGetElementsByClassName(document, "div", ClassName);
	if(psCheckArrayExist(pDivs)){
		for(var i=0; i< pDivs.length; i++){
			
			var pPros = pDivs[i].getElementsByTagName("a");
			if(psCheckArrayExist(pPros)){
				for(var j=0; j< pPros.length; j++){
					if(pPros[j].href!= null && pPros[j].href.search(/\/upsell\_info\.php/i) >= 0){
						pTemp = psGetValueFromUrl(pPros[j].href, "products_id");
						break;
					}
				}
			}
			
			var pInps = pDivs[i].getElementsByTagName("input");
			if(psCheckArrayExist(pInps)){
				for(var j=0; j< pInps.length; j++){
					if(pInps[j].alt == "Add to Cart"){
						pInps[j].prodid = pTemp;
						pInps[j].Oldf = pInps[j].onclick;
						pInps[j].onclick = function HijackAddFromShopCart(){
							psSetValueToCookie(G_PS_COOKIE_PROD_CATID, this.prodid, "Past Product Archive");
							if(this.Oldf != null){
								return this.Oldf();
							}
						}
					}
				}
			}
		}
	}
}

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 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;
}

/*
 * Process to post productview tag for the item in product detail
 */
function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()){ // Get product info successfully?
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
	}
	if(psDetectedCmId() == false){
		psCreatePageviewTag("PRODUCT: " + prd.name + ".(" + prd.id + ")", prd.catId, null ,null);
	}
}

function psGetValueByName(pName,pValueFlag)
{
	var lstNames = document.getElementsByName(pName);
	var sText = psGetElementValue(lstNames[0],pValueFlag);
	return (lstNames && lstNames.length >0)?psTrim(sText):"";
}

function psIsAddAddress()
{
	var titles = psGetElementsByClassName(document,"div","seccontent_wide");
	if(psCheckArrayExist(titles))
	{
		var sText = psTrim(psCleanHtmlTag(psHtmlDecode(titles[0].innerHTML))) ;
		if(sText.search(/Add Address Book/gi) > -1){
			return true;
		}
		if(sText.search(/Update Address Book/gi) > -1 && psIsEditPrimaryAdd() == false){
			return true;
		}
	}
	return false;
}

function psHijackUpdateAdd()
{
	var city = null;
	var state = null;
	var zipcode = null;
	var add = null;
	var frmEditAdd = document.getElementsByName("addressbook");
	if(psCheckArrayExist(frmEditAdd))
	{
		frmEditAdd[0].oldCMFunc = frmEditAdd[0].onsubmit;
		frmEditAdd[0].onsubmit = function()
		{
			city = psGetElementValueById("inputSuburb");
			state = psGetElementValueById("inputState",false);
			zipcode = psGetElementValueById("inputPCode");
			add = city + "-_-" + state + "-_-" + zipcode;
			psSetCookie(G_PS_COOKIE_BILLING,add);
			psSetCookie(G_PS_COOKIE_FLAG, "update address");
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}			
	}
}

function psHijackAddAddress()
{
	var city = null;
	var state = null;
	var zipcode = null;
	var add = null;
	var frmEditAdd = document.getElementsByName("addressbook");
	if(psCheckArrayExist(frmEditAdd))
	{
		frmEditAdd[0].oldCMFunc = frmEditAdd[0].onsubmit;
		frmEditAdd[0].onsubmit = function()
		{
			var primary = document.getElementById("primary");
			if(psCheckElementExist(primary) &&  primary.checked == true) // is add address
			{			
				city = psGetElementValueById("inputSuburb");
				state = psGetElementValueById("inputState",false);
				zipcode = psGetElementValueById("inputPCode");
				add = city + "-_-" + state + "-_-" + zipcode;
				psSetCookie(G_PS_COOKIE_BILLING,add);
				psSetCookie(G_PS_COOKIE_FLAG,"add address");
			}
			if (this.oldCMFunc != null)
				return this.oldCMFunc();
		}			
	}
}


function psGetBillingAddFromCookie()
{
	try
	{
		var sAddress = psGetCookie(G_PS_COOKIE_BILLING);
		if (psCheckElementExist(sAddress))
		{
			var uP = new psProfile();
			if(uP.readProfile())
			{
				var buf = sAddress.split("-_-");
				for (var i=0; i<buf.length; i++)
				{
					var tempVal = buf[i];
					buf[i] = (tempVal=="null" ? null : tempVal); 
				}
				uP.city = buf[0];
				uP.state = buf[1];
				uP.zipcode = buf[2];
				psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
				uP.writeProfile();
				psSetCookie(G_PS_COOKIE_FLAG,"","delete");
			}
		}
		return true;
	}
		catch (ex) { return false; }
}

function psIsEditPrimaryAdd()
{
	var primary = document.getElementById("primary");
	if(psCheckElementExist(primary))
		return false; 
	return true;
}

function psHijackUpdateAcc()
{
	var editFrm = document.getElementsByName("account_edit");
	if(psCheckArrayExist(editFrm))
	{		
		editFrm[0].OldFunction = editFrm[0].onsubmit;
		editFrm[0].onsubmit = function ()
		{			
			var cusId = psGetValueByName("nick",true);
			var email = psGetValueByName("email_address",true);
			if(psCheckElementExist(cusId))
			{
				var pValue = cusId + "-_-" + email;
				psSetCookie(G_PS_COOKIE_FLAG,"update account");
				psSetCookie(G_PS_COOKIE_EMAIL,pValue);
			}
			if(this.OldFunction != null) return this.OldFunction();
		}		
	}
}

function psIsUpdatedUnSuccessful(frmName)
{
	var editFrm = document.getElementsByName(frmName);
	if(psCheckArrayExist(editFrm))
	{		
		var allImgs = editFrm[0].getElementsByTagName("img");
		if(psCheckArrayExist(allImgs ))
		{
			for (var i=0; i<allImgs .length; i++)	
			{
				var items = allImgs [i];
				if (items.src && items.src.search(/images\/icons\/error\.gif/gi) > -1)
				{	
					return true;
				}
			}
		}
	}
	return false;
}

function psHijackCreatAccount()
{
	var allImgs = document.getElementsByTagName("img");
	if(psCheckArrayExist(allImgs ))
	{
		for (var i=0; i<allImgs.length; i++)	
		{
			var items = allImgs [i];
			if (items.src.search(/img\/b\_submit\.jpg/gi) > -1)
			{
				items.oldCMFunc = items.onclick; //backup the existing onclick function
				items.onclick = function()
				{
					var cusId = psGetValueByName("nick",true);
					var email = psGetValueByName("email_address",true);
					if(psCheckElementExist(cusId))
					{
						var uP = new psProfile();
						uP.email = email
						uP.cusId = cusId;
						uP.writeProfile();				
						psSetCookie(G_PS_COOKIE_FLAG,"new cus");
					}
					if(this.oldCMFunc != null) 
						return this.oldCMFunc();
				}
			}
		}
	}
}

function psHijackLogin()
{
	var allInputs = document.getElementsByTagName("input");
	if(psCheckArrayExist(allInputs))
	{
		for (var i=0; i<allInputs.length; i++)	
		{
			var items = allInputs[i];
			if (items.title && items.title.search(/sign in/gi) > -1 && items.src.search(/img\/b\_submit\.jpg/gi) > -1)
			{
				items.oldCMFunc = items.onclick; //backup the existing onclick function
				items.onclick = function()
				{
					var email = psGetValueByName("email_adr",true);
					if(psCheckElementExist(email))
					{
						var uP = new psProfile();
						if(psCheckEmail(email)) //login with email
							uP.email = uP.cusId = email;
						else 
							uP.cusId = email;
						uP.writeProfile();				
						psSetCookie(G_PS_COOKIE_FLAG,"login");
					}
					if (this.oldCMFunc != null)
						return this.oldCMFunc();
				}
			}
		}
	}
}

function psHijackLoginOnSite()
{
	psHijackLoginOnSiteKeypress("pass");
	psHijackLoginOnSiteKeypress("email_add");
	psHijackLoginOnSiteBtnClick();
}
function psHijackLoginOnSiteKeypress(TagId)
{
	var passWord = document.getElementById(TagId);
	if(psCheckElementExist(passWord))
	{
		passWord.oldCMFunc = passWord.onkeypress; //backup the existing onclick function
		passWord.onkeypress = function(e)
		{
			try
			{
				var key = window.event ? event.keyCode : e.keyCode;
				if(key == 13)
				{
					var email = document.getElementById("email_add");
					if(psCheckElementExist(email))
					{
						var uP = new psProfile();
						if(psCheckEmail(email.value)) //login with email
							uP.email = uP.cusId = email.value;
						else 
							uP.cusId = email.value;
						uP.writeProfile();				
						psSetCookie(G_PS_COOKIE_FLAG,"login");
					}
					if(this.oldCMFunc != null) return this.oldCMFunc(); 
				}
			}catch (ex) {}
		}
	}
}

function psHijackLoginOnSiteBtnClick()
{
	var divLogin = document.getElementById("loginsec");
	divLogin = psCheckElementExist(divLogin) == false?document.getElementById("login"):divLogin;
	if(psCheckElementExist(divLogin))
	{
		var allInputs = divLogin.getElementsByTagName("input");
		if(psCheckArrayExist(allInputs ))
		{
			for (var i=0; i<allInputs.length; i++)	
			{
				var items = allInputs[i];
				if (items.type && items.type == "image" && items.src.search(/img\/go\_button\.gif/gi) > -1)
				{
					items.oldCMFunc = items.onclick; //backup the existing onclick function
					items.onclick = function()
					{
			
						var email = document.getElementById("email_add");
						if(psCheckElementExist(email))
						{
							var uP = new psProfile();
							if(psCheckEmail(email.value)) //login with email
								uP.email = uP.cusId = email.value;
							else 
								uP.cusId = email.value;
							uP.writeProfile();				
							psSetCookie(G_PS_COOKIE_FLAG,"login");
						}
				
						if(this.oldCMFunc != null) 
							return this.oldCMFunc();
					}
				}
			}
		}
	}
}
function psIsLoginSuccessful()
{
	var links = document.getElementsByTagName("a");
	if(psCheckArrayExist(links))
	{
		for (var i=0; i<links.length; i++)	
		{
			var items = links[i];
			if (items.href && items.href.search(/\/logoff.php/gi) > -1)
			{
				return true;
			}
		}
	}	
	return false;
}

function psPostRegistration()
{
	var uP = new psProfile();
	uP.readProfile(); // get user profile from cookie
	if(uP.cusId != null)
	{
		psCreateRegistrationTag(uP.cusId, uP.email, uP.city, uP.state, uP.zipcode);
	}
	psSetCookie(G_PS_COOKIE_FLAG,"delete");
}

function psGetShopCartTable()
{
	var sTblRe = null;
	var lstTable = psGetElementsByClassName(document,"table","formtable");
	if(psCheckArrayExist(lstTable))
	{
		for (var j=0; j<lstTable.length; j++)	
		{
			var sRows = lstTable[j].rows; // use rows variable for optimization
			var sStop = (sRows.length > 1)? 2:sRows.length;
			for(var i=0; i< sStop; i++)
			{
				for(var t=0; t<sRows[i].cells.length; t++)
				{
					var sHeader = psCleanHtmlTag(sRows[i].cells[t].innerHTML);
					if (sHeader.toLowerCase().indexOf("price") > -1)
					{
						//we need catch the lastest of table so can't put a break 
						sTblRe = lstTable[j];			
					}
				}
			}
		}
	}
	return sTblRe;
}

function psGetProductId(pRow)
{
	var result = null;
	var arrInputs = pRow.getElementsByTagName("input");
	if(psCheckArrayExist(arrInputs))
	{
		for(var i = 0; i < arrInputs.length; i ++ )
		{
			if(arrInputs[i].type &&  arrInputs[i].type == "hidden" && arrInputs[i].name.search(/products\_id/gi) > -1)
			{
				result = arrInputs[i].value;
				if(result.search(/\{/gi) >= 0){
					var results = result.split(/\{/gi);
					result = psTrim(results[0]);
				}
			}
		}
	}
	return result;
	
}

function psGetProductQty(pRow)
{
	var result = null;
	var arrInputs = pRow.getElementsByTagName("input");
	if(psCheckArrayExist(arrInputs))
	{
		for(var i = 0; i < arrInputs.length; i ++ )
		{
			if(arrInputs[i].className &&  arrInputs[i].className == "inputbox" && arrInputs[i].name.search(/cart\_quantity/gi) > -1)
			{
				result = arrInputs[i].value;
			}
		}
	}
	return result;
	
}

function psSetOrderToCookie()
{              
	var pSubtotal = 0;
	var pShipping = 0;
	var pTables = psGetElementsByClassName(document, "table", "gridtable");
	if(psCheckArrayExist(pTables)){
		for(var i=0; i<pTables.length; i++){
			if(pTables[i].rows[0].cells[0].innerHTML.search(/Sub\-Total\:/i) >= 0){
				var pTds = pTables[i].getElementsByTagName("td");
				if(psCheckArrayExist(pTds)){
					for(var j=0; j<pTds.length; j++){
						if(pTds[j].innerHTML.search(/Sub\-Total\:/i) >= 0){
							pSubtotal = psCleanPrice(pTds[j + 1].innerHTML);
						}
						if(pTds[j].innerHTML.search(/Shipping\s+\(\)\:/i) >= 0){
							pShipping = psCleanPrice(pTds[j + 1].innerHTML);
							break;
						}
					}
				}
			}
		}
	}
	var pValueOrder =  pSubtotal+ "*:*" + pShipping;  
	psSetCookie(G_PS_COOKIE_ORDER, pValueOrder);                                                        
}


/*
 * Process to post shop5tags for items in shopping cart
 */
function psPostCartView()
{
	// Update the catId and pageId according to your specification
	G_PS_CUR_CATID = "CHECKOUT";
	psCreatePageviewTag("SHOPPING CART", G_PS_CUR_CATID, null);

	var pProId_tr="";
	
	psSetCookie(G_PS_COOKIE_SHOP9, "", "delete");
    psSetCookie(G_PS_COOKIE_ORDER, "", "delete");
	
	var cartTbl = null;
	//
	// TO-Do: Your logic to locate the items table (cartTbl) goes here
	//
	cartTbl = psGetShopCartTable();
	if(cartTbl == null)
		return;
	var rows = cartTbl.rows; // use rows variable for optimization
	var prd = new psProduct();
	for (var r = 0; r < rows.length; r++) // item for each row
	{
		/*
		 * Codes for skipping exceptional rows (rows that don't contain items)
		 */
		if (rows[r].innerHTML.search(/\$/gi)<0)
			 continue;
		
		if (prd.getItem5(rows[r]))
		{
			var pValueShop9 = prd.id + "|" +  prd.name + "|" + prd.quantity +"|" + prd.price.replace("$","") + "|" + prd.catId;				
			pProId_tr+=prd.id + "--";
			
			psSetValueToCookie(G_PS_COOKIE_SHOP9,prd.id,pValueShop9); 
			psCreateShopAction5Tag(prd.id, prd.name, prd.quantity, prd.price, prd.catId);
		}
	}
	psSetValueToCookie(G_PS_COOKIE_PRODID,"ProLst",pProId_tr);
	// Make sure to have actual postings
	psDisplayShop5s();
}
/*
 * Process to post shop9tags for items purchased
 */
function psPostOrderView()
{
	psCreatePageviewTag("Checkout_complete","checkout",null,null);
	var ord = new psOrder();
	var prd = new psProduct();
	if (ord.getOrder())
	{
		var uP = new psProfile();
		if (uP.readProfile())
		{
			var strProductId = psGetValueFromCookie(G_PS_COOKIE_PRODID,"ProLst");
			var arrProduct = strProductId.split("--");
			for(var i=0; i<arrProduct.length;i++)
			{
				if (arrProduct[i]!=null && arrProduct[i]!="")
				{
					prd.getItem9(arrProduct[i]);
					psCreateShopAction9Tag(prd.id, prd.name, prd.quantity, prd.price, uP.cusId, ord.id, ord.subtotal, prd.catId);
				}
			}
			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, uP.newsletter, uP.subscribe);
			psSetCookie(G_PS_COOKIE_FLAG, "", "delete");
		}
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* PURPOSE: constructor for product
 * Note: you can add more methods to psProduct in its prototype
 * RETURN: none
 */
function psProduct()
{
    this.id = null;
    this.name = null;
    this.catId = null;
    this.price = null;
    this.quantity = null;

	this.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
		this.price = null;
		this.quantity = null;
	}
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var pId = psGetValueFromUrl(psHtmlDecode(unescape(G_PS_URL_PATH)), "products_id");
			if(pId == null || pId == ""){
				pId = psGetValueFromUrl(psHtmlDecode(unescape(G_PS_URL_PATH)), "past_product_id");
			}
			if(pId == null || pId == ""){
				var G_PS_URL_PATH_TEMP = G_PS_PATHNAME.replace(/\.html/i,"");
				if(psCheckElementExist(G_PS_URL_PATH_TEMP)){
					if(G_PS_URL_PATH_TEMP.indexOf("p-") >= 0){
						var pProIds = G_PS_URL_PATH_TEMP.split("p-");
						if(psCheckArrayExist(pProIds)){
							pId = pProIds[pProIds.length - 1];
						}					
					}
				}
			}
			if(pId == null || pId == ""){
				var psCm = psGetElementByName("input", "cm_id");
				if(psCheckElementExist(psCm)){
					pId = psCm.value;
					if(pId!= null && pId != ""){
						psSetCookie(G_PS_COOKIE_CATID, "Featured Product");
					}
				}
			}
			if(pId != null || pId != ""){
				this.id = psTrim(psHtmlDecode(unescape(pId)));
			}
			var pSmall_Detail = document.getElementById("pr_details")
			if(psCheckElementExist(pSmall_Detail) == false){
				pSmall_Detail = document.getElementById("smallfish_details");
			}
			if(psCheckElementExist(pSmall_Detail)){
				var pName = pSmall_Detail.getElementsByTagName("h1");
				if(psCheckArrayExist(pName)){
					this.name = psTrim(psHtmlDecode(unescape(psGetInnerText(pName[0]))));
				}
			}
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			if(this.catId == null || this.catId == ""){
				if(G_PS_PATHNAME.search(/\-p\-/i) >= 0){
					if(G_PS_URL_REFERRER != null && G_PS_URL_REFERRER.search(/past\_product\_archive\.php/i) >= 0){
						this.catId = "Past Product Archive";
					}
					if(G_PS_URL_REFERRER != null && G_PS_URL_REFERRER.search(/news\.php/i) >= 0){
						this.catId = "Blog";
					}
				}
			}
			if(this.catId == null || this.catId == ""){
				this.catId = psGetCookie(G_PS_COOKIE_CATID);
			}
			if(this.catId == null || this.catId == ""){
				this.catId = "Unknown";
			}
			if(this.catId != "Past Product Archive"){
				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 = psGetProductId(itemRow);
			var name = itemRow.cells[2].innerHTML.toLowerCase();
			var lstNames = name.split("<br");
			if(psCheckArrayExist(lstNames))
				this.name = psTrim(psHtmlDecode(unescape(lstNames[0])));
			if(this.name.search(/Gift Voucher/gi) > -1)
				this.id = this.name;
			this.price = psTrim(psCleanHtmlTag(psHtmlDecode( itemRow.cells[3].innerHTML)));
			this.quantity = psGetProductQty(itemRow);
			// In most cases, catId is retrived from cookie G_PS_COOKIE_PROD_CATID as follows:
			this.catId = psGetValueFromCookie(G_PS_COOKIE_PROD_CATID, this.id);
			if(this.catId == null || this.catId == "")
			{
				this.catId = "Unknown";
			}
			return true;
		}
		catch (ex) { return false; }
	}
	/*
	 * Extracting product info from source code specified by the "current" row
	 * of items table in the receipt page
	 */
	this.getItem9 = function(itemRow)
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var strValue = psGetValueFromCookie(G_PS_COOKIE_SHOP9,itemRow);	
			if(strValue)
			{
				var arrValue = 	strValue.split("|");
				this.id = arrValue[0]; 	
				this.name = arrValue[1]; 
				this.quantity =  arrValue[2]; 
				this.price =  arrValue[3]; 
				this.catId = arrValue[4];
				if(this.catId == null || this.catId == "")
				{
					this.catId = "Unknown";
				}
			}
			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 pIns = psGetElementByName("input", "oid");
			if(psCheckElementExist(pIns)){
				this.id = pIns.value;
				this.id = psTrim(psHtmlDecode(unescape(this.id)));
			}
			if(this.id == null){
				this.id = psGenerateRandomValue();
			}
			var pValue = psGetCookie(G_PS_COOKIE_ORDER);
			if(pValue != null)
			{
				var arrValue = 	pValue.split("*:*");
				this.subtotal = arrValue[0] == "null"?null:arrValue[0];
				this.shipping = arrValue[1] == "null"?null:arrValue[1];
			} 
			return true;
		}
		catch (ex) {return false;}
	}
}

/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i=0; i<arguments.length; i++)
	{
		if(arguments[0] == null || arguments[i] == null)
		{
			return false;
		}
		else if(arguments[0].toUpperCase() != arguments[i].toUpperCase())
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb){
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb != null)
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1)
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

function psCleanHtmlTag(pValue)
{
    return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : 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;
}
/********************************************************/
/* 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 ==================*/