﻿/******************************************************************************
* Summary: Main script for EEM. Contains various functions that are used
*          across multiple pages of the site and some basic event handling.
*****************************************************************************/

/******************************************************************************
* Variables
*****************************************************************************/
var autoHref = 0; 
var _scrollTop = 0; 
var postbackElement;
var menuItems = new Array();

var FocusControlId;
var NoScrollLinkID;
var BehaviorID;
var retry = 3;
var helpPopUp;
var bResize=true;

var skipRequiredFieldFlag = false;

/******************************************************************************
* Summary: Call this function from the Cotent pages to display Calendar 
*          window for selecting a date
*****************************************************************************/
function GetDate(oCtlId)
{
  var oCtlId = new calendar2(document.getElementById('ctl00_cphMain_' + oCtlId));
  oCtlId.year_scroll = true;
  oCtlId.time_comp = false;
  oCtlId.popup(); 
}

/******************************************************************************
* Summary: Cancels the return key "submit" functionality
*****************************************************************************/
function stopRKey(evt) { 
    var evt = (evt) ? evt : ((event) ? event : null); 
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
    if ((evt.keyCode == 13) && (node.type=="text")){return false;} 
}

/******************************************************************************
* Summary: Stops browser scrolling when an internal link is used (for JAWS).
*****************************************************************************/
function NoScrollLink(target, clearHash) { 
    anchor = target.substr(1);
    _scrollTop = document.documentElement.scrollTop;
    //document.body.style.overflow = 'hidden';
    
    if(clearHash != null && clearHash == true)
    {
        location.hash = '#';
    }
    autoHref = 1;
    location.hash = anchor;
}

/******************************************************************************
* Summary: Resets users scroll position when an internal link is used (for JAWS).
*****************************************************************************/
function ScrollHandler(e) { 
   if (autoHref == 1) { 
        autoHref = 0;
        if(CompatibleBrowser() == 0)
        {
            //location.hash = '';
            //window.status = 'incompatible browser';
        }
        if (window.event) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        }
        if (e && e.preventDefault && e.stopPropagation) {
            
            e.preventDefault();
            e.stopPropagation();
        }
        window.scrollTo(document.documentElement.scrollLeft, _scrollTop);
   }
   //document.body.style.overflow = 'visible';
}

/******************************************************************************
* Summary: Returns the version of Internet Explorer or a -1 (indicating the use of another browser).
*****************************************************************************/
function GetIEVersion()
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

/******************************************************************************
* Summary: Returns true is the browser is "newer" and compatible with certain features
*****************************************************************************/
function CompatibleBrowser()
{
  var retVal = 1;
  var ver = GetIEVersion();

  if ( ver > -1 )
  {
    if ( ver <= 6.0 ) 
      retVal = 0;
  }
  return retVal;
}    

/******************************************************************************
* Summary: Ensures that certain date fields are actually dates.
*****************************************************************************/
function CheckDates(val1, val1Name, val2, val2Name)
{
    if(CheckDate(val1, val1Name) == 0 || CheckDate(val2, val2Name) == 0)
    {
        return false
    }
    return true;
}

/******************************************************************************
* Summary: Ensures that a certain date field is actually a date.
*****************************************************************************/
function CheckDate(val, valName)
{
    if(val.trim() == '')
    {
        return true;
    }
    if(isNaN(Date.parse(val)))
    {
        alert(valName + ' is not a valid date.');
        return false;
    }
    return true;
}

/******************************************************************************
* Summary: Cross-browser compatiable method of setting disabled button styles.
*          Some browsers don't support CSS selectors, this is an alternative (JQuery)
*****************************************************************************/
function SetDisabledButtonStyle()
{
    //use JQuery to get a handle on all disabled page buttons.
    //then set the disabled button style
    /*
    var arraySubmitButtons = $("input[@disabled][@class=button]").get(); 
    $(arraySubmitButtons).each(function(){ 
        $(this).removeClass(); 
        $(this).addClass('button-disabled'); 
    });  
    
    var navigationButtons = $("input[@disabled][@class=button-grid-navigation]").get(); 
    $(navigationButtons).each(function(){ 
        $(this).removeClass(); 
        $(this).addClass('button-grid-navigation-disabled'); 
    });
    */
}

/******************************************************************************
* Summary: Cross-browser compatiable method of setting required field styles.
*          Some browsers don't support CSS selectors, this is an alternative (JQuery)
*****************************************************************************/
function SetRequiredFieldStyle() {
    var requiredSpan = $(".label-required");
    $(requiredSpan).each(function () {
        $(this).prepend("<font color='#ff0000'>*</font>");
    });         
}    

/******************************************************************************
* Summary: Cross-browser compatiable method of setting disabled field styles.
*          Some browsers don't support CSS selectors, this is an alternative (JQuery)
*****************************************************************************/
function SetDisabledFieldStyle() {
    var disabledFields = $("input:disabled").filter(".textbox");
    if (disabledFields.length) {
        disabledFields.each(function () {
            $(this).removeClass();
            $(this).addClass('label');
        });   
    }   
}

/******************************************************************************
* Summary: Closes the bottom message bar if it was rendered and the user 
*          pressed the "close" button.
*****************************************************************************/
function CloseBottomMessageBar()
{
    var msgPanel = $get('ctl00_pnlFilesDownloaded');
    
    if(msgPanel != null)
    {
        msgPanel.style.display = 'none';
    }
}

/******************************************************************************
* Summary: AJAX begin request event handler.
*****************************************************************************/
function beginRequest(sender, args) {
    postbackElement = args.get_postBackElement();
}

/******************************************************************************
* Summary: Event handler fired when a page has completed an asyn post-back
*****************************************************************************/
function pageLoadedAsync(sender, args)
{
    if(!skipRequiredFieldFlag)
    {
        SetDisabledButtonStyle();
        SetDisabledFieldStyle();

        if(typeof(postbackElement) === "undefined" || postbackElement.id != 'ctl00_tvMenu')
        {
            SetRequiredFieldStyle();
        }
    }
}

/******************************************************************************
* Summary: Called to display the SSRepotr
*****************************************************************************/
function ShowReport(reportURL,reportName)
{
    window.open(reportURL,reportName,"resizable=yes,toolbar=no,width=700,height=600,scrollbars=yes");
    return false;
}

/******************************************************************************
* Summary: ClientSide function to set CheckedListBox Items checked state
*****************************************************************************/
function ToggleCheckedListBoxSelection(ctlId,bChecked)
{
 var cblItem = document.getElementById(ctlId);

 //ctl00_cphMain_ContactTypeRepeater_ctl01_chkType
  for(var i=0;i<=cblItem.rows.length-1;i++)
  {
    for(var j = 0;j < cblItem.rows[0].cells[0].childNodes.length; j++)
    {
        if(cblItem.rows[i].cells[0].childNodes[j].type == "checkbox")
        {
            cblItem.rows[i].cells[0].childNodes[j].checked = bChecked;
            break;
        }
    }
   }
   return false;
}

/******************************************************************************
* Handle the calling of a modal popup; 
*****************************************************************************/
function CallModalPopup(sender, args)
{
    var modalPopup = $find(BehaviorID);
    if (modalPopup == null && retry != 0) {
        retry = (retry - 1);        
        setTimeout("CallModalPopup()", 1000); 
    }
    else {    
        modalPopup.show();
        NoScrollLink(NoScrollLinkID);
    
        /* Find the control to make the default and put focus on it*/
        var modalFocusControl = document.getElementById(FocusControlId);
        if (modalFocusControl != null) { modalFocusControl.focus() };
    }
}

/******************************************************************************
* Handle the calling of a help popup; 
*****************************************************************************/
function CallPaneHelp(url) 
{
	var sw = screen.width*0.24;
	var sWD="toolbar=0,status=0,menubar=0,resizable=1,left="+(screen.width-sw)+",top=0,width="+(sw-12) + ",height="+(screen.height-30);
	bResize=false;
	top.window.resizeTo(screen.width-sw,screen.height);
	top.window.moveTo(0,0);
	helpPopUp = window.open(url,'EEMHelp',sWD);
	helpPopUp.focus();
}

/******************************************************************************
* Summary: Sets the currently selected menu node (which one is expanded) into 
* ASP.NET Session state..
*****************************************************************************/
function ToggleMenuNodeSelection(menuId)
{    
    if(menuId == "")
    {
        //BDC 9/22/2008: no menuId passed, nothing to set, skip the Ajax call
        return;
    }
   
 try
 { 
    var request = new Sys.Net.WebRequest();
    request.set_url("AjaxSupport.asmx/SetSelectedMenuItem");  

    var req = "menuId=" + menuId;
  
    request.set_body(req);   
    request.get_headers()["Content-Length"] = req.length;       
    request.invoke(); 
  }
  catch(ex)
  {    
  }
}


/******************************************************************************
* Summary: Uses AJAX to retrieve the task and transaction count. 
*****************************************************************************/
function SetMenuCount()
{
    //check to ensure we can find the menu items first to avoid unnessesary network traffic.
    GetMenuItems();
    if(menuItems[0] == null && menuItems[1] == null && menuItems[2] == null && menuItems[3] == null)
    {
        //we couldn't find any of the menu items. This is an all or nothing call, so just skip it.
        return;
    }
    var request = new Sys.Net.WebRequest();
    request.add_completed(OnMenuCountComplete);
    request.set_url("AjaxSupport.asmx/GetMenuCounts");  
    request.invoke();     
}

/******************************************************************************
* Summary: When retrieving the task/transaction count completes, this event
* handler fires.
*****************************************************************************/
function OnMenuCountComplete(response, args){
  // get the xml content. ONLY do this if your response returned Xml. 
  var xmlObj = response.get_xml();
  var xml = null
  
  try
  {
      if(xmlObj.xml != null)
      {
        xml = xmlObj.xml;
      }
      else
      {
        serializer = new XMLSerializer();
        xml = serializer.serializeToString(xmlObj);
      }
      //process the XML here, load it into the help control
      if(xml != null)
      {
        SetMenuCountValue(xmlObj, "string");
      }  
     
  }
  catch(ex)
  {
    //do nothing, just swallow the exception
  }      
}

/******************************************************************************
* Summary: Loads and array of with specific menu items if they are found.
*****************************************************************************/
function GetMenuItems()
{
    for(i = 0; i < 50; i++)
    {
        var menuItem = $get('ctl00_tvMenun' + i);
        if(menuItem == null)
        {
            break;
        }
        
        if(menuItem.innerHTML.indexOf("Tasks") > - 1)
        {
            menuItems[0] = menuItem;
        }

        if(menuItem.innerHTML.indexOf("Transactions") == 8 || menuItem.innerHTML.indexOf("Transactions") == 0)
        {
            menuItems[1] = menuItem;
        }       
        
        if(menuItem.innerHTML.indexOf("Deferred Transactions") > - 1)
        {
            menuItems[2] = menuItem;
        }  
        
        if(menuItem.innerHTML.indexOf("Pending Approvals") > - 1)
        {
            menuItems[3] = menuItem;
        }                
    }
}

/******************************************************************************
* Summary: Gets a node value from and XML object
*****************************************************************************/
function SetMenuCountValue(xmlObj, nodeName)
{  
    if(xmlObj.getElementsByTagName(nodeName)[0].childNodes.length > 0)
    {
        var counts = xmlObj.getElementsByTagName(nodeName)[0].childNodes[0].nodeValue.split("|");

        //assign the task count
        if(menuItems[0] != null)
        {
            if(counts[0] > 0)
            {
                menuItems[0].innerHTML = "Tasks <b>(" + counts[0] + ")</b>";
            }
            else
            {
                menuItems[0].innerHTML = "Tasks";
            }
        }
        
        if(menuItems[1] != null)
        {        
            //assign the transactions count
            if(counts[1] > 0)
            {
                menuItems[1].innerHTML = "Transactions <b>(" + counts[1] + ")</b>";
            }
            else
            {
                menuItems[1].innerHTML = "Transactions";
            }
        }
        
        //assign the transactions count
        if(menuItems[2] != null)
        {        
            if(counts[2] > 0)
            {
                menuItems[2].innerHTML = "Deferred Trans. <b>(" + counts[2] + ")</b>";
            }
            else
            {
                menuItems[2].innerHTML = "Deferred Transactions";
            }   
        }
        
        //assign the transactions count
        if(menuItems[3] != null)
        {        
            if(counts[3] > 0)
            {
                menuItems[3].innerHTML = "Pending Approvals <b>(" + counts[3] + ")</b>";
            }
            else
            {
                menuItems[3].innerHTML = "Pending Approvals";
            }             
        }
        
    }
    else
    {
        if(menuItems[0] != null)
            menuItems[0].innerHTML = "Tasks";
            
        if(menuItems[1] != null)            
            menuItems[1].innerHTML = "Transactions";
            
        if(menuItems[2] != null)            
            menuItems[2].innerHTML = "Deferred Transactions";

        if(menuItems[3] != null)            
            menuItems[3].innerHTML = "Pending Approvals";
    }
}

/******************************************************************************
* Summary: Adds load event handlers in a cross-browser manner.
*****************************************************************************/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

/******************************************************************************
* Wire up some basic event handlers for the window and document
*****************************************************************************/
document.onkeypress = stopRKey; 
String.prototype.trim = function() { this.replace(/^\s+|\s+$/, ''); };
window.onscroll = ScrollHandler;       
//addLoadEvent(SetTaskAndTransactionCount); 
window.onload = SetMenuCount;




