﻿$(document).ready(function()
{
    $('#mycarousel').jcarousel(
    {
        //scroll: 4,
        itemLoadCallback: mycarousel_itemLoadCallback//,
        //buttonNextHTML: '<div>&gt;&gt;</div>',
        //buttonPrevHTML: '<div>&lt;&lt;</div>'//,
        //wrap: 'circular',
        //itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
        //itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback}        
    });
});

function mycarousel_itemLoadCallback(carousel, state)
{
    // Since we get all URLs in one file, we simply add all items
    // at once and set the size accordingly.
    if (state != 'init')
        return;
        
    $.ajax({
        type: "GET",
        url: "/DynamicContent/TopSellers.aspx",
        dataType: "xml",
        processData: false,
        contentType: "text/xml",
        success: function(data, textStatus)
        {
            mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
        }
    });
};

function mycarousel_itemAddCallback(carousel, first, last, data)
{
    var index = 0;

    $(data).find('TopSeller').each(function()
    {            
        var imageUrl = $(this).find('ImageUrl').text();
        var name = $(this).find('Name').text();
        var price = $(this).find('Price').text();
        var navigateUrl = $(this).find('NavigateUrl').text();

        carousel.add(index + 1, mycarousel_getItemHTML(imageUrl, name, price, navigateUrl));
        
        index++;
    });

    carousel.size(index);
};

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(imageUrl, name, price, navigateUrl)
{
    var html = "";
    
    html += '<a href="' + navigateUrl + '"><img src="' + imageUrl + '" alt="" /></a>';
    html += '<br />';
    html += '<span><a href="' + navigateUrl + '">' + name + '</a></span>';
    html += '<br />';
    html += '<span><b>' + price + '</b></span>';
    
    return html;
};

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt)
{
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt)
{
    carousel.remove(i);
};
