var g_oLastFoldout = null;
var g_oLastFoldoutLink = null;
var g_sId = null;

// ----------------------------------------------------------------------------
// Function:    closeLastFoldout
// Purpose:     Close the last foldout panel that was opened, if any.
// Inputs:      None
// Returns:     None
// ----------------------------------------------------------------------------
function closeLastFoldout()
{
    if (g_oLastFoldout)
    {
        g_oLastFoldout.style.display = 'none';

        if (g_oLastFoldoutLink.className != "noTwistyIcon" && g_oLastFoldoutLink.className != "")
        {
            g_oLastFoldoutLink.className = 'withTwistyIconClosed';
        }

        g_oLastFoldout = null;
    }
}


// ----------------------------------------------------------------------------
// Function:    foldout
// Purpose:     Open a folded panel
// Inputs:      oLink - Pointer to the <a> object that is associated with the
//                  foldout panel
//              sFoldoutId - ID of panel to be folded out
// Returns:     None
// ----------------------------------------------------------------------------
function foldout(oLink, foldoutId, sId, sProductId, sMerchandisingGroupId, sSearchButtonId)
{
    var oPanel = document.getElementById(foldoutId);
    var bShouldShowNew = true;   
    g_sId = sId;

    // Show the new panel if the new panel is not the same as the old panel.
    // Check before closing any existing foldout, because closing the existing foldout invalidates g_oLastFoldout.
    if (g_oLastFoldout)
    {
        bShouldShowNew = (g_oLastFoldout.id != oPanel.id);

        // Always try to close the last foldout panel
        closeLastFoldout();
    }

    if (bShouldShowNew) {
        //oPanel.style.display = g_platformTRVisibleStyle;
        oPanel.style.display = 'block';
        if (oLink.className != "noTwistyIcon") {
            oLink.className = 'withTwistyIconOpen';
        }
        g_oLastFoldoutLink = oLink;
        g_oLastFoldout = oPanel;

        loadProductDescription(sProductId, sMerchandisingGroupId, sSearchButtonId);
    } else {
    oLink.className = 'withTwistyIconClosed';
    }
}

// ----------------------------------------------------------------------------
// Function:    foldoutGraphic
// Purpose:     Open a folded panel, works like foldout but doesn't set cssClass
// Inputs:      oLink - Pointer to the <a> object that is associated with the
//                  foldout panel
//              sFoldoutId - ID of panel to be folded out
// Returns:     None
// ----------------------------------------------------------------------------
function foldoutGraphic(oLink, foldoutId, sId, sProductId, sMerchandisingGroupId, sSearchButtonId) {
    var oPanel = document.getElementById(foldoutId);
    var bShouldShowNew = true;
    g_sId = sId;

    // Show the new panel if the new panel is not the same as the old panel.
    // Check before closing any existing foldout, because closing the existing foldout invalidates g_oLastFoldout.
    if (g_oLastFoldout) {
        bShouldShowNew = (g_oLastFoldout.id != oPanel.id);

        // Always try to close the last foldout panel
        closeLastFoldout();
        if (g_oLastFoldout) {
            g_oLastFoldout.style.display = 'none';
            g_oLastFoldout = null;
        } 
    }

    var prodNameLink = foldoutId.replace('productDetailInfo', 'productNameLink');

    if (bShouldShowNew) {
        oPanel.style.display = g_platformTRVisibleStyle;

        g_oLastFoldoutLink = oLink;
        g_oLastFoldout = oPanel;

        loadProductDescription(sProductId, sMerchandisingGroupId, sSearchButtonId);
        document.getElementById(prodNameLink).className = 'withTwistyIconOpen';
    } else {
        document.getElementById(prodNameLink).className = 'withTwistyIconClosed';
    }
}


function foldoutChangeDates(oLink, foldoutId, sVendorId, sMerchandisingGroupId, sSearchButtonId, changeDatesCalendarId) {
    var oPanel = document.getElementById(foldoutId);
    var bShouldShowNew = true;
    g_changeDatesCalendarId = changeDatesCalendarId;
    //debugger;
    // Show the new panel if the new panel is not the same as the old panel.
    // Check before closing any existing foldout, because closing the existing foldout invalidates g_oLastFoldout.
    if (g_oLastFoldout) {
        bShouldShowNew = (g_oLastFoldout.id != oPanel.id);

        // Always try to close the last foldout panel
        closeLastFoldout();
    }

    if (bShouldShowNew) {
        //oPanel.style.display = g_platformTRVisibleStyle;
        oPanel.style.display = 'block';
        if (oLink.className != "noTwistyIcon") {
            oLink.className = 'withTwistyIconOpen';
        }

        g_oLastFoldoutLink = oLink;
        g_oLastFoldout = oPanel;


        var startDate = null;

        if (typeof (getPscStartDate) == "function") {
            startDate = getPscStartDate();
        }
        if ((startDate != null) && (isNaN(startDate.getTime()))) {
            year = 0;
            month = 0;
        }
        else {
            year = startDate.getFullYear();
            month = (startDate.getMonth() + 1);
        }
        
        
        EComChangeDatesCalendar.RenderChangeDatesCalendar(sVendorId, sMerchandisingGroupId, sSearchButtonId, year, month, getChangeDatesCalendar_callback);

    }
}

function loadProductDescription(sProductId, sMerchandisingGroupId, sSearchButtonId)
{
    EComProductGrid.GetProductDescription(sProductId, sMerchandisingGroupId, sSearchButtonId, loadProductDescription_callback);
}

function loadProductDescription_callback(res)
{
    if (res.error)
    {
        // Availability result threw error, display the error in a friendly way...
        alert('AJAX error\n\n' + res.error.Type + '\n\n' + res.error.Message);
    }
    else
    {
        var ProductID = res.request.args.productId;
        var MerchandisingGroupID = res.request.args.merchandisingGroupId;
        var SearchButtonID = res.request.args.searchButtonId;
        
        var oDiv;
        
        oDiv = document.getElementById("description_" + g_sId);
        
        oDiv.innerHTML = res.value;
                
        oDiv = document.getElementById('availCalendar_' + g_sId);
                
        if (oDiv)
        {
            openAvailabilityCalendar(ProductID, MerchandisingGroupID, SearchButtonID);
        }        
    }
}

// ----------------------------------------------------------------------------
// Function:    openAvailabilityCalendar
// Purpose:     Open the availability calendar with default dates.  This is
//              to be used when opening or re-opening the calendar tab
// Inputs:      sProductId - Product pkid
//              sMerchandisingGroupId - Merchandising Group pkid
// Returns:     None
// ----------------------------------------------------------------------------
function openAvailabilityCalendar(sProductId, sMerchandisingGroupId, sSearchButtonId)
{
	// TODO: Determine the default date based on the existing search
	var startDate = null;
	
	if (typeof(getPscStartDate) == "function")
	{
	    startDate = getPscStartDate();
	}
	if ((startDate != null) && (!isNaN(startDate.getTime())))
	{
        getAvailabilityCalendar(sProductId, sMerchandisingGroupId, sSearchButtonId, startDate.getFullYear(), (startDate.getMonth()+1));
	}
	else
	{
        getAvailabilityCalendar(sProductId, sMerchandisingGroupId, sSearchButtonId, 0, 0);
    }
}

// ----------------------------------------------------------------------------
// Function:    getAvailabilityCalendar
// Purpose:     First half of AJAX call; performs availability calendar search.
// Inputs:      sProductId - Product pkid
//              sMerchandisingGroupId - Merchandising Group pkid
//              startDate - JS Date object; start date
// Returns:     None
// ----------------------------------------------------------------------------
function getAvailabilityCalendar(sProductId, sMerchandisingGroupId, sSearchButtonId, year, month)
{
	// Calculate the end date such that it is at the end of the month after the start date.  I.e., the
	// date range will cover up to two months.
//    var endDate = new Date( (startDate.getMonth() >= 10) ? startDate.getFullYear() + 1 : startDate.getFullYear(),
//                            (startDate.getMonth() >= 10) ? startDate.getMonth() - 10 : startDate.getMonth() + 2,
//                            01,
//                            23, 59, 59, 999);
//    endDate.setDate(0);

    EComAvailabilityCalendar.RenderAvailabilityCalendar(sProductId, sMerchandisingGroupId, sSearchButtonId, year, month, getAvailabilityCalendar_callback);
}

function getChangeDatesCalendar(sVendorId, sMerchandisingGroupId, sSearchButtonId, year, month) {

    EComChangeDatesCalendar.RenderChangeDatesCalendar(sVendorId, sMerchandisingGroupId, sSearchButtonId, year, month, getChangeDatesCalendar_callback);

}

// ----------------------------------------------------------------------------
// Function:    getAvailabilityCalendar_callback
// Purpose:     Second half of AJAX call; Builds display of availability
//              calendar based on availability search
// Inputs:      res - AjaxPro result
// Returns:     None
// ----------------------------------------------------------------------------
function getAvailabilityCalendar_callback(res)
{
    if (res.error)
    {
        // Availability result threw error, display the error in a friendly way...
        alert('AJAX error\n\n' + res.error.Type + '\n\n' + res.error.Message);
    }
    else
    {
        var ProductID = res.request.args.productId;
        var MerchandisingGroupID = res.request.args.merchandisingGroupId;
        var StartDate = res.request.args.startDate;
        
        var oDiv = document.getElementById("availCalendar_" + g_sId);
        
        oDiv.innerHTML = res.value;
        
        // AvailabilityCalendar.js
        initializeAvailabilityCalendarObjects(ProductID + "_" + MerchandisingGroupID + "_");
    }
}

function getChangeDatesCalendar_callback(res) {
    if (res.error) {
        // Availability result threw error, display the error in a friendly way...
        alert('AJAX error\n\n' + res.error.Type + '\n\n' + res.error.Message);
    }
    else {
        var VendorID = res.request.args.vendorId;
        var MerchandisingGroupID = res.request.args.merchandisingGroupId;
        var StartDate = res.request.args.startDate;

        //var oDiv = document.getElementById("changeDatesCalendar");
        var oDiv = document.getElementById(g_changeDatesCalendarId);

        oDiv.innerHTML = res.value;

        // AvailabilityCalendar.js
        initializeChangeDatesCalendarObjects(VendorID + "_" + MerchandisingGroupID + "_");
        
    }
}

// ----------------------------------------------------------------------------
// Function:    drawCalendar
// Purpose:     Generates a calendar
// Inputs:      oCalendarDiv - Div into which the calendar should be placed
//              startDate - Any date in the month that should be drawn
//              iSelectBeginDate - Not used?
//              iSelectEndDate - Not used?
//              iRestrictBeforeDate - TBD
//              arrAvailability - Availability info
// Returns:     None
// ----------------------------------------------------------------------------
function drawCalendar(oCalendarDiv, startDate, iSelectBeginDate, iSelectEndDate, iRestrictBeforeDate, arrAvailability)
{
    var thisDay = new Date(startDate.getFullYear(), startDate.getMonth(), 1);
    var today = new Date(2006, 5, 13);

    var oTRow;
    var oTCell;
    var oButton;

    // TABLE
    var oTable = document.createElement('table');
    oTable.setAttribute('class','dpTable');
    oCalendarDiv.appendChild(oTable);

    // TBODY
    var oTBody = document.createElement('tbody');
    oTable.appendChild(oTBody);

    // TITLE ROW
    oTRow = document.createElement('tr');
    oTRow.className = 'dpTitleTR';
    oTBody.appendChild(oTRow);

    oTCell = document.createElement('td');
    oTCell.setAttribute('colspan','7');
    oTCell.colSpan = 7;
    oTCell.className = 'dpTitleTD';
    oTCell.innerHTML = '<div class="dpTitleText">' + monthArrayLong[thisDay.getMonth()] + ' ' + thisDay.getFullYear() + '</div>'
    oTRow.appendChild(oTCell);
    
    // WEEKDAY HEADINGS
    oTRow = document.createElement('tr');
    oTRow.className = 'dpDayTR';
    oTBody.appendChild(oTRow);
    
    for (var i = 0; i < dayArrayShort.length; i++)
    {
        oTCell = document.createElement('td'); // should be TH
        oTCell.className = 'dpDayTD';
        oTCell.innerHTML = dayArrayShort[i];
        oTRow.appendChild(oTCell);
    }

    // CALENDAR
    oTRow = document.createElement('tr');
    oTRow.className = 'dpTR';
    oTBody.appendChild(oTRow);
    
    for (var i = 0; i < thisDay.getDay(); i++)
    {
        oTCell = document.createElement('td');
        oTCell.className = 'dpTDDisabled';
        oTCell.innerHTML = '&nbsp;';
        oTRow.appendChild(oTCell);
    }
    
    var todayNum = today.getDate();
    
    do
    {
        var dayNum = thisDay.getDate();
        
        var arrAvail = null;
        
        try
        {
            arrAvail = arrAvailability[thisDay.getFullYear()][thisDay.getMonth()+1][thisDay.getDate()];
        }
        catch (e)
        {
            arrAvail = null;
        }

        var isDisabled = (dayNum < iRestrictBeforeDate);
        var isAvailable = false;
        var hasRestrictions = false;        
        if(arrAvail)
        {
            isAvailable = arrAvail[0];
            hasRestrictions = (arrAvail[1] > 1);
        }
        
        // Availability Calendar Cell Classes
        var acClass = 'acDay';
        
        if (isDisabled)
        {
            acClass = 'acDisabled';
        }
        else if (isAvailable && hasRestrictions)
        {
            acClass = 'acAvailableWithRestrict';
        }
        else if (isAvailable)
        {
            acClass = 'acAvailable';
        }
        else
        {
            acClass = 'acNotAvailable';
        }

        // Create the cell for the date
        oTCell = document.createElement('td');
        oTCell.className = acClass;
        oTCell.innerHTML = dayNum;
        oTRow.appendChild(oTCell);
        
        //Increment the day
        thisDay.setDate(thisDay.getDate() + 1);

        // Add a new row if it is the end of this week
        if (thisDay.getDate() > 1 && thisDay.getDay() == 0)
        {
            oTRow = document.createElement('tr');
            oTRow.setAttribute('class','dpTR');
            oTBody.appendChild(oTRow);
        }
    }
    while (thisDay.getDate() > 1)
    
    if (thisDay.getDay() != 0)
    {
        for (var i = thisDay.getDay(); i <= 6; i++)
        {
            oTCell = document.createElement('td');
            oTCell.className = 'dpTDDisabled';
            oTCell.innerHTML = '&nbsp;';
            oTRow.appendChild(oTCell);
        }
    }
}


// ----------------------------------------------------------------------------
// Function:    convertListPricedChoicesToArray
// Purpose:     Converts a list of PricedChoice objects into an array that is
//              easy to access by index while building the calendar
// Inputs:      ListPricedChoice - List of Priced Choice objects
// Returns:     3-dimensnsional Array[year][month][date]
// ----------------------------------------------------------------------------
function convertListPricedChoicesToArray(ListPricedChoice)
{
    var arrYears = new Array();
    
    // Turn the list of priced choices into an array accessible by index
    for (var index = 0; index < ListPricedChoice.length; index++)
    {
        var pc = ListPricedChoice[index];
        
        if (!arrYears[pc.Year])
        {
            arrYears[pc.Year] = new Array();
        }
        
        if (!arrYears[pc.Year][pc.Month])
        {
            arrYears[pc.Year][pc.Month] = new Array();
        }
        
        arrYears[pc.Year][pc.Month][pc.Day] = new Array();
        arrYears[pc.Year][pc.Month][pc.Day][0] = pc.IsAvailable;
        arrYears[pc.Year][pc.Month][pc.Day][1] = pc.MinRequiredUnitsOfInventory;
    }
    
    return arrYears;
}

function setTimeBasedValue(timeBasedDropDown, pcid_addtoplanID)
{
    var pcid_addtoplan = document.getElementById(pcid_addtoplanID);

    pcid_addtoplan.value = timeBasedDropDown.options[timeBasedDropDown.selectedIndex].value;
}

function showMoreProducts(gridTableID, moreProductsLink)
{
    var gridTable = document.getElementById(gridTableID);
    
    var hiddenGridRows = getElementsByClass("pHiddenGridRowEven", gridTable, "div");
    
    for (i=0; i<hiddenGridRows.length; i++)
    {
        hiddenGridRows[i].className = "pGridRowEven";
    }

    hiddenGridRows = getElementsByClass("pHiddenGridRowOdd", gridTable, "div");
    
    for (i=0; i<hiddenGridRows.length; i++)
    {
        hiddenGridRows[i].className = "pGridRowOdd";
    }
    
    moreProductsLink.style.display = "none";
}

/***********************************************************************/
function invokeAddToPlan(pcid_addtoplanID, loadingPageID, loadingDivID)
{
    
    addPricedChoiceToPlan(document.getElementById(pcid_addtoplanID).value, loadingPageID, loadingDivID);
}

function addPricedChoiceToPlan(pcid, loadingPageID, loadingDivID)
{
    // Hide select boxes as they will 'peek' through the image in IE
    selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
            selects[i].style.visibility = "hidden";
    }
    
    //setTimeout("addToPlanButtonClick('" + pcid + "', '" + loadingPageID +"','" + loadingDivID + "')", 100); // click the button
    addToPlanButtonClick( pcid, loadingPageID, loadingDivID );
} 

function addToPlanButtonClick(pcid, loadingPageID, loadingDivID){
    //setTimeout("setupLoadingPage('" + loadingPageID +"','" + loadingDivID + "');",10);
    setupLoadingPage(loadingPageID, loadingDivID);
    //alert('hello');
    page.addToPlan.AddToPlan(pcid);
}