﻿Type.registerNamespace('BIT.WebControls');


BIT.WebControls.Dialog = function(element) {

    BIT.WebControls.Dialog.initializeBase(this, [element]);

    this.addProperty('useIframe', (Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7));

    this.addProperty('clientVisible', false);
    this.addProperty('pageGrayCssClass', null);

    this.addProperty('attachToScroll', false);

    this.addProperty('zIndexBase', 1000);

    this.addProperty('top', null);
    this.addProperty('left', null);

    this.addProperty('displayOnStart', false);
    this.addProperty('clientStateField', null);

    this.addEvent('show');
    this.addEvent('hide');

    this.addEvent('init');
    this.addEvent('dispose');

    this._prevZIndex = null;
    this._subElement = null;

    this._handleEndRequestDelegate = null;

}

BIT.WebControls.Dialog.prototype =
{
    get_zIndexBase: function() {
        if (!this.zIndexBase && this.zIndexBase != 0)
            return 1000;

        return this.zIndexBase;
    },

    set_top: function(value) {
        this.top = (value == '' || !value || value.IsEmpty) ? null : (!value.IsEmpty ? value.Value + 'px' : value);
    },

    set_left: function(value) {
        this.left = (value == '' || !value || value.IsEmpty) ? null : (!value.IsEmpty ? value.Value + 'px' : value);
    },


    set_clientVisible: function(value) {
        if (!this.get_isInitialized()) {
            this.clientVisible = !!value;
            this.saveClientState();
        }
        else {
            if (value)
                this.show();
            else
                this.hide();
        }
    },

    get_clientVisible: function() {
        return this.clientVisible;
    },

    get_attachToScroll: function() {
        return this.attachToScroll;
    },

    set_attachToScroll: function(value) {
        this.attachToScroll = value;
    },

    set_useIframe: function(value) {
        if (this.get_isInitialized())
            throw Error.invalidOperation();

        this.useIframe = value;
    },

    _getResizeEvtBlock: function() {
        if ((Sys.Browser.agent == Sys.Browser.InternetExplorer) ||
			(Sys.Browser.agent == Sys.Browser.Firefox))
            return window;

        return (document.getElementsByTagName && document.getElementsByTagName('body')[0])
    },

    saveClientState: function() {
        if (this.get_clientStateField()) {
            this.get_clientStateField().value = Sys.Serialization.JavaScriptSerializer.serialize(
				({
				    'clientVisible': this.get_clientVisible(),
				    'top': this.get_top(),
				    'left': this.get_left()
				})
			);
        }
    },

    show: function(left, top) {

        if (typeof (top) != 'undefined')
            this.set_top(top);

        if (typeof (left) != 'undefined')
            this.set_left(left);

        var tops = (this.attachToScroll) ? ((document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : ((document.body && document.body.scrollTop) ? document.body.scrollTop : 0)) : 0;

        var elm = this._subElement;

        elm.style.zIndex = $getComputedStyle(elm, 'z-index', true) || 1;

        if (this._prevZIndex === null)
            this._prevZIndex = elm.style.zIndex;

        var ssize = $getDocSize();
        var isize = $getDocInnerSize();

        with (elm.style) {
            position = 'absolute';
            top = this.top || (((isize.y - elm.offsetHeight) / 2 + tops) + 'px');
            left = this.left || (((isize.x - elm.offsetWidth) / 2) + 'px');
        }

        var needResizeGrayDiv = false;
        if (((isize.y - elm.offsetHeight) / 2 + tops) < tops) {
            elm.style.top = tops + 'px';
            needResizeGrayDiv = true;
        }

        var pg = BIT.WebControls.Dialog._pageGray;

        pg.className = (this.pageGrayCssClass || '');

        $clearTimeout(this, '_timerId');

        with (pg.style) {
            display = '';
            width = ssize.x + 'px';
            height = ssize.y + 'px';
            zIndex = elm.style.zIndex - 1;
        }

        for (i = 0; i < 10000; i++) { var s = s + i; }

        if (needResizeGrayDiv)
            this._windowResize();

        this._updateIframe(pg);

        pg = null;


        this.clientVisible = true;
        this.saveClientState();

        var vs = BIT.WebControls.Dialog._visibleStack;

        if (vs.length == 0)
            $addHandler(this._getResizeEvtBlock(), 'resize', BIT.WebControls.Dialog._windowResizeDelegate);

        Array.remove(vs, this);
        Array.add(vs, this);

        vs = null;

        this._updateZIndexes();

        this.raiseEvent('show');


    },


    startDrag: function(evt) {
        this._addHandlers();

        if (evt)
            this._docMove(evt);
    },

    hide: function() {
        var elm = this._subElement;

        with (elm.style) {
            position = 'absolute';
            top = left = '-1000000px';
        }

        if (this.clientVisible) {
            if (this._prevZIndex !== null) {
                elm.style.zIndex = this._prevZIndex;
                this._prevZIndex = null;
            }

            this.clientVisible = false;
            this.saveClientState();

            Array.remove(BIT.WebControls.Dialog._visibleStack, this);

            this._updateZIndexes();

            this._removeHandlers();

            this.raiseEvent('hide');
        }
    },

    toggle: function() {
        this.set_clientVisible(!this.get_clientVisible());
    },


    _updateZIndexes: function() {
        var dlg = BIT.WebControls.Dialog;

        var vs = dlg._visibleStack;
        var vsl = vs.length;

        var pg = dlg._pageGray;

        if (vsl == 0) {
            if (pg)
                pg.style.display = 'none';

            $removeHandler(this._getResizeEvtBlock(), 'resize', BIT.WebControls.Dialog._windowResizeDelegate);
            $clearTimeout(this, '_timerId');
        }
        else {
            var zib = this.get_zIndexBase();

            vs[vsl - 1]._subElement.style.zIndex = vsl + 10 + zib;
            pg.style.zIndex = vsl + 5 + zib;

            var pgclass = (vs[vsl - 1].pageGrayCssClass || '');

            if (pg.classname !== pgclass)
                pg.classname = pgclass;

            for (var i = vsl - 2; i >= 0; i--)
                vs[i]._subElement.style.zIndex = i + zib;
        }

        if (pg)
            this._updateIframe(pg);

        dlg = null;
    },


    _windowResize: function() {
        var dlg = BIT.WebControls.Dialog

        var pg = dlg._pageGray;

        pg.style.display = 'none';

        this._updateIframe(pg);

        $clearTimeout(this, '_timerId');
        $setTimeout(this, '_timerId', this._windowResizeStep, 5);

    },

    _windowResizeStep: function() {
        var dlg = BIT.WebControls.Dialog;

        if (!dlg._visibleStack || dlg._visibleStack.length == 0)
            return;

        var ssize = $getDocSize();

        with (dlg._pageGray.style) {
            display = '';
            width = ssize.x + 'px';
            height = ssize.y + 'px';
        }

        this._updateIframe(dlg._pageGray);
    },


    _docUp: function(evt) {
        this._docMove(evt);
        this._removeHandlers();

        if (document.recalc)
            document.recalc();

        var isize = $getDocSize();

        if ((isize.x != this.startSize.x) ||
			(isize.y != this.startSize.y))
            this._windowResize();

        this.startMousePos = null;
        this.startBounds = null;
        this.startSize = null;
    },



    _docMove: function(evt) {

        var pos = $getMousePos(evt);

        if (!this.startMousePos)
            this.startMousePos = pos;

        if (!this.startBounds)
            this.startBounds = $getBounds(this._subElement);

        if (!this.startSize)
            this.startSize = $getDocSize();

        this.left = (this.startBounds.x + pos.x - this.startMousePos.x) + 'px';
        this.top = (this.startBounds.y + pos.y - this.startMousePos.y) + 'px';

        with (this._subElement.style) {
            top = this.top;
            left = this.left;
        }

        evt.preventDefault();
        evt.stopPropagation();
    },


    _addHandlers: function() {
        if (this._docHandled)
            return;

        $addHandler(document, 'mousemove', this._docMoveDelegate)
        $addHandler(document, 'mouseup', this._docUpDelegate)

        this._docHandled = true;
    },

    _removeHandlers: function() {
        if (!this._docHandled)
            return;

        $removeHandler(document, 'mousemove', this._docMoveDelegate)
        $removeHandler(document, 'mouseup', this._docUpDelegate)

        this._docHandled = false;
    },

    initialize: function() {
        BIT.WebControls.Dialog.callBaseMethod(this, "initialize");


        var telm = ((document.forms.length > 0) ? document.forms[0] : document.body);

        this._subElement = telm.appendChild($removeFromParent(Sys.UI.DomElement.getChildren(this.get_element())[0]));
        this._subElement._object = window[this.get_id()] = this;

        telm = null;

        this.raiseEvent('init');

        var dlg = BIT.WebControls.Dialog;

        if (typeof (dlg._visibleStack) == 'undefined' || ((dlg._visibleStack == null || dlg._visibleStack.length == 0) && dlg._windowResizeDelegate == null)) {
            dlg._visibleStack = [];
            dlg._pageGray = document.createElement('div');

            with (dlg._pageGray.style) {
                display = 'none';
                position = 'absolute';
                top = left = '0px';
                width = height = '1px';
            }

            document.body.appendChild(dlg._pageGray);

            if (this.useIframe)
                dlg._pageGray.iframe = $addIframe(dlg._pageGray, true);

            dlg._windowResizeDelegate = Function.createDelegate(this, this._windowResize);
        }

        this._docUpDelegate = Function.createDelegate(this, this._docUp);
        this._docMoveDelegate = Function.createDelegate(this, this._docMove);

        dlg = null;


        if (this.get_clientVisible()) {
            this.show(null, null, false);
        }

        this._handleEndRequestDelegate = Function.createDelegate(this, this._handleEndRequest);

        if (Sys.WebForms && Sys.WebForms.PageRequestManager)
            this._pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();

        if (this._pageRequestManager != null)
            this._pageRequestManager.add_endRequest(this._handleEndRequestDelegate);
    },

    get_subElement: function() {
        return this._subElement;
    },


    dispose: function() {
        var elm = this._subElement;

        if (this._pageRequestManager != null)
            this._pageRequestManager.remove_endRequest(this._handleEndRequestDelegate);

        this.hide();

        var dlg = BIT.WebControls.Dialog;

        if (dlg._visibleStack.length === 0) {
            dlg._visibleStack = [];

            if (dlg._pageGray) {
                if (dlg._pageGray.iframe) {
                    $removeFromParent(dlg._pageGray.iframe);
                    dlg._pageGray.iframe = null;
                }

                $removeFromParent(dlg._pageGray);
                dlg._pageGray = null;
            }

            dlg._windowResizeDelegate = null;
        }

        dlg = null;

        this._docUpDelegate = null;
        this._docMoveDelegate = null;

        this._removeHandlers();

        this.raiseEvent('dispose');

        elm._object = window[this.get_id()] = null;

        if (this._subElement) {
            this.get_element().appendChild($removeFromParent(this._subElement));
            this._subElement = null;
        }

        BIT.WebControls.Dialog.callBaseMethod(this, "dispose");
    },

    _handleEndRequest: function(sender, arg) {
        var dataItem = arg.get_dataItems()[this.get_id()];

        if (dataItem && dataItem.length == 1)
            this._update(dataItem[0]);
    },

    _update: function(dataItem) {
        if (typeof (dataItem['top']) != 'undefined')
            this.set_top(dataItem['top']);

        if (typeof (dataItem['left']) != 'undefined')
            this.set_left(dataItem['left']);

        if (typeof (dataItem['clientVisible']) != 'undefined')
            this.set_clientVisible(dataItem['clientVisible']);

    },

    _updateIframe: function(elm) {

        if (elm && elm.iframe) {
            var stl = elm.iframe.style;

            if (elm.style.display == 'none') {
                with (stl) {
                    display = 'none';
                    top = left = '0px';
                    width = height = '1px';
                }
            }
            else {
                var bnds = $getBounds(elm);

                with (stl) {
                    display = elm.style.display;
                    width = bnds.width + 'px';
                    height = bnds.height + 'px';
                    left = bnds.x + 'px';
                    top = bnds.y + 'px';

                    zIndex = ($getComputedStyle(elm, 'z-index', true) || 2) - 1;
                }
            }


            stl = null;
        }
    }
}

BIT.WebControls.Dialog.registerClass('BIT.WebControls.Dialog', Sys.UI.Control);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();