/* 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.FormDecorator.RadFormDecorator.js */
//In Mozilla there is no insertAdjacentElement
if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement)
{
    HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode)
	{
		switch (where)
		{
		    case 'beforeBegin':
			    this.parentNode.insertBefore(parsedNode, this)
			    break;
		    case 'afterBegin':
			    this.insertBefore(parsedNode, this.firstChild);
			    break;
		    case 'beforeEnd':
			    this.appendChild(parsedNode);
			    break;
		    case 'afterEnd':
			    if (this.nextSibling) this.parentNode.insertBefore(parsedNode, this.nextSibling);
			    else this.parentNode.appendChild(parsedNode);
			    break;
		}
	};
}

       
Type.registerNamespace('Telerik.Web.UI');

Telerik.Web.UI.RadFormDecorator = function(element) {
    /// <summary>
    /// The FormDecorator control provides skinning for browser checkboxes,buttons and radiobuttons.
    /// </summary>
    /// <param name="element" type="Sys.UI.DomElement" domElement="true">
    /// DOM element associated with the behavior
    /// </param>
    Telerik.Web.UI.RadFormDecorator.initializeBase(this, [element]);           
    
    //Properties
    this._skin = "Default";
    this._formDecoratorCssUrl = "";
    this._decorationZoneID = null;                              
    this._decoratedControls = Telerik.Web.UI.FormDecoratorDecoratedControls.All;                                      
}

//NEW: Support for defining cross-browser ability for the decorator to "pick up"
Telerik.Web.UI.RadFormDecorator._globalDecorateInput = function(val) 
{ 
        //See if next sibling is of type label and update it
        var nextSibling = this.nextSibling;
        if (nextSibling && nextSibling.tagName == "LABEL")
        {            
            var classToRemove = val ? "radfdCheckboxUnchecked" : "radfdCheckboxChecked";            
            var classToAdd = val ? "radfdCheckboxChecked" : "radfdCheckboxUnchecked";            
            Sys.UI.DomElement.removeCssClass(nextSibling, classToRemove);
            Sys.UI.DomElement.addCssClass(nextSibling, classToAdd);                        
        }  
        //Not needed as we make a "passive" picking up of the value already being set properly
        //Will allow in the future to override the setAttribute method as well in case someone needs it                      
        //this.setAttribute("checked", val);                             
};


if (typeof(HTMLInputElement) != "undefined")
{             
    var d = HTMLInputElement.prototype;        
    if (d.__defineSetter__)
    {
        //Moz + Opera 9.5{    
        d.__defineSetter__("checked", Telerik.Web.UI.RadFormDecorator._globalDecorateInput);
        //SAFARI
        if ($telerik.isSafari) d.__defineSetter__("safarichecked", Telerik.Web.UI.RadFormDecorator._globalDecorateInput);
    }
}


Telerik.Web.UI.RadFormDecorator.prototype = {
    
    //###########---------------- PUBLIC API ---------------------##################//                 
    initialize : function() 
    {      
        this._showHiddenInputs();
    
        // decorate
        var zoneID = this.get_decorationZoneID();
        this.decorate(zoneID ? $get(zoneID) : null); //null will cause all to be decorated. added for clarity
       
       //Attach handler to listen for partial AJAX updates
        //It must be executed with a timeout, so as to handle the scenario when the formdecorator itself is initialized as a result of ajax request
        //and to prevent its page_load handler to [mistakenly] execute a second round of initialization.        
        window.setTimeout(Function.createDelegate(this, function()
        {
            this._trackPageUpdates();          
        }), 0);

    },
          	
//=====================================================================================================//    
    _showHiddenInputs : function()
    {
         var sheetURL = this.get_formDecoratorCssUrl();
        var styleSheet = null;

        for (var i=0; i < document.styleSheets.length; i++)
        {
            //try
            {
                var sheet = document.styleSheets[i];
                var cssHref = sheet.href; //Can be null in Opera and Safari!
        
                if (cssHref && cssHref.indexOf(sheetURL) > -1)
                {                    
                    styleSheet = sheet;
                    break;
                }
            }
           // catch (e){;}
        }
               
       if (styleSheet.deleteRule) styleSheet.deleteRule(0);
       else if (styleSheet.removeRule) styleSheet.removeRule(0);
    },
    
    
    decorate : function(rootElement)
    {             
       //Function was modified to execute against UpdatePanel requests
       //The root element is an UpdatePanel to be re-initialized, and the test function was added in the case 
       //when there exists a list of target controls and each of them needs to be tested whether reinitialization is needed.
       if (!rootElement) rootElement = $telerik.quirksMode ? document.body : document.documentElement;             
                
        Sys.UI.DomElement.addCssClass(rootElement, "radfd_" + this._skin);
        
        //TODO: Support for input and textarea
        
        //Support for scrollbars
        if((this._decoratedControls & 8) > 0)
		{
            Sys.UI.DomElement.addCssClass(rootElement, "radfd_ScrollBars");
        }
        		
		if((this._decoratedControls & 1) > 0)
		{
		    this.decorateInputs("checkbox", rootElement);
		}
		if((this._decoratedControls & 2) > 0)
		{
		    this.decorateInputs("radio", rootElement);
		}
		if((this._decoratedControls & 4) > 0)
		{
		    this.decorateButtons(rootElement);
		}                             
    },
    
	
     _trackPageUpdates : function()
    {                                                                    
        this._pageLoadedHandler = Function.createDelegate(this, function(sender, args) 
        {            
           //Event is triggered on page load as well. However, at this point there are no updated panels. Thus, there would be updated panels only after AJAX request
           var updatedPanels = args.get_panelsUpdated();
           if (!updatedPanels) return;

           for (var i=0; i < updatedPanels.length; i++) 
           {        
                var updatePanel = updatedPanels[i];                        
                
                var zoneID = this.get_decorationZoneID();
                if (zoneID) 
                {                                                                                
                    var zone = $get(zoneID);
                    if (zone)
                    {
                        var result = $telerik.isDescendantOrSelf(updatePanel, zone);
                        if (result)
                        {
                            this.decorate(zone);
                        }
                        else if ($telerik.isDescendantOrSelf(zone, updatePanel))
                        {
                            this.decorate(updatePanel);
                        }
                    }                                        
                }                                   
                else this.decorate(updatePanel);
           }  
       });              
       
       //Subscribe to be notified when the AJAX request ends
       var prm = Sys.WebForms.PageRequestManager.getInstance();
       prm.add_pageLoaded(this._pageLoadedHandler);                           
    },
    
    
//==================================================================================================//    
    dispose : function() 
    {                    
        //TODO: Add code to clear event handlers
                    
       // ---
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.remove_pageLoaded(this._pageLoadedHandler);        
        this._pageLoadedHandler = null;
        Telerik.Web.UI.RadFormDecorator.callBaseMethod(this, 'dispose'); 
        // ---
    },
    
                     
    saveClientState: function()
    {		
        /// <exclude/>
		var propsToSerialize = [""];
		var state = {};
         
		for (var i=0; i < propsToSerialize.length; i ++) {
			//state[propsToSerialize[i]] = this["get_" + propsToSerialize[i]]();
		}         
        return Sys.Serialization.JavaScriptSerializer.serialize(state);
    },
	
	
	decorateButtons : function(rootElement)
	{
		this.decorateButtonsByTagName('input', rootElement);
		this.decorateButtonsByTagName('button', rootElement);
	},
	
	decorateButtonsByTagName : function(tagName, rootElement)
	{
	   if (!rootElement) rootElement = document.body;
	   
	    var realInputButtons = rootElement.getElementsByTagName(tagName);
	    var numberInputs = realInputButtons.length;
		
		for (i = 0; i < numberInputs; i ++)
		{
			var inputButton = realInputButtons[i];						
			var inputType = inputButton.getAttribute('type');
												
			if(tagName == "button" || (inputType == 'submit' || inputType == 'reset' || inputType == 'button'))
			{
				var buttonValue = (tagName == "button" ? inputButton.innerHTML : inputButton.value);
			    var skinnedButton = this.getSkinnedButton(inputButton, buttonValue);				
			    
				if (skinnedButton)
		        {
		            inputButton.className = 'radfdRealInputButton';
		            inputButton.insertAdjacentElement('beforeBegin', skinnedButton);
		        }
			}
		}
	},
	
	_getButtonRootElement : function(e)
	{ 
	    e = e ? e : window.event;
        var element = e.srcElement ? e.srcElement : e.target;
        //We go up in parent hyerarchy until we hit a A tag
        var parent = element;
        
        while (parent.tagName != "A")
        {
            parent = parent.parentNode;
        }
        
        return parent;
	},
	
	buttonClickHandler : function(e)	
    {
        var parent = this._getButtonRootElement(e);
        //We assume that the next sibling of target is the orignal button, 
        //as skinned button was added with insertAdjacentElement beforeBegin
        var button = parent.nextSibling;
        button.click();
        return false;
    },
    
     buttonMouseOutHandler : function(e)	
    {
        var parent = this._getButtonRootElement(e);        
        if (parent) Sys.UI.DomElement.removeCssClass(parent, "radfd_Clicked");        
    },
    
    buttonMouseUpHandler : function(e)	
    {
        var parent = this._getButtonRootElement(e);
        if (parent) Sys.UI.DomElement.removeCssClass(parent, "radfd_Clicked");
    },
    
    buttonMouseDownHandler : function(e)	
    {
        var parent = this._getButtonRootElement(e);
        if (parent) Sys.UI.DomElement.addCssClass(parent, "radfd_Clicked");
    },
	
	_setStatus : function()
	{ 
	    window.status = '';return true; 
	},
			
	getSkinnedButton : function(inputButton, value)
	{					
		var skinnedbutton = document.createElement('a');
		skinnedbutton.setAttribute('href', 'javascript:void(0)');
				
		skinnedbutton.onmouseover = this._setStatus;
		skinnedbutton.onmouseout = this._setStatus;
				
		skinnedbutton.setAttribute('id', 'Skinned' + inputButton.id);
		skinnedbutton.setAttribute('title', value);
		skinnedbutton.className = 'radfdSkinnedFormButton radfd_' + this._skin;
					
		$addHandler(skinnedbutton, "click", Function.createDelegate(this, this.buttonClickHandler));
		
		//NEW
		$addHandler(skinnedbutton, "mousedown", Function.createDelegate(this, this.buttonMouseDownHandler));
		$addHandler(skinnedbutton, "mouseup", Function.createDelegate(this, this.buttonMouseUpHandler));
		$addHandler(skinnedbutton, "mouseout", Function.createDelegate(this, this.buttonMouseOutHandler));
		
		if(inputButton.offsetWidth == '0')
		{
		    skinnedbutton.style.width = 'auto';
		}
		else
		{
		    skinnedbutton.style.width = inputButton.offsetWidth + 'px';
		}
		skinnedbutton.innerHTML = '<span class="radfdOuterSpan"><span class="radfdInnerSpan">' + value + '</span></span>';
		
	    if(inputButton.disabled)
	    {
	        skinnedbutton.className += " " + "radfdInputDisabled";
	    } 
		
	    return skinnedbutton;	
	},
	
	decorateInputs: function(type, rootElement)
	{
	    if (!rootElement) rootElement = document.body;
	
	    var allInputs = rootElement.getElementsByTagName("input");
		for (var i=0; i < allInputs.length; i++)
		{
		    var currInput = allInputs[i];
		    if(currInput.type == type)
		    {
		        var label = currInput.nextSibling;
		        if(label == null || label.tagName == null || label.tagName.toLowerCase() != "label")
		        {
		            label = this.addLabel(currInput);
		        }
		        this.configureLabel(label, currInput);		        		        
		        
		        //OLD
		        //$addHandler(currInput, "click", Function.createDelegate(this, this.inputClickHandler));	
		       		        
		        //NEW
		        if (currInput.type == "checkbox" && $telerik.isIE)
		        {
		           $addHandler(currInput, "propertychange", Function.createDelegate(this, this.inputPropertyClickHandler));	       		       		           		         
		        }
		        else
		        {
		            $addHandler(currInput, "click", Function.createDelegate(this, this.inputClickHandler));	
		        }	    	        
		    }
		}
	},
	
	
	inputPropertyClickHandler : function(e)	
    {    
       var fakeEvent = e;
        var e = e.rawEvent;//e is a fake MS AJAX event wrapper that misses important info!
       if (!e) return; 
       if (e.propertyName == "checked")
       {
            var element = fakeEvent.target;                                                                              
            this.inputClickHandler(fakeEvent);                                                                                                
       }         
    },

    inputClickHandler : function(e)	
    {
        e = e ? e : window.event;
        var element = e.srcElement ? e.srcElement : e.target;
        if(element.type == "radio")
        {
            this.setAllRadiosUnchecked(element.name);
        }
        if(!element.disabled)
        {  
            this.configureLabel(element.myLabel, element);
        }
    },
	
	addLabel : function(input)
	{
	    var label = document.createElement("label");
	    
	    var id = input.id;
	    //TEKI: RadTreeView checkboxes have no ID, so we need to add one
	    if (!id)
	    {
	        id = this._getUniqueID();
	        input.id = id;
	    }
	    
	    label.htmlFor = id;
	    label.setAttribute("unselectable", "on");
	    input.insertAdjacentElement("afterEnd", label)
	    	    	    	    	  	    	                         
	    return label;
	},
	
	configureLabel : function(label, input)
	{
	    input.className = this._skin + " input";
	    
	    if (!input.myLabel) input.myLabel = label;
	    label.className = this._skin;
	    // check if the text attribute is missing a value (i.e. the innerHTML of the <label> is null) and add &nbsp; so as the label becomes clickable
	    if(label.innerHTML == "")
	    {
	        label.innerHTML = "&nbsp;";
	    }
	    if(input.disabled)
	    {
	        label.className += " " + "radfdInputDisabled";
	    } 
	    var type = input.type;
	    var inputName = type.charAt(0).toUpperCase() + type.substring(1);
	    	    
	    if(input.checked)
	    {
	        label.className += " radfd" + inputName + "Checked";
	    } 
	    else
	    {
	        label.className += " radfd" + inputName + "Unchecked";
	    }
	},
	
	
	_getUniqueID : function()
	{	       
        if (!this._idCounter) this._idCounter = 1;
        this._idCounter++;
        return (this.get_id() + (new Date()- 100) +  this._idCounter);       
	},
	
	
	setAllRadiosUnchecked : function(groupName)
	{
	    var allInputs = document.getElementsByTagName("input");
		for (var i=0; i<allInputs.length; i++)
		{
		    if(allInputs[i].type == "radio" && allInputs[i].name == groupName && !allInputs[i].disabled)
		    {
		        allInputs[i].myLabel.className = this._skin + " radfdRadioUnchecked";
		    }
		}
	},
	
	
	//======================== PROPERTIES==========================================================//		
	
	//NEW- Needed to eliminate flicker when browser controls are replaced with decorated controls
	get_formDecoratorCssUrl : function()
    {
        /// <exclude/>
        return this._formDecoratorCssUrl;
    },
    
    set_formDecoratorCssUrl : function(value)
    {
        /// <exclude/>        
        this._formDecoratorCssUrl = value;        
    },
	
	
	get_decoratedControls : function()
    {
        /// <exclude/>
        return this._decoratedControls;
    },
    
    set_decoratedControls : function(value)
    {
        /// <exclude/>
        if (this._decoratedControls != value) 
        {
           this._decoratedControls = value;  		   
        }
    },
    
    get_decorationZoneID: function()     
    {
        /// <summary>
        // Gets the id (ClientID if a runat=server is used) of a html element whose children will be decorate
        /// </summary>
        /// <value type="Sys.UI.DomElement">
        /// The id of the html element 
        /// </value>
        return this._decorationZoneID;
    },
    
    set_decorationZoneID : function(value) 
    {
        /// <summary>
        // Sets the id (ClientID if a runat=server is used) of a html element whose children will be decorate
        /// </summary>
        /// <param name="value" type="Sys.UI.DomElement">
        /// The id of the html element serving
        /// </param>
        if (this._decorationZoneID != value) { 
            this._decorationZoneID = value;            
        }
    },
    
    
	
	get_skin : function()
    {
        /// <exclude/>
        return this._skin;
    },
    
    set_skin : function(value)
    {
        /// <exclude/>
        if (this._skin != value) 
        {
           this._skin = value;  		   
        }
    }
};

Telerik.Web.UI.RadFormDecorator.registerClass('Telerik.Web.UI.RadFormDecorator', Telerik.Web.UI.RadWebControl);


Telerik.Web.UI.FormDecoratorDecoratedControls = function() {
    /// <summary>
    /// Used to set the Animation property
    /// </summary>    
    /// <field name="None" type="Number" integer="true" />    
    /// <field name="CheckBoxes" type="Number" integer="true" />
    /// <field name="RadioButtons" type="Number" integer="true" />
    /// <field name="Buttons" type="Number" integer="true" />
    /// <field name="Scrollbars" type="Number" integer="true" />
    /// <field name="All" type="Number" integer="true" />
    throw Error.invalidOperation();
}

Telerik.Web.UI.FormDecoratorDecoratedControls.prototype = 
{
    None : 0,
    CheckBoxes : 1,
	RadioButtons : 2,
    Buttons : 4,
    Scrollbars : 8,
    All : (1 | 2| 4 | 8)
};
Telerik.Web.UI.FormDecoratorDecoratedControls.registerEnum("Telerik.Web.UI.FormDecoratorDecoratedControls", false);

/* END Telerik.Web.UI.FormDecorator.RadFormDecorator.js */
/* START Telerik.Web.UI.Common.Navigation.ChangeLog.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.ChangeLog = function ()
{
	this._opCodeInsert = 1;
	this._opCodeDelete = 2;
	this._opCodeClear = 3;
	this._opCodePropertyChanged = 4;
	
	this._logEntries = null;
}

Telerik.Web.UI.ChangeLog.prototype =
{
	initialize : function ()
	{
		this._logEntries = [];
		this._serializedEntries = null;
	},
	
	logInsert : function (item)
	{
		var logEntry = {};
		logEntry.Type = this._opCodeInsert;
		logEntry.Index = item._getHierarchicalIndex();
		logEntry.Data = item._getData();
		
		Array.add(this._logEntries, logEntry);
	},
	
	logDelete : function (item)
	{
		var logEntry = {};
		logEntry.Type = this._opCodeDelete;
		logEntry.Index = item._getHierarchicalIndex();
		
		Array.add(this._logEntries, logEntry);
	},
	
	logClear : function (item)
	{
		var logEntry = {};
		logEntry.Type = this._opCodeClear;
		
		if (item._getHierarchicalIndex)
		{
			logEntry.Index = item._getHierarchicalIndex();
		}
		
		Array.add(this._logEntries, logEntry);
	},
	
	logPropertyChanged : function (item, propertyName, propertyValue)
	{
		var logEntry = {};
		logEntry.Type = this._opCodePropertyChanged;
		logEntry.Index = item._getHierarchicalIndex();
		logEntry.Data = {};
		logEntry.Data[propertyName] = propertyValue;
		
		Array.add(this._logEntries, logEntry);
	},
	
	serialize : function ()
	{	
		if(this._logEntries.length == 0)
		{
			if(this._serializedEntries == null)
			{
				return "[]";
			}

			return this._serializedEntries;
		}
	
		var newEntries = Sys.Serialization.JavaScriptSerializer.serialize(this._logEntries);		
	
		if(this._serializedEntries == null)
		{
			this._serializedEntries = newEntries;
		}
		else
		{
			this._serializedEntries = this._serializedEntries.substring(0, this._serializedEntries.length - 1) + ',' + newEntries.substring(1);
		}
		
		this._logEntries = [];
		
		return this._serializedEntries;
	}	
}

Telerik.Web.UI.ChangeLog.registerClass("Telerik.Web.UI.ChangeLog");


/* END Telerik.Web.UI.Common.Navigation.ChangeLog.js */
/* START Telerik.Web.UI.Common.Navigation.EventMap.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.EventMap = function ()
{
	this._owner = null;
	this._element = null;
	this._eventMap = {};
	this._onDomEventDelegate = null;
	this._browserHandlers = {};
}

Telerik.Web.UI.EventMap.prototype = 
{	
	initialize : function (owner, element)
	{
		this._owner = owner;
		if (!element)
			element = this._owner.get_element();
		this._element = element;
	},

	dispose : function ()
	{
		if (this._onDomEventDelegate)
		{
			for (var eventName in this._eventMap)
			{
				if (this._shouldUseEventCapture(eventName))
				{
					var browserHandler = this._browserHandlers[eventName];
					this._element.removeEventListener(eventName, browserHandler, true);
				}
				else
				{
					$removeHandler(this._element, eventName, this._onDomEventDelegate);
				}
			}
			
			this._onDomEventDelegate = null;
		}
	},
	
	// Public methods
	addHandlerForClassName : function (eventName, className, handler)
	{
		if (typeof(this._eventMap[eventName]) == "undefined")
		{
			this._eventMap[eventName] = {};
			
			if (this._shouldUseEventCapture(eventName))
			{
				var domEventHandler = this._getDomEventDelegate();
				var element = this._element;
				var browserHandler = function(e) { return domEventHandler.call(element, new Sys.UI.DomEvent(e)); }
				this._browserHandlers[eventName] = browserHandler;
				element.addEventListener(eventName, browserHandler, true);
			}
			else
			{
				$addHandler(this._element, eventName, this._getDomEventDelegate());
			}
		}
		
		var eventHandlers = this._eventMap[eventName];
		eventHandlers[className] = handler;
	},
	
	// Private methods
	_onDomEvent: function(e)
	{
		var dispatchees = this._eventMap[e.type];
		if (!dispatchees) 
			return;
		
		var target = e.target;
		while (target && target.nodeType !== 9) 
		{
			var className = target.className;
			var spaceIndex = className.indexOf(' ');
			
			if (spaceIndex >= 0) 
				className = className.substr(0, spaceIndex);
			
			var dispatchee = dispatchees[className];
			
			if (dispatchee) 
			{
				this._fillEventFields(e, target);
				if (dispatchee.call(this._owner, e) != true) 
				{
					if (!target.parentNode) 
					{
						// The target was removed from the DOM in the event handler.
						// Event propagation in this case causes "Unspecified error" in IE6.
						e.stopPropagation();
					}
					
					return;
				}
			}
			
			if (target == this._element) 
			{
				return;
			}
			
			target = target.parentNode;			
		}
	},
	
	_fillEventFields : function (e, currentTarget)
	{
		e.eventMapTarget = currentTarget;
		if (e.rawEvent.relatedTarget)
		{
			e.eventMapRelatedTarget = e.rawEvent.relatedTarget;
		}
		else
		{
			if (e.type == "mouseover")
			{
				e.eventMapRelatedTarget = e.rawEvent.fromElement;
			}
			else
			{	
				e.eventMapRelatedTarget = e.rawEvent.toElement;
			}
		}
		
		if (!e.eventMapRelatedTarget)
			return;
		
		try 
		{
			// Fix for FireFox "_moz_editor_bogus_node" problem.
			// Happens on mouseout and mouseover when the related target is an input element.
			// For some reason input elements have an "anonymous" div as a child:
			// <div class="anonymous-div" style="white-space: pre;" _moz_editor_bogus_node="TRUE" _moz_dirty="">
			// Accessing *any* attribute of such a node will throw "permission denied" error.
			var className = e.eventMapRelatedTarget.className;
		} 
		catch (ex) 
		{
			// Skip to the parent element.
			e.eventMapRelatedTarget = this._element;
		}		
	},
	
	_shouldUseEventCapture : function(eventName)
	{
		return (eventName == "blur" || eventName == "focus") && $telerik.isFirefox && Sys.Browser.version >= 3;
	},
	
	_getDomEventDelegate : function ()
	{
		if (!this._onDomEventDelegate)
		{
			this._onDomEventDelegate = Function.createDelegate(this, this._onDomEvent);
		}
		
		return this._onDomEventDelegate;
	}
}

Telerik.Web.UI.EventMap.registerClass('Telerik.Web.UI.EventMap');


/* END Telerik.Web.UI.Common.Navigation.EventMap.js */
/* START Telerik.Web.UI.Common.Navigation.AttributeCollection.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.AttributeCollection = function (owner)
{
	this._owner = owner;
	this._data = {};
	this._keys = [];
}

Telerik.Web.UI.AttributeCollection.prototype = 
{
	getAttribute : function (key)
	{
		return this._data[key];
	},
	
	setAttribute : function (key, value)
	{
		this._add(key, value);
		
		var attributeEntry = {};
		attributeEntry[key] = value;

		this._owner._notifyPropertyChanged("attributes", attributeEntry);
	},
	
	_add : function (key, value)
	{
		if (Array.indexOf(this._keys, key) < 0)
			Array.add(this._keys, key);
			
		this._data[key] = value;
	},
	
	removeAttribute : function (key)
	{
		Array.remove(this._keys, key);
		
		delete this._data[key];
	},
	
	_load : function (json)
	{
		for (var key in json)
			this._add(key, json[key]);
	},
	
	get_count : function ()
	{
		return this._keys.length;
	}
}

Telerik.Web.UI.AttributeCollection.registerClass('Telerik.Web.UI.AttributeCollection');
/* END Telerik.Web.UI.Common.Navigation.AttributeCollection.js */
/* START Telerik.Web.UI.Common.Animation.Animations.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.Animation');

// Create an alias for the namespace to save 25 chars each time it's used since
// this is a very long script and will take awhile to download
var $TWA = Telerik.Web.Animation;

$TWA.registerAnimation = function(name, type) {
    /// <summary>
    /// Register an animation with the AJAX Control Toolkit animation framework. This serves a dual purpose:
    /// 1) to add standard utility methods to the animation type (such as a <code>play</code> method that creates
    /// an animation, plays it, and disposes it when the animation is over), and 2) to associate a name with the
    /// type that will be used when creating animations from a JSON description.  This method can also be called
    /// by other animation libraries to seamlessly interoperate with the AJAX Control Toolkit's animation
    /// framework.
    /// </summary>
    /// <param name="name" type="String">
    /// Name of the animation that will be used as the XML tag name in the XML animation description.  It
    /// should be a valid XML tag (i.e. an alpha-numeric sequence with no spaces, special characters, etc.).
    /// </param>
    /// <param name="type" type="Type">
    /// The type of the new animation must inherit from <see cref="Telerik.Web.Animation.Animation" />.
    /// </param>
    /// <returns />

    // Make sure the type inherits from Telerik.Web.Animation.Animation
    if (type && ((type === $TWA.Animation) || (type.inheritsFrom && type.inheritsFrom($TWA.Animation)))) {
        // We'll store the animation name/type mapping in a "static" object off of
        // Telerik.Web.Animation.  If this __animations object hasn't been
        // created yet, demand create it on the first registration.
        if (!$TWA.__animations) {
            $TWA.__animations = { };
        }
        
        // Add the current type to the collection of animations
        $TWA.__animations[name.toLowerCase()] = type;
        
        // Add a play function that will make it very easy to create, play, and
        // dispose of an animation.  This is effectively a "static" function on
        // each animation and will take the same parameters as that animation's
        // constructor.
        type.play = function() {
            /// <summary>
            /// Create an animation, play it immediately, and dispose it when finished.
            /// </summary>
            /// <param parameterArray="true" elementType="Object">
            /// The play function takes the same parameters as the type's constructor
            /// </param>
            /// <returns />
        
            // Create and initialize a new animation of the right type and pass in
            // any arguments given to the play function
            var animation = new type();
            type.apply(animation, arguments);
            animation.initialize();
            
            // Add an event handler to dispose the animation when it's finished
            var handler = Function.createDelegate(animation,
                function() {
                    /// <summary>
                    /// Dispose the animation after playing
                    /// </summary>
                    /// <returns />
                    animation.remove_ended(handler);
                    handler = null;
                    animation.dispose();
                });
            animation.add_ended(handler);
            
            // Once the animation has been created and initialized, play it and
            // dispose it as soon as it's finished
            animation.play();            
        }
    } else {
        // Raise an error if someone registers an animation that doesn't inherit
        // from our base Animation class
        throw Error.argumentType('type', type, $TWA.Animation, "Telerik.Web.Animation.registerAnimation can only register types that inherit from Telerik.Web.Animation.Animation");
    }
}

// In the Xml comments for each of the animations below, there is a special <animation /> tag
// that describes how the animation is referenced from a generic XML animation description


$TWA.Animation = function(target, duration, fps) {
    /// <summary>
    /// <code>Animation</code> is an abstract base class used as a starting point for all the other animations.
    /// It provides the basic mechanics for the animation (playing, pausing, stopping, timing, etc.)
    /// and leaves the actual animation to be done in the abstract methods <code>getAnimatedValue</code>
    /// and <code>setValue</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <field name="DynamicProperties" type="Object">
    /// The DynamicProperties collection is used to associate JavaScript expressions with
    /// properties.  The expressions are evaluated just before the animation is played
    /// everytime (in the base onStart method).  The object itself maps strings with the
    /// names of property setters (like "set_verticalOffset") to JavaScript expressions
    /// (like "$find('MyBehavior').get_element().offsetHeight").  Note specifically that
    /// the dynamic properties are JavaScript expressions and not abitrary statements (i.e.
    /// you can't include things like "return foo;"), although you can include anything
    /// inside an anonymous function definition that you immediately invoke (i.e.,
    /// "(function() { return foo; })()").  A dynamic property can be set in the generic
    /// XML animation description by appending Script onto any legitimate property name
    /// (for example, instead of Height="70" we could use
    /// HeightScript="$find('MyBehavior').get_element().offsetHeight").  Any exceptions
    /// raised when setting dynamic properties (including both JavaScript evaluation errors
    /// and other exceptions raised by property setters) will only be propogated when
    /// debugging.
    /// </field>
    /// <remarks>
    /// Animations need to be as fast as possible - even in debug mode.  Don't add validation code to
    /// methods involved in every step of the animation.
    /// </remarks>
    /// <animation>Animation</animation>
    $TWA.Animation.initializeBase(this);
    
    // Length of the animation in seconds
    this._duration = 1;
    
    // Number of steps per second
    this._fps = 25;
    
    // Target Sys.UI.DomElement of the animation
    this._target = null;
    
    // Tick event handler
    this._tickHandler = null;
    
    // Animation timer
    this._timer = null;
    
    // Percentage of the animation already played
    this._percentComplete = 0;
    
    // Percentage of the animation to play on each step
    this._percentDelta = null;
    
    // Reference to the animation that owns this animation (currently only set in 
    // ParallelAnimation.add).  This concept of ownership allows an entire animation
    // subtree to be driven off a single timer so all the operations are properly
    // synchronized.
    this._owner = null;
    
    // Reference to the animation that contains this as a child (this is set
    // in ParentAnimation.add).  The primary use of the parent animation is in
    // resolving the animation target when one isn't specified.
    this._parentAnimation = null;
    
    // The DynamicProperties collection is used to associate JavaScript expressions with
    // properties.  The expressions are evaluated just before the animation is played
    // everytime (in the base onStart method).  See the additional information in the
    // XML <field> comment above.
    this.DynamicProperties = { };
    
    // Set the target, duration, and fps if they were provided in the constructor
    if (target) {
        this.set_target(target);
    }
    if (duration) {
        this.set_duration(duration);
    }
    if (fps) { 
        this.set_fps(fps);
    }
}
$TWA.Animation.prototype = {
    dispose : function() {
        /// <summary>
        /// Dispose the animation
        /// </summary>
        /// <returns />
        
        if (this._timer) {
            this._timer.dispose();
            this._timer = null;
        }
        
        this._tickHandler = null;
        this._target = null;
        
        $TWA.Animation.callBaseMethod(this, 'dispose');
    },
    
    play : function() {
        /// <summary>
        /// Play the animation from the beginning or where it was left off when paused.
        /// </summary>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>play</code> on its parent instead.
        /// </remarks>
        
        // If ownership of this animation has been claimed, then we'll require the parent to
        // handle playing the animation (this is very important because then the entire animation
        // tree runs on the same timer and updates consistently)
        if (!this._owner) {
            var resume = true;
            if (!this._timer) {
                resume = false;
                
                if (!this._tickHandler) {
                    this._tickHandler = Function.createDelegate(this, this._onTimerTick);
                }

                this._timer = new Telerik.Web.Timer();
                this._timer.add_tick(this._tickHandler);
               
                this.onStart();
                
                this._timer.set_interval(1000 / this._fps);
                this._percentDelta = 100 / (this._duration * this._fps);
                this._updatePercentComplete(0, true);
            }

            this._timer.set_enabled(true);
            
            this.raisePropertyChanged('isPlaying');
            if (!resume) {
                this.raisePropertyChanged('isActive');
            }
        }
    },
    
    pause : function() {
        /// <summary>
        /// Pause the animation if it is playing.  Calling <code>play</code> will resume where
        /// the animation left off.
        /// </summary>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>pause</code> on its parent instead.
        /// </remarks>
        
        if (!this._owner) {
            if (this._timer) {
                this._timer.set_enabled(false);
                
                this.raisePropertyChanged('isPlaying');
            }
        }
    },
    
    stop : function(finish) {
        /// <summary>
        /// Stop playing the animation.
        /// </summary>
        /// <param name="finish" type="Boolean" mayBeNull="true" optional="true">
        /// Whether or not stopping the animation should leave the target element in a state
        /// consistent with the animation playing completely by performing the last step.
        /// The default value is true.
        /// </param>
        /// <returns />
        /// <remarks>
        /// If this animation is the child of another, you must call <code>stop</code> on
        /// its parent instead.
        /// </remarks>
        
        if (!this._owner) {
            var t = this._timer;
            this._timer = null;
            if (t) {
                t.dispose();
                
                if (this._percentComplete !== 100) {
                    this._percentComplete = 100;
                    this.raisePropertyChanged('percentComplete');
                    if (finish || finish === undefined) {
                        this.onStep(100);
                    }
                }
                this.onEnd();
                
                this.raisePropertyChanged('isPlaying');
                this.raisePropertyChanged('isActive');
            }
        }
    },
    
    onStart : function() {
        /// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        
        this.raiseStarted();
        
        // Initialize any dynamic properties
        for (var property in this.DynamicProperties) {
            try {
                // Invoke the property's setter on the evaluated expression
                this[property](eval(this.DynamicProperties[property]));
            } catch(ex) {
                // Propogate any exceptions if we're debugging, otherwise eat them
                if ( Sys.Debug.isDebug) {
                    throw ex;
                }
            }
        }
    },
    
    onStep : function(percentage) {
        /// <summary>
        /// The <code>onStep</code> method is called repeatedly to progress the animation through each frame
        /// </summary>
        /// <param name="percentage" type="Number">Percentage of the animation already complete</param>
        /// <returns />
        
        this.setValue(this.getAnimatedValue(percentage));
    },
    
    onEnd : function() {
        /// <summary>
        /// The <code>onEnd</code> method is called just after the animation is played each time.
        /// </summary>
        /// <returns />
        
        this.raiseEnded();
    },
    
    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Determine the state of the animation after the given percentage of its duration has elapsed
        /// </summary>
        /// <param name="percentage" type="Number">Percentage of the animation already complete</param>
        /// <returns type="Object">
        /// State of the animation after the given percentage of its duration has elapsed that will
        /// be passed to <code>setValue</code>
        /// </returns>
        throw Error.notImplemented();
    },
    
    setValue : function(value) {
        /// <summary>
        /// Set the current state of the animation
        /// </summary>
        /// <param name="value" type="Object">Current state of the animation (as retreived from <code>getAnimatedValue</code>)</param>
        /// <returns />
        throw Error.notImplemented();
    },
    
    interpolate : function(start, end, percentage) {
        /// <summary>
        /// The <code>interpolate</code> function is used to find the appropriate value between starting and
        /// ending values given the current percentage.
        /// </summary>
        /// <param name="start" type="Number">
        /// Start of the range to interpolate
        /// </param>
        /// <param name="end" type="Number">
        /// End of the range to interpolate
        /// </param>
        /// <param name="percentage" type="Number">
        /// Percentage completed in the range to interpolate
        /// </param>
        /// <returns type="Number">
        /// Value the desired percentage between the start and end values
        /// </returns>
        /// <remarks>
        /// In the future, we hope to make several implementations of this available so we can dynamically
        /// change the apparent speed of the animations, although it may make more sense to modify the
        /// <code>_updatePercentComplete</code> function instead.
        /// </remarks>
        return start + (end - start) * (percentage / 100);
    },
    
    _onTimerTick : function() {
        /// <summary>
        /// Handler for the tick event to move the animation along through its duration
        /// </summary>
        /// <returns />
        this._updatePercentComplete(this._percentComplete + this._percentDelta, true);
		this.raise_onTick();
    },
    
    _updatePercentComplete : function(percentComplete, animate) {
        /// <summary>
        /// Update the animation and its target given the current percentage of its duration that
        /// has already elapsed
        /// </summary>
        /// <param name="percentComplete" type="Number">
        /// Percentage of the animation duration that has already elapsed
        /// </param>
        /// <param name="animate" type="Boolean" mayBeNull="true" optional="true">
        /// Whether or not updating the animation should visually modify the animation's target
        /// </param>
        /// <returns />
        
        if (percentComplete > 100) {
            percentComplete = 100;
        }
        
        this._percentComplete = percentComplete;
        this.raisePropertyChanged('percentComplete');
        
        if (animate) {
            this.onStep(percentComplete);
        }
        
        if (percentComplete === 100) {
            this.stop(false);
        }
    },
    
    setOwner : function(owner) {
        /// <summary>
        /// Make this animation the child of another animation
        /// </summary>
        /// <param name="owner" type="Telerik.Web.Animation.Animation">
        /// Parent animation
        /// </param>
        /// <returns />
        this._owner = owner;
    },
    
    raiseStarted : function() {
        /// <summary>
        /// Raise the <code>started</code> event
        /// </summary>
        /// <returns />
        var handlers = this.get_events().getHandler('started');
        if (handlers) {
            handlers(this, Sys.EventArgs.Empty);
        }
    },
    
    add_started : function(handler) {
        /// <summary>
        /// Adds an event handler for the <code>started</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to add to the event.
        /// </param>
        /// <returns />
        this.get_events().addHandler("started", handler);
    },
    
    remove_started : function(handler) {
        /// <summary>
        /// Removes an event handler for the <code>started</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to remove from the event.
        /// </param>
        /// <returns />
        this.get_events().removeHandler("started", handler);
    },
    
    raiseEnded : function() {
        /// <summary>
        /// Raise the <code>ended</code> event
        /// </summary>
        /// <returns />
        var handlers = this.get_events().getHandler('ended');
        if (handlers) {
            handlers(this, Sys.EventArgs.Empty);
        }
    },
    
    add_ended : function(handler) {
        /// <summary>
        /// Adds an event handler for the <code>ended</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to add to the event.
        /// </param>
        /// <returns />
        this.get_events().addHandler("ended", handler);
    },
    
    remove_ended : function(handler) {
        /// <summary>
        /// Removes an event handler for the <code>ended</code> event.
        /// </summary>
        /// <param name="handler" type="Function">
        /// The handler to remove from the event.
        /// </param>
        /// <returns />
        this.get_events().removeHandler("ended", handler);
    },

	raise_onTick : function ()
	{
        var handlers = this.get_events().getHandler('onTick');
        if (handlers)
		{
            handlers(this, Sys.EventArgs.Empty);
        }
	},
	
	add_onTick : function (handler)
	{
		this.get_events().addHandler("onTick", handler);
	},
	
	remove_onTick : function (handler)
	{
		this.get_events().removeHandler("onTick", handler);
	},

    get_target : function() {
        /// <value type="Sys.UI.DomElement" domElement="true" mayBeNull="true">
        /// Target of the animation.  If the target of this animation is null and
        /// the animation has a parent, then it will recursively use the target of
        /// the parent animation instead.
        /// </value>
        /// <remarks>
        /// Do not set this property in a generic Xml animation description. It should be set
        /// using either the extender's TargetControlID or the AnimationTarget property (the latter
        /// maps to Telerik.Web.Animation.set_animationTarget).  The only valid way to
        /// set this property in the generic Xml animation description is to use the dynamic
        /// property TargetScript="$get('myElement')".
        /// <remarks>
        if (!this._target && this._parentAnimation) {
            return this._parentAnimation.get_target();
        }
        return this._target;
    },
    set_target : function(value) {
        if (this._target != value) {
            this._target = value;
            this.raisePropertyChanged('target');
        }
    },
    
    set_animationTarget : function(id) {
        /// <value type="string" mayBeNull="false">
        /// ID of a Sys.UI.DomElement or Sys.UI.Control to use as the target of the animation
        /// </value>
        /// <remarks>
        /// If no Sys.UI.DomElement or Sys.UI.Control can be found for the given ID, an
        /// argument exception will be thrown.
        /// <remarks>
        
        // Try to find a Sys.UI.DomElement
        var target = null;
        var element = $get(id);
        if (element) {
            target = element;
        } else {
            // Try to find the control in the AJAX controls collection
            var ctrl = $find(id);
            if (ctrl) {
                element = ctrl.get_element();
                if (element) {
                    target = element;
                }
            }
        }
        
        // Use the new target if we have one, or raise an error if not
        if (target) { 
            this.set_target(target);
        } else {
            throw Error.argument('id', String.format('Telerik.Web.Animation.Animation.set_animationTarget requires the ID of a Sys.UI.DomElement or Sys.UI.Control.  No element or control could be found corresponding to "{0}"', id));
        }
    },
    
    get_duration : function() {
        /// <value type="Number">
        /// Length of the animation in seconds.  The default is 1.
        /// </value>
        return this._duration;
    },
    set_duration : function(value) {
        value = this._getFloat(value);
        if (this._duration != value) {
            this._duration = value;
            this.raisePropertyChanged('duration');
        }
    },
    
    get_fps : function() {
        /// <value type="Number" integer="true">
        /// Number of steps per second.  The default is 25.
        /// </value>
        return this._fps;
    },
    set_fps : function(value) {
        value = this._getInteger(value);
        if (this.fps != value) {
            this._fps = value;
            this.raisePropertyChanged('fps');
        }
    },
    
    get_isActive : function() {
        /// <value type="Boolean">
        /// <code>true</code> if animation is active, <code>false</code> if not.
        /// </value>
        return (this._timer !== null);
    },
    
    get_isPlaying : function() {
        /// <value type="Boolean">
        /// <code>true</code> if animation is playing, <code>false</code> if not.
        /// </value>
        return (this._timer !== null) && this._timer.get_enabled();
    },
    
    get_percentComplete : function() {
        /// <value type="Number">
        /// Percentage of the animation already played.
        /// </value>
        return this._percentComplete;
    },
    
    _getBoolean : function(value) {
        /// <summary>
        /// Helper to convert strings to booleans for property setters
        /// </summary>
        /// <param name="value" type="Object">
        /// Value to convert if it's a string
        /// </param>
        /// <returns type="Object">
        /// Value that has been converted if it was a string
        /// </returns>
        if (String.isInstanceOfType(value)) {
            return Boolean.parse(value);
        }
        return value;
    },
    
    _getInteger : function(value) {
        /// <summary>
        /// Helper to convert strings to integers for property setters
        /// </summary>
        /// <param name="value" type="Object">Value to convert if it's a string</param>
        /// <returns type="Object">Value that has been converted if it was a string</returns>
        if (String.isInstanceOfType(value)) {
            return parseInt(value);
        }
        return value;
    },
    
    _getFloat : function(value) {
        /// <summary>
        /// Helper to convert strings to floats for property setters
        /// </summary>
        /// <param name="value" type="Object">Value to convert if it's a string</param>
        /// <returns type="Object">Value that has been converted if it was a string</returns>
        if (String.isInstanceOfType(value)) {
            return parseFloat(value);
        }
        return value;
    },
    
    _getEnum : function(value, type) {
        /// <summary>
        /// Helper to convert strings to enum values for property setters
        /// </summary>
        /// <param name="value" type="Object">Value to convert if it's a string</param>
        /// <param name="type" type="Type">Type of the enum to convert to</param>
        /// <returns type="Object">Value that has been converted if it was a string</returns>
        if (String.isInstanceOfType(value) && type && type.parse) {
            return type.parse(value);
        }
        return value;
    }
}
$TWA.Animation.registerClass('Telerik.Web.Animation.Animation', Sys.Component);
$TWA.registerAnimation('animation', $TWA.Animation);


$TWA.ParentAnimation = function(target, duration, fps, animations) {
    /// <summary>
    /// The <code>ParentAnimation</code> serves as a base class for all animations that contain children (such as
    /// <see cref="Telerik.Web.Animation.ParallelAnimation" />, <see cref="Telerik.Web.SequenceAnimation" />,
    /// etc.).  It does not actually play the animations, so any classes that inherit from it must do so.  Any animation
    /// that requires nested child animations must inherit from this class, although it will likely want to inherit off of
    /// <see cref="Telerik.Web.Animation.ParallelAnimation" /> or <see cref="Telerik.Web.SequenceAnimation" />
    /// which will actually play their child animations.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="animations" mayBeNull="true" optional="true" parameterArray="true" elementType="Telerik.Web.Animation.Animation">
    /// Array of child animations to be played
    /// </param>
    /// <animation>Parent</animation>
    $TWA.ParentAnimation.initializeBase(this, [target, duration, fps]);
    
    // Array of child animations (there are no assumptions placed on order because
    // it will matter for some derived animations like SequenceAnimation, but not
    // for others like ParallelAnimation) that is demand created in add
    this._animations = [];
    
    // Add any child animations passed into the constructor
    if (animations && animations.length) {
        for (var i = 0; i < animations.length; i++) {
            this.add(animations[i]);
        }
    }
}
$TWA.ParentAnimation.prototype = {
    initialize : function() {
    	/// <summary>
        /// Initialize the parent along with any child animations that have not yet been initialized themselves
    	/// </summary>
    	/// <returns />
        $TWA.ParentAnimation.callBaseMethod(this, 'initialize');
        
        // Initialize all the uninitialized child animations
        if (this._animations) {
            for (var i = 0; i < this._animations.length; i++) {
                var animation = this._animations[i];
                if (animation && !animation.get_isInitialized) {
                    animation.initialize();
                }
            }
        }
    },
    
    dispose : function() {
    	/// <summary>
        /// Dispose of the child animations
    	/// </summary>
    	/// <returns />

        this.clear();
        this._animations = null;
        $TWA.ParentAnimation.callBaseMethod(this, 'dispose');
    },
    
    get_animations : function() {
    	/// <value elementType="Telerik.Web.Animation.Animation">
        /// Array of child animations to be played (there are no assumptions placed on order because it will matter for some
        /// derived animations like <see cref="Telerik.Web.Animation.SequenceAnimation" />, but not for
        /// others like <see cref="Telerik.Web.Animation.ParallelAnimation" />).  To manipulate the child
        /// animations, use the functions <code>add</code>, <code>clear</code>, <code>remove</code>, and <code>removeAt</code>.
    	/// </value>
        return this._animations;
    },
    
    add : function(animation) {
    	/// <summary>
        /// Add an animation as a child of this animation.
    	/// </summary>
    	/// <param name="animation" type="Telerik.Web.Animation.Animation">Child animation to add</param>
    	/// <returns />

        if (this._animations) {
            if (animation) {
                animation._parentAnimation = this;
            }
            Array.add(this._animations, animation);
            this.raisePropertyChanged('animations');
        }
    },
    
    remove : function(animation) {
        /// <summary>
        /// Remove the animation from the array of child animations.
        /// </summary>
        /// <param name="animation" type="Telerik.Web.Animation.Animation">
        /// Child animation to remove
        /// </param>
        /// <returns />
        /// <remarks>
        /// This will dispose the removed animation.
        /// </remarks>

        if (this._animations) {
            if (animation) {
                animation.dispose();
            }
            Array.remove(this._animations, animation);
            this.raisePropertyChanged('animations');
        }
    },
    
    removeAt : function(index) {
        /// <summary>
        /// Remove the animation at a given index from the array of child animations.
        /// </summary>
        /// <param name="index" type="Number" integer="true">
        /// Index of the child animation to remove
        /// </param>
        /// <returns />
        
        if (this._animations) {
            var animation = this._animations[index];
            if (animation) {
                animation.dispose();
            }
            Array.removeAt(this._animations, index);
            this.raisePropertyChanged('animations');
        }
    },
    
    clear : function() {
    	/// <summary>
        /// Clear the array of child animations.
    	/// </summary>
    	/// <remarks>
    	/// This will dispose the cleared child animations.
    	/// </remarks>
    	/// <returns />

        if (this._animations) {
            for (var i = this._animations.length - 1; i >= 0; i--) {
                this._animations[i].dispose();
                this._animations[i] = null;
            }
            Array.clear(this._animations);
            this._animations = [];
            this.raisePropertyChanged('animations');
        }
    }
}
$TWA.ParentAnimation.registerClass('Telerik.Web.Animation.ParentAnimation', $TWA.Animation);
$TWA.registerAnimation('parent', $TWA.ParentAnimation);


$TWA.ParallelAnimation = function(target, duration, fps, animations) {
    /// <summary>
    /// The <code>ParallelAnimation</code> plays several animations simultaneously.  It inherits from
    /// <see cref="Telerik.Web.Animation.ParentAnimation" />, but makes itself the owner of all
    /// its child animations to allow the use a single timer and syncrhonization mechanisms shared with
    /// all the children (in other words, the <code>duration</code> properties of any child animations
    /// are ignored in favor of the parent's <code>duration</code>).  It is very useful in creating
    /// sophisticated effects through combination of simpler animations.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="animations" mayBeNull="true" optional="true" parameterArray="true" elementType="Telerik.Web.Animation.Animation">
    /// Array of child animations
    /// </param>
    /// <animation>Parallel</animation>
    $TWA.ParallelAnimation.initializeBase(this, [target, duration, fps, animations]);
}
$TWA.ParallelAnimation.prototype = {
    add : function(animation) {
    	/// <summary>
        /// Add an animation as a child of this animation and make ourselves its owner.
    	/// </summary>
    	/// <param name="animation" type="Telerik.Web.Animation.Animation">Child animation to add</param>
    	/// <returns />
        $TWA.ParallelAnimation.callBaseMethod(this, 'add', [animation]);
        animation.setOwner(this);
    },
    
    onStart : function() {
        /// <summary>
        /// Get the child animations ready to play
        /// </summary>
        /// <returns />

        $TWA.ParallelAnimation.callBaseMethod(this, 'onStart');
        var animations = this.get_animations();
        for (var i = 0; i < animations.length; i++) {
            animations[i].onStart();
        }
    },
    
    onStep : function(percentage) {
        /// <summary>
        /// Progress the child animations through each frame
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns />

        var animations = this.get_animations();
        for (var i = 0; i < animations.length; i++) {
            animations[i].onStep(percentage);
        }
    },
    
    onEnd : function() {
        /// <summary>
        /// Finish playing all of the child animations
        /// </summary>
        /// <returns />

        var animations = this.get_animations();
        for (var i = 0; i < animations.length; i++) {
            animations[i].onEnd();
        }
        $TWA.ParallelAnimation.callBaseMethod(this, 'onEnd');
    }
}
$TWA.ParallelAnimation.registerClass('Telerik.Web.Animation.ParallelAnimation', $TWA.ParentAnimation);
$TWA.registerAnimation('parallel', $TWA.ParallelAnimation);

$TWA.FadeEffect = function() {
    /// <summary>
    /// The FadeEffect enumeration determines whether a fade animation is used to fade in or fade out.
    /// </summary>
    /// <field name="FadeIn" type="Number" integer="true" />
    /// <field name="FadeOut" type="Number" integer="true" />
    throw Error.invalidOperation();
}
$TWA.FadeEffect.prototype = {
    FadeIn : 0,
    FadeOut : 1
}
$TWA.FadeEffect.registerEnum("Telerik.Web.Animation.FadeEffect", false);

$TWA.FadeAnimation = function(target, duration, fps, effect, minimumOpacity, maximumOpacity, forceLayoutInIE) {
    /// <summary>
    /// The <code>FadeAnimation</code> is used to fade an element in or out of view, depending on the
    /// provided <see cref="Telerik.Web.Animation.FadeEffect" />, by settings its opacity.
    /// The minimum and maximum opacity values can be specified to precisely control the fade.
    /// You may also consider using <see cref="Telerik.Web.Animation.FadeInAnimation" /> or
    /// <see cref="Telerik.Web.Animation.FadeOutAnimation" /> if you know the only direction you
    /// are fading.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="effect" type="Telerik.Web.Animation.FadeEffect" mayBeNull="true" optional="true">
    /// Determine whether to fade the element in or fade the element out.  The possible values are <code>FadeIn</code>
    /// and <code>FadeOut</code>.  The default value is <code>FadeOut</code>.
    /// </param>
    /// <param name="minimumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
    /// </param>
    /// <param name="maximumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
    /// </param>
    /// <param name="forceLayoutInIE" type="Boolean" mayBeNull="true" optional="true">
    /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
    /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
    /// This is obviously ignored when working in other browsers.
    /// </param>
    /// <animation>Fade</animation>
    $TWA.FadeAnimation.initializeBase(this, [target, duration, fps]);

    // The effect determines whether or not we fade in or out
    this._effect = (effect !== undefined) ? effect : $TWA.FadeEffect.FadeIn;
    
    // Maximum and minimum opacities default to 100% and 0%
    this._max = (maximumOpacity !== undefined) ? maximumOpacity : 1;
    this._min = (minimumOpacity !== undefined) ? minimumOpacity : 0;
    
    // Starting and ending opacities
    this._start = this._min;
    this._end = this._max;
    
    // Whether the a layout has already been created (to work around IE problems)
    this._layoutCreated = false;

    // Whether or not we should force a layout to be created for IE by giving it a width
    // and setting its background color (the latter is required in case the user has ClearType enabled).
    // http://msdn.microsoft.com/library/default.asp?url=/workshop/author/filter/reference/filters/alpha.asp
    this._forceLayoutInIE = (forceLayoutInIE === undefined || forceLayoutInIE === null) ? true : forceLayoutInIE;
    
    // Current target of the animation that is cached before the animation plays (since looking up
    // the target could mean walking all the way up to the root of the animation's tree, which we don't
    // want to do for every step of the animation)
    this._currentTarget = null;
    
    // Properly set up the min/max values provided by the constructor
    this._resetOpacities();
}
$TWA.FadeAnimation.prototype = {
    _resetOpacities : function() {
    	/// <summary>
        /// Set the starting and ending opacity values based on the effect (i.e. when we're fading
        /// in we go from <code>_min</code> to <code>_max</code>, but we go <code>_max</code> to
        /// <code>_min</code> when fading out)
    	/// </summary>
    	/// <returns />

        if (this._effect == $TWA.FadeEffect.FadeIn) {
            this._start = this._min;
            this._end = this._max;
        } else {
            this._start = this._max;
            this._end = this._min;
        }
    },
    
    _createLayout : function() {
    	/// <summary>
        /// Create a layout when using Internet Explorer (which entails setting a width and also
        /// a background color if it currently has neither)
    	/// </summary>
    	/// <returns />

        var element = this._currentTarget;
        if (element) {
            // Get the original width/height/back color
            var originalWidth = $telerik.getCurrentStyle(element, 'width');
            var originalHeight = $telerik.getCurrentStyle(element, 'height');
            var originalBackColor = $telerik.getCurrentStyle(element, 'backgroundColor');

            // Set the width which will force the creation of a layout
            if ((!originalWidth || originalWidth == '' || originalWidth == 'auto') &&
                (!originalHeight || originalHeight == '' || originalHeight == 'auto')) {
                element.style.width = element.offsetWidth + 'px';
            }
            
            // Set the back color to avoid ClearType problems
            if (!originalBackColor || originalBackColor == '' || originalBackColor == 'transparent' || originalBackColor == 'rgba(0, 0, 0, 0)') {
                element.style.backgroundColor = $telerik.getInheritedBackgroundColor(element);
            }
            
            // Mark that we've created the layout so we only do it once
            this._layoutCreated = true;
        }
    },
    
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />       
        $TWA.FadeAnimation.callBaseMethod(this, 'onStart');
        
        this._currentTarget = this.get_target();
        this.setValue(this._start);
        
        // Force the creation of a layout in IE if we're supposed to and the current browser is Internet Explorer
        if (this._forceLayoutInIE && !this._layoutCreated && Sys.Browser.agent == Sys.Browser.InternetExplorer) {
            this._createLayout();
        }
    },
    
    getAnimatedValue : function(percentage) {
    	/// <summary>
        /// Determine the current opacity after the given percentage of its duration has elapsed
        /// </summary>
        /// <param name="percentage" type="Number">Percentage of the animation already complete</param>
        /// <returns type="Number">
        /// Current opacity after the given percentage of its duration has elapsed that will
        /// be passed to <code>setValue</code>
        /// </returns>
        return this.interpolate(this._start, this._end, percentage);
    },
    
    setValue : function(value) {
        /// <summary>
        /// Set the current opacity of the element.
        /// </summary>
        /// <param name="value" type="Number">
        /// Current opacity (as retreived from <code>getAnimatedValue</code>)
        /// </param>
        /// <returns />
        /// <remarks>
        /// This method will be replaced by a dynamically generated function that requires no logic
        /// to determine whether it should use filters or the style's opacity.
        /// </remarks>
        if (this._currentTarget) {
            $telerik.setOpacity(this._currentTarget, value);
        }
    },
    
//    set_target : function(value) {
//        /// <value type="Sys.UI.DomElement">
//        /// Override the <code>target</code> property to dynamically create the setValue function.
//        /// </value>
//        /// <remarks>
//        /// Do not set this property in a generic Xml animation description. It will be set automatically
//        /// using either the extender's TargetControlID or the AnimationTarget property.
//        /// <remarks>
//        $TWA.FadeAnimation.callBaseMethod(this, 'set_target', [value]);
//        
//        var element = value;
//        if (element) {
//            var filters = element.filters;
//            if (filters) {
//                var alphaFilter = null;
//                if (filters.length !== 0) {
//                    alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
//                }
//                if (!alphaFilter) {
//                    element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (this._start * 100) + ')';
//                    alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];
//                }
//                if (alphaFilter) {
//                    this.setValue = function(val) { alphaFilter.opacity = val * 100; }
//                } else {
//                    this.setValue = function(val) {
//                        element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (val * 100) + ')';
//                    };
//                }
//            }
//            else {
//                this.setValue = function(val) { element.style.opacity = val; };
//            }
//        }
//    },
    
    get_effect : function() {
    	/// <value type="Telerik.Web.Animation.FadeEffect">
        /// Determine whether to fade the element in or fade the element out.  The possible values are
        /// <code>FadeIn</code> and <code>FadeOut</code>.  The default value is <code>FadeOut</code>.
    	/// </value>
        return this._effect;
    },
    set_effect : function(value) {
        value = this._getEnum(value, $TWA.FadeEffect);
        if (this._effect != value) {
            this._effect = value;
            this._resetOpacities();
            this.raisePropertyChanged('effect');
        }
    },
    
    get_minimumOpacity : function() {
        /// <value type="Number">
        /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1.
        /// The default value is 0.
        /// </value>
	    return this._min;
    },
    set_minimumOpacity : function(value) {
        value = this._getFloat(value);
        if (this._min != value) {
            this._min = value;
            this._resetOpacities();
            this.raisePropertyChanged('minimumOpacity');
        }
    },
    
    get_maximumOpacity : function() {
        /// <value type="Number">
        /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1.
        /// The default value is 1.
        /// </value>
        return this._max;
    },
    set_maximumOpacity : function(value) {
        value = this._getFloat(value);
        if (this._max != value) {
            this._max = value;
            this._resetOpacities();
            this.raisePropertyChanged('maximumOpacity');
        }
    },
    
    get_forceLayoutInIE : function() {
        /// <value type="Boolean">
        /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
        /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
        /// This is obviously ignored when working in other browsers.
        /// </value>
        return this._forceLayoutInIE;
    },
    set_forceLayoutInIE : function(value) {
        value = this._getBoolean(value);
        if (this._forceLayoutInIE != value) {
            this._forceLayoutInIE = value;
            this.raisePropertyChanged('forceLayoutInIE');
        }
    },
    
    set_startValue : function(value) {
        /// <value type="Number">
        /// Set the start value (so that child animations can set the current opacity as the start value when fading in or out)
        /// </value>
        value = this._getFloat(value);
        this._start = value;
    }
}
$TWA.FadeAnimation.registerClass('Telerik.Web.Animation.FadeAnimation', $TWA.Animation);
$TWA.registerAnimation('fade', $TWA.FadeAnimation);


$TWA.FadeInAnimation = function(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE) {
    /// <summary>
    /// The <code>FadeInAnimation</code> will fade the target in by moving from hidden to visible.
    /// It starts the animation the target's current opacity.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="minimumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
    /// </param>
    /// <param name="maximumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
    /// </param>
    /// <param name="forceLayoutInIE" type="Boolean" mayBeNull="true" optional="true">
    /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
    /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
    /// This is obviously ignored when working in other browsers.
    /// </param>
    /// <animation>FadeIn</animation>
    $TWA.FadeInAnimation.initializeBase(this, [target, duration, fps, $TWA.FadeEffect.FadeIn, minimumOpacity, maximumOpacity, forceLayoutInIE]);
}
$TWA.FadeInAnimation.prototype = {
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        $TWA.FadeInAnimation.callBaseMethod(this, 'onStart');
        
        if (this._currentTarget) {
            this.set_startValue($telerik.getOpacity(this._currentTarget));
        }
    }
}
$TWA.FadeInAnimation.registerClass('Telerik.Web.Animation.FadeInAnimation', $TWA.FadeAnimation);
$TWA.registerAnimation('fadeIn', $TWA.FadeInAnimation);


$TWA.FadeOutAnimation = function(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE) {
    /// <summary>
    /// The FadeInAnimation will fade the element out by moving from visible to hidden. It starts the animation
    /// at the element's current opacity.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="minimumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Minimum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 0.
    /// </param>
    /// <param name="maximumOpacity" type="Number" mayBeNull="true" optional="true">
    /// Maximum opacity to use when fading in or out. Its value can range from between 0 to 1. The default value is 1.
    /// </param>
    /// <param name="forceLayoutInIE" type="Boolean" mayBeNull="true" optional="true">
    /// Whether or not we should force a layout to be created for Internet Explorer by giving it a width and setting its
    /// background color (the latter is required in case the user has ClearType enabled). The default value is <code>true</code>.
    /// This is obviously ignored when working in other browsers.
    /// </param>
    /// <animation>FadeOut</animation>
    $TWA.FadeOutAnimation.initializeBase(this, [target, duration, fps, $TWA.FadeEffect.FadeOut, minimumOpacity, maximumOpacity, forceLayoutInIE]);
}
$TWA.FadeOutAnimation.prototype = {
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        $TWA.FadeOutAnimation.callBaseMethod(this, 'onStart');

        if (this._currentTarget) {
            this.set_startValue($telerik.getOpacity(this._currentTarget));
        }
    }
}
$TWA.FadeOutAnimation.registerClass('Telerik.Web.Animation.FadeOutAnimation', $TWA.FadeAnimation);
$TWA.registerAnimation('fadeOut', $TWA.FadeOutAnimation);


$TWA.PropertyAnimation = function(target, duration, fps, property, propertyKey) {
    /// <summary>
    /// The <code>PropertyAnimation</code> is a useful base animation that will assign the value from
    /// <code>getAnimatedValue</code> to a specified <code>property</code>. You can provide the name of
    /// a <code>property</code> alongside an optional <code>propertyKey</code> (which indicates the value
    /// <code>property[propertyKey]</code>, like <code>style['backgroundColor']</code>).
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <animation>Property</animation>
    $TWA.PropertyAnimation.initializeBase(this, [target, duration, fps]);

    // Name of the property to set
    this._property = property;
    
    // Optional Key of the property to set (i.e., if the property were "style" then
    // this might be "backgroundColor")
    this._propertyKey = propertyKey;
    
    // Current target of the animation that is cached before the animation plays (since looking up
    // the target could mean walking all the way up to the root of the animation's tree, which we don't
    // want to do for every step of the animation)
    this._currentTarget = null;
}
$TWA.PropertyAnimation.prototype = {
    onStart : function() {
    	/// <summary>
        /// The <code>onStart</code> method is called just before the animation is played each time.
        /// </summary>
        /// <returns />
        $TWA.PropertyAnimation.callBaseMethod(this, 'onStart');

        this._currentTarget = this.get_target();
    },

    setValue : function(value) {
        /// <summary>
        /// Set the current value of the property
        /// </summary>
        /// <param name="value" type="Object" mayBeNull="true">
        /// Value to assign
        /// </param>
        /// <returns />

        var element = this._currentTarget;
        if (element && this._property && this._property.length > 0) { 
            if (this._propertyKey && this._propertyKey.length > 0 && element[this._property]) {
                element[this._property][this._propertyKey] = value;
            } else {
                element[this._property] = value;
            }
        }
        // Sys.TypeDescriptor.setProperty(this.get_target(), this._property, value, this._propertyKey);
    },
    
    getValue : function() {
        /// <summary>
        /// Get the current value from the property
        /// </summary>
        /// <returns type="Object" mayBeNull="true">
        /// Current value of the property
        /// </returns>

        var element = this.get_target();
        if (element && this._property && this._property.length > 0) { 
            var property = element[this._property];
            if (property) {
                if (this._propertyKey && this._propertyKey.length > 0) {
                    return property[this._propertyKey];
                }
                return property;
            }
        }
        return null;
        // return Sys.TypeDescriptor.getProperty(this.get_target(), this._property, this._propertyKey);
    },
    
    get_property : function() {
        /// <value type="String">
        /// Property of the <code>target</code> element to set when animating
        /// </value>
        return this._property;
    },
    set_property : function(value) {
        if (this._property != value) {
            this._property = value;
            this.raisePropertyChanged('property');
        }
    },
    
    get_propertyKey : function() {
        /// <value type="String" mayBeNull="true" optional="true">
        /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
        /// </value>
        return this._propertyKey;
    },
    set_propertyKey : function(value) {
        if (this._propertyKey != value) {
            this._propertyKey = value;
            this.raisePropertyChanged('propertyKey');
        }
    }
}
$TWA.PropertyAnimation.registerClass('Telerik.Web.Animation.PropertyAnimation', $TWA.Animation);
$TWA.registerAnimation('property', $TWA.PropertyAnimation);


$TWA.DiscreteAnimation = function(target, duration, fps, property, propertyKey, values) {
    /// <summary>
    /// The <code>DiscreteAnimation</code> inherits from <see cref="Telerik.Web.Animation.PropertyAnimation" />
    /// and sets the value of the <code>property</code> to the elements in a provided array of <code>values</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="values" mayBeNull="true" optional="true" parameterArray="true" elementType="Object">
    /// Array of possible values of the property that will be iterated over as the animation is played
    /// </param>
    /// <animation>Discrete</animation>
    $TWA.DiscreteAnimation.initializeBase(this, [target, duration, fps, property, propertyKey]);

    // Values to assign to the property
    this._values = (values && values.length) ? values : [];
}
$TWA.DiscreteAnimation.prototype = {
    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Assign the value whose index corresponds to the current percentage
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns type="Object">
        /// State of the animation after the given percentage of its duration has elapsed that will
        /// be passed to <code>setValue</code>
        /// </returns>
        var index = Math.floor(this.interpolate(0, this._values.length - 1, percentage));
        return this._values[index];
    },
    
    get_values : function() {
        /// <value parameterArray="true" elementType="Object">
        /// Array of possible values of the property that will be iterated over as the animation is played
        /// </value>
        return this._values;
    },
    set_values : function(value) {
        if (this._values != value) {
            this._values = value;
            this.raisePropertyChanged('values');
        }
    }
}
$TWA.DiscreteAnimation.registerClass('Telerik.Web.Animation.DiscreteAnimation', $TWA.PropertyAnimation);
$TWA.registerAnimation('discrete', $TWA.DiscreteAnimation);


$TWA.InterpolatedAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue) {
    /// <summary>
    /// The <code>InterpolatedAnimation</code> assigns a range of values between <code>startValue</code>
    /// and <code>endValue</code> to the designated property.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating.  The default value is 'style'.
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="startValue" type="Number" mayBeNull="true" optional="true">
    /// Start of the range of values
    /// </param>
    /// <param name="endValue" type="Number" mayBeNull="true" optional="true">
    /// End of the range of values
    /// </param>
    /// <animation>Interpolated</animation>
    $TWA.InterpolatedAnimation.initializeBase(this, [target, duration, fps, ((property !== undefined) ? property : 'style'), propertyKey]);

    // Start and end values
    this._startValue = startValue;
    this._endValue = endValue;
}
$TWA.InterpolatedAnimation.prototype = {
    get_startValue : function() {
        /// <value type="Number">
        /// Start of the range of values
        /// </value>
        return this._startValue;
    },
    set_startValue : function(value) {
        value = this._getFloat(value);
        if (this._startValue != value) {
            this._startValue = value;
            this.raisePropertyChanged('startValue');
        }
    },
    
    get_endValue : function() {
        /// <value type="Number">
        /// End of the range of values
        /// </value>
        return this._endValue;
    },
    set_endValue : function(value) {
        value = this._getFloat(value);
        if (this._endValue != value) {
            this._endValue = value;
            this.raisePropertyChanged('endValue');
        }
    }   
}
$TWA.InterpolatedAnimation.registerClass('Telerik.Web.Animation.InterpolatedAnimation', $TWA.PropertyAnimation);
$TWA.registerAnimation('interpolated', $TWA.InterpolatedAnimation);


$TWA.ColorAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue) {
    /// <summary>
    /// The <code>ColorAnimation</code> transitions the value of the <code>property</code> between
    /// two colors (although it does ignore the alpha channel). The colors must be 7-character hex strings
    /// (like <code>#246ACF</code>).
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating.  The default value is 'style'.
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="startValue" type="String" mayBeNull="true" optional="true">
    /// Start of the range of colors
    /// </param>
    /// <param name="endValue" type="String" mayBeNull="true" optional="true">
    /// End of the range of colors
    /// </param>
    /// <animation>Color</animation>
    $TWA.ColorAnimation.initializeBase(this, [target, duration, fps, property, propertyKey, startValue, endValue]);
    
    // Cached start/end RBG triplets
    this._start = null;
    this._end = null;
    
    // Flags indicating whether each dimension of color will be interpolated
    this._interpolateRed = false;
    this._interpolateGreen = false;
    this._interpolateBlue = false;
}
$TWA.ColorAnimation.prototype = {
    onStart : function() {
        /// <summary>
        /// Determine which dimensions of color will be animated
        /// </summary>
        /// <returns />
        $TWA.ColorAnimation.callBaseMethod(this, 'onStart');
       
        this._start = $TWA.ColorAnimation.getRGB(this.get_startValue());
        this._end = $TWA.ColorAnimation.getRGB(this.get_endValue());
        
        this._interpolateRed = (this._start.Red != this._end.Red);
        this._interpolateGreen = (this._start.Green != this._end.Green);
        this._interpolateBlue = (this._start.Blue != this._end.Blue);
    },
    
    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Get the interpolated color values
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns type="String">
        /// Current color formatted as a 7-character hex string (like <code>#246ACF</code>).
        /// </returns>

        var r = this._start.Red;
        var g = this._start.Green;
        var b = this._start.Blue;
        
        if (this._interpolateRed)
            r = Math.round(this.interpolate(r, this._end.Red, percentage));
        
        if (this._interpolateGreen)
            g = Math.round(this.interpolate(g, this._end.Green, percentage));
        
        if (this._interpolateBlue)
            b = Math.round(this.interpolate(b, this._end.Blue, percentage));
        
        return $TWA.ColorAnimation.toColor(r, g, b);
    },
    
    set_startValue : function(value) {
        /// <value type="String">
        /// Starting color of the transition formatted as a 7-character hex string (like <code>#246ACF</code>).
        /// </value>

        if (this._startValue != value) {
            this._startValue = value;
            this.raisePropertyChanged('startValue');
        }
    },
    
    set_endValue : function(value) {
        /// <value type="String">
        /// Ending color of the transition formatted as a 7-character hex string (like <code>#246ACF</code>).
        /// </value>

        if (this._endValue != value) {
            this._endValue = value;
            this.raisePropertyChanged('endValue');
        }
    }   
}
$TWA.ColorAnimation.getRGB = function(color) {
    /// <summary>
    /// Convert the color to an RGB triplet
    /// </summary>
    /// <param name="color" type="String">
    /// Color formatted as a 7-character hex string (like <code>#246ACF</code>)
    /// </param>
    /// <returns type="Object">
    /// Object representing the color with <code>Red</code>, <code>Green</code>, and <code>Blue</code> properties.
    /// </returns>

    if (!color || color.length != 7) {
        throw String.format('Color must be a 7-character hex representation (e.g. #246ACF), not "{0}"', color);
    }
    return { 'Red': parseInt(color.substr(1,2), 16),
             'Green': parseInt(color.substr(3,2), 16),
             'Blue': parseInt(color.substr(5,2), 16) };
}
$TWA.ColorAnimation.toColor = function(red, green, blue) {
    /// <summary>
    /// Convert an RBG triplet into a 7-character hex string (like <code>#246ACF</code>)
    /// </summary>
    /// <param name="red" type="Number" integer="true">
    /// Value of the color's red dimension
    /// </param>
    /// <param name="green" type="Number" integer="true">
    /// Value of the color's green dimension
    /// </param>
    /// <param name="blue" type="Number" integer="true">
    /// Value of the color's blue dimension
    /// </param>
    /// <returns type="String">
    /// Color as a 7-character hex string (like <code>#246ACF</code>)
    /// </returns>

    var r = red.toString(16);
    var g = green.toString(16);
    var b = blue.toString(16);
    if (r.length == 1) r = '0' + r;
    if (g.length == 1) g = '0' + g;
    if (b.length == 1) b = '0' + b;
    return '#' + r + g + b;
}
$TWA.ColorAnimation.registerClass('Telerik.Web.Animation.ColorAnimation', $TWA.InterpolatedAnimation);
$TWA.registerAnimation('color', $TWA.ColorAnimation);


$TWA.LengthAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue, unit) {
    /// <summary>
    /// The <code>LengthAnimation</code> is identical to <see cref="Telerik.Web.Animation.InterpolatedAnimation" />
    /// except it adds a <code>unit</code> to the value before assigning it to the <code>property</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="property" type="String" mayBeNull="true" optional="true">
    /// Property of the <code>target</code> element to set when animating.  The default value is 'style'.
    /// </param>
    /// <param name="propertyKey" type="String" mayBeNull="true" optional="true">
    /// Optional key of the property to be set (which indicates the value property[propertyKey], like style['backgroundColor']). Note that for the style property, the key must be in a JavaScript friendly format (i.e. backgroundColor instead of background-color).
    /// </param>
    /// <param name="startValue" type="Number" mayBeNull="true" optional="true">
    /// Start of the range of values
    /// </param>
    /// <param name="endValue" type="Number" mayBeNull="true" optional="true">
    /// End of the range of values
    /// </param>
    /// <param name="unit" type="String" mayBeNull="true" optional="true">
    /// Unit of the interpolated values.  The default value is <code>'px'</code>.
    /// </param>
    /// <animation>Length</animation>
    $TWA.LengthAnimation.initializeBase(this, [target, duration, fps, property, propertyKey, startValue, endValue]);
    
    // Unit of length (which defaults to px)
    this._unit = (unit != null) ? unit : 'px';
}
$TWA.LengthAnimation.prototype = {

    getAnimatedValue : function(percentage) {
        /// <summary>
        /// Get the interpolated length value
        /// </summary>
        /// <param name="percentage" type="Number">
        /// Percentage of the animation already complete
        /// </param>
        /// <returns type="String">
        /// Interpolated length
        /// </returns>

        var value = this.interpolate(this.get_startValue(), this.get_endValue(), percentage);
        return Math.round(value) + this._unit;
    },
    
    get_unit : function() {
        /// <value type="String">
        /// Unit of the interpolated values.  The default value is <code>'px'</code>.
        /// </value>
        return this._unit;
    },
    set_unit : function(value) {
        if (this._unit != value) {
            this._unit = value;
            this.raisePropertyChanged('unit');
        }
    }
}
$TWA.LengthAnimation.registerClass('Telerik.Web.Animation.LengthAnimation', $TWA.InterpolatedAnimation);
$TWA.registerAnimation('length', $TWA.LengthAnimation);


$TWA.MoveAnimation = function(target, duration, fps, horizontal, vertical, relative, unit) {
    /// <summary>
    /// The <code>MoveAnimation</code> is used to move the <code>target</code> element. If the
    /// <code>relative</code> flag is set to <code>true</code>, then it treats the <code>horizontal</code>
    /// and <code>vertical</code> properties as offsets to move the element. If the <code>relative</code>
    /// flag is <code>false</code>, then it will treat the <code>horizontal</code> and <code>vertical</code>
    /// properties as coordinates on the page where the <code>target</code> element should be moved. It is
    /// important to note that the <code>target</code> must be positioned (i.e. <code>absolutely</code>) so
    /// that settings its <code>top</code>/<code>left<code> style attributes will change its location.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="horizontal" type="Number" mayBeNull="true" optional="true">
    /// If <code>relative</code>  is <code>true</code>, this is the offset to move horizontally. Otherwise this is the x
    /// coordinate on the page where the <code>target</code> should be moved.
    /// </param>
    /// <param name="vertical" type="Number" mayBeNull="true" optional="true">
    /// If <code>relative</code> is <code>true</code>, this is the offset to move vertically. Otherwise this is the y
    /// coordinate on the page where the <code>target</code> should be moved.
    /// </param>
    /// <param name="relative" type="Boolean" mayBeNull="true" optional="true">
    /// <code>true</code> if we are moving relative to the current position, <code>false</code> if we are moving absolutely
    /// </param>
    /// <param name="unit" type="String" mayBeNull="true" optional="true">
    /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
    /// </param>
    /// <animation>Move</animation>
    $TWA.MoveAnimation.initializeBase(this, [target, duration, fps, null]);

    // Distance to move horizontally and vertically
    this._horizontal = horizontal ? horizontal : 0;
    this._vertical = vertical ? vertical : 0;
    this._relative = (relative === undefined) ? true : relative;
    
    // Length animations representing the movememnts
    this._horizontalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'left', null, null, unit);
    this._verticalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'top', null, null, unit);
    this.add(this._verticalAnimation);
    this.add(this._horizontalAnimation);
}
$TWA.MoveAnimation.prototype = {
    
    onStart : function() {
        /// <summary>
        /// Use the <code>target</code>'s current position as the starting point for the animation
        /// </summary>
        /// <returns />
        $TWA.MoveAnimation.callBaseMethod(this, 'onStart');
        
        // Set the start and end values of the animations by getting
        // the element's current position and applying the offsets
        var element = this.get_target();
        this._horizontalAnimation.set_startValue(element.offsetLeft);
        this._horizontalAnimation.set_endValue(this._relative ? element.offsetLeft + this._horizontal : this._horizontal);
        this._verticalAnimation.set_startValue(element.offsetTop); 
        this._verticalAnimation.set_endValue(this._relative ? element.offsetTop + this._vertical : this._vertical);
    },
    
    get_horizontal : function() {
        /// <value type="Number">
        /// If <code>relative</code>  is <code>true</code>, this is the offset to move horizontally. Otherwise this is the x
        /// coordinate on the page where the <code>target</code> should be moved.
        /// </value>
        return this._horizontal;
    },
    set_horizontal : function(value) {
        value = this._getFloat(value);
        if (this._horizontal != value) {
            this._horizontal = value;
            this.raisePropertyChanged('horizontal');
        }
    },
    
    get_vertical : function() {
        /// <value type="Number">
        /// If <code>relative</code> is <code>true</code>, this is the offset to move vertically. Otherwise this is the y
        /// coordinate on the page where the <code>target</code> should be moved.
        /// </value>
        return this._vertical;
    },
    set_vertical : function(value) {
        value = this._getFloat(value);
        if (this._vertical != value) {
            this._vertical = value;
            this.raisePropertyChanged('vertical');
        }
    },
    
    get_relative : function() {
        /// <value type="Boolean">
        /// <code>true</code> if we are moving relative to the current position, <code>false</code> if we are moving absolutely
        /// </value>
        return this._relative;
    },
    set_relative : function(value) {
        value = this._getBoolean(value);
        if (this._relative != value) {
            this._relative = value;
            this.raisePropertyChanged('relative');
        }
    },
    
    get_unit : function() {
        /// <value type="String" mayBeNull="true">
        /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
        /// </value>
        this._horizontalAnimation.get_unit();
    },
    set_unit : function(value) {
        var unit = this._horizontalAnimation.get_unit();
        if (unit != value) {
            this._horizontalAnimation.set_unit(value);
            this._verticalAnimation.set_unit(value);
            this.raisePropertyChanged('unit');
        }
    }
}
$TWA.MoveAnimation.registerClass('Telerik.Web.Animation.MoveAnimation', $TWA.ParallelAnimation);
$TWA.registerAnimation('move', $TWA.MoveAnimation);


$TWA.ResizeAnimation = function(target, duration, fps, width, height, unit) {
    /// <summary>
    /// The <code>ResizeAnimation</code> changes the size of the <code>target</code> from its
    /// current value to the specified <code>width</code> and <code>height</code>.
    /// </summary>
    /// <param name="target" type="Sys.UI.DomElement" mayBeNull="true" optional="true" domElement="true">
    /// Target of the animation
    /// </param>
    /// <param name="duration" type="Number" mayBeNull="true" optional="true">
    /// Length of the animation in seconds.  The default is 1.
    /// </param>
    /// <param name="fps" type="Number" mayBeNull="true" optional="true" integer="true">
    /// Number of steps per second.  The default is 25.
    /// </param>
    /// <param name="width" type="Number" mayBeNull="true" optional="true">
    /// New width of the <code>target</code>
    /// </param>
    /// <param name="height" type="Number" mayBeNull="true" optional="true">
    /// New height of the <code>target</code>
    /// </param>
    /// <param name="unit" type="String" mayBeNull="true" optional="true">
    /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
    /// </param>
    /// <animation>Resize</animation>
    $TWA.ResizeAnimation.initializeBase(this, [target, duration, fps, null]);

    // New size of the element
    this._width = width;
    this._height = height;
    
    // Animations to set the size across both dimensions
    this._horizontalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'width', null, null, unit);
    this._verticalAnimation = new $TWA.LengthAnimation(target, duration, fps, 'style', 'height', null, null, unit);
    this.add(this._horizontalAnimation);
    this.add(this._verticalAnimation);
}
$TWA.ResizeAnimation.prototype = {
    
    onStart : function() {
        /// <summary>
        /// Use the <code>target</code>'s current size as the starting point for the animation
        /// </summary>
        /// <returns />

        $TWA.ResizeAnimation.callBaseMethod(this, 'onStart');
        
        // Set the start and end values of the animations by getting
        // the element's current width and height
        var element = this.get_target();
        this._horizontalAnimation.set_startValue(element.offsetWidth);
        this._verticalAnimation.set_startValue(element.offsetHeight);
        this._horizontalAnimation.set_endValue((this._width !== null && this._width !== undefined) ?
            this._width : element.offsetWidth);
        this._verticalAnimation.set_endValue((this._height !== null && this._height !== undefined) ?
            this._height : element.offsetHeight);
    },
    
    get_width : function() {
        /// <value type="Number">
        /// New width of the <code>target</code>
        /// </value>

        return this._width;
    },
    set_width : function(value) {
        value = this._getFloat(value);
        if (this._width != value) {
            this._width = value;
            this.raisePropertyChanged('width');
        }
    },
    
    get_height : function() {
        /// <value type="Number">
        /// New height of the <code>target</code>
        /// </value>

        return this._height;
    },
    set_height : function(value) {
        value = this._getFloat(value);
        if (this._height != value) {
            this._height = value;   
            this.raisePropertyChanged('height');
        }
    },
    
    get_unit : function() {
        /// <value type="String">
        /// Length unit for the size of the <code>target</code>. The default value is <code>'px'</code>.
        /// </value>

        this._horizontalAnimation.get_unit();
    },
    set_unit : function(value) {
        var unit = this._horizontalAnimation.get_unit();
        if (unit != value) {
            this._horizontalAnimation.set_unit(value);
            this._verticalAnimation.set_unit(value);
            this.raisePropertyChanged('unit');
        }
    }
}
$TWA.ResizeAnimation.registerClass('Telerik.Web.Animation.ResizeAnimation', $TWA.ParallelAnimation);
$TWA.registerAnimation('resize', $TWA.ResizeAnimation);
/* END Telerik.Web.UI.Common.Animation.Animations.js */
/* START Telerik.Web.UI.Common.Scrolling.Scroller.js */
Type.registerNamespace("Telerik.Web.UI");

// ---------- ScrollerOrientation Enum ----------
Telerik.Web.UI.ScrollerOrientation = function(){}
Telerik.Web.UI.ScrollerOrientation.prototype = 
{
	Vertical: 0,
	Horizontal: 1
}
Telerik.Web.UI.ScrollerOrientation.registerEnum("Telerik.Web.UI.ScrollerOrientation");

// ---------- ScrollerSpeed Enum ----------
Telerik.Web.UI.ScrollerSpeed = function(){}
Telerik.Web.UI.ScrollerSpeed.prototype = 
{
	Invalid: 0,
	Slow: 1,
	Medium: 2,
	Fast: 3
}
Telerik.Web.UI.ScrollerSpeed.registerEnum("Telerik.Web.UI.ScrollerSpeed");

// ---------- ArrowPosition Enum ----------
Telerik.Web.UI.ArrowPosition = function(){}
Telerik.Web.UI.ArrowPosition.prototype = 
{
	Top: 0,
	Bottom: 1,
	Left: 2,
	Right: 3
}
Telerik.Web.UI.ArrowPosition.registerEnum("Telerik.Web.UI.ArrowPosition");

// ---------- Scroller Class ----------
Telerik.Web.UI.Scroller = function(scrolledElement, element, orientation)
{
	// Constants
	this._timerInterval = 10;
	
	this._scrolledElement = scrolledElement;
	this._element = element;
	this._orientation = orientation;
	this._minPosition = 0;
	this._maxPosition = null;
	this._currentPosition = 0;
	this._speed = Telerik.Web.UI.ScrollerSpeed.Invalid;
	this._direction = 0;
	
	this._events = null;
	
	this._timer = null;
	this._onTickDelegate = null;
}

Telerik.Web.UI.Scroller.prototype = 
{
	initialize: function()
	{
		this._onTickDelegate = Function.createDelegate(this, this._onTick);
		
		this._timer = new Telerik.Web.Timer()
		this._timer.set_interval(this._timerInterval);
		this._timer.add_tick(this._onTickDelegate);
	},
	
	dispose: function()
	{
		if (this._timer)
			this._timer.dispose();
		
		this._onTickDelegate = null;
		this._events = null;
	},
	
	// Properties
	get_element : function ()
	{
		return this._element;
	},

	get_events: function ()
	{
		if (!this._events)
			this._events = new Sys.EventHandlerList();
		return this._events;
	},
	
	
	// Events
	add_positionChanged : function(handler)
	{
		this.get_events().addHandler('positionChanged', handler);
	},
	
	remove_positionChanged : function(handler)
	{
		this.get_events().removeHandler('positionChanged', handler);        
	},

	// Public methods
	setScrollingLimits : function (minPosition, maxPosition)
	{
		this._minPosition = Math.max(0, minPosition);
		this._maxPosition = Math.min(this._getElementSize(), maxPosition);
	},
	
	isAtMinPosition : function ()
	{
		return this._currentPosition <= this._minPosition;
	},
	
	isAtMaxPosition : function ()
	{
		return this._currentPosition >= this._maxPosition;
	},
	
	resetState : function ()
	{
		this._resetOverflowStyle();
		this._scrollTo(0);
	},
	
	startScroll : function (speed, direction)
	{
		this._speed = speed;
		this._direction = direction;
		this._timer.set_enabled(true);
	},
	
	changeScrollSpeed : function (speed)
	{
		this._speed = speed;
	},
	
	stopScroll : function ()
	{
		this._speed = Telerik.Web.UI.ScrollerSpeed.Invalid;
		this._direction = 0;
		
		this._timer.set_enabled(false);
	},
	
	// Private methods
	_onTick : function ()
	{
		var nextPosition = this._currentPosition + (this._direction * this._speed);
		nextPosition = Math.max(nextPosition, this._minPosition);
		nextPosition = Math.min(nextPosition, this._maxPosition);
		
		this._scrollTo(nextPosition);
		
		if (nextPosition == this._minPosition || nextPosition == this._maxPosition)
			this.stopScroll();
	},
	
	_scrollTo : function (position)
	{
		var scrollProperty = "left";
		if (this._orientation == Telerik.Web.UI.ScrollerOrientation.Vertical)
			scrollProperty = "top";
		
		this._currentPosition = position;
		this._scrolledElement.style[scrollProperty] = -position + "px";
		
		this._raiseEvent('positionChanged', Sys.EventArgs.Empty);
	},

	_resetOverflowStyle : function ()
	{
		if ($telerik.isIE)
		{
			this._element.style.overflow = "visible";
			if (this._orientation == Telerik.Web.UI.ItemFlow.Vertical)
			{
				this._element.style.overflowX = "visible";
				this._element.style.overflowY = "hidden";
			}
			else
			{
				this._element.style.overflowX = "hidden";
				this._element.style.overflowY = "hidden";
			}
		}
		else
		{
			this._element.style.overflow = "hidden";
		}
	},
	
	_getElementSize : function ()
	{
		if (this._orientation == Telerik.Web.UI.ScrollerOrientation.Vertical)
		{
			return this._scrolledElement.offsetHeight;
		}
		else
		{
			return this._scrolledElement.offsetWidth;
		}
	},
	
	_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.Scroller.registerClass('Telerik.Web.UI.Scroller', null, Sys.IDisposable);
/* END Telerik.Web.UI.Common.Scrolling.Scroller.js */
/* START Telerik.Web.UI.Common.Navigation.AnimationSettings.js */
Type.registerNamespace("Telerik.Web.UI");

// ---------- AnimationSettings Class ----------
Telerik.Web.UI.AnimationSettings = function(serializedAnimationSettings)
{
	this._type = Telerik.Web.UI.AnimationType.OutQuart;
	this._duration = 300;
	
	if (typeof(serializedAnimationSettings.type) != "undefined")
	{
		this._type = serializedAnimationSettings.type;
	}
	
	if (typeof(serializedAnimationSettings.duration) != "undefined")
	{
		this._duration = serializedAnimationSettings.duration;
	}
}

Telerik.Web.UI.AnimationSettings.prototype =
{
	get_type : function ()
	{
		return this._type;
	},
	
	set_type : function(value)
	{
		this._type = value;
	},

	get_duration : function ()
	{
		return this._duration;
	},
	
	set_duration : function(value)
	{
		this._duration = value;
	}
}

Telerik.Web.UI.AnimationSettings.registerClass('Telerik.Web.UI.AnimationSettings');


/* END Telerik.Web.UI.Common.Navigation.AnimationSettings.js */
/* START Telerik.Web.UI.Common.Navigation.Slide.js */
Type.registerNamespace("Telerik.Web.UI");


// ---------- SlideDirection Enum ----------
Telerik.Web.UI.SlideDirection = function()
{
};
Telerik.Web.UI.SlideDirection.prototype = 
{
	Up: 1,
	Down: 2,
	Left: 3,
	Right: 4
}
Telerik.Web.UI.SlideDirection.registerEnum("Telerik.Web.UI.SlideDirection");


// ---------- Slide Class ----------
Telerik.Web.UI.Slide = function(animatedElement, expandAnimation, collapseAnimation, enableOverlay)
{
	// Constants
	this._fps = 60;
	
	this._animatedElement = animatedElement;
	this._element = animatedElement.parentNode;
	this._expandAnimation = expandAnimation;
	this._collapseAnimation = collapseAnimation;
	this._direction = Telerik.Web.UI.SlideDirection.Down;
	this._animation = null;
	this._expanding = null;
	
	if (enableOverlay == null)
	{
		this._enableOverlay = true;
	}
	else
	{
		this._enableOverlay = enableOverlay;
	}
	
	this._events = null;
	this._overlay = null;

	this._animationEndedDelegate = null;
	this._expandAnimationStartedDelegate = null;
	this._updateOverlayDelegate = null;
}

Telerik.Web.UI.Slide.prototype = 
{
	initialize: function()
	{
		if (Telerik.Web.UI.Overlay.IsSupported() && this._enableOverlay) 
		{
			var animatedElement = this.get_animatedElement();
			this._overlay = new Telerik.Web.UI.Overlay(animatedElement);
			this._overlay.initialize();
		}

		this._animationEndedDelegate = Function.createDelegate(this, this._animationEnded);
		this._expandAnimationStartedDelegate = Function.createDelegate(this, this._expandAnimationStarted);
		this._updateOverlayDelegate = Function.createDelegate(this, this._updateOverlay);
	},
	
	dispose: function()
	{
		this._animatedElement = null;
		this._events = null;

		this._disposeAnimation();

		if (this._overlay) 
		{
			this._overlay.dispose();
			this._overlay = null;
		}

		this._animationEndedDelegate = null;
		this._expandAnimationStartedDelegate = null;
		this._updateOverlayDelegate = null;
	},
	
	
	// Properties
	get_element : function ()
	{
		return this._element;
	},
	
	get_animatedElement: function()
	{
		return this._animatedElement;
	},
	
	set_animatedElement: function(value)
	{
		this._animatedElement = value;
		
		if (this._overlay)
		{
			this._overlay.set_targetElement(this._animatedElement);
		}
	},
	
	get_direction: function()
	{
		return this._direction;
	},
	
	set_direction: function(value)
	{
		this._direction = value;
	},
	
	get_events: function ()
	{
		if (!this._events)
		{
			this._events = new Sys.EventHandlerList();
		}
		
		return this._events;
	},
	
	// Public methods
	updateSize: function()
	{
		var animatedElement = this.get_animatedElement();
		var element = this.get_element();
		
		var top = 0;
		if (animatedElement.style.top) 
		{
			top = Math.max(parseInt(animatedElement.style.top), 0);
		}
		
		var left = 0;
		if (animatedElement.style.left) 
		{
			left = Math.max(parseInt(animatedElement.style.left), 0);
		}
		
		var height = animatedElement.offsetHeight + top;
		if (element.style.height != height + "px") 
		{
			element.style.height = Math.max(height, 0) + "px";
		}
		
		var width = animatedElement.offsetWidth + left;
		if (element.style.width != width + "px") 
		{
			element.style.width = Math.max(width, 0) + "px";
		}
		
		if (this._overlay)
		{
			this._updateOverlay();
		}
	},
	
	show: function()
	{
		this._showElement();
	},
	
	expand: function()
	{	
		this._expanding = true;

		// Hide element before doing the calculations to prevent flicker.
		this.get_animatedElement().style.visibility = "hidden";

		this._resetState(true);

		var startPosition = null;
		var finalPosition = null;
		
		switch (this.get_direction())
		{
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Left:
				startPosition = parseInt(this._getSize());
				finalPosition = 0;
				break;
				
			case Telerik.Web.UI.SlideDirection.Down:
			case Telerik.Web.UI.SlideDirection.Right:
				startPosition = parseInt(this._getPosition());
				finalPosition = 0;
				break;
		}
	
		if (this._animation)
		{
			this._animation.stop();
		}

		if ((startPosition == finalPosition) ||
			(this._expandAnimation.get_type() == Telerik.Web.UI.AnimationType.None))
		{
			this._expandAnimationStarted();
			this._setPosition(finalPosition);		
			this._animationEnded();
			this.get_animatedElement().style.visibility = "visible";
		}
		else 
		{
			this._playAnimation(this._expandAnimation, startPosition, finalPosition);
		}
	},
	
	collapse: function()
	{
		this._resetState();
		this._expanding = false;
		
		var startPosition = null;
		var finalPosition = null;
		var size = parseInt(this._getSize());
		var position = parseInt(this._getPosition());

		switch (this.get_direction())
		{							
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Left:
				startPosition = 0;
				finalPosition = size;
			break;

			case Telerik.Web.UI.SlideDirection.Down:
			case Telerik.Web.UI.SlideDirection.Right:
				startPosition = 0;
				finalPosition = position - size;
				break;
		}
	
		if (this._animation)
		{
			this._animation.stop();
		}
		
		if ((startPosition == finalPosition) ||
			(this._collapseAnimation.get_type() == Telerik.Web.UI.AnimationType.None))
		{
			this._setPosition(finalPosition);
			this._animationEnded();
		}
		else 
		{
			this._playAnimation(this._collapseAnimation, startPosition, finalPosition);
		}
	},
	
	
	// Events
	add_collapseAnimationEnded : function(handler)
	{
		this.get_events().addHandler('collapseAnimationEnded', handler);
	},
	
	remove_collapseAnimationEnded : function(handler)
	{
		this.get_events().removeHandler('collapseAnimationEnded', handler);        
	},
	
	add_expandAnimationEnded : function(handler)
	{
		this.get_events().addHandler('expandAnimationEnded', handler);
	},
	
	remove_expandAnimationEnded : function(handler)
	{
		this.get_events().removeHandler('expandAnimationEnded', handler);        
	},
	
	add_expandAnimationStarted : function(handler)
	{
		this.get_events().addHandler('expandAnimationStarted', handler);
	},
	
	remove_expandAnimationStarted : function(handler)
	{
		this.get_events().removeHandler('expandAnimationStarted', handler);        
	},
	
	
	// Private methods
	_playAnimation: function(animationSettings, startPosition, finalPosition)
	{
		var duration = animationSettings.get_duration();
		var animatedProperty = this._getAnimatedStyleProperty();
		var points = Telerik.Web.UI.AnimationFunctions.CalculateAnimationPoints(animationSettings, startPosition, finalPosition, this._fps);
		var animatedElement = this.get_animatedElement();

		// Show the animatedElement after the calculations have been done.		
		animatedElement.style.visibility = "visible";
		
		if (this._animation)
		{
			this._animation.set_target(animatedElement);
			this._animation.set_duration(duration / 1000);
			this._animation.set_propertyKey(animatedProperty);
			this._animation.set_values(points);
		}
		else
		{
			this._animation = new $TWA.DiscreteAnimation(animatedElement, duration / 1000, this._fps, "style", animatedProperty, points);
			this._animation.add_started(this._expandAnimationStartedDelegate);
			this._animation.add_ended(this._animationEndedDelegate);
		
			if (this._overlay) 
			{
				this._animation.add_onTick(this._updateOverlayDelegate);
			}
		}
		
		this._animation.play();
	},
	
	_animationEnded: function()
	{
		if (this._expanding)
		{
			this.get_element().style.overflow = "visible";					
			this._raiseEvent('expandAnimationEnded', Sys.EventArgs.Empty);
		}
		else
		{
			this.get_element().style.display = "none";
			this._raiseEvent('collapseAnimationEnded', Sys.EventArgs.Empty);
		}
	
		if (this._overlay)
		{
			this._updateOverlay();
		}
	},
	
	_expandAnimationStarted: function()
	{
		this._raiseEvent('expandAnimationStarted', Sys.EventArgs.Empty);
	},
	
	_updateOverlay : function ()
	{
		this._overlay.updatePosition();
	},
	
	_showElement: function()
	{
		var animatedElement = this.get_animatedElement();
		var element = this.get_element();
		
		if (!element) 
			return;
		
		if (!element.style) 
			return;
		
		// Table elements do not work well with "block" display.
		element.style.display = (element.tagName.toUpperCase() != "TABLE") ? "block" : "";
		animatedElement.style.display = (animatedElement.tagName.toUpperCase() != "TABLE") ? "block" : "";
		
		element.style.overflow = "hidden";
	},
	
	_resetState: function(resetPosition)
	{
		this._stopAnimation();
		this._showElement();
	
		if (resetPosition) 
		{
			var animatedElement = this.get_animatedElement();
			switch (this.get_direction())
			{
				case Telerik.Web.UI.SlideDirection.Up:
					animatedElement.style.top = "0px";
					break;
					
				case Telerik.Web.UI.SlideDirection.Down:
					animatedElement.style.top = -animatedElement.offsetHeight + "px";
					break;
					
				case Telerik.Web.UI.SlideDirection.Left:
					animatedElement.style.left = animatedElement.offsetWidth + "px";
					break;
					
				case Telerik.Web.UI.SlideDirection.Right:
					animatedElement.style.left = -animatedElement.offsetWidth + "px";
					break;
					
				default:
					Error.argumentOutOfRange("direction", this.get_direction(), "Slide direction is invalid. Use one of the values in the Telerik.Web.UI.SlideDirection enumeration.");
					break;
			}
		}
	},
	
	_getSize : function ()
	{
		var animatedElement = this.get_animatedElement();
		
		switch (this.get_direction())
		{
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Down:
				return animatedElement.offsetHeight;
				break;

			case Telerik.Web.UI.SlideDirection.Left:
			case Telerik.Web.UI.SlideDirection.Right:
				return animatedElement.offsetWidth;
				break;
				
			default:
				return 0;
		}
	},
	
	_setPosition : function (value)
	{
		var animatedElement = this.get_animatedElement();
		var animatedProperty = this._getAnimatedStyleProperty();
		animatedElement.style[animatedProperty] = value;		
	},
	
	_getPosition: function()
	{
		var animatedElement = this.get_animatedElement();
		var animatedProperty = this._getAnimatedStyleProperty();
		
		return animatedElement.style[animatedProperty];
	},
	
	_getAnimatedStyleProperty: function()
	{
		switch (this.get_direction())
		{
			case Telerik.Web.UI.SlideDirection.Up:
			case Telerik.Web.UI.SlideDirection.Down:
				return "top";
				
			case Telerik.Web.UI.SlideDirection.Left:
			case Telerik.Web.UI.SlideDirection.Right:
				return "left";
		}
	},
	
	_stopAnimation : function()
	{
		if (this._animation) 
		{
			this._animation.stop();
		}
	},
	
	_disposeAnimation: function()
	{
		if (this._animation) 
		{
			this._animation.dispose();
			this._animation = null;
		}
	},
	
	_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.Slide.registerClass('Telerik.Web.UI.Slide', null, Sys.IDisposable);


/* END Telerik.Web.UI.Common.Navigation.Slide.js */
/* START Telerik.Web.UI.Common.Navigation.Overlay.js */
Type.registerNamespace("Telerik.Web.UI");


// ---------- Overlay Class ----------
Telerik.Web.UI.Overlay = function(targetElement)
{
	this._targetElement = targetElement;
	this._element = null;
}

Telerik.Web.UI.Overlay.IsSupported = function ()
{
	return $telerik.isIE;
}

Telerik.Web.UI.Overlay.prototype = 
{
	initialize: function()
	{
		//Using this workaround to set the contents of the iframe (required for sectio 508 compliance)
		
		var placeholder = document.createElement("div");
		placeholder.innerHTML = "<iframe>Your browser does not support inline frames or is currently configured not to display inline frames.</iframe>";
		this._element = placeholder.firstChild;
		this._element.src = "javascript:'';";
		this._targetElement.parentNode.insertBefore(this._element, this._targetElement);

		if (this._targetElement.style.zIndex > 0)
		{
			this._element.style.zIndex = this._targetElement.style.zIndex - 1;
		}
		this._element.style.position = "absolute";	
		this._element.style.border = "0px";	
		this._element.frameBorder = 0;
		this._element.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
		this._element.tabIndex = -1;
		
		this.updatePosition();
	},
	
	dispose: function()
	{
		if (this._element.parentNode)
		{
			this._element.parentNode.removeChild(this._element);
		}

		this._targetElement = null;
		this._element = null;
	},
	
	get_targetElement : function ()
	{
		return this._targetElement;
	},
	
	set_targetElement : function (value)
	{
		this._targetElement = value;
	},
	
	updatePosition: function()
	{
		this._element.style.top = this._toUnit(this._targetElement.style.top);
		this._element.style.left = this._toUnit(this._targetElement.style.left);
		this._element.style.width = this._targetElement.offsetWidth + "px";
		this._element.style.height = this._targetElement.offsetHeight + "px";	
	},
	
	_toUnit: function(value)
	{
		if (!value) return "0px";
		return parseInt(value) + "px";
	}
}

Telerik.Web.UI.Overlay.registerClass('Telerik.Web.UI.Overlay', null, Sys.IDisposable);


/* END Telerik.Web.UI.Common.Navigation.Overlay.js */
/* START Telerik.Web.UI.Common.Navigation.AnimationFunctions.js */
Type.registerNamespace("Telerik.Web.UI");

// ---------- AnimationType Enum ----------
Telerik.Web.UI.AnimationType = function () { };

Telerik.Web.UI.AnimationType.prototype =
{
	None: 0,
	Linear: 1,

	InQuad: 2,
	OutQuad: 3,
	InOutQuad: 4,

	InCubic: 5,
	OutCubic: 6,
	InOutCubic: 7,

	InQuart: 8,
	OutQuart: 9,
	InOutQuart: 10,

	InQuint: 11,
	OutQuint: 12,
	InOutQuint: 13,

	InSine: 14,
	OutSine: 15,
	InOutSine: 16,

	InExpo: 17,
	OutExpo: 18,
	InOutExpo: 19,

	InBack: 20,
	OutBack: 21,
	InOutBack: 22,

	InBounce: 23,
	OutBounce: 24,
	InOutBounce: 25,

	InElastic: 26,
	OutElastic: 27,
	InOutElastic: 28
}

Telerik.Web.UI.AnimationType.registerEnum("Telerik.Web.UI.AnimationType");

Telerik.Web.UI.AnimationFunctions = function () { };

Telerik.Web.UI.AnimationFunctions.CalculateAnimationPoints = function(animationSettings, startPosition, finalPosition, fps)
{
	if (startPosition == finalPosition) 
	{
		return [finalPosition + "px"];
	}
	
	var duration = animationSettings.get_duration() / 1000;
	var totalFrames = Math.round((duration) * fps);
	var animationFunction = Telerik.Web.UI.AnimationFunctions[animationSettings.get_type()];
	
	var points = new Array();
	var distance = Math.max(startPosition, finalPosition) - Math.min(startPosition, finalPosition);
	
	var direction = startPosition < finalPosition ? 1 : -1;
	var lastValue = 0;
	points[0] = startPosition + "px";
	for (var frameIx = 0; frameIx < totalFrames; frameIx++) 
	{
		var currentValue = animationFunction(frameIx / fps, 0, distance, duration);
		
		if (frameIx > 0) 
		{
			var lastPoint = parseInt(points[frameIx - 1]);
			var delta = direction * (Math.round(currentValue) - Math.round(lastValue));
			points[frameIx] = (lastPoint + delta) + "px";
		}
		
		lastValue = currentValue;
	}
	
	// Not all animation functions end the sequence at the exact desired position.
	points[totalFrames - 1] = finalPosition + "px";
	
	return points;
}

/*
Easing Equations v1.5
Open source under the BSD License.

Copyright � 2001 Robert Penner
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// simple linear tweening - no easing
// t: current time, b: beginning value, c: change in value, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.Linear] = function (t, b, c, d) {
	return c*t/d + b;
};


 ///////////// QUADRATIC EASING: t^2 ///////////////////

// quadratic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be in frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InQuad] = function (t, b, c, d) {
	return c*(t/=d)*t + b;
};

// quadratic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutQuad] = function (t, b, c, d) {
	return -c *(t/=d)*(t-2) + b;
};

// quadratic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutQuad] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
};


 ///////////// CUBIC EASING: t^3 ///////////////////////

// cubic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InCubic] = function (t, b, c, d) {
	return c*(t/=d)*t*t + b;
};

// cubic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutCubic] = function (t, b, c, d) {
	return c*((t=t/d-1)*t*t + 1) + b;
};

// cubic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutCubic] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t + b;
	return c/2*((t-=2)*t*t + 2) + b;
};


 ///////////// QUARTIC EASING: t^4 /////////////////////

// quartic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InQuart] = function (t, b, c, d) {
	return c*(t/=d)*t*t*t + b;
};

// quartic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutQuart] = function (t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

// quartic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutQuart] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
	return -c/2 * ((t-=2)*t*t*t - 2) + b;
};


 ///////////// QUINTIC EASING: t^5  ////////////////////

// quintic easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in value, d: duration
// t and d can be frames or seconds/milliseconds
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InQuint] = function (t, b, c, d) {
	return c*(t/=d)*t*t*t*t + b;
};

// quintic easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutQuint] = function (t, b, c, d) {
	return c*((t=t/d-1)*t*t*t*t + 1) + b;
};

// quintic easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutQuint] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
	return c/2*((t-=2)*t*t*t*t + 2) + b;
};



 ///////////// SINUSOIDAL EASING: sin(t) ///////////////

// sinusoidal easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InSine] = function (t, b, c, d) {
	return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
};

// sinusoidal easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutSine] = function (t, b, c, d) {
	return c * Math.sin(t/d * (Math.PI/2)) + b;
};

// sinusoidal easing in/out - accelerating until halfway, then decelerating
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutSine] = function (t, b, c, d) {
	return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
};


 ///////////// EXPONENTIAL EASING: 2^t /////////////////

// exponential easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InExpo] = function (t, b, c, d) {
	return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
};

// exponential easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutExpo] = function (t, b, c, d) {
	return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
};

// exponential easing in/out - accelerating until halfway, then decelerating
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutExpo] = function (t, b, c, d) {
	if (t==0) return b;
	if (t==d) return b+c;
	if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
	return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
};


 /////////// CIRCULAR EASING: sqrt(1-t^2) //////////////

// circular easing in - accelerating from zero velocity
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InCirc] = function (t, b, c, d) {
	return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
};

// circular easing out - decelerating to zero velocity
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutCirc] = function (t, b, c, d) {
	return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
};

// circular easing in/out - acceleration until halfway, then deceleration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutCirc] = function (t, b, c, d) {
	if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
	return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
};


 /////////// ELASTIC EASING: exponentially decaying sine wave  //////////////

// t: current time, b: beginning value, c: change in value, d: duration, a: amplitude (optional), p: period (optional)
// t and d can be in frames or seconds/milliseconds

Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InElastic] = function (t, b, c, d, a, p) {
	if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
	if ((!a) || a < Math.abs(c)) { a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
};

Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutElastic] = function (t, b, c, d, a, p) {
	if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
	if ((!a) || a < Math.abs(c)) { a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
};

Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutElastic] = function (t, b, c, d, a, p) {
	if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
	if ((!a) || a < Math.abs(c)) { a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
};


 /////////// BACK EASING: overshooting cubic easing: (s+1)*t^3 - s*t^2  //////////////

// back easing in - backtracking slightly, then reversing direction and moving to target
// t: current time, b: beginning value, c: change in value, d: duration, s: overshoot amount (optional)
// t and d can be in frames or seconds/milliseconds
// s controls the amount of overshoot: higher s means greater overshoot
// s has a default value of 1.70158, which produces an overshoot of 10 percent
// s==0 produces cubic easing with no overshoot
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InBack] = function (t, b, c, d, s) {
	if (s == undefined) s = 1.70158;
	return c*(t/=d)*t*((s+1)*t - s) + b;
};

// back easing out - moving towards target, overshooting it slightly, then reversing and coming back to target
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBack] = function (t, b, c, d, s) {
	if (s == undefined) s = 1.70158;
	return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
};

// back easing in/out - backtracking slightly, then reversing direction and moving to target,
// then overshooting target, reversing, and finally coming back to target
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutBack] = function (t, b, c, d, s) {
	if (s == undefined) s = 1.70158; 
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
};


 /////////// BOUNCE EASING: exponentially decaying parabolic bounce  //////////////

// bounce easing in
// t: current time, b: beginning value, c: change in position, d: duration
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InBounce] = function (t, b, c, d) {
	return c - Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBounce] (d-t, 0, c, d) + b;
};

// bounce easing out
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBounce] = function (t, b, c, d) {
	if ((t/=d) < (1/2.75)) {
		return c*(7.5625*t*t) + b;
	} else if (t < (2/2.75)) {
		return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
	} else if (t < (2.5/2.75)) {
		return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
	} else {
		return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
	}
};

// bounce easing in/out
Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InOutBounce] = function (t, b, c, d) {
	if (t < d/2) return Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.InBounce] (t*2, 0, c, d) * .5 + b;
	return Telerik.Web.UI.AnimationFunctions[Telerik.Web.UI.AnimationType.OutBounce] (t*2-d, 0, c, d) * .5 + c*.5 + b;
};

Telerik.Web.UI.AnimationFunctions.registerClass('Telerik.Web.UI.AnimationFunctions');


/* END Telerik.Web.UI.Common.Navigation.AnimationFunctions.js */
/* START Telerik.Web.UI.Common.Navigation.ControlItemContainer.js */
function WebForm_CallbackComplete() 
{
    for (var i = 0; i < __pendingCallbacks.length; i++) {
        var callbackObject = __pendingCallbacks[i];
        if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
            __pendingCallbacks[i] = null;
            WebForm_ExecuteCallback(callbackObject);
            if (!callbackObject.async) {
                __synchronousCallBackIndex = -1;
            }
            
            var callbackFrameID = "__CALLBACKFRAME" + i;
            var xmlRequestFrame = document.getElementById(callbackFrameID);
            if (xmlRequestFrame) {
                xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
            }
        }
    }
}

Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.ControlItemContainer = function (element)
{
	Telerik.Web.UI.ControlItemContainer.initializeBase(this, [element]);
	
	this._childControlsCreated = false;
	this._enabled = true;
	this._log = new Telerik.Web.UI.ChangeLog();
	this._enableClientStatePersistence = false;
	this._eventMap = new Telerik.Web.UI.EventMap();
	this._attributes = new Telerik.Web.UI.AttributeCollection(this);
	this._children = null;
}

Telerik.Web.UI.ControlItemContainer.prototype =
{
	initialize : function ()
	{
		Telerik.Web.UI.ControlItemContainer.callBaseMethod(this, 'initialize');

		this._ensureChildControls();
		this._log.initialize();
		this._initializeEventMap();
	},
	
	dispose : function ()
	{	
		this._eventMap.dispose();

		for (var i = 0; i < this._getChildren().get_count(); i++)
		{
			this._getChildren().getItem(i)._dispose();
		}

		Telerik.Web.UI.ControlItemContainer.callBaseMethod(this, 'dispose');
	},
	
	trackChanges : function ()
	{
		this._enableClientStatePersistence = true;
	},
	
	set_enabled: function(value)
	{
		this._enabled = value;
	},
	
	get_enabled: function()
	{
		return this._enabled;
	},
	
	commitChanges : function ()
	{
		this.updateClientState();
		this._enableClientStatePersistence = false;
	},
	
	get_attributes : function ()
	{
		return this._attributes;
	},
	
	set_attributes : function (value)
	{
		this._attributes._load(value);
	},
	
	
	/*------------- Private Methods -----------*/
	_initializeEventMap : function()
	{
		this._eventMap.initialize(this);
	},

	_getChildren : function ()
	{
		this._ensureChildControls();
		return this._children;
	},
	
	_extractErrorMessage : function (error)
	{
		if (error.get_message)
		{
			// AJAX Exception
			return error.get_message();
		}
		else
		{		
			// ASP.NET callback return error messages in the following form:
			// <exception message><eventValidationLength>|<eventValidationString> e.g.
			// Object reference not set to an instance of an object.56|/wEWAwLM2oLGBwLs0bLrBgLs0fbZDC3VMN/DL8xzHgo9Pw1ztfesraLy
			return error.replace(/(\d*\|.*)/,"");
		}
	},

	_notifyPropertyChanged : function (propertyName, propertyValue)
	{
		
	},
	
	_childInserting : function (index, item, parent)
	{
		
	},
	
	_childInserted : function (index, item, parent)
	{
		if (!parent._childControlsCreated) return;
		if (!parent.get_element()) return;
		
		itemElement = item._createDomElement();
		var parentListElement = parent.get_childListElement();
		
		if (!parentListElement) 
			parentListElement = parent._createChildListElement();
		
		var nextItem = item.get_nextSibling();
		var nextItemElement = nextItem ? nextItem.get_element() : null;
		parent.get_childListElement().insertBefore(itemElement, nextItemElement);
		
		if (!item.get_element()) 
		{
			item.set_element(itemElement);
			item._initializeRenderedItem();
		}
		else 
		{
			item.set_element(itemElement);
		}
	},
	
	_childrenCleared : function (parent)
	{
		for(var i = 0; i < parent._getChildren().get_count(); i++)
		{
			parent._getChildren().getItem(i)._dispose();
		}
		
		var childListElement = parent.get_childListElement();
		if(childListElement)
			childListElement.innerHTML = "";
	},
	
	_childRemoving : function (child)
	{
		this._logRemoving(child);
	},
	
	_childRemoved : function (item, parent)
	{
		item._dispose();
	},

	_createChildListElement : function()
	{
		throw Error.notImplemeneted();
	},

	_createDomElement : function()
	{
		throw Error.notImplemented();
	},

	_getControl : function ()
	{
		return this;
	},
	
	_logInserted : function (item)
	{
		if (!item.get_parent()._childControlsCreated || !this._enableClientStatePersistence) return;
		
		this._log.logInsert(item);
		
		var children = item._getAllItems();
		for (var i = 0; i < children.length; i++)					
		{
			this._log.logInsert(children[i]);
		}
	},
	
	_logRemoving : function (item)
	{
		if (this._enableClientStatePersistence)
			this._log.logDelete(item);
	},
	
	_logClearing : function (item)
	{
		if (this._enableClientStatePersistence)
			this._log.logClear(item);
	},
	
	_itemPropertyChanged : function (item, property, value)
	{
		if (this._enableClientStatePersistence)
			this._log.logPropertyChanged(item, property, value);
	},
	
	_ensureChildControls : function ()
	{
		if (!this._childControlsCreated)
		{		
			this._createChildControls();
			this._childControlsCreated = true;
		}
	},
	
	_extractItemFromDomElement : function (element)
	{
        this._ensureChildControls();
		while (element && element.nodeType !== 9)
		{
			if (element._item && this._verifyChildType(element._itemTypeName))
				return element._item;
				
			element = element.parentNode;
		}
		return null;
	},
	
	_verifyChildType : function (targetTypeName)
	{
		return targetTypeName === this._childTypeName;
	},
	
	_getAllItems : function ()
	{
		var allItems = [];
		for (var i = 0; i < this._getChildren().get_count(); i++)
		{
			var item = this._getChildren().getItem(i);
			Array.add(allItems, item);
			Array.addRange(allItems, item._getAllItems());
		}
		
		return allItems;
	},
	
	_findItemByText : function (text)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_text() == text)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByValue : function (value)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_value() == value)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByAttribute : function(attributeName, value)
	{
		var allItems = this._getAllItems();
		for (var i = 0; i < allItems.length; i++)
		{
			if (allItems[i].get_attributes().getAttribute(attributeName) == value)
				return allItems[i];
		}
		return null;
	},
	
	_findItemByHierarchicalIndex : function (index)
	{
		var currentItem = null;
		var container = this;
		var indexes = index.split(":");
		for (var i = 0; i < indexes.length; i++)
		{
			var currentIndex = parseInt(indexes[i]);
			if (container._getChildren().get_count() <= currentIndex)
				return null;

			currentItem = container._getChildren().getItem(currentIndex);
			container = currentItem;
		}

		return currentItem;
	}
}

Telerik.Web.UI.ControlItemContainer.registerClass("Telerik.Web.UI.ControlItemContainer", Telerik.Web.UI.RadWebControl);

/* END Telerik.Web.UI.Common.Navigation.ControlItemContainer.js */
/* START Telerik.Web.UI.Common.Navigation.ControlItemCollection.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.ControlItemCollection = function (parent)
{
	this._array = new Array();
	this._parent = parent;
	this._control = null;
}

Telerik.Web.UI.ControlItemCollection.prototype = 
{
	add : function (item)
	{	
		var index = this._array.length;
		this.insert(index, item);
	},
	
	insert : function (index, item)
	{
		var itemParent = item.get_parent();
		var control = this._parent._getControl();
		
		if(itemParent)
			itemParent._getChildren().remove(item);
		
		if (control)
			control._childInserting(index, item, this._parent);
			
		Array.insert(this._array, index, item);
		item.set_parent(this._parent);

		if (control)
		{
			control._childInserted(index, item, this._parent);
			control._logInserted(item);
		}
	},
	
	remove : function (item)
	{
		var control = this._parent._getControl();
		if (control)
			control._childRemoving(item);
		
		Array.remove(this._array, item);
		
		if (control)
			control._childRemoved(item, this._parent);
			
		item.set_parent(null);
		item._control = null;
	},
	
	removeAt : function (index)
	{
		var item = this.getItem(index);
		if (item)
			this.remove(item);
	},
	
	clear : function ()
	{
		var control = this._parent._getControl();
		if (control)
		{
			control._logClearing(this._parent);
			control._childrenCleared(this._parent);
		}
		
		this._array = new Array();
	},
	
	get_count : function ()
	{
		return this._array.length;
	},
	
	getItem : function(index)
	{
		return this._array[index];
	},
	
	indexOf : function (item)
	{
		return Array.indexOf(this._array, item);
	},

	forEach : function (lambda)
	{
	    for (var i = 0, count = this.get_count(); i < count; i++)
	    {
	        lambda(this._array[i]);
	    }
	}
}

Telerik.Web.UI.ControlItemCollection.registerClass("Telerik.Web.UI.ControlItemCollection");

/* END Telerik.Web.UI.Common.Navigation.ControlItemCollection.js */
/* START Telerik.Web.UI.Common.Navigation.PostbackWrapper.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI._PostbackWrapper = function ()
{
	this._doPostbackReplaced = false;
	this._events = new Sys.EventHandlerList();
	this._originalDoPostBack = null;
	this._onWindowUnloadHandler = null;
	this._postbackEventRaised = false;
	this._beginRequestHandler = null;
	this._onsubmitHandler = null;
	this._partialRenderingEnabledChecked = false;
	this._partialRenderingEnabled = false;
}

Telerik.Web.UI._PostbackWrapper.prototype =
{
	initialize : function()
	{
        this._onWindowUnloadHandler = Function.createDelegate(this, this._onWindowUnload);

        Sys.UI.DomEvent.addHandler(window, 'unload', this._onWindowUnloadHandler);
	},

	_raiseBeforePostback : function(eventArgs)
	{
		var handler = this._events.getHandler("beforePostback");
		if (handler)
		{
			if (!eventArgs)
			{
				eventArgs = Sys.EventArgs.Empty;
			}
			handler(this, eventArgs);
		}
		this._postbackEventRaised = true;
	},
	
	_doPostback : function(eventTarget, eventArgument)
	{
		this._raiseBeforePostback(Sys.EventArgs.Empty);
		this._originalDoPostBack(eventTarget, eventArgument);
	},
	
	_onSubmit : function()
	{
		if (!this._postbackEventRaised)
		{
			this._raiseBeforePostback(Sys.EventArgs.Empty);
		}
		return true;
	},
	
	_endRequest : function()
	{
		this._postbackEventRaised = false;
	},
	
	_isPartialRenderingEnabled : function()
	{
		if (!this._partialRenderingEnabledChecked)
		{
			this._partialRenderingEnabled = true;
			if (typeof(Sys) == "undefined")
			{
				this._partialRenderingEnabled = false;
			}
			else if (typeof(Sys.WebForms) == "undefined")
			{
				this._partialRenderingEnabled = false;
			}
			else if (typeof(Sys.WebForms.PageRequestManager) == "undefined")
			{
				this._partialRenderingEnabled = false;
			}
			else if (!Sys.WebForms.PageRequestManager.getInstance())
			{
			    this._partialRenderingEnabled = false;
			}
			this._partialRenderingEnabledChecked = true;
		}
		return this._partialRenderingEnabled;
	},
	
	add_beforePostback : function(handler)
	{
		if (!this._isPartialRenderingEnabled())
		{
			return;
		}
		if (!this._onsubmitHandler)
		{
			this._onsubmitHandler = Function.createDelegate(this, this._onSubmit);
			Array.add(Sys.WebForms.PageRequestManager.getInstance()._onSubmitStatements, this._onsubmitHandler);
		}
		if (!this._endRequestHandler)
		{
			this._endRequestHandler = Function.createDelegate(this, this._endRequest);
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this._endRequestHandler);
		}
		if (!this._doPostbackReplaced)
		{
			this._replaceDoPostback();
		}
		this._events.addHandler("beforePostback", handler);
	},

	remove_beforePostback : function(handler)
	{
		this._events.removeHandler("beforePostback", handler);
	},

	_replaceDoPostback : function()
	{
		if (typeof(Page_IsValid) != "undefined")
		{
			return;
		}
		this._originalDoPostBack = window.__doPostBack;
		if (this._originalDoPostBack)
		{
			window.__doPostBack = Function.createDelegate(this, this._doPostback);
        }

		this._doPostbackReplaced = true;
	},
	
    _onWindowUnload : function(rawEvent)
    {
        this.dispose();
    },

    dispose : function()
    {
		Sys.UI.DomEvent.removeHandler(window, 'unload', this._onWindowUnloadHandler);
		if (this._endRequestHandler)
		{
			Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this._endRequestHandler);
			this._endRequestHandler = null;
		}

        if (this._originalDoPostBack)
        {
			window.__doPostBack = this._originalDoPostBack;
			this._originalDoPostBack = null;
        }
    }
}

Telerik.Web.UI._PostbackWrapper.registerClass("Telerik.Web.UI._PostbackWrapper");

Telerik.Web.UI.PostbackWrapper = new Telerik.Web.UI._PostbackWrapper();
Telerik.Web.UI.PostbackWrapper.initialize();
/* END Telerik.Web.UI.Common.Navigation.PostbackWrapper.js */
/* START Telerik.Web.UI.Common.Navigation.ControlItem.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.PropertyBag = function (owner)
{
    Telerik.Web.UI.PropertyBag.initializeBase(this);
    this._data = {};
    this._owner = owner;
}

Telerik.Web.UI.PropertyBag.prototype = {
  getValue : function (propertyName, defaultValue)
  {
    var value = this._data[propertyName];
    
    if (typeof(value) === "undefined")
        return defaultValue;
    
    return value;
  },
  
  setValue : function (propertyName, value, notify)
  {
    this._data[propertyName] = value;
    
    if (notify)
        this._owner._notifyPropertyChanged(propertyName, value);
  },
  
  load : function (data)
  {
    this._data = data;
  }
};

Telerik.Web.UI.PropertyBag.registerClass('Telerik.Web.UI.PropertyBag');

Telerik.Web.UI.ControlItem = function()
{
	this._element = null;
	this._parent = null;
	this._text = null;
	this._children = null;
	this._childControlsCreated = false;
	this._itemData = null;
	this._control = null;
	this._properties = new Telerik.Web.UI.PropertyBag(this);
	this._attributes = new Telerik.Web.UI.AttributeCollection(this);
}

Telerik.Web.UI.ControlItem.prototype = 
{
	_shouldNavigate: function()
	{
		var navigateUrl = this.get_navigateUrl();
		if (!navigateUrl) return false;
		
		return !navigateUrl.endsWith("#");
	},
	
	_getNavigateUrl : function ()
	{
		if (this.get_linkElement())
		    return this._properties.getValue("navigateUrl", this.get_linkElement().getAttribute("href", 2));
		
		return this._properties.getValue("navigateUrl", null);
	},
	
	_initialize: function(json, element)
	{
		this.set_element(element);
		
		this._properties.load(json);
		
		if (typeof(json["attributes"]) != "undefined")
			this._attributes._load(json["attributes"]);
			
		this._itemData = json["items"];
	},
		
	_dispose: function()
	{
		if (this._children) 
			this._children.forEach(function(child) { child._dispose(); } );
		
		if (this._element) 
		{
			this._element._item = null;
			this._element = null;
		}
		
		if (this._control) 
			this._control = null;
	},


	// Public methods

	_initializeRenderedItem: function()
	{
		var childItems = this._children;
		if (!childItems || childItems.get_count() < 1) 
			return;
		
		var childElements = this._getChildElements();
		Sys.Debug.assert(childItems.get_count() == childElements.length, "Length of elements and child items must be the same!");
		
		for (var i = 0, length = childItems.get_count(); i < length; i++) 
		{
			var childItem = childItems.getItem(i);
			if (!childItem.get_element()) 
			{
				childItem.set_element(childElements[i]);
				if (this._shouldInitializeChild(childItem)) 
				{
					childItem._initializeRenderedItem();
				}
			}
		}
	},
	
	get_attributes : function ()
	{
		return this._attributes;
	},
	
	// Public properties
	
	get_element: function()
	{
		return this._element;
	},
	
	set_element: function(value)
	{
		this._element = value;
		this._element._item = this;
		this._element._itemTypeName = Object.getTypeName(this);
	},
	
	get_parent: function()
	{
		return this._parent;
	},
	
	set_parent: function(value)
	{
		this._parent = value;
	},
	
	get_text : function ()
	{
		 if (this._text !== null) return this._text;

        if (this._text = this._properties.getValue("text", ""))
            return this._text;
		
		if (!this.get_element())
			return "";
		
		var textElement = this.get_textElement();
		if (!textElement)
			return "";

		if (typeof(textElement.innerText) != "undefined")
			this._text = textElement.innerText;
		else
			this._text = textElement.textContent;
			
		if($telerik.isSafari2)
		{
			this._text = textElement.innerHTML;
		}
		return this._text;
	},

	set_text : function (text)
	{ 
	    var textElement = this.get_textElement();
	    if (textElement)
			textElement.innerHTML = text;
	    
	    this._text = text;
	    this._properties.setValue("text", text, true);	    
	},
		
	get_value: function()
	{
		return this._properties.getValue("value", null);
	},
	
	set_value: function(value)
	{
		this._properties.setValue("value", value, true);
	},
	
	get_itemData: function()
	{
		return this._itemData;
	},
	
	get_index : function ()
	{
		if (!this.get_parent())
			return -1;
			
		return this.get_parent()._getChildren().indexOf(this);
	},
	
	set_enabled: function(value)
	{
		this._properties.setValue("enabled", value, true);
	},
	
	get_enabled: function()
	{
		return this._properties.getValue("enabled", true) == true;
	},
	
	get_isEnabled : function()
	{
		var control = this._getControl();
		if (control)
			return control.get_enabled() && this.get_enabled();
		
		return this.get_enabled();
	},
	
	set_visible: function(value)
	{
		this._properties.setValue("visible", value);
	},
	
	get_visible: function()
	{
		return this._properties.getValue("visible", true);
	},
	
	get_level : function ()
	{
		var parent = this.get_parent();
		var level = 0;
			
		while (parent) 
		{
			
			if (Telerik.Web.UI.ControlItemContainer.isInstanceOfType(parent)) 
			{
				return level;
			}
			
			level++;
			parent = parent.get_parent();
		}
		
		return level;
	},
	
	get_isLast : function()
	{
		return this.get_index() == this.get_parent()._getChildren().get_count() - 1;
	},
	
	get_isFirst : function()
	{
		return this.get_index() == 0;
	},
	
	get_nextSibling : function ()
	{
		if (!this.get_parent())
			return null;
		return this.get_parent()._getChildren().getItem(this.get_index() + 1);
	},
	
	get_previousSibling : function ()
	{
		if (!this.get_parent())
			return null;
		
		return this.get_parent()._getChildren().getItem(this.get_index() - 1);
	},
	
	// Private methods
	_getHierarchicalIndex : function () 
	{
		var indexes = [];
		var current = this;
		
		while (!Telerik.Web.UI.ControlItemContainer.isInstanceOfType(current))
		{
			Array.insert(indexes, 0, current.get_index());
			current = current.get_parent();
		}
		
		return indexes.join(":");
	},
	
	_getChildren : function()
	{
		this._ensureChildControls();
		return this._children;
	},
	
	_ensureChildControls: function()
	{
		if (!this._childControlsCreated) 
		{
			this._createChildControls();
			this._childControlsCreated = true;
		}
	},

	_setCssClass : function(element, cssClass)
	{
		if (element.className != cssClass)
			element.className = cssClass;
	},

	_createChildControls: function()
	{
		this._children = this._createItemCollection();
	},
	
	_createItemCollection : function()
	{
	},
	
	_getControl: function()
	{
		if (!this._control) 
		{
			var parent = this.get_parent();
			
			if (parent) 
			{
				if (Telerik.Web.UI.ControlItemContainer.isInstanceOfType(parent)) 
				{
					this._control = parent;
				}
				else 
				{
					this._control = parent._getControl();
				}
			}
		}
		
		return this._control;
	},
	
	_getAllItems: function()
	{
		var items = [];
		this._getAllItemsRecursive(items, this);
		return items;
	},
	
	_getAllItemsRecursive: function(items, currentItem)
	{
		var children = currentItem._getChildren();
		for (var i = 0; i < children.get_count(); i++) 
		{
			var child = children.getItem(i);
			Array.add(items, child);
			this._getAllItemsRecursive(items, child);
		}
	},
	
	_getData: function()
	{
		var data = this._properties._data;
		
		//we don't need this - it comes from the initial JSON
		delete data.items;	
		
		data["text"] = this.get_text()
		
		if (this.get_attributes().get_count() > 0)
			data["attributes"] = this.get_attributes()._data;
		
		return data;
	},
	
	_notifyPropertyChanged: function(property, value)
	{
		var control = this._getControl();
		if (control) 
			control._itemPropertyChanged(this, property, value);
	},
	
	_loadFromDictionary : function (data)
	{
		if (typeof(data.Text) != "undefined")
			this.set_text(data.Text);

		if (typeof(data.Value) != "undefined" && data.Value !== "")
			this.set_value(data.Value);
		
		if (typeof(data.Enabled) != "undefined" && data.Enabled !== true)
			this.set_enabled(data.Enabled);

		var attributes = this.get_attributes();
		for (var attributeKey in data.Attributes)
		{
			attributes.setAttribute(attributeKey, data.Attributes[attributeKey]);
		}
	},
	
	_createDomElement: function()
	{
		var itemElementParent = document.createElement("ul");
		var html = [];
		
		this._render(html);
		
		itemElementParent.innerHTML = html.join("");
		return itemElementParent.firstChild;
	}
}

Telerik.Web.UI.ControlItem.registerClass('Telerik.Web.UI.ControlItem');


/* END Telerik.Web.UI.Common.Navigation.ControlItem.js */
/* START Telerik.Web.UI.Menu.ClientEvents.js */
// ---------- RadMenuItemEventArgs Class ----------
Telerik.Web.UI.RadMenuItemEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemEventArgs.initializeBase(this);
	this._item = item;
	this._domEvent = domEvent || null;
}

Telerik.Web.UI.RadMenuItemEventArgs.prototype =
{
	get_item : function ()
	{
		return this._item;
	},
	get_domEvent : function()
	{
		return this._domEvent;
	}
}
Telerik.Web.UI.RadMenuItemEventArgs.registerClass('Telerik.Web.UI.RadMenuItemEventArgs', Sys.EventArgs);


// ---------- RadMenuItemCancelEventArgs Class ----------
Telerik.Web.UI.RadMenuItemCancelEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemCancelEventArgs.initializeBase(this);
	this._item = item;
	this._domEvent = domEvent || null;
}

Telerik.Web.UI.RadMenuItemCancelEventArgs.prototype =
{
	get_item : function ()
	{
		return this._item;
	},
	get_domEvent : function()
	{
		return this._domEvent;
	}
}
Telerik.Web.UI.RadMenuItemCancelEventArgs.registerClass('Telerik.Web.UI.RadMenuItemCancelEventArgs', Sys.CancelEventArgs);


// ---------- RadMenuMouseOverEventArgs Class ----------
Telerik.Web.UI.RadMenuMouseOverEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuMouseOverEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuMouseOverEventArgs.registerClass('Telerik.Web.UI.RadMenuMouseOverEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuMouseOutEventArgs Class ----------
Telerik.Web.UI.RadMenuMouseOutEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuMouseOutEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuMouseOutEventArgs.registerClass('Telerik.Web.UI.RadMenuMouseOutEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuItemFocusEventArgs Class ----------
Telerik.Web.UI.RadMenuItemFocusEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemFocusEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemFocusEventArgs.registerClass('Telerik.Web.UI.RadMenuItemFocusEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuItemBlurEventArgs Class ----------
Telerik.Web.UI.RadMenuItemBlurEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemBlurEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemBlurEventArgs.registerClass('Telerik.Web.UI.RadMenuItemBlurEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuItemClickingEventArgs Class ----------
Telerik.Web.UI.RadMenuItemClickingEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemClickingEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemClickingEventArgs.registerClass('Telerik.Web.UI.RadMenuItemClickingEventArgs', Telerik.Web.UI.RadMenuItemCancelEventArgs);


// ---------- RadMenuItemClickedEventArgs Class ----------
Telerik.Web.UI.RadMenuItemClickedEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemClickedEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemClickedEventArgs.registerClass('Telerik.Web.UI.RadMenuItemClickedEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuItemOpeningEventArgs Class ----------
Telerik.Web.UI.RadMenuItemOpeningEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemOpeningEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemOpeningEventArgs.registerClass('Telerik.Web.UI.RadMenuItemOpeningEventArgs', Telerik.Web.UI.RadMenuItemCancelEventArgs);


// ---------- RadMenuItemOpenedEventArgs Class ----------
Telerik.Web.UI.RadMenuItemOpenedEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemOpenedEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemOpenedEventArgs.registerClass('Telerik.Web.UI.RadMenuItemOpenedEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuItemClosingEventArgs Class ----------
Telerik.Web.UI.RadMenuItemClosingEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemClosingEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemClosingEventArgs.registerClass('Telerik.Web.UI.RadMenuItemClosingEventArgs', Telerik.Web.UI.RadMenuItemCancelEventArgs);


// ---------- RadMenuItemClosedEventArgs Class ----------
Telerik.Web.UI.RadMenuItemClosedEventArgs = function(item, domEvent)
{
	Telerik.Web.UI.RadMenuItemClosedEventArgs.initializeBase(this, [item, domEvent || null]);
}
Telerik.Web.UI.RadMenuItemClosedEventArgs.registerClass('Telerik.Web.UI.RadMenuItemClosedEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuItemPopulatingEventArgs Class ----------
Telerik.Web.UI.RadMenuItemPopulatingEventArgs = function(item, context)
{
	Telerik.Web.UI.RadMenuItemPopulatingEventArgs.initializeBase(this, [item]);

	this._context = context;
}

Telerik.Web.UI.RadMenuItemPopulatingEventArgs.prototype =
{
	get_context : function ()
	{
		return this._context;
	}
}
Telerik.Web.UI.RadMenuItemPopulatingEventArgs.registerClass('Telerik.Web.UI.RadMenuItemPopulatingEventArgs', Telerik.Web.UI.RadMenuItemCancelEventArgs);


// ---------- RadMenuItemPopulatedEventArgs Class ----------
Telerik.Web.UI.RadMenuItemPopulatedEventArgs = function(item)
{
	Telerik.Web.UI.RadMenuItemPopulatedEventArgs.initializeBase(this, [item]);
}
Telerik.Web.UI.RadMenuItemPopulatedEventArgs.registerClass('Telerik.Web.UI.RadMenuItemPopulatedEventArgs', Telerik.Web.UI.RadMenuItemEventArgs);


// ---------- RadMenuItemPopulationFailedEventArgs Class ----------
Telerik.Web.UI.RadMenuItemPopulationFailedEventArgs = function(item, errorMessage)
{
	Telerik.Web.UI.RadMenuItemPopulationFailedEventArgs.initializeBase(this, [item]);
	
	this._errorMessage = errorMessage;
}

Telerik.Web.UI.RadMenuItemPopulationFailedEventArgs.prototype =
{
	get_errorMessage : function ()
	{
		return this._errorMessage;
	}
}
Telerik.Web.UI.RadMenuItemPopulationFailedEventArgs.registerClass('Telerik.Web.UI.RadMenuItemPopulationFailedEventArgs', Telerik.Web.UI.RadMenuItemCancelEventArgs);

/* END Telerik.Web.UI.Menu.ClientEvents.js */
/* START Telerik.Web.UI.Menu.Scroller.js */
// ---------- MenuItemScroller Class ----------
Telerik.Web.UI.MenuItemScroller = function(childListElement, itemFlow)
{
	// Constants
	this._leftArrowCssClass = "rmLeftArrow";
	this._rightArrowCssClass = "rmRightArrow";
	this._topArrowCssClass = "rmTopArrow";
	this._bottomArrowCssClass = "rmBottomArrow";

	this._leftArrowDisabledCssClass = "rmLeftArrowDisabled";
	this._rightArrowDisabledCssClass = "rmRightArrowDisabled";
	this._topArrowDisabledCssClass = "rmTopArrowDisabled";
	this._bottomArrowDisabledCssClass = "rmBottomArrowDisabled";
	
	this._arrowsZIndex = 2000;

	this._scroller = null;
	this._childListElement = childListElement;
	this._scrollElement = null;
	this._orientation = null;
	this._minScrollPosition = null;

	this._itemFlow = itemFlow;

	this._scrollerPositionChangedDelegate = null;
	
	// Aliases for the current active arrow pair.
	this._decArrow = null; // Left (Top)
	this._incArrow = null; // Right (Bottom)
}

Telerik.Web.UI.MenuItemScroller.prototype = 
{
	initialize: function()
	{
		this._childListElement.style.position = "relative";
		
		this._scrollElement = this._childListElement.parentNode;	
		
		this._orientation = Telerik.Web.UI.ScrollerOrientation.Horizontal;
		if (this._itemFlow == Telerik.Web.UI.ItemFlow.Vertical)
		{
			this._orientation = Telerik.Web.UI.ScrollerOrientation.Vertical;
		}
		
		this._scroller = new Telerik.Web.UI.Scroller(this._childListElement, this._scrollElement, this._orientation);
		this._scroller.initialize();
		
		this._createArrows();
		this._scroller.resetState();
		
		this._scrollerPositionChangedDelegate = Function.createDelegate(this, this._onScrollerPositionChanged);
		this._scroller.add_positionChanged(this._scrollerPositionChangedDelegate);
	},
	
	dispose: function()
	{
		if (this._scroller)
		{
			this._scroller.dispose();
			this._scroller = null;
		}
		
		this._scrollerPositionChangedDelegate = null;
	},
	
	
	// Public methods
	
	updateState : function ()
	{
		this._updateScrollingLimits();
		this._updateArrows();
	},
	
	resetState : function ()
	{
		this._scroller.resetState();
	},
	
	startScroll : function (speed, direction)
	{
		this._scroller.startScroll(speed, direction);
	},
	
	changeScrollSpeed : function (speed)
	{
		this._scroller.changeScrollSpeed(speed);
	},
	
	stopScroll : function ()
	{
		this._scroller.stopScroll();
	},

	_createArrows : function ()
	{
		this._decArrow = this._createArrowDomElement();
		this._incArrow = this._createArrowDomElement();
		
		if (this._orientation == Telerik.Web.UI.ScrollerOrientation.Vertical)
		{			
			this._decArrow.style.left = "0px";	
			this._decArrow.style.top = "0px";

			this._incArrow.style.left = "0px";
			this._incArrow.style.bottom = "0px";
		}
		else
		{			
			this._decArrow.style.top = "0px";
			this._decArrow.style.left = "-1px";

			this._incArrow.style.top = "0px";
			this._incArrow.style.right = "-1px";
		}
	},
	
	_createArrowDomElement : function ()
	{
	    var arrow = document.createElement("a");
	    arrow.href = "#";
		arrow.style.zIndex = this._arrowsZIndex;
		arrow.appendChild(document.createTextNode("&nbsp;"));

		this._scrollElement.appendChild(arrow);
		
		return arrow;		
	},
	
	_updateArrows : function ()
	{
		var isAtMinPosition = this._scroller.isAtMinPosition();
		var isAtMaxPosition = this._scroller.isAtMaxPosition();

		if (isAtMinPosition)
		{
			this._decArrow.disabled = "disabled";
			this._setElementCssClass(this._decArrow, this._getDecArrowCssClass(false));
		}
		else
		{
			this._decArrow.disabled = "";
			this._setElementCssClass(this._decArrow, this._getDecArrowCssClass(true));
		}

		if (isAtMaxPosition)
		{
			this._incArrow.disabled = "disabled";
			this._setElementCssClass(this._incArrow, this._getIncArrowCssClass(false));
		}
		else
		{
			this._incArrow.disabled = "";
			this._setElementCssClass(this._incArrow, this._getIncArrowCssClass(true));
		}
	},

	_updateScrollingLimits : function ()
	{
		var totalSize = 0;
		var decArrowSize = 0;
		var incArrowSize = 0;
		
		if (this._orientation == Telerik.Web.UI.ScrollerOrientation.Vertical)
		{
			totalSize = this._childListElement.offsetHeight - this._scrollElement.offsetHeight;
			decArrowSize = this._decArrow.offsetHeight;
			incArrowSize = this._incArrow.offsetHeight;
		}
		else
		{
			totalSize = this._childListElement.offsetWidth - this._scrollElement.offsetWidth;
			decArrowSize = this._decArrow.offsetWidth;
			incArrowSize = this._incArrow.offsetWidth;
		}
		
		var minPosition = 0;
		var maxPosition = totalSize;
		// var maxPosition = totalSize + decArrowSize + incArrowSize;
		
		// Not implemented yet.
		// this._scroller.setOffset(decArrowSize);
		
		this._scroller.setScrollingLimits(minPosition, maxPosition);
	},
	
	_getDecArrowCssClass : function (isEnabled)
	{
		if (this._orientation == Telerik.Web.UI.ScrollerOrientation.Vertical)
		{
			return isEnabled ? this._topArrowCssClass : this._topArrowDisabledCssClass;
		}
		else
		{
			return isEnabled ? this._leftArrowCssClass : this._leftArrowDisabledCssClass;
		}
	},
	
	_getIncArrowCssClass : function (isEnabled)
	{
		if (this._orientation == Telerik.Web.UI.ScrollerOrientation.Vertical)
		{
			return isEnabled ? this._bottomArrowCssClass : this._bottomArrowDisabledCssClass;
		}
		else
		{
			return isEnabled ? this._rightArrowCssClass : this._rightArrowDisabledCssClass;
		}
	},
	
	_setElementCssClass : function (element, cssClass)
	{
		var oldCssClass = element.className;
		if (oldCssClass != cssClass)
		{
			element.className = cssClass;
		}
	},
	
	_onScrollerPositionChanged : function(sender, eventArgs)
	{
		this._updateArrows();
	}
}

Telerik.Web.UI.MenuItemScroller.registerClass('Telerik.Web.UI.MenuItemScroller', null, Sys.IDisposable);
/* END Telerik.Web.UI.Menu.Scroller.js */
/* START Telerik.Web.UI.Menu.RadMenuItem.js */
// ---------- RadMenuItem Class ----------
Type.registerNamespace("Telerik.Web.UI");


Telerik.Web.UI.RadMenuItemState = function()
{
};
Telerik.Web.UI.RadMenuItemState.prototype = 
{
	Closed: 0,
	Open: 1,
	AboutToClose: 2,
	AboutToOpen: 3
}
Telerik.Web.UI.RadMenuItemState.registerEnum("Telerik.Web.UI.RadMenuItemState");


Telerik.Web.UI.MenuItemExpandMode = function (){}
Telerik.Web.UI.MenuItemExpandMode.prototype = 
{
	ClientSide : 0,
	WebService : 1
}

Telerik.Web.UI.MenuItemExpandMode.registerEnum("Telerik.Web.UI.MenuItemExpandMode");


Telerik.Web.UI.RadMenuItem = function()
{
	Telerik.Web.UI.RadMenuItem.initializeBase(this);
	
	// Constants
	this._zIndexStep = 1000;
	this._scrollWrapCssClass = "rmScrollWrap";
	this._groupCssClass = "rmGroup";
	this._levelCssClass = "rmLevel";
	this._horizontalCssClass = "rmHorizontal";
	this._verticalCssClass = "rmVertical";
	this._leftImageCssClass = "rmLeftImage";
	this._defaultDisabledCssClass = "rmDisabled";
	this._defaultExpandedCssClass = "rmExpanded";
	this._defaultFocusedCssClass = "rmFocused";
	this._defaultClickedCssClass = "rmClicked";
	this._defaultScrollSize = 16;
	
	this._menu = null;
	this._groupSettings = new Telerik.Web.UI.RadMenuItemGroupSettings({});
	
	this._imageUrl = null;
	
	this._flow = null;
	
	this._openedItem = null;
	this._timeoutRef = null;
	this._focused = false;
	this._clicked = false;
	this._hovered = false;
	this._isImageOnly = null;
	this._itemsLoaded = false;
	this._itemsLoading = false;
	this._adjustSiblingsWidthOnShow = false;
	
	this._state = Telerik.Web.UI.RadMenuItemState.Closed;
	
	this._linkElement = null;
	this._imageElement = null;
	this._childListElement = null;
	this._scrollWrapElement = null;
	this._slideWrapElement = null;
	this._animatedElement = null;
	this._animationContainer = null;
	this._childrenDetached = false;
	this._autoScrollActive = false;
	
	this._collapseAnimationEndedDelegate = null;
	
	this._slide = null;
	this._scroller = null;
	this._styleCssText = null;
}

Telerik.Web.UI.RadMenuItem.prototype = 
{
	// Initialization and disposing
	
	_initialize: function(json, element)
	{
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, '_initialize', [json, element]);
		
		var menu = this.get_menu();
		if (typeof(json.groupSettings) != "undefined") 
			this._groupSettings = new Telerik.Web.UI.RadMenuItemGroupSettings(json.groupSettings, menu.get_defaultGroupSettings());
		
		this._initializeAnimation();
		this._updateTextElementClass();
		this._renderAccessKey();
	},
	
	_dispose: function()
	{
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, '_dispose');
		
		if (this._collapseAnimationEndedDelegate) 
		{
			if (this._slide) 
			{
				this._slide.remove_collapseAnimationEnded(this._collapseAnimationEndedDelegate);
			}
			
			this._collapseAnimationEndedDelegate = null;
		}
		
		if (this._slide) 
		{
			this._slide.dispose();
			this._slide = null;
		}
		
		if (this._scroller)
		{
			this._scroller.dispose();
			this._scroller = null;
		}
		
		var animationContainer = this._getAnimationContainer();
		if (animationContainer)
		{
			animationContainer._item = null;
			animationContainer._itemTypeName = null;
		}
		
		this._clearTimeout();
	},
	
	_initializeRenderedItem: function()
	{
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, '_initializeRenderedItem');
		this._initializeAnimation();
		this._updateTextElementClass();
		this._updateLinkClass();
		this._renderAccessKey();
	},
	
	
	// Public properties
	
	get_linkElement: function()
	{
		if (!this._linkElement) 
		{
			this._linkElement = $telerik.getFirstChildByTagName(this.get_element(), "a", 0);
		}
		
		return this._linkElement;
	},
	
	get_childListElement: function()
	{
		if (!this._childListElement) 
		{
			var slideWrapElement = this._getSlideWrapElement();
			if (slideWrapElement) 
			{
				var container = slideWrapElement;
				
				var scrollWrapElement = this._getScrollWrapElement();
				if (scrollWrapElement) 
				{
					container = scrollWrapElement;
				}
				
				this._childListElement = $telerik.getFirstChildByTagName(container, "ul", 0);
			}
		}
		return this._childListElement;
	},
	
	get_imageElement: function()
	{
		if (!this._imageElement)
		{
			var linkElement = this.get_linkElement();
			var element = this.get_element();
			
			this._imageElement = $telerik.getFirstChildByTagName(linkElement || element, "img", 0);
		}
		
		return this._imageElement;
	},
	
	get_textElement: function()
	{
		var link = this.get_linkElement();
		if (link) 
		{
			return $telerik.getChildByClassName(link, "rmText", 0);
		}
		else 
		{
			return null;
		}
	},
	
	get_menu: function()
	{
		return this._getControl();
	},
	
	get_items : function ()
	{
		return this._getChildren();
	},
	
	set_text: function(value)
	{
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, 'set_text', [value]);
		this._adjustSiblingsWidthOnShow = true;
	},
	
	get_navigateUrl : function()
	{
		return this._getNavigateUrl();
	},
	
	set_navigateUrl : function (value)
	{
		this._properties.setValue("navigateUrl", value, true);
		
		if (this.get_linkElement())
			this.get_linkElement().href = value;
	},
	
	get_target : function ()
	{
		return this._properties.getValue("target", null);
	},
	
	set_target : function (value)
	{
		this._properties.setValue("target", value);
		if (this.get_linkElement())
			this.get_linkElement().target = value;
	},
	
	get_groupSettings: function()
	{
		return this._groupSettings;
	},
	
	set_groupSettings: function(value)
	{
		this._groupSettings = value;
	},
	_getNextItem: function ()
	{
		var parentItems = this.get_parent().get_items();
		var index = this.get_index();
		if (index == parentItems.get_count() - 1)
		{
			return parentItems.getItem(0);
		}
		
		return parentItems.getItem(index + 1);
	},
	
	_getPreviousItem: function ()
	{
		var parentItems = this.get_parent().get_items();
		var index = this.get_index();
		if (index == 0)
		{
			return parentItems.getItem(parentItems.get_count() - 1);
		}
		
		return parentItems.getItem(index - 1);
	},
	
	_focus: function(e)
	{
		this._setFocused(true, e);
	},
	
	_blur : function(e)
	{
		this._setFocused(false, e);
	},
	
	_setFocused: function(value, e)
	{
		if (value)
		{
			this._doFocus(e);
		}
		else 
		{
			this._doBlur(e);
		}

		this._focused = value;
		this._updateLinkClass();
	},

	_open: function(e)
	{
		var menu = this.get_menu();
		var openingArgs = new Telerik.Web.UI.RadMenuItemOpeningEventArgs(this, e);
		menu._raiseEvent("itemOpening", openingArgs);

		if (openingArgs.get_cancel()) 
		{
			return;
		}

		if (this._isWebServiceCallNeeded())
		{
			this._loadChildrenFromWebService();
			return;
		}

		this._doOpen(e);
	},

	_close: function(e)
	{
		if (this.get_isSeparator() || this._state == Telerik.Web.UI.RadMenuItemState.Closed) 
		{
			return;
		}	
		
		var closingArgs = new Telerik.Web.UI.RadMenuItemClosingEventArgs(this, e);
		this.get_menu()._raiseEvent("itemClosing", closingArgs);
		
		if (closingArgs.get_cancel())
		{
			return;
		}
		
		if (this._openedItem) 
		{
			this._openedItem._close(e);
		}
		
		var parent = this.get_parent();
		parent._openedItem = null;

		if (!this._getAnimationContainer()) 
		{
			return;
		}
				
		this._state = Telerik.Web.UI.RadMenuItemState.Closed;

		var menu = this.get_menu();
		if (this.get_level() == 0) 
		{
			menu._aboutToCollapse = true;
		}

		// Clear the z-index, so other opening items can overlap us.
		if (!this._getIsImageOnly())
		{
			// Only do so if we are not in image-only mode, otherwise the next item will overlap us.
			this.get_element().style.zIndex = 0;
		}
		
		this._slide.collapse();

		this._updateLinkClass();		
		this._updateImageSrc();
		
		var closedArgs = new Telerik.Web.UI.RadMenuItemClosedEventArgs(this, e);
		this.get_menu()._raiseEvent("itemClosed", closedArgs);
		
		this._closeChildren(e);
	},

	get_nextItem: function()
	{
		return this.get_nextSibling();
	},
	
	get_previousItem: function()
	{
		return this.get_previousSibling();
	},
	
	get_focusedItem: function()
	{
		return this._focusedItem;
	},
	
	get_isSeparator: function()
	{
		return this._properties.getValue("isSeparator", false);
	},
	
	set_isSeparator : function (value)
	{
		this._properties.setValue("isSeparator", value, true);
	},
	
	get_openedItem: function()
	{
		return this._openedItem;
	},
	
	get_templated : function ()
	{
		return this._properties.getValue("templated", false) == true;
	},
	
	get_cssClass : function ()
	{
		return this._properties.getValue("cssClass", "");
	},
	
	set_cssClass : function (value)
	{
		this._properties.setValue("cssClass", value, true);
	},
	
	get_focused : function ()
	{
		return this._focused;
	},
	
	set_focused : function (value)
	{
		this._setFocused(value);
	},
	
	get_hoveredImageUrl: function()
	{
		return this._properties.getValue("hoveredImageUrl", null);
	},
	
	set_hoveredImageUrl: function(value)
	{
		this._properties.setValue("hoveredImageUrl", value, true);
		this._updateImageSrc();
	},
	
	get_clickedImageUrl : function ()
	{
		return this._properties.getValue("clickedImageUrl", null);
	},
	
	set_clickedImageUrl : function (value)
	{
		this._properties.setValue("clickedImageUrl", value, true);
		this._updateImageSrc();
	},
		
	get_imageUrl: function()
	{
		if (!this._imageUrl) 
		{
			var imageElement = this.get_imageElement();
			if (imageElement) 
			{
				this._imageUrl = imageElement.src;
			}
		}
		
		return this._imageUrl;
	},
	
	set_imageUrl: function(value)
	{
		this._imageUrl = value;
		this._properties.setValue("imageUrl", value, true);
		this._updateImageSrc();
	},
	
	set_visible : function (value)
	{
		var valueChanged = this.get_visible() != value;
		if (!valueChanged)
		{
			return;
		}
		
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, 'set_visible', [value]);

		this._adjustSiblingsWidthOnShow = true;
		this._clearWidth();

		var displayValue = value ? "" : "none";	

		var linkElement = this.get_linkElement();
		var textElement = this.get_textElement();
		var elementToHide;
	    if (linkElement)
	    {
			elementToHide = linkElement;
	    }
	    else if (textElement)
	    {
			elementToHide = textElement;
	    }

	    if (this.get_isSeparator() || this.get_templated())
	    {
			elementToHide = this.get_element().childNodes[0];
	    }

		elementToHide.style.display = displayValue;

		if (this.get_visible())
		{
			this.get_element().style.cssText = this._styleCssText;
		}
		else
		{
			this._styleCssText = this.get_element().style.cssText;
			this.get_element().style.cssText = "padding:0px;margin:0px;height:0px;overflow:hidden;";
		}


		var parentFlow = this._getParentFlow();
	    if (parentFlow == Telerik.Web.UI.ItemFlow.Vertical)    
	    {
			if (!value) 
			{
				this._clearSiblingsWidth();
			}
			
			var parent = this.get_parent();
	        if (parent.get_element().offsetWidth > 0)
	        {
	            Telerik.Web.UI.RadMenu._adjustChildrenWidth(parent);
	        }
	    }
	},
	
	get_expandedImageUrl : function ()
	{
		return this._properties.getValue("expandedImageUrl", null);
	},
	
	set_expandedImageUrl : function (value)
	{
		this._properties.setValue("expandedImageUrl", value, true);
		this._updateImageSrc();
	},
	
	get_disabledImageUrl : function ()
	{
		return this._properties.getValue("disabledImageUrl", null);
	},
	
	set_disabledImageUrl : function (value)
	{
		this._properties.setValue("disabledImageUrl", value, true);
		this._updateImageSrc();
	},
	
	get_disabledCssClass : function ()
	{
	    return this._properties.getValue("disabledCssClass", this._defaultDisabledCssClass);
	},
	
	set_disabledCssClass : function (value)
	{
	    this._properties.setValue("disabledCssClass", value, true);
	    this._updateLinkClass();
	},
	
	get_expandedCssClass : function ()
	{
	    return this._properties.getValue("expandedCssClass", this._defaultExpandedCssClass);
	},
	
	set_expandedCssClass : function (value)
	{
		this._properties.setValue("expandedCssClass", value, true);
		this._updateLinkClass();
	},
	
	get_focusedCssClass : function ()
	{
	    return this._properties.getValue("focusedCssClass", this._defaultFocusedCssClass);
	},
	
	set_focusedCssClass : function (value)
	{
		this._properties.setValue("focusedCssClass", value, true);
		this._updateLinkClass();
	},
	
	get_clickedCssClass : function ()
	{
	    return this._properties.getValue("clickedCssClass", this._defaultClickedCssClass);
	},
	
	set_clickedCssClass : function (value)
	{
		this._properties.setValue("clickedCssClass", value, true);
		this._updateLinkClass();
	},

	get_postBack : function()
	{
		return this._properties.getValue("postBack", true) == true;
	},
	
	set_postBack : function(value)
	{
		this._properties.setValue("postBack", value);
	},
	
	get_expandMode : function ()
	{
		return this._properties.getValue("expandMode", Telerik.Web.UI.MenuItemExpandMode.ClientSide);
	},
	
	set_expandMode : function (value)
	{
		this._properties.setValue("expandMode", value, true);
	},
	
	set_enabled : function (value)
	{
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, 'set_enabled', [value]);
		this._updateLinkClass();		
	},


	// Public methods
	
	open: function()
	{
		this._open(null);
	},
	
	close: function()
	{
		this._close(null);
	},
	
	hide: function()
	{
		this.set_visible(false);
	},
	
	show: function()
	{
		this.set_visible(true);
	},
	
	focus: function()
	{
		this._setFocused(true, null);
	},
	
	blur: function()
	{
		this._blur(null);
	},

	focusFirstChild: function(e)
	{
		var items = this.get_items();
		if (items.get_count() == 0)
		{
			return;
		}
		
		var item = items.getItem(0);
		var firstItem = item;	
		while (!item._canFocus())
		{
			item = item._getNextItem();
			if (item == firstItem) 
			{
				return; // no items to focus
			}
		}

		item._focus(e || null);
	},
	
	focusLastChild: function(e)
	{
		var items = this.get_items();
		if (items.get_count() == 0)
		{
			return;
		}
		
		var item = items.getItem(items.get_count() - 1);
		var lastItem = item;
		while (!item._canFocus())
		{
			item = item._getPreviousItem();
			if (item == lastItem) 
			{
				return; // no items to focus
			}		
		}
		
		item._focus(e || null);
	},
	
	focusNextItem: function(e)
	{
		var item = this._getNextItem();	
		while (!item._canFocus())
		{
			item = item._getNextItem();
		}
		item._focus(e || null);
	},
	
	focusPreviousItem: function(e)
	{
		var item = this._getPreviousItem();
		while (!item._canFocus())
		{
			item = item._getPreviousItem();
		}
		item._focus(e || null);
	},
	
	disable: function()
	{
		this.set_enabled(false);
	},
	
	enable: function()
	{
		this.set_enabled(true);
	},

	click : function()
	{
		this._click(null);
	},

	// Private properties and methods
	_modifyPositionClass : function()
	{
		var visibleIndex = this._getVisibleIndex();
		if (visibleIndex == 0)
		{
			var nextVisibleSibling = this._getNextVisibleSibling(this.get_index());
			var fromClass = this.get_visible() ? "rmItem" : "rmItem rmFirst";
			var toClass = this.get_visible() ? "rmItem rmFirst" : "rmItem";
			this._replaceCssClass(this.get_element(), fromClass, toClass);
			this._replaceCssClass(nextVisibleSibling.get_element(), toClass, fromClass);
		}

		if (visibleIndex == this._getVisibleSiblingsCount())
		{
			var previousVisibleSibling = this._getPreviousVisibleSibling(this.get_index());
			var fromClass = this.get_visible() ? "rmItem" : "rmItem rmLast";
			var toClass = this.get_visible() ? "rmItem rmLast" : "rmItem";
			this._replaceCssClass(this.get_element(), fromClass, toClass);
			this._replaceCssClass(previousVisibleSibling.get_element(), toClass, fromClass);
		}
	},
	
	_getSiblings : function()
	{
		return this.get_parent().get_items();
	},
	
	_getVisibleIndex : function()
	{
		var siblings = this._getSiblings();
		if (this.get_index() == 0)
		{
			return 0;
		}
		var visibleIndex = 0;
		for (var i=0; i<=this.get_index(); i++)
		{
			if (siblings.getItem(i).get_visible())
			{
				visibleIndex++;
			}
		}
		return visibleIndex;
	},
	
	_getVisibleSiblingsCount : function()
	{
		var siblings = this._getSiblings();
		var visibleCount = 0;
		for (var i=0; i<siblings.get_count(); i++)
		{
			if (siblings.getItem(i).get_visible())
			{
				visibleCount++;
			}
		}
		return visibleCount;
	},

	_getPreviousVisibleSibling : function(itemIndex)
	{
		var items = this.get_parent().get_items();
		for (var i=itemIndex - 1; i>=0; i--)
		{
			var item = items.getItem(i);
			if (item.get_visible())
			{
				return item;
			}
		}
		return null;
	},
	
	_getNextVisibleSibling : function(itemIndex)
	{
		var items = this.get_parent().get_items();
		for (var i=itemIndex + 1; i<items.get_count(); i++)
		{
			var item = items.getItem(i);
			if (item.get_visible())
			{
				return item;
			}
		}
		return null;
	},

	_determineCssClass: function()
	{
		var actualCssClass = "rmItem";
		var parent = this.get_parent();
		var itemsCount = parent.get_items().get_count();
		var lastIndex = itemsCount - 1;
		if (this.get_index() == 0 && itemsCount > 0) 
		{
			var previousFirstItem = parent.get_items().getItem(1);
			if (previousFirstItem && previousFirstItem.get_element()) 
			{
				if (previousFirstItem.get_index() == lastIndex) 
				{
					this._replaceCssClass(previousFirstItem.get_element(), "rmItem rmFirst", "rmItem rmLast");
				}
				else 
				{
					this._replaceCssClass(previousFirstItem.get_element(), "rmItem rmFirst", "rmItem");
				}
			}
			actualCssClass += " " + "rmFirst";
		}
		
		if (this.get_index() == lastIndex && itemsCount > 0) 
		{
			var previousLastItem = parent.get_items().getItem(lastIndex - 1);
			if (previousLastItem && previousLastItem.get_element()) 
			{
				if (previousLastItem.get_index() == 0) 
				{
					this._replaceCssClass(previousLastItem.get_element(), "rmItem rmLast", "rmItem rmFirst");
				}
				else 
				{
					this._replaceCssClass(previousLastItem.get_element(), "rmItem rmLast", "rmItem");
				}
			}
			actualCssClass += " " + "rmLast";
		}
		
		if (this.get_isSeparator()) 
		{
			actualCssClass = "rmItem" + " " + "rmSeparator";
		}
		
		return actualCssClass;
	},
	
	_renderImage: function(html)
	{
		html[html.length] = "<img alt='' src='" + this.get_imageUrl() + "' class='rmLeftImage'";
		
		if (!this.get_enabled()) 
		{
			html[html.length] = " disabled='disabled'";
		}
		
		html[html.length] = "/>";
		
		return html;
	},
	
	_renderLink: function(html)
	{
		if (this.get_isSeparator())
		{
			return;
		}
		
		var href = "#";

		var navigateUrl = this.get_navigateUrl();
		if (navigateUrl && navigateUrl != "#")
		{
			href = navigateUrl;
		}
		
		html[html.length] = "<a href=\"";
		html[html.length] = href;
		html[html.length] = "\" ";
	
		var target = this.get_target();
		if (target)
		{
			html[html.length] = "target=\"";
			html[html.length] = target;
			html[html.length] = "\" ";
		}
		
		if (this.get_enabled()) 
		{
			html[html.length] = "class=\"rmLink\"";
		}
		else 
		{
			html[html.length] = "class=\"rmLink rmDisabled\"";
		}
		
		html[html.length] = ">";
		
		return html;		
	},
	
	_renderChildList: function(html)
	{
		var childrenCount = this.get_items().get_count();
		if (childrenCount > 0) 
		{
			html[html.length] = "<div class='rmSlide' style='";
			var groupCssClass;
			var groupSettings = this.get_groupSettings();
			var groupWidth = groupSettings.get_width();
			var groupHeight = groupSettings.get_height();
			
			if (this._getRenderScroll()) 
			{
				if (groupWidth) 
				{
					html[html.length] = "width :" + groupWidth + ";"
				}
				
				if (groupHeight) 
				{
					html[html.length] = "height :" + groupHeight + ";"
				}
			}
			
			html[html.length] = " '>";
			
			var flowCssClass = groupSettings.get_flow();
			
			if (flowCssClass == 0) 
			{
				flowCssClass = "rmVertical";
			}
			else 
			{
				flowCssClass = "rmHorizontal";
			}
			
			if (this._getRenderScroll()) 
			{
				var level = "rmLevel" + (this.get_level() + 1);
				var wrapCssClass = "rmScrollWrap" + " " + "rmRootGroup" + " " + level;//rmRootGroup?
				html[html.length] = "<div   class='" + wrapCssClass + "'>";
				
				groupCssClass = flowCssClass;
			}
			else 
			{
				var level = "rmLevel" + (this.get_level() + 1);
				groupCssClass = flowCssClass + " " + "rmGroup" + " " + level;
			}
			
			html[html.length] = "<ul class='" + groupCssClass + "'>";
			for (var i = 0; i < childrenCount; i++) 
			{
				this.get_items().getItem(i)._render(html);
			}
			html[html.length] = "</ul></div>";
			
			
			if (this._getRenderScroll()) 
			{
				html[html.length] = "</div>";
			}
		}
	},
	
	
	// Private methods

	_doOpen: function(e)
	{
		var menu = this.get_menu();
		//Avoid a bug calling the click() method of a templated item:
		if (this.get_items().get_count() == 0)
			return;
		this._ensureChildControls();
		
		var parent = this.get_parent();
		
		menu._aboutToCollapse = false;
		if (parent != menu && parent._state != Telerik.Web.UI.RadMenuItemState.Open) 
		{
			parent._open(e);
		}
		
		var animationContainer = this._getAnimationContainer();
		if (!animationContainer) 
		{
			return;
		}
		
		parent._openedItem = this;
		this._state = Telerik.Web.UI.RadMenuItemState.Open;
		
		var childListElement = this.get_childListElement();
		childListElement.style.display = "block";

		// Hide the animation container until its size is fixed.
		animationContainer.style.visibility = "hidden";
		
		this._slide.show();
		
		if (this._groupSettings.get_flow() == Telerik.Web.UI.ItemFlow.Vertical) 
		{
			Telerik.Web.UI.RadMenu._adjustChildrenWidth(this);
		}
		else 
		{
			Telerik.Web.UI.RadMenu._adjustListWidth(this);
		}
		
		if (this._adjustSiblingsWidthOnShow)
		{
			this._adjustSiblingsWidth()
			this._adjustSiblingsWidthOnShow = false;
		}
		
		this._resetAnimatedElementPosition();	
		this._slide.set_direction(this._getSlideDirection());
		this._updateScrollWrapSize();
		this._slide.updateSize();
		this._positionChildContainer();
		
		animationContainer = this._getAnimationContainer();
		
		// Show the animation container after its size has been fixed.
		animationContainer.style.visibility = "visible";

		// TODO: The z-index corrections should be executed in an event handler
		// in response to expandAnimationStarting event (not implemented yet).
		
		// Invert the default stacking order by assigning decreasing z-indices to the items.
		this.get_element().style.zIndex = parent.get_items().get_count() - this.get_index();		

		// Make the zIndex of the animation container greater than the highest item z-index.
		animationContainer.style.zIndex = parent.get_items().get_count() + 1;

		// Increase the menu z-index, so it can stack over other
		// menu instances with default z-index values.	
		menu._incrementZIndex(this._zIndexStep);

		if (this._scroller)
		{
			this._scroller.updateState();
		}

		this._slide.expand();
		this._updateLinkClass();
		this._updateImageSrc();
			
		var openedArgs = new Telerik.Web.UI.RadMenuItemOpenedEventArgs(this, e);
		this.get_menu()._raiseEvent("itemOpened", openedArgs);
	},
	
	_shouldInitializeChild: function(childNode)
	{
		return true;
	},
	
	_createChildListElement: function()
	{
		var parentListElement = document.createElement("ul");
		var groupCssClass;
		var groupSettings = this.get_groupSettings();
		var flowCssClass = groupSettings.get_flow();
		
		if (flowCssClass == 0) 
		{
			flowCssClass = "rmVertical";
		}
		else 
		{
			flowCssClass = "rmHorizontal";
		}
		
		var level = "rmLevel" + (this.get_level() + 1);
		groupCssClass = flowCssClass + " " + "rmGroup" + " " + level;
		
		parentListElement.className = groupCssClass;
		var slideWrapElement = this._createSlideWrapElement();	
		var hasScroller = slideWrapElement.firstChild != null;
		
		if (hasScroller)
		{
			// Has scroll wrap
			slideWrapElement.firstChild.appendChild(parentListElement);
		}
		else
		{
			slideWrapElement.appendChild(parentListElement);
		}
		
		this.get_element().appendChild(slideWrapElement);	
		this._initializeAnimation();
		this._updateTextElementClass();

		if (hasScroller)
		{
			this._initializeScroller();
		}
		
		return slideWrapElement;
	},
	
	_createSlideWrapElement: function()
	{
		var slideWrapElement = document.createElement("div");
		
		slideWrapElement.className = "rmSlide";
		
		var groupSettings = this.get_groupSettings();
		var groupWidth = groupSettings.get_width();
		var groupHeight = groupSettings.get_height();
		
		if (this._getRenderScroll()) 
		{
			if (groupWidth) 
			{
				slideWrapElement.style.width = groupWidth;
			}
			
			if (groupHeight) 
			{
				slideWrapElement.style.height = groupHeight;
			}

			var scrollWrapElement = this._createScrollWrapElement();
			slideWrapElement.appendChild(scrollWrapElement);
		}
				
		return slideWrapElement;
	},
	
	_createScrollWrapElement: function()
	{
		var scrollWrapElement = document.createElement("div");
		
		var level = "rmLevel" + (this.get_level() + 1);
		var wrapCssClass = "rmScrollWrap" + " " + "rmRootGroup" + " " + level;
		scrollWrapElement.className = wrapCssClass;
		
		return scrollWrapElement;
	},
	
	_getRenderScroll: function()
	{
		var groupCssClass;
		
		var groupSettings = this.get_groupSettings();
		var groupWidth = groupSettings.get_width();
		if (!groupWidth) 
		{
			groupWidth = this.get_menu().get_defaultGroupSettings().get_width();
		}
		
		var groupHeight = groupSettings.get_height();
		if (!groupHeight) 
		{
			groupHeight = this.get_menu().get_defaultGroupSettings().get_height();
		}
		
		var renderScrollWrap = groupWidth || groupHeight;
		
		return renderScrollWrap;
		
	},
	
	_getChildElements: function()
	{
		return $telerik.getChildrenByTagName(this.get_childListElement(), "li");
	},
	
	_createItemCollection: function()
	{
		var items = new Telerik.Web.UI.RadMenuItemCollection(this);
		Telerik.Web.UI.RadMenu._createChildControls(this, items);
		
		return items;
	},
	
	_getSlideWrapElement: function()
	{
		if (!this._slideWrapElement) 
		{
			var slideWrap = $telerik.getFirstChildByTagName(this.get_element(), "div", 1);
			if (slideWrap && Sys.UI.DomElement.containsCssClass(slideWrap, "rmSlide"))
				this._slideWrapElement = slideWrap;
		}
		
		return this._slideWrapElement;
	},
	
	_getScrollWrapElement: function()
	{
		if (!this._scrollWrapElement) 
		{
			var slideWrapElement = this._getSlideWrapElement();
			if (slideWrapElement) 
			{
				this._scrollWrapElement = $telerik.getFirstChildByTagName(slideWrapElement, "div", 0);
			}
		}
		
		return this._scrollWrapElement;
	},
	
	_getAnimationContainer: function()
	{
		if (!this._animationContainer) 
		{
			var containerIndex = this.get_templated() ? 1 : 0;		
			this._animationContainer = $telerik.getFirstChildByTagName(this.get_element(), "div", containerIndex);
		}
		
		return this._animationContainer;
	},
	
	_getAnimatedElement: function()
	{
		if (!this._animatedElement) 
		{
			this._animatedElement = this._getScrollWrapElement() || this.get_childListElement();
		}
		
		return this._animatedElement;
	},
	
	_determineExpandDirection: function()
	{
		var groupSettings = this.get_groupSettings();
		if (groupSettings.get_expandDirection() != Telerik.Web.UI.ExpandDirection.Auto) 
		{
			return;
		}
		
		var parentFlow = this._getParentFlow();
		
		if (parentFlow == Telerik.Web.UI.ItemFlow.Vertical) 
		{
			if (this.get_menu().get_rightToLeft()) 
			{
				groupSettings.set_expandDirection(Telerik.Web.UI.ExpandDirection.Left);
			}
			else 
			{
				groupSettings.set_expandDirection(Telerik.Web.UI.ExpandDirection.Right);
			}
		}
		else 
		{
			groupSettings.set_expandDirection(Telerik.Web.UI.ExpandDirection.Down);
		}
	},

	_getSlideDirection : function()
	{
		var expandDirection = this.get_groupSettings().get_expandDirection();
		
		if (expandDirection == Telerik.Web.UI.ExpandDirection.Auto) 
		{
			return null;
		}
		
		return expandDirection;
	},
	
	_getParentFlow: function()
	{
		var parent = this.get_parent();
		if (!parent) 
		{
			return null;
		}
		
		if (parent == this.get_menu()) 
		{
			return parent._flow;
		}
		else 
		{
			return parent.get_groupSettings().get_flow();
		}
	},
	
	_initializeAnimation: function()
	{
		this._determineExpandDirection();
		var animatedElement = this._getAnimatedElement();
		if (animatedElement) 
		{
			var menu = this.get_menu();
			this._slide = new Telerik.Web.UI.Slide(animatedElement, menu.get_expandAnimation(),
													menu.get_collapseAnimation(), menu.get_enableOverlay());
			this._slide.initialize();
			this._slide.set_direction(this._getSlideDirection());

			this._collapseAnimationEndedDelegate = Function.createDelegate(this, this._onCollapseAnimationEnded);
			this._slide.add_collapseAnimationEnded(this._collapseAnimationEndedDelegate);
		}
	},
	
	_updateTextElementClass : function ()
	{
		var textElement = this.get_textElement();
		if (!textElement)
		{
			return;
		}
		
		var className = "rmText ";
		
		
		if (this.get_items().get_count() > 0 ||
			this.get_expandMode() == Telerik.Web.UI.MenuItemExpandMode.WebService)
		{
			className += " " + this._getExpandClassName();
		}
		
		textElement.className = className;
	},
	
	_onCollapseAnimationEnded : function (sender, e)
	{
		var menu = this.get_menu();

		this.get_element().style.zIndex = 0;	
		menu._restoreZIndex();

		// The menu floats to the left when dir="rtl" is set to the body (IE).
		if (this.get_level() == 0 && menu.get_rightToLeft())
		{
			var menuElement = menu.get_element();
			menuElement.style.cssText = menuElement.style.cssText;
		}
	},
	
	_initializeScroller : function ()
	{
		var scrollWrapElement = this._getScrollWrapElement();
		if (scrollWrapElement)
		{
			this._scroller = new Telerik.Web.UI.MenuItemScroller(this.get_childListElement(), this.get_groupSettings().get_flow());
			this._scroller.initialize();
		}
	},
	
	_isAutoScrollPossible : function ()
	{
		var menu = this.get_menu();
		var maximumExpandSize = this._getMaximumExpandSize();
		var animationContainer = this._getAnimationContainer();
		
		if (this.get_groupSettings().get_flow() == Telerik.Web.UI.ItemFlow.Vertical)
		{
			return (menu._autoScrollMinimumHeight < maximumExpandSize &&
					maximumExpandSize <= animationContainer.offsetHeight);
		}
		else
		{
			return (menu._autoScrollMinimumWidth < maximumExpandSize &&
					maximumExpandSize <= animationContainer.offsetWidth);
		}
	},
	
	_getMaximumExpandSize : function ()
	{
		var expandDirection = this._slide.get_direction();
		var documentSize = $telerik.getViewPortSize();
		var animationContainer = this._getAnimationContainer();
		var animationContainerPosition = $telerik.getLocation(animationContainer);
		
		if (this.get_groupSettings().get_flow() == Telerik.Web.UI.ItemFlow.Vertical)
		{
			if (expandDirection == Telerik.Web.UI.ExpandDirection.Up)
			{
				availableHeight = animationContainer.offsetHeight + animationContainerPosition.y;
			}
			else
			{
				availableHeight = documentSize.height - animationContainerPosition.y - this._defaultScrollSize;
			}
			
			return availableHeight;
		}
		else
		{
			if (expandDirection == Telerik.Web.UI.ExpandDirection.Left)
			{
				availableWidth = animationContainerPosition.x;
			}
			else
			{
				availableWidth = documentSize.width - animationContainerPosition.x;
			}
			
			return availableWidth;
		}
		
		return null;
	},
	
	_initializeAutoScroll : function ()
	{
		this._buildScrollWrap();
		this._initializeScroller();
		
		// The newly created scroll wrap will become the animated element.
		// We need to clear the cached value and re-initialize the slide.
		this._animatedElement = null;
		this._scrollWrapElement = null;
		this._slide.set_animatedElement(this._getAnimatedElement());
	},
		
	_removeAutoScroll : function ()
	{
		var children = this.get_items();
		var childrenCount = children.get_count();
		for (var i = 0; i < childrenCount; i++)
		{
			children.getItem(i)._removeAutoScroll();
		}

		this._attachChildren();
	
		if (!this._scroller)
		{
			return;
		}

		this._scroller.dispose();
		this._scroller = null;
		
		var slideWrap = this._getSlideWrapElement();
		var childList = this.get_childListElement();
		var scrollWrap = this._getScrollWrapElement();

		slideWrap.appendChild(childList);
		slideWrap.removeChild(scrollWrap);
		
		// Restore the class name for the child-list element.
		childList.className =
			String.format("{0} {1} {2}{3}", this._getFlowCssClass(), this._groupCssClass,
											this._levelCssClass, this.get_level());
		
		// Set the animated element back to the slide.
		this._animatedElement = null;
		this._scrollWrapElement = null;
		this._slide.set_animatedElement(this._getAnimatedElement());
		this._slide.updateSize();
	},
	
	_updateAutoScrollSize : function ()
	{
		var expandDirection = this._slide.get_direction();
		var documentSize = $telerik.getViewPortSize();
		var animationContainer = this._getAnimationContainer();
		var animationContainerPosition = $telerik.getLocation(animationContainer);
		var scrollWrap = this._getScrollWrapElement();
	
		scrollWrap.style.height = "";
		scrollWrap.style.width = "";
		
		var maximumExpandSize = this._getMaximumExpandSize();
		
		if (this.get_groupSettings().get_flow() == Telerik.Web.UI.ItemFlow.Vertical)
		{
			scrollWrap.style.height = maximumExpandSize + "px";
			scrollWrap.style.width = animationContainer.style.width;

			if (expandDirection == Telerik.Web.UI.ExpandDirection.Up)
			{
				animationContainer.style.top = -maximumExpandSize + "px";
			}			
		}
		else
		{
			scrollWrap.style.width = maximumExpandSize + "px";
			scrollWrap.style.height = animationContainer.style.height;
		}

		this._slide.updateSize();
		this._scroller.resetState();
	},
	
	_buildScrollWrap : function ()
	{
		var slideWrap = this._getSlideWrapElement();
		var childList = this.get_childListElement();

		var scrollWrap = document.createElement("div");
		scrollWrap.style.position = "relative";
		scrollWrap.style.overflow = "hidden";
		
		// Move the class names (rmGroup, rmLevelX) from the child-list element to the scrollWrap
		childList.className = this._getFlowCssClass();
		scrollWrap.className =
			String.format("{0} {1} {2}{3}", this._scrollWrapCssClass, this._groupCssClass,
											this._levelCssClass, this.get_level());
		
		
		scrollWrap.appendChild(childList);
		slideWrap.appendChild(scrollWrap);
	},
	
	_updateScrollWrapSize: function()
	{
		var scrollWrapElement = this._getScrollWrapElement();
		var childListElement = this.get_childListElement();
		
		if (!scrollWrapElement) 
		{
			return;
		}
		
		if (!scrollWrapElement.style.height) 
		{
			scrollWrapElement.style.height = childListElement.offsetHeight + "px";
		}
		
		if (this.get_groupSettings().get_flow() == Telerik.Web.UI.ItemFlow.Vertical) 
		{
			scrollWrapElement.style.width = childListElement.offsetWidth + "px";
		}
	},
	
	_getWidth: function()
	{
		var linkElement = this.get_linkElement();
		if (linkElement) 
		{
			return linkElement.offsetWidth;
		}
		else 
		{
			return this.get_element().offsetWidth;
		}
	},
	
	_setWidth: function(value)
	{
		var targetElement = this.get_linkElement();
		if (!targetElement) 
		{
			targetElement = this.get_element();
		}

		if (!targetElement) 
		{
			return;
		}

		if ($telerik.isOpera)
		{
			this.get_element().style.cssFloat = "none";
		}

		var parsedValue = parseInt(value);
		if (isNaN(parsedValue)) 
		{
			// "auto"		
			targetElement.style.width = value;
	
			// Force IE6 to recalculate the item size.
			targetElement.style.cssText = targetElement.style.cssText;
			return;
		}
		
		var newWidth = parsedValue;
		var padding = $telerik.getPaddingBox(targetElement).horizontal;
		var borders = $telerik.getBorderBox(targetElement).horizontal;	
		newWidth -= padding + borders;
		
		var oldWidth = targetElement.style.width;
		if (!oldWidth || newWidth != oldWidth)
		{
			targetElement.style.width = newWidth + "px";
		}
	},
	
	_clearWidth : function ()
	{
		this._setWidth("auto");
	},
	
	_getData: function()
	{
		var data = Telerik.Web.UI.RadMenuItem.callBaseMethod(this, '_getData');
		
		var navigateUrl = this.get_navigateUrl();
		if (navigateUrl && navigateUrl != "#" && (location.href + "#" !== navigateUrl)) 
			data["navigateUrl"] = navigateUrl;
		
		return data;
	},
	
	_loadFromDictionary : function (data)
	{
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, '_loadFromDictionary', [data]);
		
		if (typeof(data.ExpandMode) != "undefined" && data.ExpandMode != Telerik.Web.UI.MenuItemExpandMode.ClientSide)
			this.set_expandMode(data.ExpandMode);
		
		if (data.NavigateUrl)
			this.set_navigateUrl(data.NavigateUrl);
		
		if (data.PostBack === false)
			this.set_postBack(data.PostBack);
		
		if (data.Target)
			this.set_target(data.Target);
		
		if (data.IsSeparator === true)
			this.set_isSeparator(data.IsSeparator);
		
		if (data.CssClass)
			this.set_cssClass(data.CssClass);

		if (typeof(data.DisabledCssClass) != "undefined" && data.DisabledCssClass != this._defaultDisabledCssClass)
			this.set_disabledCssClass(data.DisabledCssClass);
		
		if (typeof(data.ExpandedCssClass) != "undefined" && data.ExpandedCssClass != this._defaultExpandedCssClass)
			this.set_expandedCssClass(data.ExpandedCssClass);
		
		if (typeof(data.FocusedCssClass) != "undefined" && data.FocusedCssClass != this._defaultFocusedCssClass)
			this.set_focusedCssClass(data.FocusedCssClass);
		
		if (typeof(data.ClickedCssClass) != "undefined" && data.ClickedCssClass != this._defaultClickedCssClass)
			this.set_clickedCssClass(data.ClickedCssClass);
		
		if (data.ImageUrl)
			this.set_imageUrl(data.ImageUrl);
		
		if (data.HoveredImageUrl)
			this.set_hoveredImageUrl(data.HoveredImageUrl);

		if (data.ClickedImageUrl)
			this.set_clickedImageUrl(data.ClickedImageUrl);
		
		if (data.DisabledImageUrl)
			this.set_disabledImageUrl(data.DisabledImageUrl);
		
		if (data.ExpandedImageUrl)
			this.set_expandedImageUrl(data.ExpandedImageUrl);
	},
	
	_replaceCssClass: function(element, oldClass, newClass)
	{
		element.className = element.className.replace(oldClass, newClass);
	},
	
	_setChildContainerPosition: function(left, top)
	{
		var animationContainer = this._getAnimationContainer();
		var parent = this.get_parent();
		
		var scrollWrap = null;
		if (parent._getScrollWrapElement)
		{
			scrollWrap = parent._getScrollWrapElement();
		}
		
		if (scrollWrap)
		{
			this._detachChildren();
			
			var element = this.get_element();
			top += element.offsetTop;
			
			var childListElement = parent.get_childListElement();
			var childListTop = parseInt(childListElement.style.top);
			if (isNaN(childListTop))
			{
				childListTop = 0;
			}
			
			if (this.get_groupSettings().get_offsetY() == 0)
			{
				// Compensate for the scroll offset only if there is no group offset Y set.
				top += childListTop;
			}
		}
		
		animationContainer.style.left = (left + this.get_groupSettings().get_offsetX()) + "px";
		animationContainer.style.top = (top + this.get_groupSettings().get_offsetY()) + "px";
	},
	
	_detachChildren : function ()
	{
		if (this._childrenDetached)
		{
			return;
		}
		
		var animationContainer = this._getAnimationContainer();
		var parent = this.get_parent();
		var parentAnimationContainer = parent._getAnimationContainer();
		
		if (!this._childrenDetached)
		{
			parentAnimationContainer.appendChild(animationContainer);
			this._childrenDetached = true;
			
			animationContainer._item = this;
			animationContainer._itemTypeName = Object.getTypeName(this);
		}
	},
	
	_attachChildren : function ()
	{
		if (this._childrenDetached)
		{
			var element = this.get_element();
			element.appendChild(this._getAnimationContainer());
			this._childrenDetached = false;
		}
	},

	_resetAnimatedElementPosition : function ()
	{
		var animatedElement = this._getAnimatedElement();
		animatedElement.style.top = "0px";
		animatedElement.style.left = "0px";
	},
	
	_positionChildContainer: function()
	{
		var documentSize = $telerik.getClientBounds();
		
		var top = 0;
		var left = 0;
		
		var animatedProperty = this._slide._getAnimatedStyleProperty();
		
		var element = this.get_element();
		
		var itemHeight = element.offsetHeight;
		var itemWidth = element.offsetWidth;
		
		var itemBox = this._getAnimationContainer();
		
		var childItemsHeight = itemBox.offsetHeight;
		var childItemsWidth = itemBox.offsetWidth;
		
		var expandDirection = this.get_groupSettings().get_expandDirection();
		switch (expandDirection)
		{				
			case Telerik.Web.UI.ExpandDirection.Up:
				top = -childItemsHeight;
				break;

			case Telerik.Web.UI.ExpandDirection.Down:
				top = itemHeight;
				break;
				
			case Telerik.Web.UI.ExpandDirection.Left:
				left = -childItemsWidth;
				break;
				
			case Telerik.Web.UI.ExpandDirection.Right:
				left = itemWidth;
				break;
		}

		var menu = this.get_menu();
		if (menu.get_rightToLeft() && this.get_level() == 0) 
		{
			left = itemWidth - childItemsWidth;
			if (this._getParentFlow() == Telerik.Web.UI.ItemFlow.Vertical)
			{
				left -= itemWidth;
			}
		}

		this._setChildContainerPosition(left, top);
		
		// Initial positioning is done.
		// Now the auto-scroll and screen boundary detection can be applied.
		var enableAutoScroll = menu.get_enableAutoScroll();
		var enableScreenBoundaryDetection = menu.get_enableScreenBoundaryDetection();
		
		var skipScreenBoundaryDetection = false;
		if (enableAutoScroll)
		{
			// Attempt to apply auto-scrolling.
			if (this._applyAutoScroll(left, top))
			{
				// Success, skip screen boundary detection.
				skipScreenBoundaryDetection = true;
			}
			else
			{
				// Clear the existing auto-scroll.
				if (this._autoScrollActive)
				{
					this._removeAutoScroll();
					this._autoScrollActive = false;
				}
				
				if (enableScreenBoundaryDetection)
				{
					var sbdResult = this._adjustForScreenBoundaries(left, top);
					skipScreenBoundaryDetection = true;
					
					// Try to apply auto-scrolling with the new direction.
					this._applyAutoScroll(sbdResult.adjustedLeft, sbdResult.adjustedTop);
				}
			}
		
			if (this._autoScrollActive)
			{
				this._updateAutoScrollSize();
			}
		}
		
		if (enableScreenBoundaryDetection && !skipScreenBoundaryDetection)
		{
			this._adjustForScreenBoundaries(left, top);
		}
	
		var textElement = this.get_textElement();
		if (textElement)
		{
			textElement.className = "rmText " + this._getExpandClassName();
		}
	},
	
	_applyAutoScroll : function (currentLeft, currentTop)
	{
		if (this._isAutoScrollPossible())
		{
			if (!this._scroller)
			{
				this._initializeAutoScroll();
				this._autoScrollActive = true;
				this._setChildContainerPosition(currentLeft, currentTop);
			}
			
			return true;
		}
		
		return false;
	},
	
	_adjustForScreenBoundaries : function (left, top)
	{
		var itemBox = this._getAnimationContainer();
		var childItemsHeight = itemBox.offsetHeight;
		var childItemsWidth = itemBox.offsetWidth;
		
		var element = this.get_element();	
		var itemHeight = element.offsetHeight;
		var itemWidth = element.offsetWidth;

		var expandDirection = this.get_groupSettings().get_expandDirection();
		var newExpandDirection = expandDirection;
		var documentSize = $telerik.getViewPortSize();
		var childItemsPosition = $telerik.getLocation(itemBox);
		
		switch (expandDirection)
		{				
			case Telerik.Web.UI.ExpandDirection.Up:
				if ($telerik.elementOverflowsTop(itemBox))
				{
					newExpandDirection = Telerik.Web.UI.ExpandDirection.Down;
					top = itemHeight;
				}
				break;

			case Telerik.Web.UI.ExpandDirection.Down:
				if ($telerik.elementOverflowsBottom(documentSize, itemBox))
				{
					//Check if there is enough space to invert the expand direction
					var elementBox = $telerik.getLocation(element);
					if (elementBox.y > itemBox.offsetHeight)
					{
						newExpandDirection = Telerik.Web.UI.ExpandDirection.Up;
						top = -childItemsHeight;
					}
				}
				break;
				
			case Telerik.Web.UI.ExpandDirection.Left:
				if ($telerik.elementOverflowsLeft(itemBox))
				{
					newExpandDirection = Telerik.Web.UI.ExpandDirection.Right;
					left = itemWidth;
				}
				break;
				
			case Telerik.Web.UI.ExpandDirection.Right:
				if ($telerik.elementOverflowsRight(documentSize, itemBox)) 
				{
					newExpandDirection = Telerik.Web.UI.ExpandDirection.Left;
					left = -childItemsWidth;
				}
				break;
		}
		
		// Side offset	
		switch (newExpandDirection)
		{
			case Telerik.Web.UI.ExpandDirection.Down:
			case Telerik.Web.UI.ExpandDirection.Up:
				if ($telerik.elementOverflowsRight(documentSize, itemBox)) 
				{
					left = documentSize.width - (childItemsPosition.x + childItemsWidth);
				}
				break;
				
			case Telerik.Web.UI.ExpandDirection.Left:
			case Telerik.Web.UI.ExpandDirection.Right:
				if ($telerik.elementOverflowsBottom(documentSize, itemBox)) 
				{
					top = documentSize.height - (childItemsPosition.y + childItemsHeight);
				}
				break;
		}
		
		this._setChildContainerPosition(left, top);	
		this._slide.set_direction(newExpandDirection);
		
		return { adjustedLeft: left, adjustedTop: top };
	},

	_closeChildren : function(e)
	{
		var childItems = this.get_items();
		for (var i = 0; i < childItems.get_count(); i++) 
		{
			var childItem = childItems.getItem(i);
			
			childItem._stopAnimation();
						
			childItem._close(e);
		}
	},
	
	_stopAnimation : function ()
	{
		if (this._slide)
		{
			this._slide._stopAnimation();
		}
	},

	_preventClose : function ()
	{
		var parent = this.get_parent();
		
		if (this._state == Telerik.Web.UI.RadMenuItemState.AboutToClose)
		{
			this._clearTimeout();
			this._state = Telerik.Web.UI.RadMenuItemState.Open;
			parent._openedItem = this;
		}
		if (parent._preventClose)
		{
			parent._preventClose();
		}		
	},
	
	_setTimeout : function (closure, delay)
	{
		this._timeoutRef = setTimeout(closure, delay);
	},
	
	_clearTimeout : function ()
	{
		if (this._timeoutRef) 
		{
			clearTimeout(this._timeoutRef);
			this._timeoutRef = null;
		}
	},

	_getExpandClassName: function ()
	{
		return "rmExpand" + this._getExpandClass();
	},
	
	_getExpandClass : function ()
	{
		var direction = this._getSlideDirection();
	
		switch (direction)
		{
			case Telerik.Web.UI.SlideDirection.Up:
				return "Top";
			
			case Telerik.Web.UI.SlideDirection.Down:
				return "Down";
				
			case Telerik.Web.UI.SlideDirection.Left:
				return "Left";
			
			case Telerik.Web.UI.SlideDirection.Right:
				return "Right";
		}
	},
	
	_updateLinkClass : function ()
	{
		if (this.get_isSeparator() || this.get_templated())
		{
			return;
		}
		
		var cssClass = "rmLink " + this.get_cssClass();
		
		if (this.get_focused())
		{
			cssClass += " " + this.get_focusedCssClass();
		}
	
		if (this._state == Telerik.Web.UI.RadMenuItemState.Open)
		{
			cssClass += " " + this.get_expandedCssClass();
		}
	
		if (this._clicked)
		{
			cssClass += " " + this.get_clickedCssClass();
		}
	
	    if (!this.get_enabled())
	    {
	        cssClass += " " + this.get_disabledCssClass();
	    }
	
		var linkElement = this.get_linkElement();
		if (linkElement)
		{
			linkElement.className = cssClass;
		}
	},
	
	_updateImageSrc : function ()
	{
		var newSrc = this.get_imageUrl();
	
		if (this._hovered && this.get_hoveredImageUrl())
		{
			newSrc = this.get_hoveredImageUrl();
		}
	
		if (this._state == Telerik.Web.UI.RadMenuItemState.Open && this.get_expandedImageUrl())
		{
			newSrc = this.get_expandedImageUrl();
		}
		
		if (!this.get_enabled() && this.get_disabledImageUrl())
		{
			newSrc = this.get_disabledImageUrl();
		}
		
		if (this._clicked && this.get_clickedImageUrl())
		{
		    newSrc = this.get_clickedImageUrl();
		}
			
		if (newSrc && this.get_element())
		{
			var imageElement = this.get_imageElement();		
			if (!imageElement)
			{
				imageElement = this._createImageElement();
			}

		    newSrc = newSrc.replace(/&amp;/ig, "&");
			if (newSrc != imageElement.src)
			{
				imageElement.src = newSrc;
			}
		}
	},

	_createImageElement : function()
	{
		this._imageElement = document.createElement("img");		
		this._imageElement.className = this._leftImageCssClass;	
		if (!this.get_enabled())
		{
			this._imageElement.disabled = "disabled";
		}
		
		var imageParent = this.get_linkElement() || this.get_element();
		if (imageParent.firstChild)
		{
			imageParent.insertBefore(this._imageElement, imageParent.firstChild);
		}
		else
		{
			imageParent.appendChild(this._imageElement);
		}
		
		return this._imageElement;
	},

	_click : function(e)
	{
		if (!this.get_enabled()) 
		{
			return false;
		}
		
		var menu = this.get_menu();	
		var clickingArgs = menu._getExtendedItemClickingEventArgs(new Telerik.Web.UI.RadMenuItemClickingEventArgs(this, e));
		menu._raiseEvent("itemClicking", clickingArgs);
		
		if (clickingArgs.get_cancel()) 
		{
			return false;
		}
		
		if (menu.get_clickToOpen() && this.get_level() == 0) 
		{
			if (menu._clicked) 
			{
				this._close(e);
			}
			else 
			{
				this._open(e);
			}
			
			menu._clicked = !menu._clicked;
		}

		var clickedArgs = menu._getExtendedItemClickedEventArgs(new Telerik.Web.UI.RadMenuItemClickedEventArgs(this, e));
		menu._raiseEvent("itemClicked", clickedArgs);

		if (this._shouldNavigate())
		{
			return true;
		}

		if (this._shouldPostBack())
		{
			menu._postback(this._getHierarchicalIndex());
		}
		return false;
	},
	
	_shouldPostBack : function()
	{
	    if(!this.get_menu()) return false;
	
		return this.get_postBack() && this.get_menu()._postBackReference;
	},

	_canFocus: function()
	{
		return (!this.get_isSeparator()) && this.get_enabled();
	},
	
	_clearSiblingsWidth: function()
	{
		var parent = this.get_parent();
        var siblings = parent.get_items();
        for (var i = 0; i < siblings.get_count(); i++)
        {
			var sibling = siblings.getItem(i);
            if (sibling != this)
            {
				var siblingLinkElement = sibling.get_linkElement();
                if (siblingLinkElement)
                {
                    siblingLinkElement.style.width = "auto";
                }
            }
        
	        if ($telerik.isSafari)
	        {
	            parent.get_childListElement().style.width = "auto";
	        }
        }
	},
	
	_doFocus: function(e)
	{	
		if (!this._canFocus())
		{
			return;
		}
	
		this._ensureChildControls();
	
		var parent = this.get_parent();
		var openedItem = parent.get_openedItem();
		if (openedItem && openedItem != this)
		{
			openedItem._close(e);
		}
	
		if (parent._state != Telerik.Web.UI.RadMenuItemState.Open && parent.open)
		{
			parent._open(e);
		}

		parent._focusedItem = this;

		var menu = this.get_menu();
		menu._focusedItem = this;
	
		var linkElement = this.get_linkElement();
		if (!this.get_focused() && linkElement)
		{
			linkElement.focus();
		}
		
		this.get_menu()._raiseEvent("itemFocus", new Telerik.Web.UI.RadMenuItemFocusEventArgs(this, e));
	},
	
	_doBlur: function(e)
	{
		if (this.get_isSeparator())
		{
			return;
		}
	
		if (this.get_focused())
		{
			this.get_linkElement().blur();
		}
	
		this.get_parent()._focusedItem = null;

		var menu = this.get_menu();
		var instance = this;
		window.setTimeout(
			function()
			{
				if (menu._focusedItem == instance)
				{
					menu._focusedItem = null;
				}
			}, 100);

		this.get_menu()._raiseEvent("itemBlur", new Telerik.Web.UI.RadMenuItemBlurEventArgs(this, e));
	},
	
	_createChildControls : function ()
	{
		Telerik.Web.UI.RadMenuItem.callBaseMethod(this, '_createChildControls');
		this._initializeScroller();
	},
	
	_onScrollArrowMouseDown : function (arrowPosition)
	{
		if (!this._scroller) return;
		this._scroller.changeScrollSpeed(Telerik.Web.UI.ScrollerSpeed.Fast);
	},
	
	_onScrollArrowMouseUp : function (arrowPosition)
	{
		if (!this._scroller) return;
		this._scroller.changeScrollSpeed(Telerik.Web.UI.ScrollerSpeed.Slow);
	},
	
	_onScrollArrowMouseOver : function (arrowPosition)
	{
		if (!this._scroller) return;
		
		var direction = 1;
		if (arrowPosition == Telerik.Web.UI.ArrowPosition.Top ||
			arrowPosition == Telerik.Web.UI.ArrowPosition.Left)
		{
			direction = -1;
		}

		this._scroller.startScroll(Telerik.Web.UI.ScrollerSpeed.Slow, direction);
	},
	
	_onScrollArrowMouseOut : function (arrowPosition)
	{
		if (!this._scroller) return;
		
		this._scroller.stopScroll();
	},
	
	_onKeyDown : function (e)
	{
		var keyCode = e.keyCode ? e.keyCode : e.rawEvent.keyCode;
		var rtl = this.get_menu().get_rightToLeft();
		
		switch (keyCode)
		{
			case Sys.UI.Key.up:
				if (!rtl)
				{
					this._onKeyboardUp(e);
				}
				else
				{
					this._onKeyboardDown(e);
				}
				break;

			case Sys.UI.Key.down:
				if (!rtl)
				{
					this._onKeyboardDown(e);
				}
				else
				{
					this._onKeyboardUp(e);
				}
				break;

			case Sys.UI.Key.left:
				if (!rtl)
				{
					this._onKeyboardLeft(e);
				}
				else
				{
					this._onKeyboardRight(e);
				}
				break;
		
			case Sys.UI.Key.right:
				if (!rtl)
				{
					this._onKeyboardRight(e);
				}
				else
				{
					this._onKeyboardLeft(e);
				}
				break;

			case Sys.UI.Key.esc:
				this._onKeyboardEsc(e);
				break;
				
			default:
				return true;
		}
		
		e.preventDefault();
		return false;
	},
	
	_onKeyboardUp : function (e)
	{
		var parentFlow = this._getParentFlow();
	    if (parentFlow == Telerik.Web.UI.ItemFlow.Vertical)    
		{
			this.focusPreviousItem(e);
		}
		else
		{
			this.focusLastChild(e);
		}
	},
	
	_onKeyboardDown : function (e)
	{
		var parentFlow = this._getParentFlow();
	    if (parentFlow == Telerik.Web.UI.ItemFlow.Vertical)    
		{
			this.focusNextItem(e);
		}
		else
		{
			this.focusFirstChild(e);
		}
	},
	
	_onKeyboardLeft : function (e)
	{
		var parentFlow = this._getParentFlow();
	    if (parentFlow == Telerik.Web.UI.ItemFlow.Horizontal)
		{
			this.focusPreviousItem(e);
			return;
		}

		var items = this.get_items();
		var groupSettings = this.get_groupSettings();	
		if (items.get_count() > 0 &&
			groupSettings.get_expandDirection() == Telerik.Web.UI.ExpandDirection.Left)
		{
			this.focusFirstChild(e);
			return;
		}
		
		var parent = this.get_parent();
		var parentGroupSettings = null;
		if (parent.get_groupSettings)
		{
			var parentGroupSettings = parent.get_groupSettings();
		}

		if (parentGroupSettings && 
			parentGroupSettings.get_expandDirection() == Telerik.Web.UI.ExpandDirection.Right)
		{
			parent._focus(e);
			return;
		}
		
		var openedItem = this.get_menu().get_openedItem();
		if (openedItem)
		{
			openedItem.focusPreviousItem(e);
		}
	},
	
	_onKeyboardRight : function (e)
	{
		var parentFlow = this._getParentFlow();
	    if (parentFlow == Telerik.Web.UI.ItemFlow.Horizontal)
		{
			this.focusNextItem(e);
			return;
		}

		var items = this.get_items();
		var groupSettings = this.get_groupSettings();	
		if (items.get_count() > 0 &&
			groupSettings.get_expandDirection() == Telerik.Web.UI.ExpandDirection.Right)
		{
			this.focusFirstChild(e);
			return;
		}
		
		var parent = this.get_parent();
		var parentGroupSettings = null;
		if (parent.get_groupSettings)
		{
			var parentGroupSettings = parent.get_groupSettings();
		}
		
		if (parentGroupSettings && 
			parentGroupSettings.get_expandDirection() == Telerik.Web.UI.ExpandDirection.Left)
		{
			parent.focus();
			return;
		}

		var openedItem = this.get_menu().get_openedItem();
		if (openedItem)
		{
			openedItem.focusNextItem(e);
		}
	},
	
	_onKeyboardEsc : function (e)
	{
		var parent = this.get_parent();
		var menu = this.get_menu();
		
		if (parent == menu)
		{
			this._blur(e);
		}
		else
		{
			parent._close(e);
			parent._focus(e);
		}
	},
	
	_render: function(html)
	{
		var cssClass = "rmItem";
		var renderSlide = false;
		if (this.get_parent().get_items().get_count() == 1) 
		{
			renderSlide = true
		}
		
		html[html.length] = "<li class='" + this._determineCssClass() + "'>";
		this._renderLink(html);
		
		if (this.get_imageUrl()) 
		{
			this._renderImage(html);
		}

		html[html.length] = "<span class='rmText'>";
		html[html.length] = this.get_text();
		html[html.length] = "</span></a>";
		
		
		var items = this.get_items();
		var childrenCount = items.get_count();
		
		this._renderChildList(html);
		
		html[html.length] = "</li>";
	},
	
	_renderAccessKey : function ()
	{
		if (this.get_isSeparator() || this.get_templated())
		{
			return;
		}
		
		var linkElement = this.get_linkElement();
		if (!linkElement) return;
		
		var accessKey = this.get_linkElement().accessKey.toLowerCase();
		
		// If accessKey is not set
		if (!accessKey) return;
		
		var text = this.get_text();
		var indexOfAccessKey = text.toLowerCase().indexOf(accessKey);
		
		if (text.toLowerCase().indexOf("<u>") != -1)
		{
			// The text already contains underline tag.
			return;
		}
		
		if (indexOfAccessKey == -1)
		{
			// The letter specified in accesKey is not found.
			return;
		}
		
		var textElement = this.get_textElement();
		textElement.innerHTML = 
			text.substr(0, indexOfAccessKey) + 
			"<u>" + 
			text.substr(indexOfAccessKey,  1) + 
			"</u>" + 
			text.substr(indexOfAccessKey + 1, text.length);
	},
	
	_getIsImageOnly : function ()
	{
		if (this._isImageOnly === null)
		{
			this._isImageOnly = this.get_imageElement() != null;
		}
		
		return this._isImageOnly;
	},
	
	_getFlowCssClass : function ()
	{
		if (this.get_groupSettings().get_flow() == Telerik.Web.UI.ItemFlow.Vertical) 
		{
			return this._verticalCssClass;
		}
		else
		{
			return this._horizontalCssClass;
		}
	},
	
	_isWebServiceCallNeeded : function ()
	{
		if (this._itemsLoading)
		{
			return false;
		}
		
		return (!this._itemsLoaded && this.get_expandMode() == Telerik.Web.UI.MenuItemExpandMode.WebService);
	},
	
	_createLoadingItem : function ()
	{
		var loadingTemplate = this.get_menu().get_loadingTemplate();
		if (loadingTemplate === "")
		{
			return;
		}
		
		var loadingItem = new Telerik.Web.UI.RadMenuItem();	
		this.get_items().add(loadingItem);
		
		loadingItem.set_text(loadingTemplate);
	},
	
	_removeLoadingItem : function ()
	{
		if (this.get_menu().get_loadingTemplate() === "")
		{
			return;
		}
		
		var loadingItem = this.get_items().getItem(0);
		this.get_items().remove(loadingItem);
	},
	
	_loadChildrenFromWebService : function ()
	{
		this.get_menu()._loadChildrenFromWebService(this);
	},
	
	_onChildrenLoading : function ()
	{
		this._itemsLoading = true;

		this._createLoadingItem();
		this._doOpen(null);
	},
	
	_onChildrenLoaded : function ()
	{
		this._removeLoadingItem();

		this._itemsLoaded = true;
		this._itemsLoading = false;

		// Update the slide to account for the added items.
		this._slide.updateSize();

		if (this._hovered)
		{
			// Only open the item if the user is still hovering the item.
			this._doOpen(null);
		}
	},
	
	_onChildrenLoadingError : function ()
	{	
		this._close(null);
		this._removeLoadingItem();

		this._itemsLoaded = false;
		this._itemsLoading = false;
	},
	
	_adjustSiblingsWidth : function ()
	{
		var parent = this.get_parent();

		if (parent)
		{	
			this._clearSiblingsWidth();
			Telerik.Web.UI.RadMenu._adjustChildrenWidth(parent);
		}
	}
}

Telerik.Web.UI.RadMenuItem.registerClass('Telerik.Web.UI.RadMenuItem', Telerik.Web.UI.ControlItem);


/* END Telerik.Web.UI.Menu.RadMenuItem.js */
/* START Telerik.Web.UI.Menu.RadMenu.js */
Type.registerNamespace("Telerik.Web.UI");


// ---------- ItemFlow Enum ----------
Telerik.Web.UI.ItemFlow = function()
{
};
Telerik.Web.UI.ItemFlow.prototype = 
{
	Vertical: 0,
	Horizontal: 1
}
Telerik.Web.UI.ItemFlow.registerEnum("Telerik.Web.UI.ItemFlow");


// ---------- ExpandDirection Enum ----------
Telerik.Web.UI.ExpandDirection = function()
{
};
Telerik.Web.UI.ExpandDirection.prototype = 
{
	Auto: 0,
	Up: 1,
	Down: 2,
	Left: 3,
	Right: 4
}
Telerik.Web.UI.ExpandDirection.registerEnum("Telerik.Web.UI.ExpandDirection");


// ---------- RadMenu Class ----------
Telerik.Web.UI.RadMenu = function(element)
{
	Telerik.Web.UI.RadMenu.initializeBase(this, [element]);
	this._childTypeName = "Telerik.Web.UI.RadMenuItem";
	
	this._itemData = null;
	this._expandAnimation = new Telerik.Web.UI.AnimationSettings({});
	this._expandDelay = 100;
	this._collapseAnimation = new Telerik.Web.UI.AnimationSettings({});
	this._collapseDelay = 500;
	this._flow = Telerik.Web.UI.ItemFlow.Horizontal;
	this._defaultGroupSettings = new Telerik.Web.UI.RadMenuItemGroupSettings({});
	this._enableAutoScroll = false;
	this._autoScrollMinimumHeight = 50;
	this._autoScrollMinimumWidth = 50;
	this._enableScreenBoundaryDetection = true;
	this._clickToOpen = false;
	this._childListElement = null;
	this._postBackReference = null;
	this._onClickDelegate = null;
	this._webServiceSettings = new Telerik.Web.UI.WebServiceSettings({});
	this._persistLoadOnDemandItems = true;
	this._enableOverlay = true;
	
	this._enabled = true;
	this._visible = true;
	this._openedItem = null;
	this._lastOpenedItem = null;
	this._childrenDetached = false;
	this._originalZIndex = null;
	this._defaultZIndex = 7000;
	this._zIndexIncrementDepth = 0;
	this._fireEvents = true;
	this._webServiceLoader = null;
	this._loadingTemplate = "";
	
	this._onMouseOutDelegate = null;
	this._onClickDelegate = null;
	this._onResizeDelegate = null;
	
	this._aboutToCollapse = false;
	
	this._rightToLeft = null;
	this._skin = null;
}

Telerik.Web.UI.RadMenu._createChildControls = function(parent, items)
{
	var itemData = parent.get_itemData();
	
	if (!itemData) 
		return;
	
	var childElements = $telerik.getChildrenByTagName(parent.get_childListElement(), "li");
	Sys.Debug.assert(itemData.length == childElements.length, "Length of elements and json must be the same!");
	
	for (var i = 0; i < itemData.length; i++) 
	{
		var item = new Telerik.Web.UI.RadMenuItem();
		items.add(item);
		item._initialize(itemData[i], childElements[i]);
	}
}

Telerik.Web.UI.RadMenu._adjustChildrenWidth = function(item, resetWidth)
{
	var menu = item._getControl();
	var childItems = item.get_items();
	var childCount = childItems.get_count();

	if (resetWidth) 
	{
		for (var i = 0; i < childCount; i++) 
		{
			childItems.getItem(i)._clearWidth();
		}
	}

	var maxWidth = Telerik.Web.UI.RadMenu._getMaxChildWidth(item) + "px";
	Telerik.Web.UI.RadMenu._setChildrenWidth(item, maxWidth);
}

Telerik.Web.UI.RadMenu._getMaxChildWidth = function (item)
{
	var maxWidth = 0;

	var menu = item._getControl();
	var childItems = item.get_items();
	var childCount = childItems.get_count();

	for (var i = 0; i < childCount; i++) 
	{
		if (menu.get_rightToLeft())
		{
			var itemImage = childItems.getItem(i).get_imageElement();
			if (itemImage)
			{
				itemImage.style.styleFloat = "left";
				itemImage.style.cssFloat = "left";
			}
		}
		var width = childItems.getItem(i)._getWidth();
		maxWidth = Math.max(width, maxWidth);
	}
	
	if (item.get_groupSettings)
	{
		groupWidth = item.get_groupSettings().get_width();
		if (groupWidth)
		{
			maxWidth = groupWidth;
		}
	}
	
	return maxWidth;
}

Telerik.Web.UI.RadMenu._setChildrenWidth = function (item, width)
{
	var menu = item._getControl();
	var childItems = item.get_items();
	var childCount = childItems.get_count();

	for (var i = 0; i < childCount; i++) 
	{
		if (menu.get_rightToLeft())
		{
			var itemImage = childItems.getItem(i).get_imageElement();
			if (itemImage)
			{
				itemImage.style.styleFloat = "right";
				itemImage.style.cssFloat = "right";
			}
		}
		childItems.getItem(i)._setWidth(width);
	}
	
	if ($telerik.isSafari)
	{
		var childListElement = item.get_childListElement();
		childListElement.style.width = width;
	}
}

Telerik.Web.UI.RadMenu._adjustRootItemWidth = function (menuId)
{
	var element = $get(menuId);
	var maxWidth = Telerik.Web.UI.RadMenu._getMaxRootItemWidth(element);
	
	Telerik.Web.UI.RadMenu._setRootItemWidth(element, maxWidth);
}

Telerik.Web.UI.RadMenu._getChildListElement = function(menuElement)
{
	var childListElement = $telerik.getFirstChildByTagName(menuElement, "ul", 0);
	if (!childListElement)
	{
		var scrollWrapElement = $telerik.getFirstChildByTagName(menuElement, "div", 0);
		childListElement = $telerik.getFirstChildByTagName(scrollWrapElement, "ul", 0);
		if (!childListElement)
		{
			var contextMenuElement = scrollWrapElement;
			scrollWrapElement = $telerik.getFirstChildByTagName(contextMenuElement, "div", 0);
			childListElement = $telerik.getFirstChildByTagName(scrollWrapElement, "ul", 0);
		}
	}
	return childListElement;
}

Telerik.Web.UI.RadMenu._getMaxRootItemWidth = function(menuElement)
{
	var childListElement = Telerik.Web.UI.RadMenu._getChildListElement(menuElement);
	
	if (childListElement == null)
	{
	    return;
	}
	
	var childNodes = childListElement.childNodes;
	var childNodesCount = childNodes.length;
	var maxWidth = 0;
	for (var i = 0; i < childNodesCount; i++)
	{
		var node = childNodes[i]; // li tag
		
		if (node.nodeType === 3) continue;
		
		var linkElement = $telerik.getFirstChildByTagName(node, "a", 0);
		var width;
		if (linkElement)
		{
			width = linkElement.offsetWidth;
		}
		else
		{
			width = node.offsetWidth;
		}
		
		maxWidth = Math.max(maxWidth, width);
	}
	
	return maxWidth;
}

Telerik.Web.UI.RadMenu._setRootItemWidth = function(menuElement, maxWidth)
{
	var childListElement = Telerik.Web.UI.RadMenu._getChildListElement(menuElement);
	
	if (childListElement == null)
	{
	    return null;
	}
	
	var childNodes = childListElement.childNodes;
	var childNodesCount = childNodes.length;
			
	if ($telerik.isOpera)
	{
		childListElement.style.cssFloat = "none";
	}

	if (maxWidth == 0)
	{
		return;
	}

	for (var i = 0; i < childNodesCount; i++)
	{
		var node = childNodes[i];
		
		if (node.nodeType == 3) continue;
		
		var element = $telerik.getFirstChildByTagName(node, "a", 0);
		if (!element)
		{
			element = node;
		}

		var newWidth = maxWidth;
		var padding = $telerik.getPaddingBox(element).horizontal;
		var borders = $telerik.getBorderBox(element).horizontal;	
		newWidth -= padding + borders;

		var oldWidth = element.style.width;
		if (!oldWidth || newWidth != oldWidth)
		{
			element.style.width = newWidth + "px";
		}
	}
	
	if ($telerik.isSafari)
	{
		childListElement.style.width = maxWidth;
	}
	
	if (menuElement.style.width === "" &&
		Telerik.Web.UI.RadMenu._requiresRightToLeft(menuElement))
	{
		menuElement.style.width = maxWidth + "px";
	}
}

Telerik.Web.UI.RadMenu._requiresRightToLeft = function(element)
{
	var currentElement = element;
	while (currentElement.nodeType !== 9)
	{
		if (currentElement.dir == "rtl")
			return true;
		
		currentElement = currentElement.parentNode;
	}
	return false;
}

// Should we make this an instance method?
Telerik.Web.UI.RadMenu._adjustListWidth = function(item)
{
	var menu = item._getControl();
	if (menu.get_rightToLeft())
	{
		Telerik.Web.UI.RadMenu._adjustChildrenWidth(item);
	}
	
	var childListElement = item.get_childListElement();
	var totalWidth = 0;
	for (var i = 0; i < childListElement.childNodes.length; i++)
	{
		var node = childListElement.childNodes[i];
		if (node.nodeType == 3) continue;
		
		totalWidth += node.offsetWidth;
		node.style.clear = "none";
	}

	childListElement.style.width = totalWidth + "px";
}

Telerik.Web.UI.RadMenu.prototype = 
{
	
	initialize: function()
	{
		Telerik.Web.UI.RadMenu.callBaseMethod(this, 'initialize');
		
		var element = this.get_element();
		
		if (this.get_rightToLeft())
		{
			this._initRightToLeft();
		}
		
		if (this._flow == Telerik.Web.UI.ItemFlow.Vertical)
		{
			var clientId = this.get_element().id;
			Telerik.Web.UI.RadMenu._adjustRootItemWidth(clientId);
		}

		this._originalZIndex = parseInt($telerik.getCurrentStyle(element, "zIndex"));
		if (!this._originalZIndex)
		{
			element.style.zIndex = this._defaultZIndex;
			this._originalZIndex = this._defaultZIndex;
		}
		
		this._onClickDelegate = Function.createDelegate(this, this._onClick);
		$addHandler(document, "click", this._onClickDelegate);

		if (!this.get_clickToOpen()) 
		{
			if ($telerik.isIE) 
			{
				this._onMouseOutDelegate = Function.createDelegate(this, this._onMouseOut);
				$addHandler(document, "mouseout", this._onMouseOutDelegate);
			}
		}
		
	    //To refresh the menu position - required for IE because the menu is relatively positioned.
		this._onResizeDelegate = Function.createDelegate(this, this._onResize);
	    $addHandler(window, "resize", this._onResizeDelegate);
	
		this._eventMap.addHandlerForClassName("mouseover", "rmItem", this._onItemMouseOver);
		this._eventMap.addHandlerForClassName("mouseout", "rmItem", this._onItemMouseOut);
		this._eventMap.addHandlerForClassName("dragstart", "rmItem", this._onItemDragStart);
		
		this._eventMap.addHandlerForClassName("click", "rmLink", this._onLinkClick);
		this._eventMap.addHandlerForClassName("mouseover", "rmLink", this._onLinkMouseOver);
		this._eventMap.addHandlerForClassName("mouseout", "rmLink", this._onLinkMouseOut);
		this._eventMap.addHandlerForClassName("mousedown", "rmLink", this._onLinkMouseDown);
		this._eventMap.addHandlerForClassName("mouseup", "rmLink", this._onLinkMouseUp);
		this._eventMap.addHandlerForClassName("blur", "rmLink", this._onLinkBlur);
		this._eventMap.addHandlerForClassName("deactivate", "rmLink", this._onLinkBlur);
		this._eventMap.addHandlerForClassName("focus", "rmLink", this._onLinkFocus);
		this._eventMap.addHandlerForClassName("activate", "rmLink", this._onLinkFocus);
		this._eventMap.addHandlerForClassName("keydown", "rmLink", this._onLinkKeyDown);
		
		// Scroller-related events
		this._eventMap.addHandlerForClassName("mousedown", "rmTopArrow", this._onTopArrowMouseDown);
		this._eventMap.addHandlerForClassName("mouseup", "rmTopArrow", this._onTopArrowMouseUp);
		this._eventMap.addHandlerForClassName("mouseover", "rmTopArrow", this._onTopArrowMouseOver);
		this._eventMap.addHandlerForClassName("mouseout", "rmTopArrow", this._onTopArrowMouseOut);
		this._eventMap.addHandlerForClassName("click", "rmTopArrow", this._onScrollArrowClicked);

		this._eventMap.addHandlerForClassName("mousedown", "rmBottomArrow", this._onBottomArrowMouseDown);
		this._eventMap.addHandlerForClassName("mouseup", "rmBottomArrow", this._onBottomArrowMouseUp);
		this._eventMap.addHandlerForClassName("mouseover", "rmBottomArrow", this._onBottomArrowMouseOver);
		this._eventMap.addHandlerForClassName("mouseout", "rmBottomArrow", this._onBottomArrowMouseOut);
		this._eventMap.addHandlerForClassName("click", "rmBottomArrow", this._onScrollArrowClicked);

		this._eventMap.addHandlerForClassName("mousedown", "rmLeftArrow", this._onLeftArrowMouseDown);
		this._eventMap.addHandlerForClassName("mouseup", "rmLeftArrow", this._onLeftArrowMouseUp);
		this._eventMap.addHandlerForClassName("mouseover", "rmLeftArrow", this._onLeftArrowMouseOver);
		this._eventMap.addHandlerForClassName("mouseout", "rmLeftArrow", this._onLeftArrowMouseOut);
		this._eventMap.addHandlerForClassName("click", "rmLeftArrow", this._onScrollArrowClicked);

		this._eventMap.addHandlerForClassName("mousedown", "rmRightArrow", this._onRightArrowMouseDown);
		this._eventMap.addHandlerForClassName("mouseup", "rmRightArrow", this._onRightArrowMouseUp);
		this._eventMap.addHandlerForClassName("mouseover", "rmRightArrow", this._onRightArrowMouseOver);
		this._eventMap.addHandlerForClassName("mouseout", "rmRightArrow", this._onRightArrowMouseOut);
		this._eventMap.addHandlerForClassName("click", "rmRightArrow", this._onScrollArrowClicked);
		
		if (!this.get_enabled())
		{
			// The menu cannot be disabled until the items have been created from the base initialize methods.
			this.set_enabled(false);
		}
		
		this._raiseEvent("load", null);
	},
	
	dispose: function()
	{
		Telerik.Web.UI.RadMenu.callBaseMethod(this, 'dispose');
		
		if (this._onClickDelegate) 
		{
			$removeHandler(document, "click", this._onClickDelegate);
			this._onClickDelegate = null;
		}
		
		if (this._onMouseOutDelegate) 
		{
			$removeHandler(document, "mouseout", this._onMouseOutDelegate);
			this._onMouseOutDelegate = null;
		}
		
		if (this._onResizeDelegate) 
		{
			$removeHandler(window, "resize", this._onResizeDelegate);
			this._onResizeDelegate = null;
		}
		
		if (this._eventMap) 
		{
			this._eventMap.dispose();
			this._eventMap = null;
		}
	},
	
	repaint : function ()
	{
		if (this._flow == Telerik.Web.UI.ItemFlow.Vertical)
			Telerik.Web.UI.RadMenu._adjustRootItemWidth(this.get_id());
	},
	
	
	// Public properties	
	get_items: function()
	{
		return this._getChildren();
	},
	
	set_items: function(value)
	{
		this._children = value;
	},
	
	get_enableScreenBoundaryDetection : function ()
	{
		return this._enableScreenBoundaryDetection;
	},

	set_enableScreenBoundaryDetection : function (value)
	{
		this._enableScreenBoundaryDetection = value;
	},
	
	get_enableAutoScroll : function ()
	{
		return this._enableAutoScroll;
	},

	set_enableAutoScroll : function (value)
	{
		this._enableAutoScroll = value;
	},
	
	get_autoScrollMinimumHeight : function ()
	{
		return this._autoScrollMinimumHeight;
	},

	set_autoScrollMinimumHeight : function (value)
	{
		this._autoScrollMinimumHeight = value;
	},
	
	get_autoScrollMinimumWidth : function ()
	{
		return this._autoScrollMinimumWidth;
	},

	set_autoScrollMinimumWidth : function (value)
	{
		this._autoScrollMinimumWidth = value;
	},
	
	get_childListElement: function()
	{
		/// <exclude/>
		
		if (!this._childListElement) 
		{
			this._childListElement = $telerik.getFirstChildByTagName(this.get_element(), "ul", 0);
		}
		return this._childListElement;
	},
	
	get_expandAnimation: function()
	{
		/// <exclude/>
		
		return this._expandAnimation;
	},
	
	set_expandAnimation: function(value)
	{
		/// <exclude/>
		
		var deserializedAnimationSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._expandAnimation = new Telerik.Web.UI.AnimationSettings(deserializedAnimationSettings);
	},
	
	get_collapseAnimation: function()
	{
		/// <exclude/>
		
		return this._collapseAnimation;
	},
	
	set_collapseAnimation: function(value)
	{
		/// <exclude/>
		
		var deserializedAnimationSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._collapseAnimation = new Telerik.Web.UI.AnimationSettings(deserializedAnimationSettings);
	},
	
	get_defaultGroupSettings: function()
	{
		/// <exclude/>
		
		return this._defaultGroupSettings;
	},
	
	set_defaultGroupSettings: function(value)
	{
		/// <exclude/>
		
		var deserializedSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._defaultGroupSettings = new Telerik.Web.UI.RadMenuItemGroupSettings(deserializedSettings);
	},
	
	get_itemData: function()
	{
		/// <exclude/>
		
		return this._itemData;
	},
	
	set_itemData: function(value)
	{
		/// <exclude/>
		
		this._itemData = value;
	},
	
	set_enabled: function(value)
	{
		Telerik.Web.UI.RadMenu.callBaseMethod(this, "set_enabled", [value]);
		
		if (!this.get_isInitialized())
			return;
		
		var element = this.get_element();
		var items = this.get_items();
		var itemCount = items.get_count();
		if (!value)
		{
			element.disabled = "disabled";
			this.disableEvents();
			
			for (var i = 0; i < itemCount; i++)
			{
				items.getItem(i).disable();
			}
		}
		else
		{
			element.disabled = "";
			this.enableEvents();
			
			for (var i = 0; i < itemCount; i++)
			{
				items.getItem(i).enable();
			}
		}
	},
	
	get_allItems: function()
	{
		return this._getAllItems();
	},
	
	get_focusedItem: function()
	{
		return this._focusedItem;
	},
	
	get_openedItem: function()
	{
		return this._openedItem;
	},
	
	get_clickToOpen : function ()
	{
		return this._clickToOpen;		
	},
	
	set_clickToOpen : function (value)
	{
		this._clickToOpen = value;
	},
	
	get_collapseDelay : function ()
	{
		return this._collapseDelay;
	},
	
	set_collapseDelay : function (value)
	{
		this._collapseDelay = value;
	},
	
	get_expandDelay : function ()
	{
		return this._expandDelay;
	},
	
	set_expandDelay : function (value)
	{
		this._expandDelay = value;
	},
	
	get_loadingTemplate : function ()
	{
		return this._loadingTemplate;
	},
	
	set_loadingTemplate : function (value)
	{
		this._loadingTemplate = value;
	},
	
	get_webServiceSettings: function()
	{
		/// <exclude/>
		
		return this._webServiceSettings;
	},
	
	set_webServiceSettings: function(value)
	{
		/// <exclude/>
		
		var deserializedWebServiceSettings = Sys.Serialization.JavaScriptSerializer.deserialize(value);
		this._webServiceSettings = new Telerik.Web.UI.WebServiceSettings(deserializedWebServiceSettings);
	},
	
	get_rightToLeft : function ()
	{
		if (this._rightToLeft === null)
		{
			this._rightToLeft = Telerik.Web.UI.RadMenu._requiresRightToLeft(this.get_element());
		}
		
		return this._rightToLeft;
	},
	
	set_rightToLeft : function (value)
	{
		this._rightToLeft = value;
	},
	
	set_clicked : function (value)
	{
		this._clicked = value;
	},
	
	get_clicked : function ()
	{
		return this._clicked;
	},

	
	// Public methods		
	saveClientState: function()
	{
		var logEntriesArray = this._log._logEntries;
		var clientState = 
		{
			logEntries: logEntriesArray
		};
		return Sys.Serialization.JavaScriptSerializer.serialize(clientState);
	},
	
	close: function()
	{
		var openedItem = this.get_openedItem();
		if (openedItem)
		{
			openedItem.close();
		}
	},
	
	disable: function()
	{
		this.set_enabled(false);
	},
	
	enable: function()
	{
		this.set_enabled(true);
	},
	
	disableEvents: function()
	{
		this._fireEvents = false;
	},
	
	enableEvents: function()
	{
		this._fireEvents = true;
	},
	
	focus: function()
	{
		this.get_element().focus();
	},
	
	findItemByText: function(text)
	{
		return this._findItemByText(text);
	},
	
	findItemByUrl: function()
	{
		Error.notImplemented();
	},
	
	findItemByValue: function(value)
	{
		return this._findItemByValue(value);
	},
		
	findItemByAttribute : function (attributeName, attributeValue)
	{
		return this._findItemByAttribute(attributeName, attributeValue);
	},

	get_allItems : function()
	{
		return this._getAllItems();
	},
	
	get_persistLoadOnDemandItems : function ()
	{
		return this._persistLoadOnDemandItems;
	},
	
	set_persistLoadOnDemandItems : function (value)
	{
		this._persistLoadOnDemandItems = value;
	},
	
	get_enableOverlay : function ()
	{
		return this._enableOverlay;
	},
	
	set_enableOverlay : function (value)
	{
		this._enableOverlay = value;
	},
	
	
	// Private methods
	_isMainElementDescendant : function(element)
	{
		return $telerik.isDescendant(this.get_element(), element)
	},

	_createChildControls: function()
	{
		this._children = new Telerik.Web.UI.RadMenuItemCollection(this);
		Telerik.Web.UI.RadMenu._createChildControls(this, this._children);
	},

	_onMouseOut : function (e)
	{
		var relatedTarget = e.rawEvent.relatedTarget ? e.rawEvent.relatedTarget : e.rawEvent.toElement;
		var element = this.get_element();

		if (!relatedTarget &&
			!this._isMainElementDescendant(e.target)) 
		{
			//The mouse is out of the window or the current frame - close the menu
			var instance = this;
			setTimeout(
				function()
				{
					instance.close();
				}, this.get_collapseDelay());
		}
	},

	_onClick : function (e)
	{
		if (!this._isMainElementDescendant(e.target))
		{
			var clickToOpen = this.get_clickToOpen();
			if (this._focusedItem || clickToOpen)
			{
				this.close();
			
				if (this.get_clickToOpen()) 
				{
					this.set_clicked(false);
				}
			}
		}
	},
			
	_onResize : function (e)
	{
	
	},
	
	_onItemMouseOver: function(e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);

		if (!item.get_enabled()) 
		{
			return true;
		}

		item._preventClose();
		
		if (this.get_clickToOpen() && !this.get_clicked())
		{
			return true;
		}
	
		if (item._state == Telerik.Web.UI.RadMenuItemState.Open ||
			item._state == Telerik.Web.UI.RadMenuItemState.AboutToOpen)
		{
			return true;
		}
	
		var parent = item.get_parent();
		var openedItem = parent.get_openedItem();

	    if (openedItem && openedItem != item)
	    {
			openedItem._clearTimeout();
			openedItem._state = Telerik.Web.UI.RadMenuItemState.AboutToClose;
			openedItem._setTimeout(
				function()
				{
					openedItem.close();
					openedItem._timeoutRef = null;
				}, this.get_expandDelay());
	    }
	
		if (item.get_items().get_count() == 0 && !item._isWebServiceCallNeeded()) 
		{
			return true;
		}
    
		this._lastOpenedItem = item;
		item._state = Telerik.Web.UI.RadMenuItemState.AboutToOpen;

		item._setTimeout(
			function ()
			{
				item.open();
				item._timeoutRef = null;
			}, this.get_expandDelay());
		
		return true;
	},
		
	_onItemMouseOut: function(e)
	{	
		var item = this._extractItemFromDomElement(e.eventMapTarget);

		if (!item.get_enabled()) 
		{
			return true;
		}

		var relatedTarget = e.eventMapRelatedTarget;
		var element = item.get_element();
    			
		if (!relatedTarget || element == relatedTarget ||
			$telerik.isDescendant(element, relatedTarget))
		{
			return true;
		}
		
	    if (this._childrenDetached &&
			$telerik.isDescendant(item.get_parent()._getAnimationContainer(), relatedTarget))
	    {
			return true;
	    }

		if (item._state == Telerik.Web.UI.RadMenuItemState.Closed ||
			item._state == Telerik.Web.UI.RadMenuItemState.AboutToClose)
		{
			return true;
		}

		if (item._state == Telerik.Web.UI.RadMenuItemState.AboutToOpen)
		{
			item._clearTimeout();
			item._state = Telerik.Web.UI.RadMenuItemState.Closed;
			item.get_parent()._openedItem = null;
			return true;
		}
	
		if (this.get_clickToOpen())
		{
			return true;
		}
	
		item._state = Telerik.Web.UI.RadMenuItemState.AboutToClose;
		item._setTimeout(
			function ()
			{
				item.close();
				item._timeoutRef = null;
			},
		this._collapseDelay);
		
		return true;
	},
	
	_onItemDragStart : function(e)
	{
		e.preventDefault();
		return false;
	},

	_onLinkClick: function(e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		
		if (!item._click(e))
		{
			e.preventDefault();
			return false;
		}
		
		return true;
	},
		
	_onLinkMouseOver: function(e)
	{
		var relatedTarget = e.eventMapRelatedTarget;
		var item = this._extractItemFromDomElement(e.eventMapTarget);

		if (!item.get_enabled()) 
		{
			return true;
		}

		var linkElement = item.get_linkElement();
		if (!relatedTarget || linkElement == relatedTarget ||
			$telerik.isDescendant(linkElement, relatedTarget))
		{
			return true;
		}
	
		item._hovered = true;
		item._updateImageSrc();
	
		this._raiseEvent("mouseOver", new Telerik.Web.UI.RadMenuMouseOverEventArgs(item, e));
			
		return true;
	},
		
	_onLinkMouseOut: function(e)
	{
		var relatedTarget = e.eventMapRelatedTarget;
		var item = this._extractItemFromDomElement(e.eventMapTarget);

		if (!item.get_enabled()) 
		{
			return true;
		}

		var linkElement = item.get_linkElement();
		
		if (!relatedTarget || !linkElement) 
		{
			return;
		}
		
		if (linkElement == relatedTarget ||
			$telerik.isDescendant(linkElement, relatedTarget))
		{
			return true;
		}

		item._hovered = false;
		item._updateImageSrc();
	
		this._raiseEvent("mouseOut", new Telerik.Web.UI.RadMenuMouseOutEventArgs(item, e));
		
		return true;
	},
		
	_onLinkMouseDown: function(e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);

		if (!item.get_enabled()) 
		{
			return true;
		}
		
		item._clicked = true;
		item._updateLinkClass();
		item._updateImageSrc();
			
		return true;
	},
		
	_onLinkMouseUp: function(e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
	
		if (!item.get_enabled()) 
		{
			return true;
		}
	
		item._clicked = false;
		item._updateLinkClass();
		item._updateImageSrc();
			
		return true;
	},
		
	_onLinkBlur: function(e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);

		if (!item.get_enabled()) 
		{
			return true;
		}
		
		// The blur method will try to blur the link element if the item is not already marked as blurred.
		item._focused = false;
		
		item.blur();
		
		return true;
	},
		
	_onLinkFocus: function(e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);

		if (!item.get_enabled()) 
		{
			return true;
		}
		
		// The focus method will try to focus the link element if the item is not already marked as focused.
		item._focused = true;
		
		item.focus();
		
		return true;
	},
		
	_onLinkKeyDown: function(e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
	
		if (!item.get_enabled()) 
		{
			return true;
		}
		
		return item._onKeyDown(e);
	},
	
	// Scroller-related event handlers
	_onTopArrowMouseDown : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseDown(Telerik.Web.UI.ArrowPosition.Top);
	},
	
	_onTopArrowMouseUp : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseUp(Telerik.Web.UI.ArrowPosition.Top);
	},
	
	_onTopArrowMouseOver : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOver(Telerik.Web.UI.ArrowPosition.Top);
	},
	
	_onTopArrowMouseOut : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOut(Telerik.Web.UI.ArrowPosition.Top);
	},

	_onBottomArrowMouseDown : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseDown(Telerik.Web.UI.ArrowPosition.Bottom);
	},
	
	_onBottomArrowMouseUp : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseUp(Telerik.Web.UI.ArrowPosition.Bottom);
	},
	
	_onBottomArrowMouseOver : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOver(Telerik.Web.UI.ArrowPosition.Bottom);
	},
	
	_onBottomArrowMouseOut : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOut(Telerik.Web.UI.ArrowPosition.Bottom);
	},

	_onLeftArrowMouseDown : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseDown(Telerik.Web.UI.ArrowPosition.Left);
	},
	
	_onLeftArrowMouseUp : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseUp(Telerik.Web.UI.ArrowPosition.Left);
	},
	
	_onLeftArrowMouseOver : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOver(Telerik.Web.UI.ArrowPosition.Left);
	},
	
	_onLeftArrowMouseOut : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOut(Telerik.Web.UI.ArrowPosition.Left);
	},

	_onRightArrowMouseDown : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseDown(Telerik.Web.UI.ArrowPosition.Right);
	},
	
	_onRightArrowMouseUp : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseUp(Telerik.Web.UI.ArrowPosition.Right);
	},
	
	_onRightArrowMouseOver : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOver(Telerik.Web.UI.ArrowPosition.Right);
	},
	
	_onRightArrowMouseOut : function (e)
	{
		var item = this._extractItemFromDomElement(e.eventMapTarget);
		item._onScrollArrowMouseOut(Telerik.Web.UI.ArrowPosition.Right);
	},
	
	_onScrollArrowClicked : function (e)
	{
		e.preventDefault();
		e.stopPropagation();
		return false;
	},

	_childrenCleared: function(parent)
	{
		//var slideWrapElement = parent.get_slideWrapElement();
		if (parent._slideWrapElement) 
		{
			parent._slideWrapElement.outerHTML = "";
			parent._slideWrapElement = null;
			parent._scrollWrapElement = null;
		}

		parent._linkElement = null;
		parent._childListElement = null;
		parent._animatedElement = null;
		parent._animationContainer = null;

		Telerik.Web.UI.RadMenu.callBaseMethod(this, "_childrenCleared", [parent]);
	},
	
	_childInserted : function(index, item, parent)
	{
		Telerik.Web.UI.RadMenu.callBaseMethod(this, "_childInserted", [index, item, parent]);
		
		if (parent._state && parent._state == Telerik.Web.UI.RadMenuItemState.Open)
		{
			// The width might be zero if the item has been just rendered.
			if (item._getWidth() > 0)
			{
				Telerik.Web.UI.RadMenu._adjustChildrenWidth(parent);
			}
		}
	},
	
	_childRemoved: function(item, parent)
	{
		item.get_text();
		
		var childElement = item.get_element();
		if (parent.get_items().get_count() == 0) 
		{
			if (parent._slide) 
			{
				parent._slide.dispose();
				parent._slide = null;
			}
			
			childElement = $telerik.getFirstChildByTagName(parent.get_element(), "div", 0);

			parent._linkElement = null;
			parent._childListElement = null;
			parent._scrollWrapElement = null;
			parent._slideWrapElement = null;
			parent._animatedElement = null;
			parent._animationContainer = null;
		}
		if (childElement) 
		{
			childElement.outerHTML = "";
			
			if (childElement.parentNode) 
			{
				childElement.parentNode.removeChild(childElement);
			}
			childElement = null;
		}
		
		var itemsCount = parent.get_items().get_count();
		if (itemsCount > 0) 
		{
			var firstItemElement = parent.get_items().getItem(0).get_element();
			if (firstItemElement && !Sys.UI.DomElement.containsCssClass(firstItemElement, "rmFirst")) 
			{
				firstItemElement.className += " rmFirst";
			}
		}
		
		var lastIndex = itemsCount - 1;
		if (itemsCount > 0) 
		{
			var lastItemElement = parent.get_items().getItem(lastIndex).get_element();
			if (lastItemElement && !Sys.UI.DomElement.containsCssClass(lastItemElement, "rmLast")) 
			{
				lastItemElement.className += " rmLast";
			}
		}
		
		Telerik.Web.UI.RadMenu.callBaseMethod(this, "_childRemoved", [item, parent]);		
			
		if (parent._state && parent._state == Telerik.Web.UI.RadMenuItemState.Open) 
		{
			Telerik.Web.UI.RadMenu._adjustChildrenWidth(parent, true);
		}
	},

	_getExtendedItemClickingEventArgs : function(radMenuItemClickingEventArgs)
	{
		return radMenuItemClickingEventArgs;
	},

	_getExtendedItemClickedEventArgs : function(radMenuItemClickedEventArgs)
	{
		return radMenuItemClickedEventArgs;
	},
	
	_incrementZIndex : function (step)
	{
		if (this._zIndexIncrementDepth == 0) 
		{		
			var element = this.get_element();
			element.style.zIndex = this._originalZIndex + step;
		}

		this._zIndexIncrementDepth++;
	},
	
	_restoreZIndex : function ()
	{
		if (this._zIndexIncrementDepth > 0) 
		{
			this._zIndexIncrementDepth--;
		}
				
		if (this._zIndexIncrementDepth == 0) 
		{		
			var element = this.get_element();
			element.style.zIndex = this._originalZIndex;
		}
	},
	
	_getRtlClassName : function()
	{
		return "rmRtl";
	},
	
	_initRightToLeft : function ()
	{
		this.get_element().dir = "ltr"
	
		if (this.get_element().className.indexOf("rmRtl") < 0)
		{
			this.get_element().className = String.format("{0} {1}", this.get_element().className, this._getRtlClassName());
			if (this._skin)
			{
				this.get_element().className = String.format("{0} RadMenu_{1}_rtl", 
					this.get_element().className, this._skin);
			}
		}
		for (var i = 0; i < this.get_items().get_count(); i++)
		{
			var item = this.get_items().getItem(i);
			var itemImage = item.get_imageElement();
			if (itemImage)
			{
				 itemImage.style.styleFloat = "left";
				 itemImage.style.cssFloat = "left";
				 item.get_linkElement().style.width = item._getWidth() + "px";
				 itemImage.style.styleFloat = "right";
				 itemImage.style.cssFloat = "right";
			}
		}
	},
	
	_postback: function(hierarchicalIndex)
	{
		if (!this._postBackReference)
			return;
			
		var postbackFunction = this._postBackReference.replace("arguments", 
				hierarchicalIndex);
		eval(postbackFunction);
	},
	
	_raiseEvent : function(eventName, eventArgs)
	{
		if (this._fireEvents)
		{
			this.raiseEvent(eventName, eventArgs);
		}
	},
	
	// Web Service LOD	
	_initializeWebServiceLoader : function()
	{
		this._webServiceLoader = new Telerik.Web.UI.WebServiceLoader(this.get_webServiceSettings());
		this._webServiceLoader.add_loadingStarted(Function.createDelegate(this, this._onItemLoadingStarted));
		this._webServiceLoader.add_loadingSuccess(Function.createDelegate(this, this._onItemLoadingSuccess));
		this._webServiceLoader.add_loadingError(Function.createDelegate(this, this._onItemLoadingError));
	},
	
	_loadChildrenFromWebService : function (item)
	{
		if (!this._webServiceLoader)
		{
			this._initializeWebServiceLoader();
		}
		
		var userContext = { };
		var itemPopulatingArgs = new Telerik.Web.UI.RadMenuItemPopulatingEventArgs(item, userContext);
		this._raiseEvent("itemPopulating", itemPopulatingArgs);
		
		if (itemPopulatingArgs.get_cancel())
		{
			return;
		}
				
		var itemData = { Text: item.get_text(), Value: item.get_value(), ExpandMode: item.get_expandMode() };	
		var params = { item: itemData, context: userContext };
		this._webServiceLoader.loadData(params, item);
	},
	
	_onItemLoadingStarted : function(sender, eventArgs)
	{
		var item = eventArgs.get_context();
		item._onChildrenLoading();
	},
	
	_onItemLoadingSuccess : function(sender, eventArgs)
	{
		var result = eventArgs.get_data();
		var item = eventArgs.get_context();

		var childItems = item.get_items();
		for (i = 0; i < result.length; i++)
		{
			var itemData = result[i];
			var dynamicItem = new Telerik.Web.UI.RadMenuItem();
			dynamicItem._loadFromDictionary(itemData);
			
			if (dynamicItem.get_navigateUrl() === "")
			{
				dynamicItem.set_navigateUrl("#");
			}
			
			childItems.add(dynamicItem);
		}
		
		item._onChildrenLoaded();

		if (this.get_persistLoadOnDemandItems())
		{
			this.trackChanges();
			
			item.set_expandMode(Telerik.Web.UI.MenuItemExpandMode.ClientSide);
			var childCount = childItems.get_count();
			for (var i = 0; i < childCount; i++)
			{
				this._log.logInsert(childItems.getItem(i));
			}
			
			this.commitChanges();
		}

		var itemPopulatedArgs = new Telerik.Web.UI.RadMenuItemPopulatedEventArgs(item);
		this._raiseEvent("itemPopulated", itemPopulatedArgs);
	},

	_onItemLoadingError : function (sender, eventArgs)
	{
		var errorMessage = eventArgs.get_message();
		var item = eventArgs.get_context();
		
		item._onChildrenLoadingError();
		
		var itemPopulationFailedArgs = new Telerik.Web.UI.RadMenuItemPopulationFailedEventArgs(item, errorMessage);
		this._raiseEvent("itemPopulationFailed", itemPopulationFailedArgs);
		
		if (itemPopulationFailedArgs.get_cancel())
		{
			return;
		}	
		
		alert(errorMessage);
	},

	
	// Events
	add_mouseOver: function(handler)
	{
		this.get_events().addHandler("mouseOver", handler);
	},
	
	remove_mouseOver: function(handler)
	{
		this.get_events().removeHandler("mouseOver", handler);
	},
	
	add_mouseOut: function(handler)
	{
		this.get_events().addHandler("mouseOut", handler);
	},
	
	remove_mouseOut: function(handler)
	{
		this.get_events().removeHandler("mouseOut", handler);
	},
	
	add_itemFocus: function(handler)
	{
		this.get_events().addHandler("itemFocus", handler);
	},
	
	remove_itemFocus: function(handler)
	{
		this.get_events().removeHandler("itemFocus", handler);
	},
	
	add_itemBlur: function(handler)
	{
		this.get_events().addHandler("itemBlur", handler);
	},
	
	remove_itemBlur: function(handler)
	{
		this.get_events().removeHandler("itemBlur", handler);
	},
	
	add_itemClicking: function(handler)
	{
		this.get_events().addHandler("itemClicking", handler);
	},
	
	remove_itemClicking: function(handler)
	{
		this.get_events().removeHandler("itemClicking", handler);
	},
	
	add_itemClicked: function(handler)
	{
		this.get_events().addHandler("itemClicked", handler);
	},
	
	remove_itemClicked: function(handler)
	{
		this.get_events().removeHandler("itemClicked", handler);
	},
	
	add_itemOpening: function(handler)
	{
		this.get_events().addHandler("itemOpening", handler);
	},
	
	remove_itemOpening: function(handler)
	{
		this.get_events().removeHandler("itemOpening", handler);
	},
	
	add_itemOpened: function(handler)
	{
		this.get_events().addHandler("itemOpened", handler);
	},
	
	remove_itemOpened: function(handler)
	{
		this.get_events().removeHandler("itemOpened", handler);
	},
	
	add_itemClosing: function(handler)
	{
		this.get_events().addHandler("itemClosing", handler);
	},
	
	remove_itemClosing: function(handler)
	{
		this.get_events().removeHandler("itemClosing", handler);
	},
	
	add_itemClosed: function(handler)
	{
		this.get_events().addHandler("itemClosed", handler);
	},
	
	remove_itemClosed: function(handler)
	{
		this.get_events().removeHandler("itemClosed", handler);
	},
	
	add_load: function(handler)
	{
		this.get_events().addHandler("load", handler);
	},
	
	remove_load: function(handler)
	{
		this.get_events().removeHandler("load", handler);
	},
	
	add_itemPopulating: function(handler)
	{
		this.get_events().addHandler("itemPopulating", handler);
	},
	
	remove_itemPopulating: function(handler)
	{
		this.get_events().removeHandler("itemPopulating", handler);
	},
	
	add_itemPopulated: function(handler)
	{
		this.get_events().addHandler("itemPopulated", handler);
	},
	
	remove_itemPopulated: function(handler)
	{
		this.get_events().removeHandler("itemPopulated", handler);
	},
	
	add_itemPopulationFailed: function(handler)
	{
		this.get_events().addHandler("itemPopulationFailed", handler);
	},
	
	remove_itemPopulationFailed: function(handler)
	{
		this.get_events().removeHandler("itemPopulationFailed", handler);
	}
}

Telerik.Web.UI.RadMenu.registerClass('Telerik.Web.UI.RadMenu', Telerik.Web.UI.ControlItemContainer);

/* END Telerik.Web.UI.Menu.RadMenu.js */
/* START Telerik.Web.UI.Menu.RadMenuItemGroupSettings.js */
Type.registerNamespace("Telerik.Web.UI");


// ---------- RadMenuItemGroupSettings Class ----------
Telerik.Web.UI.RadMenuItemGroupSettings = function (serializedSettings, defaultSettings)
{
	this._flow = Telerik.Web.UI.ItemFlow.Vertical;
	this._expandDirection = Telerik.Web.UI.ExpandDirection.Auto;
	this._offsetX = 0;
	this._offsetY = 0;
	this._width = null;
	this._height = null;
	
	if (typeof(serializedSettings.flow) != "undefined")
	{
		this._flow = serializedSettings.flow;
	}
	else
	{
		if (defaultSettings)
		{
			this._flow = defaultSettings.get_flow();
		}
	}
	
	if (typeof(serializedSettings.expandDirection) != "undefined")
	{
		this._expandDirection = serializedSettings.expandDirection;
	}
	else
	{
		if (defaultSettings)
		{
			this._expandDirection = defaultSettings.get_expandDirection();
		}
	}
	
	if (typeof(serializedSettings.offsetX) != "undefined")
	{
		this._offsetX = serializedSettings.offsetX;
	}
	else
	{
		if (defaultSettings)
		{
			this._offsetX = defaultSettings.get_offsetX();
		}
	}
	
	if (typeof(serializedSettings.offsetY) != "undefined")
	{
		this._offsetY = serializedSettings.offsetY;
	}
	else
	{
		if (defaultSettings)
		{
			this._offsetY = defaultSettings.get_offsetY();
		}
	}
	
	if (typeof(serializedSettings.width) != "undefined")
	{
		this._width = serializedSettings.width;
	}
	else
	{
		if (defaultSettings)
		{
			this._width = defaultSettings.get_width();
		}
	}
	
	if (typeof(serializedSettings.height) != "undefined")
	{
		this._height = serializedSettings.height;
	}
	else
	{
		if (defaultSettings)
		{
			this._height = defaultSettings.get_height();
		}
	}
}

Telerik.Web.UI.RadMenuItemGroupSettings.prototype =
{
	get_flow : function ()
	{
		return this._flow;
	},
	
	set_flow : function(value)
	{
		this._flow = value;
	},
	
	get_expandDirection : function ()
	{
		return this._expandDirection;
	},
	
	set_expandDirection : function(value)
	{
		this._expandDirection = value;
	},
	
	get_offsetX : function ()
	{
		return this._offsetX;
	},
	
	set_offsetX : function(value)
	{
		this._offsetX = value;
	},
	
	get_offsetY : function ()
	{
		return this._offsetY;
	},
	
	set_offsetY : function(value)
	{
		this._offsetY = value;
	},
	
	get_width : function ()
	{
		return this._width;
	},
	
	set_width : function(value)
	{
		this._width = value;
	},
	
	get_height : function ()
	{
		return this._height;
	},
	
	set_height : function(value)
	{
		this._height = value;
	}	
}

Telerik.Web.UI.RadMenuItemGroupSettings.registerClass('Telerik.Web.UI.RadMenuItemGroupSettings');



/* END Telerik.Web.UI.Menu.RadMenuItemGroupSettings.js */
/* START Telerik.Web.UI.Menu.RadMenuItemCollection.js */
Type.registerNamespace("Telerik.Web.UI");

Telerik.Web.UI.RadMenuItemCollection = function (parent)
{
	Telerik.Web.UI.RadMenuItemCollection.initializeBase(this, [parent]);
}

Telerik.Web.UI.RadMenuItemCollection.prototype = 
{
}

Telerik.Web.UI.RadMenuItemCollection.registerClass("Telerik.Web.UI.RadMenuItemCollection", Telerik.Web.UI.ControlItemCollection);

/* END Telerik.Web.UI.Menu.RadMenuItemCollection.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 maximiz