
//////////////////////////////////////////////
//RadAjaxNamespace
//////////////////////////////////////////////
(function(){
RADAJAXNAMESPACEVERSION = 25;
if(typeof(window.RadAjaxNamespace) == "undefined" || typeof(window.RadAjaxNamespace.Version) == "undefined" || window.RadAjaxNamespace.Version < RADAJAXNAMESPACEVERSION)
{
window.RadAjaxNamespace = 
{
	Version : RADAJAXNAMESPACEVERSION,
	IsAsyncResponse : false,
	LoadingPanels : {},
	ExistingScripts : {},
	IsInRequest : false,
	MaxRequestQueueSize : 5
};
//////////////////////////////////////////////

var AjaxNS = window.RadAjaxNamespace;

AjaxNS.EventManager =
{
	_registry: null,

    Initialise: function()
    {
		try
		{
			if (this._registry == null)
			{
				this._registry = [];
				AjaxNS.EventManager.Add(window, "unload", this.CleanUp);
			}
 		}
		catch(e)
		{
			AjaxNS.OnError(e)
		}
    },
           
           
    Add: function(element, eventName, eventHandler, clientID)
    {
		try
		{
			this.Initialise();

			if (element == null || eventHandler == null)
			{
				return false;
			}
	        
			if (element.addEventListener && !window.opera)
			{
				element.addEventListener(eventName, eventHandler, true);
				this._registry[this._registry.length] = {element: element, eventName: eventName, eventHandler: eventHandler, clientID: clientID};
				return true;
			}
	        
			if (element.addEventListener && window.opera)
			{
				element.addEventListener(eventName, eventHandler, false);
				this._registry[this._registry.length] = {element: element, eventName: eventName, eventHandler: eventHandler, clientID: clientID};
				return true;
			}
	        

			if (element.attachEvent && element.attachEvent("on" + eventName, eventHandler))
			{
				this._registry[this._registry.length] = {element: element, eventName: eventName, eventHandler: eventHandler, clientID: clientID};
				return true;
			}

			return false;
  		}
		catch(e)
		{
			AjaxNS.OnError(e)
		}
   },

    CleanUp: function()
    {
		try
		{
			if (AjaxNS.EventManager._registry)
			{
				for (var i = 0; i < AjaxNS.EventManager._registry.length; i++)
				{
					with (AjaxNS.EventManager._registry[i])
					{
						if (element.removeEventListener)
							element.removeEventListener(eventName, eventHandler, false);
						else if (element.detachEvent)
							element.detachEvent("on" + eventName, eventHandler);
					}
				}

				AjaxNS.EventManager._registry = null;
			}
  		}
		catch(e)
		{
			AjaxNS.OnError(e)
		}
    },
    
    CleanUpByClientID: function(id)
    {
		try
		{
			if (AjaxNS.EventManager._registry)
			{
				for (var i = 0; i < AjaxNS.EventManager._registry.length; i++)
				{
					with (AjaxNS.EventManager._registry[i])
					{
					   if(clientID + "" == id + "")
					   {
						if (element.removeEventListener)
							element.removeEventListener(eventName, eventHandler, false);
						else if (element.detachEvent)
							element.detachEvent("on" + eventName, eventHandler);
						}
					}
				}
			}
  		}
		catch(e)
		{
			AjaxNS.OnError(e)
		}
    }
};

AjaxNS.EventManager.Add(window, "load", function()
	{
		var scriptElements = document.getElementsByTagName("script");
		for (var i = 0; i < scriptElements.length; i++)
		{
			var scriptElement = scriptElements[i];
			if (scriptElement.src != "")
				AjaxNS.ExistingScripts[scriptElement.src] = true;
		}
	});


AjaxNS.ServiceRequest = function(url, args, onComplete, onError, userCompleteHandler, userErrorHandler)
{
	try
	{
		var xmlRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

		if (xmlRequest == null)
			return;

		xmlRequest.open("POST", url, true);

		xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		xmlRequest.onreadystatechange = function(){AjaxNS.HandleAsyncServiceResponse(xmlRequest, onComplete, onError, userCompleteHandler, userErrorHandler);};

        xmlRequest.send(args);
	}
	catch(ex)
	{
		if(typeof(onError) == "function")
		{
		    var e = 
		    {
		        "ErrorCode" : "",
		        "ErrorText" : ex.message,
		        "message" : ex.message, //adding for consistency
		        "Text" : "",
		        "Xml" : ""
		    };
			onError(e);
		}
	}
};

AjaxNS.SyncServiceRequest = function(url, args, onComplete, onError)
{
	try
	{
		var xmlRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

		if (xmlRequest == null)
			return null;

		xmlRequest.open("POST", url, false);
		xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xmlRequest.send(args);
        return AjaxNS.HandleSyncServiceResponse(xmlRequest, onComplete, onError);
	}
	catch(ex)
	{
		if(typeof(onError) == "function")
		{
		    var e = 
		    {
		        "ErrorCode" : "",
		        "ErrorText" : ex.message,
		        "message" : ex.message, //adding for consistency
		        "Text" : "",
		        "Xml" : ""
		    };
			onError(e);
		}
		
		return null;
	}
};

/*
//Currently not used.
AjaxNS.RssRequest = function(url, onComplete, onError)
{
	try
	{
		var xmlRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

		if (xmlRequest == null)
			return;

		xmlRequest.open("GET", url, true);

		xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		xmlRequest.onreadystatechange = function(){AjaxNS.HandleAsyncServiceResponse(xmlRequest, onComplete, onError);};

	    xmlRequest.send(null);
	}
	catch(ex)
	{
		if(typeof(onError) == "function")
		{
		    var e = 
		    {
		        "ErrorCode" : "",
		        "ErrorText" : ex.message,
		        "message" : ex.message, //adding for consistency
		        "Text" : "",
		        "Xml" : ""
		    };
			onError(e);
		}
	}
};*/

AjaxNS.Check404Status = function(xmlHttpRequestObject)
{
    try
    {
	    if (xmlHttpRequestObject && xmlHttpRequestObject.status == 404)
	    {
		    var errorText;
		    errorText = "Ajax callback error: source url not found! \n\r\n\rPlease verify if you are using any URL-rewriting code and set the AjaxUrl property to match the URL you need.";

		    var error = new Error(errorText);
		    throw(error);
    		
		    return;
	    }
	}
	catch(ex)
	{	}
} 

AjaxNS.HandleAsyncServiceResponse = function (xmlHttpRequestObject, onComplete, onError, userCompleteHandler, userErrorHandler)
{
	try
	{		
		if (xmlHttpRequestObject == null || 
			xmlHttpRequestObject.readyState != 4)
			return;
			
		AjaxNS.Check404Status(xmlHttpRequestObject);

		if(xmlHttpRequestObject.status != 200 && typeof(onError) == "function")
		{
		    var e = 
		    {
		        "ErrorCode" : xmlHttpRequestObject.status,
		        "ErrorText" : xmlHttpRequestObject.statusText,
		        "message" : xmlHttpRequestObject.statusText, //adding for consistency
		        "Text" : xmlHttpRequestObject.responseText,
		        "Xml" : xmlHttpRequestObject.responseXml
		    };
			onError(e, userErrorHandler);
			return;
		}
        
		if(typeof(onComplete) == "function")
		{
		    var e = 
		    {
		        "Text" : xmlHttpRequestObject.responseText,
		        "Xml" : xmlHttpRequestObject.responseXML
		    };
			onComplete(e, userCompleteHandler);
		}
	}
	catch(ex)
	{
		if(typeof(onError) == "function")
		{
		    var e = 
		    {
		        "ErrorCode" : "",
		        "ErrorText" : ex.message,
		        "message" : ex.message, //adding for consistency
		        "Text" : "",
		        "Xml" : ""
		    };
			onError(e);
		}
	}
	
	if (xmlHttpRequestObject != null)
	{
		xmlHttpRequestObject.onreadystatechange = AjaxNS.EmptyFunction;
	}
};

AjaxNS.HandleSyncServiceResponse = function (xmlHttpRequestObject, onComplete, onError)
{
	try
	{			
		AjaxNS.Check404Status(xmlHttpRequestObject);

		if(xmlHttpRequestObject.status != 200 && typeof(onError) == "function")
		{
		    var e = 
		    {
		        "ErrorCode" : xmlHttpRequestObject.status,
		        "ErrorText" : xmlHttpRequestObject.statusText,
		        "message" : xmlHttpRequestObject.statusText, //adding for consistency
		        "Text" : xmlHttpRequestObject.responseText,
		        "Xml" : xmlHttpRequestObject.responseXml
		    };
			onError(e);
			return null;
		}
        
		if(typeof(onComplete) == "function")
		{
		    var e = 
		    {
		        "Text" : xmlHttpRequestObject.responseText,
		        "Xml" : xmlHttpRequestObject.responseXML
		    };
			
			return onComplete(e);
		}
	}
	catch(ex)
	{
		if(typeof(onError) == "function")
		{
		    var e = 
		    {
		        "ErrorCode" : "",
		        "ErrorText" : ex.message,
		        "message" : ex.message, //adding for consistency
		        "Text" : "",
		        "Xml" : ""
		    };
			onError(e);
		}
		
		return null;
	}

};

AjaxNS.FocusElement = function(controlId)
{
    var controlToFocus = document.getElementById(controlId);
    if (controlToFocus)
    {
        var controlTagName = controlToFocus.tagName;
        var controlType = controlToFocus.type;
        
        if (controlTagName.toLowerCase()== "input" && (controlType.toLowerCase() == "checkbox" || controlType.toLowerCase() == "radio"))
        {
            window.setTimeout(
                function()
                {
                    try 
                    {
                        //AjaxNS.SetSelectionFocus(controlToFocus);
                        controlToFocus.focus();
                    }
                    catch(e)
                    {}
                }, 500);
        }
        else
        {
            try 
            {
                AjaxNS.SetSelectionFocus(controlToFocus);
                controlToFocus.focus();
            }
            catch(e)
            {}
        }
    }
}

AjaxNS.SetSelectionFocus = function(element)
{
    if (element.createTextRange == null)
    {
        return;
    }
        
	var range = null;
	try
	{
	    range = element.createTextRange();
	}
	catch(e){}
	
	if (range != null)
	{
	    range.moveStart('textedit', range.text.length);
	    range.collapse(false);
	    range.select();
	}
};

AjaxNS.GetForm = function(clientID)
{
    var form = null;
	if(typeof(window[clientID].FormID) != "undefined")
	{
		form = document.getElementById(window[clientID].FormID);
	}
	return window[clientID].Form || form || document.forms[0];
};

AjaxNS.CreateNewXmlHttpObject = function()
{
	return (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
}

if(typeof(AjaxNS.RequestQueue) == "undefined")
{
    AjaxNS.RequestQueue = [];
}

AjaxNS.QueueRequest = function()
{
    if(RadAjaxNamespace.MaxRequestQueueSize > 0 && AjaxNS.RequestQueue.length < RadAjaxNamespace.MaxRequestQueueSize)
    {
        AjaxNS.RequestQueue.push(arguments);
    }
    else
    {
        //AjaxNS.OnError(new Error("Request is being dropped because another one is currently processing..."), arguments[0]);
    }
}

AjaxNS.History = {};
AjaxNS.HandleHistory = function(clientID, data)
{
    if(window.netscape) return;

    var historyFrame = document.getElementById(clientID + "_History");
    if(historyFrame == null)
    {
        historyFrame = document.createElement("iframe");
        historyFrame.id = clientID + "_History";
        historyFrame.name = clientID + "_History";
        historyFrame.style.width = "0px";
        historyFrame.style.height = "0px";
        historyFrame.src = "javascript:''";
        historyFrame.style.visibility = "hidden";        

        var loadHandler = function(e)
        {            
            if(!AjaxNS.ShouldLoadHistory)
            {
                AjaxNS.ShouldLoadHistory = true;
                return;
            }
            
            if(!AjaxNS.IsInRequest)
            {
                var target = "";
                var argument = "";

                var dataValueElement = historyFrame.contentWindow.document.getElementById("__DATA");

                if(!dataValueElement) return;

                var dataArray = dataValueElement.value.split("&");

                for (var i = 0, length = dataArray.length; i < length; i++)
                {
                    var keyValue = dataArray[i].split("=");

                    if(keyValue[0] == "__EVENTTARGET")
                    {
                        target = keyValue[1];
                    }
                    
                    if(keyValue[0] == "__EVENTARGUMENT")
                    {
                        argument = keyValue[1];
                    }

                    var element = document.getElementById(AjaxNS.UniqueIDToClientID(keyValue[0]));
                    if(element != null)
                    {
                        AjaxNS.RestorePostData(element, AjaxNS.DecodePostData(keyValue[1]));
                    }
                }

                if(target != "")
                {
                   	var element = document.getElementById(AjaxNS.UniqueIDToClientID(target));
                    if(element != null)
                    {
                        AjaxNS.AsyncRequest(target, AjaxNS.DecodePostData(argument), clientID);
                    }
                }
            }
        };

        AjaxNS.EventManager.Add(historyFrame, "load", loadHandler);
        document.body.appendChild(historyFrame);
    }
    
    if(AjaxNS.History[data] == null)
    {
        AjaxNS.History[data] = true;
        AjaxNS.AddHistoryEntry(historyFrame, data);
    }
};

AjaxNS.AddHistoryEntry = function(historyFrame, data)
{
    AjaxNS.ShouldLoadHistory = false;

    historyFrame.contentWindow.document.open();
    historyFrame.contentWindow.document.write("<input id='__DATA' name='__DATA' type='hidden' value='" + data + "' />");
    historyFrame.contentWindow.document.close();

    if(window.netscape)
    {
        historyFrame.contentWindow.document.location.hash = "#'" + new Date() + "'";
    }
};

AjaxNS.DecodePostData = function(value)
{
    if (decodeURIComponent)
    {
        return decodeURIComponent(value);
    }
    else
    {
        return unescape(value);
    }
};

AjaxNS.UniqueIDToClientID = function(uniqueID)
{
    return uniqueID.replace(/\$/g, '_');
}

AjaxNS.RestorePostData = function(element, value)
{//alert(element.tagName + ", " + value);
    if(element.tagName.toLowerCase() == "select")
    {
        for (var i = 0, length = element.options.length; i < length; i++)
        {
            if (value.indexOf(element.options[i].value) != -1)
            {
                element.options[i].selected = true;
            }
        }
    }

    if(element.tagName.toLowerCase() == "input" && (element.type.toLowerCase() == "text" || element.type.toLowerCase() == "hidden"))
    {
        element.value = value;
    }
    
    if(element.tagName.toLowerCase() == "input" && (element.type.toLowerCase() == "checkbox" || element.type.toLowerCase() == "radio"))
    {
        element.checked = value;
    }
};

AjaxNS.AsyncRequest = function(eventTarget, eventArgument, clientID, e)
{	
	try
	{
		if (eventTarget == "" || clientID == "")
			return;

		var instance = window[clientID];
			
	    var xmlHttpRequestObject = AjaxNS.CreateNewXmlHttpObject();

		if (xmlHttpRequestObject == null)
			return;	
			
		if (AjaxNS.IsInRequest)
		{
		    AjaxNS.QueueRequest.apply(AjaxNS,arguments);
		    return;
		}
			
		if (!RadCallbackNamespace.raiseEvent("onrequeststart")) 
			return;
				
		var evt = AjaxNS.CreateClientEvent(eventTarget, eventArgument);
		if (typeof(instance.EnableAjax) != "undefined")
		{
		    evt.EnableAjax = instance.EnableAjax;		    
		}
		else
		{
		    evt.EnableAjax = true;	
		}
		evt.XMLHttpRequest = xmlHttpRequestObject;
		
		if(!AjaxNS.FireEvent(instance, "OnRequestStart", [evt]))
			return;
		
		if(!evt.EnableAjax && typeof(__doPostBack) != "undefined")
		{
			__doPostBack(eventTarget, eventArgument);
			return;
		}
		
		var result = window.OnCallbackRequestStart(instance, evt);

	    if(typeof(result) == "boolean" && result == false)
	        return;
        
		evt = null;
        
        AjaxNS.IsInRequest = true;
        
		AjaxNS.PrepareFormForAsyncRequest(eventTarget, eventArgument, clientID);

		if (typeof(instance.PrepareLoadingTemplate) == "function")
			instance.PrepareLoadingTemplate();
		AjaxNS.ShowLoadingTemplate(clientID);
		
		var postbackControlClientID = eventTarget.replace(/(\$|:)/g, "_");
		RadAjaxNamespace.LoadingPanel.ShowLoadingPanels(instance, postbackControlClientID);

		var data = AjaxNS.GetPostData(clientID, e);
        data += AjaxNS.GetUrlForAsyncRequest(clientID);
        
        if(false)
        {
            if(AjaxNS.History[""] == null)
            {
                AjaxNS.HandleHistory(clientID, "");
            }

            AjaxNS.HandleHistory(clientID, data);
        }
        
    	xmlHttpRequestObject.open("POST", AjaxNS.UrlDecode(instance.Url), true);
		
        try
        {
		    xmlHttpRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            
            if(!AjaxNS.IsNetscape())
            {   
                xmlHttpRequestObject.setRequestHeader("Content-Length", data.length);
            }
        }
        catch(e)
        {
            //
        }
		
		xmlHttpRequestObject.onreadystatechange = function(){AjaxNS.HandleAsyncRequestResponse(clientID, null, eventTarget, eventArgument, xmlHttpRequestObject);};
		xmlHttpRequestObject.send(data);
		
		data = null;
		
		var evt = AjaxNS.CreateClientEvent(eventTarget, eventArgument);
		AjaxNS.FireEvent(instance, "OnRequestSent", [evt])

		window.OnCallbackRequestSent(instance, evt);
        
		instance = null;
		postbackControlClientID = null;
		evt = null;		
	}
	catch(e)
	{
		AjaxNS.OnError(e, clientID)
	}
};

AjaxNS.CreateClientEvent = function(eventTarget, eventArgument)
{
	var postbackControlClientID = eventTarget.replace(/(\$|:)/g, "_");
	
	var evt =
		{
			EventTarget : eventTarget,
			EventArgument : eventArgument,
			EventTargetElement : document.getElementById(postbackControlClientID)
		};
	return evt;
}

AjaxNS.IncludeClientScript = function(src)
{
    if(AjaxNS.XMLHttpRequest == null)
    {
	   AjaxNS.XMLHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (AjaxNS.XMLHttpRequest == null)
		return;

	AjaxNS.XMLHttpRequest.open("GET", src, false);
	AjaxNS.XMLHttpRequest.send(null);
	
	if(AjaxNS.XMLHttpRequest.status == 200)
	{
		var scriptCode = AjaxNS.XMLHttpRequest.responseText;
		AjaxNS.EvalScriptCode(scriptCode);
	}
};

AjaxNS.EvalScriptCode = function(scriptCode)
{
	if (AjaxNS.IsSafari())
	{
		scriptCode = scriptCode.replace(/^\s*<!--((.|\n)*)-->\s*$/mi, "$1");
	}
	
    var newScript = document.createElement("script");
    newScript.setAttribute("type", "text/javascript");    		
   
    if (AjaxNS.IsSafari())
    {
        newScript.appendChild(document.createTextNode(scriptCode));
    }
    else
    {
        newScript.text = scriptCode;
    }
    
	var scriptContainer = AjaxNS.GetHeadElement();
	
	scriptContainer.appendChild(newScript);
    
    if (AjaxNS.IsSafari())
    {
        newScript.innerHTML = "";
    }
    else
    {
        newScript.parentNode.removeChild(newScript);
    }
};

AjaxNS.evaluateScriptElementCode = function(scriptElement)
{
	var scriptCode = "";
    if (AjaxNS.IsSafari())
    {
        scriptCode = scriptElement.innerHTML;
    }
    else
    {
        scriptCode = scriptElement.text;
    }

    AjaxNS.EvalScriptCode(scriptCode);
};

AjaxNS.ExecuteScripts = function(node, clientID)
{
	try
	{
	    var scripts = node.getElementsByTagName("script");
        
	    for (var i = 0, len = scripts.length; i < len; i++)
	    {
		    var script = scripts[i];
		    if((script.type && script.type.toLowerCase() == "text/javascript") || 
				(script.getAttribute("language") && script.getAttribute("language").toLowerCase() == "javascript"))
		    {
			    if(!window.opera)
			    {
				    if(script.src != "")
				    {
				        if( AjaxNS.ExistingScripts[script.src] == null)
				        {
					        AjaxNS.IncludeClientScript(script.src);
					        AjaxNS.ExistingScripts[script.src] = true;
					    }
				    }
				    else
				    {
		                AjaxNS.evaluateScriptElementCode(script);
		            }
			    }
			}
	    }
	    
	    for (var i = scripts.length - 1; i >= 0; i--)
	    {
	        RadAjaxNamespace.DestroyElement(scripts[i]);
	    }
	}
	catch(e)
	{
		AjaxNS.OnError(e, clientID)
	}
};

AjaxNS.ExecuteScriptsForDisposedIDs = function(node, clientID)
{
	try
	{
		if(node == null)
			return;

		if(window.opera)
			return;

	    var scripts = node.getElementsByTagName("script");

	    for (var i = 0, len = scripts.length; i < len; i++)
	    {
		    var script = scripts[i];		   		    
		    if(script.src != "")
		    {
		        if(!AjaxNS.ExistingScripts)
		            continue;

			      if( AjaxNS.ExistingScripts[script.src] == null)
			      {
			           AjaxNS.IncludeClientScript(script.src);
				       AjaxNS.ExistingScripts[script.src] = true;
				  }
		    }
		    if(( script.type && script.type.toLowerCase() == "text/javascript") || 
				(script.language && script.language.toLowerCase() == "javascript"))
		    {
		        if (script.text.indexOf("$create") != -1)
		        {
		            for(var j = 0, length = AjaxNS.disposedIDs.length; j < length; j++)
		            {
		                var id = AjaxNS.disposedIDs[j];

		                var createScript = AjaxNS.GetCreateCode(script, id);
		                
		                if (id != null && id != "" && createScript.indexOf(id) != -1)
		                {
				            AjaxNS.EvalScriptCode(createScript);
				            AjaxNS.disposedIDs = AjaxNS.RemoveElementFromArray(AjaxNS.disposedIDs[j], AjaxNS.disposedIDs);
				            j--;
		                }
		                
		            }
		        }
		    }
	    }
	}
	catch(e)
	{
		AjaxNS.OnError(e, clientID)
	}
};

AjaxNS.GetCreateCode = function(scriptElement, id)
{
	var scriptCode = "";
    if (AjaxNS.IsSafari())
    {
        scriptCode = scriptElement.innerHTML;
    }
    else
    {
        scriptCode = scriptElement.text;
    }
    
    var createScripts = [];

    while(scriptCode.indexOf("Sys.Application.add_init") != -1)
    {
        var code = scriptCode.substring(scriptCode.indexOf("Sys.Application.add_init"), scriptCode.indexOf("});") + 3);
        createScripts[createScripts.length] = code;
        scriptCode = scriptCode.replace(code, "");
    }

    for(var i = 0, length = createScripts.length; i < length; i++)
    {
        var code = createScripts[i];

        if(code.indexOf(id) != -1)
        {
            scriptCode = code;
            
            break;
        }
    }
    
    return scriptCode;
};

AjaxNS.RemoveElementFromArray = function(element, array)
{
    var newArray = [];
    
    for(var i = 0, length = array.length; i < length; i++)
    {
        if(element != array[i])
        {
            newArray[newArray.length] = array[i];
        }
    }
    
    return newArray;
};

AjaxNS.ResetValidators = function()
{
    if (typeof(Page_Validators) != "undefined")
    {
        Page_Validators = [];
    }		    
};

AjaxNS.ExecuteValidatorsScripts = function(node, clientID)
{
	try
	{
		if(node == null)
			return;

		if(window.opera)
			return;

	    var scripts = node.getElementsByTagName("script");

	    for (var i = 0, len = scripts.length; i < len; i++)
	    {
		    var script = scripts[i];		   		    
		    if(script.src != "")
		    {
		        if(!AjaxNS.ExistingScripts)
		            continue;

			      if( AjaxNS.ExistingScripts[script.src] == null)
			      {
			           AjaxNS.IncludeClientScript(script.src);
				       AjaxNS.ExistingScripts[script.src] = true;
				  }
		    }
		    if(( script.type && script.type.toLowerCase() == "text/javascript") || 
				(script.language && script.language.toLowerCase() == "javascript"))
		    {
		        if (
		            script.text.indexOf(".controltovalidate") == -1 && 
		            script.text.indexOf("Page_Validators") == -1 && 
		            script.text.indexOf("Page_ValidationActive") == -1 &&
		            script.text.indexOf("WebForm_OnSubmit") == -1
		           )
		        {
	                continue;
		        }   		        
				AjaxNS.evaluateScriptElementCode(script);
		    }
	    }
	}
	catch(e)
	{
		AjaxNS.OnError(e, clientID)
	}
};

AjaxNS.GetImageButtonCoordinates = function(e)
{     
    if (typeof(e.offsetX) == "number" && typeof(e.offsetY)  == "number") //IE, Opera, Safari
    {
        return {X : e.offsetX, Y: e.offsetY};
    }
    
    var mouseEventX = AjaxNS.GetMouseEventX(e);
    var mouseEventY = AjaxNS.GetMouseEventY(e);

    var image = e.target || e.srcElement;
    var imagePosition = AjaxNS.GetElementPosition(image);
    var x = mouseEventX - imagePosition.x;
    var y = mouseEventY - imagePosition.y;
    
    //TODO: gecko modification???
    if (!(AjaxNS.IsSafari() || window.opera))
    {
        x -= 2;
        y -= 2;
    }
    
    return {X : x, Y: y};
}

AjaxNS.GetMouseEventX = function(e)
{
    var mouseEventX = null;
    if (e.pageX) // Firefox, Netscape
    {
        mouseEventX = e.pageX;
    }
    else if (e.clientX) //???
    {
	    if (document.documentElement && document.documentElement.scrollLeft)
	        mouseEventX = e.clientX + document.documentElement.scrollLeft;
	    else
	        mouseEventX = e.clientX + document.body.scrollLeft;
    }
    
    return mouseEventX;
}

AjaxNS.GetMouseEventY = function(e)
{
    var mouseEventY = null;
    if (e.pageY)
    {
        mouseEventY = e.pageY;
    }
    else if (e.clientY)
    {
        if (document.documentElement && document.documentElement.scrollTop)
            mouseEventY = e.clientY + document.documentElement.scrollTop;
        else
            mouseEventY = e.clientY + document.body.scrollTop; 
    }
    
    return mouseEventY;
}

AjaxNS.GetElementPosition = function(el) 
{  
    var parent = null;
    var pos = {x: 0, y: 0};
    var box;

    if (el.getBoundingClientRect) 
    { 
		// IE
        box = el.getBoundingClientRect();
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;

        pos.x = box.left + scrollLeft - 2;
        pos.y = box.top + scrollTop - 2;
        
        return pos;
    }
    else if (document.getBoxObjectFor) 
    { 
		// gecko
        box = document.getBoxObjectFor(el);
        pos.x = box.x - 2;
        pos.y = box.y - 2;
    }
    else 
    { 
		// safari/opera
        pos.x = el.offsetLeft;
        pos.y = el.offsetTop;
        parent = el.offsetParent;
        if (parent != el)
        {
			while (parent) 
			{
				pos.x += parent.offsetLeft;
				pos.y += parent.offsetTop;
				parent = parent.offsetParent;
			}
        }
    }

	if (window.opera)
	{
		parent = el.offsetParent;
		
		while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') 
		{
			pos.x -= parent.scrollLeft;
			pos.y -= parent.scrollTop;
			parent = parent.offsetParent;
		}
	}
	else
	{
		parent = el.parentNode; 
		while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') 
		{
			pos.x -= parent.scrollLeft;
			pos.y -= parent.scrollTop;

			parent = parent.parentNode;
		}
    }

	return pos;
};

AjaxNS.IsImageButtonAjaxRequest = function(domElement, e)
{
    if (e != null)
    {
        //IE someties does not have e.srcElement and causes exceptions.
        try
        {
            var imageElement = e.target || e.srcElement;
            return domElement == imageElement;
        }
        catch(e)
        {
            return false;
        } 
    }
    else
    {
        return false;
    }
}

AjaxNS.GetPostData = function(clientID, e)
{
	try
	{
		var form = AjaxNS.GetForm(clientID);
		var formElements;
		var element;
        var stringBuffer = [];
                
        
        var userAgent = navigator.userAgent;
		if (AjaxNS.IsSafari() || userAgent.indexOf("Netscape"))
		{
			formElements = form.getElementsByTagName("*");
		}
		else
		{
			formElements = form.elements;
		}

		for (var i = 0, len1 = formElements.length; i < len1; i++)
		{
    		element = formElements[i];
    		
    		if(element.disabled == true)
    		    continue;

			var tagName = element.tagName.toLowerCase();
			if (tagName == "input")
			{
				var type = element.type;
				if ((type == "text" || type == "hidden" || type == "password" ||
				((type == "checkbox" || type == "radio") && element.checked)) 
				)
				{
				    var tmp = [];
				    tmp[tmp.length] = element.name;
				    tmp[tmp.length] = AjaxNS.EncodePostData(element.value);
					stringBuffer[stringBuffer.length] = tmp.join("=");
				}
				else if (type == "image" && AjaxNS.IsImageButtonAjaxRequest(element, e))
				{
				    var imageButtonCoordinates = AjaxNS.GetImageButtonCoordinates(e);
				    
				    var tmp = [];
				    tmp[tmp.length] = element.name + ".x";
				    tmp[tmp.length] = AjaxNS.EncodePostData(imageButtonCoordinates.X);
				    stringBuffer[stringBuffer.length] = tmp.join("=");
				    
				    var tmp = [];
				    tmp[tmp.length] = element.name + ".y";
				    tmp[tmp.length] = AjaxNS.EncodePostData(imageButtonCoordinates.Y);
				    stringBuffer[stringBuffer.length] = tmp.join("=");
				}
			}
			else if (tagName == "select")
			{
				for (var j = 0, len2 = element.options.length; j < len2; j++)
				{
					var selectChild = element.options[j];
					if (selectChild.selected == true)
					{
				        var tmp = [];
				        tmp[tmp.length] = element.name;
				        tmp[tmp.length] = AjaxNS.EncodePostData(selectChild.value);
					    stringBuffer[stringBuffer.length] = tmp.join("=");
					}
				}
			}
			else if (tagName == "textarea")
			{
				var tmp = [];
				tmp[tmp.length] = element.name;
				tmp[tmp.length] = AjaxNS.EncodePostData(element.value);
				stringBuffer[stringBuffer.length] = tmp.join("=");
			}
			
		}

		return stringBuffer.join("&");
	}
	catch(e)
	{
		AjaxNS.OnError(e, clientID)
	}
};

AjaxNS.EncodePostData = function(value)
{
    if (encodeURIComponent)
    {
        return encodeURIComponent(value);
    }
    else
    {
        return escape(value);
    }
};

AjaxNS.UrlDecode = function(encodedUrl)
{
    var div = document.createElement('div');
    div.innerHTML = AjaxNS.StripTags(encodedUrl);
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
};

AjaxNS.StripTags = function(html)
{
    return html.replace(/<\/?[^>]+>/gi, '');
};

AjaxNS.GetElementByName = function (element, name)
{
    var res = null;
    var nodes = element.getElementsByTagName("*");
    var len = nodes.length;
	for (var i = 0; i < len; i++)
	{
		var node = nodes[i];

		if(!node.name)
			continue;

		if(node.name + "" == name + "")
		{
			res = node;
			break;
		}
	}

	return res;
};

AjaxNS.GetElementByID = function (element, id, tagName)
{   
    var tagToScan = tagName || "*";
    
    var res = null;
    var nodes = element.getElementsByTagName(tagToScan);
    var len = nodes.length;
    var node = null;
    
	for (var i = 0; i < len; i++)
	{
		node = nodes[i];
		if(!node.id)
			continue;

		if(node.id + "" == id + "")
		{
			res = node;
			break;
		}
	}
	
    node = null;
	nodes = null;

	return res;
};

AjaxNS.FixCheckboxRadio = function (control)
{
    if(!control || !control.type)
        return;
        
    var isInputControl = (control.tagName.toLowerCase() == "input");
    var checkBoxOrRadio = (control.type.toLowerCase() == "checkbox" || control.type.toLowerCase() == "radio");

    if( isInputControl && checkBoxOrRadio )
    {
        var label = control.nextSibling;
        
        var hasOuterSpan = (control.parentNode.tagName.toLowerCase() == "span" && (control.parentNode.getElementsByTagName("*").length == 2 || control.parentNode.getElementsByTagName("*").length == 1));
        var hasLabel = (label != null && label.tagName && label.tagName.toLowerCase() == "label" && label.htmlFor == control.id);
                
        if (hasOuterSpan)
        {
            return control.parentNode;
        }
        else if (hasLabel)
        {
            var newParent = document.createElement("span");
            control.parentNode.insertBefore(newParent, control);
            newParent.appendChild(control);
            newParent.appendChild(label);
            return newParent;
        }
        else
        {
            return control;
        }
    }
}

AjaxNS.GetNodeNextSibling = function (node)
{
	if (node != null && node.nextSibling != null)
	{
		return node.nextSibling;
	}
	return null;
};

AjaxNS.PrepareFormForAsyncRequest = function (eventTarget, eventArgument, clientID)
{
	var instance = window[clientID];
    var form = document.getElementById(instance.FormID || "");
	if (AjaxNS.IsSafari() || form == null)
	{
		form = document.forms[0];
	}

	if(form["__EVENTTARGET"])
	{
		form["__EVENTTARGET"].value = eventTarget.split("$").join(":");
	}
	else
	{
		var input = document.createElement("input");
		input.id = "__EVENTTARGET";
		input.name = "__EVENTTARGET";
		input.type = "hidden";
		input.value = eventTarget.split("$").join(":");

		form.appendChild(input);
	}

	if(form["__EVENTARGUMENT"])
	{
		form["__EVENTARGUMENT"].value = eventArgument;
	}
	else
	{
		var input = document.createElement("input");
		input.id = "__EVENTARGUMENT";
		input.name = "__EVENTARGUMENT";
		input.type = "hidden";
		input.value = eventArgument;

		form.appendChild(input);
	}
	form = null;
};

AjaxNS.GetUrlForAsyncRequest = function (clientID)
{
	var url = "&" + "RadAJAXControlID" + "=" + clientID + "&" + "httprequest=true";

	if (window.opera)
	{
		url += "&" + "&browser=Opera"
	}

	return url;
};

//RadGrid's loading templates -- different than the LoadingPanel
AjaxNS.ShowLoadingTemplate = function (clientID)
{
	var panel = window[clientID];

	if(panel == null)
		return;
	
	var elementToUpdate;
	
	if(panel.Control)
	{
		elementToUpdate = panel.Control;
	}

	if(panel.MasterTableView && panel.MasterTableView.Control && panel.MasterTableView.Control.tBodies[0])
	{
		elementToUpdate = panel.MasterTableView.Control.tBodies[0];
	}

	if(panel.GridDataDiv)
	{
		elementToUpdate = panel.GridDataDiv;
	}

	if(elementToUpdate == null)
		return;

	elementToUpdate.style.cursor = "wait";

	if(panel.LoadingTemplate != null)
	{		
		AjaxNS.InsertAtLocation(panel.LoadingTemplate, document.body, null);

		var rect = AjaxNS.RadGetElementRect(elementToUpdate);
		panel.LoadingTemplate.style.position = "absolute";
		panel.LoadingTemplate.style.width = rect.width + "px";
		panel.LoadingTemplate.style.height = rect.height+ "px";
		panel.LoadingTemplate.style.left = rect.left+ "px";
		panel.LoadingTemplate.style.top = rect.top+ "px";
		panel.LoadingTemplate.style.textAlign = "center";
		panel.LoadingTemplate.style.verticleAlign = "middle";
		panel.LoadingTemplate.style.zIndex = 90000;
		panel.LoadingTemplate.style.overflow = "hidden";

		if(parseInt(panel.LoadingTemplateTransparency) > 0)			
		{
			var transparency = 100 - parseInt(panel.LoadingTemplateTransparency);
			if (window.netscape && !window.opera)
			{
				panel.LoadingTemplate.style.MozOpacity = transparency/100;
			}
			else if(window.opera)
			{
				panel.LoadingTemplate.style.opacity = transparency/100;
			}
			else
			{
				panel.LoadingTemplate.style.filter = "alpha(opacity=" + transparency + ");";
				
				var images = panel.LoadingTemplate.getElementsByTagName("img");
				for(var i = 0; i < images.length; i++)
				{
					images[i].style.filter = "";
				}
			}
		}
		else
		{
		    if (navigator.userAgent.toLowerCase().indexOf("msie 6.0") != -1 && !window.opera)
		    {
				var selects = elementToUpdate.getElementsByTagName("select");
				for(var i = 0; i < selects.length; i++)
				{
					selects[i].style.visibility = "hidden";
				}
		     }

			elementToUpdate.style.visibility = "hidden";
		}
		
		panel.LoadingTemplate.style.display = "";
	}
};

//RadGrid's loading templates -- different than the LoadingPanel
AjaxNS.HideLoadingTemplate = function (clientID)
{
	var instance = window[clientID];
	if(instance == null)
		return;
	
	var loadingTemplate = instance.LoadingTemplate;
    if(loadingTemplate != null)
    {
        if(loadingTemplate.parentNode != null)
        {
	        RadAjaxNamespace.DestroyElement(loadingTemplate);
	    }
	    instance.LoadingTemplate = null;
    }
}

AjaxNS.InitializeControlsToUpdate = function (ajaxControlClientID, xmlHttpRequestObject)
{
	var instance = window[ajaxControlClientID];
    var text = xmlHttpRequestObject.responseText;
	
	try
	{
        eval(text.substring(text.indexOf("/*_telerik_ajaxScript_*/"), text.lastIndexOf("/*_telerik_ajaxScript_*/")));
	}
	catch(e)
	{
	    this.OnError(e);
	}
    
    if(typeof(instance.ControlsToUpdate) == "undefined")
    {
        instance.ControlsToUpdate = [ajaxControlClientID];
    }
};

AjaxNS.FindOldControl = function(controlToUpdateID)
{
	var oldControl = document.getElementById(controlToUpdateID + "_wrapper");
    if (oldControl == null)
    {
		if (AjaxNS.IsSafari())
		{
			oldControl = AjaxNS.GetElementByID(AjaxNS.GetForm(controlToUpdateID), controlToUpdateID);
		}
		else
		{			
			oldControl = document.getElementById(controlToUpdateID);
		}
    }
    
    var checkBoxRadioControl = AjaxNS.FixCheckboxRadio(oldControl);
    
    if(typeof(checkBoxRadioControl) != "undefined")
    {
        oldControl = checkBoxRadioControl;
    }
    
    return oldControl;
}

AjaxNS.FindNewControl = function(controlToUpdateID, container, tagName)
{
    tagName = tagName || "*";
    
    var newElements = container.getElementsByTagName("div");
    for(var i = 0, len = newElements.length ; i < len ; i++)
    {
        if(newElements[i].innerHTML.indexOf("RADAJAX_HIDDENCONTROL") >= 0)
        tagName = "*";
    }
    
	var newControl = AjaxNS.GetElementByID(container, controlToUpdateID + "_wrapper", tagName);
    if (newControl == null)
    {
	    newControl = AjaxNS.GetElementByID(container, controlToUpdateID, tagName);
    }
    
    var checkBoxRadioControl = AjaxNS.FixCheckboxRadio(newControl);
    
    if(typeof(checkBoxRadioControl) != "undefined")
    {
        newControl = checkBoxRadioControl;
    }
    
    return newControl;
}

AjaxNS.InsertAtLocation = function(element, parent, nextSibling)
{	
	if (nextSibling != null)
    {		
	    return parent.insertBefore(element, nextSibling);
    }
    else
    {		
	    return parent.appendChild(element);
    }
}

AjaxNS.GetOldControlsUpdateSettings = function(controlsToUpdate)
{
	var oldControls = {};

	for(var i = 0, len = controlsToUpdate.length; i < len; i++)
	{
		var controlToUpdateID = controlsToUpdate[i];
		var oldControl = AjaxNS.FindOldControl(controlToUpdateID);
		var nextSibling = AjaxNS.GetNodeNextSibling(oldControl);
		
		if(oldControl == null)
		{
		    var error = new Error("Cannot update control with ID: " + controlToUpdateID + ". The control does not exist.");
		    throw(error);
		    continue;
		}
		
		var parent = oldControl.parentNode;
		

		oldControls[controlToUpdateID] = 
			{
				oldControl : oldControl, 
				parent : parent
			};
			
		//Don't allow multiple elements with the same ID in Safari!
		//No matter that we clean those up and leave only one
		//Safari will return null in document.getElementById()
		//We remove the old elements from the document, 
		//so that the new IDs won't screw things up
		if (AjaxNS.IsSafari())
		{

			oldControls[controlToUpdateID].nextSibling = nextSibling;
			oldControl.parentNode.removeChild(oldControl);
		}
	}
	return oldControls;
}

AjaxNS.ReplaceElement = function(oldControlSetting, newControl)
{
	var oldControl = oldControlSetting.oldControl;
	var parent = oldControlSetting.parent;
	var nextSibling = oldControlSetting.nextSibling || AjaxNS.GetNodeNextSibling(oldControl);
	
	if (parent == null)
		return;

   if(typeof(Sys) != "undefined" && 
        typeof(Sys.WebForms) != "undefined" && 
        typeof(Sys.WebForms.PageRequestManager) != "undefined")
   {
        AjaxNS.destroyTree(oldControl);
   }
		
	//Mozilla needs to remove the old element after adding the new one
    //in order to avoid the flicker
    //Opera needs to remove first or getElementById will return the old element
    if (window.opera)
		RadAjaxNamespace.DestroyElement(oldControl);

    //newControl.style.visibility = "hidden";
    
	AjaxNS.InsertAtLocation(newControl, parent, nextSibling);

	if (!window.opera)
		RadAjaxNamespace.DestroyElement(oldControl);
}

AjaxNS.disposedIDs = [];
AjaxNS.destroyTree = function (element) 
{
    if (element.nodeType === 1)
    {
        var childNodes = element.childNodes;
        for (var i = childNodes.length - 1; i >= 0; i--) 
        {
            var node = childNodes[i];
            if (node.nodeType === 1)
            {
                if (node.dispose && typeof(node.dispose) === "function")
                {
                    node.dispose();
                }
                else if (node.control && typeof(node.control.dispose) === "function")
                {
                    AjaxNS.disposedIDs[AjaxNS.disposedIDs.length] = node.id;
                    node.control.dispose();
                }
                var behaviors = Sys.UI.Behavior.getBehaviors(node);
                for (var j = behaviors.length - 1; j >= 0; j--)
                {
                    AjaxNS.disposedIDs[AjaxNS.disposedIDs.length] = node.id;
                    behaviors[j].dispose();
                }
                AjaxNS.destroyTree(node);
            }
        }
    }
}

AjaxNS.FireOnResponseReceived = function(instance, eventTarget, eventArgument, responseText)
{
	var evt = AjaxNS.CreateClientEvent(eventTarget, eventArgument);
	evt.ResponseText = responseText

	if(!AjaxNS.FireEvent(instance, "OnResponseReceived", [evt]))
		return;

	var result = window.OnCallbackResponseReceived(instance, evt);

    if(typeof(result) == "boolean" && result == false)
        return;

	evt = null;
}

AjaxNS.FireOnResponseEnd = function(instance, eventTarget, eventArgument)
{
    var evt = AjaxNS.CreateClientEvent(eventTarget, eventArgument);
    AjaxNS.FireEvent(instance, "OnResponseEnd", [evt])
    window.OnCallbackResponseEnd(instance, evt);
    RadCallbackNamespace.raiseEvent("onresponseend");
    
    evt = null;
}

AjaxNS.CreateHtmlContainer = function()
{
	var container = document.createElement("div");
	container.id = "RadAjaxHtmlContainer";
	container.style.display = "none";
	document.body.appendChild(container);
	return container;
};

AjaxNS.CreateHtmlContainer = function(name)
{
	// Attempt to return the container...
	var container = document.getElementById("htmlUpdateContainer_" + name);
	if (container != null)
		return container;
	
	// Check for the parent container (parent exists for all updates)
	var containerParent = document.getElementById("htmlUpdateContainer");
	if (containerParent == null)
	{
		containerParent = document.createElement("div");
		containerParent.id = "htmlUpdateContainer";
		containerParent.style.display = "none";
		
		if(AjaxNS.IsSafari())
	    {
	        //INPUTS leak on safari if moved between form elements...
	        containerParent = document.forms[0].appendChild(containerParent);
	    }
	    else
	    {
		    containerParent = document.body.appendChild(containerParent);
		}
	}
	
	container = document.createElement("div");
	container.id = "htmlUpdateContainer_" + name;
	container.style.display = "none";
	container = containerParent.appendChild(container);
	containerParent = null;
	return container;
};

AjaxNS.UpdateHeader = function(ajaxControlClientID, headHTML)
{
    var oldHeader = AjaxNS.GetHeadElement();

    if (oldHeader != null && headHTML != "")
    {
        var styleSheets = AjaxNS.GetTags(headHTML, "style");
        AjaxNS.ApplyStyles(styleSheets);
        
        AjaxNS.ApplyStyleFiles(headHTML);
        
        AjaxNS.UpdateTitle(headHTML);
   }
};

AjaxNS.GetHeadHtml = function(htmlString)
{
    var headMatcher = /\<head[^\>]*\>((.|\n|\r)*?)\<\/head\>/i;
    var headerMatch = htmlString.match(headMatcher);

    if (headerMatch != null && headerMatch.length > 2)
    {
       var headHTML = headerMatch[1];
       return headHTML;
    }
	else
	{
		return "";
	}
}

AjaxNS.UpdateTitle = function(headHTML)
{
	var title = AjaxNS.GetTag(headHTML, "title");
    if (title.index != -1)
    {
        var titleValue = title.inner.replace(/^\s*(.*?)\s*$/mgi, "$1");
        if (titleValue != document.title)
			document.title = titleValue;
    }
}

AjaxNS.GetHeadElement = function()
{
	var heads = document.getElementsByTagName("head");
    if (heads.length > 0)
		return heads[0];

	//DESHEV: I think all browsers have a head, even if the server does not render one
	//Just in case...
	var head = document.createElement("head");
	document.documentElement.appendChild(head);
	return head;
}

AjaxNS.ApplyStyleFiles = function(htmlString)
{
    var hrefs = AjaxNS.GetLinkHrefs(htmlString);
    
    var existingLinkHrefs = "";
    
	var head = AjaxNS.GetHeadElement();
	var linkElements = head.getElementsByTagName("link");

	for (var i = 0; i < linkElements.length; i++)
	{
        existingLinkHrefs += "\n" + linkElements[i].getAttribute("href");
	}
    
    for (var i = 0; i < hrefs.length; i++)
    {
		var href = hrefs[i];
		
		if(href.media && href.media.toString().toLowerCase() == "print")
			continue;

		if (existingLinkHrefs.indexOf(href) >= 0)
			continue;
		
		//ASP.NET sometimes renders webresource urls as &amp;amp; -- double encoding!
		href = href.replace(/&amp;amp;t/g, "&amp;t");
		if (existingLinkHrefs.indexOf(href) >= 0)
			continue;
		
        var link = document.createElement("link");
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("href", hrefs[i]);
        head.appendChild(link);
    }
}

AjaxNS.ApplyStyles = function(styleSheets)
{
	if (AjaxNS.AppliedStyleSheets == null)
		AjaxNS.AppliedStyleSheets = {};
		
    if (document.createStyleSheet != null)
    {
        //IE
        for (var i = 0; i < styleSheets.length; i++)
        {
			var cssCode = styleSheets[i].inner;
			var hashCode = AjaxNS.GetStringHashCode(cssCode);
			if (AjaxNS.AppliedStyleSheets[hashCode] != null)
				continue;
			
			AjaxNS.AppliedStyleSheets[hashCode] = true;
				
            var newStyle = null;
            try
            {
                newStyle = document.createStyleSheet();
            }
            catch(e)
            {}
            
            if(newStyle == null)
            {
                newStyle = document.createElement('style');
            }
			
			newStyle.cssText = cssCode;
        }
    }
    else
    {
        //SAFARI, Moz, Opera
        var targetStylesheet = null;
        if (document.styleSheets.length == 0)
        {
	        css = document.createElement('style');
	        css.media = 'all';
	        css.type  = 'text/css';
	        
	        var oldHeader = AjaxNS.GetHeadElement();
	        oldHeader.appendChild(css);
	        targetStylesheet = css;
        }

        if (document.styleSheets[0])
        {   
             targetStylesheet = document.styleSheets[0];
        }
        
        for (var j = 0; j < styleSheets.length; j++)
        {
			var cssCode = styleSheets[j].inner;
			var hashCode = AjaxNS.GetStringHashCode(cssCode);
			if (AjaxNS.AppliedStyleSheets[hashCode] != null)
				continue;
			
			AjaxNS.AppliedStyleSheets[hashCode] = true;
            
            var rules = cssCode.split("}");

            for (var i = 0; i < rules.length; i++)
            {
                if (rules[i].replace(/\s*/, "") == "")
                    continue;
                
                targetStylesheet.insertRule(rules[i] + "}", i + 1);
            }
        }
    }
}

AjaxNS.GetStringHashCode = function(value)
{     
    var h = 0;
    if (value) 
    {
        for (var j = value.length - 1; j >= 0; j--) 
        {
            h ^= AjaxNS.ANTABLE.indexOf(value.charAt(j)) + 1;
            for (var i = 0; i < 3; i++) 
            {
                var m = (h = h << 7 | h >>> 25) & 150994944;
                h ^= m ? (m == 150994944 ? 1 : 0) : 1;
            }
        }
    }
    return h;	
}

AjaxNS.ANTABLE  = "w5Q2KkFts3deLIPg8Nynu_JAUBZ9YxmH1XW47oDpa6lcjMRfi0CrhbGSOTvqzEV";

AjaxNS.GetLinkHrefs = function(htmlString)
{
    var html = htmlString;
    var hrefs = [];
    while(1)
    {
        var match = html.match(/<link[^>]*href=('|")?([^'"]*)('|")?([^>]*)>.*?(<\/link>)?/i);
        if (match == null || match.length < 3)
            break;
            
        var value = match[2];
        hrefs[hrefs.length] = value;
        var lastIndex = match.index + value.length;
        html = html.substring(lastIndex, html.length);
    }
    return hrefs;
}

AjaxNS.GetTags = function(htmlString, tagName)
{
    var result = [];
    var html = htmlString;
    while(1)
    {
        var tagContent = AjaxNS.GetTag(html, tagName);
        if (tagContent.index == -1)
            break;
            
        result[result.length] = tagContent;
        var lastIndex = tagContent.index + tagContent.outer.length;
        html = html.substring(lastIndex, html.length);
    }
    return result;
}

AjaxNS.GetTag = function(htmlString, tagName, defaultValue)
{
    if (typeof(defaultValue) == "undefined")
        defaultValue = "";
        
    var tagMatcher = new RegExp("<" + tagName + "[^>]*>((.|\n|\r)*?)</" + tagName + ">", "i");
    var tagMatch = htmlString.match(tagMatcher);
    
    if (tagMatch != null && tagMatch.length >= 2)
    {
        return { outer: tagMatch[0], inner: tagMatch[1], index: tagMatch.index };
    }
    else
    {
        return { outer: defaultValue, inner: defaultValue, index: -1 };
    }
}

AjaxNS.EmptyFunction = function(){};
AjaxNS.HandleAsyncRequestResponse = function (ajaxControlClientID, unusedParam, eventTarget, eventArgument, xmlHttpRequestObject)
{
	try
	{
	    RadAjaxNamespace.IsAsyncResponse = true;
		var instance = window[ajaxControlClientID];				
		
		if (instance == null)
			return;
	    	
		if (xmlHttpRequestObject == null || 
			xmlHttpRequestObject.readyState != 4)
			return;
					
	    AjaxNS.IsInRequest = false;

		AjaxNS.Check404Status(xmlHttpRequestObject);
		if(!AjaxNS.HandleAsyncRedirect(ajaxControlClientID, xmlHttpRequestObject))
			return;
					
		if (xmlHttpRequestObject.responseText == "")
			return;

		if(!AjaxNS.CheckContentType(ajaxControlClientID, xmlHttpRequestObject))
			return;
			
        AjaxNS.HideLoadingTemplate(ajaxControlClientID);        

		AjaxNS.InitializeControlsToUpdate(ajaxControlClientID, xmlHttpRequestObject);		

		AjaxNS.FireOnResponseReceived(instance, eventTarget, eventArgument, xmlHttpRequestObject.responseText)
		
		AjaxNS.UpdateControlsHtml(instance, xmlHttpRequestObject, ajaxControlClientID);
		
		AjaxNS.HandleResponseScripts(xmlHttpRequestObject);
		
	    if (xmlHttpRequestObject != null)
		    xmlHttpRequestObject.onreadystatechange = AjaxNS.EmptyFunction;
		
		AjaxNS.FireOnResponseEnd(instance, eventTarget, eventArgument);
		
		if (AjaxNS.IsSafari())
		{
			//force layout recalculation, so that the styles get applied	
			window.setTimeout(function()
				{
					var h = document.body.offsetHeight;
					var w = document.body.offsetWidth;
				}, 0);
		}

		if(AjaxNS.RequestQueue.length > 0)
	    {
	        asyncRequestArgs = AjaxNS.RequestQueue.shift();
	        window.setTimeout(function() {AjaxNS.AsyncRequest.apply(AjaxNS, asyncRequestArgs);}, 0);
	    }
	    
	    instance.Dispose();
	}
	catch(e)
	{
		AjaxNS.OnError(e, ajaxControlClientID);
	}
};

AjaxNS.UpdateControlsHtml = function(instance, xmlHttpRequestObject, ajaxControlClientID)
{
	var controlsToUpdate = instance.ControlsToUpdate;
	if (controlsToUpdate.length == 0)
		return;
		
	var oldControls = AjaxNS.GetOldControlsUpdateSettings(controlsToUpdate);		

	RadAjaxNamespace.LoadingPanel.HideLoadingPanels(instance);		

	var response = xmlHttpRequestObject.responseText;
	//DESHEV: TODO -- take this out to a separate method!
	var headHTML = AjaxNS.GetHeadHtml(response);
	try
	{
		if (instance.EnablePageHeadUpdate != false)
			AjaxNS.UpdateHeader(ajaxControlClientID, headHTML);
	}
	catch(e)
	{}
    
	//DESHEV: remove the head html contents -- IE will insist on adding <link>
	//elements if its cache settings are set to always download content
	//that will cause a browser crash on subsequent requests
	response = response.replace(headHTML, "");
	var container = AjaxNS.CreateHtmlContainer(instance.ControlID);
	
	response = AjaxNS.RemoveServerForm(response);

	container.innerHTML = response;

	var userAgent = navigator.userAgent;
	if (userAgent.indexOf("Netscape") < 0)
	{
		container.parentNode.removeChild(container);  
	}

	var shouldExecuteValidators = true;
	for(var i = 0, len = controlsToUpdate.length; i < len; i++)
	{
		var controlToUpdateID = controlsToUpdate[i];
		var oldControlSetting = oldControls[controlToUpdateID];

		if(typeof(oldControlSetting) == "undefined")
		{
			shouldExecuteValidators = false;
			continue;
		}

		var tagName = AjaxNS.GetReplacedControlTagNameSearchHint(oldControlSetting.oldControl);
		
		var newControl = AjaxNS.FindNewControl(controlToUpdateID, container, tagName);
            
		if(newControl == null)
			continue;
		    
		newControl.parentNode.removeChild(newControl);

		AjaxNS.ReplaceElement(oldControlSetting, newControl);
		AjaxNS.ExecuteScripts(newControl, ajaxControlClientID);
	}
	
	if (userAgent.indexOf("Netscape") > -1)
	{
		container.parentNode.removeChild(container);
	}
	
	AjaxNS.UpdateHiddenInputs(container.getElementsByTagName("input"), ajaxControlClientID);
           
	if(instance.OnRequestEndInternal)
	{
		instance.OnRequestEndInternal();
	}

    AjaxNS.ResetValidators();
	if(instance.EnableOutsideScripts)
	{                       
	   AjaxNS.ExecuteScripts(container, ajaxControlClientID);
	}
	else
	{
	    if(AjaxNS.disposedIDs.length > 0)
	    {
	        AjaxNS.ExecuteScriptsForDisposedIDs(container, ajaxControlClientID);
	    }
	    
		if(shouldExecuteValidators)
		{
			AjaxNS.ExecuteValidatorsScripts(container, ajaxControlClientID);
		}
	}

	RadAjaxNamespace.DestroyElement(container);	
	
};

//change the server-rendered form tag to a div -- fixes many problems on Safari and Mozilla
AjaxNS.RemoveServerForm = function(response)
{
	response = response.replace(/<form([^>]*)id=('|")([^'"]*)('|")([^>]*)>/mgi, "<div$1 id='$3" + "_tmpForm" + "'$5>");
	response = response.replace(/<\/form>/mgi, "</div>");
	return response;
}

AjaxNS.GetReplacedControlTagNameSearchHint = function(oldControl)
{
    var tagName = oldControl.tagName;
    
    if (tagName != null)
    {
	    //radio buttons and checkbox render as two tags.  handled elsewhere
	    if (tagName.toLowerCase() == "span" || tagName.toLowerCase() == "input")
	    {
		    tagName = "*";
		}
	    
	    //previously hidden controls that have invisible div placeholders
	    if (oldControl.innerHTML.indexOf("RADAJAX_HIDDENCONTROL") >= 0)
	    {
	        tagName = "*";
	    }
    }
    return tagName;
}

AjaxNS.HandleResponseScripts = function(xmlHttpRequestObject)
{
	var responseText = xmlHttpRequestObject.responseText;
	var m = responseText.match(/_RadAjaxResponseScript_((.|\n|\r)*?)_RadAjaxResponseScript_/);

	if (m && m.length > 1)
	{
		var scriptCode = m[1];
	    //window.eval(scriptCode);
	    AjaxNS.EvalScriptCode(scriptCode);
		
		//does not work for declaring new functions e.g. window.setTimeout("function Test(){...};", 0);
		//window.setTimeout(scriptCode, 0);
	}
};

//we try destroying by setting innerHTML and outerHTML to ""
//to avoid pseudo-leaks in IE
//All of those can throw exceptions under various conditions:
// - setting innerHTML = "" to a table throws
// - setting outerHTML = "" to some elements might throw (unconfirmed)
// - we need removeChild to execute if the first two fail, and it will 
//throw if element.outerHTML = "" has succeeded before that
RadAjaxNamespace.DestroyElement = function(element)
{	
	RadAjaxNamespace.DisposeElement(element);

	if (AjaxNS.IsGecko())
	{ 
		var parent = element.parentNode;
		if (parent != null)
			parent.removeChild(element);
	}
	
	try
	{	
		var garbageBin = document.getElementById('IELeakGarbageBin');
		if (!garbageBin) {
			garbageBin = document.createElement('DIV');
			garbageBin.id = 'IELeakGarbageBin';
			garbageBin.style.display = 'none';
			document.body.appendChild(garbageBin);
		}

		// move the element to the garbage bin
		garbageBin.appendChild(element);
		garbageBin.innerHTML = '';
    }
    catch(error)
    {
    }
}

//Can be overriden by customers wishing to do something special when destroying a DOM node
RadAjaxNamespace.DisposeElement = function(targetElement) 
{
//    var attributes = targetElement.attributes; 
//    if (attributes != null) 
//    {
//        var length = attributes.length;
//        for (var i = 0; i < length; i++) 
//        {
//            var n = attributes[i].name;
//            if (typeof targetElement[n] === 'function')
//            {
//                targetElement[n] = null;
//            }
//        }
//    }
};
    
RadAjaxNamespace.OnError = function (e, clientID)
{
	throw(e);
	//return false;
};

AjaxNS.HandleAsyncRedirect = function (clientID, xmlHttpRequestObject)
{
	try
	{
		var instance = window[clientID];
		var redirectURL = AjaxNS.GetResponseHeader(xmlHttpRequestObject, "Location");

		if (redirectURL && redirectURL != "")
		{
		    var tmp = document.createElement("a");
		    tmp.style.display = "none";
		    tmp.href = redirectURL;
		    document.body.appendChild(tmp);
		    if(tmp.click)
		    {
		        tmp.click();
		    }
		    else
		    {
		        window.location.href = redirectURL;
		    }
		    document.body.removeChild(tmp);
			//window.location.href = redirectURL;
			return false;					
		}
		else
		{
			return true;
		}
	}
	catch(e)
	{
		AjaxNS.OnError(e);
	}

	return true;
};

AjaxNS.GetResponseHeader = function(xmlHttpRequest, headerName)
{
	try
	{
		return xmlHttpRequest.getResponseHeader(headerName);
	}
	catch(e)
	{
		return null;
	}
}

AjaxNS.GetAllResponseHeaders = function(xmlHttpRequest)
{
	try
	{
		return xmlHttpRequest.getAllResponseHeaders();
	}
	catch(e)
	{
		return null;
	}
}

AjaxNS.CheckContentType = function (clientID, xmlHttpRequestObject)
{
	try
	{
		var instance = window[clientID];
        
		var contentType = AjaxNS.GetResponseHeader(xmlHttpRequestObject, "content-type");
		if (contentType == null && xmlHttpRequestObject.status == null)
		{
			var error = new Error("Unknown server error");
			throw(error);
			return false;
		}

		var contentTypeToCheck;
		if (!window.opera)
		{
			contentTypeToCheck = "text/javascript";
		}
		else
		{
			contentTypeToCheck = "text/xml";
		}
		
		if (contentType.indexOf(contentTypeToCheck) == -1 && xmlHttpRequestObject.status == 200)
		{
		    var e = new Error("Unexpected ajax response was received from the server.\n" +
				"This may be caused by one of the following reasons:\n\n " +
				"- Server.Transfer.\n " + 
				"- Custom http handler.\n" +
				"- Incorrect loading of an \"Ajaxified\" user control.\n\n" + 
				"Verify that you don't get a server-side exception or any other undesired behavior, by setting the EnableAJAX property to false.");
			throw(e);
			return false;
		}
		else
		{
			if (xmlHttpRequestObject.status != 200)
			{
			    var evt = 
			    {
			        Status : xmlHttpRequestObject.status,
			        ResponseText : xmlHttpRequestObject.responseText,
			        ResponseHeaders : AjaxNS.GetAllResponseHeaders(xmlHttpRequestObject)
			    }

			    if(!AjaxNS.FireEvent(instance, "OnRequestError", [evt]))
        			return false;

				document.write(xmlHttpRequestObject.responseText);
				return false;
			}
		}

		return true;
	}
	catch(e)
	{
		AjaxNS.OnError(e);
	}
};

AjaxNS.IsSafari = function()
{
	return (navigator.userAgent.match(/safari/i) != null);
};

AjaxNS.IsNetscape = function()
{
    return (navigator.userAgent.match(/netscape/i) != null);
};

AjaxNS.IsGecko = function()
{
	return (window.netscape && !window.opera);
}

AjaxNS.IsOpera = function()
{
	return window.opera != null;
}

AjaxNS.UpdateHiddenInputs = function (inputs, clientID)
{
	try
	{	    	    
		var instance = window[clientID];
		var form = AjaxNS.GetForm(clientID);

		if (AjaxNS.IsSafari())
		{
			//form = document.forms[0];
		}

		for (var i = 0, len = inputs.length; i < len; i++)
		{
		    var res = inputs[i];
		    var type = res.type.toString().toLowerCase();

			if(type != "hidden")
				continue;

			var input;
			
			if(res.id != "")
			{
				input = AjaxNS.GetElementByID(form, res.id);
				if(!input)
				{
					input = document.createElement("input");
					input.id = res.id;
					input.name = res.name;
					input.type = "hidden";
					form.appendChild(input);
				}

			}
			else if(res.name != "")
			{			    
				input = AjaxNS.GetElementByName(form, res.name);
				if(!input)
				{
					input = document.createElement("input");
					input.name = res.name;					
					input.type = "hidden";
					form.appendChild(input);
				}
			}
			else
			{
				continue;
			}

			if(input)
			{
				input.value = res.value;
			}
		}
	}
	catch(e)
	{
		AjaxNS.OnError(e);
	}
};

AjaxNS.ARWO = function(options, clientID, e)
{
    var instance = window[clientID];
	if(instance != null && typeof(instance.AsyncRequestWithOptions) == "function")
	{
	    instance.AsyncRequestWithOptions(options, e);
	}
}

AjaxNS.AR = function(eventTarget, eventArgument, clientID, e)
{
	var instance = window[clientID];
	if(instance != null && typeof(instance.AsyncRequest) == "function")
	{
	    instance.AsyncRequest(eventTarget, eventArgument, e);
	}
};

//"inspired" by WebForm_DoPostBackWithOptions
AjaxNS.AsyncRequestWithOptions = function(options, clientID, e)
{    
    var validationResult = true;   
    var isCrossPagePostBack = (options.actionUrl != null) && (options.actionUrl.length > 0); 
    
    if (options.validation) 
    {        
        if (typeof(Page_ClientValidate) == "function") 
        {               
            validationResult = Page_ClientValidate(options.validationGroup);                                    
        }
    }    
    if (validationResult) 
    {        
        if ((typeof(options.actionUrl) != "undefined") && isCrossPagePostBack) 
        {            
            theForm.action = options.actionUrl;
        }        
        if (options.trackFocus) 
        {            
            var lastFocus = theForm.elements["__LASTFOCUS"];
            if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) 
            {
                if (typeof(document.activeElement) == "undefined") 
                {
                    lastFocus.value = options.eventTarget;
                }
                else 
                {
                    var active = document.activeElement;
                    if ((typeof(active) != "undefined") && (active != null)) 
                    {
                        if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) 
                        {
                            lastFocus.value = active.id;
                        }
                        else if (typeof(active.name) != "undefined") 
                        {
                            lastFocus.value = active.name;
                        }
                    }
                }
            }
        }
    }
    
    if (isCrossPagePostBack)
    {
        __doPostBack(options.eventTarget, options.eventArgument);
        return;
    }
    
    if (validationResult)
    {
        AjaxNS.AsyncRequest(options.eventTarget, options.eventArgument, clientID, e);
    }
};

AjaxNS.ClientValidate = function(element, e, clientID)
{
	var shouldCallback = true;;

	if(typeof(Page_ClientValidate) == "function")
	{
		shouldCallback = Page_ClientValidate();
	}
	
	if (shouldCallback)
	{
		var instance = window[clientID];
		if(instance != null && typeof(instance.AsyncRequest) == "function")
		{
			instance.AsyncRequest(element.name, "", e);
		}
	}
};

AjaxNS.FireEvent = function (sender, eventHandler, eventArguments)
{	
	try
	{
		var returnValue = true;
		if (typeof(sender[eventHandler]) == "string")
		{
			returnValue = eval(sender[eventHandler]);
		}
		else if (typeof(sender[eventHandler]) == "function")
		{
			if (eventArguments)
			{
			    if(typeof(eventArguments.unshift) != "undefined")
			    {
				    eventArguments.unshift(sender);
				    returnValue = sender[eventHandler].apply(sender, eventArguments);
				}
				else
				{
				    returnValue = sender[eventHandler].apply(sender, [eventArguments]);
				}
			}
			else
			{
				returnValue = sender[eventHandler]();
			}
		}
		
		if (typeof(returnValue) != "boolean")
		{
			return true;
		}
		else
		{
			return returnValue;
		}
	}
    catch(error)
    {
	    this.OnError(error);
    }
};

RadAjaxNamespace.AddPanel = function(objectData)
{
	var panel = new RadAjaxNamespace.LoadingPanel(objectData);
	this.LoadingPanels[panel.ClientID] = panel;
};


RadAjaxNamespace.LoadingPanel = function(objectData)
{
	for (var prop in objectData)
	{
		this[prop] = objectData[prop];
	}
};

AjaxNS.IsChildOf = function (node, parentNode)
{
    var nodeElement = document.getElementById(node);
    if(nodeElement)
    {
	    while (nodeElement.parentNode)
	    {
		    if (nodeElement.parentNode.id == parentNode || nodeElement.parentNode.id == parentNode + "_wrapper")
		    {
			    return true;
		    }
		    nodeElement = nodeElement.parentNode;
	    }
	}
	else
	{
	    if(node.indexOf(parentNode) == 0)
	    {
	        return true;
	    }
	}
	return false;
};

AjaxNS.DisposeDisplayedLoadingPanels = function()
{
	AjaxNS.DisplayedLoadingPanels = null;
};

if (AjaxNS.DisplayedLoadingPanels == null)
{
	AjaxNS.DisplayedLoadingPanels = [];	
	AjaxNS.EventManager.Add(window, "unload", AjaxNS.DisposeDisplayedLoadingPanels);
};

RadAjaxNamespace.LoadingPanel.ShowLoadingPanels = function (ajaxControl, clientID)
{	
	if (ajaxControl.GetAjaxSetting == null || ajaxControl.GetParentAjaxSetting == null)
		return;
		
	var ajaxSetting = ajaxControl.GetAjaxSetting(clientID);
	if (ajaxSetting == null)
	{
	    ajaxSetting = ajaxControl.GetParentAjaxSetting(clientID);
	}
	
	if (ajaxSetting)
	{
		for (var j = 0 ; j < ajaxSetting.UpdatedControls.length; j++ )
		{
			var updatedControl = ajaxSetting.UpdatedControls[j];
			var loadingPanel = null;
			if ((typeof(updatedControl.PanelID) != "undefined") && (updatedControl.PanelID != ""))
			{
				loadingPanel = RadAjaxNamespace.LoadingPanels[updatedControl.PanelID];
			}
			else if(typeof(ajaxControl.DefaultLoadingPanelID) != "undefined" && ajaxControl.DefaultLoadingPanelID != "")
			{
			    loadingPanel = RadAjaxNamespace.LoadingPanels[ajaxControl.DefaultLoadingPanelID];
			}

			if(typeof(RadAjaxPanelNamespace) != "undefined" && ajaxControl.IsAjaxPanel)
			{
				if (loadingPanel != null)
					loadingPanel.Show(updatedControl.ControlID);
		    }
		    else
		    {
		        if (loadingPanel != null && updatedControl.ControlID != ajaxControl.ClientID)
					loadingPanel.Show(updatedControl.ControlID);
		    }
		}		
	}
}


RadAjaxNamespace.LoadingPanel.prototype.Show = function(updatedElementID)
{			
	var updatedElement = document.getElementById(updatedElementID + "_wrapper");
	if ((typeof(updatedElement) == "undefined") || (!updatedElement))
	{
		updatedElement = document.getElementById(updatedElementID);
	}
	var loadingPanelHtmlElement = document.getElementById(this.ClientID);
		
	if (!(updatedElement && loadingPanelHtmlElement))
	{
		return;
	}
	
	var initialDelay = this.InitialDelayTime;
	var loadingPanel = this;

	this.CloneLoadingPanel(loadingPanelHtmlElement, updatedElement.id);
	
	if (initialDelay)
	{		
		window.setTimeout( function() { loadingPanel.DisplayLoadingElement(updatedElement.id); }, initialDelay);				
	}
	else
	{
		this.DisplayLoadingElement(updatedElement.id);
	}	
}

RadAjaxNamespace.LoadingPanel.prototype.GetDisplayedElement = function(updatedElementID)
{
	return AjaxNS.DisplayedLoadingPanels[this.ClientID + updatedElementID];
}

RadAjaxNamespace.LoadingPanel.prototype.DisplayLoadingElement = function (updatedElementID)
{		
	loadingElement = this.GetDisplayedElement(updatedElementID);
	if (loadingElement != null)
	{
		if (loadingElement.References > 0)
		{
			var updatedElement = document.getElementById(updatedElementID);
			if (!this.IsSticky)
			{
				var rect = AjaxNS.RadGetElementRect(updatedElement);
				loadingElement.style.position = "absolute";				
				loadingElement.style.width = rect.width + "px";
				loadingElement.style.height = rect.height+ "px";
				loadingElement.style.left = rect.left+ "px";
				loadingElement.style.top = rect.top+ "px";
				loadingElement.style.textAlign = "center";
				loadingElement.style.zIndex = 90000;

				var transparency = 100 - parseInt(this.Transparency);
				if(parseInt(this.Transparency) > 0)			
				{
					if (loadingElement.style && loadingElement.style.MozOpacity != null)
					{
						loadingElement.style.MozOpacity = transparency/100;
					}
					else if(loadingElement.style && loadingElement.style.opacity != null)
					{
						loadingElement.style.opacity = transparency/100;
					}
					else if(loadingElement.style && loadingElement.style.filter != null)
					{
						loadingElement.style.filter = "alpha(opacity=" + transparency + ");";
					}
				}
				else
				{
					updatedElement.style.visibility = "hidden";
				}
			}
			
			loadingElement.StartDisplayTime = new Date();				
			loadingElement.style.display = "";
		}
	}	
}

RadAjaxNamespace.LoadingPanel.prototype.FlashCompatibleClone = function(sourceElement)
{
	var clone = sourceElement.cloneNode(false);
	clone.innerHTML = sourceElement.innerHTML;
	return clone;
}

RadAjaxNamespace.LoadingPanel.prototype.CloneLoadingPanel = function(panelElement, updatedElementID)
{
	if (!panelElement)
		return;
			
	var loadingElement = this.GetDisplayedElement(updatedElementID);
	if (loadingElement == null)
	{
		var loadingElement = this.FlashCompatibleClone(panelElement);
		
		if (!this.IsSticky)
		{
			document.body.insertBefore(loadingElement, document.body.firstChild);
		}
		else
		{
			var parent = panelElement.parentNode;
			var nextSibling = AjaxNS.GetNodeNextSibling(panelElement);
			AjaxNS.InsertAtLocation(loadingElement, parent, nextSibling);
		}
		
		loadingElement.References = 0;
		loadingElement.UpdatedElementID = updatedElementID;
		AjaxNS.DisplayedLoadingPanels[panelElement.id + updatedElementID] = loadingElement;	
	}
	
	loadingElement.References++;
	return loadingElement;
}

RadAjaxNamespace.LoadingPanel.prototype.Hide = function(updatedElementID)
{		
	var displayedPanelID = this.ClientID + updatedElementID	
	var displayedPanel = AjaxNS.DisplayedLoadingPanels[displayedPanelID];	
	displayedPanel.References--;					
	//if (displayedPanel.References == 0)
	{		
		var element = document.getElementById(updatedElementID);	   	    
		if (typeof(element) != "undefined" && (element != null))
		{
			element.style.visibility = "visible"; // show the element if the AjaxSettings had been changed and the element is not updated afterwards. Otherwise it will remain hidden.
		}		
		displayedPanel.style.display = "none";		
	} 	
	
	//AjaxNS.DisplayedLoadingPanels[displayedPanelID] = null;
}

RadAjaxNamespace.LoadingPanel.HideLoadingPanels = function (ajaxControl)
{		
    
    if (ajaxControl.AjaxSettings == null)
        return;
        
	var ajaxSetting = ajaxControl.GetAjaxSetting(ajaxControl.PostbackControlIDServer);
	
	if(ajaxSetting == null)
	{
	    ajaxSetting = ajaxControl.GetParentAjaxSetting(ajaxControl.PostbackControlIDServer);
	}
	
	if (ajaxSetting != null)
	{
		for (var j = 0 ; j < ajaxSetting.UpdatedControls.length ; j++)
		{
			var updatedControl = ajaxSetting.UpdatedControls[j];					
			RadAjaxNamespace.LoadingPanel.HideLoadingPanel(updatedControl, ajaxControl);				
		}
	}
	
}

RadAjaxNamespace.LoadingPanel.HideLoadingPanel = function(updatedControl, ajaxControl)
{	
	var loadingPanel = RadAjaxNamespace.LoadingPanels[updatedControl.PanelID];
	
	if (loadingPanel == null)
	{
	    loadingPanel = RadAjaxNamespace.LoadingPanels[ajaxControl.DefaultLoadingPanelID];
	}
		
	if (loadingPanel == null)
		return;
	
	var updatedControlID = updatedControl.ControlID;
	
	var displayedElement = loadingPanel.GetDisplayedElement(updatedControlID + "_wrapper");
	
	
	if ((typeof(displayedElement) == "undefined") || (!displayedElement))
	{
		displayedElement = loadingPanel.GetDisplayedElement(updatedControl.ControlID);
	}
	else 
	{
		updatedControlID = updatedControl.ControlID + "_wrapper";
	}
	
	var now = new Date();
	

	if (displayedElement == null)
		return;
		
	
		
	var timeSpan = now - displayedElement.StartDisplayTime;
	
	if (loadingPanel.MinDisplayTime > timeSpan)
	{
	
		window.setTimeout(
			function()
			{
				loadingPanel.Hide(updatedControlID);
				document.getElementById(updatedControl.ControlID).visibility = "visible";
			}, 
			loadingPanel.MinDisplayTime - timeSpan);
	}
	else
	{
		loadingPanel.Hide(updatedControlID);
		var updatedControlElement = document.getElementById(updatedControl.ControlID)
		if(updatedControlElement != null)
		{
		    updatedControlElement.visibility = "visible";
		}
	}	
}

AjaxNS.RadAjaxControl = function()
{
    // handles the case when we have ajaxified anchor element with options like
    // href="javascript:RadAjaxPanelNamespace.AsyncRequestWithOptions(new WebForm_PostBackOptions(...),'RadAjaxPanel1',event)"
    // there is no global event object in firefox and we declare it in order to avoid the "event is undefined" error. 
    if (typeof(window.event) == "undefined")
    {
        window.event = null;
    }
}

AjaxNS.RadAjaxControl.prototype.GetParentAjaxSetting = function(clientID)
{	
    for(var i = this.AjaxSettings.length ; i > 0 ; i--)    
    {
        if(AjaxNS.IsChildOf(clientID, this.AjaxSettings[i-1].InitControlID))
        {
            return this.GetAjaxSetting(this.AjaxSettings[i-1].InitControlID);
        }
    }
};

AjaxNS.RadAjaxControl.prototype.GetAjaxSetting = function(clientID)
{	
	var ajaxSettingIndex = 0;	
	var ajaxSetting = null;
	for(ajaxSettingIndex = 0; ajaxSettingIndex < this.AjaxSettings.length ; ajaxSettingIndex++)
	{
		var ajaxifiedControl = this.AjaxSettings[ajaxSettingIndex].InitControlID;
		if(clientID == ajaxifiedControl)
		{
		    if(ajaxSetting == null)
		    {
			    ajaxSetting = this.AjaxSettings[ajaxSettingIndex];
			}
			else
			{
			    while(this.AjaxSettings[ajaxSettingIndex].UpdatedControls.length > 0)
			    {
			        ajaxSetting.UpdatedControls.push(this.AjaxSettings[ajaxSettingIndex].UpdatedControls.shift());
			    }
			}
		}
	}
	return ajaxSetting;
}

AjaxNS.Rectangle = function (left, top, width, height) 
{ 
	this.left = (null != left ? left : 0); 
	this.top = (null != top ? top : 0); 
	this.width = (null != width ? width : 0); 
	this.height = (null != height ? height : 0); 
	  
	this.right = left + width; 
	this.bottom = top + height;
};


AjaxNS.RadGetElementRect = function(element) 
{ 
	if (!element) 
	{ 
		element = this;
	} 

	var left = 0; 
	var top = 0; 
	var width = element.offsetWidth; 
	var height = element.offsetHeight; 

	while (element.offsetParent) 
	{ 
		left += element.offsetLeft; 
		top += element.offsetTop; 
		element = element.offsetParent;
	} 
	
	if (element.x) 
	{
		left = element.x;
	}
	if (element.y) 
	{
		top = element.y;
	}
	
	//IE Hack...
	if(typeof(document.body.offsetLeft) != "undefined" && typeof(document.body.offsetTop) != "undefined")
	{
	    top = top + document.body.offsetTop;
	    left = left + document.body.offsetLeft;
	}
	
	return new AjaxNS.Rectangle(left, top, width, height);
};

//RadCallback compatibility.  Kill it when the time comes...

if(!window.RadCallbackNamespace)
{
	window.RadCallbackNamespace = {};
}

if(!window.OnCallbackRequestStart)
{
	window.OnCallbackRequestStart = function(){};
}

if(!window.OnCallbackRequestSent)
{
	window.OnCallbackRequestSent = function(){};
}

if(!window.OnCallbackResponseReceived)
{
	window.OnCallbackResponseReceived = function(){};
}

if(!window.OnCallbackResponseEnd)
{
	window.OnCallbackResponseEnd = function(){};
}

if(!RadCallbackNamespace.raiseEvent)
{
	RadCallbackNamespace.raiseEvent = function (eventName, params)
	{
		var result = true;
		var eventHandlers = RadCallbackNamespace.getRadCallbackEventHandlers(eventName);
		if (eventHandlers != null)
		{

			for (var i = 0; i < eventHandlers.length; i++)
			{
				var res = eventHandlers[i](params);
				if (res == false)
				{
					result = false;
				}
			}
		}
		return result;
	};
}

if(!RadCallbackNamespace.getRadCallbackEventHandlers)
{
	RadCallbackNamespace.getRadCallbackEventHandlers = function (sEventName)
	{
		if (typeof(AjaxNS.callbackEventNames) == "undefined")
		{
			return null;
		}
		for (var i = 0; i < AjaxNS.callbackEventNames.length; i++)
		{
			if (AjaxNS.callbackEventNames[i].eventName == sEventName)
			{
				return AjaxNS.callbackEventNames[i].eventHandlers;
			}
		}
		return null;
	};
}

if(!RadCallbackNamespace.attachEvent)
{
	RadCallbackNamespace.attachEvent = function (sEventName, fpEventHandler)
	{
		if (typeof(AjaxNS.callbackEventNames) == "undefined")
		{
			AjaxNS.callbackEventNames = new Array();
		}
		var eventHandlers = this.getRadCallbackEventHandlers(sEventName);
		if (eventHandlers == null)
		{
			AjaxNS.callbackEventNames[AjaxNS.callbackEventNames.length] = { eventName : sEventName, eventHandlers : new Array() };
			AjaxNS.callbackEventNames[AjaxNS.callbackEventNames.length - 1].eventHandlers[0] = fpEventHandler;
		}
		else
		{
			var functionIndex = this.getEventHandlerIndex(eventHandlers, fpEventHandler);
			if (functionIndex == -1)
			{
				eventHandlers[eventHandlers.length] = fpEventHandler;
			}
		}
	};
}

if(!RadCallbackNamespace.getEventHandlerIndex)
{
	RadCallbackNamespace.getEventHandlerIndex = function(eventHandlers, fpEventHandler)
	{
		for (var i = 0; i < eventHandlers.length; i++)
		{
			if (eventHandlers[i] == fpEventHandler)
			{
				return i;
			}
		}
		return -1;
	};
}

if(!RadCallbackNamespace.detachEvent)
{
	RadCallbackNamespace.detachEvent= function(sEventName, fpEventHandler)
	{
		var eventHandlers = this.getRadCallbackEventHandlers(sEventName);
		if (eventHandlers != null)	{

			var functionIndex = this.getEventHandlerIndex(eventHandlers, fpEventHandler);
			if (functionIndex > -1)
			{
				eventHandlers.splice(functionIndex, 1);
			}
		}
	};
}

window["AjaxNS"] = AjaxNS;

//////////////////////////////////////////////
}
})();

//BEGIN_ATLAS_NOTIFY
if (typeof(Sys) != "undefined")
{
    if (Sys.Application != null && Sys.Application.notifyScriptLoaded != null)
    {
        Sys.Application.notifyScriptLoaded();
    }
}
//END_ATLAS_NOTIFY


