﻿function initGrid() {
    refreshGrid();
}

// get most viewed auctions
function refreshGrid() {
    $("#mostViewedAuctions").addClass("loading");
    
    $.ajax(
    {
        type: "GET",
        dataType: "json",
        async: true,
        url: bidNowServiceUrl + "/AuctionService.svc/items/mostViewed/10/json",
        complete: function(object, status) {
            $("#mostViewedAuctions").removeClass("loading");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.responseText);
        },
        success: function(json, status) {
            bindAuctionItemsData(json);
        }
    });
}

function bindAuctionItemsData(data) {
    var container = $("#mostViewedAuctionsContainer").empty();
    
    if (data) {
        var template = $("#auctionItem_template").html();

        for (var i = 0; i < data.length; i++) {
            var html = template.replace("@title@", truncateField(data[i]["Title"].toUpperCase(), 15))
                               .replace("@startPrice@", data[i]["StartPrice"])
                               .replace("@thumbnailUrl@", bidNowServiceUrl + "/" + data[i]["ThumbnailUrl"])
                               .replace("@bidNowWebsiteUrl@", bidNowWebsiteUrl)
                               .replace("@Id@", data[i]["Id"])
            
            var item = $(html);
            container.append(item);

            addAnimation();
        }
    }
}

// Helpers
function truncateField(fieldName, maxLength)
{
    if (fieldName.length > maxLength)
    {
        return fieldName.substring(0, maxLength) + "...";
    }

    return fieldName;
}

function addAnimation() {
    $(".boxgrid.caption").hover(function() {
        $(".cover", this).stop().animate({ top: "75px" }, { queue: false, duration: 160 });
    }, function() {
        $(".cover", this).stop().animate({ top: "110px" }, { queue: false, duration: 160 });
    });
    $(".boxgrid.caption").hover();
}