/**
 * GoogleExperiments is a toolbox to help using Google Experiments in our app.
 * After choosing a variation, it will report to the application with results,
 * so we can immediately report it to our analytics.
 *
 */

var GoogleExperiments = {};

/**
 * Set chosen variation or let Google decide one and report it to our systems.
 * @param {number|null} index
 */
GoogleExperiments.chooseVariation = function(index){
    if(typeof(cxApi) === 'undefined') { return; }

    if (typeof(index) === 'number') {
        cxApi.setChosenVariation(index);
    } else {
        index = cxApi.chooseVariation();
    }

    GoogleExperiments.variation = index;

    GoogleExperiments.report(index);

    return index;
};

GoogleExperiments.ready = function ready(fn) {
    if (document.readyState != 'loading'){
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
};

GoogleExperiments.addedExperiment = function(experiments) {
    var traits = analytics.user().traits();

    for (var experiment in experiments) {
        if(traits[experiment] !== experiments[experiment])
            return true;
    }
};


GoogleExperiments.report = function(){
    GoogleExperiments.ready(function(){
        var request = new XMLHttpRequest();
        request.open('POST', '/experiments/report', true);
        request.onload = function() {
            if (this.status >= 200 && this.status < 400) {
                var data = JSON.parse(this.response);
                analytics.ready(function(){
                    if(GoogleExperiments.addedExperiment(data.experiments))
                        analytics.identify(data.experiments);
                });
            } else {
                analytics.track('Reporting Experiment Failed', { response: response, xhr: this });
            }
        };
        request.send();
    });
};

window.GoogleExperiments = GoogleExperiments;
