﻿/// <reference path="jquery-1.5.0-vsdoc.js" />

//   option            default     note
//   ------            -------     ----
//   allowedRels       []          if present only rel= matching the array will be parsed as virtual pages otherwise all rel= parsed 
//   allowHash         true        sets _gaq._setAllowHash
//   allowLocalhost    false       set true to allow calls from localhost to be sent to GA (of use primarily to developers)    
//   cookiePath        "/"         sets _gaq._setCookiePath
//   debug             false       set true to enables the debug version of GA with verbose console logging
//   pageUrl           ""          use to override window.location.pathname with a custom value when the host page is tracked
//   trackOwnDomain    false       set to true to allow relative links to be tracked in the onclick event
//   ua                ""          REQUIRED if you want to actually see your values in Google Analytics

(function ($) {
   var helpers = {
      bindPageTrack: function () {
         var $this = $(this);
         $this.click(function (e) {
            _gaq.push(["_trackPageview", $this[0].pathname]);
            //e.preventDefault();
         });
      },
      bindPageTrackVirtual: function () {
         var $this = $(this);
         $this.click(function (e) {
            //e.preventDefault();

            _gaq.push(["_trackPageview", $this.attr("rel") + "/" + $this[0].href]);
            //e.preventDefault();
         });
      }
   }

   var methods = {
      init: function (userOptions) {

         var options = {
            allowedRels: [],
            allowHash: true,
            allowLocalhost: false,
            cookiePath: "/",
            debug: false,
            pageUrl: "",
            trackOwnDomain: false,
            ua: ""
         };

         if (typeof ($.fn.tbwaga.options == "undefined")) {
            $.fn.tbwaga.options = $.extend(options, userOptions || {});
         }

         /* Create the Google ga.js script tag IF _gaq does not already exist. No sense in calling this multiple times
         if say $("a").tbwaga() was executed */
         if (typeof (_gaq) === "undefined") {

            // Set _gaq as a global variable (just how Google likes it)
            _gaq = [];

            // Setup GA properties for this page
            _gaq.push(["_setAccount", options.ua]);
            _gaq.push(["_setAllowHash", options.allowHash]);
            _gaq.push(["_setCookiePath", options.cookiePath]);

            // localhost is mostly used by developers and testers so let's not block GA for them if we don't want to
            if (options.allowLocalhost && window.location.hostname == "localhost") {
               _gaq.push(["_setDomainName", "none"]);
            }

            // Track the current page IF the html element does NOT have the .tbwaga-notrack class
            if (!$("html").hasClass("tbwaga-notrack")) {
               // If a pageUrl was not specified in the constructor then obtain from window.location (might be / instead of /filename.aspx)
               if (options.pageUrl == "") {
                  options.pageUrl = window.location.pathname;
               }
               _gaq.push(["_trackPageview", options.pageUrl]);
            }

            // Google hosts an SSL and non-ssl version of the script on different subdomains
            var protocolPrefix = "http://wwww";
            if (window.location.protocol.toLowerCase() == "http") {
               protocolPrefix = "https://ssl-";
            }

            // Google offers a debug version of the ga script that we use if options.debug == true. Call the correct version accounting for Secure Sockets Layer
            if (options.debug) {
               $.getScript((("https:" == document.location.protocol) ? "https://ssl." : "http://www.") + "google-analytics.com/u/ga_debug.js");
            }
            else {
               $.getScript((("https:" == document.location.protocol) ? "https://ssl." : "http://www.") + "google-analytics.com/ga.js");
            }
         }

         /* Iterate and check each <a> is:
         - allowed (does not have .tbwaga-notrack
         - if it has a rel then it's virtual tracking only if rel in allowable list or no list has been specified at all*/
         return this.each(function () {
            var $this = $(this);
            if (!$this.hasClass("tbwaga-notrack") && (options.trackOwnDomain || $this[0].hostname != location.hostname)) {
               if ($this.attr("rel").length > 0 && (($.inArray($this.attr("rel"), options.allowedRels) > -1) || options.allowedRels.length == 0)) {
                  helpers.bindPageTrackVirtual.apply($this);
               }
               else {
                  helpers.bindPageTrack.apply($this);
               }
            }
         });
      },

      options: function () {
         return $.fn.tbwaga.options;
      },

      trackPage: function () {
         var options = $.fn.tbwaga.options;

         return this.each(function () {
            var $this = $(this);
            if (!$this.hasClass("tbwaga-notrack")) {
               helpers.bindPageTrack.apply(this);
            }
         });
      },

      trackPageVirtual: function () {
         var options = $.fn.tbwaga.options;

         return this.each(function () {
            var $this = $(this);
            if (!$this.hasClass("tbwaga-notrack")) {
               helpers.bindPageTrackVirtual.apply(this);
            }
         });
      },

      trackEvent: function (eventType, category, action, opt_label, opt_value) {
         var options = $.fn.tbwaga.options;

         return this.each(function () {
            var $this = $(this);
            $this.bind(eventType, function () {
               _gaq.push(["_trackEvent", category, action, opt_label, opt_value]);
            });
         });
      }
   };

   $.fn.tbwaga = function (method) {
      if (methods[method]) {
         return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
      }
      else if (typeof method === "object" || !method) {
         return methods.init.apply(this, arguments);
      }
      else {
         $.error("Method " + method + " does not exist on jQuery.tbwaga");
      }
   };

})(jQuery);
