/*jslint browser: true, maxerr: 500 */
/* DO NOT REMOVE COMMENT DELIMITER: This file can be parsed as PHP or JavaScript
<?php
header('Content-Type: application/javascript');
$dir = dirname($_SERVER['SCRIPT_NAME']);
$protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];

$path = sprintf('%s://%s%s', $protocol, $host, $dir);

?>
DO NOT REMOVE COMMENT DELIMITER */

var CRC;
if (typeof(CRC) === 'undefined') {
	var CRC = {};
	CRC.initialized = false;
}
CRC.path = '/tjs';
// Config file must be loaded from server with PHP
CRC.configPath = '//www.marketingcrc.com/t';
CRC.utmGifPath = '/TJS/utmgif.asp';
if (typeof(CRC.domain) == 'undefined') {
	CRC.domain = window.location.hostname;
}


/* DO NOT REMOVE COMMENT DELIMITER
<?php
// update CRC.path variable
print base64_decode('Ki8=') . "\n";
printf("CRC.path = '%s';\n", $path);
printf("CRC.configPath = '%s';\n", $path);
print("delete CRC.utmGifPath;\n");

print "/* ";
?>
DO NOT REMOVE COMMENT DELIMITER */

var $t;
if (typeof($t) === 'undefined') {
	// $t needs to be defined by the time tinit.js finishes loading
	var $t = (function() {
		var callbacks = [];
		var t = function(fn) {
			if (typeof(fn) != 'undefined') {
				callbacks.push(fn);
			} else {
				return callbacks;
			}
		};
		return t;
	})();
	// bootstrap jquery first - onload/onreadystatechange code from jquery
	(function(url, success) {
		var head = document.getElementsByTagName('head')[0] || document.documentElement;
		var script = document.createElement('script');
		script.src = url;

		var done = false;

		// Detect when script is laoded
		script.onload = script.onreadystatechange = function() {
			if (!done && (!this.readyState ||
					this.readyState === 'loaded' || this.readyState === 'complete')) {
				done = true;
				success();

				// Handle memory leak in IE
				script.onload = script.onreadystatechange = null;
				if (head && script.parentNode) {
					head.removeChild(script);
				}
			}
		};

		// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
		// This arises when a base node is used (#2709 and #4378).
		head.insertBefore(script, head.firstChild);
	})(CRC.path + '/jquery.js', function() {
		// jquery has been loaded

		var callbacks = $t();
		// use a custom variable for our instance of jquery in case there is
		// already another version in use
		$t = jQuery.noConflict(true);

		CRC.IE6 = function(msg) {
			if ($t.browser.msie && $t.browser.version.substr(0, 1) < 7) {
				if (window.location.search.indexOf('debug=0') != -1 && document.cookie.indexOf('IE6DEBUG') != -1) {
					alert('clearing debug cookie');
					document.cookie = 'IE6DEBUG=0; expires=Fri, 27 Jul 2001 02:47:11 UTC;';
				} else if (document.cookie.indexOf('IE6DEBUG') != -1) {
					alert(msg);
				} else if (window.location.search.indexOf('debug=1') != -1) {
					alert('setting debug cookie');
					document.cookie = 'IE6DEBUG=1;';
					alert(msg);
				}
				return true;
			}
			return false;
		}

		CRC.IE6('jquery loaded: IE6!');


		for (var i = 0; i < callbacks.length; i++) {
			$t(callbacks[i]);
		}

		CRC.IE6('Ran callbacks: IE6!');

		// Load main tracking library
		var loadTjs = function() {
			CRC.IE6('in loadTjs: IE6');
			$t.ajax({
				url: CRC.path + '/t.js',
				dataType: 'script',
				cache: true,
				success: function() {
					if (CRC.IE6('loaded t.js: IE6!')) return;
				}
			});
		};

		// makes attributues stored in data[service].vars variables
		var extractVars = function(data, service) {
			if (typeof(data[service]) != 'undefined' && typeof(data[service].vars) != 'undefined') {
				for (var i = 0; i <= data[service].vars.length - 1; i++) {
					if (data[service].vars[i].global) {
						// create object in global namespace
						this.window[data[service].vars[i].name] = data[service].vars[i].value;
					} else {
						// use CRC namespace
						if (typeof(CRC[service]) == 'undefined') {
							CRC[service] = {};
						}
						CRC[service][data[service].vars[i].name] = data[service].vars[i].value;
					}
				}
			}
		}

		var loadMongoose = function(defaultCampaign) {
			CRC.IE6('loading mongoose');
			// Load Mongoose library if this site needs it
			// set customer_number_format
			// custom1 - used by inquiry id
			// custom2 - GA linker url
			// custom3 - TSA cookie values
			// set default_number
			if (typeof(phoneTrackSelector) !== 'undefined') {
				window.default_number = $t(phoneTrackSelector).text().replace(/\D/g, '');
			} else if (typeof(window.default_number) == 'undefined') {
				window.default_number = '';
			}
			// send Mongoose GA cookie data so it can record phone calls
			if (CRC.IE6('setting global variable rather than property of global object; otherwise IE6 loses window.custom2')) {
				custom2 = trackers.getLinkerUrl('').substr(1).replace(/&/g, '%26').replace(/_/g, '%5F') + '%26domain=' + CRC.domain;
			} else {
				window.custom2 = trackers.getLinkerUrl('').substr(1).replace(/&/g, '%26').replace(/_/g, '%5F') + '%26domain=' + CRC.domain;
			}
			window.mm_c = defaultCampaign;
			if (typeof(getNumber) === 'undefined') {
				var mmGetVar = '//www.mongoosemetrics.com/jsfiles/js-correlation/mm-getvar.js';
				$t.getScript(mmGetVar, function() {
					if (match = window.location.hostname.match(/^(?:[^.]+)\.(.+)\.testcrc.com$/i)) {
						// use constant for mm_chk_id while testing so we can
						// use a cached version of mm-contro.php
						try {
							mm_variables = mm_variables.replace(/(%26mm_chk_id)%3D\d+/, '$1%3D1234567890');
						} catch(e) {
						}
					}
					var mmControl = '//www.mongoosemetrics.com/jsfiles/js-correlation/mm-control.php?' + unescape(mm_variables);
					$t.getScript(mmControl, function() {
							$t(window).trigger('mongoose.done');
						}
					);
				});
			}
		}



		var loadTSA = function(siteId, wayId) {
			if (typeof(tsawaypoint) != 'undefined') {
				// tsawaypoint.php has already been loaded
				return;
			}
			$t.getScript('//thesearchagency.net/tsawaypoint.php?siteid=' + siteId + '&wayid=' + wayId,
				function() {
					CRC.IE6('loaded tsawaypoint.php: IE6!');
					$t.getScript('//thesearchagency.net/mongoose-setup.js',
						function() {
							CRC.IE6('loaded mongoose-setup.js: IE6!');
							var getCookie = function(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 '';
							}
							var val_refcd = getCookie('refcd');
							var val_tsacr = getCookie('tsacr');
							var val_visitid = getCookie('tsa1v' + siteId);
							// create global variable used by Mongoose
							window.custom3 = 'ckwid=' + val_refcd + '&tsacr=' + val_tsacr + '&myvid=' + val_visitid;
							$t(window).trigger('tsa.ready');
							CRC.IE6('triggered tsa.ready: IE6!');
						}
					);
				}
			);
			// Record livechat requests as conversions with TSA
			if (typeof(CRC.tsa.conversionWayId) != 'undefined') {
				var trackLiveChat = function() {
					$t('a[href*=liveperson.net]').click(function() {
						$t('body').append('<img style="display: none; height: 1px; width: 1px;" src="//thesearchagency.net/pixspike.php?siteid=' + CRC.tsa.siteId + '&wayid=' + CRC.tsa.conversionWayId + '&prodid=onlinechat">');
					});
				};
				trackLiveChat();
			}
		}

		// load site-specific configuration
		var loadConfig = function() {
			CRC.IE6('loadConfig called: IE6!');
			var configURL = CRC.configPath + '/config.js';
			if (typeof(CRC.domain) != 'undefined') {
				configURL += '?domain=' + CRC.domain;
			}

			var loadCRCConfig = function(data) {
				CRC.IE6('config loaded: IE6!');
				if (typeof(data['google']) != 'undefined') {
					extractVars(data, 'google');
				}
				// Mongoose waits for t.js to swap out phone number
				var mongooseDependencies = 1;

				if (typeof(data['tsa']) != 'undefined') {
					extractVars(data, 'tsa');
					// If TSA library is being used, wait for it before running Mongoose code
					mongooseDependencies++;
				}

				// waits for Mongoose dependencies to be triggered
				var mongooseDependencyLoaded = (function(dependencyCount) {
					var dependencies = dependencyCount;
					return function() {
						dependencies--;
						if (0 == dependencies) {
							$t(window).trigger('mongoose.ready');
						}
					}
				})(mongooseDependencies);

				if (typeof(data['mongoose']) != 'undefined') {
					extractVars(data, 'mongoose');
					// the phone.loaded event is called from t.js after
					// the phone number has been swapped using the GA
					// cookie
					$t(window).bind('phone.loaded', function() { mongooseDependencyLoaded(); });
					$t(window).bind('tsa.ready', function() { mongooseDependencyLoaded(); });
					$t(window).bind('mongoose.ready', function() { loadMongoose(CRC.mongoose.mm_campaign); });
				}
				CRC.initialized = true;
				CRC.IE6('CRC initialized: IE6!');

				if (typeof(data['tsa']) != 'undefined') {
					// don't call until after the tsa.ready event handler has been attached
					loadTSA(CRC.tsa.siteId, CRC.tsa.wayId);
				}

				CRC.IE6('about to load t.js: IE6!');
				loadTjs();
			};

			$t.ajax({
				url: configURL,
				dataType: 'jsonp',
				cache: true,
				jsonpCallback: CRC.IE6('disabling constant callback name for loadCRCConfig') ? null : 'loadCRCConfig',
				success: loadCRCConfig
			});
		}
		CRC.IE6('defined functions: IE6!');

		// Load Google Analytics library if not loaded
		if (typeof(_gat) === 'undefined') {
			$t.ajax({
				url: CRC.path + '/ga.js',
				dataType: 'script',
				cache: true,
				data: null,
				success: loadConfig
			});
		} else {
			loadConfig();
		}

	});


}


