﻿var ANALYTICS_USER_TOKEN = "ANALYTICS_USER_TOKEN";
//todo: modify this URL based on environment
var BASE_SERVICE_URL = "http://analytics.newsinc.com/" 


String.format = function(text) {

    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }

    return text;
};

//Function generates a unique user id token
function GenerateUuid() {

    // Private array of chars to use
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [];

    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (var i = 0; i < 36; i++) {
        if (!uuid[i]) {
            r = 0 | Math.random() * 16;
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
    }

    var d = new Date();

    return uuid.join('') + d.getTime();

}

// set the default analytics cookie
function SetAnalyticsCookie() {
    
    //check to see if cookie exists
    var cookieCheck = GetAnalyticsUserToken()

    //if the cookie does not exist then set a cookie
    if (cookieCheck == null) {

        var token = GenerateUuid();
        SetCookie(ANALYTICS_USER_TOKEN, token, 30);
        return token;
    }
    else {
        return cookieCheck;
    }
}

function GetAnalyticsUserToken() {
    return GetCookie(ANALYTICS_USER_TOKEN);
}


function SavePageView(WidgetID, FullUrl, ParentUrl, SiteSectionID, AdNetworkID) {

    var token = SetAnalyticsCookie();

    var wsUrl = BASE_SERVICE_URL + 'AnalyticsProvider.svc/jsonp/analytics/PageViewJSONP?' +
        'wid=' + WidgetID +
        '&uut=' + token +
        '&furl=' + FullUrl +
        '&purl=' + ParentUrl +
        '&ssid=' + SiteSectionID +
        '&anid=' + AdNetworkID;

    $.ajax({
        dataType: 'jsonp',
        data: '',
        jsonp: 'Callback_SavePageView',
        url: wsUrl,
        success: function() {
            return;
        }
    });

}

//Callback function for making JSONP calls
function Callback_SavePageView(data) {
    return;
}

// Create a cookie with the specified name and value.
function SetCookie(sName, sValue, expiredays) {
    // get the current date
    var exdate = new Date();

    // tack on X days
    exdate.setDate(exdate.getDate() + expiredays);

    // set the cookie
    document.cookie = sName + "=" + escape(sValue) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());

}


// Retrieve the value of the cookie with the specified name.
function GetCookie(sName) {
    // cookies are separated by semicolons
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++) {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }
    // a cookie with the requested name does not exist
    return null;
}

function GetQueryStringValue(qs)
{
    var qs = qs.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + qs.toLowerCase() + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href.toLowerCase());
    if (results == null)
    {
        return "";
    }
    else
    {
        return results[1];
    }
}