// Legacy track function
function __mm_track() {
  var trackers = ['URL', 'intActivityType', 'account', 'strDocGroup', 'strDocName', 'fltAmount', 'strKeywords', 'intSessionLen', 'campaignVarName', 'keywordVarName', 'cookie_ttl', 'strCampaignID'];

  var data = {};
  
  // Load all variables into data
  for (var i=0;i < trackers.length;i++) {
    var track = trackers[i];
    if (window['__mm_' + track]) {
      data[track] = window['__mm_' + track];
    } 
  }
  
  MM.track(data);
}

var MM = {
  init: function(startData) {
    //All variables that can be set by an account.  
    this.intActivityType = 0;
    this.account = 0;
    this.strDocGroup = "";
    this.strDocName = "";
    this.fltAmount = 0;
    this.strKeywords = "";
    this.intSessionLen = 1800; 

    this.campaignVarName = "cid";
    this.keywordVarName = "kw";
    this.cookie_ttl = 90;
    
    var protocol = document.location.href.match(/^https/) ? 'https' : 'http';
    this.URL = protocol + '://analytics.svmsolutions.com/svm/';

    //globals
    this.strCampaignID = "000_00_00000000";	
    
    // Load any passed in variables
    if (startData) {
      for (var prop in startData) {
        if (startData.hasOwnProperty(prop)) {
          this[prop] = startData[prop];
        }
      }
    }
  },
  
  track: function(startData) {
    this.init(startData);
    
    var data = {};
    
    // Direct set values
    data.dg = this.strDocGroup;
    data.dn = this.strDocName;
    data.dv = this.fltAmount

    // Direct track
    // Referrer
    data.rf = document.referrer;
  	
  	// Page Title
  	data.pt = document.title;
  	
  	// Page Url
  	data.pu = document.location.protocol + "//" + document.domain + document.location.pathname;

  	// Timezone
  	data.tzo = new Date().getTimezoneOffset()/60;
    
    data['1stv'] = 0;

    // Tracked Locals
  	var intClientID = 0;
  	var intTotalVisits = 0;
  	var intTotalPageViews = 0;
  	
  	// Used Locals
  	var sflg;
  	var blnCampaignCookieFound = 0;
  	var blnVisitorCookieFound = 0;

  	if (this.URL) {
  	  if (this.URL == null || this.account == null) {
  	    // Don't track if no url
  	    return;
	    }
  	}

  	//check cookie support
  	this.cookie.set('__mm_test','test');

  	if (this.cookie.get("__mm_test") != "test") {
  	  // Cookies disabled, return
  		return;
  	}

  	intClientID = (this.account == 0 ? null : this.account);

  	this.strCampaignID = this.getCID();

  	// If no campaign id in querystring, look in cookie for a real one.
  	if (this.strCampaignID == "000_00_00000000") {
  		this.strCampaignID = this.cookie.get("__mm_cid");
  		if (this.strCampaignID == null || this.strCampaignID == "" || this.strCampaignID == "NULL" ) {
  			this.strCampaignID = "000_00_00000000";
  		} else {
  			blnCampaignCookieFound = 1;
  		}
  	} 

  	//if campaign is from query string (not from cookie) then set expiry on for this.cookie_ttl number of days.
  	if (blnCampaignCookieFound != 1) {
	  this.cookie.destroy('__mm_cid');  //remove existing cookie			
  	  this.cookie.set('__mm_cid', this.strCampaignID, this.cookie_ttl);
  	}

  	//Check Visitor ID in cookie - if no visitor id, create one (new visitor); If exists, update expiration = now+2 years
  	// Get VisitorID from cookie, if one exists. Set actvitity types and flags for new or returning visitor.
  	// increment total visits and pageviews for both
  	data.vid = this.cookie.get("__mm_vid");

  	if (data.vid != null) { //found vid in cookie
  		blnVisitorCookieFound = 1;
  		this.cookie.set( "__mm_vid", data.vid, 730);
  		
  		// get total page views or set to 0
  		intTotalPageViews = this.cookie.get("__mm_ttlpv") || 0;
  		
  		// Increment
  		intTotalPageViews = parseInt(intTotalPageViews, 10) + 1;
  		
  		// Save updated total page views
  		this.cookie.set( "__mm_ttlpv", intTotalPageViews, 730);
  		if (this.intActivityType == 0) {
  		  this.intActivityType = 2;  //returning visitor and no explicit activity type set by account. 
		  }
  	} else {	//no vid. 1st visit. create cookie. update expiration = now+2 years
  		blnVisitorCookieFound = 0;
  		data.vid = this.uuid();
  		this.cookie.set( "__mm_vid", data.vid, 730);
  		if (this.intActivityType == 0) {
  		  this.intActivityType = 1;  //first visitor and no explicit activity type set by account.
		  }
  		data['1stv'] = 1;
  		intTotalPageViews = 1;
  		this.cookie.set( "__mm_ttlpv", intTotalPageViews, 730);
    }	

  	// Check Session ID and Session Flag cookie - if no Session Flag or no session id, create new session id and set Session flag to 1). 
  	// If session id exists, reset it to expire in SessionLen time
  	// incrmemenr
  	data.sid = this.cookie.get("__mm_sid");
  	sflg = this.cookie.get("__mm_sflg");

  	if (data.sid == null || sflg == null) {
  		data.sid = this.uuid();
  		sflg = 1;
  		intTotalVisits = this.cookie.get("__mm_ttlv");	
  		if (intTotalVisits == null) intTotalVisits = 0;
  		// Increment
  		intTotalVisits = parseInt(intTotalVisits, 10) + 1;
  		this.cookie.set( "__mm_ttlv", intTotalVisits, 730);
  		this.cookie.set( "__mm_sid", data.sid, (this.intSessionLen / 24 / 60 / 60));
  		this.cookie.set( "__mm_sflg", sflg);
  	} else {
  		this.cookie.set( "__mm_sid", data.sid, (this.intSessionLen / 24 / 60 / 60));
  		intTotalVisits = this.cookie.get("__mm_ttlv");
  	}
  	
  	data['S'] = 1;
  	data.at = this.intActivityType;
  	data.cid = this.strCampaignID;
  	data.kw = this.getKW();
  	
  	// Cache Buster
  	data.cb = Math.random();

    // From locals
  	data.clid = intClientID;
  	data.ttlv = intTotalVisits;
	data.ttlpv = intTotalPageViews;
  	
  	// Create tracking url
  	var trackingUrl = this.makeTrackUrl(data);
  	
  	// Call the server at the tracking url
  	this.trackURL(trackingUrl);
  },
  
  makeTrackUrl: function(data) {
    var params = [];
    
    for (var name in data) {
      if (data.hasOwnProperty(name)) {
        params.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
      }
    }
    
    return this.URL +	"mmtrack.php?" + params.join('&');
  },
  
  // Append a script tag to the head's dom
  trackURL: function(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  },
  
  
  getCID: function() {
  	var qString = unescape(document.location.search.substring(1));
  	var pairs = qString.split(/\&/);
  	for (var i in pairs) {
  		var nameVal = pairs[i].split(/\=/);
  		if (nameVal[0] == this.campaignVarName) {
  			return nameVal[1];
  		}
  	}
  	return "000_00_00000000";
  },
  
  
  getKW: function() {
    return this.pageArgument(this.keywordVarName);
  },
  
  pageArgument: function(name) {
    if (typeof(params) === 'undefined') {
      // Only parse once
      var params = {};
      var parts = document.location.search.substring(1).split(/\&/);
    
      for (var i=0;i < parts.length;i++) {
        var part = parts[i];
      
        var name_value = part.split(/\=/);
      
        params[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
      }
    }
    
    if (params.hasOwnProperty(name)) {
      return params[name];
    } else {
      return null;
    }
  },
  
  
  random: function() {
      return Math.round(Math.random() * 255).toString(16) + Math.round(Math.random() * 255).toString(16);	
  },

  uuid: function() {
  	var part1 = this.random();
  	part1 = this.lpad(part1,"0",4);

  	var part2 = this.random();
  	part2 = this.lpad(part2,"0",4);

  	var part3 = this.random();
  	part3 = this.lpad(part3,"0",4);

  	var part4 = this.random();
  	part4 = this.lpad(part4,"0",4);

  	var part5 = new Date().getTime().toString(16).substring(0,14);
  	part5 = this.lpad(part5,"0",11);

  	return part1 + "-" + part2 + "-" + part3 + "-" + part4 + part5;
  },
  
  lpad: function(padString, padChar, length) {
  	var str = padString;
      while (str.length < length)
          str = padChar + str;
      return str;
  },
  
  // Cookie object with get/set/destroy methods
  cookie: {
    set: function(name,value,days){
      var today = new Date();
      var expire = new Date();
      if (days==null || days==0) days=1;
      expire.setTime(today.getTime() + 3600000*24*days);
      document.cookie = name + "=" + escape(value) + ";expires="+expire.toGMTString() + ";path=/";
    },

    get: function(name) {
      var reg = new RegExp(name + '=([^;]+)', 'i');
      var result = reg.exec(document.cookie);

      if (result && result[1]) {
        return unescape(result[1]);
      } else {
        return null;
      }
    },

    destroy: function(name) {
      document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT" + ";path=/";
    }
  }
};

