//START scEnvironment.js
/***************************************************************
* Config variables used by s_code_vkistudios_BK.js for  
* tracking purposes. These should be specific to each site.
***************************************************************/

var SC_TRACKED_DOMAIN = 'calvinayre.com'   
var SC_TRACKING_SERVER = 'insight.' + SC_TRACKED_DOMAIN;
var SC_TRACKING_SERVER_SECURE = 'insights.' + SC_TRACKED_DOMAIN; 
var SC_VISITOR_NAMESPACE = 'riptownmedia';    
var SC_REPORTING_SUITE_ID_DEV = 'riptown.all.dev'; 
var SC_REPORTING_SUITE_ID_INT = 'riptown.all.int';
var SC_REPORTING_SUITE_ID_TEST = 'riptown.all.int';    
var SC_REPORTING_SUITE_ID_PROD = 'riptowncalvinayre';   
var SC_DOMAIN_PERIODS = 2;      // how many parts make your domain name 
var SC_CURRENCY_CODE = 'USD';   // Default currency code used on this environment
//END scEnvironment.js




// This .js file must be called at the very first opportunity on each page
// See change notes at end
var scvki_elver = 'e1.2.1';
var startTime = (new Date()).getTime(); // Start the timer as soon as possible
var strSearch = document.location.search;
var strSessionReferrer = '';
var intPageNo = 0;  
var intPageSkips = 0;
var strDomainName = scvki_getDomainName();
var strCookie = unescape(document.cookie);  // 100705
var isLandingPage = _scvki_setIsLandingPage();
var flt30Mins = (0.5/24);   // getValOnce & _scvki_setEvarOnce require expiry periods in days
var dt30Mins = new Date(startTime + (flt30Mins*60*60*24*1000));




    // Called before s_code file loaded so s.* functions and plug-ins not available
function _scvki_setIsLandingPage() {
    
    try { var strPreviousPage = unescape(strCookie.match(/;*vkiPreviousPage=([^;]*)/)[1]) } catch (e){};
    strCookie = vkiSetCookie( 'vkiPreviousPage', document.location.href, 30, '/', strDomainName, '');

    var strReferrer = unescape(document.referrer ? document.referrer : 'Direct');

        // _scvki_setIsLandingPage determined only by HTTP.
        // Visit definition: 30 minutes inactivity or 12 hours of continuous activity (12 hours not catered for here)
        // 30 minute cookie = vki30currentReferrer
    var isCookieMissing = (strCookie.search(/vki30currentReferrer=/) == -1);
        // Session cookie=vkiSessionReferrer; - stores the referrer of the visit (only written once per session)

        // 100705 - vkiSessionReferrer was not being refreshed (was originally a session cookie not requiring refresh) 
        // 100705 - logic changed to refresh vkiSessionReferrer and use only vki30currentReferrer to determine if new visit
    if (isCookieMissing)
        strSessionReferrer = strReferrer;
    else 
        strSessionReferrer = vkiGetCookie('vkiSessionReferrer');
        
        // 30 minute cookie = vki30currentReferrer - rewrite on every page to keep cookie alive for 30 mins of inactivity
        // stores the referrer for the current page
    strCookie = vkiSetCookie( 'vki30currentReferrer', strReferrer, 30, '/', strDomainName, '');
    strCookie = vkiSetCookie( 'vkiSessionReferrer', strSessionReferrer, 30, '/', strDomainName, '');            // 100705
    
        // to deal with diff between 30 min cookies and session cookies to determine if visit has ended
        // vki_* cookies are session cookies but deleted here if 30 mins have passed
    if (isCookieMissing)  {
            // Keep all cookies in sync - if the session has ended, kill the visit-level cookies
        strCookie = vkiSetCookie('vki_LastPageNo', '', -1, '/', strDomainName, '');
        strCookie = vkiSetCookie('vki_TotalTime', '', -1, '/', strDomainName, '');
        strCookie = vkiSetCookie('vki_TrackedPages', '', -1, '/', strDomainName, '');
        strCookie = vkiSetCookie('vki_PageNo', ++intPageNo, 30, '/', strDomainName, '');    // =1
    }
    else {
        try { intPageNo = parseInt(strCookie.match(/;*vki_PageNo=([^;]*)/)[1]) } catch (e){intPageNo = -2;};
        strCookie = vkiSetCookie('vki_PageNo', ++intPageNo, 30, '/', strDomainName, ''); // increment then save
    }
        
    return isCookieMissing;
}

/*
    eVars and events used in this code in VKI's sandbox report suite
eVar32      HTTP Session Referrer
eVar33      True Page Number in Visit
eVar34      (spare) Skipped Pages Count
eVar35      Pages Skipping SC
eVar36      Load Time Histogram
eVar37      Average Load Times
    e.g. if lngPageLoadTime = 2.9secs and intResolutionSeconds  = 2,   then eVar36 repoted as "2 < 3"
    e.g. if lngPageLoadTime = 3.9secs and intResolutionSeconds  = 2,   then eVar36 repoted as "3 < 4"

event21 Visit Events 
event22 Load Times
event23 Landing Page Skips
event24 Previous Page Skips (not including landing page skips)
*/


    // Runs immediately before the call to s.t(), usually after all s. fields have been populated
    // call to s.t() looks something like  "s_code=s.t();if(s_code)document.write(s_code)"
    // s_code file will already have been loaded so s object, plugins and functions are available
function sc_reportReferrers() {
    

        // Only for calculating avg load times
    var intTrackedPages = parseInt(vkiGetCookie('vki_TrackedPages')) || 0; // 20100526 was s.c_r('vki_TrackedPages')
    strCookie = vkiSetCookie( 'vki_TrackedPages', ++intTrackedPages, 30, '/', strDomainName, '');

    s.eVar33 = intPageNo;
    s.events = s.apl(s.events, 'event9', ',', 2);   // 100705 - added , 2 in case onEveryPage is called 2ce per page-load (but it shouldn't)
    
        // event21:Visit Events: limit 1 per browser by logic - use absence of vki_eVar32_HTTPSessionReferrer cookie to test
    if (document.cookie.search(/;?vki_eVar32_HTTPSessionReferrer=([^;]*)/) == -1) 
        s.events = s.apl(s.events, 'event21', ',', 2);
    
        // eVar32       HTTP Session Referrer
        // _scvki_setEvarOnce only lets eVar be set if value is different than stored in the cookie,  otherwise it returns ""
    s.eVar32 = _scvki_setEvarOnce('eVar32', strSessionReferrer, flt30Mins); // 20100526 was s.getValOnce(strSessionReferrer, 'vki_eVar32_HTTPSessionReferrer', flt30Mins); 
    strCookie = vkiSetCookie('vki_eVar32_HTTPSessionReferrer', strSessionReferrer, 30, '/', strDomainName, ''); // 20100526 Write it separately from the s_pers combined cookie

        // Landing Page Skips - 
        //If sc has just set s.eVar32 but its not the landing page - append event23 to s.events to count a skipped LP
    if (!isLandingPage && s.eVar32) {
        s.events = s.apl(s.events, 'event23', ',', 2); // 100705 - added , 2 in case onEveryPage is called 2ce per page-load (but it shouldn't)
    }
    
        // track entry pages
    if (isLandingPage) {
        s.prop26 = s.pageName;  // Cannot use _scvki_D() because value needs to be stored in cookie in _scvki_persistProp('prop26', s.prop26); below
        s.eVar39 = _scvki_D('s.prop26');    // persist entry pages for success metrics - logically, only set once per visit 20100526
    }
    _scvki_persistProp('prop26', s.prop26);
    
    
        // use spare s.eVar34 to track if any multiple page skips
    var intLastPageNo = parseInt(vkiGetCookie('vki_LastPageNo'));   // 20100526 was s.c_r('vki_LastPageNo')
    var intPageSkips = intPageNo-intLastPageNo-1;
    s.eVar34 = (intLastPageNo > 0 && intPageSkips > 0) ? intPageSkips : 0;
    
    strCookie = vkiSetCookie( 'vki_LastPageNo', intPageNo, 30, '/', strDomainName, '');

    // test if previous page (not a landing page) lost tracking
    try {
        strCurrentReferrer = unescape(document.cookie.match(/;*vki30currentReferrer=([^;]*)/)[1]);
            // s.getPreviousValue will return the previous value and write the current value.
            // the previous value should be the current page's referrer (if not direct or external)
        var strPreviousHref = unescape(s.getPreviousValue(document.location.href,"gpv_currentPage",""));
        if (strCurrentReferrer !== strPreviousHref && !isLandingPage && !s.eVar32) {
                // s.eVar35 = Pages Skipping SC. 
            s.eVar35 = strCurrentReferrer; // record the href that did not run the SC code
                // this could happen any number of times per visit
            s.events = s.apl(s.events, 'event24', ',', 2);      // 100705 - added , 2 in case onEveryPage is called 2ce per page-load (but it shouldn't)
        }
    } catch (e) {
            s.eVar35 = (strCookie ? 'vki30currentReferrer cookie' : 'Cookies') + ' could not be set';
    }

    var intResolutionSeconds = 3;
    var intMaxSeconds = 45;
    var endTime = (new Date()).getTime();

    var lngPageLoadTime = (endTime - startTime);
    var fltSecs = (lngPageLoadTime/1000);
    
    lngPageLoadTime = fltSecs-(fltSecs % intResolutionSeconds);

        // some timings being reported as < 0 !!! 
    if (lngPageLoadTime >= 0) {
        s.eVar36 = (lngPageLoadTime > intMaxSeconds ?
                    intMaxSeconds + 's':
                    lngPageLoadTime + 's to ' + (lngPageLoadTime+intResolutionSeconds-0.1)  + 's'
                    );
            // Running total of load times to calculate average
        var intTotalTime = parseFloat(vkiGetCookie('vki_TotalTime')) || 0; // 20100526 Was s.c_r('vki_TotalTime')
        intTotalTime += fltSecs;
        strCookie = vkiSetCookie( 'vki_TotalTime', intTotalTime, 30, '/', strDomainName, '');
        
            // accumulate load times in incrementor event - can be used in a calc metric to calc avg load times
        s.events = s.apl(s.events, 'event22', ',', 2); // 100705 - added , 2 in case onEveryPage is called 2ce per page-load (but it shouldn't)
        
        if (s.products) {
            if (s.products.search(/event\d+=/) !== -1)  s.products += '|';
            s.products += ';event22=' + fltSecs;
        }
        else
            s.products = ';;;;event22=' + fltSecs;
        
        var intAvgLoadTime = Math.floor(intTotalTime/intTrackedPages);
        intAvgLoadTime = intAvgLoadTime-(intAvgLoadTime%intResolutionSeconds);
        s.eVar37 = (intAvgLoadTime > intMaxSeconds ?
                    intMaxSeconds + 's':
                    intAvgLoadTime + 's to ' + (intAvgLoadTime+intResolutionSeconds-0.1)  + 's'
                    );
    }
    else    // lets find out which ones those are
        s.eVar36 = lngPageLoadTime + '|' + s.pageName;

        gavki_TrackGA();

}

function vkiSetCookie( name, value, expiresMinutes, path, domain, secure ) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    
    expiresMinutes = expiresMinutes * 1000 * 60;
    var expires_date = new Date( today.getTime() + (expiresMinutes) );

    domain = 'localhost' == domain  ? '' : domain;
    
    document.cookie = name + "=" +escape( value ) +
    ( ( expiresMinutes ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );

    strCookie = unescape(document.cookie);
    return strCookie
}

function vkiGetCookie(name) {
    var strValue;
    var strPattern = ";*" + name + "=([^;]*)";
    
    try {
        strValue = unescape(document.cookie).match(strPattern)[1];
    }
    catch (e) {
        strValue = '';
    }
    return strValue;
}

function vkiSetCookieIfNone( name, value, expiresMinutes, path, domain, secure ) {
    var strValue;
    var strPattern = ";*" + name + "=([^;]*)";
    try {
        strValue = unescape(document.cookie).match(strPattern)[1];
    }
    catch (e) {
        strValue = value;
    }
        //refresh the cookie
    strCookie = vkiSetCookie( name, strValue, expiresMinutes, path, domain, secure );

    return strValue;
}


function scvki_getDomainName(strURL) {
    strURL = strURL || document.location.hostname;
    var strDomainName = '';
    
    try {
            // extract the host name since full url may have been provided
        strDomainName = strURL.match(/^(?:https?:\/\/)?([^\/:]+)/)[1];  // this cannot error unless running as file://
        
        if(strDomainName.match(/(\d+\.){3}(\d+)/) || strDomainName.search(/\./) == -1) return strDomainName;    // ipaddress or localhost

        strDomainName = strDomainName.match(/(([^.\/]+\.[^.\/]{2,3}\.[^.\/]{2})|(([^.\/]+\.)[^.\/]{2,3}))(\/.*)?$/)[1];
            
    } catch (e) { 
        strDomainName = strURL; 
    }
    
    return  strDomainName;
}


var _gaq = _gaq || [];
//calvinayre
var gavki_strUA = 'UA-11325982-2';

function gavki_TrackGA(strPageName) {
    strPageName = gavki_calcPageName(strPageName);
 /*       
    if (strDomainName.search(/slots/i) >= 0) {
        gavki_strUA = 'UA-16780872-4';
    }
    else if (strDomainName.search(/bodog/i) == -1) {
        gavki_strUA = 'UA-8706900-3';
    }
   */

    _gaq.push(['_setAccount', gavki_strUA]);
    
	//not set on CA
    //_gaq.push(['_setDomainName', scvki_getDomainName()]);
    _gaq.push(['_trackPageview', strPageName]);

    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);
}

function gavki_trackGAevent(category, action, opt_label, opt_value) {
    _gaq.push(['_trackEvent', category, action, opt_label, opt_value]); 
}

function gavki_calcPageName(strPageName) {
    strPageName = strPageName || s.pageName || document.location.href; //20100526 changed to document.location.href to include http prefix per Dino
    
        // is deposit start, join complete
    if (s.pageName.indexOf('deposit-step-1-start') !== -1
        &&
        (s.prop12 == 'Joined Player' || s.prop12 == 'Non-player Joined')  // 100705 - upgraded detection following on changes to PTS
       )    
        strPageName += '?step=JoinSuccess';

        // is deposit start, join complete
        // _scvki_getSetEventOnce('event1', -1) returns if event1 has been sent - Join has occurred in this session
        //       -1 deletes event1 from cookie seeing as a Join cannot re-occur and further deposits will not be via join
    if (s.pageName.indexOf('deposit-step-2-complete') !== -1
        &&
        isFromJoin // 100705 was _scvki_getSetEventOnce('event1', -1)
       )
        strPageName += '?type=FromJoin';

        // which contact us is this
    if (s.pageName.indexOf('contact-us-complete') !== -1)
        strPageName += (s.prop3 == 'player' ? '-player' : '-anonymous');
        
    /* 20100526 - http and domain was added so removing domain no longer applicable
            // remove domain - send only URI
        try {strPageName = strPageName.match(/(?:https?:\/\/[^\/]+)?(\/?.*)/)[1] } catch (e) {};
            // Add leading forward /
        strPageName = ('/' + strPageName).replace(/^\/+/, '/');
    */ 
    
    // **********************************
    // Domains and Sub-domains are being dropped in GA 20100623
    // **********************************
    
    return strPageName
}
/* Changes
     03/08/10
        Added var _gaq = _gaq || []; and gavki_TrackGA()
        Renamed getDomainName() to scvki_getDomainName() and changed calls to it in this script
         - done for uniformity with other scripts developed after this script
        Enhanced strURL.match RegExp to handle dev and co.uk domain names
        
*/



