if (!window.wb) {
    window.wb = {};
}

var _gaq = null; // this should be in global namespace?

wb.analytics = {
    
    /**
     * This is responsible for the page tracking through our site.
     *
     * @param Page (optional) The page you wish to log if you would like to be specific, otherwise current URL
     */
    init: function(page) {
        var env = wb.util.environment();
        var code = null;
        switch (env) {
            case 'dev': code = "UA-9393083-6"; break;
            case 'qa': code = "UA-9393083-5"; break;
            case 'production': code = "UA-9393083-4"; break;
            default: null; break;
        }
        
        if (!code) {
            if(window.console) {
                console.warn("disabled GA support");
            }
            return;
        } 

        // include the external GA script in try/catch to play nice
        try {
            _gaq = _gaq || [];
            _gaq.push(['_setAccount', code]);
            _gaq.push(['_trackPageview']);
            
            (function() {
              var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
              ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
              (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
            })();

        } catch(e) {
            if(window.console) {
                console.log('Failed to load Google Analytics:' + e);
            }
        }
    },
    trackPage: function(page){  
        if (!_gaq) return;
        try {
            _gaq.push(['_trackPageview', page]);
        } catch(e) {
            if (console) {
                console.log('Problem while calling urchinTracker for Google Analytics:' + e);
            }
        }
    },
    trackEvent: function(category, action, label) {
        if (!_gaq) return;
        try {
            _gaq.push(['_trackEvent', category, action, label]);
        } catch(e) {
            if (console) {
                console.log('Problem while calling urchinTracker for Google Analytics:' + e);
            }
        }           
    }
};

// now start the thing up
wb.analytics.init();
