/* global UIManager */

(function (exports) {

    'use strict';

    var domOverlay,
            operationNameDOM,
            explanationDOM,
            closeButtonDOM,
            enabledOperationButton,
            contactExplanationDOM,
            operationImgDOM;
    var DEFAULT_SERVICE_IMG = '/styles/images/default.png';

    var EnabledOverlay = {
        onDisabledCB: null,
        show: function (globalName, iconURL, handler) {

            if (!domOverlay) {
                domOverlay = document.getElementById('enabled-overlay');
                operationNameDOM = document.getElementById('enabled-op-name');
                operationImgDOM = document.getElementById('enabled-op-img');
                explanationDOM = document.getElementById('enabled-op-explanation');
                closeButtonDOM = document.getElementById('enabled-close');
                enabledOperationButton = document.getElementById('enabled-op-button');
                contactExplanationDOM = document.getElementById('enabled-op-contact');

                // Add listeners
                closeButtonDOM.addEventListener('click', function(){
                    this.onDisabledCB(this.hide());
                }.bind(this));
                enabledOperationButton.addEventListener('click', function () {
                    this.onDisabledCB(this.hide());
                }.bind(this));
            }

            // If onDisabled is not defined, dummy handler
            this.onDisabledCB = handler || function (cb) {
                cb();
            };
            // Set title and name of the operation
            operationNameDOM.textContent = globalName || '';


            // Remove buttons if needed
            UIManager.logoutRequired(function (required) {
                var pressButtonParagraph = domOverlay.querySelector('.notification-detail:last-of-type');
                if (required) {
                    pressButtonParagraph.classList.add('hide');
                    enabledOperationButton.classList.add('hide');
                }
                else {
                    pressButtonParagraph.classList.remove('hide');
                    enabledOperationButton.classList.remove('hide');
                }
            });
            // Show the overlay
            domOverlay.classList.add('show');

            // preload the default image
            operationImgDOM.src = DEFAULT_SERVICE_IMG;

            // create a new image with the proper source
            if (iconURL) {
                var newImg = new Image();
                newImg.onload = function () {
                    operationImgDOM.src = this.src;
                };
                newImg.src = iconURL;
            }
        },
        hide: function () {
            domOverlay.classList.remove('show');
        }
    };

    exports.EnabledOverlay = EnabledOverlay;

}(this));
