(function(app) {
    
    'use strict';
    
    var moduleName = 'Campaigns';
    var loaded = false;

    var processFailedRecipients = function(responseString) {
      try {
        var response = JSON.parse(responseString);
        var parser = new DOMParser();
        var xmldoc = parser.parseFromString(response.content, 'text/xml');
        var source = xmldoc.getElementsByTagName('RECIPIENT');
        
        $scope.totalRecordsFailed += source.length;
       }
       
      catch (err) {
        if (settings.recipients.length === 0) {
         console.log('Reprocessing failed recipients...');
         currentBatch--;
        }
       
       }
     };
    
    /**
     * 
     * @param {String} campaignId
     * @returns {void}
     */
    var showSendWizard = function(campaignId) {
        
        app.api.call('read', app.api.buildURL('Users') + '/' + app.user.id, null, {
            success: function(response) {
                
                var email = response['email1'];
                
                app.api.call('read', app.api.buildURL('sp_api', 'getgeneralsettings'), null, {
                    success: function(response) {
                        
                        var settings = JSON.parse(response);
                        
                        app.api.call('read', app.api.buildURL('sp_api', 'gettotalrecordsofcampaigns') + '?campaign_id=' + campaignId, null, {
                            success: function(response) {
							
							var totalRecords = 0;
							
							if (response.content === null) {
								console.log('Campaign model lost...');
							}
							else { 
								totalRecords = response.content.length; 
								}
                                
                                var path = location.pathname.replace('index.php', '') + 'modules/SP_SendWizard/index.html';
                                var r = (new Date()).valueOf().toString();
                                var w = window.open(path, 'SPSendWizard_' + r, 'scrollbars=yes,toolbar=no,location=no,width=900,height=800');

                                w['current_user'] = app.user.id;
                                w['sugar_token'] = app.api.getOAuthToken();
                                w['sugar_refresh'] = app.api.getRefreshToken();

                                w['auth_username'] = settings['sp_username'];
                                w['auth_password'] = settings['sp_password'];

                                w['username'] = app.user.get('full_name');
                                w['usermail'] = email;

                                w['recipients'] = [];
                                w['total_records'] = totalRecords;
                                w['campaign_id'] = campaignId;

                                w['language']                       = app.lang.getLanguage();
                                
                                w['url_api_getaccesstoken'] = app.api.buildURL('sp_api', 'getaccesstoken');
                                w['url_api_getmailtemplatelist'] = app.api.buildURL('sp_api', 'getmailtemplatelist');
                                w['url_api_getmetadatalist'] = app.api.buildURL('sp_api', 'getmetadatalist');
                                w['url_api_getmailpreview'] = app.api.buildURL('sp_api', 'getmailpreview');
                                w['url_api_schedulemail'] = app.api.buildURL('sp_api', 'schedulemail');
                                w['url_api_addrecipients'] = app.api.buildURL('sp_api', 'addrecipientstoscheduledmail');
                                w['url_api_commitmail'] = app.api.buildURL('sp_api', 'commitmail');
                                w['url_api_addmailing'] = app.api.buildURL('sp_api', 'addmailing');
                                w['url_api_refreshtoken'] = app.api.buildURL('oauth2/token');
                            }
                        });
                    }
                });
            }
        });
    };

    var showExportCampaign = function(campaignId) {

        app.api.call("read", app.api.buildURL('sp_api', 'getgeneralsettings'), null, {
            "success": function(response) {
                var settings = JSON.parse(response);

                var path = location.pathname.replace('index.php', '') + 'modules/SP_ExportCampaign/index.html';
                var r = (new Date()).valueOf().toString();
                var w = window.open(path, 'SPExportCampaign_' + r, 'scrollbars=yes,toolbar=no,location=no,width=800,height=400');

                w['auth_username'] = settings['sp_username'];
                w['auth_password'] = settings['sp_password'];
                w['campaign'] = campaignId;
                w['language'] = app.lang.getLanguage();
            }
        });

    };

    var createScript = function(source) {
        var script = document.createElement("script");
        script.attributes["type"] = "text/javascript";
        script.innerHTML = source;
        document.head.appendChild(script);
    };
    
    var insertButton = function(model) {

        var path = window.location.href;
        path = path.substr(0, path.lastIndexOf("/")).replace("#bwc", "") + "custom/modules/Campaigns";
        // console.log("PATH = " + path);

        var language = app.lang.getLanguage();

        var insert = function() {
            $('iframe').contents().find('#launch_wizard_button').before('<input id="sp_sendsilverpopemail" type="button" class="button" value="Send Acoustic Campaign Email" />');
            $('iframe').contents().find('#launch_wizard_button').before('<input id="sp_exportcampaign" type="button" class="button" value="Sync Acoustic Campaign Campaign" />');

            $('iframe').contents().find('#sp_sendsilverpopemail').val(lang.LBL_SP_SEND_IBM_MC_EMAIL_BUTTON);
            $('iframe').contents().find('#sp_sendsilverpopemail').click(function() {
                showSendWizard(model.id);
            });

            $('iframe').contents().find('#sp_exportcampaign').val(lang.LBL_SP_SYNC_IBM_MC_CAMPAIGN_BUTTON);
            $('iframe').contents().find('#sp_exportcampaign').click(function() {
                showExportCampaign(model.id);
            });
        };

        if (typeof lang === 'undefined') {
            $.getScript(path + "/language/" + language + ".js")
                .done(function (response) {
                    console.info("Recieved language pack for " + language);
                    createScript(response);
                    insert();
                })
                .fail(function () {
                    console.warn("Cannot load language pack for " + language + ". Trying to load default (en_us).");
                    $.getScript(path + "/language/en_us.js")
                        .done(function (response) {
                            console.info("Recieved language pack for en_us");
                            createScript(response);
                            insert();
                        })
                        .fail(function () {
                            console.error("Cannot load language for en_us.");
                        });
                });
        } else {
            insert();
        }
    };
    
    app.events.on('app:view:change', function(view, module) {
        if (view === 'bwc' && module.module === moduleName) {
            
            loaded = false;
            
            app.events.on('data:sync:complete', function(type, model) {
                if (loaded === false) {
                    loaded = true;
                    insertButton(model);
                }
            });
        }
    });
    
})(SUGAR.App);
