jQuery(document).ready(function() {

    var width = jQuery(window).innerWidth();
    var height = jQuery(window).height();
    var w = -width;
    var h = -height;
    var nbd_append_iframe = false,
        enableAdvancedUpload = false;
    var showDesignFrame = function() {
        jQuery('body, html').addClass('nbd-prevent-scroll');
        if (nbd_layout == 'c') {
            if (!nbd_append_iframe) {
                var iframe_src = jQuery('#container-online-designer').attr('data-iframe');
                if (jQuery('form input[name="variation_id"]').length) {
                    iframe_src = addParameter(iframe_src, 'variation_id', jQuery('form input[name="variation_id"]').val(), false);
                }
                jQuery('#nbd-custom-design-wrap').prepend('<iframe id="onlinedesigner-designer"  width="100%" height="100%" scrolling="no" frameborder="0" noresize="noresize" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" src="' + iframe_src + '"></iframe>');
                nbd_append_iframe = true;
            }
        } else {
            if (is_nbd_upload_without_design) {
                jQuery('#nbd-m-upload-design-wrap').addClass('is-visible');
                if (nbu_advanced_upload == '1') {
                    enableAdvancedUpload = true;
                }
            } else if (is_nbd_upload == 0 && use_our_template == 0 && hire_us_design_for_you == 0) {
                if (!nbd_append_iframe) {
                    var iframe_src = jQuery('#container-online-designer').attr('data-iframe');
                    if (jQuery('form input[name="variation_id"]').length) {
                        iframe_src = addParameter(iframe_src, 'variation_id', jQuery('form input[name="variation_id"]').val(), false);
                    }
                    jQuery('#nbd-m-custom-design-wrap').prepend('<iframe id="onlinedesigner-designer"  width="100%" height="100%" scrolling="no" frameborder="0" noresize="noresize" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" src="' + iframe_src + '"></iframe>');
                    nbd_append_iframe = true;
                }
                jQuery('#nbd-m-custom-design-wrap').addClass('is-visible');
            }
        };
        jQuery('#container-online-designer').addClass('is-visible');
    };

    jQuery(document).on('click', '#closeFrameDesign', function() {
        if (enableAdvancedUpload) {
            jQuery(document).triggerHandler('close_advanced_upload_popup');
            return;
        }
        hideDesignFrame();
    });

    jQuery(document).on('click', '#triggerDesign, #startDesign', function() {
        console.log('first');
        if (jQuery(this).hasClass('nbdesigner_disable')) {
            alert(nbds_frontend.check_invalid_fields);
        } else {
            showDesignFrame();
            var frame = document.getElementById('onlinedesigner-designer');
            if (frame) {
                frame.contentWindow.postMessage('change_nbo_options', window.location.origin);
            }
        }
    });

    hideDesignFrame = function(mes) {
        jQuery('body, html').removeClass('nbd-prevent-scroll');
        jQuery('#container-online-designer').removeClass('is-visible');
        backtoOption();
        if (mes != null) {
            setTimeout(function() {
                alert(mes);
            }, 700);
        }
        enableAdvancedUpload = false;
        NBDESIGNERPRODUCT.scrollToAddToCart();
    };

    jQuery(document).on('click', '#open_m-custom-design-wrap', function(event) {
        jQuery('.nbd-popup-wrap').addClass('is-hidden');
        if (!nbd_append_iframe) {
            var iframe_src = jQuery('#container-online-designer').attr('data-iframe');
            if (jQuery('form input[name="variation_id"]').length) {
                iframe_src = addParameter(iframe_src, 'variation_id', jQuery('form input[name="variation_id"]').val(), false);
            }
            jQuery('#nbd-m-custom-design-wrap').prepend('<iframe id="onlinedesigner-designer"  width="100%" height="100%" scrolling="no" frameborder="0" noresize="noresize" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" src="' + iframe_src + '"></iframe>');
            nbd_append_iframe = true;
        }
        jQuery('#nbd-m-custom-design-wrap').addClass('is-visible');
    });

    jQuery(document).on('click', '#nbd__content__overlay', function(event) {
        if (event.target.id == 'nbd__content__overlay') {
            hideDesignFrame();
        }
    });


    jQuery(document).on('click', '#open_m-upload-design-wrap', function(event) {
        jQuery('.nbd-popup-wrap').addClass('is-hidden');
        jQuery('#nbd-m-upload-design-wrap').addClass('is-visible');
        if (nbu_advanced_upload == '1') {
            enableAdvancedUpload = true;
        }
    });

    function uploadFile(files) {
        var file = files[0],
            type = file.type.toLowerCase();
        /*  NBD advanced - Upload multiple Tempalete*/
        if (typeof nbct_upload_multiple_file != "undefined") {
            if (files.length > 1) {
                var mutifile = [];
                for (i = 0; i < files.length; i++) {
                    mutifile.push(files[i]);
                }
                mutifile.forEach(function(file) {
                    var arr_file = [];
                    arr_file.push(file);
                    uploadFile(arr_file);
                });
                return;
            }
        }
        if (listFileUpload.length > (nbd_number - 1)) {
            alert('Exceed number of upload files!');
            return;
        }
        //if( type == '' ){
        type = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
        //}
        type = type == 'image/jpeg' ? 'image/jpg' : type;
        if (nbd_disallow_type != '') {
            var nbd_disallow_type_arr = nbd_disallow_type.toLowerCase().split(',');
            var check = false;
            nbd_disallow_type_arr.forEach(function(value) {
                value = value == 'jpeg' ? 'jpg' : value;
                if (type.indexOf(value) > -1) {
                    check = true;
                }
            });
            if (check) {
                resetUploadInput();
                alert('Disallow extensions: ' + nbd_disallow_type);
                return;
            }
        }
        if (nbd_allow_type != '') {
            var nbd_allow_type_arr = nbd_allow_type.toLowerCase().split(',');
            var check = false;
            nbd_allow_type_arr.forEach(function(value) {
                value = value == 'jpeg' ? 'jpg' : value;
                if (type.indexOf(value) > -1) {
                    check = true;
                }
            });
            if (!check) {
                resetUploadInput();
                alert('Only support: ' + nbd_allow_type);
                return;
            }
        }
        if (file.size > nbd_maxsize * 1024 * 1024) {
            alert('Max file size' + nbd_maxsize + " MB");
            resetUploadInput();
            return;
        } else if (file.size < nbd_minsize * 1024 * 1024) {
            alert('Min file size' + nbd_minsize + " MB");
            resetUploadInput();
            return;
        };
        var formData = new FormData;
        formData.append('file', file);
        jQuery('.nbd-upload-loading').addClass('is-visible');
        jQuery('.upload-zone label').addClass('is-loading');
        jQuery('.nbd-m-upload-design-wrap').addClass('is-loading');
        var first_time = listFileUpload.length > 0 ? 2 : 1;
        var product_id = jQuery('[name="nbd-add-to-cart"]').attr('value');
        var variation_id = jQuery('[name="variation_id"]').length > 0 ? jQuery('[name="variation_id"]').attr('value') : 0;
        formData.append('first_time', first_time);
        formData.append('action', 'nbd_upload_design_file');
        formData.append('task', 'new');
        formData.append('product_id', product_id);
        formData.append('variation_id', variation_id);
        formData.append('nonce', nbds_frontend.nonce);
        jQuery.ajax({
            url: nbds_frontend.url,
            method: "POST",
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            data: formData,
            complete: function() {
                jQuery('.nbd-upload-loading').removeClass('is-visible');
                jQuery('.upload-zone label').removeClass('is-loading');
                jQuery('.nbd-m-upload-design-wrap').removeClass('is-loading');
            },
            success: function(data) {
                if (data.flag == 1) {
                    listFileUpload.push({
                        src: data.src,
                        name: data.name
                    });
                    buildPreviewUpload();
                } else {
                    alert(data.mes);
                }
                resetUploadInput();
            }
        });
    }

    /* Drag & Drop uplod file */
    var listFileUpload = [];
    ['dragenter', 'dragover'].forEach(function(eventName) {
        jQuery(document).on(eventName, 'label[for="nbd-file-upload"]', highlight)
    });
    ['dragleave', 'drop'].forEach(function(eventName) {
        jQuery(document).on(eventName, 'label[for="nbd-file-upload"]', unhighlight)
    });

    function highlight(e) {
        e.preventDefault();
        e.stopPropagation();
        jQuery('label[for="nbd-file-upload"]').addClass('highlight');
    };

    function unhighlight(e) {
        e.preventDefault();
        e.stopPropagation();
        jQuery('label[for="nbd-file-upload"]').removeClass('highlight');
    };
    jQuery(document).on('drop', 'label[for="nbd-file-upload"]', handleDrop);

    function handleDrop(e) {
        if (jQuery('#accept-term').length && !jQuery('#accept-term').is(':checked')) {
            alert(NBDESIGNCONFIG.nbdlangs.alert_upload_term);
            return;
        } else {
            if (e.originalEvent.dataTransfer) {
                if (e.originalEvent.dataTransfer.files.length) {
                    e.preventDefault();
                    e.stopPropagation();
                    handleFiles(e.originalEvent.dataTransfer.files);
                }
            }
        }
    };
    jQuery(document).on('click', '#nbd-file-upload', function(e) {
        e.stopPropagation();
    });
    jQuery(document).on('change', '#nbd-file-upload', function() {
        handleFiles(this.files);
    });

    function resetUploadInput() {
        jQuery('#nbd-file-upload').val('');
    }

    function handleFiles(files) {
        if (files.length > 0) uploadFile(files);
    }

    window.removeUploadFile = function(index) {
        listFileUpload.splice(index, 1);
        resetUploadInput();
        buildPreviewUpload();
    };

    function buildPreviewUpload() {
        show_upload_thumb(listFileUpload);
        NBDESIGNERPRODUCT.update_nbu_value(listFileUpload);
        jQuery('input[name="nbu-ignore-update"]').remove();
        jQuery('input[name="nbu-reserve"]').remove();
        var html = '';
        listFileUpload.forEach(function(file, index) {
            html += '<div class="nbd-upload-items"><div class="nbd-upload-items-inner"><img src="' + file.src + '" class="shadow nbd-upload-item"/><p class="nbd-upload-item-title">' + file.name + '</p><span class="shadow" onclick="removeUploadFile(' + index + ')" >&times;</span></div></div>';
        });
        jQuery('.upload-design-preview').html(html);
        if (nbds_frontend.hide_cart_button == 'yes') jQuery('button[type="submit"].single_add_to_cart_button').show();
    }

    show_upload_thumb = function(arr) {
        if (arr.length) {
            jQuery('#nbdesigner-upload-title').show();
        } else {
            jQuery('#nbdesigner-upload-title').hide();
        };
        var html = '';
        var d = new Date();
        jQuery.each(arr, function(key, val) {
            html += '<div class="img-con" style=\"display: inline-block; margin-right: 15px;\"><img src="' + val.src + '?t=' + d.getTime() + '" style=\"width: 100px;\"/><p class="nbd-file-title">' + val.name + '</p></div>'
        });
        jQuery('#nbdesigner_upload_preview').html('').append(html);
    };


});