$(function() {
    // Prevent links from bubbling, but we still want to follow any links
    // Add some "ajax" style handling to the document add links
    $('button.add').click(
        function(event) {
            event.stopPropagation();
            return DynamicAddDocument($(this));
        }
    );

    // Load list of documents in cart and update page to match
    if (window.location.href.indexOf('/Cart.aspx') == -1) {
        CallCartAllDocumentFiles();
    }
});

function DynamicAddDocument(obj) {
    var vintageId = obj.siblings('.VintageId').val();
    var siteId = 0;
    var assetId = obj.siblings('.AssetId').val();
    var wineryId = obj.siblings('.WineryId').val();
    
    if (vintageId == undefined)
        vintageId = 0;

    if (wineryId == undefined)
        wineryId = 0;

    obj.addClass('thinking');
    CallCartAddRemoveAsset(assetId, wineryId, vintageId, obj);
    return false;
}


function CallCartAllDocumentFiles() {
    if (gWebServicePath == '') {
        alert('Web-service path is not set');
        return;
    }

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: gWebServicePath + "/CartAllDocumentFiles",
        data: '{}',
        dataType: "json",
        success: function(data, status) {
            $('button.add').removeClass('incart');
            $('button.add').addClass('thinking');
            $.each(data.d, function(i, assetId) {
                $('input.AssetId[value=\'' + assetId + '\']').siblings('button.add').addClass('incart');
            });
            $('button.add').removeClass('thinking');
            $('li#nav-cart > a > b').text(data.d.length);
        },
        error: function(obj, status, error) {
            alert("ERROR attempting to call 'CartAllDocumentFiles'");
        },
        complete: function(obj, status) {
            //htmlObj.removeClass('thinking');
        }
    });
}

function CallCartAddRemoveAsset(assetId, wineryId, vintageId, htmlObj)
{
    if (gWebServicePath == '')
    {
        alert('Web-service path is not set');
        return;
    }

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: gWebServicePath + "/CartAddRemoveAsset",
        data: '{"assetId":' + assetId + ',"wineryId":' + wineryId + ',"vintageId":' + vintageId + '}',
        dataType: "json",
        success: function(data, status) {
            $('li#nav-cart > a > b').text(data.d.CartCount);
            if (data.d.InCart == true)
                htmlObj.addClass('incart');
            else
                htmlObj.removeClass('incart');
        },
        error: function(obj, status, error) {
            alert("ERROR attempting to call 'CallCartAddRemoveAsset'");
        },
        complete: function(obj, status) {
            htmlObj.removeClass('thinking');
        }
    });
}
