var primaryCriteriaCount = 0;
var serviceCallCount;
var serviceCallsComplete;
var lastToggledEntityId;
var refinementSearchCriteria = new Object();
var primarySearchCriteria = new Object();
var entityKey = new Object();


function set_primaryCriteriaCount(value)
{
    if (typeof(isTreeIFrame) != 'undefined' && isTreeIFrame)
    {
        parent.primaryCriteriaCount = value;
    }
    else
    {
        primaryCriteriaCount = value;
    }    
}

function onTogglePrimaryCriteriaSuccess(result, buttonID)
{   
    if (isAdvancedSearch)
    {
        set_primaryCriteriaCount(result[0]);
        
        //Raise the togglePrimaryCriteriaClick event ONLY in the case when the button id is null.
        //This will prevent from refreshing the entire search results view when clicking on the add/remove buttons
        //If there are 300 results and the user clicks multiple add/remove buttons very fast, the buttons starting flashing
        //since with every click the search result gets loaded.
        if (buttonID)
        {
            toggleButtonState(buttonID);
        }
        else
        {
            raiseEvent('togglePrimaryCriteriaClick');    
        }
        displayUpdatedShoppingCart(true);

        updateWatermark();

        // show the entity selection box if there are no more criteria
        if (result[0] == 0) 
        { 
            onSearchByClicked();
        }
        
        // If the toggle came from clicking the remove link from the shopping cart, Refresh the Tree
        if( getEntitySearchView != 'undefined' && removeFromShoppingCartAction && primarySearchCriteria['contentType'] 
            && primarySearchCriteria['dataSourceType'] && primarySearchCriteria['entityType'] )
        {
            var context = new Array();
            context[0] = primarySearchCriteria['contentType'];
            context[1] = primarySearchCriteria['dataSourceType'];
            context[2] = primarySearchCriteria['entityType'];
            getEntitySearchView(context);
            //showTree(null, primarySearchCriteria['contentType'], primarySearchCriteria['dataSourceType'], 
            //    primarySearchCriteria['entityType']);
        }
    }
    else
    {
        if (parent.OnGetResultsClicked)
        {
            parent.OnGetResultsClicked();
        }
        else
        {
           OnGetResultsClicked();
        }
    }
    raiseEvent('loadTree');
}

function isEntitySelectable(clientID, dropDownControl, selectedID, selectedIndex)
{
    var invalid = document.getElementById(clientID).innerHTML.split(",");
    for ( i=0; i < invalid.length; i++ ) {
        if (invalid[i] == selectedID) {
            var selectedText = document.getElementById(dropDownControl)[selectedIndex].text;
            showInformationalMessageBox(selectedText + " is not available under your subscription agreement." , "Please contact your Monitor Sales representative or call 1 877-347-6360 for more information on obtaining access to this data.");
            if (getURLVar('entitytype')) 
            {
                document.getElementById(dropDownControl).value = getURLVar('entitytype');
            } 
            else 
            {
                document.getElementById(dropDownControl).value = 'Company';
            }
            return false;
        }
    }
    
    if (primaryCriteriaCount > 0) 
    {
        var confirmMessage = 'You will lose all search criteria.  Do you want to continue?';
        var newValue = document.getElementById(dropDownControl).value;
        showBasicMessageBoxConfirm(confirmMessage, true, changeEntityAndPostBack, dropDownControl, newValue, null, null, null);

        //Set the dropdown to display the current entity, incase the user clicks the cancel button. If the user clicks the Ok button,
        //the function changeEntityAndPostBack will update the dropdown to the new value.
        var currentEntityType = getURLVar('entitytype')
        if (currentEntityType) {
            document.getElementById(dropDownControl).value = currentEntityType.replace('#', "");
        }
        else {
            document.getElementById(dropDownControl).value = 'Company';
        }
        
        return false;
    }
    return true;
}

// This function sets the entity dropdown value to the value that the customer picked and 
// then posts back to the server.
function changeEntityAndPostBack(dropDownControl, newValue){
    document.getElementById(dropDownControl).value = newValue;
    __doPostBack(dropDownControl, "");
}

function onTogglePrimaryCriteriaFailure(result)
{
    handleError(result);
}

function displayUpdatedShoppingCart(isSearchPage)
{
    if (primaryCriteriaCount > 0)
    {
        manageLinks(true);
    }
    else
    {
        manageLinks(false);
    }
    
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    
    showShoppingCart(isSearchPage, false, profileKey);
}

function displayCart() 
{
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    West.Firm360.Web.WebServices.ProfileManagementWebService.getPrimaryCriteriaCount(profileKey,
        onGetPrimaryCriteriaCountSuccess, onGetPrimaryCriteriaCountFailure);  
}

function onGetPrimaryCriteriaCountSuccess(result, eventArgs)
{
    primaryCriteriaCount = result;
    displayUpdatedShoppingCart(true);
}

function onGetPrimaryCriteriaCountFailure(result)
{
    handleError(result);
}

function toggleButtonState( controlId )
{

        var buttonControl = document.getElementById(controlId);
        
        if (buttonControl != null)
        {
            var added = buttonControl.parentNode.getElementsByTagName("div");
            if (buttonControl.value == "add")
            {   if (added[0]) added[0].style.display = 'block'
                buttonControl.src = "/images/remove_orange.png";
                buttonControl.value = "remove";
            }
            else if (buttonControl.value == "remove")
            {
                if (added[0]) added[0].style.display = 'none'
                buttonControl.src = "/images/Add_btn.png";
                buttonControl.value = "add";
            }
        }

}

function togglePrimaryCriteria(entityID, entityLevel, profileKey, buttonID, searchType, removeAction, overridePreviouslyAddedCriteria, 
    entityContentType, entityDataSourceType, entityType) 
{ 
    // Call web service to add or remove the primary criteria.   
    lastToggledEntityId = entityID;
    
    // Set the values for the entityKey object.  For now the Level is being hard coded.  This will change soon.
    entityKey['EntityGuid'] = entityID;
    entityKey['EntityLevel'] = entityLevel;            

    //SearchType will default to SearchType.Name
    if (searchType == null || searchType == "" || searchType == "undefined")
        searchType = West.Firm360.DataModel.Search.Entities.SearchType.Name;
    else if (searchType == "PossibleCompany")
        searchType = West.Firm360.DataModel.Search.Entities.SearchType.PossibleCompany;
    
    removeFromShoppingCartAction = (removeAction == "undefined") ? false : removeAction;
    
    if( removeFromShoppingCartAction&& entityContentType && entityDataSourceType && entityType )
    {
        primarySearchCriteria['contentType'] = entityContentType;
        primarySearchCriteria['dataSourceType'] = entityDataSourceType;
        primarySearchCriteria['entityType'] = entityType;
    }
    
    // Tracker 2862: Will not allow user to remove from shopping cart if primary criteria is reselected again from auto-fill control.
    //               This will set removePreviouslyAddedCriteria to false for Inventor Location and HeadQuarters Location Anchor actions. 
    var removePreviouslyAddedCriteria = (overridePreviouslyAddedCriteria == "undefined") ? true : !overridePreviouslyAddedCriteria;
    
    if (!isAdvancedSearch){
        // In the case of Quick Search, the user should not be able to add more than one primary criteria to the cart.
        // Lets make sure everything is cleared out before adding a new one. This will avoid the scenario where the user
        // views the results for one entity, goes back to the search results and clicks on Get Results for another entity and 
        // the report displayed will include both entities.
        
        // pass all the information needed along to the webService callback
        // function
        var context = new Array();
        context[0] = entityKey;
        context[1] = profileKey;
        context[2] = searchType;
        context[3] = removePreviouslyAddedCriteria;
        context[4] = buttonID;
        context[5] = removeAction;
        
        West.Firm360.Web.WebServices.ProfileManagementWebService.RemovePrimaryCriteriaAndRefinements(profileKey, 
            onRemovePrimaryCriteriaAndRefinementsSuccess, onRemovePrimaryCriteriaAndRefinementsFailure, context);
    }
    else
    {    
        West.Firm360.Web.WebServices.ProfileManagementWebService.TogglePrimaryCriteria(
            entityKey, profileKey, searchType, removePreviouslyAddedCriteria, onTogglePrimaryCriteriaSuccess, onTogglePrimaryCriteriaFailure, buttonID, removeAction);
    }
    
    var objDiv = document.getElementById("cartDiv");
    
    if(objDiv)
    {
        objDiv.scrollTop = 0;
    }
    
}

function onRemovePrimaryCriteriaAndRefinementsSuccess(result, context)
{
    var entityKey = context[0];
    var profileKey = context[1];
    var searchType = context[2];
    var removePreviouslyAddedCriteria = context[3];
    var buttonID = context[4];
    var removeAction = context[5];
        
    West.Firm360.Web.WebServices.ProfileManagementWebService.TogglePrimaryCriteria(
        entityKey, profileKey, searchType, removePreviouslyAddedCriteria, onTogglePrimaryCriteriaSuccess, onTogglePrimaryCriteriaFailure, buttonID, removeAction);
}

function onRemovePrimaryCriteriaAndRefinementsFailure(result, context){
}

// this version of toggerPrimaryCriteria will only ever add - for use in entitySearch dropdowns.
function addPrimaryCriteria(entityID, entityLevel, profileKey)
 {
    // Call web service to add or remove the primary criteria.   
    lastToggledEntityId = entityID;

    // Set the values for the entityKey object.  For now the Level is being hard coded.  This will change soon.
    entityKey['EntityGuid'] = entityID;
    entityKey['EntityLevel'] = entityLevel;

    //SearchType will default to SearchType.Name
    var searchType = West.Firm360.DataModel.Search.Entities.SearchType.Name;

    removeFromShoppingCartAction = false;
    var removePreviouslyAddedCriteria = false;
    
    West.Firm360.Web.WebServices.ProfileManagementWebService.TogglePrimaryCriteria(
        entityKey, profileKey, searchType, removePreviouslyAddedCriteria, onTogglePrimaryCriteriaSuccess, onTogglePrimaryCriteriaFailure);

    var objDiv = document.getElementById("cartDiv");

    if (objDiv) {
        objDiv.scrollTop = 0;
    }
}


function showCompanyNameVariants(showLabelId, companyId)
{
    var hideVariantsText = 'HideVariants';
     
    // call the web service to populate the name variants
    getCompanyNameVariants(companyId); 
           
    // find the show label and hide it
    var showLabel = document.getElementById(showLabelId);     
    showLabel.style.display = 'none';
    
    // find the hide label and display it
    var hideLabelId = hideVariantsText + companyId;    
    var hideLabel = document.getElementById(hideLabelId);        
    hideLabel.style.color = '#303188';
    hideLabel.style.textDecoration = 'underline';
    hideLabel.style.display = 'block';       
}
 
function hideCompanyNameVariants(hideLabelId, companyId)
{
    var divText = 'NameVariants';
    var showVariantsText = 'ShowVariants';

    // find the show label and display it
    var showLabelId = showVariantsText + companyId;    
    var showLabel = document.getElementById(showLabelId);      
    showLabel.style.display = 'block';
    
    // find the hide label and hide it
    var hideLabel = document.getElementById(hideLabelId);     
    hideLabel.style.display = 'none';
        
    // find the div for this control and hide it
    var variantNamesDiv = document.getElementById(divText + companyId);
    if (variantNamesDiv != null)
    {
        variantNamesDiv.style.display = 'none';          
    }
}

function getCompanyNameVariants(entityId)
{
    // Call web service to get list of Name Variants
    West.Firm360.Web.WebServices.ProfileManagementWebService.GetCompanyNameVariants(
        entityId, profileKey, onGetCompanyNameVariantsSuccess, onGetCompanyNameVariantsFailure, entityId);
}

function onGetCompanyNameVariantsSuccess(result, entityId)
{
    var divText = 'NameVariants';
    
    // find the div for this entityid and display the result from the web service
    variantNamesDiv = document.getElementById(divText + entityId);
    if (variantNamesDiv != null)
    {
        variantNamesDiv.innerHTML = result;           
        variantNamesDiv.style.display = 'block';
    }    
}

function onGetCompanyNameVariantsFailure(exception, entityId)
{
    var context = new Object;
    context.EntityId = entityId;
    context.Exception = exception;
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.onGetCompanyNameVariantsFailure", context, null, null);
}

function toggleSelectedCompanyNameVariants(entityId, selectedItemIndex, selected)
{
    // call the web service to manage the list of selected variants
    West.Firm360.Web.WebServices.ProfileManagementWebService.ToggleSelectedCompanyNameVariants(
        entityId, selectedItemIndex, selected, onToggleCompanyNameVariantsSuccess, onToggleCompanyNameVariantsFailure, entityId);
}

function onToggleCompanyNameVariantsSuccess(exception, entityId)
{
    displayUpdatedShoppingCart(true);
}

function onToggleCompanyNameVariantsFailure(exception, entityId)
{
    var context = new Object;
    context.EntityId = entityId;
    context.Exception = exception;
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.onToggleCompanyNameVariantsFailure", context, null, null);
}

function toggleSelectedRefinementFromCart(dataSourceType, contentType, key, value, displayValue, level, refocusType)
{
    refinementSearchCriteria['ContentType'] = contentType;
    refinementSearchCriteria['DataSourceType'] = dataSourceType;
    
    removeFromShoppingCartAction = true;
    
    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    West.Firm360.Web.WebServices.ProfileManagementWebService.RemoveCriteriaFromCart(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, refocusType, onToggleRefinementCriteriaFromCartSuccess, onToggleRefinementCriteriaFailure );
}

function addRemoveRefinement(dataSourceType, contentType, key, addValue, removeValue, displayValue, level, refocusType)
{
    West.Firm360.Web.WebServices.ProfileManagementWebService.AddRemoveDocumentTypeRefinementCriteria(
       dataSourceType, contentType, key, addValue, removeValue, displayValue, level, profileKey, refocusType, onToggleRefinementCriteriaSuccess, onToggleRefinementCriteriaFailure );    
}

function onToggleRefinementCriteriaFromCartSuccess()
{
    raiseEvent('removeClick');
        
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    showShoppingCart(false, false, profileKey);
    
    if (getEntitySearchView != 'undefined' && 
        refinementSearchCriteria['EntityType'] != null && 
        refinementSearchCriteria['EntityType'] != '')
    {
        var context = new Array();
        context[0] = refinementSearchCriteria['ContentType'];
        context[1] = refinementSearchCriteria['DataSourceType'];
        context[2] = refinementSearchCriteria['EntityType'];
        getEntitySearchView(context);
    }
    
    refinementSearchCriteria['EntityType'] = null;
}

//needToRefresh: is passing to refresh the refinement to update exclude/include check box
function toggleSelectedRefinement(dataSourceType, contentType, key, value, displayValue, level, refocusType, needToRefresh)
{     
    refinementSearchCriteria['ContentType'] = contentType;
    refinementSearchCriteria['DataSourceType'] = dataSourceType;
 
    var displayValueText = unescape(displayValue);
    var excludedText = " - EXCLUDED";
    var excludedIndex = displayValueText.indexOf(excludedText, 0);

    if (excludedIndex > 0) {
        displayValueText = displayValueText.substr(0, displayValueText.length - excludedText.length);
        displayValue = escape(displayValueText);
    }
    
    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.   
    West.Firm360.Web.WebServices.ProfileManagementWebService.ToggleRefinementCriteria(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, refocusType, false, onToggleRefinementCriteriaSuccess, onToggleRefinementCriteriaFailure, needToRefresh);
}

// Method used only from autoFill toggle from UI control. This is only used on autofill control(HeaderQuarter Location, Inventor Location) onkeyup/autofill item selection.
function toggleSelectedRefinementFromAutoFillLocation(dataSourceType, contentType, key, value, displayValue, level, refocusType)
{     
    refinementSearchCriteria['ContentType'] = contentType;
    refinementSearchCriteria['DataSourceType'] = dataSourceType;
    
    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.    
    
    // removePreviouslyAddedCriteria denotes that we want to ignore toggle if action is Remove.
    // we will not remove if user selects a criteria from autofill control if select criteria is already in Profile.    
    var removePreviouslyAddedCriteria  = true;  
     
    // This block of code is needed to purposely ignore the rerunning of getEntitySearchView(context) 
    //  in onToggleRefinementCriteriaSuccess(profileHash) API. This is needed because autofill control is different from the rest 
    //  where we want to refresh view. Previously, there was an issue where autofill was redisplaying drop down on ToggleRefinementFromShoppingcart.
    getEntitySearchView = 'undefined';
    refinementSearchCriteria['EntityType'] = null;
    refinementSearchCriteria['EntityType'] = ''; 
    // 
          
    West.Firm360.Web.WebServices.ProfileManagementWebService.ToggleRefinementCriteriaWithRemoveOverrideOption(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, refocusType, removePreviouslyAddedCriteria, false, onToggleRefinementCriteriaSuccess, onToggleRefinementCriteriaFailure );
}


// needToRefresh will be null if it isn't a check box refinement.
function onToggleRefinementCriteriaSuccess(exception, needToRefresh)
{   
    var isTree = typeof(isTreeIFrame) == 'undefined' ? false : isTreeIFrame;
    var callContext = isTree ? parent : this;
    
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    callContext.showShoppingCart(false, false, profileKey);
    
    if (getEntitySearchView != 'undefined' && 
        refinementSearchCriteria['EntityType'] != null && 
        refinementSearchCriteria['EntityType'] != '')
    {
        var context = new Array();
        context[0] = refinementSearchCriteria['ContentType'];
        context[1] = refinementSearchCriteria['DataSourceType'];
        context[2] = refinementSearchCriteria['EntityType'];
        getEntitySearchView(context);
    }

    if (needToRefresh != null && needToRefresh) {
        raiseEvent('refreshPage');
    }
    
    refinementSearchCriteria['EntityType'] = null;

    if (isTree) {
        raiseEvent('loadTree');
    }
}


function onToggleRefinementCriteriaFailure(exception)
{
    refinementSearchCriteria['EntityType'] = null;
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.onToggleRefinementCriteriaFailure", exception, null, null);
}

// This function is for the results page shopping cart only
function removeRefinementFromResultsCart(dataSourceType, contentType, key, value, displayValue, level, refocusType){
    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    removeFromShoppingCartAction = true;
    West.Firm360.Web.WebServices.ProfileManagementWebService.RemoveCriteriaFromCart(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, refocusType, onRemoveRefinementCriteriaSuccess, onRemoveRefinementCriteriaFailure );
}

function onRemoveRefinementCriteriaSuccess(exception)
{
    if(typeof OnRemoveButtonClick == 'function') 
    {
        OnRemoveButtonClick();
     }    
}

function onRemoveRefinementCriteriaFailure(exception)
{
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.onRemoveRefinementCriteriaFailure", exception, null, null);
}

function ToggleRefinementCriteriaByContentTypeFunction (dataSourceType, contentType, profileKey)
{
    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    West.Firm360.Web.WebServices.ProfileManagementWebService.RemoveAllCriteriaByContentType(
    contentType, dataSourceType, profileKey, onRemoveRefinementCriteriaByContentTypeSuccess, onRemoveRefinementCriteriaByContentTypeFailure);        
}

// This function is for the results page shopping cart only
function removeRefinementFromResultsCartByContentType(dataSourceType, contentType, refinementTitle) {
    
    var confirmMessage = 'You have asked to remove all of the ' + refinementTitle + ' Refinements.<br> Do you want to continue?';
    showBasicMessageBoxConfirm(confirmMessage, true, ToggleRefinementCriteriaByContentTypeFunction, dataSourceType, contentType, profileKey, null, null);

}

function onRemoveRefinementCriteriaByContentTypeSuccess(exception)
{ 
    if(typeof OnRemoveButtonClick == 'function') 
    {
        OnRemoveButtonClick();
    } 
    else
    {
        raiseEvent('refreshPage');
    }
}

function onRemoveRefinementCriteriaByContentTypeFailure (exception)
{
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.onRemoveRefinementCriteriaByContentTypeFailure", exception, null, null);
}

// Removes all refinements of a specific type (e.g. all "Litigation Court"
// refinements) from the shopping cart.
function removeRefinementsOfSpecficTypeFromResultsCart(criteriaKey, dataSourceType)
{
    West.Firm360.Web.WebServices.ProfileManagementWebService.RemoveAllCriteriaOfSpecificType(
        criteriaKey, dataSourceType, profileKey, onRemoveRefinementsOfSpecficTypeSuccess, onRemoveRefinementsOfSpecficTypeFailure);
}

function onRemoveRefinementsOfSpecficTypeSuccess(result)
{
    if (result)
    {
        if (typeof OnRemoveButtonClick == 'function') {
            OnRemoveButtonClick();
        }
        else {
            raiseEvent('refreshPage');
        }
    }
    else
    {
        onRemoveRefinementCriteriaByContentTypeFailure("Failed to remove all refinement criteria of a specific type.");
    }
}

function onRemoveRefinementsOfSpecficTypeFailure(exception) {
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.onRemoveRefinementsOfSpecficTypeFailure", exception, null, null);
}

//This function checks to see if any of the check box is selected in the given node_list.
function isAnyCheckboxSelected(tableIndex) {

    // Count the number of checked checkboxes for the table with the given table index.
    // If no checkboxes were checked, an error message shall be displayed.
    var selectedCheckboxes = $("input:checkbox[id*='chkCriteria" + tableIndex + "']:visible[checked=true]");
    return (selectedCheckboxes.length > 0)

}

// check to see if ALL checkboxes are selected
function areAllCheckboxesSelected() 
{
    // Get the total # of checked and unchecked boxes 
    // compare sum with total # of checked boxes to see if all are selected
    var checkedCheckboxes = $(":checkbox:checked").length;
    var uncheckedCheckboxes = $(":checkbox:not(:checked)").length;
    var totalCheckboxes = checkedCheckboxes + uncheckedCheckboxes;
    return (checkedCheckboxes == totalCheckboxes);
}

// This function gets the selected value from the refine criteria dropdown, determining if it's an include/exclude and executing the correct method
// Parameters: ButtonID - id of refinement image button so that focus can be put there if there is a failure
//              dropdownID - id of the refinement dropdown so that the selected value can be accessed
//              dataSourceType = The datasource that is being retrieved
//              contentType - The content type that is being retrieved
//              tableIndex - index of checked boxes, for checking to see if any of the checkboxes have been checked
//              isFullList - true if this is coming from a fulllist page
//              eplID - is this an epl?
function RefinementOptionClick(buttonID, dropdownID, dataSourceType, contentType, isFullList, eplID, tableIndex)
 {
    // get the selected value from the dropdown
    var value = $('#' + dropdownID).val();
    // split into inclusion and refocus
    var refocusOption = value.split("&");
    var dropdownType = refocusOption[0];
    var refocusType = refocusOption[1];
         
    tableIndex = tableIndex || "";
    eplID = eplID || "";
    var includeSelected;

    if (dropdownType == "Exclude") 
    {
        includeSelected = false;
        IncludeOrExcludeResultsClickHandler(buttonID, dataSourceType, contentType, includeSelected, isFullList, refocusType, eplID, tableIndex);
    }
    else if (dropdownType == "Include") 
    {
        includeSelected = true;
        IncludeOrExcludeResultsClickHandler(buttonID, dataSourceType, contentType, includeSelected, isFullList, refocusType, eplID, tableIndex);
    }
    else if (dropdownType == "Court") 
    {
        var courtKey = refocusOption[2] || "";
        var courtValue = refocusOption[3] || "";
        var courtDisplay = refocusOption[4] || "";
        var courtLevel = refocusOption[5] || "";
        addRemoveCourtRefinement(buttonID, dataSourceType, contentType, courtKey, courtValue, courtDisplay, courtLevel, refocusType, eplID);
    }
    else if (dropdownType == "ClassAction") 
    {

        var keyValue = refocusOption[2] || "";
        var key = refocusOption[3] || "";
        var displayValue = refocusOption[4] || "";

        addRemoveClassActionRefinement(dataSourceType, contentType, key, keyValue, displayValue, 0, refocusType, eplID);
    }
}

//This function handles the click event of the Include dropdown on the results and full list page
//This function makes one webservice call to add all the refinements.
function IncludeOrExcludeResultsClickHandler(buttonID, dataSourceType, contentType, includeSelected, isFullList, refocustype, eplID, tableIndex) 
{
    // added refocustype as 2nd to last criteria so that it is either a drilldown (ReusltsPage [drilldown] or Refinement[stay at same level])
    eplID = eplID || '';
    tableIndex = tableIndex || '';

    var refinementsList = new Array();
    var arrayCount = 0;

    if (!isAnyCheckboxSelected(tableIndex))
    {
        // no checkboxes have been selected
        showBasicMessageBox("Please make a selection and click the filter report button to limit all report sections based on the item selected.", buttonID);
    }
    else if (areAllCheckboxesSelected() && !includeSelected) 
    {
        // all checkboxes are checked and exclude has been selected
        showBasicMessageBox("Excluding all items is not allowed.  Please deselect one or more items to continue.", buttonID);
    }
    else if (areAllCheckboxesSelected() && includeSelected && refocustype == "Refinement") 
    {
            // all checkboxes are selected and include/stay at same level has been selected
            showBasicMessageBox("Including all items will yield the same results.  Please deselect one or more items to continue.", buttonID);
    }
    else 
    {
        var node_list = document.getElementsByTagName('input');
        //Get all elements in the form of type input.        
        for (var i = 0; i < node_list.length; i++) {
            var node = node_list[i];

            //Find the checkbox in the list.
            if (node.getAttribute('type') == 'checkbox') {
                if (node.checked) {
                    //Split the name mangled section of the ID                    
                    var arrTempID = node.id.split("chkCriteria" + tableIndex);
                    if (arrTempID.length > 1) {

                        refinementsList[arrayCount] = arrTempID[1]; //add item to the array
                        arrayCount++;
                    }
                }
            }
        }

        if (eplID == '') {
            West.Firm360.Web.WebServices.ProfileManagementWebService.AddRefinementCriteriaInBatch(
                        dataSourceType, contentType, refinementsList, profileKey, refocustype, includeSelected,

                function (results, isFullList) {
                    West.Firm360.Web.WebServices.ProfileManagementWebService.GetResultsPageUrl(profileKey, refocusResultSuccess, refocusResultFailure, isFullList)
                },

                function (exception) {
                    handleError(exception);
                },
                isFullList);
        }

        else {
            // added refocus type to criteria
            West.Firm360.Web.WebServices.ProfileManagementWebService.AddRefinementCriteriaInBatch(
                   dataSourceType, contentType, refinementsList, profileKey, refocustype, includeSelected,

                function (results, isFullList) {
                    West.Firm360.Web.WebServices.ProfileManagementWebService.GetEplResultsUrl(profileKey, eplID, refocusResultSuccess, refocusResultFailure, isFullList)
                },

                function (exception) {
                    handleError(exception);
                },
                isFullList);
        }
    }
}


//This function handles including and either refocusing or staying at the same level on the results page.
//The table index is only used for pages that have more than one refocus result button.
function refocusResultsClickHandler(buttonID, dataSourceType, contentType, tableIndex, isFullList)
{

    if (tableIndex == null || tableIndex.length == 0)
    {
        tableIndex = "";
    }
    
    //Get all elements in the form of type input.
    var node_list = document.getElementsByTagName('input');
    serviceCallCount = 0;
    serviceCallsComplete = false;

    if (!isAnyCheckboxSelected(tableIndex)) 
    {
        showBasicMessageBox("Please make a selection and click the filter report button to limit all report sections based on the item selected.", buttonID);
    }
    
    else
    {
        var key = "";
        var value = "";
        var level = "";
        
        //Find the key,value and level for the first checkbox in the list
        for (var i = 0; i < node_list.length; i++) {
            var node = node_list[i];

            //Find the checkbox in the list.
            if (node.getAttribute('type') == 'checkbox') {
                if (node.checked) {
                    //Split the name mangled section of the ID                    
                    var arrTempID = node.id.split("chkCriteria" + tableIndex);
                    if (arrTempID.length > 1) {
                        //Split the concatenated section of the id into individual elements. (key, value and Display Value)
                        var arrValues = arrTempID[1].split("~");
                        if (arrValues.length > 0) 
                        {
                            key = arrValues[0];
                            value = arrValues[1];
                            level = arrValues[3];
                            break;
                        }
                    }
                }
            }
        }    
        //The first step is to call the Clear Refinements code.
        West.Firm360.Web.WebServices.ProfileManagementWebService.ClearRefinements
        (   dataSourceType,
            contentType,
            key, 
            value,
            level,
            profileKey,
            function(result)
            {
                //On success of clearing the refinements, process the requests to add the selected refinements.
                for (var i = 0; i < node_list.length; i++)
                {                         
                    var node = node_list[i];
                    
                    //Find the checkbox in the list.
                    if (node.getAttribute('type') == 'checkbox')
                    {
                        if(node.checked)
                        {
                            //Split the name mangled section of the ID                    
                            var arrTempID = node.id.split("chkCriteria" + tableIndex);
                            if (arrTempID.length > 1)
                            {
                                //Split the concatenated section of the id into individual elements. (key, value and Display Value)
                                
                                var arrValues = arrTempID[1].split("~");
                                if (arrValues.length > 0)
                                {
                                    serviceCallCount++; //Increment the count of service calls.

                                    // temp fix for problem with $ symbols in the id.  The dollars are getting
                                    // replaced by underscores so switch them back by doing a global replace.
                                    var displayName = arrValues[2].replace(/_/g, '$');

                                    //Call the Webservice to add the criteria to the profile.
                                    addSelectedRefinement(dataSourceType, contentType, arrValues[0], arrValues[1], displayName, arrValues[3], isFullList);
                                                                       
                                }
                            }    
                        }
                    }        
                }
            },
            function(exception) {
                    //log the error
                    handleError(exception);
            }
         )
         
    }
    serviceCallsComplete = true;
}

function addSelectedRefinement(dataSourceType, contentType, key, value, displayValue, level, isFullList){

    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    West.Firm360.Web.WebServices.ProfileManagementWebService.AddRefinementCriteria(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, '', onAddRefinementCriteriaSuccess, onAddRefinementCriteriaFailure, isFullList);
}

function onAddRefinementCriteriaSuccess(exception, isFullList)
{
    serviceCallCount--;
    //Check to see if all service call have returned.
    if (serviceCallCount == 0  && serviceCallsComplete == true)
    {
        West.Firm360.Web.WebServices.ProfileManagementWebService.GetResultsPageUrl(profileKey, refocusResultSuccess, refocusResultFailure, isFullList)
    }
}

function onAddRefinementCriteriaFailure(exception)
{
    serviceCallCount--;
    handleError(exception);
}

// Function to manage the special "Show State" "Show Federal" functionality.
function addRemoveCourtRefinement(buttonID, dataSourceType, contentType, key, value, displayValue, level, refocusType, eplID){

    eplID = eplID || '';
    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    West.Firm360.Web.WebServices.ProfileManagementWebService.ToggleRefinementCriteria(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, refocusType, false, onaddRemoveCourtRefinementSuccess, onaddRemoveCourtRefinementFailure, eplID);
}

function onaddRemoveCourtRefinementSuccess(exception, eplID) {

    if (eplID == '') {
        West.Firm360.Web.WebServices.ProfileManagementWebService.GetResultsPageUrl(profileKey, refocusResultSuccess, refocusResultFailure)
    }
    else {
        West.Firm360.Web.WebServices.ProfileManagementWebService.GetEplResultsUrl(profileKey, eplID, refocusResultSuccess, refocusResultFailure)
    }
}

function onaddRemoveCourtRefinementFailure(exception)
{
}

// Adds or removes a class action flag refinement.
function addRemoveClassActionRefinement(dataSourceType, contentType, key, value, displayValue, level, refocusType, eplID) {

    eplID = eplID || '';
    var ignoreValueOnComparison = true;
    var allLitigationValue = "0";

    // If the value of the key is "0", just remove the refinement.
    if (value == allLitigationValue) {
        West.Firm360.Web.WebServices.ProfileManagementWebService.RemoveAllCriteriaOfSpecificType(
            key,
            dataSourceType,
            profileKey,
            onAddRemoveClassActionRefinementSuccess,
            onAddRemoveClassActionRefinementFailure,
            eplID
        );
    }

    else {
        // call the web service to manage the selected refinements
        // The following call depends on the profileKey variable being loaded with the correct value
        // This is done in the page.
        West.Firm360.Web.WebServices.ProfileManagementWebService.ToggleRefinementCriteria(
            dataSourceType,
            contentType,
            key,
            value,
            displayValue,
            level,
            profileKey,
            refocusType,
            ignoreValueOnComparison,
            onAddRemoveClassActionRefinementSuccess,
            onAddRemoveClassActionRefinementFailure,
            eplID);
    }
}

// Handles any actions needed upon successfully adding or removing a class action flag refinement.
function onAddRemoveClassActionRefinementSuccess(exception, eplID) {

    if (eplID == '') {
        West.Firm360.Web.WebServices.ProfileManagementWebService.GetResultsPageUrl(profileKey, refocusResultSuccess, refocusResultFailure)
    }
    else {
        West.Firm360.Web.WebServices.ProfileManagementWebService.GetEplResultsUrl(profileKey, eplID, refocusResultSuccess, refocusResultFailure)
    }
}

// Handles any actions needed upon failing to add or remove a class action flag refinement.
function onAddRemoveClassActionRefinementFailure(exception) {
    
    handleError(exception);
}

// Function to manage the special "Refocus by US only" functionality.
function addRemoveLocationRefinement(dataSourceType, contentType, key, value, displayValue, level, refocusType){

    // call the web service to manage the selected refinements
    // The following call depends on the profileKey variable being loaded with the correct value
    // This is done in the page.
    West.Firm360.Web.WebServices.ProfileManagementWebService.ToggleRefinementCriteria(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, refocusType, false, onaddRemoveLocationRefinementSuccess, onaddRemoveLocationRefinementFailure);
}

function onaddRemoveLocationRefinementSuccess(exception)
{   
    West.Firm360.Web.WebServices.ProfileManagementWebService.GetResultsPageUrl(profileKey, refocusResultSuccess, refocusResultFailure)    
}

function onaddRemoveLocationRefinementFailure(exception)
{
}

function refocusResultSuccess(result, isFullList) {

    // an anchor tag is used here because window.location doesn't work in safari with the history.
    var anchor = document.getElementById('getResultAnchor')
    if (anchor == null)
    {
        // this is needed for section.aspx
        anchor = parent.document.getElementById('getResultAnchor')
    }
    
    if (anchor != null) {
        if (isFullList)
        {
            window.opener.setTimeout('parent.location.replace("' + result + '")', 300);
            window.open('','_self',''); 
            window.close(); 
            target="_parent";
        }
        else
        {
            anchor.href=result;
            anchor.click();
        }        
        
    }
    return false;
}

function refocusResultFailure(result)
{
    handleError(result);
}

function handleError(result)
{
    if (result.get_message() == "Authentication failed.")
    {
        window.location = "/signon/default.aspx";
    }
    
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.handleError", result, null, null);
}

// Function to handle the click event for the 
// ShowDocketAndOpinion button.
function showDocketsAndOpinionsClickHandler(dataSourceType, contentType, key, value, displayValue, level, refocusType)
{
     West.Firm360.Web.WebServices.ProfileManagementWebService.ToggleRefinementCriteria(
       dataSourceType, contentType, key, value, displayValue, level, profileKey, refocusType, false, onShowDocketsAndOpinionsSuccess, onShowDocketsAndOpinionsFailure );
}

function onShowDocketsAndOpinionsSuccess(exception)
{
    West.Firm360.Web.WebServices.ProfileManagementWebService.GetResultsPageUrl(profileKey, refocusResultSuccess, refocusResultFailure)  
}

function onShowDocketsAndOpinionsFailure(exception)
{
    West.Firm360.Web.WebServices.LoggingWebService._staticInstance.LogError("manageprofile.onShowDocketsAndOpinionsFailure", exception, null, null);
}

///This function is called when a drill down link is clicked on the results page.
function onDrillDownLinkClicked(redirectUrl)
{
    window.parent.location = redirectUrl;
}

function onFullListDrillDownLinkClicked(url)
{
    window.opener.setTimeout('parent.location.replace("' + url + '")', 300); 
    window.open('','_self','');     
    window.close(); 
    target="_parent";
}

function navRefinements(buttonId, url, msg)
{
    if (primaryCriteriaCount == 0)  
    {
        showBasicMessageBox('Please select ' + msg, buttonId);
    }
    else
    {
        window.location=url;
    }
    return false;
}

function setRefinementEntityType(entityType)
{
    // sets which refinement you are removing with the remove button
    refinementSearchCriteria['EntityType'] = entityType;
}


function collapseOrExpandInstructionText()
{
    if (document.getElementById('instructionText').style.display == 'block')
    {
        document.getElementById('instructionText').style.display = 'none';
        document.getElementById('collapseDetailHeader').innerHTML = "Show Description ";
        document.getElementById('collapseDetailImage').src = "/images/gray-plus.gif"; 
    }
    else
    {
        document.getElementById('instructionText').style.display = 'block';
        document.getElementById('collapseDetailHeader').innerHTML = "Hide Description ";
        document.getElementById('collapseDetailImage').src = "/images/gray-minus.gif"; 
    }
    parent.window.resizeCaller();
}

// Method to get full online report.
// This is used from PortalSection View Full Report button.
function GetFullReport(url) 
{
    var onSuccessCallback = function(response) {
        //If the urlReferer is not null, the page is being loaded in a portal, so open full report in popup window.
        if (window.urlReferer) {
            popupLink = document.getElementById('popupCommonLinkInvoker');
            popupLink.href = url;
            popupLink.click();
        }
        else
            window.location = url;
    }
    var onFailureCallback = function(response) {
        handleError(response);
    }
    West.Firm360.Web.WebServices.ProfileManagementWebService.SetProfileInSessionToDefaultSessionType(profileKey, onSuccessCallback, onFailureCallback);
}
