Add analytics
[bus.git] / busui / owa / modules / base / js / owa.tracker.js
blob:a/busui/owa/modules/base/js/owa.tracker.js -> blob:b/busui/owa/modules/base/js/owa.tracker.js
  //
  // Open Web Analytics - An Open Source Web Analytics Framework
  //
  // Copyright 2006 Peter Adams. All rights reserved.
  //
  // Licensed under GPL v2.0 http://www.gnu.org/copyleft/gpl.html
  //
  // Unless required by applicable law or agreed to in writing, software
  // distributed under the License is distributed on an "AS IS" BASIS,
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  // See the License for the specific language governing permissions and
  // limitations under the License.
  //
  // $Id$
  //
   
  /**
  * OWA Generic Event Object
  *
  * @author Peter Adams <peter@openwebanalytics.com>
  * @copyright Copyright &copy; 2006 Peter Adams <peter@openwebanalytics.com>
  * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0
  * @category owa
  * @package owa
  * @version $Revision$
  * @since owa 1.2.1
  */
  OWA.event = function() {
   
  this.properties = new Object();
  this.set('timestamp', OWA.util.getCurrentUnixTimestamp() );
  }
   
  OWA.event.prototype = {
   
  id : '',
   
  siteId : '',
   
  properties : {},
   
  get : function(name) {
   
  if ( this.properties.hasOwnProperty(name) ) {
   
  return this.properties[name];
  }
  },
   
  set : function(name, value) {
   
  this.properties[name] = value;
  },
   
  setEventType : function(event_type) {
   
  this.set("event_type", event_type);
  },
   
  getProperties : function() {
   
  return this.properties;
  },
   
  merge : function(properties) {
   
  for(param in properties) {
   
  if (properties.hasOwnProperty(param)) {
   
  this.set(param, properties[param]);
  }
  }
  }
  }
   
  OWA.commandQueue = function() {
   
  OWA.debug('Command Queue object created');
  }
   
  OWA.commandQueue.prototype = {
  asyncCmds: '',
  push : function (cmd) {
   
  //alert(func[0]);
  var args = Array.prototype.slice.call(cmd, 1);
  //alert(args);
   
  var obj_name = '';
  var method = '';
  var check = OWA.util.strpos( cmd[0], '.' );
   
  if ( ! check ) {
  obj_name = 'OWATracker';
  method = cmd[0];
  } else {
  var parts = cmd[0].split( '.' );
  obj_name = parts[0];
  method = parts[1];
  }
   
  OWA.debug('cmd queue object name %s', obj_name);
  OWA.debug('cmd queue object method name %s', method);
   
  // is OWATracker created?
  if ( typeof window[obj_name] == "undefined" ) {
  OWA.debug('making global object named: %s', obj_name);
  window[obj_name] = new OWA.tracker( { globalObjectName: obj_name } );
  }
   
  window[obj_name][method].apply(window[obj_name], args);
  },
   
  loadCmds: function(cmds) {
   
  this.asyncCmds = cmds;
  },
   
  process: function() {
   
  for (var i=0; i < this.asyncCmds.length;i++) {
  this.push(this.asyncCmds[i]);
  }
  }
  };
   
  /**
  * Javascript Tracker Object
  *
  * @author Peter Adams <peter@openwebanalytics.com>
  * @copyright Copyright &copy; 2006 Peter Adams <peter@openwebanalytics.com>
  * @license http://www.gnu.org/copyleft/gpl.html GPL v2.0
  * @category owa
  * @package owa
  * @version $Revision$
  * @since owa 1.2.1
  */
  OWA.tracker = function( options ) {
   
  //this.setDebug(true);
  // set start time
  this.startTime = this.getTimestamp();
   
  // Configuration options
  this.options = {
  logClicks: true,
  logPage: true,
  logMovement: false,
  encodeProperties: false,
  movementInterval: 100,
  logDomStreamPercentage: 100,
  domstreamLoggingInterval: 3000,
  domstreamEventThreshold: 10,
  maxPriorCampaigns: 5,
  campaignAttributionWindow: 60,
  trafficAttributionMode: 'direct',
  sessionLength: 1800,
  thirdParty: false,
  cookie_domain: false,
  campaignKeys: [
  { public: 'owa_medium', private: 'md', full: 'medium' },
  { public: 'owa_campaign', private: 'cn', full: 'campaign' },
  { public: 'owa_source', private: 'sr', full: 'source' },
  { public: 'owa_search_terms', private: 'tr', full: 'search_terms' },
  { public: 'owa_ad', private: 'ad', full: 'ad' },
  { public: 'owa_ad_type', private: 'at', full: 'ad_type' } ],
  logger_endpoint: '',
  api_endpoint: ''
   
  };
   
  // Endpoint URL of log service. needed for backwards compatability with old tags
  var endpoint = window.owa_baseUrl || OWA.config.baseUrl ;
  if (endpoint) {
  this.setEndpoint(endpoint);
  } else {
  OWA.debug('no global endpoint url found.');
  }
   
  this.endpoint = OWA.config.baseUrl;
  // Active status of tracker
  this.active = true;
   
  if ( options ) {
   
  for (opt in options) {
   
  this.options[opt] = options[opt];
  }
  }
   
  // private vars
  this.ecommerce_transaction = '',
  this.isClickTrackingEnabled = false;
   
  // check to se if an overlay session is active
  this.checkForOverlaySession();
   
  // set default page properties
  this.page = new OWA.event();
  this.page.set('page_url', document.URL);
  this.setPageTitle(document.title);
  this.page.set("referer", document.referrer);
  this.page.set('timestamp', this.startTime);
   
  // merge page properties from global owa_params object
  if (typeof owa_params != 'undefined') {
  // merge page params from the global object if it exists
  if (owa_params.length > 0) {
  this.page.merge(owa_params);
  }
  }
  }
   
  OWA.tracker.prototype = {
   
  id : '',
  // site id
  siteId : '',
  // ???
  init: 0,
  // flag to tell if client state has been set
  stateInit: false,
  // properties that should be added to all events
  globalEventProperties: {},
  // state sores that can be shared across sites
  sharableStateStores: ['v', 's', 'c'],
  // Time When tracker is loaded
  startTime: null,
  // time when tracker is unloaded
  endTime: null,
  // campaign state holder
  campaignState : [],
  // flag for new campaign status
  isNewCampaign: false,
  // flag for new session status
  isNewSessionFlag: false,
  // flag for whether or not traffic has been attributed
  isTrafficAttributed: false,
  cookie_names: ['owa_s', 'owa_v', 'owa_c'],
  linkedStateSet: false,
  hashCookiesToDomain: true,
  /**
  * GET params parsed from URL
  */
  urlParams: {},
  /**
  * DOM stream Event Binding Methods
  */
  streamBindings : ['bindMovementEvents', 'bindScrollEvents','bindKeypressEvents', 'bindClickEvents'],
  /**
  * Page view event
  */
  page : '',
  /**
  * Latest click event
  */
  click : '',
  /**
  * Domstream event
  */
  domstream : '',
  /**
  * Latest Movement Event
  */
  movement : '',
  /**
  * Latest Keystroke Event
  */
  keystroke : '',
  /**
  * Latest Hover Event
  */
  hover : '',
   
  last_event : '',
  last_movement : '',
  /**
  * DOM Stream Event Queue
  */
  event_queue : [],
  player: '',
  overlay: '',
   
  setDebug : function(bool) {
   
  OWA.setSetting('debug', bool);
  },
   
  checkForLinkedState : function() {
   
  var ls = this.getUrlParam('owa_state');
   
  if ( ! ls ) {
  ls = this.getAnchorParam('owa_state');
  }
   
  if ( ls ) {
  OWA.debug('Shared OWA state detected...');
   
  ls = OWA.util.base64_decode(OWA.util.urldecode(ls));
  //ls = OWA.util.trim(ls, '\u0000');
  //ls = OWA.util.trim(ls, '\u0000');
  OWA.debug('linked state: %s', ls);
   
  var state = ls.split('.');
  //var state = OWA.util.explode('.', ls);
  OWA.debug('linked state: %s', JSON.stringify(state));
  if ( state ) {
   
  for (var i=0; state.length > i; i++) {
   
  var pair = state[i].split('=');
  OWA.debug('pair: %s', pair);
  // add cookie domain hash for current cookie domain
  var value = OWA.util.urldecode(pair[1]);
  OWA.debug('pair: %s', value);
  //OWA.debug('about to decode shared link state value: %s', value);
  decodedvalue = OWA.util.decodeCookieValue(value);
  //OWA.debug('decoded shared link state value: %s', JSON.stringify(decodedvalue));
  var format = OWA.util.getCookieValueFormat(value);
  //OWA.debug('format of decoded shared state value: %s', format);
  decodedvalue.cdh = OWA.util.getCookieDomainHash( this.getCookieDomain() );
   
  OWA.replaceState( pair[0], decodedvalue, true, format );
  }
  }
  }
   
  this.linkedStateSet = true;
  },
   
  /**
  * Shares User State cross domains using GET string
  *
  * gets cookies and concatenates them together using:
  * name1=encoded_value1.name2=encoded_value2
  * then base64 encodes the entire string and appends it
  * to an href
  *
  * @param url string
  */
  shareStateByLink : function(url) {
   
  OWA.debug( 'href of link: '+ url );
  if ( url ) {
   
  var state = this.createSharedStateValue();
   
  //check to see if we can just stick this on the anchor
  var anchor = this.getUrlAnchorValue();
  if ( ! anchor ) {
   
  OWA.debug('shared state: %s', state);
  document.location.href = url + '#owa_state.' + state ;
   
  // if not then we need ot insert it into GET params
  } else {
   
  }
  }
  },
   
  createSharedStateValue : function() {
   
  var state = '';
   
  for (var i=0; this.sharableStateStores.length > i;i++) {
  var value = OWA.getState( this.sharableStateStores[i] );
  value = OWA.util.encodeJsonForCookie(value, OWA.getStateStoreFormat(this.sharableStateStores[i]));
   
  if (value) {
  state += OWA.util.sprintf( '%s=%s', this.sharableStateStores[i], OWA.util.urlEncode(value) );
  if ( this.sharableStateStores.length != ( i + 1) ) {
  state += '.';
  }
  }
  }
   
  // base64 for transport
  if ( state ) {
  OWA.debug('linked state to send: %s', state);
   
  state = OWA.util.base64_encode(state);
  state = OWA.util.urlEncode(state);
  return state;
  }
  },
   
  shareShareByPost : function (form) {
   
  var state = this.createSharedStateValue();
  form.action += '#owa_state.' + state;
  form.submit();