/*
    Variable: tipsWindow
    ?.
*/
var tipsWindow = null;


/*
    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;
      keyword = kyw;
      searchPageNumber = 1;
      if (contentlist.toLowerCase() == 'bibles')
        location.href  = path + 'search/default.aspx?keyword='+ kyw + '&type=bible&p=0&translation='+ userTranslation;
      else if (contentlist.toLowerCase() == 'library')
        location.href  = path + 'search/default.aspx?keyword='+ kyw + '&type=library';
      else
				location.href  = path + 'search/default.aspx?keyword='+ kyw + '&type=library&category=' + contentlist;
    }
    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.PleaseEnterAReference);
    }
    else
    {
			var path = appRoot;
			location.href  = path + 'mybst/default.aspx?reference=' + ref + '&type=bible&translation=' + userTranslation;
    }
    return;
}


/*
    Function: onLibraryChange
    On change event of the dropdownlist library it displays or hides
    the dropdownlist of both translation and the book-group.

    Parameters:
        field - object name.
        def - selected value.

    Returns:
        nothing.

    See Also:
        <displayBibleSubCategory(boolean)>
*/
function onLibraryChange(field,def)
{
    if (field.value == def)
    {
        displayBibleSubCategory(true);
    }
    else
    {
        displayBibleSubCategory(false);
    }
}


/*
    Function: displayBibleSubCategory
    On change event of the dropdownlist library it displays or hides
    the dropdownlist of both translation and the book-group.

    Parameters:
        bool - true or false.

    Returns:
        nothing.

    See Also:
        <onLibraryChange(field,def)>
*/
function displayBibleSubCategory(bool)
{
  if (bool)
  {
      document.getElementById("ctl00_maincontent_SearchResults_ddlTranslation").style.display = 'block';
      document.getElementById("ctl00_maincontent_SearchResults_ddlCategory").style.display = 'block';
      document.getElementById("lblTranslation").style.display = 'block';
      document.getElementById("lblCategory").style.display = 'block';
  }
  else 
  {
      document.getElementById("ctl00_maincontent_SearchResults_ddlTranslation").style.display = 'none';
      document.getElementById("ctl00_maincontent_SearchResults_ddlCategory").style.display = 'none';
      document.getElementById("lblTranslation").style.display = 'none';
      document.getElementById("lblCategory").style.display = 'none';
  }
}


/*
    Function: callRefine
    Refines the search.

    Parameters:
        no-params.

    Returns:
        nothing.
*/
function callRefine()
{
    var str = "";
    var kyw = document.getElementById('txtRefineSearch');
    if (kyw.value.trim() == "")
    {
      alert(LocalStrings.PleaseEnterOneOrMoreSearchWords);
      return;
    }
    
    var type = document.getElementById('ddlLibrary');
    var trans = document.getElementById('ctl00_maincontent_SearchResults_ddlTranslation');
    var catry = document.getElementById('ctl00_maincontent_SearchResults_ddlCategory');
    
		Keyword = kyw.value.trim();
		contentType = type.options[type.selectedIndex].value;
		categoryName = type.options[type.selectedIndex].value;
		refTitle = '';
		translationId = trans.options[trans.selectedIndex].value;
		bookGroup = catry.options[catry.selectedIndex].value;
		sortBy = '';
    searchPageNumber = 1;
		
		if (contentType == 'bibles')
		{
			if (translationId == 'all')
				translationId = '';
			if (categoryName == 'all')
				categoryName = '';
		}
		else if (contentType == 'library')
		{
			translationId = '';
			categoryName = '';
			bookGroup = '';
		}
		else
		{
			contentType = 'library';
			translationId = '';
			bookGroup = '';
		}
		
		//alert('Keyword:' + Keyword + ' contentType:' + contentType + ' categoryName:' + categoryName + ' translationId:' + translationId + ' bookGroup:' + bookGroup + ' sortBy:' + sortBy);
    getSearchResults(contentType, categoryName, refTitle, Keyword, translationId, bookGroup, sortBy)
    return false;
}


/*
    Function: searchResultsPage
    Returns the search results per page number.

    Parameters:
        pageNumber - page-number of the search results.
        Index - the index of the search results contol.

    Returns:
        nothing.

    See Also:
        <getSearchResults(contentType, categoryName, refTitle, Keyword, translationId, bookGroup, sortBy)>
*/
function searchResultsPage(pageNumber, Index)
{
    searchPageNumber = pageNumber;
    getSearchResults(contentType, categoryName, refTitle, Keyword, translationId, bookGroup, sortBy)
}


/*
    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:
        <getSearchResults(contentType, categoryName, refTitle, Keyword, translationId, bookGroup, sortbyon)>
*/
function sortResults(sortbyon, sortbyoff, panel)
{
    var contentType='bible';
    if (sortBy != sortbyon)
    {
        searchPageNumber=1;
        sortBy = sortbyon;
        getSearchResults(contentType, categoryName, refTitle, Keyword, translationId, bookGroup, sortbyon)
    }
}


/*
    Function: getSearchResults
    Calls the web-service "Search.BstSearch()" to get the search result by keyword.

    Parameters:
        contenttype - the content type (bible or library).
        categoryname - the category name (concordances, faq, sermon helps, etc...).
        reftitle - the reference title.
        keyword - the keyword to search on.
        translationid - the translation code.
        bookgroup - the book-group code.
        sortby - the field name to stort by.

    Returns:
        nothing.

    See Also:
        <selectDropDownList(strObj, strItemToSelect)>
        <displayBibleSubCategory(boolean)>
        <Search.BstSearch(index,contenttype,categoryname,reftitle,keyword,translationid,bookgroup,sortby,searchPageNumber)>
        <getSearchResults_callback(result)>
*/
function getSearchResults(contenttype, categoryname, reftitle, keyword, translationid, bookgroup, sortby)
{
    document.getElementById("txtRefineSearch").value = keyword;
    var libselected = contenttype;
    if (categoryName != '') libselected = categoryName;
    var searchtitle = document.getElementById('searchTitle');
    var strSearchtitle = LocalStrings.YouSearchedInThe + ' <b>' + libselected.capitalize() + '</b> ' + LocalStrings.For + ' <b>' + keyword +'</b>';
    if (contenttype.toLowerCase() == 'bible')
    {
        if (translationid == '')
            strSearchtitle += ' ' + LocalStrings.In + '<b>' + LocalStrings.AllTranslations + '</b>';
        else
            strSearchtitle += ' ' + LocalStrings.In + '<b>' + translationid.toUpperCase() + '</b>';
    }

    searchtitle.innerHTML = strSearchtitle;
    selectDropDownList('ddlLibrary', libselected);
    if ((contenttype.toLowerCase() == 'bible') || (contenttype.toLowerCase() == 'bibles'))
    {
      displayBibleSubCategory(true);
      if (translationid != '')
        selectDropDownList('ctl00_maincontent_SearchResults_ddlTranslation', translationid);
    }
    else 
    {
			displayBibleSubCategory(false);
    }

    BibleStudyTools.Site.Search.BstSearch(1, contenttype, categoryname, reftitle, keyword, translationid, bookgroup, sortby,
                           searchPageNumber, getSearchResults_callback);
    return false;
}


/*
    Function: getSearchResults_callback
    It checks first if no error occurred. Then, it displays the search results in "mybstsearchresults" div.
    If the content type=library, then it adds one more block in the "narrow" div to display
    the results count for each category in the library.

    Parameters:
        result - Html that was created in the web service.

    Returns:
        nothing.

    See Also:
        <getSearchResults(contenttype,categoryname,reftitle,keyword,translationid,bookgroup,sortby)>
        <BibleStudyTools.Site.Search.BstSearch(index,contenttype,categoryname,reftitle,keyword,translationid,bookgroup,sortby,searchPageNumber)>
        <getHeaderFlagsTag(str, startTag, endTag, getBSTState)>
*/
function getSearchResults_callback(result)
{
  var str = result;
  str = getHeaderFlagsTag(str, "<headerFlags>", "</headerFlags>",false);
  if ( !error.IsError )
  {
    if ((contentType.toLowerCase() == 'bible') || (contentType.toLowerCase() == 'bibles'))
    {
      var container = document.getElementById('mybstsearchresults');
      container.innerHTML = str;
    }
    else 
    {
      str = processPanelDisplayTag(str, "<allresults>", "</allresults>", "mybstsearchresults");
      str = processPanelDisplayTag(str, "<resultsbycategory>", "</resultsbycategory>", "narrow");
    }
  }
  else 
  { 
		alert('error: ' + error.ErrorDescription); 
	}
  return;
}


/*
    Function: searchResultsCategory
    Calls the javascript method getSearchResults with the category name.

    Parameters:
        categoryname - category name (concordances, bst help, faq, ect...).

    Returns:
        nothing.

    See Also:
        <getSearchResults(contenttype,categoryname,reftitle,keyword,translationid,bookgroup,sortby)>

*/
function searchResultsCategory(categoryname)
{
    categoryName = categoryname;
    refTitle = '';
    if ( categoryName.toLowerCase() == 'bibles' || categoryName.toLowerCase() == 'bible')
    {
        contentType = 'bible';
    }
    else contentType = 'library';
    searchPageNumber = 1;
    getSearchResults(contentType, categoryName, refTitle, Keyword, translationId, bookGroup, sortBy);
}


/*
    Function: processPanelDisplayTag
    It parses the results based on the tag names, then it displays the html, which is inside the tag,
    and returns the rest of html as a string.

    Parameters:
        str - result from call-back method.
        startTag - opened tage name.
        endTag - closed tage name.
        divname - div name where the result is displayed.

    Returns:
        string.

    See Also:
        <processTag(str, startTag, endTag)>
*/
function processPanelDisplayTag(str, startTag, endTag, divname)
{
    var x = processTag(str, startTag, endTag);
    var container = document.getElementById(divname);
    container.innerHTML = x;
    str = newResults
    newResults = ""
    return str;
}


/*
    Function: processTag
    Returns the html inside the tags.

    Parameters:
        str - result from call-back method.
        startTag - opened tage name.
        endTag - closed tage name.

    Returns:
        string.

    See Also:
        <processPanelDisplayTag(str, startTag, endTag)>
*/
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 remain html as a string.

    Parameters:
        str - result from the call back-method.
        startTag - opened tag name.
        endTag - closed tag name.
        getBSTState - BST state object.

    Returns:
        string.

    See Also:
        <getHeaderFlags(str, getBSTState)>
*/
function getHeaderFlagsTag(str, startTag, endTag, getBSTState)
{
    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);
    str = str.replace(temp, "");
    return str;
}


/*
    Function: getHeaderFlags
    Gets the header flags from the result.

    Parameters:
        str - result from the call back-method.
        getBSTState - BST state object.

    Returns:
        nothing.

    See Also:
        <getHeaderFlagsTag(str, startTag, endTag, getBSTState)>
*/
function getHeaderFlags(str, getBSTState)
{
    try {
        var pattern = new RegExp(";", "i");
	    headerFlags = str.split(pattern);

        if ( headerFlags[0] == 0 )
            error = new ErrorHandler(false,'no error');
        else if ( headerFlags[0] == 1 )
            error = new ErrorHandler(true,headerFlags[1]);
    }
    catch(err)
    {
        error = new ErrorHandler(true,err.description);
        alert('error:' + error.getErrorMessage());
    }
    return;
}


/*
    Function: verseResultsPage
    Redirects to mybst default page and searches on the bible.

    Parameters:
        type - type.
        index - index.
        bookcode - book code.
        bookname - book name.
        chapterid - chapter id.
        verseid - verse id.
        translationcode - translation code.

    Returns:
        nothing.

    See Also:
        <contentResultsPage(contenttype, index, contentid, documenttype)>
*/
function verseResultsPage(type, index, bookcode, bookname, chapterid, verseid, translationcode)
{
    var path = appRoot;
    location.href  = path + "mybst/default.aspx?type="+type+"&translation="+translationcode+"&bookcode="+bookcode+"&bookname="+bookname+"&chapterid="+chapterid+"&verseid="+verseid;
    return;
}


/*
    Function: contentResultsPage
    Redirects to mybst default page and searches on the library.

    Parameters:
        contenttype - content type.
        index - pane index (1 or 2).
        contentid - content id.
        documenttype - document type.

    Returns:
        nothing.

    See Also:
        <verseResultsPage(type, index, bookcode, bookname, chapterid, verseid, translationcode)>
*/
function contentResultsPage(contenttype, index, contentid, documenttype)
{
    var path = appRoot;
    location.href  = path + "mybst/default.aspx?type="+contenttype+"&contentid="+contentid+"&category="+documenttype;
    return;
}


/*
    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)
{
	return true;
}
