


var HarvesterConfig = {
    charSet: "UTF-8"
	, journalCode : 'BR2'
    /* DART */
	, dartSitename: "br2.main"
	, googleAnalyticsAccount: 'UA-9924683-1'
};

Harvester.startTime = (new Date()).getTime();


function Harvester(params) {

    var startTime;
    this.params = params || {};
    this.siteConfig = (typeof (HarvesterConfig) == 'object') ? HarvesterConfig : {};
    if (this.siteConfig.jQueryNoConflictMode == true) {
        jQuery.noConflict();
    }
    this.debug = this.params.debug || this.siteConfig.debug;
    this.scheme = (("https:" == document.location.protocol) ? "https" : "http");
    this.hostname = window.location.hostname;
    this.path = window.location.pathname;
    this.randomNumber = Harvester.random();
	this.bAuth = (this.getCookie('BSTATUS') == 'true') ? 1 : 0;
    /* metrics containers - NB: try and limit metric names to 9 characters max */
    this.systemMetrics = { sFuseaction: '', sHostName: this.hostname, sID: '', sJrunInstance: '', sServerName: '', nExecutionTime: '', sHttpResponse: '', sErrorType: '' };
    this.contentMetrics = { sAuthor: '', nId: '', sTitle: '', sJournalCode: '', sKeyword: '', sLanguage: '', sLocation: '', sType: '', sArticleType: '', sAssets: '', nPage: '', sRating: '', sDiscipline: '', sSubDiscipline: '', sPrimaryDiscipline: '', sSector: '', sSubSector: '', sTaggedKeywords: '', nAge: '' };
    this.navigationMetrics = { sSite: '', sPageName: '', sMLC: ''};
    this.affiliateMetrics = { code: '' };
    this.searchMetrics = { sPhrase: '', sFilters: '' };
    this.userMetrics = { bAuth: this.bAuth, nUserID: '', sLocation: ''};
    this.customMetrics = {};
	this.customUserMetrics = (this.getCookie('USERMETRICS') != null) ? eval("(" +  this.getCookie('USERMETRICS') + ")") : {};
    /* container for pre-build key-value strings of set metrics */
    this.allMetricsKV = [];

    this.renderHead();

    return this;
};


Harvester.prototype.renderHead = function() {



};

Harvester.prototype.render = function() {
	/* Google Analytics */
	if ((typeof (this.siteConfig.googleAnalyticsAccount) != 'undefined') || (this.siteConfig.googleAnalyticsAccount != '')){
		this.renderGoogleAnalytics();
	}
};




Harvester.prototype.setSystemMetrics = function(vars) {
    this.systemMetrics = Harvester.mergeValues(this.systemMetrics, vars);
};


Harvester.prototype.setContentMetrics = function(vars) {
    this.contentMetrics = Harvester.mergeValues(this.contentMetrics, vars);
};


Harvester.prototype.setNavigationMetrics = function(vars) {
    this.navigationMetrics = Harvester.mergeValues(this.navigationMetrics, vars);
};


Harvester.prototype.setAffiliateMetrics = function(vars) {
    this.affiliateMetrics = Harvester.mergeValues(this.affiliateMetrics, vars);
};


Harvester.prototype.setSearchMetrics = function(vars) {
    this.searchMetrics = Harvester.mergeValues(this.searchMetrics, vars);
};


Harvester.prototype.setUserMetrics = function(vars) {
    this.userMetrics = Harvester.mergeValues(this.userMetrics, vars);
};


Harvester.prototype.setCustomMetrics = function(vars) {
    this.customMetrics = Harvester.mergeValues(this.customMetrics, vars);
};


Harvester.prototype.setCustomUserMetrics = function(vars) {
    this.customUserMetrics = Harvester.mergeValues(this.customUserMetrics, vars);
};




/* util - easy method to get all completed metrics as kv pairs 
* pass "requestedSet" (i.e. this.getAllMetricsKeyValue("product") ) if you want to restrict the metrics returned to one set, or leave undefined for all
*/
Harvester.prototype.getAllMetricsKeyValue = function(requestedSet, includeEmptyValues) {

    var includeEmptyValues = (includeEmptyValues == undefined) ? false : includeEmptyValues;

    var allMetrics = {
        system: this.systemMetrics
		, content: this.contentMetrics
		, navigation: this.navigationMetrics
		, affiliate: this.affiliateMetrics
		, search: this.searchMetrics
		, user: this.userMetrics
		, custom: this.customMetrics
		, customUser: this.customUserMetrics
    };

    this.allMetricsKV = [];
    for (var oneSet in allMetrics) {
        if ((requestedSet == null) || (typeof (requestedSet) == "undefined") || (oneSet == requestedSet)) {
            for (var i in allMetrics[oneSet]) {
                    var keyname = oneSet + "_" + i;
                    this.allMetricsKV[keyname] = allMetrics[oneSet][i];
            }
        }
    }
    return this.allMetricsKV;
};

Harvester.prototype.getRenderAdvertSrc = function(zone, adlocation, sizes, tile) {

    /* we need a count of ads rendered */
    if (typeof (Harvester.prototype.getRenderAdvertSrc.count) == "undefined") {
        Harvester.prototype.getRenderAdvertSrc.count = 0;
    }
    var adserver = this.scheme + "://ad.uk.doubleclick.net/adj/";
    var site = this.siteConfig.dartSitename;
    var theTile = (tile) ? tile : this.nextDARTTile();
    var customValues = this.getAdvertCustomValues();
    /* ad special k-v to first ad, allowing injection of Overlays by DART */
    if (Harvester.prototype.getRenderAdvertSrc.count == 0) {
        customValues += 'dcopt=ist;';
    }
    /* site+/+zone must be <= 64 characters */
    var siteandZone = (site + zone).substring(0, 64);
    var src = adserver + siteandZone + ';' + customValues + 'adloc=' + adlocation + ';sz=' + sizes + ';tile=' + theTile + ';ord=' + this.randomNumber + '?';

    Harvester.prototype.getRenderAdvertSrc.count++;
    this.logToConsole("getRenderAdvertSrc.count=" + Harvester.prototype.getRenderAdvertSrc.count);
    this.logToConsole("ad call=" + src);
    return src;
};

Harvester.prototype.renderAdvert = function(zone, adlocation, sizes, tile) {
    var src = this.getRenderAdvertSrc(zone, adlocation, sizes, tile);
    document.write('<SCR');
    document.write('IPT SRC="' + src + '">');
    document.write('</SCR');
    document.write('IPT>');
};

Harvester.prototype.getRenderAdvertString = function(dimensions, position, tile) {
    var src = this.getRenderAdvertSrc(dimensions, position, tile);
    var string = "<script type=\"text\/javascript\" src=\"" + src + "\"></script>";
    return string;
};

/* generate DART specific custom kv pairs */
Harvester.prototype.getAdvertCustomValues = function() {
    var customValues = "";
    var allMetrics = this.getAllMetricsKeyValue();
	var thisMetric = '';
   for (var i in allMetrics) {
		thisMetric			= this.addDARTMetricValue(i, allMetrics[i]);
		if (thisMetric != '') {
	        customValues += (thisMetric);
		}
		
    }
    return customValues;
};

Harvester.prototype.addDARTMetricValue = function(sName, sValue) {
	var sReturn						= '';
	var sType						= this.getDartKVType(sName);
	var sKey						= this.getDartKVKey(sName);
	sKey							= this.getDARTShortKeyName(sType, sKey);
	if (sKey != '') {
		sKey						= sKey.substring(0, 16); // this was 12 but needed to be changed for healthcare
		if ((typeof(sValue) == "string" && String(sValue).length > 0) || typeof(sValue) == "number") {
			sValue					= String(sValue);
			sReturn					= sKey + '=' + encodeURIComponent(sValue.toLowerCase()) + ';';
		}
		else if (typeof(sValue) == "object") {
			sReturn					= this.addDARTKVArray(sKey, sValue);
		}
	}
	
	return sReturn;
};

Harvester.prototype.getDartKVType = function(sName) {
	return sName.split('_')[0];
};

Harvester.prototype.getDartKVKey = function(sName) {
	return sName.replace(/^([^_]+)_/, '');
};

Harvester.prototype.addDARTKVArray = function(sKey, aValue) {
	var sReturn 					= '';
	for (var i = 0; i < aValue.length; i++) {
		sReturn						+= sKey + '=' + encodeURIComponent(aValue[i].toLowerCase()).substring(0, 55) + ';';
	}
	
	return sReturn;
};

Harvester.prototype.nextDARTPosition = function() {
    if (typeof (Harvester.currentDartPosition) == "undefined" || typeof (Harvester.currentDartPosition) == "null") {
        Harvester.currentDartPosition = 0;
    }
    Harvester.currentDartPosition += 1;
    return Harvester.currentDartPosition;
};

Harvester.prototype.nextDARTTile = function() {
    if (typeof (Harvester.currentDartTile) == "undefined" || typeof (Harvester.currentDartTile) == "null") {
        Harvester.currentDartTile = 0;
    }
    Harvester.currentDartTile += 1;
    return Harvester.currentDartTile;
};


Harvester.prototype.getDARTShortKeyName = function(sType, sName) {
	//always pass custom keys
	if (sType == 'custom' || sType == 'customUser') {
		return sName;
	}
	
	var mapping						= {
										sDiscipline : 'di'
										, sSubDiscipline : 's-di'
										, sPrimaryDiscipline : 'p-di'
										, sSector : 'se'
										, sSubSector : 's-se'
										, sSection : 'sc'
										, bAuth : 'auth'
										, nId : 'cid'
										, sJournalCode : 'cjc'
										, sLocation : 'loc'
										, sArticleType : 'nt'
										, bAuth : 'auth'
										, sKeywords : 'kw'
										, sPhrase: 'kw'
									};
	return (typeof(mapping[sName]) != 'undefined') ? mapping[sName] : '';
};


/**
* UTILITIES
**/

Harvester.mergeValues = function(existing, newvalues) {
    for (i in newvalues) {
        existing[i] = newvalues[i];
    }
    return existing;
};

Harvester.getUrlPathToZone = function() {
    var splitPath = window.location.pathname.split("/");
    splitPath.shift();
    splitPath.pop();
    return splitPath.join(".").toLowerCase();
};

Harvester.random = function() {
    return Math.round(Math.random() * 10000000000);
};

Harvester.stripNonAlphanum = function(text, replacement) {

    var replacement = (replacement == null) ? "" : replacement;
    return (new String(text)).replace(/[^a-zA-Z0-9_-]+/gi, replacement);
};

/* STRIP: #, * . ( ) = + < > [ ] -  i.e. non ascii */
Harvester.validChars = function(text) {

    var clean = text.replace(/[^\x00-\x7F]+/gi, "");
    return clean;
};

Harvester.prototype.logToConsole = function(text) {
    if (this.debug && window.console && window.console.firebug) {
        console.log(text)
    }
};

Harvester.prototype.getCookie = function(name) {
    var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
	
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	
	return unescape(dc.substring(begin + prefix.length, end));

};

Harvester.prototype.getCSS = function(url, media) {
	$(document.createElement('link') ).attr({
          href: url,
          media: media || 'screen',
          type: 'text/css',
          rel: 'stylesheet'
      }).appendTo('head');
};


Harvester.prototype.renderGoogleAnalytics = function() {
    var gaJsHost = ((this.scheme == "https") ? "https://ssl." : "http://www.");
    var gapath = unescape(gaJsHost + 'google-analytics.com/ga.js');
    this.includeJavascript(gapath, this.renderGoogleAnalyticsCallback, this);
};

Harvester.prototype.renderGoogleAnalyticsCallback = function(thisInstance) {
    if (typeof (_gat) == 'object') {
        pageTracker = _gat._getTracker(thisInstance.siteConfig.googleAnalyticsAccount);
        pageTracker._trackPageview();
    }
};

Harvester.prototype.includeJavascript = function(script_filename, callback, thisInstance) {
    return (typeof (jQuery) != "undefined") ? this.includeJavascriptViaJquery(script_filename, callback, thisInstance) : this.includeJavascriptViaDomInsertion(script_filename, callback, thisInstance);
};

Harvester.prototype.includeJavascriptViaJquery = function(script_filename, callback, thisInstance) {
    if (typeof (script_filename) == "string") {
        jQuery(document).ready(function() {

            jQuery.getScript(script_filename, function() {
                callback(thisInstance);
            });
        });
    }
};

Harvester.prototype.includeJavascriptViaDomInsertion = function(script_filename, callback, thisInstance) {
    if (typeof (script_filename) == "string") {
        var html_doc = document.getElementsByTagName('head').item(0);
        if (typeof (html_doc) != 'undefined') {
            var js = document.createElement('script');
            js.setAttribute('language', 'javascript');
            js.setAttribute('type', 'text/javascript');
            js.setAttribute('src', script_filename);
            html_doc.appendChild(js);

            js.onreadystatechange = function() {
                if (js.readyState == 'complete' || js.readyState == 'loaded') {
                    callback(thisInstance);
                }
            }
            js.onload = function() {
                callback(thisInstance);
            }
        }
    }
};

