/**
 * Q-CMS
 * @author Sokolov Innokenty, <sokolov.innokenty@gmail.com>
 */

$.ajaxSetup({
    type: 'POST',
    dataType: 'json',
    error: function(xhr, ajaxOptions, thrownError) {
        var result = $.parseJSON(xhr.responseText);
        var text = "ОБНАРУЖЕНА ОШИБКА! \n";
        if (result.file) text += "в файле " + result.file + "\n";
        if (result.line) text += "строка №" + result.line + "\n";
        text += "\n";
        text += "текст ошибки: \n\n" + result.error;
        alert(text);
        //if (console.log) console.log(xhr);
    }
});

if (!Q) var Q = {};

(function() {
    'use strict';

    /**
     * @namespace Q
     */
    Q.cms = {

        miniCart: {
            allItems: null, // items*count
            items: null,    // count
            price: null
        },

        /**
         * @param {integer} id
         * @param {integer} count
         */
        addItemToCart: function(id, count) {
            var _ = this;
            $.ajax({
                url: '/shop/cart/addItem/',
                data: {
                    id: id, count: count
                },
                success: function(data) {
                    if (data.success) {
                        _.updateMiniCartFromData(data.result);
                        alert('Добавлено.');
                    }
                }
            });
        },

        updateMiniCart: function() {
            var _ = this;
            $.ajax({
                url: '/shop/cart/getMiniCart/',
                success: function(data) {
                    if (data.success) {
                        _.updateMiniCartFromData(data.result);
                    }
                }
            });
        },

        /**
         * @param {object} data
         */
        updateMiniCartFromData: function(data) {
            if (this.miniCart.allItems) {
                $('#' + this.miniCart.allItems).html(data[0]);
            }

            if (this.miniCart.items) {
                $('#' + this.miniCart.items).html(data[1]);
            }

            if (this.miniCart.price) {
                $('#' + this.miniCart.price).html(data[2]);
            }
        },

        /**
         * @param {object} self
         * @param {integer} id
         * @param {integer} i
         */
        filter: function(self, id, i) {
            $.cookie('filter[' + id + '][' + i + ']', self.value, {
                path: '/'
            });
            window.location.reload(true);
        },

        /**
         * @param {string} column
         * @param {string} sortBy
         */
        sort: function(column, sortBy) {
            $.cookie('sort[price]', sortBy, {expires: 0});
            window.location.reload(true);
        },

        /**
         * Cart
         *
         * @namespace Q.cms
         */
        cart: {

            refresh: function() {
                $('#cart').submit();
            },

            /**
             * @param {integer} id
             */
            deleteItem: function(id) {
                window.location.href = '/shop/cart/deleteItem/' + id + '/';
            },

            clear: function() {
                window.location.href = '/shop/cart/clear/';
            },

            checkout: function() {
                window.location.href = '/shop/cart/checkout/';
            },

            /**
             * Clone order
             *
             * @param {integer} orderId
             */
            clone: function(orderId) {
                $.ajax({
                    url: '/profile/orders_history/clone/',
                    data: {
                        orderId: orderId
                    },
                    success: function(data) {
                        if (data.success) {
                            Q.cms.updateMiniCart();
                            alert('Заказ №' + orderId + ' успешно добавлен в корзину.')
                        }
                    }
                });
            }

        }

    };


    /**
     * @namespace Q.cms
     */
    Q.cms.auth = {

        show: function() {
            $('#login-form').show();
        },

        hide: function() {
            $('#login-form').hide();
        },

        toggle: function(){
            $('#login-form').toggle();
        },

        /**
         * @param {object} options
         */
        login: function(options) {
            console.log(options);
            var emailVal = options.login.val();
            var psswdVal = options.password.val();
            var _ = this;

            if (emailVal == '') {
                _.error(options.errorArea, 'Введите email');
                return;
            } else if (psswdVal == '') {
                _.error(options.errorArea, 'Введите пароль');
                return;
            }

            $.ajax({
                url: '/login/',
                data: {
                    email: emailVal,
                    psswd: psswdVal
                },
                success: function(data) {
                    if (data.success) {
                        $.isFunction(options.success) && options.success();
                    } else {
                        _.error(options.errorArea, 'Email или пароль введены не верно');
                    }
                }
            });

            options.errorArea.hide();
        },

        /**
         * @param {object} error
         * @param {string} msg
         */
        error: function(error, msg) {
            error.html(msg).show();
        }

    };

})();

