﻿//Class that manages windows.
//- singleton
//- regiter global event handlers
//- log a window for being shown
//- hide currently visible window
Type.registerNamespace('Sunny.Web.UI');

Sunny.Web.UI.RadWindowControllerClass = function()
{
    /// <exclude/>
    //Current visible window
    this._activeWindow = null;

    this._historyStack = [];

    //Attach body event handlers
    this._registerGlobalBodyEventHandlers();
}

Sunny.Web.UI.RadWindowControllerClass.prototype =
{
    //Returns a reference to the controller
    getInstance : function()
    {
        /// <exclude/>
        return this;
    },

    _registerGlobalBodyEventHandlers : function()
    {
        //Register a single keydown handler for the body to handle ESC

        //ESC handler
        var escHandler = Function.createDelegate(null, function(e)
        {
            if (e.keyCode == 27)//Escape
            {
                Sunny.Web.UI.RadWindowController.hideCurrentWindowIfNonModal();
            }
        });

        $addHandler(document.documentElement, 'keydown', escHandler);

        //Dispose the globale event handlers
        Sys.Application.add_unload(function()
        {
            $removeHandler(document.documentElement, 'keydown', escHandler);
        });
    },


    //Forces hide to currently visible window
    hideCurrentWindowIfNonModal : function()
    {
        /// <exclude/>
        if (this._activeWindow != null && this._activeWindow.isModal &&  !this._activeWindow.isModal())//NEW: Do not close if window is modal
        {
            this._activeWindow.close();
        }
        this._activeWindow = null;
    },

    inactivateCurrentWindow : function()
    {
        if (this._activeWindow != null)
        {
          this._activeWindow.setActive(false);
        }
        this._activeWindow = null;
    },


    set_activeWindow : function(newWindow)
    {
        /// <exclude/>
        if (newWindow == this._activeWindow) return;

        this.inactivateCurrentWindow();
        this._activeWindow = newWindow;

        //Add the window to the history stack
	    Array.remove(this._historyStack, newWindow);
	    Array.add(this._historyStack, newWindow);
    },

    notifyWindowClosed : function (newWindow)
    {
        /// <exclude/>
        if (this._activeWindow == newWindow)
        {
            this._activeWindow = null;
        }

        //Remove the window to the history stack
	    Array.remove(this._historyStack, newWindow);

        this._activatePreviousWindow();
    },

    //Factored out code activation code
	_activatePreviousWindow : function()
	{
	    var array = this._historyStack;
	    var i = array.length - 1;
	    for (; i >= 0; i--)
	    {
	        var newWindow = array[i];
	        if (!newWindow) return;

	        if (newWindow.isCreated() && !newWindow.isClosed() && !newWindow.isMinimized() )
		    {
			    newWindow.setActive(true);
			    break;
		    }
		    else
		    {
		        //Remove from stack
		        Array.removeAt(array, i);
		    }
	    }
	},

    get_activeWindow : function()
    {
        return this._activeWindow;
    }
}

Sunny.Web.UI.RadWindowControllerClass.registerClass('Sunny.Web.UI.RadWindowControllerClass', null);

//Create a singleton
if (!Sunny.Web.UI.RadWindowController)
{
    Sunny.Web.UI.RadWindowController = new Sunny.Web.UI.RadWindowControllerClass();
}


Type.registerNamespace('Sunny.Web.UI');
Type.registerNamespace('Sunny.Web.UI.RadWindowUtils');


//Localization can be overridden using Javascript
Sunny.Web.UI.RadWindowUtils.Localization =
{
    "Close" : "Close",
    "Minimize" : "Minimize",
    "Maximize" : "Maximize",
    "Reload" : "Reload",
    "PinOn" : "Pin on",
    "PinOff" : "Pin off",
    "Restore" : "Restore",
    "OK" : "OK",
    "Cancel" : "Cancel",
    "Yes" : "Yes",
    "No" : "No"
};

///////////////////////////////////////////////////////////////////////////
// Sunny.Web.UI.RadWindow
///////////////////////////////////////////////////////////////////////////
Sunny.Web.UI.RadWindow = function(element) {
    /// <summary>
    /// The Window control implements a rich UI window for a HTML target element
    /// </summary>
    /// <param name="element" type="Sys.UI.DomElement" domElement="true">
    /// DOM element associated with the behavior
    /// </param>
    Sunny.Web.UI.RadWindow.initializeBase(this, [element]);

    //Events array (needed by the clone method)
    this._eventNames = ["resize", "activate", "dragStart", "dragEnd", "show", "pageLoad", "close", "command"];

    this._openerElement = null;
    this._offsetElement = null;
    this._popupElement = null;
    this._tableElement = null;
    this._contentElement = null;
    this._contentCell = null;
    this._titleElement = null;
    this._titleCell = null;
    this._titlebarElement = null;
    this._statusCell = null;
    this._statusMessageElement = null;
    this._iframe = null;
    this._buttonsElement = null;//Button holder for elements
    this._buttonsArray = [];

    //Member variables
    this.isIE = ($Sunny.isIE);
    this._openerElementID = null;
    this._offsetElementID = null;
    this._behaviors = Sunny.Web.UI.WindowBehaviors.Default;
    this._initialBehaviors = Sunny.Web.UI.WindowBehaviors.None;
    this._navigateUrl = null;
    this._left = "";
    this._top = "";
    this._formID = null;
    this._skin = "Default";
    this._title = "";
    this._width = "300px";
    this._height = "300px";
    this._minimizeZoneID = null;
    this._restrictionZoneID = "";
    this._clientCallBackFunction = null;

    //Boolean properties
    this._reloadOnShow = false;
    this._visibleOnPageLoad = false;
    this._destroyOnClose = false;
    this._visibleTitlebar = true;
    this._visibleStatusbar = true;
    this._showContentDuringLoad = true;
    this._modal = false;
    this._overlay = false;
    this._keepInScreenBounds = false;
    this._autoSize = false;

    //TODO: These do not have clientside implementation at all yet
    this._iconUrl = null;
    this._minimizeIconUrl = null;

    //Animation
    this._animation = Sunny.Web.UI.WindowAnimation.None;
    this._windowAnimation = null;

    //Event handler delegates
    this._onMouseDownDelegate = null;
    this._onClickDelegate = null;
    this._onTitlebarDblclickDelegate = null;
    this._onTitlebarClickDelegate = null;
    this._onWindowResizeDelegate = null;
    this._onIframeLoadDelegate = null;
    this._onChildPageUnloadDelegate = null;
    this._onChildPageClickDelegate = null;

    this._onModalShowHandler = null;
    this._onModalCloseHandler = null;

    //Internal utility props
    this._loaded = false;
    this._isCloned = false;
    this._restoreRect = null;//Save the position of the window - and use it on subsequent shows
    this._popupBehavior = null;
    this._popupVisible = false;

    //Window manager!
    this._windowManager;
    
    //NEW - Svetlina - 16.12.08
    this._browserWindow = window;

    //-------------- Backward compatibility layer --------------------------//
    this.GetWindowManager = this.get_windowManager;        
    this.BrowserWindow = window;       
    this.GetContentFrame = this.get_contentFrame;
    this.GetLeftPosition = function() { this.getWindowBounds().x; };
    this.GetTopPosition = function() {  this.getWindowBounds().y; };
    this.GetTitlebar = function() { return this._titleCell; };
    this.GetStatusbar = function(){ return this._statusCell; };
    this.SetOpenerElementId = this.set_openerElementID;
    this.SetStatus  = this.set_status;
    this.GetStatus = this.get_status;
    this.SetModal = this.set_modal;
    this.SetWidth = this.set_width;
    this.SetHeight = this.set_height;
    this.GetWidth = this.get_width;
    this.GetHeight = this.get_height;
    this.SetOffsetElementId = this.set_offsetElementID;
    this.SetTitle = this.set_title;
    this.MoveTo = this.moveTo;
    this.Center = this.center;
    this.SetVisible = this.setVisible;
    this.SetSize = this.setSize;
    this.Show = this.show;
    this.Hide = this.hide;
    this.GetUrl = this.get_navigateUrl;
    this.SetUrl = this.setUrl;
    this.Reload = this.reload;
    this.SetActive = this.setActive;
    this.Minimize = this.minimize;
    this.Restore = this.restore;
    this.Maximize = this.maximize;
    this.Close = this.close;
    this.TogglePin = this.togglePin;
    this.IsMaximized = this.isMaximized;
    this.IsMinimized  = this.isMinimized;
    this.IsModal = this.isModal;
    this.IsClosed  = this.isClosed;
    this.IsPinned  = this.isPinned;
    this.IsVisible = this.isVisible;
    this.IsActive = this.isActive;
    this.IsBehaviorEnabled = this.isBehaviorEnabled;
    //-------------- End backward compatibility layer --------------------------//
}

Sunny.Web.UI.RadWindow.prototype = {

    //TODO: Replace here with "real" localization
    _getLocalization : function()
    {
        return Sunny.Web.UI.RadWindowUtils.Localization;
    },

    _registerIframeLoadHandler : function(attachEvent)
    {
        if (!this._iframe) return;

        if (attachEvent)
        {
            this._onIframeLoadDelegate = Function.createDelegate(this, this._onIframeLoad);
            $addHandler(this._iframe, "load", this._onIframeLoadDelegate);
        }
        else if (this._onIframeLoadDelegate)
        {
            $removeHandler(this._iframe, "load", this._onIframeLoadDelegate);
            this._onIframeLoadDelegate = null;
            //NEW: Memory leak in MS AJAX - only $clearHandler will set _events to null and prevent the leak
            $clearHandlers(this._iframe);
        }
    },

    _registerWindowResizeHandler : function(attachEvent)
    {
        if (attachEvent)
        {
            this._onWindowResizeDelegate = Function.createDelegate(this, this._maintainMaximizedSize);
            $addHandler(window, "resize", this._onWindowResizeDelegate);
        }
        else if (this._onWindowResizeDelegate)
        {
            $removeHandler(window, "resize", this._onWindowResizeDelegate);
            this._onWindowResizeDelegate = null;
        }
    },

     _registerOpenerElementHandler : function(targetElement, attachEvent)
    {
        if (!targetElement) return;
        if (true == attachEvent)
        {
            this._onClickDelegate = Function.createDelegate(this, this._onClick);
            $addHandler(targetElement, 'click', this._onClickDelegate);
         }
         else
         {
            var result = $removeHandler(targetElement, 'click', this._onClickDelegate);
            this._onClickDelegate = null;
         }
    },

    _registerTitlebarHandlers : function(flag)
    {
        var targetElement = this._titleCell;
	    if (flag)
	    {
            this._onTitlebarDblclickDelegate = Function.createDelegate(this, function()
            {                
                if (this.isMinimized())
                {
                    this.restore();                    
                }                
                //NEW: Make additional checks whether the behavior is enabled                                                                                
                else if(this.isBehaviorEnabled(Sunny.Web.UI.WindowBehaviors.Maximize)) 
                {
                    if (this.isMaximized()) this.restore();    
                    else this.maximize();
                }                                                                
            });

            this._onTitlebarClickDelegate = Function.createDelegate(this, function()
            {
                //Works in combination with the fact that clicking on a toolbar button should cancel the event before it gets to here
                this.setActive(true);
            });
                        
            $addHandler(targetElement, 'dblclick', this._onTitlebarDblclickDelegate);
            
            
            
            $addHandler(targetElement, 'click', this._onTitlebarClickDelegate);
	    }
	    else if (targetElement)//title cell might not exist if window UI was never created
	    {
	        if (this._onTitlebarDblclickDelegate)
	        {
	            $removeHandler(targetElement, "dblclick", this._onTitlebarDblclickDelegate);
	            this._onTitlebarDblclickDelegate = null;
	        }

	        if (this._onTitlebarClickDelegate)
	        {
	            $removeHandler(targetElement, "click", this._onTitlebarClickDelegate);
	            this._onTitlebarClickDelegate = null;
	        }
	        //Memory leak - the removeHandler function does not actually remove the _events property of the
	        //html element. Only clearHandlers does that.
	        $clearHandlers(targetElement);
	    }
    },

    //---------------------------------------- 'Modality' implementation ---------------------------------------------//
    _makeModal : function(bModal)
    {
       //Dispose of old state, whatever it was
       if (this._onModalShowHandler)
       {
           this.remove_show(this._onModalShowHandler);
           this._onModalShowHandler = null;
       }

       if (this._onModalCloseHandler)
       {
            this.remove_close(this._onModalCloseHandler);
            this._onModalCloseHandler = null;
       }

       if (this._modalExtender)
       {
            this._modalExtender.dispose();
            this._modalExtender = null;
       }

       //Return if modality should be turned off
       if (!bModal) return;

       //if it is an instance of window manager, return, we do not want associated events with the manager
       if (typeof(Sunny.Web.UI.RadWindowManager) != "undefined" && Sunny.Web.UI.RadWindowManager.isInstanceOfType(this))
       {
            return;
       }

       this._onModalShowHandler = function(sender)
       {
          //Create the modal overlay here, becase it needs to be passed an existing html this._popupElement
          if (!sender._modalExtender)
          {
            sender._modalExtender = new Sunny.Web.UI.ModalExtender(sender._popupElement);
          }


          //Show the modal overlay
          sender._modalExtender.show();

          //Re-center because of Mozilla
          sender.center();
       };
       this.add_show(this._onModalShowHandler);


       this._onModalCloseHandler = function(sender)
       {
           //Hide the modal overlay
           //It is crucial to use a timeout - or else IE crashes when closing a modal window opened from another modal window
           window.setTimeout(function()
           {
                if(sender._modalExtender) sender._modalExtender.hide();
           }, 10);
       };
       this.add_close(this._onModalCloseHandler);
    },

    //---------------------------------------- 'Resize' and 'Move' implementation ---------------------------------------------//

    _enableMoveResize : function(bEnable)
    {
        //Remove current resize extender
        if (this._resizeExtender)
        {
            this._resizeExtender.dispose();
            this._resizeExtender = null;
        }

        //Return of element must not be made resizable
        if (!bEnable) return;

        //Maybe dispose was called on the window that was never created?
        if (!this._popupElement) return;

        //This is the initialization object that must be 'filled' in and passed to the ResizeExtender
        var rows = this._tableElement.rows;

        //NEW: Do moveable and resizeable at the same time
        var hashTable = {};
        var isRightToLeft = this._isWindowRightToLeft();
                    
        //If bEnable is true, return if the resizable behavior is not enabled
        if (this.isBehaviorEnabled(Sunny.Web.UI.WindowBehaviors.Resize))
        {
            // In the case of direction=rtl, the cells of a table are automatically switched. That is why we need to switch the 
            // order in whick we pass the cells to the ResizeExtender.
            if(isRightToLeft)
            {
                hashTable =
                {
                    nw: rows[0].cells[2],
                    n: this._topResizer,
                    ne: rows[0].cells[0],
                    w: [rows[1].cells[2], rows[2].cells[2]],
                    e: [rows[1].cells[0],rows[2].cells[0]],
                    sw: rows[3].cells[2],
                    s: rows[3].cells[1],
                    se: [rows[3].cells[0], this._bottomResizer]
                };
            }
            else
            {
                hashTable =
                {
                    nw: rows[0].cells[0],
                    n: this._topResizer,
                    ne: rows[0].cells[2],
                    w: [rows[1].cells[0],rows[2].cells[0]],
                    e: [rows[1].cells[2], rows[2].cells[2]],
                    sw: rows[3].cells[0],
                    s: rows[3].cells[1],
                    se: [rows[3].cells[2], this._bottomResizer]
                };
            }
        }

        //NEW: If moveable
        if (this.isBehaviorEnabled(Sunny.Web.UI.WindowBehaviors.Move))
        {
            hashTable["move"] = this._titleCell;
        }

        this._resizeExtender = new Sunny.Web.UI.ResizeExtender(this, this._popupElement, hashTable, this._tableElement);
    },


    onResizeStart : function()
    {
        if (this.isMaximized()) return false;
        //NEW: Set active
        this.setActive(true);
        this._cachedDragZoneBounds = this._getRestrictionZoneBounds();
    },


    onResizing : function(bounds)
    {
       if (!this._cachedDragZoneBounds) return true;
       return this._checkRestrictionZoneBounds(this._cachedDragZoneBounds, bounds);
    },

    onResizeEnd : function()
    {
        /// <exclude />

        this._cachedDragWindowBounds = null;

        //Update popup size (this will make sure the overlay iframe gets updated too)
        var bounds = this._getCurrentBounds();

        //Update top and left
        this.moveTo(bounds.x, bounds.y);

        //In case you have an overlay element, you need to move it manually once the window is moved in Mozilla.
	    if(this._overlay && $Sunny.isFirefox) this._popupBehavior._onMove();

        //Raise resize event
        this.raiseEvent('resize', new Sys.EventArgs());
    },


    onDragStart : function()
	{
	    /// <exclude />
	    this.setActive(true);

	    //If pinned or NEW: maximized
        if (this.isPinned() || this.isMaximized()) return false;
        //If in a minimized zone
        if (this.isMinimized() && this.get_minimizeZoneID()) return false;

	    //Cache the zoneBounds to reduce calculations while moving in a restriction zone
        this._cachedDragZoneBounds = this._getRestrictionZoneBounds();
        //Cache current location for faster calculation - you dont change the size, you just move, so you can cache size
        this._cachedDragWindowBounds = $Sunny.getBounds(this._popupElement);

		this.raiseEvent("dragStart", new Sys.EventArgs());

        return true;
	},


	onDragEnd : function(canceled)
	{
	    /// <exclude />
	    //Destroy cached settings
	    this._cachedDragZoneBounds = null;
        this._cachedDragWindowBounds = null;

	    //In case you have an overlay element, you need to move it manually once the window is moved in Mozilla.
	    if(this._overlay && $Sunny.isFirefox) this._popupBehavior._onMove();

	    //This method is called each time the rwTitlebar is clicked, which is not so good as user might be clicking or doubleclicking
		this.raiseEvent("dragEnd", new Sys.EventArgs());
        
        //Update top and left
        var bounds = this._getCurrentBounds();
        this.moveTo(bounds.x, bounds.y);
        
        this.setActive(true);
	},


    onDrag : function(location)
    {
        /// <exclude />
        if (!this._cachedDragZoneBounds) return true;

        //If the element should be in a restriction zone
        var wndbounds = this._cachedDragWindowBounds;
        var zone = this._cachedDragZoneBounds;

        //Add width and height to the location. Use current[cached] size for the dimensions
        location.width =  wndbounds.width;
        location.height = wndbounds.height;

        var result = this._checkRestrictionZoneBounds(zone, location);
        //Modify location to return a DELTA to keep window in restriction bounds
        if (!result)
        {
            if (location.x <= zone.x)
            {
                location.x = zone.x;
            }
            else if (zone.x + zone.width <= location.x + wndbounds.width)
            {
                location.x = zone.x + zone.width - wndbounds.width;
            }

            if (location.y <= zone.y)
            {
                location.y = zone.y;
            }
            else if (zone.y + zone.height <= location.y + wndbounds.height)
            {
                location.y = zone.y + zone.height - wndbounds.height;
            }
            result = true;
        }

        return result;
    },

    //###########---------------- PUBLIC API ---------------------##################//
    initialize : function()
    {
        /// <exclude />
        Sunny.Web.UI.RadWindow.callBaseMethod(this, 'initialize');

        //if visible on page load - show        
        if (this._visibleOnPageLoad)
        {
            setTimeout(Function.createDelegate(this, function(){
                this.show();
	        })
	        , 0);
        }

        //Register window resize handler
        this._registerWindowResizeHandler(true);
    },

    dispose : function()
    {
        /// <exclude />
        var manager = this.get_windowManager();
        if (manager)
        {
            //Save state
            if (manager.get_preserveClientState()) manager.saveWindowState(this);

            //if destroyonclose - remove from window collection
            if (this._destroyOnClose)
            {
                manager.removeWindow(this);
            }
        }


        //If an open animation is currently going on, cancel it
        if (this._windowAnimation)  this._windowAnimation.dispose();

//        //the popup behavior inherits from Sys.UI.Behavior, which means it will be automatically disposed on application.unload event.
//        if (this._popupBehavior)
//        {
//            this._popupBehavior.dispose();
//            this._popupBehavior = null;
//        }

        this._enableMoveResize(false);
        this._makeModal(false);
        this._registerTitlebarHandlers(false);
        this._registerWindowResizeHandler(false);
        this._registerIframeLoadHandler(false);
        if (this._openerElement) this._registerOpenerElementHandler(this._openerElement, false);

        //Clean the buttons and detach event handlers
        this.set_behaviors(Sunny.Web.UI.WindowBehaviors.None);

		var iframe = this._iframe;
        if (iframe)
		{
			//NEW
			iframe.radWindow = null;

		    //MEMORYLEAK - Call onunload handler of the page by forcing a page change
		    iframe.src = "javascript:'<html></html>';";

		    //NEW: Destroy the iframe name - a problem in IE otherwise - when getElementById is called it returns the iframe with this name ?!
            iframe.name = "";
            iframe.removeAttribute("name");
            iframe.removeAttribute("NAME");
		}

		//Dispose the this._contentElement content if present - or else in the case with radprompt it instantiates new templates with same IDs each time
		if (this._contentElement)
		{
		    this._contentElement.innerHTML = "";
		}

		//NEW: Remove element from the DOM
		var popup = this._popupElement;
		if (popup && popup.parentNode)
		{
			popup.parentNode.removeChild(popup);
		}

        Sunny.Web.UI.RadWindow.callBaseMethod(this, 'dispose');
    },


    hide : function()
    {
        /// <summary>
        /// Hides the window
        /// </summary>
        this._hide();
        return true;
    },

    //clone method returns a new window with same settings as current
    //copyEventHandlers is a bool variable that instructs whether event handlers should be copied. Set to false when creating alert/prompt/confirm as the internal modal event handlers reference the windowmanager, and not the new window itself (valid for all event handlers that are created as delegates)
    clone : function(wndName, copyEventHandlers)
    {
       /// <summary>
       /// Creates a clone of the window
       /// </summary>
       /// <param name="value" type="String">
       /// The client id of the offset element
       /// </param>

       if (!wndName)
       {
            alert("Sunny.Web.UI.RadWindow.clone called without providing a name argument");
            return;
       }

       //Get the events object
       var evs = (copyEventHandlers != false) ? this._getEventsParameter() : null;

       //Get the properties object
       var props = this._getPropertiesParameter();

       var span = document.createElement("SPAN")//Create an element that does not need to be inserted in the document.body;
       span.setAttribute("id", wndName);//!

       var wnd = $create(Sunny.Web.UI.RadWindow,
                             props,
                             evs,
                             null,
                             span
                            );

       //Set the name
       wnd.set_name(wndName);

       //Mark as cloned
       wnd._isCloned = true;

       return wnd;
    },


    set_contentElement : function(contentElement)
    {
       /// <exclude />

       //Make sure the window UI is created before you set any content.
       this._createUI();

       //NEW: Removing the iframe causes a memory leak despite calling all kinds of detach event handlers stuff
       //if (this._iframe) this._iframe.parentNode.removeChild(this._iframe);
       //this._contentCell.innerHTML = "";
       if (this._iframe)
       {
            this._iframe.style.display = "none";
       }

       if (contentElement.parentNode && contentElement.parentNode.removeChild)
       {
           contentElement.parentNode.removeChild(contentElement);
       }

       this._contentCell.appendChild(contentElement);
       contentElement.style.display = "";//make visible

       //Set as content element in order to calculate overflow!
       this._contentElement = contentElement;
    },

    get_contentElement : function()
    {
       /// <exclude />
       return this._contentElement;
    },

    //--------------------//
    isCreated : function()
    {
        return this._popupElement != null;
    },

    show : function()
    {
        /// <summary>
        /// Displays the window at the proper position, relative to its target control.
        /// </summary>

        var isCreated = this.isCreated();

        //Lazy initialization - create UI before show
        this._createUI();

		//Has not been loaded before or should load each time
		if (this._navigateUrl && (!isCreated || this._reloadOnShow))
		{
			this.setUrl(this._navigateUrl);
		}


        //Fixes a size bug in IE in DOCTYPE strict mode
        //NEW: OR does it? we should not be setting exact height to the _tableElement, but only to the _popupElement?
        //Needs further research
        //this._fixIeHeight(this._tableElement, this._height);

        //If there is some initial behavior specified - InitialBehaviors
        if (!isCreated && (this._initialBehaviors != Sunny.Web.UI.WindowBehaviors.None))
		{
		    //Slight 2-line code duplication with below
			this._show();
            this._afterShow();

			if (this.isInitialBehaviorEnabled(Sunny.Web.UI.WindowBehaviors.Minimize))
			{
				this.minimize();
			}

			if(this.isInitialBehaviorEnabled(Sunny.Web.UI.WindowBehaviors.Maximize))
			{
				this.maximize();
			}

			if (this.isInitialBehaviorEnabled(Sunny.Web.UI.WindowBehaviors.Pin))
			{
			    this.togglePin();
			}
			//In case minimize is an initial bahavior and there is a minimize zone, calling show twice would result in
			//setting position:absolute for the window, after it is minimized to its zone and as a result, the window
			//will display outside of its zone.
			return;
		}

        //Show
        if (this._animation == Sunny.Web.UI.WindowAnimation.None)
        {
            this._show();
            //Raise event
            this._afterShow();
        }
        else
        {
            this._playAnimation();
        }
    },


    _show : function()
    {
           //TODO: Make cancelable and expose on the server
        this.raiseEvent('beforeShow', new Sys.EventArgs());

        //Set properly opener element ID
        if (this.get_offsetElementID() && !this._offsetElement)
        {
            var offsetElem = $get(this.get_offsetElementID());
            if (offsetElem)
            {
                this._offsetElement = offsetElem;
            }
        }

        //NEW: Setting the parent to be the body does not work well in quriksmode!, so we just keep the original parent instead, and then restore it
        var curParent = this._popupBehavior.get_parentElement();

        //Set the proper offset element
        if (this._offsetElement && !this._offsetSet)
        {
            this._popupBehavior.set_parentElement(this._offsetElement);

            //Once the window is shown, we do not want to offset to the parent anymore
            this._offsetSet = true;
        }

        //Set the rwTitlebar and rwStatusbar visible or hidden
        this.set_visibleTitlebar(this._visibleTitlebar);
        this.set_visibleStatusbar(this._visibleStatusbar);

        //Get window position and set it
        this._reSetWindowPosition();

        //Set the parent back to what it was, once you have shown it to avoid wrong positioning when restoring after minimize
        if (curParent != this._popupBehavior.get_parentElement()) this._popupBehavior.set_parentElement(curParent);

        //visible flag is set here, and not in _setPopupVisible as _setPopupVisible
        //is called on two occasions as a utility method to allow for proper size calculation
        this._popupVisible = true;
    },


    _hide : function()
    {
        if (!this._animation || this._animation == 0)
        {
            this._afterHide(); //no animation
        }
        else
        {
            var fnc = Function.createDelegate(this, this._afterHide);
            $Sunny.$(this._popupElement).stop().fadeOut(500, fnc);
        }        
    },

    //This function is called by both animation.onEnd and by the window code when there is no animation
    _afterHide : function()
    {
        //Possible if we have DestroyOnCLose = true + closing animation. Then with the current code dispose would run before _afterHide.
        if (!this._popupBehavior) return;

        //Set size and position - and do it before hiding the popup, else it shows up again
        if (this.isMaximized())
        {
            //this._restoreBounds();
            this.restore();
        }

        this._popupBehavior.hide(true);
        this._popupVisible = false;

        //Notify controller that window was hidden
        this._getWindowController().notifyWindowClosed(this);
        //NEW: Moved the raising of the close event to the close() method, because hide simply makes the window invisible, does not close it!
    },

    _afterShow : function()
    {
        this.setActive(true);

        //Store bounds when activating
        this._storeBounds();

        //Raise show event here!
        this.raiseEvent('show', new Sys.EventArgs());
    },

    _playAnimation : function()
    {
        //Common configuration for several animations
        var commonResizeAnimationConfiguration = Function.createDelegate(this, function()
        {
            //Get left and top relative to target element, then show window for a momenta and get absolute bounds, left and top
            var relativeBounds = this._getCalculatedPopupBounds();
            this._setPopupVisible(relativeBounds.x, relativeBounds.y);
            var endBounds = $Sunny.getBounds(this._popupElement);
            $Sunny.$(this._popupElement).hide();
            return endBounds;                   
        });                               
        
        //Get element to animate
        var animatedElement = this._popupElement;

        //Get the current animationsetting
        var animationType = this._animation;
       
        //Get startBounds                
        startBounds = this._openerElement ? $Sunny.getBounds(this._openerElement) : null;
        
        //Get end bounds
        var endBounds = commonResizeAnimationConfiguration();
       
        //Get position                 
        var position = "" + this._position;                
        
        //Get onAnimationStart
        onAnimationStart = null
        
        //Function is called on animation end
        var onAnimationEnd = Function.createDelegate(this,function()
        {
            //Make sure another window that might be visible gets hidden
            this._show();
            //Raise event
            this._afterShow();
        });
        
        Sunny.Web.UI.Animations.playJQueryAnimation(animatedElement, animationType, startBounds, endBounds, position, onAnimationStart, onAnimationEnd);
    },

    _onClick : function(e)
    {
        this.show();
        return this._cancelEvent(e);
    },

    _cancelEvent : function(e)
    {
        if (e)
        {
            e.returnValue = false;
            e.cancelBubble = true;
            e.preventDefault();//Or moz does not cancel the event
            e.stopPropagation();
        }
        return false;
    },


    _getWindowController : function()
    {
        return Sunny.Web.UI.RadWindowController.getInstance();
    },


    _getReloadOnShowUrl : function (ifrmUrl)
    {
		var str = 'rwndrnd=' + Math.random();

		if (ifrmUrl.indexOf('?') > -1) str = '&' + str;
		else str = '?' + str;
		ifrmUrl += str;

		return ifrmUrl;
	},


    _getPropertiesParameter : function()
    {
        if (!this._propertiesParameter)
        {
           var newPropsParam = {};
           for (var item in Sunny.Web.UI.RadWindow.prototype)
           {
                 var getter = this[item];

                 if (typeof(getter) == 'function' && item.indexOf("get_") == 0)
                 {
                    var propName = item.substring(4);

                    //If no setter exists, skip property
                    if (null == this["set_" + propName]) continue;

                    var result = getter.call(this);
                    if (null == result
                        //(typeof(result) != "boolean")
                        //&& (null == result || "" == result)
                        ) continue;// -> when result is boolen 'false', the following expression evals to true ->("" == result) ??
                        //NEW: In addition to this "" == 0 also returns true, which is no good
                        //so what should be done is just check for null, and that's it

                    newPropsParam[propName] = result;

                    //TODO: Implement re-initialization in a better way!
                    //We assume that the Skin property is the last property in a row in the properties list
                    if (propName == "skin") break;
                 }
           }

           this._propertiesParameter = newPropsParam;
        }

       var param = this._cloneObject(this._propertiesParameter);
       return param;
    },

    _getEventsParameter : function()
    {
        if (!this._eventsParameter)
        {
           var newEventsParam = {};
           var events = this.get_events();

           var eventNames = this._eventNames;
           for (var i=0; i < eventNames.length; i++)
           {
                var name = eventNames[i];
                var evName = events.getHandler(name);
                if (evName && typeof(eval(evName)) == "function")
                {
                    newEventsParam[name] = eval(evName);
                }
           }
           this._eventsParameter = newEventsParam;
       }
       return this._eventsParameter;
    },


    _cloneObject : function(source)
    {
        var target = {};
        for (var item in source)
        {
            target[item] = source[item];
        }
        return target;
    },

    //---------------------------------------------MORE PUBLIC API -----------------------------------------//
    getWindowBounds : function()
    {
        return this._getCalculatedPopupBounds();
    },


    toString : function()
    {
	    return "[RadWindow id=" + this.get_id() + "]";
    },

    center : function()
    {
        var bounds = this._getCentralBounds();
        this.moveTo(bounds.x, bounds.y);
    },

    moveTo : function(x,y)
    {
        var popupElement = this._popupElement;
        if(popupElement)
        {
            var popupBounds = $Sunny.getBounds(popupElement);
            var restrictionZoneBounds = this._getRestrictionZoneBounds();
            if(restrictionZoneBounds)
            {
                // Pass the absolute coordinates.
                var toUpdate = this._checkRestrictionZoneBounds(null, new Sys.UI.Bounds(x + restrictionZoneBounds.x, y + restrictionZoneBounds.y, popupBounds.width, popupBounds.height));
                if(!toUpdate) return false;
            }
        }
    
        x = parseInt(x);
        y = parseInt(y);

        //NEW: Create UI in case it is called before showing the window
        this._createUI();

        this._setPopupVisible(x,y);
        this._storeBounds();
        
        return true;
    },

    setSize : function(width, height)
    {
        this._firstShow = false;//NEW: Should be called each time when setSize is called, because in IE calling setSize explicitly ont the client sets wrong height (for which the _firstShow property was introduced in the first place)

        this.set_width(width);
        this.set_height(height);
        this._storeBounds();
    },
    
    autoSize : function()
  {   
        var contentFrame = this.get_contentFrame();                                       
        var docElem = null;            
        //try catch - if coming from another domain
        try
        {
            docElem = contentFrame.contentWindow.document.documentElement;
        }
        catch(ex) { return false; }
                              
        var iframeParentBounds = $Sunny.getBounds(contentFrame.parentNode);
        var radWindowBounds = this.getWindowBounds();
        
        //we need to set to the size to 1 in order to get the correct scrollWidth/scrollHeight in case a big page has been loaded first and small one after that
        contentFrame.style.width = "1px";
        contentFrame.style.height = "1px";
        
        //get the sizes of the content page
        var contentPageHeight = docElem.scrollHeight;     
        var contentPageWidth =  docElem.scrollWidth;
        
        //the viewPortSize is the limit for the size - it is either the browser or the restriction zone if such is set
        var restrictionZoneBounds = this._getRestrictionZoneBounds();
        var viewPortSize = restrictionZoneBounds ? restrictionZoneBounds : this._getViewportBounds();                                                            
                                    
        //Extract the sum of the other elements except for the IFRAME which are included in the RadWindow, e.g. rwTitlebar, rwStatusbar, borders           
        //Calculate the sizes to fit exactly the content page               
        var widthToFit = radWindowBounds.width - iframeParentBounds.width + contentPageWidth;
        var heightToFit = radWindowBounds.height - iframeParentBounds.height + contentPageHeight; 

        //check whether the "best fit" sizes are not bigger than the viewport
        var width  = Math.min(widthToFit, viewPortSize.width);
        var height = Math.min(heightToFit, viewPortSize.height);
                                                                                                         
        //if there is not a restriction zone we need to ensure that the RadWindow will not be moved outside the screen bounds. When there is a restriction zone, this should not be done because it will make the RadWindow leave the zone                                                      
        var keepInBounds = this.get_keepInScreenBounds();
        if(!restrictionZoneBounds)
        {
           this.set_keepInScreenBounds(true);
        }
                                                                     
        //if the calculated size is smaller than the one of the contentpage an additional scrollbar will be generated - if so, add additoinal pixels for it
        var scrollbarWidth = 16;
        if (height < contentPageHeight) width = Math.min(width + scrollbarWidth, viewPortSize.width);                        
        if (width < contentPageWidth)  height = Math.min(height + scrollbarWidth, viewPortSize.height);

        //Calculate delta of old and new size/position - and set new moveTo            
        var newLeft = this.calcPosition(radWindowBounds.x, radWindowBounds.width, width, viewPortSize.width);            
        var newTop = this.calcPosition(radWindowBounds.y, radWindowBounds.height, height, viewPortSize.height);

        //Set new location and size. Since we know the exact bounds, we must override the _checkRestrictionZoneBounds because now it prevents from moving/sizing the window properly!
        var newBounds = {
            x: newLeft + viewPortSize.scrollLeft,
            y: newTop + viewPortSize.scrollTop,
            width : width,
            height : height
        };                                               
        this.setBounds(newBounds);
        
        //Restore iframe original 100% settings!         
        contentFrame.style.width = "100%";
        contentFrame.style.height = "100%";

        //IE bug - setting a correct size causes the occurance of scrollbars in IE. So, reset those with a small timeout
        if($Sunny.isIE)
        {
           contentFrame.style.overflow = "hidden";
           setTimeout(function()
           {
                contentFrame.style.overflow = ""; 
           }, 0);
         }
                                
        //reset the old value of keepInScreenBounds if we have changed it 
        this.set_keepInScreenBounds(keepInBounds);
        return true;                           
    },

     setBounds : function(bounds)
    {
        if (!bounds) return;
        //Check if these bounds fit into the restriction zone    
        //TODO: For the time being do not do it as it does not work good for restriction zones! 
        //Problem is that moveTo takes x and y relative to the restriction zone, but the x and y is matched against absolute coordinates of the parent zone, without considering the scroll offset.
        //if (!this._checkRestrictionZoneBounds(null, bounds)) return;
        
        //Temporarily override the _checkRestrictionZoneBounds method, because it is called from within set_width, set_height and moveTo
        this._checkRestrictionZoneBounds = function(){return true;}          
        this.moveTo(bounds.x, bounds.y);       
        this.setSize(bounds.width, bounds.height);                                                        
        
        //Restore method
        this._checkRestrictionZoneBounds = Sunny.Web.UI.RadWindow.prototype._checkRestrictionZoneBounds;
    },
    
    calcPosition : function(pos, oldBounds, newBounds, viewPort)
      {          
          //Calculate delta - need to round the number becuase when odd we will get invalid value for pixels
          var result = pos + Math.round((oldBounds - newBounds)/2);
          
          //If window will go out of viewport (not desireable) use the viewport and the newHeight to calculate alternative position
          if (result < 0 || result + oldBounds > viewPort)
          {
             result = Math.round(Math.abs((viewPort - newBounds)/2));  
          }
          return result;          
      } , 

    _maintainMaximizedSize : function()
    {
        if (!this.isMaximized()) return;

        var popup = this._popupElement;
        if (!popup) return;

        //Get top and left
        var screen = this._getViewportBounds();

        //OLD
        //popup.style.top = screen.scrollTop + "px";
        //popup.style.left = screen.scrollLeft + "px";
        //NEW
        popup.style.top = (screen.scrollTop + screen.y) + "px";
        popup.style.left = (screen.scrollLeft + screen.x) + "px";
        //popup.style.width  = screen.width + "px";
        //popup.style.height  = screen.height + "px";
        // Use the setSize method, as the popup element has border, which we have to subtract from the screen width/height
        $Sunny.setSize(popup, {width: screen.width, height: screen.height});

        //To work properly in IE Scrolling should be disabled after setting top and left
        //NEW - Only disable scrolling if window not in zone
        var zoneBounds = this._getRestrictionZoneBounds();
        if (!zoneBounds)
        {
            this._enablePageScrolling(false);
        }

        //Once you are done with scrolls, set proper height, to the TABLE!
        var table = this._tableElement;
        //screen = this._getViewportBounds();
        //table.style.height = screen.height + "px";
        //this._fixIeHeight(table, screen.height);
        
        // The popup element has border, so we need to take its contentSize.
        screen = $Sunny.getContentSize(popup);
        var borderBox = $Sunny.getBorderBox(table);
        var paddingBox = $Sunny.getPaddingBox(table);
        var tableContentHeight = screen.height - borderBox.vertical - paddingBox.vertical;
        
        table.style.height = tableContentHeight + "px";
        this._fixIeHeight(table, tableContentHeight);
    },


    _enablePageScrolling : function(enable)
    {
        var body = document.body;
        var doc = document.documentElement;
        if (enable)
	    {
	        if (null != this._documentOverflow) doc.style.overflow = this._documentOverflow;
	        if (null != this._bodyOverflow) body.style.overflow = this._bodyOverflow;
		    this._documentOverflow = null;
	        this._bodyOverflow = null;
	    }
	    else
	    {
	        //Store the page overflow. As it can be called multiple times, it is important to store just original value
            if(null == this._documentOverflow) this._documentOverflow = doc.style.overflow;
            if (null == this._bodyOverflow) this._bodyOverflow = body.style.overflow;
		    body.style.overflow = 'hidden';
		    doc.style.overflow = 'hidden';
	    }
    },

    _getRestrictionZoneBounds : function()
    {
	     var zone = null;
         if (this.get_restrictionZoneID())
         {
             var elem = $get(this.get_restrictionZoneID());
             if (elem)
             {
                zone = $Sunny.getBounds(elem);
                //var offset = $Sunny.getScrollOffset(elem, true);
                //NEW - TODO: all the RadWindow code is written to use scrollLeft and scrollTop - this should be reworked
                //For the time being these should be added to the zone object and set to 0. We do not want to use the offsets when a zone is selected
                zone.scrollLeft = 0;
                zone.scrollTop = 0;
             }
         }
        return zone;
    },


    //called after show[DONE], after drag[DONE], programmatic move[DONE], programmatic resize[DONE], resize[TODO], and as last action in restore()
    _storeBounds : function()
    {
       if (!this.isCreated()) return;

       var rect = this._getCurrentBounds();

       //Method can be called when clicking on the rwTitlebar to restore size, so we make a check.
       if (this.isMaximized())
       {
            return false;
       }

       //If the window is minimized and was moved, then we only need to change the x and y
       if (this.isMinimized())
       {
            //There is the chance that the window shows initially minimized, and no restorerect is present
            //Another scenario is that there was already a restoreRect, and now we need to update only its x and y
            if (this._restoreRect)
            {
                rect.width = this._restoreRect.width;
                rect.height = this._restoreRect.height;
            }
            else
            {
                //We need to set width and height using the _width and _height
                rect.width = this.get_width();
                rect.height = this.get_height();
            }
       }

       this._restoreRect = rect;
    },

    //called when show, restore is called, and when minimize mode is MinimizeZone - because then it changes location!
    _restoreBounds : function()
    {
        if (!this._restoreRect) return;

        var rect = this._restoreRect;
        this.setSize(rect.width, rect.height);
        this.moveTo(rect.x, rect.y);
    },

    _getStoredBounds : function()
    {
        if (this._restoreRect) return this._restoreRect;
    },

    _deleteStoredBounds : function()
    {
        this._restoreRect = null;
    },

    //Simply let us know the current bounds of the window wherever it is
    _getCurrentBounds : function()
    {
        //Compute the popupWidth and popupHeight. Make sure popup is visible at this time
        var tempHide = (this._popupElement.style.display == "none") ? true : false;
        this._popupElement.style.display = "";
        //NEW - This code to compensate for IE quirk with size was in _setPopupVisible method
        //However _getCurrentBounds is called to calculate initial bounds prior to calling  _setPopupVisible
        //And thus in IE returns wrong values for calculating the central position
        //IE! When showing a window for the first time it needs its height fixed
        //If we showed it once, then don't call this function again as it causes problems due to _setPopupVisible being called when current height is NOT equal to this._height anymore.
        if (this._firstShow != true)
        {
            this._updateWindowSize(this._height);
            this._firstShow = true;
        }

        var popupBounds = $Sunny.getBounds(this._popupElement);

        if (tempHide)
        {
            this._popupElement.style.display = "none";
        }

        //NEW
        var zone = this._getRestrictionZoneBounds();
        if (zone)
        {
            //Create a new origin by adding x and y
            popupBounds.x -= zone.x;
            popupBounds.y -= zone.y;
        }
        return popupBounds;
    },


    _getCentralBounds : function()
    {
        // 1. get current bouds to obtain width and height
        var bounds = this._getCurrentBounds();
        //2. get screen boundaries
        var screenBounds = this._getViewportBounds();

        //3 calculate proper x and y
		var x = parseInt((screenBounds.width - bounds.width) / 2);
		var y = parseInt((screenBounds.height - bounds.height) / 2);

		bounds.x = x + screenBounds.scrollLeft;
		bounds.y = y +  screenBounds.scrollTop;
        return bounds;
    },


    _getViewportBounds : function()
    {
        //NEW
        var zone = this._getRestrictionZoneBounds();
        if (zone)
        {
            return zone;
        }

        //Get browser bounds
        var bounds = $Sunny.getClientBounds();

        //Add scroll information for those that need it
		var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
		var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        bounds.scrollLeft = scrollLeft;
        bounds.scrollTop = scrollTop;

        //IE non-XHTML hack
        if (this.isIE)
        {
            if (bounds.width == 0) bounds.width = document.body.clientWidth;
            if (bounds.height == 0)bounds.height = document.body.clientHeight;
        }

        return bounds;
    },
    
     _getCalculatedPopupBounds : function()
     {
        //Return stored bounds
        var storedBounds = this._getStoredBounds();
        if (storedBounds)
        {
            return storedBounds;
        }

        //Get current bounds and modify if needed
        var popupBounds = this._getCurrentBounds();

        var offsetElem = this._offsetElement;

        //Default
        if (!this._top && !this._left && !offsetElem)
        {
            //Calculate central position
            popupBounds = this._getCentralBounds();
        }
        else  //If offset element and/or top/left
        {
            //If there is no offset element, the body will be used as offset for the top/left
            if (offsetElem)
            {
                popupBounds.y = 0;
                popupBounds.x = 0;
            }
            else
            {
                 var screen = this._getViewportBounds();
                 popupBounds.x = screen.scrollLeft;
                 popupBounds.y = screen.scrollTop;
            }

            //Compute horizontal side
            var left = this._left ? this._left : 0;
            popupBounds.x += left;

            //Compute the vertical coordinate
            var top = this._top ? this._top : 0;
            popupBounds.y += top;
        }

        //Return bounds
        return popupBounds;
     },
     
     _checkRestrictionZoneBounds : function(zoneBounds, bounds)
     {
        var restrictionZoneBounds = zoneBounds;
        if(!restrictionZoneBounds)
        {
            restrictionZoneBounds = this._getRestrictionZoneBounds();
            if(!restrictionZoneBounds)
            {
                return true;
            }
        }
        
        return Sunny.Web.UI.ResizeExtender.containsBounds(restrictionZoneBounds, bounds);
     },

     _reSetWindowPosition : function()
     {
        var bounds = this._getCalculatedPopupBounds();
        this._setPopupVisible(bounds.x, bounds.y);
     },

    //Fixes a size bug in IE in DOCTYPE strict mode
     _fixIeHeight : function(oElem, height)
    {
		if ("CSS1Compat" == document.compatMode)
		{
			var difference = (oElem.offsetHeight - parseInt(height));	//oElem.style.height
			if (difference > 0)
			{

				var newHeight = (parseInt(oElem.style.height) - difference);
				if (newHeight > 0) oElem.style.height = newHeight + "px";
			}
		}
	},

	_setPopupVisible : function(x, y)
    {
        //Offset by restriction zone
        var zone = this._getRestrictionZoneBounds();
        if (zone)
        {
            //Create a new origin by adding x and y
            x += zone.x;
            y += zone.y;
        }

        // In case the popup element is visible, using set_x and set_y - the re-positioning will have 2 visible steps - the first one, changing the
        // x coordinate, and the second - the y coordinate.
        this._popupBehavior._setCoordinates(x, y);
        this._popupBehavior.show();

        //Bug in MS AJAX popup implementation sets explicit width, which is not desireable in many scenarios.
        if (!this.get_width())
        {
            this._popupElement.style.width = "";
        }

        //Make sure the title is shrinked if it is larger than the available width
        this._updateTitleWidth();
    },

    _createDefaultTable : function()
    {
        var tableElement = document.createElement('TABLE');
        tableElement.align = "left";
        tableElement.cellSpacing = 0;
        tableElement.cellPadding = 0;
        tableElement.insertRow(-1);
        return tableElement;
    },
    
    _isWindowRightToLeft : function()
    {
        var isRightToLeft = this._isRightToLeft;
        
        if(isRightToLeft == null)
        {
            //NEW:The tooltip is created by the RadWindowManager and its element is a SPAN that is not appended to the document.
            //So if no parent, return default parent (form or body)
            var element = this.get_element();
            var rtlElement = element.parentNode ? element : this._getDefaultParent();
            isRightToLeft = this._isRightToLeft = $Sunny.isRightToLeft(rtlElement);
        }
        
        return isRightToLeft;
    },
    
    _createStatusbarResizer : function(stastusbarTable)
    {
        var bottomResizerCell = stastusbarTable.rows[0].insertCell(-1);
        bottomResizerCell.style.width = "15px";
	    var resizeDiv = document.createElement('DIV');
	    bottomResizerCell.appendChild(resizeDiv);
	    this._bottomResizer = resizeDiv;
    },
    
    _createStatusbarMessageCell : function(stastusbarTable)
    {
        var statusMessageCell = stastusbarTable.rows[0].insertCell(-1);
        statusMessageCell.style.width = "100%";
        var messageInput = this._getStatusMessageElement();
        statusMessageCell.appendChild(messageInput);
    },

    _createUI : function()
    {
        //Dynamic rendering of the window
        if (!this._popupElement)
        {
            var windowID = this.get_id();
            var wrapperID = 'RadWindowWrapper_' + windowID;
            var isRightToLeft = this._isWindowRightToLeft();

            var rootDiv = document.createElement('DIV');
            rootDiv.id = wrapperID;             
            rootDiv.className = this._getFullSkinName();
            if(isRightToLeft)
            {
                Sys.UI.DomElement.addCssClass(rootDiv, "RadWindow_rtl");
            }
            rootDiv.style.width = this._width;
            rootDiv.style.height = this._height;

            rootDiv.setAttribute('unselectable', 'on');
            this._popupElement = rootDiv;

            var tableElement = document.createElement('TABLE');
            tableElement.cellSpacing = 0;
            tableElement.cellPadding = 0;
            this._tableElement = tableElement;

	        //Create the table cells of the window
	        var _classNames = [];
	        
	        // In the case of direction=rtl, the cells of a table are automatically switched. That is why we need to switch the 
            // order in whick we pass the cells to the ResizeExtender.
	        if(isRightToLeft)
	        {
	            classNames = ["rwCorner rwTopRight","rwTitlebar","rwCorner rwTopLeft",
                              "rwCorner rwBodyRight", "rwWindowContent", "rwCorner rwBodyLeft",
                              "rwCorner rwBodyRight", "rwStatusbar", "rwCorner rwBodyLeft",
                              "rwCorner rwFooterRight", "rwFooterCenter", "rwCorner rwFooterLeft"];
	        }
	        else
	        {
                classNames = ["rwCorner rwTopLeft","rwTitlebar","rwCorner rwTopRight",
                              "rwCorner rwBodyLeft", "rwWindowContent", "rwCorner rwBodyRight",
                              "rwCorner rwBodyLeft", "rwStatusbar", "rwCorner rwBodyRight",
                              "rwCorner rwFooterLeft", "rwFooterCenter", "rwCorner rwFooterRight"];
            }
            var rowClassNames = ["rwTitleRow", "rwContentRow", "rwStatusbarRow",  "rwFooterRow"];

	        var index = 0;
	        for (var i = 0; i < 4; i++)
	        {
	            var row = tableElement.insertRow(-1);
	            row.className = rowClassNames[i];

	            for (var j = 1; j <= 3; j++)
	            {
	                var cell = row.insertCell(-1);
	                cell.innerHTML = "&nbsp;";//"<!-- / -->";
	                cell.className = classNames[index];
	                index++;
		        }
	        }

		    //Append title element
		    var titleCell = tableElement.rows[0].cells[1];
		    titleCell.innerHTML = "";
		    this._titleCell = titleCell;

		    //Append the top resizer
		    var topResizer = document.createElement('DIV');
		    topResizer.className = "rwTopResize";
		    topResizer.innerHTML = "<!-- / -->";
		    this._topResizer = topResizer;
            this._titleCell.appendChild(this._topResizer);

		    //Titlebar element - holds all other elements in the rwTitlebar
		    var titlebarTable = this._createDefaultTable();
		    titlebarTable.className = "rwTitlebarControls";
		    this._titlebarElement = titlebarTable;
		    this._titleCell.appendChild(this._titlebarElement);

		    //Follow 3 rwTitlebar elements - rwIcon(span), title (em), commandbuttons(ul)- the ul is created and maintained by set_behaviros method
		    //Window Icon
		    var windowIcon = this._getTitleIcon();
		    var iconCell = this._titlebarElement.rows[0].insertCell(-1);
		    iconCell.appendChild(windowIcon);

		    //Title text
	        var titleElement = this._getTitleElement();
	        var titleCell = this._titlebarElement.rows[0].insertCell(-1);
	        titleCell.appendChild(titleElement);

	        this.set_title(this._title);

            //Set the behavior [including render available command buttons]
            var commandCell = this._titlebarElement.rows[0].insertCell(-1);
            //Setting nowrap would not work competely - the UL will still need to be sized
            commandCell.noWrap = true;
            commandCell.style.whiteSpace = "nowrap";
            commandCell.appendChild(this._getTitleCommandButtonsHolder());
            //this.set_behaviors(this._behaviors);

		    //Configure content cell
		    var contentCell = tableElement.rows[1].cells[1];
	        contentCell.vAlign = "top";
	        contentCell.innerHTML = "";//Clear all existing content
	        this._contentCell = contentCell;

	        //Name should match the server ID property! It is needed so that default browser 'target' mechanism works!
            var name = this.get_name();

	        //Create content IFRAME. Due to a bug in IE regarding setting the name attribute, the following ugly code needs to be used
            var childFrame = ($Sunny.isIE) ?
                             document.createElement("<iframe name='" + name + "'>") :
                             document.createElement("iframe");

            childFrame.name = name;
            childFrame.src = "javascript:'<html></html>';";
            childFrame.style.width = "100%";
            childFrame.style.height = "100%";
            childFrame.style.border = "0px";//set to 0
            childFrame.frameBorder = "0";
            this._iframe = childFrame;
            this._contentCell.appendChild(this._iframe);

            //Create rwStatusbar
            var stastusbarTable = this._createDefaultTable();
            stastusbarTable.style.width = "100%";
            this._statusCell = tableElement.rows[2].cells[1];
            this._statusCell.innerHTML = "";
            this._statusCell.appendChild(stastusbarTable);

            //Create rwStatusbar message cell and rwStatusbar resizer
            if(isRightToLeft)
            {
                this._createStatusbarResizer(stastusbarTable);
                this._createStatusbarMessageCell(stastusbarTable);
            }
            else
            {
                this._createStatusbarMessageCell(stastusbarTable);
                this._createStatusbarResizer(stastusbarTable);
            }

		    //Create a back reference to parent RadWindow
	        this._createBackReference();

		    //Add the wrapper table to the popup element
	        this._popupElement.appendChild(this._tableElement);

            //Add popup to the document
            this._popupElement.style.display = 'none';
            this._popupElement.style.position = 'absolute';
            this._addWindowToDocument();

            //Set behaviors (move, resize,etc etc)
            this.set_behaviors(this._behaviors);

            //Add rwTitlebar event handlers
            this._registerTitlebarHandlers(true);

            //Show/hide titlebars - it needs to be done here AND ins _show. Here - because a window can be shown with some animation. In _show - because the setting might be changed dynamically later using the API
            this.set_visibleTitlebar(this._visibleTitlebar);
            this.set_visibleStatusbar(this._visibleStatusbar);

            //alert("OUTER HTML "  + this._popupElement.outerHTML);//DEBUG
        }

        //Create the popup if it has not been created
        if (!this._popupBehavior)
        {
            this._popupBehavior = $create(Sunny.Web.PopupBehavior, { 'id': (new Date() - 100)//set a unique id
                +'PopupBehavior', 'parentElement': null, 'overlay': this._overlay, 'keepInScreenBounds': this._keepInScreenBounds }, null, null, this._popupElement);
        }
    },
    
    _getDefaultParent : function()
    { 
        var parent = this._formID ? document.getElementById(this._formID) : null;        
        if (!parent)
        {
           if (document.forms && document.forms.length > 0) parent = document.forms[0]; 
           else parent = document.body;
        }
        return parent;
    },

    //------------------------------ Titlebar and Statusbar element creation methods ---------------------------------------------------//
    _getStatusMessageElement : function()
    {
        if (null == this._statusMessageElement)
        {
            var el = document.createElement("INPUT");
            el.readOnly = "readonly";
            el.setAttribute("unselectable", "on");
            this._statusMessageElement = el;
        }
        return this._statusMessageElement;
    },


    _getTitleCommandButtonsHolder : function()
    {
        if (null == this._buttonsElement)
        {
            var ul = document.createElement("UL");
            ul.className = "rwControlButtons";
            this._buttonsElement = ul;
        }

        return this._buttonsElement;
    },

    _getTitleElement : function()
    {
		if (!this._titleElement)
		{
		    this._titleElement = document.createElement('EM');
		    this._titleElement.setAttribute("unselectable", "on");
		}
		return this._titleElement;
    },

    _getTitleIcon : function()
    {
        if (null == this._titleIconElement)
        {
            var icon = document.createElement("A");

            this._titleIconElement = icon;
            icon.className = "rwIcon";//sets width and height, but also has some offsets, so we should remove those if iconurl is set

            //Change the iconUrl
            if (this.get_iconUrl())
            {
                //icon.style.backgroundImage = "url(" + this.get_iconUrl() + ")";
                icon.style.background = "transparent url(" + this.get_iconUrl() + ") no-repeat scroll 0px 0px";
            }


        }
        return this._titleIconElement;
    },


    _getTitleCommandButton : function(butname)
    {
        if (!butname || !this._buttonsArray) return null;
        
        //Button css classes use the following convention  - "rw[Command]Button"
        var name = butname.toLowerCase();
        name = name.charAt(0).toUpperCase() + name.substring(1);
        butname = "rw" + name + "Button";

        //Go through the buttons array and find the button
        var length = this._buttonsArray.length;
        for (var i = 0; i < length; i++)
        {
            var button = this._buttonsArray[i];

            if (button && Sys.UI.DomElement.containsCssClass(button, butname))
            {
                return button;
            }
        }
        return null;
    },

    _updateTitleWidth : function()
    {
        if (this._visibleTitlebar)
        {
            var titleElem = this._getTitleElement();
            if (!titleElem) return;

            var commandList = this._getTitleCommandButtonsHolder();
            var butWidth = commandList.offsetWidth;

            //Set explicit width to the commandList in order to prevent it from being mutilated during resize
            //Ok, do not do it here, rework the header to use a table, and it will handle it automatically
            if (butWidth > 0)
            {
                var lis = commandList.getElementsByTagName("LI");
                //Need to check whether the offsetWidth is not 0, for cases when the pin button is hidded (display:none)
                //as in th case when the window is minimized.
                if (lis[0] && lis[0].offsetWidth > 0)
                {
                    butWidth = lis.length * lis[0].offsetWidth;
                }
                commandList.style.width = butWidth + "px";
            }

            //Set icon container width
            var icon = this._getTitleIcon();
            var iconWidth = icon.offsetWidth;
            if (iconWidth > 0 && icon.parentNode.tagName == "TD")
            {
                icon.parentNode.style.width = iconWidth + "px";
            }
        }
    },

    _addWindowToDocument : function()
    {
        //Append window to end of document
        //var form  = document.getElementById(this._formID);
        //if (!form) form = document.forms[0];
        //form.appendChild(this._popupElement);

        //In firefox there is a problem in a page with scrollers and page overflow disabled (e.g. when rad editor is showing a modal dialog)
        //Also, a customer reported - If any element above is floating relative the dragging and placement is obscure
        //So we provide an alternative approach here - add it to beginning of page
        var parent = this._getDefaultParent();        
        parent.insertBefore(this._popupElement, parent.firstChild);
    },

  
    _createBackReference : function()
    {
    	var theWnd = this;
	    if (!theWnd.Argument) theWnd.Argument = {};

	    var oIframe = this._iframe;

	    try
	    {
		    //Accessed in both browsers with window.frameElement.RadWindowClass
		    //in IE oIframe = window.frameElement
		    oIframe.radWindow = theWnd;//oIframe.contentWindow;

		    if (oIframe.contentWindow != null)//Opera problem
		    {
			    //Associate the radWindow oject with the iframe
			    //In Moz like this is accessed - window.RadWindowClass, undefined in IE!
			    oIframe.contentWindow.radWindow = theWnd;//" Iframe.contentWindow.RadWindowClass ";
		    }

		    //TRUE-> oIframe.contentWindow.frameElement == oIframe;
		    //TRUE -> oIframe.contentWindow == window in child!
		    //HOWEVER oIframe.contentWindow.RadWindowClass = window.RadWindowClass is false in IE??
	    }
	    catch(e){}
    },


    _getFullSkinName : function()
    {
        return "RadWindow RadWindow_" + this._skin + " rwNormalWindow rwTransparentWindow";
    },


    _configureMinimizeButton : function(asRestore)
    {
        var loc = this._getLocalization();
        var buttonText = (true == asRestore) ? loc["Restore"]: loc["Minimize"];
        var buttonClickFn = (true == asRestore) ? this.restore: this.minimize;
        this._registerTitlebarHandlersButton("Minimize", buttonText, buttonClickFn);
    },

    _configureMaximizeButton : function(asRestore)
    {
        var loc = this._getLocalization();
        var buttonText = (true == asRestore) ? loc["Restore"]: loc["Maximize"];
        var buttonClickFn = (true == asRestore) ? this.restore: this.maximize;
        this._registerTitlebarHandlersButton("Maximize", buttonText, buttonClickFn);
    },

    _registerTitlebarHandlersButton : function (buttonName, buttonText, buttonClickFn)
    {
        var titlebarButton = this._getTitleCommandButton(buttonName);
        if (titlebarButton)
        {
            //Change the localization and the onclick function
            var loc = this._getLocalization();

            titlebarButton.setAttribute("title", buttonText);
		    titlebarButton.innerHTML = buttonText;

		    //Change the onclick function
		    $clearHandlers(titlebarButton);
		    $addHandlers(titlebarButton, {"click": buttonClickFn}, this);

		    //Cancel the double click event, so that the window is not restored when you double click a button.
		    $addHandler(titlebarButton, 'dblclick', this._cancelEvent);

//TODO: Optimize. Code duplication - the event handlers are attached when the button is created, and here, when its functionality is changed
		    $addHandler(titlebarButton, 'mousedown', this._cancelEvent);
        }
    },

    //###------------------------- PUBLIC API METHODS -----------------------------------------#######//
    isCloned : function()
    {
        return this._isCloned;
    },

    isBehaviorEnabled : function(oBehavior)
    {
	    return oBehavior & this._behaviors ? true : false;
    },

    isInitialBehaviorEnabled : function(oBehavior)
    {
        //alert(oBehavior + " -- " + this._initialBehaviors );
	    return oBehavior & this._initialBehaviors ? true : false;
    },


    setVisible : function(toShow)
    {
        if (this._popupBehavior)
        {
           if (toShow) this._popupBehavior.show();
           else this._popupBehavior.hide();
        }
    },

    isVisible : function()
    {
        /// <summary>
        /// Returns whether the window control is currently visible
        /// </summary>
        /// <value type="Boolean">
        /// Whether the window control is currently visible
        /// </value>
        return this._popupVisible;
    },

    isModal : function()
    {
        return this._modal;
    },

    isActive : function()
    {
        return (this._popupElement && !Sys.UI.DomElement.containsCssClass(this._popupElement, "rwInactiveWindow"));
    },

    isPinned : function()
    {
        var pinButton = this._getTitleCommandButton("Pin");
        return (pinButton && Sys.UI.DomElement.containsCssClass(pinButton, "on"));
    },

    //Since the window is always visible - even when minimized, we can use the isVisible method [for now - unless the need to change this behavior arises later]
    isClosed : function()
    {
        return (!this.isVisible());
    },

    isMinimized : function()
    {
        return (this._popupElement && Sys.UI.DomElement.containsCssClass(this._popupElement, "rwMinimizedWindow"));
    },

    isMaximized : function()
    {
        return (this._popupElement && Sys.UI.DomElement.containsCssClass(this._popupElement, "rwMaximizedWindow"));
    },


    _moveToMinimizeZone : function()
    {
        var oZone = $get(this.get_minimizeZoneID());
		if (oZone)
		{
			//In case we are to minimize a pinned window to a minimize zone, unpin it first.
			if(this.isPinned())
			{
			    this._isPinned = true;
			    this.togglePin();
			}

			var rootDiv = this._popupElement;
			if (rootDiv.parentNode != oZone)
			{
				rootDiv.parentNode.removeChild(rootDiv);
				oZone.appendChild(rootDiv);

				//IE Bug - overlay iframe gets on top of popup itself when  minimize is called when the window is maximized.
				this.setVisible(true);

				rootDiv.style.position = "static";
				if (this.isIE) rootDiv.style.display = "inline";
				else
				{
				    rootDiv.style.cssFloat = "left";
                    //rootDiv.style.styleFloat = "left";//IE!!!
                }
			}
		}
    },

    _moveToDocument : function()
    {
        var rootDiv = this._popupElement;
        rootDiv.parentNode.removeChild(rootDiv);
        rootDiv.style.position = "absolute";

        if (this.isIE)
        {
            rootDiv.style.display = "";
        }
	    else rootDiv.style.cssFloat = "";
        //rootDiv.style.styleFloat = "";//IE!!!
        this._addWindowToDocument();
        
        //In case the window was pinned before we minimized it to the zone, restore its pinned state.
        if(this._isPinned)
        {
            this._isPinned = false;
            this.togglePin();
        }
    },

    minimize : function()
    {
       //Check if window was created at all
        if (!this.isCreated()) return;

        var toContinue = this.onCommand("Minimize");
	    if (!toContinue) return;

        //NEW: If the window is currently maximized, first move it to the old location
        if (this.isMaximized())
        {
            this._restoreBounds();
        }

        var rootDiv = this._popupElement;
        $Sunny.removeCssClasses(rootDiv, ["rwNormalWindow","rwMaximizedWindow"]);
        Sys.UI.DomElement.addCssClass(rootDiv, "rwMinimizedWindow");

        // Update the overlay IFRAME as well.
        var overlayIframe = rootDiv._hideWindowedElementsIFrame;
        if(overlayIframe)
        {
            Sys.UI.DomElement.addCssClass(overlayIframe, "rwMinimizedWindowOverlay_" + this._skin);
        }

        this._configureMinimizeButton(true);


        this._enablePageScrolling(true);

        //TODO: Change the minimize icon is on the left!

        //If Minimize Zone is specified, try to move there
        if (this.get_minimizeZoneID())
        {
            this._moveToMinimizeZone();
        }
    },


    restore : function()
    {
        //Check if window was created at all, or whether it is currently not visible / closed
        if (!this.isCreated() || this.isClosed()) return;
        
        //Raise event
	    var toContinue = this.onCommand("Restore");
	    if (!toContinue) return;

        this._configureMinimizeButton();
        this._configureMaximizeButton();

        //If window was minimized and it was in a minimize zone - restore to document
	    if (this.isMinimized() && this.get_minimizeZoneID())
	    {
	        this._moveToDocument();
	    }

	    //Fix css classes of the window wrapper
	    this._normalizeWindowRootCss();

	    //Enable page scrolling
	    this._enablePageScrolling(true);        

	    //Set size and position
        this._restoreBounds();
        
        //Make sure window is visible
        this.setVisible(true);

        //NEW  - restore a small zIndex
        if (this._restoreZindex)
        {
            this._popupElement.style.zIndex = this._restoreZindex;
            this._restoreZindex = null;
        }

        //IE Bug - overlay iframe gets on top of popup itself.  Call setVisible second time to 'fix' this behavior.
        this.setVisible(true);

	    //Activate - after the pre-maximize zIndex
	    this.setActive(true);
    },

    maximize : function()
    {
        //Check if window was created at all
        if (!this.isCreated()) return;

        var toContinue = this.onCommand("Maximize");
	    if (!toContinue) return;
	    
        //Store state
        this._storeBounds();

        //If it was minimized and it was in a minimize zone - then restore to document
        if (this.isMinimized() && this.get_minimizeZoneID())
	    {
	        this._moveToDocument();
	    }

        //Set css classes
        var rootDiv = this._popupElement;
        $Sunny.removeCssClasses(rootDiv, ["rwNormalWindow","rwMinimizedWindow"]);
        Sys.UI.DomElement.addCssClass(rootDiv, "rwMaximizedWindow");

        //Change maximize button to [restore]
        this._configureMaximizeButton(true);
        //Make sure the minimize button is properly configured too
        this._configureMinimizeButton();

        //Set size
        this._maintainMaximizedSize();

        //Call it a second time - a known bug in Mozilla when scrollers are available on the page!
        this._maintainMaximizedSize();

        // Update the overlay IFRAME as well.
        var overlayIframe = rootDiv._hideWindowedElementsIFrame;
        if(overlayIframe)
        {
            $Sunny.removeCssClasses(overlayIframe, ["rwMinimizedWindowOverlay_" + this._skin]);
            this._popupBehavior._handleElementResize();
        }

        //Set active
        if (!this.isActive()) this.setActive(true);


        //NEW - Set big zIndex in Maximize method, to make sure the window overlays all other windows
        //Make it as last action of maximize method
        //NEW: Only if window is NOT in a restriction zone
        if (!this._getRestrictionZoneBounds())
        {
            var zIndex = rootDiv.style.zIndex;
            if (zIndex) this._restoreZindex = zIndex;
            rootDiv.style.zIndex = 100000;
        }
    },

    setActive : function(bActivate)
    {
       var rootDiv = this._popupElement;
        if (!bActivate) //Make inactive
        {
            Sys.UI.DomElement.addCssClass(rootDiv, "rwInactiveWindow");
        }
        else //Make active
        {
            //Set a new zIndex!  NEW: Only if not already maximized - because when maximized the window uses a very high index
            if (!this.isMaximized())
            {
                var oldZindex = parseInt(rootDiv.style.zIndex);
                var newZIndex = Sunny.Web.UI.RadWindowUtils.get_newZindex(oldZindex);
                rootDiv.style.zIndex = "" + newZIndex;
            }

            this._getWindowController().set_activeWindow(this);

            
            //Throw Activate event - once all is done - TODO: Perhaps use it in both activated and deactivated state and let devs query the window's state by using its API?
            //NEW: Raise event here, because first time a window is shown it has the "active" class, and does not raise the event which is wrong
            this.raiseEvent("activate", new Sys.EventArgs());
            
            if (this.isActive()) return;

            $Sunny.removeCssClasses(rootDiv, ["rwInactiveWindow"]);    
        }
    },


    togglePin : function()
    {
        //Check if window was created at all
        if (!this.isCreated()) return;

        var toContinue = this.onCommand("Pin");
	    if (!toContinue) return;

        var pinButton = this._getTitleCommandButton("Pin");
        var loc = this._getLocalization();
        var isPinned = this.isPinned();
        var buttonText = isPinned ? loc["PinOn"] : loc["PinOff"];
        if (pinButton) Sys.UI.DomElement.toggleCssClass(pinButton, "on");

        this._registerTitlebarHandlersButton("Pin", buttonText, this.togglePin);

        //CAUTION: If the window is not visible yet there is problem with initial positioning
        Sunny.Web.UI.RadWindowUtils.setPinned(!isPinned, this);
    },

    reload : function()
    {
        //Check if window was created at all
        if (!this.isCreated()) return;

        var toContinue = this.onCommand("Reload");
	    if (!toContinue) return;
        if (!this._iframe) return;

        this._onWindowUrlChanging();
	    try
	    {
		    this._iframe.contentWindow.location.reload();
	    }
	    catch(e)
	    {
	        //In case there are not enough permissions
		    this._onWindowUrlChanged();
	    }
    },

    //Called in restore and close.
    //It is important to call in close, or else if a window is closed while being maximized - the browser.window.resize hander
    //_maintainMaximizedSize disables page scrolling
    _normalizeWindowRootCss : function()
    {
        //Remove the maximize and minimize css classes
	    var rootDiv = this._popupElement;
	    if (rootDiv)
	    {
            $Sunny.removeCssClasses(rootDiv, ["rwMinimizedWindow","rwMaximizedWindow"]);
            Sys.UI.DomElement.addCssClass(rootDiv, "rwNormalWindow");

            // Update the overlay IFRAME as well.
            var overlayIframe = rootDiv._hideWindowedElementsIFrame;
            if(overlayIframe)
            {
                $Sunny.removeCssClasses(overlayIframe, ["rwMinimizedWindowOverlay_" + this._skin]);
            }
        }
    },

    close : function(callBackFnArg)
    {
        if (this.isClosed()) return;
        
        //NEW - Svetlina - 16.12.08
        var cancelArgs = new Sys.CancelEventArgs();
        this.raiseEvent('beforeClose', cancelArgs);                
        if (cancelArgs.get_cancel())
        {
            return;
        }

        //Hide must be first, as if a window is modal, the modal extender takes care of scrolls as well
        this.hide();
 
        //NEW - Svetlina - 16.12.08              
        var arg = new Sys.EventArgs();
        
		arg._argument = (callBackFnArg && !(callBackFnArg instanceof Sys.UI.DomEvent)) ? callBackFnArg : null;
		arg.get_argument = function() { return this._argument; }
		
        //Raise the close event here (used to be called by hide - _hide - _afterHide). Logical error. Hiding a window is not closing it
        this.raiseEvent('close', arg);
                                          
	    this._enablePageScrolling(true);

	    //Here, as in _hide we check whether the window is currently maximized
	    this._normalizeWindowRootCss();

	    //Invoke CallBack Function	    	    
        //NEW: Always invoke callback function when closing the window - in radprompt and radconfirm this is used to determine whether user selected [x] or "Cancel"	    	    
        //The MS AJAX framework provides close method with the EVENT argument when closing from the [x] - convert this to null
	    if (callBackFnArg instanceof Sys.UI.DomEvent) callBackFnArg = null;
		this._invokeDialogCallBackFunction(callBackFnArg);
	    
        if (this._destroyOnClose)
        {
            this.dispose();
        }
    },
    
    _invokeDialogCallBackFunction : function(oArg)
    {	    
	    var oFun = this.get_clientCallBackFunction();
	    if (oFun)
	    {
		    if ("string" == typeof(oFun)) oFun = eval(oFun);
		    if ("function" == typeof(oFun)) oFun(this, oArg);
	    }
    },


    onCommand : function(commandName)
	{
		/// <summary>
		/// Invoked when a command is to be executed
		/// </summary>
		var cancelArgs = new Sys.CancelEventArgs();
		cancelArgs._commandName = commandName;
		cancelArgs.get_commandName = function() { return this._commandName; }

		this.raise_command(cancelArgs);
		if (cancelArgs.get_cancel())
		{
			return false;
		}
		return true;
	},

    setUrl : function(url)
    {
        this._createUI();

	    //If url starts with ~ maybe replace with application path?
	    this._navigateUrl = url;

	    var ifrmUrl = url;

	    //Append a random string to the url of the page so it is not cached from the browser
	    if (this._reloadOnShow)
	    {
	        ifrmUrl = this._getReloadOnShowUrl(ifrmUrl);
	    }

	    this._iframe.src = ifrmUrl;

	    this._onWindowUrlChanging();

	    //Attach handler just once for the iframe lifetime
	    if (!this._loaded)
	    {
		    this._registerIframeLoadHandler(true);
	    }
	    this._loaded = true;
    },


     //This function is called when the page inside the document is loaded and unloaded
     //It turns out that $addHandler and $removeHandler only work in the context of the current window, and we need to attach 2 handlers to elements from the child iframe
     //This is why we are "forced" to duplicate the attach/detach functionality of the framework.
    _registerChildPageHandlers : function(attachEvent)
    {
        var childBody = null;
        //Lack of enough permissions - perhaps the page comes from another domain
        try
        {
            childBody = this._iframe.contentWindow.document;//.body; -> body is not good choice as in XHTML DOCTYPE it can be too small

            //Try to compare the domain of the page, containing the RadWindow and the page, opened in the RadWindow.
            //This solves problems in FF, where we can actually get a reference to the document object, even though
            //the page, opened in the window is from a different domain. However, trying to attach a handler to the click event
            //of that document will throw a "permission denied" error.
            if(childBody.domain != document.domain)
            {
                return;
            }
        }
        catch(e) { return; }
        if (null == childBody) return;


        if (attachEvent)
        {
            this._onChildPageUnloadDelegate = Function.createDelegate(this, this._onChildPageUnload);

            //$Sunny.addExternalHandler(childBody, "unload", this._onChildPageUnloadDelegate);
            //In addition to being forced to use our own attachHandler, furthermore, in IE it simply does not work for the unload event.
            //So we actually need to revert to some really ugly code
            if (this.isIE)
            {
                childBody.onunload = this._onChildPageUnloadDelegate;
            }
            else
            {
                this._iframe.contentWindow.onunload = this._onChildPageUnloadDelegate;
            }

            this._onChildPageClickDelegate = Function.createDelegate(this, this._onChildPageClick);
            $Sunny.addExternalHandler(childBody, "click", this._onChildPageClickDelegate);
        }
        else
        {
            if (this._onChildPageClickDelegate)
            {
                $Sunny.removeExternalHandler(childBody, "click", this._onChildPageClickDelegate);
                this._onChildPageClickDelegate = null;
            }

            //$Sunny.removeExternalHandler(childBody, "unload", this._onChildPageUnloadDelegate);
            //if (this.isIE)  childBody.onunload = null;
            //else this._iframe.contentWindow.onunload = null;
        }
    },

     _onChildPageUnload : function(e)
    {
        //Detach the childpage event handlers
        this._registerChildPageHandlers(false);
    },

    _onChildPageClick : function(e)
    {
	    //If you click on a button to close the window, then the click event is fired, but you should diskard it!
        if (!this.isVisible() || this.isClosed()) return;

        //Unfortunately in some cases a window is open from another window by clicking a button. Then the event propagates to the body
        //and gets here - so the "older" window becomes "active" and goes over the "new" window. While technically speaking it is best
        //to take good care and cancel the event in the button click, it generates unnecessary support. So we will try to handle it here

        var src = e.target ?  e.target : e.srcElement;
        if (src)
        {
          if (src.tagName == "INPUT" && src.type == "button") return;
          else if (src.tagName == "BUTTON" || src.tagName == "A") return;
        }

	    //If active window already return! (or in some scanrios when a button is clicked and the handler gets executed, the effect is not as wanted
	    this.setActive(true);
    },

	_onIframeLoad : function()
    {
        //Take care of updating the window look
	    this._onWindowUrlChanged();
	    
        //Register a click handler that will set the window to gain focus when its content area is clicked	  
	    this._registerChildPageHandlers(true);

	    //Execute load event
        this.raiseEvent('pageLoad', new Sys.EventArgs());
        
        if(this.get_autoSize())
        {
          this.autoSize();          
        }        
    },


	_onWindowUrlChanging : function()
	{
		var isRTL = $Sunny.isRightToLeft(this._iframe);
		if (this._showContentDuringLoad || isRTL)
		{
			//Show the rwLoading sign to the rwStatusbar
			var input = this._getStatusMessageElement();
			if (input) Sys.UI.DomElement.addCssClass(input, "rwLoading");
		}
		else
		{
			var style = this._iframe.style;
			style.position = "absolute";
			style.top = "-10000px";
			style.left = "-10000px";

			//Show the rwLoading sign to the TD
			var td = this._iframe.parentNode;
			Sys.UI.DomElement.addCssClass(td, "rwLoading");
		}
	},


	_onWindowUrlChanged : function()
	{
		var input = this._getStatusMessageElement();
		var isRTL = $Sunny.isRightToLeft(this._iframe);
		if (this._showContentDuringLoad || isRTL)
		{
			//Hide the rwLoading sign
			if (input) Sys.UI.DomElement.removeCssClass(input, "rwLoading");
		}
		else
		{
			//Make the iframe visible again
			//Use positioning, rather than visibility to avoid the IE javascript error when the loaded page tries to set focus to a still-invisible element
			this._iframe.style.position = "";

			//NEW - remove the extra css class from the TD
			var td = this._iframe.parentNode;
			Sys.UI.DomElement.removeCssClass(td, "rwLoading");
		}

		//Set the url in the status bar
		if (input) this.set_status(this._navigateUrl);

		//Set title
		try
		{
			if (this._iframe.contentWindow.document.title) this.set_title(this._iframe.contentWindow.document.title);
		} catch (e){};
	},


    _updatePopupZindex : function()
    {
       if (this._popupBehavior)
       {
            //Have the iframe's zIndex be updated
            if (this.isVisible())
            {
                this._popupBehavior.show();
            }
        }
    },

    //#####------------------------PUBLIC PROPERTIES ACCESSORS AND MUTATORS------------------------#####//
    get_zindex : function()
    {
        if (this._popupElement) return this._popupElement.style.zIndex;
        else return -1;
    },


//NEW - Svetlina - 16.12.08
    get_browserWindow : function()
    {
         /// <summary>
        // Gets a reference to the RadWindow's parent [browser window] object 
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// The reference to the RadWindow's parent [browser window] object 
        /// </value>
        return this._browserWindow;
    },


    get_contentFrame : function()
    {
        /// <summary>
        // Gets a reference to the RadWindow's content frame
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// The reference to the content frame
        /// </value>
        return this._iframe;
    },

    get_minimizeZoneID: function()
    {
        /// <summary>
        // Gets the id (ClientID if a runat=server is used) of a html element where the window object will be docked when minimized
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// The id of the html element serving as a minimize zone
        /// </value>
        return this._minimizeZoneID;
    },
    set_minimizeZoneID : function(value)
    {
        /// <summary>
        // Sets the clientside id of a html element where the window object will be docked when minimized
        /// </summary>
        /// <param name="value" type="Sys.UI.DomElement">
        /// The id of the html element serving as a minimize zone
        /// </param>
        if (this._minimizeZoneID != value) {
            this._minimizeZoneID = value;
        }
    },

    get_restrictionZoneID: function()
    {
        /// <summary>
        // Gets the id (ClientID if a runat=server is used) of a html element in which the window object will be able to move.
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// The id of the html element serving as a zone
        /// </value>
        return this._restrictionZoneID;
    },
    set_restrictionZoneID : function(value)
    {
        /// <summary>
        // Sets the clientside id of a html element in which the window object will be able to move.
        /// </summary>
        /// <param name="value" type="Sys.UI.DomElement">
        /// The id of the html element serving as a zone
        /// </param>
        if (this._restrictionZoneID != value) {
            this._restrictionZoneID = value;
        }
    },


    get_minimizeIconUrl: function()
    {
        /// <summary>
        /// Gets the url of the minimized icon of the RadWindow
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// The url of the minimize icon
        /// </value>
        return this._minimizeIconUrl;
    },
    set_minimizeIconUrl : function(value)
    {
        /// <summary>
        /// Sets the url of the minimized icon of the RadWindow
        /// </summary>
        /// <param name="value" type="Sys.UI.DomElement">
        /// The url of the minimize icon
        /// </param>
        if (this._minimizeIconUrl != value) {
            this._minimizeIconUrl = value;
        }
    },


    get_iconUrl: function()
    {
        /// <summary>
        /// Gets the url of the icon in the upper left rwCorner of the RadWindow rwTitlebar
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// The url of the icon
        /// </value>
        return this._iconUrl;
    },
    set_iconUrl : function(value)
    {
        /// <summary>
        /// Sets the url of the icon in the upper left rwCorner of the RadWindow rwTitlebar
        /// </summary>
        /// <param name="value" type="Sys.UI.DomElement">
        /// The url of the icon
        /// </param>
        if (this._iconUrl != value) {
            this._iconUrl = value;
        }
    },



    get_clientCallBackFunction: function()
    {
        /// <summary>
        /// Returns the client callback function that will be called when a window dialog is being closed.
        /// </summary>
        /// <value type="String">
        /// Returns the window navigate URL
        /// </value>
        return this._clientCallBackFunction;
    },
    set_clientCallBackFunction : function(value)
    {
        /// <summary>
        /// Sets the client callback function that will be called when a window dialog is being closed.
        /// </summary>
        /// <param name="value" type="String">
        /// New navigate URL to the window
        /// </param>
        if (this._clientCallBackFunction != value) {
            this._clientCallBackFunction = value;
        }
    },



    get_navigateUrl: function()
    {
        /// <summary>
        /// Returns the window navigate URL
        /// </summary>
        /// <value type="String">
        /// Returns the window navigate URL
        /// </value>
        return this._navigateUrl;
    },
    set_navigateUrl : function(value)
    {
        /// <summary>
        /// Sets a new navigate URL to the window
        /// </summary>
        /// <param name="value" type="String">
        /// New navigate URL to the window
        /// </param>
        if (this._navigateUrl != value) {
            this._navigateUrl = value;
        }
    },


    get_targetControl: function()
    {
        /// <summary>
        /// Gets a reference to the window target element
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// Returns a reference to the window target element
        /// </value>
        return this._openerElement;
    },
    set_targetControl : function(value)
    {
        /// <summary>
        /// Sets a new target control to the window
        /// </summary>
        /// <param name="value" type="Sys.UI.DomElement">
        /// Reference to the target control
        /// </param>
        if (this._openerElement != value) {
            this._openerElement = value;
        }
    },

    /* Needed for rad window working with 'target' attribute of links*/
    get_name : function()
    {
        /// <exclude />
        return this._name;
    },

    set_name : function(value)
    {
        /// <exclude />
        if (this._name != value) {
            this._name = value;
        }
    },

    get_formID : function()
    {
        /// <exclude />
        return this._formID;
    },

    set_formID : function(value)
    {
        /// <exclude />
        if (this._formID != value) {
            this._formID = value;
        }
    },

    get_offsetElementID : function() {
        /// <summary>
        /// Gets the offset element [element or which the window would be positioned relatively] - works together with the Top and Left properties
        /// </summary>
        /// <value type="String">
        /// The client id of the offset element
        /// </value>
        return this._offsetElementID;
    },
    set_offsetElementID : function(value)
    {
        /// <summary>
        /// Gets the offset element [element or which the window would be positioned relatively] - works together with the Top and Left properties
        /// </summary>
        /// <param name="value" type="String">
        /// The client id of the offset element
        /// </param>
        if (this._offsetElementID != value) {
            this._offsetElementID = value;
        }

        //If the window is visible, update it
        if (this.isVisible())
        {
            this._deleteStoredBounds();
            this._offsetSet = false;//Reset the private variable that marks that the offset element was set
            this._show();
        }
    },


    get_openerElementID : function() {
        /// <summary>
        /// Gets the target control of the window
        /// </summary>
        /// <value type="String">
        /// The ID of the window's target control
        /// </value>
        return this._openerElementID;
    },
    set_openerElementID : function(value)
    {
        /// <summary>
        /// Sets a new target control to the window
        /// </summary>
        /// <param name="value" type="String">
        /// The client id of the target control
        /// </param>
        if (this._openerElementID != value)
        {
            if (this._openerElement)
            {
                this._registerOpenerElementHandler(this._openerElement, false);
                this._openerElement = null;
            }
            this._openerElementID = value;

            //Set target element and register opener event handler
            if (this._openerElementID) this._openerElement = $get(this._openerElementID);
            if (this._openerElement) this._registerOpenerElementHandler(this._openerElement, true);
        }
    },

    get_left : function()
    {
        /// <summary>
        /// Gets the horizontal offset relative to its target element
        /// </summary>
        /// <value type="Number" integer="true">
        /// The number of pixels to horizontally offset the Popup from its default position
        /// </value>
        return this._left;
    },

    set_left : function(value)
    {
        /// <summary>
        /// Sets a new horizontal offset relative to its target element
        /// </summary>
        /// <param name="value" type="Number" integer="true">
        /// The new Left value
        /// </param>
        if (this._left != value) {
            this._left = parseInt(value);
        }
    },

    get_top : function()
    {
        /// <summary>
        /// Gets the vertical offset relative to its target element
        /// </summary>
        /// <value type="Number" integer="true">
        /// The number of pixels to vertically offset the Popup from its default position
        /// </value>
        return this._top;
    },

    set_top : function(value)
    {
        /// <summary>
        /// Sets a new vertical offset relative to its target element
        /// </summary>
        /// <param name="value" type="Number" integer="true">
        /// The new Left value
        /// </param>
        if (this._top != value) {
            this._top = parseInt(value);
        }
    },


    get_title : function()
    {
        /// <summary>
        /// Gets the title of the window
        /// </summary>
        /// <value type="String">
        /// The title text of the window
        /// </value>
        return this._title;
    },

    set_title : function(value)
    {
        /// <summary>
        /// Sets a new title to the window
        /// </summary>
        /// <param name="value" type="String">
        /// The new title text
        /// </param>
        if (this._title != value) {
            this._title = value;
        }

        if (null == this._titleElement) return;
        this._titleElement.innerHTML = this._title;
        //Update the title width
        this._updateTitleWidth();
    },


    get_width : function()
    {
        /// <summary>
        /// Gets width of the window
        /// </summary>
        /// <value type="Unit">
        /// The original width of the window
        /// </value>

        //We must use parseInt for backward compatibility!
        return parseInt(this._width);
    },


    _fixSizeValue : function(value)
    {
        value = "" + value;

        if (-1 == value.indexOf("px"))
        {
            value = parseInt(value);
            if (!isNaN(value))
            {
                value = value + "px";
            }
            else value = "";
        }
        return value;
    },

    set_width : function(value)
    {
        /// <summary>
        /// Sets new width to the window
        /// </summary>
        /// <param name="value" type="Unit">
        /// The new width
        /// </param>

        if (null == value) return false;
        
        if (this.isMaximized()) return false;
        
        value = this._fixSizeValue(value);
        
        var popupElement = this._popupElement;
        if(popupElement)
        {
            var popupBounds = $Sunny.getBounds(popupElement);
            var currentWidth = parseInt(value);
            //In some scenarios the value is an empty string and MS AJAX throws an exception.
            //This is why we assign the popup bounds width.
            if (isNaN(currentWidth)) currentWidth = popupBounds.width;
            var toUpdate = this._checkRestrictionZoneBounds(null, new Sys.UI.Bounds(popupBounds.x, popupBounds.y, currentWidth, popupBounds.height))
            if(!toUpdate) return false;
        }

        if (this._width != value) {
            this._width = value;
        }

        if (popupElement)
        {
            this._deleteStoredBounds();
            //Calling _updatePopupZindex take care of the overlay IFRAME behind the window
            popupElement.style.width = this._width;
            this._updatePopupZindex();
        }
        
        return true;
    },


    get_height : function()
    {
        /// <summary>
        /// Gets height of the window
        /// </summary>
        /// <value type="Unit">
        /// The original height of the window
        /// </value>

        //We must use parseInt for backward compatibility!
        return parseInt(this._height);
    },

    set_height : function(value)
    {
        /// <summary>
        /// Sets new height to the window
        /// </summary>
        /// <param name="value" type="Unit">
        /// The new height
        /// </param>
        if (null == value) return false;
        
        if (this.isMaximized()) return false;
        
        value = this._fixSizeValue(value);
  
        var popupElement = this._popupElement;
        if(popupElement)
        {
            var popupBounds = $Sunny.getBounds(popupElement);
            var toUpdate = this._checkRestrictionZoneBounds(null, new Sys.UI.Bounds(popupBounds.x, popupBounds.y, popupBounds.width, parseInt(value)))
            if(!toUpdate) return false;
        }

        if (this._height != value) {
            this._height = value;
        }

        if (popupElement)
        {
            this._deleteStoredBounds();
            this._updateWindowSize(this._height);

            this._updatePopupZindex();
        }
        
        return true;
    },


    _updateWindowSize : function(originalSize, useCurrent)
    {
        var table = this._tableElement;
        var height = originalSize ? originalSize : table.style.height;

        //Yet another hack
        if (true == useCurrent)
        {
            height = table.offsetHeight + "px";
        }

        //Yet another hack
        if (parseInt(height) == 0) return;

        table.style.height = height;

        this._fixIeHeight(table, height);

        //Force the div size too
        table.parentNode.style.height = height;
    },

    get_initialBehaviors : function()
    {
        /// <summary>
        /// Gets behavior value for the window
        /// </summary>
        /// <value type="Sunny.Web.UI.WindowBehaviors">
        /// The current initial behavior setting
        /// </value>
        return this._initialBehaviors;
    },

    set_initialBehaviors : function(value)
    {
        /// <summary>
        /// Sets the initial behavior value for the window
        /// </summary>
        /// <param name="value" type="Sunny.Web.UI.WindowBehaviors">
        /// The new value
        /// </param>

        //Set the value
        if (this._initialBehaviors != value)
        {
            this._initialBehaviors = value;
        }
    },


    get_behaviors : function()
    {
        /// <summary>
        /// Gets behavior value for the window
        /// </summary>
        /// <value type="Sunny.Web.UI.WindowBehaviors">
        /// The current behavior setting
        /// </value>
        return this._behaviors;
    },

    set_behaviors : function(value)
    {
        /// <summary>
        /// Sets behavior value for the window
        /// </summary>
        /// <param name="value" type="Sunny.Web.UI.WindowBehaviors">
        /// The new value
        /// </param>

        //Set the value
        if (this._behaviors != value)
        {
            this._behaviors = value;
        }

        //set_behaviors is called at initialization time, when we do not have UI. So, return
        if (null == this._titlebarElement) return;

        //Make resizable - in set_behaviors
        this._enableMoveResize(false);
        this._enableMoveResize(true);

        //If buttons exist - dispose of them
        if (this._buttonsArray && this._buttonsArray.length > 0)
        {
            //Dispose buttons
            var len = this._buttonsArray.length;
            for (var i = 0; i < len; i++)
            {
                var button = this._buttonsArray[i];
                $clearHandlers(button);
            }

            //Clean array
            this._buttonsArray = [];

            //Clean _buttonsElement
            var commandButtonsHolder = this._getTitleCommandButtonsHolder();
            commandButtonsHolder.innerHTML = "";
        }

        //If the behaviors is None - return
        if (Sunny.Web.UI.WindowBehaviors.None == this._behaviors)
        {
            return;
        }
        else
        {
            var loc = this._getLocalization();
            var bhvEnum = Sunny.Web.UI.WindowBehaviors;
            var buttonsArray = [    //enabled, classname, tooltip,  clickhandler
                                    [this.isBehaviorEnabled(bhvEnum.Pin),"rwPinButton", loc["PinOn"], this.togglePin],
                                    [this.isBehaviorEnabled(bhvEnum.Reload),"rwReloadButton",loc["Reload"], this.reload],
                                    [this.isBehaviorEnabled(bhvEnum.Minimize),"rwMinimizeButton",loc["Minimize"], this.minimize],
                                    [this.isBehaviorEnabled(bhvEnum.Maximize),"rwMaximizeButton",loc["Maximize"], this.maximize],
                                    [this.isBehaviorEnabled(bhvEnum.Close),"rwCloseButton",loc["Close"], this.close]
                               ];

            for (var i = 0; i < buttonsArray.length; i++)
            {
                var info = buttonsArray[i];

                //If behavior is disabled
                if (!info[0]) continue;

                var li = document.createElement("LI");

		            var curButton = document.createElement('A');
		            curButton.href = "javascript:void(0);";
		            curButton.className = info[1];
		            curButton.setAttribute("title", info[2]);

	                var oSpan = document.createElement('SPAN');
	                oSpan.innerHTML = info[2];
	                curButton.appendChild(oSpan);

		        //Using addHandles eliminates the need of calling Function.createDelegate
		        //Cancel the double click event, so that the window is not restored when you double click a button.
	//	        $addHandler(curButton, 'dblclick', this._cancelEvent);
	//	        $addHandler(curButton, 'mousedown', this._cancelEvent);
		        $addHandlers(curButton, {'click' : info[3]
		                                 ,'dblclick' : this._cancelEvent
		                                 ,'mousedown' : this._cancelEvent
		                        }, this);

		        //Cancel the click event, so that it does not propagate either
		        //This is a bit risky to use, as browser don't call event handlers in a guaranteed order, but seems to work
		        //The maximize, etc methods could in theory receive the e event and cancel it, however, close method already receives an arg
		        $addHandler(curButton, 'click', this._cancelEvent);

		        li.appendChild(curButton);

		        //Append close element
		        this._buttonsElement.appendChild(li);

		        //Add to the buttons collection to be disposed and cleaned when needed
		        this._buttonsArray[this._buttonsArray.length] = curButton;
		    }
		}
    },

    //---------------------RadWindow boolean properties --------------//


    get_modal: function()
    {
        /// <summary>
        /// Gets a value indicating whether a window is modal or not
        /// </summary>
        /// <value type="Boolean">
        /// The current setting
        /// </value>
        return this._modal;
    },

    set_modal : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether a window is modal or not
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        if (this._modal != value) {
            this._modal = value;
        }

        this._makeModal(this._modal);

        if (this.isVisible())
        {            
            //The show event, on which the modal extener relies is raised in _afterShow
            this._afterShow();
        }
    },


    get_destroyOnClose : function()
    {
        /// <summary>
        /// Gets a value indicating whether the window will be disposed and made inaccessible once it is closed.
        /// If property is set to true, the next time a window with this ID is requested, a new window with default settings is created and returned.
        /// </summary>
        /// <value type="Boolean">
        /// The current destroy on close setting
        /// </value>
        return this._destroyOnClose;
    },

    set_destroyOnClose : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the window will be disposed and made inaccessible once it is closed.
        /// If property is set to true, the next time a window with this ID is requested, a new window with default settings is created and returned.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        if (this._destroyOnClose!= value)
        {
            this._destroyOnClose = value;
        }
    },

    get_reloadOnShow : function()
    {
        /// <summary>
        /// Gets a value indicating whether the page that is loaded in the window should be loaded everytime from the server or
        /// will leave the browser default behaviour.
        /// </summary>
        /// <value type="Boolean">
        /// The current setting
        /// </value>
        return this._reloadOnShow;
    },

    set_reloadOnShow : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the page that is loaded in the window should be loaded everytime from the server or
        /// will leave the browser default behaviour.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        if (this._reloadOnShow!= value) {
            this._reloadOnShow = value;
        }
    },


    get_showContentDuringLoad : function()
    {
        /// <summary>
        /// Gets a value indicating whether the page that is loaded
        /// in the window should be shown during the rwLoading process, or when it has finished rwLoading.
        /// </summary>
        /// <value type="Boolean">
        /// The current setting
        /// </value>
        return this._showContentDuringLoad;
    },

    set_showContentDuringLoad: function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the page that is loaded
        /// in the window should be shown during the rwLoading process, or when it has finished rwLoading.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        if (this._showContentDuringLoad != value) {
            this._showContentDuringLoad = value;
        }
    },


    get_visibleOnPageLoad: function()
    {
        /// <summary>
        /// Gets a value indicating whether the window will open automatically when its parent [aspx] page is loaded on the client.
        /// </summary>
        /// <value type="Boolean">
        /// The current setting
        /// </value>
        return this._visibleOnPageLoad;
    },

    set_visibleOnPageLoad : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the window will open automatically when its parent [aspx] page is loaded on the client.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        if (this._visibleOnPageLoad != value) {
            this._visibleOnPageLoad = value;
        }
    },


    get_visibleTitlebar: function()
    {
        /// <summary>
        /// Get a value indicating whether the window has a rwTitlebar visible
        /// </summary>
        /// <value type="Boolean">
        /// The current setting
        /// </value>
        return this._visibleTitlebar;
    },

    set_visibleTitlebar : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the window has a rwTitlebar visible
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        if (this._visibleTitlebar != value)
        {
            this._visibleTitlebar = value;
        }

        //If the element exists - show it / hide it. This code is out of the if above, because it is possible to set a value before the element is created, and then next time the method is called internally by rad window, nothing will happen
        if (this._titlebarElement)
        {
            this._titlebarElement.style.display = value ? "" : "none";
        }
    },


    get_visibleStatusbar: function()
    {
        /// <summary>
        /// Gets a value indicating whether the window has a visible status bar or not.
        /// </summary>
        /// <value type="Boolean">
        /// The current setting
        /// </value>
        return this._visibleStatusbar;
    },

    set_visibleStatusbar : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the window has a visible status bar or not.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        if (this._visibleStatusbar != value)
        {
            this._visibleStatusbar = value;
        }

        //If the element exists - show it / hide it
        if (this._statusCell)
        {
            this._statusCell.parentNode.style.display = value ? "" : "none";
        }
    },

    get_animation : function()
    {
        /// <summary>
        /// Gets animation value for the window
        /// </summary>
        /// <value type="Sunny.Web.UI.WindowAnimation">
        /// The current animation setting
        /// </value>
        return this._animation;
    },

    set_animation : function(value)
    {
        /// <summary>
        /// Sets animation value for the window
        /// </summary>
        /// <param name="value" type="Sunny.Web.UI.WindowAnimation">
        /// The new value
        /// </param>
        if (this._animation != value) {
            this._animation = value;
        }
    },

     get_overlay : function()
    {
        /// <summary>
        /// Gets a value indicating whether the window has an overlay element.
        /// </summary>
        /// <value type="Boolean">
        /// The current overlay setting
        /// </value>
        return this._overlay;
    },

    set_overlay : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the window will create an overlay element.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        this._overlay = value;
        if(this._popupBehavior)
            this._popupBehavior.set_overlay(this._overlay);

        //If the window is visible, re-show window but avoid throwing events.
        if(this.isVisible())
            this._reSetWindowPosition();
    },

    get_keepInScreenBounds : function()
    {
        /// <summary>
        /// Gets a value indicating whether the window will show in the visible viewport of the browser window.
        /// </summary>
        /// <value type="Boolean">
        /// The current keep in screen bounds setting
        /// </value>
        return this._keepInScreenBounds;
    },

    set_keepInScreenBounds : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether the window will show in the visible viewport of the browser window.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
        this._keepInScreenBounds = value;
        if(this._popupBehavior)
            this._popupBehavior.set_keepInScreenBounds(this._keepInScreenBounds);

        //If the window is visible, re-show window but avoid throwing events.
        if(this.isVisible())
            this._reSetWindowPosition();
    },
    
     get_autoSize : function()
    {
        /// <summary>
        /// Gets a value which indicates whether the window will automatically resize itself acciording to its content page or not.
        /// </summary>
        /// <value type="Boolean">
        /// The current keep in screen bounds setting
        /// </value>
        return this._autoSize;
    },

    set_autoSize : function(value)
    {
        /// <summary>
        /// Sets a value which indicates whether the window will automatically resize itself acciording to its content page or not.
        /// </summary>
        /// <param name="value" type="Boolean">
        /// The new setting
        /// </param>
       if (this._autoSize != value) {
            this._autoSize = value;
       }
    },

    get_skin : function()
    {
        /// <exclude/>
        return this._skin;
    },

    set_skin : function(value)
    {
        /// <exclude/>
        if (value && this._skin != value)
        {
           this._skin = value;
        }
    },

    //New: needed by window manager
    get_popupElement : function()
    {
        /// <exclude/>
        return this._popupElement;
    },

    //Window manager
    get_windowManager : function()
    {
        /// <exclude/>
        return this._windowManager;
    },

    set_windowManager : function(manager)
    {
        /// <exclude/>
        this._windowManager = manager;
    },


    set_status : function(message)
    {
        /// <summary>
        /// Sets a message in the status area of the window
        /// </summary>
        /// <param name="message" type="String">
        /// The new value
        /// </param>
        var input = this._getStatusMessageElement();

        //TFS 7998 RadWindow resize on long status bar text set in IE
        if (input)
        {
            window.setTimeout(function()
            {
                input.value = message;
            }, 0);
        }
    },

    get_status : function()
    {
        /// <summary>
        /// Gets current message in the status area of the window
        /// </summary>
        /// <value type="String">
        /// The current message
        /// </value>
        var input = this._getStatusMessageElement();
        if (input) return input.value;
    },



    // #region Events
    add_command : function(handler)
	{
		/// <summary>
		/// Adds a handler to the Command event
		/// </summary>
		/// <param name="handler" type="Function">
		/// handler
		/// </param>
		this.get_events().addHandler("command", handler);
	},
	remove_command : function(handler)
	{
		/// <summary>
		/// Removes a handler from the Command event
		/// </summary>
		/// <param name="handler" type="Function">
		/// handler
		/// </param>
		this.get_events().removeHandler("command", handler);
	},

	raise_command : function(args)
	{
		/// <summary>
		/// Raises the Command event
		/// </summary>
		this.raiseEvent("command", args);
	},



    add_dragStart : function(handler)
	{
		/// <summary>
		/// Adds a handler to the DragStart event
		/// </summary>
		/// <param name="handler" type="Function">
		/// handler
		/// </param>
		this.get_events().addHandler("dragStart", handler);
	},
	remove_dragStart : function(handler)
	{
		/// <summary>
		/// Removes a handler from the DragStart event
		/// </summary>
		/// <param name="handler" type="Function">
		/// handler
		/// </param>
		this.get_events().removeHandler("dragStart", handler);
	},

	add_dragEnd : function(handler)
	{
		/// <summary>
		/// Adds a handler to the DragEnd event
		/// </summary>
		/// <param name="handler" type="Function">
		/// handler
		/// </param>
		this.get_events().addHandler("dragEnd", handler);
	},
	remove_dragEnd : function(handler)
	{
		/// <summary>
		/// Removes a handler from the DragEnd event
		/// </summary>
		/// <param name="handler" type="Function">
		/// handler
		/// </param>
		this.get_events().removeHandler("dragEnd", handler);
	},



    add_activate : function(handler) {
        /// <summary>
        /// Add a handler to the Activate event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().addHandler("activate", handler);
    },
    remove_activate : function(handler) {
        /// <summary>
        /// Remove a handler from the Activate event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().removeHandler("activate", handler);
    },

    add_beforeShow : function(handler) {
        /// <summary>
        /// Add a handler to the BeforeShow event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().addHandler("beforeShow", handler);
    },
    remove_beforeShow : function(handler) {
        /// <summary>
        /// Remove a handler from the BeforeShow event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().removeHandler("beforeShow", handler);
    },



    add_show : function(handler) {
        /// <summary>
        /// Add a handler to the Show event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().addHandler("show", handler);
    },
    remove_show : function(handler) {
        /// <summary>
        /// Remove a handler from the Show event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().removeHandler("show", handler);
    },

    add_pageLoad : function(handler) {
        /// <summary>
        /// Add a handler to the PageLoad event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().addHandler("pageLoad", handler);
    },
    remove_pageLoad : function(handler) {
        /// <summary>
        /// Remove a handler from the PageLoad event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().removeHandler("pageLoad", handler);
    },

    add_close : function(handler) {
        /// <summary>
        /// Add a handler to the Close event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().addHandler("close", handler);
    },
    remove_close : function(handler) {
        /// <summary>
        /// Remove a handler from the Close event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().removeHandler("close", handler);
    },




//NEW - Svetlina - 16.12.08

add_beforeClose : function(handler) {
        /// <summary>
        /// Add a handler to the Close event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().addHandler("beforeClose", handler);
    },
    remove_beforeClose : function(handler) {
        /// <summary>
        /// Remove a handler from the Close event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().removeHandler("beforeClose", handler);
    },



     add_resize : function(handler) {
        /// <summary>
        /// Add a handler to the Resize event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().addHandler("resize", handler);
    },
    remove_resize : function(handler) {
        /// <summary>
        /// Remove a handler from the Resize event
        /// </summary>
        /// <param name="handler" type="Function">
        /// Handler
        /// </param>
        this.get_events().removeHandler("resize", handler);
    },


    saveClientState: function()
    {
        /// <exclude/>
		var propsToSerialize = [
								 "position"
								];
		var state = {};

		for (var i=0; i < propsToSerialize.length; i ++) {
			state[propsToSerialize[i]] = this["get_" + propsToSerialize[i]]();
		}

        return Sys.Serialization.JavaScriptSerializer.serialize(state);
    }
}

Sunny.Web.UI.RadWindow.registerClass('Sunny.Web.UI.RadWindow', Sunny.Web.UI.RadWebControl);
//    getDescriptor : function() {
//        var td = Sunny.Web.UI.RadWindow.callBaseMethod(this, 'getDescriptor');
//        // Add custom properties
//        td.addProperty('OpenerElementID', String);
//        td.addProperty('Position', String);
//        td.addProperty('Left', Number);
//        td.addProperty('Top', Number);
//        td.addProperty('ExtenderControlID', String);
//        return td;
//    },


Sunny.Web.UI.WindowAnimation = function() {
    /// <summary>
    /// Used to set the Animation property
    /// </summary>
    /// <field name="None" type="Number" integer="true" />
    /// <field name="Resize" type="Number" integer="true" />
    /// <field name="Fade" type="Number" integer="true" />
    /// <field name="Slide" type="Number" integer="true" />
    /// <field name="FlyIn" type="Number" integer="true" />
    throw Error.invalidOperation();
}

Sunny.Web.UI.WindowAnimation.prototype =
{
    None : 0,
    Resize: 1,
    Fade : 2,
    Slide : 4,
    FlyIn : 8
};
Sunny.Web.UI.WindowAnimation.registerEnum("Sunny.Web.UI.WindowAnimation", false);


Sunny.Web.UI.WindowMinimizeMode = function() {
    /// <summary>
    /// Used to set the Animation property
    /// </summary>
    /// <field name="SameLocation" type="Number" integer="true" />
    /// <field name="MinimizeZone" type="Number" integer="true" />
    /// <field name="Default" type="Number" integer="true" />
    throw Error.invalidOperation();
}

Sunny.Web.UI.WindowMinimizeMode.prototype =
{
   	SameLocation : 1,
	MinimizeZone : 2,
	Default	: 1
};
Sunny.Web.UI.WindowMinimizeMode.registerEnum("Sunny.Web.UI.WindowMinimizeMode", false);



Sunny.Web.UI.WindowBehaviors = function() {
    /// <summary>
    /// Used to set the Animation property
    /// </summary>
    /// <field name="None" type="Number" integer="true" />
    /// <field name="Resize" type="Number" integer="true" />
    /// <field name="Minimize" type="Number" integer="true" />
    /// <field name="Close" type="Number" integer="true" />
    /// <field name="Pin" type="Number" integer="true" />
    /// <field name="Maximize" type="Number" integer="true" />
    /// <field name="Move" type="Number" integer="true" />
    /// <field name="Reload" type="Number" integer="true" />
    /// <field name="Default" type="Number" integer="true" />
    throw Error.invalidOperation();
}

Sunny.Web.UI.WindowBehaviors.prototype =
{
    None : 0,
	Resize : 1,
	Minimize : 2,
	Close : 4,
	Pin : 8,
	Maximize : 16,
	Move: 32,
	Reload: 64,
	Default: (1 + 2 + 4 + 8 + 16 + 32 + 64)
};

Sunny.Web.UI.WindowBehaviors.registerEnum("Sunny.Web.UI.WindowBehaviors", false);


/////////////////////////////////////////////////////////////////////////////
// Global window z-index tracker
///////////////////////////////////////////////////////////////////////////
//NEW: Updated by RadWindowManager
Sunny.Web.UI.RadWindowUtils._zIndex = 3000;

//Returns a new zIndex, if the provided oldZindex is smaller than the current value, and changes the value
Sunny.Web.UI.RadWindowUtils.get_newZindex = function(oldZindex)
{
    oldZindex = parseInt(oldZindex);
    if (null == oldZindex || isNaN(oldZindex))
    {
        oldZindex = 0;
    }

    if (Sunny.Web.UI.RadWindowUtils._zIndex < oldZindex)
    {
        Sunny.Web.UI.RadWindowUtils._zIndex = oldZindex;
    }

    Sunny.Web.UI.RadWindowUtils._zIndex++;
	return Sunny.Web.UI.RadWindowUtils._zIndex;
};


///////////////////////////////////////////////////////////////////////////
// The 'Pin' implementation is here
///////////////////////////////////////////////////////////////////////////
Sunny.Web.UI.RadWindowUtils._pinnedList = {};

Sunny.Web.UI.RadWindowUtils.setPinned = function(toPin, oWnd)
{
	if (toPin)
	{
	    var screen = oWnd._getViewportBounds();
	    var wndBounds = oWnd._getCurrentBounds();

	    oWnd.LeftOffset = wndBounds.x - screen.scrollLeft;
		oWnd.TopOffset = wndBounds.y - screen.scrollTop;

		var intervalId = window.setInterval(
		                function()
		                {
		                        Sunny.Web.UI.RadWindowUtils._updatePinnedElementPosition(oWnd);
		                }, 100);

		Sunny.Web.UI.RadWindowUtils._pinnedList[intervalId] = oWnd;
	}
	else
	{
		var interval = null;
		var oList = Sunny.Web.UI.RadWindowUtils._pinnedList;
		for (var name in oList)
		{
			if (oList[name] == oWnd)
			{
				interval = name;
				break;
			}
		}
		if (null != interval)
		{
			window.clearInterval(interval);
			Sunny.Web.UI.RadWindowUtils._pinnedList[interval] = null;
		}
		oWnd.TopOffset = null;
		oWnd.LeftOffset = null;
	}
}

Sunny.Web.UI.RadWindowUtils._updatePinnedElementPosition = function(oWnd)
{
    //In case the pinned window is maximized, do not relocate it.
    if(oWnd.isMaximized() || !oWnd.isVisible()) return;

    var screen = oWnd._getViewportBounds();
	var wndBounds = oWnd._getCurrentBounds();

	var left = (oWnd.LeftOffset != null)? oWnd.LeftOffset + screen.scrollLeft : wndBounds.x;
	var top = (oWnd.TopOffset != null)? oWnd.TopOffset + screen.scrollTop : wndBounds.y;

	oWnd.moveTo(left, top);
};
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();