﻿//Handle no firebug case
//if (typeof console === "undefined") {
//    console = { error: _a, info: _a, log: _a, time: _a, timeEnd: _a };
//}

// for discarding old search results.
var searchCounter = 0;
var IsLoadingCategories = false;

// keep track of search state.
var searchPage        = "1";
var searchMode        = "all";
var searchCategories  = new Array();
var searchSources     = new Array();
var searchRecordTypes = new Array();
var searchDocumentID  = -1;

function GetNewSearchCounter()
{
    searchCounter += 1;
    return searchCounter;
}

function GetSearchCounter()
{
    return searchCounter;
}

function ArrayIndexOf(array,element)
{
    for (var i = 0; i < array.length; i += 1)  
    {
        var e = array[i];

        if(e == element)
            return i;
    }

    return -1;
}

function SetSearchTerm(term)
{
    $("#txtSearch").attr("value",term);
}

function SetSearchMode(mode)
{
    var allbutton   = $("#search-type-all");
    var edocsbutton = $("#search-type-edocs");
    var booksbutton = $("#search-type-books");

   // allbutton[0].checked   = false;
    //edocsbutton[0].checked = false;
    //booksbutton[0].checked = false;
    
    if (mode == "all")
    {
        allbutton[0].checked = "checked";
        allbutton.change();
    }
    else if (mode == "edocuments")
    {
        edocsbutton[0].checked = "checked";
        edocsbutton.change();
    }
    else if (mode == "books")
    {
        booksbutton[0].checked = "checked";
        booksbutton.change();
    }

    $("#search-type-filter").button("refresh");

    searchMode = mode;
}

function SetSearchPage(inpage)
{
    searchPage = inpage.toString();
}

function GetSearchTerm()
{
    var searchtext = $("#txtSearch").attr("value");

    return searchtext;
}

function GetSearchPage()
{
    var pageint = parseInt(searchPage);

    if (pageint == NaN)
    {
        return 1;
    }

    return pageint;
}

function GetSearchMode()
{
    return searchMode;
}

function GetSearchCategories()
{
    return searchCategories;
}

function GetSearchSources()
{
    return searchSources;
}

function GetSearchRecordTypes()
{
    return searchRecordTypes;
}

function BuildSearchParameters()
{
    var params = new Array();

    var bExactSearch = searchDocumentID != -1;

    if (bExactSearch)
    {
        params.push("documentid=" + encodeURIComponent(searchDocumentID));
    }
    else
    {
        // search text
        var searchtext = GetSearchTerm();

        if (searchtext)
        {
            params.push("searchterm=" + encodeURIComponent(searchtext));
        }

        // search page number
        var searchpage = GetSearchPage();

        if (searchpage != 1)
        {
            params.push("searchpage=" + GetSearchPage());
        }

        // search mode
        var searchmode = GetSearchMode();

        if (searchmode != "all")
        {
            params.push("searchmode=" + encodeURIComponent(searchMode));
        }

        // search categories
        var searchcategories = GetSearchCategories();

        for (c in searchcategories)
        {
            var category = searchcategories[c];

            params.push("category=" + encodeURIComponent(category));
        }

        // search sources
        var searchsources = GetSearchSources();

        for (s in searchsources)
        {
            var source = searchsources[s];

            params.push("source=" + encodeURIComponent(source));
        }

        // search record types
        var searchrecordtypes = GetSearchRecordTypes();

        for (r in searchrecordtypes)
        {
            var recordtype = searchrecordtypes[r];

            params.push("recordtype=" + encodeURIComponent(recordtype));
        }
    }

    // build the full parameter string
    var finalstring = "";
    var count = params.length;
    var i = 0;

    for (p in params)
    {
        if (i != 0)
        {
            finalstring += "&";
        }

        finalstring += params[p];

        i++;
    }
    
    return finalstring;
}

function UpdateSearchParameters()
{
    window.location.hash = BuildSearchParameters();
}

function UseSearchParameters()
{
    //TODO: parse the parameters out
    
    var splitnohash = window.location.hash.substring(1);
    var splitpairs  = splitnohash.split("&");

    var bhasparameters = false;

    //loop over all parameters and handle the cases.
    //(extract key/value pairs)
    for (pairindex in splitpairs)
    {
        var keyvalue = splitpairs[pairindex].split("=");

        // make sure we have valid key value pairs
        if (keyvalue.length == 2)
        {
            var key = keyvalue[0];
            var value = decodeURIComponent(keyvalue[1]);

            switch(key)
            {
                case "searchterm":
                    SetSearchTerm(value);
                    bhasparameters = true;
                    break;
                case "searchpage":
                    SetSearchPage(value);
                    bhasparameters = true;
                    break;
                case "documentid":
                    searchDocumentID = parseInt(value);
                    bhasparameters = true;
                    break;
                case "category":
                    AddCatFilter(value);
                    bhasparameters = true;
                    break;
                case "recordtype":
                    AddRecordTypeFilter(value);
                    bhasparameters = true;
                    break;
                case "source":
                    AddSourceFilter(value);
                    bhasparameters = true;
                    break;
                case "searchmode":
                    SetSearchMode(value);
                    bhasparameters = true;
                    break;
            default:
            }
        }
    }

    return bhasparameters;
}

// Startup Function
$(function ()
{


    //$("#btnOptions").button().click(function () {
    //    $('#SearchOptions').slideToggle();
    //});

    var runsearchfunction = function ()
    {
        UpdateSearchParameters();

        RunSearch();
    };

    var runsearchnotempty = function ()
    {
        var searchtext = GetSearchTerm();

        if (searchtext)
        {
            UpdateSearchParameters();

            RunSearch();
        }
    };

    var runsearchall = function ()
    {
        searchMode = "all";

        runsearchnotempty();
    };

    var runsearchbooks = function ()
    {
        searchMode = "books";

        runsearchnotempty();
    };

    var runsearchedocuments = function ()
    {
        searchMode = "edocuments";

        runsearchnotempty();
    };

    $("#search-type-filter").buttonset();

    $("#search-type-all").click(runsearchall);
    $("#search-type-books").click(runsearchbooks);
    $("#search-type-edocs").click(runsearchedocuments);

    SetSearchMode("all");

    //clicking the search button runs search
    $("#btnSearch").button().click(runsearchfunction);

    //enter key on txtsearch text field runs search
    $('#txtSearch').bind('keypress', function (e)
    {
        var code = (e.keyCode ? e.keyCode : e.which);

        if (code === 13)
        {
            //Enter key
            runsearchfunction();

            return false;
        }
    });


    //txtsearch text field focus runs search
    var intCurrentPage = 0;

    // focus on the text search box.
    $("#txtSearch").focus();

    //run the search, if we have text in the search box use it.
    if (UseSearchParameters())
    {
        
        if (searchDocumentID != -1)
        {
            RunSearchExact(searchDocumentID);
        }
        else
        {
            RunSearch(GetSearchPage());
        }

    }
    else
    {
        //Get categories list
        loadCategories();
    }


});

// Loads the category listing.
function loadCategories() 
{
    if(IsLoadingCategories)
        return;

    IsLoadingCategories = true;

    var searchid = GetNewSearchCounter();

    //Show Loading
    $("#Loading").show();
    var tc = $("#BrowseCategory");
    tc.empty();
    tc.show();
    tc.toggle("drop", 1);

    //get the categories as json from the GetCategorys generic handler.
    $.getJSON(baseUrl + "handlers/GetCategories.ashx", function (data) 
    {
        IsLoadingCategories = false;

        if(searchid != GetSearchCounter())
            return;

        var srcList = $("<dl></dl>");

        //Build category entries
        $(data).each(function () 
        {
            var newDiv = $("<div class='BrowseCategory'>")
            var newIDSpan = $("<span class='CategoryID'>" + this.TagID + "</span>")
            var newDT = $("<dt>")
            var newDD = $("<dd class='CategoryDesc'>" + this.TagDetails[0].DetailValue + "</dd>")

            var strTagName = this.TagName;
            var newTitleSpan = $("<div class='CategoryTitle'>" + strTagName + "</div>")
            
            $(newTitleSpan).click(function () 
            {
                AddCatFilter(strTagName);

                // Run the search when a category filter is added.
                RunSearch(1);
            });

            newDiv.append(newIDSpan);
            newDiv.append(newDT);
            newDT.append(newTitleSpan);
            newDiv.append(newDD);
            //newDiv.hide();
            srcList.append(newDiv);
            //newDiv.fadeIn(750);
        });

        //Hide Loading, display content
        $("#Loading").hide();
        tc.append("<div><h3>Filter Results by Category:</h3><div>");
        tc.append(srcList);
        tc.toggle("drop");
    });
}



//Add a category filter to the list
function AddCatFilter(Name) 
{
    //Add the category filter div item (contains filteritems)
    var strName = Name.replace(/_/g, " ").trim();

    //avoid duplicates
    if(ArrayIndexOf(searchCategories,strName) != -1)
        return;

    var strCatName = $("#CategoryFilter");
    if ($("#CategoryFilter div").length === 0) {
        var newTitleSpan = $("<div class='FilterHeader'>Filter By Category:</div>");
        newTitleSpan.hide();
        $("#CategoryFilter").append(newTitleSpan);
        newTitleSpan.fadeIn(700);
    }

    // add to the tracking array.
    searchCategories.push(strName)

    //Add the filteritem to the list, clicking the item will remove the category filteritem.
    var newSpan = $("<div class='FilterItem'>" + strName + " (x)</div>");
    $(newSpan).click(function () 
    {
        $(this).fadeOut(700, function () 
        {
            $(this).remove();
           
            if ($("#CategoryFilter div").length < 2) 
            {
                $("#CategoryFilter").empty();
            }
        });

        //Remove from the categories list
        var index = ArrayIndexOf(searchCategories, strName);
        searchCategories.splice(index, 1);

        CheckLoadCategories();

        $("#txtSearch").focus();
    });
    
    //Append to the list and focus on the search text box.
    newSpan.hide();
    $("#CategoryFilter").append(newSpan);
    newSpan.fadeIn(700);
    $("#txtSearch").focus();

};

//Add source filter
function AddSourceFilter(Name) 
{
    var strName = Name.replace(/_/g, " ").trim();

    //avoid duplicates
    if(ArrayIndexOf(searchSources,strName) != -1)
        return;

    var strCatName = $("#SourceFilter");
    if ($("#SourceFilter div").length === 0) {
        var newTitleSpan = $("<div class='FilterHeader'>Filter By Source:</div>");
        newTitleSpan.hide();
        $("#SourceFilter").append(newTitleSpan);
        newTitleSpan.fadeIn(700);
    }

    searchSources.push(strName);

    var newSpan = $("<div class='FilterItem'>" + strName + " (x)</div>");
    $(newSpan).click(function () 
    {
        $(this).fadeOut(700, function () 
        {
            $(this).remove();
            
            if ($("#SourceFilter div").length < 2) 
            {
                $("#SourceFilter").empty();
            }
        });


        //Remove from the sources list
        var index = ArrayIndexOf(searchSources, strName);
        searchSources.splice(index, 1);

        CheckLoadCategories();

        $("#txtSearch").focus();
    });


    newSpan.hide();
    $("#SourceFilter").append(newSpan);
    newSpan.fadeIn(700);
    $("#txtSearch").focus();

    
    RunSearch(1);
};



//Add record type filter
function AddRecordTypeFilter(Name) 
{
    var strName = Name.replace(/_/g, " ").trim();
    
    //avoid duplicates
    if(ArrayIndexOf(searchRecordTypes,strName) != -1)
        return;
        
    var strRecName = $("#RecordTypeFilter");
    if ($("#RecordTypeFilter div").length === 0) {
        var newTitleSpan = $("<div class='FilterHeader'>Filter By Record Type:</div>");
        newTitleSpan.hide();
        $("#RecordTypeFilter").append(newTitleSpan);
        newTitleSpan.fadeIn(700);
    }

    searchRecordTypes.push(strName);

    var newSpan = $("<div class='FilterItem'>" + strName + " (x)</div>");
    $(newSpan).click(function () 
    {
        $(this).fadeOut(700, function () 
        {
            $(this).remove();
            if ($("#RecordTypeFilter div").length < 2) 
            {
                $("#RecordTypeFilter").empty();
            }

        });
        
        //Remove from the record types list
        var index = ArrayIndexOf(searchRecordTypes,strName);
        searchRecordTypes.splice(index,1);

        CheckLoadCategories();

        $("#txtSearch").focus();
    });

    newSpan.hide();
    $("#RecordTypeFilter").append(newSpan);
    newSpan.fadeIn(700);
    $("#txtSearch").focus();
        
    RunSearch(1);
};

//TODO: not completely correct.
function ClearFilters()
{
    searchCategories = new Array();
    searchRecordTypes = new Array();
    searchSources = new Array();

    $("#CategoryFilter div").empty();
    $("#RecordTypeFilter div").empty();
    $("#SourceFilter div").empty();
}

//attempt to load the categories (if conditions met), or else run the search again.
function CheckLoadCategories()
{
    if( !searchCategories.length
    &&  !searchSources.length
    &&  !searchRecordTypes.length
    &&  !GetSearchTerm().length
    &&  !IsLoadingCategories )
    {
        $("#CategoryFilter").empty();
        $("#SearchResults").empty();
        $("#SearchTimes").empty();
        $("#Ajax-pager-top").empty();
        $("#Ajax-pager-bottom").empty();

        loadCategories();
    }
    else
    {
        RunSearch(1);
    }
}

//start the search visuals, show loading.
function StartSearchingVisuals()
{
    var sr = $("#SearchResults");

    $("#Ajax-pager-top").empty();
    $("#Ajax-pager-bottom").empty();
    $("#SearchTimes").hide();
    $("#Loading").show();

    $("#BrowseCategory").effect("drop", function ()
    {
        $("#BrowseCategory").hide();
        $("#BrowseCategory").empty();
    });

    sr.hide();
    sr.empty();
    
    return sr;
}

//end the searching visuals.
function EndSearchingVisuals(docList, sr)
{
    $("#Loading").hide();
    sr.hide();
    sr.append(docList);
    //console.log("appended");
    docList.show();
    sr.toggle("drop");
}

//run an exact search for a document by docid.
function RunSearchExact(docid)
{
    searchDocumentID = docid;

    var sr = StartSearchingVisuals();

    ClearFilters();

    UpdateSearchParameters();

    var docList = $("<dl class='SearchResults'></dl>");

    var searchid = GetNewSearchCounter();

    $.post(baseUrl + "handlers/GetDoc.ashx",
    {
        DocID: docid
    },
    function (doc)
    {
        if(searchid != GetSearchCounter())
            return;
        
        AddSearchResult(docList, doc);

        EndSearchingVisuals(docList,sr);
    });

}

//Grab the search term.
function GetSearchTerm()
{
    var searchTerm = $("#txtSearch").attr("value").trim();

    return searchTerm;
}

//Run the search using the settings on the page controls.
function RunSearch(pageNumber)
{
    // default argument handling
    if (!pageNumber)
        pageNumber = GetSearchPage();

    searchDocumentID = -1;
    SetSearchPage(pageNumber);

    UpdateSearchParameters();

    var searchTerm = GetSearchTerm();

    RunSearchTerm(pageNumber, searchTerm);
}

//run search utilizing the category, source, recordtype fields.
function RunSearchTerm(pageNumber, searchTerm) 
{
    //TODO: grab the value off the buttonset
    var buttonset = $("#search-type-filter");

    var searchtypeall   = $("#search-type-all");
    var searchtypebooks = $("#search-type-books");
    var searchtypeedocs = $("#search-type-edocs");

    var allchecked   = searchtypeall[0].checked;
    var bookschecked = searchtypebooks[0].checked;
    var edocschecked = searchtypeedocs[0].checked;

    var locationFilter = "All";

    if (bookschecked) 
    {
        locationFilter = "Books";
    }
    else if (edocschecked) 
    {
        locationFilter = "eDocuments";
    }

    // run the search with the tracked page settings.
    RunSearchWithSettings(pageNumber, searchTerm, searchCategories, searchSources, searchRecordTypes, locationFilter, true);    
}

//run the search, passing in all the settings for it.
function RunSearchWithSettings(pageNumber, searchTerm, searchCategories, searchSources, searchRecordTypes, locationFilter, bHighlight)
{
    var searchid = GetNewSearchCounter();
    
    var sr = StartSearchingVisuals();
    
    $.post(baseUrl + "handlers/SearchDocs.ashx", { LocationFilter: locationFilter, SearchTerm: searchTerm, PageNumber: pageNumber, Category: searchCategories, Source: searchSources, RecordType: searchRecordTypes }, function (data)
    {
        if(searchid != GetSearchCounter())
            return;
            
        var searchTime = data.SearchTime;
        if (searchTime.toString().substring(0, 3) === "00:")
            searchTime = searchTime.toString().substring(3);
        if (searchTime.toString().substring(0, 3) === "00:")
            searchTime = searchTime.toString().substring(3);
        if (searchTime.toString().substring(0, 3) === "00.")
            searchTime = searchTime.toString().substring(1);

        var intCurrentPage = data.CurrentPage;

        var searchResultSummary = "";
        searchResultSummary = "Search returned " + data.ResultCount + " document"
        if (data.ResultCount > 1)
            searchResultSummary += "s";
        if (data.ResultPageCount > 1)
            searchResultSummary += " on " + data.ResultPageCount + " pages";
        searchResultSummary += " in " + searchTime + " seconds.";
        $("#SearchTimes").html(searchResultSummary).effect("slide", "slow");

        var docList = $("<dl class='SearchResults'></dl>");

        var BuildDocFunction = function ()
        {
            AddSearchResult(docList, this);
        }

        //Build all category entries
        $(data.ResultSet).each( BuildDocFunction );

        var pagerTop = $("#Ajax-pager-top");
        var pagerBottom = $("#Ajax-pager-bottom");
       //pagerTop.empty();
        //pagerBottom.empty();

        var btnCount = 0;
        if (data.ResultPageCount > 1)
        {
            if (intCurrentPage > 5)
            {
                var newbtnt = $("<div id='pt1' class='pagerButton'>First</div>");
                $(newbtnt).button();
                pagerTop.append(newbtnt);
                var newbtnb = $("<div id='pb1' class='pagerButton'>First</div>");
                $(newbtnb).button();
                pagerBottom.append(newbtnb);
            }
            for (i = intCurrentPage - 5; i <= data.ResultPageCount; i++)
            {
                if (i > 0 && btnCount < 10)
                {
                    btnCount += 1;
                    var strSelected = "";
                    if (i === intCurrentPage)
                    {
                        strSelected = " ui-state-active disabled"
                    }
                    var newbtnt = $("<div id='pt" + i + "' class='pagerButton" + strSelected + "'>" + i + "</div>");
                    if (i === intCurrentPage)
                    {
                        $(newbtnt).button({ disable: true });
                    }
                    else
                    {
                        $(newbtnt).button();
                    }
                    pagerTop.append(newbtnt);
                    var newbtnb = $("<div id='pb" + i + "' class='pagerButton" + strSelected + "'>" + i + "</div>");
                    if (i === intCurrentPage)
                    {
                        $(newbtnb).button({ disable: true });
                    }
                    else
                    {
                        $(newbtnb).button();
                    }
                    pagerBottom.append(newbtnb);
                }
            };
            if (intCurrentPage < data.ResultPageCount)
            {
                var newbtnt = $("<div id='pt" + (intCurrentPage + 1) + "' class='pagerButton'>Next</div>");
                $(newbtnt).button();
                pagerTop.append(newbtnt);
                var newbtnb = $("<div id='pb" + (intCurrentPage + 1) + "' class='pagerButton'>Next</div>");
                $(newbtnb).button();
                pagerBottom.append(newbtnb);
            }
            var topButton = $("#pt" + intCurrentPage);
            topButton.button("disable");
            var bottomButton = $("#pb" + intCurrentPage);
            bottomButton.button("disable");

            $(".pagerButton").each(function ()
            {
                //$(this).button();
                $(this).click(function ()
                {
                    var p = $(this).attr("id");
                    if (p.toString().length > 2)
                    {
                        if (p.toString().substr(2) != intCurrentPage)
                        {
                            $("#Ajax-pager-bottom").hide();
                            RunSearch(p.toString().substr(2));
                        }
                    }
                });
            });
            pagerBottom.show();
            pagerTop.show();
        };

        //console.log(docList);
        EndSearchingVisuals(docList, sr);
        
        //run the highlighting code
        if (bHighlight)
        {

            //Start the highlight code here!!
            for (i = 0; i < searchCategories.length; i++)
            {
                //console.log(searchCategories[i]);
                sr.highlight(searchCategories[i]);
            }
            for (i = 0; i < searchSources.length; i++)
            {
                //console.log(searchSources[i]);
                sr.highlight(searchSources[i]);
            }
            for (i = 0; i < searchRecordTypes.length; i++)
            {
                //console.log(searchRecordTypes[i]);
                sr.highlight(searchRecordTypes[i]);
            }
            if (searchTerm.length > 0)
            {
                var strSearchTextArray = searchTerm.split(" ")
                for (i = 0; i < strSearchTextArray.length; i++)
                {
                    //console.log(strSearchTextArray[i]);
                    sr.highlight(strSearchTextArray[i]);
                }
            }
        }
    });

}

// called to add a document to the doclist tag result list
function AddSearchResult(docList,doc)
{
    var docItem = {};
    docItem.Categories = new Array();
    docItem.Sources = new Array();

    docItem.MimeType = "Link";
    docItem.DocID = doc.DocID;
    docItem.CategoryCount = 0;
    docItem.SourceCount = 0;
    docItem.URL = "";
    docItem.URLTitle = "Remote Document";
    docItem.Title = "";
    docItem.Summary = "";
    docItem.RecordType = "";
    docItem.PublishMonth = "";
    docItem.PublishYear = "";
    docItem.ReportNumber = "";
    docItem.ApprovalStatus = "";
    docItem.Notes = "";
    docItem.FileExtension = "";
    docItem.DocLocation = "";

    //initialize book data
    docItem.BookISBN = new Array();
    docItem.BookLCCN = "";
    docItem.BookLCC = "";
    docItem.BookNote = new Array();
    docItem.BookPages = "";
    docItem.BookPublisher = "";
    docItem.BookPubDate = "";
    docItem.BookTableOfContents = "";
    docItem.BookSubject = new Array();
    docItem.BookAuthor = new Array();
    docItem.BookCallNumber = new Array();
    docItem.BookLocation = "";
    docItem.URLs = new Array();

    $.each(doc.DocTags, function ()
    {
        switch (this.TagInfo.TypeInfo.TagTypeName)
        {
            case "MimeType":
                docItem.MimeType = this.TagInfo.TagName;
                break;
            case "URL":
                docItem.URL = this.TagInfo.TagName;
                docItem.URLs.push(this.TagInfo.TagName);
                break;
            case "Title":
                docItem.Title = this.TagInfo.TagName;
                break;
            case "Summary":
                docItem.Summary = this.TagInfo.TagName;
                break;
            case "RecordType":
                docItem.RecordType = this.TagInfo.TagName;
                break;
            case "PublishMonth":
                docItem.PublishMonth = this.TagInfo.TagName;
                break;
            case "PublishYear":
                docItem.PublishYear = this.TagInfo.TagName;
                break;
            case "ReportNumber":
                docItem.ReportNumber = this.TagInfo.TagName;
                break;
            case "ApprovalStatus":
                docItem.ApprovalStatus = this.TagInfo.TagName;
                break;
            case "Notes":
                docItem.Notes = this.TagInfo.TagName;
                break;
            case "FileExtension":
                docItem.FileExtension = this.TagInfo.TagName;
                break;
            case "DocLocation":
                docItem.DocLocation = this.TagInfo.TagName;
                break;
            case "Category":
                docItem.Categories[docItem.CategoryCount] = this.TagInfo.TagName;
                docItem.CategoryCount += 1;
                break;
            case "Source":
                var src = {};
                src.Name = this.TagInfo.TagName;
                src.URL = "";
                src.Description = "";
                $.each(this.TagInfo.TagDetails, function ()
                {
                    switch (this.DetailTypeInfo.DetailTypeID)
                    {
                        case 1:
                            src.Description = this.DetailValue;
                            break;
                        case 2:
                            src.URL = this.DetailValue;
                            break;
                    };
                });
                docItem.Sources[docItem.SourceCount] = src;
                docItem.SourceCount += 1;
                break;
            
            //special book cases...
            case "BookISBN":
                docItem.BookISBN.push(this.TagInfo.TagName);
            break;
            case "BookLCC":
                docItem.BookLCC = this.TagInfo.TagName;
            break;
            case "BookLCCN":
                docItem.BookLCCN = this.TagInfo.TagName;
            break;
            
            case "BookCallNumber":

                var checkoutdate = "";

                // if we have a checkout date note, set it
                $(this.Notes).each( function(index,element)
                {
                    if(element.Title == "CheckoutDate")
                        checkoutdate = element.Note;
                });
                
                var bookcallinfo = 
                {
                    CallNumber: this.TagInfo.TagName,
                    CheckoutDate: checkoutdate,
                    DocTagID: this.DocTagID,
                    TagID: this.TagInfo.TagID
                };

                docItem.BookCallNumber.push(bookcallinfo);
            break;
            case "BookNote":
                docItem.BookNote.push(this.TagInfo.TagName);
            break;
            case "BookPublisher":
                docItem.BookPublisher = this.TagInfo.TagName;
            break;

            case "BookPubDate":
                 docItem.BookPubDate = this.TagInfo.TagName;
            break;

            case "BookTableOfContents":
                docItem.BookTableOfContents = this.TagInfo.TagName;
            break;
            case "BookLocation":
                docItem.BookLocation = this.TagInfo.TagName;
            break;

            case "BookAuthor":
                docItem.BookAuthor.push(this.TagInfo.TagName);
            break;

            case "BookSubject":
                docItem.BookSubject.push(this.TagInfo.TagName);
            break;



            default:
                //console.log(this.TagInfo.TypeInfo.TagTypeName);
        };


    });

    // fix the doc url if possible.
    if (docItem.DocLocation != null)
    {
        if (docItem.DocLocation != "Remote" && docItem.RecordType != "Books")
        {
            docItem.URL = baseUrl + "handlers/GetDocBinary.ashx?d=" + docItem.DocID;
            docItem.URLTitle = "MIPT Document";
        }
        else
        {
            docItem.URLTitle = "Remote Document";
        }
    }
    else
    {
        docItem.URLTitle = "Remote Document";
    }


    //var newDoc = [];
    var newDoc = $("<div class='SearchResults SearchResultItem'>");
    var spanDocID = $("<span class='SRDocID'" + docItem.DocID + "</span>");
    newDoc.append(spanDocID);


    // create the title tag
    var dtTitle = $("<dt class='SRTitle'></dt>");
    newDoc.append(dtTitle);

    // need to find the url prefix
    var urlprefixlastindex = document.URL.lastIndexOf("/");
    var urlprefix = document.URL.substr(0, urlprefixlastindex + 1);

    // create the icon tag based on the mimetype
    // special icon for books   
    if(docItem.RecordType == "Books")
    {
        //var docIcon = $("<img src='DesktopModules/MIPT_eDocuments/images/book-icon.png'></img>");
        var docIcon = $("<img src='" + urlprefix + "DesktopModules/MIPT_eDocuments/images/book-icon.png'></img>");
        dtTitle.append(docIcon);
    }
    else
    {
        var docIcon = $("<img alt='' src='" + urlprefix + "DesktopModules/MIPT_eDocuments/images/icon_" + docItem.MimeType.toString().trim().replace('/', '') + ".gif' title='File Type:" + docItem.FileExtension + "'></img>");
        //var docIcon = $("<img alt='' src='DesktopModules/MIPT_eDocuments/images/icon_" + docItem.MimeType.toString().trim().replace('/', '') + ".gif' title='File Type:" + docItem.FileExtension + "'></img>");
        dtTitle.append(docIcon);
    }

    var docTitleSpan = $("<span class='SRTitle'><span>");
    dtTitle.append(docTitleSpan);

    // create the link if it exists
    if(docItem.URL != "" && docItem.RecordType != "Books")
    {
        var docTitleLink = $("<a CssClass='SRTitle' Target='_blank' href='" + docItem.URL + "' title='" + docItem.URLTitle + "'>" + docItem.Title + "</a>");
        dtTitle.append(docTitleLink);
    }
    else
    {
        var docTitleLink = $("<span Class='SRTitleNoLink' title='no link'>" + docItem.Title + "</span>");
        dtTitle.append(docTitleLink);
    }


    // add the doc date depending on whats on the item
    if(docItem.PublishMonth.length == 0)
    {
        if(docItem.PublishYear.length == 0)
        {
            //do nothing
        }
        else
        {
            var docDate = $("<div class='SRDate'>Publication Date: " + docItem.PublishYear + "</div>");
            newDoc.append(docDate);
        }
    }
    else
    {
        if(docItem.PublishYear.length == 0)
        {
            // do nothing, shouldn't happen
        }
        else
        {
            var docDate = $("<div class='SRDate'>Publication Date: " + docItem.PublishMonth + " / " + docItem.PublishYear + "</div>");
            newDoc.append(docDate);
        }
    }

    
    var ddDescription = $("<dd class='SRDescription'>" + docItem.Summary + "</dd>");
    newDoc.append(ddDescription);
    var descFooter = $("<div class='SearchResultFooter'></div>");
    ddDescription.append(descFooter);
    var footerDL = $("<dl></dl>");
    descFooter.append(footerDL);

    // display "Category"/"Categories"
    switch (docItem.CategoryCount)
    {
        case 0:
            break;
        case 1:
            var catDT = $("<dt class='CategoryLabel'>Category:</dt>");
            footerDL.append(catDT);
            break;
        default:
            var catDT = $("<dt class='CategoryLabel'>Categories:</dt>");
            footerDL.append(catDT);
    }

    // display categories
    var catDD = $("<dd class='CategoryName'></dd>");
    footerDL.append(catDD);
    $.each(docItem.Categories, function ()
    {
        var strCatName = this.replace(/\s/g, "_").trim();
        var catItem = $("<span class='CategoryName' title='Add as a filter'>" + this + "</span>")
        if (catDD.find("span").length > 0)
        {
            catDD.append(" : ");
        };
        catDD.append(catItem);
        $(catItem).click(function ()
        {
            AddCatFilter(strCatName);

            RunSearch(1);
        });
    });

    // display the source counts
    switch (docItem.SourceCount)
    {
        case 0:
            break;
        case 1:
            var srcDT = $("<dt class='SourceLabel'>Source:</dt>");
            footerDL.append(srcDT);
            break;
        default:
            var srcDT = $("<dt class='SourceLabel'>Sources:</dt>");
            footerDL.append(srcDT);
    }

    var srcDD = $("<dd class='SourceName'></dd>");
    footerDL.append(srcDD);

    $.each(docItem.Sources, function ()
    {
        var strSrcName = this.Name.replace(/\s/g, "_").trim();
        var srcItem = $("<span class='SourceName' title='Add as a filter'>" + this.Name + "</span>")
        srcDD.append(srcItem);
        $(srcItem).click(function ()
        {
            AddSourceFilter(strSrcName);

            RunSearch(1);
        });

        if (this.Description.length > 0)
        {
            var srcDesc = $("<span>(" + this.Description + ")</span>");
            srcItem.append(srcDesc);
        }
        if (this.URL.length > 0)
        {
            srcItem.append(" ");
            var srcLink = $("(<a href='" + this.URL + "' class='SourceWebsiteURL' target='_blank' title='" + this.URL + "'>Source Website</a>)")
            srcItem.append(srcLink);
        }
    });


    var recDT = $("<dt class='RecordTypeLabel'>Record Type:</dt>");
    footerDL.append(recDT);
    var strRecName = docItem.RecordType
    var recDD = $("<dd class='RecordTypeName' title='Add as a filter'>" + strRecName + "</dd>");
    footerDL.append(recDD);
    $(recDD).click(function ()
    {
        AddRecordTypeFilter(strRecName);

        RunSearch(1);
    });

    // if we're dealing with a Book, list additional information
    if(strRecName == "Books")
    {
        var expandbutton = $("<button class=\"ExpandBookInfoButton ui-button ui-button-icon-only ui-corner-all\" title=\"Open Book Info\">");
        var expandicon = $("<div class=\"ui-button-icon-primary ui-icon ui-icon-plus\">");

        expandbutton.button();//{ text: false });
        expandbutton.append(expandicon);

        var expanddiv = $("<div class=\"ExpandBookInfo\">");
        expanddiv.append(expandbutton);
        var expandtext = $("<span class=\"ExpandBookInfoText\">Additional Book Information</span>")
        expanddiv.append(expandtext);
        
        footerDL.append(expanddiv);

        var bookinfo = $("<div class=\"BookInfo ui-widget ui-widget-content ui-corner-all\">");
        footerDL.append(bookinfo);

        bookinfo.hide();
        
        var bexpandbutton = true;

        var expandfunction = function ()
        {
            if (bexpandbutton)
            {
                expandicon.removeClass('ui-icon-plus');
                expandicon.addClass('ui-icon-minus');
                //expanddiv.addClass('ui-icon-minus');
                //expanddiv.removeClass('ui-icon-plus');
                bookinfo.show('drop', 250);
                bexpandbutton = false;
            }
            else
            {
                expandicon.addClass('ui-icon-plus');
                expandicon.removeClass('ui-icon-minus');
                //expanddiv.addClass('ui-icon-plus');
                //expanddiv.removeClass('ui-icon-minus');
                bookinfo.hide('drop', 250);
                bexpandbutton = true;
            }

            return false;
        };

        // clicking the expand button will open the bookinfo div.
        expandbutton.click(expandfunction);
        expandtext.click(expandfunction);


        $(docItem.BookCallNumber).each(function (index, element)
        {
            var definitiontitle = $("<dt>Call Number: </dt>");
            bookinfo.append(definitiontitle);

            var definition = $("<dd>" + element.CallNumber + "</dd>");
            bookinfo.append(definition);

            // add the checkout status information
            if (element.CheckoutDate == "")
            {
                definition.append("<span class='BookCheckedIn'>(checked in)</span>");
            }
            else
            {
                definition.append("<span class='BookCheckedOut'>(checked out)</span>");
            }


            var checkout = $("<span class='BookRequestBook'>Request Book</span>");
            definition.append(checkout);

            //TEST: when checkout is clicked run a test function...
            checkout.click(function ()
            {
                var dialogtag = $("<div id=\"dialog-modal\" title=\"Request Book\">");

                var description = "<div>To request a book, fill out the form below and MIPT staff will get back with you soon!</div>";

                dialogtag.append(description);
                dialogtag.append("<br>");

                var bookcallnumber = element.CallNumber;
                var booktitle = docItem.Title;

                var booktitletag = $("<dt>Title:</dt><dd>" + booktitle + "</dd>");
                var bookcallnumbertag = $("<dt>Call Number:</dt><dd>" + bookcallnumber + "</dd>");

                dialogtag.append(booktitletag);
                dialogtag.append("<br><br>");
                dialogtag.append(bookcallnumbertag);
                dialogtag.append("<br><br>");

                function AddInputBox(name)
                {
                    var label = $("<div style='float:left; width:80px;'>" + name + "</div>");
                    var textbox = $("<input style='width: 400px;'></input>");
                    var div = $("<div>");

                    div.append(label);
                    div.append(textbox);

                    dialogtag.append(div);
                    dialogtag.append("<br>");

                    var bunch =
                    {
                        Label: label,
                        TextBox: textbox
                    };

                    return bunch;
                };

                var firstinput = AddInputBox("First Name");
                var lastinput = AddInputBox("Last Name");
                var emailinput = AddInputBox("Email Address");

                var additionalinfolabel = $("<div style='float:left; width:80px;'>Additional Info</div>");
                var additionalinfotextbox = $("<textarea style='width:400px; height:200px;'></textarea>");
                var additionalinfodiv = $("<div>");

                additionalinfodiv.append(additionalinfolabel);
                additionalinfodiv.append(additionalinfotextbox);

                dialogtag.append(additionalinfodiv);


                dialogtag.dialog(
                {
                    resizable: false,
                    width: 600,
                    height: 600,
                    modal: true,
                    buttons:
                    {
                        "Cancel": function ()
                        {
                            $(this).dialog('close');
                        },
                        "Ok": function ()
                        {
                            $(this).dialog('close');

                            //TODO: add the post
                            //TODO: write and send the email correctly.

                            var first = firstinput.TextBox.val();
                            var last = lastinput.TextBox.val();
                            var email = emailinput.TextBox.val();
                            var message = additionalinfotextbox.val();


                            $.post(baseUrl + "handlers/RequestBook.ashx",
                            {
                                Title: booktitle,
                                CallNumber: bookcallnumber,
                                First: first,
                                Last: last,
                                Email: email,
                                Message: message
                            },
                            function (data)
                            {

                                var alertdialogtag = $("<div id=\"dialog-modal\" title=\"Book Requested\">");

                                if (data == "Success!")
                                {
                                    alertdialogtag.append("Success! Your book request has been received!");
                                }
                                else
                                {
                                    alertdialogtag.append("Failure, try again later.");
                                }

                                alertdialogtag.dialog();

                            });
                        }
                    }
                });


                return false;
            });

        });



        if(docItem.BookPublisher.length > 0)
        {
            bookinfo.append("<dt>Publisher: </dt>");
            bookinfo.append("<dd>" + docItem.BookPublisher + "</dd>");
        }

        if(docItem.BookPubDate.length > 0)
        {
            bookinfo.append("<dt>Publish Date: </dt>");
            bookinfo.append("<dd>" + docItem.BookPubDate + "</dd>");
        }

        $(docItem.BookAuthor).each( function(index,element)
        {
            bookinfo.append("<dt>Author: </dt>");
            bookinfo.append("<dd>" + element + "</dd>");
        });

        if(docItem.BookTableOfContents.length > 0)
        {
            //TODO: split on " -- " and " , "
            bookinfo.append("<dt>Contents: </dt>");
            
            var contentstag = $("<dd>");
            bookinfo.append(contentstag);

            var splitcontents = docItem.BookTableOfContents.split(" -- ");

            $(splitcontents).each( function(index, element)
            {
                contentstag.append( element + "<br />");
            });
            
        }


        $(docItem.BookNote).each( function(index,element)
        {
            bookinfo.append("<dt>Note: </dt>");
            bookinfo.append("<dd>" + element + "</dd>");
        });


        if (docItem.BookSubject.length > 0)
        {
            bookinfo.append("<dt>Subjects: </dt>");

            var subjectdd = $("<dd>");


            $(docItem.BookSubject).each(function (index, element)
            {
                subjectdd.append("<span>" + element + "</span>");

                if (index + 1 < docItem.BookSubject.length)
                {
                    subjectdd.append("<span> : </span>");
                }
            });

            bookinfo.append(subjectdd);
        }

        $(docItem.BookISBN).each(function (index, element)
        {
            if (element.Length > 0)
            {
                var infodiv = $("<div>");
                infodiv.append("<dt>ISBN: </dt>");
                infodiv.append("<dd>" + element + "</dd>");
                bookinfo.append(infodiv);
            }
        });

        if (docItem.BookLCC.length > 0) 
        {
            var infodiv = $("<div>");
            infodiv.append("<dt>LCC: </dt>");
            infodiv.append("<dd>" + docItem.BookLCC + "</dd>");
            bookinfo.append(infodiv);
        }

        if(docItem.BookLCCN.length > 0)
        {
            var infodiv = $("<div>");
            infodiv.append("<dt>LCCN: </dt>");
            infodiv.append("<dd>" + docItem.BookLCCN + "</dd>");
            bookinfo.append(infodiv);
        }

        if(docItem.BookLocation.length > 0)
        {
            var infodiv = $("<div>");
            infodiv.append("<dt>Book Location: </dt>");
            infodiv.append("<dd>" + docItem.BookLocation + "</dd>");
            bookinfo.append(infodiv);
        }

        $(docItem.URLs).each( function(index,element)
        {
            bookinfo.append("<dt>URL: </dt>");
            bookinfo.append("<dd><a href=\"" + element + "\">"+ element + "</a></dd>");
        });


    }


    //newTitleSpan.hide();
    //$("#SourceFilter").append(newTitleSpan);
    //newTitleSpan.fadeIn(700);

    //docList.append(newDoc.join(""));
    //newDoc.hide();
    //console.log("loading doc");
    docList.append(newDoc);
    //newDoc.fadeIn(2000);


    // hooks in the document settings panel for the document
    GenerateDocumentSettings(newDoc, docItem);


}



jQuery.fn.highlight = function (pat) {
    function innerHighlight(node, pat) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                spannode.className = 'highlight';
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.each(function () {
        innerHighlight(this, pat.toUpperCase());
    });
};

jQuery.fn.removeHighlight = function () {
    return this.find("span.highlight").each(function () {
        this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    }).end();
};
