(function($) {
    "use strict";

    jQuery(document).ready(function($) {

        //search
        $('.click-appear').click(function() {
            $(this).parent().toggleClass('active');
            $(this).children().toggleClass('icon-search').toggleClass('icon-cancel');
        });
        
        $('#sel1').on('change', function () {
          var url = $(this).val(); // get selected value
          if (url) { // require a URL
              window.open(url,'_blank');
          }
          return false;
        });
        
        $('#click-to-open').on('change', function () {
          var url = $(this).val(); // get selected value
          if (url) { // require a URL
              window.open(url,'');
          }
          return false;
        });
        
        $('.iframe-list > li > a.active').each(function(){
            let name = $(this).text();
            $('#title-main').text(name);
        })
        
        // Change Iframe
	    $('.iframe-list .changeframe').click(function(){
	        let $id = $(this).attr('data-iframe'); 
	        let $id_2 = $('.resp-container').attr('data-src');
	        if( $id == $id_2 ){
	            e.preventDefault();
	        }
	        else{
	            $('#declinedframe').attr('src', 'https://www.youtube.com/embed/' + $id + '?autoplay=1&rel=0');
	            $('.resp-container').attr('data-src', $id);
	            $('.iframe-list').find('a').removeClass('active');
	            $(this).addClass('active');
	            $('#title-main').text($(this).text());
	            $('html, body').animate({
                    scrollTop: $("#declinedframe").offset().top - 100
                }, 300);
	        }
	    });
        

        //Subscribe

        $("#subscribe").validate({
            submitHandler: function(form) {

                var email = $("#subscribe input.form-dky").val();
                if (email == "" || email == null) {
                    email = "admin@gmail.com";
                }
                $.ajax({
                        method: "post",
                        url: "/contact-ajax",
                        data: { email: email, action: "subscribe_email" }
                    })
                    .done(function(msg) {
                        alert("Đăng ký thành công!");
                        location.reload();
                    });
            }
        });
        $("#subscribe-f").validate({
            submitHandler: function(form) {

                var email = $("#subscribe-f input.form-dky").val();
                if (email == "" || email == null) {
                    email = "admin@gmail.com";
                }
                $.ajax({
                        method: "post",
                        url: "/contact-ajax",
                        data: { email: email, action: "subscribe_email" }
                    })
                    .done(function( msg ) {
        		    swal({
        		         title: "Đăng ký thành công",
                          text: "Cảm ơn bạn đã đăng ký. Chúng tôi sẽ gửi những ưu đãi sớm nhất cho bạn!",
                          icon: "success",
                          button: "Đóng",
                          closeOnEsc: false
        		    })
        		    .then((value) => {
                        window.location.reload();
                    })
        	    }); 
            }
        });
        
        function convertDate(date){
            if(date !== '') {
                let d_arr = date.split("-");
                let newdate = d_arr[1] + '-' + d_arr[2] + '-' + d_arr[0];
                let date_convert = new Date(newdate);
                let unixTimestamp = Math.floor(date_convert.getTime() / 1000);
                return unixTimestamp;
            } else {
                return ''
            }
            
        }
        
        $("#submit_params").click(function(e){
            e.preventDefault();
            let form = $('#get_list_ds_doituong');
            let name = $("input[name='name']").val();
            if (name === '') {
                Toastify({
                  text: "Vui lòng nhập họ và tên",
                  duration: 5000,
                  newWindow: true,
                  close: true,
                  gravity: "bottom", // `top` or `bottom`
                  position: "right", // `left`, `center` or `right`
                  stopOnFocus: true, // Prevents dismissing of toast on hover
                  style: {
                    background: "linear-gradient(to right, #333, #000)",
                  },
                }).showToast();
                return false;
            } else {
                //let ngay_ky = $("input[name='ngay_ky']").val();
                let ngay_vao = $("input[name='ngay_vao']").val();
                
                let values = form.serializeArray();
                let mapValues = [...values];
                mapValues.find(input => input.name == 'ngay_vao').value = convertDate(ngay_vao);
                //mapValues.find(input => input.name == 'ngay_ky').value = convertDate(ngay_ky);
                let params = jQuery.param(mapValues);
                //window.location = `/doi-tuong-bao-tro?${params}`
                loadResultBy(params, $("#get_ds"));
                
            }
        })
        
        $("#delete_params").click(function(e){
            e.preventDefault();
            let params = '';
            $('form :input').val('');
            loadResultBy(params, $("#get_ds"));
        })
        
        function loadResultBy(params, position_load) {
            // $('html, body').animate({
            //     scrollTop: $(position_load).offset().top - 200
            // }, 1000);
            var srt_pro = '';
            $.ajax({
                'url': `/ajax-filter?${params}`,
                'type': 'GET',
                success: function(response) {
                    
                    setTimeout(function(){
                        // console.log(response)
                        if(response !== '' || response !== null) {
                            srt_pro += response;
                            
                        } else {
                            srt_pro += ('<div class="text-center not_found">Không tìm thấy đối tượng nào</div>')
                        }
                        console.log(srt_pro)
                        position_load.html(srt_pro);
                        $(".toolbox-pagination").hide();
                        
                    }, 1000);
                    
                }
            });
        }

        // lien he bao hanh
        $("#contact-fr").validate({
            submitHandler: function(form) {

                var full_name = $("#name").val();
                if (full_name == "" || full_name == null) {
                    full_name = "Admin";
                }
                // var email = $("#email").val();
                // if (email == "" || email == null) {
                //     email = "admin@gmail.com";
                // }
                var email = $("#email").val() || "khach"+Math.round(Math.random()*1234)+"@supertech.vn";
                var phone_number = $("#phone").val();
                if (phone_number == "" || phone_number == null) {
                    phone_number = "+84";
                }
                var content = $("#content").val();
                $.ajax({
                    method: "post",
                    url: "/contact-ajax",
                    data: { full_name: full_name, email: email, phone_number: phone_number, content: content, action: "feedback.add" }
                })
                .done(function( msg ) {
    		    swal({
    		         title: "Thành công",
                      text: "Cảm ơn quý khách đã liên hệ. Nhân viên chúng tôi sẽ liên lạc trong thời gian sớm nhất. Xin cảm ơn !",
                      icon: "success",
                      button: "Đóng",
                      closeOnEsc: false
    		    })
    		    .then((value) => {
                    window.location.reload();
                })
    	    });   
            }
        });
        
        // scroll header
        $(window).bind('scroll', function () {
            if ($(window).scrollTop() > 400) {
        $('.header-top').addClass('fixed-2');
        } else {
        $('.header-top').removeClass('fixed-2');
        }
});

    });
    

}(jQuery));
