// Add functionality to String object.
/********************************************************************
Remove whitespace from begining of string.
********************************************************************/
String.prototype.ltrim = function()
{
	//Match spaces at beginning of text and replace with a null string
	return this.replace(/^\s+/,'');
}
/********************************************************************
Remove trailing whitespace from string.
********************************************************************/
String.prototype.rtrim = function()
{
	//Match spaces at end of text and replace with a null string
    return this.replace(/\s+$/,'');
}
/********************************************************************
Remove leading and trailing whitespace from string.
********************************************************************/
String.prototype.trim = function()
{
    return this.ltrim().rtrim();
}

/********************************************************************
String format function similar to way Format works in c#.
Based on http://community.hdri.net/blogs/ray_blog/archive/2006/02/27/5.aspx
Example:
	var firstName = 'Ray';
	var lastName = 'Houston';
	
	var hello = String.format('Hello. My name is {0} {1}.', firstName, lastName);
outputs
	Hello. My name is Ray Houston.	
********************************************************************/
String.format = function()
{
	if (arguments.length == 0)
		return null;

	var str = arguments[0];

	for (var i=1;i<arguments.length;i++)
	{
		var re = new RegExp('\\{' + (i-1) + '\\}','gm');

		str = str.replace(re, arguments[i]);
	}

	return str;
}

/********************************************************************
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(control.isTextEdit && control.type != 'submit')
    {
        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. This verifies that
rsfooter_ResetTimeout() exists in case the footer is not being
displayed.


Pass true for the "forceReset" parameter if you have just
successfully returned from an AJAX call and know that the timeout
should be reset. This is in case the timeout expired message
occurred just as you were trying to reset it.
********************************************************************/
function rsweb_ResetTimeout(forceReset)
{
	if (typeof(rsfooter_ResetTimeout) == 'function')
		rsfooter_ResetTimeout(forceReset);
}

/********************************************************************
When calling alert(), the timer does not fire and does not count down.
So, if the timer is set to 15 seconds, the timer still would not fire
for 15 seconds AFTER the user has pressed OK on the Alert message.
This could be confusing if the message is left on the screen for over
15 seconds.

Call this to update the footer to reflect the actual time remaining.
timeout to original value. This verifies that rsfooter_Timer()
exists in case the footer is not being displayed.
********************************************************************/
function rsweb_UpdateTimeout()
{
	if (typeof(rsfooter_Timer) == 'function')
		rsfooter_Timer();
}

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(); 
}