var addSnippetAnnotationFromOuputRedirectUrl = "addSnippetAnnotationFromOuputRedirectUrl"; // id for hidden field to do redirect within add snippet/annotation in customization output page 

var lastOrder ='';
function getEventTypes()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.GetEventTypes( profileKey,
        onGetEventTypesSuccess, onGetEventTypesFailure);
}

function onGetEventTypesSuccess(result)
{
       document.getElementById('legalEventTypes').innerHTML = result; 
}

function onGetEventTypesFailure(result)
{
    handleError(result);
}

function getSectionList()
{
    // Call web service to get list of Name Variants
    West.Firm360.Web.WebServices.OutputConfiguratorService.GetOutputSections(profileKey, primaryFilterIDKey, reportIDKey,
        onGetOutputSectionsSuccess, onGetOutputSectionsFailure);
}

function getSectionListFromEditFormat()
{
    // Call web service to get list of Name Variants
    West.Firm360.Web.WebServices.OutputConfiguratorService.GetOutputSectionsEditMode(
        profileKey,
        function(result)
        {
            SetUndoFromEditFormat();
            document.getElementById('resultsTable').innerHTML = result;
            initTable('reportsTable');
        },
        function(result)
        {
            handleError(result);
        }
    );
}


function onGetOutputSectionsSuccess(result)
{
    SetUndo();
    document.getElementById('resultsTable').innerHTML = result;
    getSectionDataAvailable();

    initTable('reportsTable');
}

function onGetOutputSectionsFailure(exception)
{
    handleError(exception);
}

function reorderList(newOrder)
{
    if (lastOrder != newOrder) {
        West.Firm360.Web.WebServices.OutputConfiguratorService.ReorderList(profileKey, newOrder,
            OnReOrderSuccess, onReOrderFailure);
    } else {
        getSectionList(); 
    }
    lastOrder = newOrder;
}
function reorderListEditView(newOrder)
{
    if (lastOrder != newOrder) {
        West.Firm360.Web.WebServices.OutputConfiguratorService.ReorderList("", newOrder,
            function(response){
                setHasHistoryInUrl(true);
                getSectionListFromEditFormat();
            }, 
            function(response)
            {
                 handleError(response);
            }
       );
    } else {
        getSectionListFromEditFormat(); 
    }
    lastOrder = newOrder;
}

function OnReOrderSuccess() 
{
    setHasHistoryInUrl(true);
    getSectionList();
    deselectAll_click();
    setDeletionButtonsState();
}

function onReOrderFailure(result) 
{
    handleError(result);
}

function Undo()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.Undo(profileKey, OnUndoSuccess, onUndoFailure);
}

function isPdfReady(ticketId)
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.isPdfReady(ticketId, onIsPdfReadySuccess, onIsPdfReadyFail);
}

function onIsPdfReadySuccess(result)
{
    var segments = result.split(',')
    if (segments[0] == "refresh") 
    {
        var ticketId = segments[1];
        var pageCount = segments[2];
        document.getElementById('pageCount').innerHTML = pageCount;
        setTimeout('isPdfReady(\"' + ticketId +'\")', 3000);
    }
    else if (segments[0] == "done")
    {
        document.getElementById("loading").style.display = "none";
        document.getElementById("done").style.display = "block";
        document.getElementById("download").href = segments[1];
    }
}

function onIsPdfReadyFail(result)
{
    West.Firm360.Web.WebServices.LoggingWebService.LogError("output.isPdfReady", result, null, null);
    history.go(-1);
}

function UndoFromEditFormat()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.Undo("", 
        function(result)
        {
            document.getElementById('Wait').style.display = 'none';
            getSectionListFromEditFormat();
        }, 
        function(result)
        {
            document.getElementById('Wait').style.display = 'none';
            DisableUndo(result);
            getSectionListFromEditFormat();
        }
    );
}

function OnUndoSuccess(result) 
{
    document.getElementById('Wait').style.display = 'none';

    if (result == false)
        DisableUndo();
        
    getSectionList();
    getEventTypes();
    window.setTimeout('setDeletionButtonsState()', 500);
}

function onUndoFailure(result) 
{
    //log the exception
    handleError(result); 
}

function SetUndo()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.ItemsInHistory(profileKey, onItemsInHistorySuccess, onItemsInHistoryFailure); 
}
function SetUndoFromEditFormat()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.ItemsInHistory("", onItemsInHistorySuccess, onItemsInHistoryFailure);
}

function onItemsInHistorySuccess(result) 
{
    if (result == true)
        EnableUndo();
    else
        DisableUndo();
}

function onItemsInHistoryFailure(result) 
{
    //log the exception
    handleError(result); 
}

function EnableUndo()
{
    document.getElementById('UndoDisabled').style.display = 'none';
    document.getElementById('RestoreDisabled').style.display = 'none';
    
    if(getHasHistoryInUrlFromUrl() == true){
        document.getElementById('Undo').style.display = 'inline';
    }else{
        document.getElementById('Undo').style.display = 'none';
        document.getElementById('UndoDisabled').style.display = 'inline';
    }
//    
    document.getElementById('Restore').style.display = 'inline';
}

function DisableUndo()
{
    document.getElementById('UndoDisabled').style.display = 'inline';
    
    if(getIsOutputResultOrderTemplateInUrl() == false){
        document.getElementById('RestoreDisabled').style.display = 'inline';
    }
    
    document.getElementById('Undo').style.display = 'none';
    
    if(getIsOutputResultOrderTemplateInUrl() == false){
        document.getElementById('Restore').style.display = 'none';
    }else{
         document.getElementById('Restore').style.display = 'block';
    }
    
    setHasHistoryInUrl(false);   
    
}
    

function DeleteItem(itemID)
{
    document.getElementById(itemID).style.display='none';
    West.Firm360.Web.WebServices.OutputConfiguratorService.DeleteItem(profileKey, itemID,
        OnDeleteSuccess, OnDeleteFailure);
}

function DeleteItems(itemIDs) {
    EnableUndo();
    $.each(
        itemIDs,
        function (index, value) {
            document.getElementById(value).style.display = 'none';
        });

    West.Firm360.Web.WebServices.OutputConfiguratorService.DeleteItems(profileKey, itemIDs,
        OnDeleteSuccess, OnDeleteFailure);
}

function DeleteItemFromEditFormat(itemID)
{
    document.getElementById(itemID).style.display='none';
    West.Firm360.Web.WebServices.OutputConfiguratorService.DeleteItem("", itemID,
        function(result)
        {
            setHasHistoryInUrl(true);
            getSectionListFromEditFormat();
        }, OnDeleteFailure
    );
}

function OnDeleteSuccess()
{
    setHasHistoryInUrl(true);
    getSectionList();
}

function OnDeleteFailure(result)
{
    handleError(result);
}

function RestoreDefaults()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.RestoreDefaults(profileKey,
        OnUndoSuccess, onUndoFailure);   
        
    this.UpdateApplySavedReportFormatViewControls();   
}
function RestoreDefaultsFromEditFormat()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.RestoreDefaults("",
        function (result) {
            document.getElementById('Wait').style.display = 'none';
            getSectionListFromEditFormat();
            setDeletionButtonsState();
        },
        function (result) {
            document.getElementById('Wait').style.display = 'none';
            DisableUndo(result);
            getSectionListFromEditFormat();
        }
    );        
}

// clear output session cache and redirect to result output page
function RunOutputPageAction(redirect)
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.ClearOutputSettingsFromSession(profileKey,
        function(result)
        {
             window.open(redirect, "result_output_window");
        }, 
        function(result)
        {
             handleError(result);
        }
    );            
}

/// Start - Saved Report Output Template 

function ApplyTemplateAction(controlId)
{
     var Ids = GetApplyTemplateButtonAndDropDownIds();
    var hfId = Ids[2];
    var hiddenField =  document.getElementById(hfId);
    var templateGuid;
    
    if(hiddenField != null)
    {
        templateGuid = hiddenField.value;      
    }
    else
    {
        return false;
    }
    
    // call webservice to determine what sections in saved templated are not applicable for given report.
    West.Firm360.Web.WebServices.OutputConfiguratorService.ApplyTemplateCheckSectionAvailability(profileKey, templateGuid,
        function(result)
        {
             //prompt user that some sections do not have data and will not be included in report.
             if(result.length > 0)
             {
                 var message = "The following sections from this report template do not have data: <br><br>";
                 for(var i = 0; i < result.length;i++)
                 {
                    message += result[i] + "<br>";
                 }
                message += "<br><br> If you would like to apply the template to the results with these sections excluded, click OK.<br>";
                showBasicMessageBoxConfirm(message, true, __doPostBack, controlId, null, null, null, null )
             }
             else
             {
                 // OK - apply template
                 __doPostBack(controlId, "");
             }
        }, 
        function(result)
        {
             handleError(result);
        }
    );            
}

function getHasHistoryInUrlFromUrl(){
    // set the correct serachtype on the url
    var url = document.location.href;
    if (url.indexOf('#HasHistory', 0) > 0)
    {
        var startPos = url.indexOf('#HasHistory', 0);
        var value = url.substr(startPos, url.length - startPos);
        if(value.split('=')[1] == "false"){
            return false;
        }else{
            return true;
        }
    }
    else {
        return false;
    }   
}
function getIsOutputResultOrderTemplateInUrl(){
    // set the correct serachtype on the url
    var url = document.location.href;
    
    if (url.indexOf('#IsOutputResultOrderTemplate', 0) > 0)
    {
        var startPos = url.indexOf('#IsOutputResultOrderTemplate', 0);
        var value = url.substr(startPos, url.length - startPos);
        if(value.split('=')[1] == "false"){
            return false;
        }else{
            return true;
        }
    }
    else {
        return false;
    }   
}

function setIsOutputResultOrderTemplateInUrl(isAvailable){
    var parameterVal = isAvailable.toString();
    var origUrl = document.location.href;
    var newUrl;
    if (origUrl.indexOf('#IsOutputResultOrderTemplate', 0) > 0) 
    {
        var startPos = origUrl.indexOf('#IsOutputResultOrderTemplate');
        // take off the old
        newUrl = origUrl.substr(0, startPos);
        // put on the new
        newUrl = newUrl + '#IsOutputResultOrderTemplate=' + parameterVal;
    }
    else {
        newUrl = origUrl + '#IsOutputResultOrderTemplate=' + parameterVal;
    }
    document.location.href = newUrl;  
}
function setHasHistoryInUrl(isAvailable){
    var parameterVal = isAvailable.toString();
    var origUrl = document.location.href;
    var newUrl;
    if (origUrl.indexOf('#HasHistory', 0) > 0) 
    {
        var startPos = origUrl.indexOf('#HasHistory');
        // take off the old
        newUrl = origUrl.substr(0, startPos);
        // put on the new
        newUrl = newUrl + '#HasHistory=' + parameterVal;
    }
    else {
        newUrl = origUrl + '#HasHistory=' + parameterVal;
    }
    document.location.href = newUrl;  
}

function UpdateApplySavedReportFormatViewControls()
{
    var Ids = GetApplyTemplateButtonAndDropDownIds();
    var dropDownId = Ids[0];
    var applyButtonId = Ids[1];
    var dropdown = document.getElementById(dropDownId);  
    var button = document.getElementById(applyButtonId);
    
    if(dropdown != null && button != null)
    {
        dropdown.value = "";
        button.setAttribute("disabled");
        button.disabled = true;
    }
    
    setHasHistoryInUrl(false);
    setIsOutputResultOrderTemplateInUrl(false)
}
function ChangeApplyTemplateButtonOnSelectIndexChange(value)
{  
    var Ids = GetApplyTemplateButtonAndDropDownIds();
    var applyButtonId = Ids[1]; 
    var button = document.getElementById(applyButtonId);  
    if(button == null)
    {
        return;
    }   
    if(value.length != 0)
    {
        try{
            //IE
            button.setAttribute("disabled");
            button.disabled = false;
        }
        catch(e)
        {
            //FireFox
            button.removeAttribute("disabled");
        } 
        setCurrentSelectedSavedTemplateFromDropDownToHiddenField(value);
    }
    else
    {
        button.setAttribute("disabled", "disabled"); 
    }
}
function setCurrentSelectedSavedTemplateFromDropDownToHiddenField(value)
{
    var Ids = GetApplyTemplateButtonAndDropDownIds();
    var hfId = Ids[2];
    var hiddenField =  document.getElementById(hfId);
    if(hiddenField != null)
    {
        hiddenField.value = value;
    }
}
/// End - Saved Report Output Template 


function getSectionDataAvailableForResults()
{  
    West.Firm360.Web.WebServices.OutputConfiguratorService.SectionDataAvailable(profileKey, getSectionsForResultsSuccess, getSectionsFailure);
}

function getSectionsForResultsSuccess(result)
{
    var returnVal = result.split("!");
    var finished = returnVal[0].split(";");
    var error = returnVal[1].split(";");
    var noData = returnVal[2].split(";");
    for (i =1; i<error.length; i++) 
    {
        if (document.getElementById("noData"+trim(error[i])))
        {
            document.getElementById("hasData" + trim(error[i])).style.display = "none";
            document.getElementById("noData" + trim(error[i])).style.display = "inline";
        } else
        {
        }
    }
    
    for (i =1; i<noData.length; i++) 
    {
        // Fix for Tracker 4470
        // In the case of classifications, check the rest of the classifications before disabling the link. 
        // All classifications are based on the same link.
        if ((noData[i] == "^IntellectualPropertyPatents^IPPatentPCTFilings^Classification" ||
            noData[i] == "^IntellectualPropertyPatents^IPPatentPCTFilings^International Classification" ||
            noData[i] == "^IntellectualPropertyPatents^IPPatentPCTFilings^Derwent Classification")) {
            // find the finished classifications
            var finishedClassifications = jQuery.grep(finished, function(n) {
                return (n == "^IntellectualPropertyPatents^IPPatentPCTFilings^Classification" ||
                          n == "^IntellectualPropertyPatents^IPPatentPCTFilings^International Classification" ||
                          n == "^IntellectualPropertyPatents^IPPatentPCTFilings^Derwent Classification");
            });

            if (finishedClassifications.length <= 0) {
                //disable the link
                if (document.getElementById("noData" + trim(noData[i]))) 
                {
                    document.getElementById("hasData" + trim(noData[i])).style.display = "none";
                    document.getElementById("noData" + trim(noData[i])).style.display = "inline";
                }

            }
        }
        else if ((noData[i] == "^IntellectualPropertyPatents^IPPatentApplications^Classification" ||
            noData[i] == "^IntellectualPropertyPatents^IPPatentApplications^International Classification" ||
            noData[i] == "^IntellectualPropertyPatents^IPPatentApplications^Derwent Classification")) {
            // find the finished classifications
            var finishedClassifications = jQuery.grep(finished, function(n) {
            return (n == "^IntellectualPropertyPatents^IPPatentApplications^Classification" ||
                          n == "^IntellectualPropertyPatents^IPPatentApplications^International Classification" ||
                          n == "^IntellectualPropertyPatents^IPPatentApplications^Derwent Classification");
            });

            if (finishedClassifications.length <= 0) {
                //disable the link
                if (document.getElementById("noData" + trim(noData[i]))) {
                    document.getElementById("hasData" + trim(noData[i])).style.display = "none";
                    document.getElementById("noData" + trim(noData[i])).style.display = "inline";
                }

            }
        }
        else if ((noData[i] == "^IntellectualPropertyPatents^IPPatentGrantedPatents^Classification" ||
            noData[i] == "^IntellectualPropertyPatents^IPPatentGrantedPatents^International Classification" ||
            noData[i] == "^IntellectualPropertyPatents^IPPatentGrantedPatents^Derwent Classification")) {
            // find the finished classifications
            var finishedClassifications = jQuery.grep(finished, function(n) {
            return (n == "^IntellectualPropertyPatents^IPPatentGrantedPatents^Classification" ||
                          n == "^IntellectualPropertyPatents^IPPatentGrantedPatents^International Classification" ||
                          n == "^IntellectualPropertyPatents^IPPatentGrantedPatents^Derwent Classification");
            });

            if (finishedClassifications.length <= 0) {
                //disable the link
                if (document.getElementById("noData" + trim(noData[i]))) {
                    document.getElementById("hasData" + trim(noData[i])).style.display = "none";
                    document.getElementById("noData" + trim(noData[i])).style.display = "inline";
                }

            }
        }
        else 
        {
            if (document.getElementById("noData" + trim(noData[i]))) {
                document.getElementById("hasData" + trim(noData[i])).style.display = "none";
                document.getElementById("noData" + trim(noData[i])).style.display = "inline";

            } 
        }
    }

    if (finished[0] == "done") 
    {
        clearInterval(previewInterval);
    }
}


function getSectionDataAvailable()
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.SectionDataAvailable(profileKey, getSectionsSuccess, getSectionsFailure);
}

function getSectionsSuccess(result)
{
    var returnVal = result.split("!");
    var finished = returnVal[0].split(";");
    var error = returnVal[1].split(";");
    var noData = returnVal[2].split(";");
    for (i = 1; i < finished.length; i++)
    {
        if (document.getElementById("img" + finished[i] + ";"))
        {
            var details = finished[i].split("^");
            document.getElementById("unavailable" + finished[i] + ";").style.display = "none";
            document.getElementById("available" + finished[i] + ";").style.display = "inline";
            document.getElementById("annotationButton" + finished[i] + ";").style.display = "inline";
        } else
        {
        }
    }
    for (i = 1; i < error.length; i++)
    {
        if (document.getElementById("img" + error[i] + ";"))
        {
            var details = error[i].split("^");
            document.getElementById("unavailable" + error[i] + ";").style.display = "none";
            document.getElementById("available" + error[i] + ";").style.display = "none";
            document.getElementById("annotationButton" + error[i] + ";").style.display = "none";
            document.getElementById("error" + error[i] + ";").style.display = "inline";
        } else
        {
        }
    }

    //    alert(document.getElementById(noData[1]+";").innerHTML)
    for (i = 1; i < noData.length; i++)
    {
        if (document.getElementById(noData[i] + ";"))
        {
            document.getElementById("unavailable" + noData[i] + ";").style.display = "none";
            document.getElementById("available" + noData[i] + ";").style.display = "none";
            document.getElementById("error" + noData[i] + ";").style.display = "none";
            document.getElementById("text" + noData[i] + ";").style.backgroundColor = "gray";
            document.getElementById("annotationButton" + noData[i] + ";").style.display = "none";
            // Hide the normal section label and show the label with no data message
            if (document.getElementById("hasDataSectionLabel" + noData[i] + ";"))
            {
                document.getElementById("hasDataSectionLabel" + noData[i] + ";").style.display = "none";
            }
            if (document.getElementById("hasNoDataSectionLabel" + noData[i] + ";"))
            {
                document.getElementById("hasNoDataSectionLabel" + noData[i] + ";").style.display = "inline";
            }
        } else
        {
        }
    }

    if (finished[0] == "done")
    {
        clearInterval(previewInterval);
    }
}

function getSectionsFailure(result)
{
    clearInterval(previewInterval);

    handleError(result);
}



function handleError(result)
{
    if (result.get_message() == "Authentication failed.")
    {
        window.location = "/signon/default.aspx";
    }
    
    West.Firm360.Web.WebServices.LoggingWebService.LogError("output.handleError", result, null, null);
}

function toggleIncludeFullListInOutput(controlId)
{
    var control = document.getElementById(controlId);
    var include = true;
    if (control != null)
    {
        if (control.alt.indexOf("Remove") >= 0)
        {
            include = false;
        }
    }
    
    var sortExpressionValue = "";
    var sortExpression = document.getElementById("sortExp");    
    if (sortExpression != null)
    {
        sortExpressionValue = sortExpression.value;
    }
    
    West.Firm360.Web.WebServices.OutputConfiguratorService.ToggleIncludeFullListInOutput(
        profileKey, include, sortExpressionValue,
            onToggleIncludeFullListInOutputSuccess, onToggleIncludeFullListInOutputFailure, controlId);

}

function onToggleIncludeFullListInOutputSuccess(result, controlId)
{

    var control = document.getElementById(controlId);
    var include = true;
    if (control != null)
    {
        if (control.alt.indexOf("Remove") >= 0)
        {
            include = false;
        }
    }

    var documentType;
    if (result == West.Firm360.DataModel.Profiles.Sections.SectionType.CompanySummarySECFilings)
    {
        viewType = "SEC Filing";
    }
    else
    {
        viewType = "full list";
    }
    if (include == true)
    {
        showInformationalMessageBox("This " + viewType + " will be included in your output");
        control.src = "/images/Remove_fr_Output.gif";
        control.alt = "Remove From Output";        
    }
    else
    {
        showInformationalMessageBox("This " + viewType + " will not be included in your output");  
        control.src = "/images/Add_To_Output.gif";
        control.alt = "Add To Output";          
    }
    
}

function onToggleIncludeFullListInOutputFailure(exception)
{
   
}

//Function to add selected snippets to output
function addSnippetsToOutput() 
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.AddSnippetsToOutput(profileKey,
                      function() {
                          //Load the section list. Call the function on the parent since the section list is on the parent window.
                          parent.getSectionList();
                          //Close the add snippets window.
                          var obj = parent.document.getElementById('TB_closeWindowButton');
                          obj.click();
                      },
                      function() {
                          //handle error
                      }
                  );
}

function addSnippets_Click(url)
{
    proxyLink = document.getElementById('addSnippetsLinkInvoker');
    if (proxyLink) {
        proxyLink.title = "";
        proxyLink.href = url + "&keepThis=true&TB_iframe=true&width=700&height=500";
        proxyLink.click();
    }
}

function addAnnotations_Click(url)
{
    proxyLink =  document.getElementById('addSnippetsLinkInvoker');
   
    if (proxyLink == null)
    {
        // coming from output page
        var old = parent.document.getElementById("TB_title");
        if(old)
        {
            // remove current thickbox div, this is to prevent nested thickbox rendering.
            if(old.parentNode)
            {
                old.parentNode.removeChild(old);
            }
        }
        proxyLink =  parent.document.getElementById('addSnippetsLinkInvoker');
    }
    
    // find global profileKey-- depending on context retrieve from parent or current context
    var _profileKey = (typeof(profileKey) == "undefined") ? parent.profileKey: profileKey;
    
    if(proxyLink != null && _profileKey != null)
    {
        proxyLink.title = "";
        proxyLink.href = url + "&profileKey=" + _profileKey  + "&keepThis=true&TB_iframe=true&width=700&height=500";
        proxyLink.click();
    }
}


// Add Annotation - makes a webservice call to add an annotation to the specified
// ProfileSectionInfoDisplay object.  This will be called from the Add Snippet/Annotation page.
// The Annotation plus/minus image does not have to be updated here since the parent gets reloaded.
function addAnnotationToSection(button, profileKey, annotationId, dataSource, sectionType, snippetId, sectionViewType)
{
    button.src = "/images/remove_orange.png";
    
    West.Firm360.Web.WebServices.OutputConfiguratorService.AddAnnotationToProfileSectionInfoDisplay(
        profileKey, annotationId, dataSource, sectionType, snippetId, sectionViewType,
        
        function(result)
        {
            SetUndo();
            parent.parent.location.reload(true);           
        },
        function(result)
        {
            // Log the error
        }
     );
}

// Remove Annotation - makes a web service call to remove an annotation from a 
// specified ProfileSectionInfoDisplay object.  Also updates the Annotation image to show a "Plus".
function removeAnnotationFromSection(button, profileKey, dataSource, sectionType, snippetId, snippetUrl, sectionViewType)
{
    West.Firm360.Web.WebServices.OutputConfiguratorService.RemoveAnnotationFromProfileSectionInfoDisplay(
        profileKey, dataSource, sectionType, snippetId,sectionViewType,

        function(result) {
            if (result) {
                if (button != null) {
                    button.src = "/images/gray-plus.gif";
                    button.onclick = function() { addAnnotations_Click(snippetUrl); return false; }
                    SetUndo();
                }
            } else {
                // removing the annotation was unsuccessful
            }
        },
        function(result) {
            // Log ERROR
        }
    );
}

// Function: run asynchronus call to render view from output customization for snippets and annnotations.
function OnAddSnippetPageLoad_event(myMonitorSection, userProfileHistoryType, entityType, canvasId, sectionType, sectionViewType, datasourceType, snippetId, url)
{
    initializeThickBox = false;
    if(typeof(myMonitorActionHandler) != "undefined")
    {        
        // create target catered for Snippets and Annotations.
        // Somethings are unique: SectionType, DataSourceType, ActionType
        var myMonitorAction = 1; //West.Firm360.Thomlets.MyMonitor.Add
        var target = new MyMonitorSearchSelectionState(entityType, myMonitorSection, userProfileHistoryType, canvasId); 
        var currentPageSizeSelection = myMonitorActionHandler.getCurrentPageSizeSelection();     
        target.setPageSize(currentPageSizeSelection); 
        target.setIsFirstLoad(true);
        target.setSectionType(sectionType);
        target.setSectionViewType(sectionViewType);
        target.setDataSourceType(datasourceType);
        target.setMyMonitorAction(myMonitorAction);  
        target.setSelectedSnippetId(snippetId);
        myMonitorActionHandler.onPageLoad(target, url);
               
        // persist redirect data on save annotation/cancel actions in thickbox view.
        var hiddenFieldAddAnnotationRedirectFromOutputPage = parent.document.getElementById(addSnippetAnnotationFromOuputRedirectUrl);
        var hiddenFieldCurrentEntityOnAddSnippetAnnotationView = parent.document.getElementById("currentEntityOnAddSnippetAnnotationView");
        if(hiddenFieldAddAnnotationRedirectFromOutputPage)
        {
            hiddenFieldAddAnnotationRedirectFromOutputPage.value = url;
        }
        if(hiddenFieldCurrentEntityOnAddSnippetAnnotationView)
        {
            hiddenFieldCurrentEntityOnAddSnippetAnnotationView.value = entityType;
        }
        ///
    }
}

/*
 * Function to select all checkboxes on the page.
 */
function selectAll_click() {

    $('input:visible[id *= "delete_"]').attr('checked', true);
    setDeletionButtonsState();
}

/*
 * Function to deselect all checkboxes on the page.
 */
function deselectAll_click() {

    $('input:visible[id *= "delete_"]').removeAttr('checked');
    setDeletionButtonsState();
}

/*
 * Function to delete all selected sections on the page.
 */
   function deleteSelected_click() 
   {
        // Determine if any checkboxes are selected.
        var selectedCheckboxes = $('input:checked[id *= "delete_"]');
        var checkboxes = $('input:visible[id *= "delete_"]');

        if (selectedCheckboxes.length == checkboxes.length) {
            var message =   "All sections are selected for deletion, please de-select at least one section for output to your report.";
            showBasicMessageBoxAlert(message);
        }
        else {
            var itemIDs = new Array();
            if (selectedCheckboxes && selectedCheckboxes.length > 0) {
                // Parse out the IDs of the items that are supposed to be deleted and delete them.
                $.each(
                selectedCheckboxes,
                function (index, value) {

                    var itemID = $(value).attr('id').replace('delete_', '');
                    itemIDs.push(itemID);
                });

                if (itemIDs.length > 0) {

                    DeleteItems(itemIDs);
                }
            }
            setDeletionButtonsState();
        }
    }

/*
 * Function to set the enabled/disabled state of the three deletion-related
 * buttons (select all, de-select all and delete selected).
 */
    function setDeletionButtonsState() 
    {
    // Get access to the three buttons so that their images can be manipulated if
    // need be.
    var btnSelect = $('img#btnSelectAll');
    var btnDeselectAll = $('img#btnDeselectAll');
    var btnDeleteSelected = $('img#btnDeleteSelected');

    // Determine if any checkboxes are selected.
    var selectedCheckboxes = $('input:visible:checked[id *= "delete_"]');
    var checkboxes = $('input:visible[id *= "delete_"]');

    // Only process button state if there are checkboxes on the page
    if (checkboxes && checkboxes.length > 0) 
    {        
        if (selectedCheckboxes && selectedCheckboxes.length > 0) 
        {
            // there are some or all checkboxes selected
            if (checkboxes && checkboxes.length == selectedCheckboxes.length) 
            {
                // All checkboxes are checked.
                $(btnSelect).attr('src', '/images/select_all_disabled.png');
                $(btnSelect).css('cursor', 'default');
            }
            else 
            {
                 // Some checkboxes are selected, but not all
                 $(btnSelect).attr('src', '/images/select_all.png');
                  $(btnSelect).css('cursor', 'pointer');
             }

             $(btnDeselectAll).attr('src', '/images/deselect_all.png');
             $(btnDeleteSelected).attr('src', '/images/delete_selected.png');

             $(btnDeselectAll).css('cursor', 'pointer');
             $(btnDeleteSelected).css('cursor', 'pointer');
        } 
         // no checkboxes are selected
         else 
        {
            $(btnSelect).attr('src', '/images/select_all.png');
            $(btnDeselectAll).attr('src', '/images/deselect_all_disabled.png');
            $(btnDeleteSelected).attr('src', '/images/delete_selected_disabled.png');

            $(btnSelect).css('cursor', 'pointer');
            $(btnDeselectAll).css('cursor', 'default');
            $(btnDeleteSelected).css('cursor', 'default');
        }
    }
 }

 $(window).load(function () {
     window.setTimeout('setDeletionButtonsState()', 500);
 });
