﻿// Gets a unique identifier based on the current date/time in milliseconds. Should always be unique..
function GetUniqueIdentifier()
{
    return new Date().getTime();
}

// Reusable control focus method
function SetDefaultFocus(sFocusElementID) 
{ 
    if (!sFocusElementID)
	    sFocusElementID = 'SearchTextBox';
	
	if (document.getElementById(sFocusElementID))
	    if (document.getElementById(sFocusElementID).disabled == false)
	        document.getElementById(sFocusElementID).focus();
} 

// MM Note: This works for any control, not just DIVs..
function hideDIV(elementID) 
{
	if (document.getElementById(elementID)) 
	{
		document.getElementById(elementID).style.display = 'none';
		//MM: Generally, I've found that these should be used together
		document.getElementById(elementID).style.visibility = 'hidden';
	}
	return;
}

// MM Note: This works for any control, not just DIVs..
function showDIV(elementID, pbUseInline) 
{
    if (pbUseInline == undefined)
        pbUseInline = false;

	if (document.getElementById(elementID)) 
	{
	    //MM: At times, 'inline' needs to be used instead of 'block'...
	    if (pbUseInline)
		    document.getElementById(elementID).style.display = 'inline';
		else
		    document.getElementById(elementID).style.display = 'block';
		    
		//MM: Generally, I've found that these should be used together
		document.getElementById(elementID).style.visibility = 'visible';
	}
	return;
}

// Experimental DIV hide/show code, not currently being used for anything..
/*function toggleVisible(id,headingid,hidetext,showtext) 
{
	if (document.getElementById(id).style.display == '') {
		document.getElementById(id).style.display = 'none';
		eval(headingid).innerHTML = '<a href="javascript:toggleVisible(\'' + id + '\',\'' + headingid + '\',\'' + hidetext + '\',\'' + showtext + '\');">' + showtext + '</a>';
	}
	else {
		document.getElementById(id).style.display = '';
		eval(headingid).innerHTML = '<a href="javascript:toggleVisible(\'' + id + '\',\'' + headingid + '\',\'' + hidetext + '\',\'' + showtext + '\');">' + hidetext + '</a>';
	}
}*/

function CloseCurrentWindow()
{
    window.close();
}

// Opens a centered browser window.
function openCenteredWindowLite(sURL, iWidth, iHeight) 
{
    openCenteredWindowV2(sURL, iWidth, iHeight, '');
/*	var iLeft = (screen.width - iWidth) / 2;
	var iTop = (screen.height - iHeight) / 2;
	var sWindowName = 'UserWindow' + GetUniqueIdentifier();
	
	var sFeatures = 'left=' +iLeft +',top=' +iTop +',width=' +iWidth +',height=' +iHeight +',scrollbars=no,resizable=no';
	var oWindowHandle = window.open(sURL, sWindowName, sFeatures);

	if (!oWindowHandle || !oWindowHandle.top)
	    alert('Error, the application is trying to open a new window, but your browser is blocking it.\nPlease disable any pop-up blockers for this site, and try the action again.');
*/	    
}

// Opens a centered browser window.
function openCenteredWindow(sURL, iWidth, iHeight) 
{
    openCenteredWindowV2(sURL, iWidth, iHeight, '');
/*    if (iWidth > screen.width)
        iWidth = screen.width - 2;
    
    if (iHeight > screen.height)
        iHeight = screen.height - 2;

	var iLeft = (screen.width - iWidth) / 2;
	var iTop = (screen.height - iHeight) / 2;
	var sWindowName = 'UserWindow' + GetUniqueIdentifier();
	
	sFeatures = 'left=' +iLeft +',top=' +iTop +',width=' +iWidth +',height=' +iHeight +',scrollbars=yes,resizable=yes';
	var oWindowHandle = window.open(sURL, sWindowName, sFeatures);

	if (!oWindowHandle || !oWindowHandle.top)
	    alert('Error, the application is trying to open a new window, but your browser is blocking it.\nPlease disable any pop-up blockers for this site, and try the action again.');
*/	    
}

// Opens a centered browser window.
function openCenteredWindowV2(sURL, iWidth, iHeight, sCustomOptions) 
{
    if (iWidth > screen.width)
        iWidth = screen.width - 2;
    
    if (iHeight > screen.height)
        iHeight = screen.height - 2;

	var iLeft = (screen.width - iWidth) / 2;
	var iTop = (screen.height - iHeight) / 2;
	var sWindowName = 'UserWindow' + GetUniqueIdentifier();

	if (sCustomOptions == '' || sCustomOptions == undefined)
		sCustomOptions = 'scrollbars=yes,resizable=yes';

	sFeatures = 'left=' +iLeft +',top=' +iTop +',width=' +iWidth +',height=' +iHeight +',' +sCustomOptions;
	var oWindowHandle = window.open(sURL, sWindowName, sFeatures);

	if (!oWindowHandle || !oWindowHandle.top)
	    alert('Error, the application is trying to open a new window, but your browser is blocking it.\nPlease disable any pop-up blockers for this site, and try the action again.');
	else 
	{
	    if (!oWindowHandle.opener) 
	        oWindowHandle.opener = self;
	    
	    // Set focus on new window...
	    if (window.focus) 
	        oWindowHandle.focus();
	    
	    // *** This next line was breaking things :(
	    //return oWindowHandle;
	}
}

// FUTURE: NOT FINISHED!
/*
function openCenteredWindowV3(sURL, sWindowName, iWidth, iHeight, sOptions)
{
    var newwindow = '';

	if (!newwindow.closed && newwindow.location)
	{
		newwindow.location.href = url;
	}
	else
	{
		newwindow = window.open(url,'name','height=200,width=150');
		if (!newwindow.opener) 
		    newwindow.opener = self;
	}
	
	if (window.focus) 
	    newwindow.focus();
	
	return false;
}
*/

function OpenGenericRichTextEditor(sFieldFrom, sFieldTo)
{
    openCenteredWindowV2(appRootRelativePath + '/Common/GenericRichTextEditor.aspx?FieldFrom=' + sFieldFrom + '&FieldTo=' + sFieldTo, 750, 350, '');
}

// This function (for IE only) will copy a field's contents to the Windows Clipboard.
function copytoCB(theField) 
{
	var tempval=eval('document.'+theField);
	tempval.focus();
	tempval.select();
	if (document.all){
		therange=tempval.createTextRange();
		therange.execCommand('Copy');
	}
}

//this code is not used for anything.
/*function datagrid_KeepHeaderAtTopOfDIV(sDIVName, sDatagridName)
{
    if (!document.getElementById(sDIVName))
        return false;
   
    if (!document.getElementById(sDatagridName))
        return false;
    
    var oFirstLevel = document.getElementById(sDatagridName);
    if (oFirstLevel.firstChild)
    {
        // check for children
        var oTBODY = oFirstLevel.firstChild;
        while(oTBODY)
        {
            //nodeType 1 = HTML Tag
            //nodeType 2 = HTML Tag Attribute
            //nodeType 3 = Text           
        
            if(oTBODY.nodeType == 1)
            {                                                                                                                              
                var oTR = oTBODY.firstChild;
                while(oTR)
                {                 
                    if (oTR.nodeType == 1)
                    {
                        if (oTR.tagName == 'TR') 
                        {
                            //alert('triggered');
                            oTR.style.position = 'relative';
                            oTR.style.backgroundColor = 'white';
                            oTR.style.zindex = 10;
                            oTR.style.top = document.getElementById(sDIVName).scrollTop;                               
                            //break;                                            
                            return;
                        }                        
                    }
                    oTR = oTR.nextSibling;                   
                }                    
            }
            oTBODY = oTBODY.nextSibling;
        }        
    }        
}*/

function SetCursorToDefault()
{    
    document.body.style.cursor = 'default';
}

function SetCursorToHourglass()
{    
    document.body.style.cursor = 'wait';
}

/*
function AttachLinkDisableOnClick(poObject)
{
    if (poObject.onclick != null)
    {
        alert('js:AttachLinkDisableOnClick:: Warning, ' + poObject.id + ' already has an onclick event!');
    } 
    
    poObject.onclick = DisableLinkOnClick;  
}

function DisableLinkOnClick(e)
{
	if (!e) var e = window.event;
	// e gives access to the event in all browsers
    if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;		    
    
    DisableLink(targ);
    
    SetMessageLineToPleaseWait();
    
    SetCursorToHourglass();
}

function DisableLink(pObject)
{
    pObject.disabled = true;
    pObject.onclick = null;        
    //targ.innerHTML = 'please wait...';    
    
    // set the href of the link after 1 second. this allows the "postback" to occur. otherwise javascript instantly changes the href, and the original
    // href never gets activated.
    setTimeout('document.getElementById(\'' + pObject.id + '\').href = \'javascript:void(0);\'',1000);    
}

function SetMessageLineToPleaseWait()
{
    if (document.getElementById('MessageLine'))
    {
        document.getElementById('MessageLine').innerHTML = '&nbsp;&nbsp;Please wait...';
    }  
}
*/

// ************************************************************************************************************************************************************
// ************ POSTBACK FUNCTIONS ****************************************************************************************************************************
// ************************************************************************************************************************************************************

// Allows you to perform a generic postback of the given SubmitType
function GenericPostback(psSubmitType)
{
	var oForm;
	oForm = document.forms[0];
	    
    document.getElementById('SubmitType').value = psSubmitType;
    oForm.submit();
}

// Attaches the enter key to an object (usually a textbox), triggering the specified SubmitType when enter is pressed inside.
function AttachEnterKeyPostback(poTextBoxObject, psSubmitType)
{    
    poTextBoxObject.onkeypress = function(event){        
        if (is_ie) {
            if (window.event && window.event.keyCode == 13)
            {
                GenericPostback(psSubmitType);
                return false;
            } else {
                return true;
            }
        } else {
            if (event && event.which == 13)
            {
                GenericPostback(psSubmitType);
                return false;
            } else {
                return true;                
            }
        }
    };
}

function AttachEnterKeyEventTrigger(poTextBoxObject, psStatementToEval)
{
    poTextBoxObject.onkeypress = function(event){        
        if (is_ie) {
            if (window.event && window.event.keyCode == 13)
            {
                eval(psStatementToEval);
                return false;
            } else {
                return true;
            }
        } else {
            if (event && event.which == 13)
            {
                eval(psStatementToEval);
                return false;
            } else {
                return true;                
            }
        }
    };
}

/********************************************************************************************************************
// Matt Major - 10.12.2004
// function LimitMaxLength(object poField, int piCharLimit, bool pbShowAlert)
// Implementation:
// html: <input onkeypress="return LimitMaxLength(this, nLimit, true" ...> 
// server-side: MemoEditBox.Attributes.Add("onkeypress","return LimitMaxLength(this,40,false);")
// javascript: document.id.attributes.add('onkeypress','return LimitMaxLength(this, int CharLimit, bool ShowAlert) 
*********************************************************************************************************************/
function LimitMaxLength(poField, piCharLimit, pbShowAlert) 
{
    if (poField.value.length + 1 > piCharLimit)
    {
        poField.value = poField.value.substring(0, piCharLimit);
        
        if (pbShowAlert)
            alert('This field has a ' +piCharLimit +' character limit')
            
        return false;
    }
    else
        return true;
} 


function RTFLimitMaxLength(poField, piCharLimit, pbShowAlert) 
{
    if (poField.length + 1 > piCharLimit)
    {
        poField = poField.substring(0, piCharLimit);
        
        if (pbShowAlert)
            alert('This field has a ' +piCharLimit +' character limit')
            
        return false;
    }
    else
        return true;
} 

// from http://www.quirksmode.org/dom/maxlength.html
// Simply call setMaxLengthOnTextAreas() and all TextArea's with MaxLength defined will get automatically set up to have a max length validation.

function setMaxLengthOnTextAreas() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			x[i].onkeyup = x[i].onchange = checkMaxLengthOnTextArea;
			x[i].onkeyup();
		}
	}
}

function checkMaxLengthOnTextArea() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength)
	    this.value = this.value.substring(0, maxLength);
}

// from http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
// All it does is add a couple of div elements to the document and actually measure widths with and without the
// scroller. But I was pretty excited to be able to grab that value correctly and reliably for Safari, as well 
// as for Firefox on Linux and on Windows -- with both the XP "Hasbro" look and the old-skool Soviet-bloc style.
function getScrollerWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}

function selectElement (element) {
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(element);
    range.select();
  }
  else if (window.getSelection) {
    var range = document.createRange();
    range.selectNodeContents(element);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
 }
}

// Used to generically create an ActiveX object on the page. This is needed in order to get around the lame Microsoft/Eolas patent dispute, and the "click to activate control" nonsense.
function CreateActiveXObject(sDivId, sObjectId, iWidth, iHeight, sCodebase, sClassId, sParameters)
{
    var oDIV = document.getElementById(sDivId);
    oDIV.innerHTML = '<object id="' + sObjectId + '" ' + 'width="' + iWidth + '" ' + 'height="' + iHeight + '" ' + 'codebase="' + sCodebase + '" ' + 'classid="' + sClassId + '" ' + 'VIEWASTEXT>' + sParameters + '</object>';
}

function SelectDropDownOptionByValue(poDropDown, psValue)
{
	for (var j = poDropDown.length - 1;j > -1;j--) {
		if (poDropDown.options[j].value == psValue) {
			poDropDown.options[j].selected = true;
		}
	}
}

function SelectDropDownOptionByText(poDropDown, psText)
{
	for (var j = poDropDown.length - 1;j > -1;j--) {
		if (poDropDown.options[j].text == psValue) {
			poDropDown.options[j].selected = true;
		}
	}
}