/*
 * Silverpop, Omniture, DGAnalytics Integration
 * version 1
 *
 */

/* The starter site has already WMG declared in the 'Site Configuration'
 * javascript block in the header, which defines static site specific
 * configuration
 */
var WMG = WMG || {};

/*
 * Omniture  classes
 */
WMG.Omniture = function () {
    var init = function () {

    };
    return {
        init: init
    };
}();

WMG.OmnitureHelper = function () {
    var populate = function (DrupalObj, OmnitureObj) {

    };
    return {
        populate: populate
    };
}();

/*
 *  Silverpop classes
 */
WMG.SilverPop = function () {
    var config = {
        server: "https://signup.wmg.com/register",
        siteName: "",
        siteId: "",
        keywordId: "",
        newsletterId: "",
        Datasource: "",
        autoreply: ""
    };

    var spObj = {
        "email": "",
        "sex": "",
        "js": "true",
        "newsletterId": "",
        "keywordId": "",
        "EosUserDisplayName": "",
        "EosSiteAccountId": "",
        "EosMasterAccountId": "",
        "siteName": "",
        "SiteId": "",
        "postalcode": "",
        "TwitterHandle": "",
        "state": "",
        "phone": "",
        "lastname": "",
        "firstname": "",
        "dobYear": "",
        "dobDay": "",
        "dobMonth": "",
        "city": "",
        "age": "",
        "country": "",
        "address1": "",
        "address2": "",
        "address3": "",
        "global_optin": "",
    };

    //controller for this class. Uses datapreparation method to prepar the data.
    // Uses submitData to submit the data to the server.
    var mergeSiteLevelVars = function (userData) {
        if (typeof config.siteId !== "undefined") {
            userData.siteId = config.siteId;
        }
        if (typeof config.siteName !== "undefined") {
            userData.siteName = config.siteName;
        }
        if (typeof config.newsletterId !== "undefined") {
            userData.newsletterId = config.newsletterId;
        }
        if (typeof config.keywordId !== "undefined") {
            userData.keywordId = config.keywordId;
        }
        if (typeof config.Datasource !== "undefined") {
            userData.Datasource = config.Datasource;
        }
        if (typeof config.autoreply !== "undefined") {
            userData.autoreply = config.autoreply;
        }
        return userData;
    };
    var submit = function (userData) {
        userData = mergeSiteLevelVars(userData);
        var validate = validateObj(userData);
        if (validate.status === true) {
            ping(userData);
            return true;
        } else {
            var errors = validate.errors;
            return errors;
        }
    };

    var validateObj = function (userData) {
		/* List of thing to check before we can send the data.
		 Essentially we check only the user input data, that can be corrected.*/
        var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var mobileFilter = /^[.]{0}$|^\d{10,15}$/;
        var mobileFilterUS = /^[.]{0}$|^\d{10}$/;
        var mobileFilterOTHER = /^[.]{0}$|^\d{10,15}$/;
        var retObj = {
            status: true
        };
        var errors = {};
        if (!emailFilter.test(userData.email)) {
            errors.email = "Email Format is invalid";
        }
        if (typeof userData.mobile !== "undefined") {
            if (userData.country === "United States") {
                mobileFilter = mobileFilterUS;
            }
            if (!mobileFilter.test(userData.mobile)) {
                errors.mobile = "Mobile Number is invalid";
            }
        }
        var mobile = userData.mobile;
        if (!jQuery.isEmptyObject(errors)) {
            retObj.errors = errors;
            retObj.status = false;
        }
        return retObj;
    };

    var getObj = function () {
        var silverPopObj = spObj;
        return silverPopObj;
    };
    var ping = function (userData) {
        var qStr = "";
        if (userData.global_optin === "true") {
            userData.newsletterId = userData.newsletterId + "," + WMG.MailingList.labelListId;
        }
        jQuery.each(userData, function (key, value) {
            if (value !== "" && typeof value !== "undefined") {
                qStr += key + "=" + value + "&";
            }
        });
        qStr = qStr.slice(0, -1);
        jQuery.ajax({
            url: config.server,
            data: qStr,
            dataType: "script",
            success: function (data) {
                /* Ignore this now */
            }
        });
    };

    var callback = function (a, b) {
		/* Errors are supressed.
		 * The problem is there is no way,
		 * to report back to the calling function,
		 * that there are errors.
		 */
    };

    var init = function (userConfig) {
        if (typeof userConfig !== "undefined") {
            jQuery.extend(config, userConfig);
        }
    };

    return {
        init: init,
        submit: submit,
        callback: callback,
        getObj: getObj
    };
}();
if (typeof callback === "undefined") {
    /* Variable hoisted intended */
    callback = function (a, b) {
        WMG.SilverPop.callback(a, b);
    };
};
WMG.SilverPopHelper = function () {

    var dateFormatter = function (dateString) {
        var dateString = dateString.split(" ");
        var regexDate = /^((?:19|20)\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/;
        var result = regexDate.exec(dateString[0]);
        if (jQuery.isArray(result)) {
            var output = {};
            output.year = result[1];
            output.month = result[2];
            output.day = result[3];
        } else {
            output = false;
        }
        return output;
    };
    var genderFormatter = function (gender) {
        var retGender = "";
        if (typeof gender === "string") {
            switch (jQuery.trim(gender.toLowerCase())) {
                case "male":
                    retGender = 2;
                    break;
                case "female":
                    retGender = 1;
                    break;
            }
        };
        return retGender;
    };
    var populate = function (spObj, serverVars) {
        /* Take care of newsletterID, signup Type */
        if (serverVars.user_email !== null) {
            spObj.email = serverVars.user_email;
        }
        if (serverVars.user_gender !== null) {
            spObj.sex = genderFormatter(serverVars.user_gender);
        }
        if (serverVars.user_eos_wide_id !== null) {
            spObj.EosMasterAccountId = serverVars.user_eos_wide_id;
        }
        if (serverVars.user_eos_site_id !== null) {
            spObj.EosSiteAccountId = serverVars.user_eos_site_id;
        }
        if (serverVars.site_name !== null) {
            spObj.siteName = serverVars.site_name;
        }
        if (serverVars.user_postal_code !== null) {
            spObj.postalcode = serverVars.user_postal_code;
        }
        if (serverVars.user_twitter !== null) {
            spObj.TwitterHandle = serverVars.user_twitter;
        }
        if (serverVars.user_state !== null) {
            spObj.state = serverVars.user_state;
        }
        if (serverVars.user_eos_display_name !== null) {
            spObj.EosUserDisplayName = serverVars.user_eos_display_name;
        }
        if (serverVars.user_birthdate !== null) {
            var dateObj = dateFormatter(serverVars.user_birthdate);
            if (dateObj !== false) {
                spObj.dobYear = dateObj.year;
                spObj.dobDay = dateObj.day;
                spObj.dobMonth = dateObj.month;
            }
        }
        if (serverVars.user_city !== null) {
            spObj.city = serverVars.user_city;
        }
        if (serverVars.user_country !== null) {
            spObj.country = serverVars.user_country;
        }
        if (serverVars.spUpdate === true) {
            spObj.updateprofile = "yes";
        };
        if (serverVars.actuser_field_global_optin === 1) {
            spObj.global_optin = "true";
        }
        return spObj;
    };
    return {
        populate: populate
    };
}();

WMG.AnalyticsController = function () {

    var config = {
        omniture: WMG.Omniture,
        silverpop: WMG.SilverPop,
        serverVars: ""
    };

    var sendToSilverPop = function () {
        var spObj = WMG.SilverPop.getObj();
        spObj = WMG.SilverPopHelper.populate(spObj, config.serverVars);
        config.silverpop.submit(spObj);
    };
    var sendToOmniture = function () {

    };
    var processAnalytics = function () {
        var verifiedEmail = false;
        if (config.serverVars === "") {
            return;
        }
        /* This is an update scenario. */
        if (config.serverVars.action === "update" && config.serverVars.entity_type == "node") {
            config.serverVars.spUpdate = true;
            sendToSilverPop();
        }

        /*An user has been inserted in the database. But email need not be verified*/
        if (config.serverVars.action == "insert" && config.serverVars.entity_type == "node") {

            digitalData.page.pageInfo.pageName = digitalData.content.artist + ":Registration Email Sent" ; 
			_satellite.track("register");

        }
        /*Email Verification step reached.*/
        if (location.href.indexOf("pass-reset-token") !== -1) {
            verifiedEmail = true;
            digitalData.page.pageInfo.pageName = digitalData.content.artist + ":One-Time Login" ; 
        }

        if (verifiedEmail) {
            config.serverVars.spUpdate = false;
            sendToSilverPop();
        }

    };
    var init = function (userConfig) {
        /*Check for validity of serverVariable. If it does not come back. Just ignore it.*/
        if (typeof userConfig !== "undefined") {
            jQuery.extend(config, userConfig);
            processAnalytics();
        }
    };

    return {
        init: init
    };
}();

/* Invoking silverpop */
WMG.SilverPop.init({
    siteName: Drupal.settings.server_variables.site_name,
    siteId: WMG.siteID, /*Legacy EOS IDS*/
    keywordId: WMG.MailingList.MobileKeywordIds["United States"],
    newsletterId: WMG.MailingList.EmailListIds["United States"],
    Datasource: WMG.MailingList.Datasource,
    autoreply: WMG.MailingList.autoreply
});
WMG.Omniture.init();
if (typeof Drupal.settings.server_variables !== "undefined") {
    /*Pass Omniture, MailingList class. So that this is configurable. We can truly configure our variables. */
    WMG.AnalyticsController.init({
        serverVars: Drupal.settings.server_variables,
        omniture: WMG.Omniture,
        silverpop: WMG.SilverPop
    });
}