
//-------------------- Valid Email Function ------------
function wpyarValidEmail($email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test($email);
}
//-------------------- Valid Mobile Function ------------
function wpyarValidMobile($phone) {
    var phonereg = /^0\d{2,3}\d{8}$/;
    return phonereg.test($phone);
}

if (localStorage.getItem("mode") === "dark-theme") {
    document.documentElement.style.setProperty('--wud-bakp-color', '#131a29');
    document.documentElement.style.setProperty('--wud-white-color', '#25324f');
    document.documentElement.style.setProperty('--wud-black-color', '#fff');
    document.documentElement.style.setProperty('--wud-grey-color', '#c3c3c3');
} else {
    document.documentElement.style.setProperty('--wud-bakp-color', '#f6fbf8');
    document.documentElement.style.setProperty('--wud-white-color', '#ffffff');
    document.documentElement.style.setProperty('--wud-black-color', '#000000');
    document.documentElement.style.setProperty('--wud-grey-color', '#6f6f6f');
}
jQuery(document).ready(function ($) {

    jQuery(document).on('click','.wpyar_certificate_pop',function (){
        id = $(this).attr('data-id');
        $('.notification_popup_wpyar_panel').find('input[name="course_id"]').val(id).attr('value',id);
        $('.notification_popup_wpyar_panel').addClass('show');
        $('.ovl_wpyar').addClass('show');
    });
    jQuery(document).on('click','.notification_popup_wpyar_panel .close,.ovl_wpyar',function (){
       $('.notification_popup_wpyar_panel').removeClass('show');
       $('.ovl_wpyar').removeClass('show');
    });
  /***************** Toggle theme ***********************/
    $(document).on("change",".switch_theme_nirweb",function() {
        if(!localStorage.getItem("mode") || localStorage.getItem("mode") === 'light-theme'){
            document.documentElement.style.setProperty('--wud-bakp-color', '#131a29');
            document.documentElement.style.setProperty('--wud-white-color', '#25324f');
            document.documentElement.style.setProperty('--wud-black-color', '#fff');
            document.documentElement.style.setProperty('--wud-grey-color', '#6f6f6f');
            localStorage.setItem("mode", "dark-theme");
        }else{
            document.documentElement.style.setProperty('--wud-bakp-color', '#f6fbf8');
            document.documentElement.style.setProperty('--wud-white-color', '#ffffff');
            document.documentElement.style.setProperty('--wud-black-color', '#000000');
            document.documentElement.style.setProperty('--wud-grey-color', '#c3c3c3');
            localStorage.setItem("mode", "light-theme");
        }

    });
  /****************** End Toggle theme **********************/

    const Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
    })

   $('.gv-table-view').addClass('TableWpyarPanel');

   $('.inputProfileEditWpyarPanel.woo-mail').keyup(function (e) {
        if ($(this).val().length > 3) {
           $('.req_te').text(wpyarud.get_info_user).removeClass('clic');
           $('input[name="woo_wallet_transfer_user_id"]').val('');
           $('.req_te').slideDown();
            jQuery.ajax({
                url: wpyarud.ajax_url,
                type: "POST",
                data: {
                    action: "get_search_user",
                    email:$(this).val()
                },
                success: function (response) {
                    if (response == 'nouser') {
                       $('.req_te').text(wpyarud.nouser).removeClass('clic');
                       $('input[name="woo_wallet_transfer_user_id"]').val('');
                    } else {
                        response = JSON.parse(response);
                       $('.req_te').text(response['email']).attr('data-id', response['user_id']).addClass('clic');
                    }
                },
            });
        }
    })
   $('body').on('click', '.req_te.clic', function () {
        id =$(this).attr('data-id');
       $('input[name="woo_wallet_transfer_user_id"]').val(id);
       $(this).slideUp().attr('data-id', '').removeClass('clic');
    });
   $('.colseAlertWpyarpanel').click(function () {
       if ( $(this).closest('.alertBoxWpyarPanel').hasClass('nclose')){
           id = 'nirweb_'+$(this).closest('.alertBoxWpyarPanel').attr('data-ind');
           document.cookie = id+"="+$(this).closest('.alertBoxWpyarPanel').attr('data-ind');
           $(this).closest('.alertBoxWpyarPanel').fadeOut("slow", function () {
               $(this).remove();
           })
       }

    })



   $(document).on("click", function (event) {
        var $trigger =$(".iconsSidebarWpyarpanel li");
        if ($trigger !== event.target && !$trigger.has(event.target).length) {
           $(".ListDropDownIconsMenu >ul").slideUp("fast");
        }
    });
    if ($(window).width() < 992) {
       $('.LogoBoxWpyarPanel.mobile').html($('.LogoBoxWpyarPanel').html());
       $('body').on('click','.mobile_menu',function (e) {
           $('.ovl_menu ').addClass('open');
           $('.sidebarBoxWpyarPanel ').addClass('open');
        })
       $('.ovl_menu').click(function (e) {
           $(this).removeClass('open');
           $('.sidebarBoxWpyarPanel ').removeClass('open');
        })
    }
    if ($(window).width() < 576) {
       $('.iconsBoxWpyarPanelmobile').html($('.iconsBoxWpyarPaneldesk').html());
       $('.iconsBoxWpyarPaneldesk').remove();
    }
    //----------- Change Avatar Image Preview ---------------------------
    function changeAvatarPreviewWpyarPanel(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
               $('.previewImageWpyarPanel img').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]); // convert to base64 string
        }
    }
   $("#ImageSelectInputWpyarPanel").change(function () {
       var image_select = jQuery('#ImageSelectInputWpyarPanel').val();
       if (image_select) {
           var size_file = jQuery('#ImageSelectInputWpyarPanel')[0].files[0]['size'];
           var ac_size = '500000';

           if (size_file >= ac_size) {

               alert_error('حجم فایل نامعتبر می باشد')
               this.value = '';
               return false
           }

       }
        var ext = this.value.match(/\.(.+)$/)[1];
        switch (ext) {
            case 'jpg':
            case 'jpeg':
            case 'png':
                changeAvatarPreviewWpyarPanel(this);
                break;
            default:
                Toast.fire({
                    icon: 'error',
                    title: wpyarud.notValidFile,
                })
                this.value = '';
        }
    });
    //-------------------------- Send Image for Profile ------------------
   $('body').on('click', '.changeImageProfileWpyarPanel', function (e) {
        var image_select =$('#ImageSelectInputWpyarPanel').val();
        if (image_select) {
           $(this).text(wpyarud.sendreq)
            var formData = new FormData();
            formData.append('updoc',$('#ImageSelectInputWpyarPanel')[0].files[0]);
            formData.append('action', "changeProfileWpyarPanel");
            jQuery.ajax({
                url: wpyarud.ajax_url,
                type: "POST",
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                success: function (data) {
                    location.reload();
                    return false;
                },
                error: function () {
                   $(this).text(wpyarud.change_image);
                    return false;
                }
            });
        } else {
            Toast.fire({
                icon: 'error',
                title: wpyarud.select_image,
            })
            return false
        }
    });
    //-------------------------- Display Content Notification -----------------
   $('.baseWpyarPanelItemNotification').click(function () {
       $(this).closest('.ItemNotification ').find('.contentWpyarPanelNotification').slideToggle();
       $(this).find('.arrowNotificationWpyarPanel').toggleClass('open');
    });
    //-------------------------- Display Content Notification -----------------
   $('.baseWpyarPanelItemDownloadsWpyarPanel').click(function () {
       $(this).closest('.ItemDownloadsWpyarPanel ').find('.contentWpyarPanelDownloads').slideToggle();
       $(this).closest('.ItemDownloadsWpyarPanel ').find('i').toggleClass('open');
    });
    //-------------------------- Paginate wallet Page tans -----------------
   $('#data').after('<div id="navWpyarPanelWooWallet"></div>');
    var rowsShown = 7;
    var rowsTotal =$('#data tbody tr').length;
    var numPages = rowsTotal / rowsShown;
    for (i = 0; i < numPages; i++) {
        var pageNum = i + 1;
       $('#navWpyarPanelWooWallet').append('<a class="bgSecColor-wpyarpanel-wpyarpanel wColor-wpyarpanel"  rel="' + i + '">' + pageNum + '</a> ');
    }
   $('#data tbody tr').hide();
   $('#data tbody tr').slice(0, rowsShown).show();
   $('#navWpyarPanelWooWallet a:first').addClass('active');
   $('#navWpyarPanelWooWallet a').bind('click', function () {
       $('#navWpyarPanelWooWallet a').removeClass('active');
       $(this).addClass('active');
        var currPage =$(this).attr('rel');
        var startItem = currPage * rowsShown;
        var endItem = startItem + rowsShown;
       $('#data tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
        css('display', 'table-row').animate({
            opacity: 1
        }, 300);
    });
    //-------------------- Confirm Mobile --------------------
   $('body').on('click', '.btn_c_phoneWpyar', function () {
        var mobile =$('#wpyarud_phone').val();
        if (mobile.length == 0 || !wpyarValidMobile(mobile)) {
            Toast.fire({
                icon: 'error',
                title: wpyarud.mob_format_invalid,
            })
           $('.btn_c_phoneWpyar').text(wpyarud.send_req);
            return false
        } else {
           $('.btn_c_phoneWpyar').text(wpyarud.send_req + '...');
            $.ajax({
                url: wpyarud.ajax_url,
                type: "POST",
                data: {
                    action: "confirmMobileWpyarud",
                    mobile
                },
                success: function (data) {
                    data = $.parseJSON(data);
                    if (data['status'] == 'error') {
                        Toast.fire({
                            icon: 'error',
                            title: data['message'],
                        })
                       $('.btn_c_phoneWpyar').text(wpyarud.send_req);
                        return false;
                    } else {
                       $('.c_phoneWpyar').html(data['form']);
                       $('.c_phoneWpyar input').addClass('inputProfileEditWpyarPanel');
                       $('.c_phoneWpyar .check_code ').addClass('bgSecColor-wpyarpanel-wpyarpanel wColor-wpyarpanel sendFormProfileWpyarPanel');
                    }
                },
                error:function (){
                    $('.btn_c_phoneWpyar').text(wpyarud.send_req);
                    Toast.fire({
                        icon: 'error',
                        title: wpyarud.error_req,
                    })
                    return false
                }
            });
        }
    });
    //------- Check Code  --------------
   $('body').on('click', '.check_code', function (e) {
        e.preventDefault();
        old_val =$(this).text();
        code =$('input[name="check_code"]').val();
        user =$('input[name="user_check"]').val();
        if (code.length == 0) {
            Toast.fire({
                icon: 'error',
                title: wpyarud.enter_code,
            });
           $('.check_code').text(wpyarud.send_req);
            return false;
        }
       $('.check_code').text(wpyarud.check_code);
        $.ajax({
            url: wpyarud.ajax_url,
            data: {
                code,
                user,
                action: "check_code_confirm_wpyarPanel"
            },
            type: "POST",
            success: function (data) {
                data = $.parseJSON(data)
                if (data['status'] == 'error') {
                   $('.check_code').text(old_val);
                   $('.suc_form_auth').removeClass('suc_form_auth').html(data['message']).addClass('error_form_auth');
                    Toast.fire({
                        icon: 'error',
                        title: data['message'],
                    })
                   $('.check_code').text(wpyarud.send_req);
                    return false;
                }
                window.location.reload();
            }
        })
    });
    //-------------- Dropdwon menu item icons ----------
   $('.iconsSidebarWpyarpanel li').click(function (e) {
        if ($(this) ==$('.iconsSidebarWpyarpanel li').eq(1) ||$(this) ==$('.iconsSidebarWpyarpanel li').eq(2)) {
            e.preventDefault();
        }
        var id_target = '#' +$(this).attr('data-target');
       $('.ListDropDownIconsMenu >ul').hide();
       $(id_target).slideDown();
        e.stopPropagation();
    })
    //----------- Save Profile and check Email ------------ 
    email_profile =$('#saveUserProfile input[type="email"]').val();
    phone_profile =$('#wpyarud_phone').val();
   $('body').on('click', 'form#saveUserProfile .sendFormProfileWpyarPanel', function (e) {
        e.preventDefault();
        all_is_ok = true;
        //---Check Email ----
        if ($('#saveUserProfile input[type="email"]').val().length == 0 &&$('#saveUserProfile input[type="email"]').val() != email_profile) {
            all_is_ok = false;
            Toast.fire({
                icon: 'error',
                title: wpyarud.emp_email,
            })
            return false;
        }

        if ($('#saveUserProfile input[type="email"]').val().length > 0 &&$('#saveUserProfile input[type="email"]').val() != email_profile) {
            if (!wpyarValidEmail($('#saveUserProfile input[type="email"]').val())) {
                Toast.fire({
                    icon: 'error',
                    title: wpyarud.email_incorrect,
                })
                return false;
            }
           $(this).text(wpyarud.sendreq + '...');
            all_is_ok = false;
            $.ajax({
                url: wpyarud.ajax_url,
                data: {
                    action: "changEmailInProfile",
                    email:$('#saveUserProfile input[type="email"]').val()
                },
                type: "POST",
                success: function (data) {
                    data = $.parseJSON(data)
                    if (data['status'] == 'error') {
                        Toast.fire({
                            icon: 'error',
                            title: data['message'],
                        })
                       $('form#saveUserProfile .sendFormProfileWpyarPanel').text(data['btn_text']);
                        return false;
                    } else {
                       $('form#saveUserProfile .sendFormProfileWpyarPanel').text(data['btn_text']).fadeOut();
                       $('.change_resp_email').html(data['form']);
                    }
                }
            })
        }
        if (phone_profile && phone_profile !=$('#wpyarud_phone').val()) {
           $(this).text(wpyarud.sendreq + '...');
            if (!wpyarValidMobile($('#wpyarud_phone').val())) {
                Toast.fire({
                    icon: 'error',
                    title: wpyarud.mob_incorrect,
                })
               $(this).text(wpyarud.sendreq);
                return false;
            }
            all_is_ok = false;
           $(this).text(wpyarud.sendreq + '...');
            $.ajax({
                url: wpyarud.ajax_url,
                data: {
                    action: "changmobInProfile",
                    mob:$('#wpyarud_phone').val()
                },
                type: "POST",
                success: function (data) {
                    data = $.parseJSON(data)
                    if (data['status'] == 'error') {
                        Toast.fire({
                            icon: 'error',
                            title: data['message'],
                        })
                       $('form#saveUserProfile .sendFormProfileWpyarPanel').text(data['btn_text']);
                        return false;
                    } else {
                       $('form#saveUserProfile .sendFormProfileWpyarPanel').text(data['btn_text']).fadeOut();
                       $('.change_resp_mob').html(data['form']);
                    }
                }
            })
        }
        if (all_is_ok) {
           $('#saveUserProfile').attr('action', wpyarud.ajax_url + '?action=saveprofile');
           $('#saveUserProfile').submit();
        }
    })
    //------Check Code in editaccount -----------
   $('body').on('click', '.code_change_email_wpyarpanel', function (e) {
       is_ok= false
        if ($('#saveUserProfile input[name="code_change_email"]').val() != undefined) {
            if ($('#saveUserProfile input[name="code_change_email"]').val().length > 0) {
                email =$('#saveUserProfile input[name="user_email"]').val();
                mob = false
                code =$('#saveUserProfile input[name="code_change_email"]').val();
                is_ok= true
            }
        }
        if ($('#saveUserProfile input[name="code_change_mob"]').val() != undefined) {
            if ($('#saveUserProfile input[name="code_change_mob"]').val().length > 0) {
                mob =$('#saveUserProfile #wpyarud_phone').val();
                email = false
                code =$('#saveUserProfile input[name="code_change_mob"]').val();
                is_ok= true
            }
        }
       if(is_ok){
           console.log(email);
           console.log(code);
           console.log(mob);
            $.ajax({
                url: wpyarud.ajax_url,
                data:{
                action: "checkCodeEditAccount",
                mob,code,email
            },
                type: "POST",
                success: function (data) {
                    data = $.parseJSON(data)
                    if (data['status'] == 'error') {
                        Toast.fire({
                            icon: 'error',
                            title: data['message'],
                        })
                       $('.code_change_email_wpyarpanel').text(wpyarud.cbtntext);
                        return false;
                    }
                    if (data['status'] == 'sucsses') {
                        Toast.fire({
                            icon: 'success',
                            title: data['message'],
                        })
                        setTimeout(() => {
                            window.location.reload();
                        }, 2500);
                    }
                }
            })
        } else {
            Toast.fire({
                icon: 'error',
                title: wpyarud.enter_ver_code,
            })
           $('form#saveUserProfile .sendFormProfileWpyarPanel').text(wpyarud.cbtntext);
            return false;
        }
    })
}); //------- End Code jQuery Doc Ready