/*
 This script provides access to the Adchemy Variation Service.

 TODO: Add some more documentation in this header

 Copyright(C) 2009 Adchemy, Inc.

 */


/**
 * This function forces the include of a javascript file.
 */
function loadScript(url, callback){
    var script = document.createElement("script");
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                if (callback) {
                    callback();
                }
            }
        };
    } else {  //Others
        script.onload = function(){
            if (callback) {
                callback();
            }
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

/**
 * Helper class to parse a Blue Kai response into one or
 * more Adchemy VC attributes and then generate an event
 * to the component server so the VC attributes get logged.
 *
 * Notes:
 *  This class depends on the adchemyVariationFetcher which resides
 *  in adchemy.js and must be loaded explicitly before calling any
 *  methods in this class.
 *
 *  If variations have not been fetched via adchemyVariationFetcher
 *  it is up to the caller to have set a valid session ID on the
 *  variationFetcher via adchemyVariationFetcher.sessionId
 *
 *  The name of the event to generate can be overriden prior
 *  to calling the generateEvent method.
 */
var adchemyBkxHelper = new function() {
    var defaultEventName = "bluekai tags post";
    var startTime = new Date().getTime();
    var accountId = 0;

    // Can be overriden by user.
    this.eventName = defaultEventName;

    // Method to generate the async call to BlueKai.  This is the
    // main method users of this class should call to generate
    // BK vc (which will automatically be posted to the Component Server).
    this.generateEvent = function(adchemyAccountId, bkAccountId) {
        var bkurl = "http://tags.bluekai.com/site/" + bkAccountId + "?ret=js";
        accountId = adchemyAccountId;
        startTime = new Date().getTime();
        loadScript(bkurl, this.onBkScriptLoad);
    };

    // Callback method which is invoked after the BK javascript result
    // has been loaded into the browser.
    this.onBkScriptLoad = function() {
        var latency = new Date().getTime() - startTime;
        var visitorContextMap = new Object();
        visitorContextMap["bkxLatency"] = latency.toString();

        if (typeof(bk_results) != "undefined") {
            adchemyBkxHelper.parseBkResults(bk_results, visitorContextMap);
            adchemyBkxHelper.generateDebugInfo(bk_results, visitorContextMap);
        } else {
            adchemyBkxHelper.generateDebugInfo(null, visitorContextMap);
        }
        adchemyVariationFetcher.setAccountId(accountId);
        adchemyVariationFetcher.postEvent(adchemyBkxHelper.eventName, visitorContextMap);
    };

    // Parse a BK result object into one or more VC attributes.  Each
    // BK campain and it's associated category data will be encoded into
    // a single VC attribute.
    this.parseBkResults = function(bkData, visitorContextMap) {
        if (!visitorContextMap) {
            visitorContextMap = new Object();
        }

        if (bkData) {
            if (0 < bkData.campaigns.length) {
                var bkVc = "";
                for (var i = 0; i < bkData.campaigns.length; i++) {
                    bkVc += "[" + bkData.campaigns[i].campaign.toString() + "]";

                    for (var j = 0; j < bkData.campaigns[i].categories.length; j++) {
                        bkVc += bkData.campaigns[i].categories[j].categoryID.toString();

                        if (j < bkData.campaigns[i].categories.length - 1) {
                            bkVc += ";";
                        }
                    }

                }

                visitorContextMap["bkxData"] = bkVc;
            }
        }

        return visitorContextMap;
    };

    // Utility method to stringify the BK result object and the
    // VC attribute map to dump for debugging.  Don't be tempted to
    // replace this code with toSource() on the objects, it doesn't work
    // in all browsers (Safari in particular barfs on toSource).
    this.generateDebugInfo = function(bkData, vcMap) {
        if (adchemyVariationFetcher.isDebug) {
            var debugInfo = "";
            if (!bkData) {
                debugInfo += "No data obtained from BlueKai<br/>";
            } else if (0 == bkData.campaigns.length) {
                debugInfo += "BlueKai result contained no campaign data.<br/>";
            } else {
                for (var i = 0; i < bkData.campaigns.length; i++) {
                    debugInfo += bkData.campaigns[i].campaign.toString() + "[";
                    for (var j = 0; j < bkData.campaigns[i].categories.length; j++) {
                        debugInfo += bkData.campaigns[i].categories[j].categoryID.toString();
                        if ((j + 1) < bkData.campaigns[i].categories.length) {
                            debugInfo += ",";
                        }
                    }
                    debugInfo += "]<br/>";
                }
            }

            if (!vcMap) {
                debugInfo += "No VC generated.<br/>";
            } else {
                for (var key in vcMap) {
                    debugInfo += key + "=" + vcMap[key] + " ";
                }
                debugInfo += "<br/>";
            }
            adchemyDebugInfo.append(debugInfo);
        }
    };
};

