// just for prestashop
var url_ajax_product = "/modules/tshirtecommerce/ajax.php?method=products";
var url_ajax_product_changed = "/modules/tshirtecommerce/ajax.php?method=changeproduct";
var url_ajax_options_ps = "/modules/tshirtecommerce/ajax.php?method=attributes";
var url_ajax_customization = '/modules/tshirtecommerce/ajax.php?method=customization';
var url_ajax_options_ps_new = "/modules/tshirtecommerce/ajax.combination.php";

var prestashop = {
    datas_tmp: {},
    selectColor: function(e) { /* @since 1.0.6 */
        jQuery('#color_to_pick_list > li').removeClass('selected');
        jQuery(e).parent().addClass('selected');
        jQuery('#ps_color_pick_hidden').val(jQuery(e).data('id'));
        design.ajax.getPrice();
    },
    // April 01, 2019 - fixed add prestashop customizaton on designer tool
    customizaton: {
        save: function() {
            var psform = jQuery("#ps-customizations")[0];
            var psdata = new FormData(psform);

            event.preventDefault();
            jQuery.ajax({
                type: "POST",
                cache: false,
                processData: false,
                contentType: false,
                dataType: 'json',
                url: mainURL+url_ajax_customization+'&task=save'+'&id='+window.parent.ps_product_id,
                data: psdata,
                success: function(res) {
                    event.stopPropagation();
                    if (res.error == '0') {
                        if (Object.keys(res.html.file).length > 0) {
                            for (var k in res.html.file) {
                                if (res.html.file.hasOwnProperty(k)){
                                    jQuery('.design-ps-customizations .ps-file-customization-'+k).html(res.html.file[k]);
                                }
                            }
                        }
                        if (Object.keys(res.html.text).length > 0) {
                            for (var k in res.html.text) {
                                if (res.html.text.hasOwnProperty(k)){
                                    jQuery('.design-ps-customizations .ps-text-customization-'+k).html(res.html.text[k]);
                                }
                            }
                        }

                        alert(res.message);
                    } else {
                        alert(res.message);
                    }
                }
            });
        },
        remove: function(e, idx) {
            jQuery.ajax({
                url: mainURL+url_ajax_customization+'&task=remove&index='+idx+'&id='+window.parent.ps_product_id,
                type: 'get',
                dataType: 'json',
                success: function(res) {
                    if (res.error == '0') {
                        alert(res.message);
                        jQuery(e).parent().remove();
                    } else if (res.message != '') {
                        alert(res.message);
                    }
                }
            });
        }
    },
    combination: function(e) {
        var params = [];

        if (typeof e != 'undefined') {
            jQuery('#tool_cart_ps .product-variants-item select').each(function() {
                params[jQuery(this).attr('data-product-attribute')] = jQuery(this).val();
            });

            jQuery('#tool_cart_ps .product-variants-item input[type="radio"]:checked').each(function() {
                params[jQuery(this).attr('data-product-attribute')] = jQuery(this).val();
            });
        }

        jQuery.ajax({
            type: 'POST',
            url: window.parent.baseDir+url_ajax_options_ps_new,
            data: {
                id_product: window.parent.ps_product_id,
                params: params,
            },
            cache: false,
            dataType: 'html',
            success: function(json) {
                jQuery('.ps-attributes-combinations').remove();

                jQuery('#tool_cart').after(json);
                window.parent.setHeigh(jQuery('#dg-wapper').height());
                design.ajax.getPrice();
            }
        });
    }
};

design.ajax.getPrice = function() {
    var datas = this.form();
    var options_ps = jQuery("#tool_cart_ps").serializeObject();
    var datas_ps = jQuery.extend(datas, options_ps);
    if (typeof window.parent.baseDir != 'undefined') {
        var url_ajax = window.parent.baseDir + "modules/tshirtecommerce/ajax.php";
    } else {
        var url_ajax = mainURL + "modules/tshirtecommerce/ajax.php";
    }
    jQuery.ajax({
        url: url_ajax,
        type: "POST",
        data: {
            method: "prices",
            id: window.parent.ps_product_id,
            lang: window.parent.ps_language_id,
            shop: window.parent.ps_shop_id,
            attributes: datas_ps,
            id_customer: window.parent.ps_id_customer,
            id_currency: window.parent.ps_id_currency,
            id_country: window.parent.ps_id_country,
            id_group: window.parent.ps_id_group,
            quantity: jQuery("#quantity").val(),
        },
        dataType: "json",
        success: function(json) {
            datas.ps_price_sale = json.price;
            datas.ps_price_old = json.price;
            datas.ps_taxes = json.taxes;
            datas.ps_round_mode = json.round_mode;
            // datas.ps_specific = json.specific; // @deprecated 1.3.0.b
            min_order = json.min_order;
            max_order = json.max_order;

            jQuery("#idCombination").val(json.ipa);
            //datas.ps_taxes = json.taxes;
            var lable = jQuery("#product-price .product-price-title");
            var div = jQuery("#product-price .product-price-list");
            var title = "";
            lable.html("Updating...");
            jQuery.ajax({
                type: "POST",
                processData: false,
                dataType: "json",
                url: siteURL + "ajax.php?type=prices",
                data: JSON.stringify(datas),
                contentType: "application/json; charset=utf-8"
            }).done(function(data) {
                if (data != "") {
                    if (typeof data.sale != "undefined") {
                        jQuery(document).triggerHandler("price.addtocart.design", data);
                        jQuery(".price-sale-number").html(data.sale);
                        jQuery(".price-old-number").html(data.old);
                        if (data.sale == data.old) {
                            jQuery("#product-price-old").css("display", "none");
                        } else {
                            jQuery("#product-price-old").css("display", "inline-block");
                        }
                    }
                }
            }).always(function() {
                lable.html(title);
                design.print.colors();
            });
        }
    });
};

jQuery(document).on('before.product.change.design', function(event, product) {
    jQuery('#app-wrap .product-design').html('');
    var ps_id = product.parent_id;

    jQuery.ajax({
        url: mainURL + url_ajax_product_changed,
        type: "POST",
        dataType: "json",
        data: {
            id: ps_id,
            shop: window.parent.ps_shop_id,
            lang: window.parent.ps_language_id,
        }
    }).done(function(res) {
        c_parent_id = res.parent_id;
        product.parent_id = res.parent_id;
        window.parent.ps_product_id = res.parent_id;
        product.min_order = res.min_order;
        product.max_order = res.max_order;
        product.id = res.design_id;
        product.price = res.price;
        jQuery("#quantity").val(product.min_order);
    });
});
jQuery(document).on('product.change.design', function(event, product) {
    jQuery("#tool_cart_ps").remove();

    var width = jQuery(window).width();
    if (width < 510) {
        design.mobile.areaDesign();
    }

    prestashop.combination(0);
});

design.saveDesignAdmin = function() {
    if (design.view != "done") {
        //if (jQuery('#view-'+design.view+' .product-design').html() != '')
        //{
        if (design.view == "back") {
            design.view = "left";
            design.svg.items("back", design.saveDesignAdmin);
            return false;
        } else if (design.view == "left") {
            design.view = "right";
            design.svg.items("left", design.saveDesignAdmin);
            return false;
        } else if (design.view == "right") {
            design.view = "done";
            design.svg.items("right", design.saveDesignAdmin);
            return false;
        }
    } else {
        var leftViewFlg = true, rightViewFlg = true;
        if (jQuery("#view-left .product-design").html() == "") {
            leftViewFlg = false;
        }
        if (jQuery("#view-right .product-design").html() == "") {
            rightViewFlg = false;
        }
        if (design.view == "back") {
            if (leftViewFlg) {
                design.view = "right";
                design.svg.items("left", design.saveDesignAdmin);
                return false;
            } else {
                if (rightViewFlg) {
                    design.view = "done";
                    design.svg.items("right", design.saveDesignAdmin);
                    return false;
                }
            }
        } else if (design.view == "left") {
            if (rightViewFlg) {
                design.view = "done";
                design.svg.items("right", design.saveDesignAdmin);
                return false;
            }
        }
    }
    var data = design.ajax.form();
    data.images = {};
    if (jQuery("#view-front .product-design").html() != "") {
        if (design.isIE()) {
            data.images.front = design.front.svgThum;
        } else {
            data.images.front = design.output.front.toDataURL();
        }
    } else {
        data.images.front = "";
    }
    if (jQuery("#view-back .product-design").html() != "") {
        if (design.isIE()) {
            data.images.back = design.back.svgThum;
        } else {
            data.images.back = design.output.back.toDataURL();
        }
    } else {
        data.images.back = "";
    }
    if (jQuery("#view-left .product-design").html() != "") {
        if (design.isIE()) {
            data.images.left = design.left.svgThum;
        } else {
            data.images.left = design.output.left.toDataURL();
        }
    } else {
        data.images.left = "";
    }
    if (jQuery("#view-right .product-design").html() != "") {
        if (design.isIE()) {
            data.images.right = design.right.svgThum;
        } else {
            data.images.right = design.output.right.toDataURL();
        }
    } else {
        data.images.right = "";
    }
    var vectors = JSON.stringify(design.exports.vector());
    var teams = JSON.stringify(design.teams);
    var productColor = design.exports.productColor();
    var thumb = "";
    if (data.images.front != "") {
        thumb = data.images.front;
    } else if (data.images.back != "") {
        thumb = data.images.back;
    } else if (data.images.left != "") {
        thumb = data.images.left;
    } else if (data.images.right != "") {
        thumb = data.images.right;
    }
    data.image = thumb;
    data.vectors = vectors;
    data.teams = teams;
    data.fonts = design.fonts;
    data.product_id = product_id;
    data.parent_id = parent_id;
    data.design_id = design.design_id;
    data.design_file = design.design_file;
    data.designer_id = design.designer_id;
    data.design_key = design.design_key;
    data.product_color = productColor;
    data.isIE = design.isIE();
    data.title = jQuery("#design-save-title-admin").val();
    data.description = jQuery("#design-save-description-admin").val();
    jQuery(document).triggerHandler("before.save.design", data);
    jQuery.ajax({
        url: siteURL + "ajaxps.php?type=saveDesignAdmin",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(data)
    }).done(function(msg) {
        var results = eval("(" + msg + ")");
        if (results.error == 1) {
            alert(results.msg);
        } else {
            design.design_id = results.content.design_id;
            design.design_file = results.content.design_file;
            design.designer_id = results.content.designer_id;
            design.design_key = results.content.design_key;
            design.productColor = productColor;
            design.product_id = product_id;
            results.content.productColor = productColor;
            results.content.product_id = product_id;
            jQuery(document).triggerHandler("done.save.design", results.content);
            var linkEdit = siteURL + "sharing.php?/" + results.content.user_id + ":" + results.content.design_key + ":" + product_id + ":" + productColor + ":" + parent_id;
            jQuery("#link-design-saved").val(linkEdit);
            jQuery("#dg-share").modal();
        }
        jQuery("#dg-mask").css("display", "none");
        jQuery("#dg-designer").css("opacity", "1");
    });
};

design.products.addProduct = function(products) {
    jQuery('.product-list').html('');
    if (products.length == 0) return;

    var seft = this;
    jQuery.each(products, function(i, product){
        var div = document.createElement('div');
            div.setAttribute('data-id', product.id);
            if (typeof product.parent_id !== 'undefined') {
                div.setAttribute('ps-product-id', product.parent_id);
            }
            div.className = 'product-box col-xs-6 col-sm-4 col-md-3';
        jQuery(div).click(function(){
            //seft.changeProduct(this, product);
            design.products.changeDesign(div, product.id);
        });

        html = '<div class="thumbnail"><img src="'+product.image+'" alt="'+product.title+'" class="img-responsive"> <div class="caption">' + product.title +'</div></div>';
            div.innerHTML = html;

        jQuery('.product-list').append(div);
    });
};

design.products.productCate = function(id) {
    var seft = this;
    if (typeof seft.products[id] != "undefined") {
        seft.addProduct(seft.products[id]);
    } else {
        jQuery("#dg-products .modal-body").addClass("loading");
        var cat_idx = 1, cat_idx_id = 1, category_id = 0;

        while (jQuery("#parent-categories-"+cat_idx).length > 0) {
            cat_idx_id = cat_idx;
            if (jQuery("#parent-categories-"+cat_idx).val() == 0) {
                var tmp = cat_idx - 1;
                category_id = jQuery("#parent-categories-"+tmp).val();
            } else {
                category_id = jQuery("#parent-categories-"+cat_idx).val();
            }
            cat_idx++;
        }
        if (category_id == 'undefined' || category_id == undefined) category_id = 0;
        jQuery.ajax({
            type: "POST",
            dataType: "json",
            url: mainURL + url_ajax_product,
            data: {
                id: window.parent.ps_product_id,
                lang: window.parent.ps_language_id,
                shop: window.parent.ps_shop_id,
                category: category_id,
            }
        }).done(function(data) {
            if (data != '') {
                jQuery.each(data.products, function(i, product) {
                    seft.product[product.id] = product;
                });
                seft.products[id] = data.products;
                seft.addProduct(data.products);
            }
        }).always(function() {
            jQuery("#dg-products .modal-body").removeClass("loading");
        });
    }
};

jQuery(document).on('ini.design', function(event) {
    if (typeof window.parent.tshirtecommerce_admin === "undefined" && window.parent.tshirtecommerce_admin != 1) {
        if (typeof window.parent.baseDir !== 'undefined') {
            if (jQuery('#tool_cart_ps').length == 0) {
                prestashop.combination(0);
            }
        }
    }

    jQuery(document).triggerHandler( "prestashop.update.taxes");

    var input_size = jQuery('.list-number input.size-number');
    if (typeof min_order !== 'undefined') {
        if (input_size.length > 0) jQuery(input_size[0]).val(min_order);
        jQuery('#quantity').val(min_order);
    }

    design.ajax.getPrice();
});

jQuery(document).ready(function($) {
    /* re-calc height on designer tool */
    if (typeof window.parent.getfullWidth !== 'undefined') {
        var width_site = window.parent.getfullWidth();
        if (width_site > 500) {
            var wh = jQuery('#dg-wapper').height() + 30;
            jQuery('#dg-wapper').css('height', wh+'px');
        }
    }
});

jQuery(document).on('form.addtocart.design', function(event, datas) {
    var options_ps = jQuery("#tool_cart_ps").serializeObject();
    datas = jQuery.extend(datas, options_ps);
});

jQuery(document).on('before.addtocart.design', function(event, datas) {
    prestashop.datas_tmp = datas;
});

jQuery(document).on('after.addtocart.design', function(event, data) {
    if (data != "") {
        if (data.error == 0) {
            data.product.product_id = parent_id;
            data.product.token = window.parent.token;
            //data.product.id_combination = datas.id_product_attribute;
            data.product.id_combination = prestashop.datas_tmp.id_product_attribute;
            if (typeof prestashop !== 'undefined' && typeof prestashop.datas_tmp !== 'undefined' && typeof prestashop.datas_tmp.print_type !== 'undefined') {
                data.product.print_type = prestashop.datas_tmp.print_type;
            } else {
                data.product.print_type = '';
            }

            data.product.design_imgs = "";
            data.product.attributes = jQuery('#tool_cart').serializeObject();
            data.product.tshirtecommerce_color = jQuery('#product-list-colors .bg-colors.active').data('color');

            if (typeof product_id !== 'undefined') {
                data.product.tshirtecommerce_product_id = product_id;
            } else {
                data.product.tshirtecommerce_product_id = 0;
            }
            if (typeof data.product.images !== "undefined") {
                data.product.design_imgs = data.product.images;
            }
            data.product.tshirtecommerce_design_cart_id = "";
            if (typeof data.product.rowid !== "undefined") {
                data.product.tshirtecommerce_design_cart_id = data.product.rowid;
            }
        }
    }
});

jQuery(document).on('prestashop.update.taxes', function(event) {
    if (jQuery('#product-attributes').length) {
        var datas = {};
        datas.eattributes = jQuery('#tool_cart').serializeObject();

        var psdatas = {};
        psdatas.method = 'tattributes';
        psdatas.id = parent_id;
        psdatas.tshirtecommerce_product_id = product_id;

        datas = jQuery.extend(datas, psdatas);

        jQuery.ajax({
            type: 'post',
            url: mainURL+'/modules/tshirtecommerce/ajax.php',
            data: datas,
            dataType: 'html',
            cache: false,
            success: function(res) {
                if (res.trim() != '') {
                    jQuery('#product-attributes').html(res);

                    jQuery("#tool_cart select, input[type='radio'], input[type='checkbox']").change(function(){
                        design.ajax.getPrice();
                    });

                    jQuery( "#quantity" ).spinner({
                        min: 0,
                        max: 1000,
                        stop: function(event, ui){
                            design.ajax.getPrice();
                        }
                    }).parent().addClass('field-quantity');

                    if (jQuery('#product-attributes .size-number').length) {
                        jQuery( ".size-number" ).spinner({
                            min: 0,
                            start: function(){
                                return design.team.changeSize();
                            },
                            stop: function(event, ui){
                                design.products.sizes();
                            }
                        });

                        jQuery('#product-attributes .size-number').click(function(){
                            design.team.changeSize();
                        });

                        jQuery('#product-attributes .size-number').keyup(function(){
                            design.products.sizes();
                        });
                        jQuery('#quantity').keyup(function(e){
                            design.ajax.getPrice();
                            var code = e.keyCode || e.which;
                            if (code == 13) {
                                e.preventDefault();
                                return false;
                            }
                        });

                        jQuery('#product-attributes .size-number').first().val(jQuery('#quantity').val());
                    }
                }
            }
        });
    }
});
