(function(sugarApp) {
    "use strict";

    const moduleName = "SP_MailingTemplates";
    var loaded = false;

    /**
     * Shows the sync wizard.
     */
    function showSyncWizard() {
        var path    = Backbone.history.location.pathname + 'modules/SP_SyncMailingTemplates/index.html';
        var name    = 'sp_syncwizard_' + (new Date().valueOf()).toString() + '_' + Math.ceil(Math.random() * 10000);
        var params  = 'scrollbars=0,toolbar=0,location=0,resizable=0,menubar=0,width=600,height=320';

        var w = window.open(path, name, params);

        if (w == null) {
            console.error("FATAL ERROR: Cannot open sync wizard!");
            alert("Error: cannot open sync wizard!");
            return;
        }

        w["access_token"]   = sugarApp.api.getOAuthToken();
        w["language"]       = sugarApp.lang.getLanguage();
    }

    // On sync complete
    sugarApp.events.on("app:sync:complete", function() {

        // Skip if module is already loaded...
        if (loaded) { return; }
        loaded = true;

        // On route list
        sugarApp.router.on("route:list", function(module) {
            if (module === moduleName) {
                // On sync button click
                sugarApp.controller.context.on("button:sp_syncmailingtemplates:click", function() {
                    showSyncWizard();
                });
            }
        });
    });

})(SUGAR.App);
