﻿/**
* @name Affiliate-Network Recognition
* @description Analyzes the URL in order to determine whether the current uses comes from one of our affiliates; if an affiliate is detected the value will be saved to a cookie
* @param networks array of affiliate-objects that contain information about our partner-networks
* @param cookieName the name of the affiliate cookie (e.g. AffiliateNetworkInformation)
* @param cookieValueSeperator this string seperates the affiliate network name from the affiliate id in the cookie value
* @return bool returns true if an affiliate was recognized and the cookie was saves successfully
*/
function recognizeAffiliateNetworks(networks, cookieName, cookieValueSeperator) {
    if (!networks) { return false; }
    var result = false;

    /* get relevant configuration values from network settings */
    var providers = [];
    for (var n = 0; n < networks.length; n++) {
        var network = networks[n];
        if (network) {
            var entry = {};

            for (var i = 0; i < network.settings.length; i++) {
                var setting = network.settings[i];

                if (setting.name.toLowerCase() === "recognitionpattern") {
                    entry.networkName = network.name;
                    entry.networkId = network.id;
                    entry.recognitionPattern = new RegExp(setting.value, "i");
                } else if (setting.name.toLowerCase() === "cookielifetime") {
                    entry.cookieLifetime = Number(setting.value);
                } else if (setting.name.toLowerCase() === "redirectpattern") {
                    entry.redirectPattern = new RegExp(setting.value, "i");
                }
            }

            if (entry.networkName && entry.networkId && entry.recognitionPattern) {
                providers.push(entry);
            }
        }
    }

    /* test if current URL matches one of the supplied patterns */
    for (var n = 0; n < providers.length; n++) {
        var provider = providers[n];

        if (provider.recognitionPattern.test(document.location.href)) {
            /* determine cookie expiration date */
            var cookieLifeTime = provider.cookieLifetime;
            if (!provider.cookieLifetime) {
                cookieLifeTime = 60;
            }

            /* determine affiliate id */
            var affiliateId = {};
            var affiliateIdMatches = provider.recognitionPattern.exec(document.location);

            // All networks must have a match. If a network does not provice an id, take any string, e.g. the network name
            if (affiliateIdMatches.length > 1) {
                affiliateId = affiliateIdMatches[affiliateIdMatches.length - 1];

                if (typeof(externalServiceUrl) !== 'undefined') {
                    var serviceUrl = window.location.protocol + '//' + externalServiceUrl + '/dataservices/EncryptionService.svc/encrypt?method=?';

                    try {
                        $.ajax({
					        type: 'GET',
                            url: serviceUrl,
                            data: { affiliatePartnerId: affiliateId },
                            dataType: 'jsonp',
					        success: function (encryptedAffiliatePartnerId) {
						        /* save affiliate information to cookie */
                               var value = provider.networkName + cookieValueSeperator + escape(encryptedAffiliatePartnerId);
                               Cookies.set(cookieName, value, cookieLifeTime);

                               /* redirect */
                               if (provider.redirectPattern) {
                                   var redirectUrl = {};
                                   var redirectUrlMatches = provider.redirectPattern.exec(document.location);
                                   if (redirectUrlMatches != null && redirectUrlMatches.length > 1) {
                                       redirectUrl = redirectUrlMatches[redirectUrlMatches.length - 1];

                                       document.location = redirectUrl;
                                   }
                               }
					        }
                        });
                    } catch (ex) {}
                }
                // if the affiliate network was found, no others have to be checked
                break;
            }
            else {
                affiliateId = "affiliate-Id-is-not-specified";
            }
        }
    }

    return result;
}
