// SegmentMaster
// version 108
// Copyright 2010 Radius Marketing, Inc.

// These variables and function are visible in the global space
var $RadiusSM; // API
var sm_;       // value - Global SegmentMaster hash
var sm_Set;    // function - Inject a value into the global SegmentMaster hash
var sm_QSVar;  // function - Extract a query string variable
var sm_End;    // function - Fire up the pixel
var sm_Pixel;  // pixel Image object

// Setup
(function() {
    var sm_dt     = new Date();
    var sm_dtnum  = new Date().getTime();
    var sm_URL    = document.URL.split("?");
    var sm_Proto  = location.protocol;
    var sm_Remote = null;

    // Object Creation
    sm_ = new Object();
    sm_.env = new Object();
    sm_.view = new Object();
    sm_.visit = new Object();
    sm_.visitor = new Object();
    sm_.conv = new Object();
    var sm_OLD = new Object();
    sm_OLD.env = new Object();
    sm_OLD.view = new Object();
    sm_OLD.visit = new Object();
    sm_OLD.visitor = new Object();
    sm_OLD.conv = new Object();

    // Environment Variables
    sm_.env.vers = '108';
    sm_.env.sess = '1800000';

    // JSON function library
    if (!this.JSON) { this.JSON = {}; } (function() { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function(key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function(a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function(value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function(text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function(a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());

    // SM Functions
    var sm_GetC = function(c_name) {
	if (document.cookie.length > 0) {
	    var c_start = document.cookie.indexOf(c_name + "=");
	    if (c_start != -1) {
		var c_start = c_start + c_name.length + 1;
		var c_end = document.cookie.indexOf(";", c_start);
		if (c_end == -1) c_end = document.cookie.length;
		var err;
		try {
		    return decodeURIComponent(document.cookie.substring(c_start, c_end));
		} catch(err) {
		    try {
			return unescape(document.cookie.substring(c_start, c_end));
		    } catch(err) {
		    }
		}
	    }
	}
	return "";
    };

    var sm_setSmid = function(sm_abbrev) {
	sm_dt = new Date();
	var sm_Y = sm_dt.getUTCFullYear().toString();
	var sm_M = (sm_dt.getUTCMonth() + 1).toString();
	var sm_D = sm_dt.getUTCDate().toString();
	var sm_H = sm_dt.getUTCHours().toString();
	var sm_m = sm_dt.getUTCMinutes().toString();
	var sm_S = sm_dt.getUTCSeconds().toString();
	var sm_ms = sm_dt.getUTCMilliseconds().toString();
	if (sm_M.length < 2) sm_M = "0" + sm_M;
	if (sm_D.length < 2) sm_D = "0" + sm_D;
	if (sm_H.length < 2) sm_H = "0" + sm_H;
	if (sm_m.length < 2) sm_m = "0" + sm_m;
	if (sm_S.length < 2) sm_S = "0" + sm_S;
	if (sm_ms.length < 3) {
	    if (sm_ms.length < 2) {
		var sm_ms = "00" + sm_ms;
	    } else {
		var sm_ms = "0" + sm_ms;
	    }
	}
	var sm_T = sm_Y + sm_M + sm_D + sm_H + sm_m + sm_S + sm_ms;
	return sm_abbrev + sm_T + Math.floor(Math.random() * 10000000);
    };

    sm_QSVar = function(name) {
	name = name.toLowerCase();
	if (sm_.view.QS) {
	    var pairs = sm_.view.QS.split("&");
	    for (var i = pairs.length - 1; i >= 0; --i) {
		var pair = pairs[i].split("=");
		if (pair[0].toLowerCase() === name) {
		    return pair[1];
		}
	    }
	}
	return null;
    };

    sm_Set = function(scope, name, value) {
	sm_[scope][name] = value ? value : (sm_OLD[scope][name] ? sm_OLD[scope][name] : '');
    };

    sm_End = function() {
	if (sm_Remote) {
	    // Do nothing;  Manually specified for debugging/qa
	} else {
    	    sm_Remote = sm_.env.abbrev + '.segmentmaster.net/sm';
	}

	var sm_smid = sm_QSVar('smid');
	if (sm_smid) {
	    sm_.visitor.smid = sm_smid;
	    if (sm_OLD.visitor.smid && (sm_.visitor.smid != sm_OLD.visitor.smid)) {
		if (!sm_.visitor.smidOLD) {
		    sm_.visitor.smidOLD = new Object;
		}
		sm_.visitor.smidOLD[sm_dt] = sm_OLD.visitor.smid;
	    }
	} else {
	    sm_.visitor.smid = sm_OLD.visitor.smid ? sm_OLD.visitor.smid : sm_setSmid(sm_.env.abbrev);
	}
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + 1825);
	var cookie = 'sm_=' + encodeURIComponent(JSON.stringify(sm_)) + ';expires=' + exdate.toGMTString() + ';path=' + sm_.env.path;
	if (sm_.env.domain) {
	    //cookie += ';domain=' + sm_.env.domain;
	}
	document.cookie = cookie;
	var sm_rnd = Math.floor(Math.random() * 10000000000000000);
	sm_Pixel = new Image();
	sm_Pixel.src = sm_Proto + '//' + sm_Remote + '/' + sm_rnd + '.gif?' + encodeURIComponent(JSON.stringify(sm_));
	// alert('sm_.visitor.smid: ' + sm_.visitor.smid);
    };

    // Cookie Handling
    var sm_tmp = sm_GetC('sm_');
    if (sm_tmp) {
	if (sm_tmp.match('vers=103')) {
	    var sm_tmp2 = sm_tmp.split("&");
	    for (var i = 0; i < sm_tmp2.length; i++) {
		var tmppair = sm_tmp2[i].split('=');
		tmppair[0] == 'dtnum' ? sm_OLD.view.dtnum = tmppair[1] : null;
		tmppair[0] == 'smid' ? sm_OLD.visitor.smid = tmppair[1] : null;
		tmppair[0] == 'vc' ? sm_OLD.visitor.visitcount = parseInt(tmppair[1]) : null;
		tmppair[0] == 'pc' ? sm_OLD.visitor.viewcount = parseInt(tmppair[1]) : null;
		tmppair[0] == 'vpc' ? sm_OLD.visit.viewcount = parseInt(tmppair[1]) : null;
		tmppair[0] == 'UserId' ? sm_OLD.visitor.UserId = tmppair[1] : null;
	    }
	} else {
	    var sm_OLD = JSON.parse(sm_tmp);
	    sm_ = JSON.parse(sm_tmp);
	}
    }

    // View Variables
    sm_.view.dt = sm_dt;
    sm_.view.dtnum = sm_dtnum;
    sm_.view.title = document.title;
    sm_.view.referrer = document.referrer;
    sm_.view.URI = sm_URL[0];
    sm_.view.QS = sm_URL[1] ? sm_URL[1] : '';
    sm_.view.duration = (!sm_OLD.view.dtnum) ? 0 : parseInt(sm_.view.dtnum) - parseInt(sm_OLD.view.dtnum);

    if (sm_.view.duration > sm_.env.sess) {
	sm_.visit.viewcount = 1;
	sm_.visit.visitstartdt = sm_.view.dt;
	sm_.visit.visitstartdtnum = sm_.view.dtnum;
	sm_.visitor.visitcount = (!sm_OLD.visitor.visitcount) ? 1 : sm_OLD.visitor.visitcount + 1;
    } else {
	sm_.visit.viewcount = (!sm_OLD.visit.viewcount) ? 1 : sm_OLD.visit.viewcount + 1;
	sm_.visit.visitstartdt = (!sm_OLD.visit.visitstartdt) ? sm_.view.dt : sm_OLD.visit.visitstartdt;
	sm_.visit.visitstartdtnum = (!sm_OLD.visit.visitstartdtnum) ? sm_.view.dtnum : sm_OLD.visit.visitstartdtnum;
	sm_.visitor.visitcount = (!sm_OLD.visitor.visitcount) ? 1 : sm_OLD.visitor.visitcount;
    }

    sm_.visit.visitduration = parseInt(sm_.view.dtnum) - parseInt(sm_.visit.visitstartdtnum);
    sm_.visitor.viewcount = (!sm_OLD.visitor.viewcount) ? 1 : sm_OLD.visitor.viewcount + 1;
    sm_.visitor.firstseen = (!sm_OLD.visitor.firstseen) ? sm_.view.dt : sm_OLD.visitor.firstseen;

    $RadiusSM = {
      'sm_':       sm_,
      'set':       sm_Set,
      'qsVar':     sm_QSVar,
      'end':       sm_End,
      'setRemote': function(remote) { sm_Remote = remote; }
    };
})();

