/************************************************************************************/
/*
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/
/*===========================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;

// 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();

/*========================= END GLOBAL VARIABLES =============================*/

cmSetClientID("90273057",true,"stjude.org");

//Production data warehouse flag
cmSetupCookieMigration(true, true, ".stjude.org", null, "GiftCatalog/express-donation.do", null, null); 
cmSetProduction();

/*=========================== TAG PAGE AND PRODUCT PAGES ===============================*/

	if (psIsProductView()) {
		psPostProductView();
	}
	else {
		psPostPageView();
	}

/*=========================== READ PAGE AND PRODUCT NAMES AND CODES ===============================*/

function psPostProductView()
{
	var prd = new psProduct();
	if (prd.getProduct()){
		psCreateProductviewTag(prd.id, prd.name, prd.catId);
	}
}

function psPostPageView(){	
	var pPageId = null;
	var pCatId = null;

	if(document.title!=null) { 
		pCatId = 'CONTENT';
		pPageId = document.title;
	}
	else if(G_PS_PATHNAME.indexOf("/stjude/v/index.jsp")>=0) { 
		var fTags = psGetElementsByClassName(document,"a","title");
		if(psCheckArrayExist(fTags)){ 
			for(var i=0; i<fTags.length; i++){  
					pPageId = "CONTENT: " + psShorttenPageID(psTrim(psHtmlDecode(unescape(psGetInnerText(fTags[i])))));
					break;
			}
		}
		if (pPageId == null) { 
			fTags = psGetElementsByClassName(document,"span","articleTitle");
			if(psCheckArrayExist(fTags)){ 
				for(var i=0; i<fTags.length; i++){ 
					pPageId = "CONTENT: " + psShorttenPageID(psTrim(psHtmlDecode(unescape(psGetInnerText(fTags[i])))));
					break;
				}
			}
		}
		if (pPageId == null) {  
			var altPage = psGetElementValueById("dh_content");
			if (altPage == null) { 
				pPageId = "CONTENT: VGN CODE: " + psShorttenPageID(psGetValueFromUrl(G_PS_QUERYSTRING,"vgnextoid"));
			}
			else {
				pPageId = "CONTENT: " + psShorttenPageID(psTrim(psHtmlDecode(unescape(psGetInnerText(altPage)))));
			}
		}
		pCatId = "CONTENT";
	}
	else {
		pPageId = G_PS_PATHNAME;
		pCatId = pPageId;
	}
	if(pPageId == null || pCatId == null){
		return false;
	}

	pPageId = psTrim(psHtmlDecode(unescape(pPageId)));
	pCatId = psTrim(psHtmlDecode(unescape(pCatId)));
	
	pPageId = pPageId.toUpperCase();
	pCatId = pCatId.toUpperCase();
	
	psCreatePageviewTag(pPageId, pCatId, null, null);	
	
	return true;
}

/*
 * Determine if the page is the product detail page
 */
function psIsProductView()
{   
	if (G_PS_QUERYSTRING.indexOf("pid=")>=0)
		return true;
	else if(G_PS_PATHNAME.indexOf("/giftcatalog/express-donation.do")>=0)
		return true;
	return false;
}

/* 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.reset = function()
	{
		this.id = null;
		this.name = null;
		this.catId = null;
	}
	/*
	 * Extracting product info from source code for posting productview tag
	 */
	this.getProduct = function()
	{
		try
		{
			this.reset(); // DO NOT REMOVE THIS IMPORTANT STATEMENT!
			var fTags = psGetElementsByClassName(document,"div","cart-title");
			if(psCheckArrayExist(fTags)){
				for(var i=0; i<fTags.length; i++){ 
						this.id = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(fTags[i]))))).substring(0,9);
						this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(fTags[i]))))).substring(9,50);
						break;
				}
			}
			if (this.name == "") 	{
				var fTags = psGetElementsByClassName(document,"h1","headline");
				if(psCheckArrayExist(fTags)){
					for(var i=0; i<fTags.length; i++){
						this.id = psGetValueFromUrl(G_PS_QUERYSTRING,"pid");
						this.name = psCleanProductName(psTrim(psHtmlDecode(unescape(psGetInnerText(fTags[i])))));
						break;
					}
				}
				else {  //does not handle every product detail case.
					this.id = "UNKNOWN";
					this.name = "UNKNOWN";
				}
			}
			
			var crumbs = psGetElementValueById("breadcrumbs");
			this.catId = psCleanProductName(psGetInnerText(psGetValueFromUrl(crumbs,"cID")));

			return true;
		}
		catch (ex) { return false; }
	}
}

/*====================== END TAGGING BUSSINESS LOGIC =========================*/


/*======================= GENERAL UTILITY FUNCTION ===========================*/

/* 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: 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 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 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;
}


/*
 * 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 > 50) ? temp1.substr(0, 50) : temp1; //256 max page size
	}
	return temp1;
}

function psCleanNumber(pNumber){
	var pattern = /[^0-9]/gi;
    return (pNumber != null ? pNumber.toString().replace(pattern, "") : 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;
}

/********************************************************/
/* 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);
}

