$(function () {

//  $('.preloader').removeClass('preloader-deactivate');
  $(document).ajaxStart(function () {
    $('.preloader').removeClass('preloader-deactivate');
  });
  $(document).ajaxStop(function () {
    $('.preloader').addClass('preloader-deactivate');
  });

  $('.eye-btn').on('click', function () {

    var id = $(this).attr('id');
    $.control.fngetproductdetail(id);
  });


  $('.add-to-cart').on('click', function () {

    var id = $(this).attr('id');
    $.control.fnaddproducttocart(id);
  });


  $('.remove_cart_item_cart_list,.remove_cart_item').on('click', function () {
    var id = $(this).attr('id');
    $.control.fnRemoveProductFromMyCart(id);
  });

  $('#btn-update_my_cart').on('click', function () {
    $.control.fnUpdateMyCartItems();
  });

  $('#form_check_out #rfq_zip_code').on('blur', function () {
    var val = $(this).val();
    if (val != '') {
      $.control.fngetAddress(val);
    }
  });



  $("#form_check_out").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
      // handle the invalid form...
      $.control.formError("#contactForm");
      $.control.submitMSG(false, "กรุณากรอกข้อมูลให้ครบถ้วน !", "#contactForm");
    } else {
      // everything looks good!
      event.preventDefault();
      $.control.checkout_submitForm();
    }
  });

  $("#form_login").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
      $.control.formError("#form_login_");
      $.control.submitMSG(false, "กรุณากรอกข้อมูลให้ครบถ้วน !", "#form_login_");
    } else {
      event.preventDefault();
      $.control.login_submitForm();
    }
  });
  $("#form_update_profile").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
//             $.control.formError("#form_update_profile_");
//             $.control.submitMSG(false, "กรุณากรอกข้อมูลให้ครบถ้วน !","#form_update_profile_");
    } else {
      event.preventDefault();
      $.control.profile_submitForm();
    }
  });
  
  $("#form_forgot_password").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {

    } else {
      event.preventDefault();
      $.control.forgot_password_submitForm();
    }
  });
  
  
  $("#form_change_password").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
//             $.control.formError("#form_update_profile_");
//             $.control.submitMSG(false, "กรุณากรอกข้อมูลให้ครบถ้วน !","#form_update_profile_");
    } else {
      event.preventDefault();
      $.control.change_password_submitForm();
    }
  });

  var status_1 = 0;
  var status_2 = 0;
  var status_3 = 0;
  var status_4 = 0;
  $('input[type=password].input_password').keyup(function () {
    var pswd = $(this).val();
    //validate the length

    if (pswd.length < 8) {
      $('#length').removeClass('valid').addClass('invalid');
      status_1 = 0;
    } else {
      $('#length').removeClass('invalid').addClass('valid');
      status_1 = 1;
    }

    //validate letter
    if (pswd.match(/[A-z]/)) {
      $('#letter').removeClass('invalid').addClass('valid');
      status_2 = 1;
    } else {
      $('#letter').removeClass('valid').addClass('invalid');
      status_2 = 0;
    }

    //validate capital letter
    if (pswd.match(/[A-Z]/)) {
      $('#capital').removeClass('invalid').addClass('valid');
      status_3 = 1;
    } else {
      $('#capital').removeClass('valid').addClass('invalid');
      status_3 = 0;
    }

    //validate number
    if (pswd.match(/\d/)) {
      $('#number').removeClass('invalid').addClass('valid');
      status_4 = 1;
    } else {
      $('#number').removeClass('valid').addClass('invalid');
      status_4 = 0;
    }

    var con_pswd = $('#confirm_new_password').val();


    if ((status_1 + status_2 + status_3 + status_4 == 4) && pswd == con_pswd) {
      $('button.save_change_password').prop('disabled', false);
    } else {
      $('button.save_change_password').prop('disabled', true);
    }

  }).focus(function () {
    $('#pswd_info').show();
  }).blur(function () {
    $('#pswd_info').hide();
  });

  $('input[type=password].input_confiem_password').keyup(function () {
    var pswd = $('#new_password').val();
    var con_pswd = $('#confirm_new_password').val();

    if ((status_1 + status_2 + status_3 + status_4 == 4) && pswd == con_pswd) {
      $('button.save_change_password').prop('disabled', false);
    } else {
      $('button.save_change_password').prop('disabled', true);
    }

  });

  $('input[type=password].input_confiem_password').blur(function () {
    var pswd = $('#new_password').val();
    var con_pswd = $('#confirm_new_password').val();
    if (pswd != con_pswd) {
      $.control.fnShowResult('301# กรุณายืนยันรหัสผ่านให้ถูกต้อง !');
    }
  });
  
  $("#form_reset_password").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
    } else {
      event.preventDefault();
      $.control.reset_password_submitForm();
    }
  });
  

  $('.btn-cancal_rfq').on('click', function () {
     var rfq_id = $('.btn-cancal_rfq').attr('id');
     $.control.fnCancelRFQ(rfq_id);
    
//    swal({
//      title: 'กรุณายืนยันข้อมูล',
//      text: 'คุณต้องการยกเลิกข้อมูลนี้หรือไม่ ?',
//      type: 'info',
//      html: true,
//      showCancelButton: 'cancel',
//      confirmButtonClass: "btn-primary",
//      cancelButtonClass: "btn-danger",
//      confirmButtonText: 'ตกลง',
//      cancelButtonText: "ยกเลิก",
//      closeOnConfirm: true,
//      closeOnCancel: true
//    },
//            function (isConfirm) {
//              if (isConfirm) {
//               
//              }
//            });


  });

  $('.rfq_address_type').on('click', function () {
    var address_type = $(this).val();
    if (address_type == '1') {
      $('.company_address').show();
      $('.other_address').hide();
    } else {
      $('.company_address').hide();
      $('.other_address').show();
    }

  });

  var full = $.base_url;//location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');
  $.control = {
    defaultUrl: full,
    defaultUrl_output: full + '/application/output/',
    title_confirm_delete: 'Are you sure you want to delete this item ?',
    text_confirm_delete: "Please Confirm",
    title_confirm_logout: "Do you want to sign out ?",
    title_warning: "Warning",
    text_please_select_data: "Please Select Item !",
    text_please_confirm: "Please confirm",
    fngetproductdetail: function (id) {
      var url = $.control.defaultUrl + 'product/get_product_data';
      $.ajax({
        url: url,
        type: "POST",
        data: {id: id},
        cache: false,
        async: false,
        dataType: 'text',
        success: function (response) {
          var res = JSON.parse(response);
          $('#form-prduct_detail #product_name').html(res.data.product_name);
          $('#form-prduct_detail #product_brand').html(res.data.pd_brand_name);
          $('#form-prduct_detail #product_model').html(res.data.product_model);
          $('#form-prduct_detail #product_detail').html(res.data.product_detail);
          $('#form-prduct_detail #product_category').html(res.data.pd_category);

          $('#form-prduct_detail #product_price').html(res.data.product_price);
          $('#form-prduct_detail #image_path').prop('src', res.data.image_path);
          $('#form-prduct_detail #image_path_thumb').prop('src', res.data.image_path_thumb);
          $('#form-prduct_detail #product_url').prop('href', res.data.product_url);
          $('#form-prduct_detail .add-to-cart').prop('id', 'add_pd_id_' + res.data.product_id);
          $('#form-prduct_detail .cart_item_qty').attr('id', 'cart_item_qty_' + res.data.product_id);
          $('#form-prduct_detail .cart_item_qty').attr('name', 'cart_item_qty_' + res.data.product_id);


          $('#product-detail-Modal').modal('show');

        }
      });
    },
    fnaddproducttocart: function (id) {
      var arr_id = id.split('_');
      var url = $.control.defaultUrl + 'my_cart/add_product_to_cart';
      var qty = $('#cart_item_qty_' + arr_id[3]).val() != "undefined" ? $('#cart_item_qty_' + arr_id[3]).val() : 1;


      $.ajax({
        url: url,
        type: "POST",
        data: {id: id, qty: qty},
        cache: false,
        async: false,
        dataType: 'text',
        success: function (response) {
          var res = JSON.parse(response);

          if ($.control.fnShowResult(res.data.add_status) == '2') {


            var html = '<li class="cart_item" id="cart_item_id_' + res.data.product_id + '"><a href="' + res.data.product_url + '"><img src="' + res.data.image_path_thumb + '" class=" align-items-center" style=" height:  60px; margin: auto;" alt="' + res.data.product_name + '"></a><a href="' + res.data.product_url + '">' + res.data.product_name + '</a>รุ่น : ' + res.data.product_model + ' <span>จำนวน : ' + res.data.cart_item_qty + ' ' + res.data.product_unit + '</span><a href="javascript:void(0);" class="remove_cart_item" id="removecart_item_id_' + res.data.product_id + '"><i class="ri-close-fill"></i></a></li>';

            $('#popup_cart_list').append(html);
            $('#cart_total').html(res.data.cart_total);
            $('#popup_cart_total').html(res.data.cart_total + ' รายการ');
          }
        }
      });
    },
    fnRemoveProductFromMyCart: function (id) {

      var url = $.control.defaultUrl + 'my_cart/remove_product_from_cart';
      $.ajax({
        url: url,
        type: "POST",
        data: {id: id},
        cache: false,
        async: false,
        dataType: 'text',
        success: function (response) {
          var res = JSON.parse(response);
          if ($.control.fnShowResult(res.data.add_status) == '2') {
            $('#cart_total').html(res.data.cart_total);
            $('#popup_cart_total').html(res.data.cart_total + ' รายการ');
            $('#cart_total_2').html(res.data.cart_total + ' รายการ');
            $('#cart_show_item_' + res.data.product_id).remove();
            $('#cart_item_id_' + res.data.product_id).remove();

          }
        }
      });
    },
    fnUpdateMyCartItems: function () {

      var url = $.control.defaultUrl + 'my_cart/update_my_cart_items';
      var input = $('#form_my_cart').serializeArray();
      $.ajax({
        url: url,
        type: "POST",
        data: {data: input},
        cache: false,
        async: false,
        dataType: 'text',
        success: function (response) {
          var res = JSON.parse(response);
          if ($.control.fnShowResult(res.data.add_status) == '2') {

            $.each(res.data.product_data, function (i, v) {

              $('#popup_cart_item_qty_' + i).html(v);
              $('#cart_item_qty_' + i).val(v);
            });

          }
        }
      });
    },
    fngetAddress: function (val) {
      var url = $.control.defaultUrl + 'my_cart/get_address_by_zip_code';
      $.ajax({
        url: url,
        type: "POST",
        data: {zip_code: val},
        cache: false,
        async: false,
        dataType: 'text',
        success: function (response) {
          var res = JSON.parse(response);

          if (res.data.get_status == 'NO') {
            $.control.fnShowResult(res.data.status_text);

            $('#rfq_sub_district option').remove();
            $('#rfq_sub_district').prop('disabled', false);
            $('#rfq_district option').remove();
            $('#rfq_district').prop('disabled', false);
            $('#rfq_province option').remove();
            $('#rfq_province').prop('disabled', false);
          } else {
            var sub_district = '<option value="">-- กรุณาเลือก --</option>';
            var district = '<option value="">-- กรุณาเลือก --</option>';
            var province = '';
            $.each(res.data.sub_district, function (i, v) {
              sub_district += '<option value="' + i + '">' + v + '</option>';
            });

            $.each(res.data.district, function (i, v) {
              district += '<option value="' + i + '">' + v + '</option>';
            });

            $.each(res.data.province, function (i, v) {
              province += '<option value="' + i + '">' + v + '</option>';
            });

            if (sub_district != '') {
              $('#rfq_sub_district option').remove();
              $('#rfq_sub_district').append(sub_district);
              $('#rfq_sub_district').prop('disabled', false);
            } else {
              $('#rfq_sub_district option').remove();
              $('#rfq_sub_district').prop('disabled', false);
            }

            if (district != '') {
              $('#rfq_district option').remove();
              $('#rfq_district').append(district);
              $('#rfq_district').prop('disabled', false);
            } else {
              $('#rfq_district option').remove();
              $('#rfq_district').prop('disabled', false);
            }

            if (province != '') {
              $('#rfq_province option').remove();
              $('#rfq_province').append(province);
              $('#rfq_province').prop('disabled', false);
            } else {
              $('#rfq_province option').remove();
              $('#rfq_province').prop('disabled', false);
            }

          }
        }
      });
    },
    checkout_submitForm: function () {
      var url = $.control.defaultUrl + 'my_cart/check_out_save';
      var input = $('#form_check_out').serializeArray();
      $.ajax({
        type: "POST",
        url: url,
        cache: false,
        async: false,
        dataType: 'text',
        data: {data: input},
        success: function (response) {
          var res = JSON.parse(response);
          if (res.data.tran_status == 'OK') {
            window.location = $.control.defaultUrl + 'my_cart/check_out_completed?rfq_code=' + res.data.rfq_code;
          } else {
            window.location = $.control.defaultUrl + 'my_cart/check_out_unsuccess';
          }

        }
      });
    },
    login_submitForm: function () {
      var url = $.control.defaultUrl + 'my_account/login_process';
      var input = $('#form_login').serializeArray();
      $.ajax({
        type: "POST",
        url: url,
        cache: false,
        async: false,
        dataType: 'text',
        data: {data: input},
        success: function (response) {
          var res = JSON.parse(response);
          
          if (res.data.login_status != 'OK') {
            $.control.fnShowResult(res.data.login_textstatus);
          } else {
            window.location = $.control.defaultUrl + 'my_account/home';
          }

        }
      });
    },
    profile_submitForm: function () {

      var url = $.control.defaultUrl + 'my_account/update_profile';
      var input = $('#form_update_profile').serializeArray();
      $.ajax({
        type: "POST",
        url: url,
        cache: false,
        async: false,
        dataType: 'text',
        data: {data: input},
        success: function (response) {
          var res = JSON.parse(response);
          $.control.fnShowResult(res.data.update_status);


        }
      });

    },
    change_password_submitForm: function () {
      var url = $.control.defaultUrl + 'my_account/confirm_change_password';
      var input = $('#form_change_password').serializeArray();
      $.ajax({
        type: "POST",
        url: url,
        cache: false,
        async: false,
        dataType: 'text',
        data: {data: input},
        success: function (response) {
          var res = JSON.parse(response);

          $.control.fnShowResult(res.data.change_textstatus,'my_account/home');
         
        }
      });
    },
    
    fnCancelRFQ: function (rfq_id) {

      var url = $.control.defaultUrl + 'my_account/cancel_rfq';
      $.ajax({
        type: "POST",
        url: url,
        cache: false,
        async: false,
        dataType: 'text',
        data: {rfq_id: rfq_id},
        success: function (response) {
          var res = JSON.parse(response);
          $.control.fnShowResult(res.data.cancel_textstatus,'my_account/rfq_history');
         

        }
      });

    },
    forgot_password_submitForm:function(){
      var url = $.control.defaultUrl + 'my_account/confirm_forgot_password';
      var input = $('#form_forgot_password').serializeArray();
      $.ajax({
        type: "POST",
        url: url,
        cache: false,
        async: false,
        dataType: 'text',
        data: {data: input},
        success: function (response) {
          var res = JSON.parse(response);
		 
          $.control.fnShowResult(res.data.forgot_textstatus,'my_account/forgot_password_success');
          //my_account

        }
      });
    },
    reset_password_submitForm : function(){
      var url = $.control.defaultUrl + 'my_account/confirm_reset_password';
      var input = $('#form_reset_password').serializeArray();
      $.ajax({
        type: "POST",
        url: url,
        cache: false,
        async: false,
        dataType: 'text',
        data: {data: input},
        success: function (response) {
          var res = JSON.parse(response);
          $.control.fnShowResult(res.data.reset_textstatus,'my_account');
          //my_account

        }
      });
    },
    formSuccess: function () {
      $("#contactForm")[0].reset();
      submitMSG(true, "Message Submitted!");
    },

    formError: function (form) {
      $(form).addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
        $(this).removeClass();
      });
    },

    submitMSG: function (valid, msg, form) {
      if (valid) {
        var msgClasses = "h4 tada animated text-success";
      } else {
        var msgClasses = "h4 text-danger";
      }
      $(form).removeClass().addClass(msgClasses).text(msg);
    },
    fnShowResult: function (str, url, id_focus) {
      var arr = str.split('#');
      var message = arr[1];
      var type, icon = '';
      var cancel = false;
      var cfText = "OK";

      

      if (arr.length > 1) {

        var num = arr[0].substr(0, 1);

        if (num == 1) {
          type = 'error', icon = 'พบข้อผิดพลาด', cancel = true, cfText = "ยืนยัน";
        } else if (num == 2) {
          type = 'success', icon = 'ดำเนินการสำเร็จ';
        } else if (num == 3) {
          type = 'warning', icon = 'แจ้งเตือน';
        } else {
          type = 'info', icon = 'แจ้งข้อมูล';
        }

        if (url !== '' && url !== undefined && num == 2) {
         
          swal({
            title: icon,
            text: message,
            type: type,
            html: true,
            showCancelButton: cancel,
            confirmButtonClass: "btn-primary",
            confirmButtonText: cfText,
            cancelButtonText: "Cancel",
            closeOnConfirm: true,
            closeOnCancel: true
          },
                  function (isConfirm) {
                    if (isConfirm) {
                      
//                      alert(url)
                      if (url == 'modal') {
                        $('#modal-div').modal('hide');
                      } else if (url == 'table') {
                        $('.card-block').find('.table').DataTable().ajax.reload();
                        $('#modal-div').modal('hide');
                      } else {
                        var obj = url.split('-');
                        if (obj[0] == 'option') {
                          $('#' + obj[1]).append('<option value="' + arr[2] + '">' + arr[3] + '</option>');
                          $('#modal-div').modal('hide');
                          $('#' + obj[1]).val(arr[2]);
                          $('#' + obj[2]).val(arr[3]);
                        } else if (obj[0] == 'id') {
                          window.location = $.base_url + obj[1] + arr[2];
                        } else {
                          
                          window.location = $.base_url + url;
                        }
                      }

                    }
                  });
        } else if (id_focus != '' && id_focus !== undefined) {
          swal({
            title: icon,
            text: message,
            type: type,
            html: true,
            showCancelButton: cancel,
            confirmButtonClass: "btn-primary",
            confirmButtonText: cfText,
            cancelButtonText: "Cancel",
            closeOnConfirm: false,
            closeOnCancel: true
          },
                  function (isConfirm) {
                    swal.close();
                    if (isConfirm) {
                      if ($(id_focus).filter('.select2, .select2-no_search').length > 0) {
                        $(id_focus).select2('open');
                      } else {
                        $(id_focus).focus();
                      }
                    }
                  });
        } else {
          swal({
            title: icon,
            text: message,
            type: type,
            showCancelButton: false,
            confirmButtonClass: "btn-primary",
            confirmButtonText: "OK",
            closeOnConfirm: true
          });
        }

      }

      return num;
    },
    logout: function () {


      swal({
        title: $.control.title_confirm_logout,
        type: "info",
        showCancelButton: true,
        confirmButtonColor: '#4CAF50',
        confirmButtonText: 'Yes',
        cancelButtonText: "No",
        closeOnConfirm: false,
        showLoaderOnConfirm: false
      }, function () {
        var url = $.control.defaultUrl + 'login/destroy';
        $.ajax({
          type: "POST",
//          data: {data},
          url: url,
          async: false,
          success: function (response) {
            if (response == 'OK') {
              window.location = $.control.defaultUrl + 'login';
            }
          }
        });
      });

    },
  }


});