﻿var addingToCartFlag = false;

function checkPartAvailability(UniqueID, PartNumber, BrandID, Quantity)
{
    var userContext = new Object();
    userContext.UniqueID = UniqueID;
    userContext.Quantity = Quantity;
    
    CheckPartAvailabilityService.UpdateWPItemAvailability(PartNumber, BrandID, Quantity,
	                                                      checkPartAvailabilityCallback, 
	                                                      checkPartAvailabilityError,
	                                                      userContext);
}

function checkPartAvailabilityCallback(result, userContext)
{
    var uniqueID = userContext.UniqueID;
    var quantity = userContext.Quantity;
    var dateFormatString = "M/d/yyyy h:mm:ss tt";
    
    if (result != null)
    {
        // set hidden inputs
        var shipsAtInput = document.getElementById('shipsAt' + uniqueID);
        var submitByInput = document.getElementById('submitBy' + uniqueID);
        var quantityAvailableInput = document.getElementById('quantityAvailable' + uniqueID);
        var daysUntilShipInput = document.getElementById('daysUntilShip' + uniqueID);
        var warehouseIDInput = document.getElementById('warehouseID' + uniqueID);
        var sellingIncrement = document.getElementById('sellingIncrement' + uniqueID);
        var sellingIncrementDD = document.getElementById('sellingIncrementDD' + uniqueID);

        if (sellingIncrementDD != undefined && sellingIncrement != undefined && sellingIncrement != undefined && shipsAtInput != undefined && submitByInput != undefined && quantityAvailableInput != undefined && daysUntilShipInput != undefined && warehouseIDInput != undefined)
        {
            shipsAtInput.value = result.ShipsAt.format(dateFormatString);
            submitByInput.value = result.SubmitBy.format(dateFormatString);
            quantityAvailableInput.value = result.QuantityAvailable;
            daysUntilShipInput.value = result.DaysUntilShip;
            warehouseIDInput.value = result.WpWarehouseID;

            populateSellingIncrementDropDown(sellingIncrementDD, sellingIncrement.value, result.QuantityAvailable);
        }

        var checkingStock = document.getElementById('checkingStock' + uniqueID);
        var inStock = document.getElementById('inStock' + uniqueID);
        var addedToCart = document.getElementById('addedToCart' + uniqueID);
        var availability = document.getElementById('availability' + uniqueID);
        var outOfStock = document.getElementById('outOfStock' + uniqueID);

        if (checkingStock != undefined && outOfStock != undefined && inStock != undefined)
        {
            checkingStock.style.display = 'none';
            outOfStock.style.display = 'none';

            // Set up array to translate day of week to name for class names
            var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

            // Test to turn today into yesterday, so that "Ships Tomorrrow" appears
            // today = new Date(today.getTime() - 86400000);

            // Today's date
            var today = new Date();
            var todayDayOfWeek = today.getDay();

            // Tomorrow's date
            var tomorrow = new Date(today.getTime() + 86400000)
            var tomorrowDayOfWeek = tomorrow.getDay();

            var shipsAtDate = new Date(Date.parse(shipsAtInput.value));
            var shipsAtDayOfWeek = shipsAtDate.getDay();

            // If today's day == ship date, use "inStockShipsToday" as the class
            // else If tomorrow's day == ship date, use "inStockShipsTomorrow" as the class
            // else switch calculate the day of week and print it use it "inStockShipsWednesday"

            if (shipsAtDayOfWeek == todayDayOfWeek)
            {
                // use threshold to determine shipping estimate
                if (typeof (partsShippingThreshold) != 'undefined' && partsShippingThreshold != null && partsShippingThreshold != "")
                {
                    var threshold = new Date(Date.parse(partsShippingThreshold));

                    if (today.getTime() > threshold.getTime())
                    {
                        if (shipsAtDayOfWeek == 5)// is Friday?
                        {
                            if (result.NextBusinessDate != null)
                            {
                                var nextBusinessDate = new Date(Date.parse(result.NextBusinessDate.format(dateFormatString)));
                                inStock.className = "inStockShips" + daysOfWeek[nextBusinessDate.getDay()];
                            }
                            else
                            {
                                inStock.className = "inStockShipsTomorrow";
                            }
                        }
                        else
                        {
                            inStock.className = "inStockShipsTomorrow";
                        }
                    }
                    else
                    {
                        inStock.className = "inStockShipsToday";
                    }
                }
                else
                {
                    inStock.className = "inStockShipsToday";
                }
            }
            else if (shipsAtDayOfWeek == tomorrowDayOfWeek)
            {
                inStock.className = "inStockShipsTomorrow";
            }
            else
            {
                inStock.className = "inStockShips" + daysOfWeek[shipsAtDayOfWeek];
            }

            inStock.style.display = 'block';
        }
    }
    else
    {
        var outOfStockErr = document.getElementById('outOfStock' + uniqueID);
        var checkingStockErr = document.getElementById('checkingStock' + uniqueID);
        var availability = document.getElementById('availability' + uniqueID);

        if (checkingStockErr != undefined && outOfStockErr != undefined)
        {
            checkingStockErr.style.display = 'none';
            outOfStockErr.style.display = 'block';
        }
    }
}

function populateSellingIncrementDropDown(sellingIncrementDD, sellingIncrement, maxQuantity)
{
	if (sellingIncrementDD != undefined)
	{
		ClearDropDown(sellingIncrementDD);
		for (var i = sellingIncrement; i <= parseInt(maxQuantity); i = parseInt(i) + parseInt(sellingIncrement))
		{
			AddToDropDownList(sellingIncrementDD, i, i);
			
			// show max of 10 numbers in this list
			if (i >= sellingIncrement * 10)
			{
				break;
			}
		}
	}
}

function ClearDropDown(dropDownList)
{
	for (var x = dropDownList.length; x >= 0; x = x - 1)
	{
		dropDownList[x] = null;
	}
}

function AddToDropDownList(dropDownList, value, text)
{
	// Add option to the bottom of the list
	dropDownList[dropDownList.length] = new Option(text, value);
}

function addToCartWebService(uniqueID, variantID, fromPopup)
{
	if (!addingToCartFlag)
	{
		addingToCartFlag = true;
		var userContext = new Object();
		userContext.uniqueID = uniqueID;
		userContext.variantID = variantID;

		var shipsAtInput = document.getElementById('shipsAt' + uniqueID);
		var submitByInput = document.getElementById('submitBy' + uniqueID);
		var quantityAvailableInput = document.getElementById('quantityAvailable' + uniqueID);
		var daysUntilShipInput = document.getElementById('daysUntilShip' + uniqueID);
		var warehouseIDInput = document.getElementById('warehouseID' + uniqueID);
		var addingToCart = document.getElementById('addingToCart' + uniqueID);

		addingToCart.style.display = 'block';

		if (fromPopup == true)
		{
			var sellingIncrementDD = document.getElementById('popupSellingIncrementDD');
		}
		else
		{
			var sellingIncrementDD = document.getElementById('sellingIncrementDD' + uniqueID);
		}

		var shipsAt = shipsAtInput.value;
		var submitBy = submitByInput.value;

		var quantityAvailable = quantityAvailableInput.value;
		var daysUntilShip = daysUntilShipInput.value;
		var warehouseID = warehouseIDInput.value;
		var quantity = sellingIncrementDD.value;

		if (shipsAt == 'undefined' || submitBy == 'undefined' || quantityAvailable == 'undefined' || daysUntilShip == 'undefined' || warehouseID == 'undefined')
		{
			alert('We were unable to add this part to your cart.  Please refresh the browser and try again.');
			addToCartCallback(null, userContext);
		}
		else
		{
			CheckPartAvailabilityService.AddToCart(uniqueID, visitID, visitorID, variantID, quantity, shipsAt, submitBy, quantityAvailable, daysUntilShip, warehouseID, addToCartCallback, addToCartError, userContext);
		}
	}
}

function addToCartCallback(result, userContext)
{
	if (result != null)
	{
		var inStock = document.getElementById('inStock' + userContext.uniqueID);
		var addedToCart = document.getElementById('addedToCart' + userContext.uniqueID);

		inStock.style.display = 'none';
		addedToCart.style.display = 'block';
	}
	else
	{
		// hide progress and enable button functionality
		var addingToCart = document.getElementById('addingToCart' + userContext.uniqueID);
		addingToCart.style.display = 'none';
	}
	addingToCartFlag = false;
}

function addToCartError()
{
	alert("An error has occurred while trying to process your request. Please refresh the browser and try again.");
}

function checkPartAvailabilityError(error, userContext)
{
	// on error show out of stock
	if (typeof (userContext) != 'undefined' && userContext != null)
	{
		if (typeof (userContext.UniqueID) != 'undefined' && userContext.UniqueID != null && userContext.UniqueID != "")
		{
			var uniqueID = userContext.UniqueID;

			var outOfStockErr = document.getElementById('outOfStock' + uniqueID);
			var checkingStockErr = document.getElementById('checkingStock' + uniqueID);
			var availability = document.getElementById('availability' + uniqueID);

			if (checkingStockErr != undefined && outOfStockErr != undefined)
			{
				checkingStockErr.style.display = 'none';
				outOfStockErr.style.display = 'block';
			}
		}
	}
}

function generateLeftNav(navigationValues, mainNavSelectionText, websiteURL, imagePath)
{
	// LEFT_NAV_DESC_DELIMITER and LEFT_NAV_LINK_DELIMITER are defined in PartsNavigation.cs

	var navigationArray = navigationValues.split(LEFT_NAV_LINK_DELIMITER);

	var leftNavHTML = "<p class=\"imageHeading\"><img src=\"" + imagePath + "/website3/parts/left_nav/shop_auto_parts.gif\" alt=\"Shop Auto Parts\" /></p><ul>";

	for(var i = 0; i < navigationArray.length; i++)
	{
		var urlName = navigationArray[i].split(LEFT_NAV_DESC_DELIMITER);
		if(typeof(urlName) != undefined)
		{
			if(urlName[0] == mainNavSelectionText)
			{
				leftNavHTML = leftNavHTML + "<li><strong><a href=\"" + websiteURL + urlName[1] + "\">" + urlName[0] + "</a></strong></li>";
			}
			else
			{
				leftNavHTML = leftNavHTML + "<li><a href=\"" + websiteURL + urlName[1] + "\">" + urlName[0] + "</a></li>";
			}
		}
	}

	leftNavHTML = leftNavHTML + "</ul><img alt=\"bottom\" src=\"" + imagePath + "/website3/left_nav/background_grey_bottom.gif\" style=\"margin: 0; padding: 0; background: #fff; width: 160px; display: block;\"/>";

	var partsNavigationDiv = document.getElementById("autoPartsNavigation");

	partsNavigationDiv.innerHTML = leftNavHTML;
}
