// rwtag.js
// Version 0.9.6 2006-03-01

// Javascipt file for redware tag server.
// Copyright redware research ltd 2005 - www.redware.com (apart from cookie functions).
// Tag called normally with rwTag() with no parameters.
// Use rwAddTag('document.pdf') to generate an additional tag on an onlclick for example.
// Declare variable rwTagPrefix to set a prefix into the tag url.
// 2005-01-07 0.3 Stamati Crook www.redware.com
// 2005-08-29 0.4 Implement rwSetup function and cookie functionality.
// 2005-09-01 0.5 Implement prefix/suffix with global variable rwTagPrefix.
// 2005-09-12 0.6 Implement rwAddTag.
// 2005-09-12 0.7 Take out if (variable) and replace with if (typeof(variable)=="string").
// 2005-09-26 0.8 Rewrite rwAddTag to have prefix parameter. Add debug flag.
// 2005-11-30 0.9 Split into two sections and bugfix for MSIE 6.0. Also tidy code.
// 0.9.2 Add cookiedomain and put back into one file.
// 0.9.3 2006-02-27 Add URL.
// 0.9.4 2006-02-28 Make sure that the path defaults to /.
// 0.9.5 2006-03-01 General tidy up and reduce code bloat and get rid of cookie function.
// 0.9.6 2006-03-01 Add rw.sq sequence session cookie and tag.
// rename rwcreatecookie to rwCookieCreate.
// use location.href instead of window.document.url

// rwAddTag - Creates an additonal tag for extra downloads, events etc.
// Pass in page name as parameter: rwAddTag('document.pdf').
// Change rwAddTitle to use rw.ul and have title parameter.

// Declare (global) setup object.
var rwSetup = new rwSetup();

// Global image required becuse image object is asynchronous when setting the source.
var rwImage = new Image;

// Routine to pick up exisiting PPC parameters. Adapt and uncomment code as necessary.
// Regular expression matches http://www.mysite.com/landingpage/?source=PPCENGINENAME&keyword=SEARCHTERM
//var rwTagPrefix
//rwGrep = new RegExp("source=([^&]+)\&keyword=([^&]+)");
//if (rwGrep.test(location.href)) {
//	matches = location.href.match(rwGrep);
//	rwTagPrefix="rw.cm="+matches[1]+",PPC,"+matches[2];
//}


// rwSetup - setup variables change for each implementation.
function rwSetup() {

	this.rwVersion = "0.9.6";
	this.rwProfile = "redware";
	
	// Do not put in http:// protocol for the tag gif.
	// GIF is required in root of website.
	this.rwTagServerGIF = "/rwtag.gif";
	this.rwCheckMetaTags = true;
	this.rwSendTitle = true;
	this.rwSendURL = true;
	this.rwSequence = false;	// 0.9.6
	
	// CookieName refers to a first party cookie and should be a persistent not session cookie.
	this.rwCookieName = "rwtag";	

	// CookieCreate will determine if a first party cookie is created if absent.	
	this.rwCookieCreate = true;
		
	this.rwCookieDays = 3650;
	// If using first party cookies across subdomains, set this.rwCookieDomain = ".domain.com";
	this.rwCookieDomain = ".redware.com";
	this.rwCookieEnabledCheck = true;
	
	this.rwDebug = false;
}


// rwAddTag() - Creates an additonal tag for extra downloads, events etc. e.g. rwAddTag('document.pdf','rw.oc=download').
// 1. rwPage - Page name relative to the current folder e.g. "document.pdf"
// 2. rwPrefix - is optional prefix strig to specify additional tag. e.g. "rw.oc=sale,electrical,dvd,39.99".
// Returns the URL requested from tagserver.
// Set protocol and tagserver gif. Add prefix and parameters. Add url with current path. Add title if required.
function rwAddTag( rwPage, rwPrefix, rwPageTitle ) {
	if (typeof rwPage =="string" && rwPage.length>0){
		var rwString = "http"+(window.location.protocol.indexOf('https:')==0?'s':'') + "://" + rwSetup.rwTagServerGIF;
		rwString = rwString + "?" + (typeof rwPrefix =="string" && rwPrefix.length>0 ? rwPrefix + "&" : "")  + rwParameters();
		rwString = rwString + "&rw.ul=" + escape(location.href.substring(0, location.href.lastIndexOf("/")+1) + rwPage) + "&rw.rf=" + escape(location.href);
		if (typeof rwPageTitle =="string" && rwPageTitle.length>0 && rwSetup.rwSendTitle){
			rwString = rwString + "&rw.ti=" + escape(rwPageTitle);
		}
		// Now call the tag server.
		return rwTagServer(rwString);
	}
	return null;
}


// rwCookieTag - Returns cookie string value as RW.CK tag according to RWCOOKIENAME.
// rwCookieCreate and RWCOOKIEDAYS determine whether a cookie is created if absent.
function rwCookieTag(){
	var rwCookieName = rwSetup.rwCookieName
	var rwCookiePath = "/";
	var rwCookieDomain = rwSetup.rwCookieDomain;
	var rwCookieDays = rwSetup.rwCookieDays;
	var rwCookieString = "";
	
	// System uses third party cookies only.
	if (rwCookieName.length == 0){
		return "";
	}
	
	// Get first party cookie value. 
	// Use least specific if there are multiple cookies as path will be /.
	rwCookieString = rwGetCookieLastValue( rwCookieName );
	if (typeof rwCookieString =="string" && rwCookieString.length>0){
		// Cookie OK so return tag value.
		return "rw.ck=" + rwCookieString; 
	}
	
	if (rwSetup.rwCookieCreate == false){
		// Cookie should be there but is absent and creation not specified.
		return "rw.ck=";
	} else {
	
		// Create new cookie with a random cookie value.
		var rwNowString = new Date().getTime();
		var rwCookieString = "rwtag." + location.href.length + "." + navigator.userAgent.length + "." + rwNowString;
		
		var rwCookieExpiry = null;
		if (rwCookieDays>0) {
			rwCookieExpiry = new Date();
			rwCookieExpiry.setDate(rwCookieExpiry.getDate() + parseInt(rwCookieDays))
			rwCookieExpiry = rwCookieExpiry.toGMTString();
		}
		
		// 0.9.4 Make sure the cookie path defaults to /.
		rwSetCookie( rwCookieName, rwCookieString, rwCookieExpiry, rwCookiePath, rwCookieDomain, null);
		// Check that cookie has been created.
		rwCookieString = "";
		rwCookieString = rwGetCookieLastValue(rwCookieName);
		if (typeof rwCookieString =="string"){
			return "rw.ck=" + rwCookieString + "&rw.ckcreated=" +  rwNowString;
		} else {
			// Cannot create new cookie.
			// Note that cookie disabled status is set in the rwParameters function.
			return "rw.ck=";
		}
	}
	return "";
}
	
// rwMetaTags - return all meta tags with prefix rw. in an ampersand delimited string.
function rwMetaTags(){		
	var rwMT = "";
	var rwMTags;
	if (document.all){
		rwMTags = document.all.tags("meta");
	} else if (document.documentElement){
		rwMTags = document.getElementsByTagName("meta");
	}
	if (typeof rwMTags !="undefined"){
		for (var i=1;i<=rwMTags.length;i++){
			var rwMTag=rwMTags.item(i-1);
			if (rwMTag.name){
				if (rwMTag.name.indexOf('rw.')==0){
					rwMT=rwMT+"&"+rwMTag.name+"="+escape(rwMTag.content);
				}
			}
		}
	}
	return rwMT;
}
	
// rwParameters - return parameters for profile tag, cache busting, first party cookie, cookie disabled flag.
function rwParameters(){
	var rwNow = new Date();
	var rwString = "rw.pf=" + rwSetup.rwProfile + "&rw.nw="+ rwNow.getTime();	
	if (rwSetup.rwCookieName.length>0){
		rwString = rwString + "&" + rwCookieTag();
	}			
	if (rwSetup.rwCookieEnabledCheck == true && rwIsCookieEnabled()==false) {
		rwString = rwString + "&rw.ckstatus=disabled";
	}	
	
	// 0.9.6 Add a sequence.
	if (rwSetup.rwSequence == true ){
		var rwSequence = rwGetCookieLastValue("rwsequence");
		if (typeof rwSequence=="string" && rwSequence.length>0){
			// Add 1 and convert back to a string.
			rwSequence = "" + (parseInt(rwSequence)+1);
			rwTagHTML = rwString + "&rw.sq=" + rwSequence;
			rwSetCookie("rwsequence",rwSequence,null,"/",rwSetup.rwCookieDomain,null);		
		} else {
			rwSequence = "1";
			rwSetCookie("rwsequence",rwSequence,null,"/",rwSetup.rwCookieDomain,null);		
			rwTagHTML = rwString + "&rw.sq=" + rwSequence;
		}
	}

	return rwString;	
}

// rwTag - Called by end user to generate log record on tag server.
function rwTag( rwPrefix ){			
	return rwTagServer( rwURL( rwPrefix ));
}
	
// rwTagServer - Request URL from tag server.
function rwTagServer( rwURLString ){	
	var rwTagHTML = rwURLString;
	
	if (rwTagHTML.length>2048&&navigator.userAgent.indexOf('MSIE')>=0){
		rwTagHTML=rwTagHTML.substring(0,2040)+"&rw.End=1";
	}
	if (document.images){
		// Get image into variable without displaying on form.
		// Make sure image variable is global.
		rwImage.src = rwTagHTML;
	} else {
		// Alternatively write an image request in HTML to the page.
		// Note that IMG string must be split to prevent browser problems.
		rwTagHTML = '<I' + 'MG BORDER=\"0\" NAME=\"rwtag\" WIDTH=\"1\" HEIGHT=\"1\" SRC=\"' + rwTagHTML + ' \" >' ;
		document.write( rwTagHTML );
	}
	// 0.8 Debug.
	if (rwSetup.rwDebug == true) {
		//alert(rwTagHTML);
		document.write("<br/><b>"+rwTagHTML+"<b/>");
	}
	return rwTagHTML;
}	


// rwURL - return the tag URL for HTTP or HTTPS.
function rwURL( rwPrefix ){
	var rwURLString = "";

	// Check for global parameter (comes before prefix).
	if (typeof rwTagPrefix== "string" && rwTagPrefix.length>0) {
		rwURLString = rwTagPrefix;
	}
	// Set prefix if necessary.
	if (typeof rwPrefix == "string" && rwPrefix.length>0){
		rwURLString = (rwURLString.length>0 ? rwURLString + "&" : "") + rwPrefix;
	} 

	// Add profile cookie, cache-busting etcetera parameters.
	rwURLString = "?" + (rwURLString.length>0 ? rwURLString + "&" : "") + rwParameters();

	// Protocol is http or https.
	rwURLString = "http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://" + rwSetup.rwTagServerGIF + rwURLString;		

	// Add URL parameter if specified in setup.
	if (rwSetup.rwSendURL == true){
		rwURLString = rwURLString + "&rw.ul=" + escape(location.href);	
	}
	
	// 0.9.2. Add the referrer.
	rwURLString = rwURLString + "&rw.rf=" + escape(window.document.referrer);
	
	if (rwSetup.rwCheckMetaTags == true){
		// No need for & seperator.
		rwURLString = rwURLString + rwMetaTags();
	}	
	// Optionally send the title as the last element (it may be truncated).
	if (rwSetup.rwSendTitle == true) {
		rwURLString = rwURLString + "&rw.ti=" + escape(document.title);
	}
	return rwURLString;
}
	
	
// rwIsCookieEnabled - returns false if cookies are disabled.
function rwIsCookieEnabled() {
	var rwEnabled = (typeof document.cookie == "string" && document.cookie.length>0 ? true : false);
	if ( rwEnabled == false && typeof document.cookie == "string"){
		document.cookie = "rwCheckCookie=testing";
		if (document.cookie == "rwCheckCookie=testing"){
			rwEnabled = true;
		}
	}
	return rwEnabled;	
}
	

// Return the last (least specific) cookie value.
// Cookie name is case-sensitive.
function rwGetCookieLastValue( rwCookieName ) {
	if (typeof rwCookieName=="string" && rwCookieName.length>0){
		// Add seperators to begginning of cookie string and search string for simplicity.
		var rwString = "; " + rwCookieName + "=";
		var rwCookie = "; " + document.cookie;
		var rwStartPos = rwCookie.lastIndexOf( rwString );
		if (rwStartPos>-1){
			rwStartPos = rwStartPos + rwString.length;
			var rwEndPos = rwCookie.indexOf( ";", rwStartPos );
			rwString = rwCookie.substring( rwStartPos, (rwEndPos<0 ? rwCookie.length : rwEndPos ));
			return unescape(rwString);
		}
	}
	return "";
}

// rwSetCookie utility functions derived from cookies.js From "JavaScript and DHTML Cookbook"
// Published by O'Reilly & Associates Copyright 2003 Danny Goodman
// store cookie value with optional details as needed
function rwSetCookie(name, value, expires, path, domain, secure) {
		document.cookie = name + "=" + escape (value) +
		((expires) ? "; expires=" + expires : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}



