﻿
/*****************************************************************************
 * This is needed due to a bug in IE6 (SP1?)
 * When the onBeforeUnload event fires due to a postback (not hyperlink),
 * and then the user hits "cancel" to stay on the page, we get "unspecified error"
 * This function will ignore "unspecified error", but allow all others to go through.
 *****************************************************************************/
function window.onerror(strError) 
{
    if (strError.toLowerCase().indexOf('unspecified error') >= 0) 
        {window.event.returnValue = true; }
    else 
        {window.event.returnValue = false; } 
} 




/*****************************************************************************
 * This function removes the leading and trailing white space from strings
 *****************************************************************************/
function TrimWhiteSpace( value )
{
	return value.replace( /^\s+|\s+$/,'' );
}

/**********************************************************************************
 * Opens a dialig box (popup windows) using the supplied parameters.
 * Opens modally if support by the browser.
 *********************************************************************************/
function OpenPopupWindow( URL, Left, Top, Width, Height )
{
    
	if( window.showModalDialog )
	{
		OpenModalDialog( URL, Left, Top, Width, Height )
	}
	else
	{
		OpenWindowModal( URL, Left, Top, Width, Height )
	}
}


/************************************************************
 * Opens a modal dialig box using the supplied parameters.
 * This function is called by OpenPopupWindow.  See OpenPopupWindow.
 ************************************************************/
function OpenModalDialog( URL, Left, Top, Width, Height )
{	
    Left = getScreenX(Left);      
    Top = getScreenY(Top);
    
	try
	{

		window.showModalDialog( URL, window.self, "dialogLeft:" + Left + "px; dialogTop:" + Top + "px; dialogWidth:" + Width + "px; dialogHeight:" + Height + "px; status:no; resizable:yes; scroll:yes;" );
	}
	catch(e)
	{
		alert( "This application requires that popup windows be enabled in your browser. Please enable popup windows for this site and try again." );
	}
}


/**********************************************************************************
 * Opens a dialig box (popup form) using the supplied parameters.
 * This function is called by OpenPopupWindow.  See OpenPopupWindow.
 *********************************************************************************/
function OpenWindowModal( URL, Left, Top, Width, Height )
{
    Left = getScreenX(Left);      
    Top = getScreenY(Top);

	var features = 'left=' + Left + 'px, top=' + Top + 'px, width=' + Width + 'px, height=' + Height + 'px,';
	features += 'titlebar=no,scrollbars=yes,fullscreen=no,modal=yes, resizable=yes';
	var childWindow = window.open( URL, '_blank', features, false );
	if (window.focus) {childWindow.focus();}
	return childWindow;
}


/**********************************************************************************
 * Opens a new standard window (non-modal)
 *********************************************************************************/
function OpenNonModalWindow( URL, Left, Top, Width, Height )
{
    Left = getScreenX(Left);      
    Top = getScreenY(Top);

	var features = 'left=' + Left + 'px, top=' + Top + 'px, width=' + Width + 'px, height=' + Height + 'px,';
	features += 'titlebar=no,scrollbars=yes,fullscreen=no,modal=no, resizable=yes';
	var childWindow = window.open( URL, '_blank', features, false );
	if (window.focus) {childWindow.focus();}
	return childWindow;
}

/********************************************************************************************
 * Translates X-Coordinate to make it relative to the client window, not the screen/monitor.
 * Need to test functionality in FireFox and on multi-screen monitor configurations
 ********************************************************************************************/
function getScreenX(xOffset)
{
    if (window.screenLeft)
    {
        return window.screenLeft + xOffset;
    }
    else if (window.screenX)
    {   // not tested:
        return window.screenX + xOffset;
    }
    else return xOffset;
}


/********************************************************************************************
 * Translates Y-Coordinate to make it relative to the client window, not the screen/monitor.
 * Need to test functionality in FireFox and on multi-screen monitor configurations
 ********************************************************************************************/
function getScreenY(yOffset)
{
    if (window.screenTop)
    {
        return window.screenTop + yOffset;
    }
    else if (window.screenY)
    {   // not tested:
        return window.screenY + yOffset;
    }
    else return yOffset;
}

/*****************************************************************************
 * Use this function for getting values out of the querystring
 *****************************************************************************/
function QueryString( src )
{
	var q = document.location.href.split( '?' );
	if( q.length == 1 ) return "";
	q1 = q[1].split( '&' );
	
	for( x = 0; x < q1.length; x++ )
	{
		q2 = q1[x].split( '=' );
		if( q2[0] == src ) return q2[1];
	}
	return "";
}

 
/************************************************************************************
 * This function limits the amount of text that can be TYPED into a multiline textbox
 * (SEE THE NEXT FUNCTION)
 ************************************************************************************/ 
function limitTextboxChars(limitField, limitNum) 
{	
    var IsIE = ( navigator.appName.indexOf( "Microsoft" ) != -1 );
	if (!IsIE) return true;  // not tested in other browsers
	if(limitField.value.length >limitNum - 1) 
	{	
		return false; 
	}
	else 
	{ 
		return true;
	} 
}

/**************************************************************************************
 * This function limits the amount of text that can be PASTED into a multiline textbox
 * (SEE THE PREVIOUS FUNCTION)
 **************************************************************************************/ 
function limitTextboxPaste(limitField,limitNum)
{	
    var IsIE = ( navigator.appName.indexOf( "Microsoft" ) != -1 );
	if (!IsIE) return true;  // not tested in other browsers
	var sData = window.clipboardData.getData("Text");
	var CanInsertLength = limitNum - limitField.value.length ; 

	if(CanInsertLength <= 0)
	{
		return false;
	}
	else
	{
		var newData = sData.substr(0,CanInsertLength);
		window.clipboardData.setData("Text",newData);
		return true; 
	}
}


/********************************************************************************************
*  USED WITH DEBUGGING JAVASCRIPT - LOGS DEBUG/TRACE MESSAGES TO A NEW POPUP WINDOW
********************************************************************************************/
function logMessage(message, showTime) 
{
    if (showTime == null) showTime = true;
    
    var loggingEnabled = true; // change to false to turn off logging, true to turn on logging
    if (loggingEnabled)
    {
        if (showTime)
            message = Date() + " ---- " + message;
        
        if (!logMessage.window_ || logMessage.window_.closed) {
            var win = window.open("", null, "width=400,height=200, scrollbars=yes,resizable=yes,status=no, location=no,menubar=no,toolbar=no");
            if (!win) return;
            var doc = win.document;
            doc.write("<html><head><title>Debug Log</title></head><body></body></html>");
            doc.close();
            logMessage.window_ = win;
        }
        var logLine = logMessage.window_.document.createElement("div");
        logLine.appendChild(logMessage.window_.document.createTextNode(message));
        logMessage.window_.document.body.appendChild(logLine);
    }
}

/* Use this function to dump all properties of an object to the logMessage window */
/* TODO: make recursive, evaluate functions, lots of ways to enhance              */
function logObject(obj)
{
    for(var i in obj)
    {
        logMessage('  ' + i + ' :: ' + new String(obj[i]).substr(0,100) + '\r\n', false);
    }
}

/*************************************************************************************************************
*  FINDS ALL LISTBOXES (html <select>) ON A PAGE and scrolls them so that the first selected item is visible
*  USAGE:  Call this script when page first loads to fix all listboxes on the page.
***************************************************************************************************************/
function scrollListBoxesToSelectedIndex()
{
    var listBoxes = document.getElementsByTagName("select");
    if (listBoxes != null)
    {
        for (var i=0; i<listBoxes.length; i++)
        {
            if (listBoxes[i].multiple == true)
                if (listBoxes[i].selectedIndex > 0)
                {
                    listBoxes[i].selectedIndex = listBoxes[i].selectedIndex;
                }
        }
    }
    listBoxes = null;
}


/*************************************************************************************************************
*  Displays access keys for buttons when Alt is pressed
*  USAGE:  Call this script when page first loads to fix all listboxes on the page.
***************************************************************************************************************/
function displayAccessKeys(e)
{
    if (!e) e = window.event;
    if (e.keyCode == 18)
    {
        toggleAccessKeys();
        document.onkeydown = null;
        document.onkeyup = hideAccessKeys;
    }
}

function hideAccessKeys(e)
{
    if (!e) e = window.event;
    if (e.keyCode == 18)
    {
        toggleAccessKeys();
        document.onkeyup = null;
        document.onkeydown = displayAccessKeys;
    }
}

function toggleAccessKeys()
{
    var spans = document.getElementsByTagName('span');
    var text = ''; 
    var showText = document.getElementById('spanAccessKeys');
    for (var k=0;k<spans.length;k++)
    {
        if (spans[k].className == 'accessKey' )
        {
            text = text + spans[k].innerHTML + '<br>';
        }
    }
       
    showText.innerHTML = text;
    
//  if (text != '')
//  {
        if ( 'inline' != showText.style.display)
               { showText.style.display = 'inline'; }
        else
              {  showText.style.display = 'none';   }     
             
//  }     
}


/*************************************************************************************************************
*  LISTBOX FUNCTIONS
***************************************************************************************************************/
/* This function will return true if the given value is selected in the given listbox */
function listboxIsSelected(lst, id)
{
    // if no selections are made, then that is the same as *all* selections.  Always return true.
    if (lst.selectedIndex == -1) return true;
        
    // return true if the given id is selected in the given listbox.
    var count = lst.options.length;
    for(var i=count-1; i>=0; i-- )
        if( lst.options[i].selected & lst.options[i].value == id )
            return true;
}
        
/* This function will add a new item to a listbox */
function listboxAdd(lst, id, text)
{
    var opt = new Option(text);
    opt.value = id;
    opt.description = text;
    lst.options[lst.options.length] = opt;
}

        
/* This function will clear the items from a listbox */        
function listboxClear(lst)
{
    var count = lst.options.length;
    for(var i=count-1; i>=0; i-- )
	    lst.options.remove(i);        
}   


// takes the selected item in a list and swaps it with the item above it (moves it up in the list by one line).
function listboxMoveItemUp(lst)
{
    if (lst.selectedIndex > 0)
    {
        // swap option w/ the one above it
        var selectedIndex = lst.selectedIndex;
        var selectedOption = lst.options[selectedIndex];
        var prevOption = lst.options[selectedIndex - 1];
        
        var saveValue = prevOption.value;
        var saveText = prevOption.text;               
        prevOption.value = selectedOption.value;        
        prevOption.text = selectedOption.text;
        selectedOption.value = saveValue;
        selectedOption.text = saveText;
        
        lst.selectedIndex = selectedIndex - 1;
    } 
}

// takes the selected item in a list and swaps it with the item below it (moves it down in the list by one line).
function listboxMoveItemDown(lst)
{
    if (lst.selectedIndex < lst.options.length - 1)
    {
        // swap option w/ the one above it
        var selectedIndex = lst.selectedIndex;
        var selectedOption = lst.options[selectedIndex];
        var nextOption = lst.options[selectedIndex + 1];
        
        var saveValue = nextOption.value;
        var saveText = nextOption.text;               
        nextOption.value = selectedOption.value;        
        nextOption.text = selectedOption.text;
        selectedOption.value = saveValue;
        selectedOption.text = saveText;
        
        lst.selectedIndex = selectedIndex + 1;
    } 

}

// Select an item in a list, searching by listitem value
function listboxSelectByValue (lst, value)
{
    for (var i=0; i<lst.options.length; i++)
    {
        if (lst.options[i].value == value)
        {
            lst.selectedIndex = i;
            break;
        }
    }
}

// Select an item in a list, searching by listitem text
function listboxSelectByText (lst, text)
{
    for (var i=0; i<lst.options.length; i++)
    {
        if (lst.options[i].text == text)
        {
            lst.selectedIndex = i;
            break;
        }
    }
}


/********************************************************************************************

 * This function will compare two dates and return false if date1 comes after date2.

 ********************************************************************************************/

function compareDates(strDate1, strDate2)

{   
      try
      {
            // only continue w/ comparison if each field has a value
            if ((strDate1.length == 0) | (strDate2.length == 0))
            {
                  return true;
            }
            
            var date1 = new Date(strDate1);
            var date2 = new Date(strDate2);

            if (isNaN(date1) | isNaN(date2))
            {
                return false;
            }
 
            if (date2.valueOf() < date1.valueOf())
            {
               return false;
            }
            
            return true;

      }
      catch(e)
      {   // test fails if any errors occur
            return false;
      }

}  

 /********************************************************************************************

 * This function will verify if the specified string is  a date. 

 ********************************************************************************************/

function validateDateFormat(value)
{
    
    try

      {

        if (value.length == 0)
        {
            return true;
        }
        
        date1 = new Date(value);
        
        if ( !date1) return false;
        if (isNaN(date1) ) { return false; }

        return true;
     }

      catch(e)

      {   // test fails if any errors occur

            return false;

      }


}

// Copies the text (specified in textToCopy) to the clipboard
// NOTE: Only the IE specific code has been tested
function copyToClipBoard(textToCopy)
{
    if (window.clipboardData) // Internet Explorer
    {
        //alert("Text to Copy: " + textToCopy);
        try
        {
			window.clipboardData.setData("Text", textToCopy);
	    	alert("Text successfully copied to clipboard:\n\n" + textToCopy);
	    }
		catch(e)
		{
            alert("Failed to copy text to clipboard.\n\n" + e);
        }
    }
    else 
    {   
        //if (window.netscape) // Netscape (Untested in PDS)
        //{ 
        //    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

        //    var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        //    
        //    if (!clip) return;

        //    var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);

        //    if (!trans) return;

        //    trans.addDataFlavor('text/unicode');

        //    var str = new Object();
        //    var len = new Object();

        //    var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

        //    var copytext=textToCopy;

        //    str.data=copytext;

        //    trans.setTransferData("text/unicode",str,copytext.length*2);

        //    var clipid=Components.interfaces.nsIClipboard;

        //    if (!clip) return false;

        //    clip.setData(trans,null,clipid.kGlobalClipboard);
        //}
        //else
        //{
            alert("Browser doesn't support copy to clipboard feature.");
        //}
    }
    return false;
}

/********************************************************************************************

 * Displays errors in custom validation summary control without postback 

 ********************************************************************************************/


//function CheckForm()
//    {
//      for (i=0; i<Page_Validators.length; i++) 
//        {
//            DisplayError(Page_Validators[i].errormessage,!Page_Validators[i].isvalid);
//        }
//      
//    }
//            
// function DisplayError(value,message)
// {
//    var s = document.getElementById('ValidationProblems').innerHTML;
//    var msg = "<LI>" + message + "</LI>";
//       if (value)
//       {
//          var matchPos1 = s.search(msg);
//          if(matchPos1 == -1) s += msg;
//       }
//       else
//       {
//         s = s.replace(msg,"");
//       }
//       
//       document.getElementById('ValidationProblems').innerHTML = s;
//       DisplayErrorPanel( s.length > 0) ;
// }
// 
// function DisplayErrorImage(value,obj)
// {
//    if(value)
//    { obj.style.display = 'inline'; }
//    else
//    { obj.style.display = 'none'; }
// }
// 
// function DisplayErrorPanel(value)
// {
//    if (value)
//    {
//        document.getElementById('SummaryValidation').style.display = 'inline';
//    }
//    else
//    {
//        document.getElementById('SummaryValidation').style.display = 'none';
//    }
//}


/***********************************************************************************************************
 * The purpose of this function is to check/uncheck all checkboxes that have the same html name attribute
 * INPUTS:
 *    chkName - the name attribute of the checkboxes to set.  Note that this will only work when
 *              all checkboxes have the same name.  Therefore, use <input type=checkbox>, not <asp:checkbox>
 *    chkState - checked or unchecked
 ***********************************************************************************************************/ 
function CheckAll( chkName, chkState )
{
    var checkboxes = document.getElementsByName(chkName);
    for (var i=0; i<checkboxes.length; i++)
        checkboxes[i].checked = chkState;
        
    event.cancelBubble = true;  // IE Only.  FireFox uses stopPropagation().  Need to get event object for FireFox.
            
}


/***********************************************************************************************************
 * These functions should work the same as the server-side functions Server.HtmlEncode and Server.HtmlDecode.
 * NOTE: They have not been thoroughly tested, so any differences in functionality should be fixed.
 ***********************************************************************************************************/ 

function HtmlEncode(str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

function HtmlDecode(str)
{
    var div = document.createElement('div');
    div.innerHTML = str.replace(/<\/?[^>]+>/gi, '');
    return div.childNodes[0].nodeValue;  // try .data if .nodeValue does not work
}
 /********************************************************************************************************************************
 * The purpose of this function is to do a postback which causes the current page to refresh.
 * The field called "RefreshFlag" is set to "true" and can be inspected in the Form_Load event of the page being refreshed.
 ********************************************************************************************************************************/
function refreshWithPostBack()
{
    var theForm = document.forms['aspnetForm'];
    if (!theForm) {theForm = document.forms[0];}

    doPostBack_AspNet('', '');
}



/********************************************************************************************
 * The purpose of this function is to mimick an ASP.Net postback: function __doPostBack()
 ********************************************************************************************/
function doPostBack_AspNet(eventTarget, eventArg)
{
    var theForm = document.forms['aspnetForm'];
    if (!theForm) {theForm = document.forms[0]; } //document.aspnetForm;}

    if (!theForm.onsubmit || (theForm.onsubmit() != false)) 
    {
        if(theForm.__EVENTTARGET) theForm.__EVENTTARGET.value = eventTarget;
        if(theForm.__EVENTARGUMENT) theForm.__EVENTARGUMENT.value = eventArg;
        theForm.submit();
    }
}
        
        
/********************************************************************************************
*  GIVEN A STRING, RETURN AN XML DOM DOCUMENT.  GREAT FOR PROCESSING XML DOCS ON THE CLIENT.  
********************************************************************************************/
function getXmlDoc(xmlDocString)
{
    if (window.ActiveXObject) 
    { 
        var xmlDom = new ActiveXObject("microsoft.xmldom"); 
        xmlDom.async = false; 
        xmlDom.loadXML(xmlDocString); 
        return xmlDom;
    }
    else 
    { 
        var domParser = new DOMParser(); 
        return domParser.parseFromString(xmlDocString, "text/xml");         
    }
}
        


/********************************************************************************************
*  RETURN A REFERENCE TO THE OPENER OF A CHILD WINDOW
********************************************************************************************/      
function GetOpener()
{
    var openerForm = null;
	
    try
    {
        // This should work if the window was opened modally by 'OpenModalDialog()' in this file.
        // This also should work any time the window was opened with window.showModalDialog(url, dialogArguments, features)
        //       as long as a reference to the parent window was passed in parameter two: dialogArguments.
        openerForm = dialogArguments; 
    }
    catch(e)
    {
        // This should work any time the window was opened non-modally by "window.open()"
        openerForm = opener; 
    }
    
    return openerForm;
}      
      
/********************************************************************************************
*  REFRESH PARENT FORM (AFTER CLOSING A POPUP).  OPTIONALLY REFRESH BY DOING A POSTBACK.
********************************************************************************************/        
function RefreshParent(boolUsePostBack)
{
    var openerForm = GetOpener();
	
    if (openerForm != null)
    {
        if (boolUsePostBack)
        {
            if (openerForm.refreshCustom)
            {   // refresh the form in a custom way by calling the "refreshCustom" function on the parent form:
                openerForm.refreshCustom();
            }
            else
            {   // refresh the form in a standard way by just doing a postback:
                openerForm.refreshWithPostBack();
            }
        }
        else
        {            
            openerForm.document.location.href = openerForm.document.location.href;  
            // note: reload() will not work because the user could get a propmt stating that information will be re-posted.
        }    
    }

}

/********************************************************************************************
*  Disable functions  
********************************************************************************************/

function disableText(obj)
{
    obj.disabled = true;
    obj.readOnly = "ReadOnly";
    obj.className = "ReadOnly";
}

function enableText(obj)
{
    obj.disabled = false;
    obj.readOnly = "";
    obj.className = "";
}

/********************************************************************************************
*  REPLACEMENT FOR JAVASCRIPT CONFIRM() FUNCTION  
********************************************************************************************/
// TODO: Still looks like crap.  Need to "pretty it up."
// DEPENDENCY:  THIS FUNCTION DEPENDS ON THE EXISTENCE OF A .JS VARIABLE CALLED, "AppRoot".  (Written out by master page)
function showConfirm( val, confirmText, cancelText )
{
	var confirm = "";
	var cancel = "";
	
	if( confirmText != null && confirmText.length > 0 )
		confirm = confirmText;
	if( cancelText != null && cancelText.length > 0 )
		cancel = cancelText;
		
	returnValue = false;
	window.showModalDialog(  AppRoot + "common/confirm.aspx?prompt=" + escape(val) + "&confirmText=" + escape(confirm) + "&cancelText=" + escape(cancel), window.self, "dialogWidth:500px; dialogHeight:200px; status:no; resizable:no; scroll:no;" );
	return returnValue;
}

/********************************************************************************************
    Use this function to disable text selection for an element.  
    Very useful in situations where normal text selection interferes with custom selection like
    when higlighting rows of a grid or highlighting items for drag&drop 
********************************************************************************************/    
function disableSelection(element) 
{
    element.onselectstart = function() {return false;};
    element.unselectable = "on";
    element.style.MozUserSelect = "none";
    element.style.cursor = "default";
}


/*************************************************************************************************
    HELPER FUNCTIONS WHEN WORKING WITH MICROSOFT EXCEL AND OUTLOOK
*************************************************************************************************/
function GetExcelInstance()
{ 
	try { var oXL = new ActiveXObject("Excel.Application"); }
	catch(e) { 	alert('There was an error exporting data to Excel.  The most likely cause is that your Web Browser security settings are set to prevent this interaction.'); }
	return oXL;
}
function ExportHtmlToExcel(html, fastMode)
{		
    if (fastMode != true)    
    {   
        // THIS WORKS GREAT, BUT IS *REALLY* SLOW WITH LARGE AMOUNTS OF DATA.  1MB COULD TAKE > 10MIN.
        
	    // remove all hyperlinks (The edit and delete columns are removed via CSS using media=print and display:none)	    
	    var re = new RegExp('(<a.*>)(.*)(</a>)', 'gi'); 
	    html = String(html.replace(re, '$2')); 						    	
    	
	    // Convert checkboxes into Y/N:
	    re = RegExp('<input .* type\=checkbox checked.*>.*', 'gi')
	    html = String(html.replace(re, 'Y')); 		
	    re = RegExp('<input .* type\=checkbox .*>.*', 'gi')
	    html = String(html.replace(re, 'N'));
	}
	

	try
	{				
		var oXL = GetExcelInstance() //new ActiveXObject("Excel.Application");
		var oBook;					
		oBook = oXL.Workbooks.Add;
		oBook.HTMLProject.HTMLProjectItems("Sheet1").Text = html;
		oBook.HTMLProject.RefreshDocument();
		oXL.Visible = true;
		oXL.UserControl = true;	
	}
	catch (e) 
	{
		//do nothing - user probably hit 'No, don't create ActiveX object'
	}
}
function ComposeEmailUsingOutlook(to, subject, body, isHTML)
{
	try 
	{ 
	    var outlook = new ActiveXObject("Outlook.Application"); 
        var message = outlook.CreateItem(0);  // 0=Mail; 1=Appointment; 2=Contact; 3=Task; 4=Journal; 5=Note; 6=Post; 7=DistList
        message.Subject = subject;
        if (isHTML) message.HTMLBody = body;    // html
        else message.Body = body;               // plain text
        if (to.length > 0) message.Recipients.Add (to);
        message.Display();
	}
	catch(e) 
	{ 	
	    alert('There was an error composing an email using Microsoft Outlook.  Make sure you have Outlook (not Outlook Express) installed and configured and that your web browser security settings are set to allow this action.'); 
	}
}
/*****************************************************************************************************************/


/*************************************************************************************************
    ENABLE OR DISABLE AN INPUT CONTROL.  WORKS WITH PDSCHECKBOX AND PDSRADIOBUTTON.
    INPUTS: id=clientId of html element; enabled = true or false;
*************************************************************************************************/
function toggleFieldEnabled(id, enabled)
{   
    var control = $get(id);
    if (control.tagName.toLowerCase() == "input")
    {        
        if (control.type.toLowerCase() == "checkbox" || control.type.toLowerCase() == "radio")
        {
            control.disabled = false; // never disable the actual checkbox or radio button to ensure they always postback their state
            control.style.display = (enabled) ? "inline" : "none";
            var img = document.getElementById(id + "_img")
            var src = img.src;
            src = src.replace("un", "");
            img.src = (control.checked) ? src : src.replace("checked", "unchecked");
            img.style.display = (enabled) ? "none" : "inline";
            var state = (enabled) ? "1" : "0";
            state += ":";
            state += (control.checked) ? "1" : "0";
            document.getElementById(id + "_state").value = state;
        }
        else
        {
            control.disabled = !enabled;
        }
    }    
}