/*** 
 * WiderFunnel - GWO Tracking and Goal script functions for A/B Tests
 * Copyright 2011, Stephen Liu 
 * WiderFunnel Marketing Optimization 
 * Website: http://www.widerfunnel.com
 * 
 * Requires widerfunnel.lib.js  
 * Date: 2011-11-09
 **/


// Initialize globals
var _gaq = _gaq || [],
    _wf = _wf || {};

if (typeof _wf._lib_client === 'undefined') {   

    var __WF_DOMAIN = ''; // production
        __WF_DOCKETTE = 'HOT002-FE1';

    _udn = __WF_DOMAIN;
    
    // Keep in global
    function utmx_section(){}
    function utmx(){}

    _wf._lib_client = '2.0.3a_wf';
    _wf.runTest = true; 
    _wf.redirect = location.search.indexOf("wfvar=") === -1;        
    
    // Overriden by GWO:
    _wf.redirectParam = 'ctrl.php'; 
    _wf.varName = 'ctrl';       
    _wf.swapbox = {};

    // 
    _wf._ExperimentConfig = {    
        defaultGa : 'UA-718928-1', // allpopart.com    
        wfgwo : 'UA-17186630-1',
        domain : __WF_DOMAIN,
        allowLinker : '', // use boolean value
        allowHash : '', // use boolean value
        cookieKey : __WF_DOCKETTE,
        dockette : __WF_DOCKETTE,
        cvslot : 1, // use slots 1 to 5
        k : '2991469943',        
        setCampTermKey : "",
        enableVPTracking : true, // enable custom var and vp tracking, this will cause extra pageviews!
        enablePreviewCookie : false,
        async : true // async tracking
    };  

    // Experiment State Info, readonly info.
    _wf._ExperimentInfo = {        
        isGWOLibLoaded : false,
        isGALibLoaded : !(typeof _gat === 'undefined' || !_gat || !_gat._getTracker),
        isGoalTracked : false,
        isVariationTracked : false,
        isLive : "",
        isPreview : "",
        combinationCookie : _wf.readCookie(_wf._ExperimentConfig.cookieKey)
    };

    _wf.getVPPattern = function() {
        var varName = _wf.readCookie(_wf._ExperimentConfig.cookieKey);
        if (_wf._ExperimentConfig.enableVPTracking && varName !== null) {            
            return __WF_DOCKETTE + "/" + varName;
        } else {
            return "";
        }        
    };    

    // callback(data) - called if experiment is active and before redirect.
    // requires siteop.js
    _wf.runABTest = function(opts) {    
        opts = opts || {};
        opts = {
            callback : opts.callback || null          
        };
        
        var isLive = _wf._ExperimentInfo.isLive = utmx("live"),  
            isPreview = _wf._ExperimentInfo.isPreview = utmx("preview");           
                
                
        if (_wf.runTest && _wf.redirect) {        
            if (isLive || isPreview) {          
                if (isPreview && _wf._ExperimentConfig.enablePreviewCookie)
                    _wf.setExperimentCookie({value:_wf.varName});
                else if (isLive)
                    _wf.setExperimentCookie({value:_wf.varName});
                
                if (opts.callback) {
                    opts.callback(_wf.varName);
                }
                _wf.controlPageRedirect(_wf.redirectParam);            
            } else if (typeof _wf.varName === 'undefined' || _wf.varName !== 'ctrl') {                    
                if (isPreview && opts.enablePreviewCookie)
                    _wf.setExperimentCookie({value:_wf.varName});
                if (opts.callback) {                    
                    opts.callback(_wf.varName);
                }
                _wf.controlPageRedirect(_wf.redirectParam);                
            }     
        } 
    };
   
    // Example {cvslot : 2}
    _wf.trackCombination = function(options) {        
        options = options || {};
        options = {
            ga : options.ga || true, // load ga library?    
            cvslot : options.cvslot || _wf._ExperimentConfig.cvslot // Use 0 to turn off cv tracking            
        };

        // GA Tracking
        var combo = _wf.readCookie(_wf._ExperimentConfig.cookieKey);            
        if (combo !== null) {             
            var vp = _wf.getVPPattern(),
                cv = {slot:options.cvslot, label:_wf._ExperimentConfig.dockette, value:combo, scope:1};

            if (_wf._ExperimentConfig.defaultGa && _wf._ExperimentConfig.enableVPTracking) {
                _wf.trackPageView({
                    id:_wf._ExperimentConfig.defaultGa, 
                    domain : _wf._ExperimentConfig.domain,
                    customVar: cv, 
                    vp: vp, 
                    referrerOverride:_wf.refOverride,
                    allowLinker : _wf._ExperimentConfig.allowLinker,
                    allowHash : _wf._ExperimentConfig.allowHash        
                }); 
            }
          
        } 

        // GWO Tracking
        _wf.trackPageView({
                name:'wfgwo', 
                id:_wf._ExperimentConfig.wfgwo, 
                domain : _wf._ExperimentConfig.domain,
                vp: '/' + _wf._ExperimentConfig.k + '/test',
                allowLinker : _wf._ExperimentConfig.allowLinker,
                allowHash : _wf._ExperimentConfig.allowHash        
        });  
        
        _wf._ExperimentInfo.isVariationTracked = true;

        // Load GA library
        _wf.loadGALib(); 
    };

  // Example {vp: 'vp/goal/'} override vp goal
    _wf.trackGoal= function(options) {       
        options = options || {};
        options = {
            vp : options.vp || ""            
        };

        // GA Tracking
        var combo = _wf.readCookie(_wf._ExperimentConfig.cookieKey);        
        if (combo !== null) {                               
            var vp = _wf.getVPPattern();
            
            if (_wf._ExperimentConfig.defaultGa && _wf._ExperimentConfig.enableVPTracking) {            
                _wf.trackPageView({
                    id:_wf._ExperimentConfig.defaultGa, 
                    domain : _wf._ExperimentConfig.domain,
                    vp: vp,
                    allowLinker : _wf._ExperimentConfig.allowLinker,
                    allowHash : _wf._ExperimentConfig.allowHash
                });  // Default tracker          
            }
       
        }         

        // GWO Reporting            
        _wf.trackPageView({ name:'wfgwo', 
                            id:_wf._ExperimentConfig.wfgwo, 
                            domain : _wf._ExperimentConfig.domain,
                            vp: '/' + _wf._ExperimentConfig.k + '/goal',
                            allowLinker : _wf._ExperimentConfig.allowLinker,
                            allowHash : _wf._ExperimentConfig.allowHash});                  
        
        _wf._ExperimentInfo.isGoalTracked = true;

        // Load GA library
        _wf.loadGALib();    
    };

    _wf.setExperimentCookie = function(options) {
        options = options || {};
        options = {
            key : options.key || _wf._ExperimentConfig.cookieKey,
            value : options.value || _wf.varName,
            days : options.days || 365,
            domain : options.domain || ""
        };    

        if (options.domain) {
            _wf.createCookie(options.key, options.value, options.days, options.domain);         
        } else {
            _wf.createCookie(options.key, options.value, options.days);         
        }    
    };

    _wf.trackPageView = function(config) {    
        config = config || {};    
        config = {
            name :config.name || "",
            id : config.id || "",
            vp : config.vp || "",
            domain : config.domain || "",
            customVar : config.customVar || "",
            allowLinker : config.allowLinker || "",
            allowHash : config.allowHash || "",
            referrerOverride : config.referrerOverride || "",
            async: config.async || _wf._ExperimentConfig.async
        };

        _wf.trackPageViewAsync(config);      
    };   
    
    _wf.trackPageViewAsync = function(config) {
        if (config.name) {
            config.name = config.name + "."
        } 
        _gaq.push([config.name + '_setAccount', config.id]);    

        if (config.domain) {
            _gaq.push([config.name + '_setDomainName', config.domain]);
        }
        
        if (config.referrerOverride) {
            _gaq.push([config.name + '_setReferrerOverride', config.referrerOverride]);
        }        
            
        if (config.setCampTermKey) {
            _gaq.push([config.name + '_setCampTermKey', config.setCampTermKey]);        
        }
        
        if (config.allowLinker) {
            _gaq.push([config.name + '_setAllowLinker', config.allowLinker]);
        }
        
        if (config.allowHash) {
            _gaq.push([config.name + '_setAllowHash', config.allowHash]);
        }

        if (config.customVar && config.customVar.slot != 0) {
            var cv = config.customVar;        
            _gaq.push([config.name + '_setCustomVar', cv.slot, cv.label, cv.value, cv.scope]);
        }        

        if (config.vp) {
            _gaq.push([config.name + '_trackPageview', config.vp]);            
        } else {
            _gaq.push([config.name + '_trackPageview']);                    
        }        
    };

    // loads siteop.js library
    _wf.loadGWOLib = function() {      
        if (!_wf._ExperimentInfo.isGWOLibLoaded) {    
            (function(){var k=_wf._ExperimentConfig.k,d=document,l=d.location,c=d.cookie;function f(n){
            if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.indexOf(';',i);return escape(c.substring(i+n.length+1,j<0?c.length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;
            d.write('<sc'+'ript src="'+ 'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com'
            +'/siteopt.js?v=1&utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='
            +new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
            '" type="text/javascript" charset="utf-8"></sc'+'ript>')})();
            
            // utmx not available yet.
            _wf._ExperimentInfo.isGWOLibLoaded = true;                     
        }    
    };

    _wf.loadGALib = function() {    
        if (!_wf._ExperimentInfo.isGALibLoaded) {            
            (function(){var a=document.createElement("script");a.type="text/javascript";a.async=true;a.src=("https:"==document.location.protocol?"https://ssl":"http://www")+".google-analytics.com/ga.js";var b=document.getElementsByTagName("script")[0];b.parentNode.insertBefore(a,b)})();                        
            
            _wf._ExperimentInfo.isGALibLoaded = true;
        }    
    };    
} // end _lib_client

