﻿var affiliate = {
    affiliateId: null,
    bannerSize: null,
    imageTag: null,
    //campaignId: null, v2 release
    currentCampaign: 'Test',

    // Checks for referral id
    checkUrl: function () {
        string = 'affiliate';
        name = string.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null) {
            return "";
        } else {
            this.affiliateId = results[1];
            this.createCookie();
            this.createClickThrough();
        }
    },

    createClickThrough: function () {
        var url = 'http://www.glutenfreely.com/affiliates/processaffiliates.aspx';
        $.get(url, { process: 'addClick', AffiliateID: this.affiliateId }, function (data) {
            // do something
        })
    },

    createCookie: function () {
        var date = new Date();
        date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
        document.cookie = "Affiliate=" + this.affiliateId + expires + "; path=/";
    },

    readCookie: function () {
        var nameEQ = "Affiliate=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            // Use this line to return a value -- if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            if (c.indexOf(nameEQ) == 0) return true;
        }
        return false;
    },

    eraseCookie: function (name) {
        createCookie(name, "", -1);
    }
}
