/**
 * @namespace GlobalResources
 * @requires /js/common.js
 * @requires /js/events.js
 */

/**
 * Класс для отрисовки всплывающих окон
 * @param {Number} width Ширина содержимого окна
 * @param {Number} height Высота содержимого окна
 * @param {Object} options Опции
 *
 */
GlobalResources.Window = function(options) {
    this._options = options || {};
    this._d = document.documentElement;
    this._eventDispatcher = new $G.EventDispatcher();
    this._setup();
}

GlobalResources.Window.prototype = {
    /**
     * Показать окно
     */
    show: function() {
        this._draw();
    },

    /**
     * Закрыть окно
     */
    close: function() {
        this._hide();
        this._eventDispatcher.dispatchEvent('close');
    },

    /**
     * Подключить обработчик события
     * @param {String} event Событие
     * @param {Function} handler Обработчик
     */
    attachEventListener: function(event, handler) {
        this._eventDispatcher.attachEvent(event, handler);
    },

    /**
     * Снять обработчик события
     * @param {String} event Событие
     * @param {Funciton} [handler] Обработчие
     */
    removeEventListener: function(event, handler) {
        this._eventDispatcher.removeEvent(event, handler);
    },

    /**
     * Настройка параметров
     */
    _setup: function() {
        this.innerWidth = this._options.width || 0;
        this.innerHeight = this._options.height || 0;
        this.align = this._options.align || 'left-top';
        this.contentOverflow = this._options.overflow || 'hidden';
        this.animation = this._options.animation || false;
        this.fadeDuration = this._options.fadeDuration || 300;

        this.animationSlide = this._options.animationSlide || false;
        this.slideDuration = this._options.slideDuration || 300;
        this._slideAncestor = this._options.slideAncestor;
    },

    /**
     * Функция отрисовки окна
     */
    _draw: function() {
        var self = this;

        // Рисуем подложку
        this._$overlay = $(document.createElement('div'))
            .addClass('popup-overlay')
            .click(function() { self.close(); })
            .appendTo(document.body);
        if (Browser.isIE6) {
            this._$overlay.css({
                position : 'absolute',
                height   : Browser.getScrollBody().scrollHeight
            });
        }
        // Враппер
        this._$wrap = $(document.createElement('div'))
            .addClass('popup-window')
            .css({
                width  : this.innerWidth,
                height : this.innerHeight
            })
            .hide()
            .appendTo(document.body);

        this.outerWidth = this._$wrap.outerWidth();
        this.outerHeight = this._$wrap.outerHeight();

        // Кнопка закрытия
        $(document.createElement('div'))
            .addClass('close-btn')
            .html('Закрыть')
            .appendTo(this._$wrap)
            .click(function() { self.close() });

        // Место контента
        this.$content = $(document.createElement('div'))
            .css({
                clear    : 'both',
                overflow : this.contentOverflow,
                height   : this.innerHeight
            })
            .appendTo(this._$wrap);

        // Выравниваем
        var pos = this._getAlignmentCoords();
        this._$wrap.css({
            left : pos.left,
            top  : pos.top
        })

        // Событие отрисовки
        this._eventDispatcher.dispatchEvent('draw', this);

        // Показываем окно
        if (this.animation) {
            var __show = function() {
                self._$wrap.fadeIn(
                    self.fadeDuration,
                    function() {
                        self._eventDispatcher.dispatchEvent('show', self);
                    }
                );
            }

            if ((this.animationSlide) && (this._slideAncestor)) {
                var $sa = $(this._slideAncestor);
                var aPos = $sa.offset();
                $(document.createElement('div'))
                    .addClass('pw-slide')
                    .css({
                        left   : aPos.left,
                        top    : aPos.top,
                        width  : $sa.outerWidth(),
                        height : $sa.outerHeight()
                    })
                    .animate(
                        {
                            left   : pos.left,
                            top    : pos.top,
                            width  : this.outerWidth,
                            height : this.outerHeight
                        },
                        this.slideDuration,
                        'swing',
                        function () {
                            __show();
                            $(this).remove();
                        }
                    )
                    .appendTo(this._d);

            } else {
                __show();
            }
        } else {
            this._$wrap.show();
            this._eventDispatcher.dispatchEvent('show', this);
        }
    },

    /**
     * Скрытие окна
     */
    _hide: function() {
        var self = this;
        if (this.animation) {
            this._$wrap.fadeOut(
                this.fadeDuration,
                function() {
                    self._$wrap.remove();
                    self._$overlay.remove();
                }
            );

        } else {
            this._$wrap.remove();
            this._$overlay.remove();
        }
    },

    /**
     * Координаты для выравнивания окна
     */
    _getAlignmentCoords: function() {
        var al = this.align.split('-');
        var top = 0, left = 0;

        switch (al[0]) {
            case 'left':
                left = this.borderOffset;
                break;
            case 'right':
                left = this._d.clientWidth - this.outerWidth - this.borderOffset;
                break;
            case 'center':
                left = (this._d.clientWidth - this.outerWidth) / 2;
        }
        switch (al[1]) {
            case 'top':
                top = this.borderOffset;
                break;
            case 'bottom':
                top = this._d.clientHeight - this.outerHeight - this.borderOffset;
                break;
            case 'center':
                top = (this._d.clientHeight - this.outerHeight) / 2;
        }
        var scrollBody = Browser.getScrollBody();
        left += scrollBody.scrollLeft;
        top += scrollBody.scrollTop;

        return {
            left : left,
            top  : top
        }
    }
};


