/**
 * EventTrackingController
 * 
 * Uses Google Analytics to track events.
 * 
 * @author Daniel Holden
 */
var EventTrackingController = new Class({
  
  /**
   * Holds the current trackers that are configured
   */
  trackers: [],
  
  
  /**
   * Constructor. Initialize Event Tracking
   * 
   * @param trackers An optional array of tracker objects
   */
  initialize: function(trackers)
  {
    // only continue if the _gaq object has been set, usually defined by Google Analytics
    if(typeof(_gaq) == "undefined")
      return;
    
    // assign trackers, if we have any
    if(trackers !== undefined)
      this.trackers = trackers;
    
    // init trackers
    this._initializeTrackers();
  },
  
  
  /**
   * Rrefresh the trackers. This will initialize any new trackers that have been added
   */
  refresh: function()
  {
    this._initializeTrackers();
  },
  
  
  /**
   * Add a tracker to the array fo trackers
   * 
   * @param tracker The tracker object to add
   */
  addTracker: function(tracker)
  {
    this.trackers.push(tracker);
    this.refresh();
  },
  
  
  /**
   * Initialize trackers.
   */
  _initializeTrackers: function()
  {
    // if no trackers have been specified, return.
    if(this.trackers === undefined || this.trackers.length == 0)
      return;
    
    // setup an array to store initlized trackers - we dont want to init twice
    if(this._initTrackers === undefined)
      this._initTrackers = [];
    
    // loop through each tracker and apply the required functionality
    this.trackers.each(function(tracker)
    {
      if(!this._trackerIsInitialized(tracker))
      {
        if(tracker.trackEvents !== undefined)
          tracker.trackEvents();
        this._initTrackers.push(tracker);
      }
    }.pbind(this));
  },
  
  
  /**
   * Checks whether the passed in tracker has already been initialized
   * 
   * @param tracker The tracker object
   * @return bool
   */
  _trackerIsInitialized: function(tracker)
  {
    // if initialize hasn't been called, auto-return false
    if(this._initTrackers === undefined)
      return false;
    
    return this._initTrackers.contains(tracker);
  }
  
});

// create a new controller on dom ready
var eventTrackingController = false;
window.addEvent('domready', function()
{
  eventTrackingController = new EventTrackingController();
  window.fireEvent('taipanEventTracker');
});
