/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD
 * Coremetrics  v1.2, 2010/06/18
 * COPYRIGHT 1999-2010 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 = ['mercuryvmp.com'];//value must be one array of domains or null
// current page url
var G_PS_URL_PATH = "" + document.location.href.toLowerCase();
var G_PS_PATHNAME = document.location.pathname.toLowerCase();
var G_PS_QUERYSTRING = document.location.search.toLowerCase();
var G_PS_URL_REFERRER = document.referrer.toLowerCase();
var G_PS_COOKIE_LIFETIME = 432000; // 5*24*60*60 = 5 days
// cookie name
var G_PS_COOKIE_CATID = "PS_CATID";
var G_PS_COOKIE_PROD_CATID = "PS_PROD_CATID";
var G_PS_COOKIE_PROD_NAME = "PS_PROD_NAME";
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_COOKIE_FLAG = "PS_FLAG"; // used as a "session" variable to handle events between pages
// current category ID while browsing/searching/refining, etc
var G_PS_CUR_CATID = null;
/*========================= END GLOBAL VARIABLES =============================*/

/*=========================== BEGIN NAVIGATION ===============================*/
// Navigation logic should go here!
try
{
	psDoNavigation();
}
catch (e){};

/*================ Navigation Function ================*/
function psDoNavigation ()
{
	var lString = DoURLdecode((G_PS_PATHNAME.concat(G_PS_QUERYSTRING)).toLowerCase());
	if (psIsErrorPage())
	{
		psCreateErrorTag('Error', 'Error', null, null);
		psSetCookie(G_PS_COOKIE_CATID, 'HOME');
	}
	else if (psIsHomePageView())
	{
		psCreatePageviewTag('HOME', 'HOME', null, null);
		psSetCookie(G_PS_COOKIE_CATID, 'HOME');
	}
	else if (psIsSignInView ())
	{
		psPostSignInView();
	}
	else if (psIsSignUpView())
	{
		psPostSignUpView();
	}
	else if (psIsTopMenusView())
	{
		psPostTopMenus();
	}
	else if (psIsContentPageView())
	{
		psPostContentPage();
	}
	else if (lString.indexOf ('/index.php/analytics/?status=submitted') >-1)
	{	
		psCreatePageviewTag('analytics', 'HOME', null, null);
		psSetCookie(G_PS_COOKIE_CATID, 'HOME');
	}
	else if (lString.match(/^\/([A-Za-z_]+)\/\?clickid\=/) !== null)
	{
		psCreatePageviewTag(RegExp.$1, 'HOME', null, null);
		psSetCookie(G_PS_COOKIE_CATID, 'HOME');
	}
	else if (lString.match (/^\/([A-Za-z_]+)(?:\/([A-Za-z_\.]+)\/?([A-Za-z_\.]+)?)\/?/) !== null)
	{
		var lPageID = '';
		var lCatID = '';
		
		var lValue01 = RegExp.$1 + '';
		var lValue02 = RegExp.$2 + '';
		var lValue03 = RegExp.$3 + '';
		if (lValue03 !== '')
		{
			lPageID = lValue03;
			lCatID = lValue02;
		}
		else
		{
			lPageID = lValue02;
			lCatID = lValue01;
		}
		lPageID = lPageID.replace (/\.([a-z0-9]+)/ig,'');
		psCreatePageviewTag(lPageID, lCatID, null, null);
		psSetCookie(G_PS_COOKIE_CATID, lCatID);
	}
	else if (lString.match (/^\/index\.php\?\/includes\/([A-Za-z_]+)/) !== null)
	{
		psCreatePageviewTag(RegExp.$1, 'includes', null, null);
		psSetCookie(G_PS_COOKIE_CATID, 'includes');
	}
	else if (lString.match (/^\/([a-z0-9A-Z]+)\.html/) !== null)
	{
		psCreatePageviewTag(G_PS_PATHNAME, 'Error', null, null);
		psSetCookie(G_PS_COOKIE_CATID, 'Error');
	}
	else 
	{
		psCreatePageviewTag(G_PS_PATHNAME, "ADD URL"); // Other pages go to "ADD URL" category
	}
	psCheckLoggedIn ();
	psDoStuffs ();
}
/*================ End Of Navigation Function ================*/

/*================ Navi Confirmation Functions ================*/
function psIsHomePageView ()
{
	var lString = DoURLdecode((G_PS_PATHNAME.concat(G_PS_QUERYSTRING)).toLowerCase());
	if ((lString.match(/^(\/)+$/) !== null) ||(lString.match(/^\/index\.php((\/)+)?$/) !== null))
	{
		if (G_PS_URL_PATH.match (/^http\:\/\/(www\.)?mercuryvmp\.com/) !== null)
		{
			return true;
		}
	}
	return false;
}

function psCheckLoggedIn ()
{
	if (psIsSignInView())
	{
		psSetValueToCookie(G_PS_COOKIE_FLAG, 'SignInBtnClicked', 'no');
	}
	else
	{
		if (psGetValueFromCookie (G_PS_COOKIE_FLAG,'SignInBtnClicked') == 'yes')
		{
			var lUp = new psProfile();
			lUp.saveTemp();
			psCreateRegistrationTag(lUp.email, lUp.email, lUp.city, lUp.state, lUp.zipcode);
			psSetValueToCookie(G_PS_COOKIE_FLAG, 'SignInBtnClicked', 'no');
		}
	}
}

function psDoStuffs ()
{
	var lString = DoURLdecode((G_PS_PATHNAME.concat(G_PS_QUERYSTRING)).toLowerCase());
	if (psIsErrorPage ())
	{
		psSetValueToCookie(G_PS_COOKIE_FLAG, 'IsSubmitted', 'no');
	}
	else
	{
		if (psGetValueFromCookie (G_PS_COOKIE_FLAG,'IsSubmitted') == 'yes')
		{
			var lUp1 = new psProfile();
			lUp1.saveTemp();
			psCreateRegistrationTag(lUp1.email, lUp1.email, lUp1.city, lUp1.state, lUp1.zipcode);
			psSetValueToCookie(G_PS_COOKIE_FLAG, 'IsSubmitted', 'no');
		}
	}
	
	if (lString.indexOf('/admin/usermanagement/usermanagement.aspx') > -1)
	{
		if (psHasError ())
		{
			psSetValueToCookie(G_PS_COOKIE_FLAG, 'PIsSaved', 'no');
		}
		else
		{
			if (psGetValueFromCookie (G_PS_COOKIE_FLAG,'PIsSaved') == 'yes')
			{
				var lUp4 = new psProfile();
				lUp4.saveTemp();
				psCreateRegistrationTag(lUp4.email, lUp4.email, lUp4.city, lUp4.state, lUp4.zipcode);
				psSetValueToCookie(G_PS_COOKIE_FLAG, 'PIsSaved', 'no');
			}	
		}
		
		var lDivEle01 = ele ('ctl00_ctl00_Main_Main_tbMain_ctl00');
		if (psIsElement (lDivEle01))
		{
			var lUp3 = new psProfile();
			if (lUp3.readProfile())
			{
				var lCurEmail = psGetElementValueById('ctl00_ctl00_Main_Main_m_oContactInfo_txtEmail', false);
				if (lCurEmail === '')
				{
					lCurEmail = lUp3.cusId = 'empty';
				}
				if (lUp3.cusId === lCurEmail)
				{
					if (typeof lDivEle01.onclick == 'function')
					{
						lDivEle01.onclick = function ()
						{
							var oldFunc = this.onclick;			
							lUp3._cusId = psGetElementValueById('ctl00_ctl00_Main_Main_m_oContactInfo_txtEmail', false);
							lUp3._email = lUp3._cusId;
							lUp3._city = psGetElementValueById('ctl00_ctl00_Main_Main_m_oCompanyInfo_txtCity', false);
							lUp3._state = psGetElementValueById('ctl00_ctl00_Main_Main_m_oCompanyInfo_ddlState', true);
							lUp3._zipcode = psGetElementValueById('ctl00_ctl00_Main_Main_m_oCompanyInfo_txtZip', false);
							lUp3.writeProfile();
							psSetValueToCookie(G_PS_COOKIE_FLAG, 'PIsSaved', 'yes');
							return function (){oldFunc();};
						}
					}
				}
			}
		}
	}
	
	//Hijack all the links
	var lAllLinkEles = elsByTname (document,'a');
	if (psIsArray (lAllLinkEles))
	{
		for (var k=0; k<lAllLinkEles.length;k++)
		{
			var lHref = lAllLinkEles[k].href;
			if (lHref.match (/alamode_MedianFeeReport/ig) !== null)
			{
				psSetEventHandler (lAllLinkEles[k],'click',function ()
				{
					psCreateConversionEventTag('AFR',2,'AFR download');
				});
			}
			if (lHref.match (/MercNetSpec_t/ig) !== null)
			{
				psSetEventHandler (lAllLinkEles[k],'click',function ()
				{
					psCreatePageviewTag('MercNetMailer', 'documents', null, null);
					psSetCookie(G_PS_COOKIE_CATID, 'documents');
				});
			}
			if (lHref.match (/MercuryNetwork_Features/ig) !== null)
			{
				psSetEventHandler (lAllLinkEles[k],'click',function ()
				{
					psCreatePageviewTag('MercuryNetwork_Features', 'documents', null, null);
					psSetCookie(G_PS_COOKIE_CATID, 'documents');
				});
			}
			if (lHref.match (/MercNetMailer/ig) !== null)
			{
				psSetEventHandler (lAllLinkEles[k],'click',function ()
				{
					psCreatePageviewTag('MercNetMailer', 'documents', null, null);
					psSetCookie(G_PS_COOKIE_CATID, 'documents');
				});
			}
		}
	}
	
	var lForm1 = ele ('freeform');
	if (psIsElement (lForm1))
	{
		var lInputEles = elsByTname (lForm1,'input');
		if (psIsArray (lInputEles))
		{
			var lSubmitBtn = null;
			for (var i=0; i<lInputEles.length;i++)
			{
				if (lInputEles[i].name !== undefined)
				{
					if (lInputEles[i].name == 'submit')
					{
						lSubmitBtn = lInputEles[i];
						break;
					}
				}
			}
			if (psIsElement (lSubmitBtn))
			{
				psSetEventHandler (lSubmitBtn,'click',function ()
				{
					var lInputsE = elsByTname (lForm1,'input');
					if (psIsArray (lInputsE))
					{
						var lEmailTextField = null;
						for (var j=0; j<lInputsE.length;j++)
						{
							if (lInputsE[j].name !== undefined)
							{
								if (lInputsE[j].name == 'email')
								{
									lEmailTextField = lInputsE[j];
									break;
								}
							}
						}
						if (psIsElement (lEmailTextField))
						{
							var lUp2 = new psProfile();
							lUp2._cusId = lEmailTextField.value;
							lUp2._email = lUp2._cusId;
							lUp2.writeProfile();	
							psSetValueToCookie(G_PS_COOKIE_FLAG, 'IsSubmitted', 'yes');
						}
					}
				});
			}
		}
	}
}

function psHasError ()
{
	var lDivEle01 = ele ('AlertDialogTitle');
	if (psIsElement (lDivEle01))
	{
		var lInnerHTML = lDivEle01.innerHTML;
		if (lInnerHTML.toLowerCase().indexOf('error') >-1)
		{
			return true;
		}
	}
	var lDivEle02 = ele ('ctl00_ctl00_Main_Main_vsMain');
	if (psIsElement (lDivEle02))
	{
		var lLiEles = elsByTname (lDivEle02,'li');
		if (psIsArray (lLiEles))
		{
			return true;
		}
	}
	return false;
}

function psIsErrorPage ()
{
	var lTitleEle = elsByTname (document,'title');
	if (psIsArray (lTitleEle))
	{
		lTitleEle = lTitleEle[0];
		var lHTML = lTitleEle.innerHTML;
		lHTML = psCleanHtmlTag (lHTML);
		if (lHTML.toLowerCase().indexOf ('error') > -1)
		{
			return true;
		}	
	}
	return false;	
}

function psIsTopMenusView ()
{
	var lString = DoURLdecode((G_PS_PATHNAME.concat(G_PS_QUERYSTRING)).toLowerCase());
	return (lString.match (/^\/([A-Za-z_]+)\/?$/) !== null)? true:false;
}

function psIsContentPageView ()
{
	var lString = DoURLdecode((G_PS_PATHNAME.concat(G_PS_QUERYSTRING)).toLowerCase());
	return (lString.match (/^\/([A-Za-z_]+)(?:\/([A-Za-z_\.]+)\/?([A-Za-z_\.]+)?)\/?$/) !== null)? true:false;
}

function psIsSignInView()
{
	var lFormEle = ele ('aspnetForm');
	if (psIsElement (lFormEle))
	{
		var lHTMLcode = lFormEle.innerHTML;
		if (lHTMLcode.match (/Mercury\sNetwork\sSign\sIn/ig)!== null)
		{
			return true;
		}
	}
	return false;
}

function psIsSignUpView ()
{
	return (G_PS_PATHNAME.toLowerCase().indexOf ('signupwiz.aspx') > -1);
}

/*================ End Of Navi Confirmation Functions ================*/
/*============================ END NAVIGATION ================================*/
/*===================== BEGIN TAGGING BUSSINESS LOGIC ========================*/
/*================ Posting Logic Functions ================*/
function psPostTopMenus()
{
	var lPageID = '';
	var lCatID = '';
	var lString = DoURLdecode((G_PS_PATHNAME.concat(G_PS_QUERYSTRING)).toLowerCase());
	if (lString.match(/^\/([A-Za-z_]+)\/?$/) !== null)
	{
		lPageID = RegExp.$1;
		lCatID = 'HOME';
	}
	psCreatePageviewTag(lPageID, lCatID, null, null);
	psSetCookie(G_PS_COOKIE_CATID, lCatID);
}

function psPostContentPage ()
{
	var lPageID = '';
	var lCatID = '';
	var lString = DoURLdecode((G_PS_PATHNAME.concat(G_PS_QUERYSTRING)).toLowerCase());
	if (lString.match(/^\/([A-Za-z_]+)(?:\/([A-Za-z_\.]+)\/?([A-Za-z_\.]+)?)\/?$/) !== null)
	{
		var lValue01 = RegExp.$1 + '';
		var lValue02 = RegExp.$2 + '';
		var lValue03 = RegExp.$3 + '';
		if (lValue03 !== '')
		{
			lPageID = lValue03;
			lCatID = lValue02;
		}
		else
		{
			lPageID = lValue02;
			lCatID = lValue01;
		}
		if (lValue01 === 'documents')
		{
			lCatID = 'documents';
		}
		
		lPageID = lPageID.replace (/\.([a-z0-9]+)/ig,'');
	}
	// Added for feedback 2010/06/18.
	if(G_PS_PATHNAME.search(/\/appraiser\/faq/g)>=0){
		lPageID = G_PS_URL_PATH.split(/\//);
		if(psIsArray(lPageID) && lPageID.length > 1){
			lCatID = lPageID[lPageID.length -2];
			lPageID = lPageID[lPageID.length -1];
			if(lPageID.search(/top/g)>=0){
				lPageID = "faq";
			}
		}
		psHijackAppraiserLink();
	}
	psCreatePageviewTag(lPageID, lCatID, null, null);
	psSetCookie(G_PS_COOKIE_CATID, lCatID);
}

function psHijackAppraiserLink(){
	var pLeftRail = document.getElementById("left_rail");
	if(psIsElement(pLeftRail)){
		var pTagA = pLeftRail.getElementsByTagName("a");
		if(pTagA.length >0){
			for(var i =0; i<pTagA.length; i++){
				var pArrayLink = pTagA[i].href;
				if(pArrayLink != null && pArrayLink != "" && pArrayLink.search(/\#/)>=0 && pArrayLink.search(/top/)<0){	
					pTagA[i].pArrayLink = pArrayLink;
					pTagA[i].Oldf = pTagA[i].onclick;
					pTagA[i].onclick = function(){
						var pArrayLink_temp = this.pArrayLink.split(/\//);
						var pPageID = psTrim(unescape(pArrayLink_temp[pArrayLink_temp.length -1]));
						var pCatID = psTrim(unescape(pArrayLink_temp[pArrayLink_temp.length -2]));
						psCreatePageviewTag(pPageID, pCatID, null, null);
					}
					if(this.Oldf != null){
						return this.Oldf();
					}
				}
			}
		}
	}
}

function psPostSignInView ()
{
	var lPageID = 'SignIn';
	var lCatID = 'SignIn';
	
	psSetEventHandler ('ctl00_ctl00_Main_Main_btnSignIn', 'click', function ()
	{
		var lUp = new psProfile();
		lUp._cusId = psGetElementValueById('ctl00_ctl00_Main_Main_txtEmail', false);
		lUp._email = lUp._cusId;
		lUp.writeProfile();
		psSetValueToCookie(G_PS_COOKIE_FLAG, 'SignInBtnClicked', 'yes');
	});
	
	psCreatePageviewTag(lPageID, lCatID, null, null);
	psSetCookie(G_PS_COOKIE_CATID, lCatID);
}

function psPostSignUpView ()
{
	var lPageID = 'SignUp';
	var lCatID = 'SignUp';
	
	var lDoneBtn = ele ('ctl00_ctl00_Main_Main_wizSignUp_ctl06_btnStep1Next');
	if (psIsElement (lDoneBtn))
	{
		var lUp = new psProfile();
		lUp.saveTemp();
		psCreateRegistrationTag(lUp.email, lUp.email, lUp.city, lUp.state, lUp.zipcode);
	}
	psSetEventHandler ('ctl00_ctl00_Main_Main_wizSignUp_ctl05_btnStep1Next', 'click', function ()
	{
		var lUp = new psProfile();
		lUp._cusId = psGetElementValueById('ctl00_ctl00_Main_Main_wizSignUp_ctl05_ctlAccountSearchCriteria_txtEmail', false);
		lUp._email = lUp._cusId;
		lUp._state = psGetElementValueById('ctl00_ctl00_Main_Main_wizSignUp_ctl05_ctlAccountSearchCriteria_lbState', true);
		lUp.writeProfile();
	});
	psSetEventHandler ('ctl00_ctl00_Main_Main_wizSignUp_StepNavigationTemplateContainerID_StepNextButton', 'click', function ()
	{
		var lUp = new psProfile();
		if (lUp.readProfile ())
		{
			lUp._cusId = psGetElementValueById('ctl00_ctl00_Main_Main_wizSignUp_ctlAccountDetails_txtEmail', false);
			lUp._email = lUp._cusId;
			lUp._city = psGetElementValueById('ctl00_ctl00_Main_Main_wizSignUp_ctlAccountDetails_txtCity', false);
			lUp._state = psGetElementValueById('ctl00_ctl00_Main_Main_wizSignUp_ctlAccountDetails_ddlState', true);
			lUp._zipcode = psGetElementValueById('ctl00_ctl00_Main_Main_wizSignUp_ctlAccountDetails_txtZip', false);
			lUp.writeProfile();
		}		
	});
	psCreatePageviewTag(lPageID, lCatID, null, null);
	psSetCookie(G_PS_COOKIE_CATID, lCatID);
}
/*================ End Of Posting Logic Functions ================/
/*====================== END TAGGING BUSSINESS LOGIC =========================*/
/*======================= GENERAL UTILITY FUNCTION ===========================*/
/* 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;
	
	this._cusId = null;
	this._email = null;
	this._city = null;
	this._state = null;
	this._zipcode = null;
	this._newsletter = null;
	this._subscribe = null;
	
	this.saveTemp = function()
	{
		try 
		{
			if (!this.readProfile()) 
			{
				return false;
			}
			else 
			{
				this.cusId = this._cusId;
				this.email = this._email;
				this.city = this._city;
				this.state = this._state;
				this.zipcode = this._zipcode;
				this.newsletter = this._newsletter;
				this.subscribe = this._subscribe;
				if (this.writeProfile()) 
				{
					return true;
				}
				else 
				{
					return false;
				}
			}
		} 
		catch (aExcep) 
		{
			return false;
		}
	}
	
	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];
					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];
				
				this._cusId = buf[7];
				this._email = buf[8];
				this._city = buf[9];
				this._state = buf[10];
				this._zipcode = buf[11];
				this._newsletter = buf[12];
				this._subscribe = buf[13];
			}
			return true;
		} 
		catch (ex) 
		{
			return false;
		}
	};
	
	this.writeProfile = function()
	{
		try 
		{
			if (this.cusId === null && this._cusId === null) 
			{
				return false;
			}
			var data = this.cusId + '|' +
			this.email +
			'|' +
			this.city +
			'|' +
			this.state +
			'|' +
			this.zipcode +
			'|' +
			this.newsletter +
			'|' +
			this.subscribe +
			'|' +
			this._cusId +
			'|' +
			this._email +
			'|' +
			this._city +
			'|' +
			this._state +
			'|' +
			this._zipcode +
			'|' +
			this._newsletter +
			'|' +
			this._subscribe;
			psSetCookie(G_PS_COOKIE_PROFILE, data);
			return true;
		} 
		catch (ex) 
		{
			return false;
		}
	};
}
/* PURPOSE: Compare case-insensitive strings
 * RETURN: true: strings are not null and the same
 *         false: any of the string is null or not the same
 */
function psIsEqual()
{
	for (var i = 0; i < arguments.length; i++) 
	{
		if (arguments[0] === null || arguments[i] === null) 
		{
			return false;
		}
		else if (arguments[0].toUpperCase() != arguments[i].toUpperCase()) 
		{
			return false;
		}
	}
	return true;
}

/* PURPOSE: Get inner text of an object or remove html tags of a particular string
 *          work properly even when the designated tag/text has script tag inside
 * RETURN: resultant string or null object
 */
function psGetInnerText(pTagOjb)
{
	var pattern = /<script[\s\S]*?<\/script>/gi; // question mark means non-greedy
	if (pTagOjb !== null) 
	{
		var sT = (typeof(pTagOjb) == "object") ? pTagOjb.innerHTML : pTagOjb;
		// remove all script tags and its content
		while (sT.search(pattern) > -1) 
		{
			sT = sT.replace(pattern, "");
		}
		return sT.replace(/\<+.+?\>+/g, "");
	}
	return null;
}

/* PURPOSE: Remove all unaccepted characters in categoryid, including
 * [, ', ", :, comma,]
 * RETURN: string
 */
function psCleanCatId(pCatId)
{
	return (pCatId !== null) ? pCatId.replace(/[\'\":,\™\®]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId !== null) ? pPageId.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null;
}

function psCleanProductName(pProductName)
{
	return (pProductName !== null) ? pProductName.replace(/[\n\t\v\r’\'\"\™\®]/gi, "") : null;
}

/* PURPOSE: Remove all leading & trailing spaces of a string
 * Note: [&nbsp;] is also considered as a space
 * RETURN: string
 */
function psTrim(pStr)
{
	if (pStr === null || typeof(pStr) != "string") 
	{
		return pStr;
	}
	return (pStr !== null) ? pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '') : null;
}

/* PURPOSE: extract value from the URL
 * in format of http://xxx.com/page.ext?key1=value1&key2=value2
 * or key1=value1&key2=value2
 * RETURN: string value of the parameter
 */
function psGetValueFromUrl(pUrl, pKey)
{
	pUrl = (pUrl !== null) ? "?" + psTrim(pUrl.toLowerCase()) : null;
	pKey = (pKey !== null) ? psTrim(pKey.toLowerCase()) : null;
	
	if (pUrl === null || pKey === null || pUrl.indexOf(pKey) == -1) 
	{
		return null;
	}
	
	var start = pUrl.indexOf('&' + pKey + '=');
	start = (start == -1) ? pUrl.indexOf('?' + pKey + '=') : start;
	if (start >= 0) 
	{
		start = start + pKey.length;
		var end = pUrl.indexOf("&", start);
		if (end == -1) 
		{
			end = pUrl.length;
		}
		var middle = pUrl.indexOf("=", start);
		return pUrl.substring(middle + 1, end);
	}
	return null;
}

/* PURPOSE: returns the value of an element based on element_id
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN:
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 */
function psGetElementValueById(pTagId, pValueFlag)
{
	var tag = document.getElementById(pTagId);
	return psGetElementValue(tag, pValueFlag);
}

/* PURPOSE: returns the value of an element based on element object
 * Note: this function returns decoded text
 * to avoid "double" decode, don't invoke psHtmlDecode on returned value again
 * @pValueFlag: TRUE means VALUE  attribute of SELECT object returned, not innerHTML
 * RETURN:
 *  Normal tag: decoded innerHTML
 *  INPUT tag: value attribute
 *  SELECT tag: decoded label of the selected option
 *  NULL: if element not exist
 */
function psGetElementValue(pTagObj, pValueFlag)
{
	var tagValue = null;
	if (pTagObj !== null) 
	{
		if (pTagObj.tagName.search(/^INPUT$/i) > -1) 
		{
			tagValue = pTagObj.value;
		}
		else if (pTagObj.tagName.search(/^SELECT$/i) > -1) 
		{
			if (pValueFlag === true) 
			{
				tagValue = pTagObj.options[pTagObj.selectedIndex].value;
			}
			else 
			{
				tagValue = psHtmlDecode(pTagObj.options[pTagObj.selectedIndex].innerHTML);// return label instead of value
			}
		}
		else 
		{
			tagValue = psHtmlDecode(pTagObj.innerHTML);
		}
	}
	
	return tagValue;
}

/* PURPOSE: validate email format
 * RETURN: boolean
 */
function psCheckEmail(pEmail)
{
	if (pEmail) 
	{
		var i = pEmail.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
		return (i > -1);
	}
	
	return false;
}

/* PURPOSE: convert special HTML characters to normal character
 * Note: for each project, this function needs to be updated
 * RETURN: decoded string
 */
function psHtmlDecode(pValue)
{
	if (pValue) 
	{
		pValue = pValue.replace(/&nbsp;/gi, " ");
		pValue = pValue.replace(/&quot;/gi, '"');
		pValue = pValue.replace(/&amp;/gi, "&");
		pValue = pValue.replace(/&lt;/gi, "<");
		pValue = pValue.replace(/&gt;/gi, ">");
	}
	
	return pValue;
}

/* PURPOSE: extract main domain from the URL
 * RETURN: main domain
 */
function psGetMainDomain(pUrl)
{
	var se = /^https*\:\/\/([^\/\:]+)/gi;
	var domain = (pUrl.search(se) > -1) ? RegExp.$1 : null;
	if (domain !== null) 
	{
		if (domain.indexOf("www") === 0) 
		{
			domain = domain.substring(4, domain.length);
		}
		if (G_PS_ARR_DOMAIN !== null) 
		{
			for (var i = 0; i < G_PS_ARR_DOMAIN.length; i++) 
			{
				se = new RegExp("[\.]" + G_PS_ARR_DOMAIN[i] + "$", "gi");
				if (("." + domain).search(se) > -1) 
				{
					domain = G_PS_ARR_DOMAIN[i];
					break;
				}
			}
		}
		domain = "." + domain;
	}
	return domain;
	
}

/* PURPOSE: extract domain part in the URL
 * RETURN: domain
 */
function psGetDomain(pUrl)
{
	var se = /^https*\:\/\/([^\/\:]+)/gi;
	return (pUrl.search(se) > -1) ? RegExp.$1 : null;
}

/* PURPOSE: remove unnecessary characters (dollar sign, comma, quote, minus, etc) 
 * from price to make it work properly with parseFloat/parseInt
 * RETURN: well-formed price
 */
function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
	return (pPrice !== null ? pPrice.toString().replace(pattern, "") : null);
}

/* PURPOSE: retrieve cookie value
 * RETURN: string
 */
function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if (!pCookieName || !cookies) 
	{
		return null;
	}
	
	cookies = "; " + cookies.toLowerCase();
	var key = "; " + pCookieName.toLowerCase() + "=";
	var start = cookies.lastIndexOf(key);
	if (start >= 0) 
	{
		start = start + key.length;
		var end = cookies.indexOf(";", start);
		if (end == -1) 
		{
			end = cookies.length;
		}
		
		return unescape(cookies.substring(start, end));
	}
	
	return null;
}

function psCookieBase(pCookieName, pCookieValue, pLifeTime)
{
	var pDomain = psGetMainDomain(G_PS_URL_PATH);
	CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
	if (pLifeTime == "delete") 
	{
		return true;
	}
	
	// set cookie by calling coremetrics's cookie function
	var expire = (pLifeTime) ? (new Date((new Date()).getTime() + (1000 * pLifeTime))).toGMTString() : null;
	
	return CB(pCookieName, escape(pCookieValue), expire, pDomain);
}

function encodeHtml(strValue)
{
	if (strValue !== null) 
	{
		strValue = escape(strValue);
		strValue = strValue.replace(/\//g, "%2F");
		strValue = strValue.replace(/\?/g, "%3F");
		strValue = strValue.replace(/\=/g, "%3D");
		strValue = strValue.replace(/&/g, "%26");
		strValue = strValue.replace(/@/g, "%40");
	}
	return strValue;
}

/* PURPOSE: set cookie value
 * Note: if the designated cookie is too big, the old items will be removed
 * because cookie size is limited to 4K
 * @pLifeTime in seconds
 * pDomain: don't specify if using current domain
 * RETURN: boolean
 */
function psSetCookie(pCookieName, pCookieValue, pLifeTime)
{
	if (!pCookieName) 
	{
		return false;
	}
	
	pCookieValue = (pCookieValue === null) ? "null" : pCookieValue;
	
	if (pLifeTime != "delete") 
	{
		pCookieName = psTrim(pCookieName);
		var oldCookieValue = psGetCookie(pCookieName);
		oldCookieValue = (oldCookieValue === null) ? "null" : oldCookieValue;
		var totalSize;
		if (document.cookie.indexOf(pCookieName) > -1) 
		{
			totalSize = document.cookie.length + encodeHtml(pCookieValue).length - encodeHtml(oldCookieValue).length;
		}
		else 
		{
			totalSize = document.cookie.length + encodeHtml(pCookieValue).length + encodeHtml(pCookieName).length;
		}
		if (totalSize > 3500) 
		{
			return false;
		}
	}
	psCookieBase(pCookieName, pCookieValue, pLifeTime);
}

/* PURPOSE: set value in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 * NOTE: Use null or '' for pValue to remove the pair specified by pKey
 */
function psSetValueToCookie(pCookieName, pKey, pValue)
{
	if (!pCookieName || !pKey) 
	{
		return false;
	}
	
	pCookieName = psTrim(pCookieName);
	pKey = (pKey !== null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	var catCookie = psGetCookie(pCookieName);
	catCookie = (catCookie === null) ? "" : catCookie;
	pValue = (pValue === null) ? "null" : pValue;
	var oldCatCookie = catCookie;
	
	var start = catCookie.indexOf(pKey);
	
	var totalsize;
	if (start >= 0) // Store before -> remove the old value
	{
		var oldValue = psGetValueFromCookie(pCookieName, pKey.replace(/[\~\#]/gi, ""));
		oldValue = (oldValue === null) ? "null" : oldValue;
		var end = catCookie.indexOf("#", start + pKey.length);
		if (end == -1) 
		{
			end = catCookie.length;
		}
		catCookie = catCookie.replace(catCookie.substring(start, end), "");
		totalsize = document.cookie.length + encodeHtml(pKey).length + encodeHtml(pValue).length - encodeHtml(oldValue).length;
	}
	else 
	{
		totalsize = document.cookie.length + encodeHtml(pKey).length + encodeHtml(pValue).length;
		if (document.cookie.indexOf(pCookieName) < 0) 
		{
			totalsize += encodeHtml(pCookieName).length;
		}
	}
	catCookie = pKey + pValue + catCookie;
	var cookieArray = null;
	//Check existed ?
	while (totalsize > 3500) 
	{
		var l1 = encodeHtml(catCookie).length;//length before pop
		cookieArray = catCookie.split("#");
		cookieArray.pop();
		catCookie = cookieArray.join("#");
		var l2 = encodeHtml(catCookie).length;//length after pop                                                        
		totalsize -= (l1 - l2);
	}
	if (catCookie === null || catCookie === "") 
	{
		catCookie = oldCatCookie;
	}
	// Save to cookie              
	psCookieBase(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

/* PURPOSE: get value stored in cookie in format of:
 * #key1~value1#key2~value2
 * RETURN: string
 */
function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey !== null) ? "#" + psTrim(pKey).toLowerCase() + "~" : pKey;
	// extract catId associated with the specified key (pKey)
	var catCookie = psGetCookie(pCookieName);
	if (catCookie !== null) 
	{
		var start = catCookie.indexOf(pKey);
		if (start >= 0) 
		{
			start = start + pKey.length;
			var end = catCookie.indexOf("#", start);
			if (end == -1) 
			{
				end = catCookie.length;
			}
			return catCookie.substring(start, end);
		}
		return null;
	}
	return null;
}

/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dtDate = new Date();
	var cusRandom = (dtDate.getTime() % 10000000) + (Math.floor(Math.random() * 10000));
	return cusRandom;
}

function psShorttenPageID(pLink)
{
	var temp1 = pLink;
	if (temp1 !== null) 
	{
		temp1 = (temp1.length > 255) ? temp1.substr(0, 255) : temp1;
	}
	return temp1;
}

/*================== Vu libs ==================*/
function psCleanHtmlTag(pValue)
{
	return (pValue != null) ? pValue.replace(/\<+.+?\>+/g, "") : null;
}

function DoURLdecode(aURL)
{
	var lReturn = aURL;
	if (lReturn) 
	{
		lReturn = lReturn.replace(/\%7e/gi, "~");
		lReturn = lReturn.replace(/\%20/gi, " ");
		lReturn = lReturn.replace(/\+/gi, " ");
	}
	return lReturn;
}

function elsByCname(pSearchClass, pNode, pTag)
{
	var classElements = [];
	var lNode = (pNode === null || pNode === undefined || pNode === '') ? document : pNode;
	var lTag = (pTag === null || pTag === undefined || pTag === '') ? '*' : pTag;
	var els = lNode.getElementsByTagName(lTag);
	if (els.length <= 0) 
	{
		return null;
	}
	var pattern = new RegExp('(^|\\\\s)' + pSearchClass + '(\\\\s|$)');
	for (var i = 0; i<els.length; i++)
	{
		if (pattern.test (els[i].className))
		{
			classElements.push (els[i]);
		}
	}
	return (classElements.length <= 0) ? null : classElements;
}

function convertToArray(pInput)
{
	var lReturnValue = [];
	
	if (pInput.length === 0) 
	{
		return lReturnValue;
	}
	else 
	{
		for (var i=0; i<pInput.length; i++)
		{
			lReturnValue.push (pInput[i]);
		}
		return lReturnValue;
	}
}

function elsByTname(pObj, pTagName)
{
	var lTag = (pTagName === null || pTagName === undefined || pTagName === '') ? '*' : pTagName;
	var lNode = (pObj === null || pObj === undefined || pObj === '') ? document : pObj;
	var els = lNode.getElementsByTagName(lTag);
	if (els.length <= 0) 
	{
		return null;
	}
	return convertToArray(els);
}

function psIsExisted(pInput)
{
	return (typeof(pInput) === "undefined" || pInput === null) ? false : true;
}

function psIsElement(o)
{
	if (!psIsExisted(o)) 
	{
		return false;
	}
	return (typeof HTMLElement === "object" ? o instanceof HTMLElement : typeof o === "object" && o.nodeType === 1 && typeof o.nodeName === "string");
}

function psIsArray(pInput)
{
	if (!psIsExisted(pInput) || typeof pInput != 'object') 
	{
		return false;
	}
	else 
	{
		var criterion = pInput.constructor.toString().match(/array/i);
		return (criterion !== null);
	}
}

function psIsString(pStr)
{
	if (pStr === undefined || pStr === null) 
	{
		return false;
	}
	if (typeof pStr == 'string') 
	{
		return true;
	}
	if (typeof pStr == 'object') 
	{
		var lObjConstructor = pStr.constructor;
		if (typeof(lObjConstructor) === "undefined" || lObjConstructor === null) 
		{
			return false;
		}
		
		var criterion = pStr.constructor.toString().match(/string/i);
		return (criterion !== null);
	}
	return false;
}

function psDoBind(pObj, pFunc, pArgs)
{
	return function()
	{
		var lObj = (pObj === true) ? this : pObj;
		return (pFunc === undefined || pFunc === null || typeof pFunc != 'function') ? null : pFunc.apply(lObj, Array.prototype.slice.call(pArgs || []).concat(Array.prototype.slice.call(arguments)));
	};
}

function ele()
{
	var elements = [];
	for (var i = (arguments.length - 1); i >= 0; i--) 
	{
		var element = arguments[i];
		if (typeof element == 'string') 
		{
			element = document.getElementById(element);
		}
		if (arguments.length == 1) 
		{
			return element;
		}
		elements.push(element);
	}
	return elements;
}

function psSetEventHandler(pInput, pEvent, pFunc)
{
	function tuneStr(pStr)
	{
		var output = pStr.toLowerCase();
		return (output.indexOf('on') === 0) ? output.slice(2) : output;
	}
	
	function addEvent(pObj, aEvt, aFn)
	{
		if (document.addEventListener) 
		{
			addEvent = function(pObj, aEvt, aFn)
			{
				pObj.addEventListener(aEvt, aFn, false);
			};
		}
		else if (document.attachEvent) 
		{
			addEvent = function(pObj, aEvt, aFn)
			{
				pObj.attachEvent('on' + aEvt, aFn);
			};
		}
		else 
		{
			addEvent = function(pObj, aEvt, aFn)
			{
				pObj['on' + aEvt] = aFn;
			};
		}
		addEvent(pObj, aEvt, aFn);
	}
	
	// get out of the function if the parameters is not valide, for faster compile
	if (pInput === undefined || pEvent === "" || pInput === null ||
	!psIsString(pEvent) ||
	pEvent === "" ||
	pFunc === undefined ||
	pFunc === null ||
	typeof pFunc != 'function') 
	{
		return false;
	}
	
	var lDomElement = psIsString(pInput) ? document.getElementById(pInput) : pInput;
	
	if (lDomElement === null || lDomElement === undefined || !psIsElement(lDomElement)) 
	{
		return false;
	}
	
	var lEventStr = tuneStr(pEvent);
	
	if (typeof lDomElement['on' + lEventStr] == 'function') 
	{
		lDomElement.oldEventHandler = lDomElement['on' + lEventStr];
		lDomElement['on' + lEventStr] = psDoBind(lDomElement, function()
		{
			pFunc.apply(this);
			return this.oldEventHandler();
		});
		return true;
	}
	else 
	{
		addEvent(lDomElement, lEventStr, psDoBind(lDomElement, pFunc));
		return true;
	}
}

/*================== End of Vu libs ==================*/
/********************************************************/
/* 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 ==================*/