var pwDiagnosticMode = false;
var pwCustomFunctionManager = null;
//var pwLiveControlsScriptVersion = "1.1.2.1";

// **************************************************************************************************
// enum BrowserType - enumerates the types of browsers.
// **************************************************************************************************
var PW_UNSUPPORTED = -1;
var PW_IE = 0;
var PW_MOZILLA = 1;
var PW_IE5 = 2;
var PW_IE5MAC = 3;
var PW_OPERA = 4;
var PW_KONQUEROR = 5;
var PW_GALEON = 6;
var PW_NETSCAPE6 = 7;

// **************************************************************************************************
// enum ErrorType - enumerates the types of errors.
// **************************************************************************************************
var PW_NOERROR = 0;
var PW_UNABLETOACQUIREREQUEST = 1;

// **************************************************************************************************
// enum ErrorBehavior - enumerates the types of errors
// **************************************************************************************************
var PW_DISABLEAUTOBEHAVIOR = 0;
var PW_SHOWALERT = 1;

var pwTimerArray = new Array();
var pwTimerCount = 0;

function pwAddPageTimer(pwTimer){
	if(pwGetPageTimer(pwTimer.id) == null)
		pwTimerArray[pwTimerCount++] = pwTimer;
}

function pwGetPageTimer(pwId){
	for(var i=0; i<pwTimerCount; i++){
		if(pwTimerArray[i].id == pwId)
			return pwTimerArray[i];
	}
	return null;
}

function pwTimerIsTicking(pwId){
	var pwTempTimer = pwGetPageTimer(pwId);
	return (pwTempTimer == null?false:pwTempTimer.started);
}

function pwDisablePageTimer(pwId){
	var pwTempTimer = pwGetPageTimer(pwId);
	if (pwTempTimer) {
		if(typeof(pwTempTimer.timeoutId) != "undefined"){
			clearTimeout(pwTempTimer.timeoutId);
			pwTempTimer.started = false;
		}
	}
}

function pwMacTick(){
	var pwTheTimer = pwTimerArray[0];
	if(!pwTheTimer) return '';
	if(pwTheTimer.started)
		pwBeginCallback(pwTheTimer.id, 'Tick', '', 'pwInternalCallback', null, pwTheTimer.block, pwTheTimer.waitLabel, pwTheTimer.waitMessage, pwTheTimer.errorBehavior, pwTheTimer.errorMessage, pwTheTimer.updateAll);
	if(pwTheTimer.started)pwTheTimer.timeoutId = setTimeout("pwMacTick()", pwTheTimer.interval);
}

// **************************************************************************************************
// object pwTimer - Represents a timer on the client side.
// **************************************************************************************************
function pwTimer(id, interval, started, block, waitLabel, waitMessage, errorBehavior, errorMessage, updateAll, eventName){
	this.id = id;
	this.interval = interval;
	this.started = started;
	this.block = block;
	this.waitLabel = waitLabel;
	this.waitMessage = waitMessage;
	this.errorBehavior = errorBehavior;
	this.errorMessage = errorMessage;
	this.updateAll = updateAll;
	this.tick = new Function(this.getFunctionText(id));
	this.timeoutId = "";
	if(!eventName)
		this.eventName = "Tick";
	else
		this.eventName = eventName;
	if(started) this.start();
}

pwTimer.prototype.start = function(){
	this.started = true;
	// MAC IE takes a string argument, not a reference to a function
	if(pwManager.detectedBrowser == PW_IE5MAC)
		this.timeoutId = setTimeout("pwMacTick()", this.interval);
	else
		this.timeoutId = setTimeout(this.tick, this.interval);
}

pwTimer.prototype.stop = function(){
	clearTimeout(this.timeoutId);
	this.started = false;
}

pwTimer.prototype.getFunctionText = function(pwId){
		var text = "var pwTimerId = '" + pwId + "';";
		text+= "pwTheTimer = pwGetPageTimer(pwTimerId);";
		//text+= "pwAddDebug('tick event...' + pwTimerId + ' ' + new Date().toTimeString() + ' interval = ' + pwTheTimer.interval);";
		text+= "if(!pwTheTimer) return '';";
		text+= "if(pwTheTimer.started){";
		text+= "pwBeginCallback(pwTheTimer.id, pwTheTimer.eventName, '', 'pwInternalCallback', null, pwTheTimer.block, pwTheTimer.waitLabel, pwTheTimer.waitMessage, pwTheTimer.errorBehavior, pwTheTimer.errorMessage, pwTheTimer.updateAll);";
		text+= "}";
		text+= "if(pwTheTimer.started)pwTheTimer.timeoutId = setTimeout(pwTheTimer.tick, pwTheTimer.interval);";
		return text;
}	

// **************************************************************************************************
// object pwRsRequestManager - Global object used to store the pool of RsRequest objects.
// **************************************************************************************************
function pwRsRequestManager(pwDetectedBrowser){
	this.requestCount = 0;							// Number of requests in the pool.
	this.requests = new Array();					// Array for containing requests.
	this.detectedBrowser = PW_UNSUPPORTED;			// The type of browser detected.
	this.initialRequestPoolSize = 1;				// The initial size of the request pool
	this.callbackNumber = 0;						// Autoincremented number appended to each callback.
	if(pwDetectedBrowser != null) this.detectedBrowser = pwDetectedBrowser;
	this.createInitialRequests();
}

pwRsRequestManager.prototype.createInitialRequests = function(){
	//if(this.detectedBrowser == PW_OPERA) return;
	// Create some requests
	for(var i=0; i<this.initialRequestPoolSize; i++)
		this.createRequest();
}

// method acquireRequest - Return any unused request. Create a new request if none are available.
pwRsRequestManager.prototype.acquireRequest = function(){
	
	//trace+= "attempting to get request\r\n";
	//alert("attempting to get request");

	// First check for an already created and unused request
	for(var i=0; i<this.requestCount; i++){
		if(this.requests[i].busy == false){
			//trace+= "found request. ID = " + this.requests[i].id + "\r\n";
			this.requests[i].busy = true;	
			return this.requests[i];
		}
	}
	
	//trace+= "no requests found...creating a new one\r\n";
	
	// OK, got this far, so there are no free requests. Create a new one.
	this.createRequest();
	this.requests[this.requestCount - 1].busy = true;
	//trace+= "created request. ID = " + this.requests[this.requestCount -1].id + "\r\n";
	return this.requests[this.requestCount - 1];
}

pwRsRequestManager.prototype.getRequestIndex = function(pwRequestId){
	for(var i=0; i<this.requestCount; i++){
		if(this.requests[i].id == pwRequestId)
			return i;
	}
	return -1;
}

pwRsRequestManager.prototype.removeRequest = function(pwRequestId){
	var pwIndex = this.getRequestIndex(pwRequestId);
	if(pwIndex > -1){
		this.requests.splice(pwIndex,0);
		this.requestCount--;
	}
}

pwRsRequestManager.prototype.createRequest = function(){
	this.requests[this.requestCount] = new pwRsRequest(pwBaseUrl, "request" + this.requestCount);
	this.requestCount++;
}

// method retrieveRequest - Return a request for a given ID
pwRsRequestManager.prototype.retrieveRequest = function(pwRequestId){
	for(var i=0; i<this.requestCount; i++){
		if(this.requests[i].id == pwRequestId)
			return this.requests[i];
	}
	return null;
}

// method isBlocking - Return true if a blocking request is pending, false otherwise
pwRsRequestManager.prototype.isBlocking = function(){
	for(var i=0; i<this.requestCount; i++){
		if(this.requests[i].busy == true && this.requests[i].block == true){
			return true;
		}
	}
	return false;
}

pwRsRequestManager.prototype.isPendingCallback = function(){
	for(var i=0; i<this.requestCount; i++){
		if(this.requests[i].busy == true){
			return true;
		}
	}
	return false;
}

pwRsRequestManager.prototype.isPendingTick = function(pwId){
	for(var i=0; i<this.requestCount; i++){
		if(this.requests[i].serverEvent == "Tick" && this.requests[i].caller.id == pwId){
			return true;
		}
	}
	return false;
}
/*
	**** XmlHttp HACK ****
	
	The issue is this. The original plan was to create a global array of XmlHttp objects with a shared handler function (since the
	actual number of XmlHttp objects is unknown, this was convenient). At first, this worked fine, the request was sent and the handler
	function was raised upon completion. However, I soon found out that it was impossible to get the XmlHttp object back within the handler
	(which we HAD to do in order to get the responseText from the XmlHttp) because both "this.xmlHttp == null" AND event.srcElement 
	referred to the global Window object. Apparantly MS did not consider a global array of XmlHttp in their implementation.
	
	...so...
	
	We have a global pool of requests available. The problem was, how to get the request out from the global pool. The solution was to dynamically create 
	a unique handler function for each request. Within that dynamically created handler, we would dynamically create a variable called "requestId" 
	which contains the ID of the request in the pool. We can use this variable to retrieve the request.
	
	The code below is used as the content for the dynamic handler.
*/
var handlerText = "";
handlerText+= "var pendingRequest = pwManager.retrieveRequest(requestId);";
//handlerText+= "alert(pendingRequest.xmlHttp.readyState);";
//handlerText+= "trace+= 'onreadystate change. = ' + pendingRequest.xmlHttp.readyState;";;
//handlerText+= "pwAddDebug('state:' + pendingRequest.xmlHttp.readyState);";
handlerText+= "if(pendingRequest.xmlHttp.readyState != 4) return;";		// 4 means the request is complete.
handlerText+= "if(pendingRequest.xmlHttp.status != 200) return;";
//handlerText+= "trace+= 'in dynamic handler: ' + requestId;";
// Response made up of two parts...code to execute and view state to update
//handlerText+= "document.write(pendingRequest.xmlHttp.responseText);";
//handlerText+= "var parts = pendingRequest.xmlHttp.responseText.split(pwViewStateDelimiter);";
//handlerText+= "alert('data: ' + parts[0]);";
//handlerText+= "alert('viewstate: ' + parts[1]);";
//handlerText+= "document.write(parts[0]);";
handlerText+= "pendingRequest.callbackObject.rawData = pendingRequest.xmlHttp.responseText;";
//handlerText+= "pendingRequest.callbackObject.data = parts[0];";
handlerText+= "pendingRequest.callbackObject.data = pwTrim(pendingRequest.callbackObject.rawData);";
//handlerText+= "pendingRequest.callbackObject.viewState = parts[1];";
handlerText+= "if(pendingRequest.block) pwFakeUnblock(pendingRequest.caller);";
handlerText+= "pendingRequest.clearWaitLabel();";
handlerText+= "if(typeof(pwAfterCallback) == 'function')";
handlerText+= "pwAfterCallback();";
handlerText+= "pendingRequest.busy=false;";
//handlerText+= "pendingRequest.caller = null;";
//handlerText+= "pendingRequest.caller.focus();";
handlerText+= "eval(pendingRequest.callbackFunction + '(pendingRequest.callbackObject)');";
handlerText+= "pendingRequest.serverEvent = '';";
//handlerText+= "alert('completed request for : ' + requestId);";


function pwHandleCustom(pwCallbackObject, pwText, pwHandler){
	pwCallbackObject.data = pwText;
	eval(pwHandler + "(pwCallbackObject);");
}
// **************************************************************************************************
// object pwRsRequest - Used to perform server callbacks.
// **************************************************************************************************
function pwRsRequest(pwServerUrl, pwId){
	this.serverUrl = pwServerUrl;					// Url of the page to which the callback will be issued.
	this.id = pwId;									// ID of this request (must be unique).
	this.xmlHttp = null;							// If the browser is XmlHttp compatible, this will contain the XmlHttp object used for sending callbacks.
	this.flash = null;								// If the browser supports flash, this will contain the flash movie object used for sending callbacks.
	this.iframe = null;							// If the browser is not XmlHttp compatible, this will contain the container object used for sending callbacks.
	this.busy = false;								// Set to true when a callback is pending.
	this.block = true;								// Set this to false for a callback that does not impact UI
	this.updateAll = true;							// Set to false to skip posting all form fields
	this.callbackFunction = null;					// Contains the user callback function.
	this.callbackObject = null;						// Contains the callback object which will eventually be passed into the callback function.
	this.caller = null;								// Contains a reference to the object calling the callback.
	this.serverEvent = "";							// Contains the string of the server event to be raised.
	this.waitLabel = null;							// If this callback should update a label when it occurs, this contains the label object.
	this.waitMessage = "";							// This contains the message to display.
	this.errorBehavior = null;						// Contains the error behavior type
	this.errorMessage = "";							// Contains the error message to display
	this.oldWaitMessage = "";						// Holds a reference to the old wait message text;
	this.createCallbackMechanism();
}

var pwTempObj = null;
var pwTempRequest = null;

pwRsRequest.prototype.createXmlHttp = function(){
	var pwSuccess = false;
	try{
		// Microsoft format
		this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		pwSuccess = true;
	}
	catch(err){
		try{
			// Microsoft format 2
			this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			pwSuccess = true;
		}
		catch(err){
			try{
				// Other (Firefox, etc) format.
				this.xmlHttp = new XMLHttpRequest();
				pwSuccess = true;
			}
			catch(err){
			}
		}
	}
	if(pwSuccess == true && pwCallbackType == "AutoDetect")
		pwCallbackType = "XmlHttp";
	return pwSuccess;
}

pwRsRequest.prototype.createFlash = function(){
	// dynamically create the following element
	// <embed src="Dart.PowerWEB.LiveControls.GetResource.aspx?Res=PWCallback.swf" loop="false" swLiveConnect="true" height="1" width="1" id="PWFlashCallback" name="PWFlashCallback" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" />
	var pwSuccess = false;
	try{
		var pwFlashId = "PWFlashCallback";
		var pwSpanObj = document.getElementById("pwBin");
		var pwFlash = "<embed src='Dart.PowerWEB.LiveControls.GetResource.aspx?Res=PWCallback.swf' loop='false' swLiveConnect='true' height='1' width='1' id='" + pwFlashId + "' name='" + pwFlashId + "' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' />";
		pwSpanObj.innerHTML = pwFlash;
		this.flash = document.getElementById(pwFlashId);
	}
	catch(err){
	}
	if(pwSuccess == true && pwCallbackType == "AutoDetect")
		pwCallbackType = "Flash";
	return pwSuccess;
}



pwRsRequest.prototype.createIFrame = function(pwFromCallback){
	if(pwFromCallback){
		pwCreateAllIFrames();
	}
	else{
		if(pwIsInitialized == false){
			document.body.onload = pwCreateAllIFrames;
			pwIsInitialized = true;
			return;
		}
	}
}


// method createCallbackMechanism - Determines browser capability and sets communication mechanism appropriately.
pwRsRequest.prototype.createCallbackMechanism = function(){
	if(pwCallbackType == "AutoDetect"){
		var isCreated = this.createXmlHttp();
		if(!isCreated)isCreated = this.createFlash();
		if(!isCreated)isCreated = this.createIFrame();
		if(pwCallbackType == "AutoDetect") pwCallbackType = "None";
	}
	else if(pwCallbackType == "XmlHttp")
		this.createXmlHttp();
	else if(pwCallbackType == "Flash")
		this.createFlash();
	else if(pwCallbackType == "IFrame")
		this.createIFrame();
}


// method callback. Perform a PowerWEB integrated callback.
pwRsRequest.prototype.callback = function(pwEventSrc, pwEventTarget, pwEventArgs){
	/*
		Several things have to happen prior to a callback.
			- Create the request url (basically just gather form variables)
			- Changing the interface to blocking (if so configured)
			- Updating wait labels.
			- Performing form validation
	*/
	
	// Update the wait label for this callback
	this.setWaitLabel();
	// Check to see if they implemented the beforeCallback function
	if(typeof(pwBeforeCallback) == "function"){
		pwBeforeCallback();	
	}
	
	// Create the request URL
	var requestUrl = "";
	if(pwIsCookieless == true)
		requestUrl = (pwCookielessUrl.indexOf("?") > -1)?pwCookielessUrl + "&":pwCookielessUrl + "?";
	else
		requestUrl = (pwBaseUrl.indexOf("?") > -1)?pwBaseUrl + "&":pwBaseUrl + "?";
	var requestData = "";
	requestData+= pwEventSrcKey + "=" + pwEscape(pwEventSrc);

	if(this.updateAll){
		var pwTempFields = pwGetFormFields(pwEventSrc);
		if(pwTempFields == "!!!ERROR!!!"){
			this.busy = false;
			return;
		}
		requestData+= "&" + pwTempFields;
	}
	requestData+= "&" + pwGetHiddenFields(pwEventSrc);
	requestData+= "requestId=" + this.id;
	//if(pwEventTarget == "Click")
	var pwHandlingControl = "";
	if(this.caller.type == "radio") pwHandlingControl = pwFixGroupName(this.caller.name);
	if(this.caller.name == "" || this.caller.name == null || pwHandlingControl == "") pwHandlingControl = this.caller.id;
	if(!pwSkipField(requestData, pwEventSrc)){
		requestData+= "&" + pwGetHandlingControl(pwHandlingControl) + "=" + pwObj(pwEventSrc).value;
	}
	requestData+= "&__EVENTTARGET=" + pwEventSrc;
	requestData+= "&__EVENTARGUMENT=";
	requestData+= "&" + pwEventTargetKey + "=" + pwEscape(pwEventTarget);
	requestData+= "&" + pwEventArgsKey + "=" + pwEscape(pwEventArgs);
	requestData+= "&" + pwCallbackKey + "=true";
	requestData+= "&" + pwCallbackNumberKey + "=" + pwManager.callbackNumber++;
	requestData+= "&" + pwCallbackTypeKey + "=" + pwCallbackType;
	
	// Perform form validation
	var pwValidator = pwInArray(pwHandlingControl, pwArrValidators);
	if(pwValidator){
		if(typeof(Page_ClientValidate) == "function"){
			if(!Page_ClientValidate()){
				this.busy = false;
				return;
			}
		}
	}
	// Change the interface to blocking if needed
	if(this.block){
		// Do fake blocking
		if(this.caller.className != "pwNonVisual")
			pwFakeBlock(this.caller);
	}

	if(pwDiagnosticMode)pwAddDebug(requestData, "request");
	
	// Send the request
	if(pwCallbackType == "XmlHttp"){
		this.xmlHttp.open("POST", requestUrl, true);
		this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.internalHandler = new Function("var requestId = '" + this.id + "';" + handlerText);
		this.xmlHttp.onreadystatechange = this.internalHandler;
		this.xmlHttp.send(requestData);
	}
	else if(pwCallbackType == "Flash"){
		requestData = pwReplaceString(requestData, "&&", "&");
		pwSendFlashCallback(this, pwServer + requestUrl + requestData);
	}
	else if(pwCallbackType == "IFrame"){
		if(pwIsIE()){
			this.iframe.open();
		    this.iframe.write('<html><body>');
            this.iframe.write('<form name="pwForm" action="' + requestUrl + '" method="post">');
            this.iframe.write('<input type="hidden" name="macplaceholder" value="filler" />\r\n');
               
            var pwMacArgs = requestData.split('&');
            for(var i=0; i<pwMacArgs.length; i++){
				var pwMacParts = pwMacArgs[i].split('=');
				if(pwMacParts.length >= 2){
					var pw2ndField = pwMacParts[1];
					for(var j=2; j<pwMacParts.length; j++)
						pw2ndField+= "=";
					var blah = '<input type="hidden" name="' + pwMacParts[0] + '" value="' + pw2ndField + '" />\r\n';
					this.iframe.write(blah);
				}
            }
			this.iframe.write('</form></body></html>');
            this.iframe.close();
            this.iframe.forms['pwForm'].submit();
		}
		else{
			requestData = pwReplaceString(requestData, "&&", "&");
			this.iframe.location.replace(requestUrl + requestData);
		}
	}
	else{
		// do regular postback
		
		// first add fields using a hidden form.
		// check if they exist
		if(typeof(document.forms[0].__EVENTTARGET) == "undefined"){
			// they don't...create it
			var pwTarget = document.createElement("input type=hidden");
			pwTarget.name = "__EVENTTARGET";
			pwTarget.value = pwEventSrc;
			document.forms[0].appendChild(pwTarget);
			if(document.all) document.forms[0].normalize();
		}
		else
			document.forms[0].__EVENTTARGET.value = pwEventSrc;
		document.forms[0].submit();
	}
}

pwRsRequest.prototype.setWaitLabel = function(){
	if(this.waitLabel){
		if(typeof(this.waitLabel.value) != "undefined")
			this.waitLabelProp = "value";	
		else if(typeof(this.waitLabel.text) != "undefined")
			this.waitLabelProp = "text";
		else
			this.waitLabelProp = "innerHTML";
		this.oldWaitMessage = eval("this.waitLabel." + this.waitLabelProp);
		eval("this.waitLabel." + this.waitLabelProp + "='"  + this.waitMessage + "'");
	}
}

pwRsRequest.prototype.clearWaitLabel = function(){
	if(this.waitLabel){
		eval("this.waitLabel." + this.waitLabelProp + "='" + this.oldWaitMessage + "'");
	}
}

var pwIFramesCompleted = false;

function pwCreateAllIFrames(){
	pwIFramesCompleted = false;
	for(var i=0; i<pwManager.requestCount; i++){
		pwCreateIFrame(pwManager.requests[i]);
	}
}

function pwCreateIFrame(pwRequest){
	var pwSuccess = false;
	try{
		if(pwIsIE()){
		    var newIFrame=document.createElement('iframe');
			newIFrame.setAttribute('id','pwIFrame');
			newIFrame.setAttribute('name','pwIFrame');
			newIFrame.style.border='0px';
			newIFrame.style.width='0px';
			newIFrame.style.height='0px';
			newObj = document.body.appendChild(newIFrame);
			newObj = document.frames['pwIFrame'];
			pwRequest.iframe = newObj.document;
			pwSuccess = true;
		}
		else{
			var newFrame=document.createElement('iframe');
			newFrame.setAttribute('id','pwIFrame' + this.id);
			newFrame.setAttribute('name','pwIFrame' + this.id);
			newFrame.style.border='0px';
			newFrame.style.width='0px';
			newFrame.style.height='0px';
			pwRequest.pwTempObj = document.body.appendChild(newFrame);
			setTimeout(pwCompleteIFrames, 50);
			pwSuccess = true;
		}
	}
	catch(err){
	}
	if(pwSuccess == true)
		pwCallbackType = "IFrame";
}


function pwCompleteIFrames(){
	if(pwIFramesCompleted == false){
		pwIFramesCompleted = true;
		for(var i=0; i<pwManager.requestCount; i++){
			pwManager.requests[i].iframe = pwManager.requests[i].pwTempObj.contentDocument;
		}
	}
}

// IFRAME callbacks do not need to use the XmlHttp dynamically generated callback function approach.
function pwInternalFrameCallback(pwRequestId, pwCode){
	//alert("callback complete");
	var pendingRequest = pwManager.retrieveRequest(pwRequestId);
	
	// Response made up of two parts...code to execute and view state to update
	//var parts = pwCode.split(pwViewStateDelimiter);	
	//alert("obj: " + pendingRequest.callbackObject);
	pendingRequest.callbackObject.rawData = pwCode;
    //pendingRequest.callbackObject.data = parts[0];
    pendingRequest.callbackObject.data = pwTrim(pendingRequest.callbackObject.rawData);
    
    // remove formatting added by IFRAME
    pendingRequest.callbackObject.data = pwReplaceString(pendingRequest.callbackObject.data, "\r\n", "");
    pendingRequest.callbackObject.data = pwReplaceString(pendingRequest.callbackObject.data, "\t", "");
    
    //\x22
    //pendingRequest.callbackObject.viewState = parts[1];
	//alert(pwDiagnosticMode);
	//if(pwDiagnosticMode)pwAddDebug("response: " + pwCallbackObject.data);
	
	//alert("executing tasks");
	// Execute code
	if(!pwManager.isBlocking()) pwFakeUnblock(pendingRequest.caller);
	pendingRequest.clearWaitLabel();
	if(typeof(pwAfterCallback) == 'function')
		pwAfterCallback();
		
	pendingRequest.busy = false;
	//alert("sending to function");
	eval(pendingRequest.callbackFunction + '(pendingRequest.callbackObject)');
	pendingRequest.caller = null;
	pendingRequest.serverEvent = "";
	//if(pwManager.detectedBrowser == PW_OPERA) pwPause(200);
	//if(pwManager.detectedBrowser == PW_OPERA || pwManager.detectedBrowser == PW_NETSCAPE6)   // need to recreate container each time for opera and nn6
}

function pwUpdateViewState(pwViewState){
if(!pwViewState) return;
if(pwViewState == "") return;
if(pwIsIE())
		document.getElementById("__VIEWSTATE").value = pwViewState;
	else{
		try{
			for(var i=0;i<document.forms[0].elements.length;i++){
				var pwFormEl = document.forms[0].elements[i];
				if(pwFormEl.name == "__VIEWSTATE")
					pwFormEl.value = pwViewState;
			}
		}
		catch(err){
		}
	}
}

function pwInternalCallback(pwCallbackObject){
	
	// First check if it is a timer. If it is, and the timer has been stopped since the callback was sent, then don't execute anything
	if(pwCallbackObject.request.serverEvent == "Tick"){
		if(!pwTimerIsTicking(pwCallbackObject.request.caller.id)){
			return;
		}
	}
	
	// Update the ViewState
	/*
	if(pwIsIE())
		document.getElementById(pwViewStateKey).value = pwCallbackObject.viewState;
	else{
		try{
			for(var i=0;i<pwElem.form.elements.length;i++){
				var pwFormEl = pwElem.form.elements[i];
				if(pwFormEl.name == "pwViewState")
					pwFormEl.value = pwCallbackObject.viewState;
			}
		}
		catch(err){
		}
	}
	*/
	if(pwDiagnosticMode)pwAddDebug(pwCallbackObject.data, "response");
	
	// check if it is an html response and document.write instead
	if(pwCallbackObject.data.indexOf("<!DOCTYPE HTML") > -1 || pwCallbackObject.data.indexOf("<HTML") > -1){
		document.write(pwCallbackObject.data);
	}
	else{
		//pwAddDebug(pwCallbackObject.data);
		eval(pwCallbackObject.data);
	}
}

// **************************************************************************************************
// object pwRsCallbackResponse - Represents a callback.
// **************************************************************************************************
function pwRsCallbackResponse(pwContext){
	this.error = PW_NOERROR;				//
	this.errorMessage = "";					//
	this.data = "";							//
	this.rawData = "";
	this.context = pwContext;				//
	//this.viewState = "";					//
	this.request = null;
}


// **************************************************************************************************
// global pwFakeBlock function - Updates the interface for our "psuedo-blocking" mechanism.
// **************************************************************************************************
function pwFakeBlock(pwElement){
	if(pwElement) pwElement.disabled = true;
	//pwDoUpdateUI("wait", true);
}

function pwFixFields(pwData){
	pwData = pwReplaceString(pwData, "==&", "@#$#@&");
	var pwFixedFields = "";
	var pwFields = pwData.split('&');
	for(var i=0; i<pwFields.length; i++){
		var pwParts = pwFields[i].split('=');
		if(pwParts.length == 2){
			if(pwParts[0] != "" && pwParts[1] != "")
				pwFixedFields+= pwParts[0] + "=" + pwParts[1] + "&"
		}
	}
	pwFixedFields = pwFixedFields(pwData, "@#$#@&", "==&");
	return pwFixedFields;
}

// **************************************************************************************************
// global pwFakeUnblock function - Returns the interface to normal.
// **************************************************************************************************
function pwFakeUnblock(pwElement){
	if(pwElement) pwElement.disabled = false;
	//pwDoUpdateUI("default", false);
}

function pwSkipField(pwRequestString, pwEventSrc){
	var pwCaller = pwObj(pwEventSrc);

	if(pwInRequest(pwRequestString, pwCaller))
		return true;
	
	// Check if it is a checkbox and unchecked
	if(pwCaller.type == "checkbox")
		if(!pwCaller.checked) return true;
	
	// Check if the value is null
	if(typeof(pwCaller.value) == "undefined")
		return true;
		
	// If is one of our non-visual controls, do not add it to the form data
	if(pwCaller.className == "pwNonVisual")
		return true;
	
	return false;
}

function pwInRequest(pwRequestString, pwElement){
	// Check if already in request
	var fields = pwRequestString.split("&");
	for(var i=0; i<fields.length; i++){
		var parts = fields[i].split("=");
		if(parts[0] == pwElement.name) return true;
	}
}

function pwDoUpdateUI(pwCursorType, pwDisabled){
	//if(pwManager.detectedBrowser == 8){
	//	document.classes.pwLiveObject.all.cursor = pwCursorType;
	//	return;
	//}
	//else
	//	window.document.body.style.cursor = pwCursorType;
		
	// Unfortunately, the cursor does not apply to form elements, so we have to override.
	for(var i=0; i<document.forms.length; i++){
		for(var j=0; j<document.forms[i].elements.length; j++){
			if(pwManager.detectedBrowser == PW_IE || pwManager.detectedBrowser == PW_MOZILLA){
				if(pwCursorType == "wait"){
					document.forms[i].elements[j].origDisabled = document.forms[i].elements[j].disabled;
					document.forms[i].elements[j].disabled = pwDisabled;	
				}
				else 
					document.forms[i].elements[j].disabled = document.forms[i].elements[j].origDisabled;
			}
			//if(window.setCursor)
			//	window.setCursor(pwCursorType);
			//else
				//document.forms[i].elements[j].style.cursor = pwCursorType;	
				
			// Keep them from double-clicking the element when blocking.
			document.forms[i].elements[j].onClick = (pwDisabled == true)?pwOnClick:"";
		}
	}
}

function pwGetHiddenFields(pwElemId){
	pwElem = pwObj(pwElemId);
	if(typeof(pwElem) == "undefined") return "";
	var pwHiddenFields = "";
		
	// Stupid Mozilla bug...it can't reference __ViewState using getElementById, so we have to dig it out by iterating through the forms collection.
	if(pwManager.detectedBrowser == PW_IE){
		pwHiddenFields = "__VIEWSTATE=" + pwEscape(pwObj("__VIEWSTATE").value) + "&";
		//pwHiddenFields+= "pwViewState=" + pwEscape(pwObj("pwViewState").value) + "&";
	}
	else{
		try{
			for(var i=0;i<pwElem.form.elements.length;i++){
				var pwFormEl = pwElem.form.elements[i];
				if(pwFormEl.name == "__VIEWSTATE")
					pwHiddenFields+= "__VIEWSTATE=" + pwEscape(pwFormEl.value) + "&";
				//if(pwFormEl.name == "pwViewState")
				//	pwHiddenFields+= "pwViewState=" + pwEscape(pwFormEl.value) + "&";
			}
		}
		catch(err){
		}
	}
	return pwHiddenFields;
}

// **************************************************************************************************
// global pwGetFormField function - Gets all fields in the current form and returns them, "querystring-ready"
// **************************************************************************************************
function pwGetFormFields(pwElemId){
	pwElem = pwObj(pwElemId);
	if(!pwElem) return;
	var pwFields = "";
	try{
		if(!pwElem.form)pwElem.form = pwGetForm(pwElem);
		if(!pwElem.form)pwElem.form = document.forms[0];
	}
	catch(err){
		pwDisablePageTimer(pwElemId);
		return "!!!ERROR!!!";
	}
	for(var i=0;i<pwElem.form.elements.length;i++){
		var pwFormEl = pwElem.form.elements[i];
		//alert("name: " + pwFormEl.name);
		//alert("val: " + pwFormEl.value);
		if(pwFormEl.type == "radio"){
			if(!pwInRequest(pwFields, pwFormEl)){
				if(pwFormEl.checked)
					pwFields+= pwEscape(pwFormEl.name) + "=" + pwEscape(pwFormEl.value) + "&";
			}
		}
		else{
			if(pwFormEl.type == "button")continue;
			if(pwFormEl.type == "submit") continue;
			if(pwFormEl.name == "") continue;
			if(pwFormEl.value == null) continue;
			if(pwFormEl.name == "__EVENTTARGET") continue;
			if(pwFormEl.name == "__EVENTARGUMENT") continue;
			if(pwFormEl.className == "pwNonVisual")continue;
			if(pwFormEl.name == "__VIEWSTATE")continue;
			//if(pwFormEl.name == "pwViewState")continue;
			
			if(pwFormEl.type == "select-one" || pwFormEl.type == "select-multiple"){
				var selectedValues = "";
				for (var j=0; j<pwFormEl.options.length; j++){
					if (pwFormEl.options[j].selected)
						selectedValues += (pwFormEl.options[j].value + ",");
				}
				selectedValues = selectedValues.substring(0, selectedValues.length-1);
				if(selectedValues != "") pwFields += pwEscape(pwFormEl.name) + "=" + pwEscape(selectedValues) + "&";
			}
			else if(pwFormEl.type == "checkbox"){
				if(pwFormEl.checked)
					pwFields+= pwEscape(pwFormEl.name) + "=on&";
				else
					pwFields+= pwEscape(pwFormEl.name) + "=&";
			}
			else
				pwFields+= pwEscape(pwFormEl.name) + "=" + pwEscape(pwFormEl.value) + "&";
		}
	}
	//pwFields+= "__VIEWSTATE=";
	if(pwFields != "") pwFields = pwFields.substring(0, pwFields.length - 1);
	return pwFields;
}

// **************************************************************************************************
// global pwGetForm function - For any non-form controls, gets the first parent form.
// **************************************************************************************************
function pwGetForm(pwElem){
	return pwGetInstance("form", pwElem);
}

// **************************************************************************************************
// global pwGetInstance function - Recursively searches for a parentElement of the specified type.
// **************************************************************************************************
function pwGetInstance(pwElementType, pwSelectedElement){
    if(pwElementType.toLowerCase() == pwSelectedElement.tagName.toLowerCase())
		return pwSelectedElement;
    else if(pwSelectedElement.tagName.toLowerCase() == "body")
		return null;
    else{
		var pNode = null;
		pNode = (pwIsIE()?pwSelectedElement.parentElement:pwSelectedElement.parentNode);
		return pwGetInstance(pwElementType, pNode);
	}
}

function pwIsIE(){
	if(pwManager.detectedBrowser == PW_IE
		|| pwManager.detectedBrowser == PW_IE5
		|| pwManager.detectedBrowser == PW_IE5MAC)
		return true;
	return false;
}

// **************************************************************************************************
// global pwEscape function - Escapes the characters for Internet transmission
// **************************************************************************************************
function pwEscape(pwString){
	// This is to bypass the validaterequest bug
	//pwString = escape(pwString);
	pwString = pwReplaceString(pwString, "<", "%253C");
	pwString = pwReplaceString(pwString, ">", "%253E");
	pwString = pwReplaceString(pwString, "%3C", "%253C");
	pwString = pwReplaceString(pwString, "%3E", "%253E");
	
	if(!(pwIsIE() && pwCallbackType == "IFrame")){
		pwString = pwReplaceString(pwString, "+", "%2B");
		pwString = pwReplaceString(pwString, "&", "%26");
	}
	
	//pwString = pwReplaceString(pwString, "%", "%25");
	//pwString = pwReplaceString(pwString, "<", "0x3C");
	//pwString = pwReplaceString(pwString, ">", "0x3E");
	//pwString = pwReplaceString(pwString, "%3C", "");
	//pwString = pwReplaceString(pwString, "%3E", "");
	return pwString;
}



// **************************************************************************************************
// global pwReplaceString function - Replaces all instances of a character in a string with another character
// **************************************************************************************************
function pwReplaceString(pwStr, pwStrFind, pwStrReplace) { 
  while(pwStr.indexOf(pwStrFind) != -1) {
     pwStr = pwStr.replace(pwStrFind, pwStrReplace);
  } 
  return pwStr;     
} 

function pwTrim(pwStr) {
   if (typeof pwStr != "string") { return pwStr; }
   var retValue = pwStr;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { 
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") {
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) {
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
   }
   return retValue;
}

var pwLoopCount = 0;
var pwSavedRequest = null;

// **************************************************************************************************
// global BeginCallback function - The main interface point for PowerWEB-sourced callbacks.
// **************************************************************************************************
function pwBeginCallback(pwEventSrc, pwEventTarget, pwEventArgs, pwCallbackFunction, pwContext, pwBlock, pwWaitLabel, pwWaitMessage, pwErrorBehavior, pwErrorMessage, pwUpdateAll){

	//pwAddDebug("args: " + pwEventArgs);
	
	// Check if currently blocking
	if(pwManager.isBlocking()){
		return;
	}

	// If the event is "Tick", check to make sure there is no pending tick
	if(pwEventTarget == "Tick"){
		if(pwManager.isPendingTick(pwEventSrc)){
			return;
		}
	}
	
	// Haven't figured out a good way to multithread a Flash movie yet, so no simultaneous requests allowed
	if(pwCallbackType == "Flash" && pwManager.isPendingCallback())
		return;
	
	if(typeof(pwInitCallback) == "function")
		pwInitCallback();
	
	
	// Try to get a free request
	var internalRequest = pwManager.acquireRequest();
	if(internalRequest == null){
		// Failed (this should never happen because a new request should be created if needed)
		var nullCallback = new pwRsCallbackResponse(null);
		nullCallback.error = PW_UNABLETOACQUIREREQUEST;
		nullCallback.errorMessage = "Unable to acquire a request.";
		pwCallbackFunction;
		return null;
	}
	else{
		if(pwCallbackType == "IFrame")
			internalRequest.createIFrame(true);
		else if(pwManager.detectedBrowser == PW_MOZILLA && pwCallbackType != "Flash"){
			if(pwEventTarget == "ConfirmResponse" || pwEventTarget == "PromptResponse" || pwEventTarget=="PromptNullResponse") // With MessageBox, Mozilla unsuccessfully posts back. So we reinit the request.
				internalRequest.createCallbackMechanism();
		}			
			
		//alert("successfully got request: " + internalRequest.id);
		// OK, we have a free request, so we can send a callback.
		
		// before we continue, be sure caller is not null. This could happen if the element is removed from the DOM while the callback is pending
		var pwCaller = pwObj(pwEventSrc);
		if(!pwCaller) 
		{
			pwManager.removeRequest(internalRequest.id);
			return;
		}
		
		internalRequest.callbackFunction = pwCallbackFunction;
		internalRequest.block = pwBlock;
		internalRequest.updateAll = pwUpdateAll;
		internalRequest.waitLabel = document.getElementById(pwWaitLabel);
		internalRequest.waitMessage = pwWaitMessage;
		internalRequest.errorBehavior = pwErrorBehavior;
		internalRequest.errorMessage = pwErrorMessage;
		internalRequest.callbackObject = new pwRsCallbackResponse(pwContext);
		internalRequest.callbackObject.request = internalRequest;
		internalRequest.callerId = pwEventSrc;
		internalRequest.caller = pwCaller;
		internalRequest.serverEvent = pwEventTarget;	
		internalRequest.serverArgs = pwEventArgs;
		pwSavedRequest = internalRequest;
		if(pwCallbackType == "IFrame" && (!pwIsIE()))
			setTimeout(pwDoCallback, 50);
		else{
			internalRequest.callback(pwEventSrc, pwEventTarget, pwEventArgs);
		}
	}
}

function pwDoCallback(){
	pwSavedRequest.callback(pwSavedRequest.callerId, pwSavedRequest.serverEvent, pwSavedRequest.serverArgs);
}

// **************************************************************************************************
// global pwBeginCallServerFunction function - The main interface point for custom callbacks which call a server function.  
// **************************************************************************************************
function pwBeginCallServerFunction(pwFunctionName, pwCallbackFunction, pwContext, pwBlock, pwP1, pwP2, pwP3, pwP4, pwP5, pwP6, pwP7, pwP8, pwP9){
	var pwArgs = "";
	if(pwP1 && pwP1 != "")pwArgs+= pwP1 + pwViewStateDelimiter;
	if(pwP2 && pwP2 != "")pwArgs+= pwP2 + pwViewStateDelimiter;
	if(pwP3 && pwP3 != "")pwArgs+= pwP3 + pwViewStateDelimiter;
	if(pwP4 && pwP4 != "")pwArgs+= pwP4 + pwViewStateDelimiter;
	if(pwP5 && pwP5 != "")pwArgs+= pwP5 + pwViewStateDelimiter;
	if(pwP6 && pwP6 != "")pwArgs+= pwP6 + pwViewStateDelimiter;
	if(pwP7 && pwP7 != "")pwArgs+= pwP7 + pwViewStateDelimiter;
	if(pwP8 && pwP8 != "")pwArgs+= pwP8 + pwViewStateDelimiter;
	if(pwP9 && pwP9 != "")pwArgs+= pwP9 + pwViewStateDelimiter;
	//if(pwArgs != "") pwArgs.substring(pwArgs.length - pwViewStateDelimiter.length, pwViewStateDelimiter.length)
	pwArgs+= pwCallbackFunction;
	//pwBeginCallback(pwCustomFunctionManager, pwFunctionName, pwArgs, pwCallbackFunction, pwContext, pwBlock, '', '')
	var pwUpdateAll = true;
	try{
		if(typeof(pwCustomFunctionManagerUpdateAll) != "undefined")
			pwUpdateAll = pwCustomFunctionManagerUpdateAll;
	}catch(err){}
	pwBeginCallback(pwCustomFunctionManager, pwFunctionName, pwArgs, "pwInternalCallback", pwContext, pwBlock, '', '', null, null, pwUpdateAll);
}

// **************************************************************************************************
// global pwObj function. Shorthand function to reduce the amount of code going over the wire.
// **************************************************************************************************
function pwObj(pwObjId){
	var pwObjRef = pwGetElement(pwObjId);
	if(pwObjRef) return pwObjRef;
	return pwGetElement(pwGetHandlingControl(pwObjId));
}

function pwGetElement(pwObjId){
	var pwObjRef = document.getElementById(pwObjId);
	if(pwObjRef)return pwObjRef;
	var pwTempObjId = pwReplaceString(pwObjId, "$", "_");
	pwObjRef = document.getElementById(pwTempObjId);
	if(pwObjRef)return pwObjRef;
	pwObjId = pwReplaceString(pwObjId, ":", "_");
	pwObjRef = document.getElementById(pwObjId);
	if(pwObjRef)return pwObjRef;
	var pwParts = pwObjId.split('_');
	pwObjRef = document.getElementById(pwParts[pwParts.length-1]);
	if(pwObjRef)return pwObjRef;
	//alert("couldn't find....going further");
	pwObjRef = pwFindChangedControl(pwObjId);
	//alert(pwObjRef);
	return pwObjRef;
}

// This function attempts to match up controls in a case where they are dynamically loaded in a placeholder. This could result
// in something like a client side control named _ctl47_livebutton attempting to raise an event on a control named _ctl87_livebutton
function pwFindChangedControl(pwId){
	//alert("finding: " + pwId);
	var pwParts = pwId.split("_");
	//alert("length: " + pwParts.length);
	var pwI = 0;
	for(pwI=0; pwI<pwParts.length; pwI++){
		//alert("checking part: " + pwParts[pwI]);
		if(pwParts[pwI].indexOf("ctl") == 0) break;
	}
	//alert("index: " + pwI);
	if(pwI == pwParts.length) return null;
	var pwPart = pwParts[pwI];
	//alert("part: " + pwPart);
	var pwSnum = pwReplaceString(pwPart, "ctl", "");
	//alert("num: " + pwSnum);
	if(pwSnum == "") return null;
	var pwNum = parseInt(pwSnum);
	//alert("parsed num: " + pwNum);
	//alert("part: " + pwPart);
	for(var i=pwNum; i<5000; i++){
		//alert("old id: " + pwId);
		//alert("num: " + i);
		var pwNewId = pwId.replace("_" + pwPart + "_", "_ctl" + i + "_");
		//alert("new id: " + pwNewId);
		var pwObj = document.getElementById(pwNewId);
		if(pwObj) return pwObj;
	}
	return null;
}

function pwGetHandlingControl(pwId){
	var gridId = pwInArray(pwId, pwArrGrids);
	if(gridId != null && gridId != "") return gridId;
	if(pwId.indexOf("__") > -1)
		return pwId.split('__')[0];
	if(pwId.indexOf(":") > -1)
		return pwReplaceString(pwId, ":", "%3A");
		//return pwId.split("_")[pwId.split("_").length-1];
	return pwId;
}

function pwInArray(pwId, pwArr){
	for(var i=0; i<pwArr.length; i++){
		if(pwId.indexOf(pwArr[i]) == 0) return pwArr[i];
		var pwParts = pwArr[i].split(':');
		var pwCounter = 0;
		if(pwParts.length == 1) pwCounter = 0;
		for(var j=pwCounter; j<pwParts.length; j++){
			if(pwParts[j].indexOf("_") != 0){
				if(pwId.indexOf(pwParts[j]) > -1)
				return pwArr[i];
			}
		}
	}
	return null;
}
function pwFixGroupName(pwId){
	return pwId.split(":")[pwId.split(":").length-1];
}

function pwRecursiveSetDisplay(pwObj, pwVisibility){
   for(var i=0; i<pwObj.childNodes.length; i++){
      try{
      pwObj.childNodes[i].style.display = pwVisibility;
      }
      catch(err){}
      pwRecursiveSetDisplay(pwObj.childNodes[i], pwVisibility);
   }
}

function pwSetMozillaOuterHTML(pwId, pwData){
	var pwEl = pwObj(pwId);
	if(!pwEl)return;
	var pwRange = document.createRange();
	pwRange.selectNode(pwEl);
	var pwFrag = pwRange.createContextualFragment(pwData);
	pwEl.parentNode.replaceChild(pwFrag, pwEl);
}

function pwReloadList(pwId, pwArrText, pwArrValue, pwArrSelected){
	var listObj = pwObj(pwId);
	if(listObj == null) return;
	
	var selIndex = pwObj(pwId).selectedIndex;
	
	// Clear current values
	for(var i=listObj.options.length; i>0; i--)
		listObj.removeChild(listObj.options[i-1]);
	
	// Reload with new
	for(var i=0; i<pwArrText.length; i++){
		 var pwOption = document.createElement("OPTION");
		 pwOption.text = pwArrText[i];
		 pwOption.value = pwArrValue[i];
		 pwOption.selected = pwArrSelected[i];
		 // Nice! (sarcasm) options.add doesn't work for Netscape 6...so we have to use an alternate approach
		 if(pwManager.detectedBrowser == PW_NETSCAPE6)
			listObj.add(pwOption, null);
		else
			listObj.options.add(pwOption);  
	}
	pwObj(pwId).selectedIndex = selIndex;
}

function pwReloadTable(pwId, pwArrText, pwArrValue, pwArrSelected, pwType){
	var listObj = pwObj(pwId);
	if(listObj == null) return;
	
	// Clear current values
	var count = listObj.rows.length;
	for (var i=0; i<count; i++)
		listObj.deleteRow(0);
		
	for (var i=0; i<pwArrText.length; i++)
	{	
		var pwRadio = document.createElement("input");
		pwRadio.onclick = "pwBeginCallback('" + listObj.id + "_" + i + "', 'Click',event.clientX + '@' + event.clientY, 'pwInternalCallback', '', false, '','Processing...');";
		pwRadio.id = listObj.id + "_" + i;
		pwRadio.type = pwType;
		pwRadio.value = pwArrValue[i];
		pwRadio.checked = pwArrSelected[i];
		var pwRadioString = pwRadio.outerHTML;
		
		//Add the "name" attribute which specifies the radiolist group, and
		//For some reason is stripped from outerHTML if pwRadio.name is set
		pwRadioString = pwRadioString.substr(0, pwRadioString.length-1) + " name=" + listObj.id + ">";

		var pwLabel = document.createElement("label");
		pwLabel.htmlfor = pwRadio.id;
		pwLabel.innerHTML = pwArrText[i];
		
		var pwNewRow = listObj.insertRow();
		var pwNewCell = pwNewRow.insertCell();
		pwNewCell.innerHTML=pwRadioString + pwLabel.outerHTML;
	}	
}
	
function pwReloadFlowList(pwId, pwArrText, pwArrValue, pwArrSelected, pwType) {
	var listObj = pwObj(pwId);
	if(listObj == null) return;
	
	var count = listObj.childNodes.length;
	for (var i=0; i<count; i++)
	{
		var pwChild = listObj.children(0);
		listObj.removeChild(pwChild);
	}
	
	for (var i=0; i<pwArrText.length; i++)
	{	
		var pwRadio = document.createElement("input");
		pwRadio.onclick = "pwBeginCallback('" + listObj.id + "_" + i + "', 'Click',event.clientX + '@' + event.clientY, 'pwInternalCallback', '', false, '','Processing...');";
		pwRadio.id = listObj.id + "_" + i;
		pwRadio.type = pwType;
		pwRadio.value = pwArrValue[i];
		pwRadio.checked = pwArrSelected[i];
		
		//for some reason, the name attribute is removed
		//so add NName attribute to be replaced later
		var namedItem = document.createAttribute("Nname");
		namedItem.value = listObj.id;
		pwRadio.attributes.setNamedItem(namedItem);
		
		//for some reason, when item is appended, the checked value gets cleared
		//so it's done manually
		if (pwArrSelected[i])
		{
			var namedItem = document.createAttribute("checked");
			namedItem.value = "checked";
			pwRadio.attributes.setNamedItem(namedItem);
		}
		listObj.appendChild(pwRadio);
	
		var pwLabel = document.createElement("label");
		pwLabel.htmlfor = pwRadio.id;
		pwLabel.innerHTML = pwArrText[i];
		listObj.appendChild(pwLabel);
		
		if (i!=(pwArrText.length-1))
		{
			var pwBreak = document.createElement("br"); 
			listObj.appendChild(pwBreak);
		}
	}
	
	//Replace stub Nname
	listObj.outerHTML = pwReplaceString(listObj.outerHTML, "Nname", "name");
}

var pwDebugWindow = null;

function pwKillWindowIfOpen(){
	if(pwDebugWindow != null){
		if(!pwDebugWindow.closed)
			pwDebugWindow.close();
		pwDebugWindow = null;
	}
}
function pwAddDebug(pwStr, pwTitle){
	window.onunload = pwKillWindowIfOpen;
	if(pwDebugWindow == null || pwDebugWindow.closed){
		pwDebugWindow = window.open("about:blank","name","resizable=yes,scrollbars=yes,height=" + (window.screen.height/2) + ",width=" + (window.screen.width/2));
		if (!pwDebugWindow.opener) pwDebugWindow.opener = self;
		pwDebugWindow.document.write("<html><head><title>PowerWEB Diagnostic Window</title></head><body><div style='font-family:verdana;font-size:12px'>");
		
	}
	pwStr = pwReplaceString(pwStr, "<", "&lt;");
	pwStr = pwReplaceString(pwStr, ">", "&gt;");
	
	if (window.focus) pwDebugWindow.focus();
	if(pwTitle == "response")
		pwStr = "<span style='color:blue'>" + pwStr + "</span>";
	pwDebugWindow.document.write("<br><b>" + pwTitle + "</b>:<br>" + pwStr + "<br>");
	if(pwTitle == "response")
		pwDebugWindow.document.write("<hr width='100%'>");
	pwDebugWindow.scrollTo(0, pwDebugWindow.document.all?pwDebugWindow.document.body.scrollHeight:pwDebugWindow.document.height);
}


function pwGetScriptSources(){
	var pwScriptSources = document.getElementsByTagName("script");
	var pwScriptString = "";
	for(var i=0; i<pwScriptSources.length; i++){
		if(typeof(pwScriptSources[i].src) != "undefined" 
			&& pwScriptSources[i].src.indexOf("Dart.PowerWEB.LiveControls") == -1){
			pwScriptString = pwScriptString + pwScriptSources[i].src + "&";
		}
	}
	if(pwScriptString.length > 0) pwStringString = pwScriptString.substr(0, pwScriptString.length-1);
	return pwScriptString.split('&');
}

function pwResetScriptSources(){
	for(var i=0; i<pwArrSources.length; i++){
		if(pwArrSources[i] != ""){
			var newScript = document.createElement("script");
			newScript.src = pwArrSources[i];
			document.body.appendChild(newScript);
		}
	}
}

// .mjb.6-1-05.3195.Disable use of pwLoadImage until we have time to set up a better way to use it.
/*
var currentLoadImg = null;
function pwLoadImage(pwId, pwSrc){
	if(currentLoadImg && (!currentLoadImg.complete))return;
	var pwImg = new Image();
	pwImg.id = pwId + "_temploader";
	pwImg.src = pwSrc;
	currentLoadImg = pwImg;
	setTimeout(pwCheckLoad, 3);
}

function pwCheckLoad(){
	if(currentLoadImg == null) return;
	if(currentLoadImg.complete){
		pwId = currentLoadImg.id.replace("_temploader", "");
		//pwAddDebug("loaded: " + pwId);
	    pwObj(pwId).src = currentLoadImg.src;
	    currentLoadImg = null
	}
	else
		setTimeout(pwCheckLoad, 3);
}
*/

var pwSoundObj = null;


function pwPlaySound(pwSoundId, pwType, pwSoundFile){
    if(!pwSoundObj)
		pwSoundObj = pwObj(pwSoundId);
    if(!pwSoundObj){
		pwSoundObj = document.createElement(pwType);
		//pwSoundObj.onreadystatechange
		pwSoundObj.id = pwSoundId;
		document.body.appendChild(pwSoundObj);	
	}
	if(pwSoundObj.src != pwSoundFile){
		pwSoundObj.src = pwSoundFile;
	}
	try{
		pwSoundObj.play();
		played = true;
	}
	catch(err){
		try{
			var pwNewId = pwReplaceString(pwSoundId, "Embed", "Sound");
			pwSoundObj = pwObj(pwNewId);
			pwSoundObj.src = pwSoundFile;
		}
		catch(err2){
		}
	}
}


function pwPlayFlashSound(pwSoundFile){
   var pwSoundObj = window.document.PWSound;
   if(typeof(pwSoundObj.length) != "undefined")
      pwSoundObj = pwSoundObj[0];
   pwSoundObj.LoadMovie(-9999,"Dart.PowerWEB.LiveControls.GetResource.aspx?Res=PwSound.swf");
   var pwSoundLoaded = false;
   while (!pwSoundLoaded){
      if (pwSoundObj.PercentLoaded() == 100)
		pwSoundLoaded = true;
   }
   pwSoundObj.Play();
   pwSoundObj.SetVariable("_root.pwUrl", pwSoundFile);
   pwSoundObj.GotoFrame(9);
}

var pwFlashObj = null;
var pwFlashScript = "";
var pwFlashViewState = "";
var pwFlashHandled = false;
function pwSendFlashCallback(pwRequest, pwUrl){
	//alert(pwUrl);
   pwFlashObj = pwRequest.flash;
   if(typeof(pwFlashObj.length) != "undefined") pwFlashObj = pwFlashObj[0];
   //pwFlashObj.StopPlay();
   //pwFlashObj.GotoFrame(1);
   pwFlashObj.SetVariable("_root.url", pwUrl);
   pwFlashObj.SetVariable("_root.requestID", pwRequest.id);
   pwFlashHandled = false;
   pwFlashObj.Play();
   setTimeout(pwCheckFlashData, 5);
}

function pwCheckFlashData(){
      pwFlashViewState = pwFlashObj.GetVariable("_root.viewState");
      pwFlashScript = pwFlashObj.GetVariable("_root.script");
      var requestId = pwFlashObj.GetVariable("_root.requestID");
	  if(typeof(pwFlashViewState) != "undefined" && pwFlashViewState != "undefined" && pwFlashViewState != "" && pwFlashViewState != null && pwFlashHandled == false){
		//alert(pwFlashViewState);
		//alert(pwFlashScript);
	    pwFlashObj.StopPlay();
	    pwFlashObj.GotoFrame(0);
	    pwFlashObj.SetVariable("_root.url", "");
	    pwFlashObj.SetVariable("_root.script", "");
	    pwFlashObj.SetVariable("_root.viewState", "");
	    pwFlashHandled = true;
	    
	    // unencode any encoded strings...including encoded HTML entities
	    pwFlashViewState = pwReplaceString(pwFlashViewState, "%2B", "+");
	    pwFlashScript = pwReplaceString(pwFlashScript, "%2B", "+");
	    pwFlashScript = pwReplaceString(pwFlashScript, "#pwpercentatt#", "%\"");
	    pwFlashScript = pwReplaceString(pwFlashScript, "#pwpercentsty#", "%;");
	    
	    
		var entities = ["&quot;","&ldquo;","&lsaquo;","&lsquo;","&rdquo;","&rsaquo;","&rsquo;", "&nbsp;", "&lt;", "&gt;"];
		for(var i=0; i<entities.length; i++){
			var tempEntity = "#pwent" + i + "#";
			pwFlashScript = pwReplaceString(pwFlashScript, tempEntity, entities[i]);
		}
	    pwFlashScript = pwReplaceString(pwFlashScript, "\r\n", "");
	    pwFlashScript = pwReplaceString(pwFlashScript, "\t", "");
	    
	    var handlerText = "";
		var pendingRequest = pwManager.retrieveRequest(requestId);
		pendingRequest.callbackObject.rawData = pwFlashScript;// + pwViewStateDelimiter + pwFlashViewState + "";
		pendingRequest.callbackObject.data = pwTrim(pendingRequest.callbackObject.rawData);
		//pendingRequest.callbackObject.viewState = pwFlashViewState + "";
		
		if(pendingRequest.block) pwFakeUnblock(pendingRequest.caller);
		pendingRequest.clearWaitLabel();
		if(typeof(pwAfterCallback) == 'function')pwAfterCallback();
		pendingRequest.busy=false;
		eval(pendingRequest.callbackFunction + '(pendingRequest.callbackObject)');
		pendingRequest.serverEvent = '';
		pendingRequest.caller = null;
	  }
      else
	     setTimeout(pwCheckFlashData, 5);
}

function pwChangeRowStyle(pwRowId, pwStyleString){
	var pwRow = document.getElementById(pwRowId);
	if(pwRow){
		pwSetStyleString(pwRow.id, pwStyleString);
		for(var j=0; j<pwRow.cells.length; j++){
			pwSetStyleString(pwRow.cells[j].id, pwStyleString);
		}
	}
}

function pwClearRowStyle(pwRowId){
	var pwRow = document.getElementById(pwRowId);
	if(pwRow){
		pwClearElementStyle(pwRow);
		for(var j=0; j<pwRow.cells.length; j++)
			pwClearElementStyle(pwRow.cells[j]);
	}
}

function pwClearElementStyle(pwElem){
	pwElem.style.backgroundColor = "";
	pwElem.style.borderWidth = "";
	pwElem.style.borderColor = "";
	pwElem.style.borderStyle = "";
	pwElem.style.color = "";
	pwElem.style.fontFamily = "";
	pwElem.style.fontSize = "";
	pwElem.style.fontStyle = "";
	pwElem.style.fontWeight = "";
	pwElem.style.textDecoration = "";
}

function pwToggleRowVisibility(pwGridId, pwRowIndex, pwDisplay){
	var pwRow = pwRowObj(pwGridId, pwRowIndex);
	if(!pwRow)return;
	pwRow.style.display = pwDisplay;
		
}

function pwRowObj(pwGridId, pwRowIndex){
	var pwGrid = pwObj(pwGridId);
	if(!pwGrid) return null;
	return pwGrid.rows[pwRowIndex];
}

function pwCellObj(pwGridId, pwRowIndex, pwCellIndex){
	var pwRow = pwRowObj(pwGridId, pwRowIndex);
	if(!pwRow)return null;
	return pwRow.cells[pwCellIndex];
}

function pwSetStyleString(pwControlId, pwPropString){
	if(!pwControlId) return;
	var pwControl = null;
	if(typeof(pwControlId) == "string")
		pwControl = pwObj(pwControlId);
	else if(typeof(pwControlId) == "object")
		pwControl = pwControlId;
	if(!pwControl) return;
	//Format of property string is like: "color='Blue';font-style='italic'"
	//Process .style properties first
	var pwPropItems = pwPropString.split(';');
	for(var i=0; i<pwPropItems.length; i++){
		try{
			eval("pwControl." + pwPropItems[i]);
		}
		catch(err){
			//err evaluating expression
		}
	}
	/*
	// If it is a table, need to apply styles to rows.
	if(pwControl.tagName == "TABLE"){
		for(var i=0; i<pwControl.rows.length; i++){
			pwSetStyleString(pwControl.rows[i], pwPropString);
			for(var j=0; j<pwControl.rows[i].cells.length; j++)
				pwSetStyleString(pwControl.rows[i].cells[j], pwPropString);
		}
	}
	*/
}
