//--------------------------------------------------------------------------------
// CollectionStatusPanel.js
// Handles the construction and display of the collectionStatusPanel that is used
// to display the status of collections as a search is going on.
//--------------------------------------------------------------------------------

/*global YAHOO, document */

/**
 * Default constructor... not used to create an instance
 */
function CollectionStatusPanel()
{
}

/**
 * The strings used for labeling the columns in this panel
 */
CollectionStatusPanel.nameColumnLabel = "<<>>";
CollectionStatusPanel.resultsColumnLabel = "<<>>";
CollectionStatusPanel.totalsColumnLabel = "<<>>";

/**
 * The data source for the collectionStatusTable
 */
CollectionStatusPanel.dataSource = null;

/**
 * The table that will display the collection status
 */
CollectionStatusPanel.collectionStatusTable = null;

/**
 * The panel that the table will be rendered in
 */
CollectionStatusPanel.panel = null;

/**
 * True if the panel is visible
 */
CollectionStatusPanel.isVisible = false;

/**
 * The list of hidden collection codes for the current view
 */
CollectionStatusPanel.hiddenCollectionCodes = [];

/**
 * Formatter function for the status column in the datatable
 * @param elCell the cell element
 * @param oRecord the record being written to the table
 * @param oColumn the column being written
 * @param oData extra data for the cell.  Not used
 */
CollectionStatusPanel.collectionStatusFormatter = function(elCell, oRecord, oColumn, oData)
{
    YAHOO.util.Dom.addClass(elCell, "status");
    var status;
    var ext = ".png";
    var altTitle = oRecord.getData("errorDetails");
    if (altTitle === null)
    {
        altTitle = "";
    }
    else
    {
        altTitle = altTitle.substring(altTitle.indexOf(":") + 1, altTitle.length);
        altTitle = altTitle.replace(/"/g, "&quot;");
    }

    status = oRecord.getData("status").toLowerCase();

    // Check for the case where there was a continuation that failed, but there were
    // results from the first run.  If so, then display the complete icon.
    if ((status == "failed" || status == "timed_out") && parseInt(oRecord.getData("numResults"), 10) > 0)
    {
        status = "complete";
        altTitle = "";
    }

    if (status == "running")
    {
        ext = ".gif";
    }

    var images = elCell.getElementsByTagName("img");
    if (images.length === 0)
    {
        elCell.innerHTML = ' <img src="' + getImageDir() + '/' + status + ext + '" width="16" title="' + altTitle + '">';
    }
    else
    {
        images[0].src = getImageDir() + '/' + status + ext;
        images[0].title = altTitle;
    }
};

/**
 * Formatter used to display the total column
 * @param elCell the cell element
 * @param oRecord the record being written to the table
 * @param oColumn the column being written
 * @param oData extra data for the cell.  Not used
 */
CollectionStatusPanel.totalsFormatter = function(elCell, oRecord, oColumn, oData)
{
    YAHOO.util.Dom.addClass(elCell, "status");

    var totalCollectionCounts = oRecord.getData("totalCollectionCounts");
    var numResults = oRecord.getData("numResults");
    if (totalCollectionCounts === null || parseInt(totalCollectionCounts, 10) < parseInt(numResults, 10))
    {
        totalCollectionCounts = numResults;
    }

    elCell.innerHTML = CoralUtils.formatInteger(totalCollectionCounts);
};

/**
 * Creates an instance of the collection status panel
 * @param data the data to use to create the table
 */
CollectionStatusPanel.createCollectionStatusTable = function(data)
{
    // Determine the position on the screen at which to put the status panel
    var leftPos = YAHOO.util.Dom.getViewportWidth() - 340;

    // Create the panel that will contain the collection status
    CollectionStatusPanel.panel = new YAHOO.widget.Dialog("collectionStatusPanel", {y:0, x:leftPos, zIndex:1000, width:"320px", draggable:true, visible:false, constraintoviewport:true });
    CollectionStatusPanel.panel.hideEvent.subscribe(function()
    {
        document.getElementById("collectionStatusPanel").style.display = "none";
        CollectionStatusPanel.isVisible = false;
    }, null, false);
    CollectionStatusPanel.panel.showEvent.subscribe(function()
    {
        document.getElementById("collectionStatusPanel").style.display = "";
        CollectionStatusPanel.isVisible = true;

      //If the height of the panel is higher than the viewport then we set the height to the viewport height
        if(document.getElementById("collectionStatusPanelBody").offsetHeight > YAHOO.util.Dom.getViewportHeight())
        {
            document.getElementById("collectionStatusPanel").style.height = YAHOO.util.Dom.getViewportHeight()+ 50 + "px";
            document.getElementById("collectionStatusPanelBody").style.height =  YAHOO.util.Dom.getViewportHeight()+"px";

        }

    }, null, false);

    // Define the columns for the table
    var columnDefs = [
        {key:"name", label: CollectionStatusPanel.nameColumnLabel, sortable:false, resizeable:true},
        {key:"status", className: "statusColumn", label: "", width: "16", formatter:CollectionStatusPanel.collectionStatusFormatter, sortable:false, resizeable:false},
        {key:"numResults", className: "numResultsColumn", label: CollectionStatusPanel.resultsColumnLabel, formatter:YAHOO.widget.DataTable.formatNumber, sortable:false, resizeable:true},
        {key:"totalCollectionCounts", className: "totalCollectionCountsColumn", label: CollectionStatusPanel.totalsColumnLabel, formatter:CollectionStatusPanel.totalsFormatter, sortable:false, resizeable:true}
    ];

    //Take the hidden collections out of the list so we don't show them
    for(var i = 0; i < data.length; i++)
    {
        for(var j = 0; j < CollectionStatusPanel.hiddenCollectionCodes.length; j++)
        {
            if(data[i].code == CollectionStatusPanel.hiddenCollectionCodes[j])
            {
                data.splice(i,1);
                i--;
                break;
            }
        }
    }

    CollectionStatusPanel.dataSource = new YAHOO.util.DataSource(data);
    CollectionStatusPanel.dataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
    CollectionStatusPanel.dataSource.responseSchema = {
        fields: ["name","code","status","numResults", "totalCollectionCounts","errorDetails"]
    };

    CollectionStatusPanel.collectionStatusTable = new YAHOO.widget.DataTable("collectionStatusPanelBody",
            columnDefs, CollectionStatusPanel.dataSource,
    {
        caption:"",
        sortedBy:{key:"name", dir:"asc"}
    }
            );

    // Render the panel
    CollectionStatusPanel.panel.render();

};

/**
 * Toggles the visibility state of the panel
 * @return always return false to prevent the onclick event from the initiating button
 * from being propagted.
 */
CollectionStatusPanel.toggle = function()
{
    if (!CollectionStatusPanel.panel)
    {
        return;
    }

    if (CollectionStatusPanel.isVisible)
    {
        CollectionStatusPanel.panel.hide();
        document.getElementById("collectionStatusPanel").style.display = "none";
    }
    else
    {
        CollectionStatusPanel.panel.show();
        document.getElementById("collectionStatusPanel").style.display = "";
    }

    return false;
};

/**
 * Refreshes the data in the table
 * @param data the new set of data
 */
CollectionStatusPanel.updateCollectionStatusTable = function(data)
{

    //Take the hidden collections out of the list so we don't show them
    for(var i = 0; i < data.length; i++)
    {
        for(var j = 0; j < CollectionStatusPanel.hiddenCollectionCodes.length; j++)
        {
            if(data[i].code == CollectionStatusPanel.hiddenCollectionCodes[j])
            {
                data.splice(i,1);
                i--;
                break;
            }
        }
    }

    // Loop through the data, and update the rows in the data table
    for (var i = 0; i < data.length; ++i)
    {
        CollectionStatusPanel.collectionStatusTable.updateRow(i, data[i]);
    }
};

/**
 * Sets the collection status.  It will create the collectionStatusTable, if needed.
 * @param collectionStatus a list of collectionSearchInfo objects
 */
CollectionStatusPanel.setCollectionStatus = function(collectionStatus)
{
    if (CollectionStatusPanel.collectionStatusTable === null)
    {
        CollectionStatusPanel.createCollectionStatusTable(collectionStatus);
    }
    else
    {
        CollectionStatusPanel.updateCollectionStatusTable(collectionStatus);
    }
};
