﻿/**
* jQuery plugin to add a product to an order
*
* Author: Tim Booker
* Date 15/01/2010
*/
(function($) {

    $.fn.changeOrderItemQuantity = function (options) {

        var settings = {

            // Method to call when process starts
            started: started,

            // Method to execute when process finishes successfully
            succeeded: succeeded,

            // Method to execute when process fails
            failed: failed,

            // Product GUID to add, if not provided then it will be located on a parent product container
            productGuid: false,

            // Quantity to add
            quantity: 1

        };
        // Override the default settings with the options object
        if (options)
            $.extend(settings, options);

        var _this = null;

        function started() {
            $(_this).progressIndicator({ mode: 'indeterminate', func: 'start' });

            $(window).trigger('changeOrderItemQuantityStarted');
        }

        function succeeded() {
            $(_this).progressIndicator({ mode: 'indeterminate', func: 'stop' });

            $(window).trigger('changeOrderItemQuantitySucceeded');
        }

        function failed() {
            $(_this).progressIndicator({ mode: 'indeterminate', func: 'stop' });

            $(window).trigger('changeOrderItemQuantityFailed');

            error('Add to basket failed');
        }

        function error(message) {
            // TODO: Implement real user notifications
            alert(message);
        }

        this.each(function() {

            _this = this;

            settings.started();

            // Try to read the product ID from a parent product container
            if (!$.isGuid(settings.productGuid)) {
                var productContainer = $.locateContainer(this, 'Aspidistra.Ecommerce.Sales.OrderItem');
                if (productContainer !== false)
                    settings.productGuid = productContainer.data('ItemId');
            }

            if (!$.isGuid(settings.productGuid)) {
                settings.failed();
                return;
            }

            // Make the AJAX call
            Aspidistra.Ecommerce.Web.ScriptServices.SalesScriptService.ChangeOrderItemQuantity(
                settings.productGuid,
                settings.quantity,
                settings.succeeded,
                settings.failed
            );
        });

        return this;
    }


})(jQuery);

