var ApplicationPath = '/databases/modus';

var SiteContentsId = 'sitecontents';
var TableOfContentsId = 'tableofcontents';
var PasswordFieldId = 'tlrnz_password_field';
var BookmarkAnchorId = 'tlrnz_bookmark';
var PasswordFormClassName = 'password-form';
var SearchTemplateClassName = 'SearchTemplate';
var FormIsHiddenClassName = 'form-is-hidden';
var SecondaryAuthorisationFormId = 'secondary-authorisation-form';
var DBLoginSubmitButton = 'dblogin_submit';
var DBLoginPasswordInputBox = 'password_field';
var DBLoginPasswordCheckBox = 'rememberme';
var MegaSearchFormId = 'megasearch';
var ExportFormId = 'tlrnz_export_content_form';
var downloadLegislationButton = 'tlrnz_download_Legislation';
var contentPagingStateTop = 'contentPagingTop';
var contentPagingStateBottom = 'contentPaging';
var MySelectionsFormId = 'tlrnz_my_selections_form';
var MySelectionsCompileCheckedButtonId = 'tlrnz_compile_checked';
var MySelectionsExportCheckedButtonId = 'tlrnz_export_checked';
var MySelectionsRemoveCheckedButtonId = 'tlrnz_remove_checked';
var MySelectionsIncludeAdditionalContentButtonId = 'tlrnz_include_additional_content_dropdown';
var MySelectionsExcludeAdditionalContentButtonId = 'tlrnz_exclude_additional_content_dropdown';
var MySelectionsCheckAllButton = 'tlrnz_my_selections_select_all';
var MySelectionsUncheckAllButton = 'tlrnz_my_selections_select_none';
var MySelectionsCheckboxName = 'MySelectionsSelectedItems';
var MySelectionsCheckItemsPostKey = 'my.selections.checked.items';
var SessionDictionaryManagerPageName = 'list.manager';
var HitListFormId = 'tlrnz_submit_my_selections';
var HitListNavigationDivId = 'tlrnz_hitlist_navigation';
var HeartbeatPageName = 'ping';
var REFRESH_INTERVAL = 900000;//milliseconds
var ReturnToNormalViewLinkId = 'return_to_normal_view_button';
var InlinedFragmentsKey = "inlined-fragments";

// fired by window.onLoad
function onLoadHandler()
{
    setupEventHandlers();
    checkJumpTo();
    setFocusOnPasswordField();
    initiatePeriodicRefresh();
    setScrollBarsOnTables();
}


//Add a scrollbar and hightlight large tables.
function setScrollBarsOnTables()
{
    //Are we on the 'Print this document' page?
    var printMode = $(ReturnToNormalViewLinkId);
    
    //Check each large table on the page.
    $$('.large_table').each( function(t){
            t.down('table').setStyle( { tableLayout :'auto'} );                            
            if(!printMode)
            {
               t.down('div').addClassName('inner_large_table_div');
               if(msieversion() > 0 )
               {
                    t.down('div').setStyle( {overflowX:'scroll'} );
               }                          
            }        
        }            
    );        
}

document.observe("dom:loaded",onLoadHandler);

// hack to correctly position
function ieResizeHack()
{
    var graphic = $("tlrnz_toggle_related_sidebar");
    if(!graphic)
        return;

    graphic.style.pixelRight=20;
    if(graphic.hasClassName('tlrnz_rightbar_hidden'))
        graphic.style.pixelRight=0;
    else
        graphic.style.pixelRight=221;
}
function msieversion()
// Return Microsoft Internet Explorer (major) version number, or 0 for others.
// This function works by finding the "MSIE " string and extracting the version number
// following the space, up to the semicolon
{
    // is Microsoft Internet Explorer; return version number
    if(Prototype.Browser.IE)
    {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf ( "MSIE " );
        return parseFloat ( ua.substring ( msie+5, ua.indexOf ( ";", msie ) ) );
   }
    return 0;    // is other browser
}

function initiatePeriodicRefresh()
{
    setInterval(sendHeartbeat, REFRESH_INTERVAL);
}

function sendHeartbeat()
{
    new Ajax.Request(ApplicationPath+'/'+HeartbeatPageName, {method:"get"});
}

function setFocusOnPasswordField()
{
    var passwordField = $(PasswordFieldId);
    if (passwordField)
    {
        // IE will sometimes fail this test for the secondary login form, where the password field is not visible,
        // by virtue of its parent having style display:none in some instances.
        try{ passwordField.focus(); } catch (e){}
    }
}

function setupEventHandlers()
{
    var bookmarkNode = $(BookmarkAnchorId);
    if (bookmarkNode)
        bookmarkNode.onclick = addBookmark;

    // Get All forms within the Document.
        var formNodes = $$('form').each( function (formNode)
        {
            // If Form contains "SearchTemplateClassName".
                if (formNode.hasClassName(SearchTemplateClassName))
        {
          // Handler for Search-Form Submit
          // Note: BDLogin-Submit & MegaSearch-Submit reside on Same Form!
                    formNode.observe('submit', handleSearchFormSubmit);
                }
        // If Form contains "PasswordFormClassName".
//                else if (formNode.hasClassName(PasswordFormClassName))  // not required here since we are handling this in the authentication xslt
//                {
//            // Handler for Login Submit.
//                    formNode.observe('submit', handleLoginFormSubmit);  
//                }
        });
    
  // Hook-up Manual Submit functionality for DBLogin.
  // Note: BDLogin-Submit & MegaSearch-Submit reside on Same Form!
    var megaSearchForm = $(MegaSearchFormId);
    if (megaSearchForm)
    {
    // Handlers for DBLogin Submit - Manual Submit!
    var dbLoginSubmitButtonNode = $(DBLoginSubmitButton);
    if (dbLoginSubmitButtonNode)
        {
        // OnClick handler for DBLogin Submit Button!
        dbLoginSubmitButtonNode.onclick = function() { submitDbLogin(megaSearchForm) };

      // KeyPress Handlers - <Enter Key> to Trigger Manual Submit.
      var dbLoginPasswordInputBoxNode = $(DBLoginPasswordInputBox);
      if (dbLoginPasswordInputBoxNode)
          dbLoginPasswordInputBoxNode.onkeypress = function(e) { return submitKeyPress(e, dbLoginSubmitButtonNode) };
      var dbLoginPasswordCheckBoxNode = $(DBLoginPasswordCheckBox);
      if (dbLoginPasswordCheckBoxNode)
          dbLoginPasswordCheckBoxNode.onkeypress = function(e) { return submitKeyPress(e, dbLoginSubmitButtonNode) };
        }
  }

    // Show/Hide Legislation Button - Only Display If Legislation is Available to Download - (ie. Element Exists)
    var downloadLegislationButtonNode = $(downloadLegislationButton);
    if ((downloadLegislationButtonNode) && ($("source-pdf") == null)) // Element will only Exist if Leg/Pre-Leg PDF Exists!
    {
        // Hide the Button-Node & the Containing ListItem-Node
        $(downloadLegislationButtonNode).hide();
        $($(downloadLegislationButtonNode).parentNode).hide(); // Required for IE!!!
    }

    // Show/Hide Document-Paging - Only for Briefcase - (Initial Paging Display - Page-Load)
    var contentPagingStateTopNode = $(contentPagingStateTop);
    var contentPagingStateBottomNode = $(contentPagingStateBottom);
    if ((contentPagingStateTopNode) && (contentPagingStateBottomNode) && ($("content-paging-state") != null)) // Element will only Exist if contentPaging_isHidden Exists!
    {
        // Hide/Show the Content-Paging Display (ie. the Page 1, 2, 3...)
        $(contentPagingStateTopNode).style.display = $("content-paging-state").getAttribute("display-state");
        $(contentPagingStateBottomNode).style.display = $("content-paging-state").getAttribute("display-state");
    }

    var siteContentsNode = $(SiteContentsId);
    if (siteContentsNode && handleClick)
        siteContentsNode.onclick = handleClick;

    var tocContentsNode = $(TableOfContentsId);
    if (tocContentsNode && handleClick)
        tocContentsNode.onclick = function(e) { return handleClick(e, true); }

    var mySelectionsForm = $(MySelectionsFormId);
    if (mySelectionsForm)
    {
        var compileCheckedButtonNode = $(MySelectionsCompileCheckedButtonId);
        if (compileCheckedButtonNode)
            compileCheckedButtonNode.onclick = function() { compileCheckedItems(mySelectionsForm) };

        var exportCheckedButtonNode = $(MySelectionsExportCheckedButtonId);
        if (exportCheckedButtonNode)
            exportCheckedButtonNode.onclick = function() { exportCheckedItems(mySelectionsForm) };

        var removeCheckedButtonNode = $(MySelectionsRemoveCheckedButtonId);
        if (removeCheckedButtonNode)
            removeCheckedButtonNode.onclick = function() { removeCheckedItems(mySelectionsForm) };

        var includeExtraContentNode = $(MySelectionsIncludeAdditionalContentButtonId);
        if (includeExtraContentNode)
            includeExtraContentNode.onchange = function() { applyAdditionalContentAcrossCheckedItems(mySelectionsForm) }

        var excludeExtraContentNode = $(MySelectionsExcludeAdditionalContentButtonId);
        if (excludeExtraContentNode)
            excludeExtraContentNode.onchange = function() { applyAdditionalContentAcrossCheckedItems(mySelectionsForm) }

        // MySelections Selection
        BindMySelectionsSelectedItems(mySelectionsForm, MySelectionsCheckAllButton, true);
        BindMySelectionsSelectedItems(mySelectionsForm, MySelectionsUncheckAllButton, false);
        // Additional Content

        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_Commentary', 'Commentary');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_Editorial', 'EditorialNotes');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_History', 'HistoryNotes');

        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_Updater', 'Updater');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_Contents', 'Contents');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_CaseSummary', 'CaseSummary');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_Headnote', 'Headnote');        
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_CitingReferences', 'CitingReferences');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_JudgmentText', 'JudgmentText');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_Amendments', 'Amendments');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_Amends', 'Amends');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_CaseLaw', 'CaseLaw');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_SubordinateLegislation', 'SubordinateLegislation');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_PursuantTo', 'PursuantTo');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_FormsAndPrecedents', 'FormsAndPrecedents');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_LegislationReferredTo', 'LegislationReferredTo');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_RelatedDocuments', 'RelatedDocuments');

        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_ActsFromThisBill', 'ActsFromThisBill');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_SupplementaryOrderPapers', 'SupplementaryOrderPapers');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_SourceBills', 'SourceBills');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_EarlierLaterStages', 'EarlierLaterStages');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_BillsReferredTo', 'BillsReferredTo');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_RelatedBills', 'RelatedBills');
        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_BrookersBills', 'BrookersBills');

        BindMySelectionsAdditionContent(mySelectionsForm, 'tlrnz_my_selections_select_CasesCited', 'CasesCited');

    }

    var hitListForm = $(HitListFormId);
    if (hitListForm)
    {
        hitListForm.onclick = function(e)
        {
            var t = getEventTarget(e);

            if (t!=null && t.nodeName.toLowerCase() == "a" && t.parentNode.id != HitListNavigationDivId)
                return handleHyperlinkClick(t, null);
        }
    }

    var returnToNormalViewLink = $(ReturnToNormalViewLinkId);
    if (returnToNormalViewLink)
        returnToNormalViewLink.onclick = function() { history.back(); return false; }

    if(msieversion() > 0 && msieversion() < 7)
    {
        var contentNode = $("contentFrame");
        if(contentNode)
        {
            contentNode.onresize = ieResizeHack;
            if(checkForOversizeContent(contentNode))
                issueOversizeWarning();
        }
    }

    if(msieversion() > 0 && msieversion() < 8)
    {
    contentarea = $("actualContentArea");
    if(contentarea)
        contentarea.oncopy = function() { DoFormattedCopy(); };
  }
}

function DoFormattedCopy()
{
    if (window.event.shiftKey)
        return;


    var range = document.selection.createRange();
    var collapsedrange = range.duplicate();
    var wrapper = range.parentElement();

    collapsedrange.collapse(true);
    var firstelement = collapsedrange.parentElement();

    var container = document.createElement("div");
    container.style.display = "none";
        container.innerHTML = range.htmlText;;

    document.body.appendChild(container);

    for(var i=container.childNodes.length;i>0;i--) {
        ParseNodes(container.childNodes[i]);
    }

        //here we re-serialize the selection in an iframe 
        // to get a valid document fragment
    var CopyIFrame = document.createElement("iframe");
        CopyIFrame.setAttribute("id", "copy-iframe");
        CopyIFrame.style.width = 0+"px";
        CopyIFrame.style.height = 0+"px";
        document.body.appendChild(CopyIFrame);

        // TODO: we can do this faster and better by implementing
        // techniques used  at http://mozile.mozdev.org/0.8/doc/jsdoc/
    document.frames['copy-iframe'].document.open();
    document.frames['copy-iframe'].document.write(container.innerHTML);
    document.frames['copy-iframe'].document.close();

    var copyDoc = document.frames['copy-iframe'].document;
    copyDoc.execCommand("SelectAll");   
    copyDoc.execCommand("Copy");
    copyDoc.execCommand("Unselect");

    document.body.removeChild(CopyIFrame);
    document.body.removeChild(container);

    event.returnValue = false;
    return(false);
}

function ParseNodes(elem) {

    if (elem == null)
        return;

    if (elem.nodeType == 1) {
        elem.style.fontSize   = elem.currentStyle.fontSize;
        elem.style.color      = elem.currentStyle.color;
        elem.style.fontWeight = elem.currentStyle.fontWeight;
        elem.style.fontFamily = elem.currentStyle.fontFamily;
    }

    if (elem.childNodes != null) {
        for(var i=elem.childNodes.length-1;i>-1;i--) {
            ParseNodes(elem.childNodes[i]);
        }
    }
    if (elem.nodeType == 1 && elem.nodeName == 'DIV' && elem.className == "list-itemfirstline" && elem.childNodes != null) {
        var newnode = document.createElement('SPAN');
        var spacenode = document.createTextNode(' ');
        newnode.appendChild(spacenode);

        newnode.style.fontSize   = elem.currentStyle.fontSize;
        newnode.style.color      = elem.currentStyle.color;
        newnode.style.fontWeight = elem.currentStyle.fontWeight;
        newnode.style.fontFamily = elem.currentStyle.fontFamily;

        if (elem.childNodes != null)
            for(var i=0;i<elem.childNodes.length;i++) {
                newnode.appendChild(elem.childNodes[i].cloneNode(true));
            }
        elem.replaceNode(newnode);

    }
    else if (elem.nodeType == 1 && (elem.nodeName == 'H1' || elem.nodeName == 'H2' || elem.nodeName == 'H3' || elem.nodeName == 'H4')) {
        var newnode = document.createElement('DIV');

        newnode.style.fontSize   = elem.currentStyle.fontSize;
        newnode.style.color      = elem.currentStyle.color;
        newnode.style.fontWeight = elem.currentStyle.fontWeight;
        newnode.style.fontFamily = elem.currentStyle.fontFamily;

        if (elem.childNodes != null) {
            for(var i=0;i<elem.childNodes.length;i++) {
                newnode.appendChild(elem.childNodes[i].cloneNode(true));
            }
        }
        elem.replaceNode(newnode);

    }
    else if (elem.nodeType == 1 && elem.nodeName == 'DIV' && elem.className == "list-item" && elem.childNodes != null) {
        var newnode = document.createElement('UL');

        newnode.style.marginBottom = elem.currentStyle.marginBottom;
        newnode.style.marginTop = elem.currentStyle.marginTop;

        if (elem.childNodes != null)
            while(elem.firstChild != null) {
                newnode.appendChild(elem.firstChild);
            }

        elem.insertBefore(newnode, null);
    }
}


function issueOversizeWarning()
{
    alert("Some content may not fit in your browser window. Collapse the sidebars, or choose 'Print this document' to see the full image or table.");
}

function checkForOversizeContent(containerNode)
{
    if(window.location.href.indexOf('pv=1') >= 0)
        return false;

    var maxWidth = containerNode.clientWidth;
    var tables = containerNode.getElementsByTagName('table');
    for(var i = 0;i<tables.length;i++)
    {
        if (tables[i].parentNode.className == 'landscape')
            return true;
    }

    var imgs = containerNode.getElementsByTagName('img');
    for(var i = 0;i<imgs.length;i++)
    {
        imgWidth = imgs[i].clientWidth;
        if (imgWidth > maxWidth)
            return true;
    }

    return false;
}

// Assign Methods for Additional Content buttons
function BindMySelectionsAdditionContent(mySelectionsForm, elementID, val)
{
    var includeContentNode = $(elementID);
    //alert(elementID, includeContentNode.href);
    if (includeContentNode)
        includeContentNode.onclick = function() { toggleAdditionalContent(mySelectionsForm, val) }
}

// Assign Methods for MySelections Select-All/Select-None buttons
function BindMySelectionsSelectedItems(mySelectionsForm, elementID, checkState)
{
    var includeContentNode = $(elementID);
    if (includeContentNode)
        includeContentNode.onclick = function() { updateMySelectionsCheckedItems(mySelectionsForm, checkState) }
}

// Export Document - "PDF" & "RTF" Only!!!
function downloadDocument(e, exportFormat)
{
    // Pre-Check Required Form is Available...
    if ($(ExportFormId) == null)
        return;

    // If No MySelections Selected - Error!
    if (($(MySelectionsFormId) != null) && (areAnyMySelectionsChecked() == false))
    {
        alert("No items have been selected for Export!");
        return;
    }

    //Only modus/xml content can be exported as rtf
    if( (exportFormat == "application/rtf") && !validRTFSelection() )
    {
        return;
    }
   
    // Capture Selected Items for Submit.
    var selectionList = new Array();
    var inlineList = new Array();
    var elementList = new Array(); // Temporary Element Collection Container.
    var endPointContent = false;

    // If MySelections Form with Selections?
    if (($(MySelectionsFormId) != null) && ($("Content") != null))
    {
        elementList = $(MySelectionsFormId).select("[name='MySelectionsSelectedItems']"); // Capture EndPoints from MySelections Form.
        for(i=0;i<elementList.length;i++) // Extract the EndPoint Selection Information (ie. EndPoint URL).
        {
            if (elementList[i].checked) // EndPoint Selections
                selectionList.push($(elementList[i]).value);
        }

        elementList = $(MySelectionsFormId).select("[name='ShowInlineSetting']"); // Capture EndPoints from MySelections Form.
        for(i=0;i<elementList.length;i++) // Extract the Inline Selection InformationType (ie. "Commentary" and EndPoint URL).
        {
            if (elementList[i].checked) // Inline Selections
                inlineList.push(elementList[i].value);
        }
    }

    // If Not MySelections But EndPoint Content?
    if (($(MySelectionsFormId) == null) && ($("Content") != null))
    {
        var contentSelection = window.location; // Capture Currently Displayed EndPoint URL from Content Form.
        selectionList.push(contentSelection);

        endPointContent = true;

        elementList = $$(".inlinedContent"); // Capture the InlinedContent Elements on the Form.
        for(i=0;i<elementList.length;i++) // Extract the Type (eg. "Commentary") and Append Displayed EndPoint URL.
        {
            // Class identifies "InlinedContent" + "InlinedContent" Type!
            var elType = elementList[i].className; // ClassName supported by both Browsers! (GetArrtibute("class") not supported by IE)
            // capitalise the first character of the string
            var strArray = elType.substring(elType.indexOf(" ")+1, elType.length).split(" ");
            var fragmentStr = strArray[0].capitalize();
            // append "Notes" if fragment string is 'History' or 'Editorial'            
            switch(fragmentStr)
            {
                case "History":
                case "Editorial":
                    fragmentStr = fragmentStr + "Notes";
                    break;
                case "Explanatory-note":
                    fragmentStr = "ClauseDescription";
                    break;
            }
            // now we need to camelize the string but still maintain the first capital letter of the string
            if (fragmentStr.include("-"))
            {
                var tempStr = fragmentStr.substring(0, fragmentStr.indexOf("-"))+ fragmentStr.substring(fragmentStr.indexOf("-")+1, fragmentStr.length).capitalize();
                fragmentStr = tempStr;
            }
            inlineList.push(fragmentStr + ";" + contentSelection);
        }
        if($("inlineAnalysis"))
        {
            inlineList.push("Contents;" + contentSelection);
        }
        inlineList = inlineList.uniq(); // Remove Duplicates (eg Multiple "History Notes").     
    }

    // If List of Selections to Export Exist... (Selections => MySelections -OR- Content)
    if (selectionList.length > 0)
    {
        // Set Export Format (AKA Output Mime-Type).
        if ($("export-format") != null)
            $("export-format").value = exportFormat;

        // clear/remove existing MySelectionsSelectedItems 'hidden' input elements from export form
        var inputs = $(ExportFormId).getInputs('hidden', 'MySelectionsSelectedItems');
        inputs.invoke('remove');

        // clear/remove existing ShowInlineSetting hidden form input elements from export form
        inputs = $(ExportFormId).getInputs('hidden', 'ShowInlineSetting');
        inputs.invoke('remove');

        // Set Selected Items for Export
        for(i=0;i<selectionList.length;i++) 
        { 
            // Create and Insert Input Elements - Element Simulates the MySelections Selected Items!
            $(ExportFormId).insert(new Element("input", { type: "hidden", name: "MySelectionsSelectedItems", value: String(selectionList[i]) }));
        }
        // Set Inline Items for Export
        for(i=0;i<inlineList.length;i++) 
        { 
            // Create and Insert Input Elements - Element Simulates the MySelections Selected Items!
            $(ExportFormId).insert(new Element("input", { type: "hidden", name: "ShowInlineSetting", value: String(inlineList[i]) }));
        }

        if (endPointContent) {
            // hidden element used to indicate that this is not MySelections but EndPoint content export
            $(ExportFormId).insert(new Element("input", { type: "hidden", name: "EndPointContent", value: true }));
        }

        // Post to the Export Service
        $(ExportFormId).submit();
    }
}

function downloadLegislation(e)
{
    // Check Element Exists
    if ($("source-pdf") != null)
    {
        var sourceDoc = $("source-pdf");
        var contentDocument = sourceDoc.getAttribute("pdf-doc").toUpperCase();
    }
    // Check Element is Legislation/Pre-Legislation
    if ((sourceDoc == null || contentDocument == null) || 
         ((contentDocument.indexOf("ACT-") != 0) && (contentDocument.indexOf("REG-") != 0) && (contentDocument.indexOf("BILL-") != 0) && (contentDocument.indexOf("SOP-") != 0) && (contentDocument.indexOf("DLEG-") != 0)))
    {
        alert("Failed to locate associated PDF File!");
        return;
    }

    // Capture Element data...
    var pdfFileSize = $("source-pdf").getAttribute("pdf-size");
    var pdfFileName = $("source-pdf").getAttribute("pdf-name");
    // DownloadURL will perform File Exists Checking!
    var downloadURL = "download?file=" + pdfFileName + "&download=Attachment";  // Download File as Attachment (ie. Prompt to "Save As").

    // Check File Exists...
    if ((pdfFileSize == null || pdfFileSize.length == 0) || (pdfFileName == null || pdfFileName.length == 0))
    {
        alert("PDF File is not available!");
        return;
    }

    // Prompt for Download...
  var download = true;
  if ((contentDocument.indexOf("BILL-") != 0) && (contentDocument.indexOf("SOP-") != 0))
    download = confirm("Are you sure you wish to download the entire Act or Regulation?" + "\n" + "The size of the PDF is " + pdfFileSize)
  
  if (download == true)
  {
        location = downloadURL;
  }
}

function handleSearchFormSubmit(e)
{
    // Get Search Form.
    var searchValidated = validateSearchForm(e.target);
    if ( !searchValidated )
    {
        Event.stop(e);
        return searchValidated;
    }

    var siteContentsNode = $(SiteContentsId);
    if ( siteContentsNode )
    {
        var isSearchTargetValid = validateSearchTarget(siteContentsNode);
        if (!isSearchTargetValid)
        {
            // The user has not selected any database(s) therefore call Event.stop
            Event.stop(e);
        }
        return isSearchTargetValid;
    }
}

function handleLoginFormSubmit(e)
{
    // Process Login Submit
    return handleLoginSubmit(e.target);
}

function handleLoginSubmit(submitForm)
{
    // Validate Data Input on the Form Specified.
    return validatePasswordForm(submitForm);
}

// "e" is an event object. It's browser-dependent as to what properties are available on an event object!
function getEventTarget(e)
{
    // Get the Event - (Event obtained Differently for Mozilla and IE)
    if (!e) e = window.event;
    return (e.currentTarget) ? e.currentTarget : e.srcElement;
}

function addBookmark(e)
{
    var t = getEventTarget(e);

    if (window.external) {
        window.external.AddFavorite(t.href, document.title);
        return false
    }
    else if (! window.sidebar) // i.e. doesn't support above or rel="sidebar" in the link
    {
        alert("Your browser does not seem to support bookmarking from a link in a webpage.\nUse your browser's built-in bookmarking feature instead.");
    }
}

function toggleNavSidebar()
{
    $("navSidebar", "contentFrame", "tlrnz_navbar_graphic").each(function(f){f.toggleClassName('tlrnz_leftbar_hidden');});
    flipSessionState("tlrnz_leftbar_hidden", $("navSidebar").hasClassName("tlrnz_leftbar_hidden"));
}

function toggleRelatedSidebar()
{
    $("relatedSidebar", "contentPaddingFrame", "tlrnz_toggle_related_sidebar").each(function(f){f.toggleClassName('tlrnz_rightbar_hidden');});
    flipSessionState("tlrnz_rightbar_hidden", $("relatedSidebar").hasClassName("tlrnz_rightbar_hidden"));
}

function toggleRawServerVariables(link, rawServerVariablesId)
{
    var rawServerVariablesDiv = $(rawServerVariablesId);
    if (rawServerVariablesDiv.className == 'hidden')
    {
        rawServerVariablesDiv.className = '';
        link.childNodes[0].nodeValue = 'Hide Details';
    }
    else
    {
        rawServerVariablesDiv.className = 'hidden';
        link.childNodes[0].nodeValue = 'View More Details';
    }
}

/* Begin Viewcase functions */
function ViewJudgment(viewcaseFragmentUrl) {
    // If you change the width of the window, be sure to
    // match this in the Viewcase component and Viewcase CSS.

    var openFeatures = [];

    openFeatures.push('top=0');
    openFeatures.push('left=0');
    openFeatures.push('height=525');
    openFeatures.push('width=740');
    openFeatures.push('resizable=yes');
    openFeatures.push('scrollbars=yes');

    window.open(viewcaseFragmentUrl, 'Judgment_Viewer', openFeatures.join(','));
}

function ViewcasePrint()
{
    if (navigator.appName.indexOf('Microsoft') != -1)
    {
        parent.frames[0].focus();
        window.print();
    }
    else
    {
        parent.frames[0].print();
    }
}

/* End Viewcase functions */

function toggleShowHide(btn)
{
    var button = $(btn);
    var contentBlockId = button.id.substring(2)+'Content';
    var contentBlock = $(contentBlockId);
    if ( contentBlock ) {
        if ( contentBlock.visible() ) {
            contentBlock.setStyle({'display': 'none'});
            button.removeClassName('ticked');
        } else {
            contentBlock.setStyle({'display': 'block'});
            contentBlock.scrollTo();
            window.scrollBy(0,-100);
            button.addClassName('ticked');
        }
    }
}

function expandDiv(divId, master)
{
    var selectedDiv = $(divId);
    if(selectedDiv) {
            if ( master.hasClassName("expanded") ) {
            selectedDiv.setStyle({'display': 'block'});
        } else {
            selectedDiv.setStyle({'display': 'none'});
        }
    }
}

/* Start of Expandable/Collapsible sections functions */
function toggleShowHideDiv(divId, linkId){
    if($(divId).getStyle('display') == 'none'){
      $(divId).setStyle({'display': 'block'});
      $(linkId).className = "expanded-section-link";
      flipSessionState(linkId + "_hidden", "false");
    }else{
      $(divId).setStyle({'display': 'none'});
      $(linkId).className = "collapsed-section-link";
      flipSessionState(linkId + "_hidden", "true");
    }
    updateContentPaging();
  }
 
 function updateContentPaging()
 {
    var className = $('collapsibleCaseSummaryDiv').readAttribute('class');
    if ((className != null) && (className != ""))
    {
        var strArray = className.split(" ");
        var bcaseValue = Number(strArray[2]);

        switch(bcaseValue)
        {
            case 7:
                // Case Summary, Citing References, Full Text
                // if they are all not visible, then we should hide the page navigation
                if($('collapsibleFullTextDiv').getStyle('display') == 'none') { 
                    toggleContentPaging('none');
                }
                else {
                    toggleContentPaging('block');
                }
                break;
            case 6:
                // Case Summary, Citing References
                if(($('collapsibleCitingRefDiv').getStyle('display') == 'none')) {
                    toggleContentPaging('none');
                }
                else {
                    toggleContentPaging('block');
                }
                break;
            case 5:
                // Case Summary, Full Text
                if(($('collapsibleFullTextDiv').getStyle('display') == 'none')) {
                    toggleContentPaging('none');
                }
                else {
                    toggleContentPaging('block');
                }
                break;
            case 4:
                // Case Summary
                if(($('collapsibleCaseSummaryDiv').getStyle('display') == 'none')) {
                    toggleContentPaging('none');
                }
                else {
                    toggleContentPaging('block');
                }
                break;
        }
    }
 }

function toggleContentPaging(blockStyle)
{
    var element = $('contentPagingTop');
    if (element != null) {
        switch(blockStyle)
        {
            case 'none':
                $('contentPagingTop', 'contentPaging').invoke('hide');
                flipSessionState("contentPaging_isHidden", "true");
                break;
            case 'block':
                $('contentPagingTop', 'contentPaging').invoke('show');
                flipSessionState("contentPaging_isHidden", "false");
                break;
        }
    }
    else
    {
        //update paging session variable so that the next page rendered which includes content paging is not affected
        switch(blockStyle)
        {
            case 'none':
                flipSessionState("contentPaging_isHidden", "true");
                break;
            case 'block':
                flipSessionState("contentPaging_isHidden", "false");
                break;
        }
    }
}

function toggleHistoricText(divId, endPointId)
{    
    var currentStyle = $(divId).getStyle('display');
    var historicLinkId = 'HistoricTextLink' + divId.substr(divId.indexOf("-"), divId.length);
    var action = null;
    if (currentStyle == "none")
    {
        action = "Add";
        var currentText = $(historicLinkId).innerHTML;
        $(historicLinkId).update("Hide " + currentText.substr(currentText.indexOf(" "),currentText.length));
    }
    else if (currentStyle == "block")
    {
        action = "Remove";        
        var currentText = $(historicLinkId).innerHTML;
        $(historicLinkId).update("Show " + currentText.substr(currentText.indexOf(" "),currentText.length));
    }
    $(divId).toggle();
    new Ajax.Request(ApplicationPath+'/'+SessionDictionaryManagerPageName+'?session-key='+InlinedFragmentsKey,{method:'post', parameters:{'list.action':action,'list.value':endPointId}});        
}

/* End of Collapsible - Expandable sections functions */

function expandRelated(buttonId)
{
    var button = $(buttonId);
    if ( button.hasClassName("expanded")) {
        button.removeClassName("expanded");
        button.next().setStyle({'display': 'none'});
        flipSessionState(button.id + "_hidden", "true");
    } else {
        button.addClassName("expanded");
        button.next().setStyle({'display': 'block'});
        flipSessionState(button.id + "_hidden", "false");
    }
}

function checkJumpTo()
{
    if ( location.search.match(/[&?]j=([^&#]+)/) )
    {
        var anchorId = decodeURIComponent(RegExp.$1);
        var node = $(anchorId);
        if (node)
        {
            node.scrollTo();
        }
    }
}

function openPopup(a_ref)
{
    var popupWindow = window.open(unescape(a_ref.href), a_ref.target, 'menubar=no,resizable=yes,width=500,scrollbars=yes');
    popupWindow.focus();
    return false;
}


// Currently used for the inline help bubbles which appear on the CAMS case 
// fragments. Clicking on a help bubble directs the user to a specific
// help page.
function gotoPageRef(content_type)
{
    var a;
    switch(content_type)
    {
        case (content_type = 'case-summary'):
           a = '/databases/modus/caselaw/bcase/GEN-BCASE!1';
           break;
        case (content_type = 'citing-references'):
           a = '/databases/modus/caselaw/bcase/GEN-BCASE!4';
           break;
        case (content_type = 'full-text'):
           a = '/databases/modus/caselaw/bcase/GEN-BCASE!3';
           break;
        case 'my-selections':
            a = '/databases/modus/help?popup=my-selections';
            break;
        default:
           a = '/databases/modus/help';
           break;
    }
    this.location = a;
    return false;
}


function setStyleSheet(title)
{
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++)
    {
        if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
        {
            a.disabled = true;
            if(a.getAttribute("title") == title) a.disabled = false;
        }
    }
}

function flipSessionState(key, value)
{
    setSessionDictionaryValue(key, value)
}

function setSessionDictionaryValue(key, value)
{
    new Ajax.Request(ApplicationPath+'/'+SessionDictionaryManagerPageName+'?session-key='+key, {method:'put', parameters:{'session-value':value}});
}

function toggleFolderExpand(node, tocId)
{
    $(node).toggleClassName('expanded');
}

function openSiblingLink(node)
{
    var linkNode = findNodeByTagName(node.parentNode, 'a');
    self.location.href = linkNode.href;
}

function findNodeByTagName(node, tagName)
{
    if ( node.tagName == tagName )
        return node;

    for ( var i = 0; i < node.childNodes.length; i++ )
    {
        var childNode = node.childNodes[i];
        if ( childNode.tagName && childNode.tagName.toLowerCase() == tagName )
        {
            return childNode;
        }
    }
    return null;
}

function setWindowName() {
    if ( location.search.match(/[&?]wn=([^&#]+)/i) ) {
        window.name = RegExp.$1;
    } else if ( window.name.length == 0 ) {
        window.name = 'bks' + Math.round(Math.random()*1000)
    }
}

// Validate Form for Password Data Entered...
function validatePasswordForm(form)
{
    for (var i = 0; i < form.elements.length; i++) 
    {
        var el = form.elements[i];
        if (el.type == 'password' && el.value.length > 0)
            return true; // has something so validated okay
    }

    // Nothing Validated - Display Error Mressage.
    alert('Please enter your password.');
    return false;
}

// Validate Form for Search Data Entered...
function validateSearchForm(form)
{
    for (var i = 0; i < form.elements.length; i++) 
    {
        var el = form.elements[i];
        if (el.type == 'text' && el.value.length > 0)
            return true; // has something so validated okay
        if (el.type == 'hidden' && el.title == 'classification-assistant' && el.value.length > 0)
                    return true; // This is expected to be the hidden ExtraClassification field
    }

    // Nothing Validated - Display Error Mressage.
    alert('Please enter some search terms.');
    return false;
}


function validateSearchTarget(siteContentsNode)
{
    // get all checkboxes for the siteContentsNode
    var inputNodes = $(siteContentsNode).adjacent("input[type='checkbox']");
    for (var i = 0; i < inputNodes.length; i++)
    {
        // any node(s) selected?
        if (inputNodes[i].checked) 
        {
            return true;
        }
    }

    alert('Please select database(s) to search');
    return false;
}

function getChildrenWithTagName(node, tagName)
{
    var nodes = new Array();
    recurseGetChildrenWithTagName(node, tagName.toLowerCase(), nodes);
    return nodes;
}

function recurseGetChildrenWithTagName(node, tagName, nodes)
{
    if (! node.tagName)
        return;

    if ( node.tagName.toLowerCase() == tagName )
        nodes[nodes.length] = node;

    for (var i = 0; i < node.childNodes.length; i++)
        recurseGetChildrenWithTagName(node.childNodes[i], tagName, nodes);
}

// Code paths that return false will not make a GET request using the href.
// Those that return true will make a GET request (ie. Process through LinkResolution).
function handleHyperlinkClick(link, translatedId, forceGetRequest)
{
    if (window.isInPreviewPaneMode())
    {
        var pathnameArray = link.pathname.split('/');
        for (var i = 0; i < pathnameArray.length; i++)
        {
            // Splice the preview pane page name in front of the 'link' path name.
            if (pathnameArray[i] == 'link')
            {
                pathnameArray.splice(i, 0, previewPanePageName);
                break;
            }
            // Add the preview pane page name to the end of the path if this isn't a 'link' URL.
            if (i == pathnameArray.length - 1)
            {
                pathnameArray.push(previewPanePageName);
                break;
            }
        }
        var previewPaneUrl = pathnameArray.join('/') + link.search + link.hash;

        window.open(previewPaneUrl, window.previewPaneName, window.getPreviewPaneOpenFeatures());

        return false;
    }

    // Handle Links (Note: Not in PreviewPane Mode)
    var targetElement = $(translatedId);
    if ((targetElement) && (!forceGetRequest)) 
    {
        // Link in Current Document and not a Forced Get!
        targetElement.scrollTo();
        return false;
    }
    else
    {
        // Link to another Document or Forced Get.
        return true;
    }
}

function showSecondaryLogin()
{
    var secondaryLoginForm = $(SecondaryAuthorisationFormId);
    var formWasHidden = secondaryLoginForm.hasClassName(FormIsHiddenClassName);

    if (secondaryLoginForm.hasClassName(FormIsHiddenClassName))
    {
        secondaryLoginForm.removeClassName(FormIsHiddenClassName);
        setFocusOnPasswordField();
    }
    else
    {
        secondaryLoginForm.addClassName(FormIsHiddenClassName);
    }
}

/* what we are doing here is when the Exclude TIBs checkbox has been checked, we also check the following checkboxes:-
    Exclude Binding Ruling
    Exclude Determinations
    Exclude Exemption Notices
    Exclude Interpretation Statements
    Exclude Policy Statements
    Exclude Standard Practice Statements
*/
function onExcludeTibsCheckboxClick(idStr) {
    if ($(idStr).checked) {
        checkboxes = $$(".automate");
        if (checkboxes != null) {
            checkboxes.each(function(elemnt) {
              if (!elemnt.checked) {
                elemnt.checked = true;
              }
            });
        }
    }
}

/*** this stuff is for the classification tree which is rendered in the help ***/

function showBranch(branch) {
    if ($(branch).getStyle('display') == "block")
        $(branch).setStyle({ 'display': 'none' });
    else
        $(branch).setStyle({ 'display': 'block' });
}

function swapFolder(img) {
    objImg = $(img);
    if (objImg.hasClassName('collapsed'))
        objImg.className = 'expanded';
    else
        objImg.className = 'collapsed';
}

/*** end classification tree ***/

setWindowName();

//need to enable only in the development environment
/*
if (!window.console) {
  window.console = {
    timers: {},
    openwin: function() {
      window.top.debugWindow =
          window.open("",
                      "Debug",
                      "left=0,top=0,width=300,height=700,scrollbars=yes,"
                      +"status=yes,resizable=yes");
      window.top.debugWindow.opener = self;
      window.top.debugWindow.document.open();
      window.top.debugWindow.document.write('<html><head><title>debug window</title></head><body><hr /><pre>');
    },

    log: function(entry) {
      window.top.debugWindow.document.write(entry+"\n");
    },

    time: function(title) {
      window.console.timers[title] = new Date().getTime();
    },

    timeEnd: function(title) {
      var time = new Date().getTime() - window.console.timers[title];
      console.log(['<strong>', title, '</strong>: ', time, 'ms'].join(''));
    }

  }

  if (!window.top.debugWindow) { console.openwin(); }
}
*/
