/**
 * Enable event-tracking on selected elements by inserting a 'ga_track' class.
 * Requires jQuery.
 */

/**
 * STRING class_begins(OBJECT the_element, STRING the_string)
 * If the_element has a class that begins with the_string, class_begins returns the remainder of that class.
 * If the_element does not have a class that begins with the_string, class_begins returns false.
 */
function class_begins(the_element, the_string) {
  var classes = the_element.className.split(" ");
  for (var i=0; i<classes.length; i++) {
      var this_class = classes[i];
      if (this_class.indexOf(the_string) == 0) {
          var j=classes[i];
          var last = j.substring(the_string.length);
          return last;
      };
  }
  return false;
}

/**
 * Enable event tracking on all elements with a ga_track class.
 * The element to be event tracked can have three additional event tracking related classes:
 *  - ga_category_<string>
 *  - ga_action_<string>
 *  - ga_label_<string>
 * ...where <string> is any valid string.
 */
$(document).ready(function(){        
    $(".ga_track").click(function(){
        var category = (class_begins(this, 'ga_category_')) ? class_begins(this, 'ga_category_') : 'undefined';
        var action = (class_begins(this, 'ga_action_')) ? class_begins(this, 'ga_action_') : 'Click';
        
        if (class_begins(this, 'ga_label_')) {
            var label = class_begins(this, 'ga_label_');
        } else {
            if (typeof $(this).attr('href') == 'undefined') {
                var label = "'" + $(this)[0].nodeName.toUpperCase() + "' element at " + window.location;
            } else {
                var label = "Link to: " + $(this).attr('href');
            }
        }

        _gaq.push(['_trackEvent', category, action, label]);
        
    });
});

