/*
Module: MyBST.js
    This module provides all functions and variables that manage MyBst default page.
*/


/*
    Variable: singleView
    Determines whether a user is displaying the single or the parallel view.

    Variable: lowPaneOn
    An array of the low-pane tabs.
*/
var singleView=true;
var lowPaneOn = new Array(2);

/*
    Function: initializeMyBST
    Initialize the low-pane tabs to the user-notes tab.

    Parameters:
        no-params.

    Returns:
        nothing.
*/
function initializeMyBST()
{
    lowPaneOn[0] = "imgUsernotes1";
    lowPaneOn[1] = "imgUsernotes2";
}


/*
    Function: callKeywordSearch
    Gets the value of the keyword text-box and the search type, then it redirects the page
    to the search default page.

    Parameters:
        no-params.

    Returns:
        nothing.

    See Also:
        <callReferenceSearch()>
*/
function callKeywordSearch()
{
    var kyw = document.getElementById('txtKeywords').value;
    var ct = document.getElementById('ddlContentlist');
    var contentlist = ct.options[ct.selectedIndex].value;
    if (kyw == LocalStrings.StartANewSearch || kyw=='')
    {
	    alert(LocalStrings.PleaseEnterOneOrMoreSearchWords);
    }
    else 
    {
      var path = appRoot;
			
			var idx = 1;
			if (contentlist.toLowerCase() == 'bibles')
			{
				if (! isScriptureReference(kyw))
				{
					getFinderSearchResults(idx, 'bibles', '', kyw, 'All', 'All', '', true);
				}
				else
				{
					var translationCode = userTranslation;
					if (BSTState.panel[0].TranslationId.length > 0)
						translationCode = BSTState.panel[0].TranslationId;
					callRefSearchByString(kyw, 1, translationCode, BSTState);
				}
      }
      else if (contentlist.toLowerCase() == 'library')
        getFinderSearchResults(idx, 'library', '', kyw, '', LocalStrings.All, 'bible', true);
      else 
				getFinderSearchResults(idx, 'library', contentlist, kyw, '', LocalStrings.All, '', true);
    }
    return;
}


/*
    Function: callReferenceSearch
    Gets the value of the Jump-to text-box, then it redirects to the my-bst default page.

    Parameters:
        no-params.

    Returns:
        nothing.

    See Also:
        <callKeywordSearch()>
*/
    function callReferenceSearch()
    {
        var ref = document.getElementById('txtReference').value;
        if (ref == LocalStrings.ScriptureReference || ref == '')
        {
	        alert(LocalStrings.PleaseEnterAValidReference);
        }
        else
        {
					// use current translation or preferred.
					var translationCode = userTranslation;
					if (BSTState.panel[0].TranslationId.length > 0)
						translationCode = BSTState.panel[0].TranslationId;
					
          callRefSearchByString(ref, 1, translationCode, BSTState);
        }
        return;
    }

 /*
    Function: getFinderSearchResults
    It calls the web-service "BstSearch" and displays the search results in My-Bst panels.

    Parameters:
        panel - panel index (1 or 2).
        contenttype - the content type (bible or library).
        category - the category name (concordances, faq, sermon helps, etc...).
        keyword - the keyword to search on.
        translationid - the translation code.
        bookgroup - the book-group code.
        sortby - the field name to stort by.
        savestate - savestate object, which maintain the state of the panels.

    Returns:
        nothing.

    See Also:
        <BibleStudyTools.Site.Search.BstSearch(panel, contenttype, category, '', keyword, translationid, bookgroup, sortby, searchPageNumber)>
*/
function getFinderSearchResults(panel, contenttype, category, keyword, translationid, bookgroup, sortby, savestate)
{
    BSTState.panel[panel-1].CategoryName = contenttype;
    BSTState.panel[panel-1].Keyword = keyword;
    BSTState.panel[panel-1].TranslationId = translationid;
    BSTState.panel[panel-1].BookGroup = bookgroup;
    BSTState.panel[panel-1].SortBy = sortby;

    var context = panel;//index,content,words,translation,category,"bible",true
    showBusyCursor('mybstsearchresultdisplay' + panel,
                   'mybstversesdisplay' + panel,
                   'verseDisplay' + panel);

    BibleStudyTools.Site.Search.BstSearch(panel, contenttype, category, '', keyword, translationid,
                           bookgroup, sortby, searchPageNumber,
                           MyBstWS_callback, MyBstWSFailed_callback, context, null);

    BSTState.panel[panel-1].SaveState = savestate;
    return;
}


/*
    Function: callRefSearchByString
    Runs the reference search by string / Jump too.

    Parameters:
        value - reference to search on.
        panel - pane index.
        translation - translation code.
        obj - state object.

    Returns:
        nothing.

    See Also:
        <BibleStudyTools.Site.Search.ReferenceSearchByString(panel, translation, value, obj.panel[panel-1].LoadTranslation, true/false>
*/
function callRefSearchByString(value, panel, translation, obj)
{
        //alert(' - value:' + value + ' - panel:' + panel + ' - translation:' + translation);
    obj.CurrentPanel = panel;
    obj.Translation = translation;
    if (!obj.panel[panel-1])
    {
        obj.panel.Add(new Panel());
    }
    obj.panel[panel-1].TranslationId = translation;
    obj.panel[panel-1].Reference = value;
    showBusyCursor('mybstversesdisplay' + panel,
                   'mybstsearchresultdisplay' + panel,
                   'verseDisplay' + panel);
    var context = panel;
    BibleStudyTools.Site.Search.ReferenceSearchByString(panel, translation, value,
                                         obj.panel[panel-1].LoadTranslation,
                                         true,
                                         MyBstWS_callback, MyBstWSFailed_callback, context, null);
    return;
}


/*
    Function: verseResultsPage
    Calls the JavaScript method "callRefSearchByKey()" to get the verses by key.

    Parameters:
        type - content type (bible or library).
        index - pane index.
        bookcode - book code.
        bookname - book name.
        chapterid - chapter id.
        verseid - verse id.
        translationcode - translation code.

    Returns:
        nothing.

    See Also:
        <callRefSearchByKey(index, bookcode, bookname, chapterid, verseid, translationcode, true/false)>
*/
function verseResultsPage(type, index, bookcode, bookname, chapterid, verseid, translationcode)
{
  callRefSearchByKey(index, bookcode, bookname, chapterid, verseid, translationcode, true)
  return;
}


/*
    Function: contentResultsPage
    Calls the JavaScript method "callGetLibraryDocument()" to get the documents by key.

    Parameters:
        categoryname - category name (article, reference,...).
        panel - pane index.
        contentID - content ID.
        documentType - document type.

    Returns:
        nothing.

    See Also:
        <callGetLibraryDocument(panel, contentID, documentType, true/false)>
*/
function contentResultsPage(categoryname, panel, contentID, documentType)
{
	callGetLibraryDocument(panel, contentID, documentType, true);
	return;
}


/*
    Function: contentResultsPageByTitle
    Gets the search results by title (returns the documents: ref, dict,...).

    Parameters:
        p - panel index/integer.
        section - string.
        searchtype - string.
        searchtext - string.
        bookmark - string.

    Returns:
        nothing.

    See Also:
        <BibleStudyTools.Site.CMSService.GetReferenceDocumentByTitle(section, searchtype, searchtext, p)>
*/
function contentResultsPageByTitle(p, section, searchtype, searchtext, bookmark){
    var context = p + '|' + '0' + '|' + 'library' + '|' + section + '|' + searchtype + '|' + searchtext;
    BibleStudyTools.Site.CMSService.GetReferenceDocumentByTitle(section, searchtype, searchtext, p, MyBstWS_callback, MyBstWSFailed_callback, context, null);
    BSTState.panel[p-1].SaveState = true;
    return;
}


/*
    Function: contentStrongsFrequency
    Get the strongs document and displays it in My-Bst pane.

    Parameters:
        p - integer/panel index (1 or 2).
        bookcode - string.
        strongsnumber - string.
        frequency - string.
        translationcode - string.

    Returns:
        nothing.

    See Also:
        <Search.StrongsSearch(translationcode, bookcode, strongsnumber, p)>
*/
function contentStrongsFrequency(p, bookcode, strongsnumber, frequency, translationcode){
    var context = p + '|' + translationcode + "|" + bookcode + "|" + strongsnumber;
    BibleStudyTools.Site.Search.StrongsSearch(translationcode, bookcode, strongsnumber, p, MyBstWS_callback, MyBstWSFailed_callback, context, null);
    BSTState.panel[p-1].SaveState = true;
    return;
}


/*
    Function: callRefSearchByKey
    Calls the web-service and gets the verses by the key (bookcode,chapterid,verseid, and translationcode).

    Parameters:
        panel - integer/panel index(1 or 2).
        bookcode - string.
        bookname - string.
        chapterid - integer.
        verseid - integer.
        translationcode - string.
        savestate - object.

    Returns:
        nothing.

    See Also:
        <Search.ReferenceSearchByKey(context, translationcode.toLowerCase(), bookcode, chapterid, verseid, items,>
*/
function callRefSearchByKey(panel, bookcode, bookname, chapterid, verseid, translationcode, savestate)
{
    BSTState.CurrentPanel = panel;
    BSTState.panel[panel-1].TranslationId = translationcode.toLowerCase();
    BSTState.panel[panel-1].BookCode = bookcode;
    BSTState.panel[panel-1].BookName = bookname;
    BSTState.panel[panel-1].ChapterId = chapterid;
    BSTState.panel[panel-1].VerseId = verseid;
    var context = panel;
    showBusyCursor('mybstversesdisplay' + context,
                   'mybstsearchresultdisplay' + context,
                   'verseDisplay' + context);
    BSTState.panel[panel-1].SaveState = savestate;
    BibleStudyTools.Site.Search.ReferenceSearchByKey(context,
                                      translationcode.toLowerCase(),
                                      bookcode, chapterid, verseid, 0,
                                      BSTState.panel[panel-1].LoadTranslation,
                                      BSTState.panel[panel-1].SaveState,
                                      MyBstWS_callback, MyBstWSFailed_callback, context, null);
    return;
}


/*
    Function: onChangeTranslation
    Gets the verses when a user changes the translation from the translation-dropdown. Also, it resets the
    values of the display-options (pop-up window).

    Parameters:
        value - translation code/string.
        obj - dropdownlist object.
        panel - panel index/integer.

    Returns:
        nothing.

    See Also:
        <BibleStudyTools.Site.Search.ReferenceSearchByKey(panel,value,bookCode,chapterId,verseId,items,true/false,true/false)>
        <processDisplayOptions(panel,hascrossreferences,hasfootnotes,hasstrongs,hasredletters)>
*/
function onChangeTranslation(value, obj, panel) 
{

    if (value == 'login-more') 
    {
        dashboardLoginExpand();
        return;
    }

    BSTState.CurrentPanel = panel;
    BSTState.panel[panel-1].TranslationId = value;
    var context = panel;
    showBusyCursor('mybstversesdisplay' + panel,
                   'mybstsearchresultdisplay' + panel,
                   'verseDisplay' + panel);
    //Stats.BibleReferenceSearch(value);  // register page view
    BibleStudyTools.Site.Search.ReferenceSearchByKey(panel,
                                      value,
                                      BSTState.panel[panel-1].BookCode,
                                      BSTState.panel[panel-1].ChapterId,
                                      BSTState.panel[panel-1].VerseId,
                                      0,
                                      false,
                                      true,
                                      MyBstWS_callback, MyBstWSFailed_callback, context, null );

    processDisplayOptions( panel,
                           obj.options[obj.selectedIndex].getAttribute('hascr'),
                           obj.options[obj.selectedIndex].getAttribute('hasfn'),
                           obj.options[obj.selectedIndex].getAttribute('hasst'),
                           obj.options[obj.selectedIndex].getAttribute('hasrl') );
    return;
}


/*
    Function: onChangeBookChapter
    Gets the new verses when a user navigates through the chanpters and/or the books. Also, it saves the
    results in the state-history object

    Parameters:
        panel - panel index/integer.
        translationid - string.
        bookcode - string.
        bookname - string.
        chapterid - integer.
        verseid - integer.
        source - string (chapter or book).
        dir - (+) when a user clicks on the next chapter/book.
              (-) when a user clicks on the previous chapter/book.

    Returns:
        nothing.

    See Also:
        <BibleStudyTools.Site.Search.ReferenceSearchByKey(panel,value,bookCode,chapterId,verseId,items,true/false,true/false)>
*/
function onChangeBookChapter(panel, translationid, bookcode, bookname, chapterid, verseid, source, dir)
{
    if (source == 'book')
    {
        bookcode = dir + bookcode;
    }
    else if (source == 'chapter')
    {
        if (dir == "-")
        {
            chapterid = parseInt(chapterid) - 1;
        }
        else if (dir == "+")
        {
            chapterid = parseInt(chapterid) + 1;
        }
    }
    BSTState.CurrentPanel = panel;
    var context = panel;
    showBusyCursor('mybstversesdisplay' + panel,
                   'mybstsearchresultdisplay' + panel,
                   'verseDisplay' + panel);
    BibleStudyTools.Site.Search.ReferenceSearchByKey(panel,
                                      translationid,
                                      bookcode, chapterid, verseid, 0,
                                      false,
                                      true,
                                      MyBstWS_callback, MyBstWSFailed_callback, context, null);
    return;
}


/*
    Function: openStrongs
    Gets the strongs document by strongs number and saves the results in the history if the "savestate" is true.

    Parameters:
        strongsnum - strongs number.
        panel - panel index.
        savestate - save-state object (that manages the panels history).

    Returns:
        nothing.

    See Also:
        <GetStrongsDocument(translationId,bookCode,strongsnum)>
*/
function openStrongs(strongsnum, panel, savestate)
{
    var context = panel + '|' + BSTState.panel[panel-1].TranslationId + "|" + BSTState.panel[panel-1].BookCode + "|" + strongsnum;
    BibleStudyTools.Site.CMSService.GetStrongsDocument(BSTState.panel[panel-1].TranslationId,
                                  BSTState.panel[panel-1].BookCode,
                                  strongsnum,
                                  panel,
                                  MyBstWS_callback, MyBstWSFailed_callback, context, null);
    BSTState.panel[panel-1].SaveState = savestate;
}


/*
    Function: callGetLibraryDocument
    Gets the library documents by the document-id and saves the results in the history if the "savestate" is set to true.

    Parameters:
        p - panel index.
        docId - document id.
        type - type of the document.
        savestate - save-state object (that manages the panels history).

    Returns:
        nothing.

    See Also:
        <GetLibraryDocument(docId, type, panel)>
*/
function callGetLibraryDocument(p, docId, type, savestate)
{
    var context = p + '|' + docId + '|' + type;
    BibleStudyTools.Site.CMSService.GetLibraryDocument(docId, type, p, MyBstWS_callback, MyBstWSFailed_callback, context, null);
    BSTState.panel[p-1].SaveState = savestate;
}


/*
    Function: MyBstWS_callback
    Manages the call-back methods within My-Bst.

    Parameters:
        result - results form the call-back method.
        context - holds the parameters of the Ajax calls to web-services.
        methodName - returns the JavaScript method that is been called when a user calls the web-service.

    Returns:
        nothing.

    See Also:
        <processVerses(result, context)>
        <processFinderResults(result, context)>
        <processStrongs(result, context)>
        <processLibraryDocument(result, context)>
        <processStrongsFrequency(result, context)>
*/
function MyBstWS_callback(result, context, methodName)
{
    switch(methodName)
    {
        case "ReferenceSearchByString":
          processVerses(result, context);
          break;
        case "ReferenceSearchByKey":
          processVerses(result, context);
          break;
        case "BstSearch":
          processFinderResults(result, context);
          break;
        case "GetStrongsDocument":
          processStrongs(result, context);
          break;
        case "GetLibraryDocument":
          processLibraryDocument(result, context);
          break;
        case "GetReferenceDocumentByTitle":
          processLibraryDocument(result, context);
          break;
        case "StrongsSearch":
          processStrongsFrequency(result, context);
          break;
        case "AddUserFlag":
					MyFlags.StartFlagAnimation();
					break;
        //default: 
					//alert("Oops, error occurred.");
    }

}


/*
    Function: MyBstWSFailed_callback
    Maintains the error messages when an error occurred.

    Parameters:
        result - results form the call-back method.
        context - holds the parameters of the Ajax calls to web-services.

    Returns:
        nothing.

    See Also:
        <MyBstWSFailed_callback(result, context)>
*/
function MyBstWSFailed_callback(result,context, methodName)
{
    alert(LocalStrings.ErrorInWebMethod + " '"+methodName+"'.\n" + LocalStrings.Message + "='"+result._message+"'\n" + LocalStrings.StatusCode + "="+result._statusCode+"\n" + LocalStrings.StackTrace + "='"+result._stackTrace+"'\n" + LocalStrings.ExceptionType + "='"+result._exceptionType+"'\n" + LocalStrings.TimedOut + "="+result._timedOut);
}


/*
    Function: processVerses
    Processes the verses within My-Bst panes.

    Parameters:
        result - results form the call-back method.
        p - panel index/integer.

    Returns:
        nothing.

    See Also:
        <getHeaderFlagsTag(result, startdag, enddag, savestate, panel)>
        <setToolBar(result, context)>
        <writeToPanel(result, panel)>
        <setBooksNavigator(panel, translationId, bookCode, bookName, chapterId, verseId)>
        <setAddNoteButton(panel, translationId, bookCode, bookName, chapterId, verseId)>
        <largePrint(panel, mainpane, footerpane)>
        <scrollSet(row-number,div-name,top-padding)>
        <setBackForward(panel)>
        <displayError(div-name,error-text)>
*/
    function processVerses(result, p)
    {

        var str = result;
        if (str.trim() == "")
        {
            error.setError(true, "no results");
            alert(error.getErrorMessage());
            return;
        }

        //always check the header flags which holds the error flag.
        str = getHeaderFlagsTag(str, "<headerFlags>", "</headerFlags>", true, p);
        if (!error.ErrorOccurred())
        {
            setToolBar(true, p, '_on','_off','_inactive');
            writeToPanel(str, p);
            MyFlags.ShowFlagsInVerses(BSTState.panel[p-1].TranslationId, BSTState.panel[p-1].BookCode, BSTState.panel[p-1].ChapterId, p);

            setBooksNavigator(p,
                              BSTState.panel[p-1].TranslationId,
                              BSTState.panel[p-1].BookCode,
                              BSTState.panel[p-1].BookName,
                              BSTState.panel[p-1].ChapterId,
                              BSTState.panel[p-1].VerseId,
                              BSTState.panel[p-1].ChapterCount);

            setAddNoteButton( p,
                              BSTState.panel[p-1].TranslationId,
                              BSTState.panel[p-1].BookCode,
                              BSTState.panel[p-1].BookName,
                              BSTState.panel[p-1].ChapterId,
                              BSTState.panel[p-1].VerseId);

            if (BSTState.panel[p-1].LoadTranslation)
            {
                BSTState.panel[p-1].FontSize = defTextSize;
                setVerseFont(defTextSize, p, 'mybstversesdisplay'+p, 'verseFooter'+p);

                BSTState.panel[p-1].history.Add(new History("verse",
                                                          BSTState.panel[p-1].BookCode + "|" +
                                                          BSTState.panel[p-1].BookName + "|" +
                                                          BSTState.panel[p-1].ChapterId + "|" +
                                                          BSTState.panel[p-1].VerseId + "|" +
                                                          BSTState.panel[p-1].TranslationId
                                                ) );

               var si = BSTState.Save();
               document.getElementById("leftstate").innerHTML=BSTState.Display();
               BSTState.panel[p-1].LoadTranslation = false;
            }
            else {
                if ( BSTState.panel[p-1].SaveState)
                {
                    BSTState.panel[p-1].history.Add(new History("verse",
                                                                      BSTState.panel[p-1].BookCode + "|" +
                                                                      BSTState.panel[p-1].BookName + "|" +
                                                                      BSTState.panel[p-1].ChapterId + "|" +
                                                                      BSTState.panel[p-1].VerseId + "|" +
                                                                      BSTState.panel[p-1].TranslationId
                                                                      ) );
                    var si = BSTState.Save();
                    document.getElementById("leftstate").innerHTML=BSTState.Display();
                    document.getElementById("imgBack"+p).src = document.getElementById("imgBack"+p).src.replace('inactive', 'on');
                    defHovImgBack[p-1] = defHovImgBack[p-1].replace('inactive', 'on');
                    defOutImgBack[p-1] = defOutImgBack[p-1].replace('inactive', 'off');
                }
            }

            scrollSet('verseRow'+BSTState.panel[p-1].VerseId, 'verseDisplay' + p, 0);
            if ( p == 2 )
            {
                var ch = BSTState.panel[0].history.CurrentHistory;
                var displaytype = BSTState.panel[0].history[ch].DisplayType;
                if ( displaytype == 'verse' ) scrollSet('verseRow'+BSTState.panel[0].VerseId, 'verseDisplay1', 0);
            }
            setBackForward(p);


        }
        else {
            // Error
            displayError('mybstversesdisplay'+p, error.ErrorMessage);
        }
        return;
    }


/*
    Function: processFinderResults
    Processes the finder results within My-Bst panes.

    Parameters:
        result - results form the call-back method.
        panel - panel index/integer.

    Returns:
        nothing.

    See Also:
        <getHeaderFlagsTag(result, startdag, enddag, savestate, panel)>
        <hidediv(div-name)>
        <setToolBar(result, context)>
        <scrollReset(divname)>
        <setBackForward(panel)>
        <displayError(div-name,error-text)>
*/
    function processFinderResults(result, panel)
    {

        str = getHeaderFlagsTag(result, "<headerFlags>", "</headerFlags>",false, panel);
        if ( !error.IsError )
        {
            if (BSTState.panel[panel-1].CategoryName == 'bible')
            {
                var container = document.getElementById('mybstsearchresultdisplay' + panel);
                container.innerHTML = str;
            }
            else {
                str = processPanelDisplayTag(str, "<allresults>", "</allresults>", "mybstsearchresultdisplay", panel);
            }
            hidediv("mybsttranslationresults" + panel);
            hidediv("verseSeperator" + panel);

            setToolBar(false, panel, '_on','_off','_inactive');
            scrollReset('verseDisplay' + panel);
            if ( panel == 2 ) scrollReset('verseDisplay1');
            //alert(BSTState.panel[panel-1].SaveState);
            if ( BSTState.panel[panel-1].SaveState)
            {
                BSTState.panel[panel-1].history.Add(new History("search",
                                                                 BSTState.panel[panel-1].CategoryName + "|" +
                                                                 BSTState.panel[panel-1].Keyword + "|" +
                                                                 BSTState.panel[panel-1].TranslationId + "|" +
                                                                 BSTState.panel[panel-1].BookGroup + "|" +
                                                                 BSTState.panel[panel-1].SortBy + "|" +
                                                                 searchPageNumber
                                                                                   ) );
                var si = BSTState.Save();
                //document.getElementById("leftstate").innerHTML=BSTState.Display();
            }
            if ( panel == 2 )
            {
                var ch = BSTState.panel[0].history.CurrentHistory;
                var displaytype = BSTState.panel[0].history[ch].DisplayType;
                if ( displaytype == 'verse' ) scrollSet('verseRow'+BSTState.panel[0].VerseId, 'verseDisplay1', 0);
            }
            setBackForward(panel);
        }
        else {
            // Error
            // when we get here, the verse text may contain a neverending search cursor busy icon
            displayError('mybstversesdisplay'+panel, error.ErrorMessage);
        }

        return;
    }


/*
    Function: processStrongs
    Processes the strongs documents within My-Bst panes.

    Parameters:
        result - results form the call-back method.
        context - string (panel + '|' + translationid + '|' + bookcode + '|' + strongsnumber).
                  context also can be an array (check user-notes functions)

    Returns:
        nothing.

    See Also:
        <showdiv(div-name)>
        <hidediv(div-name)>
        <setToolBar(result, context)>
        <scrollReset(div-name))
        <setBackForward(panel)>
*/
    function processStrongs(result, context)
    {
        var panel = context.split('|')[0];
        context = context.replace(panel+'|', "");
        var translationid= context.split('|')[0];
        context = context.replace(translationid+'|', "");
        var bookcode= context.split('|')[0];
        context = context.replace(bookcode+'|', "");
        var strongsnumber = context;

        var container = document.getElementById('mybstversesdisplay' + panel);
        showdiv("mybstversesdisplay" + panel);
        hidediv("mybstsearchresultdisplay" + panel);

        container.innerHTML = result;
        setToolBar(false, panel, '_on','_off','_inactive');
        scrollReset('verseDisplay' + panel);
        if ( panel == 2 ) scrollReset('verseDisplay1');
        if ( BSTState.panel[panel-1].SaveState )
        {
            BSTState.panel[panel-1].history.Add(new History("strongs", translationid + "|" + bookcode + "|" + strongsnumber ) );
            var si = BSTState.Save();
        }
        if ( panel == 2 )
        {
                var ch = BSTState.panel[0].history.CurrentHistory;
                var displaytype = BSTState.panel[0].history[ch].DisplayType;
                if ( displaytype == 'verse' ) scrollSet('verseRow'+BSTState.panel[0].VerseId, 'verseDisplay1', 0);
        }

        //when this type of the document handles uernotes, then we need to include the noteslist within the results
        var notes = document.getElementById('usernotes' + panel);
        notes.innerHTML = "";

        setBackForward(panel);
        return;
    }


/*
    Function: processStrongsFrequency
    Processes the strongs-frequency documents within My-Bst panes.

    Parameters:
        result - results form the call-back method.
        context - string (panel + '|' + translationid + '|' + bookcode + '|' + strongsnumber).
                  context also can be an array (check user-notes functions)

    Returns:
        nothing.

    See Also:
        <showdiv(div-name)>
        <hidediv(div-name)>
        <setToolBar(result, context)>
        <scrollReset(div-name))
        <setBackForward(panel)>
        <scrollSet(row-number,div-name,top-padding)
*/
    function processStrongsFrequency(result, context)
    {

        var panel = context.split('|')[0];
        context = context.replace(panel+'|', "");
        var translationid= context.split('|')[0];
        context = context.replace(translationid+'|', "");
        var bookcode= context.split('|')[0];
        context = context.replace(bookcode+'|', "");
        var strongsnumber = context;

        var container = document.getElementById('mybstversesdisplay' + panel);
        showdiv("mybstversesdisplay" + panel);
        hidediv("mybstsearchresultdisplay" + panel);

        container.innerHTML = result;
        setToolBar(false, panel, '_on','_off','_inactive');
        scrollReset('verseDisplay' + panel);
        if ( panel == 2 ) scrollReset('verseDisplay1');
        if ( BSTState.panel[panel-1].SaveState )
        {
            BSTState.panel[panel-1].history.Add(new History("strongs", translationid + "|" + bookcode + "|" + strongsnumber ) );
            var si = BSTState.Save();
        }
        if ( panel == 2 )
        {
                var ch = BSTState.panel[0].history.CurrentHistory;
                var displaytype = BSTState.panel[0].history[ch].DisplayType;
                if ( displaytype == 'verse' ) scrollSet('verseRow'+BSTState.panel[0].VerseId, 'verseDisplay1', 0);
        }

        //when this type of the document handles uernotes, then we need to include the noteslist within the results
        var notes = document.getElementById('usernotes' + panel);
        notes.innerHTML = "";

        setBackForward(panel);
        return;
    }


/*
    Function: processLibraryDocument
    Processes the library documents within My-Bst panes.

    Parameters:
        result - results form the call-back method.
        context - string (panel + '|' + documentid).
                  context also can be an array (check user-notes functions)

    Returns:
        nothing.

    See Also:
        <showdiv(div-name)>
        <hidediv(div-name)>
        <setToolBar(result, context)>
        <scrollReset(div-name))
        <setBackForward(panel)>
        <scrollSet(row-number,div-name,top-padding)
*/
    function processLibraryDocument(result, context)
    {

        var panel = context.split('|')[0];
        context = context.replace(panel + '|', "");
        var docid = context.split('|')[0];
        context = context.replace(docid + '|', "");
        var type = context;
        var container = document.getElementById('mybstversesdisplay' + panel);
        showdiv("mybstversesdisplay" + panel);
        hidediv("mybstsearchresultdisplay" + panel);
        hidediv("mybsttranslationresults" + panel);
        hidediv("verseSeperator" + panel);

        setToolBar(false, panel, '_on','_off','_inactive');
        container.innerHTML = result;              //pf, 10/30/07
        scrollReset('verseDisplay' + panel);
        if ( panel == 2 ) scrollReset('verseDisplay1');
        if ( BSTState.panel[panel-1].SaveState )
        {
            BSTState.panel[panel-1].history.Add(new History("ref", docid + "|" + type) );
            var si = BSTState.Save();
        }
        if ( panel == 2 )
        {
                var ch = BSTState.panel[0].history.CurrentHistory;
                var displaytype = BSTState.panel[0].history[ch].DisplayType;
                if ( displaytype == 'verse' ) scrollSet('verseRow'+BSTState.panel[0].VerseId, 'verseDisplay1', 0);
        }

        //when this type of the document handles uernotes, then we need to include the noteslist within the results
        var notes = document.getElementById('usernotes' + panel);
        notes.innerHTML = "";

        setBackForward(panel);
    }


/*
    Function: writeToPanel
    Parses and displays the results in the panes.

    Parameters:
        str - results as Html.
        p - panel index (1 or 2).

    Returns:
        nothing.

    See Also:
        <processAudioButton(showaudio, panel)>
        <enableDisplayOptions()>
        <enableAnnotation()>
        <processPanelDisplayTag(results, startTag, endTag, divname, panel)>
        <displayOptionsCrossRef(id,panel)>
        <displayOptionsFootnotes(id,panel)>
        <displayOptionsUsernotes(id,panel)>
        <displayOptionsStrongs(id,panel)>
        <displayOptionsRedletter(id,panel)>
        <enableTooltips()>
        <enableNotesWindow()>
        <showdiv(div-name)>
        <hidediv(div-name)>
*/
    function writeToPanel(str, p)
    {
        //call this following code by this order: Translation, Verselist, Footnotes, UserNotes, Cross-Reference,
	    //and Strongs div's names id="usernotes1" div id="footnotes1" div id="crossreference1" div id="strongs1"
	    //handle the the verseList Tag

	    var bookname = document.getElementById('ctl00_maincontent_ReadingPanels_bookname' + p);
	    bookname.innerHTML = BSTState.panel[p-1].BookName + ' ' +  BSTState.panel[p-1].ChapterId;
	    if (BSTState.panel[p-1].LoadTranslation)
	    {
	        var translations = processTag(str,"<translations>", "</translations>");
	        var arr = translations.split('|');
            var ddlTranslation = document.getElementById('ctl00_maincontent_ReadingPanels_ddlTranslation' + p);
            var selectedindex=0;
            for (var i=0; i<arr.length; i++)
            {
                if (arr[i].trim() != "")
                {
                    var ar = arr[i].split(':');
                    if (ar[0].trim().toLowerCase() == BSTState.panel[p-1].TranslationId.toLowerCase())
                    {
                        selectedindex = i;
                    }
                    ddlTranslation.options[i] = new Option(ar[1].trim(),ar[0].trim());
                    ddlTranslation.options[i].setAttribute( 'hasaudio', ar[2].trim() );  //hasAudio
                    ddlTranslation.options[i].setAttribute( 'hascr', ar[3].trim() );     //HasCrossReferences
                    ddlTranslation.options[i].setAttribute( 'hasfn', ar[4].trim() );     //HasFootnotes
                    ddlTranslation.options[i].setAttribute( 'hasst', ar[5].trim() );     //HasStrongsNumbers
                    ddlTranslation.options[i].setAttribute( 'hasrl', ar[6].trim() );     //HasRedLetters
                }
            }            
            
            ddlTranslation.selectedIndex = selectedindex;
            processAudioButton( ddlTranslation.options[selectedindex].getAttribute('hasaudio'), p );
    	    str = newResults;

            var sa = false;
            if (showBlockAnnotation=='block') sa=true;
						enableDisplayOptions('imgDisplayOptions1',1,
	                             ddlTranslation.options[selectedindex].getAttribute('hascr'),
	                             ddlTranslation.options[selectedindex].getAttribute('hasfn'),
	                             ddlTranslation.options[selectedindex].getAttribute('hasst'),
	                             ddlTranslation.options[selectedindex].getAttribute('hasrl'),
	                             sa );
            enableDisplayOptions('imgDisplayOptions2',2,
	                             ddlTranslation.options[selectedindex].getAttribute('hascr'),
	                             ddlTranslation.options[selectedindex].getAttribute('hasfn'),
	                             ddlTranslation.options[selectedindex].getAttribute('hasst'),
	                             ddlTranslation.options[selectedindex].getAttribute('hasrl'),
	                             sa );

	       if (showBlockAnnotation=='block')
	       {
	           enableAnnotation('imgForeColor1', 1, true);
	           enableAnnotation('imgForeColor2', 2, true);
	           enableAnnotation('imgHiliteColor1', 1, false);
	           enableAnnotation('imgHiliteColor2', 2, false);
	       }
	    }
	    else {
	        var ddlTranslation = document.getElementById('ctl00_maincontent_ReadingPanels_ddlTranslation' + p);
	        var selectedindex=0;
	        for (var i=0; i<ddlTranslation.options.length; i++)
	        {
	            if (ddlTranslation.options[i].value == BSTState.panel[p-1].TranslationId.trim())
	            {
	                selectedindex = i;
                    processAudioButton( ddlTranslation.options[i].getAttribute('hasaudio'), p );
                }
            }
            ddlTranslation.selectedIndex = selectedindex;
	    }

	    str = processPanelDisplayTag(str, "<verseList>", "</verseList>", "mybstversesdisplay", p);
	    var subjectheader = document.getElementById('verseNum_' + p + '_0');

	    var i=1;
	    try {
	        while (subjectheader.id != null)
	        {
	            subjectheader.id = 'subjectheader'+i;
	            subjectheader.style.display = 'none';
	            i++;
	            subjectheader = document.getElementById('verseNum_' + p + '_0');
	        }
	    }
	    catch(err)
	    {
	        // skip this error
	    }

	    //  return;
	    //handle the the footnoteList Tag
	    str = processPanelDisplayTag(str, "<footnoteList>", "</footnoteList>", "footnotes", p);

      //handle the the usernoteList
      var tabNotes = document.getElementById('usernotes'+p);
      var imgNotes = document.getElementById('imgUsernotes'+p);
      str = processPanelDisplayTag(str, "<usernoteList>", "</usernoteList>", "usernotes", p);
      if (showBlockAnnotation=='block')
      {
          imgNotes.style.display='inline-block';
          tabNotes.style.display='inline-block';
      }
      else 
      {
          imgNotes.style.display='none';
          tabNotes.style.display='none';
      }

			//handle the the crossrefList Tag
			str = processPanelDisplayTag(str, "<crossrefList>", "</crossrefList>", "crossreference", p);

      ////handle the the strongsList
     //str = processPanelDisplayTag(str, "<strongsList>", "</strongsList>", "strongs", p);

      if (showBlockAnnotation=='block')
      {
          showdiv("usernotes" + p);
          hidediv("footnotes" + p);
      }
      else {
          hidediv("usernotes" + p);
          showdiv("footnotes" + p);
      }
      hidediv("crossreference" + p);
      //hidediv("strongs" + p);

      showdiv("mybsttranslationresults" + p);
      showdiv("verseSeperator" + p);
      //showdiv("verseFooter" + p);
      //maxTabContent(p);

      displayOptionsCrossRef(null,p);
      displayOptionsFootnotes(null,p);
      displayOptionsUsernotes(null,p);
      displayOptionsStrongs(null,p);
      displayOptionsRedletter(null,p);
      enableTooltips();
      if (showBlockAnnotation=='block')
				enableNotesWindow();

      return;
    }


/*
    Function: setBooksNavigator
    Maintains the books & chapters navigator.

    Parameters:
        panel - integer(1 or 2).
        translationid - string.
        bookcode - string.
        bookname - string.
        chapterid - integer.
        verseid - integer.
        chaptercount - integer

    Returns:
        nothing.

    See Also:
        <replaceLinks(str, translationid, bookcode, bookname, chapterid, verseid)>
*/
    function setBooksNavigator(panel, translationid, bookcode, bookname, chapterid, verseid, chaptercount)
    {
        //left chapter link
        var tlChapter = document.getElementById("ctl00_maincontent_ReadingPanels_tlChapter"+panel);
        var blChapter = document.getElementById("ctl00_maincontent_ReadingPanels_blChapter"+panel);
        var x = "javascript:onChangeBookChapter(" + panel + ",'%ti','%bi','%bn','%ci','%vi','chapter','-')";
        tlChapter.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)
        blChapter.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)
        tlChapter.style.visibility = (parseInt(chapterid) > 1 ? 'visible': 'hidden');
        blChapter.style.visibility = (parseInt(chapterid) > 1 ? 'visible': 'hidden');

        //left book link
        var tlBook = document.getElementById("ctl00_maincontent_ReadingPanels_tlBook"+panel);
        var blBook = document.getElementById("ctl00_maincontent_ReadingPanels_blBook"+panel);
        x = "javascript:onChangeBookChapter(" + panel + ",'%ti','%bi','%bn','%ci','%vi','book','-')";
        tlBook.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)
        blBook.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)

        //right chapter link
        var trChapter = document.getElementById("ctl00_maincontent_ReadingPanels_trChapter"+panel);
        var brChapter = document.getElementById("ctl00_maincontent_ReadingPanels_brChapter"+panel);
         x = "javascript:onChangeBookChapter(" + panel + ",'%ti','%bi','%bn','%ci','%vi','chapter','+')";
        trChapter.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)
        brChapter.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)
        trChapter.style.visibility = (parseInt(chapterid) < chaptercount ? 'visible': 'hidden');
        brChapter.style.visibility = (parseInt(chapterid) < chaptercount ? 'visible': 'hidden');

        //right book link
        var trBook = document.getElementById("ctl00_maincontent_ReadingPanels_trBook"+panel);
        var brBook = document.getElementById("ctl00_maincontent_ReadingPanels_brBook"+panel);
         x = "javascript:onChangeBookChapter(" + panel + ",'%ti','%bi','%bn','%ci','%vi','book','+')";
        trBook.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)
        brBook.href = replaceLinks(x, translationid, bookcode, bookname, chapterid, verseid)
    }


/*
    Function: setAddNoteButton
    Adds attributes to the user-notes icons.

    Parameters:
        panel - integer(1 or 2).
        translationid - string.
        bookcode - string.
        bookname - string.
        chapterid - integer.
        verseid - integer.

    Returns:
        nothing.
*/
    function setAddNoteButton(panel, translationid, bookcode, bookname, chapterid, verseid)
    {
        // image Id: addWNotes1 or addWNotes2
        var addNotes = document.getElementById('addWNotes'+panel);
        addNotes.setAttribute( 'translation', translationid );
        addNotes.setAttribute( 'bookcode', bookcode );
        addNotes.setAttribute( 'chapterid', chapterid );
        addNotes.setAttribute( 'verseid', verseid );

        var bottom_addWNotes = document.getElementById('bottom_addWNotes'+panel);
        bottom_addWNotes.setAttribute( 'translation', translationid );
        bottom_addWNotes.setAttribute( 'bookcode', bookcode );
        bottom_addWNotes.setAttribute( 'chapterid', chapterid );
        bottom_addWNotes.setAttribute( 'verseid', verseid );
        return;
    }


/*
    Function: replaceLinks
    Replaces the flags (translationid, bookcode, bookname, chapterid, verseid) with the current data.

    Parameters:
        str - href/string.
        translationid - string.
        bookcode - string.
        bookname - string.
        chapterid - integer.
        verseid - integer.

    Returns:
        nothing.
*/
    function replaceLinks(str, translationid, bookcode, bookname, chapterid, verseid)
    {
        str = str.replace("%ti",translationid);
        str = str.replace("%bi",bookcode);
        str = str.replace("%bn",bookname);
        str = str.replace("%ci",chapterid);
        str = str.replace("%vi",verseid);
        return str
    }


/*
    Function: copyPanel
    Copies one panel to the other one.

    Parameters:
        fromIndex - panel index/integer.
        toIndex - panel index/integer.

    Returns:
        nothing.

    See Also:
        <copyFromHistVerses(requeststring, panel, savestate)>
        <processDisplayOptions(panel, hascross-ref, hasfootnotes, hasstrongs, hasredletters)>
        <copyFromHistSearch(requeststring, panel, savestate)>
        <copyFromHistDocument(requeststring, panel, savestate)>
        <copyFromHistStrongs(requeststring, panel, savestate)>
*/
    function copyPanel(fromIndex, toIndex)
    {
        var panel = fromIndex;
        var ch = BSTState.panel[panel-1].history.CurrentHistory;
        var displaytype = BSTState.panel[panel-1].history[ch].DisplayType;
        var requeststring = BSTState.panel[panel-1].history[ch].RequestString;
        switch(displaytype)
        {
            case "verse":
                copyFromHistVerses(requeststring, toIndex, true);
                // reset displayOptions object
                displayOptions[toIndex-1].setCrossref( displayOptions[fromIndex-1].getCrossref() );
                displayOptions[toIndex-1].setFootnotes( displayOptions[fromIndex-1].getFootnotes() );
                displayOptions[toIndex-1].setUsernotes( displayOptions[fromIndex-1].getUsernotes() );
                displayOptions[toIndex-1].setStrongs( displayOptions[fromIndex-1].getStrongs() );
                displayOptions[toIndex-1].setRedletteron( displayOptions[fromIndex-1].getRedletteron() );

                var ddlTranslationFrom = document.getElementById('ctl00_maincontent_ReadingPanels_ddlTranslation' + fromIndex);
                processDisplayOptions( toIndex,
                               ddlTranslationFrom.options[ddlTranslationFrom.selectedIndex].getAttribute('hascr'),
                               ddlTranslationFrom.options[ddlTranslationFrom.selectedIndex].getAttribute('hasfn'),
                               ddlTranslationFrom.options[ddlTranslationFrom.selectedIndex].getAttribute('hasst'),
                               ddlTranslationFrom.options[ddlTranslationFrom.selectedIndex].getAttribute('hasrl') );
                break;

            case "search":
                BSTState.panel[toIndex-1].CategoryName = BSTState.panel[fromIndex-1].CategoryName;
                BSTState.panel[toIndex-1].Keyword = BSTState.panel[fromIndex-1].Keyword;
                BSTState.panel[toIndex-1].TranslationId = BSTState.panel[fromIndex-1].TranslationId;
                BSTState.panel[toIndex-1].ChapterId = BSTState.panel[fromIndex-1].ChapterId;
                BSTState.panel[toIndex-1].BookGroup = BSTState.panel[fromIndex-1].BookGroup;
                BSTState.panel[toIndex-1].SortBy = BSTState.panel[fromIndex-1].SortBy;
                copyFromHistSearch(requeststring, toIndex, true);
                break;

            case "ref":
                copyFromHistDocument(requeststring, toIndex, true);
                break;

            case "strongs":
                copyFromHistStrongs(requeststring, toIndex, true);
                break;

//            case "":
//                break;

            default: alert("Oops an error occurred.");
        }
    }


    //remove this
    function copyFromHistory(displaytype, requeststring, panel)
    {
        BSTState.panel[panel-1].SaveState = false;
        switch(displaytype)
        {
            case "verse":
                copyFromHistVerses(requeststring, panel, false);
                break;

            case "search":
                copyFromHistSearch(requeststring, panel, false);
                break;

            case "ref":
                copyFromHistDocument(requeststring, panel, false);
                break;

            case "strongs":
                copyFromHistStrongs(requeststring, panel, false);
                break;

            default: alert(LocalStrings.AnErrorHasOccurredForThisOperationPleaseTryAgain);
        }
    }


/*
    Function: copyFromHistVerses
    Reads the search parameters from the panel-history object and copies the results (verses) to
    the second panel.

    Parameters:
        requeststring - params.
        panel - panel index (1 or 2).
        savestate - save state that manages the panels history.

    Returns:
        nothing.

    See Also:
        <callRefSearchByKey(panel, bookcode, bookname, chapterid, verseid, translationcode, savestate)>
*/
    function copyFromHistVerses(requeststring, panel, savestate)
    {
        //process verses
        var bookcode = requeststring.split('|')[0];
        requeststring = requeststring.replace(bookcode+'|', "");
        var bookname= requeststring.split('|')[0];
        requeststring = requeststring.replace(bookname+'|', "");
        var chapterid = requeststring.split('|')[0];
        requeststring = requeststring.replace(chapterid+'|', "");
        var verseid = requeststring.split('|')[0];
        requeststring = requeststring.replace(verseid+'|', "");
        var translationcode = requeststring;
        callRefSearchByKey(panel, bookcode, bookname, chapterid, verseid, translationcode, savestate);
    }


/*
    Function: copyFromHistDocument
    Reads the search parameters from the panel-history object and copies the results (library document)
    to the second panel.

    Parameters:
        requeststring - params.
        panel - panel index (1 or 2).
        savestate - save state that manages the panels history.

    Returns:
        nothing.

    See Also:
        <callGetLibraryDocument(panel, contentid, type, savestate)>
*/
    function copyFromHistDocument(requeststring, panel, savestate)
    {
        var contentid = requeststring.split('|')[0];
        requeststring = requeststring.replace(contentid+'|', "");
        var type = requeststring;
        callGetLibraryDocument(panel, contentid, type, savestate);
    }


/*
    Function: copyFromHistStrongs
    Reads the search parameters from the panel-history object and copies the results (strongs)
    to the second panel.

    Parameters:
        requeststring - params.
        panel - panel index (1 or 2).
        savestate - save state that manages the panels history.

    Returns:
        nothing.

    See Also:
        <openStrongs(strongs, panel, savestate)>
*/
    function copyFromHistStrongs(requeststring, panel, savestate)
    {
        var translationid = requeststring.split('|')[0];
        requeststring = requeststring.replace(translationid+'|', "");
        var bookcode = requeststring.split('|')[0];
        requeststring = requeststring.replace(bookcode+'|', "");
        var strongs = requeststring;
        BSTState.panel[panel-1].TranslationId =translationid;
        BSTState.panel[panel-1].BookCode = bookcode;
        openStrongs(strongs, panel, savestate);
    }


/*
    Function: copyFromHistSearch
    Reads the search parameters from the panel-history object and copies the search results
    to the second panel.

    Parameters:
        requeststring - params.
        panel - panel index (1 or 2).
        savestate - save state that manages the panels history.

    Returns:
        nothing.

    See Also:
        <getFinderSearchResults(panel,contenttype,'',keyword,translationid,bookgroup,sortby,savestate)>
*/
    function copyFromHistSearch(requeststring, panel, savestate)
    {
        var contenttype = requeststring.split('|')[0];
        requeststring = requeststring.replace(contenttype+'|', "");
        var keyword= requeststring.split('|')[0];
        requeststring = requeststring.replace(keyword+'|', "");
        var translationid = requeststring.split('|')[0];
        requeststring = requeststring.replace(translationid+'|', "");
        var bookgroup = requeststring.split('|')[0];
        requeststring = requeststring.replace(bookgroup+'|', "");
        var sortby = requeststring.split('|')[0];
        requeststring = requeststring.replace(sortby+'|', "");
        var searchpagenum = requeststring;
        searchPageNumber = searchpagenum;
        getFinderSearchResults(panel,
                               contenttype,'',
                               keyword,
                               translationid,
                               bookgroup,
                               sortby, savestate);
        return;
    }


/*
    Function: showBusyCursor
    Shows the busy-cursor.

    Parameters:
        divon - div-name which needs to be on.
        divoff - div-name which needs to be off.
        parent - the parent div.

    Returns:
        returnedValue nothing.

    See Also:
        <hidediv(div-name)>
        <showdiv(div-name)>
*/
    function showBusyCursor(divon, divoff, parent)
    {
        var objPar = document.getElementById(parent);
        var objLeft = (objPar.offsetWidth) / 2 - 65;
        var objTop = 50;
        hidediv(divoff);
        showdiv(divon);
        var container = document.getElementById(divon);
        var waitHtml = '';
        //waitHtml += '<table style="position:absolute; left:' + objLeft +'px; top:' + objTop + 'px;">';
        //waitHtml += '<tr><td align="center" class="busycursor">&nbsp;</td></tr>';
        //waitHtml += '<tr><td align="center">' + LocalStrings.ProcessingYourRequest + '</td></tr></table>';
        container.innerHTML = waitHtml;
    }


/*
    Function: processAudioButton
    Processes the audio-button.

    Parameters:
        showaudio - boolean(true or false).
        panel - panel index/integer.

    Returns:
        nothing.
*/
    function processAudioButton(showaudio, panel)
    {

        var objAudioPlayer = document.getElementById('audioPlayer'+panel);
        var audioPath;
        var strSequence = BSTState.panel[panel-1].Sequence;
        var strChapter = BSTState.panel[panel-1].ChapterId;
        var strTranslation = BSTState.panel[panel-1].TranslationId;

        if (BSTState.panel[panel-1].HasAudio == true)
        {
            // insert some embed code for flash player
            if (strSequence.length == 1)
							strSequence = '0' + strSequence;
            
            if (strChapter.length == 1)
							strChapter = '00' + strChapter
						else if (strChapter.length == 2)
							strChapter = '0' + strChapter;
            
            audioPath = 'http://ht.salemweb.net/bst/' + strTranslation + '-mp3/' + strSequence + '_' + BSTState.panel[panel-1].BookCode + '_' + strChapter + '.mp3';
            //audioPath = 'http://swn.edgeboss.net/download/swn/bst/' + strTranslation + '-mp3/' + strSequence + '_' + BSTState.panel[panel-1].BookCode + '_' + strChapter + '.mp3';
						
            objAudioPlayer.innerHTML =
                '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="26" height="26">' +
                '<param name="movie" value="../siteinfo/flash/mp3_player.swf?audio=' + audioPath + '">' +
                '<param name="quality" value="high">' +
                '<param name="wmode" value="transparent">' +
                '<embed src="../siteinfo/flash/mp3_player.swf?audio=' + audioPath + '" width="26" height="26" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent"></embed></object>';
        } else 
        {
					// display inactive audio image
          objAudioPlayer.innerHTML = '<img src="' + imagepath + 'button_Audio_inactive.gif" />';
        } // end if (BSTState.panel[panel-1].HasAudio = 1)

        return;
    }


/*
    Function: processPanelDisplayTag
    Retreives a tag-block(startTag & endTag) from the string Str and writes to the div (divname+panel).
    Then, it returns the remain text from the source Str.

    Parameters:
        str - string/source text.
        startTag - opened-tag.
        endTag - closed-tag.
        divname - div-name.
        panel - panel index.

    Returns:
        string.

    See Also:
        <processTag(str, startTag, endTag)>
*/
    function processPanelDisplayTag(str, startTag, endTag, divname, panel)
    {
      var x = processTag(str, startTag, endTag);
      var container = document.getElementById(divname + panel);

	    if (panel == 1)
        container.innerHTML = x;//x1;
	    else if (panel == 2)
        container.innerHTML = x;//x2;

	    str = newResults;
	    newResults = "";

	    return str;
    }


/*
    Function: processTag
    Returns the html inside the tags.

    Parameters:
        str - result from call-back method.
        startTag - opened-tag name.
        endTag - closed-tag name.

    Returns:
        string.

    See Also:
        <processPanelDisplayTag(str, startTag, endTag, divname, panel>
*/
    function processTag(str, startTag, endTag)
    {
			regStart = new RegExp(startTag, "i");
			regEnd = new RegExp(endTag, "i");
			var tagContent = str.split(regEnd)[0];
			var temp = tagContent + endTag;

			tagContent = tagContent.replace(startTag, "");
			newResults = str.replace(temp, "");

			return tagContent;
    }


/*
    Function: getHeaderFlagsTag
    Gets the header flags from the result, and returns the rest of the Str as a string.

    Parameters:
        str     - result from the call back-method.
        startTag - opened-tag name.
        endTag - closed-tag name.
        getBSTState - state object.
        panel - panel index.

    Returns:
        string.

    See Also:
        <getHeaderFlags(flags,getBSTState, panel)>
*/
    function getHeaderFlagsTag(str, startTag, endTag, getBSTState, panel)
    {
        regStart = new RegExp(startTag, "i");
	    regEnd = new RegExp(endTag, "i");

	    var flags = str.split(regEnd)[0];
	    var temp = flags + endTag;

	    flags = flags.replace(startTag, "");
	    getHeaderFlags(flags,getBSTState, panel);
	    str = str.replace(temp, "");
	    return str;
    }


/*
    Function: getHeaderFlags
    Sets the header flags from the result to an array "headerFlags".

    Parameters:
        str - result from the call back-method.
        getBSTState - state object.
        panel - panel index.

    Returns:
        string.

    See Also:
        <displayError(div-name, error-message)>
*/
    function getHeaderFlags(str, getBSTState, panel)
    {
        try {
            var pattern = new RegExp(";", "i");
	        headerFlags = str.split(pattern);

            if ( headerFlags[0] == 0 )
                 error = new ErrorHandler(false,'no error/getHeaderFlags/IF headerFlags== 0');
            else if ( headerFlags[0] == 1 )
                 error = new ErrorHandler(true,headerFlags[1]); // + '/getHeaderFlags/IF headerFlags== 1');
            if (getBSTState)
            {
                BSTState.panel[panel-1].TranslationId = headerFlags[2];
                BSTState.panel[panel-1].ChapterId = headerFlags[3];
                BSTState.panel[panel-1].BookCode = headerFlags[4];
                BSTState.panel[panel-1].BookName = headerFlags[5];
                BSTState.panel[panel-1].VerseId = headerFlags[6];
                if ( headerFlags[7] == 0 )
                    BSTState.panel[panel-1].LoadTranslation = false;
                else if ( headerFlags[7] == 1 )
                    BSTState.panel[panel-1].LoadTranslation = true;

                if ( headerFlags[8] == 0 )
                    BSTState.panel[panel-1].SaveState = false;
                else if ( headerFlags[8] == 1 )
                    BSTState.panel[panel-1].SaveState = true;

                if ( headerFlags[11] == 0 )
                    BSTState.panel[panel-1].HasAudio = false;
                else
                    BSTState.panel[panel-1].HasAudio = true;

                BSTState.panel[panel-1].Sequence = headerFlags[12];
                BSTState.panel[panel-1].ChapterCount = headerFlags[13];

             }
        }
        catch(err)
        {
            error = new ErrorHandler(true,err.description); // + '/getHeaderFlags/unhandled error');
            // Error
            displayError('mybstversesdisplay'+panel, error.ErrorMessage);
        }
	    return;
    }


    //remove this
    function setMyBSTAudio(panel, object, showaudiolink, href)
    {
        if (showaudiolink == "True")
        {
            var obj = document.getElementById(object);
            obj.href = href;
            showobject(object);
        }
        else hideobject(object);
        return;
    }
    //remove this
    function testVerseId(obj, verseid)
    {
        //alert(obj.id + ' - ' + verseid);
        var style = 'inline-block';
        if (verseid=0)
        {
            style='none';
        }
        obj.style.display = style;

    }


/*
    Function: openVersesWithinPanels
    Maintains and displays the verses within My-Bst panels.

    Parameters:
        panel - panel index.

    Returns:
        nothing.

    See Also:
        <hidediv(div-name)>
        <showdiv(div-name)>
        <showdiv(div-name, height)>
*/
    function openVersesWithinPanels(panel)
    {
        hidediv('mybstsearchresultdisplay' + panel);
        showdiv('mybstversesdisplay' + panel);

        showdiv('mybsttranslationresults' + panel);
        showdiv('headerNav' + panel);
        showdiv('verseFooter' + panel);
        showobject('lhrefChapter' + panel);
        showobject('lhrefBook' + panel);
        showobject('rhrefChapter' + panel);
        showobject('rhrefBook' + panel);
        setDivHeight('verseDisplay'+panel,'404px');
    }


/*
    Function: openSearchResultWithinPanels
    Maintains and displays the search results within My-Bst panels.

    Parameters:
        panel - panel index.

    Returns:
        nothing.

    See Also:
        <hidediv(div-name)>
        <showdiv(div-name)>
        <showdiv(div-name, height)>
        <scrollReset(div-name)>
*/
    function openSearchResultWithinPanels(panel)
    {
        showdiv('mybstsearchresultdisplay' + panel);
        hidediv('mybstversesdisplay' + panel);

        hidediv('mybsttranslationresults' + panel);
        hidediv('headerNav' + panel);
        hidediv('verseFooter' + panel);
        hideobject('lhrefChapter' + panel);
        hideobject('lhrefBook' + panel);
        hideobject('rhrefChapter' + panel);
        hideobject('rhrefBook' + panel);
        setDivHeight('verseDisplay'+panel,'585px');

        scrollReset('verseDisplay'+panel);
    }


/*
    Function: handleOver
    Handles the "over" behavior of an object.

    Parameters:
        obj - object name.
        on - active-state.
        off - off-state.
        inactive - inactive-state.

    Returns:
        nothing.
*/
    function handleOver(obj, on, off, inactive)
    {
        var x = obj.src.toLowerCase();
        x = x.replace(off, on);
        obj.src = x;
    }

/*
    Function: handleOut
    Handles the "out" behavior of an object.

    Parameters:
        obj - object name.
        on - active-state.
        off - off-state.
        inactive - inactive-state.

    Returns:
        nothing.
*/
    function handleOut(obj, on, off, inactive)
    {
        var x = obj.src.toLowerCase();
        x = x.replace(on, off);
        obj.src = x;
    }


/*
    Function: handleClick
    Handles the "click" event of an object.

    Parameters:
        obj - object name.
        on - active-state.
        hov - hover-state.
        off - off-state.
        inactive - inactive-state.
        panel - panel index.
        tabindex - tab-index.

    Returns:
        nothing.

    See Also:
        <showLowPaneTab(panel, tabindex)>
*/
    function handleClick(obj, on, hov, off, inactive, panel, tabindex)
    {
        var x = obj.src.toLowerCase();
        if ( x.indexOf(on) != -1 || x.indexOf(inactive) != -1 ) return;
        x = x.replace(hov, on);
        var temp = document.getElementById(lowPaneOn[panel-1]);
        var z = temp.src.toLowerCase();
        z = z.replace(on, off);
        lowPaneOn[panel-1] = obj.id;
        temp.src = z;
        obj.src = x;
        showLowPaneTab(panel, tabindex);
    }


/*
    Function: showLowPaneTab
    Shows & hides the low-pane tabs (user-notes, footnotes, cross-ref).

    Parameters:
        panel - panel index.
        tabindex - tabindex(user-notes, footnotes, cross-ref).

    Returns:
        nothing.

    See Also:
        <getLowPaneContent(div1, div2, div3, div4)>
*/
    function showLowPaneTab(panel, tabindex)
    {
        switch(tabindex)
        {
            case 1:
                getLowPaneContent("usernotes"+panel,"footnotes"+panel,"crossreference"+panel,"strongs"+panel);
                break;
            case 2:
                getLowPaneContent("footnotes"+panel,"usernotes"+panel,"crossreference"+panel,"strongs"+panel);
                break;
            case 3:
                getLowPaneContent("crossreference"+panel,"usernotes"+panel,"footnotes"+panel,"strongs"+panel);
                break;
            case 4:
                getLowPaneContent("strongs"+panel,"usernotes"+panel,"footnotes"+panel,"crossreference"+panel);
                break;
            default: getLowPaneContent("usernotes"+panel,"footnotes"+panel,"crossreference"+panel,"strongs"+panel);
        }
        return;
    }


/*
    Function: getLowPaneContent
    Shows the div1 & hides the div2/div3/div4.

    Parameters:
        div1 - div-name.
        div2 - div-name.
        div3 - div-name.
        div4 - div-name.

    Returns:
        nothing.
*/
    function getLowPaneContent(div1, div2, div3, div4)
    {
        if (document.getElementById)
        { // DOM3 = IE5, NS6
                document.getElementById(div1).style.display = 'block';
                document.getElementById(div2).style.display = 'none';
                document.getElementById(div3).style.display = 'none';
                //document.getElementById(div4).style.display = 'none';
                }
        else {
            if (document.layers)
            { // Netscape 4
                document.div1.display = 'block';
                document.div2.display = 'none';
                document.div3.display = 'none';
                //document.div4.display = 'none';
            }
            else { // IE 4
                document.all.div1.style.display = 'block';
                document.all.div2.style.display = 'none';
                document.all.div3.style.display = 'none';
                //document.all.div4.style.display = 'none';
            }
        }
        return;
    }


/*
    Function: replace
    Replaces the part of the image-source ("_inactive") to "_on" or to "_off".

    Parameters:
        object - image name (as object).
        inactive - inactive-state image source.
        on - on-state image source.
        off - off-state image source.

    Returns:
        string/image-source.
*/
    function replace(obj, inactive, off, on)
    {
        var x = obj.src.toLowerCase();
        if (on == null)
        {
            x = x.replace(inactive, off); }
        else {
            if (x.indexOf(on) == -1)
            {
                x = x.replace(inactive, off);}
            else {
                x = x.replace(inactive, on);}
        }
        obj.src = x;
    }


/*
    Function: setLowPaneNav
    Enables or disables the low-pane tabs.

    Parameters:
        bool - true/false.
        panel - panel index.
        on - on-state image source.
        off - off-state image source.
        inactive - inactive-state image source.

    Returns:
        nothing.

    See Also:
        <showLowPaneTab(panel, tab-index)>
*/
    function setLowPaneNav(bool, panel, on, off, inactive)
    {
        var t6 = document.getElementById("imgUsernotes"+panel);
        var t7 = document.getElementById("imgFootnotes"+panel);
        var t8 = document.getElementById("imgCrossreference"+panel);
        //var t9 = document.getElementById("imgStrongs"+panel);
        if (bool )
        {
            replace(t6, inactive, off, on);
            replace(t7, inactive, off, on);
            replace(t8, inactive, off, on);
            //replace(t9, inactive, off, on);
        }
        else {
            if (lowPaneOn[panel-1] != "imgUsernotes"+panel)
            {
                var temp = document.getElementById(lowPaneOn[panel-1]);
                replace(temp, on, inactive, null);
                temp = document.getElementById("imgUsernotes"+panel);
                replace(temp, off, on, null);
                lowPaneOn[panel-1] = "imgUsernotes"+panel;
                showLowPaneTab(panel, 1);
            }

            replace(t6, off, inactive, on);
            replace(t7, off, inactive, on);
            replace(t8, off, inactive, on);
            //replace(t9, off, inactive, on);
        }
    }


/*
    Function: setToolBar
    Enables or disables the pane's tool-bar.

    Parameters:
        bool - true/false.
        panel - panel index.
        on - on-state image source.
        off - off-state image source.
        inactive - inactive-state image source.

    Returns:
        nothing.

    See Also:
        <setLowPaneNav(bool, panel, on, off, inactive)>
*/
    function setToolBar(bool, panel, on, off, inactive)
    {
        var sa = false;
        if (showBlockAnnotation=='block') sa = true;
        var t1 = document.getElementById("imgSize"+panel);
        var t2 = document.getElementById("imgBold"+panel);
        var t3 = document.getElementById("imgAddFlag"+panel);
        var t4 = document.getElementById("imgForeColor"+panel);
        var t5 = document.getElementById("imgAudio"+panel);
        var t6 = document.getElementById("imgDisplayOptions"+panel);
        var t7 = document.getElementById("imgDefHiliteColor"+panel);
        var t8 = document.getElementById("imgHiliteColor"+panel);
        var t9 = document.getElementById("imgClearAnnotations"+panel);
        var t10 = document.getElementById("imgDefForeColor"+panel);
        var t11 = document.getElementById("addWNotes"+panel);

        if (bool )
        {
            replace(t1, inactive, off, null);
            if (sa)
            {
                replace(t2, inactive, off, null);
                replace(t3, inactive, off, null);
                replace(t4, inactive, off, null);
                replace(t7, inactive, off, null);
                replace(t8, inactive, off, null);
                replace(t9, inactive, off, null);
                replace(t10, inactive, off, null);
                replace(t11, inactive, off, null);
            }
            else {
                replace(t2, off, inactive, null);
                replace(t3, off, inactive, null);
                replace(t4, off, inactive, null);
                replace(t7, off, inactive, null);
                replace(t8, off, inactive, null);
                replace(t9, off, inactive, null);
                replace(t10, off, inactive, null);
                replace(t11, off, inactive, null);
            }
            replace(t5, inactive, off, null);
            replace(t6, inactive, off, null);
        }
        else {
            replace(t1, off, inactive, null);
            replace(t2, off, inactive, null);
            replace(t3, off, inactive, null);
            replace(t4, off, inactive, null);
            replace(t5, off, inactive, null);
            replace(t6, off, inactive, null);
            replace(t7, off, inactive, null);
            replace(t8, off, inactive, null);
            replace(t9, off, inactive, null);
            replace(t10, off, inactive, null);
            replace(t11, off, inactive, null);

        }

        setLowPaneNav(bool, panel, on, off, inactive);
    }


/*
    Function: setBackForward
    Maintains the back & forward buttons within My-Bst panels.

    Parameters:
        panel - panel index

    Returns:
        nothing.
*/
    function setBackForward(panel)
    {
        if (BSTState.panel[panel-1].history.CurrentHistory == 0)
        {
            var x = document.getElementById("imgBack"+panel).src;
            if ( x.indexOf('_off') )
                x = x.replace('_off', '_inactive');
            else
                x = x.replace('_on', '_inactive');
            document.getElementById("imgBack"+panel).src = x;
            defHovImgBack[panel-1] = defHovImgBack[panel-1].replace('_on', '_inactive');
            defOutImgBack[panel-1] = defOutImgBack[panel-1].replace('_off', '_inactive');
        }
        else {
            var x = document.getElementById("imgBack"+panel).src.replace('_inactive', '_off');
            document.getElementById("imgBack"+panel).src = x;
            defHovImgBack[panel-1] = defHovImgBack[panel-1].replace('_inactive', '_on');
            defOutImgBack[panel-1] = defOutImgBack[panel-1].replace('_inactive', '_off');
        }
        if (BSTState.panel[panel-1].history.CurrentHistory == BSTState.panel[panel-1].history.length-1)
        {
            var x = document.getElementById("imgForward"+panel).src;
            if ( x.indexOf('_off') )
                x = x.replace('_off', '_inactive');
            else
                x = x.replace('_on', '_inactive');
            document.getElementById("imgForward"+panel).src = x;
            defHovImgForward[panel-1] = defHovImgForward[panel-1].replace('_on', '_inactive');
            defOutImgForward[panel-1] = defOutImgForward[panel-1].replace('_off', '_inactive');
        }
        else {
            var x = document.getElementById("imgForward"+panel).src.replace('_inactive', '_off');
            document.getElementById("imgForward"+panel).src = x;
            defHovImgForward[panel-1] = defHovImgForward[panel-1].replace('_inactive', '_on');
            defOutImgForward[panel-1] = defOutImgForward[panel-1].replace('_inactive', '_off');
        }
    }


/*
    Function: largePrint
    SummaryOfTheFunction.

    Parameters:
        panel - panel index.
        mainpane - main panel (where verses is displayed).
        footerpane - footnotes, cross-ref, and user-notes divs

    Returns:
        nothing.
*/
    function largePrint(panel, mainpane, footerpane )
    {
			var x = parseInt(BSTState.panel[panel-1].FontSize);

			if (x >= 16) 
				x = 8
			else	
				x += 2;
				
			setVerseFont(x, panel, mainpane, footerpane);
    }
    
    function setVerseFont(fontSize, panel, mainpane, footerpane)
    {
			BSTState.panel[panel-1].FontSize = fontSize;
			document.getElementById(mainpane).style.fontSize= BSTState.panel[panel-1].FontSize + 'pt';
			document.getElementById(footerpane).style.fontSize= BSTState.panel[panel-1].FontSize + 'pt';
    }


/*
    Function: printDocument
    Print Document - Builds a URL from the current platter state.
    and opens a printer-friendly page in a new window.

    Parameters:
        panel - panel index.

    Returns:
        nothing.
*/
    function printDocument(panel)
    {
			var i = BSTState.panel[panel-1].history.CurrentHistory;

			if (i >= 0)
			{
				var displayType = BSTState.panel[panel-1].history[i].DisplayType;
				var params = BSTState.panel[panel-1].history[i].RequestString.split('|');
				var url = '';

				if (displayType == 'verse')
				{
					url = 'print.aspx?';
					url += 'type=bible';
					url += '&reference=' + params[0] + ' ' + params[2];
					url += '&translation=' + params[4];
				}
				else if (displayType == 'ref')
				{
					url = 'print.aspx?';
					url += 'type=library';
					url += '&category=' + params[1];
					url += '&contentid=' + params[0];
				}

				if (url.length > 0)
				{
					var windowOptions = 'height=600,width=450,location=0,menubar=0,scrollbars=1,status=0,toolbar=0,resizable=1';
					window.open(url, 'MyBSTPrint', windowOptions, true);
				}
			}


    }


/*
    Function: maxTabContent
    Maximize the low-pane div.

    Parameters:
        panel - panel index.

    Returns:
        nothing.

    See Also:
        <setDivHeight(div-name,height)>
        <showdiv(div-name)>
        <hidediv(div-name)>
*/
function maxTabContent(panel)
{
    setDivHeight('verseDisplay'+panel,'404px');
    showdiv('verseFooter'+panel);
    showdiv('minBar'+panel);
    hidediv('maxBar'+panel);
    showobject('imgUsernotes'+panel);
    showobject('imgFootnotes'+panel);
    showobject('imgCrossreference'+panel);
    //showobject('imgStrongs'+panel);
    return;
}


/*
    Function: minTabContent
    Minimize the low-pane div.

    Parameters:
        panel - panel index.

    Returns:
        nothing.

    See Also:
        <setDivHeight(div-name,height)>
        <showdiv(div-name)>
        <hidediv(div-name)>
*/
function minTabContent(panel)
{
    setDivHeight('verseDisplay'+panel,'528px');
    hidediv('verseFooter'+panel);
    hidediv('minBar'+panel);
    showdiv('maxBar'+panel);
    return;
}


/*
    Function: addParallel
    Maintains the parallel view.

    Parameters:
        no-params.

    Returns:
        nothing.

    See Also:
        <copyPanel(from,to)>
        <enableTooltips()>
*/
function addParallel()
{
	var leftpanel = 'versePanel1';
    var rightpanel = 'versePanel2';
    var adpanel = 'adPanel3';
    var btnparallel = 'imgAddParallel1';
    var btnclose = 'imgClose1';
    var leftsearchbox = 'verseDisplay1';
    var rightsearchbox = 'verseDisplay2';

    singleView = false;

    copyPanel(1,2);
    if (document.getElementById)
    { // DOM3 = IE5, NS6
        document.getElementById(adpanel).style.display='none';
        document.getElementById(btnparallel).style.display='none';
        document.getElementById(btnclose).style.display='block';
        document.getElementById(leftpanel).style.width = '485px';
        document.getElementById(rightpanel).style.display = 'block';
        document.getElementById(rightpanel).style.width = '485px';
        document.getElementById(leftsearchbox).style.width = '483px';
        document.getElementById(rightsearchbox).style.width = '483px';
    }
    else {
        if (document.layers)
        { // Netscape 4
            document.adpanel.display = 'none';
            document.btnparallel.display = 'none';
            document.btnclose.display = 'block';
            document.leftpanel.width = '485px';
            document.rightpanel.display = 'block';
            document.rightpanel.width = '485px';
            document.leftsearchbox.width = '483px';
            document.rightsearchbox.width = '483px';
        }
        else { // IE 4
            document.all.adpanel.style.display = 'none';
            document.all.btnparallel.style.display = 'none';
            document.all.btnclose.style.display = 'block';
            document.all.leftpanel.style.width = '485px';
            document.all.rightpanel.style.display = 'block';
            document.all.rightpanel.style.width = '485px';
            document.all.leftsearchbox.style.width = '483px';
            document.all.rightsearchbox.style.width = '483px';
        }
    }
    enableTooltips();

    return;
}


/*
    Function: closeRightPanel
    Closes the right panel.

    Parameters:
        no-params.

    Returns:
        nothing.

    See Also:
        <enableTooltips()>
*/
function closeRightPanel( )
{
	var leftpanel = 'versePanel1';
    var rightpanel = 'versePanel2';
    var adpanel = 'adPanel3';
    var btnparallel = 'imgAddParallel1';
    var btnclose = 'imgClose1';
    var leftsearchbox = 'verseDisplay1';
    var rightsearchbox = 'verseDisplay2';
    singleView = true;

    if (document.getElementById)
    { // DOM3 = IE5, NS6
        document.getElementById(adpanel).style.display='block';
        document.getElementById(btnparallel).style.display='block';
        document.getElementById(btnclose).style.display='none';
        document.getElementById(leftpanel).style.width = '800px';
        document.getElementById(rightpanel).style.display = 'none';
        document.getElementById(leftsearchbox).style.width = '798px';
    }
    else {
        if (document.layers)
        { // Netscape 4
            document.adpanel.display = 'block';
            document.btnparallel.display = 'block';
            document.btnclose.display = 'none';
            document.leftsearchbox.width = '798px';
            document.leftpanel.width = '800px';
            document.rightpanel.display = 'none';
        }
        else { // IE 4
            document.all.adpanel.style.display = 'block';
            document.all.btnparallel.style.display = 'block';
            document.all.btnclose.style.display = 'none';
            document.all.leftsearchbox.style.width = '798px';
            document.all.leftpanel.style.width = '800px';
            document.all.rightpanel.style.display = 'none';
        }
    }

    enableTooltips();
    var ch = BSTState.panel[0].history.CurrentHistory;
    var displaytype = BSTState.panel[0].history[ch].DisplayType;
    if ( displaytype == 'verse' ) scrollSet('verseRow'+BSTState.panel[0].VerseId, 'verseDisplay1', 0);
    return;
}


/*
    Function: closeLeftPanel
    Copies the content of the right panel to the left panel and closes the right panel.

    Parameters:
        no-params.

    Returns:
        nothing.

    See Also:
        <copyPanel(from,to)>
        <closeRightPanel()>
*/
function closeLeftPanel()
{
    copyPanel(2,1);
    closeRightPanel();
    return;
}


/*
    Function: setDivHeight
    Sets the height of the div.

    Parameters:
        divname - div name.
        height - integer+'px'.

    Returns:
        nothing.
*/
function setDivHeight(divname, height)
{
    if (document.getElementById)
    { // DOM3 = IE5, NS6
        document.getElementById(divname).style.height = height;
    }
    else {
        if (document.layers)
        { // Netscape 4
            document.divname.height = height;
        }
        else { // IE 4
            document.all.divname.style.height = height;
        }
    }
    return;
}


/*
    Function: searchResultsPage
    Requests the search result per page-number.

    Parameters:
        pageNumber - pageNumber.
        panel - panel index.

    Returns:
        nothing.

    See Also:
        <getFinderSearchResults(panel,CategoryName,'',Keyword,TranslationId,BookGroup,SortBy,savestate)>
*/
function searchResultsPage(pageNumber, panel)
{
    BSTState.CurrentPanel = panel;
    searchPageNumber = pageNumber;
    getFinderSearchResults(panel,
                           BSTState.panel[BSTState.CurrentPanel-1].CategoryName,'',
                           BSTState.panel[BSTState.CurrentPanel-1].Keyword,
                           BSTState.panel[BSTState.CurrentPanel-1].TranslationId,
                           BSTState.panel[BSTState.CurrentPanel-1].BookGroup,
                           BSTState.panel[BSTState.CurrentPanel-1].SortBy, true);
}


/*
    Function: sortResults
    Sorts the search results.

    Parameters:
        sortbyon - sort by is on.
        sortbyoff - sort by is off.
        panel - the index of the search results contol.

    Returns:
        nothing.

    See Also:
        <getFinderSearchResults(panel,CategoryName,'',Keyword,TranslationId,BookGroup,SortBy,savestate)>
*/
function sortResults(sortbyon, sortbyoff, panel)
{
    if ( BSTState.panel[BSTState.CurrentPanel-1].SortBy != sortbyon)
    {
        searchPageNumber=1;
        BSTState.CurrentPanel = panel;
        BSTState.panel[BSTState.CurrentPanel-1].SortBy = sortbyon;
        getFinderSearchResults(panel,
                               BSTState.panel[BSTState.CurrentPanel-1].CategoryName,'',
                               BSTState.panel[BSTState.CurrentPanel-1].Keyword,
                               BSTState.panel[BSTState.CurrentPanel-1].TranslationId,
                               BSTState.panel[BSTState.CurrentPanel-1].BookGroup,
                               BSTState.panel[BSTState.CurrentPanel-1].SortBy, true);
    }
}


/*
    Function: displayError
    Displays a friendly error-message inside the "divname".

    Parameters:
        divname - div-name inside my-bst pane.
        errortext - friendly error-message to be displayed.

    Returns:
        nothing.
*/
function displayError(divname,errortext)
{
    if(errortext==""){
        document.getElementById(divname).innerHTML = '<span class="error">' + LocalStrings.AnErrorHasOccurredForThisOperationPleaseTryAgain + '</span>';
    } else {
        document.getElementById(divname).innerHTML = '<span class="error">' + errortext + '</span>';
    }
}


/*
    Function: onStartVerse
    Returns the verse-row# when a user clicks on My-Bst pane.

    Parameters:
        verseid - integer/verse id

    Returns:
        nothing.

    See Also:
        <onEndVerse(panel, verseid)>
*/
function onStartVerse(verseid)
{
    startVerse = verseid;
    return;
}


/*
    Function: onEndVerse
    Returns the verse-row# when a user releases the mouse after clicking on My-Bst pane.

    Parameters:
        panel - integer/panel index
        verseid - integer/verse id

    Returns:
        nothing.

    See Also:
        <onStartVerse(verseid)>
*/
function onEndVerse(panel, verseid)
{
    endVerse = verseid;
    if ( parseInt(startVerse) > parseInt(endVerse) )
    {
        var temp = startVerse;
        startVerse = endVerse;
        endVerse = temp;
    }
    else if ( parseInt(endVerse) > parseInt(startVerse) )
    {
        if (parseInt(startVerse) == 0 ) startVerse = 1;
    }

    var addNotes = document.getElementById('addWNotes' + panel);
    addNotes.setAttribute( 'verseid', startVerse );
    
    addNotes = document.getElementById('bottom_addWNotes' + panel);
    addNotes.setAttribute('verseid', startVerse);
    return;
}


//remove this
function onSave()
{

    return;
}
//remove this
function getElementText(elemId)
{
    var verseTag = document.getElementById(elemId);
    if (verseTag.innerText)
	    return verseTag.innerText
    else
	    return verseTag.textContent;
}


/*
    Function: annotateClick
    Manages the annotation functions.

    Parameters:
        p - integer/panel index.
        format - string(bold,underline,italic,forecolor,hilitecolor).
        option - color hex-number.

    Returns:
        nothing.

    See Also:
        <BibleStudyTools.Site.BLLService.AddUserFormat(translationId,bookCode, chapterId, verseId, html>
*/
function annotateClick(p, format, option)
{
	if (showBlockAnnotation=='none') return;
    if ( startVerse == 0 || endVerse == 0 ) return;

    var html;
    var re;

    for (var i=startVerse; i<= endVerse; i++)
    {
	    html = document.getElementById('verseTxt_' + p + '_' + i).innerHTML;

	    switch (format)
	    {
		    case 'bold':
			    re = new RegExp('<(/*)strong>', 'im');
			    if (! html.match(re))
				    html = '<strong>' + html + '</strong>';
			    else
				    html = html.replace('<strong>', '').replace('</strong>', '');
			    break;

		    case 'underline':
			    re = new RegExp('<(/*)u>', 'im');
			    if (! html.match(re))
				    html = '<u>' + html + '</u>';
			    else
				    html = html.replace('<u>', '').replace('</u>', '');
			    break;

		    case 'italic':

			    re = new RegExp('<(/*)em>', 'im');
			    if (! html.match(re))
				    html = '<em>' + html + '</em>';
			    else
				    html = html.replace('<em>', '').replace('</em>', '');
			    break;

		    case 'forecolor':
			    html = processForecolor(html, option);
			    break;

        case 'hilitecolor':
          html = processHighlitecolor(html, option);
			    break;

		    default:
			    break;
        }

        var context = html + '|' + p + '|' + i;
        BibleStudyTools.Site.BLLService.AddUserFormat(BSTState.panel[p-1].TranslationId,BSTState.panel[p-1].BookCode,
		                            BSTState.panel[p-1].ChapterId, i, html,
		                            Annotations_callback, AnnotationsFailed_callback, context, null);

    }
    startVerse = 0;
    endVerse = 0;

}


/*
    Function: Annotations_callback
    Manages the annotaion-callback method. If there's no error, then it displays the new formatted Html
    within My-Bst pane (verses).

    Parameters:
        result - string.
        context - string/html+'|'+panel+'|'+verseid

    Returns:
        nothing.
*/
function Annotations_callback(result, context)
{
    var str = getHeaderFlagsTag(result, "<headerFlags>", "</headerFlags>", false, 1);
    if (!error.ErrorOccurred())
    {
        var html = context.split('|')[0];
        context = context.replace(html+'|', "");
        var panel= context.split('|')[0];
        context = context.replace(panel+'|', "");
        var row = context;
        document.getElementById('verseTxt_' + panel + '_'  + row).innerHTML = html;
    }
    else {
        alert('Error Occurred - ' + error.getErrorMessage());
    }

}


/*
    Function: AnnotationsFailed_callback
    Displays an error message to users.

    Parameters:
        result - string.
        context - string/html+'|'+panel+'|'+verseid.
        methodName - JavaScript method that is been called.

    Returns:
        nothing.
*/
function AnnotationsFailed_callback(result,context, methodName)
{
		alert(LocalStrings.ErrorInWebMethod + " '"+methodName+"'.\n" + LocalStrings.Message + "='"+result._message+"'\n" + LocalStrings.statusCode + "="+result._statusCode+"\n" + LocalStrings.StackTrace + "='"+result._stackTrace+"'\n" + LocalStrings.ExceptionType + "='"+result._exceptionType+"'\n" + LocalStrings.TimedOut + "="+result._timedOut);
}


/*
    Function: clearAnnotations
    Clears the annotations from the selected verses.

    Parameters:
        p - panel index.

    Returns:
        nothing.

    See Also:
        <BibleStudyTools.Site.BLLService.DeleteUserFormat(translationId, bookCode, chapterId, startVerse, endVerse)>
*/
function clearAnnotations(p)
{
	if (showBlockAnnotation=='none') return;
    var context = p;

    BibleStudyTools.Site.BLLService.DeleteUserFormat(BSTState.panel[p-1].TranslationId, BSTState.panel[p-1].BookCode,
		                     BSTState.panel[p-1].ChapterId, startVerse, endVerse,
		                     ClearAnnotations_callback, ClearAnnotationsFailed_callback, context, null);
	return;

}


/*
    Function: ClearAnnotations_callback
    Manages the Clear Annotations-callback method. If there's no error, then it clears the annotations
    from the selected verses.

    Parameters:
        result - string.
        context - string/html+'|'+panel+'|'+verseid

    Returns:
        nothing.
*/
function ClearAnnotations_callback(result, context)
{

    var str = getHeaderFlagsTag(result, "<headerFlags>", "</headerFlags>", false, 1);
    if (!error.ErrorOccurred())
    {
        var html;
        var re;
	    var panel= context;

        for (var i=startVerse; i<= endVerse; i++)
        {
            html = document.getElementById('verseTxt_' + panel + '_' + i).innerHTML;

            re = new RegExp('<(/*)strong>', 'im');
	        if ( html.match(re) )
	        {
		        html = html.replace('<strong>', '').replace('</strong>', '');
		        html = html.replace('<STRONG>', '').replace('</STRONG>', '');
		    }
    		re = new RegExp('<(/*)em>', 'im');
	        if ( html.match(re) )
	        {
		        html = html.replace('<em>', '').replace('</em>', '');
		        html = html.replace('<EM>', '').replace('</EM>', '');
		    }
    		html = clearForecolor(html);
		    html = clearHighlitecolor(html);

		    document.getElementById('verseTxt_' + panel + '_' + i).innerHTML = html;

        }
    }
    else {
        alert(LocalStrings.ErrorOccurred + ' - ' + error.getErrorMessage());
    }

}


/*
    Function: ClearAnnotationsFailed_callback
    Displays an error message to users.

    Parameters:
        result - string.
        context - string/html+'|'+panel+'|'+verseid.
        methodName - JavaScript method that is been called.

    Returns:
        nothing.
*/
function ClearAnnotationsFailed_callback(result,context, methodName)
{
    alert("Error in Web Method '"+methodName+"'.\nMessage='"+result._message+"'\nStatus Code="+result._statusCode+"\nStack Trace='"+result._stackTrace+"'\nException Type='"+result._exceptionType+"'\nTimed Out="+result._timedOut);
}


/*
    Function: onDefaultColorClick
    Manages the annotation with the default colors.

    Parameters:
        p - integer/panel index.
        format - string(bold,underline,italic,forecolor,hilitecolor).
        color - color hex-number.

    Returns:
        nothing.

    See Also:
        <annotateClick(panel, format, color)>
*/
function onDefaultColorClick(p, format, color)
{
	if (showBlockAnnotation=='none') return;
    annotateClick(p, format, color);
}


/*
    Function: processForecolor
    Sets the forecolor of the selected verses (html).

    Parameters:
        html - string/selected verses.
        color - color number/hex-number.

    Returns:
        nothing.
*/
function processForecolor(html, color)
{

    var newHtml = '';
    var forecolor = 'color="' + color + '"';
    var re = new RegExp('<font color="?#[0123456789ABCDEFabcdef]{6}"?>','im');
    if ( html.match(re) )
    {
        var fontTag = html.match(re).toString();

        var re_1 = new RegExp('color="?#[0123456789ABCDEFabcdef]{6}"?','im');
        var colorStyle = fontTag.match(re_1).toString();

        newHtml = html.replace(colorStyle, forecolor);

    }
    else {
        newHtml = '<font color="' + color + '">' + html + '</font>';
    }
    return newHtml;

}


/*
    Function: processHighlitecolor
    Changes the highlite-color of the selected verses "html".

    Parameters:
        html - string/selected verses.
        color - color number/hex-number.

    Returns:
        nothing.
*/
function processHighlitecolor(html, color)
{

    var newHtml = '';
    var highlightColor = 'background-color:' + color + ';">';
    var re = new RegExp('<span style="background-color.*">','im');
    if ( html.match(re) )
    {
        var spanTag = html.match(re).toString();

        var x = 'background-color: rgb.*;">';
        var re_1 = new RegExp(x,'im');
        var highlightStyle = '';
        if ( spanTag.match(re_1) )
        {
					highlightStyle = spanTag.match(re_1).toString();
        }
        else 
        {
          x = 'background-color: #[0123456789ABCDEFabcdef]{6}">';
          re_1 = new RegExp(x,'im');
          highlightStyle = spanTag.match(re_1).toString();
        }

        newHtml = html.replace(highlightStyle, highlightColor);
    }
    else 
    {
        newHtml = '<span style="background-color:' + color + '">' + html + '</span>';
    }
    return newHtml;

}


/*
    Function: clearForecolor
    Returns the new html after it clears the forecolor from the selected verses.

    Parameters:
        html - string/selected verses.

    Returns:
        string.
*/
function clearForecolor(html)
{

    var newHtml = html;

    var re = new RegExp('<font color="?#[0123456789ABCDEFabcdef]{6}"?>','im');
    if ( html.match(re) )
    {
        var fontTag = html.match(re).toString();
        newHtml = html.replace(fontTag, '').replace('</font>','').replace('</FONT>','');
    }

    return newHtml;

}


/*
    Function: clearHighlitecolor
    Returns the new html after it clears the highlite from the selected verses.

    Parameters:
        html - string/selected verses.

    Returns:
        string.
*/
function clearHighlitecolor(html)
{

    var newHtml = html;
    var re = new RegExp('<span style="background-color.*">','im');

    if ( html.match(re) )
    {
        var spanTag = html.match(re).toString();

        var x = 'background-color: rgb.*;">';
        var re_1 = new RegExp(x,'im');
        var highlightStyle = '';

        if ( spanTag.match(re_1) )
        {
            highlightStyle = spanTag.match(re_1).toString();
            highlightStyle = '<span style="' + highlightStyle;
        }
        else {
            x = 'background-color: ?#[0123456789ABCDEFabcdef]{6}">';
            re_1 = new RegExp(x,'im');

            highlightStyle = spanTag.match(re_1).toString();
            x = '<span style="' + highlightStyle;
            re_1 = new RegExp(x,'im');
            highlightStyle = html.match(re_1).toString();
        }

        newHtml = html.replace(highlightStyle, '').replace('</span>','').replace('</SPAN>','');

    }

    return newHtml;

}


/*
    Function: searchResultClick
    Handles click event on a specific search result

    Parameters:
        contentType - type of content
        contentId - id of content
        index - panel# (if applicable)

    Returns:
        true/false - indicating whether link should proceed

*/
function searchResultClick(contentType, contentId, panelNumber)
{
	callGetLibraryDocument(panelNumber, contentId, contentType, true);
	return false;
}


/*  -------- MyFlags Classes --------- */

var MyFlags = new MyFlagsManager();
var MyFlagsAnimatedImage = null;
var MyFlagsAnimationTimeoutId = 0;

function MyFlagsManager()
{ 
	this.FlagItems = new Array();
	this.MaxFlagItems = 20;

	this.AddFlag = function(panelNumber)
	{
		if ((parseInt(startVerse) == 0) || (parseInt(endVerse) == 0) || (parseInt(startVerse) > parseInt(endVerse)) || (!userLoggedIn)) 
			return;
			
		if (this.FlagItems.length >= this.MaxFlagItems)
		{
			alert(LocalStrings.UnableToSaveFlag);
			return;
		}

		if (MyFlagsAnimationTimeoutId > 0)
		{
			window.clearTimeout(MyFlagsAnimationTimeoutId);
			this.EndFlagAnimation(); // in case indicator is active
		}

		var verseText = document.getElementById('verseTxt_' + panelNumber + '_' + startVerse).innerHTML;
		if (this._addFlagToCollection(BSTState.panel[panelNumber-1].TranslationId,	BSTState.panel[panelNumber-1].BookCode,	BSTState.panel[panelNumber-1].BookName, BSTState.panel[panelNumber-1].ChapterId,	startVerse,	endVerse, verseText))
		{
			this.AddFlagPanelNumber = panelNumber;
			BibleStudyTools.Site.BLLService.AddUserFlag(BSTState.panel[panelNumber-1].TranslationId,	BSTState.panel[panelNumber-1].BookCode,	BSTState.panel[panelNumber-1].ChapterId,	startVerse,	endVerse, MyBstWS_callback, MyBstWSFailed_callback);
			// re-render myflags boxes
			this.OutputFinderHtml();
			this.ShowFlagsInVerses(BSTState.panel[panelNumber-1].TranslationId, BSTState.panel[panelNumber-1].BookCode, BSTState.panel[panelNumber-1].ChapterId, panelNumber);
		}
	}
	
	this.RemoveFlag = function(flagIndex)
	{
		if ((userLoggedIn) && (flagIndex >= 0) && (flagIndex < this.FlagItems.length))
		{
			var fi = this.FlagItems[flagIndex];
			
			// remove flag indicator(s) from verse panels
			var vf = document.getElementById('verseFlag_1_' + fi.VerseStart);  // panel 1
			if (vf) vf.parentNode.removeChild(vf);
			vf = document.getElementById('verseFlag_2_' + fi.VerseStart);  // panel 2
			if (vf) vf.parentNode.removeChild(vf);
			
			BibleStudyTools.Site.BLLService.RemoveUserFlag(fi.TranslationCode, fi.BookCode, fi.Chapter, fi.VerseStart);
			this.FlagItems.splice(flagIndex, 1);  // remove from collection
			this.OutputFinderHtml();  // re-render myflags boxes
		}
	}

	this.StartFlagAnimation = function()
	{
		MyFlagsAnimatedImage = document.getElementById('btnGotoMyFlags' + this.AddFlagPanelNumber);
		MyFlagsAnimatedImage.src = MyFlagsAnimatedImage.src.toLowerCase().replace('_off', '_animated');
		MyFlagsAnimationTimeoutId = window.setTimeout(this.EndFlagAnimation, 2500);
	}

	this.EndFlagAnimation = function()
	{
		MyFlagsAnimationTimeoutId = 0;
		MyFlagsAnimatedImage.src = MyFlagsAnimatedImage.src.toLowerCase().replace('_animated', '_off');
		MyFlagsAnimatedImage = null;
	}
	
	this.NavigateToFlag = function(flagIndex, panelNumber)
	{
		if (flagIndex >= 0 && flagIndex < this.FlagItems.length)
		{
			var fi = this.FlagItems[flagIndex];
			var passage = fi.BookCode + ' ' + fi.Chapter + ':' + fi.VerseStart;
			callRefSearchByString(passage, panelNumber, fi.TranslationCode, BSTState);
		}
	}

	this.OutputFinderHtml = function()
	{
		// renders current list of flags as html
		var fi;
		var html;
		var ref;
		
		for (var panelNumber = 1; panelNumber <= 2; panelNumber++)
		{
			if (this.FlagItems.length > 0)
			{
				html = '<table>';
				for (var i=0; i < this.FlagItems.length; i++)
				{
					fi = this.FlagItems[i];

					ref = fi.BookName + ' ' + fi.Chapter + ':' + fi.VerseStart;
					if (parseInt(fi.VerseEnd) > parseInt(fi.VerseStart))
						ref += '-' + fi.VerseEnd;
					ref += ' (' + fi.TranslationCode.toUpperCase() + ')';

					html += '<tr><td>';
					html += '<a href="#" onclick="MyFlags.NavigateToFlag(' + i + ', ' + panelNumber + ');return false;">';
					html += ref;
					html += '</a>'
					html += ' - <i>&quot;' + substringWords(fi.VerseText, 65 - ref.length) + '&hellip;&quot;</i>';
					html += '</td><td>';
					html += '<img class="removeFlag" src="' + skinImagePath + 'button_remove.gif" onclick="MyFlags.RemoveFlag(' + i + ')" alt="' + LocalStrings.RemoveThisFlag + '" />';
					html += '</td></tr>';
				}
				
				html += '</table>';
			}
			else
			{
				html = LocalStrings.MyFlagsIntroduction;
			}
						
			// put into Myflags finder box.
			document.getElementById('myflagsitems' + panelNumber).innerHTML = html;
		}
	}
	
	this._addFlagToCollection = function(translationCode, bookCode, bookName, chapter, verseStart, verseEnd, verseText)
	{
		translationCode = translationCode.toLowerCase();
		// see if item has not already been added
		var fi;
		for (var i=0; i < this.FlagItems.length; i++)
		{
			fi = this.FlagItems[i];
			if ((fi.TranslationCode == translationCode) && (fi.BookCode == bookCode) && (parseInt(fi.Chapter) == parseInt(chapter)) && (parseInt(fi.VerseStart) == parseInt(verseStart)))
				return false;
		}

		fi = new MyFlagItem(translationCode, bookCode, bookName, chapter, verseStart, verseEnd, verseText);
		if (this.FlagItems.length == 0)
			this.FlagItems[0] = fi
		else 
			this.FlagItems[this.FlagItems.length] = fi;
		return true;
	}
	
	this.ShowFlagsInVerses = function(translationCode, bookCode, chapter, panelNumber)
	{
		if (this.FlagItems.length == 0)
			return;
	
		translationCode = translationCode.toLowerCase();
		var vf, vn;

		for (var i=0; i < this.FlagItems.length; i++)
		{
			fi = this.FlagItems[i];
			if ((fi.TranslationCode == translationCode) && (fi.BookCode == bookCode) && (parseInt(fi.Chapter) == parseInt(chapter)))
			{
				vf = document.getElementById('verseFlag_' + panelNumber + '_' + fi.VerseStart);
				if (! vf)
				{
					vn = document.getElementById('verseNum_' + panelNumber + '_' + fi.VerseStart);
					if (vn)
					{
						vf = document.createElement('li');
						vf.id = 'verseFlag_' + panelNumber + '_' + fi.VerseStart;
						vn.parentNode.appendChild(vf);
						
						var img = document.createElement('img');
						img.src = skinImagePath + 'icon_flag-1.gif'
						img.setAttribute('onclick', 'openFinder(\'f\', ' + panelNumber + ',\'\',\'\',\'\');');
						img.style.cursor = 'pointer';
						img.title = LocalStrings.MyFlagsFlagAlreadySet;
						vf.appendChild(img);
					}
				}
			}
		}
	}
}


// MyFlagItem Class
function MyFlagItem(translation, bookCode, bookName, chapter, verseStart, verseEnd, verseText)
{
	this.TranslationCode = translation.toLowerCase();
	this.BookCode = bookCode;
	this.BookName = bookName;
	this.Chapter = chapter;
	this.VerseStart = verseStart;
	this.VerseEnd = verseEnd;
	this.VerseText = verseText.replace(/(<([^>]+)>)/ig,""); // strip html tags
}


/* END -------- MyFlags Classes --------- END */


/* Extracts the first maxCharacters from text based on word boundary */
function substringWords(sourceText, maxCharacters)
{
	var pattern = /\ +/;
	var arr = sourceText.split(pattern);
	var returnVal = '';
	for (var i=0; i < arr.length; i++)
	{
		if ((returnVal.length + arr[i].length + 1) > maxCharacters)
			break;
		
		if (returnVal.length > 0) returnVal += ' ';
		returnVal += arr[i];
	}
	
	return returnVal;
}

function isScriptureReference(passage)
{
	//var regex = /([1-3]\s){0,1}[a-zA-Z\ ]+\s+[0-9]{1,3}([:\.][0-9]{0,3}([,-][0-9]{0,3})?)?/;
	var regex = /[\d]*\s?[a-ýÿz\-\s]+\.?\s*[\d,:;\-\ ]+\(?([a-ýÿz\-]*)\)?;?.*/i;
	
	return regex.test(passage);
}