var _gaq = _gaq || [];
var TP_GA = {
  setup: function(){
    if (window.jwplayer != undefined) {
      /** Attach to JW Player **/
      jwplayer().onReady(function () {
        jQuery(".botrplayer").each(function(index){
          new TP_GA.JWPlayerTracker(
            jwplayer(jQuery(this).children("embed").attr("id"))
          );
        });
        jQuery(".singlefile").each(function(index){
          new TP_GA.JWPlayerTracker(
            jwplayer(jQuery(this).find("object").attr("id"))
          );
        });
      });
    }
    if (window.flowplayer != undefined) {
      /** Attach to FlowPlayer **/
      flowplayer("*").each(function() {
        new TP_GA.FlowPlayerTracker(this);
      });
    }
    /** Track PDF Download */ 
    jQuery("a[href]").each(function (index) {
      if (jQuery(this).attr('href').indexOf(".pdf")>0) {
        jQuery(this).click(function() {
          _gaq.push(['_trackEvent', 'Download', 'PDF', jQuery(this).attr("href")]);
        })
      }
    })
    /** Capture Error message on the Form */
    jQuery("form.userForm .formError").each(function(index){
      var formid = "Form ID: " + jQuery(this).parents("form.userForm").find('input[type="hidden"][name="form[formId]"]').val();
      var value = jQuery(this).attr("id") + ": " + jQuery(this).html();
      _gaq.push(['_trackEvent', 'Form', 'Submit Error', formid, formid + " - " + value]);
    });
    /** Capture Error Message on the Site */
    if (jQuery("#system-message .message").size() > 0) {
      var value = "";
      jQuery("#system-message .message ul li").each(function (index) {
        value += jQuery(this).html() + " ";
      });
      _gaq.push(['_trackEvent', 'Message', "Error", value]);
    }
    /** Track the time to fill a form */
    jQuery("form.userForm").each(function (index) {
      new TP_GA.FormFillerTracker(this);
    });
  }
};

/**
 * Class to record time take to fill in the a form.
 */
TP_GA.FormFillerTracker = function(form) {
  this.form = form;
  var that = this;
  jQuery(form).find("input", "select").change(function(){
    that.startTimer.call(that)
  });
  jQuery(form).submit(function(){
    that.stopTimer.call(that)
  });
  this.timerStarted = false;
  this.startTime = 0;
  this.stopTime = 0;
};

TP_GA.FormFillerTracker.prototype = {
  stopTimer: function() {
    if (this.timerStarted) {
      this.stopTime = (new Date()).getTime(); 
      var timeTaken = (this.stopTime - this.startTime) / 1000;
      var formid = "Form ID: " + jQuery(this.form).find('input[type="hidden"][name="form[formId]"]').val();
      _gaq.push(['_trackEvent', 'Form', 'Time Required' ,formid, timeTaken]);
    }
  },
  startTimer: function() {
    if (this.timerStarted == false) {
      this.timerStarted = true;
      this.startTime = (new Date()).getTime();
    }
  }
};

/**
 * JW Player Tracking Server.
 * This class will track JW Player on play, pause, fullscreen, mute and complete.
 * @param {Object} player
 */
TP_GA.JWPlayerTracker = function(player){
  this.player = player;
  var that = this;
  player.onFullscreen(function(status){
    that.onFullScreen.call(that, status);
  });
  player.onMute(function(status){
    that.onMute.call(that, status);
  });
  player.onPlay(function(status){
    that.onPlay.call(that, status);
  });
  player.onPause(function(status){
    that.onPause.call(that, status);
  });
  player.onComplete(function(){
    that.onComplete.call(that);
  });
  this.status = {
    play: false,
    pause: false,
    fullscreen: false,
    mute: false,
    complete: false
  };
};

TP_GA.JWPlayerTracker.prototype = {
  onComplete: function() {
    if (!this.status.complete) {
      _gaq.push(['_trackEvent', 'Video', "Complete", this.getPlayInfo()]);
      this.status.complete = true;
    }
  },
  onFullScreen: function(fullScreenState){
    if (fullScreenState && !this.status.fullscreen) {
      _gaq.push(['_trackEvent', 'Video', "Full Screen", this.getPlayInfo()]);
      this.status.fullscreen = true;
    }
  },
  onMute: function(muteState){
    if (muteState && !this.status.mute) {
      _gaq.push(['_trackEvent', 'Video', "Mute", this.getPlayInfo()]);
      this.status.mute = true;
    }
  },
  onPlay: function(oldStatus){
    if (oldStatus.oldstate == "PAUSED" && !this.status.play) {
      _gaq.push(['_trackEvent', 'Video', "Play", this.getPlayInfo()]);
      this.status.play = true;
    }
  },
  onPause: function(oldStatus){
    if (oldStatus.oldstate == "PLAYING" && !this.status.pause) {
      _gaq.push(['_trackEvent', 'Video', "Pause", this.getPlayInfo()]);
      this.status.pause = true;
    }
  },
  getPlayInfo: function(){
    return this.player.getPlaylistItem().title + ":" + this.player.getPosition();
  }
};

TP_GA.FlowPlayerTracker = function(player) {
  this.player = player;
  var that = this;
  player.onFullscreen(function(){
    that.onFullScreen.call(that);
  });
  player.onMute(function(){
    that.onMute.call(that);
  });
  player.onClipAdd(function(clip, index){
    that.onClipAdd.call(that, clip, index);
  });
  player.onError(function(errorCode, errorMsg){
    that.onError.call(that, errorCode, errorMsg);
  });
  jQuery.each(player.getPlaylist(), function (index, p) {
    that.onClipAdd.call(that, p, index);
  });
};

TP_GA.FlowPlayerTracker.prototype = {
  onFullScreen: function(){
    _gaq.push(['_trackEvent', 'Video', "Full Screen", this.getPlayInfo()]);
  },
  onMute: function(){
    _gaq.push(['_trackEvent', 'Video', "Mute", this.getPlayInfo()]);
  },
  onClipAdd: function(clip, index) {
    var that = this;
    clip.onStart(function() {
      _gaq.push(['_trackEvent', 'Video', "Play", that.getPlayInfo()]);
    });
    clip.onPause(function() {
      _gaq.push(['_trackEvent', 'Video', "Pause", that.getPlayInfo()]);
    });
    clip.onBufferEmpty(function() {
      _gaq.push(['_trackEvent', 'Video', "Buffer Empty", that.getPlayInfo()]);
    });
    clip.onFinish(function() {
      _gaq.push(['_trackEvent', 'Video', "Complete", that.getPlayInfo()]);
    });
  },
  onError: function(errorCode, errorMsg) {
    _gaq.push(['_trackEvent', 'Video', "Error: "+errorMsg, this.getPlayInfo()]);
  },
  getPlayInfo: function(){
    return this.player.getClip().completeUrl + ":" + this.player.getTime();
  }
};

window.addEvent("domready", function(){
  TP_GA.setup();
});
