/*
 * CbidGA - CBID Google Analystics utilities
 * To use, create an instance of cbidga class, e.g.
 * 		var o = new CbidGA("UA-16476402-3");
 * 		o.track("RF");
 */

var _gaq = _gaq || [];

(function() {
	var ga = document.createElement('script');
	ga.type = 'text/javascript';
	ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(ga, s);
})();

function Logger() { // for debug purpose
	this.debug = function(s) {
		document.writeln(s + "<br>");
	};
}

// assume caller has defined var pageid
// constructor; trackerId is the google account id; e.g. "UA-12345-1"
function CbidGA(trackerId) {

	this.getCookie = function(c_name) {
		if (document.cookie.length > 0) {
			c_start = document.cookie.indexOf(c_name + "=");
			if (c_start != -1) {
				c_start = c_start + c_name.length + 1;
				c_end = document.cookie.indexOf(";", c_start);
				if (c_end == -1)
					c_end = document.cookie.length;
				return unescape(document.cookie.substring(c_start, c_end));
			}
		}
		return "";
	};

	this.getUserCookie = function() {
		return this.getCookie('CBID_EXT_USERNAME');
	};

	this.getEmailCookie = function() {
		return this.getCookie('CBID_EXT_EMAIL');
	};

	this.getUserTypeCookie = function() {
		return this.getCookie('CBID_EXT_USER_TYPE');
	};

	this.getSourceCookie = function() {
		var source = this.getCookie('CBID_EXT_SOURCE');
		return source;
	};

	this.getMilestonesCookie = function() {
		return this.getCookie('CBID_MILESTONES');
	};

	this.user = ""; // to-be-filled in by
	this.userType = this.getUserTypeCookie();

	this.trackerId = trackerId;
	_gaq.push( [ '_setAccount', this.trackerId ]);

	this.push = function(url) { // Async. call google analytics
		if (this.trackerId == 'debug') {
			document.writeln(url + "<br>");
		} else {
			// document.writeln(url + "<br>");
			_gaq.push( [ '_trackPageview', url ]);
			// console.log('track ' + url);
		}
	};

	this.COMMON_URL = {
		'PRF' : '/cbidtoday/subscription/form/paid',
		'PRP' : '/cbidtoday/subscription/preview/paid',
		'PRC' : '/cbidtoday/subscription/confirm/paid',
		'PRX' : '/cbidtoday/subscription/cancel/paid',
		'TRF' : '/cbidtoday/subscription/form/trial',
		'TRP' : '/cbidtoday/subscription/preview/trial',
		'TRC' : '/cbidtoday/subscription/confirm/trial',
		'TRX' : '/cbidtoday/subscription/cancel/trial',
		'VRF' : '/cbidtoday/subscription/form/vip',
		'VRP' : '/cbidtoday/subscription/preview/vip',
		'VRC' : '/cbidtoday/subscription/confirm/vip',
		'VRX' : '/cbidtoday/subscription/cancel/vip',
		'CRF' : '/cbidtoday/subscription/form/cai',
		'CRP' : '/cbidtoday/subscription/preview/cai',
		'CRC' : '/cbidtoday/subscription/confirm/cai',
		'CRX' : '/cbidtoday/subscription/cancel/cai',
		'LAND' : '/cbidtoday/landing',
		'SAMPLE' : '/cbidtoday/samplePDF',
		'NEWSFD' : '/newsfeed/headlines',
		'SEARCH' : '/newsfeed/search',
		'NFVIEW' : '/newsfeed/viewnews',
		'NFNEWS' : '/newsfeed/newscontent',
		'NEWSLT' : '/newsletter/viewnews',
		'SUBJECT' : '/newsfeed/subject',
		'REGION' : '/newsfeed/region',
		'STOCK' : '/newsfeed/stock',
		'INDUSTRY' : '/newsfeed/industry',
		'HOME' : '/home',
		'ABOUTUS' : '/aboutus',
		'CONTACTUS' : '/contactus',
		'COPYRIGHT' : '/copyright',
		'DISCLAIMER' : '/disclaimer',
		'PRIVACY' : '/privacy',
		'LEGAL' : '/legal',
		'TERMS' : '/terms',
		'CBIDTERMS' : '/cbidterms',
		'PROFILE' : '/profile',
		'FORGOTPWD' : '/forgotpassword',
		'FEEDBACK' : '/feedback',
		'VISIT' : '/pageByUser?u=',
		'LOOKUPNEWSCONTENT' : '/newsfeed/newscontent',
		'CLICKTHRU' : '/clickthru?s='
	};

	this.isEmpty = function(s) {
		if (s == undefined || s == null)
			return true;
		return String(s).replace(' ', '').length == 0;
	};

	this.contains = function(a, s) {
		for ( var i = 0; i < a.length; i++) {
			if (a[i] == s)
				return true;
		}
		return false;
	};

	this.setCookie = function(c_name, value, expiredays, path) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie = c_name + "=" + escape(value) + ((path == null) ? "" : ";path=" + path)
				+ ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
	};

	this.addMilestoneCookie = function(milestone) {
		var milestones = this.getMilestonesCookie();
		if (this.isEmpty(milestones)) {
			this.setCookie('CBID_MILESTONES', milestone, 9999, '/');
		} else {
			var array = milestones.split('|');
			if (this.contains(array, milestone)) {
				// do nothing
				return;
			}
			// not exist => add one
			array[array.length] = milestone;
			array.sort();
			// store the result in cookie
			// expiry in 9999 is virtually forever
			// path=/ so that it is available across webapps
			this.setCookie('CBID_MILESTONES', array.join('|'), 9999, '/');
		}
	};

	this.getRealUrl = function(pageid) {
		var url = this.COMMON_URL[pageid];
		return url;
	};

	this.composeParams = function(map) {
		var keys = [ 'u', 't', 'h', 's', 'm', 'n', 'c', 'r', 'd', 'z', 'g', 'i', 's1', 'r1', 's2', 'i1' ];

		var v;
		var params = new Array();
		for ( var k in keys) {
			v = map[keys[k]];
			if (!this.isEmpty(v)) {
				params.push(keys[k] + '=' + v);
			}
		}
		return (params.length > 0) ? ('?' + params.join('&')) : '';

	};

	this.track_page = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		// TODO: do track page here...
		this.push("/page" + url + this.composeParams( {
			'n' : newsid,
			'c' : code1,
			'r' : code2
		}));
	};

	this.track_pageByUser = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		if (this.isEmpty(this.user)) {
			return;
		}
		// TODO: do track page here...
		this.push("/pageByUser" + url + this.composeParams( {
			'u' : this.user,
			'n' : newsid,
			'c' : code1,
			'r' : code2
		}));
	};

	this.track_pageByUserType = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		if (this.isEmpty(this.userType)) {
			return;
		}
		// TODO: do track page here...
		this.push("/pageByType" + url + this.composeParams( {
			't' : this.userType,
			'n' : newsid,
			'c' : code1,
			'r' : code2
		}));
	};

	this.track_pageByHour = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		var hour = (new Date()).getUTCHours() + ""; // convert to string
		this.push("/pageByHour" + url + this.composeParams( {
			'h' : hour,
			'n' : newsid,
			'c' : code1,
			'r' : code2
		}));
	};

	this.track_pageBySource = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		this.push("/loginSource" + url + this.composeParams( {
			's' : this.getSourceCookie(),
			'n' : newsid,
			'c' : code1,
			'r' : code2
		}));
	};

	this.track_matrix = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		if (this.userType == 'C') {
			// do not count CAI internal staffs
			// assume HKEJ users are treated as CAI internal staffs
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		var hour = (new Date()).getUTCHours() + ""; // convert to string
		var milestones = this.getMilestonesCookie();
		this.push("/matrix" + url + this.composeParams( {
			'u' : this.user,
			't' : this.userType,
			'h' : hour,
			's' : this.getSourceCookie(),
			'm' : milestones,
			'n' : newsid,
			'c' : code1,
			'r' : code2
		}));
	};

	this.track_lookup = function(pageid, newsid, subject, region, stockcode, industrycode) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		if (this.userType == 'C') {
			// do not count CAI internal staffs
			// assume HKEJ users are treated as CAI internal staffs
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		var hour = (new Date()).getUTCHours() + ""; // convert to string
		var milestones = this.getMilestonesCookie();
		this.push("/lookup" + url + this.composeParams( {
			'u' : this.user,
			't' : this.userType,
			'h' : hour,
			's' : this.getSourceCookie(),
			'm' : milestones,
			'n' : newsid,
			's1' : subject,
			'r1' : region,
			's2' : stockcode,
			'i1' : industrycode
		}));
	};

	this.track_milestone = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		// TODO: do track page here...
		this.addMilestoneCookie(pageid);
		var milestones = this.getMilestonesCookie();
		this.push("/milestone" + url + this.composeParams( {
			'u' : this.user,
			'm' : milestones,
			'n' : newsid,
			'c' : code1,
			'r' : code2
		}));
	};

	this._track_all = function(pageid, newsid, code1, code2) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		if (this.userType == 'C') {
			// do not count CAI internal staffs
			// assume HKEJ users are treated as CAI internal staffs
			return;
		}
		// track the page hit
		this.track_page(pageid, newsid, code1, code2);
		// track page hit by user
		this.track_pageByUser(pageid, newsid, code1, code2);
		// track page hit by user type
		this.track_pageByUserType(pageid, newsid, code1, code2);
		// track page hit by hour
		this.track_pageByHour(pageid, newsid, code1, code2);
		// track milestone
		this.track_milestone(pageid, newsid, code1, code2);
		// track page hit by source
		this.track_pageBySource(pageid, newsid, code1, code2);
		// track matrix (combinations of all parameters)
		this.track_matrix(pageid, newsid, code1, code2);
	};

	this.track = function(pageid, newsid) {
		this.user = this.getUserCookie();
		this.userType = this.getUserTypeCookie();
		if (this.userType == 'C') {
			// do not count CAI internal staffs
			// assume HKEJ users are treated as CAI internal staffs
			return;
		}
		if (this.userType == 'T') {
			var email = this.getEmailCookie();
			if (!this.isEmpty(email)) {
				this.user = email;
			}
		}
		// define customer variables to track user name and type
		_gaq.push( [ '_setCustomVar', 1, 'user', this.user, 1 ]);
		_gaq.push( [ '_setCustomVar', 2, 'type', this.userType, 1 ]);
		//
		return this._track_all(pageid, newsid);
	};

	this.trackNewsletter = function(pageid, e, userType) {
		var u = /&email=(.*)$/.exec(e);
		this.user = u[1];
		this.userType = userType;
		if (this.userType == 'C') {
			// do not count CAI internal staffs
			// assume HKEJ users are treated as CAI internal staffs
			return;
		}
		// define customer variables to track user name and type
		_gaq.push( [ '_setCustomVar', 1, 'user', this.user, 1 ]);
		_gaq.push( [ '_setCustomVar', 2, 'type', this.userType, 1 ]);
		//
		return this._track_all(pageid);
	};

	this.trackMultiValues = function(pageid, values) {
		if (this.isEmpty(values))
			return;
		if (this.userType == 'C') {
			// do not count CAI internal staffs
			// assume HKEJ users are treated as CAI internal staffs
			return;
		}
		// define customer variables to track user name and type
		_gaq.push( [ '_setCustomVar', 1, 'user', this.user, 1 ]);
		_gaq.push( [ '_setCustomVar', 2, 'type', this.userType, 1 ]);
		//
		var array = values.split('|');
		for ( var i in array) {
			var code1 = array[i];
			var code2 = null;
			var dot = code1.indexOf('.');
			if (dot >= 0) {
				code2 = code1.substring(dot + 1);
				code1 = code1.substring(0, dot);
			}
			this._track_all(pageid, "", code1, code2);
		}
	};

	this.track_pageviewsByUser = function(pageid) {
		this.user = this.getUserCookie();
		this.userType = this.getUserTypeCookie();
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		if (this.userType == 'C') {
			// do not count CAI internal staffs
			// assume HKEJ users are treated as CAI internal staffs
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			return;
		}
		// define customer variables to track user name and type
		_gaq.push( [ '_setCustomVar', 1, 'user', this.user, 1 ]);
		_gaq.push( [ '_setCustomVar', 2, 'type', this.userType, 1 ]);
		//
		// console.log("track_pageviewsByUser [" + this.user + "]");
		// TODO: do track page here...
		if (this.isEmpty(this.user) || this.user == "") {
			// non-login user
			this.push("/pageByUser?nologin");
		} else {
			// login user
			this.push("/pageByUser" + this.composeParams( {
				'u' : this.user
			}));
		}
	};
	
	this.track_ClickThru = function(pageid,source) {
		if (this.isEmpty(pageid)) {
			// do nothing if no pageid defined
			return;
		}
		var url = this.getRealUrl(pageid);
		if (this.isEmpty(url)) {
			// do nothing if no url mapped
			return;
		}
		if (this.isEmpty(source)) {
			// do nothing if no source
			return;
		}
		this.push(url+source);
	};
}
