// If New Tab/Window is used, window.name is empty. Redirect to the
// default page to display the invalid access message.
if (window.name == "") {

    // Make sure the window.name is empty. If user type in the URL again,
    // and the Request.UrlReferrer method did not catch the error if the
    // page is cached, this will also catch the error.
    window.name = "";  
    window.open("default.aspx?InvalidAccess=1", "_self");
    // Starting from IE7, closing the window that the program did
    // not open will cause the brower to display the message "The
    // webpage you are viewing is trying to close the window. Do you
    // want to close the window?". Therefore using the method below
    // will not work well as user can still select NO to access
    // the RSWebNET page.
    //      alert("Invalid access. Please close the window.");
    //      window.close();
}


/********************************************************************
Adds an event listener to an html element.
********************************************************************/
function rsweb_addEventListener(obj,eventName,callbackFunction,flag)
{ 
	if (obj.addEventListener)
		obj.addEventListener(eventName,callbackFunction,flag);
	else if (obj.attachEvent)
		obj.attachEvent("on"+eventName,callbackFunction);
	else
		eval("obj.on"+eventName+"="+callbackFunction);
}

/********************************************************************
Set focus to specified control. Handles Infragistics controls.
********************************************************************/
function rsweb_SetFocus(ctrl)
{
	// First try Infragistic edit controls.
	try
	{
		var edit = igedit_getById(ctrl);
		if(edit != null && typeof(edit) != 'undefined')
		{
			//edit.elem.focus();
			edit.focus();
			return ;
		}
	}
	catch (e)
	{
	}

	// Now try our account control.
	try
	{
		var acct = rsaccount_GetAcctObjByID(ctrl);
		if (acct != null && !acct.disabled && typeof(acct) != 'undefined')
		{
			// Set focus to 1st edit control.
			acct.focus(0);
			return ;
		}
	}
	catch (e)
	{
	}
	
	// Next try standard control.
	var control = document.getElementById(ctrl);
	if(control.type == 'hidden' || control.disabled ||
			(!control.isTextEdit && control.tagName != "SELECT"))
		control = rsweb_getNextElement(control);

    // If isTextEdit = true and control.type = 'button', f.select() cannot be used
    // and will cause javascript error.
    if (control.isTextEdit && control.type != 'submit' && control.type != 'button') 
	{
        // For selecting text in a text edit control
        var f = control.createTextRange();
        f.select();
    }
    try
    {
        control.focus();
    }
    catch(e)
    {
    }
	
}

/********************************************************************
Get next control in the TAB sequence. Based on code taken from
	http://www.faqts.com/knowledge_base/view.phtml/aid/995/fid/129
	
Parameters:
	field		Control to which you wish to return the next tab
				control.
********************************************************************/
function rsweb_getNextElement(field)
{
	var fieldFound = false;
	for (var e = 0; e < document.all.length; e++)
	{
		if (fieldFound && document.all[e].type != 'hidden' && !document.all[e].isDisabled && document.all[e].isTextEdit)
			return document.all[e];
		if (field.id == document.all[e].id)
			fieldFound = true;
	}
	return field;
}

/********************************************************************
Map the <Enter> key to a button press.

Parameters:
	buttonID			button control ID to press

********************************************************************/
function rsweb_KeyDownHandler(buttonID)
{ 
	// Process only the Enter key 
	if (event.keyCode == 13 || event.keyCode == 10)
	{
		if (event.srcElement.type != 'textarea' || event.ctrlKey)
		{
			// Cancel the default submit 
			event.returnValue=false;
			event.cancel = true; 
			// Submit the form by programmatically clicking the specified button 
			var button=document.getElementById(buttonID);
			button.click();
		}
	} 
}

/********************************************************************
Cancel the current event

Parameters:
	e			event object

********************************************************************/
function rsweb_CancelEvent(e)
{
	if (!e) var e = window.event;
	
	if(document.all)
	{
		e.cancelBubble=true;
		e.returnValue=false;
		return true;
	}
	else
	{
		e.stopPropagation();
		e.preventDefault();
		return false;
	}
}

function rsweb_OnSubmit()
{
	if (typeof(showClockOnSubmit) != "undefined" && showClockOnSubmit)
	{
		// Make page invisible.
		document.forms[0].style.display='none';

		// If new page takes more than 2 seconds to display,
		// display the please wait form.
		setTimeout('rsweb_DisplayPleaseWaitForm()', 2000);
	}
}

function rsweb_DisplayPleaseWaitForm()
{
	if (document.forms['PleaseWaitFormFrame'] != null)
    {
		document.forms['PleaseWaitFormFrame'].style.display='inline';
		frame = document.getElementById('PleaseWaitFrame');
		frame.src= 'PleaseWaitProgress.html?msg=' + TxtPleaseWait;
    }
    
}

function rsweb_Submit()
{
	rsweb_OnSubmit();

	this._submit();
}
/********************************************************************
Close all RSDropDown combo currently opened before other types of 
dropdown is shown, such as datechooser.  
*********************************************************************/
function rsweb_CloseRSDropDown(closeDateDropDown)
{
    if((typeof(rsdropdownaccountIds) == "object" && rsdropdownaccountIds != null) 
        || (typeof(rsWebcombo_comboState) == "object" && rsWebcombo_comboState != null))
    {
        rsWebcombo_closeAllDropDowns(window.event);
    }
    if((typeof(rsAjaxGridcombo_comboState) == "object" && rsAjaxGridcombo_comboState != null))
            rsAjaxGridcombo_closeAllDropDowns(window.event);
            
    // also close date chooser drop downs if any exist on page
    if (typeof(igdrp_getComboById) != "undefined" &&
			(typeof(closeDateDropDown) == "undefined" || closeDateDropDown))
    {
		for (var id in document.all)
		{
			var igDate = igdrp_getComboById(id);
			
			if (typeof(igDate) != "undefined" && igDate != null)
			    //igdrp_getComboById() also returns the input object of the combo and
			    //since the input object doesn't have setDropDownVisible() method so an
			    //exception is thrown.  Fix: add a condition to select the calendar combo
			    //before calling it's method
			    if(igDate.Calendar != 'undefined' && igDate.Calendar != null) 
				    igDate.setDropDownVisible(false);
		}
    }
}
/*******************************************************************************
Reset timeout to original value.

Kept for backwards compatibility.
*******************************************************************************/
function rsweb_ResetTimeout(forceReset)
{
    OSI.RSWebNET.resetTimeout(forceReset);
}

/*******************************************************************************
Update timeout to actual value.

Kept for backwards compatibility.
*******************************************************************************/
function rsweb_UpdateTimeout()
{
    OSI.RSWebNET.updateTimeout();
}

function rsweb_TimeoutExpired()
{
	if (typeof(rsfooter_Timer) == 'function')
		return rsfooter_TimeoutExpired();

	// No footer exists, so it is not known whether the timeout
	// has expired. Just return false in this case.
	return false;
}

/********************************************************************
Returns XMLHttpRequest object based on the current browser.
Returns null if could not allocate.
********************************************************************/
function rsweb_GetXMLHttpRequestObject() 
{
    var http_request = null;
    
    if (window.XMLHttpRequest) 
    { 
        // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) 
    { 
        // IE
        try 
        {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) 
        {
            try 
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {}
        }
    }
    
    return http_request;
}
/********************************************************************
* Convert lowercase characters to uppercase.
********************************************************************/
function rsweb_OnKeyPress(evt)
{
	if (evt.keyCode >= "a".charCodeAt(0) && evt.keyCode <= "z".charCodeAt(0))
		// Convert to uppercase
		evt.keyCode = String.fromCharCode(evt.keyCode).toUpperCase().charCodeAt(0);
}

/********************************************************************
Global variables.
********************************************************************/
var CSSMessage = "RSMessage";
var CSSError = "RSError";

/********************************************************************
The following bit of script checks to see if document.all is present,
but document.getElementById is not. If this is the case it then
assigns a new function to document.getElementById that wraps around
document.all
Taken from http://www.metalusions.com/backstage/articles/8/
********************************************************************/
if (document.all && !document.getElementById)
{
	document.getElementById = function(id)
	{
		return document.all[id];
	}
}

// If a script calls someForm.submit(), the onsubmit event does not
// fire, so we need to redefine the submit method of the
// form class.
document.forms[0]._submit = document.forms[0].submit;
document.forms[0].submit = rsweb_Submit;

/**************************textCharacterLimit***********************************/
// keep users from inputing characters more than maxlength in the textarea control
// Parameters:
// textareaId   textarea control id
// limit        textarea text maxlength
/*******************************************************************************/
function textCharacterLimit(textareaId, limit)
{
    var textAreaItemDesc = document.getElementById(textareaId);
    var evt = window.event;
    
    if (textAreaItemDesc != null)
    {
        //allow changing the highlighted text
        var oTR = document.selection.createRange();
        if(oTR)
            oTR.text = "";
        
        //--no carriage returns are allowed when the text length less than 256 characters
        //--carriage return inserts two characters  
        if(evt.keyCode == 13 && ((limit-1 < 256) || (textAreaItemDesc.value.length+1 >= limit-1)))
        {
            evt.returnValue = false;
            return;
        } 
        else if(textAreaItemDesc.value.length >= limit-1)
        {
           event.returnValue = false;
           return;
        }
    }
}
/**************************doPaste**********************************************/
// keep users from pasting characters more than maxlength in the textarea control
// Parameters:
// textareaId   textarea control id
// limit        textarea text maxlength
/*******************************************************************************/
function doPaste(textareaId, limit)
{
    event.returnValue = false;
    var oTR = document.selection.createRange();
    var insertLength = (limit - 1) - document.getElementById(textareaId).value.length + oTR.text.length;
    var iData = window.clipboardData.getData("Text").substr(0,insertLength);
    oTR.text = iData;
}
/****************************************************************************************
** The function switches the keypress event to click event and cancel keypress event
** this function is needed since the setting of buttons "CausesValidation=false" fails to  
** prevent the page from doing validation for buttons like "Cancel", "Reset"
*****************************************************************************************/
function rsweb_ButtonKeypressToClick(id)
{
   var btn = document.getElementById(id);
   btn.click();
   //cancel onkeypress event
   rsweb_CancelEvent();

}

/****************************************************************************************
** Provide delay before execution of next function. Only a small amount of delay should
** be used in most cases. Excessive delay may cause browser to display warning message.
** Parameters:
** delay   in milliseconds
*****************************************************************************************/
function rsweb_Sleep(delay) 
{
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
