/* DO NOT REMOVE COMMENT DELIMITER: This file can be parsed as PHP or JavaScript
<?php
header('Content-Type: application/x-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 */

if (typeof(CRC) === 'undefined') {
	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 */
 
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);

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

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

		// 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) {
			// 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
			window.custom2 = trackers.getLinkerUrl('').replace(/&/g, '%26').replace(/_/g, '%5F') + '%26domain=' + CRC.domain;
			window.mm_c = defaultCampaign;
			if (typeof(getNumber) === 'undefined') {
				$t.getScript('//www.mongoosemetrics.com/jsfiles/js-correlation/mm-getvar.js',
					function() {
						$t.getScript('//www.mongoosemetrics.com/jsfiles/js-correlation/mm-control.php?' + unescape(mm_variables),
							function() {
							}
						);
					}
				);
			}
		}



		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() {
					$t.getScript('//thesearchagency.net/mongoose-setup.js',
						function() {
							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("tsa1v686");
							// create global variable used by Mongoose
							window.custom3 = "&ckwid=" + val_refcd + "&tsacr=" + val_tsacr + "&myvid=" + val_visitid;	
							$t(window).trigger('tsa.ready');
						}
					);
				}
			);
			// Record livechat requests as conversions with TSA
			if (typeof(CRC.tsa.conversionWayId) != 'undefined') {
				$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 + '&productid=onlinechat">');
				});
			}
		}

		// load site-specific configuration
		var loadConfig = function() {
			var configURL = CRC.configPath+ '/config.js';
			if (typeof(CRC.domain) != 'undefined') {
				configURL += '?domain=' + CRC.domain;
			}
			$t.ajax({
				url: configURL,
				dataType: 'jsonp',
				cache: true,
				jsonpCallback: 'loadCRCConfig',
				success: function(data) {
					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;

					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);
					}

					loadTjs();
				}
			});
		}

		// 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();
		}
	});


}
