//PDTS $Revision: 94 $

//PDTS v1.8.2
// Fixing a bug where "Paid Search" did not get the search terms.  This is because
// the keywords for the ad was added as _kk={keyword} on the landing page

//PDTS v1.8.1
// We had a problem in IE7.  It didn't support trailing commas in arrays.
// Also changed the logging mechanism from XMLHttpRequest to new Image().src = "logLocation"

//PDTS v1.8.0
// Added instrumentation to the PDTS server to help debug the problems we have been seeing

//PDTS v1.7.1
// Improved parsing of international google domains

//PDTS v1.7.0
// Altered script to accept lst_source from referrer links in addition to umt_source.

//PDTS v1.6.5
//Altered script to use jQuery and recognize form submission fields
//  that match sfMedium, sfRefUrl in the IDs at the end.
//  Conditionaly pull in the dependency jQuery.

//PDTS v1.6.4
//Altered script to fulfill new use case outcomes

//PDTS v1.6.3
//Improved GetDomain and DeleteCookie functions to hopefully fix Ticket #5

//PDTS v1.5
//Removed client specific changes. pdts-server handles mapping to client
//  specific field names and hard coded values.

//PDTS v1.3.1
//Added bing to the list of search sites.
//-- R. Seward 23 July 2009

//PDTS v1.3
//Improved classification of the linkType based on the LandingPage
// Reformated with http://jsbeautifier.org/
//-- R. Seward 3 July 2009

//PDTS v1.25
//Added Campaign and Medium Data
//-- D O'Neil 20 May 2008

//PDTS v1.2
//Major change to SetSubmitValues api; now set up as a hash array that will automatically search for
// and populate fields described in the user-defined values below

//pdts v1.1
// i. Corrected "direct tracking" bug 
//ii. simplified submission data set and separated into a specific function
//-- D O'Neil 16 May 2008

// pdts with google autotagging as well as general tagging capabilities.  
// installation of this script is a 3 step process:
// 1. 	Upload this script to the website and call it from EVERY page on the website.  
//		Sample installation code:  <script src="/scripts/PDTS.js"></script>

// 2.	In Salesforce, determine the form values mapping as assigned by the system.
//		Record those default mappings in the variables below:


// RDS: These values are mapped in the pdts-server YAML file now. Each client
//  form needs to store these form values with standard field names:
//     RefUrl, RefDomain, SearchTerms, LandingPage, LinkType, MonthYear, 
//     Campaign, Medium
//  pdts-server handles mapping the field names to the salesforce specific names

var pdtsSfRefUrl = "sfRefUrl"
var pdtsSfRefDomain = "sfRefDomain"
var pdtsSfSearchTerms = "sfSearchTerms"
var pdtsSfLandingPage = "sfLandingPage"
var pdtsSfLinkType = "sfLinkType"
var pdtsSfMonthYear = "sfMonthYear"
var pdtsSfSource = "sfSource"
var pdtsSfCampaign = "sfCampaign"
var pdtsSfMedium = "sfMedium"
var pdtsPvQos = "pvPdtsQos"    // a field for passing Quality of Service info
var pdtsPvComplete =  0;
var pdtsVersion = "$Revision: 94 $".replace(/\$Revision: ([^ ]*) \$/, "$1");

// 3.	Using the form values generated by Salesforce, add the appropriate hidden form fields to the website's form.  
//		Finally, call the function ParseSearchQuery as an onsubmit javascript action from your form(s).  This will properly
//		populate the hidden variables on your form as well as deleting the cookies. 

// 4.	If you want to track campaigns such as email campaigns, you can use the utm_medium and utm_source parameters
//		in the parameter. utm_medium will track the type of campaign (email, television, radio), and the 
//		utm_source will track the specific campaign (idaho email, for example). this will be put into the 
//		Campaign Channel and Web Campaign fields, respectively.

//5.	For Google, you're ready to go.  For any other paid search effort, a custom tag must be appended to the landing page URL
//		Currently, that tag is "paidSearch"  Both this tag and the native Google tag can be changed here:

var pdtsAdwordsTag = "_kk";
var pdtsAdwordsTag2 = "gclid";
var pdtsGeneralTag = "paidSearch";
var pdtsMailBlastTag = "utm_medium";
var pdtsImageCache = new Array();

//rawDate = Date()
//splitDate = rawDate.split(" ")
//monthYear = splitDate[1] + " " + splitDate[3]

pdtsLogMessage();

pdtsSetRef(document.referrer, document.URL);

function PdtsMap() {
    // members
    this.keyArray = new Array(); // Keys
    this.valArray = new Array(); // Values

    // methods
    this.put = PdtsMapPut;
    this.get = PdtsMapGet;
    this.size = PdtsMapSize;
    this.clear = PdtsMapClear;
    this.keySet = PdtsMapKeySet;
    this.valSet = PdtsMapValSet;
    this.showMe = PdtsMapShowMe; // returns a string with all keys and values in map.
    this.findIt = PdtsMapFindIt;
    this.remove = PdtsMapRemove;
    this.has    = PdtsMapHas;
}

function PdtsMapPut(key, val) {
    var elementIndex = this.findIt(key);

    if (elementIndex == ( - 1)) {
        this.keyArray.push(key);
        this.valArray.push(val);
    }
    else {
        this.valArray[elementIndex] = val;
    }
}

function PdtsMapGet(key) {
    var result = null;
    var elementIndex = this.findIt(key);

    if (elementIndex != ( - 1)) {
        result = this.valArray[elementIndex];
    }
    return result;
}

function PdtsMapRemove(key) {
    var result = null;
    var elementIndex = this.findIt(key);

    if (elementIndex != ( - 1)) {
        this.keyArray = this.keyArray.removeAt(elementIndex);
        this.valArray = this.valArray.removeAt(elementIndex);
    }
    return;
}

function PdtsMapSize() {
    return (this.keyArray.length);
}

function PdtsMapClear() {
    for (var i = 0; i < this.keyArray.length; i++) {
        this.keyArray.pop();
        this.valArray.pop();
    }
}

function PdtsMapKeySet() {
    return (this.keyArray);
}

function PdtsMapValSet() {
    return (this.valArray);
}

function PdtsMapShowMe() {
    var result = "";

    for (var i = 0; i < this.keyArray.length; i++) {
        result += "Key: " + this.keyArray[i] + "\tValues: " + this.valArray[i] + "\n";
    }
    return result;
}

function PdtsMapFindIt(key) {
    var result = ( - 1);

    for (var i = 0; i < this.keyArray.length; i++) {
        if (this.keyArray[i] == key) {
            result = i;
            break;
        }
    }
    return result;
}

function PdtsMapRemoveAt(index) {
    var part1 = this.slice(0, index);
    var part2 = this.slice(index + 1);

    return (part1.concat(part2));
}
Array.prototype.removeAt = PdtsMapRemoveAt;

function PdtsMapHas(key) {
	return this.find(key) > -1;
}

function pdtsDocumentCookieGet() {
    return document.cookie;
}

function pdtsDocumentCookieSet(val) {
    document.cookie = val;
}

//from: http://techpatterns.com/downloads/javascript_cookies.php 
function pdtsGetCookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = pdtsDocumentCookieGet().split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');

        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function pdtsDeleteCookie(name, path, domain) {
    // this deletes the cookie when called
    //if (GetCookie(name)) {
		pdtsDocumentCookieSet(
				      name + "=" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT");
    //}
}

function pdtsSetCookie(name, value, expiryInDays, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();

    today.setTime(today.getTime());
    /*
	if the expiryInDays variable is set, make the correct 
	expiryInDays time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/

    if (expiryInDays) {
        expiryInDays = expiryInDays * 1000 * 60 * 60 * 24;
    }

    var expires_date = new Date(today.getTime() + (expiryInDays));
    pdtsDocumentCookieSet(name + "=" + escape(value) + ((expiryInDays) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path: "") + ((domain) ? ";domain=" + domain: "") + ((secure) ? ";secure": ""));
}

// This function attempts to infer how many parts constitute the
//   min number of parts for a domain.
function pdtsInferMinDomLen(host) {
   var minDomLen = 2;  // US domains like .google.com require two domain components
   var h = host.split('.');

   if ( h.length > 0 ) {
     tld = h.slice(h.length-1);

     if ( tld == 'jp' || tld == 'uk' || tld == 'in' || tld == 'tw' || tld == 'gt' ) {
       // these internation domains require 3 parts to the domain name
       minDomLen=3;
     }
   }

   return minDomLen;
}

// Improved GetDomain function that attempts to deal with international domains
function pdtsGetDomain(url) {
    //alert('GetDomain('+url+')');
    if (url) {
        //alert('GetDomain before match');
        var host = url.match( /:\/\/?([^\/:]+)/ );
        var h = '';

        if (host) {
            h = host[1];
        } else {
            // Try to accept raw domain names without http urls
            host = url.match(/(.*\.[^\.]+$)/);
            h = host ? host[1] : '';
        }

        var beforeSplit=h;

        //alert("Before split: "+h);

        var minDomLen = pdtsInferMinDomLen( h );
        var domain = h.split(".");

        var d = '';
        if (domain.length == minDomLen) {
           d = domain.join('.');
        } else if (domain.length > minDomLen) {
           // remove the host name
           //alert('remove the host name');
           d = domain.slice(1).join('.');
        }

        //alert('beforeSplit='+beforeSplit+'\n'+
        //      'afterSplit=.'+d);
        return '.'+d;
    }

    return ''
}


/**
 * Debug function, used to display the cookies while testing
 */
function pdtsShowCookies() {
    var PDTSref = pdtsGetCookie('PDTSref');
    var PDTSlanding = pdtsGetCookie('PDTSlanding');

    if (PDTSref) {} else { PDTSref = "null"; }
        //alert("PDTSref="+PDTSref);
        var debugNode = document.getElementById('PDTSref');
        if (debugNode) {
            debugNode.innerHTML = PDTSref;
        }
    if (PDTSlanding) {} else { PDTSlanding = "null"; }
        //alert("PDTSlanding="+PDTSlanding);
        var debugNode = document.getElementById('PDTSlanding');
        if (debugNode) {
            debugNode.innerHTML = PDTSlanding;
        }
		
}

function pdtsRecentlySubmitted() {
    return pdtsGetCookie("pdtsSubmitting") ? true : false;
}

function pdtsSubmitting() {
    pdtsSetCookie("pdtsSubmitting", "true", 1/24, "/", pdtsGetDomain(document.url));
}


function pdtsSetRef(ref, doc) {
    
    //alert("ref="+ref+", doc="+doc);
    //alert("ref.domain="+pdtsGetDomain(ref)+", doc.domain="+pdtsGetDomain(doc));

    var PDTSref = pdtsGetCookie('PDTSref');
    var PDTSlanding = pdtsGetCookie('PDTSlanding');

    if (pdtsGetDomain(ref) == pdtsGetDomain(doc)) {
	if(PDTSref == null && PDTSlanding == null && !pdtsRecentlySubmitted()) {
	    pdtsSetCookie('PDTSref', ref, 365, "/", pdtsGetDomain(doc));
	    pdtsSetCookie('PDTSlanding', doc, 365, "/", pdtsGetDomain(doc));
	}
    } else {
        //alert("PDTSref="+PDTSref+" "+GetDomain(ref));
        if (PDTSref == null) {
            pdtsSetCookie('PDTSref', ref, 365, "/", pdtsGetDomain(doc));
            //alert("PDTSref="+ref);
        }
        if (PDTSlanding == null) {
            pdtsSetCookie('PDTSlanding', doc, 365, "/", pdtsGetDomain(doc));
            //alert("PDTSlanding="+doc);
        }
    }

}

function pdtsGetQueryParams(urlString, resultHash) {
    var queryString;
    var pairs;
    var stringPairs;
    var keyval;

    //alert("refUrl is: " + urlString);
    if (urlString && urlString.indexOf("?") > -1) {

        //Get everything to the right of the "?"
        queryString = urlString.split("?")[1];

        // split the query string
        pairs = queryString.split("&");
        //alert ("pairlength: "+pairs.length);
        for (var i = 0; i <= (pairs.length - 1); i++) {
            //alert("count="+i+" val:"+pairs[i]);
            keyval = pairs[i].split("=");
            resultHash.put(keyval[0], keyval[1]);
        }
        //alert("pairsplit loop completed");
    }
    return resultHash;
}

function pdtsSetWhenEmpty(theVar, newValue) {
    if (!theVar) {
        theVar = newValue;
    }
    return theVar;
}

function pdtsGetLandParm(hashobj, parm) {
    // look for the landing page parm val in lst_parm first and then
    // utm_parm second. For backwards compatibility.

    var parmVal = hashobj.get("lst_"+parm);
    parmVal = pdtsSetWhenEmpty( parmVal, hashobj.get("utm_"+parm) );

    return parmVal;
}


function pdtsInferVisit(visitData) {
    // 2-part activity
    // Step 1: parse between direct and referrer
    // Step 2: Get Seach terms if result is a search engine
    // additional var/value combinations from the url script
    // that don't require parsing are simply stored in the hashmap

    var refUrl
    var searchTerms
    var landingPage
    var linkType;
    var searchParam;
    var refDomain;
    var resultHash = new PdtsMap();
    var lpQueryParms = new PdtsMap();

    landingPage = visitData.get("landingPage");
    refUrl = visitData.get("refUrl");
    //alert(refUrl)
    lpQueryParms = pdtsGetQueryParams(landingPage, lpQueryParms);

    //alert("landingPage= "+landingPage);	
    //alert("refUrl= "+refUrl);
    //alert("lpQueryParms="+lpQueryParms.showMe());


    // Checking the landing page for obvious reasons for the visitor to be here
    if (landingPage) {
        var source = pdtsGetLandParm( lpQueryParms, "source");
        
        if (landingPage.indexOf(pdtsAdwordsTag) > -1) {
            linkType = pdtsSetWhenEmpty(linkType, "Paid Search");
        
	} else if ( landingPage.indexOf(pdtsAdwordsTag2) > -1) {
            linkType = pdtsSetWhenEmpty(linkType, "Paid Search");
        
	} else if (landingPage.indexOf(pdtsGeneralTag) > -1) {
            linkType = pdtsSetWhenEmpty(linkType, "Paid Search");
	
	} else if (source) {
            if ( source == "ysm" || source == "MSN"  ) 
            {
               linkType = pdtsSetWhenEmpty(linkType, "Medium");
               if ( ! pdtsGetLandParm( lpQueryParms, "campaign") ) {
		             lpQueryParms.put("lst_campaign","Paid Search");
               }
            } else {
              linkType = pdtsSetWhenEmpty(linkType, "Email Blast");
            }
        }
    }

    // Step 1. This check is for direct visits to the site
    // if it's a direct visit then load this list
    if (! (refUrl)) {
        refUrl = null;
        refDomain = "Direct";
        linkType = pdtsSetWhenEmpty(linkType, "Direct");
        searchTerms = null;

        // otherwise it's a referrer, so we
        // 1) Need to parse the cookie data    
        // 2) need to get search engine data if need be
    } else {

        refDomain = pdtsGetDomain(refUrl);
        //alert("refDomain="+refDomain);

        // This check parses referrals from search engines
        // and defines the search as a search engine or a referral
        if (refDomain.indexOf("yahoo") > -1) {
            searchParam = "p";
        } else if (refDomain.indexOf("aol") > -1) {
            searchParam = "query";
        } else if (refDomain.indexOf("netscape") > -1) {
            searchParam = "query";
        } else if (refDomain.indexOf("google") > -1) {
            searchParam = "q";
        } else if (refDomain.indexOf("bing") > -1) {
            searchParam = "q";
        }

        // grab parameters from the referrer page and set search terms
        resultHash = pdtsGetQueryParams(refUrl, resultHash);
        searchTerms = resultHash.get(searchParam);
        // alert("searchParam="+searchParam+" searchTerms="+searchTerms+" refUrl="+refUrl);

	if( !searchTerms) {
	    searchTerms = lpQueryParms.get(pdtsAdwordsTag);
	}

        // grab parameters from the landing page
        resultHash = lpQueryParms;

        //alert("searchParam="+searchParam);
        // This check identifies the referral linkType 
        if (searchParam) {
            // Earlier we should have identified the referral as a Paid Search
            // if linkType is empty then this a Natural Search
            linkType = pdtsSetWhenEmpty(linkType, "Natural Search");
        } else {
            // This request has a referer but wasn't a search
            linkType = pdtsSetWhenEmpty(linkType, "Referral");
        }
    }
    //alert("linkType="+linkType);

    //alert("set hashmap results");
    // Set Result HashMap
    resultHash.put("refUrl", refUrl);
    resultHash.put("refDomain", refDomain);
    resultHash.put("searchTerms", searchTerms);
    resultHash.put("landingPage", landingPage);
    resultHash.put("linkType", linkType);
    resultHash.put("cookiesEnabled", visitData.get("cookiesEnabled"));

    //alert("resultHash: "+resultHash.showMe());
    // Submit Data Results	

    return resultHash;
}

function pdtsCookiesEnabled()
{
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;

	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
	{ 
		pdtsDocumentCookieSet("testcookie");
		cookieEnabled = (pdtsDocumentCookieGet().indexOf("testcookie") != -1) ? true : false;
	}
	return (cookieEnabled);
}

function pdtsParseSearchQuery() {
    pdtsPvComplete = 0;

    //alert("Parsing...");
	var landingPage = pdtsGetCookie('PDTSlanding') || "";
    var refUrl = pdtsGetCookie('PDTSref') || "";

	if(landingPage === "" && refUrl === "") {
		landingPage = document.URL;
		refUrl = document.referrer;
	}

    var visitData = new PdtsMap();
    var cookiesEnabled = "N";
    
    if (pdtsCookiesEnabled()) {
    	cookiesEnabled = "Y";
    }
    //alert("cookiesEnabled="+cookiesEnabled);

    visitData.put("refUrl", refUrl);
    visitData.put("landingPage",landingPage);
    visitData.put("cookiesEnabled", cookiesEnabled);

    var resultHash = pdtsInferVisit(visitData);

    pdtsSetSubmitValues(resultHash);

    //delete cookie so that we can do this fun again!
    pdtsDeletePdtsCookies(pdtsGetDomain(landingPage));
    pdtsPvComplete = 1;
 
    pdtsSubmitting();   
    pdtsLogMessage("ParseSearchQuery");
}

function pdtsCheckCompletion(ret) {
  if (pdtsPvComplete == 1) {
    alert('ParseSearchQuery completed');
  } else {
    alert('ParseSearchQuery failed to complete');
  }

  return ret;
}

function pdtsDeletePdtsCookies(domain) {
    pdtsDeleteCookie('PDTSref', "/", domain);
    pdtsDeleteCookie('PDTSlanding', "/", domain);
}

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function getInputsThatEndWith(text) {

    var result = [];
    var inputs = document.getElementsByTagName("input");

    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].id.endsWith(text)) {
            result.push(inputs[i]);
        }
    }

    return result;
}

function pdtsSetElementValue(id, val)
{
    var inputs = getInputsThatEndWith(id);
    val = val || "";

    for (var i = 0; i < inputs.length; i++) {
	    var input = inputs[i];
	    if(!input.value || input.value === "")
        	inputs[i].value = val;
    }
}

/**
 * This function formats a string. For instance:
 *   "{0} is dead. Long live {1}!".pdtsFormat("Microsoft", "Oracle");
 * We generate the string:
 *   "Microsoft is dead. Long live Oracle!"
 */
String.prototype.pdtsFormat = function() {
	var formatted = this;
	var idx = 0;
	var argc = arguments.length;
	while ( idx < argc ) {
		  formatted = formatted.replace("{"+idx+"}", arguments[idx]);
      idx++;
	}
	return formatted;
};


function pdtsSetSubmitValues(resultHash) {
  pdtsSetElementValue(pdtsSfRefUrl, resultHash.get("refUrl") );
  pdtsSetElementValue(pdtsSfRefDomain, resultHash.get("refDomain"));
  pdtsSetElementValue(pdtsSfSearchTerms, resultHash.get("searchTerms"));
  pdtsSetElementValue(pdtsSfLandingPage, resultHash.get("landingPage"));
  pdtsSetElementValue(pdtsSfLinkType, resultHash.get("linkType"));
  pdtsSetElementValue(pdtsSfMonthYear, resultHash.get("monthYear"));

  var source = pdtsGetLandParm( resultHash, "source");
  var campaign = pdtsGetLandParm( resultHash, "campaign");
  var medium = pdtsGetLandParm( resultHash, "medium");

  pdtsSetElementValue(pdtsSfSource, source);
  pdtsSetElementValue(pdtsSfCampaign, campaign);
  pdtsSetElementValue(pdtsSfMedium, medium);

//alert("Computing qos...");  
  var qos = "ver:{0};cookies:{1};".pdtsFormat(pdtsVersion, resultHash.get("cookiesEnabled")); 

//alert("qos="+qos);  
  pdtsSetElementValue(pdtsPvQos, qos);
  
    //alert("results entered and submitted.");
};

function pdtsCookieStoreTest()
{
	pdtsSetCookie('PDTS_COOKIE_STORE_TEST', "asdf", 365, "/", pdtsGetDomain(document.URL));
	return pdtsGetCookie('PDTS_COOKIE_STORE_TEST') == "asdf";
}


function getImage() { 
    var result = new Image();
    pdtsImageCache.push(result);
    return result;
};

function getXmlHttp() {
	var xmlHttp = null;
	if (typeof XMLHttpRequest == "object" || typeof XMLHttpRequest == "function") {
		xmlHttp = new XMLHttpRequest();
	} 
	return xmlHttp;
}

function sendAsync(request) {
	var xmlRequest = getXmlHttp();
	if(xmlRequest) {
            try {
		 xmlRequest.open("GET", request);
		 xmlRequest.send();
            } catch(err) {
                 getImage().src = request;
            }
	} else {
		 getImage().src = request;
	}
}

function pdtsLogServer() {
	if(document.URL.indexOf("accuricytometers.com") > -1)
	    return "pdts.purevisibility.com";
	return "pdts-test.purevisibility.com";
}

function pdtsLogHash(message){
  var querystring="";
  for(var key in message)
  {
    querystring+= escape(key) + "=" + escape(message[key]) + "&";
  }
  querystring = querystring.substr(0,querystring.length-1);

  sendAsync("http://" + pdtsLogServer() + "/pdtsLogger?" + querystring);
};

function pdtsLogMessage(message){
  pdtsLogHash({"id":pdtsGetOrCreateId(), 
                "message":message,
                "cookiesEnabled":navigator.cookieEnabled,
				"pdtsCookiesEnabled":pdtsCookiesEnabled(),
				"pdtsCookieStoreTest":pdtsCookieStoreTest(),
				"PDTSref": pdtsGetCookie('PDTSref'),
				"PDTSlanding": pdtsGetCookie('PDTSlanding'),
				"refurl": document.referrer,
				"docurl": document.URL
				});
};

function pdtsGetOrCreateId() {

  var getCookie = function(name) {
    var pairs = pdtsDocumentCookieGet().split(';')
    for(var i=0; i < pairs.length; i++) {
		var pair = pairs[i];
		
		while (pair.charAt(0)==' ') 
		    pair = pair.substring(1,pair.length);
		
		if (pair.indexOf(name+"=") == 0) 
		{
			return pair.substring(name.length + 1,pair.length);
		}
	}
	return null;
  };

  if("globalPdtsId" in window && globalPdtsId != null)
    return globalPdtsId.toString();  

  var cookieID = getCookie("pdtsId");  

  if(!cookieID) {
     cookieID = Math.random();
     
     pdtsDocumentCookieSet("pdtsId=" + cookieID);
  }

  globalPdtsId = cookieID;

  return cookieID.toString();
}


