(function($) {
    'use strict';

    $.validator.addMethod("noSpace", function(value, element) {
        return value.indexOf(" ") < 0 && value != "";
    }, "No space please and don't leave it empty");

    $.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please insert only numbers and +."
    );

    $.validator.addMethod('filesize', function (value, element, param) {
        var file_size = element.files[0].size/ 1048576;
        return this.optional(element) || (file_size <= param)
    }, 'File size must be less than {0} MB');

    // $(':input').bind('keyup', function(){
    //     $(this).val(  $.trim($(this).val()) );
    // });

    $.each($('.validateForm'),function () {
        // console.log(grecaptcha.getResponse());
        $(this).validate({
            submitHandler: function(form) {
                // console.log(grecaptcha.getResponse());
                if (grecaptcha.getResponse()) {
                    form.submit();
                    grecaptcha.reset();
                } else {
                    alert('Please confirm captcha to proceed')
                }
            }
        });
    });

    $( "#scForm" ).validate({
        rules: {
            cv: {
                required: true,
                extension: "doc|docx|pdf"
            }
        },
        messages:{
            cv:{
                extension:"Please select ( pdf,docs,doc) file."
            }
        }
    });

    $('#nlForm').validate({
        submitHandler:function (form) {
            if (grecaptcha.getResponse()) {
                // form.submit();
            } else {
                alert('Please confirm captcha to proceed');
                return false;
            }
            
            var $form = $(form);
            // return false;
            $.ajax({
                type: 'POST',
                url: $form.attr('action'),
                dataType:'json',
                data: {
                    _token: $('meta[name="csrf-token"]').attr('content'),
                    company_name: $form.find('#company_name').val(),
                    name: $form.find('#name').val(),
                    email: $form.find('#email').val(),
                    mobile: $form.find('#mobile').val(),
                    country: $form.find('#country').val()
                },
                success:function (data) {
                    // console.log(data);
                    grecaptcha.reset();
                    if(data.nlResponse){
                        $form.find('.alert-danger').addClass('d-none');
                        $form.find('.alert-success').removeClass('d-none');
                        $form[0].reset();
                    }
                    else{
                        var errors = '<ul>';
                        $.each(data.nlMsg,function (k,v) {
                            errors += '<li>' + v + '</li>';
                        });
                        errors += '</ul>';
                        $form.find('.alert-success').addClass('d-none');
                        $form.find('.alert-danger').find('span').html(errors);
                        $form.find('.alert-danger').removeClass('d-none');
                    }
                },
                error:function (data) {
                    $form.find('.alert-success').addClass('d-none');
                    $form.find('.alert-danger').removeClass('d-none');
                }
            });
            // return false;
        }
    });

    $("#mobile").rules("add", { regex: "^[0-9+]{9,30}$" });
    $("#phone").rules("add", { regex: "^[0-9+]{6,30}$" });
    $("#website").rules("add", { url:true });
    $("#file").rules("add", { filesize: 5});
    // $(":input").rules("add",{noSpace:true});


    $(function(){
        setTimeout(function () {            
            if ($('.post-body').length > 0) {
                let str = $('.post-body').html();
                // console.log(str);
                var yturl= /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([\w\-]{10,12})(?:&feature=related)?(?:[\w\-]{0})?/g;
                var ytplayer= '<div class="embed-responsive embed-responsive-16by9 mt-3 mb-3"> <iframe  src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe> </div>';
                $('.post-body').html(str.replace(yturl, ytplayer));
                // let str = str.html();
                // str.replace(/(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="420" height="345" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>');
            }
        },1000);
    });

    // $('#moForm').validate({
    //     submitHandler:function (form) {
    //         var $form = $(form);
    //         var data = $form.serialize();
    //
    //         $.ajax({
    //             type: 'POST',
    //             url: $form.attr('action'),
    //             dataType:'json',
    //             data: data,
    //             success:function (data) {
    //                 console.log(data);
    //
    //             },
    //             error:function (data) {
    //                 console.log(data);
    //             }
    //         });
    //     }
    // });
    $('#newsletterModalForm').validate({
        submitHandler: function(form) {
            // console.log(grecaptcha.getResponse());
            if (grecaptcha.getResponse()) {
                var form = $(form);
                var data = form.serialize();
                var action = form.attr('action');
                // console.log(data);
                $.ajax({
                    type: 'POST',
                    url: action,
                    dataType:'json',
                    data: data,
                    success:function (data) {
                        grecaptcha.reset();
                        if (data.success) {
                            $('#newsletterModal').modal('hide');
                            setTimeout (function () {
                                window.open(data.url,'_blank');
                            },1500);                    
                        }
                        // console.log(data);
                    },
                    error:function (data) {
                        console.log(data);
                    }
                });        
                return false;
            } else {
                alert('Please confirm captcha to proceed')
            }
        }        
    });

    

    $('#moForm .product_category_ideeee').on('change',function () {
        var row = $(this).closest('.product-row');
        var category_id = $(this).val();
        var product_list = row.find('.product_id');
        if ($.isNumeric(category_id )){
            $.ajax({
                type: 'GET',
                url: base_url + '/get-category-products',
                dataType:'json',
                data: {
                    _token: $('meta[name="csrf-token"]').attr('content'),
                    category_id: category_id,
                },
                success:function (data) {
                    // console.log(data);
                    var products = '<option value="">Select Product Name</option>';
                    $.each(data,function (k,v) {
                        products += '<option value="' + k + '">' + v + '</option>';
                    });
                    product_list.html(products);
                },
                error:function (data) {
                }
            });
        }
    });

    if (1==2) {
        // No White Space
        $.validator.addMethod("noSpace", function(value, element) {
            if( $(element).attr('required') ) {
                return value.search(/[a-z0-9]/i) == 0;
            }

            return true;
        }, 'Please fill this empty field.');

        /*
        Assign Custom Rules on Fields
        */
        $.validator.addClassRules({
            'form-control': {
                noSpace: true
            }
        });

        /*
        Contact Form: Basic
        */
        $('#contactForm').validate({
            submitHandler: function(form) {

                var $form = $(form),
                    $messageSuccess = $('#contactSuccess'),
                    $messageError = $('#contactError'),
                    $submitButton = $(this.submitButton),
                    $errorMessage = $('#mailErrorMessage'),
                    submitButtonText = $submitButton.val();

                $submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);

                // Ajax Submit
                $.ajax({
                    type: 'POST',
                    url: $form.attr('action'),
                    data: {
                        name: $form.find('#name').val(),
                        email: $form.find('#email').val(),
                        subject: $form.find('#subject').val(),
                        message: $form.find('#message').val()
                    }
                }).always(function(data, textStatus, jqXHR) {

                    $errorMessage.empty().hide();

                    if (data.response == 'success') {

                        $messageSuccess.removeClass('d-none');
                        $messageError.addClass('d-none');

                        // Reset Form
                        $form.find('.form-control')
                            .val('')
                            .blur()
                            .parent()
                            .removeClass('has-success')
                            .removeClass('has-danger')
                            .find('label.error')
                            .remove();

                        if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
                            $('html, body').animate({
                                scrollTop: $messageSuccess.offset().top - 80
                            }, 300);
                        }

                        $form.find('.form-control').removeClass('error');

                        $submitButton.val( submitButtonText ).attr('disabled', false);

                        return;

                    } else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
                        $errorMessage.html(data.errorMessage).show();
                    } else {
                        $errorMessage.html(data.responseText).show();
                    }

                    $messageError.removeClass('d-none');
                    $messageSuccess.addClass('d-none');

                    if (($messageError.offset().top - 80) < $(window).scrollTop()) {
                        $('html, body').animate({
                            scrollTop: $messageError.offset().top - 80
                        }, 300);
                    }

                    $form.find('.has-success')
                        .removeClass('has-success');

                    $submitButton.val( submitButtonText ).attr('disabled', false);

                });
            }
        });

        /*
        Contact Form: Advanced
        */
        $('#contactFormAdvanced').validate({
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            rules: {
                'captcha': {
                    captcha: true
                },
                'checkboxes[]': {
                    required: true
                },
                'radios': {
                    required: true
                }
            },
            errorPlacement: function(error, element) {
                if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
                    error.appendTo(element.closest('.form-group'));
                } else {
                    error.insertAfter(element);
                }
            }
        });
    }
}).apply(this, [jQuery]);

function removeProduct(btn,server = false){
    var pro_count = $('.product-row').length;
    var row = $(btn).closest('.product-row');
    var pro_id = row.find('.product_id');
    // console.log(pro_id);
    if(pro_count > 1){

        var conf = confirm('Are you sure?');
        if (conf == true) {
            if (server == true){
                row.remove();
                return false;
            }

            $.ajax({
                type: 'POST',
                url: base_url + '/en/remove-product-row',
                data: {
                    _token: $('meta[name="csrf-token"]').attr('content'),
                    pro_id: pro_id.val()
                },
                success:function (data) {
                    // console.log(data);
                    if (data.response == true){
                        $('.cart-products-count').html(data.cart_products_count);
                        row.remove();
                        // window.location.reload();
                    }
                }
            });

        }
    }
    else
        alert('Order must include at least one product.');
}

function getCatProducts(select_tag){
    var row = $(select_tag).closest('.product-row');
    var category_id = parseInt($(select_tag).val()) ;
    var product_list = row.find('.product_id');
    if ($.isNumeric(category_id )){
        $.ajax({
            type: 'GET',
            url: base_url + '/get-category-products',
            dataType:'json',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                category_id: category_id,
            },
            success:function (data) {
                console.log(data);
                var products = '' ;
                if(data != undefined || ($.isArray(data) && data.length > 0) ){
                    products += '<option value="">Select Product </option>';
                    $.each(data,function (k,v) {
                        products += '<option value="' + k + '">' + v + '</option>';
                    });
                }
                else
                    products += '<option value="">No Products Available</option>';

                product_list.html(products);
            },
            error:function (data) {
            }
        });
    }
}

function updateCart(product_id,row_id){
    // console.log(row_id);
    // return;
    if(product_id != undefined){
        $.ajax({
            type: 'POST',
            url: base_url + '/en/update-cart',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                pro_id: product_id,
                row_id: row_id
            },
            success:function (data) {
                console.log(data);
                if (data.response == true){
                    $('.cart-products-count').html(data.cart_products_count);
                    // window.location.reload();
                }
            }
        });
    }
}

function addProduct(btn){

    // Cookies.set('koko', 'toto');
    // var cart = Cookies.get('koko');
    // console.log(cart);
    // return false;
    var this_row = $('.product-row').last();
    var pro_count = $('.product-row').length;
    // console.log(pro_count);
    if (pro_count>0){
        $.ajax({
            type: 'POST',
            url: base_url + '/en/get-product-row',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                pro_count: pro_count
            },
            success:function (data) {
                // console.log(data);
                this_row.after(data);
                // Cookies.set('koko', 'toto');
                // var cart = Cookies.get('mega_trade_session');
                // console.log(cart);
            }
        });
    }
}

function downloadFile(file_path , file_name){
    $.ajax({
        type: "POST",
        dataType:'json',
        data: {
            file_path: file_path,
            file_name : file_name,
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        url: base_url + "/download-file",
        success: function(response)
        {
            // console.log(response);
        }
    });
    // return false;
}