var page_body;
var lookupCanceled = false;

/*****************************************************
** FunctionName: wasRadioButtonSelected             **
** ProcessingLogic:								    **
**   Returns true if a radio button was				**
**   checked, false otherwise						**
*****************************************************/
function wasRadioButtonSelected()
{
	// Get all the radion buttons
	var allSelectable = document.getElementsByTagName("input");
	var count = allSelectable.length;
	var retVal = false;
	
	// Check to see if they are selected
	for( var i=0; i<count; i++ ){
		if((allSelectable[i].type.toLowerCase() == 'radio') && (allSelectable[i].checked)){
			retVal = true;
			break;
		}
	}
	return retVal;
}

/**
* Allows including of javascript files from a JS file
*
**/
function include(filename) {
    var head = document.getElementsByTagName('head')[0];

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';

    head.appendChild(script)
}

/*****************************************************
** FunctionName: wasCheckboxSelected 	            **
** ProcessingLogic:								    **
**   Returns true if a checkbox was					**
**   checked, false otherwise						**
*****************************************************/
function wasCheckboxSelected()
{
	var numSelected = numberCheckboxesSelected();
	return numSelected > 0;
}

/*****************************************************
** FunctionName: wereAllCheckboxesSelected  	    **
** ProcessingLogic:				    				**
**   Returns true in all checkboxes were selected,  **
**   false otherwise                                **
*****************************************************/
function wereAllCheckboxesSelected()
{
	// Get all the checkboxes
	var allSelectable = document.getElementsByTagName("input");
	var count = allSelectable.length;
	var checkboxCount = 0;
	var countSelected = 0;
	
	// Check to see if they are selected
	for( var i=0; i<count; i++ ){
		if( allSelectable[i].type.toLowerCase() == 'checkbox' ){
		    checkboxCount++;
		    if( allSelectable[i].checked ){
			    countSelected++;
			}
		}
	}
	return (countSelected==checkboxCount);
}

/*****************************************************
** FunctionName: selectAllCheckboxes                **
** ProcessingLogic:								    **
**	Select/deselect all the checkboxes in the page	**
**  except for the checkbox passed into the function**
*****************************************************/
function selectAllCheckboxes( selection, elementId ) {
    if (elementId != null && elementId != "") {
        // do not do anything to the state of checkboxes 
        // for the current all jursidictions checkbox
        // or for the notifyEmail checkbox
        $('[type=checkbox]')
        .not('[id*= notifyCheckBox]')
        .not('[id*=' + elementId + ']')
        .attr('checked', selection);
    }
    else {
        $('[type=checkbox]')
        .attr('checked', selection);
    }
}


/*****************************************************
** FunctionName: numberCheckboxesSelected			**
** ProcessingLogic:				    				**
**   Returns the number of the selected checkboxes  **
*****************************************************/
function numberCheckboxesSelected()
{
	// Get all the checkboxes
	var allSelectable = document.getElementsByTagName("input");
	var count = allSelectable.length;
	var countSelected = 0;
	
	// Check to see if they are selected
	for( var i=0; i<count; i++ ){
		if( (allSelectable[i].type.toLowerCase() == 'checkbox') && (allSelectable[i].checked) ){
			countSelected++;
		}
	}
	return countSelected;
}

/*****************************************************
** FunctionName: getNumberOfCheckboxesInPage    	**
** ProcessingLogic:				    				**
**   Returns the number of the checkboxes in page   **
*****************************************************/
function getNumberOfCheckboxesInPage()
{
	// Get all the checkboxes
	var allSelectable = document.getElementsByTagName("input");
	var count = allSelectable.length;
	var checkboxCount = 0;
	
	// Check to see if they are selected
	for( var i=0; i<count; i++ ){
		if( (allSelectable[i].type.toLowerCase() == 'checkbox') ){
			checkboxCount++;
		}
	}
	return checkboxCount;
}
/*****************************************************
** FunctionName: enableElement						**
** ProcessingLogic:				    				**
**   Enables/Disables the element with the given Id **
*****************************************************/
function enableElement( enabled, elementId ){
	if( elementId == null ) return;
	var theElement = document.getElementById( elementId );
	if( theElement != null ){
		theElement.disabled = !enabled;
	}
}

/*****************************************************
** FunctionName: validateEmailAddress				**
** ProcessingLogic:				    				**
**  Returns true if the given email address has a	**
**	valid format, false otherwise					**
*****************************************************/
function validateEmailAddress( emailAddress ){
	if( emailAddress == null ) return false;
	var emailReg = /^([a-zA-Z0-9])+([\.a-zA-Z0-9'_-])*@([a-zA-Z0-9-_])+(\.[a-zA-Z0-9_-]+)+$/;
    return emailReg.test( emailAddress );
}

/*****************************************************
** FunctionName: isCheckBoxSelected					**
** ProcessingLogic:				    				**
**   returns whether or not the checkbox is selected**
*****************************************************/
function isCheckBoxSelected( checkBoxId )
{
	// Get the checkbox
	var checkBox = document.getElementById(checkBoxId);
	return checkBox.checked;
}

/*****************************************************
** FunctionName: toggleCheckBoxSelected				**
** ProcessingLogic:				    				**
**   toggles the state of a single checkbox			**
*****************************************************/
function toggleCheckBoxSelected( checkBoxId )
{
	// Get the checkbox
	var checkBox = document.getElementById(checkBoxId);
	checkBox.checked = !checkBox.checked;
}

/*****************************************************
** FunctionName: toggleCheckBoxSelected				**
** ProcessingLogic:				    				**
**   toggles the state of a single checkbox			**
*****************************************************/
function toggleCheckBoxSelected( checkBoxId, selection )
{
	// Get the checkbox
	var checkBox = document.getElementById(checkBoxId);
	checkBox.checked = selection;
}

/*****************************************************
** FunctionName: maxSizeReached                     **
** ProcessingLogic:								    **
**  Returns true if at the text in the text area	**
**	has reached the max length, false otherwise		**
*****************************************************/
function maxSizeReached( textAreaId, maxSize ){  

	// Check that the browser supports the function
	if( typeof( document.getElementById ) == "undefined" ) return;
	
	// Check the parameter passed in
    if( textAreaId == null || maxSize == null ) return;
   
	var textArea = document.getElementById( textAreaId );
	if( textArea.value.length > maxSize ){
		textArea.value = textArea.value.substring(0, maxSize);  
	}
}

/*****************************************************
** FunctionName: checkQuickReport                   **
** ProcessingLogic:								    **
**  Returns true if a company and a report were		**
**	selected before the Go button was clicked.		**
*****************************************************/
function checkQuickReport(userEmail, adminEmail, companyDropDownListId, reportDropDownListId){

	var retVal = true;
	// Get the dropdown menus
	var companyDropDownList = document.getElementById(companyDropDownListId);
	var reportDropDownList = document.getElementById(reportDropDownListId);

	if( userEmail == null || userEmail == "" || adminEmail == null || adminEmail == "" ){
		alert( "Quick Report: No e-mail address found, unable to send report" );
		retVal = false;
	}else if( companyDropDownList.selectedIndex == 0 && reportDropDownList.selectedIndex == 0 ){
		alert( "Quick Report: Please select a company and a report template" );
		retVal = false;
	}else if( companyDropDownList.selectedIndex == 0 ){
		alert( "Quick Report: Please select a company" );
		retVal = false;
	}else if( reportDropDownList.selectedIndex == 0 ){
		alert( "Quick Report: Please select a report template" );
		retVal = false;
	}
	return retVal;
}

function isNumberKey(evt)
{
	var charCode = (evt.which) ? evt.which : event.keyCode
	
	if (charCode > 31 && (charCode < 48 || charCode > 57))
	{
		return false;
	}

	return true;
}

function setControlDisplay( controlId, displayControl )
{
	if (document.layers)
	{
		current = displayControl ? 'block' : 'none';
		document.layers[controlId].display = current;
	}
	else if (document.all)
	{
		current = displayControl ? 'block' : 'none';
		document.all[controlId].style.display = current;
	}
	else if (document.getElementById)
	{
		vista = displayControl ? 'block' : 'none';
		document.getElementById(controlId).style.display = vista;
	}
}

/*****************************************************
** FunctionName: checkBrowserRedirect               **
** ProcessingLogic:								    **
** Checks for valid browser type and version - and  **
** redirects user to browser error page if not valid**
******************************************************/
function checkBrowserRedirect (url) {
   // check for supported browser type 
   if  (!( ($.browser.msie && $.browser.version >= 6) || 
           ($.browser.mozilla && $.browser.version >=  2) ||
           ($.browser.safari && event.metaKey ) )) {        
       window.location = url;
   }
}

/*****************************************************
** FunctionName: clientIsIE                         **
** ProcessingLogic:								    **
**  Returns true if a the client browser is Internet**
**  Explorer.		                                **
*****************************************************/
function clientIsIE(){
    if( window.event )
    {
        return true;
    }
    else
    {
        return false;
    }
}

/*****************************************************
** FunctionName: clientIsFF                         **
** ProcessingLogic:								    **
**  Returns true if a the client browser is Firefox **
*****************************************************/
function clientIsFF(){
    if( clientIsIE() )
    {
        return false;
    }
    else
    {
        // They're not using IE...Do a more in depth check to see if they're
        // using Firefox in particular.
        var userAgent = navigator.userAgent.toLowerCase();
        if( userAgent.indexOf('firefox') != -1 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/*****************************************************
** FunctionName: clientIsSafari                     **
** ProcessingLogic:								    **
**  Returns true if a the client browser is Safari  **
*****************************************************/
function clientIsSafari()
{
 
    if (  navigator.vendor && navigator.vendor.indexOf('Apple') >= 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/*****************************************************
** FunctionName: checkFullListInOutput              **
** ProcessingLogic:								    **
**  Calls the WebService to check if a FullList     **
**  has been included in the output                 **
*****************************************************/
function checkFullListInOutput()
{
    var argArray = new Array(arguments.length);
    
    for(var i = 0; i<arguments.length; i++)
    {
        argArray[i] = arguments[i];
    }
    West.Firm360.Web.WebServices.OutputConfiguratorService.IsFullListInOutput(profileKey, onIsFullListInOutputSuccess, onIsFullListInOutputFailure, argArray);
}

/*****************************************************
** FunctionName: onIsFullListInOutputSuccess        **
** ProcessingLogic:								    **
**  Checks the result value and prompts the user    **
**  to continue. If the user responds "YES"         **
**  the appropriate function is called.             **
*****************************************************/

function ClearOutputSettingsFromSessionFunction (profileKey, args )
{
    //Clear the FullList from output if the user selects YES.
    West.Firm360.Web.WebServices.OutputConfiguratorService.ClearOutputSettingsFromSession(profileKey, onClearOutputSuccess, onClearOutputFailure, args);        
}

function onIsFullListInOutputSuccess(result, args)
{      
     // result contains the message to be displayed
    if (result && result.length > 0)
    {
        showBasicMessageBoxConfirm(result, true, ClearOutputSettingsFromSessionFunction, profileKey, args, null, null, null);

    }
    else //If FullList is not included.. clear the output result order and continue as normal
        // Call the ClearOutputResultOrder Function.
    {
        // Note: the onClearOutputSuccess method must be called AFTER the
        // ClearOutputResultOrderFromSession web service method call has
        // returned.  Otherwise the web service call can clear out the
        // OutputResultOrder session state value AFTER the Results page has
        // populated it.  This results in the Company Summary sections
        // failing to load properly.
        West.Firm360.Web.WebServices.OutputConfiguratorService.ClearOutputResultOrderFromSession(profileKey, onClearOutputSuccess, onClearOutputSuccess, args);
    }
}     

function onClearOutputSuccess(result,args)
{
     var callingCode;
     
     if (args.length > 0)
     {
        callingCode = args[0] + '('; // the first parameter should always be the function name
        
        //Loop through the array and construct the function definition.
        for(var i = 1; i<args.length; i++)
        {
            switch (typeof(args[i]))
            {
                case "string":
                    callingCode = callingCode + "'" +args[i] + "'";
                    break;
                default:
                    callingCode = callingCode + args[i];                
            }
            
            if (i< args.length - 1)
                callingCode = callingCode + ',';
            
        }
        callingCode = callingCode + ')'; //Close the parantheses
            
        eval(callingCode); //Call the function.
    }
        
}

function onClearOutputFailure()
{
}

/*****************************************************
** FunctionName: onIsFullListInOutputFailure        **
** ProcessingLogic:								    **
**  Do nothing on web service call failure          **
*****************************************************/
function onIsFullListInOutputFailure(result)
{
}


/*****************************************************
** FunctionName: getEventSource                     **
** @param evt the source event for Firefox          **
**            (but not IE--IE uses window.event)    **
** ProcessingLogic:								    **
**  Returns the source element from an event in a   **
**  way that works for IE and Firefox and Safari    **
*****************************************************/
function getEventSource(evt) {
    if (clientIsIE()) {
        evt = window.event; // For IE
        return evt.srcElement;
    } else {
        return evt.target; // For Firefox
    }
}

if(typeof(Sys) !== "undefined")Sys.Application.notifyScriptLoaded();

/*****************************************************
** FunctionName: init                               **
** ProcessingLogic:								    **
**  Loads the page body with the element tag name   **
**  assigns it to a global variable for general use **
*****************************************************/
// Load the page body with the element tag name
function init()
{   
	page_body = (document.getElementsByTagName ? document.getElementsByTagName("body")[0] : (document.body || null));
}

/*****************************************************
** FunctionName: removePrimaryCriteriaInTree        **
** ProcessingLogic:	This function updates the tree  **
** after an entity has been removed from the        **
** shopping cart                                    **
*****************************************************/
function removePrimaryCriteriaInTree(entityId)
{
    if (clientIsFF() || clientIsSafari())
    {
        if( window.frames[0].removePrimaryCriteria )
        {
            window.frames[0].removePrimaryCriteria(entityId);
        }
    }
    else
    {
        if(window.frames['treeframe'])
        {
            window.frames['treeframe'].removePrimaryCriteria(entityId);
        }
    }
}


/*****************************************************
** FunctionName: getUrlParameter                    **
** ProcessingLogic:								    **
**  Retrieves the value of a url parameter          **
**  given the parameter name.                       **
*****************************************************/
function getUrlParameter(paramName)
{
    if(paramName)
    {
        paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+paramName+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
          return "";
        else
          return results[1];
    }
}


function findPos(obj) 
{
    var curleft = curtop = 0;
    if (obj.offsetParent) {
	    do {
		    curleft += obj.offsetLeft;
		    curtop += obj.offsetTop;
	    } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

//same as findPos but this will return an object with x y values
function getPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return { x: curleft, y: curtop };
}

/*****************************************************
** FunctionName: format                             **
** String.Format() In JavaScript As In C#           **
**  Example: format('Hello {0}.', 'World');         **
*****************************************************/
function format(str)
{
  for(i = 1; i < arguments.length; i++)
  {
    while (str.indexOf('{' + (i - 1) + '}') > -1)
    {
        str = str.replace('{' + (i - 1) + '}', arguments[i]);
    }
  }
  return str;
}

/*****************************************************
** FunctionName: trim                               **
** trim() In JavaScript As In C#                    **
**  Example: trim(' Hello ');   will return 'Hello' **
*****************************************************/
function trim(str)
{
    return str.replace(/^\s*/, "").replace(/\s*$/, "");
}

/******************************************
* Parse URL parameters
* access with getURLVar('varname')
*******************************************/

function getURLVar(urlVarName) {
    //divide the URL in half at the '?' 
    var urlHalves = String(document.location).split('?');
    var urlVarValue = '';
    if(urlHalves[1]){
    //load all the name/value pairs into an array 
    var urlVars = urlHalves[1].split('&');
    //loop over the list, and find the specified url variable 
    for(i=0; i<=(urlVars.length); i++){
        if(urlVars[i]){
            //load the name/value pair into an array 
            var urlVarPair = urlVars[i].split('=');
            if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
                //I found a variable that matches, load it's value into the return variable 
                urlVarValue = urlVarPair[1];
                }
            }
        }
    }
    return urlVarValue;   
}

/******************************************
* Try to call the function to update
* information for currently viewed data.
*******************************************/
function tryUpdateCurrentlyViewedDataInfo() {

    try {
        var documentObject = document;
        var isFromChildWindow = false;

        if (window.parent.document) {
            documentObject = window.parent.document;
            isFromChildWindow = true;
        }

        if (documentObject.getElementById('isCurrentlyViewedDataInfoEnabled') != null) {
            var isCurrentlyViewedDataInfoEnabledValue =
            documentObject.getElementById('isCurrentlyViewedDataInfoEnabled').value;

            if (isCurrentlyViewedDataInfoEnabledValue == 'True') {
                if (isFromChildWindow) {
                    if (typeof window.parent.updateCurrentlyViewedDataInfo == 'function') {
                        window.parent.updateCurrentlyViewedDataInfo();
                    }
                }
                else {
                    if (typeof updateCurrentlyViewedDataInfo == 'function') {
                        updateCurrentlyViewedDataInfo();
                    }
                }
            }
        }
    }
    catch (exception) {
        // Ignore exception. This function updates the info in the CurrentViewedDataInfo control at the top of the page,
        // but in case of EPL, the control does not exist.
    }
}


notWhitespace = /\S/

function cleanWhitespace(node) {
  for (var x = 0; x < node.childNodes.length; x++) {
    var childNode = node.childNodes[x]
    if ((childNode.nodeType == 3)&&(!notWhitespace.test(childNode.nodeValue))) {
// that is, if it's a whitespace text node
      node.removeChild(node.childNodes[x])
      x--
    }
    if (childNode.nodeType == 1) {
// elements can have text child nodes of their own
      cleanWhitespace(childNode)
    }
  }
}

// Browser independent means of opening a modal window.
function openModalWindow(url, name, width, height) {
    
    /*
     * IE supports showModalDialog but other browsers do not.
     * For those browsers we need to use window.open() with a
     * modal=yes attribute.
     */
    if (window.showModalDialog) {
        // Internet Explorer.  Default to maximum size if width and height
        // are not provided.
        var dialogWidth = 'dialogWidth:' + screen.width + 'px;';
        if (width.length > 0) {
            dialogWidth = 'dialogWidth:' + width + 'px;';
        }
        
        var dialogHeight = 'dialogHeight:' + screen.height + 'px;';
        if (height.length > 0) {
            dialogHeight = 'dialogHeight:' + height + 'px;';
        }
        
        window.showModalDialog(url, name, dialogWidth + dialogHeight);
    }
    
    else
    {
        // Other browser.
        var widthString = '';
        if (width.length > 0) {
            widthString = 'width=' + width + ',';
        }
        
        var heightString = '';
        if (height.length > 0) {
            heightString = 'height=' + height + ',';
        }
        
        window.open(url, name, heightString + widthString + 'toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes');
    }
}


/******************************************
* Sends a request to the CN Server
* On success, sets the flag in the session to true or false
*******************************************/
function pingCNServer() {

    if ($.browser.msie) {

        var url = "http://cnpmintegration/services/service.svc/ping?app=pm&callback=?";

        //Call the JSON API to get the data.
        $.getJSON(url, function(data) {
            var cnServerExists = false;
            if (data.Message != null && data.Message == "hello") {
                cnServerExists = true;
            }
            //Call the webservice to update the value in the session.
            West.Firm360.Web.WebServices.PreferencesWebService.SetIsCNEnabledFlag(cnServerExists,
            function() { /* on success do nothing */ },
            function(result) { /* log the error */West.Firm360.Web.WebServices.LoggingWebService.LogError("common.pingCNServer.onSetIsCNEnabledFlagFailure", result, null, null); });
        });
    }
       
}


