﻿function registerProductComponents() {
    $('.cart-container').cart('rebind');
    $('input.auto-submit-star').rating({
        callback: function (value, link) {
            $.getJSON(this.id, function (data) {
            });
        }
    });
    $('select.product-price-list').priceSelector();
}

(function ($) {
    /* timer instance HACK!!!! to lazy to do this properly, so here it is biatch!!! */
    var timer = null;

    $.fn.notify = function (options) {
        var defaults = { action: 'show', message: '', sticky: true, autoHide: true };
        var options = $.extend(defaults, options);
        return this.each(function () {
            if (options.action == 'hide') {
                $(this).hide();
            } else if (options.action == 'show') {
                $(this).html(options.message);
                $(this).show('highlight');
                if (options.sticky) {
                    $(this).css({ 'position': 'fixed', 'top': '0px', 'left': '0px' });
                }
                var container = $(this);
                if (timer)
                    clearTimeout(timer);
                if (options.autoHide) {
                    timer = setTimeout(function () { $(container).fadeOut(); }, 5000);
                }
            }
        });
    };

    $.fn.priceSelector = function (options) {
        return this.each(function () {
            $(this).change(function () {
                var obj = $.parseJSON($(this).val());
                var container = $(this).parent();
                container.find('.product-price-deliver').html('+ ' + obj.Diff + ' delivered');
                container.find('.product-price-collect').html(obj.Collect);
                container.find('.product-price-designation').val(obj.Designation);
                container.find('.product-price-id').val(obj.PriceId);
                container.show('highlight');
            });
        });
    };
})(jQuery);

/* ----------------------- SHOPPING CART -------------------------*/
(function ($) {
    $.widget("platform.cart", {
        options: {
            url_add: '',
            url_refresh: '',
            url_remove: '',
            url_clear: '',
            url_update: '',
            url_changeDeliveryOption: '',
            id_container: '',
            text_loading: '<div>Refreshing...</div>',
            changed: function() { }
        },
        _create: function () {
            this._bind(this);
            this._bindLocal(this);
        },
        _bindLocal: function(cart){
            var container = $(this.options.id_container);
            container.find('a.cart-clear').click(function () {
                cart.clear();
            });
            container.find('a.cart-update').click(function () {
                cart._update(cart._serialize());
            });
            container.find('a.cart-cancel').click(function () {
                cart._refresh();
            });
            container.find('a.cart-remove').click(function () {
                var container = $(this).parent().parent().parent();
                var params = {
                    itemId: container.find('input.itemid').val(),
                    priceId: container.find('input.priceid').val(),
                    designation: container.find('input.designation').val()
                };
                cart.remove(params);
            });
            container.find('.cart-delivery-option').change(function() {
                cart.changeDeliveryOption($(this).val());
            });
            container.find('.cart-changed').hide();
            container.find('input.qty').keyup(function() { 
                $('#global_notification').notify({ message: 'Please click the update button to save changes to your shopping cart.', autoHide: false });
                $('.cart-changed').show('highlight');
            });
        },
        _bind: function (cart) {
            $('a.cart-add').click(function () {
                var params = {
                    itemId: $(this).parent().children('input.itemid').val(),
                    priceId: $(this).parent().children('input.priceid').val(),
                    designation: $(this).parent().children('input.designation').val(),
                    company: $(this).parent().children('input.company').val()
                };
                cart.add(params);
            });
        },
        _busy: function (message) {
            $(this.options.id_container).html(this.options.text_loading);
        },
        _notify: function (message) {
            $('#global_notification').notify({ message: message });
        },
        _error: function (data) {
            $('#global_notification').notify({ message: 'Error: ' + data.Error, autoHide: false });
        },
        _refresh: function () {
            var cart = this;
            $.get(this.options.url_refresh, function (data) {
                $(cart.options.id_container).html(data);
                cart._bindLocal(cart);
            });
        },
        _serialize: function() {
            var items = new Array();
            $('.cart-lineitem').each(function() {
                var item = {
                    ItemId: $(this).find('input.itemid').val(),
                    PriceId: $(this).find('input.priceid').val(),
                    Designation: $(this).find('input.designation').val(),
                    Qty: $(this).find('input.qty').val()
                };
                items.push(item);
            });
            return $.toJSON(items);
        },
        _update: function(json) {
            this._busy();
            this._notify('Updating shopping cart, please wait...');
            var cart = this;
            $.ajax({
                    url: this.options.url_update,
                    type: "POST",
                    dataType: 'json',
                    data: json,
                    contentType: "application/json; charset=utf-8",
                    success: function(data) {
                        if (data.Ok != true) {
                            cart._error(data);
                        } else {
                            cart._notify('Shopping cart updated.');
                        }
                        cart._refresh();
                }
            });
        },
        add: function (params) {
            this._busy();
            this._notify('Adding item to your order, please wait...');
            var cart = this;
            $.getJSON(this.options.url_add, params,
                            function (data) {
                                if (data.Ok != true) {
                                    cart._error(data);
                                } else {
                                    cart._notify('Item has been added.');
                                }
                                cart._refresh();
                            });
        },
        remove: function(params) {
            this._busy();
            this._notify('Removing item from your order please wait.');
            var cart = this;
            $.getJSON(this.options.url_remove, params,
                            function (data) {
                                if (data.Ok != true) {
                                    cart._error(data);
                                } else {
                                    cart._notify('Item has been removed.');
                                }
                                cart._refresh();
                            });
        },
        changeDeliveryOption: function(option) {
            this._busy();
            this._notify('Updating shopping cart, please wait...');
            var cart = this;
            $.getJSON(this.options.url_changeDeliveryOption, {option: option}, function(data) {
                        if (data.Ok != true) {
                            cart._error(data);
                        } else {
                            cart._notify('Shopping cart updated.');
                            cart.options.changed();
                        }
                        cart._refresh();
                });
        },
        clear: function () {
            this._busy();
            this._notify('Clearing your shopping cart, please wait...');
            var cart = this;
            $.getJSON(this.options.url_clear,
                            function (data) {
                                if (data.Ok != true) {
                                    cart._error(data);
                                } else {
                                    cart._notify('Shopping cart has been cleared.');
                                }
                                cart._refresh();
                            });
        },
        rebind: function() {
            this._bind(this);
        }
    });
})(jQuery);
