/************************************************************************************/
/* $Revision: $
 * $Id: $
 *
 * Author: Coremetrics/PSD 
 * Coremetrics 01/29/2009
 * COPYRIGHT 1999-2009 COREMETRICS, INC. 
 * ALL RIGHTS RESERVED. U.S.PATENT PENDING
 * Disclaimer: Coremetrics is not responsible for hosting or maintenance or this file
 *
 */
/************************************************************************************/

cmSetProduction();
var G_PS_URL_PATH = "" + document.location;
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 = 259200; // 3*24*60*60 = 3 days

var G_PS_COOKIE_FLAG = "PS_FLAG"; // used as a "session" variable to handle events between pages
var G_PS_COOKIE_PROFILE = "PS_PROFILE";
var G_PS_CUR_CATID = psGetValueFromCookie(G_PS_COOKIE_FLAG, "catId");
var G_PS_CUR_PAGEID = false;

// Navigation

if ( ( psIsDomainToTag('homeinstead.com') || psIsDomainToTag('mossbp') ) && document.body != null)
{
	if (document.body.innerHTML.search('404 NOT FOUND')>=0)
	{
		// Error tags
		G_PS_CUR_CATID = "HOME"; // Main page
		psCreateErrorTag("404 NOT FOUND", G_PS_CUR_CATID);
	}
	else if (psIsSearchView())
	{
		// Search results page
		G_PS_CUR_CATID = "SEARCH";
		psPostSearchView();
	}
	else if (psIsRegistration())
	{
		// Registration
		psPostRegistration();
	}
	else
	{
		// Content pages
		psPostPageView();
	}

	// Renew catId in cookies
	psSetValueToCookie(G_PS_COOKIE_FLAG, "catId", G_PS_CUR_CATID);
}

function parsePathname_To_CATID(pathname) {
	var pathArray = pathname.split("/");
	var CategoryID = "";
    
	for(i = 0; i < pathArray.length-1; i++){
		if (pathArray[i] != "" && pathArray[i].toLowerCase() != "pages" ) {
			CategoryID += pathArray[i].replace(".aspx","") + ":";
		} 
	}
	
	// If the URL Is Rewritten, we need to add the Franchise number to the beginning of the Category ID
	var actualDomainName = "w"+"w"+"w"+".homeinstead.com";  // Need to employ clever tricks to stop the replacement of this string
	if (document.location.hostname.toLowerCase() != actualDomainName && jsFranchiseNumber != "")
	    CategoryID = jsFranchiseNumber + ":" + CategoryID;

	if (CategoryID != "") return CategoryID.slice(0, -1);
	else return "HOME";
}

function parsePathname_To_PAGEID(pathname) {
	var pathArray = pathname.split("/");
	return pathArray[pathArray.length-1].replace(".aspx","");
}

function parsePathname_to_FranNum(pathname) {
	var pathArray = pathname.split("/");
    
    if (testFloat(jsFranchiseNumber)) return jsFranchiseNumber;
    else if (testFloat(pathArray[1])) return pathArray[1];
    else  return 0;  

}

function testFloat(str) {
	str = alltrim(str);
	return /^[-+]?[0-9]+(\.[0-9]+)?$/.test(str);
}	

function alltrim(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

function psIsDomainToTag(psDomain)
{
	var domain = document.location.hostname.replace("www.", "").toLowerCase();
	domain = domain.replace("daytonoh.", "").toLowerCase();
	cm_JSFPCookieDomain = domain;
	return (psDomain == domain);
}

// 404 error page

function psCreateErrorTag(pPageID, pCatId) 
{
	pPageID = psCleanPageId(pPageID);
	pCatId = psCleanCatId(pCatId);
	cmCreateErrorTag(pPageID, pCatId);
}


// Search results

function psIsSearchView()
{
	return (G_PS_URL_PATH.search(/aspx\?q=/gi)>=0);
}

function psGetSearchResults()
{
	if ((document.body != null) && (document.body.innerHTML.search('No results found')>0))
		return "0";
	else
		return "1";
}

function psPostSearchView()
{
	// Your logic of throwing pageview tag for search functionalities goes here
	G_PS_CUR_CATID = "SEARCH";
	var pageId = null;
	var sTerm = psGetValueFromUrl(G_PS_QUERYSTRING, "q");
	var sResult = psGetSearchResults();
	
	if (document.body != null && document.body.innerHTML.search('No results found')>0)
		pageId = "SEARCH UNSUCCESSFUL";
	else
		pageId = "SEARCH SUCCESSFUL";

	// Throw pageview tag
	if (pageId != null)
		psCreatePageviewTag(pageId, G_PS_CUR_CATID, sTerm, sResult, "");
}


// Registration

function psIsRegistration()
{
	var result = false;
	if (G_PS_PATHNAME.search(/becomeacaregiver\/employmentinquiry\/Pages\/EmploymentInquiry.aspx/gi)>=0) result = true;
	if (G_PS_PATHNAME.search(/serviceinquiry\/Pages\/RequestSeniorCareServices.aspx/gi)>=0) result = true;

	if (result) G_PS_CUR_CATID = "REGISTRATION";

	return result;	
}

function psPostRegistration()
{
	psGetUrlDetails();
	psCreatePageviewTag(G_PS_CUR_PAGEID, G_PS_CUR_CATID);
	if (document.Form1 != null)
	{
		onsubmitGuestRegisterFormPtr = document.Form1.onsubmit; // Back up original pointer
		document.Form1.onsubmit = function()
		{
			// Capture new user profile to persist to cookie
			var uP = new psProfile();

			// Get tag info
			if (G_PS_PATHNAME.search(/becomeacaregiver\/employmentinquiry\/Pages\/EmploymentInquiry.aspx/gi)>=0) uP.becomeacaregiver();
			else if (G_PS_PATHNAME.search(/serviceinquiry\/Pages\/RequestSeniorCareServices.aspx/gi)>=0) uP.serviceinquiry();

			// Post registration tag
			uP.postTag();

			// Invoke original function
			if (onsubmitGuestRegisterFormPtr != null)
				return onsubmitGuestRegisterFormPtr();
		}
	}
	else if (document.Form2 != null)
	{
		onsubmitGuestRegisterFormPtr = document.Form2.onsubmit; // Back up original pointer
		document.Form2.onsubmit = function()
		{
			// Capture new user profile to persist to cookie
			var uP = new psProfile();

			// Get tag info
			if (G_PS_PATHNAME.search(/becomeacaregiver\/employmentinquiry\/Pages\/EmploymentInquiry.aspx/gi)>=0) uP.becomeacaregiver();
			else if (G_PS_PATHNAME.search(/serviceinquiry\/Pages\/RequestSeniorCareServices.aspx/gi)>=0) uP.serviceinquiry();

			// Post registration tag
			uP.postTag();

			// Invoke original function
			if (onsubmitGuestRegisterFormPtr != null)
				return onsubmitGuestRegisterFormPtr();
		}
	}
}

// Pageview

function psPostPageView()
{
	psGetUrlDetails();
	psCreatePageviewTag(G_PS_CUR_PAGEID, G_PS_CUR_CATID);
}

function psGetUrlDetails() 
{
	G_PS_CUR_PAGEID = null; G_PS_CUR_CATID = null; franchize = null;

	if (G_PS_PATHNAME != null) 
	{
	    G_PS_CUR_CATID = parsePathname_To_CATID(G_PS_PATHNAME);
	    G_PS_CUR_PAGEID = parsePathname_To_PAGEID(G_PS_PATHNAME);
	    franchize = parsePathname_to_FranNum(G_PS_PATHNAME);
	}
	
	return true;
}

/* PURPOSE: constructor for profile
 * Note: you can add more methods to psProfile in its prototype
 * RETURN: none
 */
function psProfile()
{
    this.id = null;
    this.email = null;
    this.city = null;
    this.state = null;
    this.zip = null;
    this.country = null;
    this.franchise = null;

	/*
	 * Reset all fields to null by default
	 */
	this.reset = function()
	{
		this.id = null;
		this.email = null;
		this.city = null;
		this.state = null;
		this.zip = null;
		this.country = null;
		this.franchise = null;
	}

	/*
	 * Get user profile from cookie
	 */
	this.readProfile = function()
	{
		try
		{
			this.reset();
			this.id = psGetCookie(G_PS_COOKIE_PROFILE);
			if (this.id != null)
			{
				var buf = this.id.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" || tempVal=="NULL")? null : tempVal); 
				}
				this.id = buf[0];
				this.email = buf[1];
				this.city = buf[2];
				this.state = buf[3];
				this.zip = buf[4];
				this.country = buf[5];
				this.franchise = buf[6];
			}
			// make sure that customerId never gets null
			if (!this.id)
				this.id = psGenerateRandomValue(); // Placeholder -- will be replaced later

			return true;
		}
		catch (ex) { return false; }
	}
	
	/*
	 * Extract
	 * http://www.homeinstead.com/994/becomeacaregiver/employmentinquiry/Pages/EmploymentInquiry.aspx
	 */
	this.becomeacaregiver = function()
	{
		try
		{
			this.reset();

			this.email = this.getField(document.Form1.ctl00_PlaceHolderMain_ctl02_email);
			this.id = this.email;
			this.city = this.getField(document.Form1.ctl00_PlaceHolderMain_ctl02_mailInfoAddrCity);
			this.state = this.getSelect(document.Form1.ctl00_PlaceHolderMain_ctl02_mailInfoAddrState);
			this.zip = this.getField(document.Form1.ctl00_PlaceHolderMain_ctl02_mailInfoAddrZip);
			this.country = "USA";
			this.franchise = this.getFranchize();

			G_PS_CUR_PAGEID = "Become Caregiver";

			//
			// Persist profile to cookie
			this.writeProfile();

			return true;
		}
		catch (ex) {return false;}
	}

	/*
	 * Extract
	 * http://www.homeinstead.com/994/serviceinquiry/Pages/RequestSeniorCareServices.aspx
	 */
	this.serviceinquiry = function()
	{
		try
		{
			this.reset();

			this.email = this.getField(document.Form1.ctl00_PlaceHolderMain_ctl01_contactEmail);
			this.id = this.email;
			this.city = this.getField(document.Form1.ctl00_PlaceHolderMain_ctl01_mailInfoAddrCity);
			this.state = this.getSelect(document.Form1.ctl00_PlaceHolderMain_ctl01_mailInfoAddrState);
			this.zip = this.getField(document.Form1.ctl00_PlaceHolderMain_ctl01_mailInfoAddrZip);
			this.country = "USA";
			this.franchise = this.getFranchize();
			
			G_PS_CUR_PAGEID = "Service Inquiry";

			//
			// Persist profile to cookie
			this.writeProfile();

			return true;
		}
		catch (ex) {return false;}
	}

	this.getFranchize = function()
	{
		var pul = G_PS_PATHNAME.split("/");
		if (pul[1] != "frandev") pul = parseInt(pul[1]);
		else pul = pul[1];
		if(isNaN(pul) && pul != "frandev")
			return null;
		else
			return pul;		
	}

	this.getField = function(field)
	{
		result = null;
		if (field != null && field != "" && field.value != null)
		{
			result = psTrim(field.value);
		}
		
		return result;
	}

	this.getSelect = function(field)
	{
		result = null;
		if (field != null && field != "")
		{
			return psTrim(field.options[field.selectedIndex].text);
		}
	}

	/*
	 * Set user profile to cookie
	 */
	this.writeProfile = function()
	{
		if (this.id == null)
			return;

		var data = this.id + '|' + this.email + '|' + this.city + '|' + this.state + '|' + this.zip +	'|' + this.country + '|' + this.franchise;
		// store on cookie
		psSetCookie(G_PS_COOKIE_PROFILE, data);
	}
	
	this.postTag = function()
	{
		this.readProfile();

		cmCreateRegistrationTag(this.id, this.email, this.city, this.state, this.zip, null, null, this.country, this.franchise);
	}
}

// Info utils

function psGetCookie(pCookieName)
{
	var cookies = document.cookie;
	if (!pCookieName || !cookies)
		return null;

	cookies = "; " + cookies.toUpperCase();
	var key = "; " + pCookieName.toUpperCase() + "=";
	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 psSetCookie(pCookieName, pCookieValue, pLifeTime, pDomain)
{
    if (!pCookieName)
		return false;

	if(pLifeTime == "delete") 
    {         
        CC(pCookieName, pDomain);//delete cookie by calling coremetrics's cookie function
        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 psSetValueToCookie(pCookieName, pKey, pValue)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = (pKey != null ? psTrim(pKey).toUpperCase() : pKey);
	// 
	var catCookie = psGetCookie(pCookieName);
	if (catCookie == null)
		catCookie = '';

	if (catCookie.indexOf(pKey) >=0) // Store before -> remove the old value
	{
        var reg = new RegExp("#" + pKey + "~([^#]*)", "gi");
        catCookie = catCookie.replace(reg, "");
	}
	// remove the last items (eldest items) until cookie size < 3500	
	if (pValue != null && pValue != '')
	{
		catCookie = "#" + pKey + "~" + pValue + catCookie;
		var cookieArray = null;
		while (catCookie.length > 3500)
		{
			cookieArray = catCookie.split("#");
			cookieArray.pop();
			catCookie = cookieArray.join("#");
		}
	}
	// Save to cookie
	psSetCookie(pCookieName, catCookie, G_PS_COOKIE_LIFETIME);
}

function psGetValueFromCookie(pCookieName, pKey)
{
	// "normalize" input parameters
	pCookieName = psTrim(pCookieName);
	pKey = psTrim(pKey);
	// extract catId associated with the specified key (pKey)
    var catCookie = psGetCookie(pCookieName);
    if (catCookie != null)
    {
        var re = new RegExp("#" + pKey + "~([^#$]+)", "i");
		if (catCookie.search(re) == -1)
			return null;

        return RegExp.$1;
    }
    return null;
}

function psGetValueFromUrl(pUrl, pKey)
{
    var re = new RegExp("[?&amp;&]" + pKey + "=([^&$]*)", "i");
    if (pUrl.search(re) == -1)
		return null;
    return unescape(RegExp.$1);
}

function psGetInnerText(node, ignorewhitespace)
{
	if (node == null)
		return "";

	var text = "";
	if (typeof(node) == "object")
	{
		if (node.hasChildNodes())
		{
			var children = node.childNodes;
			for(var i=0; i<children.length; i++)
			{
				if(children[i].nodeName == "#text")
				{
					if(ignorewhitespace)
					{
						if(!/^\s+$/.test(children[i].nodeValue))
							text = text.concat(children[i].nodeValue);
					}
					else
						text = text.concat(children[i].nodeValue);
				}
				else if(children[i].nodeName.search(/BR/i)>=0)
					text = text.concat(" "); // a break line for a <br> tag
				else
					text = text.concat(psGetInnerText(children[i])); // recursively get text
			}
		}
		else
		{
			if(node.nodeName == "#text")
				text = text.concat(node.nodeValue);
			else if(node.nodeName.search(/BR/i)>=0)
				text = text.concat("\n"); // a break line for a <br> tag
		}
	}
	else
		text =  node.replace(/\<+.+?\>+/g, "");

	return text;
}

function psGetFirstElementByClassName(pClassName, node)
{
	if (node == null)
		node = document;
	var allPageTags = node.getElementsByTagName("*");	
	for (var k = 0; k < allPageTags.length; k++)
	{
		if (allPageTags[k].className.toLowerCase() == pClassName.toLowerCase())
			return  allPageTags[k];
	}
	return null;
}

// Cleaning info

function psTrim(pStr)
{
	if (pStr == null || typeof(pStr) == "undefined")
		return pStr;

	return pStr.replace(/&nbsp;|\u00A0/gi, ' ').replace(/^\s+|\s+$/g, '');
}

function psHtmlDecode(pValue)
{
    if (pValue)
    {
        pValue = pValue.replace(/&nbsp;/gi, " ");
        pValue = pValue.replace(/&quot;/gi, '"');
        pValue = pValue.replace(/&amp;/gi, "&");
        pValue = pValue.replace(/&lt;/gi, "<");
        pValue = pValue.replace(/&gt;/gi, ">");
    }

    return pValue;
}

function psCleanPrice(pPrice)
{
	var pattern = /[^0-9\.]/gi;
    return (pPrice != null ? pPrice.toString().replace(pattern, "") : null);
}

function psCleanCatId(pCatId)
{
    return (pCatId != null) ? pCatId.replace(/[\'\",]/g, "") : null;
}

function psCleanPageId(pPageId)
{
	return (pPageId != null) ? pPageId.replace(/[\n\t\v\r?\'\"]/gi, "") : null; 
}

function psCleanProductName(pProductName)
{
	return (pProductName != null) ? pProductName.replace(/[\n\t\v\r?\'\"]/gi, "") : null; 
}

function psStrReplace ( search, replace, subject ) 
{
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
 
    return subject;
}


// Tagging functions

function psCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult, pAttributes)
{
	pId = psCleanPageId(pId);
	pCatId = psCleanCatId(pCatId);
    if (pSrchResult != null)
        pSrchResult += "";
        cmCreatePageviewTag(pId, pCatId, pSrchTerm, pSrchResult, pAttributes);
}

/*
 * Generate a random number
 */
function psGenerateRandomValue()
{
	var dt = new Date();
	return (dt.getTime()%10000000) + (Math.floor(Math.random()*10000));
}
