﻿/// <reference name="MicrosoftAjax.js"/>



Type.registerNamespace("TUI.Web.UI.WebControls");



TUI.Web.UI.WebControls.DialogPosition = function() {}
TUI.Web.UI.WebControls.DialogPosition.prototype =
{
    centerClient: 0,
    centerBelowTarget: 1,
    centerAboveTarget: 2,
    nearTargetInsideClient: 3,
    custom: 4
}
TUI.Web.UI.WebControls.DialogPosition.registerEnum('TUI.Web.UI.WebControls.DialogPosition');



TUI.Web.UI.WebControls.Dialog = function(element) {
    TUI.Web.UI.WebControls.Dialog.initializeBase(this, [element]);

    this._$element = $(element);
    this._$overlay = null;
    this._targetControl = null;
    this._customCloseControl = null;
    this._showAtStartup = false;
    this._isDraggable = false;
    this._isModal = false;
    this._clearInputsOnDisplay = false;
    this._showOverlay = false;
    this._dynamicServiceFullPath = null;
    this._dynamicServiceArguments = null;
    this._dialogPosition = TUI.Web.UI.WebControls.DialogPosition.centerClient;
    this._callBackFunction = null;

    if (this._$element.children().length == 0) {
        // Clientside creation
        if (element.tagName.toLowerCase() != 'div') {
            throw Error.argument('element', 'An error occured during clientside creation of a Dialog control. The top element must be of type DIV.');
        }

        this._$element.addClass('dialog');
        this._$element.append("<div class='dialog-top'><div class='dialog-top-outer'><div class='dialog-top-inner'><div class='dialog-top-text'></div><a class='dialog-top-close-link' href='javascript:void(0)' title=''></a></div></div></div>"); // Caption
        this._$element.append("<div class='dialog-center'><div class='dialog-center-outer'><div class='dialog-center-inner'></div></div></div>"); // Content
        this._$element.append("<div class='dialog-bottom'><div class='dialog-bottom-outer'><div class='dialog-bottom-inner'></div></div></div>"); // Bottom

        if ($.browser.msie) {
            this._$element.addClass('dialog-ie');

            if ($.browser.version <= 6) {
                // Insert invisible image for correct IE6 collapse behaviour
                var invisibleImgStr = "<img src='"+oBaseAppSettings.IncludeSiteDirectory+"/images/clear.gif' />";
                this._$element.find('div.dialog-top-text, div.dialog-bottom-inner').html(invisibleImgStr);
            }
        }
    }
}
TUI.Web.UI.WebControls.Dialog.prototype =
{
    initialize: function() {
        TUI.Web.UI.WebControls.Dialog.callBaseMethod(this, 'initialize');

        Sys.UI.DomElement.setVisibilityMode(this.get_element(), Sys.UI.VisibilityMode.hide);
        this._$element.find('a.dialog-top-close-link').click(Function.createDelegate(this, this.hide));

        if (this.get_showAtStartup()) {
            this.show();
        }
    },
    dispose: function() {
        TUI.Web.UI.WebControls.Dialog.callBaseMethod(this, 'dispose');

        if (this._$overlay != null) {
            this.get_$overlay().remove();
        }

        if (this.get_targetControl() != null) {
            $clearHandlers(this.get_targetControl());
        }
    },
    updated: function() {
        TUI.Web.UI.WebControls.Dialog.callBaseMethod(this, 'updated');

        if (this.get_isDraggable()) {
            if (!this._$element.hasClass('ui-draggable')) {
                this._$element.draggable({ handle: 'div.dialog-top' });
            }
        }
        else if (this._$element.hasClass('ui-draggable')) {
            this._$element.draggable('destroy');
        }

        if (Sys.UI.DomElement.getVisible(this.get_element())) {
            this.updatePosition();

            if (this.get_dynamicServiceFullPath() != null) {
                this.performDynamicPopulation();
            }
        }
    },
    show: function() {
        if (!Sys.UI.DomElement.getVisible(this.get_element())) {
            if ((this.get_showOverlay() || this.get_isModal()) && !($.browser.msie && $.browser.version <= 6)) {
                this.get_$overlay().show();
            }

            if (this.get_clearInputsOnDisplay()) {
                this._$element.find('input:text, textarea').val('');
                this._$element.find('select').each(function() { this.selectedIndex = 0; });
                this._$element.find(':checked').attr('checked', false);
            }

            Sys.UI.DomElement.setVisible(this.get_element(), true);
            this.updatePosition();

            if (this.get_dynamicServiceFullPath() != null) {
                this.performDynamicPopulation();
            }
        }
    },
    hide: function() {
        if ((this.get_showOverlay() || this.get_isModal()) && !($.browser.msie && $.browser.version <= 6)) {
            this.get_$overlay().hide();
        }

        Sys.UI.DomElement.setVisible(this.get_element(), false);
    },
    updatePosition: function() {
        this._$element.css('position', ''); // Reset to default css specification

        var DialogPositionEnum = TUI.Web.UI.WebControls.DialogPosition;

        if (this.get_dialogPosition() != DialogPositionEnum.custom) {
            if (this.get_targetControl() == null && this.get_dialogPosition() != DialogPositionEnum.centerClient) {
                throw Error.invalidOperation(String.format("DialogPosition was set to {0} but no target control has been specified, which is not allowed", this.get_dialogPosition()));
            }

            var 
                dialogLeft,
                dialogTop,
                clientWidth = document.documentElement ? document.documentElement.clientWidth : 600,
                clientHeight = document.documentElement ? document.documentElement.clientHeight : 400,
                $targetControl = this.get_targetControl() ? $(this.get_targetControl()) : null;

            switch (this.get_dialogPosition()) {
                case DialogPositionEnum.centerClient:
                    this._$element.css('position', $.browser.msie && $.browser.version <= 6 ? 'absolute' : 'fixed');
                    dialogLeft = clientWidth / 2 - this._$element.width() / 2;
                    dialogTop = clientHeight / 2 - this._$element.height() / 2;
                    break;
                case DialogPositionEnum.centerBelowTarget:
                    dialogLeft = $targetControl.position().left + $targetControl.width() / 2 - this._$element.width() / 2;
                    dialogTop = $targetControl.position().top + $targetControl.height() + 5;
                    break;
                case DialogPositionEnum.centerAboveTarget:
                    dialogLeft = $targetControl.position().left + $targetControl.width() / 2 - this._$element.width() / 2;
                    dialogTop = $targetControl.position().top - this._$element.height() - 5;
                    break;
                case DialogPositionEnum.nearTargetInsideClient:
                    if ($targetControl.offset().left < clientWidth / 2) {
                        // Align left
                        dialogLeft = $targetControl.position().left;

                        if ($targetControl.offset().top < clientHeight / 2) {
                            // From top left towards center
                            dialogTop = $targetControl.position().top + $targetControl.height() + 5;
                        }
                        else {
                            // From bottom left towards center
                            dialogTop = $targetControl.position().top - this._$element.height() - 5;
                        }
                    }
                    else {
                        // Align right
                        dialogLeft = $targetControl.position().left + $targetControl.width() - this._$element.width();

                        if ($targetControl.offset().top < clientHeight / 2) {
                            // From top right towards center
                            dialogTop = $targetControl.position().top + $targetControl.height() + 5;
                        }
                        else {
                            // From bottom right towards center
                            dialogTop = $targetControl.position().top - this._$element.height() - 5;
                        }
                    }
                    break;
            }

            // Set position and ensure within browser upper-left bounds
            this._$element.css('left', dialogLeft < 10 ? 10 : dialogLeft);
            this._$element.css('top', dialogTop < 10 ? 10 : dialogTop);
        }
    },
    performDynamicPopulation: function() {
        var 
            isProxyAjaxMethod,
            $dialogCenterInner = this._$element.find('div.dialog-center-inner');

        $dialogCenterInner.html("<img class='ajax-loader' src='" + oBaseAppSettings.IncludeSiteDirectory + "/images/clear.gif' />");

        try {
            isProxyAjaxMethod = (typeof eval(this.get_dynamicServiceFullPath())).toLowerCase() == 'function';
        }
        catch (e) {
            isProxyAjaxMethod = false;
        }

        if (isProxyAjaxMethod) {
            // The handler is a clientside MS AJAX javascript proxy method
            var 
                dynamicServiceInvocationExpression = this.get_dynamicServiceFullPath(),
                dynamicServiceArguments = this.get_dynamicServiceArguments();

            dynamicServiceInvocationExpression += "(";

            for (key in dynamicServiceArguments) {
                dynamicServiceInvocationExpression += "dynamicServiceArguments['" + key + "']";
                dynamicServiceInvocationExpression += ",";
            }

            dynamicServiceInvocationExpression += "Function.createDelegate(this, function(content) { $dialogCenterInner.html(content); this.updatePosition(); })";
            dynamicServiceInvocationExpression += ")";
            eval(dynamicServiceInvocationExpression);
        }
        else {
            // The handler is an ordinary page
            $dialogCenterInner.load(this.get_dynamicServiceFullPath(), this.get_dynamicServiceArguments(), Function.createDelegate(this, function() { this.updatePosition(); if (typeof (this.get_callBackFunction()) != "undefined") { eval(this.get_callBackFunction()); } }));
        }
    },
    get_$overlay: function() {
        if (this._$overlay == null) {
            this._$overlay = $("<div class='dialog-overlay'></div>").prependTo(this._$element.parent());

            if (this.get_showOverlay()) {
                // Apply background color css class to make the overlay become visible
                this._$overlay.addClass('dialog-overlay-background');
            }
            else {
                this._$overlay.removeClass('dialog-overlay-background');
            }

            if (!this.get_isModal()) {
                // Clicking on a non-modal overlay should simply close the dialog
                this._$overlay.click(Function.createDelegate(this, this.hide));
            }
        }

        return this._$overlay;
    },
    get_targetControl: function() { return this._targetControl; },
    set_targetControl: function(element) {
        if (this._targetControl != null) {
            $clearHandlers(this._targetControl);
        }

        this._targetControl = element;

        if (element != null) {
            $addHandler(element, 'click', Function.createDelegate(this, function(e) { e.preventDefault(); if (Sys.UI.DomElement.getVisible(this.get_element())) { this.hide(); } else { this.show(); } }));
        }
    },
    get_customCloseControl: function() { return this._customCloseControl; },
    set_customCloseControl: function(element) {
        if (this._customCloseControl != null) {
            $clearHandlers(this._customCloseControl);
        }

        this._customCloseControl = element;

        if (element != null) {
            $addHandler(element, 'click', Function.createDelegate(this, function(e) { e.preventDefault(); this.hide(); }));
        }
    },
    get_showAtStartup: function() { return this._showAtStartup; },
    set_showAtStartup: function(value) { this._showAtStartup = value; },
    get_isDraggable: function() { return this._isDraggable; },
    set_isDraggable: function(value) { this._isDraggable = value; },
    get_isModal: function() { return this._isModal; },
    set_isModal: function(value) { this._isModal = value; },
    get_clearInputsOnDisplay: function() { return this._clearInputsOnDisplay; },
    set_clearInputsOnDisplay: function(value) { this._clearInputsOnDisplay = value; },
    get_showOverlay: function() { return this._showOverlay; },
    set_showOverlay: function(value) { this._showOverlay = value; },
    get_dialogPosition: function() { return this._dialogPosition; },
    set_dialogPosition: function(value) { this._dialogPosition = value; },
    get_dynamicServiceFullPath: function() { return this._dynamicServiceFullPath; },
    set_dynamicServiceFullPath: function(value) { this._dynamicServiceFullPath = value; },
    get_dynamicServiceArguments: function() { return this._dynamicServiceArguments; },
    set_dynamicServiceArguments: function(value) { this._dynamicServiceArguments = value; },
    get_callBackFunction: function() { return this._callBackFunction; },
    set_callBackFunction: function(value) { this._callBackFunction = value; },
    get_innerHtmlTop: function(value) {
        this._$element.find('div.dialog-top-text').html();
    },
    set_innerHtmlTop: function(value) {
        this._$element.find('div.dialog-top-text').html(value);
    },
    get_innerHtmlCenter: function(value) {
        this._$element.find('div.dialog-center-text').html();
    },
    set_innerHtmlCenter: function(value) {
        this._$element.find('div.dialog-center-inner').html(value);
    },
    get_innerHtmlBottom: function(value) {
        this._$element.find('div.dialog-bottom-text').html();
    },
    set_innerHtmlBottom: function(value) {
        this._$element.find('div.dialog-bottom-inner').html(value);
    }
}

TUI.Web.UI.WebControls.Dialog._globalDialogControl = null;

// Gets the current global dialog, or null if no global dialog has been created
TUI.Web.UI.WebControls.Dialog.getCurrentGlobalDialog = function()
{
    return TUI.Web.UI.WebControls.Dialog._globalDialogControl;
}

// Hides and destroys the last global dialog that was created, then creates a new global dialog based on the given properties.
TUI.Web.UI.WebControls.Dialog.createNewGlobalDialog = function(properties, extraCssClasses)
{
    var
        globalDialogControl = TUI.Web.UI.WebControls.Dialog._globalDialogControl,
        globalDialogElement;
    
    if (globalDialogControl != null)
    {
        globalDialogElement = globalDialogControl.get_element();
        globalDialogControl.hide();
        globalDialogControl.dispose();
        $(globalDialogElement).remove();
    }
    
    globalDialogElement = $("<div id='global-dialog'></div>").appendTo("form").get(0);
    
    if (extraCssClasses)
    {
        $(globalDialogElement).addClass(extraCssClasses);
    }
    
    return globalDialogControl = TUI.Web.UI.WebControls.Dialog._globalDialogControl = $create
    (
        TUI.Web.UI.WebControls.Dialog, 
        properties,
        null, 
        null, 
        globalDialogElement
    );
}

TUI.Web.UI.WebControls.Dialog.registerClass('TUI.Web.UI.WebControls.Dialog', Sys.UI.Control);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();