//-----------------------------------------------------------------------------
// File:  PrintResults.js
//
// Purpose:  This file controlls all the functionality associated with printing
//           results from resultList.html, markList.html, and alets.html
//
// Depenedencies: YUI
//-----------------------------------------------------------------------------

//Define the namespace
function PrintResults()
{

}

PrintResults.printDialog = null;
PrintResults.spinCtrl = null;
PrintResults.formData = null;
PrintResults.printMethod = null;
PrintResults.page = null;
PrintResults.searchCriteria = null;
PrintResults.printButton = "<<<uninitialized>>>";
PrintResults.cancelButton = "<<<uninitialized>>>";
PrintResults.alertName = null;

/**
 * Handles the submission of PrintResults.printDialog
 */
PrintResults.submitPrintDlg = function()
{
    //Get the form data JSON object
    PrintResults.formData = this.printDialog.getData();

    PrintResults.printMethod = PrintResults.formData.printMethod;

    PrintResults.page = PrintResults.formData.page;

    //Create action url
    var action;
    var urlBuilder = new URLBuilder("results-print-page.html");
    urlBuilder.addParam("page", PrintResults.page);
    urlBuilder.addParam("printMethod", PrintResults.printMethod);

    switch(PrintResults.page){
        case "result-list":
            action = PrintResults.submitResultList(urlBuilder);
            PrintResults.printDialog.form.action = action;
            break;

        case "mark-list":
            action = PrintResults.submitMarkList(urlBuilder);
            PrintResults.printDialog.form.action = action;
            break;


        case "alerts":
            action = PrintResults.submitAlerts(urlBuilder);
            PrintResults.printDialog.form.action = action;
            break;
    }

    //Submit the form
    PrintResults.printDialog.doSubmit();
    //Close the dialog
    PrintResults.printDialog.cancel();
};

/**
 * Builds the action url for submitting a print request from resultList.html
 * @param urlBuilder the object used to build the action url
 * @return the action url string.
 */
PrintResults.submitResultList = function(urlBuilder)
{
    var activePane = ResultList.instance.getActivePane();
    var paneId = activePane.paneId;
    var tabIndex = ResultList.instance.currentTabIndex;
    var sortfield;
    var maxResults;
    PrintResults.searchCriteria = PrintResults.formData.searchCriteria;

    switch(PrintResults.printMethod){
        case "printPage":
        //Need to submit a different start position depending on which page of results are being displayed
            urlBuilder.addParam("startPosition", activePane.startPosition);

        //activePane.resultCount is the number of results being displayed on the page
            maxResults = activePane.resultCount;
            sortfield = activePane.resultSortField;
            break;

        case "printAllTab":
        //activePane.displayCount is the total number of of results available for display in the tab
            maxResults = activePane.displayCount;
            sortfield = activePane.resultSortField;
            break;

        case "printAll":
        //if there is only one tab then maxResults is the total for the tab
            if(ResultList.instance.tabCount === 1)
            {
                maxResults = activePane.displayCount;
            }
            else
            {
                maxResults = ResultList.instance.displayTotal;
            }
            break;

        case "printFirstX":
        //Get the value of the spin control object
            maxResults = PrintResults.spinCtrl.GetCurrentValue();
            break;
    }

    //If the user has selected a "Limit to" option
    if(activePane.selectedCollection !== "")
    {
        urlBuilder.addParam("selectedCollection", activePane.selectedCollection);
    }

    urlBuilder.addParam("ssid", ResultList.instance.ssid);
    urlBuilder.addParam("paneId", paneId);
    urlBuilder.addParam("tabIndex", tabIndex);
    urlBuilder.addParam("sortField", sortfield);
    urlBuilder.addParam("maxResults", maxResults);
    urlBuilder.addParam("searchCriteria", PrintResults.searchCriteria);

    return urlBuilder.toString();

};

/**
 * Builds the action url for submitting a print request from markList.html
 * @param urlBuilder the object used to build the action url
 * @return the action url string.
 */
PrintResults.submitMarkList = function(urlBuilder)
{
    var maxResults;

    switch(PrintResults.printMethod){
        case "printPage":
            urlBuilder.addParam("startPosition", MarkList.instance.startPosition);
            maxResults = MarkList.instance.resultCount;
            break;

        case "printAll":
            maxResults = MarkList.instance.totalResultCount;
            break;

        case "printFirstX":
        //Get the value of the spin control object
            maxResults = PrintResults.spinCtrl.GetCurrentValue();
            break;
    }

    urlBuilder.addParam("maxResults", maxResults);
    urlBuilder.addParam("ssid", MarkList.instance.ssid);

    return urlBuilder.toString();
};

/**
 * Builds the action url for submitting a print request from alerts.html
 * @param printMethod the print method which the user has selected
 * @param urlBuilder the object used to build the action url
 * @return the action url string.
 */
PrintResults.submitAlerts = function(urlBuilder)
{
    var tabIndex = AlertList.instance.tabView.getTabIndex(AlertList.instance.tabView.get("activeTab"));
    var activePaginator = AlertList.instance.alertPaginators[tabIndex];
    var maxResults;
    PrintResults.alertName = AlertList.instance.selectedAlertName;

    switch(PrintResults.printMethod){
        case "printPage":
            urlBuilder.addParam("startPosition", activePaginator.startPosition);
            maxResults = activePaginator.resultCount;
            break;

        case "printAllTab":
            maxResults = activePaginator.totalResultCount;
            break;

        case "printFirstX":
        //Get the value of the spin control object
            maxResults = PrintResults.spinCtrl.GetCurrentValue();
            break;
    }

    urlBuilder.addParam("maxResults", maxResults);
    urlBuilder.addParam("alertSearchId", activePaginator.searchId);
    urlBuilder.addParam("alertId", activePaginator.alertId);
    urlBuilder.addParam("alertName", PrintResults.alertName);


    return urlBuilder.toString();
};

/**
 * Handles the actual disabling and enabling of the spin control
 * @param change the change desired
 */
PrintResults.handleSpinInput = function(change)
{
    var spinContainer = document.getElementById("spinContainer");
    var spinInput = document.getElementById("spinInput");
    var upBtn = document.getElementById("spinUpBtn");
    var downBtn = document.getElementById("spinDownBtn");

    if(change == "enable")
    {
        spinInput.disabled = false;
        PrintResults.spinCtrl.SetBackgroundColor("#FFFFFF");
        PrintResults.spinCtrl.SetButtonColor("#000000");
        PrintResults.spinCtrl.SetFontColor("#000000");
        PrintResults.spinCtrl.StartListening();
    }
    else
    {
        spinInput.disabled = true;
        PrintResults.spinCtrl.SetBackgroundColor("#CCCCCC");
        PrintResults.spinCtrl.SetButtonColor("#CCCCCC");
        PrintResults.spinCtrl.SetFontColor("#CCCCCC");
        PrintResults.spinCtrl.StopListening();
    }
};

/**
 * Handles disabling and enabling of the spin control based on the input selected
 * @param id the id of the input element
 */
PrintResults.toggleDisabled = function(id){

    if(id == "printFirstX")
    {
        PrintResults.handleSpinInput("enable");
    }
    else
    {
        PrintResults.handleSpinInput("disable");
    }
};

/**
 * Does all the work associated with displaying the YUI dialog
 */
PrintResults.showPrintResultsDlg = function()
{
    //Get the total number of results for the page we're on.
    var pathName = location.pathname;
    var resultsReqexp = new RegExp("result-list");
    var markListReqexp = new RegExp("mark-list");
    var alertsReqexp = new RegExp("alerts");
    var totalResults;

    if(!(pathName.search(resultsReqexp) === -1))
    {
        //If the tab count is only 1 then the total results will be the results from that tab
        if(ResultList.instance.tabCount === 1)
        {
            var activePane = ResultList.instance.getActivePane();
            totalResults = activePane.displayCount;
        }
        else
        {
            totalResults = ResultList.instance.displayTotal;
        }
    }
    else if(!(pathName.search(markListReqexp) === -1))
    {
        totalResults = MarkList.instance.totalResultCount;
    }
    else if(!(pathName.search(alertsReqexp) === -1))
    {
        var tabIndex = AlertList.instance.tabView.getTabIndex(AlertList.instance.tabView.get("activeTab"));

        /*
         If tabIndex is null it means that there are no alerts created.
         If it's 0 then the first tab (edit form) is selected so there
         are no results to display.
         */
        if(tabIndex === 0 || tabIndex === null)
        {
            totalResults = 0;
        }
        else
        {
            var activePaginator = AlertList.instance.alertPaginators[tabIndex];
            totalResults = activePaginator.totalResultCount;
        }
    }

    if(totalResults > 0 )
    {
        if(PrintResults.printDialog === null)
        {
            //Create the spin control
            PrintResults.spinCtrl = new SpinControl();
            PrintResults.spinCtrl.SetIncrement(1);
            PrintResults.spinCtrl.SetMinValue(1);
            PrintResults.spinCtrl.SetCurrentValue(10);

            //Add the spin control to the page
            var el = document.getElementById('spinCtrlContainer');
            el.appendChild(PrintResults.spinCtrl.GetContainer());

            //Disable the spin input on initial load
            PrintResults.handleSpinInput("disable");

            //Create handler functions for the dialog
            var printResultsDlg_cancel = function()
            {
                this.cancel();
            };

            var printResultsDlg_print = function()
            {
                PrintResults.submitPrintDlg();
            };

            //Create a new dialog object
            PrintResults.printDialog = new YAHOO.widget.Dialog(
                    "printResultsDlg",
            {
                visible: false,
                fixedcenter: true,
                width: "350",
                modal: true,
                underlay: "shadow",
                draggable: true,
                constraintoviewport: true,
                postmethod: "form",
                buttons: [ { text:PrintResults.cancelButton, handler:printResultsDlg_cancel},
                    { text:PrintResults.printButton, handler:printResultsDlg_print, isDefault:true } ]
            });

            //Attach keyboard keyhandlers
            YahooDlgHelper.attachKeyEventHandlers(PrintResults.printDialog, printResultsDlg_cancel);

            //set focus to the default button
            YahooDlgHelper.enableFocusOnShow(PrintResults.printDialog);

            //The dialog div needs to be displayed before the YUI can manipulate it
            var dlgDiv = document.getElementById("printResultsDlg");
            dlgDiv.style.display = "";

            PrintResults.printDialog.render();
        }

        //We have to set this value every time we show the dialog because the total results may change
        PrintResults.spinCtrl.SetMaxValue(totalResults);

        PrintResults.printDialog.show();
    }
    else
    {
        window.print();
    }
};

