/****************************************************
    Google Analytics script
	Authors:
		Alexandre Frantz (One4ads.com)
		Axel Queffeulou (One4ads.com)
	Version: 1.6 (25 juillet 2010)
****************************************************/

var utm_module = window.location.href.match(/([^\/\.]*)\.(html|aspx?)/i);
var utm_pathname = top.location.pathname;
try {
	if (currentPageType == 'PopUp') {
		utm_module = window.opener.location.href.match(/([^\/\.]*)\.(html|aspx?)/i);
		utm_pathname = window.opener.top.location.pathname;
	}
} catch (ex) { }

if (utm_module == null) {
	utm_module = '';
}


var utm_modulestep = location.search.match(/action=([^&#]*)/i);

function utmx_section() { }
function utmx() { }

TM.GoogleWebOptimiser = {
	RegisterControlScript: function(id) {
		(function() {
			var k = id, d = document, l = d.location, c = d.cookie;
			function f(n) {
				if (c) {
					var i = c.indexOf(n + '=');
					if (i > -1) {
						var j = c.indexOf(';', i);
						return c.substring(i + n.length + 1, j < 0 ? c.length : j);
					}
				}
			}
			var x = f('__utmx'), xx = f('__utmxx'), h = l.hash;
			d.write('<sc' + 'ript src="' + 'http' + (l.protocol == 'https:' ? 's://ssl' : '://www') + '.google-analytics.com'
					+ '/siteopt.js?v=1&utmxkey=' + k + '&utmx=' + (x ? x : '') + '&utmxx=' + (xx ? xx : '') + '&utmxtime='
					+ new Date().valueOf() + (h ? '&utmxhash=' + escape(h.substr(1)) : '')
					+ '" type="text/javascript" charset="utf-8"></sc' + 'ript>');
		})();
	},
	CallUtmx: function() {
		utmx("url", 'A/B');
	},
	RegisterTrackingScript: function(id) {
		if (typeof (_gat) != 'object')
			document.write('<sc' + 'ript src="http' + (document.location.protocol == 'https:' ? 's://ssl' : '://www')
				+ '.google-analytics.com/ga.js"></sc' + 'ript>');
		try {
			var gwoTracker = _gat._getTracker("UA-4406200-14");
			gwoTracker._setDomainName(".tourisme-montreal.org");
			gwoTracker._trackPageview("/" + id + "/test");
		} catch (err) { }
	},
	RegisterConversionScript: function(id) {
		if (typeof (_gat) != 'object')
			document.write('<sc' + 'ript src="http' + (document.location.protocol == 'https:' ? 's://ssl' : '://www')
				+ '.google-analytics.com/ga.js"></sc' + 'ript>');
		try {
			var gwoTracker = _gat._getTracker("UA-4406200-14");
			gwoTracker._setDomainName(".tourisme-montreal.org");
			gwoTracker._trackPageview("/" + id + "/goal");
		} catch (err) { }
	}
}

TM.GoogleAnalytics = {
	extTrack: ["localhost", "127.0.0.1", "tourisme-montreal.org", "tm-qaweb2008.cactus.net", "uattm.cactuscommerce.com"],
	extDoc: [".doc", ".xls", ".exe", ".zip", ".pdf", ".ppt", ".wav", ".mp3", ".mov", ".mpg", ".avi", ".wmv"],
	utm_pagename: "",
	utm_account: "UA-4406200-1",
	//utm_defaultparams: "",
	//utm_moreparams: "",

	gup: function(name) {
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.href);
		if (results == null)
			return "";
		else
			return results[1];
	},

	trackPageview: function() { },

	doHeader: function(callGA) {
		this.initialize();
		if (callGA) this.callGA();
		this.loadGA();
	},

	doFooter: function() {
		this.trackPagename();
		this.addLinkerEvents("");
	},

	initialize: function() {
		// CONFIG
		_gaq.push(['_setAccount', this.utm_account]);
		if (location.host.indexOf("tourisme-montreal.org") > -1) {
			_gaq.push(['_setDomainName', '.tourisme-montreal.org']);
		}
	},

	callGA: function() {
		// LOCAL VARS
		var lang = 'fr';
		var silo = 'undefined';
		var logged = 'false';
		var internalcampaign = 'undefined';
		var pagename = document.location.pathname + document.location.search;
		if (typeof (currentLanguageId) != "undefined") { if (currentLanguageId == 2) { lang = 'en'; } else { lang = 'fr'; } }
		//switch(currentSiloId){case 1: silo='traveller'; break; case 2: silo='meeting-planner'; break; case 3: silo='travel-professional'; break; case 4: silo='journalist'; break; case 5: silo='member-partner'; break; default: silo='undefined';}
		if (typeof (currentWebSiloSection) != "undefined") silo = currentWebSiloSection;
		if (typeof (currentUserAnonymous) != "undefined") { if (currentUserAnonymous == false) { logged = 'true'; } else { logged = 'false'; } }
		var icid = this.gup("utm_icid");
		if (icid.length > 60) {
			icid = icid.substr(0, 60);
		}

		// CUSTOM VARS
		_gaq.push(['_setCustomVar', 1, 'language', lang, 2]);
		_gaq.push(['_setCustomVar', 2, 'silo', silo, 2]);
		_gaq.push(['_setCustomVar', 3, 'logged', logged, 2]);
		if (icid != "") _gaq.push(['_setCustomVar', 4, 'ic', icid, 3]);
		if (typeof (currentSearch) != "undefined") _gaq.push(['_setCustomVar', 5, 'search', currentSearch, 2]);

		// SITE SEARCH
		if (location.pathname.match(/\/(Recherche|Search)\//)) {
			var utm_keyword = location.pathname.match(/([^\/]*)$/i);
			pagename = pagename + (location.search.length > 0 ? '&' : '?') + 'utm_keyword=' + utm_keyword[0];
		}


		// TRACK PAGEVIEW
		if (typeof (currentPageType) == "undefined" || currentPageType != "IFrame")
			_gaq.push(['_trackPageview', pagename]);

	},

	loadGA: function() {
		// LOAD GA
		(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';
			(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
		})();
	},

	trackExitLink: function(link) {
		if (typeof (_gaq) != 'undefined') {
			this.trackEvent('exit', link.href, this.getDirectLinkValue());
		}
		window.open(link.href);
	},

	getDirectLinkValue: function() {
		var pagenamevalue = location.pathname + location.search;

		if (typeof (currentPageName) != "undefined" && currentPageName.length > 0) {
			pagenamevalue = currentPageName;
		}
		return pagenamevalue;
	},

	/* deprecated */
	customLink: function(utm_action, utm_actionelement, gaparams) {

		// deprecated functions tracking :
		this.trackEvent('deprecated function used', 'trackUserDefined', document.location.pathname);

		if (typeof (utm_actionelement) == "undefined" || utm_actionelement == "") {
			utm_actionelement = utm_action;
		}
		//this.trackPagename("utm_action=" + utm_action + "&utm_actionelement=" + utm_actionelement + (gaparams.length > 0 ? "&" + gaparams : ""));
		this.trackPagename("utm_action=" + utm_action);

	},

	setDefaultPagename: function(moreparams) {
		var pagename = this.getDirectLinkValue();
		this.setPagename(pagename, moreparams);
	},

	setPagename: function(basePagename, moreparams) {
		//this.utm_moreparams = typeof (moreparams) != "undefined" ? moreparams : "";
		this.utm_pagename = basePagename;
	},

	trackPagename: function(gaparams) {
		if (typeof (_gaq) != "undefined") {
			if (this.utm_pagename == "") {
				this.setDefaultPagename("");
			}
			//var queryparams = this.utm_defaultparams + (this.utm_defaultparams.length > 0 && this.utm_moreparams.length > 0 ? "&" : "") + this.utm_moreparams + (typeof (gaparams) != "undefined" && gaparams.length > 0 ? ((this.utm_defaultparams.length > 0 || this.utm_moreparams.length > 0 ? "&" : "") + gaparams) : "");
			//var pageview = this.utm_pagename + (queryparams.length > 0 ? ((this.utm_pagename.indexOf("?") > -1 ? "&" : "?") + queryparams) : "");
			var pageview = this.utm_pagename;
			_gaq.push(['_trackPageview', pageview]);
		}
	},

	/*
	* getCookie(): given a cookie name, get its value. Returns null if the cookie can't be found.
	* From http://www.webreference.com/js/column8/functions.html
	*
	*/
	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));
	},

	/*
	* utmvCookieCheck(): given a value, read the __utmv cookie and see if
	* that value is already set. Return true if so, false otherwise.
	*
	*/
	utmvCookieCheck: function(value) {
		var utmvCookie = this.getCookie("__utmv");

		if (utmvCookie == null)
			return false;

		// get rid of the Google's domain prefix ID, which appear on all
		// GA cookies
		utmvCookie = utmvCookie.replace(/^\d*\./, '');

		return (utmvCookie == value) ? true : false;
	},

	/* deprecated */
	trackUserDefined: function(userDefinedValue) {

		// deprecated functions tracking :
		this.trackEvent('deprecated function used', 'trackUserDefined', document.location.pathname);

		if (typeof (_gaq) != "undefined") {
			// from: http://www.startupcto.com/marketing-tech/google-analytics/setvar-and-the-zero-bounce-rate-bug
			if (!this.utmvCookieCheck(userDefinedValue)) {
				_gaq.push(['_setVar', userDefinedValue]);
			}
		}
	},

	trackEvent: function(category, action, label, value) {
		if (typeof (_gaq) != "undefined") {
			if (value == null) {
				if (label == null)
					_gaq.push(['_trackEvent', category, action]);
				else
					_gaq.push(['_trackEvent', category, action, label]);
			}
			else
				_gaq.push(['_trackEvent', category, action, label, parseInt(value,10)]);
		}
	},

	/* deprecated */
	trackCommerce: function(category, product, sku) {

		// deprecated functions tracking :
		this.trackEvent('deprecated function used', 'trackUserDefined', document.location.pathname);

		if (typeof (_gaq) == "undefined") {
			return;
		}

		var timeObj = new Date;
		var unixTimeMs = timeObj.getTime();
		var unixTime = parseInt(unixTimeMs / 1000);

		var t = this.utm_defaultparams;
		var z = 0;
		var utm_prefix = "";
		while (t) {
			var y = t.indexOf("&");
			y = y < 0 ? t.length : y;
			t = t.substring(0, y);
			if (t.indexOf("=")) {
				utm_prefix += t.substring(t.indexOf("=") + 1, t.length) + "-";
			}
			z += y + 1;
			t = this.utm_defaultparams.substring(z, this.utm_defaultparams.length);
			t = z < this.utm_defaultparams.length ? t : '';
		}

		var orderID = utm_prefix + '-' + unixTime;

		_gaq.push(['_addTrans',
			orderID,             			// order ID - required 
			"", 							// affiliation or store name
			0,            					// total - required
			"",             				// tax
			"",          					// shipping
			"",  		       				// city
			"",       						// state or province
			"" 			            		// country
		]);

		_gaq.push(['_addItem',
			orderID,             			// order ID - required
			sku, 						// SKU/code
			product,         				// product name
			category,     					// category or variation
			0,            					// unit price - required
			1                 				// quantity - required
		]);

		_gaq.push(['_trackTrans']);
	}
};
