/**
 * This is the Cookie( ) constructor function.
 *
 * This constructor looks for a cookie with the specified name for the
 * current document. If one exists, it parses its value into a set of
 * name/value pairs and stores those values as properties of the newly created
 * object.
 *
 * To store new data in the cookie, simply set properties of the Cookie
 * object. Avoid properties named "store" and "remove", since these are
 * reserved as method names.
 *
 * To save cookie data in the web browser's local store, call store( ).
 * To remove cookie data from the browser's store, call remove( ).
 *
 * The static method Cookie.enabled( ) returns true if cookies are
 * enabled and returns false otherwise.
 * 
 */
function Cookie(name) {
    this.$name = name;  // Remember the name of this cookie
	
		var cookie = Cookie.findCookieByName(name);

    // If we didn't find a matching cookie, quit now
    if (cookie == null) return;

    // The cookie value is the part after the equals sign
    var cookieval = cookie.substring(name.length+1);
    // Now that we've extracted the value of the named cookie, we
    // must break that value down into individual state variable
    // names and values. The name/value pairs are separated from each
    // other by ampersands, and the individual names and values are
    // separated from each other by colons. We use the split( ) method
    // to parse everything.
    var a = cookieval.split('&'); // Break it into an array of name/value pairs
    for(var i=0; i < a.length; i++)  // Break each pair into an array
        a[i] = a[i].split(':');

    // Now that we've parsed the cookie value, set all the names and values
    // as properties of this Cookie object. Note that we decode
    // the property value because the store( ) method encodes it.
    for(var i = 0; i < a.length; i++) {
   		if (a[i].length == 2) {
        	this[a[i][0]] = decodeURIComponent(a[i][1]);
        }
    }
}

/**
 * This function is the store( ) method of the Cookie object.
 *
 * Arguments:
 *
 *   daysToLive: the lifetime of the cookie, in days. If you set this
 *     to zero, the cookie will be deleted. If you set it to null, or
 *     omit this argument, the cookie will be a session cookie and will
 *     not be retained when the browser exits. This argument is used to
 *     set the max-age attribute of the cookie.
 *   path: the value of the path attribute of the cookie
 *   domain: the value of the domain attribute of the cookie
 *   secure: if true, the secure attribute of the cookie will be set
 */
Cookie.prototype.store = function(daysToLive, path, domain, secure) {
    // First, loop through the properties of the Cookie object and
    // put together the value of the cookie. Since cookies use the
    // equals sign and semicolons as separators, we'll use colons
    // and ampersands for the individual state variables we store
    // within a single cookie value. Note that we encode the value
    // of each property in case it contains punctuation or other
    // illegal characters.
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with '$' and also methods
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function'))
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + encodeURIComponent(this[prop]);
    }

    // Now that we have the value of the cookie, put together the
    // complete cookie string, which includes the name and the various
    // attributes specified when the Cookie object was created
    var cookie = this.$name + '=' + cookieval;
    if (daysToLive || daysToLive == 0) {
   		var expires = new Date();
   		expires .setTime(expires.getTime() + daysToLive * 24 * 60 * 60 * 1000);
   		cookie += "; expires=" + expires.toGMTString(); 
        cookie += "; max-age=" + (daysToLive*24*60*60);
    }

    if (path) cookie += "; path=" + path;
    if (domain) cookie += "; domain=" + domain;
    if (secure) cookie += "; secure";

    // Now store the cookie by setting the magic Document.cookie property
    document.cookie = cookie;
}

/**
 * This function is the remove( ) method of the Cookie object; it deletes the
 * properties of the object and removes the cookie from the browser's
 * local store.
 *
 * The arguments to this function are all optional, but to remove a cookie
 * you must pass the same values you passed to store( ).
 */
Cookie.prototype.remove = function(path, domain, secure) {
    // Delete the properties of the cookie
    for(var prop in this) {
        if (prop.charAt(0) != '$' && typeof this[prop] != 'function')
            delete this[prop];
    }

    // Then, store the cookie with a lifetime of 0
    this.store(0, path, domain, secure);
}

/**
 * This static method attempts to determine whether cookies are enabled.
 * It returns true if they appear to be enabled and false otherwise.
 * A return value of true does not guarantee that cookies actually persist.
 * Nonpersistent session cookies may still work even if this method
 * returns false.
 */
Cookie.enabled = function( ) {
    // Use navigator.cookieEnabled if this browser defines it
    if (navigator.cookieEnabled != undefined) return navigator.cookieEnabled;

    // If we've already cached a value, use that value
    if (Cookie.enabled.cache != undefined) return Cookie.enabled.cache;

    // Otherwise, create a test cookie with a lifetime
    document.cookie = "testcookie=test; max-age=10000";  // Set cookie

    // Now see if that cookie was saved
    var cookies = document.cookie;
    if (cookies.indexOf("testcookie=test") == -1) {
        // The cookie was not saved
        return Cookie.enabled.cache = false;
    }
    else {
        // Cookie was saved, so we've got to delete it before returning
        document.cookie = "testcookie=test; max-age=0";  // Delete cookie
        return Cookie.enabled.cache = true;
    }
}

Cookie.findCookieByName = function(name) {
  // First, get a list of all cookies that pertain to this document.
  // We do this by reading the magic Document.cookie property.
  // If there are no cookies, we don't have anything to do.
  var allcookies = document.cookie;
  if (allcookies == "") return null;

	
  // Break the string of all cookies into individual cookie strings
  // Then loop through the cookie strings, looking for our name
  var cookies = allcookies.split(';');
  var cookie = null;
  for(var i = 0; i < cookies.length; i++) {
  	// remove leading spaces
      cookies[i] = cookies[i].replace(/^\s*/i,"");

      // Does this cookie string begin with the name we want?
      if (cookies[i].substring(0, name.length+1) == (name + "=")) {
          cookie = cookies[i];
          break;
      }
  }
  return cookie;
}

//----------------------------------------------------------------------------
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function formatInteger(number, length) {
	var str = number.toString(10);
	while (str.length < length) {
		str = '0' + str;		
	}
	return str;
}

function removeSpaces(iString) {
	var tString = "";
	for(i=0; i<iString.length;i++) {
		if(iString.charAt(i)!=' ') {
			tString = tString + iString.charAt(i);
		}
	}
	return tString;
}

function removeBreadcrumbTrailHome(breadcrumbTrail) {
	var newBreadcrumbTrail='';
  var len = breadcrumbTrail.length;
  
	if(breadcrumbTrail.substr(0,4) == 'Home') {
		newBreadcrumbTrail = breadcrumbTrail.substr(5,len);
	}
	
	if(breadcrumbTrail.substr(0,9) == 'Microsite') {
		newBreadcrumbTrail = breadcrumbTrail.substr(10,len);
	}
	
	if(breadcrumbTrail.substr(0,3) == String.fromCharCode(12507,12540,12512)){
		newBreadcrumbTrail = breadcrumbTrail.substr(4,len);
	}
	
	if(newBreadcrumbTrail.charAt(newBreadcrumbTrail.length-1) == '/') {
		newBreadcrumbTrail = newBreadcrumbTrail.substr(0,newBreadcrumbTrail.length-1);
	}
	
	return newBreadcrumbTrail;
}

//----------------------------------------------------------------------------
function breadcrumbAbbreviation(breadcrumbTrail, maxSize) {
  var newBreadcrumbTrail = '';
  var COMPONENT_LENGTH = 4;
  if(breadcrumbTrail.length > (maxSize - 1)) {
  	var breadcrumbTrailArray = breadcrumbTrail.split('/');
  	if(breadcrumbTrailArray.length <= 1) {
  	  return breadcrumbTrail;
  	}
  	for(i = breadcrumbTrailArray.length - 1; i>0; i--) {
  		var channelName = breadcrumbTrailArray[i];
  		if(channelName.length > COMPONENT_LENGTH) {
  			breadcrumbTrailArray[i] = channelName.substr(0,COMPONENT_LENGTH) + '_';
  		}
  		newBreadcrumbTrail = breadcrumbTrailArray.join('/');
  		if(newBreadcrumbTrail.length <= (maxSize - 1)) {
  			break;
  	  }
  	}
  	return newBreadcrumbTrail;
  }
  return breadcrumbTrail;
}

function breadcrumbTrail(breadcrumbTrail,maxSize){

	var newBreadcrumbTrail = removeBreadcrumbTrailHome(breadcrumbTrail);

	return (breadcrumbAbbreviation(removeSpaces(newBreadcrumbTrail), maxSize).toLowerCase());
}


function breadcrumbTrailLastNode(breadcrumbTrail){
	var lastNodeName;
	var breadcrumbTrailArray = breadcrumbTrail.split('/');
	for(i=breadcrumbTrailArray.length - 1; i>0;i--){
		lastNodeName = breadcrumbTrailArray[i];
		if(lastNodeName != ''){
			break;
		}
	}
	return lastNodeName;
}

/*
	URL encoding/decoding function
*/
var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}

}

//----------------------------------------------------------------------------

/**
  Revision history.
  6-Sep-2007	Sasmito Adibowo	Initial creation.
  Requires: cookie_util.js
*/
function WebAnalytics() {
	this.domainName="";
	this.cookie = null;
}

WebAnalytics.prototype.kickStart = function() {
									
														                            
	this.cookie = new Cookie("WebAnalytics");
	if (typeof this.cookie.userTrackingID != "string" ) {
		this.initCookie();
	}

	// re-store cookie to persist age
	with (this.cookie) {
		// ten years cookie age.
		var cookieAgeInDays = 365.25 * 10;
		
		// see file "scripts.js" function setRegionCookie() for the list of domains that need to be set.
		
		// J.S. ONLY SAVE USER TRACKING ID IF COOKIE NOT ALREADY SET
		var myWebAnalytics = readCookie("WebAnalytics");
		if (myWebAnalytics == null)
		{	
			var vanityDomains = new Array(
													'www.barcap.ch',
													'www.barcap.co.kr',
													'www.barcap.co.uk',
													'www.barcap.co.za',
													'www.barcap.com',
													'www.barcap.com.br',
													'www.barcap.com.hk',
													'www.barcap.com.mx',
													'www.barcap.com.sg',
													'www.barcap.info',
													'www.barcap.net',
													'www.barcap.nl',
													'www.barcap.org',
													'www.barclayscapital.ch',
													'www.barclayscapital.co.in',
													'www.barclayscapital.co.kr',
													'www.barclayscapital.co.uk',
													'www.barclayscapital.co.za',
													'www.barclayscapital.com',
													'www.barclays-capital.com',
													'www.barclayscapital.com.au',
													'www.barclayscapital.com.br',
													'www.barclayscapital.com.fr',
													'www.barclayscapital.com.hk',
													'www.barclayscapital.com.my',
													'www.barclayscapital.com.sg',
													'www.barclayscapital.de',
													'www.barclayscapital.fr',
													'www.barclayscapital.info',
													'www.barclayscapital.net',
													'www.barclays-capital.net',
													'www.barclayscapital.nl',
													'www.barclayscapital.org',
													'www.barclays-capital.org',
													'www.barclaysmail.com',
													'www.bzwint.com',
													'www.cbtraders.com',
													'www.cbtrading.com',
													'www.cbuniverse.com',
													'www.e-cb.com',
													'www.econvertible.com',
													'www.econvertibles.com',
													'www.e-convertibles.com',
													'www.barclayscapital.co.jp',
													'www.barcap.com/think',
													'www.bpe.com',
													'www.barclays-private-equity.com',
													'www.barclays-private-equity.co.uk',												
													'www.barclays-private-equity.fr',												
													'www.barclays-private-equity.de',
													'www.barclays-private-equity-infrastructure.co.uk',
													'www.barclaysinfrastructurefunds.com',
													'www.barclaysinfrastructurefunds.co.uk',
													'barclaysinfrastructure.co.uk',
													'barclaysinfrastructure.com');		
			store(cookieAgeInDays , "/");
			for(i=0; i<vanityDomains.length;i++){
				store(cookieAgeInDays , "/", vanityDomains[i]);
			}
		}
	}
}

WebAnalytics.prototype.initCookie = function() {
	var now = new Date();
	this.cookie.userTrackingID
			= now.getUTCFullYear() + formatInteger(now.getUTCMonth() + 1,2) + formatInteger(now.getUTCDate(),2)
				+ formatInteger(now.getUTCHours(),2) + formatInteger(now.getUTCMinutes(),2) + formatInteger(now.getUTCSeconds(),2)
				+ formatInteger(Math.floor(Math.random() * 10000000),7);
	//this.cookie.disclaimer = "This cookie is to be used for web analytics purposes only.";
}

//----------------------------------------------------------------------------

// kickStart.
if (typeof webAnalytics == 'undefined') {
	webAnalytics = new WebAnalytics();
	webAnalytics.kickStart();
}	

// pre-init
if (typeof s != 'undefined') {
	
	s.visitorID = webAnalytics.cookie.userTrackingID;

	s.prop1  = window.location.pathname;
	s.prop2  = document.title; 

	var MONTHS = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var lastModified = new Date(document.lastModified);
	s.prop3  = lastModified.getUTCDate() + ' ' + MONTHS[lastModified.getUTCMonth()] + ' ' + lastModified.getUTCFullYear();	

	s.prop13 = s.visitorID;
}
