﻿function addBoxes(container, items, showTimer) {
    var counter = 1;
    var maxHeight = 0;

    $.each(items, function (index, item) {
        var newItem = null;

        if (item.type == 0)
            //Category Type
            newItem = createCategoryBox(item, showTimer);

        if (item.type == 1)
            //Item type
            newItem = createItemBox(item, showTimer);

        $(container).append(newItem);

        var currentHeight = $(newItem).height();
        if (currentHeight > maxHeight) {
            maxHeight = currentHeight;
        }

        $(newItem).removeAttr("style").hide().fadeIn("slow");
    });

    $("div.box").height(maxHeight);
}

function clearBoxes(container) {
    $(container).empty();
}

function createCategoryBox(item, showTimer) {
    var box = $("<div>").attr("class", "box category-box");
    var boxImage = $("<div>")
        .attr("class", "box-image")
        .attr("style", "background-image:url(" + $Url.resolve(item.url) + ");");
    var pCategory = $("<p>")
        .attr("class", "category-name")
        .append(item.description);
    var closeSoonImage = $('<span class="flag closing-soon">Closing Soon</span>');
    var closedImage = $(
        '<span class="flag bidding-closed">Bidding Closed</span>'
    );
    var previewImage = $('<span class="flag bidding-preview">Preview</span>');

    var pEnds = "";
    if (showTimer && item.StateFriendlyMessage != "" && item.AuctionState == 3 && !item.AlwaysOpen) {
        // Only show the category message when on Silent Auction
        pEnds = $("<p>")
            .attr("class", "category-state")
            .append(item.StateFriendlyMessage);
    }

    $(box).append(boxImage);
    $(box).append(pCategory);
    $(box).append(pEnds);

    $(box).attr("categoryId", item.id);
    $(box).attr("type", "category");

    // EC-1984: Add closed & closing banners on home page
    if (item.EndsInThirtyMinutes && !item.IsEnded) $(box).append(closeSoonImage);

    // Category start-end dates only apply for silent auction
    if (item.IsEnded && item.AuctionState != 5) {
        $(box).append(closedImage);
        $(box).addClass("box-disabled");
    }

    // Not Started - Do not show if pre online auction is open
    if (!item.IsStarted && item.AuctionState != 1) {
        $(box).append(previewImage);
    }

    return $(box);
}

function createItemBox(item, showTimer) {
    var box = $("<div>").attr("class", "box item-box");
    var boxWatch = $(
        '<a href="#" class="box-watch cancelRedirection" data-toggle="tooltip" data-placement="top" title="Add to watch list"><i class="icon-love-it cancelRedirection"></i><span class="sr-only cancelRedirection">Watch this item</span></a>'
    );

    if (item.AddedToWatchList) {
        boxWatch.addClass('watching');
        boxWatch.attr('title', 'Remove from watchlist');
    }

    if (isTouchDevice()) {
        boxWatch.removeAttr('title');
    }

    var boxImage = $("<div>")
        .attr("class", "box-image")
        .attr("style", "background-image:url(" + $Url.resolve(item.url) + ");");
    var boxContent = $("<div>").attr("class", "box-content");
    var boxContentFooter = $("<div>").attr("class", "box-content-footer");
    var pItem = $("<p>").attr("class", "item").append(item.description);
    var spanItemNumber = $("<span>").attr("class", "item-number").append(item.id);
    var soldOutImage = "";

    // Watch list initialization
    if (!isTouchDevice()) {
        boxWatch.tooltip();
    }
    boxWatch.click(function (e) {
        e.preventDefault();
        var id = $(this).parent().attr('itemId');
        var parent = $(this);

        if (isTouchDevice()) {
            boxWatch.removeAttr('title');
        }

        toggleItemFromWatchlist(id, function (success, onWatchlist) {
            if (success) {
                $(parent).toggleClass("watching")
                var title = '';
                var origTitle = '';
                if (onWatchlist) {
                    title = "Added to watch list";
                    origTitle = "Remove from watchlist";
                }
                else {
                    title = "Removed from watch list";
                    origTitle = "Add to watch list";
                }

                $(parent).attr('title', title).attr('data-original-title', title).tooltip('update').tooltip('show');
                setTimeout(function () {
                    $(parent).attr('title', origTitle).attr('data-original-title', origTitle).tooltip('update').tooltip('hide');
                }, 2000);
            }
            else {
                toastr.error('We could not add this package to the watchlist, please try again leter');
            }
        });
    });

    if (item.IsMultiItem == true && item.QtyAvailable <= 0) {
        soldOutImage = $('<span class="flag sold-out">Sold Out</span>');
    }
    if (item.IsBuyNow == true && item.IsSold == true) {
        soldOutImage = $('<span class="flag sold-out">Sold</span>');
    }

    var closeSoonImage = $('<span class="flag closing-soon">Closing Soon</span>');
    var closedImage = $(
        '<span class="flag bidding-closed">Bidding Closed</span>'
    );
    var previewImage = $('<span class="flag bidding-preview">Preview</span>');

    // Check for current bid
    var pBid;
    var pQty = "";
    if (item.IsMultiItem) {
        
        if (item.DonationPackagesEnabled && item.IsDonationItem) {
            var title = "Raised:";
            var amount = addThousandSeparator(item.totalRaised);
        }
        else {
            var title = 'Price:';
            var amount = addThousandSeparator(item.bid);
        }


        if (!item.IsUnlimited) {
            if (item.QtyAvailable > 0) {
                pQty = ""; //  $('<p>').attr('class', 'item-qty').append('<span>Qty:</span> ' + item.QtyAvailable);
                pBid = $("<p>")
                    .attr("class", "item-bid")
                    .append("<span>" + title + "</span> $" + amount);
            } else {
                pBid = $("<p>")
                    .attr("class", "item-bid")
                    .append("<span>" + title + "</span> $" + amount);
            }
        } else {
            pQty = ""; //  $('<p>').attr('class', 'item-qty').append('<span>Qty:</span> &infin;');
            pBid = $("<p>")
                .attr("class", "item-bid")
                .append("<span>" + title + "</span> $" + amount);
        }
    } else {
        if (item.hasCurrentBid) {
            pBid = $("<p>")
                .attr("class", "item-bid")
                .append("<span>Currently</span> $" + addThousandSeparator(item.bid));
        } else {
            pBid = $("<p>")
                .attr("class", "item-bid")
                .append("<span>Minimum:</span> $" + addThousandSeparator(item.bid));
        }
    }

    // Not ended
    if (item.AuctionState != 6) {
        $(box).append(boxWatch);
    }
    $(box).append(boxImage);
    $(box).append(boxContent);
    $(boxContent).append(pItem);
    $(boxContent).append(boxContentFooter);
    $(boxContentFooter).append(spanItemNumber);
    if (pQty != "") $(boxContentFooter).append(pQty);
    $(boxContentFooter).append(pBid);

    var soldOut = false;
    if (item.IsMultiItem == true && item.QtyAvailable <= 0) {
        soldOut = true;
        $(box).append(soldOutImage);
        $(box).addClass("box-disabled");
    }
    if (item.IsBuyNow == true && item.IsSold == true) {
        soldOut = true;
        $(box).append(soldOutImage);
        $(box).addClass("box-disabled");
    }

    $(box).attr("itemId", item.id);
    $(box).attr("isLive", item.IsLive);
    $(box).attr("categoryId", item.categoryId);
    $(box).attr("type", "package");

    // Closing soon
    if (
        item.EndsInThirtyMinutes &&
        !(item.IsBuyNow == true && item.IsSold == true) &&
        !(item.IsMultiItem == true && item.QtyAvailable <= 0) &&
        item.IsStarted &&
        !item.IsEnded
    )
        if (item.IsMultiItem && item.OverrideMU) {
        } else {
            $(box).append(closeSoonImage);
        }

    // Closed
    if (!(item.CanBeSold == true) || (
        !(item.IsBuyNow == true && item.IsSold == true) &&
        !(item.IsMultiItem == true && item.QtyAvailable <= 0) &&
        item.IsStarted &&
        item.IsEnded 
    )) {
        if (item.IsMultiItem && item.OverrideMU) {
            // Nothing
        }
        else if (soldOut == true) {
            // Nothing
        }
        else {
            $(box).append(closedImage);
            $(box).addClass("box-disabled");
        }
    }

    // Not Started
    if (
        !(item.IsBuyNow == true && item.IsSold == true) &&
        !(item.IsMultiItem == true && item.QtyAvailable <= 0) &&
        !item.IsStarted
    ) {
        if (
            item.IsMultiItem &&
            item.OverrideMU &&
            !auctionIsOpen(item.AuctionState)
        ) {
        } else if (item.CanBeSold == true) {
            $(box).append(previewImage);
        }
    }

    return $(box);
}

function addThousandSeparator(val) {
    if (val == null) val = 0;
    return val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

function auctionIsOpen(state) {
    return state == 1 || state == 3 || state == 5;
}

function isTouchDevice() {
    return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
