/* START Telerik.Web.UI.Common.Core.js */
// Avoids the background image flickering in IE 6 (http://www.mister-pixel.com/)
try
{
	document.execCommand("BackgroundImageCache", false, true);
}
catch(err) {}

Type.registerNamespace("Telerik.Web.UI");

window.$telerik = window.TelerikCommonScripts = Telerik.Web.CommonScripts = {
	
	_borderStyleNames : ['borderTopStyle','borderRightStyle','borderBottomStyle','borderLeftStyle'],
	_borderWidthNames : ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth'],
	_paddingWidthNames : ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],
	_marginWidthNames : ['marginTop', 'marginRight', 'marginBottom', 'marginLeft'],
	radControls : [],
	
	registerControl : function (control)
	{
		if (!Array.contains(this.radControls, control))
			Array.add(this.radControls, control);
	},
	
	unregisterControl : function (control)
	{
		Array.remove(this.radControls, control);
	},
	
	repaintChildren : function (parentControl)
	{
		var parentElement = parentControl.get_element();
		
		for (var i = 0, length = this.radControls.length; i < length; i ++)
		{
	        var control = this.radControls[i];
        
		    if (control.repaint && this.isDescendant(parentElement, control.get_element()))
				control.repaint();
		}
	},
	
	_borderThickness : function ()
	{
		$telerik._borderThicknesses = { };

		var div0 = document.createElement('div');
		var div1 = document.createElement('div');

		div0.style.visibility = 'hidden';
		div0.style.position = 'absolute';
		div0.style.fontSize = '1px';
	    
		div1.style.height = '0px';
		div1.style.overflow = 'hidden';
	    
		document.body.appendChild(div0).appendChild(div1);
	                    
		var base = div0.offsetHeight;
		div1.style.borderTop = 'solid black';        

		div1.style.borderTopWidth = 'thin';
		$telerik._borderThicknesses['thin'] = div0.offsetHeight - base;
	    
		div1.style.borderTopWidth = 'medium';
		$telerik._borderThicknesses['medium'] = div0.offsetHeight - base;
	    
		div1.style.borderTopWidth = 'thick';
		$telerik._borderThicknesses['thick'] = div0.offsetHeight - base;
	    
		if (typeof(div0.removeChild) !== "undefined")
			div0.removeChild(div1);
			
		document.body.removeChild(div0);
		div0 = null;
		div1 = null;
	},
	
	getCurrentStyle : function(element, attribute, defaultValue) {
     
        var currentValue = null;
        if (element) {
            if (element.currentStyle) {
                currentValue = element.currentStyle[attribute];
            } else if (document.defaultView && document.defaultView.getComputedStyle) {
                var style = document.defaultView.getComputedStyle(element, null);
                if (style) {
                    currentValue = style[attribute];
                }
            }
            
            if (!currentValue && element.style.getPropertyValue) {
                currentValue = element.style.getPropertyValue(attribute);
            }
            else if (!currentValue && element.style.getAttribute) {
                currentValue = element.style.getAttribute(attribute);
            }       
        }
        
        if ((!currentValue || currentValue == "" || typeof(currentValue) === 'undefined')) {
            if (typeof(defaultValue) != 'undefined') {
                currentValue = defaultValue;
            }
            else {
                currentValue = null;
            }
        }   
        return currentValue;  
    },
    
    getInheritedBackgroundColor : function(element) {
        if (!element) return '#FFFFFF';
        var background = $telerik.getCurrentStyle(element, 'backgroundColor');
        try {
            while (!background || background == '' || background == 'transparent' || background == 'rgba(0, 0, 0, 0)') {
                element = element.parentNode;
                if (!element) {
                    background = '#FFFFFF';
                } else {
                    background = $telerik.getCurrentStyle(element, 'backgroundColor');
                }
            }
        } catch(ex) {
            background = '#FFFFFF';
        }
        return background;
    },
    
	getLocation : function(element) {

		// workaround for an issue in getLocation where it will compute the location of the document element.
		// this will return an offset if scrolled.
		//
		if (element === document.documentElement) {
			return new Sys.UI.Point(0,0);
		}

		// Workaround for IE6 bug in getLocation (also required patching getBounds - remove that fix when this is removed)
		
		//TEKI: When in IE7 in a scenario when item is in a FRAMESET, the location value is wrong. However, using the IE6 code below it works fine
		if (Sys.Browser.agent == Sys.Browser.InternetExplorer /*&& Sys.Browser.version < 7*/) {
			if (element.window === element || element.nodeType === 9 || !element.getClientRects || !element.getBoundingClientRect) return new Sys.UI.Point(0,0);

			// Get the first bounding rectangle in screen coordinates
			var screenRects = element.getClientRects();
			if (!screenRects || !screenRects.length) {
				return new Sys.UI.Point(0,0);
			}
			var first = screenRects[0];

			// Delta between client coords and screen coords
			var dLeft = 0;
			var dTop = 0;

			var inFrame = false;
			try {
				inFrame = element.ownerDocument.parentWindow.frameElement;
			} catch(ex) {
				// If accessing the frameElement fails, a frame is probably in a different
				// domain than its parent - and we still want to do the calculation below
				inFrame = true;
			}

			// If we're in a frame, get client coordinates too so we can compute the delta
			if (inFrame) {
				// Get the bounding rectangle in client coords
				var clientRect = element.getBoundingClientRect();
				if (!clientRect) {
					return new Sys.UI.Point(0,0);
				}

				// Find the minima in screen coords
				var minLeft = first.left;
				var minTop = first.top;
				for (var i = 1; i < screenRects.length; i++) {
					var r = screenRects[i];
					if (r.left < minLeft) {
						minLeft = r.left;
					}
					if (r.top < minTop) {
						minTop = r.top;
					}
				}

				// Compute the delta between screen and client coords
				dLeft = minLeft - clientRect.left;
				dTop = minTop - clientRect.top;
			}

			// Subtract 2px, the border of the viewport (It can be changed in IE6 by applying a border style to the HTML element,
			// but this is not supported by ASP.NET AJAX, and it cannot be changed in IE7.), and also subtract the delta between
			// screen coords and client coords
			var ownerDocument = element.document.documentElement;
			
			var position = new Sys.UI.Point(first.left - 2 - dLeft + ownerDocument.scrollLeft, first.top - 2 - dTop + ownerDocument.scrollTop);

			if ($telerik.quirksMode)
			{						
				position.x += document.body.scrollLeft;
				position.y += document.body.scrollTop;
			}
			
			return position;
		}

		var position = Sys.UI.DomElement.getLocation(element);
		
		if ($telerik.isOpera)
		{
			var parent = element.offsetParent;
			
			while (parent && parent.tagName.toUpperCase() != 'BODY' 
				&& parent.tagName.toUpperCase() != 'HTML') 
			{
				position.x -= parent.scrollLeft;
				position.y -= parent.scrollTop;
				parent = parent.offsetParent;
			}
		}
		
		if ($telerik.isSafari)
		{
			var parent = element.parentNode;
			
			var parentTD = null;
			var parentTABLE = null;
			
			while (parent && parent.tagName.toUpperCase() != 'BODY' 
				&& parent.tagName.toUpperCase() != 'HTML') 
			{
				position.x -= parent.scrollLeft;
				position.y -= parent.scrollTop;
				
				// Workaround for a problem with parent TABLES - when you have a parent TABLE element with border,
				// Safari acts as if the TABLE/TD has no border and calculates X and Y incorrectly. 
				// That is why we need to add the borders manually. In case this is fixed in a future verion of the browser
				// we will need to remove this code.
				if($telerik.isSafari3 || $telerik.isSafari2)
				{
				    if(parent.tagName.toUpperCase() == "TD")
			        {
			            parentTD = parent;
			        }
                    else if(parent.tagName.toUpperCase() == "TABLE")
                    {
                        parentTABLE = parent;
                    }
                    
                    if(parentTD && parentTABLE)
                    {                
                        position.x += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderTopWidth'));
                        position.y += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderLeftWidth'));
                            
                        // In case the TABLE has borderCollapse:collapse, we need to take the borderWidth of either
                        // the TABLE or the TD.
                        if($telerik.getCurrentStyle(parentTABLE, 'borderCollapse') != 'collapse')
                        {
                            position.x += parseInt($telerik.getCurrentStyle(parentTD, 'borderTopWidth'));
                            position.y += parseInt($telerik.getCurrentStyle(parentTD, 'borderLeftWidth'));
                        }
                        
                        parentTD = null;
                        parentTABLE = null;
                    }
                    // In case we use getLocation for a TD element, we need to calculate the borderWidth of its TABLE
                    // only in case that TABLE has no borderCollapse:collapse.
                    else if(parentTABLE)
                    {
                        if($telerik.getCurrentStyle(parentTABLE, 'borderCollapse') != 'collapse')
                        {
                            position.x += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderTopWidth'));
                            position.y += parseInt($telerik.getCurrentStyle(parentTABLE, 'borderLeftWidth'));
                        }
                        parentTABLE = null;
                    }
                }
                
                // END of Workaround for a problem with parent TABLES
				
				parent = parent.parentNode;
			}			
		}

		if ($telerik.isIE && $telerik.quirksMode)
		{
			position.x += document.body.scrollLeft;
			position.y += document.body.scrollTop;
		}

		return position;
	},

    setLocation : function(element, point) {
        Sys.UI.DomElement.setLocation(element, point.x, point.y);
    },
    
    getContentSize : function(element) {
        /// <summary>
        /// Gets the "content-box" size of an element.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Size of the element (in the form {width,height})
        /// </returns>
        /// <remarks>
        /// The "content-box" is the size of the content area *inside* of the borders and
        /// padding of an element. The "content-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        var size = $telerik.getSize(element);
        var borderBox = $telerik.getBorderBox(element);
        var paddingBox = $telerik.getPaddingBox(element);
        return {
            width :  size.width - borderBox.horizontal - paddingBox.horizontal,
            height : size.height - borderBox.vertical - paddingBox.vertical
        }
    },
    
    getSize : function(element) {
        /// <summary>
        /// Gets the "border-box" size of an element.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Size of the element (in the form {width,height})
        /// </returns>
        /// <remarks>
        /// The "border-box" is the size of the content area *outside* of the borders and
        /// padding of an element.  The "border-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        return {
            width:  element.offsetWidth,
            height: element.offsetHeight
        };
    },
    
    setContentSize : function(element, size) {
        /// <summary>
        /// Sets the "content-box" size of an element.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="size" type="Object">
        /// Size of the element (in the form {width,height})
        /// </param>
        /// <remarks>
        /// The "content-box" is the size of the content area *inside* of the borders and
        /// padding of an element. The "content-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if (!size) {
            throw Error.argumentNull('size');
        }
        // FF respects -moz-box-sizing css extension, so adjust the box size for the border-box
        if($telerik.getCurrentStyle(element, 'MozBoxSizing') == 'border-box' || $telerik.getCurrentStyle(element, 'BoxSizing') == 'border-box') {
            var borderBox = $telerik.getBorderBox(element);
            var paddingBox = $telerik.getPaddingBox(element);
            size = {
                width: size.width + borderBox.horizontal + paddingBox.horizontal,
                height: size.height + borderBox.vertical + paddingBox.vertical
            };
        }
        element.style.width = size.width.toString() + 'px';
        element.style.height = size.height.toString() + 'px';
    },
    
    setSize : function(element, size) {
        /// <summary>
        /// Sets the "border-box" size of an element.
        /// </summary>
        /// <remarks>
        /// The "border-box" is the size of the content area *outside* of the borders and 
        /// padding of an element.  The "border-box" size does not include the margins around
        /// the element.
        /// </remarks>
        /// <param name="element" type="Sys.UI.DomElement">DOM element</param>
        /// <param name="size" type="Object">Size of the element (in the form {width,height})</param>
        /// <returns />
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if (!size) {
            throw Error.argumentNull('size');
        }
        var borderBox = $telerik.getBorderBox(element);
        var paddingBox = $telerik.getPaddingBox(element);
        var contentSize = {
            width:  size.width - borderBox.horizontal - paddingBox.horizontal,
            height: size.height - borderBox.vertical - paddingBox.vertical
        };
        $telerik.setContentSize(element, contentSize);
    },
	
	getBounds : function(element) {
        /// <summary>Gets the coordinates, width and height of an element.</summary>
        /// <param name="element" domElement="true"/>
        /// <returns type="Sys.UI.Bounds">
        ///   A Bounds object with four fields, x, y, width and height, which contain the pixel coordinates,
        ///   width and height of the element.
        /// </returns>

        var offset = $telerik.getLocation(element);
        return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0);
    },
	
	setBounds : function(element, bounds) {
        /// <summary>
        /// Sets the "border-box" bounds of an element
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="bounds" type="Object">
        /// Bounds of the element (of the form {x,y,width,height})
        /// </param>
        /// <remarks>
        /// The "border-box" is the size of the content area *outside* of the borders and
        /// padding of an element.  The "border-box" size does not include the margins around
        /// the element.
        /// </remarks>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if (!bounds) {
            throw Error.argumentNull('bounds');
        }
        $telerik.setSize(element, bounds);
        $telerik.setLocation(element, bounds);
    },
    
    getClientBounds : function() {
        /// <summary>
        /// Gets the width and height of the browser client window (excluding scrollbars)
        /// </summary>
        /// <returns type="Sys.UI.Bounds">
        /// Browser's client width and height
        /// </returns>

        var clientWidth;
        var clientHeight;
        switch(Sys.Browser.agent) {
            case Sys.Browser.InternetExplorer:
                clientWidth = document.documentElement.clientWidth;
                clientHeight = document.documentElement.clientHeight;
                if (clientWidth == 0 && clientHeight == 0)
                {
                    //no doctype. use the body settings
                    clientWidth = document.body.clientWidth;
                    clientHeight = document.body.clientHeight;
                }
                break;
            case Sys.Browser.Safari:
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
                break;
            case Sys.Browser.Opera:
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
                break;
            default:  // Sys.Browser.Firefox, etc.
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
                break;
        }
        return new Sys.UI.Bounds(0, 0, clientWidth, clientHeight);
    },
    
    getMarginBox : function(element) {
        /// <summary>
        /// Gets the entire margin box sizes.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Element's margin box sizes (of the form {top,left,bottom,right,horizontal,vertical})
        /// </returns>
        if (!element) {
            throw Error.argumentNull('element');
        }
        var box = {
            top: $telerik.getMargin(element, Telerik.Web.BoxSide.Top),
            right: $telerik.getMargin(element, Telerik.Web.BoxSide.Right),
            bottom: $telerik.getMargin(element, Telerik.Web.BoxSide.Bottom),
            left: $telerik.getMargin(element, Telerik.Web.BoxSide.Left)
        }
        
        box.horizontal = box.left + box.right;
        box.vertical = box.top + box.bottom;
        return box;
    },
    
    getPaddingBox : function(element) {
        /// <summary>
        /// Gets the entire padding box sizes.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Element's padding box sizes (of the form {top,left,bottom,right,horizontal,vertical})
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        var box = {
            top: $telerik.getPadding(element, Telerik.Web.BoxSide.Top),
            right: $telerik.getPadding(element, Telerik.Web.BoxSide.Right),
            bottom: $telerik.getPadding(element, Telerik.Web.BoxSide.Bottom),
            left: $telerik.getPadding(element, Telerik.Web.BoxSide.Left)
        }
        box.horizontal = box.left + box.right;
        box.vertical = box.top + box.bottom;
        return box;
    },
    
    getBorderBox : function(element) {
        /// <summary>
        /// Gets the entire border box sizes.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <returns type="Object">
        /// Element's border box sizes (of the form {top,left,bottom,right,horizontal,vertical})
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        var box = {
            top: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Top),
            right: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Right),
            bottom: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Bottom),
            left: $telerik.getBorderWidth(element, Telerik.Web.BoxSide.Left)
        }
        box.horizontal = box.left + box.right;
        box.vertical = box.top + box.bottom;
        return box;
    },

	isBorderVisible : function(element, boxSide) {
        /// <summary>
        /// Gets whether the current border style for an element on a specific boxSide is not 'none'.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Boolean">
        /// Whether the current border style for an element on a specific boxSide is not 'none'.
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        var styleName = $telerik._borderStyleNames[boxSide];
        var styleValue = $telerik.getCurrentStyle(element, styleName);
        return styleValue != "none";
    },
    getMargin : function(element, boxSide) {
        /// <summary>
        /// Gets the margin thickness of an element on a specific boxSide.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Number" integer="true">
        /// Margin thickness on the element's specified side
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        var styleName = $telerik._marginWidthNames[boxSide];
        var styleValue = $telerik.getCurrentStyle(element, styleName);

        try { return $telerik.parsePadding(styleValue); } catch(ex) { return 0; }
    },

    getBorderWidth : function(element, boxSide) {
        /// <summary>
        /// Gets the border thickness of an element on a specific boxSide.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Number" integer="true">
        /// Border thickness on the element's specified side
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        if(!$telerik.isBorderVisible(element, boxSide)) {
            return 0;
        }        
        var styleName = $telerik._borderWidthNames[boxSide];    
        var styleValue = $telerik.getCurrentStyle(element, styleName);
        return $telerik.parseBorderWidth(styleValue);
    },
    
    getPadding : function(element, boxSide) {
        /// <summary>
        /// Gets the padding thickness of an element on a specific boxSide.
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// DOM element
        /// </param>
        /// <param name="boxSide" type="Telerik.Web.BoxSide">
        /// Side of the element
        /// </param>
        /// <returns type="Number" integer="true">
        /// Padding on the element's specified side
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        if(boxSide < Telerik.Web.BoxSide.Top || boxSide > Telerik.Web.BoxSide.Left) {
            throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Telerik.Web.BoxSide'));
        }
        var styleName = $telerik._paddingWidthNames[boxSide];
        var styleValue = $telerik.getCurrentStyle(element, styleName);
        return $telerik.parsePadding(styleValue);
    },
    
    parseBorderWidth : function(borderWidth) {
        /// <summary>
        /// Parses a border-width string into a pixel size
        /// </summary>
        /// <param name="borderWidth" type="String" mayBeNull="true">
        /// Type of border ('thin','medium','thick','inherit',px unit,null,'')
        /// </param>
        /// <returns type="Number" integer="true">
        /// Number of pixels in the border-width
        /// </returns>
        
        if(borderWidth) {
            switch(borderWidth) {
                case 'thin':
                case 'medium':
                case 'thick':
                    return $telerik._borderThicknesses[borderWidth];
                case 'inherit':
                    return 0;
            }
            var unit = $telerik.parseUnit(borderWidth);
            return unit.size;
        }
        return 0;
    },
    
    parsePadding : function(padding) {
        /// <summary>
        /// Parses a padding string into a pixel size
        /// </summary>
        /// <param name="padding" type="String" mayBeNull="true">
        /// Padding to parse ('inherit',px unit,null,'')
        /// </param>
        /// <returns type="Number" integer="true">
        /// Number of pixels in the padding
        /// </returns>
        
        if(padding) {
            if(padding == 'inherit') {
                return 0;
            }
            var unit = $telerik.parseUnit(padding);
            return unit.size;
        }
        return 0;
    },
    
    parseUnit : function(value) {
        /// <summary>
        /// Parses a unit string into a unit object
        /// </summary>
        /// <param name="value" type="String" mayBeNull="true">
        /// Value to parse (of the form px unit,% unit,em unit,...)
        /// </param>
        /// <returns type="Object">
        /// Parsed unit (of the form {size,type})
        /// </returns>
        
        if (!value) {
            throw Error.argumentNull('value');
        }
        
        value = value.trim().toLowerCase();
        var l = value.length;
        var s = -1;
        for(var i = 0; i < l; i++) {
            var ch = value.substr(i, 1);
            if((ch < '0' || ch > '9') && ch != '-' && ch != '.' && ch != ',') {
                break;
            }
            s = i;
        }
        if(s == -1) {
            throw Error.create('No digits');
        }
        var type;
        var size;
        if(s < (l - 1)) {
            type = value.substring(s + 1).trim();
        } else {
            type = 'px';
        }
        size = parseFloat(value.substr(0, s + 1));
        if(type == 'px') {
            size = Math.floor(size);
        }
        return { 
            size: size,
            type: type
        };
    },
    
    containsPoint : function(rect, x, y) {
        /// <summary>
        /// Tests whether a point (x,y) is contained within a rectangle
        /// </summary>
        /// <param name="rect" type="Object">The rectangle</param>
        /// <param name="x" type="Number">The x coordinate of the point</param>
        /// <param name="y" type="Number">The y coordinate of the point</param>
        
        //ORIGINAL TOOLKIT SCRIPT CHANGE: instead of rect.height it was written rect.width (!!!) Clearly a major bug!!!!
        return x >= rect.x && x <= (rect.x + rect.width) && y >= rect.y && y <= (rect.y + rect.height);
    },

    isDescendant : function(ancestor, descendant) {
        /// <summary>
        /// Whether the specified element is a descendant of the ancestor
        /// </summary>
        /// <param name="ancestor" type="Sys.UI.DomElement">Ancestor node</param>
        /// <param name="descendant" type="Sys.UI.DomElement">Possible descendant node</param>
        /// <returns type="Boolean" />
        
        for (var n = descendant.parentNode; n != null; n = n.parentNode) {
            if (n == ancestor) return true;
        }
        return false;
    },
	
	isDescendantOrSelf : function(ancestor, descendant) {
        /// <summary>
        /// Whether the specified element is a descendant of the ancestor or the same as the ancestor
        /// </summary>
        /// <param name="ancestor" type="Sys.UI.DomElement">Ancestor node</param>
        /// <param name="descendant" type="Sys.UI.DomElement">Possible descendant node</param>
        /// <returns type="Boolean" />

        if (ancestor === descendant) 
            return true;
        return $telerik.isDescendant(ancestor, descendant);
    },
    
	setOuterHeight : function (element, height)
	{
		if (height <= 0 || height == "") 
		{
			element.style.height = "";
		} 
		else
		{
			element.style.height = height + "px";
			var diff = element.offsetHeight - height;
			var newHeight = height - diff;
			if (newHeight > 0) {
				element.style.height = newHeight + "px";
			} else {
				element.style.height = "";
			}
		}
	},
	
    setOpacity : function(element, value) {
        /// <summary>
        /// Set the element's opacity
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// Element
        /// </param>
        /// <param name="value" type="Number">
        /// Opacity of the element
        /// </param>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        try
        {
            if (element.filters) {
                var filters = element.filters;
                var createFilter = true;
                if (filters.length !== 0) {
                    var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
                    if (alphaFilter) {
                        createFilter = false;
                        alphaFilter.opacity = value * 100;
                    }
                }
                if (createFilter) {
                    element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (value * 100) + ')';
                }
            }
            else {
                element.style.opacity = value;
            }
        }
        catch (ex) {}
    },
    	
    getOpacity : function(element) {
        /// <summary>
        /// Get the element's opacity
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement" domElement="true">
        /// Element
        /// </param>
        /// <returns type="Number">
        /// Opacity of the element
        /// </returns>
        
        if (!element) {
            throw Error.argumentNull('element');
        }
        
        var hasOpacity = false;
        var opacity;
        
        try
        {
            if (element.filters) {
                var filters = element.filters;
                if (filters.length !== 0) {
                    var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
                    if (alphaFilter) {
                        opacity = alphaFilter.opacity / 100.0;
                        hasOpacity = true;
                    }
                }
            }
            else {
                opacity = $telerik.getCurrentStyle(element, 'opacity', 1);
                hasOpacity = true;
            }
        }
        catch (ex) {}
        
        if (hasOpacity === false) {
            return 1.0;
        }
        return parseFloat(opacity);
    },

    addCssClasses : function(element, classNames) {
        /// <summary>
        /// Adds multiple css classes to a DomElement
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement">The element to modify</param>
        /// <param name="classNames" type="Array">The class names to add</param>
        
        for(var i = 0; i < classNames.length; i++) {
            Sys.UI.DomElement.addCssClass(element, classNames[i]);
        }
    },
    
    removeCssClasses : function(element, classNames) {
        /// <summary>
        /// Removes multiple css classes to a DomElement
        /// </summary>
        /// <param name="element" type="Sys.UI.DomElement">The element to modify</param>
        /// <param name="classNames" type="Array">The class names to remove</param>
        
        for(var i = 0; i < classNames.length; i++) {
            Sys.UI.DomElement.removeCssClass(element, classNames[i]);
        }
    },    	
	setOuterWidth : function (element, width)
	{
		if (width <= 0 || width == "") 
		{
			element.style.width = "";
		}
		else
		{
			element.style.width = width + "px";
			var diff = element.offsetWidth - width;
			var newWidth = width - diff;
			if (newWidth > 0) {
				element.style.width = newWidth + "px";
			} else {
				element.style.width = "";
			}
		}
	},
	
	getScrollOffset : function(element, recursive)
	{
		var left = 0;
		var top = 0;
		var parent = element;

		while (parent != null && parent.scrollLeft != null) {
			left += parent.scrollLeft;
			top += parent.scrollTop;
			// Don't include anything below the body. 
			if (!recursive || (parent == document.body && (parent.scrollLeft != 0 || parent.scrollTop != 0)))
				break;

			parent = parent.parentNode;
		}

		return { x: left, y: top };
	},
	
	getElementByClassName : function(element, className, tagName)
	{
		var children = null;
		if (tagName)
		{
			children = element.getElementsByTagName(tagName);
		}
		else
		{
			children = element.getElementsByTagName("*");
		}
	    
		for (var i = 0, length = children.length; i < length; i++)
		{
			var child = children[i];
	        
			if (Sys.UI.DomElement.containsCssClass(child, className))
			{
				return child;
			}
		}
	    
		return null;
	},
	
	//The $addHandler and $removeHandler only work with DOM HTML elements.
	//In products that use iframes (RadWindow, RadEditor, EditorPopup) events need to be attached to the iframes' document and/or contentWindow.
	//In addition to this to construct an event object, the MS AJAX framework attempts to use the window.event - which is null in the main page, when the event originates from a child frame
	//Thus, the need to provide an alternative to the MS AJAX framework arises
	addExternalHandler : function(element, eventName, handler)
	{        	
		if (element.addEventListener)
		{
			element.addEventListener(eventName, handler, false);
		}
		else if (element.attachEvent)
		{	
			element.attachEvent("on" + eventName, handler);
		}
	},
	removeExternalHandler : function(element, eventName, handler)
	{    	
		if (element.addEventListener)
		{
			element.removeEventListener(eventName, handler, false);
		}
		else if (element.detachEvent)
		{
			element.detachEvent("on" + eventName, handler);
		}
	},
	
	cancelRawEvent : function(e)
	{    	
		if (!e) return false;
		if (e.preventDefault) e.preventDefault();
		if (e.stopPropagation) e.stopPropagation();
		e.cancelBubble = true;
		e.returnValue = false;	
		return false;
	},
	
	getOuterHtml : function(element)
	{
		if (element.outerHTML)
		{
			return element.outerHTML;
		}
		else
		{
			var elementCopy = element.cloneNode(true);
			var tmpDiv = element.ownerDocument.createElement("DIV");
			tmpDiv.appendChild(elementCopy);
			return tmpDiv.innerHTML;		
		}
	},
	
	setVisible : function(e, value) 
	{
		if (!e) return;

		if (value != $telerik.getVisible(e)) {
	        
			if (value) {
				if (e.style.removeAttribute) {
					e.style.removeAttribute("display");
				} else {
				   e.style.removeProperty("display");
				}
			}
			else {
				e.style.display = 'none';
			}
	        
			e.style.visibility = value ? 'visible' : 'hidden';
		}
	},
	
	getVisible : function(e) 
	{
		if (!e) return false;

		return (("none" != $telerik.getCurrentStyle(e, "display")) &&
        ("hidden" != $telerik.getCurrentStyle(e, "visibility")));
	},
	
	getViewPortSize : function()
	{
		var width = 0;
		var height = 0;

		var canvas = document.body;

		if (!$telerik.quirksMode && !$telerik.isSafari)
		{
			canvas = document.documentElement;
		}

		if (window.innerWidth)
		{
			width = window.innerWidth;
			height = window.innerHeight;
		}
		else
		{
			width = canvas.clientWidth;
			height = canvas.clientHeight;
		}

		width += canvas.scrollLeft;
		height += canvas.scrollTop;

		return { width : width - 6, height : height - 6 };
	},
	
	elementOverflowsTop : function (element)
	{
		return $telerik.getLocation(element).y < 0;
	}, 

	elementOverflowsLeft : function (element)
	{
		return $telerik.getLocation(element).x < 0;
	},

	elementOverflowsBottom : function (screenSize, element)
	{
		var bottomEdge = $telerik.getLocation(element).y + element.offsetHeight;
		return bottomEdge > screenSize.height;
	},

	elementOverflowsRight : function (screenSize, element)
	{
		var rightEdge = $telerik.getLocation(element).x + element.offsetWidth;
		return rightEdge > screenSize.width;
	},

	getDocumentRelativeCursorPosition : function(e)
	{
		var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
		var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
		var left = e.clientX + scrollLeft;
		var top = e.clientY + scrollTop;
		return {left:left, top:top};
	},
	
//	//Lini: this code is not needed anymore. It will be removed for the Q1 2008 release.
//	makeCompatible : function(type)
//	{
//		/// <exclude />
//		/// <summary>
//		///		Doubles the get_propertyName, set_propertyName, add_event, remove_event
//		///		methods with get_PropertyName, set_PropertyName, etc. ones, to save troubles for
//		///		users already having client-side code with the mistaken client-side convention.
//		///
//		///     Doubles the methodName(...) with MethodName(...) member to save troubles for
//	    ///		users already having client-side code with the mistaken client-side convention.
//		/// </summary>

//		var proto = type.prototype;
//		for (var memberName in proto)
//		{
//			if (/([gs]et|add|remove|raise)_[a-z].*/.test(memberName))
//			{
//				var propNameStart = RegExp.$1.length + 1;
//				var oldPropName = memberName.substr(0, propNameStart) + memberName.charAt(propNameStart).toUpperCase() + memberName.substr(propNameStart + 1);
//				proto[oldPropName] = proto[memberName];
//			}
//			else if (/^[a-z][a-zA-Z]+$/.test(memberName) && 
//		             proto.hasOwnProperty(memberName) &&
//		             typeof(proto[memberName]) == "function" && 
//		             memberName != "initialize" &&
//		             memberName != "dispose")
//		    {
//		        var oldMethodName = memberName.charAt(0).toUpperCase() + memberName.substr(1);
//		        proto[oldMethodName] = proto[memberName];		    
//		    }
//		}
//	},
	
	getFirstChildByTagName : function (element, tagName, index)
	{
		if (!element || !element.childNodes)
		{
			return null;
		}
		
		var currentNode = element.childNodes[index] || element.firstChild;
		
		while (currentNode)
		{
			if (currentNode.nodeType == 1 && currentNode.tagName.toLowerCase() == tagName)
				return currentNode;
			
			currentNode = currentNode.nextSibling;
		}
	
		return null;
	},

	getChildByClassName : function(element, className, index)
	{
		var currentNode = element.childNodes[index] || element.firstChild;
		while (currentNode)
		{
			if (currentNode.nodeType == 1 && currentNode.className.indexOf(className) > -1)
				return currentNode;
			currentNode = currentNode.nextSibling;
		}
		return null;
	},

	getChildrenByTagName : function (element, tagName)
	{
		var children = new Array();
		var childNodes = element.childNodes;
		for (var i = 0, length = childNodes.length; i < length; i++)
		{
			var child = childNodes[i];
			if (child.nodeType == 1 && child.tagName.toLowerCase() == tagName)
				Array.add(children, child);
		}
		return children;
	},
	
	getChildrenByClassName : function (element, className)
	{
		var children = new Array();
		var childNodes = element.childNodes;
		for (var i = 0, length = childNodes.length; i < length; i++)
		{
			var child = childNodes[i];
			if (child.nodeType == 1 && child.className.indexOf(className) > -1)
				Array.add(children, child);
		}
		return children;
	}
}

$telerik.isIE = Sys.Browser.agent == Sys.Browser.InternetExplorer;
$telerik.isIE7 = $telerik.isIE && Sys.Browser.version == 7;
$telerik.isIE6 = $telerik.isIE && Sys.Browser.version < 7;
$telerik.isOpera = Sys.Browser.agent == Sys.Browser.Opera;
$telerik.isSafari = Sys.Browser.agent == Sys.Browser.Safari;
$telerik.isSafari3 = $telerik.isSafari && Sys.Browser.version > 500;
$telerik.isSafari2 = $telerik.isSafari && Sys.Browser.version <= 500;
$telerik.isFirefox = Sys.Browser.agent == Sys.Browser.Firefox;
$telerik.quirksMode = $telerik.isIE && document.compatMode != "CSS1Compat";
$telerik.standardsMode = !$telerik.quirksMode;

//Initialize the thickness of borders based on their style
$telerik._borderThickness();

Telerik.Web.UI.Orientation = function() {
    /// <summary>
    /// The Telerik.Web.UI.Orientation enumeration is used to specify 
    /// the orientation of a given asset
    /// </summary>
    /// <field name="Horizontal" type="Number" integer="true"/>
    /// <field name="Vertical" type="Number" integer="true"/>
    throw Error.invalidOperation();
}
Telerik.Web.UI.Orientation.prototype = {
    Horizontal : 0,
    Vertical : 1
} 
Telerik.Web.UI.Orientation.registerEnum('Telerik.Web.UI.Orientation', false);

Telerik.Web.UI.RadWebControl = function(element) 
{
    Telerik.Web.UI.RadWebControl.initializeBase(this, [element]);
    
    this._clientStateFieldID = null;
}

Telerik.Web.UI.RadWebControl.prototype = 
{
    initialize: function() 
    {
        Telerik.Web.UI.RadWebControl.callBaseMethod(this, 'initialize');
        
        $telerik.registerControl(this);
        
        if(!this.get_clientStateFieldID()) return;
        
        var input = $get(this.get_clientStateFieldID());    
        
        if(!input) return;
        
        input.setAttribute('autocomplete', 'off');
    },
    
    dispose: function() 
    {
        $telerik.unregisterControl(this);
        
        Telerik.Web.UI.RadWebControl.callBaseMethod(this, 'dispose');
    },
    
    raiseEvent : function(eventName, eventArgs) {
        /// <summary>
        /// Raise the event
        /// </summary>
        /// <param name="eventName" type="String" mayBeNull="false">
        /// Name of the event to be raised
        /// </param>
        /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="true">
        /// Event arguments for the given event
        /// </param>
        /// <returns />

		var handler = this.get_events().getHandler(eventName);
		if (handler) {
			if (!eventArgs) {
				eventArgs = Sys.EventArgs.Empty;
			}
			handler(this, eventArgs);
        }
    },
    
    updateClientState: function()
    {
        /// <summary>
        /// Call this function to update the client state hidden field.
        /// Use this function with caution, because it is resource hungry.
        /// </summary>
		this.set_clientState(this.saveClientState());
    },
    
    saveClientState: function()
    {
        /// <summary>
        /// This function should return the serialized client state of the control.
        /// </summary>
        /// <example>
		/// saveClientState: function()
		/// {
		///		var state = 
		///		{
		///			Collapsed	: this.get_collapsed(),
		///			Width		: this.get_width(),
		///			Height		: this.get_height()
		///		};
		///		return Sys.Serialization.JavaScriptSerializer.serialize(state);
		/// }
        /// </example>
         return null;
    },
    
    get_clientStateFieldID : function() 
    {
        /// <value type="String">
        /// ID of the hidden field used to store the client state
        /// </value>
        return this._clientStateFieldID;
    },
    set_clientStateFieldID : function(value) 
    {
        if (this._clientStateFieldID != value) 
        {
            this._clientStateFieldID = value;
            this.raisePropertyChanged('ClientStateFieldID');
        }
    },

    get_clientState : function() {
        /// <value type="String">
        /// Client state
        /// </value>
        if (this._clientStateFieldID) 
        {
            var input = document.getElementById(this._clientStateFieldID);
            if (input) 
            {
                return input.value;
            }
        }
        return null;
    },
    set_clientState : function(value) 
    {
        if (this._clientStateFieldID) 
        {
            var input = document.getElementById(this._clientStateFieldID);
            if (input) 
            {
                input.value = value;
            }
        }
    },
    
    _getChildElement : function(id)
	{
		return $get(this.get_id() + "_" + id);
	},
	
	_findChildControl : function(id)
	{
		return $find(this.get_id() + "_" + id);
	}
}

Telerik.Web.UI.RadWebControl.registerClass('Telerik.Web.UI.RadWebControl', Sys.UI.Control);

Telerik.Web.Timer = function() {
    Telerik.Web.Timer.initializeBase(this);
    
    this._interval = 1000;
    this._enabled = false;
    this._timer = null;
    
    this._timerCallbackDelegate = Function.createDelegate(this, this._timerCallback);
}

Telerik.Web.Timer.prototype = {
    get_interval: function() {
        
        return this._interval;
    },
    set_interval: function(value) {
        
        if (this._interval !== value) {
            this._interval = value;
            this.raisePropertyChanged('interval');
            
            if (!this.get_isUpdating() && (this._timer !== null)) {
                this._stopTimer();
                this._startTimer();
            }
        }
    },
    
    get_enabled: function() {
        
        return this._enabled;
    },
    set_enabled: function(value) {
        
        if (value !== this.get_enabled()) {
            this._enabled = value;
            this.raisePropertyChanged('enabled');
            if (!this.get_isUpdating()) {
                if (value) {
                    this._startTimer();
                }
                else {
                    this._stopTimer();
                }
            }
        }
    },

    
    add_tick: function(handler) {
        this.get_events().addHandler("tick", handler);
    },

    remove_tick: function(handler) {
        this.get_events().removeHandler("tick", handler);
    },

    dispose: function() {
        this.set_enabled(false);
        this._stopTimer();
        
        Telerik.Web.Timer.callBaseMethod(this, 'dispose');
    },
    
    updated: function() {
        Telerik.Web.Timer.callBaseMethod(this, 'updated');

        if (this._enabled) {
            this._stopTimer();
            this._startTimer();
        }
    },

    _timerCallback: function() {
        var handler = this.get_events().getHandler("tick");
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    },

    _startTimer: function() {
        this._timer = window.setInterval(this._timerCallbackDelegate, this._interval);
    },

    _stopTimer: function() {
        window.clearInterval(this._timer);
        this._timer = null;
    }
}

Telerik.Web.Timer.registerClass('Telerik.Web.Timer', Sys.Component);

Telerik.Web.BoxSide = function() {
}
Telerik.Web.BoxSide.prototype = {
    Top : 0,
    Right : 1,
    Bottom : 2,
    Left : 3
}
Telerik.Web.BoxSide.registerEnum("Telerik.Web.BoxSide", false);

if (Sys.CultureInfo.prototype._getAbbrMonthIndex) {
    try {
        Sys.CultureInfo.prototype._getAbbrMonthIndex('');
    } catch(ex) {
        Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) {
            if (!this._upperAbbrMonths) {
                this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
            }
            return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
        }
        Sys.CultureInfo.CurrentCulture._getAbbrMonthIndex = Sys.CultureInfo.prototype._getAbbrMonthIndex;
        Sys.CultureInfo.InvariantCulture._getAbbrMonthIndex = Sys.CultureInfo.prototype._getAbbrMonthIndex;
    }
}

Type.registerNamespace("Telerik.Web.UI.Dialogs");

Telerik.Web.IParameterConsumer = function() {
}
Telerik.Web.IParameterConsumer.prototype = {
    clientInit: function(parameters) { throw Error.notImplemented(); }
}
Telerik.Web.IParameterConsumer.registerInterface('Telerik.Web.IParameterConsumer');

Telerik.Web.UI.Dialogs.CommonDialogScript = function()
{
}
Telerik.Web.UI.Dialogs.CommonDialogScript.get_windowReference = function()
{
	if (window.radWindow)
	{
		return window.radWindow;
	}
	if (window.frameElement && window.frameElement.radWindow)
	{
		return window.frameElement.radWindow;
	}
	return null;
};

Telerik.Web.UI.Dialogs.CommonDialogScript.registerClass('Telerik.Web.UI.Dialogs.CommonDialogScript', null);

Telerik.Web.UI.WebServiceLoaderEventArgs = function(context)
{
	Telerik.Web.UI.WebServiceLoaderEventArgs.initializeBase(this);
	this._context = context;
}

Telerik.Web.UI.WebServiceLoaderEventArgs.prototype =
{
	get_context : function ()
	{
		return this._context;
	}
}

Telerik.Web.UI.WebServiceLoaderEventArgs.registerClass('Telerik.Web.UI.WebServiceLoaderEventArgs', Sys.EventArgs);


// ---------- WebServiceLoaderSuccessEventArgs Class ----------
Telerik.Web.UI.WebServiceLoaderSuccessEventArgs = function(data, context)
{
	Telerik.Web.UI.WebServiceLoaderSuccessEventArgs.initializeBase(this, [context]);
	this._data = data;
}

Telerik.Web.UI.WebServiceLoaderSuccessEventArgs.prototype =
{
	get_data : function ()
	{
		return this._data;
	}	
}

Telerik.Web.UI.WebServiceLoaderSuccessEventArgs.registerClass('Telerik.Web.UI.WebServiceLoaderSuccessEventArgs', Telerik.Web.UI.WebServiceLoaderEventArgs);


// ---------- WebServiceLoaderErrorEventArgs Class ----------
Telerik.Web.UI.WebServiceLoaderErrorEventArgs = function(message, context)
{
	Telerik.Web.UI.WebServiceLoaderErrorEventArgs.initializeBase(this, [context]);
	this._message = message;
}

Telerik.Web.UI.WebServiceLoaderErrorEventArgs.prototype =
{
	get_message : function ()
	{
		return this._message;
	}
}

Telerik.Web.UI.WebServiceLoaderErrorEventArgs.registerClass('Telerik.Web.UI.WebServiceLoaderErrorEventArgs', Telerik.Web.UI.WebServiceLoaderEventArgs);


// ---------- WebServiceLoader Class ----------
Telerik.Web.UI.WebServiceLoader = function(webServiceSettings)
{
	this._webServiceSettings = webServiceSettings;
	this._events = null;
	this._currentWebRequest = null;
	this._onWebServiceSuccessDelegate = Function.createDelegate(this, this._onWebServiceSuccess);
	this._onWebServiceErrorDelegate = Function.createDelegate(this, this._onWebServiceError);
}

Telerik.Web.UI.WebServiceLoader.prototype =
{
	// Public properties
	get_webServiceSettings : function ()
	{
		return this._webServiceSettings;
	},
	
	get_events: function ()
	{
		if (!this._events)
		{
			this._events = new Sys.EventHandlerList();
		}
		
		return this._events;
	},
	
	
	// Public methods
	loadData : function (params, context)
	{
		var webServiceSettings = this.get_webServiceSettings();
		
		if (webServiceSettings.get_isEmpty())
		{
			Error.invalidOperation("Please, specify valid web service and method.");
			return;
		}

		var webServicePath = webServiceSettings.get_path();
		var webMethod = webServiceSettings.get_method();
		
		this._raiseEvent("loadingStarted", new Telerik.Web.UI.WebServiceLoaderEventArgs(context));

		this._currentWebRequest =	Sys.Net.WebServiceProxy.invoke(webServicePath, webMethod, false, params,
										this._onWebServiceSuccessDelegate, this._onWebServiceErrorDelegate, context);
	},
	
	
	// Events
	add_loadingStarted : function(handler)
	{
		this.get_events().addHandler("loadingStarted", handler);
	},

	add_loadingError : function(handler)
	{
		this.get_events().addHandler("loadingError", handler);
	},

	add_loadingSuccess : function(handler)
	{
		this.get_events().addHandler("loadingSuccess", handler);
	},
	
	
	// Private methods	
	_onWebServiceSuccess : function (data, context)
	{
		var successEventArgs = new Telerik.Web.UI.WebServiceLoaderSuccessEventArgs(data, context);
		this._raiseEvent("loadingSuccess", successEventArgs);
	},
	
	_onWebServiceError : function (error, context)
	{	
		var errorEventArgs = new Telerik.Web.UI.WebServiceLoaderErrorEventArgs(error.get_message(), context);
		this._raiseEvent("loadingError", errorEventArgs);
	},

	_raiseEvent : function (eventName, eventArgs)
	{
		var handler = this.get_events().getHandler(eventName);        

		if (handler)
		{
			if (!eventArgs)
			{
				eventArgs = Sys.EventArgs.Empty;
			}

			handler(this, eventArgs);
		}
	}
}

Telerik.Web.UI.WebServiceLoader.registerClass('Telerik.Web.UI.WebServiceLoader');

Telerik.Web.UI.WebServiceSettings = function(serializedWebServiceSettings)
{
	this._path = null;
	this._method = null;
	
	//Add a check for the parameter existance
	if (!serializedWebServiceSettings) serializedWebServiceSettings = {};
	
	if (typeof(serializedWebServiceSettings.path) != "undefined")
	{
		this._path = serializedWebServiceSettings.path;
	}
	
	if (typeof(serializedWebServiceSettings.method) != "undefined")
	{
		this._method = serializedWebServiceSettings.method;
	}
}

Telerik.Web.UI.WebServiceSettings.prototype =
{
	get_path : function ()
	{
		return this._path;
	},
	
	set_path : function(value)
	{
		this._path = value;
	},

	get_method : function ()
	{
		return this._method;
	},
	
	set_method : function(value)
	{
		this._method = value;
	},
	
	get_isEmpty : function ()
	{
		/// <value type="Boolean">
		///		A value indicating wether the web service settings contain
		///		a non-null and non-empty service path and method.
		/// </value>
		var path = this.get_path();
		var method = this.get_method();
		
		return (!(path && method))
	}
}

Telerik.Web.UI.WebServiceSettings.registerClass('Telerik.Web.UI.WebServiceSettings');

/* END Telerik.Web.UI.Common.Core.js */
/* START Telerik.Web.UI.Common.Popup.ResizeExtender.js */
Type.registerNamespace('Telerik.Web');
Type.registerNamespace('Telerik.Web.UI'); 

Telerik.Web.UI.ResizeExtender = function(jsOwner, element, resizeHandles, tableElement, doc)//NEW: Allow for external document
{     
    /// <summary>
    /// Implements resize functionality for an element. The three arguments are as follows:
    /// - javascript object, which should [optionally] implement onResizeStart, onResize, onResizeEnd methods
    /// - the element that gets resized
    /// - a hashtable (object) of html elements that serve as handles for the resize directions
    ///    resizeHandles =     
    ///        n: elem1,
    ///        ne: elem2,
    ///        e: elem3,
    ///        se: elem4,
    ///        s: elem5,
    ///        sw: elem6,
    ///        w: elem7,
    ///        nw: [elem8, elem9, elem10]
    ///        move : [] //NEW!
    ///    };    
    /// </summary>               
    this._document = doc ? doc : document;
    this._documentMouseMoveDelegate = null;
    this._documentMouseUpDelegate = null;        
    this._element = null;
    this._tableElement = null;
    this._enabled = true;
    this._jsOwner = null;
    this._saveDelegates = {};
    this.makeResizable(jsOwner, element, resizeHandles, tableElement);        
}

Telerik.Web.UI.ResizeExtender.prototype = {    
            
    dispose : function()
    {
       /// <summary>
       /// Detaches and disposes resize eventhandlers
       /// </summary>        
       this._attachDocumentHandlers(false);
       this._configureHandleElements(false);
       this._jsOwner = null;
    },
    
    enable : function(bEnable)
    {  
       /// <summary>
       /// Enables or disables the resizing
       /// </summary>              
       this._enabled = bEnable;        
    },
    
    makeResizable : function(jsOwner, oElement, resizeFlags, tableElement)
    {   
        /// <summary>
        /// Configures an element to be resizable [see class declaration above for extra information on parameters]
        /// </summary>       
        if (!oElement) return;
                
        if (this._element)
        {
            alert("Element " + oElement.getAttribute("id") + " cannot be made resizable, as the resizeExtender already has the element " 
                  + this._element.getAttribute("id") + " associated with it. You must create a new extender resizer object");
            return;
        };
        
        this._jsOwner = jsOwner;        
        this._element = oElement;
        this._tableElement = tableElement;
        this._resizeHandles = resizeFlags;
               
        //Set other properties          
        this._startX = 0;
        this._startY = 0;
        this._cancelResize = true;


//NEW: Do not attach handlers here - attach them in last possible moment                                                                                                             
//        this._attachDocumentHandlers(true);               
        this._configureHandleElements(true);                                            
    },
    
    //==========================================================================================================//    
                        
    //NEW METHOD : Move support
    _raiseDragEvent : function(eventName, ev)
    {        
        if (this._jsOwner && this._jsOwner["on" + eventName])
        {                        
            //Let the method return a value whether to continue the operation                        
            return this._jsOwner["on" + eventName](ev);
        }                
        return true;
    },
    
  
    //Raises events: Argument values can be ResizeStart, Resize, ResizeEnd
    //Calls  methods onResizeStart, onResize, onResizeEnd
    _raiseEvent : function(eventName, ev)
    {        
        if (this._jsOwner && this._jsOwner["on" + eventName])
        {
            //Create resize object
            if (!ev)
            {
                ev = new Sys.EventArgs();
            }
            else if (eventName == "Resize") 
            {
                ev = this._resizeDir;                            
            } 
            else if (eventName == "Resizing")
            {
                //Create a delta - the ev has the proposed changes only                
                ev = this._getProposedBounds(ev);                
            }
                 
            //Let the method return a value whether to continue the operation                        
            return this._jsOwner["on" + eventName](ev);
        }                
        return true;
    },           
    
    _getProposedBounds : function(b1) 
    {        
        var b2 = $telerik.getBounds(this._element);            
        
        return { x: b1.x || b2.x, 
                 y: b1.y || b2.y,
                 width : b1.width || b2.width,
                 height : b1.height || b2.height
               };
    },
    
        
    _resize: function(e)
    {            
       if (!this._enabled || this._cancelResize) return false;
                                                                                
        var nWidth = 0;
        var nHeight = 0;
        var nLeft = 0;
        var nTop = 0;        
        var bounds = this._originalBounds;
        
        //NEW: Move            
        var isMoving = this._resizeDir.move;

        if (isMoving)                                   
        {
            nLeft = bounds.x + (e.clientX - this._startX);
            nTop = bounds.y + (e.clientY - this._startY);
        }
        else
        {                                        
            if (this._resizeDir.east) 
            { 
                nWidth = bounds.width + (e.clientX - this._startX);
            }
            else if (this._resizeDir.west)
            {                
                nLeft = e.clientX;
                nWidth = bounds.width - (e.clientX - this._startX);
            }
                                                                       
            if (this._resizeDir.south) 
            { 
                nHeight = bounds.height + (e.clientY - this._startY);
            }
            else if (this._resizeDir.north)
            {
                nTop = e.clientY;
                nHeight = bounds.height - (e.clientY - this._startY);
            } 
        }

        //Take care whether parent is relatively positioned - we will need to calculate its offset as well to set proper position
        if (this._offsetLocation)
        {    
            nLeft -= this._offsetLocation.x;
            nTop -= this._offsetLocation.y;
        }
                        
        //NEW: These coords can be modifed from within the event handler so - we use this object later in the code        
        var newBounds = new Sys.UI.Bounds(nLeft, nTop, nWidth, nHeight);        

        //NEW: Add _onDrag event
        //To control the process, raise event with proposed new location and/or size
        var result = isMoving ? this._raiseDragEvent("Drag", newBounds) : this._raiseEvent("Resizing", newBounds);
        
        if (false == result)
        {
            //Return true, rather than false, because we indicate to the caller mousemove method that there is currently resizing operation going on.
            //If false is returned, the mousemove will not cancel the event and will propagate it up to the browser! 
            return true;
        }
        
        
        //NEW: Always set value when moving - this will allow it to go out if the screen bounds if need be        
        if (isMoving || newBounds.x > 0) this._element.style.left = newBounds.x  + 'px';                       
                 
        //NEW: Always set value when moving - this will allow it to go out if the screen bounds if need be
        if (isMoving || newBounds.y > 0)
        {
            this._element.style.top = newBounds.y  + 'px';                       
        }
            
        //Change the size of the element
        if (newBounds.width > 0)
        {
             this._element.style.width = newBounds.width + 'px'; 
        }
        
        if (newBounds.height > 0)
        {
            this._element.style.height = newBounds.height + 'px';              
        }
        
        //Update the size of the inner [window/dock/anything] table (due to IE problems, but is not needed when moving as size does not change)
        if (!isMoving) this._updateInnerTableSize();   
    
        return true;
    },
    
    //Called when the mousedown event is fired on a border/corner stores the coordinates of the mouse pointer
    _storeStartCoords: function(e)
    {        
        if (!this._enabled) return;
    
        this._cancelResize = false;
        this._startX = e.clientX;
        this._startY = e.clientY;
        
        var elemBounds = $telerik.getBounds(this._element);       
        
        //Store original dimensions
        this._originalBounds = elemBounds;
        
        //Store parent offset if it is a relatively positioned element
        var isRelative = ("relative" == $telerik.getCurrentStyle(this._element.parentNode, 'position'));          
        this._offsetLocation = (isRelative ? $telerik.getLocation(this._element.parentNode) : null);
                                                                        
        var targetElement = e.target ? e.target : e.srcElement;//raw event!
        
        //Bug in Safari browser
        if (targetElement && targetElement.type == 3)
        {
           targetElement = targetElement.parentNode;
        }
        
        //Determine current resize type
        this._resizeType = $telerik.getCurrentStyle(targetElement, 'cursor');            
        
        //Set resize properties
        this._resizeDir = 
        {                             
            north : this._resizeType.match(/n.?-/) ? 1 : 0,
            east : this._resizeType.match(/e-/) ? 1 : 0,
            south : this._resizeType.match(/s.?-/) ? 1 : 0,
            west : this._resizeType.match(/w-/) ? 1 : 0,
            move : this._resizeType.match(/move/) ? 1 : 0
        };          
                          
        //NEW: Move support
        if (this._resizeDir.move)
        {
            //If a window is pinned it should not be dragged
            var continueDrag = this._raiseDragEvent("DragStart"); 
            this._cancelResize = (continueDrag == false);//if continue drag is false stop resizing
        }
        else this._raiseEvent("ResizeStart");                 
        
        
        //DO those only if resize or drag will actually start!
        if (!this._cancelResize)
        {        
            this._clearSelection();         
            this._setIframesVisible(false); 
            
            
//NEW - Reduce number of eventhandlers
//Detach and reatach document handlers
this._attachDocumentHandlers(false);
this._attachDocumentHandlers(true);
            
        }
    },

   
    //==========================================================================================================//
     _updateInnerTableSize : function() 	
    {                        
        //IE HACK - table height problem in STRICT DOCTYPE when tables are involved - as is the case with rad window and rad editor
        var dir = this._resizeDir;   
        if (dir.south || dir.north)
        {        
            var nHeight = this._element.style.height;                                                                     
            var table = this._tableElement;            
            if (table)
            {
                table.style.height = nHeight;          
                this._fixIeHeight(table, nHeight);
            }
        }                           
    },
    
    
    _setIframesVisible : function(bVisible)
    {
        var windowFrames =  this._document.getElementsByTagName("IFRAME");
		for (var i = 0; i < windowFrames.length; i++)
		{			
			windowFrames[i].style.visibility = bVisible ? "" : "hidden";			
		}
    },
        
    _configureHandleElements : function(attachEvent)
    {                                            
        var cursorArray = [ 'nw','n','ne', 'w','e','sw','s','se', 'move'];
        
        for( var i = 0; i < cursorArray.length; i++)
        {                    
            var cResizeType = cursorArray[i];            
            var curElem = this._resizeHandles[cResizeType];                        
                                    
            if(curElem)
            {                          
                if (curElem instanceof Array)//There can be more than 1 element for a given resizeType
                { 
                    for( var j = 0; j < curElem.length; j++)
                    {
                        this._configureHandle("id" + i + "_" + j, attachEvent, curElem[j], cResizeType);
                    }              
                }
                else this._configureHandle("id" + i, attachEvent, curElem, cResizeType);
            }            
        }     
        
        //if disposing
        if (!attachEvent)              
        {
            this._saveDelegates = {};
        }
     },
          
     _configureHandle : function(uniqueID, attachEvent, curElem, cResizeType)
     {
                                
        if (attachEvent) 
        {            
            var mouseDelegate = Function.createDelegate(this, this._onHandleMouseDown);            
            $telerik.addExternalHandler(curElem, "mousedown", mouseDelegate); 
            
            this._saveDelegates[uniqueID] = {delegate: mouseDelegate, element: curElem};
            
            //If move
            var cursor = (cResizeType == "move" ? "move" : cResizeType + '-resize');            
            curElem.style.cursor = cursor;
        }
        else
        {
            //Detach the handlers on dispose
            //Maybe add extra check whether curElem == this._saveDelegates[uniqueID].element?                            
            $telerik.removeExternalHandler(curElem, 'mousedown', this._saveDelegates[uniqueID].delegate);            
            curElem.style.cursor = "";
        }
     },
                  
    _attachDocumentHandlers : function(attachEvent)
    {
        var targetElement =  this._document;
        
        if (true == attachEvent)
        {            
            this._documentMouseMoveDelegate = Function.createDelegate(this, this._onDocumentMouseMove);                                            
            $telerik.addExternalHandler(targetElement, "mousemove", this._documentMouseMoveDelegate); 
            
            this._documentMouseUpDelegate = Function.createDelegate(this, this._onDocumentMouseUp);                                            
            $telerik.addExternalHandler(targetElement, "mouseup", this._documentMouseUpDelegate);       
         }
         else
         {                                      
            if (this._documentMouseMoveDelegate) $telerik.removeExternalHandler(targetElement, 'mousemove', this._documentMouseMoveDelegate);                                   
            this._documentMouseMoveDelegate = null;
                        
            if(this._documentMouseUpDelegate) $telerik.removeExternalHandler(targetElement, 'mouseup', this._documentMouseUpDelegate);                                   
            this._documentMouseUpDelegate = null;
         }    
    },
            
    _onDocumentMouseMove : function(e)
    {
       var toCancel = this._resize(e);     
       //In FireFox the document.mousemove event is used to show tooltips, so it is not a good idea to cancel it when no resizing occurs
       if (toCancel) return $telerik.cancelRawEvent(e);       
    },
    
    _onDocumentMouseUp : function(e)
    {        
       //Avoid throwing event every time the mouse is up - test if resize was actually being conducted
       var toRaise = !this._cancelResize;        
       this._cancelResize = true;
       
       if (toRaise)
       {
            //Show all iframes on the page [which were visible]          
            this._clearSelection();
            this._setIframesVisible(true);                    
            
            //Raise event
            if (this._resizeDir && this._resizeDir.move)                                   
            {
               this._raiseDragEvent("DragEnd"); 
            }
            else this._raiseEvent("ResizeEnd"); 

//NEW - Detach document handlers when drag is over!
this._attachDocumentHandlers(false);            
       }
    },
    
    _onHandleMouseDown : function(e)
    {
       this._storeStartCoords(e);
       return $telerik.cancelRawEvent(e); 
    },
                                                    
    _clearSelection : function()
    {
        if ( this._document.selection &&  this._document.selection.empty)  this._document.selection.empty();
    },
    
        
     //TODO: Move to a common location. Used in several controls using tables. Fixes a size bug in IE in DOCTYPE strict mode
     _fixIeHeight : function(oElem, height)
    {    
		if ("CSS1Compat" == document.compatMode) 
		{								
			var difference = (oElem.offsetHeight - parseInt(height));
			if (difference > 0)
			{			
				var newHeight = (parseInt(oElem.style.height) - difference);
				if (newHeight > 0) oElem.style.height = newHeight + "px";
			}
		}
	}
};

Telerik.Web.UI.ResizeExtender.registerClass('Telerik.Web.UI.ResizeExtender', null);
/* END Telerik.Web.UI.Common.Popup.ResizeExtender.js */
/* START Telerik.Web.UI.Common.Popup.DragDropScripts.js */
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.


///////////////////////////////////////////////////////////////////////////////
// IDropSource

Type.registerNamespace('Telerik.Web');

Telerik.Web.IDragSource = function() {
}
Telerik.Web.IDragSource.prototype = {
    // Type get_dragDataType()
    get_dragDataType: function() { throw Error.notImplemented(); },
    // Object getDragData(Context)
    getDragData: function() { throw Error.notImplemented(); },
    // DragMode get_dragMode()
    get_dragMode: function() { throw Error.notImplemented(); },
    // void onDragStart()
    onDragStart: function() { throw Error.notImplemented(); },
    // void onDrag()
    onDrag: function() { throw Error.notImplemented(); },
    // void onDragEnd(Cancelled)
    onDragEnd: function() { throw Error.notImplemented(); }
}
Telerik.Web.IDragSource.registerInterface('Telerik.Web.IDragSource');

///////////////////////////////////////////////////////////////////////////////
// IDropTarget
Telerik.Web.IDropTarget = function() {
}
Telerik.Web.IDropTarget.prototype = {
    get_dropTargetElement: function() { throw Error.notImplemented(); },
    // bool canDrop(DragMode, DataType, Data)
    canDrop: function() { throw Error.notImplemented(); },
    // void drop(DragMode, DataType, Data)
    drop: function() { throw Error.notImplemented(); },
    // void onDragEnterTarget(DragMode, DataType, Data)
    onDragEnterTarget: function() { throw Error.notImplemented(); },
    // void onDragLeaveTarget(DragMode, DataType, Data)
    onDragLeaveTarget: function() { throw Error.notImplemented(); },
    // void onDragInTarget(DragMode, DataType, Data)
    onDragInTarget: function() { throw Error.notImplemented(); }
}
Telerik.Web.IDropTarget.registerInterface('Telerik.Web.IDropTarget');

///////////////////////////////////////////////
// DragMode
//

Telerik.Web.DragMode = function() {
    throw Error.invalidOperation();
}
Telerik.Web.DragMode.prototype = {
    Copy: 0,
    Move: 1
}
Telerik.Web.DragMode.registerEnum('Telerik.Web.DragMode');

////////////////////////////////////////////////////////////////////
// DragDropEventArgs
//

Telerik.Web.DragDropEventArgs = function(dragMode, dragDataType, dragData) {
    this._dragMode = dragMode;
    this._dataType = dragDataType;
    this._data = dragData;
}
Telerik.Web.DragDropEventArgs.prototype = {
    get_dragMode: function() {
        return this._dragMode || null;
    },
    get_dragDataType: function() {
        return this._dataType || null;
    },
    get_dragData: function() {
        return this._data || null;
    }
}
Telerik.Web.DragDropEventArgs.registerClass('Telerik.Web.DragDropEventArgs');


Telerik.Web._DragDropManager = function() {
    this._instance = null;
    this._events =  null;
}
Telerik.Web._DragDropManager.prototype = {

    add_dragStart: function(handler) {
        this.get_events().addHandler('dragStart', handler);
    },
    remove_dragStart: function(handler) {
        this.get_events().removeHandler('dragStart', handler);
    },
    
    get_events: function() {
    // todo: doc comments. this one is commented out (two //) due to a bug with the preprocessor.
        // <value type="Sys.EventHandlerList">
        // </value>
        if (!this._events) {
            this._events = new Sys.EventHandlerList();
        }
        return this._events;
    },
    
    add_dragStop: function(handler) {
        this.get_events().addHandler('dragStop', handler);
    },
    remove_dragStop: function(handler) {
        this.get_events().removeHandler('dragStop', handler);
    },
    
    _getInstance: function() {
        if (!this._instance) {
            if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
                this._instance = new Telerik.Web.IEDragDropManager();
            }
            else {
                this._instance = new Telerik.Web.GenericDragDropManager();
            }
            this._instance.initialize();
            this._instance.add_dragStart(Function.createDelegate(this, this._raiseDragStart));
            this._instance.add_dragStop(Function.createDelegate(this, this._raiseDragStop));
        }
        return this._instance;
    },
    
    startDragDrop: function(dragSource, dragVisual, context) {
        this._getInstance().startDragDrop(dragSource, dragVisual, context);
    },
    
    //ORIGINAL TOOLKIT SCRIPT CHANGE
    // We will hack this code in order to put the document drop target
    // on the end of the _dropTargets array. This will allow us to 
    // fall back to it every time a dock was dragged outside of a zone.
    registerDropTarget: function(target, append) {
        this._getInstance().registerDropTarget(target, append);
    },
    
    unregisterDropTarget: function(target) {
        this._getInstance().unregisterDropTarget(target);
    },
    
    dispose: function() {
        delete this._events;
        Sys.Application.unregisterDisposableObject(this);
        Sys.Application.removeComponent(this);
    },
    
    _raiseDragStart: function(sender, eventArgs) {
        var handler = this.get_events().getHandler('dragStart');
        if(handler) {
            handler(this, eventArgs);
        }
    },
    
    _raiseDragStop: function(sender, eventArgs) {
        var handler = this.get_events().getHandler('dragStop');
        if(handler) {
            handler(this, eventArgs);
        }
    }
}
Telerik.Web._DragDropManager.registerClass('Telerik.Web._DragDropManager');
Telerik.Web.DragDropManager = new Telerik.Web._DragDropManager();


Telerik.Web.IEDragDropManager = function() {
    Telerik.Web.IEDragDropManager.initializeBase(this);
    
    this._dropTargets = null;
    // Radius of the cursor used to determine what drop target we 
    // are hovering. Anything below the cursor's zone may be a 
    // potential drop target.
    this._radius = 10;
    this._activeDragVisual = null;
    this._activeContext = null;
    this._activeDragSource = null;
    this._underlyingTarget = null;
    this._oldOffset = null;
    this._potentialTarget = null;
    this._isDragging = false;
    this._mouseUpHandler = null;
    this._documentMouseMoveHandler = null;
    this._documentDragOverHandler = null;
    this._dragStartHandler = null;
    this._mouseMoveHandler = null;
    this._dragEnterHandler = null;
    this._dragLeaveHandler = null;
    this._dragOverHandler = null;
    this._dropHandler = null;
    this._areEventsWired = false;
}
Telerik.Web.IEDragDropManager.prototype = {

    add_dragStart : function(handler) {
        this.get_events().addHandler("dragStart", handler);
    },
    
    remove_dragStart : function(handler) {
        this.get_events().removeHandler("dragStart", handler);
    },
    
    add_dragStop : function(handler) {
        this.get_events().addHandler("dragStop", handler);
    },
    
    remove_dragStop : function(handler) {
        this.get_events().removeHandler("dragStop", handler);
    },
    
    initialize : function() {
        Telerik.Web.IEDragDropManager.callBaseMethod(this, 'initialize');
        this._mouseUpHandler = Function.createDelegate(this, this._onMouseUp);
        this._documentMouseMoveHandler = Function.createDelegate(this, this._onDocumentMouseMove);
        this._documentDragOverHandler = Function.createDelegate(this, this._onDocumentDragOver);
        this._dragStartHandler = Function.createDelegate(this, this._onDragStart);
        this._mouseMoveHandler = Function.createDelegate(this, this._onMouseMove);
        this._dragEnterHandler = Function.createDelegate(this, this._onDragEnter);
        this._dragLeaveHandler = Function.createDelegate(this, this._onDragLeave);
        this._dragOverHandler = Function.createDelegate(this, this._onDragOver);
        this._dropHandler = Function.createDelegate(this, this._onDrop);
    },
    
    
    dispose : function() {
        if(this._dropTargets) {
            for (var i = 0; i < this._dropTargets; i++) {
                this.unregisterDropTarget(this._dropTargets[i]);
            }
            this._dropTargets = null;
        }
        
        Telerik.Web.IEDragDropManager.callBaseMethod(this, 'dispose');
    },
    

    startDragDrop : function(dragSource, dragVisual, context) {
        var ev = window._event;
        
        // Don't allow drag and drop if there is another active drag operation going on.
        if (this._isDragging) {
            return;
        }
        
        this._underlyingTarget = null;
        this._activeDragSource = dragSource;
        this._activeDragVisual = dragVisual;
        this._activeContext = context;
        
        var mousePosition = { x: ev.clientX, y: ev.clientY };
        
        // By default we use absolute positioning, unless a different type 
        // of positioning is set explicitly.
        dragVisual.originalPosition = dragVisual.style.position;
		//ORIGINAL TOOLKIT SCRIPT CHANGE:
		// 1) CommonScripts.getLocation did not return the proper location when in quirks mode;
		// 2) The location is calculated improperly when having float:left objects in a
		//     parent element and position is set to "absolute" before the location calculation
        var location = $telerik.getLocation(dragVisual);

        dragVisual.style.position = "absolute";
        
        document._lastPosition = mousePosition;
        dragVisual.startingPoint = mousePosition;
        var scrollOffset = this.getScrollOffset(dragVisual, /* recursive */ true);
        
        dragVisual.startingPoint = this.addPoints(dragVisual.startingPoint, scrollOffset);
        if (dragVisual.style.position == "absolute") {
		//ORIGINAL TOOLKIT SCRIPT CHANGE:
		// The location is calculated improperly when having float:left objects in a
		//  parent element and position is set to "absolute" before the location calculation
            dragVisual.startingPoint = this.subtractPoints(dragVisual.startingPoint, location);
        }
        else {
            var left = parseInt(dragVisual.style.left);
            var top = parseInt(dragVisual.style.top);
            if (isNaN(left)) left = "0";
            if (isNaN(top)) top = "0";
            
            dragVisual.startingPoint = this.subtractPoints(dragVisual.startingPoint, { x: left, y: top });
        }
        
        // Monitor DOM changes.
        this._prepareForDomChanges();
        dragSource.onDragStart();
        var eventArgs = new Telerik.Web.DragDropEventArgs(
            dragSource.get_dragMode(),
            dragSource.get_dragDataType(),
            dragSource.getDragData(context));
        var handler = this.get_events().getHandler('dragStart');
        if(handler) handler(this,eventArgs);
        this._recoverFromDomChanges();
        
        //Detach any handlers that might still be attached - solves problems in case you try to drag an element outside of the 
        //browser in Mozilla and drop it there, after that move back to the browser window and really drop the element.
        this._unwireEvents();
        
        this._wireEvents();
        
        this._drag(/* isInitialDrag */ true);
    },
    
    
    _stopDragDrop : function(cancelled) {
        var ev = window._event;
        if (this._activeDragSource != null) {
            this._unwireEvents();
        
            if (!cancelled) {
                // The drag operation is cancelled if there 
                // is no drop target.
                cancelled = (this._underlyingTarget == null);
            }

            if (!cancelled && this._underlyingTarget != null) {
                this._underlyingTarget.drop(this._activeDragSource.get_dragMode(), this._activeDragSource.get_dragDataType(),
                    this._activeDragSource.getDragData(this._activeContext));
            }

            this._activeDragSource.onDragEnd(cancelled);
            var handler = this.get_events().getHandler('dragStop');
            if(handler) handler(this,Sys.EventArgs.Empty);
            
            this._activeDragVisual.style.position = this._activeDragVisual.originalPosition;

            this._activeDragSource = null;
            this._activeContext = null;
            this._activeDragVisual = null;
            this._isDragging = false;
            this._potentialTarget = null;
            ev.preventDefault();
        }
    },
    
    _drag : function(isInitialDrag) {
        var ev = window._event;
        var mousePosition = { x: ev.clientX, y: ev.clientY };
        
        // NOTE: We store the event object to be able to determine the current 
        // mouse position in Mozilla in other event handlers such as keydown.
        document._lastPosition = mousePosition;
        
        var scrollOffset = this.getScrollOffset(this._activeDragVisual, /* recursive */ true);
        var position = this.addPoints(this.subtractPoints(mousePosition, this._activeDragVisual.startingPoint), scrollOffset);
        
        // Check if the visual moved at all.
        if (!isInitialDrag && parseInt(this._activeDragVisual.style.left) == position.x && parseInt(this._activeDragVisual.style.top) == position.y) {
            return;
        }
        
        $telerik.setLocation(this._activeDragVisual, position);
        
        // Monitor DOM changes.
        this._prepareForDomChanges();
        this._activeDragSource.onDrag();
        this._recoverFromDomChanges();
        
        // Find a potential target.
        this._potentialTarget = this._findPotentialTarget(this._activeDragSource, this._activeDragVisual);
        
        var movedToOtherTarget = (this._potentialTarget != this._underlyingTarget || this._potentialTarget == null);
        // Check if we are leaving an underlying target.
        if (movedToOtherTarget && this._underlyingTarget != null) {
            this._leaveTarget(this._activeDragSource, this._underlyingTarget);
        }
        
        if (this._potentialTarget != null) {
            // Check if we are entering a new target.
            if (movedToOtherTarget) {
                this._underlyingTarget = this._potentialTarget;
                // Enter the new target.
                this._enterTarget(this._activeDragSource, this._underlyingTarget);
            }
            else {
                this._moveInTarget(this._activeDragSource, this._underlyingTarget);
            }
        }
        else {
            this._underlyingTarget = null;
        }
    },
    
    
    _wireEvents : function() {
        $addHandler(document, "mouseup", this._mouseUpHandler);
        $addHandler(document, "mousemove", this._documentMouseMoveHandler);
        $addHandler(document.body, "dragover", this._documentDragOverHandler);
        
        $addHandler(this._activeDragVisual, "dragstart", this._dragStartHandler);
        $addHandler(this._activeDragVisual, "dragend", this._mouseUpHandler);
        $addHandler(this._activeDragVisual, "drag", this._mouseMoveHandler);
        
        this._areEventsWired = true;
    },
    
    
    _unwireEvents : function() {
        if(!this._areEventsWired)
            return;
            
        $removeHandler(this._activeDragVisual, "drag", this._mouseMoveHandler);
        $removeHandler(this._activeDragVisual, "dragend", this._mouseUpHandler);
        $removeHandler(this._activeDragVisual, "dragstart", this._dragStartHandler);

        $removeHandler(document.body, "dragover", this._documentDragOverHandler);
        $removeHandler(document, "mousemove", this._documentMouseMoveHandler);
        $removeHandler(document, "mouseup", this._mouseUpHandler);
        this._areEventsWired = false;
    },
    
    
    registerDropTarget : function(dropTarget, append) {
        if (this._dropTargets == null) {
            this._dropTargets = [];
        }
        //ORIGINAL TOOLKIT SCRIPT CHANGE
        // We will hack this code in order to put the document drop target
        // on the end of the _dropTargets array. This will allow us to 
        // fall back to it every time a dock was dragged outside of a zone.
        if (append)
        {
			Array.add(this._dropTargets, dropTarget);
		}
		else
		{
			Array.insert(this._dropTargets, 0, dropTarget);
		}
        this._wireDropTargetEvents(dropTarget);
    },
    
    
    unregisterDropTarget : function(dropTarget) {
        this._unwireDropTargetEvents(dropTarget);
        if (this._dropTargets) {
            Array.remove(this._dropTargets, dropTarget);
        }
    },
    
    
    _wireDropTargetEvents : function(dropTarget) {
        var associatedElement = dropTarget.get_dropTargetElement();
        associatedElement._dropTarget = dropTarget;
        $addHandler(associatedElement, "dragenter",  this._dragEnterHandler);
        $addHandler(associatedElement, "dragleave",  this._dragLeaveHandler);
        $addHandler(associatedElement, "dragover", this._dragOverHandler);
        $addHandler(associatedElement, "drop", this._dropHandler);
    },
    
    
    _unwireDropTargetEvents : function(dropTarget) {
        var associatedElement = dropTarget.get_dropTargetElement();
        // make sure that the handlers are not removed twice
        if(associatedElement._dropTarget)
        {
            associatedElement._dropTarget = null;
            $removeHandler(associatedElement, "dragenter",  this._dragEnterHandler);
            $removeHandler(associatedElement, "dragleave",  this._dragLeaveHandler);
            $removeHandler(associatedElement, "dragover", this._dragOverHandler);
            $removeHandler(associatedElement, "drop", this._dropHandler);
        }
    },
    
    
    _onDragStart : function(ev) {
        window._event = ev;
        document.selection.empty();
        
        var dt = ev.dataTransfer;
        if(!dt && ev.rawEvent) dt = ev.rawEvent.dataTransfer;
        
        var dataType = this._activeDragSource.get_dragDataType().toLowerCase();
        var data = this._activeDragSource.getDragData(this._activeContext);
        
        if (data) {
            // TODO: How do we want to deal with 'non-compatible types'?
            if (dataType != "text" && dataType != "url") {
                dataType = "text";
                
                if (data.innerHTML != null) {
                    data = data.innerHTML;
                }
            }
            
            dt.effectAllowed = "move";
            dt.setData(dataType, data.toString());
        }
    },
    
    _onMouseUp : function(ev) {
        window._event = ev;
        this._stopDragDrop(false);
    },
    
    _onDocumentMouseMove : function(ev) {
        window._event = ev;
        this._dragDrop();
    },

    _onDocumentDragOver : function(ev) {
        window._event = ev;
        if(this._potentialTarget) ev.preventDefault();
        //ev.returnValue = (_potentialTarget == null);
    },
    
    _onMouseMove : function(ev) {
        window._event = ev;
        this._drag();
    },
    
    _onDragEnter : function(ev) {
        window._event = ev;
        if (this._isDragging) {
            ev.preventDefault();
            //ev.returnValue = false;
        }
        else {
            // An external object is dragged to the drop target.
            var dataObjects = Telerik.Web.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));
            for (var i = 0; i < dataObjects.length; i++) {
                this._dropTarget.onDragEnterTarget(Telerik.Web.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);
            }
        }
    },
    
    _onDragLeave : function(ev) {
        window._event = ev;
        if (this._isDragging) {
            ev.preventDefault();
            //ev.returnValue = false;
        }
        else {
            // An external object is dragged to the drop target.
            var dataObjects = Telerik.Web.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));
            for (var i = 0; i < dataObjects.length; i++) {
                this._dropTarget.onDragLeaveTarget(Telerik.Web.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);
            }
        }
    },
    
    _onDragOver : function(ev) {
        window._event = ev;
        if (this._isDragging) {
            ev.preventDefault();
            //ev.returnValue = false;
        }
        else {
            // An external object is dragged over the drop target.
            var dataObjects = Telerik.Web.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));
            for (var i = 0; i < dataObjects.length; i++) {
                this._dropTarget.onDragInTarget(Telerik.Web.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);
            }
        }
    },
    
    _onDrop : function(ev) {
        window._event = ev;
        if (!this._isDragging) {
            // An external object is dropped on the drop target.
            var dataObjects = Telerik.Web.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));
            for (var i = 0; i < dataObjects.length; i++) {
                this._dropTarget.drop(Telerik.Web.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);
            }
        }
        ev.preventDefault();
        //ev.returnValue = false;
    },
    
    _getDropTarget : function(element) {
        while (element) {
            if (element._dropTarget != null) {
                return element._dropTarget;
            }
            element = element.parentNode;
        }
        return null;
    },
    
    _dragDrop : function() {
        if (this._isDragging) {
            return;
        }
        
        this._isDragging = true;
        this._activeDragVisual.dragDrop();
        document.selection.empty();
    },
    
    _moveInTarget : function(dragSource, dropTarget) {
        // Monitor DOM changes.
        this._prepareForDomChanges();
        dropTarget.onDragInTarget(dragSource.get_dragMode(), dragSource.get_dragDataType(), dragSource.getDragData(this._activeContext));
        this._recoverFromDomChanges();
    },
    
    _enterTarget : function(dragSource, dropTarget) {
        // Monitor DOM changes.
        this._prepareForDomChanges();
        dropTarget.onDragEnterTarget(dragSource.get_dragMode(), dragSource.get_dragDataType(), dragSource.getDragData(this._activeContext));
        this._recoverFromDomChanges();
    },
    
    _leaveTarget : function(dragSource, dropTarget) {
        // Monitor DOM changes.
        this._prepareForDomChanges();
        dropTarget.onDragLeaveTarget(dragSource.get_dragMode(), dragSource.get_dragDataType(), dragSource.getDragData(this._activeContext));
        this._recoverFromDomChanges();
    },
    
    _findPotentialTarget : function(dragSource, dragVisual) {
        var ev = window._event;

        if (this._dropTargets == null) {
            return null;
        }
        
        var type = dragSource.get_dragDataType();
        var mode = dragSource.get_dragMode();
        var data = dragSource.getDragData(this._activeContext);

        // Get the current cursor location.
        var scrollOffset = this.getScrollOffset(document.body, /* recursive */ true);

        var x = ev.clientX + scrollOffset.x;
        var y = ev.clientY + scrollOffset.y;
        var cursorRect = { x: x - this._radius, y: y - this._radius, width: this._radius * 2, height: this._radius * 2 };
        
        // Find any targets near the current cursor location.
        var targetRect;
        for (var i = 0; i < this._dropTargets.length; i++) {
		//ORIGINAL TOOLKIT SCRIPT CHANGE:
		//CommonScripts.getBounds did not return proper bounds when in quirks mode:
            targetRect = $telerik.getBounds(this._dropTargets[i].get_dropTargetElement());
            if (this._overlaps(cursorRect, targetRect) && this._dropTargets[i].canDrop(mode, type, data)) {
                return this._dropTargets[i];
            }
        }
        
        return null;
    },
    
    _overlaps : function (r1, r2)
	{
		var xLeft = (r1.x >= r2.x && r1.x <= (r2.x + r2.width));
		var xRight = ((r1.x + r1.width) >= r2.x && (r1.x + r1.width) <= r2.x + r2.width);
		var xComplete = ((r1.x < r2.x) && ((r1.x + r1.width) > (r2.x + r2.width)));
    
		var yLeft = (r1.y >= r2.y && r1.y <= (r2.y + r2.height));
		var yRight = ((r1.y + r1.height) >= r2.y && (r1.y + r1.height) <= r2.y + r2.height);
		var yComplete = ((r1.y < r2.y) && ((r1.y + r1.height) > (r2.y + r2.height)));
		if ((xLeft || xRight || xComplete) && (yLeft || yRight || yComplete)) {
			return true;
		}
    
		return false;
	},
	
    _prepareForDomChanges : function() {
		//ORIGINAL TOOLKIT SCRIPT CHANGE:
		//CommonScripts.getLocation did not return the proper location when in quirks mode:
        this._oldOffset = $telerik.getLocation(this._activeDragVisual);
    },
    
    _recoverFromDomChanges : function() {
		//ORIGINAL TOOLKIT SCRIPT CHANGE:
		//CommonScripts.getLocation did not return the proper location when in quirks mode:
        var newOffset = $telerik.getLocation(this._activeDragVisual);
        if (this._oldOffset.x != newOffset.x || this._oldOffset.y != newOffset.y) {
            this._activeDragVisual.startingPoint = this.subtractPoints(this._activeDragVisual.startingPoint, this.subtractPoints(this._oldOffset, newOffset));
            scrollOffset = this.getScrollOffset(this._activeDragVisual, /* recursive */ true);
            var position = this.addPoints(this.subtractPoints(document._lastPosition, this._activeDragVisual.startingPoint), scrollOffset);
            $telerik.setLocation(this._activeDragVisual, position);
        }
    },
    
    addPoints : function(p1, p2) {
        return { x: p1.x + p2.x, y: p1.y + p2.y };
    },
    
    subtractPoints : function(p1, p2) {
        return { x: p1.x - p2.x, y: p1.y - p2.y };
    },
    
    // -- Drag and drop helper methods.
    getScrollOffset : function(element, recursive) {
        var left = element.scrollLeft;
        var top = element.scrollTop;
        if (recursive) {
            var parent = element.parentNode;
            while (parent != null && parent.scrollLeft != null) {
                left += parent.scrollLeft;
                top += parent.scrollTop;
                // Don't include anything below the body.
                if (parent == document.body && (left != 0 && top != 0))
                    break;
                parent = parent.parentNode;
            }
        }
        return { x: left, y: top };
    },
    
    getBrowserRectangle : function() {
        var width = window.innerWidth;
        var height = window.innerHeight;
        if (width == null) {
            width = document.body.clientWidth;
        }
        if (height == null) {
            height = document.body.clientHeight;
        }
        
        return { x: 0, y: 0, width: width, height: height };
    },
    
    getNextSibling : function(item) {
        for (item = item.nextSibling; item != null; item = item.nextSibling) {
            if (item.innerHTML != null) {
                return item;
            }
        }
        return null;
    },
    
    hasParent : function(element) {
        return (element.parentNode != null && element.parentNode.tagName != null);
    }
}
Telerik.Web.IEDragDropManager.registerClass('Telerik.Web.IEDragDropManager', Sys.Component);

Telerik.Web.IEDragDropManager._getDataObjectsForDropTarget = function(dropTarget) {
    if (dropTarget == null) {
        return [];
    }
    var ev = window._event;
    var dataObjects = [];
    var dataTypes = [ "URL", "Text" ];
    var data;
    for (var i = 0; i < dataTypes.length; i++) {
        var dt = ev.dataTransfer;
        if(!dt && ev.rawEvent) dt = ev.rawEvent.dataTransfer;
        data = dt.getData(dataTypes[i]);
        if (dropTarget.canDrop(Telerik.Web.DragMode.Copy, dataTypes[i], data)) {
            if (data) {
                Array.add(dataObjects, { type : dataTypes[i], value : data });
            }
        }
    }

    return dataObjects;
}


Telerik.Web.GenericDragDropManager = function() {
    Telerik.Web.GenericDragDropManager.initializeBase(this);
    
    this._dropTargets = null;
    // Radius of the cursor used to determine what drop target we 
    // are hovering. Anything below the cursor's zone may be a 
    // potential drop target.
    this._scrollEdgeConst = 40;
    this._scrollByConst = 10;
    this._scroller = null;
    this._scrollDeltaX = 0;
    this._scrollDeltaY = 0;
    this._activeDragVisual = null;
    this._activeContext = null;
    this._activeDragSource = null;
    this._oldOffset = null;
    this._potentialTarget = null;
    this._mouseUpHandler = null;
    this._mouseMoveHandler = null;
    this._keyPressHandler = null;
    this._scrollerTickHandler = null;
    this._areEventsWired = false;
}
Telerik.Web.GenericDragDropManager.prototype = {
   
    initialize : function() {
        Telerik.Web.GenericDragDropManager.callBaseMethod(this, "initialize");
        this._mouseUpHandler = Function.createDelegate(this, this._onMouseUp);
        this._mouseMoveHandler = Function.createDelegate(this, this._onMouseMove);
        this._keyPressHandler = Function.createDelegate(this, this._onKeyPress);
        this._scrollerTickHandler = Function.createDelegate(this, this._onScrollerTick);
        if (Sys.Browser.agent === Sys.Browser.Safari) {
            Telerik.Web.GenericDragDropManager.__loadSafariCompatLayer(this);
        }
        this._scroller = new Telerik.Web.Timer();
        this._scroller.set_interval(10);
        this._scroller.add_tick(this._scrollerTickHandler);
    },

    startDragDrop : function(dragSource, dragVisual, context) {
        this._activeDragSource = dragSource;
        this._activeDragVisual = dragVisual;
        this._activeContext = context;
        
        Telerik.Web.GenericDragDropManager.callBaseMethod(this, "startDragDrop", [dragSource, dragVisual, context]);
    },
    
    _stopDragDrop : function(cancelled) {
        this._scroller.set_enabled(false);
        
        Telerik.Web.GenericDragDropManager.callBaseMethod(this, "_stopDragDrop", [cancelled]);
    },
    
    _drag : function(isInitialDrag) {
        Telerik.Web.GenericDragDropManager.callBaseMethod(this, "_drag", [isInitialDrag]);
        
        this._autoScroll();
    },
    
    _wireEvents : function() {
        $addHandler(document, "mouseup", this._mouseUpHandler);
        $addHandler(document, "mousemove", this._mouseMoveHandler);
        $addHandler(document, "keypress", this._keyPressHandler);
        
        this._areEventsWired = true;
    },
    
    _unwireEvents : function() {
        if(!this._areEventsWired)
            return;
    
        $removeHandler(document, "keypress", this._keyPressHandler);
        $removeHandler(document, "mousemove", this._mouseMoveHandler);
        $removeHandler(document, "mouseup", this._mouseUpHandler);
        
        this._areEventsWired = false;
    },
    
    _wireDropTargetEvents : function(dropTarget) {
        //
    },
    
    _unwireDropTargetEvents : function(dropTarget) {
        //
    },
    
    _onMouseUp : function(e) {
        window._event = e;
        this._stopDragDrop(false);
    },
    
    _onMouseMove : function(e) {
        window._event = e;
        this._drag();
    },
    
    _onKeyPress : function(e) {
        window._event = e;
        // Escape.
        var k = e.keyCode ? e.keyCode : e.rawEvent.keyCode;
        if (k == 27) {
            this._stopDragDrop(/* cancel */ true);
        }
    },
    
    _autoScroll : function() {
        var ev = window._event;
        var browserRect = this.getBrowserRectangle();
        if (browserRect.width > 0) {
            this._scrollDeltaX = this._scrollDeltaY = 0;
            if (ev.clientX < browserRect.x + this._scrollEdgeConst) this._scrollDeltaX = -this._scrollByConst;
            else if (ev.clientX > browserRect.width - this._scrollEdgeConst) this._scrollDeltaX = this._scrollByConst;
            if (ev.clientY < browserRect.y + this._scrollEdgeConst) this._scrollDeltaY = -this._scrollByConst;
            else if (ev.clientY > browserRect.height - this._scrollEdgeConst) this._scrollDeltaY = this._scrollByConst;
            if (this._scrollDeltaX != 0 || this._scrollDeltaY != 0) {
                this._scroller.set_enabled(true);
            }
            else {
                this._scroller.set_enabled(false);
            }
        }
    },
    
    _onScrollerTick : function() {
        var oldLeft = document.body.scrollLeft;
        var oldTop = document.body.scrollTop;
        window.scrollBy(this._scrollDeltaX, this._scrollDeltaY);
        var newLeft = document.body.scrollLeft;
        var newTop = document.body.scrollTop;
        
        var dragVisual = this._activeDragVisual;
        var position = { x: parseInt(dragVisual.style.left) + (newLeft - oldLeft), y: parseInt(dragVisual.style.top) + (newTop - oldTop) };
        $telerik.setLocation(dragVisual, position);
    }
}
Telerik.Web.GenericDragDropManager.registerClass('Telerik.Web.GenericDragDropManager', Telerik.Web.IEDragDropManager);


if (Sys.Browser.agent === Sys.Browser.Safari) {
    Telerik.Web.GenericDragDropManager.__loadSafariCompatLayer = function(ddm) {
        ddm._getScrollOffset = ddm.getScrollOffset;

        ddm.getScrollOffset = function(element, recursive) {
            return { x: 0, y: 0 };
        }

        ddm._getBrowserRectangle = ddm.getBrowserRectangle;

        ddm.getBrowserRectangle = function() {
            var browserRect = ddm._getBrowserRectangle();
            
            var offset = ddm._getScrollOffset(document.body, true);
            return { x: browserRect.x + offset.x, y: browserRect.y + offset.y,
                width: browserRect.width + offset.x, height: browserRect.height + offset.y };
        }
    }
}

/* END Telerik.Web.UI.Common.Popup.DragDropScripts.js */
/* START Telerik.Web.UI.Common.Popup.ModalExtender.js */
Type.registerNamespace('Telerik.Web');
Type.registerNamespace('Telerik.Web.UI'); 

Telerik.Web.UI.ModalExtender = function(flElement)
{     
    /// <summary>
    /// Implements modality functionality for an element.   
    /// </summary>               
    this._windowResizeDelegate = null;
    this._windowScrollDelegate = null;   
    
    this._xCoordinate = -1;
    this._yCoordinate = -1;
    this._backgroundElement = null;
    this._foregroundElement = flElement;
                    
    this._saveTabIndexes = new Array();
    this._saveDesableSelect = new Array();
    this._tagWithTabIndex = new Array('A','AREA','BUTTON','INPUT','OBJECT','SELECT','TEXTAREA','IFRAME');        
}

Telerik.Web.UI.ModalExtender.prototype = {    
            
    dispose : function()
    {
       /// <summary>
       /// Detaches and disposes eventhandlers       
       this.hide();
       this._backgroundElement = null;
       this._foregroundElement = null;
    },
     
    show : function()
    {
        this._attachWindowHandlers(true);    
        //Append the modal overlay
        var elem = this._getModalOverlay();        
        this._foregroundElement.parentNode.appendChild(elem);
        
        //Set z-Index        
        elem.style.zIndex = $telerik.getCurrentStyle(this._foregroundElement, 'zIndex', this._foregroundElement.style.zIndex) - 1;// + 1;                
        
        //Make the overlay visible
        elem.style.display = '';                        
        
        //Disable TAB
        this._disableTab();
        
//Disable page scrolling        
//Disabling scrolling in Mozilla, causes page to jump. When jumping is compensated, it causes the page to flicker - which is not fixable             
//        this._storeBrowserPosition();        
//        this._enableScroll(false);//MOZ problem - disabling scrolling causes the page to scroll to top
//        this._restoreBrowserPosition();

        //Calculate the overlay size
        this._updatePageLayout();
        // On pages that don't need scrollbars, Firefox and Safari act like
        // one or both are present the first time the layout code runs which
        // obviously leads to display issues - run the layout code a second
        // time to work around this problem
        this._updatePageLayout();
    },
    
    _storeBrowserPosition : function()
    {	    
	    var oBody = document.body;
	    var oDoc = document.documentElement;	
	    this._browserTop  = oBody.scrollTop > oDoc.scrollTop ? oBody.scrollTop  : oDoc.scrollTop;	
	    this._browserLeft = oBody.scrollLeft > oDoc.scrollLeft ? oBody.scrollTop : oDoc.scrollLeft;	
    },

    _restoreBrowserPosition : function(left, top)
    {
	    try
	    {
	        if (null == left) left = this._browserLeft;
	        if (null == top) top = this._browserTop;
	        
		    var oBody = document.body;
		    var oDoc = document.documentElement;		    
		    oBody.scrollTop = top;
		    oBody.scrollLeft = left;
		    oDoc.scrollTop  = top;
		    oDoc.scrollLeft = left;
	    }
	    catch(ex){};
    },
    
    hide : function()
    {                
        this._backgroundElement.style.display = 'none';        
        this._restoreTab();
//Disabling scrolling in Mozilla, causes page to jump. When jumping is compensated, it causes the page to flicker - which is not fixable     
//        this._enableScroll(true);
        this._attachWindowHandlers(false);
    },     
        
    _enableScroll : function(enable)
    {    
        if (enable)
	    {		        
		    document.body.style.overflow = null != this._overflow ? this._overflow : '';		    
		    document.documentElement.style.overflow = null != this._documentOverflow ? this._documentOverflow : '';
		    
		    document.body.style.marginRight = '';
	    }
	    else
	    {		
	        this._overflow = document.body.style.overflow;	        	        	        
		    document.body.style.overflow = 'hidden';
		    
		    this._documentOverflow = document.documentElement.style.overflow;
		    document.documentElement.style.overflow = 'hidden';
		    
		    //!TODO: Better implementation to prevent the scroller from shaking the page when being hidden 
		    document.body.style.marginRight = '18px';		    
	    }
    },
    
    _getModalOverlay : function()
    {
        if (!this._backgroundElement)
        {
            var div = document.createElement('div');
            div.style.display = 'none';
            div.style.position = 'absolute';
            div.style.left = '0px';
            div.style.top = '0px';        
            div.style.zIndex = 10000;            
            div.style.backgroundColor = "#aaaaaa";
            div.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=50)";
            div.style.opacity = ".5";
            div.style.mozOpacity = ".5";
            
            //Classname should be set to allow for devs to output it on the page, and style the DIV
            div.className = "TelerikModalOverlay";
                                    			
            
            this._backgroundElement = div;
        }
        return this._backgroundElement;                
    },
                                        
    _attachWindowHandlers : function(attachEvent)
    {
        var targetElement = window;//document;
        
        if (true == attachEvent)
        {            
            this._windowResizeDelegate = Function.createDelegate(this, this._updatePageLayout);                                
            $addHandler(targetElement, 'resize', this._windowResizeDelegate);  
            
            this._windowScrollDelegate = Function.createDelegate(this, this._updatePageLayout);                                
            $addHandler(targetElement, 'scroll', this._windowScrollDelegate);                          
         }
         else
         {                          
            if (this._windowResizeDelegate) $removeHandler(targetElement, 'resize', this._windowResizeDelegate);                                   
            this._windowResizeDelegate = null;
            
            if (this._windowScrollDelegate) $removeHandler(targetElement, 'scroll', this._windowScrollDelegate);                                   
            this._windowScrollDelegate = null;
         }    
    }, 
                               
    _updatePageLayout : function() {
        
        ///Make the overlay div as big as the page        
        var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
        var clientBounds = $telerik.getClientBounds();
        var clientWidth = clientBounds.width;
        var clientHeight = clientBounds.height;
        
        var elem = this._getModalOverlay();        
        elem.style.width = Math.max(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), clientWidth)+'px';
        elem.style.height = Math.max(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), clientHeight)+'px';            
    },
    
     _disableTab : function() {        
        /// Change the tab indices so we only tab through the modal popup
        /// (and hide SELECT tags in IE6)
        
        var i = 0;
        var tagElements;
        var tagElementsInPopUp = new Array();
        Array.clear(this._saveTabIndexes);

        //Save all popup's tag in tagElementsInPopUp
        for (var j = 0; j < this._tagWithTabIndex.length; j++) {
            tagElements = this._foregroundElement.getElementsByTagName(this._tagWithTabIndex[j]);
            for (var k = 0 ; k < tagElements.length; k++) {
                tagElementsInPopUp[i] = tagElements[k];
                i++;
            }
        }

        i = 0;
        for (var j = 0; j < this._tagWithTabIndex.length; j++) {
            tagElements = document.getElementsByTagName(this._tagWithTabIndex[j]);
            for (var k = 0 ; k < tagElements.length; k++) {
                if (Array.indexOf(tagElementsInPopUp, tagElements[k]) == -1)  {
                    this._saveTabIndexes[i] = {tag: tagElements[k], index: tagElements[k].tabIndex};
                    tagElements[k].tabIndex="-1";
                    i++;
                }
            }
        }

        //IE6 Bug with SELECT element always showing up on top
        i = 0;
        if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
            //Save SELECT in PopUp
            var tagSelectInPopUp = new Array();
            for (var j = 0; j < this._tagWithTabIndex.length; j++) {
                tagElements = this._foregroundElement.getElementsByTagName('SELECT');
                for (var k = 0 ; k < tagElements.length; k++) {
                    tagSelectInPopUp[i] = tagElements[k];
                    i++;
                }
            }

            i = 0;
            Array.clear(this._saveDesableSelect);
            tagElements = document.getElementsByTagName('SELECT');
            for (var k = 0 ; k < tagElements.length; k++) {
                if (Array.indexOf(tagSelectInPopUp, tagElements[k]) == -1)  {
                    this._saveDesableSelect[i] = {tag: tagElements[k], visib: $telerik.getCurrentStyle(tagElements[k], 'visibility')} ;
                    tagElements[k].style.visibility = 'hidden';
                    i++;
                }
            }
        }
    },

    _restoreTab : function() {        
        /// Restore the tab indices so we tab through the page like normal
        /// (and restore SELECT tags in IE6)        

        for (var i = 0; i < this._saveTabIndexes.length; i++) {
            this._saveTabIndexes[i].tag.tabIndex = this._saveTabIndexes[i].index;
        }

        //IE6 Bug with SELECT element always showing up on top
        if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
            for (var k = 0 ; k < this._saveDesableSelect.length; k++) {
                this._saveDesableSelect[k].tag.style.visibility = this._saveDesableSelect[k].visib;
            }
        }
    }
};

Telerik.Web.UI.ModalExtender.registerClass('Telerik.Web.UI.ModalExtender', null);
/* END Telerik.Web.UI.Common.Popup.ModalExtender.js */
/* START Telerik.Web.UI.Common.Popup.BehaviorBase.js */
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.


Type.registerNamespace('Telerik.Web');

// This is the base behavior for all extender behaviors
Telerik.Web.BehaviorBase = function(element) {
    /// <summary>
    /// Base behavior for all extender behaviors
    /// </summary>
    /// <param name="element" type="Sys.UI.DomElement" domElement="true">
    /// Element the behavior is associated with
    /// </param>
    Telerik.Web.BehaviorBase.initializeBase(this,[element]);
    
    this._clientStateFieldID = null;
    this._pageRequestManager = null;
    this._partialUpdateBeginRequestHandler = null;
    this._partialUpdateEndRequestHandler = null;
}
Telerik.Web.BehaviorBase.prototype = {
    initialize : function() {
        /// <summary>
        /// Initialize the behavior
        /// </summary>

        // TODO: Evaluate necessity
        Telerik.Web.BehaviorBase.callBaseMethod(this, 'initialize');
    },

    dispose : function() {
        /// <summary>
        /// Dispose the behavior
        /// </summary>
        Telerik.Web.BehaviorBase.callBaseMethod(this, 'dispose');

        if (this._pageRequestManager) {
            if (this._partialUpdateBeginRequestHandler) {
                this._pageRequestManager.remove_beginRequest(this._partialUpdateBeginRequestHandler);
                this._partialUpdateBeginRequestHandler = null;
            }
            if (this._partialUpdateEndRequestHandler) {
                this._pageRequestManager.remove_endRequest(this._partialUpdateEndRequestHandler);
                this._partialUpdateEndRequestHandler = null;
            }
            this._pageRequestManager = null;
        }
    },

    get_ClientStateFieldID : function() {
        /// <value type="String">
        /// ID of the hidden field used to store client state
        /// </value>
        return this._clientStateFieldID;
    },
    set_ClientStateFieldID : function(value) {
        if (this._clientStateFieldID != value) {
            this._clientStateFieldID = value;
            this.raisePropertyChanged('ClientStateFieldID');
        }
    },

    get_ClientState : function() {
        /// <value type="String">
        /// Client state
        /// </value>
        if (this._clientStateFieldID) {
            var input = document.getElementById(this._clientStateFieldID);
            if (input) {
                return input.value;
            }
        }
        return null;
    },
    set_ClientState : function(value) {
        if (this._clientStateFieldID) {
            var input = document.getElementById(this._clientStateFieldID);
            if (input) {
                input.value = value;
            }
        }
    },

    registerPartialUpdateEvents : function() {
        /// <summary>
        /// Register for beginRequest and endRequest events on the PageRequestManager,
        /// (which cause _partialUpdateBeginRequest and _partialUpdateEndRequest to be
        /// called when an UpdatePanel refreshes)
        /// </summary>

        if (Sys && Sys.WebForms && Sys.WebForms.PageRequestManager){
            this._pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
            if (this._pageRequestManager) {
                this._partialUpdateBeginRequestHandler = Function.createDelegate(this, this._partialUpdateBeginRequest);
                this._pageRequestManager.add_beginRequest(this._partialUpdateBeginRequestHandler);
                this._partialUpdateEndRequestHandler = Function.createDelegate(this, this._partialUpdateEndRequest);
                this._pageRequestManager.add_endRequest(this._partialUpdateEndRequestHandler);
            }
        }
    },

    _partialUpdateBeginRequest : function(sender, beginRequestEventArgs) {
        /// <summary>
        /// Method that will be called when a partial update (via an UpdatePanel) begins,
        /// if registerPartialUpdateEvents() has been called.
        /// </summary>
        /// <param name="sender" type="Object">
        /// Sender
        /// </param>
        /// <param name="beginRequestEventArgs" type="Sys.WebForms.BeginRequestEventArgs">
        /// Event arguments
        /// </param>

        // Nothing done here; override this method in a child class
    },
    
    _partialUpdateEndRequest : function(sender, endRequestEventArgs) {
        /// <summary>
        /// Method that will be called when a partial update (via an UpdatePanel) finishes,
        /// if registerPartialUpdateEvents() has been called.
        /// </summary>
        /// <param name="sender" type="Object">
        /// Sender
        /// </param>
        /// <param name="endRequestEventArgs" type="Sys.WebForms.EndRequestEventArgs">
        /// Event arguments
        /// </param>

        // Nothing done here; override this method in a child class
    }
}
Telerik.Web.BehaviorBase.registerClass('Telerik.Web.BehaviorBase', Sys.UI.Behavior);

/* END Telerik.Web.UI.Common.Popup.BehaviorBase.js */
/* START Telerik.Web.UI.Common.Popup.PopupBehavior.js */
// JScript File

// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.
Type.registerNamespace('Telerik.Web');

Telerik.Web.PositioningMode = function() {
    throw Error.invalidOperation();
}
Telerik.Web.PositioningMode.prototype = {
    Absolute: 0,
    Center: 1,
    BottomLeft: 2,
    BottomRight: 3,
    TopLeft: 4,
    TopRight: 5
}

Telerik.Web.PositioningMode.registerEnum('Telerik.Web.PositioningMode');

Telerik.Web.PopupBehavior = function(element) {
    /// <param name="element">The DOM element the behavior is associated with.</param>
    Telerik.Web.PopupBehavior.initializeBase(this, [element]);

    this._x = 0;
    this._y = 0;
    this._positioningMode = Telerik.Web.PositioningMode.Absolute;
    this._parentElement = null;
    this._parentElementID = null;
    this._moveHandler = null;
    this._firstPopup = true;    
    this._originalParent = null;
    this._overlay = false;
    this._keepInScreenBounds = true;
    
    // This is only used by the RadSlidingPane, as its popupElement is never hidden with visibility:hidden or displya:none
    // for performance reasons.
    this._manageVisibility = true;
}

Telerik.Web.PopupBehavior._ie6pinnedList = {};


Telerik.Web.PopupBehavior.prototype = {
    
    getPageOffset : function()
    {
        var bounds = 
        {
            x : (document.documentElement.scrollLeft || document.body.scrollLeft),
            y : (document.documentElement.scrollTop || document.body.scrollTop)
        };
        return bounds;
    },

    pin : function(toPin)
    {		
        var element = this.get_element();
        var scrolls = this.getPageOffset();
                		    		    
        if ($telerik.isIE6)
        {        
            var id = this.get_id();
                            
            if (toPin)
            {        
                if (Telerik.Web.PopupBehavior._ie6pinnedList[id]) return;
                        
                var bounds = $telerik.getBounds(element);  
                                                 
                Telerik.Web.PopupBehavior._ie6pinnedList[id] = window.setInterval(Function.createDelegate(this, function()
                {                                                
                   var curScrolls = this.getPageOffset();                                        
                   var x = bounds.x - scrolls.x + curScrolls.x;
                   var y = bounds.y - scrolls.y + curScrolls.y;
                          
                   //Set the parent to be the documentElement in order to work
                   var elem = this.get_parentElement();
                   this.set_parentElement(document.documentElement);
                   
                   this.set_x(x);
                   this.set_y(y);
                                  
                   this.show();
                   
                   //Restore original parent
                   this.set_parentElement(elem);  
                }), 130);
                
            }
            else
            {   
                var timeout = Telerik.Web.PopupBehavior._ie6pinnedList[id];
                if (timeout)         
                {
                    window.clearInterval(timeout);
                }
                delete Telerik.Web.PopupBehavior._ie6pinnedList[id];
            }
        }
        else
        {               
            var next = toPin ? "fixed" : "absolute";        
            if (element.style.position == next) return;
            
            //Else if position is fixed and there is offset from top/left, it needs to be recalculated and repositioned taking offset into account
            var bounds = $telerik.getBounds(element);  
            
            //If there is scroll offset from the page, the element needs to be repositioned when setting it to be fixed.
            //Element must be positioned and made visible BEFORE setting the position to fixed        
            //Also, calling set_y() or show() causes a nasty flicker in FireFox, this is why we need to set it directly
            //TODO: We are not taking into consideration the this._positioningMode - refactor the switch statement out of show() method, and call it here and there as well
            if (toPin && (scrolls.x || scrolls.y))
            {            
                this._x = bounds.x - scrolls.x;
                this._y = bounds.y - scrolls.y;                        
                $telerik.setLocation(element, { x:this._x, y:this._y });    
            }                                                                   
            
            element.style.position = next;           
        }
    },

    //NEW - to be used in RadWindow and possibly RadDock
    center : function()
    {
       var element = this.get_element();
       if(this._manageVisibility)
       {
            $telerik.setVisible(element, true);
       }
       
       var screenBounds =  $telerik.getClientBounds();
       var elementBounds = $telerik.getBounds(element);          
       var x = parseInt((screenBounds.width - elementBounds.width) / 2);
       var y = parseInt((screenBounds.height - elementBounds.height) / 2);
       
       //Set the parent to be the documentElement in order for the center to work
       var elem = this.get_parentElement();
       this.set_parentElement(document.documentElement);
       
       this.set_x(x);
       this.set_y(y);
       
       //setLocation will not take care of offset, but the show method will.
       //Sys.UI.DomElement.setLocation(element, x,y);
       this.show();
       
       //Restore original parent
       this.set_parentElement(elem);
    },

    
    get_parentElement : function() {
        /// <value>Parent dom element.</value>        
        if (!this._parentElement && this._parentElementID) {
            this.set_parentElement($get(this._parentElementID));
            Sys.Debug.assert(this._parentElement != null, String.format('Couldn\'t find parent element "{0}"', this._parentElementID));
        }        
        return this._parentElement;
    },    
    set_parentElement : function(element) {
        this._parentElement = element;
    },
    
    get_parentElementID : function() {
        /// <value>Parent dom element.</value>
        if (this._parentElement) return this._parentElement.id
        return this._parentElementID;
    },
    set_parentElementID : function(elementID) {
        this._parentElementID = elementID;
        if (this.get_isInitialized()) {
            this.set_parentElement($get(elementID));
        }
    },
        
    get_positioningMode : function() {
        /// <value type="Telerik.Web.PositioningMode">Positioning mode.</value>
        return this._positioningMode;
    },
    set_positioningMode : function(mode) {
        this._positioningMode = mode;
    },
    
    get_x : function() {
        /// <value type="Number">X coordinate.</value>
        return this._x;
    },
    set_x : function(value) {
        if (value != this._x) {
            this._x = value;
            if ($telerik.getVisible(this.get_element()) && this._manageVisibility) {
                this.show();
            }
        }
    },
    
    get_y : function() {
        /// <value type="Number">Y coordinate.</value>
        return this._y;
    },
    set_y : function(value) {
        if (value != this._y) {
            this._y = value;
            if ($telerik.getVisible(this.get_element()) && this._manageVisibility) {
                this.show();
            }
        }
    },   
    
    get_overlay : function() {
        /// <value type="Boolean">Create an overlay.</value>
        return this._overlay;
    },    
    set_overlay : function(value) {
        this._overlay = value;
            
        //Detach the handlers, in case these are already attached.
        this._attachWindowHandlers(false);
        
        //Handle the resize and scroll events of the window to set the new position for the overlay in FF.
        if(this._overlay)
        {
            this._attachWindowHandlers(true);
        }
        else if (!((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)))
        {
            //In case the IFRAME has been created, hide it.
            var elt = this.get_element();
            var childFrame = elt._hideWindowedElementsIFrame;
            if (childFrame) {
                childFrame.style.display = "none";                
            }
        }
    }, 
    
    get_manageVisibility : function() {
        /// <value type="Boolean">Manage the visibility of the popup element.</value>
        return this._manageVisibility;
    },    
    set_manageVisibility : function(value) {
        this._manageVisibility = value;
    },
    
    get_keepInScreenBounds : function() {
        /// <value type="Boolean">Show the element in the visible viewport of the browser.</value>
        return this._keepInScreenBounds;
    },    
    set_keepInScreenBounds : function(value) {
        this._keepInScreenBounds = value;
    },

    hide : function() {
        var elt = this.get_element();
        if(this._manageVisibility)
        {
            $telerik.setVisible(elt, false);
        }
        
        if (elt.originalWidth) {
            elt.style.width = elt.originalWidth + "px";
            elt.originalWidth = null;
        }
        if (Sys.Browser.agent === Sys.Browser.InternetExplorer || this._overlay) {
            var childFrame = elt._hideWindowedElementsIFrame;
            if (childFrame) {
                childFrame.style.display = "none";                
            }
        }
    },    
    
    show : function() {                
        var elt = this.get_element();
        
        //Set current top offset, or else the page scrolls down in Mozilla - in the case when scrolling is disabled
        //This was needed in scenarios where a window is modal (as the modality would disable page scrolling)
        //However, due to other problems in Mozilla with modality & disabled scrolling - e.g. a nasty flicker in some scenarios
        //The current modal implementation does not remove scrollbars. SO this code here is not needed
        //And it will be commented because it cause a short flicker when finishing a radwindow resize operation.
        //if (Sys.Browser.agent == Sys.Browser.Firefox)
        //{
            //var bounds = this._getViewportBounds();        
            //elt.style.top = bounds.scrollTop + "px";
        //}
        
         
        //Modification of code above: If firefox and document scrolling is disabled, then showing a popup/dropdown causes the page to jump                
        if ($telerik.isFirefox)
        {
            var doc = document.documentElement;        
            var overflow =  $telerik.getCurrentStyle(doc, 'overflow');
            if ("hidden" == overflow)
            {             
                elt.style.left =  doc.scrollLeft + "px";
                elt.style.top =  doc.scrollLeft + "px";                                     
            }
        }
        
        if(this._manageVisibility)
        {
            $telerik.setVisible(elt, true);
        }
        
        // offsetParent (doc element if absolutely positioned or no offsetparent available)
        var offsetParent = elt.offsetParent || document.documentElement;

        // diff = difference in position between element's offsetParent and the element we will attach popup to.
        // this is basically so we can position the popup in the right spot even though it may not be absolutely positioned
        var diff;
        var parentBounds;
        if(this._parentElement) {
            // we will be positioning the element against the assigned parent
			//ORIGINAL TOOLKIT SCRIPT CHANGE:
			//CommonScripts.getBounds did not return proper bounds when in quirks mode:
            parentBounds = $telerik.getBounds(this._parentElement);
            
            //TEKI: Now getBounds DOES return proper offset, so this code causes problems in Quirksmode!
            //There are a lot of people who want to use the tooltip in DNN, so we need to take care of quirksmode properly!            
            //var offsetParentLocation = $telerik.getLocation(offsetParent);
            //diff = {x: parentBounds.x - offsetParentLocation.x, y:parentBounds.y - offsetParentLocation.y};            
            diff = {x: parentBounds.x, y:parentBounds.y};                             
        }
        else {
            // we will be positioning the element against the offset parent by default, since no parent element given
			//ORIGINAL TOOLKIT SCRIPT CHANGE:
			//CommonScripts.getBounds did not return proper bounds when in quirks mode:
            parentBounds = $telerik.getBounds(offsetParent);            
            diff = {x:0, y:0};
        }

        // width/height of the element, needed for calculations that involve width like centering
        var width = elt.offsetWidth - (elt.clientLeft ? elt.clientLeft * 2 : 0);
        var height = elt.offsetHeight - (elt.clientTop ? elt.clientTop * 2 : 0);
        
        var position;
        switch (this._positioningMode) {
            case Telerik.Web.PositioningMode.Center:
                position = {
                    x: Math.round(parentBounds.width / 2 - width / 2),
                    y: Math.round(parentBounds.height / 2 - height / 2)
                };
                break;
            case Telerik.Web.PositioningMode.BottomLeft:
                position = {
                    x: 0,
                    y: parentBounds.height
                };
                break;
            case Telerik.Web.PositioningMode.BottomRight:
                position = {
                    x: parentBounds.width - width,
                    y: parentBounds.height
                };
                break;
            case Telerik.Web.PositioningMode.TopLeft:
                position = {
                    x: 0,
                    y: -elt.offsetHeight
                };
                break;
            case Telerik.Web.PositioningMode.TopRight:
                position = {
                    x: parentBounds.width - width,
                    y: -elt.offsetHeight
                };
                break;
            default:
                position = {x: 0, y: 0};
        }
        position.x += this._x + diff.x;
        position.y += this._y + diff.y;
        
        $telerik.setLocation(elt, position);
       
        if(this._firstPopup) {
            // 23098: Setting the width causes the element to grow by border+passing every time. But not setting it
            // causes strange behavior in safari. Just set it once.
            elt.style.width = width + "px";
        }
        this._firstPopup = false;

        var newPosition = $telerik.getBounds(elt);        
        var boundsCheck = this._getViewportBounds();
        
        if(this._keepInScreenBounds)
        {
            var updateNeeded = false;
            
            var documentWidth = self.innerWidth ? self.innerWidth : document.documentElement.clientWidth;
            // CONSIDER: Create a generic function to return this information.
            if (!documentWidth) {
                documentWidth = document.body.clientWidth;
            }
            //Take into account the value of scrollLeft - solves problems in case the elm is not in the visible viewport
            //initially. 
            if (newPosition.x + newPosition.width - boundsCheck.scrollLeft > documentWidth ) {//- 5
                position.x -= newPosition.x + newPosition.width - documentWidth + boundsCheck.scrollLeft;//5 + 
                updateNeeded = true;
            }
            if (newPosition.x < 0) {
                position.x -= newPosition.x;
                updateNeeded = true;
            }
            if (newPosition.y < 0) {
                position.y -= newPosition.y;
                updateNeeded = true;
            }
            
            //Take into account the value of scrollTop - solves problems in case the elm is not in the visible viewport
            //initially. 
            if (boundsCheck.height < newPosition.y + newPosition.height - boundsCheck.scrollTop)
            {
                //the default popup does not check its vertical bounds
                //this check should help if the popup is near the bottom of the viewport
                if (boundsCheck.height - newPosition.height >0)
                {
                    position.y = boundsCheck.height - newPosition.height + boundsCheck.scrollTop;
                    updateNeeded = true;
                }
            }

            if (updateNeeded) {
                $telerik.setLocation(elt, position);
                
                //Update the variable that holds the position for the IFRAME that will be created (for IE6).
                newPosition = $telerik.getBounds(elt);
            }
        }
        
        elt.zIndex = 1000;

        if (((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) || this._overlay) {
            var childFrame = elt._hideWindowedElementsIFrame;
            if (!childFrame) {
                childFrame = document.createElement("iframe");
                childFrame.src = "javascript:'<html></html>';";
                childFrame.style.position = "absolute";
                childFrame.style.display = "none";
                childFrame.scrolling = "no";
                childFrame.frameBorder = "0";
                childFrame.tabIndex = "-1";
                childFrame.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
                //Similar insertion code is called in _onMove, but it causes "loading..." progress bar to show in the FireFox status bar
                //So it is commented there. IN theory this can be a problem if the get_element() is moved in the DOM.
                elt.parentNode.insertBefore(childFrame, elt);
                
                elt._hideWindowedElementsIFrame = childFrame;
                this._moveHandler = Function.createDelegate(this, this._onMove);
                Sys.UI.DomEvent.addHandler(elt, "move", this._moveHandler);
            }

            $telerik.setBounds(childFrame, newPosition);
            //We need to use fixed position for the ovelay in FF, so that it hides flash and media objects.
            if(Sys.Browser.agent === Sys.Browser.Firefox)
            {
                //Fixed position supports left and top, always relative to the visible viewport. That is why in case you scroll
                //down the page, the top of the ovelay should become negative.
                childFrame.style.top = parseInt(newPosition.y) - boundsCheck.scrollTop + "px";
                childFrame.style.left = parseInt(newPosition.x) - boundsCheck.scrollLeft + "px";
                childFrame.style.position = "fixed";
            }
            
            //TEKI: When in IE6 and the doctype is not XHTML this line causes the browser to freeze. No workaround was found - 
            //neither timeouts, neither modifying frame property, nor anything. The only solution is to not show the iframe          
            if ($telerik.quirksMode) return;
            
            childFrame.style.display = elt.style.display;
                                                
            if (elt.currentStyle && elt.currentStyle.zIndex)
            {
                childFrame.style.zIndex = elt.currentStyle.zIndex;
            }
            else if (elt.style.zIndex)
            {
                childFrame.style.zIndex = elt.style.zIndex;
            }
        }
    },
    
     _getViewportBounds : function()
     {
        //Get browser bounds
        var bounds = $telerik.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;
        
        return bounds;
     },
     
    _setCoordinates : function(x, y) 
    {
        var areCoordinatesUpdated = false;
        
        if (x != this._x)
        {
            this._x = x;
            areCoordinatesUpdated = true;
        }
        if(y != this._y)
        {
            this._y = y;
            areCoordinatesUpdated = true;
        }
        if ($telerik.getVisible(this.get_element()) && areCoordinatesUpdated && this._manageVisibility) {
            this.show();
        }
    },

    
    initialize : function() {
        Telerik.Web.PopupBehavior.callBaseMethod(this, 'initialize');
        this.hide();
        this.get_element().style.position = "absolute";
    },
    
    dispose : function() {  
        var elt = this.get_element();
        if (elt) {
            //Remove handlers.
            if (this._moveHandler) {
                Sys.UI.DomEvent.removeHandler(elt, "move", this._moveHandler);
                this._moveHandler = null;
            }
            this._attachWindowHandlers(false);
            
            if ($telerik.getVisible(elt) && this._manageVisibility) {
                this.hide();
            }
            if (this._originalParent) {
                elt.parentNode.removeChild(elt);
                this._originalParent.appendChild(elt);
                this._originalParent = null;
            }
        }
        this._parentElement = null;
        Telerik.Web.PopupBehavior.callBaseMethod(this, 'dispose');
    },
    
    _onMove : function() 
    {
        var elt = this.get_element();
        var overlayIframe = elt._hideWindowedElementsIFrame;
        if (overlayIframe) 
        {   
            //Called multiple times, not needed
            //elt.parentNode.insertBefore(elt._hideWindowedElementsIFrame, elt);
            if(Sys.Browser.agent === Sys.Browser.Firefox) 
            {
                var boundsCheck = this._getViewportBounds();
                overlayIframe.style.top = parseInt(elt.style.top) - boundsCheck.scrollTop + "px";
                overlayIframe.style.left = parseInt(elt.style.left) - boundsCheck.scrollLeft + "px";
                overlayIframe.style.position = "fixed";
            }
            else
            {
                overlayIframe.style.top = elt.style.top;
                overlayIframe.style.left = elt.style.left;           
            }            
        }
    },
    
    _handleElementResize : function()
    {
        var elt = this.get_element();
        var overlayIframe = elt._hideWindowedElementsIFrame;
        if (overlayIframe) 
        {
            var newBounds = $telerik.getBounds(elt);
            $telerik.setBounds(overlayIframe, newBounds);
        }
    },
    
    _attachWindowHandlers : function(attachEvent)
    {
        if(! Sys.Browser.agent === Sys.Browser.Firefox) return;
        
        var targetElement = window;
        
        if (true == attachEvent)
        {            
            this._windowResizeDelegate = Function.createDelegate(this, this._onMove);                                
            $addHandler(targetElement, 'resize', this._windowResizeDelegate);  
            
            this._windowScrollDelegate = Function.createDelegate(this, this._onMove);   
            $addHandler(targetElement, 'scroll', this._windowScrollDelegate);                          
         }
         else
         {                          
            if (this._windowResizeDelegate) $removeHandler(targetElement, 'resize', this._windowResizeDelegate);                                   
            this._windowResizeDelegate = null;
            
            if (this._windowScrollDelegate) $removeHandler(targetElement, 'scroll', this._windowScrollDelegate);                                   
            this._windowScrollDelegate = null;
         }    
    }

}
//Telerik.Web.PopupBehavior.descriptor = {
//    properties: [   {name: 'parentElement', attributes: [ Sys.Attributes.Element, true ] },
//                    {name: 'positioningMode', type: Telerik.Web.PositioningMode},
//                    {name: 'x', type: Number},
//                    {name: 'y', type: Number} ],
//    events: [   {name: 'show'},
//                {name: 'hide'} ]
//}
Telerik.Web.PopupBehavior.registerClass('Telerik.Web.PopupBehavior', Telerik.Web.BehaviorBase);//AjaxControlToolkit.BehaviorBase);




/* END Telerik.Web.UI.Common.Popup.PopupBehavior.js */
/* START Telerik.Web.UI.Window.RadWindow.js */
//Class that manages windows.
//- singleton
//- regiter global event handlers
//- log a window for being shown
//- hide currently visible window
Type.registerNamespace('Telerik.Web.UI');

Telerik.Web.UI.RadWindowControllerClass = function() 
{                 
    /// <exclude/>               
    //Current visible window
    this._activeWindow = null;    
        
    this._historyStack = [];	        
    
    //Attach body event handlers 
    this._registerGlobalBodyEventHandlers();    
}

Telerik.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
            {                                
                Telerik.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;
    }                    
}   

Telerik.Web.UI.RadWindowControllerClass.registerClass('Telerik.Web.UI.RadWindowControllerClass', null); 

//Create a singleton
if (!Telerik.Web.UI.RadWindowController)
{
    Telerik.Web.UI.RadWindowController = new Telerik.Web.UI.RadWindowControllerClass();    
}


Type.registerNamespace('Telerik.Web.UI');
Type.registerNamespace('Telerik.Web.UI.RadWindowUtils');


//Localization can be overridden using Javascript
Telerik.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"  
};

///////////////////////////////////////////////////////////////////////////
// Telerik.Web.UI.RadWindow 
///////////////////////////////////////////////////////////////////////////
Telerik.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>
    Telerik.Web.UI.RadWindow.initializeBase(this, [element]);
    
    //Events array (needed by the clone method)
    this._eventNames = ["resize", "activate", "dragStart", "dragEnd", "show", "pageLoad", "close", "command"];
                               
    //HTML elements    
    this._bodyElement = ($telerik.standardsMode) ? document.documentElement : document.body;    
            
    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 = ($telerik.isIE);
    this._openerElementID = null;    
    this._offsetElementID = null;        
    this._behaviors = Telerik.Web.UI.WindowBehaviors.Default;
    this._initialBehaviors = Telerik.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;
                
    //TODO: These do not have clientside implementation at all yet    
    this._iconUrl = null;
    this._minimizeIconUrl = null;    
                                           
    //Animation
    this._animation = Telerik.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;
    
    //-------------- 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 --------------------------//        
}

Telerik.Web.UI.RadWindow.prototype = {

    //TODO: Replace here with "real" localization
    _getLocalization : function()
    {            
        return Telerik.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;
        }									
    },
        
    _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.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 (this._titleCell)//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;
	        }
	    }
    },
    
    //---------------------------------------- '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(Telerik.Web.UI.RadWindowManager) != "undefined" && Telerik.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 Telerik.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 = {};

        //If bEnable is true, return if the resizable behavior is not enabled
        if (this.isBehaviorEnabled(Telerik.Web.UI.WindowBehaviors.Resize))
        {
                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(Telerik.Web.UI.WindowBehaviors.Move)) 
        {
            hashTable["move"] = this._titleCell;
        }
                                   
        this._resizeExtender = new Telerik.Web.UI.ResizeExtender(this, this._popupElement, hashTable, this._tableElement);            
    },
    
    
    onResizeStart : function()
    {        
       this._cachedDragZoneBounds = this._getRestrictionZoneBounds();    
    },
    
    
    onResizing : function(bounds)
    {   
       if (!this._cachedDragZoneBounds) return true;
       return this._containsBounds(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 && $telerik.isFirefox) this._popupBehavior._onMove();
                                                              
        //Raise resize event    
        this.raiseEvent('resize', new Sys.EventArgs());          
    },
    
              
    onDragStart : function() 
	{	
	    /// <exclude />  	    	    
	    this.setActive(true);	    	    	    	    
	    	    
        if (this.isPinned()) return false;
        //NEW: 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 = $telerik.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 && $telerik.isFirefox) this._popupBehavior._onMove();
	        	        	  
	    //This method is called each time the titlebar is clicked, which is not so good as user might be clicking or doubleclicking	    
		this.raiseEvent("dragEnd", new Sys.EventArgs());						
        this._storeBounds();        
        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._containsBounds(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;
    },
    
        
    _isInBounds : function(mousePos, zoneBounds, popupBounds)
    {
        var inBounds = $telerik.containsPoint(zoneBounds, mousePos.x, mousePos.y);//left
	    if (inBounds)      	        
	    {
	        var x = mousePos.x + popupBounds.width;
	        var y = mousePos.y + popupBounds.height;
	        inBounds = $telerik.containsPoint(zoneBounds, x, y);//bottom right	        	        
	    }
        return inBounds;	            
    },
        
    //###########---------------- PUBLIC API ---------------------##################//                 
    initialize : function() 
    {
        /// <exclude />
        Telerik.Web.UI.RadWindow.callBaseMethod(this, 'initialize');
              
        //if visible on page load - show
        if (this._visibleOnPageLoad)
        {        
            this.show();
        }        
        
        //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();
            
        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(Telerik.Web.UI.WindowBehaviors.None);
        
         if (this._iframe)
		{					
		    //MEMORYLEAK - Call onunload handler of the page by forcing a page change
		    this._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 ?!
	        var iframe = this._iframe;        
            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 = "";
		}
                                                  
        Telerik.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("Telerik.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(Telerik.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 != Telerik.Web.UI.WindowBehaviors.None))
		{	
		    //Slight 2-line code duplication with below
			this._show();            
            this._afterShow();
            				
			if (this.isInitialBehaviorEnabled(Telerik.Web.UI.WindowBehaviors.Minimize))
			{				
				this.minimize();			
			}
			 
			if(this.isInitialBehaviorEnabled(Telerik.Web.UI.WindowBehaviors.Maximize))
			{
				this.maximize();			
			}
			 			 
			if (this.isInitialBehaviorEnabled(Telerik.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 == Telerik.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;                
            }                        
        }
        
        this._popupBehavior.set_parentElement(this._bodyElement);
        
        //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 titlebar and statusbar visible or hidden
        this.set_visibleTitlebar(this._visibleTitlebar);
        this.set_visibleStatusbar(this._visibleStatusbar);
                
        //Get window position and set it
        this._reSetWindowPosition();
        
        //Set the parent to be the body now, once you have shown it to avoid wrong positioning when restoring after minimize
        this._popupBehavior.set_parentElement(this._bodyElement);
                                                                                                                
        //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 an open animation is currently going on, cancel it - make sure this code is before next check - because sometimes animations execute a bit later and it results in incorrect behavior
        if (this._windowAnimation)  this._windowAnimation.stop();                             
                                                                                                                                         
        //Add onclose animation here
        if (this._windowAnimation)
        {
            this._windowAnimation.play(true);                                   
        }
        else this._afterHide();               
    },
    
    //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._popupBehavior.hide(true);
        this._popupVisible = false;

        //Notify controller that window was hidden                                
        this._getWindowController().notifyWindowClosed(this);
        this.raiseEvent('close', new Sys.EventArgs());
    },
    
    _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()
        {	                             	                                          
           var wnd = this.controller;
                              
           //Get left and top relative to target element, then show window for a momenta and get absolute bounds, left and top 
           var relativeBounds = wnd._getCalculatedPopupBounds();                   
           wnd._setPopupVisible(relativeBounds.x, relativeBounds.y);
           var popupBounds = $telerik.getBounds(wnd._popupElement);                               
           wnd._popupBehavior.hide();  
           
           //Configure animation end bounds
           this.set_endBounds(popupBounds);                                            
        };                                       
                         
     
        if (!this._windowAnimation)
        {        
            if (this._animation == Telerik.Web.UI.WindowAnimation.Fade)
            {                                                	        	        	       
	            this._windowAnimation = new Telerik.Web.UI.Animations.FadeAnimation(this, .4, null, this._popupElement,null, this._openerElement);	                        	                              
	            
	            this._windowAnimation.onShowStart = function()
                {	                            
                   this.controller._show();               
                };
            }                
            else if (this._animation == Telerik.Web.UI.WindowAnimation.Slide)
            {
                this._windowAnimation = new Telerik.Web.UI.Animations.SlideAnimation(this, .2, null, this._popupElement, null, this._openerElement);
	            this._windowAnimation.onShowStart = commonResizeAnimationConfiguration;
            }
            else if (this._animation == Telerik.Web.UI.WindowAnimation.FlyIn)
            {                
                this._windowAnimation = new Telerik.Web.UI.Animations.FlyInAnimation(this, null, null, this._popupElement, null, this._openerElement);
	            this._windowAnimation.onShowStart = commonResizeAnimationConfiguration;
            }
            
            else if (this._animation == Telerik.Web.UI.WindowAnimation.Resize)
            {        
                this._windowAnimation = new Telerik.Web.UI.Animations.ResizeAnimation(this, .2, 50, this._popupElement, null, this._openerElement);	                            
                this._windowAnimation.onShowStart = commonResizeAnimationConfiguration;
            }
        }

        if (this._windowAnimation)
        {                                      
            this._windowAnimation.onShowEnd = function()
            {	
                //Make sure another window that might be visible gets hidden
                this.controller._show();   
                //Raise event
                this.controller._afterShow();
            };  
                        
            this._windowAnimation.onHideEnd = function()
            {	
                this.controller._afterHide();//!
            };    	                    
    
            this._windowAnimation.play();                             
        }
    },
     
    _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 Telerik.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 Telerik.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)
    {    
        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();
    },
    
    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();                  
    },
    
    
    _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"; 
   
        //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);                                
    },

    
    _enablePageScrolling : function(enable)
    {
        //In fact rad window only disables scrolling when it itself is maximized! 
        //So what we need to do is change the scrolling only if it was the window that originally changed it in the first place                
        if (enable)
	    {		
	        var overflow = this._documentOverflowX;        	        
	        if (null != overflow)
	        {
	            this._documentOverflowX = null;		    
		        document.documentElement.style.overflowX = overflow ? overflow : '';
		    }
		    
		    overflow = this._documentOverflowY;        	        
	        if (null != overflow)
	        {
	            this._documentOverflowY = null;		    
		        document.documentElement.style.overflowY = overflow ? overflow : '';
		    }
		    
		    overflow = this._bodyOverflowX; 
		    if(null != overflow)
		    {
		        this._bodyOverflowX = null;
		        document.body.style.overflowX = overflow ? overflow : '';
		    }
		    
		    overflow = this._bodyOverflowY; 
		    if(null != overflow)
		    {
		        this._bodyOverflowY = null;
		        document.body.style.overflowY = overflow ? overflow : '';
		    }
	    }
	    else
	    {	
	        //Pick-up and store the current page overflow. As it can be called multiple times, it is important to store just original value
	        if (!this._documentOverflowX)
	        {
                this._documentOverflowX = $telerik.getCurrentStyle(document.documentElement, 'overflowX');
            }
            
            if(!this._documentOverflowY)
            {
                this._documentOverflowY = $telerik.getCurrentStyle(document.documentElement, 'overflowY');
            }
            
            if(!this._bodyOverflowX)
            {
                this._bodyOverflowX = $telerik.getCurrentStyle(document.body, 'overflowX');
            }
            
            if(!this._bodyOverflowY)
            {
                this._bodyOverflowY = $telerik.getCurrentStyle(document.body, 'overflowY');
            }
            	
		    document.body.style.overflow = 'hidden';
		    document.documentElement.style.overflow = 'hidden';
	    }
    },
    
   
   //TODO: Perhaps move to a $telerik core? 
    _containsBounds : function(parentBounds, childBounds)
    {                
        if (!parentBounds || !childBounds) return false;
                        
        var inBounds = $telerik.containsPoint(parentBounds, childBounds.x, childBounds.y);          
        if (inBounds)      	        
        {
            var x = childBounds.x + childBounds.width;
            var y = childBounds.y + childBounds.height;            
            inBounds = $telerik.containsPoint(parentBounds, x, y);//bottom right	        	        
        }                        
        return inBounds;	      
    },
        
    _getRestrictionZoneBounds : function()
    {        
	     var zone = null;
         if (this.get_restrictionZoneID())
         {
             var elem = $get(this.get_restrictionZoneID());             
             if (elem)
             {
                zone = $telerik.getBounds(elem);                                        
                //var offset = $telerik.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 titlebar 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 = $telerik.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 = $telerik.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;        
     },
     
     _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;
    },
    
    _createUI : function()
    {
        //Dynamic rendering of the window
        if (!this._popupElement)
        {        
            var windowID = this.get_id();
            var wrapperID = 'RadWindowWrapper_' + windowID;
            
            var rootDiv = document.createElement('DIV');        
            rootDiv.id = wrapperID;                        
                        
            rootDiv.className = this._getFullSkinName();
            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 = ["corner topleft","titlebar","corner topright",
                              "corner bodyleft", "windowcontent", "corner bodyright",                                 
                              "corner bodyleft", "statusbar", "corner bodyright",
                              "corner footerleft", "footercenter", "corner footerright"];		                                                       
            var rowClassNames = ["titlerow", "contentrow", "statusbarrow",  "footerrow"];
                                           
		    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 = "topresize";    		
    		topResizer.innerHTML = "<!-- / -->";
    		this._topResizer = topResizer;
            this._titleCell.appendChild(this._topResizer);
    		        		
    		//Titlebar element - holds all other elements in the titlebar
    		var titlebarTable = this._createDefaultTable();
    		titlebarTable.className = "titlebarcontrols";  
    		this._titlebarElement = titlebarTable;    		
    		this._titleCell.appendChild(this._titlebarElement);
    		    		    				    		    		    		    		    		    		        		        		    
    		//Follow 3 titlebar elements - windowicon(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 = ($telerik.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 statusbar
            var stastusbarTable = this._createDefaultTable();
            stastusbarTable.style.width = "100%";
            this._statusCell = tableElement.rows[2].cells[1];                        
            this._statusCell.innerHTML = "";
            this._statusCell.appendChild(stastusbarTable);
            
            //Create statusbar message cell
            var statusMessageCell = stastusbarTable.rows[0].insertCell(-1);
            statusMessageCell.style.width = "100%";
            var messageInput = this._getStatusMessageElement();        		
            statusMessageCell.appendChild(messageInput);
            
            //Create statusbar resizer
            var bottomResizerCell = stastusbarTable.rows[0].insertCell(-1);
            bottomResizerCell.style.width = "15px";
    		var resizeDiv = document.createElement('DIV');
    		bottomResizerCell.appendChild(resizeDiv);
    		this._bottomResizer = resizeDiv;
    		
			//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 titlebar 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(Telerik.Web.PopupBehavior, { 'id': (new Date() - 100)//set a unique id
                +'PopupBehavior', 'parentElement': null, 'overlay': this._overlay, 'keepInScreenBounds': this._keepInScreenBounds }, null, null, this._popupElement);
        }        
    },
    

    //------------------------------ 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 = "controlbuttons";            
            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 = "windowicon";//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)
    {
        //Button css classes use the following convention  - "[commandName]button"
        if (!butname || !this._buttonsArray) return null;
        butname = butname.toLowerCase() + "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 form = document.getElementById(this._formID);   
        if (!form) form = document.forms[0];   
        form.insertBefore(this._popupElement, form.firstChild);  
    },
    
    
    _invokeDialogCallBackFunction : function(oArg, bKeepOpen)
    {	
	    if (true != bKeepOpen) this.close();
    		
	    var oFun = this.get_clientCallBackFunction();
	    if (oFun)
	    {		
		    if ("string" == typeof(oFun)) oFun = eval(oFun);
		    if ("function" == typeof(oFun)) oFun(this, oArg);
	    }
    },
    
    _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 + " normalwindow transparentwindow";
    },
          
                                            
    _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, "inactivewindow"));
    },
    
    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, "minimizedwindow"));
    },
    
    isMaximized : function()
    {                
        return (this._popupElement && Sys.UI.DomElement.containsCssClass(this._popupElement, "maximizedwindow"));
    },
    
            
    setActive : function(bActivate)
    {         
        var rootDiv = this._popupElement;
        if (!bActivate) //Make inactive
        {
            Sys.UI.DomElement.addCssClass(rootDiv, "inactivewindow");                     
        }
        else //Make active
        {                   
            //Set a new zIndex!            
            var oldZindex = parseInt(rootDiv.style.zIndex);
            var newZIndex = Telerik.Web.UI.RadWindowUtils.get_newZindex(oldZindex); 
            rootDiv.style.zIndex = "" + newZIndex;

            //NEW      
            this._getWindowController().set_activeWindow(this);   
            
            if (this.isActive()) return;
                                     
            $telerik.removeCssClasses(rootDiv, ["inactivewindow"]);                                  
                                    
            //TODO: Research why! Can cause window to move to previous location when dropping after move
            //this._updatePopupZindex();
               
            //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?        
            this.raiseEvent('activate', new Sys.EventArgs());                        
        }                                        
    },
    
    _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;

        var rootDiv = this._popupElement;
        $telerik.removeCssClasses(rootDiv, ["normalwindow","maximizedwindow"]);
        Sys.UI.DomElement.addCssClass(rootDiv, "minimizedwindow"); 
        
        // Update the overlay IFRAME as well.
        var overlayIframe = rootDiv._hideWindowedElementsIFrame;
        if(overlayIframe)
        {
            Sys.UI.DomElement.addCssClass(overlayIframe, "minimizedwindowoverlay_" + 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
        if (!this.isCreated()) return;
 
        //Remove the maximize and minimize css classes
        //var rootDiv = this._popupElement;
            
        //Raise event	    
	    var toContinue = this.onCommand("Restore");
	    if (!toContinue) return;          
            
        this._configureMinimizeButton();
        this._configureMaximizeButton();
                  
        //If it was minimized and it was in a minimize zone - then restore to document
	    if (this.isMinimized() && this.get_minimizeZoneID())
	    {
	        this._moveToDocument();
	    }
	    
	    //New - called in close as well
	    this._normalizeWindowRootCss();
                                	
	    //Enable page scrolling
	    this._enablePageScrolling(true);    
    	    	    	    	    		    
        //Make sure it is visible
        this.setVisible(true);

	    //Set size and position
        this._restoreBounds();
 		        		  
        //IE Bug - overlay iframe gets on top of popup itself.  Call setVisible second time to 'fix' this behavior.
        this.setVisible(true);    		        		  
    		        		        	    	
	    //Activate
	    this.setActive(true);
    },
    
    maximize : function()
    {        
        //Check if window was created at all
        if (!this.isCreated()) return;
        
        var toContinue = this.onCommand("Maximize");
	    if (!toContinue) return;
	    
	    //Check whether the Maximize behavior is disabled and the user has double-clicked the titlebar.
	    if(!this.isBehaviorEnabled(Telerik.Web.UI.WindowBehaviors.Maximize)) 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();
	    }
    
        var rootDiv = this._popupElement;
        $telerik.removeCssClasses(rootDiv, ["normalwindow","minimizedwindow"]);
        Sys.UI.DomElement.addCssClass(rootDiv, "maximizedwindow");                    
        
        //Change maximize button to [restore]        
        this._configureMaximizeButton(true);        
        //Make sure the minimize button is properly configured too
        this._configureMinimizeButton();
        
        // Because of restriction zone functionality all sizing and positioning code is moved to _maintainMaximizedSize        
        //rootDiv.style.width = "";
        //rootDiv.style.height = "";
                     
        //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)
        {
            $telerik.removeCssClasses(overlayIframe, ["minimizedwindowoverlay_" + this._skin]);
            this._popupBehavior._handleElementResize();
        } 
                
        if (!this.isActive()) this.setActive(true);
    },
    
    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
        Telerik.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)
	    {
            $telerik.removeCssClasses(rootDiv, ["minimizedwindow","maximizedwindow"]);
            Sys.UI.DomElement.addCssClass(rootDiv, "normalwindow"); 
            
            // Update the overlay IFRAME as well.
            var overlayIframe = rootDiv._hideWindowedElementsIFrame;
            if(overlayIframe)
            {
                $telerik.removeCssClasses(overlayIframe, ["minimizedwindowoverlay_" + this._skin]);
            }      
        }
    },
        
    close : function(callBackFnArg)
    {             
        if (this.isClosed()) return;
        
        //this._normalizeWindowRootCss(); //Move it from here to be after hide
        
        //Hide must be first, as if a window is modal, the modal extender takes care of scrolls as well
        this.hide();                  
	    this._enablePageScrolling(true);
	    
	    //Here, as in _hide we check whether the window is currently maximized
	    this._normalizeWindowRootCss();        
	    	     	
	    	     	
	    //Invoke CallBack Function
	    //1. Careful with changes! CallBack calls Close again, so make sure hide is called first to set the isClosed = true and avoid recursion!
	    //2. Also The MS AJAX framework provides close method with the EVENT argument when closing from the [x]! This was not the case in old RadWindow and should be TAKEN CARE OF!
	    if (null != callBackFnArg && !(callBackFnArg instanceof Sys.UI.DomEvent))
	    {    	    
		    this._invokeDialogCallBackFunction(callBackFnArg);
	    }

        if (this._destroyOnClose)
        {
            this.dispose();
        }
    }, 
    
  
                
    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);
            
            //$telerik.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);
            $telerik.addExternalHandler(childBody, "click", this._onChildPageClickDelegate);                                             
        }
        else 
        {                     
            if (this._onChildPageClickDelegate)
            {
                $telerik.removeExternalHandler(childBody, "click", this._onChildPageClickDelegate);        
                this._onChildPageClickDelegate = null;
            }
            
            //$telerik.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();
	   	
	   	//Do not activate the window - when shown it was set to be the active one.
	   	//If user clicked on another window, the active focus should not be moved just because the page loaded
	    //if (!this.isVisible() || this.isActive() || this.isClosed()) {} //Do nothing
	    //else this.setActive(true);
	    	    								
	    this._registerChildPageHandlers(true);
	    
	    //Execute load event			    
        this.raiseEvent('pageLoad', new Sys.EventArgs());
    }, 


    _onWindowUrlChanging : function()
    {
        //Show the loading sign
        var input = this._getStatusMessageElement();                
        if (input) Sys.UI.DomElement.addCssClass(input, "loading");   
        
        if (!this._showContentDuringLoad) 
	    {	        
		    this._iframe.style.width  = "0px";
		    this._iframe.style.height = "0px";
	    }        
    },
    
    
    _onWindowUrlChanged : function()
    {       
       var input = this._getStatusMessageElement();        
       if (input)
       {
            //Hide the loading sign
            Sys.UI.DomElement.removeCssClass(input, "loading");
       
            //Set the url in the status bar            
            this.set_status(this._navigateUrl);
       }
       
        //Make the iframe visible again if necessary
        if (!this._showContentDuringLoad) 
	    {
            this._iframe.style.width  = "100%";
	        this._iframe.style.height = "100%";
	    }	        
	    
	    //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;
    },
    
    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 corner of the RadWindow titlebar
        /// </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 corner of the RadWindow titlebar
        /// </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;            
        value = this._fixSizeValue(value);
                
        if (this._width != value) {
            this._width = value;            
        }
        
        if (this._popupElement)
        {
            this._deleteStoredBounds();
            //Calling _updatePopupZindex take care of the overlay IFRAME behind the window
            this._popupElement.style.width = this._width;                                                    
            this._updatePopupZindex();
        }
    },
               
    
    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;            
        value = this._fixSizeValue(value);
        
        if (this._height != value) {
            this._height = value;            
        }
        
        if (this._popupElement)
        {   
            this._deleteStoredBounds();                             
            this._updateWindowSize(this._height);
            
            this._updatePopupZindex();
        }        
    },
    
    
    _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="Telerik.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="Telerik.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="Telerik.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="Telerik.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 (Telerik.Web.UI.WindowBehaviors.None == this._behaviors)
        {
            return;
        }
        else
        {               
            var loc = this._getLocalization();                           
            var bhvEnum = Telerik.Web.UI.WindowBehaviors;                
            var buttonsArray = [    //enabled, classname, tooltip,  clickhandler    
                                    [this.isBehaviorEnabled(bhvEnum.Pin),"pinbutton", loc["PinOn"], this.togglePin],
                                    [this.isBehaviorEnabled(bhvEnum.Reload),"reloadbutton",loc["Reload"], this.reload],                                    
                                    [this.isBehaviorEnabled(bhvEnum.Minimize),"minimizebutton",loc["Minimize"], this.minimize],                                    
                                    [this.isBehaviorEnabled(bhvEnum.Maximize),"maximizebutton",loc["Maximize"], this.maximize],                                    
                                    [this.isBehaviorEnabled(bhvEnum.Close),"closebutton",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())
        {         
            //this._show(); 
            //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 loading process, or when it has finished loading.
        /// </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 loading process, or when it has finished loading.
        /// </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 titlebar 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 titlebar 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="Telerik.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="Telerik.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_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);
    },
    
    
     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);
    }
}

Telerik.Web.UI.RadWindow.registerClass('Telerik.Web.UI.RadWindow', Telerik.Web.UI.RadWebControl);
//    getDescriptor : function() {
//        var td = Telerik.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;
//    },


Telerik.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();
}

Telerik.Web.UI.WindowAnimation.prototype = 
{
    None : 0,
    Resize: 1,
    Fade : 2,  
    Slide : 4,
    FlyIn : 8
};
Telerik.Web.UI.WindowAnimation.registerEnum("Telerik.Web.UI.WindowAnimation", false);


Telerik.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();
}

Telerik.Web.UI.WindowMinimizeMode.prototype = 
{
   	SameLocation : 1,	
	MinimizeZone : 2, 
	Default	: 1
};
Telerik.Web.UI.WindowMinimizeMode.registerEnum("Telerik.Web.UI.WindowMinimizeMode", false);



Telerik.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();
}

Telerik.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)
};

Telerik.Web.UI.WindowBehaviors.registerEnum("Telerik.Web.UI.WindowBehaviors", false);


/////////////////////////////////////////////////////////////////////////////
// Global window z-index tracker 
///////////////////////////////////////////////////////////////////////////
//NEW: Updated by RadWindowManager
Telerik.Web.UI.RadWindowUtils._zIndex = 3000;

//Returns a new zIndex, if the provided oldZindex is smaller than the current value, and changes the value
Telerik.Web.UI.RadWindowUtils.get_newZindex = function(oldZindex)
{	
    oldZindex = parseInt(oldZindex);
    if (null == oldZindex || isNaN(oldZindex))
    {
        oldZindex = 0;
    }
        
    if (Telerik.Web.UI.RadWindowUtils._zIndex < oldZindex)
    {
        Telerik.Web.UI.RadWindowUtils._zIndex = oldZindex;
    }
    
    Telerik.Web.UI.RadWindowUtils._zIndex++;
	return Telerik.Web.UI.RadWindowUtils._zIndex;
};


///////////////////////////////////////////////////////////////////////////
// The 'Pin' implementation is here
///////////////////////////////////////////////////////////////////////////
Telerik.Web.UI.RadWindowUtils._pinnedList = {};

Telerik.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()
		                {
		                        Telerik.Web.UI.RadWindowUtils._updatePinnedElementPosition(oWnd); 
		                }, 100);
		
		Telerik.Web.UI.RadWindowUtils._pinnedList[intervalId] = oWnd;
	}
	else
	{		
		var interval = null;
		var oList = Telerik.Web.UI.RadWindowUtils._pinnedList;
		for (var name in oList)
		{
			if (oList[name] == oWnd)
			{
				interval = name;
				break;
			}
		}		
		if (null != interval)
		{
			window.clearInterval(interval);
			Telerik.Web.UI.RadWindowUtils._pinnedList[interval] = null;	
		}		
		oWnd.TopOffset = null;	
		oWnd.LeftOffset = null;
	}
}

Telerik.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);	
};
/* END Telerik.Web.UI.Window.RadWindow.js */
/* START Telerik.Web.UI.Window.RadWindowManager.js */
// - RadWindowManager has the ability to act as factory for RadWindow objects
// - Provides the radwindow, radprompt, radconfirm and radopen methods
// - Stores windows' state
Type.registerNamespace('Telerik.Web.UI');
Type.registerNamespace('Telerik.Web.UI.WindowManager');

//Backward compatibility function - it needs the existance of a RadWindowManager
//It returns the first registered manager on the page
function GetRadWindowManager()
{
    return Telerik.Web.UI.WindowManager.Manager;	
}

window.radalert = function(text, oWidth, oHeight, oTitle)
{	
    var oManager = GetRadWindowManager();
	var oWnd = oManager._getStandardPopup("alert", text);				
	
	if (typeof(oTitle) != 'undefined')
	{
		oWnd.set_title(oTitle)
	}	
	oWnd.setSize(oWidth ? oWidth : 280 , oHeight ? oHeight : 200);	
	
	//Logical problem - show does not center the [modal] window properly, as the page height is calculated as if scrollbars exist, but they are disababled
	oWnd.show();					
	oWnd.center();							
	return oWnd;								
}

window.radconfirm = function (text, callBackFn, oWidth, oHeight, callerObj, oTitle)
{	
    var oManager = GetRadWindowManager();
	var oWnd = oManager._getStandardPopup("confirm", text);				
	
	if (typeof(oTitle) != 'undefined')
	{
		oWnd.set_title(oTitle)
	}	
	oWnd.setSize(oWidth ? oWidth : 280 , oHeight ? oHeight : 200);	
	
	oWnd.callBack = function(result)
	{
	    if (callBackFn) callBackFn(result);
	    oWnd.close();
	    oWnd.callBack = null;
	};
	
	//Logical problem - show does not center the [modal] window properly, as the page height is calculated as if scrollbars exist, but they are disababled	
	oWnd.show();		
	oWnd.center();										
	return oWnd;								
}

window.radprompt = function (text, callBackFn, oWidth, oHeight, callerObj, oTitle, initialValue)
{	
    var oManager = GetRadWindowManager();
    
	var oWnd = oManager._getStandardPopup("prompt", text, initialValue);				
	
	if (typeof(oTitle) != 'undefined')
	{
		oWnd.set_title(oTitle)
	}	
	oWnd.setSize(oWidth ? oWidth : 280 , oHeight ? oHeight : 200);	
	
	oWnd.callBack = function(result)
	{
	    if (callBackFn) callBackFn(result);
	    oWnd.close();
	    oWnd.callBack = null;
	};
	
	//Logical problem - show does not center the [modal] window properly, as the page height is calculated as if scrollbars exist, but they are disababled	
	oWnd.show();		
	oWnd.center();										
	return oWnd;								
}

window.radopen = function(url, name)
{	
    var oManager = GetRadWindowManager();    
    return oManager.open(url, name);        
}	

//-------------------------------------------------------------//
Telerik.Web.UI.RadWindowManager = function(element) 
{   
    /// <exclude/>
    Telerik.Web.UI.RadWindowManager.initializeBase(this, [element]);                    
    this._windowIDs = [];
    this._windows = [];
    this._preserveClientState = false;
    
    //TODO:
    //this._singleNonMinimizedWindow = false;		 
    	    
    //Backward compatibility layer
    this.Open = this.open;    
    this.GetWindowByName = this.getWindowByName;
    this.GetWindowById = this.getWindowById;
    this.GetActiveWindow = this.getActiveWindow;
    this.GetWindowObjects = this.get_windows;
    this.GetWindows = this.get_windows;            
    this.Cascade = this.cascade;        
    this.Tile = this.tile;    
    this.RestoreAll = this.restoreAll;
    this.MaximizeAll = this.maximizeAll;
    this.MinimizeAll = this.minimizeAll;
    this.ShowAll = this.showAll;
    this.CloseAll = this.closeAll;
    this.CloseActiveWindow = this.closeActiveWindow; 
    this.MinimizeActiveWindow = this.minimizeActiveWindow; 
    this.RestoreActiveWindow  = this.restoreActiveWindow;
}

Telerik.Web.UI.RadWindowManager.prototype = 
{        
    //NEW
    get_zIndex : function() 
    {
        /// <exclude />             
        return Telerik.Web.UI.RadWindowUtils._zIndex;
    },
    
    set_zIndex : function(value) 
    {          
        var zIndex = parseInt(value);        
        if (isNaN(value)) return;                         
        Telerik.Web.UI.RadWindowUtils._zIndex = value;        
    },
        
    initialize : function(element)
    {    
        //Set z-Index
        try
        {
            var zIndex = this.get_element().style.zIndex;
            if (zIndex) this.set_zIndex(zIndex);
        } catch(e){;};
                    
        /// <exclude/>                
        //Create a list of window objects                                        
        this._initialize();                     
        
        //Try to register as a page window manager        
        this._registerAsPageManager();        
        
        //Restore state
        //AutoSave - preserve client window state in a cookie		
	    if(this.get_preserveClientState())
	    {
		    this.restoreState();
	    }
    },
        
    dispose : function()
    {         
        /// <exclude/>                
        
        var preserveState = this.get_preserveClientState();
        if (preserveState)
        {
            this.saveState();
        }
        
        this._disposeWindows();             
        this._windows = null;
        Telerik.Web.UI.RadWindowManager.callBaseMethod(this, 'dispose');        
    },
            
    open : function(url, wndName)
    {	    
	    var oWnd = this.getWindowByName(wndName);		
	    if (!oWnd)
	    {		
	        //Backward compatibility - if no wndName is provided, create a new one
	        if (!wndName)
	        {
	            wndName = this.get_id() + this._getUniqueId();
	        }
	        
		    oWnd = this._createWindow(wndName);	
	    }	
	    	    
	    if(url) oWnd.setUrl(url);
    		    
	    oWnd.show();		
	    
	    return oWnd;
    },
    
   
    getActiveWindow : function()
    {
        return Telerik.Web.UI.RadWindowController.get_activeWindow();
    },
            
    getWindowById : function(id)
    {
	    var oArr = this.get_windows();
	    for (var i=0; i < oArr.length; i++)
	    {
		    var oWnd = oArr[i];
		    if (id == oWnd.get_id())
		    {			   
			     return oWnd;
		    }
	    }	
	    return null;	
    },

    getWindowByName : function(name)
    {	
	    var oArr = this.get_windows();
	    if (!oArr) return null;
	    
	    for (var i=0; i < oArr.length; i++)
	    {	
		    var oWnd = oArr[i];
		    if (name == oWnd.get_name())
		    {			     
			     return oWnd;
		    }
	    }	
	    return null;	
    },    
    
    //Called when a window is being disposed on destroy on close = true
    removeWindow : function (oWnd)
    {
        if (!oWnd) return;        
        var w = this.getWindowByName(oWnd.get_name());        
        var windows = this.get_windows();
        if (w) Array.remove(windows, w);
    },
    
    //---------------------------------------------------- Utility methods -------------------------------------------//
    _getUniqueId : function()
    {
        return "" + (new Date() - 100);
    },
    
    _initialize : function()
    {
        //Obtain window objects from the page and add them to the window collection
        var array = this._windowIDs;
        
        for (var i = 0; i < array.length; i++)
        { 
            var windowID = array[i];
            var oWindow = $find(windowID);     

            if (!oWindow) continue;
            
            //Set a reference in the window to the window manager!
            oWindow.set_windowManager(this);            
            
            //Add to window collection
            this._windows[this._windows.length] = oWindow;   
        }
    },
    
     _disposeWindows : function()
    {
       for (var i=0; i < this._windows.length; i++)
       {
            var t = this._windows[i];
            
            //Windows' dispose method will be called second time here - at least for the windows that originally existed on the page!
            //This can potentially lead to problems
            //So, dispose only windows that are cloned from the window manager and did not exists before
            if(t.isCloned()) t.dispose();            
       }
       this._windows = [];
    },
    
     _createWindow : function(wndName, copyEventHandlers)
    {             
        var wnd = this.clone(wndName, copyEventHandlers);
        this._windows[this._windows.length] = wnd;       
        
        //Set a reference in the window to the window manager!
        wnd.set_windowManager(this);                       		    
	    return wnd;
    },
    
    _replaceLocalization : function(searchString, localizationHash)
	{
		var replacer = /##LOC\[(.*?)\]##/;
		while (searchString.match(replacer))
		{
			var replacement = localizationHash[RegExp.$1] ? localizationHash[RegExp.$1] : "";
			searchString = searchString.replace(replacer, replacement)
		}
		return searchString;
	},

    
    _getStandardPopup : function(popupType, popupText, initialContent)
    {                
        //Set a more complex name to the window to FireFox causigng probs when the name of the window <iframe name = alert            
        var newWnd = this._createWindow(popupType + this._getUniqueId(), false);
        
        //Set destroy on close = true
        newWnd.set_destroyOnClose(true);
        
        //Set modal
        newWnd.set_modal(true);
                                
        //Set a content element
        var div = document.getElementById(this.get_id() + "_" + popupType.toLowerCase() + "template");
                
        //STEP 1 - Replace the template {}
        var endString = this._stringFormat(
                             div.innerHTML,     //the original template content
                             newWnd.get_id(),   //the window ID (to get a reference to the window object)
                             popupText,         //the text to be displayed in the popup
                             initialContent ? initialContent : ""   //the initial content (in case of radprompt)                             
                            );
       
        //STEP 2 - Add Localization 
        endString = this._replaceLocalization(endString, Telerik.Web.UI.RadWindowUtils.Localization);
         
        //STEP 3 - Set content
        var newDiv =  document.createElement("DIV");                        
        newDiv.innerHTML = endString;
        
        newWnd.set_behaviors(Telerik.Web.UI.WindowBehaviors.Close);        
        newWnd.set_visibleStatusbar(false);        
        newWnd.set_contentElement(newDiv);
        
        return newWnd;        
    },
    
    _stringFormat : function(text)
     {
        for (var i = 1; i < arguments.length; i++)
        {
            text = text.replace(new RegExp("\\{" + (i - 1) + "\\}", "ig"), arguments[i]);
        }        
        return text;
     },
                       
    
    _registerAsPageManager : function()
    {
        var existingManager = Telerik.Web.UI.WindowManager.Manager;
        var myID = this.get_id();         
        if (existingManager && existingManager.get_id() == myID)
        {                    
            existingManager.dispose();
            Telerik.Web.UI.WindowManager.Manager = null;
        }
        
        if (!Telerik.Web.UI.WindowManager.Manager)
        {
            Telerik.Web.UI.WindowManager.Manager = this;
        }    
    },    
                        
    //---------------------------------------------------- Save state -------------------------------------------//                                                    
    
    //Called by radwindow's dispose as it is called prior to radwindowmanager's dispose    
    saveWindowState : function(oWnd)
    {   
        //Skip if window is not created 			
        if (!oWnd || !oWnd.isCreated()) return;

	    var bounds = oWnd.getWindowBounds();
	    var oVal = 
			       (oWnd.isVisible() || oWnd.isMinimized()) + "@" +					   
			       bounds.width + "@" + 
			       bounds.height + "@" + 
			       bounds.x + "@" + 
			       bounds.y + "@" + 
			       oWnd.isMinimized();					   
	    this._setRadWindowCookie(oWnd.get_id(), oVal);
    },
    
    
    saveState : function()
	{	
		var oWnds = this.get_windows();
		for (i=0; i < oWnds.length; i++)
		{
			var oWnd = oWnds[i];						
			//Save state only of windows that are cloned from RadWindowManager. The framework will take care of the others
		    if (oWnd.isCloned() ) this.saveWindowState(oWnd);
		}
	},
    
    restoreState : function()
    {		
		function restoreWindow(oWnd, oStr)
		{
			var array = oStr.split("@");											
			if (array.length > 1)
			{			
				if ("true" == array[0] && !oWnd.isVisible()) oWnd.show();
				
								
				//If we set timeout to 0 there is problem in IE - it sometimes shows both the minimized window and the window itself				
				//However, if it is > 0 then there is flickering on the screen. 
				//TODO: Hopefully eventually there would be some good workaround for this
				window.setTimeout(function()
				{																												
					if(parseInt(array[1]) > 0) oWnd.set_width(array[1]);
					if(parseInt(array[2]) > 0) oWnd.set_height(array[2]);
					
					//If not visible, do not call moveTo						
					if ("true" == array[0]) oWnd.moveTo(parseInt(array[3]), parseInt(array[4]));			
					if ("true" == array[5])
					{						
						oWnd.minimize();							
					}										
				}, 1);
			}
		};
		
		
		var oWnds = this.get_windows();
				
		for (i=0; i < oWnds.length; i++)
		{
			var oWnd = oWnds[i];
			var oStr = this._getRadWindowCookie(oWnd.get_id());			
									
			if (oStr)
			{
				restoreWindow(oWnd, oStr);
			}			
		}		
    },
    
	_getOnlyCookie : function()
	{
		var sName = "RadWindowCookie";
	
		var aCookie = document.cookie.split("; ");
		for (var i=0; i<aCookie.length; i++)
		{
			var aCrumb = aCookie[i].split("=");
			if (sName == aCrumb[0]) return aCrumb[1];
		}
		return null;
	},

	_setRadWindowCookie : function(sName, sValue)
	{
		sName = "[" + sName + "]";
		var stringToSplit = this._getOnlyCookie();
		var begStr = "";
		var endStr = "";
			
		if (stringToSplit)
		{				
			var array = stringToSplit.split(sName);	
			if (array && array.length > 1)
			{
				begStr = array[0];
				endStr =array[1].substr(array[1].indexOf("#") + 1);
			}
			else endStr = stringToSplit;		
		}

		var today = new Date();
		today.setFullYear(today.getFullYear() + 10);
		document.cookie = "RadWindowCookie" + "=" + (begStr + sName +"-" + sValue + "#" + endStr) + ";path=/;expires=" + today.toUTCString() + ";";
	},

	_getRadWindowCookie : function(sName)
	{	
		var cook = this._getOnlyCookie();
		if (!cook) return;
		
		var sValue = null;
		sName = "[" + sName + "]";

		var index = cook.indexOf(sName);
		if (index >=0)
		{
			var endIndex = index + sName.length + 1;
			sValue = cook.substring(endIndex, cook.indexOf("#", endIndex));
		}
		return sValue;
	},
	
	//---------------------------------------------------- More public API -------------------------------------------//
     cascade : function()
    {
	    var oTop = 40;
	    var oLeft = 40;
    	
	    var oArray = this._getWindowsSortedByZindex();
    	
	    for (var i=0; i<oArray.length; i++)	
	    {
		    var oWnd = oArray[i];
		    if (!oWnd.isClosed() && oWnd.isVisible()) 
		    {			
			    var oRet = oWnd.restore();				
			    oWnd.moveTo(oTop, oLeft);		 
			    
			    oWnd.setActive(true);
			    oTop += 25;
			    oLeft += 25;
		    }
	    }
    },


    tile : function()
    {					
	    var oArray = this._getWindowsSortedByZindex();	
	    //Heuristic - let's say we have a maximum of 5 columns. 
	    //Calculate the smallest number of rows that you need to fit the windows
	    var oLen = 0;
	    //Only the visible windows should be used
	    for (var i=0; i < oArray.length; i++)
	    {
		    var oWin = oArray[i];
    		
		    if (!oWin.isClosed() && oWin.isVisible()) 
		    {
			    oLen++;
		    }
	    }
    	    	    	
	    var oMaxCols = 5;	
	    var oCols = 0;
	    var oRows = 1;
    		
	    if (oLen <= oMaxCols)
	    {
		     oCols = oLen;
	    }
	    else
	    {
		    var i = 2;					
		    //Try to get a heuristic by multiplying the (oLength * i) > (oMaxCols i-1)
		    while ((oLen * i) < (oMaxCols * (i+1)))
		    {
			    i++;			
			    if (i > 6) break;//In case something goes wrong
		    }
		    oRows = i;	
		    //Calculate cols
		    oCols = Math.ceil(oLen / oRows);
	    }
    	
    	
	    var oScreen = $telerik.getClientBounds();
    	
	    //See to what two-dimentional grid it correspends
	    var oWinWidth  = Math.floor(oScreen.width / oCols);
	    var oWinHeight = Math.floor(oScreen.height / oRows);    		    
	    var left = document.documentElement.scrollLeft || document.body.scrollLeft;
		var top = document.documentElement.scrollTop || document.body.scrollTop;   
	        	
	    var tiledWindowCount = 0;			
	    for (var i = 0; i < oArray.length; i++)
	    {	
		    var oWin = oArray[i];				
		    if (!oWin.isClosed() && oWin.isVisible()) 
		    {	
			    tiledWindowCount++;
			    if ( (tiledWindowCount-1) % (oCols) == 0 && tiledWindowCount > oCols)
			    {
				    top += oWinHeight;				    
				    left =  document.documentElement.scrollLeft || document.body.scrollLeft;
			    }		
    				
			    oWin.restore();		
			    oWin.moveTo(left, top);
			    oWin.setSize(oWinWidth, oWinHeight);		
			    left += oWinWidth;
		    }
	    }
    },
    
    closeActiveWindow : function()
    {
	    this._executeActiveWindow("close");
    },

    minimizeActiveWindow : function()
    {
	    this._executeActiveWindow("minimize");
    },

    restoreActiveWindow : function()
    {
	    this._executeActiveWindow("restore");
    },

    closeAll : function()
    {
	    this._executeAll("close");	
    },

    showAll : function()
    {
	    this._executeAll("show");
    },

    minimizeAll : function()
    {
	    this._executeAll("minimize");
    },

    maximizeAll : function()
    {
	    this._executeAll("maximize");
    },

    restoreAll : function()
    {
	    this._executeAll("restore");
    },
    
    
    _getWindowsSortedByZindex : function()
    {
	    var oArray = this._windows.concat([]);//Clone the original array
	    var oSortFun = function(oWin1, oWin2)
	    {	  	  
	        var z1 = oWin1.get_zindex();
	        var z2 = oWin2.get_zindex();
	        
	        if (z1 == z2) return 0;		
		    return (z1 < z2 ? -1 : 1);				
	    };	
    	
	    return oArray.sort(oSortFun);
    },
    
    _executeAll : function(fnName) 
    {	
	    if (!this._windows) return;
    	
	    var oArray = this._windows.concat([]);
	    for (var i=0; i < oArray.length; i++)	
	    {
		    oArray[i][fnName]();
	    }
    },

    _executeActiveWindow : function(cmdName)
    {		
        var activeWindow = this.getActiveWindow();
	    if (activeWindow && "function" == typeof(activeWindow[cmdName]))
	    {		
		    activeWindow[cmdName]();
	    }
    },
    
    //---------------------------------------------------- Properties methods -------------------------------------------//
    get_preserveClientState : function()    
    {
        /// <summary>
        /// Gets the value indicating whether window objects' state (size, location, behavior) will be persisted in a client cookie to restore state over page postbacks.
        /// </summary>
        /// <value type="bool">
        /// The current setting
        /// </value>
        return this._preserveClientState;
    },
        
    set_preserveClientState : function(value)
    {
        /// <summary>
        /// Sets a value indicating whether window  objects' state (size, location, behavior) will be persisted in a client cookie to restore state over page postbacks.
        /// </summary>
        /// <param name="value" type="bool">
        /// The new value
        /// </param>  
        
        //Set the value          
        if (this._preserveClientState != value)
        {          
            this._preserveClientState = value;            
        }              
    },
    
    
    //Called by the server to initialize the WindowManager              
    set_windowControls : function(value)
    {    
        /// <exclude/>              
        //It must come in the form of strings
        this._windowIDs = eval(value);            
                
        //Dispose all [old] windows (if any);
        this._disposeWindows();                        
    },                   
    
    //Needed by the framework to propery call the set_windowControls!
    get_windowControls : function()
    {
        /// <exclude/>        
    },
    
    get_windows : function()
    {
        return this._windows;
    }       
}    

/*
//TODO, Related to _singleNonMinimizedWindow property
MinimizeInactiveWindows = function()
{
	var activeWnd = this.ActiveWindow;	
	var theArray = this._windows;
	var oLength = theArray.length;		
	for (var i=0; i < oLength; i++)
	{	
		var oWin = theArray[i];
		if (oWin != activeWnd) oWin.Minimize();		
		//else oWin.Restore();
	}		
},
*/
Telerik.Web.UI.RadWindowManager.registerClass('Telerik.Web.UI.RadWindowManager', Telerik.Web.UI.RadWindow);

/* END Telerik.Web.UI.Window.RadWindowManager.js */
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();
(function() {var fn = function() {$get('ScriptManager_HiddenField').value += ';;Telerik.Web.UI, Version=2008.1.619.0, Culture=neutral, PublicKeyToken=29ac1a93ec063d92:it-IT:f030301f-40d4-4f92-b5a2-0122b989382c:393f5085:6ea64e21:62a7b334:4e368cee:730ff4ad:418b151e:80c4ad6d:527acb41';Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);})();
